// Generated by Construct, the game and animation creation tool // Visit: https://www.construct.net // ../3rdparty/glmatrix.js { /*! @fileoverview gl-matrix - High performance matrix and vector operations @author Brandon Jones @author Colin MacKenzie IV @version 3.4.1 Copyright (c) 2015-2021, Brandon Jones, Colin MacKenzie IV. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var EPSILON=1e-6,ARRAY_TYPE="undefined"!=typeof Float32Array?Float32Array:Array,RANDOM=Math.random,ANGLE_ORDER="zyx";function setMatrixArrayType(t){ARRAY_TYPE=t}var degree=Math.PI/180;function toRadian(t){return t*degree}function equals$9(t,a){return Math.abs(t-a)<=EPSILON*Math.max(1,Math.abs(t),Math.abs(a))}Math.hypot||(Math.hypot=function(){for(var t=0,a=arguments.length;a--;)t+=arguments[a]*arguments[a];return Math.sqrt(t)});var common={__proto__:null,EPSILON:EPSILON,get ARRAY_TYPE(){return ARRAY_TYPE},RANDOM:RANDOM,ANGLE_ORDER:ANGLE_ORDER,setMatrixArrayType:setMatrixArrayType,toRadian:toRadian,equals:equals$9};function create$8(){var t=new ARRAY_TYPE(4);return ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0),t[0]=1,t[3]=1,t}function clone$8(t){var a=new ARRAY_TYPE(4);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a}function copy$8(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t}function identity$5(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t}function fromValues$8(t,a,r,n){var e=new ARRAY_TYPE(4);return e[0]=t,e[1]=a,e[2]=r,e[3]=n,e}function set$8(t,a,r,n,e){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t}function transpose$2(t,a){if(t===a){var r=a[1];t[1]=a[2],t[2]=r}else t[0]=a[0],t[1]=a[2],t[2]=a[1],t[3]=a[3];return t}function invert$5(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r*o-e*n;return u?(u=1/u,t[0]=o*u,t[1]=-n*u,t[2]=-e*u,t[3]=r*u,t):null}function adjoint$2(t,a){var r=a[0];return t[0]=a[3],t[1]=-a[1],t[2]=-a[2],t[3]=r,t}function determinant$3(t){return t[0]*t[3]-t[2]*t[1]}function multiply$8(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[0],i=r[1],c=r[2],l=r[3];return t[0]=n*s+o*i,t[1]=e*s+u*i,t[2]=n*c+o*l,t[3]=e*c+u*l,t}function rotate$4(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=Math.sin(r),i=Math.cos(r);return t[0]=n*i+o*s,t[1]=e*i+u*s,t[2]=n*-s+o*i,t[3]=e*-s+u*i,t}function scale$8(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[0],i=r[1];return t[0]=n*s,t[1]=e*s,t[2]=o*i,t[3]=u*i,t}function fromRotation$4(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=r,t[2]=-r,t[3]=n,t}function fromScaling$3(t,a){return t[0]=a[0],t[1]=0,t[2]=0,t[3]=a[1],t}function str$8(t){return"mat2("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}function frob$3(t){return Math.hypot(t[0],t[1],t[2],t[3])}function LDU(t,a,r,n){return t[2]=n[2]/n[0],r[0]=n[0],r[1]=n[1],r[3]=n[3]-t[2]*r[1],[t,a,r]}function add$8(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t}function subtract$6(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t[3]=a[3]-r[3],t}function exactEquals$8(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]}function equals$8(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=a[0],s=a[1],i=a[2],c=a[3];return Math.abs(r-u)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(u))&&Math.abs(n-s)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(s))&&Math.abs(e-i)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(i))&&Math.abs(o-c)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(c))}function multiplyScalar$3(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t}function multiplyScalarAndAdd$3(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t[3]=a[3]+r[3]*n,t}var mul$8=multiply$8,sub$6=subtract$6,mat2=Object.freeze({__proto__:null,create:create$8,clone:clone$8,copy:copy$8,identity:identity$5,fromValues:fromValues$8,set:set$8,transpose:transpose$2,invert:invert$5,adjoint:adjoint$2,determinant:determinant$3,multiply:multiply$8,rotate:rotate$4,scale:scale$8,fromRotation:fromRotation$4,fromScaling:fromScaling$3,str:str$8,frob:frob$3,LDU:LDU,add:add$8,subtract:subtract$6,exactEquals:exactEquals$8,equals:equals$8,multiplyScalar:multiplyScalar$3,multiplyScalarAndAdd:multiplyScalarAndAdd$3,mul:mul$8,sub:sub$6});function create$7(){var t=new ARRAY_TYPE(6);return ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0,t[4]=0,t[5]=0),t[0]=1,t[3]=1,t}function clone$7(t){var a=new ARRAY_TYPE(6);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a[4]=t[4],a[5]=t[5],a}function copy$7(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=a[4],t[5]=a[5],t}function identity$4(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function fromValues$7(t,a,r,n,e,o){var u=new ARRAY_TYPE(6);return u[0]=t,u[1]=a,u[2]=r,u[3]=n,u[4]=e,u[5]=o,u}function set$7(t,a,r,n,e,o,u){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t[4]=o,t[5]=u,t}function invert$4(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=r*o-n*e;return i?(i=1/i,t[0]=o*i,t[1]=-n*i,t[2]=-e*i,t[3]=r*i,t[4]=(e*s-o*u)*i,t[5]=(n*u-r*s)*i,t):null}function determinant$2(t){return t[0]*t[3]-t[1]*t[2]}function multiply$7(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=r[0],l=r[1],$=r[2],h=r[3],f=r[4],M=r[5];return t[0]=n*c+o*l,t[1]=e*c+u*l,t[2]=n*$+o*h,t[3]=e*$+u*h,t[4]=n*f+o*M+s,t[5]=e*f+u*M+i,t}function rotate$3(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=Math.sin(r),l=Math.cos(r);return t[0]=n*l+o*c,t[1]=e*l+u*c,t[2]=n*-c+o*l,t[3]=e*-c+u*l,t[4]=s,t[5]=i,t}function scale$7(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=r[0],l=r[1];return t[0]=n*c,t[1]=e*c,t[2]=o*l,t[3]=u*l,t[4]=s,t[5]=i,t}function translate$3(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=r[0],l=r[1];return t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=n*c+o*l+s,t[5]=e*c+u*l+i,t}function fromRotation$3(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=r,t[2]=-r,t[3]=n,t[4]=0,t[5]=0,t}function fromScaling$2(t,a){return t[0]=a[0],t[1]=0,t[2]=0,t[3]=a[1],t[4]=0,t[5]=0,t}function fromTranslation$3(t,a){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=a[0],t[5]=a[1],t}function str$7(t){return"mat2d("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+")"}function frob$2(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],1)}function add$7(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t[4]=a[4]+r[4],t[5]=a[5]+r[5],t}function subtract$5(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t[3]=a[3]-r[3],t[4]=a[4]-r[4],t[5]=a[5]-r[5],t}function multiplyScalar$2(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t[4]=a[4]*r,t[5]=a[5]*r,t}function multiplyScalarAndAdd$2(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t[3]=a[3]+r[3]*n,t[4]=a[4]+r[4]*n,t[5]=a[5]+r[5]*n,t}function exactEquals$7(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]&&t[4]===a[4]&&t[5]===a[5]}function equals$7(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=t[4],s=t[5],i=a[0],c=a[1],l=a[2],$=a[3],h=a[4],f=a[5];return Math.abs(r-i)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(i))&&Math.abs(n-c)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(c))&&Math.abs(e-l)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(l))&&Math.abs(o-$)<=EPSILON*Math.max(1,Math.abs(o),Math.abs($))&&Math.abs(u-h)<=EPSILON*Math.max(1,Math.abs(u),Math.abs(h))&&Math.abs(s-f)<=EPSILON*Math.max(1,Math.abs(s),Math.abs(f))}var mul$7=multiply$7,sub$5=subtract$5,mat2d=Object.freeze({__proto__:null,create:create$7,clone:clone$7,copy:copy$7,identity:identity$4,fromValues:fromValues$7,set:set$7,invert:invert$4,determinant:determinant$2,multiply:multiply$7,rotate:rotate$3,scale:scale$7,translate:translate$3,fromRotation:fromRotation$3,fromScaling:fromScaling$2,fromTranslation:fromTranslation$3,str:str$7,frob:frob$2,add:add$7,subtract:subtract$5,multiplyScalar:multiplyScalar$2,multiplyScalarAndAdd:multiplyScalarAndAdd$2,exactEquals:exactEquals$7,equals:equals$7,mul:mul$7,sub:sub$5});function create$6(){var t=new ARRAY_TYPE(9);return ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[5]=0,t[6]=0,t[7]=0),t[0]=1,t[4]=1,t[8]=1,t}function fromMat4$1(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[4],t[4]=a[5],t[5]=a[6],t[6]=a[8],t[7]=a[9],t[8]=a[10],t}function clone$6(t){var a=new ARRAY_TYPE(9);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a[4]=t[4],a[5]=t[5],a[6]=t[6],a[7]=t[7],a[8]=t[8],a}function copy$6(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=a[4],t[5]=a[5],t[6]=a[6],t[7]=a[7],t[8]=a[8],t}function fromValues$6(t,a,r,n,e,o,u,s,i){var c=new ARRAY_TYPE(9);return c[0]=t,c[1]=a,c[2]=r,c[3]=n,c[4]=e,c[5]=o,c[6]=u,c[7]=s,c[8]=i,c}function set$6(t,a,r,n,e,o,u,s,i,c){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t[4]=o,t[5]=u,t[6]=s,t[7]=i,t[8]=c,t}function identity$3(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function transpose$1(t,a){if(t===a){var r=a[1],n=a[2],e=a[5];t[1]=a[3],t[2]=a[6],t[3]=r,t[5]=a[7],t[6]=n,t[7]=e}else t[0]=a[0],t[1]=a[3],t[2]=a[6],t[3]=a[1],t[4]=a[4],t[5]=a[7],t[6]=a[2],t[7]=a[5],t[8]=a[8];return t}function invert$3(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8],$=l*u-s*c,h=-l*o+s*i,f=c*o-u*i,M=r*$+n*h+e*f;return M?(M=1/M,t[0]=$*M,t[1]=(-l*n+e*c)*M,t[2]=(s*n-e*u)*M,t[3]=h*M,t[4]=(l*r-e*i)*M,t[5]=(-s*r+e*o)*M,t[6]=f*M,t[7]=(-c*r+n*i)*M,t[8]=(u*r-n*o)*M,t):null}function adjoint$1(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8];return t[0]=u*l-s*c,t[1]=e*c-n*l,t[2]=n*s-e*u,t[3]=s*i-o*l,t[4]=r*l-e*i,t[5]=e*o-r*s,t[6]=o*c-u*i,t[7]=n*i-r*c,t[8]=r*u-n*o,t}function determinant$1(t){var a=t[0],r=t[1],n=t[2],e=t[3],o=t[4],u=t[5],s=t[6],i=t[7],c=t[8];return a*(c*o-u*i)+r*(-c*e+u*s)+n*(i*e-o*s)}function multiply$6(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=r[0],f=r[1],M=r[2],m=r[3],d=r[4],v=r[5],b=r[6],p=r[7],A=r[8];return t[0]=h*n+f*u+M*c,t[1]=h*e+f*s+M*l,t[2]=h*o+f*i+M*$,t[3]=m*n+d*u+v*c,t[4]=m*e+d*s+v*l,t[5]=m*o+d*i+v*$,t[6]=b*n+p*u+A*c,t[7]=b*e+p*s+A*l,t[8]=b*o+p*i+A*$,t}function translate$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=r[0],f=r[1];return t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=s,t[5]=i,t[6]=h*n+f*u+c,t[7]=h*e+f*s+l,t[8]=h*o+f*i+$,t}function rotate$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=Math.sin(r),f=Math.cos(r);return t[0]=f*n+h*u,t[1]=f*e+h*s,t[2]=f*o+h*i,t[3]=f*u-h*n,t[4]=f*s-h*e,t[5]=f*i-h*o,t[6]=c,t[7]=l,t[8]=$,t}function scale$6(t,a,r){var n=r[0],e=r[1];return t[0]=n*a[0],t[1]=n*a[1],t[2]=n*a[2],t[3]=e*a[3],t[4]=e*a[4],t[5]=e*a[5],t[6]=a[6],t[7]=a[7],t[8]=a[8],t}function fromTranslation$2(t,a){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=1,t[5]=0,t[6]=a[0],t[7]=a[1],t[8]=1,t}function fromRotation$2(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=r,t[2]=0,t[3]=-r,t[4]=n,t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function fromScaling$1(t,a){return t[0]=a[0],t[1]=0,t[2]=0,t[3]=0,t[4]=a[1],t[5]=0,t[6]=0,t[7]=0,t[8]=1,t}function fromMat2d(t,a){return t[0]=a[0],t[1]=a[1],t[2]=0,t[3]=a[2],t[4]=a[3],t[5]=0,t[6]=a[4],t[7]=a[5],t[8]=1,t}function fromQuat$1(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r+r,s=n+n,i=e+e,c=r*u,l=n*u,$=n*s,h=e*u,f=e*s,M=e*i,m=o*u,d=o*s,v=o*i;return t[0]=1-$-M,t[3]=l-v,t[6]=h+d,t[1]=l+v,t[4]=1-c-M,t[7]=f-m,t[2]=h-d,t[5]=f+m,t[8]=1-c-$,t}function normalFromMat4(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8],$=a[9],h=a[10],f=a[11],M=a[12],m=a[13],d=a[14],v=a[15],b=r*s-n*u,p=r*i-e*u,A=r*c-o*u,y=n*i-e*s,g=n*c-o*s,R=e*c-o*i,E=l*m-$*M,q=l*d-h*M,x=l*v-f*M,P=$*d-h*m,L=$*v-f*m,O=h*v-f*d,S=b*O-p*L+A*P+y*x-g*q+R*E;return S?(S=1/S,t[0]=(s*O-i*L+c*P)*S,t[1]=(i*x-u*O-c*q)*S,t[2]=(u*L-s*x+c*E)*S,t[3]=(e*L-n*O-o*P)*S,t[4]=(r*O-e*x+o*q)*S,t[5]=(n*x-r*L-o*E)*S,t[6]=(m*R-d*g+v*y)*S,t[7]=(d*A-M*R-v*p)*S,t[8]=(M*g-m*A+v*b)*S,t):null}function projection(t,a,r){return t[0]=2/a,t[1]=0,t[2]=0,t[3]=0,t[4]=-2/r,t[5]=0,t[6]=-1,t[7]=1,t[8]=1,t}function str$6(t){return"mat3("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+")"}function frob$1(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8])}function add$6(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t[4]=a[4]+r[4],t[5]=a[5]+r[5],t[6]=a[6]+r[6],t[7]=a[7]+r[7],t[8]=a[8]+r[8],t}function subtract$4(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t[3]=a[3]-r[3],t[4]=a[4]-r[4],t[5]=a[5]-r[5],t[6]=a[6]-r[6],t[7]=a[7]-r[7],t[8]=a[8]-r[8],t}function multiplyScalar$1(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t[4]=a[4]*r,t[5]=a[5]*r,t[6]=a[6]*r,t[7]=a[7]*r,t[8]=a[8]*r,t}function multiplyScalarAndAdd$1(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t[3]=a[3]+r[3]*n,t[4]=a[4]+r[4]*n,t[5]=a[5]+r[5]*n,t[6]=a[6]+r[6]*n,t[7]=a[7]+r[7]*n,t[8]=a[8]+r[8]*n,t}function exactEquals$6(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]&&t[4]===a[4]&&t[5]===a[5]&&t[6]===a[6]&&t[7]===a[7]&&t[8]===a[8]}function equals$6(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=t[4],s=t[5],i=t[6],c=t[7],l=t[8],$=a[0],h=a[1],f=a[2],M=a[3],m=a[4],d=a[5],v=a[6],b=a[7],p=a[8];return Math.abs(r-$)<=EPSILON*Math.max(1,Math.abs(r),Math.abs($))&&Math.abs(n-h)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(h))&&Math.abs(e-f)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(f))&&Math.abs(o-M)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(M))&&Math.abs(u-m)<=EPSILON*Math.max(1,Math.abs(u),Math.abs(m))&&Math.abs(s-d)<=EPSILON*Math.max(1,Math.abs(s),Math.abs(d))&&Math.abs(i-v)<=EPSILON*Math.max(1,Math.abs(i),Math.abs(v))&&Math.abs(c-b)<=EPSILON*Math.max(1,Math.abs(c),Math.abs(b))&&Math.abs(l-p)<=EPSILON*Math.max(1,Math.abs(l),Math.abs(p))}var mul$6=multiply$6,sub$4=subtract$4,mat3=Object.freeze({__proto__:null,create:create$6,fromMat4:fromMat4$1,clone:clone$6,copy:copy$6,fromValues:fromValues$6,set:set$6,identity:identity$3,transpose:transpose$1,invert:invert$3,adjoint:adjoint$1,determinant:determinant$1,multiply:multiply$6,translate:translate$2,rotate:rotate$2,scale:scale$6,fromTranslation:fromTranslation$2,fromRotation:fromRotation$2,fromScaling:fromScaling$1,fromMat2d:fromMat2d,fromQuat:fromQuat$1,normalFromMat4:normalFromMat4,projection:projection,str:str$6,frob:frob$1,add:add$6,subtract:subtract$4,multiplyScalar:multiplyScalar$1,multiplyScalarAndAdd:multiplyScalarAndAdd$1,exactEquals:exactEquals$6,equals:equals$6,mul:mul$6,sub:sub$4});function create$5(){var t=new ARRAY_TYPE(16);return ARRAY_TYPE!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function clone$5(t){var a=new ARRAY_TYPE(16);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a[4]=t[4],a[5]=t[5],a[6]=t[6],a[7]=t[7],a[8]=t[8],a[9]=t[9],a[10]=t[10],a[11]=t[11],a[12]=t[12],a[13]=t[13],a[14]=t[14],a[15]=t[15],a}function copy$5(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=a[4],t[5]=a[5],t[6]=a[6],t[7]=a[7],t[8]=a[8],t[9]=a[9],t[10]=a[10],t[11]=a[11],t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15],t}function fromValues$5(t,a,r,n,e,o,u,s,i,c,l,$,h,f,M,m){var d=new ARRAY_TYPE(16);return d[0]=t,d[1]=a,d[2]=r,d[3]=n,d[4]=e,d[5]=o,d[6]=u,d[7]=s,d[8]=i,d[9]=c,d[10]=l,d[11]=$,d[12]=h,d[13]=f,d[14]=M,d[15]=m,d}function set$5(t,a,r,n,e,o,u,s,i,c,l,$,h,f,M,m,d){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t[4]=o,t[5]=u,t[6]=s,t[7]=i,t[8]=c,t[9]=l,t[10]=$,t[11]=h,t[12]=f,t[13]=M,t[14]=m,t[15]=d,t}function identity$2(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function transpose(t,a){if(t===a){var r=a[1],n=a[2],e=a[3],o=a[6],u=a[7],s=a[11];t[1]=a[4],t[2]=a[8],t[3]=a[12],t[4]=r,t[6]=a[9],t[7]=a[13],t[8]=n,t[9]=o,t[11]=a[14],t[12]=e,t[13]=u,t[14]=s}else t[0]=a[0],t[1]=a[4],t[2]=a[8],t[3]=a[12],t[4]=a[1],t[5]=a[5],t[6]=a[9],t[7]=a[13],t[8]=a[2],t[9]=a[6],t[10]=a[10],t[11]=a[14],t[12]=a[3],t[13]=a[7],t[14]=a[11],t[15]=a[15];return t}function invert$2(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8],$=a[9],h=a[10],f=a[11],M=a[12],m=a[13],d=a[14],v=a[15],b=r*s-n*u,p=r*i-e*u,A=r*c-o*u,y=n*i-e*s,g=n*c-o*s,R=e*c-o*i,E=l*m-$*M,q=l*d-h*M,x=l*v-f*M,P=$*d-h*m,L=$*v-f*m,O=h*v-f*d,S=b*O-p*L+A*P+y*x-g*q+R*E;return S?(S=1/S,t[0]=(s*O-i*L+c*P)*S,t[1]=(e*L-n*O-o*P)*S,t[2]=(m*R-d*g+v*y)*S,t[3]=(h*g-$*R-f*y)*S,t[4]=(i*x-u*O-c*q)*S,t[5]=(r*O-e*x+o*q)*S,t[6]=(d*A-M*R-v*p)*S,t[7]=(l*R-h*A+f*p)*S,t[8]=(u*L-s*x+c*E)*S,t[9]=(n*x-r*L-o*E)*S,t[10]=(M*g-m*A+v*b)*S,t[11]=($*A-l*g-f*b)*S,t[12]=(s*q-u*P-i*E)*S,t[13]=(r*P-n*q+e*E)*S,t[14]=(m*p-M*y-d*b)*S,t[15]=(l*y-$*p+h*b)*S,t):null}function adjoint(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=a[4],s=a[5],i=a[6],c=a[7],l=a[8],$=a[9],h=a[10],f=a[11],M=a[12],m=a[13],d=a[14],v=a[15],b=r*s-n*u,p=r*i-e*u,A=r*c-o*u,y=n*i-e*s,g=n*c-o*s,R=e*c-o*i,E=l*m-$*M,q=l*d-h*M,x=l*v-f*M,P=$*d-h*m,L=$*v-f*m,O=h*v-f*d;return t[0]=s*O-i*L+c*P,t[1]=e*L-n*O-o*P,t[2]=m*R-d*g+v*y,t[3]=h*g-$*R-f*y,t[4]=i*x-u*O-c*q,t[5]=r*O-e*x+o*q,t[6]=d*A-M*R-v*p,t[7]=l*R-h*A+f*p,t[8]=u*L-s*x+c*E,t[9]=n*x-r*L-o*E,t[10]=M*g-m*A+v*b,t[11]=$*A-l*g-f*b,t[12]=s*q-u*P-i*E,t[13]=r*P-n*q+e*E,t[14]=m*p-M*y-d*b,t[15]=l*y-$*p+h*b,t}function determinant(t){var a=t[0],r=t[1],n=t[2],e=t[3],o=t[4],u=t[5],s=t[6],i=t[7],c=t[8],l=t[9],$=t[10],h=t[11],f=t[12],M=t[13],m=t[14],d=a*u-r*o,v=a*s-n*o,b=r*s-n*u,p=c*M-l*f,A=c*m-$*f,y=l*m-$*M;return i*(a*y-r*A+n*p)-e*(o*y-u*A+s*p)+t[15]*(c*b-l*v+$*d)-h*(f*b-M*v+m*d)}function multiply$5(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=a[9],f=a[10],M=a[11],m=a[12],d=a[13],v=a[14],b=a[15],p=r[0],A=r[1],y=r[2],g=r[3];return t[0]=p*n+A*s+y*$+g*m,t[1]=p*e+A*i+y*h+g*d,t[2]=p*o+A*c+y*f+g*v,t[3]=p*u+A*l+y*M+g*b,p=r[4],A=r[5],y=r[6],g=r[7],t[4]=p*n+A*s+y*$+g*m,t[5]=p*e+A*i+y*h+g*d,t[6]=p*o+A*c+y*f+g*v,t[7]=p*u+A*l+y*M+g*b,p=r[8],A=r[9],y=r[10],g=r[11],t[8]=p*n+A*s+y*$+g*m,t[9]=p*e+A*i+y*h+g*d,t[10]=p*o+A*c+y*f+g*v,t[11]=p*u+A*l+y*M+g*b,p=r[12],A=r[13],y=r[14],g=r[15],t[12]=p*n+A*s+y*$+g*m,t[13]=p*e+A*i+y*h+g*d,t[14]=p*o+A*c+y*f+g*v,t[15]=p*u+A*l+y*M+g*b,t}function translate$1(t,a,r){var n,e,o,u,s,i,c,l,$,h,f,M,m=r[0],d=r[1],v=r[2];return a===t?(t[12]=a[0]*m+a[4]*d+a[8]*v+a[12],t[13]=a[1]*m+a[5]*d+a[9]*v+a[13],t[14]=a[2]*m+a[6]*d+a[10]*v+a[14],t[15]=a[3]*m+a[7]*d+a[11]*v+a[15]):(n=a[0],e=a[1],o=a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=a[8],h=a[9],f=a[10],M=a[11],t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=s,t[5]=i,t[6]=c,t[7]=l,t[8]=$,t[9]=h,t[10]=f,t[11]=M,t[12]=n*m+s*d+$*v+a[12],t[13]=e*m+i*d+h*v+a[13],t[14]=o*m+c*d+f*v+a[14],t[15]=u*m+l*d+M*v+a[15]),t}function scale$5(t,a,r){var n=r[0],e=r[1],o=r[2];return t[0]=a[0]*n,t[1]=a[1]*n,t[2]=a[2]*n,t[3]=a[3]*n,t[4]=a[4]*e,t[5]=a[5]*e,t[6]=a[6]*e,t[7]=a[7]*e,t[8]=a[8]*o,t[9]=a[9]*o,t[10]=a[10]*o,t[11]=a[11]*o,t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15],t}function rotate$1(t,a,r,n){var e,o,u,s,i,c,l,$,h,f,M,m,d,v,b,p,A,y,g,R,E,q,x,P,L=n[0],O=n[1],S=n[2],Y=Math.hypot(L,O,S);return Y0?(r[0]=2*(s*u+l*n+i*o-c*e)/$,r[1]=2*(i*u+l*e+c*n-s*o)/$,r[2]=2*(c*u+l*o+s*e-i*n)/$):(r[0]=2*(s*u+l*n+i*o-c*e),r[1]=2*(i*u+l*e+c*n-s*o),r[2]=2*(c*u+l*o+s*e-i*n)),fromRotationTranslation$1(t,a,r),t}function getTranslation$1(t,a){return t[0]=a[12],t[1]=a[13],t[2]=a[14],t}function getScaling(t,a){var r=a[0],n=a[1],e=a[2],o=a[4],u=a[5],s=a[6],i=a[8],c=a[9],l=a[10];return t[0]=Math.hypot(r,n,e),t[1]=Math.hypot(o,u,s),t[2]=Math.hypot(i,c,l),t}function getRotation(t,a){var r=new ARRAY_TYPE(3);getScaling(r,a);var n=1/r[0],e=1/r[1],o=1/r[2],u=a[0]*n,s=a[1]*e,i=a[2]*o,c=a[4]*n,l=a[5]*e,$=a[6]*o,h=a[8]*n,f=a[9]*e,M=a[10]*o,m=u+l+M,d=0;return m>0?(d=2*Math.sqrt(m+1),t[3]=.25*d,t[0]=($-f)/d,t[1]=(h-i)/d,t[2]=(s-c)/d):u>l&&u>M?(d=2*Math.sqrt(1+u-l-M),t[3]=($-f)/d,t[0]=.25*d,t[1]=(s+c)/d,t[2]=(h+i)/d):l>M?(d=2*Math.sqrt(1+l-u-M),t[3]=(h-i)/d,t[0]=(s+c)/d,t[1]=.25*d,t[2]=($+f)/d):(d=2*Math.sqrt(1+M-u-l),t[3]=(s-c)/d,t[0]=(h+i)/d,t[1]=($+f)/d,t[2]=.25*d),t}function decompose(t,a,r,n){a[0]=n[12],a[1]=n[13],a[2]=n[14];var e=n[0],o=n[1],u=n[2],s=n[4],i=n[5],c=n[6],l=n[8],$=n[9],h=n[10];r[0]=Math.hypot(e,o,u),r[1]=Math.hypot(s,i,c),r[2]=Math.hypot(l,$,h);var f=1/r[0],M=1/r[1],m=1/r[2],d=e*f,v=o*M,b=u*m,p=s*f,A=i*M,y=c*m,g=l*f,R=$*M,E=h*m,q=d+A+E,x=0;return q>0?(x=2*Math.sqrt(q+1),t[3]=.25*x,t[0]=(y-R)/x,t[1]=(g-b)/x,t[2]=(v-p)/x):d>A&&d>E?(x=2*Math.sqrt(1+d-A-E),t[3]=(y-R)/x,t[0]=.25*x,t[1]=(v+p)/x,t[2]=(g+b)/x):A>E?(x=2*Math.sqrt(1+A-d-E),t[3]=(g-b)/x,t[0]=(v+p)/x,t[1]=.25*x,t[2]=(y+R)/x):(x=2*Math.sqrt(1+E-d-A),t[3]=(v-p)/x,t[0]=(g+b)/x,t[1]=(y+R)/x,t[2]=.25*x),t}function fromRotationTranslationScale(t,a,r,n){var e=a[0],o=a[1],u=a[2],s=a[3],i=e+e,c=o+o,l=u+u,$=e*i,h=e*c,f=e*l,M=o*c,m=o*l,d=u*l,v=s*i,b=s*c,p=s*l,A=n[0],y=n[1],g=n[2];return t[0]=(1-(M+d))*A,t[1]=(h+p)*A,t[2]=(f-b)*A,t[3]=0,t[4]=(h-p)*y,t[5]=(1-($+d))*y,t[6]=(m+v)*y,t[7]=0,t[8]=(f+b)*g,t[9]=(m-v)*g,t[10]=(1-($+M))*g,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function fromRotationTranslationScaleOrigin(t,a,r,n,e){var o=a[0],u=a[1],s=a[2],i=a[3],c=o+o,l=u+u,$=s+s,h=o*c,f=o*l,M=o*$,m=u*l,d=u*$,v=s*$,b=i*c,p=i*l,A=i*$,y=n[0],g=n[1],R=n[2],E=e[0],q=e[1],x=e[2],P=(1-(m+v))*y,L=(f+A)*y,O=(M-p)*y,S=(f-A)*g,Y=(1-(h+v))*g,T=(d+b)*g,N=(M+p)*R,_=(d-b)*R,I=(1-(h+m))*R;return t[0]=P,t[1]=L,t[2]=O,t[3]=0,t[4]=S,t[5]=Y,t[6]=T,t[7]=0,t[8]=N,t[9]=_,t[10]=I,t[11]=0,t[12]=r[0]+E-(P*E+S*q+N*x),t[13]=r[1]+q-(L*E+Y*q+_*x),t[14]=r[2]+x-(O*E+T*q+I*x),t[15]=1,t}function fromQuat(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r+r,s=n+n,i=e+e,c=r*u,l=n*u,$=n*s,h=e*u,f=e*s,M=e*i,m=o*u,d=o*s,v=o*i;return t[0]=1-$-M,t[1]=l+v,t[2]=h-d,t[3]=0,t[4]=l-v,t[5]=1-c-M,t[6]=f+m,t[7]=0,t[8]=h+d,t[9]=f-m,t[10]=1-c-$,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function frustum(t,a,r,n,e,o,u){var s=1/(r-a),i=1/(e-n),c=1/(o-u);return t[0]=2*o*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*o*i,t[6]=0,t[7]=0,t[8]=(r+a)*s,t[9]=(e+n)*i,t[10]=(u+o)*c,t[11]=-1,t[12]=0,t[13]=0,t[14]=u*o*2*c,t[15]=0,t}function perspectiveNO(t,a,r,n,e){var o=1/Math.tan(a/2);if(t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=e&&e!==1/0){var u=1/(n-e);t[10]=(e+n)*u,t[14]=2*e*n*u}else t[10]=-1,t[14]=-2*n;return t}var perspective=perspectiveNO;function perspectiveZO(t,a,r,n,e){var o=1/Math.tan(a/2);if(t[0]=o/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=o,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,null!=e&&e!==1/0){var u=1/(n-e);t[10]=e*u,t[14]=e*n*u}else t[10]=-1,t[14]=-n;return t}function perspectiveFromFieldOfView(t,a,r,n){var e=Math.tan(a.upDegrees*Math.PI/180),o=Math.tan(a.downDegrees*Math.PI/180),u=Math.tan(a.leftDegrees*Math.PI/180),s=Math.tan(a.rightDegrees*Math.PI/180),i=2/(u+s),c=2/(e+o);return t[0]=i,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=c,t[6]=0,t[7]=0,t[8]=-(u-s)*i*.5,t[9]=(e-o)*c*.5,t[10]=n/(r-n),t[11]=-1,t[12]=0,t[13]=0,t[14]=n*r/(r-n),t[15]=0,t}function orthoNO(t,a,r,n,e,o,u){var s=1/(a-r),i=1/(n-e),c=1/(o-u);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*i,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*c,t[11]=0,t[12]=(a+r)*s,t[13]=(e+n)*i,t[14]=(u+o)*c,t[15]=1,t}var ortho=orthoNO;function orthoZO(t,a,r,n,e,o,u){var s=1/(a-r),i=1/(n-e),c=1/(o-u);return t[0]=-2*s,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*i,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=c,t[11]=0,t[12]=(a+r)*s,t[13]=(e+n)*i,t[14]=o*c,t[15]=1,t}function lookAt(t,a,r,n){var e,o,u,s,i,c,l,$,h,f,M=a[0],m=a[1],d=a[2],v=n[0],b=n[1],p=n[2],A=r[0],y=r[1],g=r[2];return Math.abs(M-A)0&&(l*=f=1/Math.sqrt(f),$*=f,h*=f);var M=i*h-c*$,m=c*l-s*h,d=s*$-i*l;return(f=M*M+m*m+d*d)>0&&(M*=f=1/Math.sqrt(f),m*=f,d*=f),t[0]=M,t[1]=m,t[2]=d,t[3]=0,t[4]=$*d-h*m,t[5]=h*M-l*d,t[6]=l*m-$*M,t[7]=0,t[8]=l,t[9]=$,t[10]=h,t[11]=0,t[12]=e,t[13]=o,t[14]=u,t[15]=1,t}function str$5(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function frob(t){return Math.hypot(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function add$5(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t[3]=a[3]+r[3],t[4]=a[4]+r[4],t[5]=a[5]+r[5],t[6]=a[6]+r[6],t[7]=a[7]+r[7],t[8]=a[8]+r[8],t[9]=a[9]+r[9],t[10]=a[10]+r[10],t[11]=a[11]+r[11],t[12]=a[12]+r[12],t[13]=a[13]+r[13],t[14]=a[14]+r[14],t[15]=a[15]+r[15],t}function subtract$3(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t[3]=a[3]-r[3],t[4]=a[4]-r[4],t[5]=a[5]-r[5],t[6]=a[6]-r[6],t[7]=a[7]-r[7],t[8]=a[8]-r[8],t[9]=a[9]-r[9],t[10]=a[10]-r[10],t[11]=a[11]-r[11],t[12]=a[12]-r[12],t[13]=a[13]-r[13],t[14]=a[14]-r[14],t[15]=a[15]-r[15],t}function multiplyScalar(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t[3]=a[3]*r,t[4]=a[4]*r,t[5]=a[5]*r,t[6]=a[6]*r,t[7]=a[7]*r,t[8]=a[8]*r,t[9]=a[9]*r,t[10]=a[10]*r,t[11]=a[11]*r,t[12]=a[12]*r,t[13]=a[13]*r,t[14]=a[14]*r,t[15]=a[15]*r,t}function multiplyScalarAndAdd(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t[3]=a[3]+r[3]*n,t[4]=a[4]+r[4]*n,t[5]=a[5]+r[5]*n,t[6]=a[6]+r[6]*n,t[7]=a[7]+r[7]*n,t[8]=a[8]+r[8]*n,t[9]=a[9]+r[9]*n,t[10]=a[10]+r[10]*n,t[11]=a[11]+r[11]*n,t[12]=a[12]+r[12]*n,t[13]=a[13]+r[13]*n,t[14]=a[14]+r[14]*n,t[15]=a[15]+r[15]*n,t}function exactEquals$5(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]&&t[4]===a[4]&&t[5]===a[5]&&t[6]===a[6]&&t[7]===a[7]&&t[8]===a[8]&&t[9]===a[9]&&t[10]===a[10]&&t[11]===a[11]&&t[12]===a[12]&&t[13]===a[13]&&t[14]===a[14]&&t[15]===a[15]}function equals$5(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=t[4],s=t[5],i=t[6],c=t[7],l=t[8],$=t[9],h=t[10],f=t[11],M=t[12],m=t[13],d=t[14],v=t[15],b=a[0],p=a[1],A=a[2],y=a[3],g=a[4],R=a[5],E=a[6],q=a[7],x=a[8],P=a[9],L=a[10],O=a[11],S=a[12],Y=a[13],T=a[14],N=a[15];return Math.abs(r-b)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(b))&&Math.abs(n-p)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(p))&&Math.abs(e-A)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(A))&&Math.abs(o-y)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(y))&&Math.abs(u-g)<=EPSILON*Math.max(1,Math.abs(u),Math.abs(g))&&Math.abs(s-R)<=EPSILON*Math.max(1,Math.abs(s),Math.abs(R))&&Math.abs(i-E)<=EPSILON*Math.max(1,Math.abs(i),Math.abs(E))&&Math.abs(c-q)<=EPSILON*Math.max(1,Math.abs(c),Math.abs(q))&&Math.abs(l-x)<=EPSILON*Math.max(1,Math.abs(l),Math.abs(x))&&Math.abs($-P)<=EPSILON*Math.max(1,Math.abs($),Math.abs(P))&&Math.abs(h-L)<=EPSILON*Math.max(1,Math.abs(h),Math.abs(L))&&Math.abs(f-O)<=EPSILON*Math.max(1,Math.abs(f),Math.abs(O))&&Math.abs(M-S)<=EPSILON*Math.max(1,Math.abs(M),Math.abs(S))&&Math.abs(m-Y)<=EPSILON*Math.max(1,Math.abs(m),Math.abs(Y))&&Math.abs(d-T)<=EPSILON*Math.max(1,Math.abs(d),Math.abs(T))&&Math.abs(v-N)<=EPSILON*Math.max(1,Math.abs(v),Math.abs(N))}var mul$5=multiply$5,sub$3=subtract$3,mat4=Object.freeze({__proto__:null,create:create$5,clone:clone$5,copy:copy$5,fromValues:fromValues$5,set:set$5,identity:identity$2,transpose:transpose,invert:invert$2,adjoint:adjoint,determinant:determinant,multiply:multiply$5,translate:translate$1,scale:scale$5,rotate:rotate$1,rotateX:rotateX$3,rotateY:rotateY$3,rotateZ:rotateZ$3,fromTranslation:fromTranslation$1,fromScaling:fromScaling,fromRotation:fromRotation$1,fromXRotation:fromXRotation,fromYRotation:fromYRotation,fromZRotation:fromZRotation,fromRotationTranslation:fromRotationTranslation$1,fromQuat2:fromQuat2,getTranslation:getTranslation$1,getScaling:getScaling,getRotation:getRotation,decompose:decompose,fromRotationTranslationScale:fromRotationTranslationScale,fromRotationTranslationScaleOrigin:fromRotationTranslationScaleOrigin,fromQuat:fromQuat,frustum:frustum,perspectiveNO:perspectiveNO,perspective:perspective,perspectiveZO:perspectiveZO,perspectiveFromFieldOfView:perspectiveFromFieldOfView,orthoNO:orthoNO,ortho:ortho,orthoZO:orthoZO,lookAt:lookAt,targetTo:targetTo,str:str$5,frob:frob,add:add$5,subtract:subtract$3,multiplyScalar:multiplyScalar,multiplyScalarAndAdd:multiplyScalarAndAdd,exactEquals:exactEquals$5,equals:equals$5,mul:mul$5,sub:sub$3});function create$4(){var t=new ARRAY_TYPE(3);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function clone$4(t){var a=new ARRAY_TYPE(3);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a}function length$4(t){var a=t[0],r=t[1],n=t[2];return Math.hypot(a,r,n)}function fromValues$4(t,a,r){var n=new ARRAY_TYPE(3);return n[0]=t,n[1]=a,n[2]=r,n}function copy$4(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t}function set$4(t,a,r,n){return t[0]=a,t[1]=r,t[2]=n,t}function add$4(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t[2]=a[2]+r[2],t}function subtract$2(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t[2]=a[2]-r[2],t}function multiply$4(t,a,r){return t[0]=a[0]*r[0],t[1]=a[1]*r[1],t[2]=a[2]*r[2],t}function divide$2(t,a,r){return t[0]=a[0]/r[0],t[1]=a[1]/r[1],t[2]=a[2]/r[2],t}function ceil$2(t,a){return t[0]=Math.ceil(a[0]),t[1]=Math.ceil(a[1]),t[2]=Math.ceil(a[2]),t}function floor$2(t,a){return t[0]=Math.floor(a[0]),t[1]=Math.floor(a[1]),t[2]=Math.floor(a[2]),t}function min$2(t,a,r){return t[0]=Math.min(a[0],r[0]),t[1]=Math.min(a[1],r[1]),t[2]=Math.min(a[2],r[2]),t}function max$2(t,a,r){return t[0]=Math.max(a[0],r[0]),t[1]=Math.max(a[1],r[1]),t[2]=Math.max(a[2],r[2]),t}function round$2(t,a){return t[0]=Math.round(a[0]),t[1]=Math.round(a[1]),t[2]=Math.round(a[2]),t}function scale$4(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t[2]=a[2]*r,t}function scaleAndAdd$2(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t[2]=a[2]+r[2]*n,t}function distance$2(t,a){var r=a[0]-t[0],n=a[1]-t[1],e=a[2]-t[2];return Math.hypot(r,n,e)}function squaredDistance$2(t,a){var r=a[0]-t[0],n=a[1]-t[1],e=a[2]-t[2];return r*r+n*n+e*e}function squaredLength$4(t){var a=t[0],r=t[1],n=t[2];return a*a+r*r+n*n}function negate$2(t,a){return t[0]=-a[0],t[1]=-a[1],t[2]=-a[2],t}function inverse$2(t,a){return t[0]=1/a[0],t[1]=1/a[1],t[2]=1/a[2],t}function normalize$4(t,a){var r=a[0],n=a[1],e=a[2],o=r*r+n*n+e*e;return o>0&&(o=1/Math.sqrt(o)),t[0]=a[0]*o,t[1]=a[1]*o,t[2]=a[2]*o,t}function dot$4(t,a){return t[0]*a[0]+t[1]*a[1]+t[2]*a[2]}function cross$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=r[0],s=r[1],i=r[2];return t[0]=e*i-o*s,t[1]=o*u-n*i,t[2]=n*s-e*u,t}function lerp$4(t,a,r,n){var e=a[0],o=a[1],u=a[2];return t[0]=e+n*(r[0]-e),t[1]=o+n*(r[1]-o),t[2]=u+n*(r[2]-u),t}function slerp$1(t,a,r,n){var e=Math.acos(Math.min(Math.max(dot$4(a,r),-1),1)),o=Math.sin(e),u=Math.sin((1-n)*e)/o,s=Math.sin(n*e)/o;return t[0]=u*a[0]+s*r[0],t[1]=u*a[1]+s*r[1],t[2]=u*a[2]+s*r[2],t}function hermite(t,a,r,n,e,o){var u=o*o,s=u*(2*o-3)+1,i=u*(o-2)+o,c=u*(o-1),l=u*(3-2*o);return t[0]=a[0]*s+r[0]*i+n[0]*c+e[0]*l,t[1]=a[1]*s+r[1]*i+n[1]*c+e[1]*l,t[2]=a[2]*s+r[2]*i+n[2]*c+e[2]*l,t}function bezier(t,a,r,n,e,o){var u=1-o,s=u*u,i=o*o,c=s*u,l=3*o*s,$=3*i*u,h=i*o;return t[0]=a[0]*c+r[0]*l+n[0]*$+e[0]*h,t[1]=a[1]*c+r[1]*l+n[1]*$+e[1]*h,t[2]=a[2]*c+r[2]*l+n[2]*$+e[2]*h,t}function random$3(t,a){a=a||1;var r=2*RANDOM()*Math.PI,n=2*RANDOM()-1,e=Math.sqrt(1-n*n)*a;return t[0]=Math.cos(r)*e,t[1]=Math.sin(r)*e,t[2]=n*a,t}function transformMat4$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=r[3]*n+r[7]*e+r[11]*o+r[15];return u=u||1,t[0]=(r[0]*n+r[4]*e+r[8]*o+r[12])/u,t[1]=(r[1]*n+r[5]*e+r[9]*o+r[13])/u,t[2]=(r[2]*n+r[6]*e+r[10]*o+r[14])/u,t}function transformMat3$1(t,a,r){var n=a[0],e=a[1],o=a[2];return t[0]=n*r[0]+e*r[3]+o*r[6],t[1]=n*r[1]+e*r[4]+o*r[7],t[2]=n*r[2]+e*r[5]+o*r[8],t}function transformQuat$1(t,a,r){var n=r[0],e=r[1],o=r[2],u=r[3],s=a[0],i=a[1],c=a[2],l=e*c-o*i,$=o*s-n*c,h=n*i-e*s,f=e*h-o*$,M=o*l-n*h,m=n*$-e*l,d=2*u;return l*=d,$*=d,h*=d,f*=2,M*=2,m*=2,t[0]=s+l+f,t[1]=i+$+M,t[2]=c+h+m,t}function rotateX$2(t,a,r,n){var e=[],o=[];return e[0]=a[0]-r[0],e[1]=a[1]-r[1],e[2]=a[2]-r[2],o[0]=e[0],o[1]=e[1]*Math.cos(n)-e[2]*Math.sin(n),o[2]=e[1]*Math.sin(n)+e[2]*Math.cos(n),t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function rotateY$2(t,a,r,n){var e=[],o=[];return e[0]=a[0]-r[0],e[1]=a[1]-r[1],e[2]=a[2]-r[2],o[0]=e[2]*Math.sin(n)+e[0]*Math.cos(n),o[1]=e[1],o[2]=e[2]*Math.cos(n)-e[0]*Math.sin(n),t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function rotateZ$2(t,a,r,n){var e=[],o=[];return e[0]=a[0]-r[0],e[1]=a[1]-r[1],e[2]=a[2]-r[2],o[0]=e[0]*Math.cos(n)-e[1]*Math.sin(n),o[1]=e[0]*Math.sin(n)+e[1]*Math.cos(n),o[2]=e[2],t[0]=o[0]+r[0],t[1]=o[1]+r[1],t[2]=o[2]+r[2],t}function angle$1(t,a){var r=t[0],n=t[1],e=t[2],o=a[0],u=a[1],s=a[2],i=Math.sqrt((r*r+n*n+e*e)*(o*o+u*u+s*s)),c=i&&dot$4(t,a)/i;return Math.acos(Math.min(Math.max(c,-1),1))}function zero$2(t){return t[0]=0,t[1]=0,t[2]=0,t}function str$4(t){return"vec3("+t[0]+", "+t[1]+", "+t[2]+")"}function exactEquals$4(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]}function equals$4(t,a){var r=t[0],n=t[1],e=t[2],o=a[0],u=a[1],s=a[2];return Math.abs(r-o)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(o))&&Math.abs(n-u)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(u))&&Math.abs(e-s)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(s))}var sub$2=subtract$2,mul$4=multiply$4,div$2=divide$2,dist$2=distance$2,sqrDist$2=squaredDistance$2,len$4=length$4,sqrLen$4=squaredLength$4,forEach$2=function(){var t=create$4();return function(a,r,n,e,o,u){var s,i;for(r||(r=3),n||(n=0),i=e?Math.min(e*r+n,a.length):a.length,s=n;s0&&(u=1/Math.sqrt(u)),t[0]=r*u,t[1]=n*u,t[2]=e*u,t[3]=o*u,t}function dot$3(t,a){return t[0]*a[0]+t[1]*a[1]+t[2]*a[2]+t[3]*a[3]}function cross$1(t,a,r,n){var e=r[0]*n[1]-r[1]*n[0],o=r[0]*n[2]-r[2]*n[0],u=r[0]*n[3]-r[3]*n[0],s=r[1]*n[2]-r[2]*n[1],i=r[1]*n[3]-r[3]*n[1],c=r[2]*n[3]-r[3]*n[2],l=a[0],$=a[1],h=a[2],f=a[3];return t[0]=$*c-h*i+f*s,t[1]=-l*c+h*u-f*o,t[2]=l*i-$*u+f*e,t[3]=-l*s+$*o-h*e,t}function lerp$3(t,a,r,n){var e=a[0],o=a[1],u=a[2],s=a[3];return t[0]=e+n*(r[0]-e),t[1]=o+n*(r[1]-o),t[2]=u+n*(r[2]-u),t[3]=s+n*(r[3]-s),t}function random$2(t,a){var r,n,e,o,u,s;a=a||1;do{u=(r=2*RANDOM()-1)*r+(n=2*RANDOM()-1)*n}while(u>=1);do{s=(e=2*RANDOM()-1)*e+(o=2*RANDOM()-1)*o}while(s>=1);var i=Math.sqrt((1-u)/s);return t[0]=a*r,t[1]=a*n,t[2]=a*e*i,t[3]=a*o*i,t}function transformMat4$1(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3];return t[0]=r[0]*n+r[4]*e+r[8]*o+r[12]*u,t[1]=r[1]*n+r[5]*e+r[9]*o+r[13]*u,t[2]=r[2]*n+r[6]*e+r[10]*o+r[14]*u,t[3]=r[3]*n+r[7]*e+r[11]*o+r[15]*u,t}function transformQuat(t,a,r){var n=a[0],e=a[1],o=a[2],u=r[0],s=r[1],i=r[2],c=r[3],l=c*n+s*o-i*e,$=c*e+i*n-u*o,h=c*o+u*e-s*n,f=-u*n-s*e-i*o;return t[0]=l*c+f*-u+$*-i-h*-s,t[1]=$*c+f*-s+h*-u-l*-i,t[2]=h*c+f*-i+l*-s-$*-u,t[3]=a[3],t}function zero$1(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=0,t}function str$3(t){return"vec4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}function exactEquals$3(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]}function equals$3(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=a[0],s=a[1],i=a[2],c=a[3];return Math.abs(r-u)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(u))&&Math.abs(n-s)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(s))&&Math.abs(e-i)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(i))&&Math.abs(o-c)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(c))}var sub$1=subtract$1,mul$3=multiply$3,div$1=divide$1,dist$1=distance$1,sqrDist$1=squaredDistance$1,len$3=length$3,sqrLen$3=squaredLength$3,forEach$1=function(){var t=create$3();return function(a,r,n,e,o,u){var s,i;for(r||(r=4),n||(n=0),i=e?Math.min(e*r+n,a.length):a.length,s=n;sEPSILON?(t[0]=a[0]/n,t[1]=a[1]/n,t[2]=a[2]/n):(t[0]=1,t[1]=0,t[2]=0),r}function getAngle(t,a){var r=dot$2(t,a);return Math.acos(2*r*r-1)}function multiply$2(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[0],i=r[1],c=r[2],l=r[3];return t[0]=n*l+u*s+e*c-o*i,t[1]=e*l+u*i+o*s-n*c,t[2]=o*l+u*c+n*i-e*s,t[3]=u*l-n*s-e*i-o*c,t}function rotateX$1(t,a,r){r*=.5;var n=a[0],e=a[1],o=a[2],u=a[3],s=Math.sin(r),i=Math.cos(r);return t[0]=n*i+u*s,t[1]=e*i+o*s,t[2]=o*i-e*s,t[3]=u*i-n*s,t}function rotateY$1(t,a,r){r*=.5;var n=a[0],e=a[1],o=a[2],u=a[3],s=Math.sin(r),i=Math.cos(r);return t[0]=n*i-o*s,t[1]=e*i+u*s,t[2]=o*i+n*s,t[3]=u*i-e*s,t}function rotateZ$1(t,a,r){r*=.5;var n=a[0],e=a[1],o=a[2],u=a[3],s=Math.sin(r),i=Math.cos(r);return t[0]=n*i+e*s,t[1]=e*i-n*s,t[2]=o*i+u*s,t[3]=u*i-o*s,t}function calculateW(t,a){var r=a[0],n=a[1],e=a[2];return t[0]=r,t[1]=n,t[2]=e,t[3]=Math.sqrt(Math.abs(1-r*r-n*n-e*e)),t}function exp(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=Math.sqrt(r*r+n*n+e*e),s=Math.exp(o),i=u>0?s*Math.sin(u)/u:0;return t[0]=r*i,t[1]=n*i,t[2]=e*i,t[3]=s*Math.cos(u),t}function ln(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=Math.sqrt(r*r+n*n+e*e),s=u>0?Math.atan2(u,o)/u:0;return t[0]=r*s,t[1]=n*s,t[2]=e*s,t[3]=.5*Math.log(r*r+n*n+e*e+o*o),t}function pow(t,a,r){return ln(t,a),scale$2(t,t,r),exp(t,t),t}function slerp(t,a,r,n){var e,o,u,s,i,c=a[0],l=a[1],$=a[2],h=a[3],f=r[0],M=r[1],m=r[2],d=r[3];return(o=c*f+l*M+$*m+h*d)<0&&(o=-o,f=-f,M=-M,m=-m,d=-d),1-o>EPSILON?(e=Math.acos(o),u=Math.sin(e),s=Math.sin((1-n)*e)/u,i=Math.sin(n*e)/u):(s=1-n,i=n),t[0]=s*c+i*f,t[1]=s*l+i*M,t[2]=s*$+i*m,t[3]=s*h+i*d,t}function random$1(t){var a=RANDOM(),r=RANDOM(),n=RANDOM(),e=Math.sqrt(1-a),o=Math.sqrt(a);return t[0]=e*Math.sin(2*Math.PI*r),t[1]=e*Math.cos(2*Math.PI*r),t[2]=o*Math.sin(2*Math.PI*n),t[3]=o*Math.cos(2*Math.PI*n),t}function invert$1(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r*r+n*n+e*e+o*o,s=u?1/u:0;return t[0]=-r*s,t[1]=-n*s,t[2]=-e*s,t[3]=o*s,t}function conjugate$1(t,a){return t[0]=-a[0],t[1]=-a[1],t[2]=-a[2],t[3]=a[3],t}function fromMat3(t,a){var r,n=a[0]+a[4]+a[8];if(n>0)r=Math.sqrt(n+1),t[3]=.5*r,r=.5/r,t[0]=(a[5]-a[7])*r,t[1]=(a[6]-a[2])*r,t[2]=(a[1]-a[3])*r;else{var e=0;a[4]>a[0]&&(e=1),a[8]>a[3*e+e]&&(e=2);var o=(e+1)%3,u=(e+2)%3;r=Math.sqrt(a[3*e+e]-a[3*o+o]-a[3*u+u]+1),t[e]=.5*r,r=.5/r,t[3]=(a[3*o+u]-a[3*u+o])*r,t[o]=(a[3*o+e]+a[3*e+o])*r,t[u]=(a[3*u+e]+a[3*e+u])*r}return t}function fromEuler(t,a,r,n){var e=arguments.length>4&&void 0!==arguments[4]?arguments[4]:ANGLE_ORDER,o=Math.PI/360;a*=o,n*=o,r*=o;var u=Math.sin(a),s=Math.cos(a),i=Math.sin(r),c=Math.cos(r),l=Math.sin(n),$=Math.cos(n);switch(e){case"xyz":t[0]=u*c*$+s*i*l,t[1]=s*i*$-u*c*l,t[2]=s*c*l+u*i*$,t[3]=s*c*$-u*i*l;break;case"xzy":t[0]=u*c*$-s*i*l,t[1]=s*i*$-u*c*l,t[2]=s*c*l+u*i*$,t[3]=s*c*$+u*i*l;break;case"yxz":t[0]=u*c*$+s*i*l,t[1]=s*i*$-u*c*l,t[2]=s*c*l-u*i*$,t[3]=s*c*$+u*i*l;break;case"yzx":t[0]=u*c*$+s*i*l,t[1]=s*i*$+u*c*l,t[2]=s*c*l-u*i*$,t[3]=s*c*$-u*i*l;break;case"zxy":t[0]=u*c*$-s*i*l,t[1]=s*i*$+u*c*l,t[2]=s*c*l+u*i*$,t[3]=s*c*$-u*i*l;break;case"zyx":t[0]=u*c*$-s*i*l,t[1]=s*i*$+u*c*l,t[2]=s*c*l-u*i*$,t[3]=s*c*$+u*i*l;break;default:throw new Error("Unknown angle order "+e)}return t}function str$2(t){return"quat("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+")"}var clone$2=clone$3,fromValues$2=fromValues$3,copy$2=copy$3,set$2=set$3,add$2=add$3,mul$2=multiply$2,scale$2=scale$3,dot$2=dot$3,lerp$2=lerp$3,length$2=length$3,len$2=length$2,squaredLength$2=squaredLength$3,sqrLen$2=squaredLength$2,normalize$2=normalize$3,exactEquals$2=exactEquals$3;function equals$2(t,a){return Math.abs(dot$3(t,a))>=1-EPSILON}var rotationTo=function(){var t=create$4(),a=fromValues$4(1,0,0),r=fromValues$4(0,1,0);return function(n,e,o){var u=dot$4(e,o);return u<-.999999?(cross$2(t,a,e),len$4(t)<1e-6&&cross$2(t,r,e),normalize$4(t,t),setAxisAngle(n,t,Math.PI),n):u>.999999?(n[0]=0,n[1]=0,n[2]=0,n[3]=1,n):(cross$2(t,e,o),n[0]=t[0],n[1]=t[1],n[2]=t[2],n[3]=1+u,normalize$2(n,n))}}(),sqlerp=function(){var t=create$2(),a=create$2();return function(r,n,e,o,u,s){return slerp(t,n,u,s),slerp(a,e,o,s),slerp(r,t,a,2*s*(1-s)),r}}(),setAxes=function(){var t=create$6();return function(a,r,n,e){return t[0]=n[0],t[3]=n[1],t[6]=n[2],t[1]=e[0],t[4]=e[1],t[7]=e[2],t[2]=-r[0],t[5]=-r[1],t[8]=-r[2],normalize$2(a,fromMat3(a,t))}}(),quat=Object.freeze({__proto__:null,create:create$2,identity:identity$1,setAxisAngle:setAxisAngle,getAxisAngle:getAxisAngle,getAngle:getAngle,multiply:multiply$2,rotateX:rotateX$1,rotateY:rotateY$1,rotateZ:rotateZ$1,calculateW:calculateW,exp:exp,ln:ln,pow:pow,slerp:slerp,random:random$1,invert:invert$1,conjugate:conjugate$1,fromMat3:fromMat3,fromEuler:fromEuler,str:str$2,clone:clone$2,fromValues:fromValues$2,copy:copy$2,set:set$2,add:add$2,mul:mul$2,scale:scale$2,dot:dot$2,lerp:lerp$2,length:length$2,len:len$2,squaredLength:squaredLength$2,sqrLen:sqrLen$2,normalize:normalize$2,exactEquals:exactEquals$2,equals:equals$2,rotationTo:rotationTo,sqlerp:sqlerp,setAxes:setAxes});function create$1(){var t=new ARRAY_TYPE(8);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[4]=0,t[5]=0,t[6]=0,t[7]=0),t[3]=1,t}function clone$1(t){var a=new ARRAY_TYPE(8);return a[0]=t[0],a[1]=t[1],a[2]=t[2],a[3]=t[3],a[4]=t[4],a[5]=t[5],a[6]=t[6],a[7]=t[7],a}function fromValues$1(t,a,r,n,e,o,u,s){var i=new ARRAY_TYPE(8);return i[0]=t,i[1]=a,i[2]=r,i[3]=n,i[4]=e,i[5]=o,i[6]=u,i[7]=s,i}function fromRotationTranslationValues(t,a,r,n,e,o,u){var s=new ARRAY_TYPE(8);s[0]=t,s[1]=a,s[2]=r,s[3]=n;var i=.5*e,c=.5*o,l=.5*u;return s[4]=i*n+c*r-l*a,s[5]=c*n+l*t-i*r,s[6]=l*n+i*a-c*t,s[7]=-i*t-c*a-l*r,s}function fromRotationTranslation(t,a,r){var n=.5*r[0],e=.5*r[1],o=.5*r[2],u=a[0],s=a[1],i=a[2],c=a[3];return t[0]=u,t[1]=s,t[2]=i,t[3]=c,t[4]=n*c+e*i-o*s,t[5]=e*c+o*u-n*i,t[6]=o*c+n*s-e*u,t[7]=-n*u-e*s-o*i,t}function fromTranslation(t,a){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t[4]=.5*a[0],t[5]=.5*a[1],t[6]=.5*a[2],t[7]=0,t}function fromRotation(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=0,t[5]=0,t[6]=0,t[7]=0,t}function fromMat4(t,a){var r=create$2();getRotation(r,a);var n=new ARRAY_TYPE(3);return getTranslation$1(n,a),fromRotationTranslation(t,r,n),t}function copy$1(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[4]=a[4],t[5]=a[5],t[6]=a[6],t[7]=a[7],t}function identity(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t[6]=0,t[7]=0,t}function set$1(t,a,r,n,e,o,u,s,i){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t[4]=o,t[5]=u,t[6]=s,t[7]=i,t}var getReal=copy$2;function getDual(t,a){return t[0]=a[4],t[1]=a[5],t[2]=a[6],t[3]=a[7],t}var setReal=copy$2;function setDual(t,a){return t[4]=a[0],t[5]=a[1],t[6]=a[2],t[7]=a[3],t}function getTranslation(t,a){var r=a[4],n=a[5],e=a[6],o=a[7],u=-a[0],s=-a[1],i=-a[2],c=a[3];return t[0]=2*(r*c+o*u+n*i-e*s),t[1]=2*(n*c+o*s+e*u-r*i),t[2]=2*(e*c+o*i+r*s-n*u),t}function translate(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=.5*r[0],i=.5*r[1],c=.5*r[2],l=a[4],$=a[5],h=a[6],f=a[7];return t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=u*s+e*c-o*i+l,t[5]=u*i+o*s-n*c+$,t[6]=u*c+n*i-e*s+h,t[7]=-n*s-e*i-o*c+f,t}function rotateX(t,a,r){var n=-a[0],e=-a[1],o=-a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=s*u+l*n+i*o-c*e,h=i*u+l*e+c*n-s*o,f=c*u+l*o+s*e-i*n,M=l*u-s*n-i*e-c*o;return rotateX$1(t,a,r),n=t[0],e=t[1],o=t[2],u=t[3],t[4]=$*u+M*n+h*o-f*e,t[5]=h*u+M*e+f*n-$*o,t[6]=f*u+M*o+$*e-h*n,t[7]=M*u-$*n-h*e-f*o,t}function rotateY(t,a,r){var n=-a[0],e=-a[1],o=-a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=s*u+l*n+i*o-c*e,h=i*u+l*e+c*n-s*o,f=c*u+l*o+s*e-i*n,M=l*u-s*n-i*e-c*o;return rotateY$1(t,a,r),n=t[0],e=t[1],o=t[2],u=t[3],t[4]=$*u+M*n+h*o-f*e,t[5]=h*u+M*e+f*n-$*o,t[6]=f*u+M*o+$*e-h*n,t[7]=M*u-$*n-h*e-f*o,t}function rotateZ(t,a,r){var n=-a[0],e=-a[1],o=-a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=s*u+l*n+i*o-c*e,h=i*u+l*e+c*n-s*o,f=c*u+l*o+s*e-i*n,M=l*u-s*n-i*e-c*o;return rotateZ$1(t,a,r),n=t[0],e=t[1],o=t[2],u=t[3],t[4]=$*u+M*n+h*o-f*e,t[5]=h*u+M*e+f*n-$*o,t[6]=f*u+M*o+$*e-h*n,t[7]=M*u-$*n-h*e-f*o,t}function rotateByQuatAppend(t,a,r){var n=r[0],e=r[1],o=r[2],u=r[3],s=a[0],i=a[1],c=a[2],l=a[3];return t[0]=s*u+l*n+i*o-c*e,t[1]=i*u+l*e+c*n-s*o,t[2]=c*u+l*o+s*e-i*n,t[3]=l*u-s*n-i*e-c*o,s=a[4],i=a[5],c=a[6],l=a[7],t[4]=s*u+l*n+i*o-c*e,t[5]=i*u+l*e+c*n-s*o,t[6]=c*u+l*o+s*e-i*n,t[7]=l*u-s*n-i*e-c*o,t}function rotateByQuatPrepend(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[0],i=r[1],c=r[2],l=r[3];return t[0]=n*l+u*s+e*c-o*i,t[1]=e*l+u*i+o*s-n*c,t[2]=o*l+u*c+n*i-e*s,t[3]=u*l-n*s-e*i-o*c,s=r[4],i=r[5],c=r[6],l=r[7],t[4]=n*l+u*s+e*c-o*i,t[5]=e*l+u*i+o*s-n*c,t[6]=o*l+u*c+n*i-e*s,t[7]=u*l-n*s-e*i-o*c,t}function rotateAroundAxis(t,a,r,n){if(Math.abs(n)0){r=Math.sqrt(r);var n=a[0]/r,e=a[1]/r,o=a[2]/r,u=a[3]/r,s=a[4],i=a[5],c=a[6],l=a[7],$=n*s+e*i+o*c+u*l;t[0]=n,t[1]=e,t[2]=o,t[3]=u,t[4]=(s-n*$)/r,t[5]=(i-e*$)/r,t[6]=(c-o*$)/r,t[7]=(l-u*$)/r}return t}function str$1(t){return"quat2("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+")"}function exactEquals$1(t,a){return t[0]===a[0]&&t[1]===a[1]&&t[2]===a[2]&&t[3]===a[3]&&t[4]===a[4]&&t[5]===a[5]&&t[6]===a[6]&&t[7]===a[7]}function equals$1(t,a){var r=t[0],n=t[1],e=t[2],o=t[3],u=t[4],s=t[5],i=t[6],c=t[7],l=a[0],$=a[1],h=a[2],f=a[3],M=a[4],m=a[5],d=a[6],v=a[7];return Math.abs(r-l)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(l))&&Math.abs(n-$)<=EPSILON*Math.max(1,Math.abs(n),Math.abs($))&&Math.abs(e-h)<=EPSILON*Math.max(1,Math.abs(e),Math.abs(h))&&Math.abs(o-f)<=EPSILON*Math.max(1,Math.abs(o),Math.abs(f))&&Math.abs(u-M)<=EPSILON*Math.max(1,Math.abs(u),Math.abs(M))&&Math.abs(s-m)<=EPSILON*Math.max(1,Math.abs(s),Math.abs(m))&&Math.abs(i-d)<=EPSILON*Math.max(1,Math.abs(i),Math.abs(d))&&Math.abs(c-v)<=EPSILON*Math.max(1,Math.abs(c),Math.abs(v))}var quat2=Object.freeze({__proto__:null,create:create$1,clone:clone$1,fromValues:fromValues$1,fromRotationTranslationValues:fromRotationTranslationValues,fromRotationTranslation:fromRotationTranslation,fromTranslation:fromTranslation,fromRotation:fromRotation,fromMat4:fromMat4,copy:copy$1,identity:identity,set:set$1,getReal:getReal,getDual:getDual,setReal:setReal,setDual:setDual,getTranslation:getTranslation,translate:translate,rotateX:rotateX,rotateY:rotateY,rotateZ:rotateZ,rotateByQuatAppend:rotateByQuatAppend,rotateByQuatPrepend:rotateByQuatPrepend,rotateAroundAxis:rotateAroundAxis,add:add$1,multiply:multiply$1,mul:mul$1,scale:scale$1,dot:dot$1,lerp:lerp$1,invert:invert,conjugate:conjugate,length:length$1,len:len$1,squaredLength:squaredLength$1,sqrLen:sqrLen$1,normalize:normalize$1,str:str$1,exactEquals:exactEquals$1,equals:equals$1});function create(){var t=new ARRAY_TYPE(2);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0),t}function clone(t){var a=new ARRAY_TYPE(2);return a[0]=t[0],a[1]=t[1],a}function fromValues(t,a){var r=new ARRAY_TYPE(2);return r[0]=t,r[1]=a,r}function copy(t,a){return t[0]=a[0],t[1]=a[1],t}function set(t,a,r){return t[0]=a,t[1]=r,t}function add(t,a,r){return t[0]=a[0]+r[0],t[1]=a[1]+r[1],t}function subtract(t,a,r){return t[0]=a[0]-r[0],t[1]=a[1]-r[1],t}function multiply(t,a,r){return t[0]=a[0]*r[0],t[1]=a[1]*r[1],t}function divide(t,a,r){return t[0]=a[0]/r[0],t[1]=a[1]/r[1],t}function ceil(t,a){return t[0]=Math.ceil(a[0]),t[1]=Math.ceil(a[1]),t}function floor(t,a){return t[0]=Math.floor(a[0]),t[1]=Math.floor(a[1]),t}function min(t,a,r){return t[0]=Math.min(a[0],r[0]),t[1]=Math.min(a[1],r[1]),t}function max(t,a,r){return t[0]=Math.max(a[0],r[0]),t[1]=Math.max(a[1],r[1]),t}function round(t,a){return t[0]=Math.round(a[0]),t[1]=Math.round(a[1]),t}function scale(t,a,r){return t[0]=a[0]*r,t[1]=a[1]*r,t}function scaleAndAdd(t,a,r,n){return t[0]=a[0]+r[0]*n,t[1]=a[1]+r[1]*n,t}function distance(t,a){var r=a[0]-t[0],n=a[1]-t[1];return Math.hypot(r,n)}function squaredDistance(t,a){var r=a[0]-t[0],n=a[1]-t[1];return r*r+n*n}function length(t){var a=t[0],r=t[1];return Math.hypot(a,r)}function squaredLength(t){var a=t[0],r=t[1];return a*a+r*r}function negate(t,a){return t[0]=-a[0],t[1]=-a[1],t}function inverse(t,a){return t[0]=1/a[0],t[1]=1/a[1],t}function normalize(t,a){var r=a[0],n=a[1],e=r*r+n*n;return e>0&&(e=1/Math.sqrt(e)),t[0]=a[0]*e,t[1]=a[1]*e,t}function dot(t,a){return t[0]*a[0]+t[1]*a[1]}function cross(t,a,r){var n=a[0]*r[1]-a[1]*r[0];return t[0]=t[1]=0,t[2]=n,t}function lerp(t,a,r,n){var e=a[0],o=a[1];return t[0]=e+n*(r[0]-e),t[1]=o+n*(r[1]-o),t}function random(t,a){a=a||1;var r=2*RANDOM()*Math.PI;return t[0]=Math.cos(r)*a,t[1]=Math.sin(r)*a,t}function transformMat2(t,a,r){var n=a[0],e=a[1];return t[0]=r[0]*n+r[2]*e,t[1]=r[1]*n+r[3]*e,t}function transformMat2d(t,a,r){var n=a[0],e=a[1];return t[0]=r[0]*n+r[2]*e+r[4],t[1]=r[1]*n+r[3]*e+r[5],t}function transformMat3(t,a,r){var n=a[0],e=a[1];return t[0]=r[0]*n+r[3]*e+r[6],t[1]=r[1]*n+r[4]*e+r[7],t}function transformMat4(t,a,r){var n=a[0],e=a[1];return t[0]=r[0]*n+r[4]*e+r[12],t[1]=r[1]*n+r[5]*e+r[13],t}function rotate(t,a,r,n){var e=a[0]-r[0],o=a[1]-r[1],u=Math.sin(n),s=Math.cos(n);return t[0]=e*s-o*u+r[0],t[1]=e*u+o*s+r[1],t}function angle(t,a){var r=t[0],n=t[1],e=a[0],o=a[1],u=Math.sqrt((r*r+n*n)*(e*e+o*o)),s=u&&(r*e+n*o)/u;return Math.acos(Math.min(Math.max(s,-1),1))}function zero(t){return t[0]=0,t[1]=0,t}function str(t){return"vec2("+t[0]+", "+t[1]+")"}function exactEquals(t,a){return t[0]===a[0]&&t[1]===a[1]}function equals(t,a){var r=t[0],n=t[1],e=a[0],o=a[1];return Math.abs(r-e)<=EPSILON*Math.max(1,Math.abs(r),Math.abs(e))&&Math.abs(n-o)<=EPSILON*Math.max(1,Math.abs(n),Math.abs(o))}var len=length,sub=subtract,mul=multiply,div=divide,dist=distance,sqrDist=squaredDistance,sqrLen=squaredLength,forEach=function(){var t=create();return function(a,r,n,e,o,u){var s,i;for(r||(r=2),n||(n=0),i=e?Math.min(e*r+n,a.length):a.length,s=n;s=0&&i<=1&&y>=0&&y<=1}function triangleArea(o,n,t){return(n[0]-o[0])*(t[1]-o[1])-(t[0]-o[0])*(n[1]-o[1])}function isLeft(o,n,t){return triangleArea(o,n,t)>0}function isLeftOn(o,n,t){return triangleArea(o,n,t)>=0}function isRight(o,n,t){return triangleArea(o,n,t)<0}function isRightOn(o,n,t){return triangleArea(o,n,t)<=0}var tmpPoint1=[],tmpPoint2=[];function collinear(o,n,t,e){if(e){var l=tmpPoint1,p=tmpPoint2;l[0]=n[0]-o[0],l[1]=n[1]-o[1],p[0]=t[0]-n[0],p[1]=t[1]-n[1];var g=l[0]*p[0]+l[1]*p[1],r=Math.sqrt(l[0]*l[0]+l[1]*l[1]),i=Math.sqrt(p[0]*p[0]+p[1]*p[1]);return Math.acos(g/(r*i))t[n][0])&&(n=e);return!isLeft(polygonAt(o,n-1),polygonAt(o,n),polygonAt(o,n+1))&&(polygonReverse(o),!0)}function polygonReverse(o){for(var n=[],t=o.length,e=0;e!==t;e++)n.push(o.pop());for(e=0;e!==t;e++)o[e]=n[e]}function polygonIsReflex(o,n){return isRight(polygonAt(o,n-1),polygonAt(o,n),polygonAt(o,n+1))}var tmpLine1=[],tmpLine2=[];function polygonCanSee(o,n,t){var e,l,p=tmpLine1,g=tmpLine2;if(isLeftOn(polygonAt(o,n+1),polygonAt(o,n),polygonAt(o,t))&&isRightOn(polygonAt(o,n-1),polygonAt(o,n),polygonAt(o,t)))return!1;l=sqdist(polygonAt(o,n),polygonAt(o,t));for(var r=0;r!==o.length;++r)if((r+1)%o.length!==n&&r!==n&&isLeftOn(polygonAt(o,n),polygonAt(o,t),polygonAt(o,r+1))&&isRightOn(polygonAt(o,n),polygonAt(o,t),polygonAt(o,r))&&(p[0]=polygonAt(o,n),p[1]=polygonAt(o,t),g[0]=polygonAt(o,r),g[1]=polygonAt(o,r+1),e=lineInt(p,g),sqdist(polygonAt(o,n),e)0?polygonSlice(o,n):[o]}function polygonSlice(o,n){if(0===n.length)return[o];if(n instanceof Array&&n.length&&n[0]instanceof Array&&2===n[0].length&&n[0][0]instanceof Array){for(var t=[o],e=0;ep)return console.warn("quickDecomp: max level ("+p+") reached."),n;for(var R=0;Rf&&(f+=o.length),a=Number.MAX_VALUE,f3&&e>=0;--e)collinear(polygonAt(o,e-1),polygonAt(o,e),polygonAt(o,e+1),n)&&(o.splice(e%o.length,1),t++);return t}function polygonRemoveDuplicatePoints(o,n){for(var t=o.length-1;t>=1;--t)for(var e=o[t],l=t-1;l>=0;--l)points_eq(e,o[l],n)&&o.splice(t,1)}function scalar_eq(o,n,t){return t=t||0,Math.abs(o-n)<=t}function points_eq(o,n,t){return scalar_eq(o[0],n[0],t)&&scalar_eq(o[1],n[1],t)}self.polyDecomp={decomp:polygonDecomp,quickDecomp:polygonQuickDecomp,isSimple:polygonIsSimple,removeCollinearPoints:polygonRemoveCollinearPoints,removeDuplicatePoints:polygonRemoveDuplicatePoints,makeCCW:polygonMakeCCW}; } // lib/c3.js { let isReady=!1,hasAppStarted=!1,buildMode="dev";const internalApiToken=Symbol("Construct internal API token");let internalApiTokenAccessesRemaining=16;const C3=self.C3=class{constructor(){throw TypeError("static class can't be instantiated")}static _GetInternalAPIToken(){if(internalApiTokenAccessesRemaining<=0)throw new Error("cannot obtain internal API token");return--internalApiTokenAccessesRemaining,internalApiToken}static SetReady(){isReady=!0}static IsReady(){return isReady}static SetAppStarted(){hasAppStarted=!0}static HasAppStarted(){return hasAppStarted}static SetBuildMode(e){buildMode=e}static GetBuildMode(){return buildMode}static IsReleaseBuild(){return"final"===buildMode}};C3.isDebug=!1,C3.isDebugDefend=!1,C3.hardwareConcurrency=navigator.hardwareConcurrency||2,self.C3X={}; } // ../lib/queryParser.js { const C3=self.C3;C3.QueryParser=class{constructor(e){this._queryString=e,this._parameters=new Map,this._Parse()}_Parse(){let e=this._queryString;(e.startsWith("?")||e.startsWith("#"))&&(e=e.substr(1));const r=e.split("&");for(const e of r)this._ParseParameter(e)}_ParseParameter(e){if(!e)return;if(!e.includes("="))return void this._parameters.set(e,null);const r=e.indexOf("="),t=decodeURIComponent(e.substring(0,r)),s=decodeURIComponent(e.substring(r+1));this._parameters.set(t,s)}LogAll(){for(const e of this._parameters)console.log("[QueryParser] Parameter '"+e[0]+"' = "+(null===e[1]?"null":"'"+e[1]+"'"))}Has(e){return this._parameters.has(e)}Get(e){const r=this._parameters.get(e);return void 0===r?null:r}ClearHash(){history.replaceState("",document.title,location.pathname+location.search)}Reparse(e){this._queryString=e,this._parameters.clear(),this._Parse()}},C3.QueryString=new C3.QueryParser(location.search),C3.LocationHashString=new C3.QueryParser(location.hash),C3.QueryString.Has("perf")&&(C3.isPerformanceProfiling=!0),"dev"!==C3.QueryString.Get("mode")&&C3.SetBuildMode("final"); } // ../lib/detect/detect.js { const C3=self.C3,UNKNOWN="(unknown)";C3.Platform={OS:UNKNOWN,OSVersion:UNKNOWN,Browser:UNKNOWN,BrowserVersion:UNKNOWN,BrowserVersionNumber:NaN,BrowserEngine:UNKNOWN,Context:"browser",IsDesktop:!0,IsMobile:!1,IsAppleOS:!1,IsIpadOS:!1,GetDetailedInfo:async()=>{}};const windowsNTVerMap=new Map([[5,"2000"],[5.1,"XP"],[5.2,"XP"],[6,"Vista"],[6.1,"7"],[6.2,"8"],[6.3,"8.1"],[10,"10"]]);function GetWindowsNTVersionName(r){const o=parseFloat(r),e=windowsNTVerMap.get(o);return e||(o>=13?"11":"NT "+r)}const uaStr=navigator.userAgent,uaData=navigator["userAgentData"];if(uaData&&uaData["brands"].length>0){C3.Platform.OS=uaData["platform"],C3.Platform.IsMobile=uaData["mobile"],C3.Platform.IsDesktop=!C3.Platform.IsMobile;const r=new Map([["Google Chrome","Chrome"],["Microsoft Edge","Edge"],["Opera","Opera"],["Opera GX","Opera GX"],["Mozilla Firefox","Firefox"],["Apple Safari","Safari"],["NW.js","NW.js"]]),o=new Map([["Chromium","Chromium"],["Gecko","Gecko"],["WebKit","WebKit"]]);function ReadBrandList(e){let t="",a="",s="",n="";for(const i of e){const e=r.get(i["brand"]);!t&&e&&(t=e,a=i["version"]);const m=o.get(i["brand"]);!s&&m&&(s=m,n=i["version"])}t||"Chromium"!==s||(C3.Platform.Browser="Chromium",C3.Platform.BrowserVersion=n),C3.Platform.Browser=t||UNKNOWN,C3.Platform.BrowserVersion=a||UNKNOWN,C3.Platform.BrowserEngine=s||UNKNOWN}ReadBrandList(uaData["brands"]);let e=!1;C3.Platform.GetDetailedInfo=async()=>{if(!e)try{const r=await navigator["userAgentData"]["getHighEntropyValues"](["platformVersion","fullVersionList"]);ReadBrandList(r["fullVersionList"]),"Windows"===C3.Platform.OS?C3.Platform.OSVersion=GetWindowsNTVersionName(r["platformVersion"]):C3.Platform.OSVersion=r["platformVersion"],e=!0}catch(r){console.warn("Failed to get detailed user agent information: ",r)}}}else{function RunTest(r,o){const e=Array.isArray(r)?r:[r];for(const r of e){const e=r.exec(uaStr);if(e){o(e);break}}}RunTest(/windows\s+nt\s+([\d\.]+)/i,r=>{C3.Platform.OS="Windows";const o=r[1];C3.Platform.OSVersion=GetWindowsNTVersionName(o)}),RunTest(/mac\s+os\s+x\s+([\d\._]+)/i,r=>{C3.Platform.OS="macOS",C3.Platform.OSVersion=r[1].replace(/_/g,".")}),RunTest(/CrOS/,()=>{C3.Platform.OS="Chrome OS"}),RunTest(/linux|openbsd|freebsd|netbsd/i,()=>{C3.Platform.OS="Linux"}),RunTest(/android/i,()=>{C3.Platform.OS="Android"}),RunTest(/android\s+([\d\.]+)/i,r=>{C3.Platform.OS="Android",C3.Platform.OSVersion=r[1]}),C3.Platform.OS===UNKNOWN&&(RunTest(/(iphone|ipod|ipad)/i,r=>{C3.Platform.OS="iOS"}),RunTest([/iphone\s+os\s+([\d\._]+)/i,/ipad[^)]*os\s+([\d\._]+)/i],r=>{C3.Platform.OS="iOS",C3.Platform.OSVersion=r[1].replace(/_/g,".")}));const t=/chrome\//i.test(uaStr),a=/chromium\//i.test(uaStr),s=/edg\//i.test(uaStr),n=/OPR\//.test(uaStr),i=/nwjs/i.test(uaStr),m=/safari\//i.test(uaStr),l=/webkit/i.test(uaStr);s||n||RunTest(/chrome\/([\d\.]+)/i,r=>{C3.Platform.Browser="Chrome",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium"}),RunTest(/edg\/([\d\.]+)/i,r=>{C3.Platform.Browser="Edge",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium"}),RunTest(/OPR\/([\d\.]+)/,r=>{C3.Platform.Browser="Opera",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium"}),RunTest(/chromium\/([\d\.]+)/i,r=>{C3.Platform.Browser="Chromium",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium"}),RunTest(/nwjs\/[0-9.]+/i,r=>{C3.Platform.Browser="NW.js",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Chromium",C3.Platform.Context="nwjs"}),RunTest(/firefox\/([\d\.]+)/i,r=>{C3.Platform.Browser="Firefox",C3.Platform.BrowserVersion=r[1],C3.Platform.BrowserEngine="Gecko"}),!m||t||a||s||n||i||(C3.Platform.Browser="Safari",C3.Platform.BrowserEngine="WebKit",RunTest(/version\/([\d\.]+)/i,r=>{C3.Platform.BrowserVersion=r[1]}),RunTest(/crios\/([\d\.]+)/i,r=>{C3.Platform.Browser="Chrome for iOS",C3.Platform.BrowserVersion=r[1]}),RunTest(/fxios\/([\d\.]+)/i,r=>{C3.Platform.Browser="Firefox for iOS",C3.Platform.BrowserVersion=r[1]}),RunTest(/edgios\/([\d\.]+)/i,r=>{C3.Platform.Browser="Edge for iOS",C3.Platform.BrowserVersion=r[1]})),C3.Platform.BrowserEngine===UNKNOWN&&l&&(C3.Platform.BrowserEngine="WebKit"),"Android"===C3.Platform.OS&&"Safari"===C3.Platform.Browser&&(C3.Platform.Browser="Stock");const f=new Set(["Windows","macOS","Linux","Chrome OS"]).has(C3.Platform.OS)||"nwjs"===C3.Platform.Context;C3.Platform.IsDesktop=f,C3.Platform.IsMobile=!f}"Chrome"===C3.Platform.Browser&&"browser"===C3.Platform.Context&&/wv\)/.test(uaStr)&&(C3.Platform.Context="webview"),"nwjs"!==C3.Platform.Context&&"undefined"!=typeof window&&(window.matchMedia&&window.matchMedia("(display-mode: standalone)").matches||navigator["standalone"])&&(C3.Platform.Context="webapp"),C3.Platform.BrowserVersionNumber=parseFloat(C3.Platform.BrowserVersion);const looksLikeIPadOS="macOS"===C3.Platform.OS&&navigator["maxTouchPoints"]&&navigator["maxTouchPoints"]>2;looksLikeIPadOS&&(C3.Platform.OS="iOS",C3.Platform.OSVersion=C3.Platform.BrowserVersion,C3.Platform.IsDesktop=!1,C3.Platform.IsMobile=!0,C3.Platform.IsIpadOS=!0),C3.Platform.IsAppleOS="macOS"===C3.Platform.OS||"iOS"===C3.Platform.OS; } // ../lib/storage/kvStorage.js { "use strict";{const e=2,t="keyvaluepairs",r=new Map,n="undefined"!=typeof IDBObjectStore&&"function"==typeof IDBObjectStore.prototype.getAll,o="undefined"!=typeof IDBObjectStore&&"function"==typeof IDBObjectStore.prototype.getAllKeys;function s(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}function a(e){return new Promise((t,r)=>{e.oncomplete=()=>t(),e.onerror=()=>r(e.error),e.onabort=()=>r(e.error)})}function c(e,t){return u(e,t)}function i(e,t){return u(e,t,!0)}async function u(e,n,o=!1,s=!0){const a=await l(e);try{return n(a.transaction([t],o?"readwrite":"readonly"))}catch(t){if(s&&"InvalidStateError"===t["name"])return r.delete(e),u(e,n,o,!1);throw t}}function l(e){f(e);let t=r.get(e);return t instanceof Promise||(t=y(e),r.set(e,t),t.catch(t=>r.delete(e))),t}async function y(r){f(r);const n=indexedDB.open(r,e);return n.addEventListener("upgradeneeded",e=>{try{e.target.result.createObjectStore(t)}catch(e){console.error(`Failed to create objectstore for database ${r}`,e)}}),s(n)}function f(e){if("string"!=typeof e)throw new TypeError("expected string")}function d(e,r){const n=e.objectStore(t).openCursor();return new Promise(e=>{const t=[];n.onsuccess=n=>{const o=n.target.result;if(o){switch(r){case"entries":t.push([o.key,o.value]);break;case"keys":t.push(o.key);break;case"values":t.push(o.value)}o.continue()}else e(t)}})}class m{constructor(e){f(e),this.name=e}async ready(){await l(this.name)}set(e,r){return f(e),i(this.name,async n=>{const o=s(n.objectStore(t).put(r,e)),c=a(n);await Promise.all([c,o])})}get(e){return f(e),c(this.name,async r=>{const n=s(r.objectStore(t).get(e)),o=a(r),[c,i]=await Promise.all([o,n]);return i})}delete(e){return f(e),i(this.name,async r=>{const n=s(r.objectStore(t).delete(e)),o=a(r);await Promise.all([o,n])})}clear(){return i(this.name,async e=>{const r=s(e.objectStore(t).clear()),n=a(e);await Promise.all([n,r])})}keys(){return c(this.name,async e=>{let r;if(o){r=s(e.objectStore(t).getAllKeys())}else r=d(e,"keys");const n=a(e),[c,i]=await Promise.all([n,r]);return i})}values(){return c(this.name,async e=>{let r;if(n){r=s(e.objectStore(t).getAll())}else r=d(e,"values");const o=a(e),[c,i]=await Promise.all([o,r]);return i})}entries(){return c(this.name,async e=>{const t=d(e,"entries"),r=a(e),[n,o]=await Promise.all([r,t]);return o})}}self.KVStorageContainer=m} } // ../lib/storage/localForageAdaptor.js { "use strict";{const e=self.KVStorageContainer,t=[/no available storage method found/i,/an attempt was made to break through the security policy of the user agent/i,/the user denied permission to access the database/i,/a mutation operation was attempted on a database that did not allow mutations/i,/idbfactory\.open\(\) called in an invalid security context/i];new WeakMap;function r(e){throw new Error(`"${e}" is not implemented`)}function a(e){if("function"==typeof e)throw new Error("localforage callback API is not implemented; please use the promise API instead")}function o(e){return"object"==typeof e?new Promise(t=>{const{port1:r,port2:a}=new MessageChannel;a.onmessage=e=>t(e.data),r.postMessage(e)}):Promise.resolve(e)}class s{constructor(e){this._inst=e,this._isInMemory=!this._inst,this._isInMemory||"undefined"!=typeof indexedDB||(this._isInMemory=!0,console.warn("Unable to use local storage because IndexedDB API is not available")),this._memoryStorage=new Map}_MaybeSwitchToMemoryFallback(e){if(!this._isInMemory)for(const r of t)if(e&&r.test(e.message)){console.error("Unable to use local storage, reverting to in-memory store: ",e,e.message),this._isInMemory=!0;break}}async _getItemFallback(e){const t=this._memoryStorage.get(e),r=await o(t);return void 0===r?null:r}async _setItemFallback(e,t){t=await o(t),this._memoryStorage.set(e,t)}_removeItemFallback(e){this._memoryStorage.delete(e)}_clearFallback(){this._memoryStorage.clear()}_keysFallback(){return Array.from(this._memoryStorage.keys())}IsInMemory(){return this._isInMemory}GetMemoryStorage(){return this._memoryStorage}SetMemoryStorage(e){this._memoryStorage=e}async getItem(e,t){if(a(t),this._isInMemory)return await this._getItemFallback(e);let r;try{r=await this._inst.get(e)}catch(t){return this._MaybeSwitchToMemoryFallback(t),this._isInMemory?await this._getItemFallback(e):(console.error(`Error reading '${e}' from storage, returning null: `,t),null)}return void 0===r?null:r}async setItem(e,t,r){if(a(r),void 0===t&&(t=null),this._isInMemory)await this._setItemFallback(e,t);else try{await this._inst.set(e,t)}catch(r){if(this._MaybeSwitchToMemoryFallback(r),!this._isInMemory)throw r;await this._setItemFallback(e,t)}}async removeItem(e,t){if(a(t),this._isInMemory)this._removeItemFallback(e);else try{await this._inst.delete(e)}catch(t){this._MaybeSwitchToMemoryFallback(t),this._isInMemory?this._removeItemFallback(e):console.error(`Error removing '${e}' from storage: `,t)}}async clear(e){if(a(e),this._isInMemory)this._clearFallback();else try{await this._inst.clear()}catch(e){this._MaybeSwitchToMemoryFallback(e),this._isInMemory?this._clearFallback():console.error("Error clearing storage: ",e)}}async keys(e){if(a(e),this._isInMemory)return this._keysFallback();let t=[];try{t=await this._inst.keys()}catch(e){if(this._MaybeSwitchToMemoryFallback(e),this._isInMemory)return this._keysFallback();console.error("Error getting storage keys: ",e)}return t}ready(e){return a(e),this._isInMemory?Promise.resolve(!0):this._inst.ready()}createInstance(t){if(t.forceInMemoryFallback)return new s(null);{const r=t.name;if("string"!=typeof r)throw new TypeError("invalid store name");const a=new e(r);return new s(a)}}length(e){r("localforage.length()")}key(e,t){r("localforage.key()")}iterate(e,t){r("localforage.iterate()")}setDriver(e){r("localforage.setDriver()")}config(e){r("localforage.config()")}defineDriver(e){r("localforage.defineDriver()")}driver(){r("localforage.driver()")}supports(e){r("localforage.supports()")}dropInstance(){r("localforage.dropInstance()")}}self["localforage"]=new s(new e("localforage"))} } // ../lib/misc/supports.js { const C3=self.C3;if(C3.Supports={},C3.Supports.WebAnimations=(()=>{try{if("undefined"==typeof document)return!1;const e=document.createElement("div");if(void 0===e.animate)return!1;return void 0!==e.animate([{opacity:"0"},{opacity:"1"}],1e3).reverse}catch(e){return!1}})(),C3.Supports.DialogElement="undefined"!=typeof HTMLDialogElement,C3.Supports.RequestIdleCallback=!!self.requestIdleCallback,C3.Supports.ImageBitmap=!!self.createImageBitmap,C3.Supports.ImageBitmapOptions=!1,C3.Supports.ImageBitmapOptionsResize=!1,C3.Supports.ImageBitmap){try{self.createImageBitmap(new ImageData(32,32),{"premultiplyAlpha":"none"}).then(()=>{C3.Supports.ImageBitmapOptions=!0}).catch(()=>{C3.Supports.ImageBitmapOptions=!1})}catch(e){C3.Supports.ImageBitmapOptions=!1}try{self.createImageBitmap(new ImageData(32,32),{"resizeWidth":10,"resizeHeight":10}).then(e=>{C3.Supports.ImageBitmapOptionsResize=10===e.width&&10===e.height}).catch(()=>{C3.Supports.ImageBitmapOptionsResize=!1})}catch(e){C3.Supports.ImageBitmapOptionsResize=!1}}if(C3.Supports.ClipboardReadText=!(!navigator["clipboard"]||!navigator["clipboard"]["readText"]),C3.Supports.PermissionsQuery=!(!navigator["permissions"]||!navigator["permissions"]["query"]),C3.Supports.ClipboardPermissionsQuery=!1,C3.Supports.PermissionsQuery){const e={"name":"clipboard-read"};navigator["permissions"]["query"](e).then(()=>{C3.Supports.ClipboardPermissionsQuery=!0}).catch(()=>{C3.Supports.ClipboardPermissionsQuery=!1})}C3.Supports.AsyncClipboardApi=!!(navigator["permissions"]&&navigator["clipboard"]&&self["ClipboardItem"]),C3.Supports.Proxies="undefined"!=typeof Proxy,C3.Supports.DownloadAttribute=(()=>{if("undefined"==typeof document)return!1;return void 0!==document.createElement("a").download})(),C3.Supports.Fetch="function"==typeof fetch,C3.Supports.PersistentStorage=!!(self.isSecureContext&&"Opera"!==C3.Platform.Browser&&navigator["storage"]&&navigator["storage"]["persist"]),C3.Supports.StorageQuotaEstimate=!!(self.isSecureContext&&navigator["storage"]&&navigator["storage"]["estimate"]),C3.Supports.Fullscreen=(()=>{if("undefined"==typeof document)return!1;if("iOS"===C3.Platform.OS)return!1;const e=document.documentElement;return!!(e.requestFullscreen||e.msRequestFullscreen||e.mozRequestFullScreen||e.webkitRequestFullscreen)})(),C3.Supports.ImageDecoder=void 0!==self["ImageDecoder"],C3.Supports.WebCodecs=!!self["VideoEncoder"],C3.Supports.NativeFileSystemAPI=!!self["showOpenFilePicker"],C3.Supports.FileInputDirectory=function(){if("undefined"==typeof document)return!1;const e=document.createElement("input");return e.type="file","webkitdirectory"in e||"directory"in e}(),C3.Supports.QueryLocalFonts=!!self["queryLocalFonts"],C3.Supports.UserActivation=!!navigator["userActivation"],C3.Supports.CanvasToBlobWebP=!1,(async()=>{let e;"undefined"==typeof document?e=new OffscreenCanvas(32,32):(e=document.createElement("canvas"),e.width=32,e.height=32);const t=e.getContext("2d");t.fillStyle="blue",t.fillRect(0,0,32,32);let o=null;try{e["convertToBlob"]?o=await e["convertToBlob"]({"type":"image/webp","quality":1}):e.toBlob&&(o=await new Promise(t=>e.toBlob(t,"image/webp",1))),C3.Supports.CanvasToBlobWebP=o&&"image/webp"===o.type}catch(e){C3.Supports.CanvasToBlobWebP=!1}})(); } // ../lib/misc/polyfills.js { const C3=self.C3;String.prototype.replaceAll||(String.prototype.replaceAll=function(t,e){return this.replace(new RegExp(C3.EscapeRegex(t),"g"),e)}),Array.prototype.at||(Array.prototype.at=function(t){if((t=Math.trunc(t)||0)<0&&(t+=this.length),!(t<0||t>=this.length))return this[t]}),String.prototype.at||(String.prototype.at=function(t){if((t=Math.trunc(t)||0)<0&&(t+=this.length),!(t<0||t>=this.length))return this[t]}),RegExp.escape||(RegExp.escape=function(t){return String(t).replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}),Set.prototype.isSubsetOf||(Set.prototype.isSubsetOf=function(t){if(!(t instanceof Set))throw new TypeError("argument must be a Set");for(const e of this)if(!t.has(e))return!1;return!0}),Set.prototype.difference||(Set.prototype.difference=function(t){if(!(t instanceof Set))throw new TypeError("argument must be a Set");const e=new Set;for(const r of this)t.has(r)||e.add(r);return e}),Set.prototype.union||(Set.prototype.union=function(t){const e=new Set(this);for(const r of t)e.add(r);return e}),navigator["storage"]&&!navigator["storage"]["estimate"]&&navigator["webkitTemporaryStorage"]&&navigator["webkitTemporaryStorage"]["queryUsageAndQuota"]&&(navigator["storage"]["estimate"]=function(){return new Promise((t,e)=>navigator["webkitTemporaryStorage"]["queryUsageAndQuota"]((e,r)=>t({"usage":e,"quota":r}),e))}); } // lib/misc/assert.js { const C3=self.C3;function assertFail(e){let s="Assertion failure: "+e+"\n\nStack trace:\n"+C3.GetCallStack();console.error(s)}self.assert=function(e,s){e||assertFail(s)}; } // ../lib/misc/typeChecks.js { const C3=self.C3,C3X=self.C3X;C3.IsNumber=function(e){return"number"==typeof e},C3.IsFiniteNumber=function(e){return C3.IsNumber(e)&&isFinite(e)},C3.RequireNumber=function(e){if(!C3.IsNumber(e))throw new TypeError("expected number")},C3.RequireOptionalNumber=function(e){C3.IsNullOrUndefined(e)},C3.RequireNumberInRange=function(e,n,r){if(!C3.IsNumber(e)||isNaN(e)||n>e||r{console.log(`%c${e}`,"font-weight: bold",...t),logRafIds.set(e,-1)}))},C3.StartMeasure=function(e){performance.mark(e),measures||(measures=new Map),measures.has(e)||measures.set(e,{current:0,total:0,average:0,calls:1,toString:function(){return`${e} :: current => ${this.current.toPrecision(3)} :: average => ${this.average.toPrecision(3)} :: calls => ${this.calls}`}})},C3.EndMeasure=function(e){performance.measure(`measure-${e}`,e);const t=performance.getEntriesByName(`measure-${e}`)[0],r=measures.get(e);r.current=t.duration,r.total+=r.current,r.average=r.total/r.calls,console.log(r.toString()),r.calls++,performance.clearMarks(e),performance.clearMeasures(`measure-${e}`)},C3.GetCallStack=function(){return(new Error).stack},C3.Debugger=function(){},C3.cast=function(e,t){return e&&e instanceof t?e:null},C3.getName=function(e){return void 0===e?"undefined":null===e?"null":"boolean"==typeof e?"":C3.IsNumber(e)?"":C3.IsString(e)?"":C3.IsArray(e)?"":"symbol"==typeof e?"<"+e.toString()+">":C3.IsFunction(e)?e.name&&"Function"!==e.name?e.name:"":"object"==typeof e?e.constructor&&e.constructor.name&&"Object"!==e.constructor.name?e.constructor.name:"":""},C3.getType=function(e){return null===e?"null":Array.isArray(e)?"array":typeof e},C3.range=function*(e,t){if(!isFinite(Math.abs(e-t)))throw new Error("Invalid parameters");if(e>t)for(let r=e-1;r>=t;r--)yield r;else for(let r=e;r0||ctorProxyToObject.size>0){let e=[...new Set([...ctorObjectToProxy.keys()].map(e=>C3.getName(e)))].join(",");console.warn(`An object derived from DefendedBase was not protected with debugDefend(). This will disable some checks. See the coding guidelines! Possible affected class names: ${e}`),ctorObjectToProxy.clear(),ctorProxyToObject.clear()}}C3.DefendedBase=class{constructor(){if(!C3.isDebugDefend||!C3.Supports.Proxies)return;let e=new.target,t=Object.create(e.prototype),r=new Proxy(t,C3.DefendHandler);return ctorObjectToProxy.set(t,r),ctorProxyToObject.set(r,t),proxyToObject.set(r,t),-1===checkRafId&&(checkRafId=requestAnimationFrame(CheckDefendedObjectsUsedCorrectly)),r}},C3.debugDefend=function(e){if(C3.isDebugDefend&&C3.Supports.Proxies&&e instanceof C3.DefendedBase){if(!ctorProxyToObject.has(e))return e;let t=ctorProxyToObject.get(e);return ctorProxyToObject.delete(e),ctorObjectToProxy.delete(t),e}return C3.isDebug?Object.seal(e):e},C3.New=function(e,...t){let r;try{r=new e(...t)}catch(e){throw ctorProxyToObject.clear(),ctorObjectToProxy.clear(),e}return C3.isDebugDefend&&VerifyObjectPropertiesConsistent(e,r),C3.debugDefend(r)},C3.Release=function(e){let t=proxyToObject.get(e);t&&releasedObjects.set(t,C3.GetCallStack())},C3.WasReleased=function(e){let t=proxyToObject.get(e);return!!t&&!!releasedObjects.get(t)};let typeProperties=new Map;function getObjectPropertySet(e){let t=new Set;for(let r in e)t.add(r);return t}function VerifyObjectPropertiesConsistent(e,t){let r=getObjectPropertySet(t),n=typeProperties.get(e);if(n){let t=[];for(let e of n.values())r.has(e)?r.delete(e):t.push(e);C3.appendArray(t,[...r]),t.length&&console.warn(`[Defence] '${C3.getName(e)}' constructor creates inconsistent properties: ${t.join(", ")}`)}else typeProperties.set(e,r)}C3.PerfMark=class{constructor(e){this._name="",e&&this.start(e)}start(e){C3.isPerformanceProfiling&&(this._name=e,performance.mark(this._name+"-Start"))}end(){C3.isPerformanceProfiling&&(performance.mark(this._name+"-End"),performance.measure(this._name,this._name+"-Start",this._name+"-End"))}next(e){C3.isPerformanceProfiling&&(this.end(),this._name=e,performance.mark(this._name+"-Start"))}}; } // ../lib/misc/mathutil.js { const C3=globalThis.C3,glMatrix=globalThis.glMatrix,vec3=glMatrix.vec3,TWO_PI=2*Math.PI,D_TO_R=Math.PI/180,R_TO_D=180/Math.PI;C3.wrap=function(t,e,n){t=Math.floor(t),e=Math.floor(e);const r=(n=Math.floor(n))-e;if(0===r)return n;if(tn?n:t},C3.clampAngle=function(t){return(t%=TWO_PI)<0&&(t+=TWO_PI),t},C3.toRadians=function(t){return t*D_TO_R},C3.toDegrees=function(t){return t*R_TO_D},C3.hypot2DFast=function(t,e){return Math.sqrt(t*t+e*e)},C3.hypot3DFast=function(t,e,n){return Math.sqrt(t*t+e*e+n*n)},C3.distanceTo=function(t,e,n,r){return C3.hypot2DFast(n-t,r-e)},C3.distanceSquared=function(t,e,n,r){const c=n-t,a=r-e;return c*c+a*a},C3.distanceTo3d=function(t,e,n,r,c,a,s=1){return C3.hypot3DFast(r-t,c-e,(a-n)*s)},C3.distanceSquared3d=function(t,e,n,r,c,a){const s=r-t,o=c-e,i=a-n;return s*s+o*o+i*i},C3.angleTo=function(t,e,n,r){return Math.atan2(r-e,n-t)},C3.angleDiff=function(t,e){if(t===e)return 0;let n=Math.sin(t),r=Math.cos(t),c=n*Math.sin(e)+r*Math.cos(e);return c>=1?0:c<=-1?Math.PI:Math.acos(c)},C3.angleRotate=function(t,e,n){let r=Math.sin(t),c=Math.cos(t),a=Math.sin(e),s=Math.cos(e);return Math.acos(r*a+c*s)>n?c*a-r*s>0?C3.clampAngle(t+n):C3.clampAngle(t-n):C3.clampAngle(e)},C3.angleClockwise=function(t,e){let n=Math.sin(t);return Math.cos(t)*Math.sin(e)-n*Math.cos(e)<=0},C3.angleLerp=function(t,e,n,r=0){let c=C3.angleDiff(t,e);const a=TWO_PI*r;return C3.angleClockwise(e,t)?C3.clampAngle(t+(c+a)*n):C3.clampAngle(t-(c+a)*n)},C3.angleLerpClockwise=function(t,e,n,r=0){const c=C3.angleDiff(t,e),a=TWO_PI*r;return C3.angleClockwise(e,t)?C3.clampAngle(t+(c+a)*n):C3.clampAngle(t+(TWO_PI-c+a)*n)},C3.angleLerpAntiClockwise=function(t,e,n,r=0){const c=C3.angleDiff(t,e),a=TWO_PI*r;return C3.angleClockwise(e,t)?C3.clampAngle(t-(-TWO_PI+c-a)*n):C3.clampAngle(t-(c+a)*n)},C3.angleReflect=function(t,e){const n=C3.angleDiff(t,e);return C3.angleClockwise(t,e)?C3.clampAngle(e-n):C3.clampAngle(e+n)},C3.lerp=function(t,e,n){return t+n*(e-t)},C3.unlerp=function(t,e,n){return t===e?0:(n-t)/(e-t)},C3.relerp=function(t,e,n,r,c){return C3.lerp(r,c,C3.unlerp(t,e,n))},C3.qarp=function(t,e,n,r){return C3.lerp(C3.lerp(t,e,r),C3.lerp(e,n,r),r)},C3.cubic=function(t,e,n,r,c){return C3.lerp(C3.qarp(t,e,n,c),C3.qarp(e,n,r,c),c)},C3.cosp=function(t,e,n){return(t+e+(t-e)*Math.cos(n*Math.PI))/2},C3.isPOT=function(t){return t>0&&!(t-1&t)},C3.nextHighestPowerOfTwo=function(t){--t;for(let e=1;e<32;e<<=1)t|=t>>e;return t+1},C3.roundToNearestFraction=function(t,e){return Math.round(t*e)/e},C3.floorToNearestFraction=function(t,e){return Math.floor(t*e)/e},C3.roundToDp=function(t,e){e=Math.max(Math.floor(e),0);const n=Math.pow(10,e);return Math.round(t*n)/n},C3.countDecimals=function(t){return Math.floor(t)!==t&&t.toString().split(".")[1].length||0},C3.toFixed=function(t,e){let n=t.toFixed(e),r=n.length-1;for(;r>=0&&"0"===n.charAt(r);--r);return r>=0&&"."===n.charAt(r)&&--r,r<0?n:n.substr(0,r+1)},C3.PackRGB=function(t,e,n){return C3.clamp(t,0,255)|C3.clamp(e,0,255)<<8|C3.clamp(n,0,255)<<16};const ALPHAEX_SHIFT=1024,ALPHAEX_MAX=1023,RGBEX_SHIFT=16384,RGBEX_MAX=8191,RGBEX_MIN=-8192;function isNegativeZero(t){return 0===t&&1/t<0}C3.PackRGBAEx=function(t,e,n,r){return(t=C3.clamp(Math.floor(1024*t),-8192,8191))<0&&(t+=16384),(e=C3.clamp(Math.floor(1024*e),-8192,8191))<0&&(e+=16384),(n=C3.clamp(Math.floor(1024*n),-8192,8191))<0&&(n+=16384),-(16384*t*16384*1024+16384*e*1024+1024*n+(r=C3.clamp(Math.floor(1023*r),0,1023)))},C3.PackRGBEx=function(t,e,n){return C3.PackRGBAEx(t,e,n,1)},C3.GetRValue=function(t){if(t>=0)return(255&t)/255;{let e=Math.floor(-t/274877906944);return e>8191&&(e-=16384),e/1024}},C3.GetGValue=function(t){if(t>=0)return((65280&t)>>8)/255;{let e=Math.floor(-t%274877906944/16777216);return e>8191&&(e-=16384),e/1024}},C3.GetBValue=function(t){if(t>=0)return((16711680&t)>>16)/255;{let e=Math.floor(-t%16777216/1024);return e>8191&&(e-=16384),e/1024}},C3.GetAValue=function(t){if(isNegativeZero(t))return 0;if(t>=0)return 1;return Math.floor(-t%1024)/1023},C3.greatestCommonDivisor=function(t,e){for(t=Math.floor(t),e=Math.floor(e);0!==e;){let n=e;e=t%e,t=n}return t};const COMMON_ASPECT_RATIOS=[[3,2],[4,3],[5,4],[5,3],[6,5],[14,9],[16,9],[16,10],[21,9]];C3.getAspectRatio=function(t,e){if((t=Math.floor(t))===(e=Math.floor(e)))return[1,1];for(let n of COMMON_ASPECT_RATIOS){let r=t/n[0]*n[1];if(Math.abs(e-r)<1)return n.slice(0);if(r=t/n[1]*n[0],Math.abs(e-r)<1)return[n[1],n[0]]}let n=C3.greatestCommonDivisor(t,e);return[t/n,e/n]},C3.segmentsIntersect=function(t,e,n,r,c,a,s,o){const i=Math.min(t,n),u=Math.max(t,n),l=Math.min(c,s),C=Math.max(c,s);if(uC)return!1;const f=Math.min(e,r),m=Math.max(e,r),h=Math.min(a,o),M=Math.max(a,o);if(mM)return!1;const g=c-t+s-n,p=a-e+o-r,d=n-t,v=r-e,I=s-c,T=o-a,x=Math.abs(v*I-T*d),A=I*p-T*g;if(Math.abs(A)>x)return!1;const y=d*p-v*g;return Math.abs(y)<=x},C3.segmentsIntersectPreCalc=function(t,e,n,r,c,a,s,o,i,u,l,C){const f=Math.min(i,l),m=Math.max(i,l);if(am)return!1;const h=Math.min(u,C),M=Math.max(u,C);if(oM)return!1;const g=i-t+l-n,p=u-e+C-r,d=n-t,v=r-e,I=l-i,T=C-u,x=Math.abs(v*I-T*d),A=I*p-T*g;if(Math.abs(A)>x)return!1;const y=d*p-v*g;return Math.abs(y)<=x},C3.segmentIntersectsQuad=function(t,e,n,r,c){const a=Math.min(t,n),s=Math.max(t,n),o=Math.min(e,r),i=Math.max(e,r),u=c.getTlx(),l=c.getTly(),C=c.getTrx(),f=c.getTry(),m=c.getBrx(),h=c.getBry(),M=c.getBlx(),g=c.getBly();return C3.segmentsIntersectPreCalc(t,e,n,r,a,s,o,i,u,l,C,f)||C3.segmentsIntersectPreCalc(t,e,n,r,a,s,o,i,C,f,m,h)||C3.segmentsIntersectPreCalc(t,e,n,r,a,s,o,i,m,h,M,g)||C3.segmentsIntersectPreCalc(t,e,n,r,a,s,o,i,M,g,u,l)},C3.segmentIntersectsAnyN=function(t,e,n,r,c){const a=Math.min(t,n),s=Math.max(t,n),o=Math.min(e,r),i=Math.max(e,r);let u=0;for(let l=c.length-4;u<=l;u+=2)if(C3.segmentsIntersectPreCalc(t,e,n,r,a,s,o,i,c[u],c[u+1],c[u+2],c[u+3]))return!0;return C3.segmentsIntersectPreCalc(t,e,n,r,a,s,o,i,c[u],c[u+1],c[0],c[1])};const NO_HIT=2,PADDING=1e-6;C3.rayIntersect=function(t,e,n,r,c,a,s,o){const i=n-t,u=o-a,l=i*u-(r-e)*(s-c);if(0===l)return 2;const C=((e-r)*(s-t)+i*(o-e))/l;return 0=0&&T>=0&&I+T<=1},C3.triangleCartesianToBarycentric=function(t,e,n,r,c,a,s,o){const i=c-n,u=a-r,l=s-n,C=o-r,f=t-n,m=e-r,h=i*i+u*u,M=i*l+u*C,g=l*l+C*C,p=f*i+m*u,d=f*l+m*C,v=h*g-M*M,I=(g*p-M*d)/v,T=(h*d-M*p)/v;return[1-I-T,I,T]},C3.triangleBarycentricToCartesian3d=function(t,e,n,r,c,a,s,o,i,u,l,C){return[t*r+e*s+n*u,t*c+e*o+n*l,t*a+e*i+n*C]};const tmpEdge1=vec3.create(),tmpEdge2=vec3.create(),tmpDirection=vec3.create(),tmpH=vec3.create(),tmpS=vec3.create(),tmpQ=vec3.create(),SIT3D_EPSILON=1e-7;C3.segmentIntersectsTriangle3d=function(t,e,n,r,c,a){vec3.subtract(tmpEdge1,c,r),vec3.subtract(tmpEdge2,a,r),vec3.subtract(tmpDirection,n,e),vec3.cross(tmpH,tmpDirection,tmpEdge2);const s=vec3.dot(tmpEdge1,tmpH);if(s>-1e-7&&s<1e-7)return!1;const o=1/s;vec3.subtract(tmpS,e,r);const i=o*vec3.dot(tmpS,tmpH);if(i<0||i>1)return!1;vec3.cross(tmpQ,tmpS,tmpEdge1);const u=o*vec3.dot(tmpDirection,tmpQ);if(u<0||i+u>1)return!1;const l=o*vec3.dot(tmpEdge2,tmpQ);return l>1e-7&&l<=1&&(t&&vec3.scaleAndAdd(t,e,tmpDirection,l),!0)},C3.segmentIntersectsQuad3d=function(t,e,n,r,c,a,s){return!!C3.segmentIntersectsTriangle3d(t,e,n,r,c,a)||C3.segmentIntersectsTriangle3d(t,e,n,r,a,s)};const tempVec3a=vec3.create(),tempVec3b=vec3.create(),tempVec3c=vec3.create(),tempVec3d=vec3.create(),tempVec3e=vec3.create();C3.segmentIntersects2DQuadAs3DBox=function(t,e,n,r,c,a){const s=tempVec3a,o=tempVec3b,i=tempVec3c,u=tempVec3d,l=t?tempVec3e:null,C=r.getTlx(),f=r.getTly(),m=r.getTrx(),h=r.getTry(),M=r.getBrx(),g=r.getBry(),p=r.getBlx(),d=r.getBly();let v=1/0;if(vec3.set(s,C,f,c),vec3.set(o,m,h,c),vec3.set(i,M,g,c),vec3.set(u,p,d,c),C3.segmentIntersectsQuad3d(t,e,n,s,o,i,u)){if(!t)return!0;v=vec3.squaredDistance(e,t)}if(vec3.set(o,C,f,a),vec3.set(i,p,d,a),C3.segmentIntersectsQuad3d(l,e,n,s,o,i,u)){if(!l)return!0;{const n=vec3.squaredDistance(e,l);n1&&"/"===e.slice(-1)&&(e=e.slice(0,-1));const n=e.lastIndexOf("/")+1;let r,a="",s=e,i="";n>0&&(a=e.slice(0,n),s=e.slice(n)),r=s;const o=s.lastIndexOf(".");o>0&&(i=s.slice(o),r=s.slice(0,-i.length));return{dir:a,base:s,name:r,root:t,ext:i,full:t+a+s}},C3.Wait=function(e,t){return new Promise((n,r)=>{self.setTimeout(n,e,t)})},C3.swallowException=function(e){try{e()}catch(e){C3.isDebug&&console.warn("Swallowed exception: ",e)}},C3.noop=function(){},C3.equalsNoCase=function(e,t){return"string"==typeof e&&"string"==typeof t&&(e===t||e.normalize().toLowerCase()===t.normalize().toLowerCase())},C3.equalsCase=function(e,t){return"string"==typeof e&&"string"==typeof t&&(e===t||e.normalize()===t.normalize())},C3.typedArraySet16=function(e,t,n){e[n++]=t[0],e[n++]=t[1],e[n++]=t[2],e[n++]=t[3],e[n++]=t[4],e[n++]=t[5],e[n++]=t[6],e[n++]=t[7],e[n++]=t[8],e[n++]=t[9],e[n++]=t[10],e[n++]=t[11],e[n++]=t[12],e[n++]=t[13],e[n++]=t[14],e[n]=t[15]},C3.truncateArray=function(e,t){e.length=t},C3.clearArray=function(e){e&&0!==e.length&&C3.truncateArray(e,0)},C3.clear2DArray=function(e){if(e){for(let t=0;tr&&C3.extendArray(e,t,n)},C3.shallowAssignArray=function(e,t){C3.clearArray(e),C3.appendArray(e,t)},C3.appendArray=function(e,t){if(t.length<1e4)e.push(...t);else for(let n=0,r=t.length;n=e.length)return;let n=e.length-1;for(let r=t;r=0&&e.splice(n,1)},C3.arraysEqual=function(e,t){let n=e.length;if(t.length!==n)return!1;for(let r=0;r=0&&ee.trim()).filter(e=>!!e):[]},C3.ensureSet=function(e){return e instanceof Set?e:new Set(e)},C3.filterSet=function(e,t,n){const r=new Set;for(const a of e.values())t(a)&&(n?r.add(n(a)):r.add(a));return r},C3.mergeSetsInPlace=function(e,t){for(const n of t)e.add(n);return e},C3.first=function(e){for(let t of e)return t;return null},C3.xor=function(e,t){return!e!=!t},C3.compare=function(e,t,n){switch(t){case 0:return e===n;case 1:return e!==n;case 2:return en;case 5:return e>=n;default:return!1}},C3.hasAnyOwnProperty=function(e){for(let t in e)if(e.hasOwnProperty(t))return!0;return!1},C3.PromiseAllWithProgress=function(e,t){return e.length?new Promise((n,r)=>{const a=[];let s=0,i=!1;for(let o=0,l=e.length;o{i||(a[o]=r,++s,s===e.length?n(a):t(s,e.length))}).catch(e=>{i=!0,r(e)})}):Promise.resolve([])};let memoryCallbacks=[];C3.AddLibraryMemoryCallback=function(e){memoryCallbacks.push(e)},C3.GetEstimatedLibraryMemoryUsage=function(){let e=0;for(let t of memoryCallbacks){e+=t()}return Math.floor(e)};let nextTaskId=1;const activeTaskIds=new Map;function OnTask(e){const t=activeTaskIds.get(e);activeTaskIds.delete(e),t&&t(performance.now())}const scheduler=globalThis["scheduler"],taskMessageChannel=new MessageChannel;taskMessageChannel.port2.onmessage=e=>OnTask(e.data),C3.RequestUnlimitedAnimationFrame=function(e,t="user-visible"){const n=nextTaskId++;return activeTaskIds.set(n,e),scheduler?scheduler["postTask"](()=>OnTask(n),{priority:t}):taskMessageChannel.port1.postMessage(n),n},C3.CancelUnlimitedAnimationFrame=function(e){activeTaskIds.delete(e)},C3.PostTask=C3.RequestUnlimitedAnimationFrame,C3.WaitForNextTask=function(){return new Promise(e=>C3.PostTask(e))};const activeRPAFids=new Set;C3.RequestPostAnimationFrame=function(e){const t=self.requestAnimationFrame(async n=>{await C3.WaitForNextTask(),activeRPAFids.has(t)&&(activeRPAFids.delete(t),e(n))});return activeRPAFids.add(t),t},C3.CancelPostAnimationFrame=function(e){activeRPAFids.has(e)&&(self.cancelAnimationFrame(e),activeRPAFids.delete(e))}; } // lib/misc/runtimeutil.js { const C3=self.C3;C3.IsAbsoluteURL=function(e){return/^(?:[a-z\-]+:)?\/\//.test(e)||"data:"===e.substr(0,5)||"blob:"===e.substr(0,5)},C3.IsRelativeURL=function(e){return!C3.IsAbsoluteURL(e)},C3.ThrowIfNotOk=function(e){if(!e.ok)throw new Error(`fetch '${e.url}' response returned ${e.status} ${e.statusText}`)},C3.FetchOk=function(e,t){return fetch(e,t).then(e=>(C3.ThrowIfNotOk(e),e))},C3.FetchText=function(e){return C3.FetchOk(e).then(e=>e.text())},C3.FetchJson=function(e){return C3.FetchOk(e).then(e=>e.json())},C3.FetchBlob=function(e){return C3.FetchOk(e).then(e=>e.blob())},C3.FetchArrayBuffer=function(e){return C3.FetchOk(e).then(e=>e.arrayBuffer())},C3.FetchImage=function(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=e=>n(e),r.src=e})},C3.BlobToArrayBuffer=function(e){return"function"==typeof e["arrayBuffer"]?e["arrayBuffer"]():new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsArrayBuffer(e)})},C3.BlobToString=function(e){return"function"==typeof e["text"]?e["text"]():new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)})},C3.BlobToJson=function(e){return C3.BlobToString(e).then(e=>JSON.parse(e))},C3.BlobToImage=async function(e,t){let n=URL.createObjectURL(e);try{const e=await C3.FetchImage(n);return URL.revokeObjectURL(n),n="",t&&"function"==typeof e["decode"]&&await e["decode"](),e}finally{n&&URL.revokeObjectURL(n)}},C3.CreateCanvas=function(e,t){if("undefined"!=typeof document&&"function"==typeof document.createElement){const n=document.createElement("canvas");return n.width=e,n.height=t,n}return new OffscreenCanvas(e,t)},C3.CanvasToBlob=function(e,t,n){if("number"!=typeof n&&(n=1),t=t||"image/png",n=C3.clamp(n,0,1),e["convertToBlob"])return e["convertToBlob"]({"type":t,"quality":n});if(e.toBlob)return new Promise(r=>e.toBlob(r,t,n));throw new Error("could not convert canvas to blob")},C3.DrawableToBlob=function(e,t,n){const r=C3.CreateCanvas(e.width,e.height);return r.getContext("2d").drawImage(e,0,0),C3.CanvasToBlob(r,t,n)},C3.ImageDataToBlob=function(e,t,n){if(C3.Supports.ImageBitmapOptions)return createImageBitmap(e,{"premultiplyAlpha":"none"}).then(e=>C3.DrawableToBlob(e,t,n));if(C3.Supports.ImageBitmap)return createImageBitmap(e).then(e=>C3.DrawableToBlob(e,t,n));{const r=C3.CreateCanvas(e.width,e.height);return r.getContext("2d").putImageData(e,0,0),C3.CanvasToBlob(r,t,n)}},C3.CopySet=function(e,t){e.clear();for(const n of t)e.add(n)},C3.MapToObject=function(e){const t=Object.create(null);for(const[n,r]of e.entries())t[n]=r;return t},C3.ObjectToMap=function(e,t){t.clear();for(const[n,r]of Object.entries(e))t.set(n,r)},C3.ToSuperJSON=function e(t){if("object"==typeof t&&null!==t){if(t instanceof Set)return{"_c3type_":"set","data":[...t].map(t=>e(t))};if(t instanceof Map)return{"_c3type_":"map","data":[...t].map(t=>[t[0],e(t[1])])};{const n=Object.create(null);for(const[r,o]of Object.entries(t))n[r]=e(o);return n}}return t},C3.FromSuperJSON=function e(t){if("object"==typeof t&null!==t){if("set"===t["_c3type_"])return new Set(t["data"].map(t=>e(t)));if("map"===t["_c3type_"])return new Map(t["data"].map(t=>[t[0],e(t[1])]));{const n=Object.create(null);for(const[r,o]of Object.entries(t))n[r]=e(o);return n}}return t},C3.CSSToCamelCase=function(e){if(e.startsWith("--"))return e;let t="",n=!1,r=0;for(const o of e)"-"===o?r>0&&(n=!0):n?(t+=o.toUpperCase(),n=!1):t+=o,++r;return t},C3.IsIterator=function(e){return"object"==typeof e&&"function"==typeof e.next},C3.MakeFilledArray=function(e,t){const n=[];if("function"==typeof t)for(let r=0;r1&&(e-=1),e<1/6?t+6*(s-t)*e:e<.5?s:e<2/3?t+(s-t)*(2/3-e)*6:t}C3.Color=class{constructor(t,s,e,r){this._r=NaN,this._g=NaN,this._b=NaN,this._a=NaN,this._r=0,this._g=0,this._b=0,this._a=0,t instanceof C3.Color?this.set(t):this.setRgba(t||0,s||0,e||0,r||0)}setRgb(t,s,e){return this._r=+t,this._g=+s,this._b=+e,this.clamp(),this}setRgba(t,s,e,r){return this._r=+t,this._g=+s,this._b=+e,this._a=+r,this.clamp(),this}set(t){return this._r=t._r,this._g=t._g,this._b=t._b,this._a=t._a,this}copy(t){return this.set(t)}add(t){this._r+=t._r,this._g+=t._g,this._b+=t._b,this._a+=t._a,this.clamp()}addRgb(t,s,e,r=0){this._r+=+t,this._g+=+s,this._b+=+e,this._a+=+r,this.clamp()}diff(t){this.setR(Math.max(this._r,t._r)-Math.min(this._r,t._r)),this.setG(Math.max(this._g,t._g)-Math.min(this._g,t._g)),this.setB(Math.max(this._b,t._b)-Math.min(this._b,t._b)),this.setA(Math.max(this._a,t._a)-Math.min(this._a,t._a)),this.clamp()}copyRgb(t){this._r=t._r,this._g=t._g,this._b=t._b}setR(t){this._r=C3.clamp(+t,0,1)}getR(){return this._r}setG(t){this._g=C3.clamp(+t,0,1)}getG(){return this._g}setB(t){this._b=C3.clamp(+t,0,1)}getB(){return this._b}setA(t){this._a=C3.clamp(+t,0,1)}getA(){return this._a}clone(){return C3.New(C3.Color,this._r,this._g,this._b,this._a)}toArray(){return[this._r,this._g,this._b,this._a]}toTypedArray(){return new Float64Array(this.toArray())}writeToTypedArray(t,s){t[s++]=this._r,t[s++]=this._g,t[s++]=this._b,t[s]=this._a}writeToTypedArrayx4(t,s){const e=this._r,r=this._g,i=this._b,a=this._a;t[s++]=e,t[s++]=r,t[s++]=i,t[s++]=a,t[s++]=e,t[s++]=r,t[s++]=i,t[s++]=a,t[s++]=e,t[s++]=r,t[s++]=i,t[s++]=a,t[s++]=e,t[s++]=r,t[s++]=i,t[s]=a}writeRGBToTypedArray(t,s){t[s++]=this._r,t[s++]=this._g,t[s]=this._b}equals(t){return this._r===t._r&&this._g===t._g&&this._b===t._b&&this._a===t._a}equalsIgnoringAlpha(t){return this._r===t._r&&this._g===t._g&&this._b===t._b}equalsRgb(t,s,e){return this._r===t&&this._g===s&&this._b===e}equalsRgba(t,s,e,r){return this._r===t&&this._g===s&&this._b===e&&this._a===r}equalsF32Array(t,s){return t[s]===Math.fround(this._r)&&t[s+1]===Math.fround(this._g)&&t[s+2]===Math.fround(this._b)&&t[s+3]===Math.fround(this._a)}equalsRGBF32Array(t,s){return t[s]===Math.fround(this._r)&&t[s+1]===Math.fround(this._g)&&t[s+2]===Math.fround(this._b)}multiply(t){this._r*=t._r,this._g*=t._g,this._b*=t._b,this._a*=t._a}multiplyAlpha(t){this._r*=t,this._g*=t,this._b*=t,this._a*=t}premultiply(){return this._r*=this._a,this._g*=this._a,this._b*=this._a,this}unpremultiply(){return this._r/=this._a,this._g/=this._a,this._b/=this._a,this}clamp(){return this._r=C3.clamp(this._r,0,1),this._g=C3.clamp(this._g,0,1),this._b=C3.clamp(this._b,0,1),this._a=C3.clamp(this._a,0,1),this}setFromRgbValue(t){this._r=C3.GetRValue(t),this._g=C3.GetGValue(t),this._b=C3.GetBValue(t),this._a=C3.GetAValue(t)}getCssRgb(t,s,e){return`rgb(${100*(C3.IsFiniteNumber(t)?t:this.getR())}%, ${100*(C3.IsFiniteNumber(s)?s:this.getG())}%, ${100*(C3.IsFiniteNumber(e)?e:this.getB())}%)`}getCssRgba(t,s,e,r){return`rgba(${100*(C3.IsFiniteNumber(t)?t:this.getR())}%, ${100*(C3.IsFiniteNumber(s)?s:this.getG())}%, ${100*(C3.IsFiniteNumber(e)?e:this.getB())}%, ${C3.IsFiniteNumber(r)?r:this.getA()})`}toHexString(t=!1){const s=Math.round(255*this.getR()),e=Math.round(255*this.getG()),r=Math.round(255*this.getB());let i="#"+padTwoDigits(s.toString(16))+padTwoDigits(e.toString(16))+padTwoDigits(r.toString(16));if(t){i+=padTwoDigits(Math.round(255*this.getA()).toString(16))}return i}parseHexString(t){if("string"!=typeof t)return!1;let s,e,r,i;if("#"===(t=t.trim()).charAt(0)&&(t=t.substr(1)),3===t.length||4===t.length)s=parseInt(t[0],16)/15,e=parseInt(t[1],16)/15,r=parseInt(t[2],16)/15,4===t.length&&(i=parseInt(t[3],16)/15);else{if(6!==t.length&&8!==t.length)return!1;s=parseInt(t.substr(0,2),16)/255,e=parseInt(t.substr(2,2),16)/255,r=parseInt(t.substr(4,2),16)/255,8===t.length&&(i=parseInt(t.substr(6,2),16)/255)}return!!(Number.isFinite(s)&&Number.isFinite(e)&&Number.isFinite(r))&&(this.setRgb(s,e,r),Number.isFinite(i)?this.setA(i):this.setA(1),!0)}toCommaSeparatedRgb(){return`${Math.round(255*this.getR())}, ${Math.round(255*this.getG())}, ${Math.round(255*this.getB())}`}toRgbArray(){return[Math.round(255*this.getR()),Math.round(255*this.getG()),Math.round(255*this.getB())]}parseCommaSeparatedRgb(t){if("string"!=typeof t)return!1;const s=(t=t.replace(/^rgb\(|\)|%/,"")).split(",");if(s.length<3)return!1;const e=parseInt(s[0].trim(),10)/255,r=parseInt(s[1].trim(),10)/255,i=parseInt(s[2].trim(),10)/255;return isFinite(e)&&this.setR(e),isFinite(r)&&this.setG(r),isFinite(i)&&this.setB(i),this.setA(1),!0}parseCommaSeparatedPercentageRgb(t){if("string"!=typeof t)return!1;const s=(t=t.replace(/^rgb\(|\)|%/,"")).split(",");if(s.length<3)return!1;const e=parseInt(s[0].trim(),10)/100,r=parseInt(s[1].trim(),10)/100,i=parseInt(s[2].trim(),10)/100;return isFinite(e)&&this.setR(e),isFinite(r)&&this.setG(r),isFinite(i)&&this.setB(i),this.setA(1),!0}parseCommaSeparatedRgba(t){if("string"!=typeof t)return!1;const s=(t=t.replace(/^rgba\(|\)|%/,"")).split(",");if(s.length<4)return!1;const e=parseInt(s[0].trim(),10)/255,r=parseInt(s[1].trim(),10)/255,i=parseInt(s[2].trim(),10)/255,a=parseFloat(s[3].trim());return isFinite(e)&&this.setR(e),isFinite(r)&&this.setG(r),isFinite(i)&&this.setB(i),isFinite(a)&&this.setA(a),!0}parseCommaSeparatedPercentageRgba(t){if("string"!=typeof t)return!1;const s=(t=t.replace(/^rgba\(|\)|%/,"")).split(",");if(s.length<4)return!1;const e=parseInt(s[0].trim(),10)/100,r=parseInt(s[1].trim(),10)/100,i=parseInt(s[2].trim(),10)/100,a=parseFloat(s[3].trim());return isFinite(e)&&this.setR(e),isFinite(r)&&this.setG(r),isFinite(i)&&this.setB(i),isFinite(a)&&this.setA(a),!0}parseString(t){if("string"!=typeof t)return!1;if((t=t.replace(/\s+/,"")).includes(",")){if(t.startsWith("rgb("))return t.includes("%")?this.parseCommaSeparatedPercentageRgb(t):this.parseCommaSeparatedRgb(t);if(t.startsWith("rgba("))return t.includes("%")?this.parseCommaSeparatedPercentageRgba(t):this.parseCommaSeparatedRgba(t);if(t.startsWith("hsl(")||t.startsWith("hsla("))return this.parseHSLString(t);{const s=t.split(",");return t.includes("%")?3===s.length?this.parseCommaSeparatedPercentageRgb(t):4===s.length&&this.parseCommaSeparatedPercentageRgba(t):3===s.length?this.parseCommaSeparatedRgb(t):4===s.length&&this.parseCommaSeparatedRgba(t)}}return this.parseHexString(t)}toJSON(){return[this._r,this._g,this._b,this._a]}setFromHSLA(t,s,e,r){let i,a,h;if(t%=360,s=C3.clamp(s,0,100),e=C3.clamp(e,0,100),r=C3.clamp(r,0,1),t/=360,e/=100,0===(s/=100))i=a=h=e;else{const r=e<.5?e*(1+s):e+s-e*s,n=2*e-r;i=hueToRGB(n,r,t+1/3),a=hueToRGB(n,r,t),h=hueToRGB(n,r,t-1/3)}return this.setR(i),this.setG(a),this.setB(h),this.setA(r),this}parseHSLString(t){const s=t.replace(/ |hsl|hsla|\(|\)|;/gi,""),e=HSL_TEST.exec(s),r=HSLA_TEST.exec(s);return e&&4===e.length?(this.setFromHSLA(+e[1],+e[2],+e[3],1),!0):!(!r||5!==r.length)&&(this.setFromHSLA(+e[1],+e[2],+e[3],+e[4]),!0)}toHSLAString(){const t=this._r,s=this._g,e=this._b,r=this._a;return`hsla(${C3.Color.GetHue(t,s,e)}, ${C3.Color.GetSaturation(t,s,e)}%, ${C3.Color.GetLuminosity(t,s,e)}%, ${r})`}toHSLAArray(){const t=this._r,s=this._g,e=this._b;return[C3.Color.GetHue(t,s,e),C3.Color.GetSaturation(t,s,e),C3.Color.GetLuminosity(t,s,e),this._a]}setFromJSON(t){Array.isArray(t)&&(t.length<3||(this._r=t[0],this._g=t[1],this._b=t[2],t.length>=4?this._a=t[3]:this._a=1))}set r(t){this.setR(t)}get r(){return this.getR()}set g(t){this.setG(t)}get g(){return this.getG()}set b(t){this.setB(t)}get b(){return this.getB()}set a(t){this.setA(t)}get a(){return this.getA()}setAtIndex(t,s){switch(t){case 0:this.setR(s);break;case 1:this.setG(s);break;case 2:this.setB(s);break;case 3:this.setA(s);break;default:throw new RangeError("invalid color index")}}getAtIndex(t){switch(t){case 0:return this.getR();case 1:return this.getG();case 2:return this.getB();case 3:return this.getA();default:throw new RangeError("invalid color index")}}static Equals(t,s){let e,r;if(Array.isArray(t))e=new C3.Color,e.setFromJSON(t);else{if(!(t instanceof C3.Color))throw new Error("unexpected type");e=t}if(Array.isArray(s))r=new C3.Color,r.setFromJSON(s);else{if(!(s instanceof C3.Color))throw new Error("unexpected type");r=s}return e.equals(r)}static DiffChannel(t,s){return C3.clamp(Math.max(t,s)-Math.min(t,s),0,1)}static Diff(t,s){const e=new C3.Color;return e.setR(Math.max(t._r,s._r)-Math.min(t._r,s._r)),e.setG(Math.max(t._g,s._g)-Math.min(t._g,s._g)),e.setB(Math.max(t._b,s._b)-Math.min(t._b,s._b)),e.setA(Math.max(t._a,s._a)-Math.min(t._a,s._a)),e}static DiffNoAlpha(t,s){const e=new C3.Color(0,0,0,1);return e.setR(Math.max(t._r,s._r)-Math.min(t._r,s._r)),e.setG(Math.max(t._g,s._g)-Math.min(t._g,s._g)),e.setB(Math.max(t._b,s._b)-Math.min(t._b,s._b)),e}static GetHue(t,s,e){const r=Math.max(t,s,e),i=Math.min(t,s,e);if(r===i)return 0;let a=0;switch(r){case t:a=(s-e)/(r-i)+(s.5?a/(2-r-i):a/(r+i);return Math.round(100*h)}static GetLuminosity(t,s,e){const r=Math.max(t,s,e),i=(r+Math.min(t,s,e))/2;return r?Math.round(100*i):0}},C3.Color.White=Object.freeze(C3.New(C3.Color,1,1,1,1)),C3.Color.Black=Object.freeze(C3.New(C3.Color,0,0,0,1)),C3.Color.TransparentBlack=Object.freeze(C3.New(C3.Color,0,0,0,0)); } // ../lib/geometry/vector2.js { const C3=self.C3;C3.Vector2=class{constructor(t,s){this._x=0,this._y=0,t instanceof C3.Vector2?this.copy(t):this.set(t||0,s||0)}set(t,s){this._x=+t,this._y=+s}copy(t){this._x=t._x,this._y=t._y}equals(t){return this._x===t._x&&this._y===t._y}equalsValues(t,s){return this._x===t&&this._y===s}equalsF32Array(t,s){return t[s]===Math.fround(this._x)&&t[s+1]===Math.fround(this._y)}setX(t){this._x=+t}getX(){return this._x}setY(t){this._y=+t}getY(){return this._y}toArray(){return[this._x,this._y]}toTypedArray(){return new Float64Array(this.toArray())}writeToTypedArray(t,s){t[s++]=this._x,t[s]=this._y}offset(t,s){this._x+=+t,this._y+=+s}scale(t,s){this._x*=t,this._y*=s}divide(t,s){this._x/=t,this._y/=s}round(){this._x=Math.round(this._x),this._y=Math.round(this._y)}floor(){this._x=Math.floor(this._x),this._y=Math.floor(this._y)}ceil(){this._x=Math.ceil(this._x),this._y=Math.ceil(this._y)}angle(){return C3.angleTo(0,0,this._x,this._y)}lengthSquared(){return this._x*this._x+this._y*this._y}length(){return C3.hypot2DFast(this._x,this._y)}rotatePrecalc(t,s){const h=this._x*s-this._y*t;this._y=this._y*s+this._x*t,this._x=h}rotate(t){0!==t&&this.rotatePrecalc(Math.sin(t),Math.cos(t))}rotateAbout(t,s,h){0===t||s===this._x&&h===this._y||(this._x-=s,this._y-=h,this.rotatePrecalc(Math.sin(t),Math.cos(t)),this._x+=+s,this._y+=+h)}move(t,s){0!==s&&(this._x+=Math.cos(t)*s,this._y+=Math.sin(t)*s)}normalize(){const t=this.length();0!==t&&1!==t&&(this._x/=t,this._y/=t)}clamp(t,s){this._x=C3.clamp(this._x,t,s),this._y=C3.clamp(this._y,t,s)}dot(t){return this._x*t._x+this._y*t._y}reverse(){this._x=-this._x,this._y=-this._y}perp(){let t=this._x;return this._x=this._y,this._y=-t,this}}; } // ../lib/geometry/rect.js { const C3=self.C3;C3.Rect=class{constructor(t,i,h,o){this._left=NaN,this._top=NaN,this._right=NaN,this._bottom=NaN,this._left=0,this._top=0,this._right=0,this._bottom=0,t instanceof C3.Rect?this.copy(t):this.set(t||0,i||0,h||0,o||0)}set(t,i,h,o){this._left=+t,this._top=+i,this._right=+h,this._bottom=+o}setWH(t,i,h,o){t=+t,i=+i,this._left=t,this._top=i,this._right=t+ +h,this._bottom=i+ +o}copy(t){this._left=+t._left,this._top=+t._top,this._right=+t._right,this._bottom=+t._bottom}setFromAABB3D(t){this._left=t.getLeft(),this._top=t.getTop(),this._right=t.getRight(),this._bottom=t.getBottom()}clone(){return new C3.Rect(this._left,this._top,this._right,this._bottom)}static Merge(t,i){const h=new C3.Rect;return h.setLeft(Math.min(t._left,i._left)),h.setTop(Math.min(t._top,i._top)),h.setRight(Math.max(t._right,i._right)),h.setBottom(Math.max(t._bottom,i._bottom)),h}static FromObject(t){return new C3.Rect(t.left,t.top,t.right,t.bottom)}equals(t){return this._left===t._left&&this._top===t._top&&this._right===t._right&&this._bottom===t._bottom}equalsWH(t,i,h,o){return this._left===t&&this._top===i&&this.width()===h&&this.height()===o}equalsF32Array(t,i){return t[i]===Math.fround(this._left)&&t[i+1]===Math.fround(this._top)&&t[i+2]===Math.fround(this._right)&&t[i+3]===Math.fround(this._bottom)}setLeft(t){this._left=+t}getLeft(){return this._left}setTop(t){this._top=+t}getTop(){return this._top}setRight(t){this._right=+t}getRight(){return this._right}setBottom(t){this._bottom=+t}getBottom(){return this._bottom}toArray(){return[this._left,this._top,this._right,this._bottom]}toTypedArray(){return new Float64Array(this.toArray())}toDOMRect(){return new DOMRect(this._left,this._top,this.width(),this.height())}static fromDOMRect(t){return C3.New(C3.Rect,t.left,t.top,t.right,t.bottom)}writeToTypedArray(t,i){t[i++]=this._left,t[i++]=this._top,t[i++]=this._right,t[i]=this._bottom}writeAsQuadToTypedArray(t,i){const h=this._left,o=this._top,s=this._right,_=this._bottom;t[i++]=h,t[i++]=o,t[i++]=s,t[i++]=o,t[i++]=s,t[i++]=_,t[i++]=h,t[i]=_}writeAsQuadToTypedArray3D(t,i,h){const o=this._left,s=this._top,_=this._right,e=this._bottom;t[i++]=o,t[i++]=s,t[i++]=h,t[i++]=_,t[i++]=s,t[i++]=h,t[i++]=_,t[i++]=e,t[i++]=h,t[i++]=o,t[i++]=e,t[i]=h}width(){return this._right-this._left}height(){return this._bottom-this._top}midX(){return(this._left+this._right)/2}midY(){return(this._top+this._bottom)/2}offset(t,i){t=+t,i=+i,this._left+=t,this._top+=i,this._right+=t,this._bottom+=i}offsetLeft(t){this._left+=+t}offsetTop(t){this._top+=+t}offsetRight(t){this._right+=+t}offsetBottom(t){this._bottom+=+t}toSquare(t){if("x"!==t)throw new Error("invalid axis, only 'x' supported");this._topthis._right&&this.swapLeftRight(),this._top>this._bottom&&this.swapTopBottom()}intersectsRect(t){return!(t._rightthis._right||t._top>this._bottom)}intersectsRectOffset(t,i,h){return!(t._right+ithis._right||t._top+h>this._bottom)}containsPoint(t,i){return t>=this._left&&t<=this._right&&i>=this._top&&i<=this._bottom}containsRect(t){return t._left>=this._left&&t._top>=this._top&&t._right<=this._right&&t._bottom<=this._bottom}intersectsAABB3D(t){return!(t.getRight()this._right||t.getTop()>this._bottom)}containsAABB3D(t){return t.getLeft()>=this._left&&t.getTop()>=this._top&&t.getRight()<=this._right&&t.getBottom()<=this._bottom}expandToContain(t){t._leftthis._right&&(this._right=+t._right),t._bottom>this._bottom&&(this._bottom=+t._bottom)}lerpInto(t){this._left=C3.lerp(t._left,t._right,this._left),this._top=C3.lerp(t._top,t._bottom,this._top),this._right=C3.lerp(t._left,t._right,this._right),this._bottom=C3.lerp(t._top,t._bottom,this._bottom)}}; } // ../lib/geometry/quad2d.js { const C3=self.C3;C3.Quad2D=class{constructor(t,s,i,h,_,r,e,l){this._tlx=NaN,this._tly=NaN,this._trx=NaN,this._try=NaN,this._brx=NaN,this._bry=NaN,this._blx=NaN,this._bly=NaN,this._tlx=0,this._tly=0,this._trx=0,this._try=0,this._brx=0,this._bry=0,this._blx=0,this._bly=0,t instanceof C3.Quad2D?this.copy(t):this.set(t||0,s||0,i||0,h||0,_||0,r||0,e||0,l||0)}set(t,s,i,h,_,r,e,l){this._tlx=+t,this._tly=+s,this._trx=+i,this._try=+h,this._brx=+_,this._bry=+r,this._blx=+e,this._bly=+l}setRect(t,s,i,h){this.set(t,s,i,s,i,h,t,h)}setFromQuad3d(t){this.set(t.getTlx(),t.getTly(),t.getTrx(),t.getTry(),t.getBrx(),t.getBry(),t.getBlx(),t.getBly())}copy(t){this._tlx=t._tlx,this._tly=t._tly,this._trx=t._trx,this._try=t._try,this._brx=t._brx,this._bry=t._bry,this._blx=t._blx,this._bly=t._bly}equals(t){return this._tlx===t._tlx&&this._tly===t._tly&&this._trx===t._trx&&this._try===t._try&&this._brx===t._brx&&this._bry===t._bry&&this._blx===t._blx&&this._bly===t._bly}setTlx(t){this._tlx=+t}getTlx(){return this._tlx}setTly(t){this._tly=+t}getTly(){return this._tly}setTrx(t){this._trx=+t}getTrx(){return this._trx}setTry(t){this._try=+t}getTry(){return this._try}setBrx(t){this._brx=+t}getBrx(){return this._brx}setBry(t){this._bry=+t}getBry(){return this._bry}setBlx(t){this._blx=+t}getBlx(){return this._blx}setBly(t){this._bly=+t}getBly(){return this._bly}toDOMQuad(){return new DOMQuad(new DOMPoint(this._tlx,this._tly),new DOMPoint(this._trx,this._try),new DOMPoint(this._brx,this._bry),new DOMPoint(this._blx,this._bly))}static fromDOMQuad(t){return C3.New(C3.Quad2D,t.p1.x,t.p1.y,t.p2.x,t.p2.y,t.p3.x,t.p3.y,t.p4.x,t.p4.y)}toArray(){return[this._tlx,this._tly,this._trx,this._try,this._brx,this._bry,this._blx,this._bly]}toTypedArray(){return new Float64Array(this.toArray())}writeToTypedArray(t,s){t[s++]=this._tlx,t[s++]=this._tly,t[s++]=this._trx,t[s++]=this._try,t[s++]=this._brx,t[s++]=this._bry,t[s++]=this._blx,t[s]=this._bly}writeToTypedArray3D(t,s,i){t[s++]=this._tlx,t[s++]=this._tly,t[s++]=i,t[s++]=this._trx,t[s++]=this._try,t[s++]=i,t[s++]=this._brx,t[s++]=this._bry,t[s++]=i,t[s++]=this._blx,t[s++]=this._bly,t[s]=i}offset(t,s){t=+t,s=+s,this._tlx+=t,this._tly+=s,this._trx+=t,this._try+=s,this._brx+=t,this._bry+=s,this._blx+=t,this._bly+=s}round(){this._tlx=Math.round(this._tlx),this._tly=Math.round(this._tly),this._trx=Math.round(this._trx),this._try=Math.round(this._try),this._brx=Math.round(this._brx),this._bry=Math.round(this._bry),this._blx=Math.round(this._blx),this._bly=Math.round(this._bly)}floor(){this._tlx=Math.floor(this._tlx),this._tly=Math.floor(this._tly),this._trx=Math.floor(this._trx),this._try=Math.floor(this._try),this._brx=Math.floor(this._brx),this._bry=Math.floor(this._bry),this._blx=Math.floor(this._blx),this._bly=Math.floor(this._bly)}ceil(){this._tlx=Math.ceil(this._tlx),this._tly=Math.ceil(this._tly),this._trx=Math.ceil(this._trx),this._try=Math.ceil(this._try),this._brx=Math.ceil(this._brx),this._bry=Math.ceil(this._bry),this._blx=Math.ceil(this._blx),this._bly=Math.ceil(this._bly)}setFromRect(t){this._tlx=t._left,this._tly=t._top,this._trx=t._right,this._try=t._top,this._brx=t._right,this._bry=t._bottom,this._blx=t._left,this._bly=t._bottom}setFromAABB3DIgnoringZ(t){this._tlx=t.getLeft(),this._tly=t.getTop(),this._trx=t.getRight(),this._try=t.getTop(),this._brx=t.getRight(),this._bry=t.getBottom(),this._blx=t.getLeft(),this._bly=t.getBottom()}setFromRotatedRect(t,s){0===s?this.setFromRect(t):this.setFromRotatedRectPrecalc(t,Math.sin(s),Math.cos(s))}setFromRotatedRectPrecalc(t,s,i){const h=t._left*s,_=t._top*s,r=t._right*s,e=t._bottom*s,l=t._left*i,x=t._top*i,y=t._right*i,b=t._bottom*i;this._tlx=l-_,this._tly=x+h,this._trx=y-_,this._try=x+r,this._brx=y-e,this._bry=b+r,this._blx=l-e,this._bly=b+h}getBoundingBox(t){t.set(Math.min(this._tlx,this._trx,this._brx,this._blx),Math.min(this._tly,this._try,this._bry,this._bly),Math.max(this._tlx,this._trx,this._brx,this._blx),Math.max(this._tly,this._try,this._bry,this._bly))}containsPoint(t,s){let i=this._trx-this._tlx,h=this._try-this._tly;const _=this._brx-this._tlx,r=this._bry-this._tly,e=t-this._tlx,l=s-this._tly;let x=i*i+h*h,y=i*_+h*r,b=i*e+h*l;const a=_*_+r*r,n=_*e+r*l;let o=1/(x*a-y*y),c=(a*b-y*n)*o,u=(x*n-y*b)*o;return c>=0&&u>0&&c+u<1||(i=this._blx-this._tlx,h=this._bly-this._tly,x=i*i+h*h,y=i*_+h*r,b=i*e+h*l,o=1/(x*a-y*y),c=(a*b-y*n)*o,u=(x*n-y*b)*o,c>=0&&u>0&&c+u<1)}midX(){return(this._tlx+this._trx+this._brx+this._blx)/4}midY(){return(this._tly+this._try+this._bry+this._bly)/4}intersectsSegment(t,s,i,h){return!(!this.containsPoint(t,s)&&!this.containsPoint(i,h))||C3.segmentIntersectsQuad(t,s,i,h,this)}intersectsQuad(t){let s=t.midX(),i=t.midY();if(this.containsPoint(s,i))return!0;if(s=this.midX(),i=this.midY(),t.containsPoint(s,i))return!0;const h=this._tlx,_=this._tly,r=this._trx,e=this._try,l=this._brx,x=this._bry,y=this._blx,b=this._bly;return C3.segmentIntersectsQuad(h,_,r,e,t)||C3.segmentIntersectsQuad(r,e,l,x,t)||C3.segmentIntersectsQuad(l,x,y,b,t)||C3.segmentIntersectsQuad(y,b,h,_,t)}rotatePointsAnticlockwise(){const t=this._tlx,s=this._tly;this._tlx=this._trx,this._tly=this._try,this._trx=this._brx,this._try=this._bry,this._brx=this._blx,this._bry=this._bly,this._blx=t,this._bly=s}mirror(){this._swap(0,2),this._swap(1,3),this._swap(6,4),this._swap(7,5)}flip(){this._swap(0,6),this._swap(1,7),this._swap(2,4),this._swap(3,5)}diag(){this._swap(2,6),this._swap(3,7)}_swap(t,s){const i=this._getAtIndex(t);this._setAtIndex(t,this._getAtIndex(s)),this._setAtIndex(s,i)}_getAtIndex(t){switch(t){case 0:return this._tlx;case 1:return this._tly;case 2:return this._trx;case 3:return this._try;case 4:return this._brx;case 5:return this._bry;case 6:return this._blx;case 7:return this._bly;default:throw new RangeError("invalid quad point index")}}_setAtIndex(t,s){switch(s=+s,t){case 0:this._tlx=s;break;case 1:this._tly=s;break;case 2:this._trx=s;break;case 3:this._try=s;break;case 4:this._brx=s;break;case 5:this._bry=s;break;case 6:this._blx=s;break;case 7:this._bly=s;break;default:throw new RangeError("invalid quad point index")}}divide(t,s){this._tlx/=t,this._tly/=s,this._trx/=t,this._try/=s,this._brx/=t,this._bry/=s,this._blx/=t,this._bly/=s}},C3.Quad=C3.Quad2D; } // ../lib/geometry/quad3d.js { const C3=globalThis.C3;C3.Quad3D=class{#t=NaN;#s=NaN;#i=NaN;#h=NaN;#r=NaN;#l=NaN;#b=NaN;#y=NaN;#x=NaN;#z=NaN;#e=NaN;#a=NaN;constructor(t,s,i,h,r,l,b,y,x,z,e,a){this.#t=0,this.#s=0,this.#i=0,this.#h=0,this.#r=0,this.#l=0,this.#b=0,this.#y=0,this.#x=0,this.#z=0,this.#e=0,this.#a=0,t instanceof C3.Quad3D?this.copy(t):this.set(t??0,s??0,i??0,h??0,r??0,l??0,b??0,y??0,x??0,z??0,e??0,a??0)}set(t,s,i,h,r,l,b,y,x,z,e,a){this.#t=+t,this.#s=+s,this.#i=+i,this.#h=+h,this.#r=+r,this.#l=+l,this.#b=+b,this.#y=+y,this.#x=+x,this.#z=+z,this.#e=+e,this.#a=+a}toArray(){return[this.#t,this.#s,this.#i,this.#h,this.#r,this.#l,this.#b,this.#y,this.#x,this.#z,this.#e,this.#a]}copy(t){[this.#t,this.#s,this.#i,this.#h,this.#r,this.#l,this.#b,this.#y,this.#x,this.#z,this.#e,this.#a]=t.toArray()}setFromQuad2d(t,s=0){[this.#t,this.#s,this.#h,this.#r,this.#b,this.#y,this.#z,this.#e]=t.toArray(),this.#i=s,this.#l=s,this.#x=s,this.#a=s}setTlx(t){this.#t=+t}getTlx(){return this.#t}setTly(t){this.#s=+t}getTly(){return this.#s}setTlz(t){this.#i=+t}getTlz(){return this.#i}setTrx(t){this.#h=+t}getTrx(){return this.#h}setTry(t){this.#r=+t}getTry(){return this.#r}setTrz(t){this.#l=t}getTrz(){return this.#l}setBrx(t){this.#b=+t}getBrx(){return this.#b}setBry(t){this.#y=+t}getBry(){return this.#y}setBrz(t){this.#x=t}getBrz(){return this.#x}setBlx(t){this.#z=+t}getBlx(){return this.#z}setBly(t){this.#e=+t}getBly(){return this.#e}setBlz(t){this.#a=t}getBlz(){return this.#a}midX(){return(this.#t+this.#h+this.#b+this.#z)/4}midY(){return(this.#s+this.#r+this.#y+this.#e)/4}midZ(){return(this.#i+this.#l+this.#x+this.#a)/4}writeToTypedArray(t,s){t[s++]=this.#t,t[s++]=this.#s,t[s++]=this.#i,t[s++]=this.#h,t[s++]=this.#r,t[s++]=this.#l,t[s++]=this.#b,t[s++]=this.#y,t[s++]=this.#x,t[s++]=this.#z,t[s++]=this.#e,t[s]=this.#a}writeToTypedArrayWithZOffset(t,s,i){t[s++]=this.#t,t[s++]=this.#s,t[s++]=this.#i+i,t[s++]=this.#h,t[s++]=this.#r,t[s++]=this.#l+i,t[s++]=this.#b,t[s++]=this.#y,t[s++]=this.#x+i,t[s++]=this.#z,t[s++]=this.#e,t[s]=this.#a+i}getBoundingAABB3D(t){t.set(Math.min(this.#t,this.#h,this.#b,this.#z),Math.min(this.#s,this.#r,this.#y,this.#e),Math.min(this.#i,this.#l,this.#x,this.#a),Math.max(this.#t,this.#h,this.#b,this.#z),Math.max(this.#s,this.#r,this.#y,this.#e),Math.max(this.#i,this.#l,this.#x,this.#a))}toQuad2dXYPlane(t){t.set(this.#t,this.#s,this.#h,this.#r,this.#b,this.#y,this.#z,this.#e)}toQuad2dYZPlane(t){t.set(this.#s,this.#i,this.#r,this.#l,this.#y,this.#x,this.#e,this.#a)}toQuad2dXZPlane(t){t.set(this.#t,this.#i,this.#h,this.#l,this.#b,this.#x,this.#z,this.#a)}}; } // ../lib/geometry/aabb3d.js { const C3=globalThis.C3;C3.AABB3D=class{#t=NaN;#i=NaN;#h=NaN;#s=NaN;#o=NaN;#e=NaN;constructor(t,i,h,s,o,e){t instanceof C3.Rect?this.copyRect(t):t instanceof C3.AABB3D?this.copyAABB3D(t):this.set(t??0,i??0,h??0,s??0,o??0,e??0)}set(t,i,h,s,o,e){this.#t=+t,this.#i=+i,this.#h=+h,this.#s=+s,this.#o=+o,this.#e=+e}setWHD(t,i,h,s,o,e){t=+t,i=+i,h=+h,this.#t=t,this.#i=i,this.#h=h,this.#s=t+ +s,this.#o=i+ +o,this.#e=h+ +e}setFromRect(t,i=0,h=0){this.#t=t.getLeft(),this.#i=t.getTop(),this.#h=+i,this.#s=t.getRight(),this.#o=t.getBottom(),this.#e=+h}copy(t){if(t instanceof C3.Rect)this.copyRect(t);else{if(!(t instanceof C3.AABB3D))throw new TypeError("expected Rect or AABB3D");this.copyAABB3D(t)}}copyRect(t){this.#t=t.getLeft(),this.#i=t.getTop(),this.#h=0,this.#s=t.getRight(),this.#o=t.getBottom(),this.#e=0}copyAABB3D(t){this.#t=t.getLeft(),this.#i=t.getTop(),this.#h=t.getBack(),this.#s=t.getRight(),this.#o=t.getBottom(),this.#e=t.getFront()}clone(){return new C3.AABB3D(this.#t,this.#i,this.#h,this.#s,this.#o,this.#e)}toRect(){return new C3.Rect(this.#t,this.#i,this.#s,this.#o)}toDOMRect(){return new DOMRect(this.#t,this.#i,this.width(),this.height())}toArray(){return[this.#t,this.#i,this.#h,this.#s,this.#o,this.#e]}setLeft(t){this.#t=+t}getLeft(){return this.#t}setTop(t){this.#i=+t}getTop(){return this.#i}setBack(t){this.#h=+t}getBack(){return this.#h}setRight(t){this.#s=+t}getRight(){return this.#s}setBottom(t){this.#o=+t}getBottom(){return this.#o}setFront(t){this.#e=+t}getFront(){return this.#e}width(){return this.#s-this.#t}height(){return this.#o-this.#i}depth(){return this.#e-this.#h}midX(){return(this.#t+this.#s)/2}midY(){return(this.#i+this.#o)/2}midZ(){return(this.#h+this.#e)/2}offset(t,i,h){t=+t,i=+i,h=+h,this.#t+=t,this.#i+=i,this.#h+=h,this.#s+=t,this.#o+=i,this.#e+=h}offsetLeft(t){this.#t+=+t}offsetTop(t){this.#i+=+t}offsetBack(t){this.#h+=+t}offsetRight(t){this.#s+=+t}offsetBottom(t){this.#o+=+t}offsetFront(t){this.#e+=+t}swapLeftRight(){const t=this.#t;this.#t=this.#s,this.#s=t}swapTopBottom(){const t=this.#i;this.#i=this.#o,this.#o=t}swapBackFront(){const t=this.#h;this.#h=this.#e,this.#e=t}normalize(){this.#t>this.#s&&this.swapLeftRight(),this.#i>this.#o&&this.swapTopBottom(),this.#h>this.#e&&this.swapBackFront()}expandToContain(t){t.getLeft()this.#s&&(this.#s=t.getRight()),t.getBottom()>this.#o&&(this.#o=t.getBottom()),t.getFront()>this.#e&&(this.#e=t.getFront())}intersectsRect(t){return!(t.getRight()this.#s||t.getTop()>this.#o)}containsRect(t){return t.getLeft()>=this.#t&&t.getTop()>=this.#i&&t.getRight()<=this.#s&&t.getBottom()<=this.#o}intersectsAABB3D(t){return!(t.getRight()this.#s||t.getTop()>this.#o||t.getBack()>this.#e)}intersectsAABB3DIgnoringZ(t){return!(t.getRight()this.#s||t.getTop()>this.#o)}containsPoint(t,i,h){return t>=this.#t&&t<=this.#s&&i>=this.#i&&i<=this.#o&&h>=this.#h&&h<=this.#e}containsPoint2d(t,i){return t>=this.#t&&t<=this.#s&&i>=this.#i&&i<=this.#o}}; } // ../lib/geometry/hexahedron.js { const C3=globalThis.C3;C3.Hexahedron=class{#t=NaN;#l=NaN;#h=NaN;#s=NaN;#i=NaN;#r=NaN;#u=NaN;#b=NaN;#x=NaN;#y=NaN;#z=NaN;#N=NaN;#a=NaN;#n=NaN;#o=NaN;#e=NaN;#c=NaN;#m=NaN;#M=NaN;#A=NaN;#C=NaN;#d=NaN;#g=NaN;#B=NaN;constructor(t){t instanceof C3.Hexahedron?this.copy(t):(this.#t=0,this.#l=0,this.#h=0,this.#s=0,this.#i=0,this.#r=0,this.#u=0,this.#b=0,this.#x=0,this.#y=0,this.#z=0,this.#N=0,this.#a=0,this.#n=0,this.#o=0,this.#e=0,this.#c=0,this.#m=0,this.#M=0,this.#A=0,this.#C=0,this.#d=0,this.#g=0,this.#B=0)}toArray(){return[this.#t,this.#l,this.#h,this.#s,this.#i,this.#r,this.#u,this.#b,this.#x,this.#y,this.#z,this.#N,this.#a,this.#n,this.#o,this.#e,this.#c,this.#m,this.#M,this.#A,this.#C,this.#d,this.#g,this.#B]}copy(t){[this.#t,this.#l,this.#h,this.#s,this.#i,this.#r,this.#u,this.#b,this.#x,this.#y,this.#z,this.#N,this.#a,this.#n,this.#o,this.#e,this.#c,this.#m,this.#M,this.#A,this.#C,this.#d,this.#g,this.#B]=t.toArray()}getBoundingAABB3D(t){t.set(Math.min(this.#t,this.#s,this.#u,this.#y,this.#a,this.#e,this.#M,this.#d),Math.min(this.#l,this.#i,this.#b,this.#z,this.#n,this.#c,this.#A,this.#g),Math.min(this.#h,this.#r,this.#x,this.#N,this.#o,this.#m,this.#C,this.#B),Math.max(this.#t,this.#s,this.#u,this.#y,this.#a,this.#e,this.#M,this.#d),Math.max(this.#l,this.#i,this.#b,this.#z,this.#n,this.#c,this.#A,this.#g),Math.max(this.#h,this.#r,this.#x,this.#N,this.#o,this.#m,this.#C,this.#B))}}; } // lib/misc/collisionPoly.js { const C3=self.C3,assert=self.assert,DEFAULT_POLY_POINTS=[0,0,1,0,1,1,0,1],tempQuad=C3.New(C3.Quad2D);C3.CollisionPoly=class extends C3.DefendedBase{constructor(t,s=!0){super(),t||(t=DEFAULT_POLY_POINTS),this._ptsArr=Float64Array.from(t),this._bbox=new C3.Rect,this._isBboxChanged=!0,this._enabled=s}Release(){}pointsArr(){return this._ptsArr}pointCount(){return this._ptsArr.length/2}setPoints(t){this._ptsArr.length===t.length?this._ptsArr.set(t):this._ptsArr=Float64Array.from(t),this._isBboxChanged=!0}setDefaultPoints(){this.setPoints(DEFAULT_POLY_POINTS)}copy(t){this.setPoints(t._ptsArr)}setBboxChanged(){this._isBboxChanged=!0}_updateBbox(){if(!this._isBboxChanged)return;const t=this._ptsArr;let s=t[0],e=t[1],r=s,n=e;for(let o=0,i=t.length;or&&(r=i),hn&&(n=h)}this._bbox.set(s,e,r,n),this._isBboxChanged=!1}setFromRect(t,s,e){let r=this._ptsArr;8!==r.length&&(r=new Float64Array(8),this._ptsArr=r),r[0]=t.getLeft()-s,r[1]=t.getTop()-e,r[2]=t.getRight()-s,r[3]=t.getTop()-e,r[4]=t.getRight()-s,r[5]=t.getBottom()-e,r[6]=t.getLeft()-s,r[7]=t.getBottom()-e,this._bbox.copy(t),0===s&&0===e||this._bbox.offset(-s,-e),this._isBboxChanged=!1}setFromQuad(t,s,e){tempQuad.copy(t),tempQuad.offset(s,e),this.setPoints(tempQuad.toArray()),this._isBboxChanged=!0}transform(t,s,e){let r=0,n=1;0!==e&&(r=Math.sin(e),n=Math.cos(e)),this.transformPrecalc(t,s,r,n)}transformPrecalc(t,s,e,r){const n=this._ptsArr;for(let o=0,i=n.length;o!e.GetEditorEaseData(s,a)||e.GetEditorEaseData(s,a).transition.IsForAnyPurpose())):(t=CUSTOM_EASE_RUNTIME_MAP,i=[...t.keys()]);const x=i.sort();return[...PREDEFINED_EASE_MAP.keys()].concat(x).filter(e=>!s.includes(e))}static GetRuntimeEaseNames(){this._CreateEaseMap();const e=[...CUSTOM_EASE_RUNTIME_MAP.keys()];return e.sort(),[...PREDEFINED_EASE_MAP.keys()].concat(e)}static GetCustomRuntimeEaseNames(){this._CreateEaseMap();const e=[...CUSTOM_EASE_RUNTIME_MAP.keys()];return e.sort(),e}static IsPredefinedTranslatedName(e){for(const a of EASE_TRANSLATION_KEYS){if(self.lang(`ui.bars.timeline.eases.${a}`)===e)return!0}for(const a of SHORT_EASE_TRANSLATION_KEYS){if(self.lang(`ui.bars.timeline.short-eases.${a}`)===e)return!0}}static IsNamePredefined(e){return this._CreateEaseMap(),[...PREDEFINED_EASE_MAP.keys()].includes(e)}static _GetEase(a){const s=ALIAS_MAP.get(a);return s?EASE_MAP.get(s):e.IsNamePredefined(a)?EASE_MAP.get(a):PRIVATE_EASE_MAP.has(a)?PRIVATE_EASE_MAP.get(a):void 0}static GetBuiltInTransition(e){return this._CreateEaseMap(),BUILT_IN_TRANSITION_MAP.get(e)}static GetEditorEase(a,s){this._CreateEaseMap();const t=e._GetEase(a);if(t)return t;if(!s)throw new Error("missing ease function");return CUSTOM_EASE_EDITOR_MAP.get(s).get(a)}static GetEditorEaseData(e,a){this._CreateEaseMap();const s=CUSTOM_EASE_DATA_EDITOR_MAP.get(a);if(s)return s.get(e)}static HasEditorEase(a,s){this._CreateEaseMap();return!!e._GetEase(a)||!!CUSTOM_EASE_EDITOR_MAP.get(s).get(a)}static GetRuntimeEase(a){this._CreateEaseMap();const s=e._GetEase(a);return s||CUSTOM_EASE_RUNTIME_MAP.get(a)}static GetRuntimeEaseData(e){return this._CreateEaseMap(),CUSTOM_EASE_DATA_RUNTIME_MAP.get(e)}static GetEaseFromIndex(e){this._CreateEaseMap();return this.GetRuntimeEaseNames()[e]}static GetIndexForEase(e,a){this._CreateEaseMap();return this.GetEditorEaseNames(a).indexOf(e)}static GetIndexForEaseAtRuntime(e){return this.GetIndexForEase(e)}static _CreateEaseMap(){0===EASE_MAP.size&&(this._AddPredifinedEase("default",()=>{}),this._AddPredifinedEase("noease",[{"x":0,"y":0,"sax":.336,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.336,"eay":0,"se":!1,"ee":!0}],!0),this._AddPredifinedEase("easeinsine",[{"x":0,"y":0,"sax":.485,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.038,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutsine",[{"x":0,"y":0,"sax":.038,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.485,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutsine",[{"x":0,"y":0,"sax":.336,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.336,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinelastic",[{"x":0,"y":0,"sax":.018,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.116,"y":.002,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.266,"y":-.005,"sax":.024,"say":0,"eax":-.021,"eay":0,"se":!0,"ee":!0},{"x":.416,"y":.016,"sax":.024,"say":0,"eax":-.026,"eay":0,"se":!0,"ee":!0},{"x":.566,"y":-.045,"sax":.061,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.716,"y":.132,"sax":.072,"say":-.004,"eax":-.045,"eay":0,"se":!0,"ee":!0},{"x":.866,"y":-.373,"sax":.06,"say":0,"eax":-.049,"eay":-.002,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.038,"eay":-.263,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutelastic",[{"x":0,"y":0,"sax":.038,"say":.263,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.136,"y":1.373,"sax":.049,"say":.002,"eax":-.06,"eay":0,"se":!0,"ee":!0},{"x":.286,"y":.868,"sax":.045,"say":0,"eax":-.072,"eay":.004,"se":!0,"ee":!0},{"x":.436,"y":1.045,"sax":.025,"say":0,"eax":-.061,"eay":0,"se":!0,"ee":!0},{"x":.586,"y":.984,"sax":.026,"say":0,"eax":-.024,"eay":0,"se":!0,"ee":!0},{"x":.736,"y":1.005,"sax":.021,"say":0,"eax":-.024,"eay":0,"se":!0,"ee":!0},{"x":.886,"y":.998,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.018,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutelastic",[{"x":0,"y":0,"sax":.025,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.067,"y":.001,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.18,"y":-.005,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.292,"y":.025,"sax":.053,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.405,"y":-.118,"sax":.069,"say":0,"eax":-.027,"eay":0,"se":!0,"ee":!0},{"x":.597,"y":1.118,"sax":.027,"say":0,"eax":-.069,"eay":0,"se":!0,"ee":!0},{"x":.71,"y":.975,"sax":.025,"say":0,"eax":-.053,"eay":0,"se":!0,"ee":!0},{"x":.822,"y":1.005,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.935,"y":.999,"sax":.025,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.025,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinback",[{"x":0,"y":0,"sax":.35,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.34,"eay":-1.579,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutback",[{"x":0,"y":0,"sax":.34,"say":1.579,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.35,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutback",[{"x":0,"y":0,"sax":.035,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.242,"y":-.1,"sax":.258,"say":0,"eax":-.025,"eay":0,"se":!0,"ee":!0},{"x":.76,"y":1.1,"sax":.025,"say":0,"eax":-.26,"eay":0,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.035,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinbounce",[{"x":0,"y":0,"sax":.033,"say":.025,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.092,"y":0,"sax":.026,"say":.078,"eax":-.033,"eay":.025,"se":!0,"ee":!0},{"x":.274,"y":0,"sax":.097,"say":.319,"eax":-.026,"eay":.078,"se":!0,"ee":!0},{"x":.637,"y":0,"sax":.105,"say":.625,"eax":-.097,"eay":.319,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.125,"eay":-.004,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutbounce",[{"x":0,"y":0,"sax":.125,"say":.004,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.365,"y":1,"sax":.097,"say":-.319,"eax":-.105,"eay":-.625,"se":!0,"ee":!0},{"x":.728,"y":1,"sax":.026,"say":-.078,"eax":-.097,"eay":-.319,"se":!0,"ee":!0},{"x":.91,"y":1,"sax":.033,"say":-.025,"eax":-.026,"eay":-.078,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.033,"eay":-.025,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutbounce",[{"x":0,"y":0,"sax":.01,"say":.006,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.046,"y":0,"sax":.021,"say":.038,"eax":-.01,"eay":.006,"se":!0,"ee":!0},{"x":.137,"y":0,"sax":.059,"say":.158,"eax":-.021,"eay":.038,"se":!0,"ee":!0},{"x":.319,"y":0,"sax":.117,"say":.744,"eax":-.059,"eay":.158,"se":!0,"ee":!0},{"x":.683,"y":1,"sax":.059,"say":-.158,"eax":-.117,"eay":-.744,"se":!0,"ee":!0},{"x":.865,"y":1,"sax":.021,"say":-.038,"eax":-.059,"eay":-.158,"se":!0,"ee":!0},{"x":.956,"y":1,"sax":.01,"say":-.006,"eax":-.021,"eay":-.038,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.01,"eay":-.006,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeincubic",[{"x":0,"y":0,"sax":.75,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.138,"eay":-.321,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutcubic",[{"x":0,"y":0,"sax":.138,"say":.321,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.75,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutcubic",[{"x":0,"y":0,"sax":.285,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.5,"y":.5,"sax":.081,"say":.272,"eax":-.081,"eay":-.272,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.285,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinquad",[{"x":0,"y":0,"sax":.4,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.178,"eay":-.392,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutquad",[{"x":0,"y":0,"sax":.178,"say":.392,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.4,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutquad",[{"x":0,"y":0,"sax":.25,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.5,"y":.5,"sax":.03,"say":.065,"eax":-.03,"eay":-.065,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.25,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinquart",[{"x":0,"y":0,"sax":.5,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.25,"eay":-1,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutquart",[{"x":0,"y":0,"sax":.25,"say":1,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.5,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutquart",[{"x":0,"y":0,"sax":.765,"say":.03,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.765,"eay":-.03,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinquint",[{"x":0,"y":0,"sax":.6,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.2,"eay":-1,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutquint",[{"x":0,"y":0,"sax":.2,"say":1,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.6,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutquint",[{"eax":0,"eay":0,"ee":!1,"sax":.84,"say":0,"se":!0,"x":0,"y":0},{"eax":-.84,"eay":0,"ee":!0,"sax":0,"say":0,"se":!1,"x":1,"y":1}]),this._AddPredifinedEase("easeincirc",[{"x":0,"y":0,"sax":.25,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.024,"eay":-.808,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutcirc",[{"x":0,"y":0,"sax":.024,"say":.808,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.25,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutcirc",[{"x":0,"y":0,"sax":.125,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":.5,"y":.5,"sax":.02,"say":.428,"eax":-.02,"eay":-.428,"se":!0,"ee":!0},{"x":1,"y":1,"sax":0,"say":0,"eax":-.125,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinexpo",[{"x":0,"y":0,"sax":.66,"say":0,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.14,"eay":-1,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeoutexpo",[{"x":0,"y":0,"sax":.14,"say":1,"eax":0,"eay":0,"se":!0,"ee":!1},{"x":1,"y":1,"sax":0,"say":0,"eax":-.66,"eay":0,"se":!1,"ee":!0}]),this._AddPredifinedEase("easeinoutexpo",[{"eax":0,"eay":0,"ee":!1,"sax":.345,"say":0,"se":!0,"x":0,"y":0},{"eax":-.06,"eay":-.5,"ee":!0,"sax":.06,"say":.5,"se":!0,"x":.5,"y":.5},{"eax":-.335,"eay":0,"ee":!0,"sax":0,"say":0,"se":!1,"x":1,"y":1}]),this._AddPrivateCustomEase("cubicbezier",this.EaseCubicBezier),this._AddPrivateCustomEase("spline",this.EaseSpline))}static _AddPredifinedEase(a,s,t=!1){if("function"==typeof s)e._AddEase(a,s,"predefined");else{if(!C3.IsArray(s))throw new Error("unexpected arguments");if(self.BuiltInTransition){const i=C3.New(self.BuiltInTransition,a,t);i.SetFromJson(s),e._AddEase(a,(e,a,s,t)=>i.Interpolate(e,a,s,t),"predefined"),BUILT_IN_TRANSITION_MAP.set(a,i)}else{const i=C3.New(C3.Transition,[a,s.map(e=>[e["x"],e["y"],e["sax"],e["say"],e["eax"],e["eay"],e["se"],e["ee"]])],!1);i.MakeLinear(t),e._AddEase(a,(e,a,s,t)=>i.Interpolate(e,a,s,t),"predefined")}}}static _AddPrivateCustomEase(a,s){e._AddEase(a,s,"private")}static AddCustomEase(a,s,t,i){this._CreateEaseMap(),e._AddEase(a,s,"custom",t,i)}static RemoveCustomEase(e,a){if(this.IsNamePredefined(e))return;if([...PRIVATE_EASE_MAP.keys()].includes(e))return;const s=CUSTOM_EASE_EDITOR_MAP.get(a);s&&s.delete(e);const t=CUSTOM_EASE_DATA_EDITOR_MAP.get(a);t&&t.delete(e)}static _AddEase(e,a,s,t,i){switch(s){case"predefined":EASE_MAP.set(e,a),PREDEFINED_EASE_MAP.set(e,a);break;case"custom":if(t){CUSTOM_EASE_EDITOR_MAP.has(t)||CUSTOM_EASE_EDITOR_MAP.set(t,new Map),CUSTOM_EASE_DATA_EDITOR_MAP.has(t)||CUSTOM_EASE_DATA_EDITOR_MAP.set(t,new Map);CUSTOM_EASE_EDITOR_MAP.get(t).set(e,a);CUSTOM_EASE_DATA_EDITOR_MAP.get(t).set(e,i)}else CUSTOM_EASE_RUNTIME_MAP.set(e,a),CUSTOM_EASE_DATA_RUNTIME_MAP.set(e,i);break;case"private":EASE_MAP.set(e,a),PRIVATE_EASE_MAP.set(e,a);break;default:throw new Error("unexpected ease mode")}}static NoEase(e,a,s,t){return 0===t?a:s*e/t+a}static EaseCubicBezier(e,a,s,t,i){return a+3*e*(s-a)+3*e**2*(a+t-2*s)+e**3*(i-a+3*s-3*t)}static EaseSpline(e,s,t,i,x,y,n,E,_,r){if(i===x&&y===n)return e;const u=get_t_for_x(e,s,i,y,E,r),d=a(t,x,n,_),A=b(t,x,n,_),o=c(t,x,n,_);return calc_bezier(u,d,A,o)}static GetBezierSamples(e,s,t,i){const x=[],y=a(e,s,t,i),n=b(e,s,t,i),E=c(e,s,t,i);for(let e=0;et-3*s+3*a-e,b=(e,a,s,t)=>3*s-6*a+3*e,c=(e,a,s,t)=>3*(a-e),calc_bezier=(e,a,s,t)=>((a*e+s)*e+t)*e,get_slope=(e,a,s,t)=>3*a*e*e+2*s*e+t,get_t_for_x=(e,s,t,i,x,y)=>{if(1==e)return 1;let n=0,E=1,_=y[E],r=SAMPLE_COUNT-1;y[SAMPLE_COUNT-1];for(;E!=r&&_<=e;)E++,_=y[E],n+=SAMPLE_STEP;E--,_=y[E];let u=n+(e-_)/(y[E+1]-_)*SAMPLE_STEP;const d=a(s,t,i,x),A=b(s,t,i,x),o=c(s,t,i,x),M=get_slope(u,d,A,o);if(0===M)return u;if(M>=.01){for(let a=0;a<4;++a){u-=(calc_bezier(u,d,A,o)-e)/get_slope(u,d,A,o)}return u}{let a,s,t=n,i=n+SAMPLE_STEP,x=0;do{u=t+(i-t)/2;let y=calc_bezier(u,d,A,o)-e;y>0?i=u:t=u,a=Math.abs(y)>1e-7,s=++x<10}while(a&&s);return u}}; } // ../lib/misc/probability.js { const C3=self.C3;function RequireStringOrNumber(t){C3.IsString(t)}C3.ProbabilityTable=class{constructor(t){this._items=[],this._name=t||"",this._totalWeight=0}Release(){this.Clear(),this._items=null}GetName(){return this._name}Clear(){C3.clear2DArray(this._items),this._totalWeight=0}GetTotalWeight(){return this._totalWeight}Sample(t=Math.random()*this.GetTotalWeight()){let e=0;for(const[i,s]of this._items)if(e+=i,t0||(this.#e&&(this.#e.clear(),this.#e=null),this.#s&&(this.#s.clear(),this.#s=null),this.#i&&(C3.clearArray(this.#i),this.#i=null),C3.Release(this))}_AddListener(e,s){if(this.#r())return this.#i||(this.#i=[]),void this.#i.push({op:"add",func:e,capture:s});s?(this.#e||(this.#e=new Set),this.#e.add(e)):(this.#s||(this.#s=new Set),this.#s.add(e))}_RemoveListener(e,s){if(this.#r())return this.#i||(this.#i=[]),void this.#i.push({op:"remove",func:e,capture:s});s?this.#e&&(this.#e.delete(e),0===this.#e.size&&(this.#e=null)):this.#s&&(this.#s.delete(e),0===this.#s.size&&(this.#s=null))}_IsEmpty(){return!this.#e&&!this.#s}#r(){return this.#t>0}#n(){if(this.#i){for(const e of this.#i)if("add"===e.op)this._AddListener(e.func,e.capture);else{if("remove"!==e.op)throw new Error("invalid op");this._RemoveListener(e.func,e.capture)}C3.clearArray(this.#i),this.#i=null}}_FireCancellable(e){this.#h();let s=!1;if(this.#e)for(const t of this.#e)if(t(e),e.propagationStopped){s=!0;break}if(!s&&this.#s)for(const s of this.#s)if(s(e),e.propagationStopped)break;return this.#o(),!e.defaultPrevented}_FireNonCancellable(e){if(this.#h(),this.#e)for(const s of this.#e)s(e);if(this.#s)for(const s of this.#s)s(e);return this.#o(),!0}#h(){this.#t++}#o(){this.#t--,0===this.#t&&this.#i&&this.#i.length>0&&this.#n()}SetDelayRemoveEventsEnabled(e){e?this.#h():this.#o()}_FireAsync(e){let s=[];if(this.#e)for(const t of this.#e)s.push(C3.Asyncify(()=>t(e)));if(this.#s)for(const t of this.#s)s.push(C3.Asyncify(()=>t(e)));return Promise.all(s).then(()=>!e.defaultPrevented)}_FireAndWait_AsyncOptional(e){const s=[];if(this.#h(),this.#e)for(const t of this.#e){const i=t(e);i instanceof Promise&&s.push(i)}if(this.#s)for(const t of this.#s){const i=t(e);i instanceof Promise&&s.push(i)}return this.#o(),s.length?Promise.all(s).then(()=>!e.defaultPrevented):!e.defaultPrevented}async _FireAndWaitAsync(e){return await this._FireAndWait_AsyncOptional(e)}async _FireAndWaitAsyncSequential(e){if(this.#h(),this.#e)for(const s of this.#e){const t=s(e);t instanceof Promise&&await t}if(this.#s)for(const s of this.#s){const t=s(e);t instanceof Promise&&await t}return this.#o(),!e.defaultPrevented}*_FireAsGenerator(e){if(this.#h(),this.#e)for(const s of this.#e){const t=s(e);C3.IsIterator(t)&&(yield*t)}if(this.#s)for(const s of this.#s){const t=s(e);C3.IsIterator(t)&&(yield*t)}this.#o()}}; } // ../lib/events/dispatcher.js { const C3=self.C3,releasedDispatchers=new WeakSet;C3.Event.Dispatcher=class extends C3.DefendedBase{#e=null;constructor(){super()}Release(){if(releasedDispatchers.has(this))throw new Error("already released");this.ClearEvents(),releasedDispatchers.add(this),C3.Release(this)}WasReleased(){return releasedDispatchers.has(this)}ClearEvents(){if(this.#e){for(const e of this.#e.values())e.Release();this.#e.clear(),this.#e=null}}_GetHandlerByType(e,t){if(this.#e){const t=this.#e.get(e);if(t)return t}if(t){const t=C3.New(C3.Event.Handler);return this.#e||(this.#e=new Map),this.#e.set(e,t),t}return null}HasAnyHandlerFor(e){return this.#e&&this.#e.has(e)}addEventListener(e,t,n){this._GetHandlerByType(e,!0)._AddListener(t,!!n)}removeEventListener(e,t,n){const s=this._GetHandlerByType(e,!1);s&&(s._RemoveListener(t,!!n),this.#e&&s._IsEmpty()&&this.#e.delete(e))}dispatchEvent(e){const t=this._GetHandlerByType(e.type,!1);return!t||(e.cancelable?t._FireCancellable(e):t._FireNonCancellable(e))}dispatchEventAsync(e){const t=this._GetHandlerByType(e.type,!1);return t?(e.isAsync=!0,t._FireAsync(e)):Promise.resolve(!0)}async dispatchEventAndClearAsync(e){const t=this._GetHandlerByType(e.type,!1);if(!t)return!0;this.#e&&this.#e.delete(e.type),e.isAsync=!0;const n=await t._FireAsync(e);return t.Release(),n}async dispatchEventAndWaitAsync(e){const t=this._GetHandlerByType(e.type,!1);return!t||await t._FireAndWaitAsync(e)}dispatchEventAndWait_AsyncOptional(e){const t=this._GetHandlerByType(e.type,!1);return!t||t._FireAndWait_AsyncOptional(e)}async dispatchEventAndWaitAsyncSequential(e){const t=this._GetHandlerByType(e.type,!1);return!t||await t._FireAndWaitAsyncSequential(e)}dispatchGeneratorEvent(e){const t=this._GetHandlerByType(e.type,!1);if(!t)return null;if(e.cancelable)throw new Error("not supported");return t._FireAsGenerator(e)}SetDelayRemoveEventsEnabled(e){if(this.#e)for(const t of this.#e.values())t.SetDelayRemoveEventsEnabled(e)}}; } // ../lib/util/asyncify.js { const C3=self.C3,SETTIMEOUT_WORK_DURATION=12,SETTIMEOUT_INTERVAL=16,IDLECALLBACK_TIMEOUT=35,SUPPORTS_RIC="undefined"!=typeof requestIdleCallback;let workQueue=[],callbackId=-1,highThroughputMode=0;function SetNewCallback(e){callbackId=SUPPORTS_RIC&&0===highThroughputMode?requestIdleCallback(DoAsyncifiedWork,{timeout:35}):setTimeout(DoAsyncifiedWork,highThroughputMode>0?1:e)}function DoAsyncifiedWork(e){if(callbackId=-1,!workQueue.length)return;let o=performance.now(),i=o,t=0,n=0;do{DoNextAsyncifiedJob(workQueue.shift()),i=performance.now(),++t,n=(i-o)/t*1.1}while(workQueue.length&&(SUPPORTS_RIC&&0===highThroughputMode&&void 0!==e?n{workQueue.push({func:e,resolve:i,reject:t,stack:o}),asyncifyDisabled?DoNextAsyncifiedJob(workQueue.pop()):-1===callbackId&&SetNewCallback(16)})},C3.Asyncify.SetHighThroughputMode=function(e){if(e)++highThroughputMode;else if(--highThroughputMode,highThroughputMode<0)throw new Error("already turned off high throughput mode")}; } // ../lib/util/idleTimeout.js { const C3=self.C3,IDLE_CHECK_MIN_INTERVAL=1e3,IDLE_CHECK_TIMER_OVERSHOOT=100;let cachedNowTime=-1;function ClearTimeCache(){cachedNowTime=-1}C3.FastGetDateNow=function(){return-1===cachedNowTime&&(cachedNowTime=Date.now(),self.setTimeout(ClearTimeCache,16)),cachedNowTime};let timerId=-1,nextDeadline=-1,activeIdleTimeouts=new Set;function CheckActiveIdleTimeouts(){timerId=-1,nextDeadline=-1;let e=Date.now();for(let t of activeIdleTimeouts)if(t._CheckTimeout(e)){let e=t._GetDeadline();(-1===nextDeadline||ee+1e3&&(self.clearTimeout(timerId),nextDeadline=this._deadline,timerId=self.setTimeout(CheckActiveIdleTimeouts,this._timeout+100))}_CheckTimeout(e){return!(e>=this._deadline)||(this._callback()?(this._deadline=e+this._timeout,!0):(this._isActive=!1,!1))}_GetDeadline(){return this._deadline}Cancel(){this._isActive&&(activeIdleTimeouts.delete(this),this._isActive=!1,0===activeIdleTimeouts.size&&-1!==timerId&&(self.clearTimeout(timerId),timerId=-1,nextDeadline=-1))}Release(){this.Cancel(),this._callback=null}}; } // ../lib/util/disposable.js { const C3=self.C3,disposedDisposables=new WeakSet;C3.Disposable=class s{constructor(s){this._disposeAction=s}Dispose(){disposedDisposables.has(this)||(disposedDisposables.add(this),this._disposeAction&&(this._disposeAction(),this._disposeAction=null))}IsDisposed(){return disposedDisposables.has(this)}Release(){this.Dispose()}static Release(e){return new s(()=>e.Release())}static From(s,e,i,o,t){if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("expected string or array");if(null==o)o=!1;else if("boolean"!=typeof o&&"object"!=typeof o)throw new TypeError("invalid event listener options");if(t&&(i=i.bind(t)),Array.isArray(e)||e.includes(" ")){"string"==typeof e&&(e=e.split(" "));const t=new C3.CompositeDisposable;for(const r of e)s.addEventListener(r,i,o),t.Add(C3.New(C3.Disposable,()=>s.removeEventListener(r,i,o)));return t}return s.addEventListener(e,i,o),C3.New(C3.Disposable,()=>s.removeEventListener(e,i,o))}},C3.StubDisposable=class extends C3.Disposable{SetAction(s){this._disposeAction=s}},C3.CompositeDisposable=class extends C3.Disposable{constructor(...s){super(),this._disposables=new Set;for(const e of s)this.Add(e)}Add(...s){if(this.IsDisposed())throw new Error("already disposed");for(const e of s)this._disposables.add(e)}Remove(s){if(this.IsDisposed())throw new Error("already disposed");this._disposables.delete(s)}RemoveAll(){if(this.IsDisposed())throw new Error("already disposed");if(this._disposables){for(const s of this._disposables)s.Dispose();this._disposables.clear()}}Dispose(){if(this.IsDisposed())throw new Error("already disposed");super.Dispose();for(const s of this._disposables)s.Dispose();this._disposables.clear(),this._disposables=null}}; } // lib/util/kahanSum.js { const C3=self.C3;C3.KahanSum=class extends C3.DefendedBase{constructor(){super(),this._c=0,this._y=0,this._t=0,this._sum=0}Add(s){s=+s,this._y=s-this._c,this._t=this._sum+this._y,this._c=this._t-this._sum-this._y,this._sum=this._t}Subtract(s){this._sum-=+s}Get(){return this._sum}Reset(){this._c=0,this._y=0,this._t=0,this._sum=0}Set(s){this._c=0,this._y=0,this._t=0,this._sum=+s}Copy(s){this._c=s._c,this._y=s._y,this._t=s._t,this._sum=s._sum}Release(){}}; } // lib/util/redblackset.js { const C3=self.C3,js_cols={},RED=!0,BLACK=!1;js_cols.RBnode=function(t){this.tree=t,this.right=this.tree.sentinel,this.left=this.tree.sentinel,this.parent=null,this.color=!1,this.key=null},js_cols.RedBlackSet=function(t){this.size=0,this.sentinel=new js_cols.RBnode(this),this.sentinel.color=false,this.root=this.sentinel,this.root.parent=this.sentinel,this.compare=t||this.default_compare},js_cols.RedBlackSet.prototype.default_compare=function(t,e){return t0){var e=this.get_(t);if(e==this.sentinel)return null;if(e.right!=this.sentinel)return this.min(e.right).key;for(var s=e.parent;s!=this.sentinel&&e==s.right;)e=s,s=s.parent;return s!=this.sentinel?s.key:null}return null},js_cols.RedBlackSet.prototype.predecessor=function(t){if(this.size>0){var e=this.get_(t);if(e==this.sentinel)return null;if(e.left!=this.sentinel)return this.max(e.left).key;for(var s=e.parent;s!=this.sentinel&&e==s.left;)e=s,s=s.parent;return s!=this.sentinel?s.key:null}return null},js_cols.RedBlackSet.prototype.getMin=function(){return this.min(this.root).key},js_cols.RedBlackSet.prototype.getMax=function(){return this.max(this.root).key},js_cols.RedBlackSet.prototype.get_=function(t){for(var e=this.root;e!=this.sentinel&&0!=this.compare(e.key,t);)e=this.compare(t,e.key)<0?e.left:e.right;return e},js_cols.RedBlackSet.prototype.contains=function(t){return null!=this.get_(t).key},js_cols.RedBlackSet.prototype.getValues=function(){var t=[];return this.forEach(function(e){t.push(e)}),t},js_cols.RedBlackSet.prototype.insertAll=function(t){if("array"==js_cols.typeOf(t))for(var e=0;ee)return!1;var s=0;if(this.isEmpty())return!0;for(var r=this.min(this.root);r!=this.sentinel;r=this.successor_(r))js_cols.contains.call(t,t,r.key)&&s++;return s==this.getCount()},js_cols.RedBlackSet.prototype.intersection=function(t){var e=new js_cols.RedBlackSet(this.compare);if(this.isEmpty())return e;for(var s=this.min(this.root);s!=this.sentinel;s=this.successor_(s))t.contains.call(t,s.key,s.key,this)&&e.insert(s.key);return e},C3.RedBlackSet=class extends C3.DefendedBase{constructor(t){super(),this._rbSet=new js_cols.RedBlackSet(t),this._enableQueue=!1,this._queueInsert=new Set,this._queueRemove=new Set}Add(t){this._enableQueue?this._rbSet.contains(t)?this._queueRemove.delete(t):this._queueInsert.add(t):this._rbSet.insert(t)}Remove(t){this._enableQueue?this._rbSet.contains(t)?this._queueRemove.add(t):this._queueInsert.delete(t):this._rbSet.remove(t)}Has(t){return this._enableQueue?!!this._queueInsert.has(t)||!this._queueRemove.has(t)&&this._rbSet.contains(t):this._rbSet.contains(t)}Clear(){this._rbSet.clear(),this._queueInsert.clear(),this._queueRemove.clear()}toArray(){if(this._enableQueue)throw new Error("cannot be used in queueing mode");return this._rbSet.getValues()}GetSize(){return this._rbSet.getCount()+this._queueInsert.size-this._queueRemove.size}IsEmpty(){return 0===this.GetSize()}Front(){if(this.IsEmpty())throw new Error("empty set");if(this._enableQueue)throw new Error("cannot be used in queueing mode");const t=this._rbSet;return t.min(t.root).key}Shift(){if(this.IsEmpty())throw new Error("empty set");if(this._enableQueue)throw new Error("cannot be used in queueing mode");const t=this.Front();return this.Remove(t),t}SetQueueingEnabled(t){if(t=!!t,this._enableQueue!==t&&(this._enableQueue=t,!t)){for(const t of this._queueRemove)this._rbSet.remove(t);this._queueRemove.clear();for(const t of this._queueInsert)this._rbSet.insert(t);this._queueInsert.clear()}}ForEach(t){this._rbSet.forEach(t)}*values(){if(this.IsEmpty())return;const t=this._rbSet;for(let e=t.min(t.root);e!=t.sentinel;e=t.successor_(e))yield e.key}[Symbol.iterator](){return this.values()}}; } // ../lib/util/promiseThrottle.js { const C3=self.C3;C3.PromiseThrottle=class{constructor(e=C3.hardwareConcurrency){this._maxParallel=e,this._queue=[],this._activeCount=0}Add(e,t){return new Promise((r,n)=>{const s={func:e,resolve:r,reject:n,opts:t};t?.signal&&t.signal.aborted?n(new Error("abort")):(t?.signal&&(s.onabort=()=>{const e=this._queue.indexOf(s);-1!==e&&(this._queue.splice(e,1),n(new Error("abort")))},t.signal.addEventListener("abort",s.onabort)),this._queue.push(s),this._MaybeStartNext())})}_FindInQueue(e){for(let t=0,r=this._queue.length;t=this._maxParallel)return;this._activeCount++;const e=this._queue.shift();e.opts?.signal&&e.onabort&&e.opts.signal.removeEventListener("abort",e.onabort);try{const t=await e.func();e.resolve(t)}catch(t){e.reject(t)}this._activeCount--,this._MaybeStartNext()}}; } // ../lib/util/rateLimiter.js { const C3=self.C3;C3.RateLimiter=class{constructor(t,e,i){this._callback=t,this._interval=e,this._intervalOnBattery=i||2*e,this._timerId=-1,this._lastCallTime=-1/0,this._timerCallFunc=()=>this._OnTimer(),this._ignoreReset=!1,this._canRunImmediate=!1,this._callbackArguments=null}SetCanRunImmediate(t){this._canRunImmediate=!!t}_GetInterval(){return void 0!==C3.Battery&&C3.Battery.IsOnBatteryPower()?this._intervalOnBattery:this._interval}Call(...t){if(-1!==this._timerId)return;this._callbackArguments=t;let e=C3.FastGetDateNow(),i=e-this._lastCallTime,l=this._GetInterval();i>=l&&this._canRunImmediate?(this._lastCallTime=e,this._RunCallback()):this._timerId=self.setTimeout(this._timerCallFunc,Math.max(l-i,4))}_RunCallback(){this._ignoreReset=!0;const t=this._callbackArguments;this._callbackArguments=null,t?this._callback(...t):this._callback(),this._ignoreReset=!1}Reset(){this._ignoreReset||(this._CancelTimer(),this._callbackArguments=null,this._lastCallTime=C3.FastGetDateNow())}_OnTimer(){this._timerId=-1,this._lastCallTime=C3.FastGetDateNow(),this._RunCallback()}_CancelTimer(){-1!==this._timerId&&(self.clearTimeout(this._timerId),this._timerId=-1)}Release(){this._CancelTimer(),this._callback=null,this._callbackArguments=null,this._timerCallFunc=null}}; } // ../lib/util/svgRaster/svgRasterManager.js { const C3=self.C3;C3.SVGRasterManager=class{constructor(){this._images=new Map,this._allowNpotSurfaces=!1,this._getBaseSizeCallback=null,this._rasterAtSizeCallback=null,this._releaseResultCallback=null,this._redrawCallback=null}SetNpotSurfaceAllowed(e){this._allowNpotSurfaces=!!e}IsNpotSurfaceAllowed(){return this._allowNpotSurfaces}SetGetBaseSizeCallback(e){this._getBaseSizeCallback=e}GetBaseSize(e){if(!this._getBaseSizeCallback)throw new Error("no get base size callback set");return this._getBaseSizeCallback(e)}SetRasterAtSizeCallback(e){this._rasterAtSizeCallback=e}RasterAtSize(e,a,t,l,s,r){if(!this._rasterAtSizeCallback)throw new Error("no raster at size callback set");return this._rasterAtSizeCallback(e,a,t,l,s,r)}SetReleaseResultCallback(e){this._releaseResultCallback=e}ReleaseResult(e){if(!this._releaseResultCallback)throw new Error("no release result callback set");this._releaseResultCallback(e)}SetRedrawCallback(e){this._redrawCallback=e}Redraw(){if(!this._redrawCallback)throw new Error("no redraw callback set");this._redrawCallback()}AddImage(e){let a=this._images.get(e);return a||(a=C3.New(C3.SVGRasterImage,this,e),this._images.set(e,a)),a.IncReference(),a}_RemoveImage(e){this._images.delete(e.GetDataSource())}OnTexturesChanged(){for(const e of this._images.values())e.ReleaseRasterizedResult(),e.ForceRasterAgain()}}; } // ../lib/util/svgRaster/svgRasterImage.js { const C3=self.C3,MAX_SURFACE_SIZE=4096;C3.SVGRasterImage=class{constructor(e,t){this._manager=e,this._dataSource=t,this._refCount=0,this._baseWidth=0,this._baseHeight=0,this._getBaseSizePromise=this._manager.GetBaseSize(t).then(e=>{this._manager&&(this._baseWidth=e[0],this._baseHeight=e[1],this._manager.Redraw())}).catch(e=>{console.error("[SVG] Error loading SVG: ",e),this._hadError=!0,this._manager&&this._manager.Redraw()}),this._rasterSurfaceWidth=0,this._rasterSurfaceHeight=0,this._rasterImageWidth=0,this._rasterImageHeight=0,this._isRasterizing=!1,this._rasterizedResult=null,this._forceRaster=!1,this._hadError=!1}Release(){if(this._refCount<=0)throw new Error("already released");this._refCount--,0===this._refCount&&this._Release()}ReleaseRasterizedResult(){this._rasterizedResult&&(this._manager.ReleaseResult(this._rasterizedResult),this._rasterizedResult=null)}_Release(){this.ReleaseRasterizedResult(),this._manager._RemoveImage(this),this._manager=null}GetDataSource(){return this._dataSource}IncReference(){this._refCount++}HasReferences(){return this._refCount>0}GetRasterizedResult(){return this._rasterizedResult}ForceRasterAgain(){this._forceRaster=!0}async StartRasterForSize(e,t,r){if(0===t||0===r||this._hadError)return;if(this._isRasterizing)return;let s=C3.nextHighestPowerOfTwo(Math.ceil(t)),a=C3.nextHighestPowerOfTwo(Math.ceil(r));const i=Math.max(s,a);if(i>4096){const e=4096/i;t*=e,r*=e,s=Math.min(Math.ceil(s*e),4096),a=Math.min(Math.ceil(a*e),4096)}if(te?(t=a*e,r=a):(t=s,r=s/e)}if(this._manager.IsNpotSurfaceAllowed()&&(s=Math.ceil(t),a=Math.ceil(r)),s<=this._rasterSurfaceWidth&&a<=this._rasterSurfaceHeight&&!this._forceRaster)return;this._isRasterizing=!0,this._rasterSurfaceWidth=s,this._rasterSurfaceHeight=a;const h=await this._manager.RasterAtSize(this._dataSource,e,this._rasterSurfaceWidth,this._rasterSurfaceHeight,t,r);this._manager&&(this.ReleaseRasterizedResult(),this._rasterizedResult=h,this._rasterImageWidth=t,this._rasterImageHeight=r,this._isRasterizing=!1,this._forceRaster=!1,this._manager.Redraw())}WhenBaseSizeReady(){return this._getBaseSizePromise}GetBaseWidth(){return this._baseWidth}GetBaseHeight(){return this._baseHeight}GetRasterWidth(){return this._rasterImageWidth}GetRasterHeight(){return this._rasterImageHeight}HadError(){return this._hadError}}; } // ../lib/str/str.js { const C3=self.C3;C3.UTF8_BOM="\ufeff";const NUMERIC_CHARS=new Set("0123456789");C3.IsNumericChar=function(t){return NUMERIC_CHARS.has(t)};const WHITESPACE_CHARS=new Set(" \t\n\r …           ​\u2028\u2029   ");C3.IsWhitespaceChar=function(t){return WHITESPACE_CHARS.has(t)},C3.FilterWhitespace=function(t){return[...t].filter(t=>!C3.IsWhitespaceChar(t)).join("")},C3.IsStringAllWhitespace=function(t){for(const e of t)if(!C3.IsWhitespaceChar(e))return!1;return!0},C3.IsCharArrayAllWhitespace=function(t){for(const e of t)if(!C3.IsWhitespaceChar(e))return!1;return!0},C3.IsUnprintableChar=function(t){return 1===t.length&&t.charCodeAt(0)<32},C3.FilterUnprintableChars=function(t){return[...t].filter(t=>!C3.IsUnprintableChar(t)).join("")};let cjkPunctuationRegex=null;try{cjkPunctuationRegex=new RegExp("\\p{P}(?<=[\\u3000-\\u303F\\uFF00-\\uFFEF])","u")}catch(t){console.warn("Unable to detect CJK punctuation: ",t)}C3.IsCJKPunctuationChar=function(t){return!C3.IsWhitespaceChar(t)&&cjkPunctuationRegex&&cjkPunctuationRegex.test(t)};const NUMERIC_STRING_CHARS=new Set("0123456789.+-e");C3.IsStringNumber=function(t){if(!(t=t.trim()).length)return!1;let e=t.charAt(0);if("-"!==e&&!NUMERIC_CHARS.has(e))return!1;for(let e of t)if(!NUMERIC_STRING_CHARS.has(e))return!1;return!0},C3.RemoveTrailingDigits=function(t){let e=t.length;for(;e>0;){let n=t.charAt(e-1);if(!C3.IsNumericChar(n))break;--e}return t.substr(0,e)},C3.IncrementNumberAtEndOf=function(t){let e=C3.RemoveTrailingDigits(t),n=t.substr(e.length);return n=n?(parseInt(n,10)+1).toString():"2",e+n};const HTML_ENTITY_MAP=new Map([["&","&"],["<","<"],[">",">"],['"',"""],["'","'"]]);function lookupHtmlEntity(t){return HTML_ENTITY_MAP.get(t)}const HTML_ENTITY_REGEX=/[&<>"']/g;C3.EscapeHTML=function(t){return t.replace(HTML_ENTITY_REGEX,lookupHtmlEntity)},C3.EscapeJS=function(t){let e=C3.ReplaceAll(t,"\\","\\\\");return e=C3.ReplaceAll(e,'"','\\"'),e=C3.ReplaceAll(e,"\t","\\t"),e=C3.ReplaceAll(e,"\r",""),C3.ReplaceAll(e,"\n","\\n")},C3.EscapeXML=function(t){let e=C3.ReplaceAll(t,"&","&");return e=C3.ReplaceAll(e,"<","<"),e=C3.ReplaceAll(e,">",">"),C3.ReplaceAll(e,'"',""")};const ESCAPE_REGEX=/[-[\]{}()*+?.,\\^$|#\s]/g;C3.EscapeRegex=function(t){return t.replace(ESCAPE_REGEX,"\\$&")},C3.CountCharsInString=function(t,e){let n=0;for(const r of t)r===e&&++n;return n},C3.StringPosToLineNumber=function(t,e){let n=0,r=0;for(;n-1;)l.push(i),o=i+r;return l},C3.ReplaceAll=function(t,e,n){return t.replaceAll(e,()=>n)},C3.ReplaceAllCaseInsensitive=function(t,e,n){return t.replace(new RegExp(C3.EscapeRegex(e),"gi"),()=>n)},C3.SetElementContent=function(t,e){"string"==typeof e?t.textContent=e:e.isPlainText()?t.textContent=e.toString():(t.innerHTML=e.toHTML(),e instanceof C3.BBString&&e.attachLinkHandlers(t))},C3.StringLikeEquals=function(t,e){return t instanceof C3.HtmlString||t instanceof C3.BBString?t.equals(e):e instanceof C3.HtmlString||e instanceof C3.BBString?e.equals(t):t===e},C3.StringSubstitute=function(t,...e){let n=t;for(let r=0,o=e.length;r=0&&o>=0&&re?1:tr?1:n0&&(t-=24*e*3600,n.push(o(".days",null,e)))}if(e.hours){const e=Math.floor(t/3600);(e>0||n.length)&&(t-=3600*e,n.push(o(".hours",null,e)))}if(e.minutes){const r=Math.floor(t/60);(r>0||n.length||!e.seconds)&&(t-=60*r,n.push(o(".minutes",null,r)))}if(e.seconds){const e=Math.floor(t%60);n.push(o(".seconds",null,e))}const i=(e.approximate?r(".approx-prefix"):"")+n.join(r(".separator"));return C3.Lang.PopContext(),i},C3.ZeroPad=function(t,e){let n=t<0?"-":"",r=(t=Math.abs(t)).toString(),o=e-r.length;for(let t=0;tt.toUpperCase())},C3.CompareVersionStrings=function(t,e){let n=t.split(".").map(t=>t.trim()),r=e.split(".").map(t=>t.trim());C3.resizeArray(n,4,"0"),C3.resizeArray(r,4,"0"),n=n.map(t=>parseInt(t,10)),r=r.map(t=>parseInt(t,10));for(let t=0;t<4;++t){const e=n[t]-r[t];if(0!==e)return e<0?-1:1}return 0},C3.CreateGUID=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.floor(16*Math.random());return("x"===t?e:3&e|8).toString(16)})},C3.StringHammingDistance=function(t,e){if(t.length!==e.length)throw new Error("strings must be same length");let n=0;for(let r=0,o=t.length;re.length&&(n=t,t=e,e=n),s=Array(t.length+1),r=0;r<=t.length;r++)s[r]=r;for(r=1;r<=e.length;r++){for(i=r,o=1;o<=t.length;o++)l=e[r-1]===t[o-1]?s[o-1]:Math.min(s[o-1]+1,Math.min(i+1,s[o]+1)),s[o-1]=i,i=l;s[t.length]=i}return s[t.length]},C3.StringByteLengthAsUTF8=function(t){return(new TextEncoder).encode(t).length}; } // ../lib/str/bbstring.js { const C3=self.C3,assert=self.assert,BB_CODE_MAP=new Map([["b","strong"],["i","em"],["s","s"],["u","u"],["sub","sub"],["sup","sup"],["small","small"],["mark","mark"],["code","code"],["a1","a"],["a2","a"],["a3","a"],["a4","a"],["a5","a"],["a6","a"],["a7","a"],["a8","a"],["a9","a"],["tip1","abbr"],["tip2","abbr"],["tip3","abbr"],["tip4","abbr"],["tip5","abbr"],["tip6","abbr"],["tip7","abbr"],["tip8","abbr"],["tip9","abbr"],["bad",["span","bbCodeBad"]],["good",["span","bbCodeGood"]],["info",["span","bbCodeInfo"]],["h1",["span","bbCodeH1"]],["h2",["span","bbCodeH2"]],["h3",["span","bbCodeH3"]],["h4",["span","bbCodeH4"]],["item",["span","bbCodeItem"]]]),SELF_CLOSING_TAGS=new Set(["icon"]),BBREGEX=/\[(\/?)([a-zA-Z0-9]+)\]/g,CUSTOM_BBREGEX=/\[(\/?)([^\[\n]*?)\]/g;let linkActions=null,tipList=null,classIndex=0;function bbToHtmlReplacerFunc(t,s,i){const n=BB_CODE_MAP.get(i);if(!n)return"class"===i?s?"":``:t;if("string"==typeof n){if("a"===n&&0===linkActions.length||"abbr"===n&&0===tipList.length)return t;if("a"!==n||s){if("abbr"!==n||s)return"<"+s+n+">";{const t=parseInt(i.substring(3),10)-1;if(t<0||t>=tipList.length)throw new Error("invalid bbcode tip substitution");const s=tipList[t];let n="";if("string"==typeof s?n=s:"function"==typeof s&&(n=s()),"string"!=typeof n)throw new TypeError("invalid bbcode tip");return``}}{const t=parseInt(i.substring(1),10)-1;if(t<0||t>=linkActions.length)throw new Error("invalid bbcode link substitution");const s=linkActions[t];if("string"==typeof s)return``;if("function"==typeof s)return``;throw new TypeError("invalid bbcode link action")}}if(Array.isArray(n)){let t=n[0],i=n[1];return s?"":`<${t} class="${i}">`}}const LINEBREAK_REGEX=/\n/g;C3.BBString=class{constructor(t,s){if(this._bbstr=s&&s.noEscape?t:C3.EscapeHTML(t),this._htmlstr="",this._convertLineBreaks=!1,this._linkActions=[],this._tipList=[],s){if(this._convertLineBreaks=!!s.convertLineBreaks,s.links){if(s.links.length>9)throw new Error("too many links");this._linkActions=s.links}if(s.tips){if(s.tips.length>9)throw new Error("too many tips");this._tipList=s.tips}}this._hasAnyBBtags=this._bbstr.includes("["),this._needsLineBreakConversion=this._convertLineBreaks&&this._bbstr.includes("\n"),this._isPlain=!this._hasAnyBBtags&&!this._needsLineBreakConversion&&!this._bbstr.includes("&"),this._hasParsedFragments=!1,this._fragments=[]}toString(){return this._bbstr}valueOf(){return this._bbstr}isPlainText(){return this._isPlain}toPlainText(){return this._hasAnyBBtags?this._bbstr.replace(BBREGEX,""):this._bbstr}toHTML(){if(this._isPlain)return this._bbstr;if(!this._htmlstr&&this._bbstr){let t=this._bbstr;this._hasAnyBBtags&&(classIndex=0,linkActions=this._linkActions,tipList=this._tipList,t=t.replace(BBREGEX,bbToHtmlReplacerFunc),linkActions=null,tipList=null),this._needsLineBreakConversion&&(t=t.replace(LINEBREAK_REGEX,"
")),this._htmlstr=t}return this._htmlstr}attachLinkHandlers(t){if(this._linkActions.length)for(let s=0,i=this._linkActions.length;s0&&"\\"===s.charAt(r-1))continue;const a=e[0],o=e[1],l=e[2],b=s.substring(n,r);if(n=r+a.length,b&&t.push({text:b,styles:i.slice(0)}),l)if(o){const t=l.toLowerCase();for(let s=i.length-1;s>=0;--s)if(i[s].tag===t){i.splice(s,1);break}}else{let s=l,n=null;const e=l.indexOf("=");if(-1!==e?(s=l.substring(0,e).toLowerCase(),n=l.substring(e+1)):s=s.toLowerCase(),SELF_CLOSING_TAGS.has(s)){if("icon"!==s)throw new Error(`unknown self-closing tag ${s}`);t.push({icon:n,styles:i.slice(0)})}else i.push({tag:s,param:n})}}nt.icon?C3.New(C3.IconFragment,{icon:t.icon,styles:t.styles}):C3.New(C3.TextFragment,{chArr:C3.SplitGraphemes(t.text),styles:t.styles})),this._hasParsedFragments=!0,this._fragments}_ProcessBBCodeEscapeSequences(t){return t=C3.ReplaceAll(t,"\\[","["),C3.ReplaceAll(t,"\\\\","\\")}static StripTags(t){return C3.New(C3.BBString,t,{noEscape:!0}).toPlainText()}static StripAnyTags(t){return t.replace(CUSTOM_BBREGEX,"")}}; } // ../lib/str/textLayout/wordWrap.js { const C3=self.C3;function IsWordBreakWhiteSpace(t){return" "!==t&&" "!==t&&C3.IsWhitespaceChar(t)}const CJK_OPEN_PUNCTUATION=new Set("〈《「『【〔〖〘〚〝");function IsOpeningCJKPunctiationChar(t){return CJK_OPEN_PUNCTUATION.has(t)}function IsContinuingCJKPunctuationChar(t){return C3.IsCJKPunctuationChar(t)&&!IsOpeningCJKPunctiationChar(t)}function WordBreakTrimEnd(t){for(;t.length>0&&IsWordBreakWhiteSpace(t.at(-1));)t.pop()}function IsNewline(t){return"\n"===t||"\r\n"===t}class CurrentLineState{constructor(){this.fragments=[],this.width=0,this.height=0,this.fontBoundingBoxAscent=0,this.fontBoundingBoxDescent=0,this.topToAlphabeticDistance=0,this.isMeasured=!1}static FromSingleFragment(t,e,n,i,s,r){const h=new CurrentLineState;return h.fragments.push(t),h.width=e,h.height=n,h.fontBoundingBoxAscent=i,h.fontBoundingBoxDescent=s,h.topToAlphabeticDistance=r,h}Copy(t){this.fragments=t.fragments.map(t=>t._Clone()),this.width=t.width,this.height=t.height,this.fontBoundingBoxAscent=t.fontBoundingBoxAscent,this.fontBoundingBoxDescent=t.fontBoundingBoxDescent,this.topToAlphabeticDistance=t.topToAlphabeticDistance,this.isMeasured=t.isMeasured}Reset(){this.fragments=[],this.width=0,this.height=0,this.fontBoundingBoxAscent=0,this.fontBoundingBoxDescent=0,this.topToAlphabeticDistance=0,this.isMeasured=!1}SetMetrics(t,e){e||(this.width=t.width),this.height=t.height||0,this.fontBoundingBoxAscent=t.fontBoundingBoxAscent||0,this.fontBoundingBoxDescent=t.fontBoundingBoxDescent||0,this.topToAlphabeticDistance=t.topToAlphabeticDistance||0,this.isMeasured=!0}AddWord(t){const e=this.fragments.length?this.fragments.at(-1):null;let n=0;e&&e.IsText()&&t[0].IsText()&&t[0].GetStyles()===e.GetStyles()&&(e._Append(t[0].GetCharacterArray()),n=1);for(let e=t.length;n0&&e.push(n),e.push([s]),n=[];else for(const r of s.GetCharacterArray())if(IsNewline(r))n.length>0&&e.push(n),e.push([C3.New(C3.TextFragment,{chArr:["\n"],styles:t})]),n=[];else if(0===n.length)n.push(C3.New(C3.TextFragment,{chArr:[r],styles:t})),i=IsWordBreakWhiteSpace(r);else{const s=IsWordBreakWhiteSpace(r);if(s===i){const e=n.at(-1);e.GetStyles()===t?e._AppendChar(r):n.push(C3.New(C3.TextFragment,{chArr:[r],styles:t}))}else e.push(n),n=[C3.New(C3.TextFragment,{chArr:[r],styles:t})],i=s}}return n.length>0&&e.push(n),e}_TokeniseByCJK(t){const e=[];let n=[],i=!1;for(const s of t){const t=s.GetStyles();if(s.IsIcon())n.length>0&&e.push(n),e.push([s]),n=[];else for(const r of s.GetCharacterArray())if(IsNewline(r))n.length>0&&e.push(n),e.push([C3.New(C3.TextFragment,{chArr:["\n"],styles:t})]),n=[];else if(0===n.length)n.push(C3.New(C3.TextFragment,{chArr:[r],styles:t})),i=IsOpeningCJKPunctiationChar(r);else if(i||IsContinuingCJKPunctuationChar(r)){const e=n.at(-1);e.GetStyles()===t?e._AppendChar(r):n.push(C3.New(C3.TextFragment,{chArr:[r],styles:t})),i=IsOpeningCJKPunctiationChar(r)}else e.push(n),n=[C3.New(C3.TextFragment,{chArr:[r],styles:t})],i=IsOpeningCJKPunctiationChar(r)}return n.length>0&&e.push(n),e}_TokeniseByChar(t){const e=[];for(const n of t)if(n.IsText()){const t=n.GetCharacterArray();C3.appendArray(e,t.map(t=>[C3.New(C3.TextFragment,{chArr:[t],styles:n.GetStyles()})]))}else e.push([n]);return e}_MeasureLine(t,e){let n=0,i=0,s=0,r=0,h=0;for(const o of t){if(-1===o.GetWidth()){const t=e(o);o.SetHeight(t.height),o.SetFontBoundingBoxAscent(t.fontBoundingBoxAscent||0),o.SetFontBoundingBoxDescent(t.fontBoundingBoxDescent||0),o.SetTopToAlphabeticDistance(t.topToAlphabeticDistance||0),o.IsText()?o.SetWidth(t.width):o.IsIcon()&&o.CalculateWidthFromHeight(this._iconSet)}n+=o.GetWidth(),i=Math.max(i,o.GetHeight()),s=Math.max(s,o.GetFontBoundingBoxAscent()),r=Math.max(r,o.GetFontBoundingBoxDescent()),h=Math.max(h,o.GetTopToAlphabeticDistance())}return{width:n,height:i,fontBoundingBoxAscent:s,fontBoundingBoxDescent:r,topToAlphabeticDistance:h}}_ResetLineStates(){this._lastFitLineState.Reset(),this._tryLineState.Reset()}_AddLine(t){this._lines.push(new C3.WordWrap.Line(t)),this._ResetLineStates()}_IsWordNewLine(t){return 1===t.length&&t[0].IsText()&&1===t[0].GetLength()&&IsNewline(t[0].GetCharacterArray()[0])}_IsWordWhitespace(t){return t[0].IsText()&&C3.IsCharArrayAllWhitespace(t[0].GetCharacterArray())}_WrapText(t,e,n,i,s){let r=0;for(;r0){if(!this._tryLineState.isMeasured){const t=this._MeasureLine(this._tryLineState.fragments,e);this._tryLineState.SetMetrics(t)}this._AddLine(this._tryLineState)}this._TrimLinesTrailingWhitespace(e,s),this._ResetLineStates(),this._hitNewline=!1}_WrapText_Chunk(t,e,n,i,s){const r=this._lastFitLineState,h=this._tryLineState,o=t[e];if(this._IsWordNewLine(o)){if(!h.isMeasured){const t=n(C3.New(C3.TextFragment,{chArr:[" "],styles:o[0].GetStyles()}));h.SetMetrics(t,!0)}return this._AddLine(h),e+1}const a=this._WrapText_CollectChunk(t,e,s),c=this._MeasureLine(h.fragments,n);return h.SetMetrics(c),c.width>=i?this._WrapText_RetryChunk(t,e,n,i):(r.Copy(h),this._hitNewline&&this._AddLine(r),a+1)}_WrapText_CollectChunk(t,e,n){const i=this._tryLineState;this._hitNewline=!1;let s=e,r=0;for(let e=t.length;s=i){let n;return s.fragments.length>0?n=s:(n=r,++h,h0&&(s=i.at(-1),s.OffsetWidth(e),n.OffsetWidth(e))}}}Clear(){C3.clearArray(this._lines)}GetMaxLineWidth(){return this._lines.reduce((t,e)=>Math.max(t,e.GetWidth()),0)}GetTotalLineHeight(){return this._lines.reduce((t,e)=>t+e.GetHeight(),0)}}; } // ../lib/str/textLayout/line.js { const C3=self.C3;C3.WordWrap.Line=class{constructor(t){this._fragments=t.fragments,this._width=t.width,this._height=t.height,this._fontBoundingBoxAscent=t.fontBoundingBoxAscent,this._fontBoundingBoxDescent=t.fontBoundingBoxDescent,this._topToAlphabeticDistance=t.topToAlphabeticDistance,this._posX=0,this._posY=0}fragments(){return this._fragments.values()}*fragmentsReverse(){const t=this._fragments;for(let e=t.length-1;e>=0;--e)yield t[e]}_GetFragmentsArray(){return this._fragments}OffsetWidth(t){this._width+=t}GetWidth(){return this._width}GetHeight(){return this._height}GetFoundBoundingBoxAscent(){return this._fontBoundingBoxAscent}GetFontBoundingBoxDescent(){return this._fontBoundingBoxDescent}GetTopToAlphabeticDistance(){return this._topToAlphabeticDistance}SetPosX(t){this._posX=t}GetPosX(){return this._posX}SetPosY(t){this._posY=t}GetPosY(){return this._posY}}; } // ../lib/str/textLayout/fragmentBase.js { const C3=self.C3;C3.FragmentBase=class{constructor(t){this._styles=t.styles||[],this._width=t.width||-1,this._height=t.height||-1,this._fontBoundingBoxAscent=t.fontBoundingBoxAscent||-1,this._fontBoundingBoxDescent=t.fontBoundingBoxDescent||-1,this._topToAlphabeticDistance=t.topToAlphabeticDistance||-1,this._posX=0,this._posY=0}IsText(){return!1}IsIcon(){return!1}GetStyles(){return this._styles}GetStyleTag(t){const e=this._styles;for(let s=e.length-1;s>=0;--s){const n=e[s];if(n.tag===t)return n}return null}HasStyleTag(t){return!!this.GetStyleTag(t)}GetStyleMap(){const t=new Map;for(const e of this._styles)t.set(e.tag,e.param);return t}OffsetWidth(t){this._width+=t}SetWidth(t){this._width=t}GetWidth(){return this._width}SetHeight(t){this._height=t}GetHeight(){return this._height}SetFontBoundingBoxAscent(t){this._fontBoundingBoxAscent=t}GetFontBoundingBoxAscent(){return this._fontBoundingBoxAscent}SetFontBoundingBoxDescent(t){this._fontBoundingBoxDescent=t}GetFontBoundingBoxDescent(){return this._fontBoundingBoxDescent}SetTopToAlphabeticDistance(t){this._topToAlphabeticDistance=t}GetTopToAlphabeticDistance(){return this._topToAlphabeticDistance}SetPosX(t){this._posX=t}GetPosX(){return this._posX}SetPosY(t){this._posY=t}GetPosY(){return this._posY}}; } // ../lib/str/textLayout/textFragment.js { const C3=self.C3;C3.TextFragment=class extends C3.FragmentBase{constructor(t){super(t),this._chArr=t.chArr}IsText(){return!0}_Append(t){C3.appendArray(this._chArr,t),this._width=-1,this._height=-1,this._fontBoundingBoxAscent=-1,this._fontBoundingBoxDescent=-1,this._topToAlphabeticDistance=-1}_AppendChar(t){this._chArr.push(t)}_Clone(){return C3.New(C3.TextFragment,{chArr:this._chArr.slice(0),styles:this._styles,width:this._width,height:this._height,fontBoundingBoxAscent:this._fontBoundingBoxAscent,fontBoundingBoxDescent:this._fontBoundingBoxDescent,topToAlphabeticDistance:this._topToAlphabeticDistance})}GetCharacterArray(){return this._chArr}SetCharacterArray(t){this._chArr=t}GetLength(){return this._chArr.length}IsEmpty(){return 0===this._chArr.length}HasNewLine(){return this._chArr.includes("\n")}}; } // ../lib/str/textLayout/iconFragment.js { const C3=self.C3;C3.IconFragment=class extends C3.FragmentBase{constructor(t){super(t),this._icon=t.icon}IsIcon(){return!0}GetIconParameter(){return this._icon}_Clone(){return C3.New(C3.IconFragment,{icon:this._icon,styles:this._styles,width:this._width,height:this._height,fontBoundingBoxAscent:this._fontBoundingBoxAscent,fontBoundingBoxDescent:this._fontBoundingBoxDescent,topToAlphabeticDistance:this._topToAlphabeticDistance})}GetTextIcon(t){if(!t)return null;let e=Number(this._icon);return String(e)===this._icon?(e=Math.floor(e),t.GetTextIconByIndex(e)):t.GetTextIconByTag(this._icon)}CalculateWidthFromHeight(t){const e=this.GetTextIcon(t);this._width=e?this._height*e.GetWidth()/e.GetHeight():0}GetDrawable(t){const e=this.GetTextIcon(t);return e?e.GetDrawable():null}GetLength(){return 1}}; } // ../lib/str/textLayout/textIconManager.js { const C3=self.C3;C3.TextIconManager=class{constructor(t){this._iconSets=new Map,this._getIconSetMetaCallback=t.getIconSetMeta,this._getIconSetContentCallback=t.getIconSetContent}Release(){for(const t of this._iconSets.values())t.Release();this._iconSets.clear()}GetIconSet(t){let e=this._iconSets.get(t);if(e)return e;const n=this._getIconSetMetaCallback(t);return e=C3.New(C3.TextIconSet,this,{source:t,iconMeta:n}),this._iconSets.set(t,e),e}HasIconSet(t){return this._iconSets.has(t)}DeleteIconSet(t){const e=this._iconSets.get(t);e&&e.Release(),this._iconSets.delete(t)}async _GetIconSetContent(t){return await this._getIconSetContentCallback(t)}}; } // ../lib/str/textLayout/textIconSet.js { const C3=self.C3;C3.TextIconSet=class{constructor(t,s){this._textIconManager=t,this._source=s.source,this._iconsArray=[],this._iconsByTag=new Map,this._hasStartedLoad=!1,this._isLoading=!1,this._loadPromise=null;const o=s.iconMeta.icons;for(let t=0,s=o.length;t=this._iconsArray.length?null:this._iconsArray[t]}GetTextIconByTag(t){return this._iconsByTag.get(t.toLowerCase())||null}}; } // ../lib/str/textLayout/textIcon.js { const C3=self.C3;C3.TextIcon=class{constructor(t,e){this._textIconSet=t,this._source=e.source||null,this._index=e.index,this._tag=e.tag,this._width=e.width,this._height=e.height,this._drawable=null}Release(){this._width=0,this._height=0,this._textIconSet=null}GetSource(){return this._source}GetWidth(){return this._width}GetHeight(){return this._height}_SetDrawable(t){this._drawable=t}GetDrawable(){return this._drawable}}; } // ../lib/gfx/gfx.js { const C3=self.C3,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,mat4=glMatrix.mat4,tempVec3a=vec3.create(),tempVec3b=vec3.create(),tempVec3c=vec3.create(),tempVec4=vec4.create(),tempMat4=mat4.create(),neartl=vec3.create(),neartr=vec3.create(),nearbl=vec3.create(),nearbr=vec3.create(),fartl=vec3.create(),fartr=vec3.create(),farbl=vec3.create(),farbr=vec3.create(),unitViewport=vec4.fromValues(0,0,1,1);C3.Gfx={Project(t,e,n,r,s,i,o){const c=r[0]*t+r[4]*e+r[8]*n+r[12],a=r[1]*t+r[5]*e+r[9]*n+r[13],P=r[2]*t+r[6]*e+r[10]*n+r[14],h=r[3]*t+r[7]*e+r[11]*n+r[15];let l=s[0]*c+s[4]*a+s[8]*P+s[12]*h,f=s[1]*c+s[5]*a+s[9]*P+s[13]*h,m=s[2]*c+s[6]*a+s[10]*P+s[14]*h,p=s[3]*c+s[7]*a+s[11]*P+s[15]*h;return 0!==p&&(p=1/p,l*=p,f*=p,m*=p,o[0]=(.5*l+.5)*i[2]+i[0],o[1]=(.5*f+.5)*i[3]+i[1],o[2]=.5*(1+m),!0)},Unproject(t,e,n,r,s,i,o){const c=tempMat4,a=tempVec4;return mat4.multiply(c,s,r),null!==mat4.invert(c,c)&&(vec4.set(a,(t-i[0])/i[2]*2-1,(e-i[1])/i[3]*2-1,2*n-1,1),vec4.transformMat4(a,a,c),0!==a[3]&&(a[3]=1/a[3],o[0]=a[0]*a[3],o[1]=a[1]*a[3],o[2]=a[2]*a[3],!0))},UnprojectToWorldRay:(t,e,n,r,s,i,o)=>!!C3.Gfx.Unproject(t,e,0,n,r,s,i)&&C3.Gfx.Unproject(t,e,1,n,r,s,o),UnprojectScreenToPlane(t,e,n,r,s,i,o){const c=tempVec3a,a=tempVec3b;if(!C3.Gfx.UnprojectToWorldRay(t,e,r,s,i,c,a))return!1;const P=n.segmentIntersection(c[0],c[1],c[2],a[0],a[1],a[2]);return null!==P&&(vec3.set(o,P[0],P[1],P[2]),!0)},UnprojectScreenToXYPlane:(t,e,n,r,s,i,o)=>(tempPlane.set(0,0,1,n),C3.Gfx.UnprojectScreenToPlane(t,e,tempPlane,r,s,i,o)),UnprojectScreenToYZPlane:(t,e,n,r,s,i,o)=>(tempPlane.set(1,0,0,n),C3.Gfx.UnprojectScreenToPlane(t,e,tempPlane,r,s,i,o)),UnprojectScreenToXZPlane:(t,e,n,r,s,i,o)=>(tempPlane.set(0,1,0,n),C3.Gfx.UnprojectScreenToPlane(t,e,tempPlane,r,s,i,o))};class Plane{#t=NaN;#e=NaN;#n=NaN;#r=NaN;#s=NaN;#i=NaN;#o=NaN;constructor(){}setFromPoints(t,e,n){const r=tempVec3c;vec3.subtract(tempVec3a,n,e),vec3.subtract(tempVec3b,t,e),vec3.cross(r,tempVec3a,tempVec3b),vec3.normalize(r,r),this.set(r[0],r[1],r[2],vec3.dot(t,r))}set(t,e,n,r){this.#t=t,this.#e=e,this.#n=n,this.#r=r,this.#s=t>0?1:0,this.#i=e>0?1:0,this.#o=n>0?1:0}isPointInFront(t,e,n){return this.#t*t+this.#e*e+this.#n*n>=this.#r}segmentIntersection(t,e,n,r,s,i){const o=this.#t*t+this.#e*e+this.#n*n-this.#r,c=this.#t*r+this.#e*s+this.#n*i-this.#r;if(o*c>0)return null;const a=c-o,P=r-t,h=s-e,l=i-n;if(a*a<1e-12*(P*P+h*h+l*l))return null;const f=-o/a;return[t+f*P,e+f*h,n+f*l]}checkAABB3DIntersection(t){const e=t.getLeft(),n=t.getTop(),r=t.getBack(),s=t.getRight(),i=t.getBottom(),o=t.getFront(),c=this.#t,a=this.#e,P=this.#n,h=this.#r,l=this.#s,f=this.#i,m=this.#o,p=1-l,I=1-f,u=1-m;if(c*e*l+c*s*p+a*n*f+a*i*I+P*r*m+P*o*u>=h)return 1;return c*s*l+c*e*p+a*i*f+a*n*I+P*o*m+P*r*u<=h?-1:0}}const tempPlane=new Plane;C3.Gfx.ViewFrustum=class{#c=new Plane;#a=new Plane;#P=new Plane;#h=new Plane;#l=new Plane;#f=new Plane;constructor(){}CalculatePlanes(t,e,n=0,r=1,s=1,i=0){const o=unitViewport;C3.Gfx.Unproject(n,r,0,t,e,o,neartl),C3.Gfx.Unproject(s,r,0,t,e,o,neartr),C3.Gfx.Unproject(n,i,0,t,e,o,nearbl),C3.Gfx.Unproject(s,i,0,t,e,o,nearbr),C3.Gfx.Unproject(n,r,1,t,e,o,fartl),C3.Gfx.Unproject(s,r,1,t,e,o,fartr),C3.Gfx.Unproject(n,i,1,t,e,o,farbl),C3.Gfx.Unproject(s,i,1,t,e,o,farbr),this.#c.setFromPoints(nearbl,neartl,fartl),this.#a.setFromPoints(neartl,neartr,fartr),this.#P.setFromPoints(neartr,nearbr,farbr),this.#h.setFromPoints(nearbr,nearbl,farbl),this.#f.setFromPoints(farbl,fartl,fartr),this.#l.setFromPoints(nearbr,neartr,neartl)}ContainsAABB(t){return this.#m(t,0)}FullyContainsAABB3D(t){return this.#m(t,1)}#m(t,e){return this.#c.checkAABB3DIntersection(t)>=e&&this.#a.checkAABB3DIntersection(t)>=e&&this.#P.checkAABB3DIntersection(t)>=e&&this.#h.checkAABB3DIntersection(t)>=e&&this.#l.checkAABB3DIntersection(t)>=e&&this.#f.checkAABB3DIntersection(t)>=e}ContainsPoint(t,e,n){return this.#c.isPointInFront(t,e,n)&&this.#a.isPointInFront(t,e,n)&&this.#P.isPointInFront(t,e,n)&&this.#h.isPointInFront(t,e,n)&&this.#l.isPointInFront(t,e,n)&&this.#f.isPointInFront(t,e,n)}#p(t,e,n,r){return(t===this.#c||this.#c.isPointInFront(e,n,r))&&(t===this.#a||this.#a.isPointInFront(e,n,r))&&(t===this.#P||this.#P.isPointInFront(e,n,r))&&(t===this.#h||this.#h.isPointInFront(e,n,r))&&(t===this.#l||this.#l.isPointInFront(e,n,r))&&(t===this.#f||this.#f.isPointInFront(e,n,r))}IsBehindNearPlane(t,e,n){return!this.#l.isPointInFront(t,e,n)}#I(t,e,n,r,s,i,o){const c=t.segmentIntersection(e,n,r,s,i,o);return c&&this.#p(t,c[0],c[1],c[2])?c:null}FirstSegmentIntersection(t,e,n,r,s,i){let o=this.#I(this.#c,t,e,n,r,s,i);return o||(o=this.#I(this.#a,t,e,n,r,s,i),o||(o=this.#I(this.#P,t,e,n,r,s,i),o||(o=this.#I(this.#h,t,e,n,r,s,i),o||(o=this.#I(this.#l,t,e,n,r,s,i),o||this.#I(this.#f,t,e,n,r,s,i)))))}FirstTwoSegmentIntersections(t,e,n,r,s,i){let o=this.#I(this.#c,t,e,n,r,s,i),c=this.#I(this.#a,t,e,n,r,s,i);if(c){if(o)return[o,c];o=c}if(c=this.#I(this.#P,t,e,n,r,s,i),c){if(o)return[o,c];o=c}if(c=this.#I(this.#h,t,e,n,r,s,i),c){if(o)return[o,c];o=c}if(c=this.#I(this.#l,t,e,n,r,s,i),c){if(o)return[o,c];o=c}if(c=this.#I(this.#f,t,e,n,r,s,i),c){if(o)return[o,c];o=c}return[o,c]}}; } // ../lib/gfx/rendererBase.js { const C3=self.C3,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,mat4=glMatrix.mat4,tempMat4=mat4.create(),tmpVec3a=vec3.fromValues(0,0,0),tmpVec3b=vec3.fromValues(0,0,0),tmpVec3c=vec3.fromValues(0,0,0),defaultUpVector=vec3.fromValues(0,1,0),tmpVec4=vec4.fromValues(0,0,0,0),tmpQuad=new C3.Quad2D,tmpRect=new C3.Rect,defaultTexCoordsQuad=new C3.Quad2D(0,0,1,0,1,1,0,1),DEFAULT_RENDERERBASE_OPTS={nearZ:1,farZ:1e4},matWebGLtoWebGPU=mat4.fromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1),SAMPLING_MODES=["auto","nearest","bilinear","trilinear"],SAMPLING_MODE_TO_NUMBER=new Map;for(let e=0,t=SAMPLING_MODES.length;e=SAMPLING_MODES.length)throw new RangeError("invalid sampling number");return SAMPLING_MODES[e]}static IsValidSamplingMode(e){return SAMPLING_MODE_TO_NUMBER.has(e)}SetBaseZ(e){this._baseZ=e}GetBaseZ(){return this._baseZ}SetCurrentZ(e){this._currentZ=e,this._currentStateGroup=null}GetCurrentZ(){return this._currentZ}Line(e,t,i,a){const s=C3.angleTo(e,t,i,a),r=Math.sin(s),l=Math.cos(s),n=.5*this._lineWidth,h=r*n,o=l*n,p=this._lineCap;2===p?this.LinePreCalc_LineCap2(e,t,0,i,a,0,h,o):1===p?this.LinePreCalc_LineCap1(e,t,0,i,a,0,h,o):this.LinePreCalc_LineCap0(e,t,0,i,a,0,h,o)}Line3D(e,t,i,a,s,r){const l=C3.angleTo(e,t,a,s),n=Math.sin(l),h=Math.cos(l),o=.5*this._lineWidth,p=n*o,_=h*o,c=this._lineCap;2===c?this.LinePreCalc_LineCap2(e,t,i,a,s,r,p,_):1===c?this.LinePreCalc_LineCap1(e,t,i,a,s,r,p,_):this.LinePreCalc_LineCap0(e,t,i,a,s,r,p,_)}LinePreCalc_LineCap2(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h-n,p=t+h-l,_=a+h+n,c=s+h+l,u=2*n,d=2*l,C=o+l,m=p-n,L=o-l+u,S=p+n+d,g=_+l,f=c-n,P=_-l-u,M=c+n-d;this.Quad3D2(C,m,i,g,f,r,P,M,r,L,S,i,defaultTexCoordsQuad)}LinePreCalc_LineCap1(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h-n,p=t+h-l,_=a+h+n,c=s+h+l,u=o+l,d=p-n,C=o-l,m=p+n,L=_+l,S=c-n,g=_-l,f=c+n;this.Quad3D2(u,d,i,L,S,r,g,f,r,C,m,i,defaultTexCoordsQuad)}LinePreCalc_LineCap0(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h,p=t+h,_=a+h,c=s+h,u=o+l,d=p-n,C=o-l,m=p+n,L=_+l,S=c-n,g=_-l,f=c+n;this.Quad3D2(u,d,i,L,S,r,g,f,r,C,m,i,defaultTexCoordsQuad)}TexturedLine(e,t,i,a,s,r){const l=C3.angleTo(e,t,i,a),n=Math.sin(l),h=Math.cos(l),o=.5*this._lineWidth,p=n*o,_=h*o,c=this._lineCap;2===c?this.TexturedLinePreCalc_LineCap2(e,t,i,a,p,_,s,r):1===c?this.TexturedLinePreCalc_LineCap1(e,t,i,a,p,_,s,r):this.TexturedLinePreCalc_LineCap0(e,t,i,a,p,_,s,r)}TexturedLinePreCalc_LineCap2(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h-r,p=t+h-s,_=i+h+r,c=a+h+s,u=2*r,d=2*s,C=o+s,m=p-r,L=o-s+u,S=p+r+d,g=_+s,f=c-r,P=_-s-u,M=c+r-d;tmpQuad.set(C,m,g,f,P,M,L,S),tmpRect.set(l,0,n,0),this.Quad3(tmpQuad,tmpRect)}TexturedLinePreCalc_LineCap1(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h-r,p=t+h-s,_=i+h+r,c=a+h+s,u=o+s,d=p-r,C=o-s,m=p+r,L=_+s,S=c-r,g=_-s,f=c+r;tmpQuad.set(u,d,L,S,g,f,C,m),tmpRect.set(l,0,n,0),this.Quad3(tmpQuad,tmpRect)}TexturedLinePreCalc_LineCap0(e,t,i,a,s,r,l,n){const h=this._lineOffset,o=e+h,p=t+h,_=i+h,c=a+h,u=o+s,d=p-r,C=o-s,m=p+r,L=_+s,S=c-r,g=_-s,f=c+r;tmpQuad.set(u,d,L,S,g,f,C,m),tmpRect.set(l,0,n,0),this.Quad3(tmpQuad,tmpRect)}LineRect(e,t,i,a){const s=.5*this._lineWidth,r=this._lineCap;2===r?this._LineRectPreCalc_LineCap2(e,t,i,a,s):1===r?this._LineRectPreCalc_LineCap1(e,t,i,a,s):this._LineRectPreCalc_LineCap0(e,t,i,a,s)}_LineRectPreCalc_LineCap2(e,t,i,a,s){this.LinePreCalc_LineCap2(e,t,0,i,t,0,0,s),this.LinePreCalc_LineCap2(i,t,0,i,a,0,s,0),this.LinePreCalc_LineCap2(i,a,0,e,a,0,0,-s),this.LinePreCalc_LineCap2(e,a,0,e,t,0,-s,0)}_LineRectPreCalc_LineCap1(e,t,i,a,s){this.LinePreCalc_LineCap1(e,t,0,i,t,0,0,s),this.LinePreCalc_LineCap1(i,t,0,i,a,0,s,0),this.LinePreCalc_LineCap1(i,a,0,e,a,0,0,-s),this.LinePreCalc_LineCap1(e,a,0,e,t,0,-s,0)}_LineRectPreCalc_LineCap0(e,t,i,a,s){this.LinePreCalc_LineCap0(e,t,0,i,t,0,0,s),this.LinePreCalc_LineCap0(i,t,0,i,a,0,s,0),this.LinePreCalc_LineCap0(i,a,0,e,a,0,0,-s),this.LinePreCalc_LineCap0(e,a,0,e,t,0,-s,0)}LineRect2(e){this.LineRect(e.getLeft(),e.getTop(),e.getRight(),e.getBottom())}LineQuad(e){const t=C3.angleTo(e.getTlx(),e.getTly(),e.getTrx(),e.getTry()),i=Math.sin(t),a=Math.cos(t),s=.5*this._lineWidth,r=i*s,l=a*s,n=this._lineCap;2===n?this._LineQuadPreCalc_LineCap2(e,r,l):1===n?this._LineQuadPreCalc_LineCap1(e,r,l):this._LineQuadPreCalc_LineCap0(e,r,l)}_LineQuadPreCalc_LineCap2(e,t,i){this.LinePreCalc_LineCap2(e.getTlx(),e.getTly(),0,e.getTrx(),e.getTry(),0,t,i),this.LinePreCalc_LineCap2(e.getTrx(),e.getTry(),0,e.getBrx(),e.getBry(),0,i,-t),this.LinePreCalc_LineCap2(e.getBrx(),e.getBry(),0,e.getBlx(),e.getBly(),0,-t,-i),this.LinePreCalc_LineCap2(e.getBlx(),e.getBly(),0,e.getTlx(),e.getTly(),0,-i,t)}_LineQuadPreCalc_LineCap1(e,t,i){this.LinePreCalc_LineCap1(e.getTlx(),e.getTly(),0,e.getTrx(),e.getTry(),0,t,i),this.LinePreCalc_LineCap1(e.getTrx(),e.getTry(),0,e.getBrx(),e.getBry(),0,i,-t),this.LinePreCalc_LineCap1(e.getBrx(),e.getBry(),0,e.getBlx(),e.getBly(),0,-t,-i),this.LinePreCalc_LineCap1(e.getBlx(),e.getBly(),0,e.getTlx(),e.getTly(),0,-i,t)}_LineQuadPreCalc_LineCap0(e,t,i){this.LinePreCalc_LineCap0(e.getTlx(),e.getTly(),0,e.getTrx(),e.getTry(),0,t,i),this.LinePreCalc_LineCap0(e.getTrx(),e.getTry(),0,e.getBrx(),e.getBry(),0,i,-t),this.LinePreCalc_LineCap0(e.getBrx(),e.getBry(),0,e.getBlx(),e.getBly(),0,-t,-i),this.LinePreCalc_LineCap0(e.getBlx(),e.getBly(),0,e.getTlx(),e.getTly(),0,-i,t)}SetLineWidth(e){this._lineWidth=e,this._lineWidthStack[this._lineWidthStack.length-1]=e}GetLineWidth(){return this._lineWidth}PushLineWidth(e){if(this._lineWidthStack.length>=100)throw new Error("pushed too many line widths - check push/pop pairs");this._lineWidthStack.push(e),this._lineWidth=e}PopLineWidth(){if(this._lineWidthStack.length<=1)throw new Error("cannot pop last line width - check push/pop pairs");this._lineWidthStack.pop(),this._lineWidth=this._lineWidthStack.at(-1)}SetLineCapButt(){this._lineCap=0,this._lineCapStack[this._lineCapStack.length-1]=0}SetLineCapSquare(){this._lineCap=1,this._lineCapStack[this._lineCapStack.length-1]=0}SetLineCapZag(){this._lineCap=2,this._lineCapStack[this._lineCapStack.length-1]=0}PushLineCap(e){if("butt"===e)this.PushLineCapButt();else if("square"===e)this.PushLineCapSquare();else{if("zag"!==e)throw new Error("invalid line cap");this.PushLineCapZag()}}PushLineCapButt(){if(this._lineCapStack.length>=100)throw new Error("pushed too many line caps - check push/pop pairs");this._lineCapStack.push(0),this._lineCap=0}PushLineCapSquare(){if(this._lineCapStack.length>=100)throw new Error("pushed too many line caps - check push/pop pairs");this._lineCapStack.push(1),this._lineCap=1}PushLineCapZag(){if(this._lineCapStack.length>=100)throw new Error("pushed too many line caps - check push/pop pairs");this._lineCapStack.push(2),this._lineCap=2}PopLineCap(){if(this._lineCapStack.length<=1)throw new Error("cannot pop last line cap - check push/pop pairs");this._lineCapStack.pop(),this._lineCap=this._lineCapStack.at(-1)}SetLineOffset(e){this._lineOffset=e,this._lineOffsetStack[this._lineOffsetStack.length-1]=e}GetLineOffset(){return this._lineOffset}PushLineOffset(e){if(this._lineOffsetStack.length>=100)throw new Error("pushed too many line offsets - check push/pop pairs");this._lineOffsetStack.push(e),this._lineOffset=e}PopLineOffset(){if(this._lineOffsetStack.length<=1)throw new Error("cannot pop last line offset - check push/pop pairs");this._lineOffsetStack.pop(),this._lineOffset=this._lineOffsetStack.at(-1)}IsColorDataF16(){return!1}ResetCullState(){this.SetCullFaceMode(0),this.SetFrontFaceWinding(0)}ConvexPoly(e){const t=e.length/2;if(t<3)throw new Error("need at least 3 points");const i=t-2,a=i-1,s=e[0],r=e[1];for(let t=0;t0)throw new Error("releasing state group still in use");this._renderer=null,this._shaderProgram=null,this._shaderProgramName=""}Apply(){const e=this._renderer;e.SetProgram(this._shaderProgram),e.SetBlendMode(this._blendMode),e.SetColor(this._color),e.SetCurrentZ(this._zElevation),e.SetCullFaceMode(this._cullFaceMode),e.SetFrontFaceWinding(this._frontFaceWinding),e._SetCurrentStateGroup(this)}GetKey(){return C3.Gfx.StateGroup.MakeKey(this._shaderProgramName,this._blendMode,this._color,this._zElevation,this._cullFaceMode,this._frontFaceWinding)}AddRef(){++this._refCount}DecRef(){--this._refCount}_GetRefCount(){return this._refCount}OnContextLost(){this._shaderProgram=null}OnContextRestored(e){if(this._shaderProgram=e.GetShaderProgramByName(this._shaderProgramName),!this._shaderProgram)throw new Error("failed to restore shader program")}static MakeKey(e,r,t,s,o,a){return("string"==typeof e?e:e.GetName())+","+r+","+t.getR()+","+t.getG()+","+t.getB()+","+t.getA()+","+s+","+o+","+a}}; } // ../lib/gfx/deformMesh.js { const C3=globalThis.C3,assert=globalThis.assert,MAX_VERTICES=65535;function interpolateQuad(t,e,s){const i=s.getTlx(),h=s.getTly(),o=s.getTrx()-i,n=s.getTry()-h;return[i+o*t+(s.getBlx()-i)*e,h+n*t+(s.getBly()-h)*e]}C3.Gfx.DeformMeshPoint=class{#t;#e=0;#s=0;#i=NaN;#h=NaN;#o=NaN;#n=NaN;#a=NaN;constructor(t,e,s){this.#t=t,this.#e=e,this.#s=s,this.#i=0,this.#h=0,this.#o=0,this.#n=0,this.#a=0}_Init(t,e,s,i){this.#i=t,this.#h=e,this.#n=s,this.#a=i}CopyFrom(t,e=1,s=1){this.#i=t.GetX()*e,this.#h=t.GetY()*s,this.#o=t.GetZ(),this.#n=t.GetU()*e,this.#a=t.GetV()*s}GetX(){return this.#i}SetX(t){this.#i!==t&&(this.#i=t,this.#t._SetPointsChanged())}GetY(){return this.#h}SetY(t){this.#h!==t&&(this.#h=t,this.#t._SetPointsChanged())}GetZ(){return this.#o}SetZ(t){this.#o!==t&&(this.#o=t,this.#t._SetPointsChanged())}GetU(){return this.#n}SetU(t){this.#n=t}GetV(){return this.#a}SetV(t){this.#a=t}_Interpolate_TexRect(t,e,s){[this.#i,this.#h]=interpolateQuad(t.GetX(),t.GetY(),e),this.#o=t.GetZ(),this.#n=C3.lerp(s.getLeft(),s.getRight(),t.GetU()),this.#a=C3.lerp(s.getTop(),s.getBottom(),t.GetV())}_Interpolate_TexQuad(t,e,s){[this.#i,this.#h]=interpolateQuad(t.GetX(),t.GetY(),e),this.#o=t.GetZ(),[this.#n,this.#a]=interpolateQuad(t.GetU(),t.GetV(),s)}SaveToJson(){return{"x":this.GetX(),"y":this.GetY(),"z":this.GetZ(),"u":this.GetU(),"v":this.GetV()}}LoadFromJson(t){this.SetX(t["x"]),this.SetY(t["y"]),t.hasOwnProperty("z")&&this.SetZ(t["z"]),this.SetU(t["u"]),this.SetV(t["v"])}GetMesh(){return this.#t}GetColumn(){return this.#e}GetRow(){return this.#s}},C3.Gfx.DeformMesh=class{#r=null;#l=0;#G=0;#m=[];#u=0;#c=0;#M=0;#C=0;#f=0;#d=0;#p=!1;#g=null;#y=!0;#x=0;#z=new C3.Color(0,0,0,0);constructor(t,e,s){if(t<2||e<2)throw new Error("invalid mesh size");this.#l=t,this.#G=e,this.#r=s||null;const i=t-1,h=e-1;for(let s=0;s0}GetMeshPointAt(t,e){return t=Math.floor(t),e=Math.floor(e),t<0||t>=this.#l||e<0||e>=this.#G?null:this.#m[e][t]}CalculateTransformedMesh(t,e,s){const i=s instanceof C3.Rect;if(t.GetHSize()!==this.GetHSize()||t.GetVSize()!==this.GetVSize())throw new Error("source mesh wrong size");const h=t._GetPoints(),o=this._GetPoints();for(let t=0,n=o.length;t[t,e,s]);const s=this.#m;let i=s[0];for(let h=1,o=s.length;h{m=C3.clamp(C3.lerp(m,f,p),0,1),u=C3.clamp(C3.lerp(u,d,p),0,1),h.push(m,u)};for(let t=0,x=i.length;t1e6)throw new Error("Too many mesh poly points");const t=c*a,i=M*r,o=(c+1)*a,n=(M+1)*r;if(C=C3.isPointInTriangleInclusive(m,u,t,i,o,i,o,n),0!==g&&(p=C3.rayIntersectExtended(m,u,f,d,t,i,o,n,-.001),p>=0&&p<=s))y(),C=!C,g=0;else if(M>0&&2!==g&&(p=C3.rayIntersectExtended(m,u,f,d,t,i,o,i,e),p>=0&&p<=s))y(),M--,C=!1,g=4;else if(c=0&&p<=s))y(),c++,C=!1,g=1;else if(c>0&&1!==g&&(p=C3.rayIntersectExtended(m,u,f,d,t,i,t,n,e),p>=0&&p<=s))y(),c--,C=!0,g=3;else{if(!(M=0&&p<=s)))break;y(),M++,C=!0,g=2}}}return C3.New(C3.CollisionPoly,h)}TransformCollisionPoly(t,e){const s=this.#w(t);this.#T(s),e.setPoints(s)}#w(t){const e=[],s=t.pointsArr();for(let t=0,i=s.length;t.001||0==u&&0===c)&&e.push(i,h),i=G,h=m,o=u,n=c}e.length>=6&&e.lengtht.map(t=>t.SaveToJson()))}}LoadFromJson(t){const e=this.GetHSize(),s=this.GetVSize();if(t["cols"]!==e||t["rows"]!==s)throw new Error("mesh data wrong size");const i=t["points"];for(let t=0;tthis.#i)throw new RangeError(`invalid data range (${e} to ${t} outside allowed range 0 to ${this.#i})`);this.#e?(this.#t=Math.min(e,this.#t),this.#n=Math.max(t,this.#n)):(this.#e=!0,this.#t=e,this.#n=t)}GetPendingChange(){return this.#e?{start:this.#t,end:this.#n}:null}Reset(){this.#e=!1}}C3.Gfx.MeshData=class{positions=null;texCoords=null;texIndices=null;colors=null;indices=null;#s;#a="";#r=0;#d=0;#o=!1;#h=0;#l=new PendingBufferUpdate;#u=new PendingBufferUpdate;#x=null;#C=new PendingBufferUpdate;#c=new PendingBufferUpdate;constructor(e,t,n,i){if(t=Math.floor(t),n=Math.floor(n),t<0||n<0)throw new Error("invalid count");this.#s=e,this.#r=t,this.#d=n,i=Object.assign({},DEFAULT_MESHDATA_OPTS,i),this.#o=i.texIndices,this.#a=i.debugLabel,this.#l.SetMaxSize(t),this.#u.SetMaxSize(t),this.#C.SetMaxSize(t),this.#c.SetMaxSize(n),this.#o&&(this.#x=new PendingBufferUpdate,this.#x.SetMaxSize(t))}Release(){this.#s._ReleaseMeshData(this),this.ReleaseGPUResources(),this.positions=null,this.texCoords=null,this.texIndices=null,this.colors=null,this.indices=null,this.#s=null}GetRenderer(){return this.#s}GetDebugLabel(){return this.#a}CreateGPUResources(){if(!this.positions)if(this.positions=new Float32Array(3*this.#r),this.texCoords=new Float32Array(2*this.#r),this.#o&&(this.texIndices=new Uint32Array(this.#r)),this.#s.IsColorDataF16()?this.colors=new globalThis["Float16Array"](4*this.#r):this.colors=new Float32Array(4*this.#r),this.IsIndexTypeUint16()){const e=4*Math.ceil(this.#d/2),t=new ArrayBuffer(e);this.indices=new Uint16Array(t,0,this.#d)}else this.indices=new Uint32Array(this.#d)}WriteGPUData(){}ReleaseGPUResources(){this.positions=null,this.texCoords=null,this.texIndices=null,this.colors=null,this.indices=null,this.#s._GetCurrentMeshData()===this&&this.#s.EndBatch()}OnContextLost(){}OnContextRestored(){this.CreateGPUResources(),this.MarkAllVertexDataChanged(),this.MarkIndexDataChanged()}IsIndexTypeUint16(){return this.GetVertexCount()<65536}GetVertexCount(){return this.#r}GetIndexCount(){return this.#d}IsSmall(){return this.GetVertexCount()<128&&this.GetIndexCount()<1024}GetPendingBufferUpdate(e){switch(e){case"positions":return this.#l;case"texCoords":return this.#u;case"texIndices":if(!this.#o)throw new Error("texture indices not enabled");return this.#x;case"colors":return this.#C;case"indices":return this.#c;default:throw new Error(`invalid buffer type '${e}'`)}}MarkDataChanged(e,t,n){(t=Math.floor(t))!==(n=Math.floor(n))&&this.GetPendingBufferUpdate(e).MarkChanged(t,n)}MarkAllVertexDataChanged(e=0,t=this.GetVertexCount()){this.MarkDataChanged("positions",e,t),this.MarkDataChanged("texCoords",e,t),this.MarkDataChanged("colors",e,t),this.#o&&this.MarkDataChanged("texIndices",e,t)}MarkPositionDataChanged(e=0,t=this.GetVertexCount()){this.MarkDataChanged("positions",e,t)}MarkTexCoordsDataChanged(e=0,t=this.GetVertexCount()){this.MarkDataChanged("texCoords",e,t)}MarkColorsDataChanged(e=0,t=this.GetVertexCount()){this.MarkDataChanged("colors",e,t)}MarkIndexDataChanged(e=0,t=this.GetIndexCount()){this.MarkDataChanged("indices",e,t)}FillColor(e,t,n,i){const s=this.colors;for(let a=0,r=s.length;ar||this._height>r)throw new Error("texture data exceeds maximum texture size");const a=this._renderer.GetContext(),s=this._renderer.GetWebGLVersionNumber();this._texture=a.createTexture(),a.bindTexture(a.TEXTURE_2D,this._texture),a.pixelStorei(a["UNPACK_PREMULTIPLY_ALPHA_WEBGL"],t.premultiplyAlpha),a.pixelStorei(a["UNPACK_FLIP_Y_WEBGL"],!1);const n=GetFormatSpecifiers(this._pixelFormat,a);if(this._renderer.SupportsNPOTTextures()||i||!this._IsTiled())if(s>=2){let t;t=this._isMipMapped?Math.floor(Math.log2(Math.max(this._width,this._height))+1):1,a.texStorage2D(a.TEXTURE_2D,t,n.sizedinternalformat,this._width,this._height),e instanceof ArrayBuffer?a.texSubImage2D(a.TEXTURE_2D,0,0,0,this._width,this._height,n.format,n.type,new Uint8Array(e)):null!==e&&a.texSubImage2D(a.TEXTURE_2D,0,0,0,n.format,n.type,e)}else e instanceof ArrayBuffer?a.texImage2D(a.TEXTURE_2D,0,n.internalformat,this._width,this._height,0,n.format,n.type,new Uint8Array(e)):null===e?a.texImage2D(a.TEXTURE_2D,0,n.internalformat,this._width,this._height,0,n.format,n.type,null):a.texImage2D(a.TEXTURE_2D,0,n.internalformat,n.format,n.type,e);else{if(null===e)throw new Error("cannot pass null data when creating a NPOT tiled texture without NPOT support");if(e instanceof ArrayBuffer&&(e=new ImageData(new Uint8ClampedArray(e),this._width,this._height)),e instanceof ImageData){const t=C3.CreateCanvas(this._width,this._height);t.getContext("2d").putImageData(e,0,0),e=t}const t=C3.CreateCanvas(C3.nextHighestPowerOfTwo(this._width),C3.nextHighestPowerOfTwo(this._height)),i=t.getContext("2d");i.imageSmoothingEnabled="nearest"!==this.#e,i.drawImage(e,0,0,this._width,this._height,0,0,t.width,t.height),a.texImage2D(a.TEXTURE_2D,0,n.internalformat,n.format,n.type,t)}null!==e&&this.#a(a),s<2&&this.#s(a),s>=2&&!this._isMipMapped&&a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAX_LEVEL,0),a.bindTexture(a.TEXTURE_2D,null),this._renderer._ResetLastTexture(),this._refCount=1,allTextures.add(this)}_CreateDynamic(e,t,i){if(i=Object.assign({},CREATEFROM_DEFAULT_OPTIONS,i),this._texture)throw new Error("already created texture");if(this._wrapX=i.wrapX,this._wrapY=i.wrapY,this._pixelFormat=i.pixelFormat,this._isMipMapped=!!i.mipMap&&this._renderer.AreMipmapsEnabled(),this._mipMapQuality=i.mipMapQuality,this.SetDefaultSampling(i.defaultSampling),!VALID_WRAP_MODES.has(this._wrapX)||!VALID_WRAP_MODES.has(this._wrapY))throw new Error("invalid wrap mode");if(!VALID_PIXEL_FORMATS.has(this._pixelFormat))throw new Error("invalid pixel format");if(!VALID_MIPMAP_QUALITIES.has(this._mipMapQuality))throw new Error("invalid mipmap quality");this._isStatic=!1,this._width=Math.floor(e),this._height=Math.floor(t);const r=C3.isPOT(this._width)&&C3.isPOT(this._height),a=this._renderer.GetMaxTextureSize();if(this._width<=0||this._height<=0)throw new Error("invalid texture size");if(this._width>a||this._height>a)throw new Error("texture exceeds maximum texture size");if(!this._renderer.SupportsNPOTTextures()&&this._IsTiled()&&!r)throw new Error("non-power-of-two tiled textures not supported");const s=this._renderer.GetContext(),n=this._renderer.GetWebGLVersionNumber();this._texture=s.createTexture(),s.bindTexture(s.TEXTURE_2D,this._texture),s.pixelStorei(s["UNPACK_PREMULTIPLY_ALPHA_WEBGL"],i.premultiplyAlpha),s.pixelStorei(s["UNPACK_FLIP_Y_WEBGL"],!1);const h=GetFormatSpecifiers(this._pixelFormat,s),_=n>=2?h.sizedinternalformat:h.internalformat;s.texImage2D(s.TEXTURE_2D,0,_,this._width,this._height,0,h.format,h.type,null),this.#a(s),n<2&&this.#s(s),n>=2&&!this._isMipMapped&&s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAX_LEVEL,0),s.bindTexture(s.TEXTURE_2D,null),this._renderer._ResetLastTexture(),this._refCount=1,allTextures.add(this)}GetDefaultSampling(){return this.#e}SetDefaultSampling(e){if(!C3.Gfx.RendererBase.IsValidSamplingMode(e)||"auto"===e)throw new Error("invalid sampling");"trilinear"!==e||this._isMipMapped||(e="bilinear"),this.#e=e,this.#t=C3.Gfx.RendererBase.SamplingModeToNumber(this.#e)-1}_GetDefaultSamplingIndex(){return this.#t}_IsTiled(){return"clamp-to-edge"!==this._wrapX||"clamp-to-edge"!==this._wrapY}#n(e){if("default"===this._mipMapQuality)return this._isStatic?e.NICEST:e.FASTEST;if("low"===this._mipMapQuality)return e.FASTEST;if("high"===this._mipMapQuality)return e.NICEST;throw new Error("invalid mipmap quality")}#a(e){(C3.isPOT(this._width)&&C3.isPOT(this._height)||this._renderer.SupportsNPOTTextures())&&this._isMipMapped&&(e.hint(e.GENERATE_MIPMAP_HINT,this.#n(e)),e.generateMipmap(e.TEXTURE_2D))}#s(e){const t=this._renderer;e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,t._GetTextureWrapMode(this._wrapX)),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,t._GetTextureWrapMode(this._wrapY))}_WebGL1SetTextureSampling(e,t){if(this.#i===t)return;this.#i=t;const i=this._renderer;if(0===t)e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST);else{e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR);(C3.isPOT(this._width)&&C3.isPOT(this._height)||i.SupportsNPOTTextures())&&this._isMipMapped?e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,2===t?e.LINEAR_MIPMAP_LINEAR:e.LINEAR_MIPMAP_NEAREST):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR)}const r=i._GetAnisotropicExtension();if(r){const a=2===t?this._anisotropy:1;e.texParameterf(e.TEXTURE_2D,r["TEXTURE_MAX_ANISOTROPY_EXT"],Math.min(a,i._GetMaxAnisotropy()))}}_Update(e,t){if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||e instanceof ImageData))throw new Error("invalid texture source");if(!this._texture||this._refCount<=0)throw new Error("texture not created");if(this._isStatic)throw new Error("cannot update static texture");t=Object.assign({},UPDATE_DEFAULT_OPTIONS,t);const i=e.width||e.videoWidth,r=e.height||e.videoHeight,a=this._renderer.GetWebGLVersionNumber(),s=this._renderer.GetContext();s.bindTexture(s.TEXTURE_2D,this._texture),s.pixelStorei(s["UNPACK_PREMULTIPLY_ALPHA_WEBGL"],t.premultiplyAlpha),s.pixelStorei(s["UNPACK_FLIP_Y_WEBGL"],!!t.flipY);const n=GetFormatSpecifiers(this._pixelFormat,s),h=a>=2?n.sizedinternalformat:n.internalformat;try{if(this._width===i&&this._height===r)s.texSubImage2D(s.TEXTURE_2D,0,0,0,n.format,n.type,e),this.#a(s);else{this._width=i,this._height=r;const t=C3.isPOT(this._width)&&C3.isPOT(this._height);if(!this._renderer.SupportsNPOTTextures()&&this._IsTiled()&&!t)throw new Error("non-power-of-two tiled textures not supported");s.texImage2D(s.TEXTURE_2D,0,h,n.format,n.type,e),this.#a(s)}}catch(e){console.error("Error updating WebGL texture: ",e)}s.bindTexture(s.TEXTURE_2D,null),this._renderer._ResetLastTexture()}_Delete(){if(this._refCount>0)throw new Error("texture still has references");if(!this._texture)throw new Error("already deleted texture");allTextures.delete(this);this._renderer.GetContext().deleteTexture(this._texture),this._texture=null,this.#r.fill(null)}_GetSampler(e){return this.#r[e]||(this.#r[e]=this._renderer._GetSampler({wrapX:this._wrapX,wrapY:this._wrapY,sampling:C3.Gfx.RendererBase.SamplingNumberToMode(e+1),anisotropy:this._anisotropy})),this.#r[e]}_SetAnisotropy(e){this._anisotropy=e,this.#r.fill(null),this._renderer.GetWebGLVersionNumber()<2&&(this.#i=-1)}IsValid(){return!!this._texture}_GetTexture(){return this._texture}GetRenderer(){return this._renderer}AddReference(){this._refCount++}SubtractReference(){if(this._refCount<=0)throw new Error("no more references");this._refCount--}GetReferenceCount(){return this._refCount}GetWidth(){return this._width}GetHeight(){return this._height}IsStatic(){return this._isStatic}GetEstimatedMemoryUsage(){let e=this._width*this._height;switch(this._pixelFormat){case"rgba8":e*=4;break;case"rgb8":e*=3;break;case"rgba4":case"rgb5_a1":case"rgb565":e*=2}return this._isMipMapped&&(e+=Math.floor(e/3)),e}static OnContextLost(){allTextures.clear()}static allTextures(){return allTextures.values()}}; } // ../lib/gfx/webgl/renderTarget.js { const C3=self.C3,assert=self.assert,glMatrix=self.glMatrix,vec3=glMatrix.vec3,mat4=glMatrix.mat4,DEFAULT_RENDERTARGET_OPTIONS={defaultSampling:"trilinear",alpha:!0,depth:!1,isSampled:!0,isDefaultSize:!0,multisampling:0},allRenderTargets=new Set;C3.Gfx.WebGLRenderTarget=class{#e="trilinear";constructor(e){this._renderer=e,this._frameBuffer=null,this._frameBufferNoDepth=null,this._texture=null,this._renderBuffer=null,this._width=0,this._height=0,this._isDefaultSize=!0,this._alpha=!0,this._depth=!1,this._isSampled=!0,this._multisampling=0,this._projectionMatrix=mat4.create(),this._lastFov=0,this._lastNearZ=0,this._lastFarZ=0}_Create(e,t,r){r=Object.assign({},DEFAULT_RENDERTARGET_OPTIONS,r);const i=this._renderer.GetWebGLVersionNumber();if(this._texture||this._renderBuffer)throw new Error("already created render target");if(this.#e=r.defaultSampling,this._alpha=!!r.alpha,this._depth=!!r.depth,this._isSampled=!!r.isSampled,this._isDefaultSize=!!r.isDefaultSize,this._multisampling=r.multisampling,!C3.Gfx.RendererBase.IsValidSamplingMode(this.#e)||"auto"===this.#e)throw new Error("invalid sampling");if(this._multisampling>0&&(i<2||this._isSampled))throw new Error("invalid use of multisampling");if(i<2&&(this._isSampled=!0),this._width=e,this._height=t,this._width<=0||this._height<=0)throw new Error("invalid render target size");this._CalculateProjection();const a=this._renderer.GetContext();if(this._frameBuffer=a.createFramebuffer(),this._depth&&(this._frameBufferNoDepth=a.createFramebuffer()),this._isSampled){this._texture=this._renderer.CreateDynamicTexture(this._width,this._height,{defaultSampling:this.#e,pixelFormat:this._alpha?"rgba8":"rgb8",mipMap:!1});const e=this._texture._GetTexture();a.bindFramebuffer(a.FRAMEBUFFER,this._frameBuffer),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,e,0),this._depth&&(a.bindFramebuffer(a.FRAMEBUFFER,this._frameBufferNoDepth),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,e,0))}else{this._renderBuffer=a.createRenderbuffer(),a.bindRenderbuffer(a.RENDERBUFFER,this._renderBuffer);const e=this._alpha?a.RGBA8:a.RGB8;if(this._multisampling>0){const t=a.getInternalformatParameter(a.RENDERBUFFER,e,a.SAMPLES);if(t&&t[0]){const e=t[0];this._multisampling>e&&(this._multisampling=e)}else this._multisampling=0}0===this._multisampling?a.renderbufferStorage(a.RENDERBUFFER,e,this._width,this._height):a.renderbufferStorageMultisample(a.RENDERBUFFER,this._multisampling,e,this._width,this._height),a.bindFramebuffer(a.FRAMEBUFFER,this._frameBuffer),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.RENDERBUFFER,this._renderBuffer),this._depth&&(a.bindFramebuffer(a.FRAMEBUFFER,this._frameBufferNoDepth),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.RENDERBUFFER,this._renderBuffer)),a.bindRenderbuffer(a.RENDERBUFFER,null)}const s=this._renderer._GetDepthBuffer();this._depth&&s&&(a.bindFramebuffer(a.FRAMEBUFFER,this._frameBuffer),this._renderer._CanSampleDepth()?a.framebufferTexture2D(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.TEXTURE_2D,s,0):a.framebufferRenderbuffer(a.FRAMEBUFFER,a.DEPTH_STENCIL_ATTACHMENT,a.RENDERBUFFER,s)),a.bindFramebuffer(a.FRAMEBUFFER,null),allRenderTargets.add(this)}_Resize(e,t){if(this._width===e&&this._height===t)return;this._width=e,this._height=t,this._CalculateProjection();const r=this._renderer.GetContext();r.bindFramebuffer(r.FRAMEBUFFER,this._frameBuffer),this._texture?this._texture._Update(new ImageData(this._width,this._height)):(r.bindRenderbuffer(r.RENDERBUFFER,this._renderBuffer),r.renderbufferStorage(r.RENDERBUFFER,this._alpha?r.RGBA8:r.RGB8,this._width,this._height),r.bindRenderbuffer(r.RENDERBUFFER,null));const i=this._renderer._GetDepthBuffer();this._depth&&i&&(this._renderer._CanSampleDepth()?r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.TEXTURE_2D,i,0):r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,i)),r.bindFramebuffer(r.FRAMEBUFFER,null)}_Delete(){if(!this._texture&&!this._renderBuffer)throw new Error("already deleted render target");allRenderTargets.delete(this);const e=this._renderer.GetContext();this._texture?(e.bindFramebuffer(e.FRAMEBUFFER,this._frameBuffer),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0),this._depth&&(e.bindFramebuffer(e.FRAMEBUFFER,this._frameBufferNoDepth),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)),this._renderer.DeleteTexture(this._texture),this._texture=null):this._renderBuffer&&(e.bindFramebuffer(e.FRAMEBUFFER,this._frameBuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,null),this._depth&&(e.bindFramebuffer(e.FRAMEBUFFER,this._frameBufferNoDepth),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,null)),e.deleteRenderbuffer(this._renderBuffer),this._renderBuffer=null),e.bindFramebuffer(e.FRAMEBUFFER,null),this._renderer.GetWebGLVersionNumber()>=2&&(e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null)),e.deleteFramebuffer(this._frameBuffer),this._depth&&e.deleteFramebuffer(this._frameBufferNoDepth);const t=this._renderer.GetBatchState();t.currentFramebuffer=null,t.currentFramebufferNoDepth=null,this._frameBuffer=null}_CalculateProjection(){this._renderer.CalculatePerspectiveMatrix(this._projectionMatrix,this._width/this._height),this._lastFov=this._renderer.GetFovY(),this._lastNearZ=this._renderer.GetNearZ(),this._lastFarZ=this._renderer.GetFarZ()}_GetFramebuffer(){return this._frameBuffer}_GetFramebufferNoDepth(){return this._frameBufferNoDepth}GetRenderer(){return this._renderer}GetTexture(){return this._texture}GetProjectionMatrix(){return this._renderer.GetFovY()===this._lastFov&&this._renderer.GetNearZ()===this._lastNearZ&&this._renderer.GetFarZ()===this._lastFarZ||this._CalculateProjection(),this._projectionMatrix}HasAlpha(){return this._alpha}IsSampled(){return this._isSampled}HasDepthBuffer(){return this._depth}GetWidth(){return this._width}GetHeight(){return this._height}IsDefaultSize(){return this._isDefaultSize}SetDefaultSampling(e){this.#e=e,this._texture&&this._texture.SetDefaultSampling(e)}GetDefaultSampling(){return this.#e}GetMultisampling(){return this._multisampling}GetOptions(){const e={alpha:this._alpha,isSampled:this._isSampled};return this._isDefaultSize||(e.width=this._width,e.height=this._height),e}IsCompatibleWithOptions(e){return!!(e=Object.assign({},DEFAULT_RENDERTARGET_OPTIONS,e)).alpha===this.HasAlpha()&&(!!e.depth===this.HasDepthBuffer()&&(!(this._renderer.GetWebGLVersionNumber()>=2&&!!e.isSampled!==this.IsSampled())&&("number"==typeof e.width||"number"==typeof e.height?!this.IsDefaultSize()&&this.GetWidth()===Math.floor(e.width)&&this.GetHeight()===Math.floor(e.height):this.IsDefaultSize())))}_GetWebGLTexture(){return this._texture?this._texture._GetTexture():null}GetEstimatedMemoryUsage(){return this._texture?this._texture.GetEstimatedMemoryUsage():this._width*this._height*(this._alpha?4:3)}static async DebugReadPixelsToBlob(e,t){const r=await e.ReadBackRenderTargetToImageData(t,!0);return await C3.ImageDataToBlob(r)}static OnContextLost(){allRenderTargets.clear()}static allRenderTargets(){return allRenderTargets.values()}static ResizeAll(e,t){for(const r of allRenderTargets)r.IsDefaultSize()&&r._Resize(e,t)}}; } // ../lib/gfx/webgl/shaderProgram.js { const C3=self.C3,glMatrix=self.glMatrix,vec3=glMatrix.vec3,mat4=glMatrix.mat4,RESERVED_UNIFORM_NAMES=new Set(["aPos","aTex","aColor","aPoints","matP","matMV","samplerFront","samplerBack","samplerDepth","destStart","destEnd","srcStart","srcEnd","srcOriginStart","srcOriginEnd","pixelSize","seconds","devicePixelRatio","layerScale","layerAngle","layoutStart","layoutEnd","color","color2_","pointTexStart","pointTexEnd","zElevation","tileSize","tileSpacing","outlineThickness","zNear","zFar"]);C3.Gfx.WebGLShaderProgram=class extends C3.Gfx.ShaderProgramBase{static async Compile(e,t){const i=e.GetContext(),r=t.src,o=t.vertexSrc,n=t.name,a=i.createShader(i.FRAGMENT_SHADER);i.shaderSource(a,r),i.compileShader(a);const l=i.createShader(i.VERTEX_SHADER);i.shaderSource(l,o),i.compileShader(l);const s=i.createProgram();i.attachShader(s,a),i.attachShader(s,l),i.bindAttribLocation(s,0,"aPos"),i.bindAttribLocation(s,1,"aTex"),i.bindAttribLocation(s,2,"aColor"),i.bindAttribLocation(s,3,"aPoints"),i.linkProgram(s);const h=e._GetParallelShaderCompileExtension();if(h?await e._WaitForObjectReady(()=>i.getProgramParameter(s,h["COMPLETION_STATUS_KHR"])):await C3.Wait(5),!i.getShaderParameter(a,i.COMPILE_STATUS)){const e=i.getShaderInfoLog(a);throw i.deleteShader(a),i.deleteShader(l),i.deleteProgram(s),new Error("Error compiling fragment shader: "+e)}if(!i.getShaderParameter(l,i.COMPILE_STATUS)){const e=i.getShaderInfoLog(l);throw i.deleteShader(a),i.deleteShader(l),i.deleteProgram(s),new Error("Error compiling vertex shader: "+e)}if(!i.getProgramParameter(s,i.LINK_STATUS)){const e=i.getProgramInfoLog(s);throw i.deleteShader(a),i.deleteShader(l),i.deleteProgram(s),new Error("Error linking shader program: "+e)}const d=C3.FilterUnprintableChars(i.getProgramInfoLog(s)||"").trim();return d&&!C3.IsStringAllWhitespace(d)&&console.info(`[WebGL] Shader program '${n}' compilation log: `,d),i.deleteShader(a),i.deleteShader(l),s}static async Create(e,t){const i=await C3.Gfx.WebGLShaderProgram.Compile(e,t);return new C3.Gfx.WebGLShaderProgram(e,i,t)}constructor(e,t,i){super(e,i);const r=e.GetContext(),o=e.GetBatchState();e.EndBatch(),r.useProgram(t),this._gl=r,this._shaderProgram=t,this._isDeviceTransform=""===i.name,this._uMatP=new C3.Gfx.WebGLShaderUniform(this,"matP","mat4"),this._uMatMV=new C3.Gfx.WebGLShaderUniform(this,"matMV","mat4"),this._uColor=new C3.Gfx.WebGLShaderUniform(this,"color","vec4"),this._uSamplerFront=new C3.Gfx.WebGLShaderUniform(this,"samplerFront","sampler"),this._uPointTexStart=new C3.Gfx.WebGLShaderUniform(this,"pointTexStart","vec2"),this._uPointTexEnd=new C3.Gfx.WebGLShaderUniform(this,"pointTexEnd","vec2"),this._uZElevation=new C3.Gfx.WebGLShaderUniform(this,"zElevation","float"),this._uTileSize=new C3.Gfx.WebGLShaderUniform(this,"tileSize","vec2"),this._uTileSpacing=new C3.Gfx.WebGLShaderUniform(this,"tileSpacing","vec2"),this._uColor2=new C3.Gfx.WebGLShaderUniform(this,"color2_","vec4"),this._uOutlineThickness=new C3.Gfx.WebGLShaderUniform(this,"outlineThickness","float"),this._uSamplerBack=new C3.Gfx.WebGLShaderUniform(this,"samplerBack","sampler"),this._uSamplerDepth=new C3.Gfx.WebGLShaderUniform(this,"samplerDepth","sampler"),this._uDestStart=new C3.Gfx.WebGLShaderUniform(this,"destStart","vec2"),this._uDestEnd=new C3.Gfx.WebGLShaderUniform(this,"destEnd","vec2"),this._uSrcStart=new C3.Gfx.WebGLShaderUniform(this,"srcStart","vec2"),this._uSrcEnd=new C3.Gfx.WebGLShaderUniform(this,"srcEnd","vec2"),this._uSrcOriginStart=new C3.Gfx.WebGLShaderUniform(this,"srcOriginStart","vec2"),this._uSrcOriginEnd=new C3.Gfx.WebGLShaderUniform(this,"srcOriginEnd","vec2"),this._uPixelSize=new C3.Gfx.WebGLShaderUniform(this,"pixelSize","vec2"),this._uSeconds=new C3.Gfx.WebGLShaderUniform(this,"seconds","float"),this._uDevicePixelRatio=new C3.Gfx.WebGLShaderUniform(this,"devicePixelRatio","float"),this._uLayerScale=new C3.Gfx.WebGLShaderUniform(this,"layerScale","float"),this._uLayerAngle=new C3.Gfx.WebGLShaderUniform(this,"layerAngle","float"),this._uLayoutStart=new C3.Gfx.WebGLShaderUniform(this,"layoutStart","vec2"),this._uLayoutEnd=new C3.Gfx.WebGLShaderUniform(this,"layoutEnd","vec2"),this._uZNear=new C3.Gfx.WebGLShaderUniform(this,"zNear","float"),this._uZFar=new C3.Gfx.WebGLShaderUniform(this,"zFar","float"),this._hasAnyOptionalUniforms=!!(this._uPixelSize.IsUsed()||this._uSeconds.IsUsed()||this._uSamplerBack.IsUsed()||this._uDestStart.IsUsed()||this._uDestEnd.IsUsed()||this._uSrcStart.IsUsed()||this._uSrcEnd.IsUsed()||this._uSrcOriginStart.IsUsed()||this._uSrcOriginEnd.IsUsed()||this._uDevicePixelRatio.IsUsed()||this._uLayerScale.IsUsed()||this._uLayerAngle.IsUsed()||this._uLayoutStart.IsUsed()||this._uLayoutEnd.IsUsed());const n=i.parameters||[];this._uCustomParameters=[],this._usesAnySrcRectOrPixelSize=this._uPixelSize.IsUsed()||this._uSrcStart.IsUsed()||this._uSrcEnd.IsUsed()||this._uSrcOriginStart.IsUsed()||this._uSrcOriginEnd.IsUsed(),this._hasCurrentMatP=!1,this._hasCurrentMatMV=!1,this._uColor.Init4f(1,1,1,1),this._uColor2.Init4f(1,1,1,1),this._uSamplerFront.Init1i(0),this._uSamplerBack.Init1i(1),this._uSamplerDepth.Init1i(2),this._uPointTexStart.Init2f(0,0),this._uPointTexEnd.Init2f(1,1),this._uZElevation.Init1f(0),this._uTileSize.Init2f(0,0),this._uTileSpacing.Init2f(0,0),this._uDestStart.Init2f(0,0),this._uDestEnd.Init2f(1,1),this._uSrcStart.Init2f(0,0),this._uSrcEnd.Init2f(0,0),this._uSrcOriginStart.Init2f(0,0),this._uSrcOriginEnd.Init2f(0,0),this._uPixelSize.Init2f(0,0),this._uDevicePixelRatio.Init1f(1),this._uZNear.Init1f(e.GetNearZ()),this._uZFar.Init1f(e.GetFarZ()),this._uLayerScale.Init1f(1),this._uLayerAngle.Init1f(0),this._uSeconds.Init1f(0),this._uLayoutStart.Init2f(0,0),this._uLayoutEnd.Init2f(0,0),this._uOutlineThickness.Init1f(1);for(const e of n){const t=e[0],i=e[2],r=new C3.Gfx.WebGLShaderUniform(this,t,i);"color"===i?r.Init3f(0,0,0):r.Init1f(0),this._uCustomParameters.push(r)}this._isDeviceTransform?this._UpdateDeviceTransformUniforms(o.currentMatP):(this.UpdateMatP(o.currentMatP,!0),this.UpdateMatMV(o.currentMV,!0));const a=o.currentShader;r.useProgram(a?a._shaderProgram:null)}Release(){this._gl.deleteProgram(this._shaderProgram),this._shaderProgram=null,this._renderer._RemoveShaderProgram(this),this._gl=null,super.Release()}GetWebGLContext(){return this._gl}GetShaderProgram(){return this._shaderProgram}GetParameterCount(){return this._uCustomParameters.length}GetParameterType(e){return e<0||e>=this._uCustomParameters.length?null:this._uCustomParameters[e].GetType()}AreCustomParametersAlreadySetInBatch(e){for(let t=0,i=e.length;t=2?o="#version 300 es\n"+C3.Gfx.WebGLShaderProgram._GetConservativeDepthShaderPrefix(r):(t&&(o="#extension GL_EXT_frag_depth : enable\n"),i&&(o+="#extension GL_EXT_shader_texture_lod : enable\n",o+="#extension GL_OES_standard_derivatives : enable\n")),o+`\nprecision highp float;\n${e>=2?"in":"varying"} vec2 vTex;\n${e>=2?"out lowp vec4 outColor;":""}\n${e>=2?"in":"varying"} lowp vec4 vColor;\nuniform lowp sampler2D samplerFront;\nuniform vec2 pixelSize;\n\nuniform vec2 tileSize;\nuniform vec2 tileSpacing;\nuniform float outlineThickness;\n\nconst float PI = 3.1415926;\n\nlowp vec4 cospVec4(lowp vec4 a, lowp vec4 b, float x)\n{\n\treturn (a + b + (a - b) * cos(x * PI)) / 2.0;\n}\n\nvec3 randVec3(vec2 seed)\n{\n\treturn vec3(fract(sin(dot(seed.xy + vec2(0.1, 0.1), vec2(12.9898,78.233))) * 43758.5453),\n\t\t\t\tfract(sin(dot(seed.yx + vec2(0.1, 0.1), vec2(12.9898,-78.233))) * 43758.5453),\n\t\t\t\tfract(sin(dot(seed.xy + vec2(0.1, 0.1), vec2(-12.9898,-78.233))) * 43758.5453));\n}\n\nlowp vec4 sampleTile(vec2 tile, vec2 uv, vec2 ddx, vec2 ddy)\n{\n\tvec2 posRandom = tileSize;\n\tfloat angleRandom = outlineThickness;\n\t\n\tvec3 rand = (randVec3(floor(tile + 0.5)) - 0.5) * 2.0;\n\t\n\tfloat angle = angleRandom * rand.z * PI;\n\tfloat sin_a = sin(angle);\n\tfloat cos_a = cos(angle);\n\tfloat aspect = pixelSize.x / pixelSize.y;\n\n\tvec2 mid = tile + vec2(0.5, 0.5);\n\tvec2 dp = uv - mid;\n\tdp.x /= aspect;\n\tvec2 r = vec2(dp.x * cos_a - dp.y * sin_a,\n\t\t\t\t dp.y * cos_a + dp.x * sin_a);\n\tr.x *= aspect;\n\n\tvec2 p = mid + r + (posRandom * rand.xy / 2.0);\n\t\n\t${e>=2?"return textureGrad(samplerFront, p, ddx, ddy);":""}\n\t${e<2&&i?"return texture2DGradEXT(samplerFront, p, ddx, ddy);":""}\n\t${e<2&&!i?"return texture2D(samplerFront, p);":""}\n}\n\nvoid main(void) {\n\t\n\t${e<2?"lowp vec4 outColor;":""}\n\t\n\tfloat blendMarginX = tileSpacing.x;\n\tfloat blendMarginY = tileSpacing.y;\n\t\n\tvec2 tile = floor(vTex);\n\tvec2 tex = fract(vTex);\n\tvec2 ddx = ${e>=2||i?"dFdx(vTex)":"vec2(0.0, 0.0)"};\n\tvec2 ddy = ${e>=2||i?"dFdy(vTex)":"vec2(0.0, 0.0)"};\n\t\n\tvec4 curTile = sampleTile(tile, vTex, ddx, ddy);\n\t\n\tbool inLeftMargin = (tex.x < blendMarginX);\n\tbool inRightMargin = (tex.x > 1.0 - blendMarginX);\n\tbool inTopMargin = (tex.y < blendMarginY);\n\tbool inBottomMargin = (tex.y > 1.0 - blendMarginY);\n\t\n\tif (inLeftMargin)\n\t{\n\t\tlowp vec4 leftTile = sampleTile(tile + vec2(-1.0, 0.0), vTex, ddx, ddy);\n\t\tfloat leftMix = (tex.x / (blendMarginX * 2.0)) + 0.5;\n\t\tlowp vec4 leftMixedTile = cospVec4(leftTile, curTile, leftMix);\n\t\t\n\t\tif (inTopMargin)\n\t\t{\n\t\t\tlowp vec4 topTile = sampleTile(tile + vec2(0.0, -1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 topLeftTile = sampleTile(tile + vec2(-1.0, -1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 topLeftMixedTile = cospVec4(topLeftTile, topTile, leftMix);\n\t\t\t\n\t\t\toutColor = cospVec4(topLeftMixedTile, leftMixedTile, (tex.y / (blendMarginY * 2.0)) + 0.5);\n\t\t}\n\t\telse if (inBottomMargin)\n\t\t{\n\t\t\tlowp vec4 bottomTile = sampleTile(tile + vec2(0.0, 1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 bottomLeftTile = sampleTile(tile + vec2(-1.0, 1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 bottomLeftMixedTile = cospVec4(bottomLeftTile, bottomTile, leftMix);\n\t\t\t\n\t\t\toutColor = cospVec4(leftMixedTile, bottomLeftMixedTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));\n\t\t}\n\t\telse\n\t\t{\n\t\t\toutColor = leftMixedTile;\n\t\t}\n\t}\n\telse if (inRightMargin)\n\t{\n\t\tlowp vec4 rightTile = sampleTile(tile + vec2(1.0, 0.0), vTex, ddx, ddy);\n\t\tfloat rightMix = (tex.x - (1.0 - blendMarginX)) / (blendMarginX * 2.0);\n\t\tlowp vec4 rightMixedTile = cospVec4(curTile, rightTile, rightMix);\n\t\t\n\t\tif (inTopMargin)\n\t\t{\n\t\t\tlowp vec4 topTile = sampleTile(tile + vec2(0.0, -1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 topRightTile = sampleTile(tile + vec2(1.0, -1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 topRightMixedTile = cospVec4(topTile, topRightTile, rightMix);\n\t\t\t\n\t\t\toutColor = cospVec4(topRightMixedTile, rightMixedTile, (tex.y / (blendMarginY * 2.0)) + 0.5);\n\t\t}\n\t\telse if (inBottomMargin)\n\t\t{\n\t\t\tlowp vec4 bottomTile = sampleTile(tile + vec2(0.0, 1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 bottomRightTile = sampleTile(tile + vec2(1.0, 1.0), vTex, ddx, ddy);\n\t\t\tlowp vec4 bottomRightMixedTile = cospVec4(bottomTile, bottomRightTile, rightMix);\n\t\t\t\n\t\t\toutColor = cospVec4(rightMixedTile, bottomRightMixedTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));\n\t\t}\n\t\telse\n\t\t{\n\t\t\toutColor = rightMixedTile;\n\t\t}\n\t}\n\telse if (inTopMargin)\n\t{\n\t\tlowp vec4 topTile = sampleTile(tile + vec2(0.0, -1.0), vTex, ddx, ddy);\n\t\toutColor = cospVec4(topTile, curTile, (tex.y / (blendMarginY * 2.0)) + 0.5);\n\t}\n\telse if (inBottomMargin)\n\t{\n\t\tlowp vec4 bottomTile = sampleTile(tile + vec2(0.0, 1.0), vTex, ddx, ddy);\n\t\toutColor = cospVec4(curTile, bottomTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));\n\t}\n\telse\n\t{\n\t\toutColor = curTile;\n\t}\n\t\n\toutColor *= vColor;\n\t${e<2?"gl_FragColor = outColor;":""}\n\t${e>=2?"gl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);":""}\n\t${e<2&&t?"gl_FragDepthEXT = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);":""}\n}\n`}static GetPointVertexShaderSource_WebGL1(){return["attribute vec4 aPoints;","varying float pointOpacity;","uniform float zElevation;","uniform mat4 matP;","uniform mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPoints.xy, zElevation, 1.0);","\tgl_PointSize = aPoints.z;","\tpointOpacity = aPoints.w;","}"].join("\n")}static GetPointVertexShaderSource_WebGL2(){return["#version 300 es","in vec4 aPoints;","out float pointOpacity;","uniform float zElevation;","uniform mat4 matP;","uniform mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPoints.xy, zElevation, 1.0);","\tgl_PointSize = aPoints.z;","\tpointOpacity = aPoints.w;","}"].join("\n")}static GetPointFragmentShaderSource_WebGL1_NoFragDepth(){return["uniform lowp sampler2D samplerFront;","varying lowp float pointOpacity;","uniform mediump vec2 pointTexStart;","uniform mediump vec2 pointTexEnd;","uniform lowp vec4 color;","void main(void) {","\tmediump vec2 pointTexMin = min(pointTexStart, pointTexEnd);","\tmediump vec2 pointTexMax = max(pointTexStart, pointTexEnd);","\tmediump vec2 pointCoord = (pointTexEnd.x > pointTexStart.x ? gl_PointCoord : vec2(1.0 - gl_PointCoord.y, gl_PointCoord.x));","\tgl_FragColor = texture2D(samplerFront, mix(pointTexMin, pointTexMax, pointCoord)) * color * pointOpacity;","}"].join("\n")}static GetPointFragmentShaderSource_WebGL1_FragDepthEXT(){return["#extension GL_EXT_frag_depth : enable","uniform lowp sampler2D samplerFront;","varying lowp float pointOpacity;","uniform mediump vec2 pointTexStart;","uniform mediump vec2 pointTexEnd;","uniform lowp vec4 color;","void main(void) {","\tmediump vec2 pointTexMin = min(pointTexStart, pointTexEnd);","\tmediump vec2 pointTexMax = max(pointTexStart, pointTexEnd);","\tmediump vec2 pointCoord = (pointTexEnd.x > pointTexStart.x ? gl_PointCoord : vec2(1.0 - gl_PointCoord.y, gl_PointCoord.x));","\tgl_FragColor = texture2D(samplerFront, mix(pointTexMin, pointTexMax, pointCoord)) * color * pointOpacity;","\tgl_FragDepthEXT = (gl_FragColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetPointFragmentShaderSource_WebGL2(e){return["#version 300 es",C3.Gfx.WebGLShaderProgram._GetConservativeDepthShaderPrefix(e),"uniform lowp sampler2D samplerFront;","in lowp float pointOpacity;","uniform mediump vec2 pointTexStart;","uniform mediump vec2 pointTexEnd;","uniform lowp vec4 color;","out lowp vec4 outColor;","void main(void) {","\tmediump vec2 pointTexMin = min(pointTexStart, pointTexEnd);","\tmediump vec2 pointTexMax = max(pointTexStart, pointTexEnd);","\tmediump vec2 pointCoord = (pointTexEnd.x > pointTexStart.x ? gl_PointCoord : vec2(1.0 - gl_PointCoord.y, gl_PointCoord.x));","\toutColor = texture(samplerFront, mix(pointTexMin, pointTexMax, pointCoord)) * color * pointOpacity;","\tgl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetColorFillFragmentShaderSource(){return["varying lowp vec4 vColor;","void main(void) {","\tgl_FragColor = vColor;","}"].join("\n")}static GetLinearGradientFillFragmentShaderSource(){return["precision lowp float;","varying mediump vec2 vTex;","varying vec4 vColor;","uniform vec4 color2_;","vec3 fromLinear(vec3 linearRGB)","{","\tbvec3 cutoff = lessThan(linearRGB, vec3(0.0031308));","\tvec3 higher = vec3(1.055) * pow(abs(linearRGB), vec3(1.0/2.4)) - vec3(0.055);","\tvec3 lower = linearRGB * vec3(12.92);","\treturn mix(higher, lower, vec3(cutoff));","}","vec3 toLinear(vec3 sRGB)","{","\tbvec3 cutoff = lessThan(sRGB, vec3(0.04045));","\tvec3 higher = pow(abs((sRGB + vec3(0.055))/vec3(1.055)), vec3(2.4));","\tvec3 lower = sRGB/vec3(12.92);","\treturn mix(higher, lower, vec3(cutoff));","}","void main(void) {","\tvec3 linearGrad = mix(toLinear(vColor.rgb), toLinear(color2_.rgb), vTex.x);","\tfloat a = mix(vColor.a, color2_.a, vTex.x);","\tgl_FragColor = vec4(fromLinear(linearGrad) * a, a);","}"].join("\n")}static GetPenumbraFillFragmentShaderSource(){return["precision lowp float;","varying highp vec2 vTex;","varying vec4 vColor;","void main(void) {","\thighp float grad = vTex.x / (1.0 - vTex.y);","\tgl_FragColor = vColor * (1.0 - (cos(grad * 3.141592653589793) + 1.0) / 2.0);","}"].join("\n")}static GetSmoothLineFillFragmentShaderSource(){return["varying mediump vec2 vTex;","varying lowp vec4 vColor;","void main(void) {","\tlowp float f = 1.0 - abs(vTex.y - 0.5) * 2.0;","\tgl_FragColor = vColor * f;","}"].join("\n")}static GetHardEllipseFillFragmentShaderSource(){return["varying highp vec2 vTex;","varying lowp vec4 vColor;","void main(void) {","\thighp vec2 diff = vTex - vec2(0.5, 0.5);","\thighp vec2 diffSq = diff * diff;","\thighp float f = step(diffSq.x + diffSq.y, 0.25);","\tgl_FragColor = vColor * f;","}"].join("\n")}static GetHardEllipseOutlineFragmentShaderSource(){return["varying highp vec2 vTex;","varying lowp vec4 vColor;","uniform highp vec2 pixelSize;","uniform highp float outlineThickness;","void main(void) {","\thighp vec2 diff = vTex - vec2(0.5, 0.5);","\thighp vec2 diffSq = diff * diff;","\thighp float distSq = diffSq.x + diffSq.y;","\thighp vec2 norm = normalize(diff);","\thighp vec2 halfNorm = norm * 0.5;","\thighp float innerF = step(distSq, 0.25);","\thighp vec2 innerEdge = halfNorm - pixelSize * norm * outlineThickness;","\thighp vec2 innerEdgeSq = innerEdge * innerEdge;","\thighp float outerF = step(innerEdgeSq.x + innerEdgeSq.y, distSq);","\tgl_FragColor = vColor * innerF * outerF;","}"].join("\n")}static GetSmoothEllipseFillFragmentShaderSource(){return["varying highp vec2 vTex;","varying lowp vec4 vColor;","uniform highp vec2 pixelSize;","void main(void) {","\thighp vec2 diff = vTex - vec2(0.5, 0.5);","\thighp vec2 diffSq = diff * diff;","\thighp vec2 norm = normalize(diff);","\thighp vec2 halfNorm = norm * 0.5;","\thighp vec2 halfNormSq = halfNorm * halfNorm;","\thighp vec2 innerEdge = halfNorm - pixelSize * norm;","\thighp vec2 innerEdgeSq = innerEdge * innerEdge;","\thighp float f = smoothstep(halfNormSq.x + halfNormSq.y, innerEdgeSq.x + innerEdgeSq.y, diffSq.x + diffSq.y);","\tgl_FragColor = vColor * f;","}"].join("\n")}static GetSmoothEllipseOutlineFragmentShaderSource(){return["varying highp vec2 vTex;","varying lowp vec4 vColor;","uniform highp vec2 pixelSize;","uniform highp float outlineThickness;","void main(void) {","\thighp vec2 diff = vTex - vec2(0.5, 0.5);","\thighp vec2 diffSq = diff * diff;","\thighp float distSq = diffSq.x + diffSq.y;","\thighp vec2 norm = normalize(diff);","\thighp vec2 halfNorm = norm * 0.5;","\thighp vec2 halfNormSq = halfNorm * halfNorm;","\thighp vec2 pxNorm = pixelSize * norm;","\thighp vec2 innerEdge1 = halfNorm - pxNorm;","\thighp vec2 innerEdge1Sq = innerEdge1 * innerEdge1;","\thighp float innerF = smoothstep(halfNormSq.x + halfNormSq.y, innerEdge1Sq.x + innerEdge1Sq.y, distSq);","\thighp vec2 innerEdge2 = halfNorm - pxNorm * outlineThickness;","\thighp vec2 innerEdge2Sq = innerEdge2 * innerEdge2;","\thighp vec2 innerEdge3 = halfNorm - pxNorm * (outlineThickness + 1.0);","\thighp vec2 innerEdge3Sq = innerEdge3 * innerEdge3;","\thighp float outerF = smoothstep(innerEdge3Sq.x + innerEdge3Sq.y, innerEdge2Sq.x + innerEdge2Sq.y, distSq);","\tgl_FragColor = vColor * innerF * outerF;","}"].join("\n")}}; } // ../lib/gfx/webgl/shaderUniform.js { const C3=self.C3,glMatrix=self.glMatrix,mat4=glMatrix.mat4,TYPE_SIZES=new Map([["float",1],["percent",1],["sampler",1],["vec2",2],["vec3",3],["color",3],["vec4",4],["mat4",16]]);C3.Gfx.WebGLShaderUniform=class{constructor(t,s,a){if(!TYPE_SIZES.has(a))throw new Error("invalid uniform type");this._owner=t,this._gl=this._owner.GetWebGLContext(),this._name=s,this._type=a,this._isColorType="color"===this._type,this._location=this._gl.getUniformLocation(this._owner.GetShaderProgram(),s),this._isUsed=!!this._location;const i=TYPE_SIZES.get(a);this._lastValue=new Float32Array(i),this._lastBatchValue=new Float32Array(i)}Release(){this._owner=null,this._gl=null,this._location=null}IsUsed(){return this._isUsed}GetType(){return this._type}IsColorType(){return this._isColorType}Init1f(t){this.IsUsed()&&(this._lastValue[0]=t,this._lastBatchValue.set(this._lastValue),this._gl.uniform1f(this._location,t))}Init1i(t){this.IsUsed()&&(this._lastValue[0]=t,this._lastBatchValue.set(this._lastValue),this._gl.uniform1i(this._location,t))}Init2f(t,s){this.IsUsed()&&(this._lastValue[0]=t,this._lastValue[1]=s,this._lastBatchValue.set(this._lastValue),this._gl.uniform2f(this._location,t,s))}Init3f(t,s,a){this.IsUsed()&&(this._lastValue[0]=t,this._lastValue[1]=s,this._lastValue[2]=a,this._lastBatchValue.set(this._lastValue),this._gl.uniform3f(this._location,t,s,a))}Init4f(t,s,a,i){this.IsUsed()&&(this._lastValue[0]=t,this._lastValue[1]=s,this._lastValue[2]=a,this._lastValue[3]=i,this._lastBatchValue.set(this._lastValue),this._gl.uniform4f(this._location,t,s,a,i))}Update1f(t){t=Math.fround(t);const s=this._lastValue;s[0]!==t&&(s[0]=t,this._gl.uniform1f(this._location,t))}Update1i(t){const s=this._lastValue;s[0]!==t&&(s[0]=t,this._gl.uniform1i(this._location,t))}Update2f(t,s){t=Math.fround(t),s=Math.fround(s);const a=this._lastValue;a[0]===t&&a[1]===s||(a[0]=t,a[1]=s,this._gl.uniform2f(this._location,t,s))}Update3f(t,s,a){t=Math.fround(t),s=Math.fround(s),a=Math.fround(a);const i=this._lastValue;i[0]===t&&i[1]===s&&i[2]===a||(i[0]=t,i[1]=s,i[2]=a,this._gl.uniform3f(this._location,t,s,a))}Update4f(t,s,a,i){t=Math.fround(t),s=Math.fround(s),a=Math.fround(a),i=Math.fround(i);const l=this._lastValue;l[0]===t&&l[1]===s&&l[2]===a&&l[3]===i||(l[0]=t,l[1]=s,l[2]=a,l[3]=i,this._gl.uniform4f(this._location,t,s,a,i))}UpdateMatrix4fv(t){const s=this._lastValue;mat4.exactEquals(s,t)||(C3.typedArraySet16(s,t,0),this._gl.uniformMatrix4fv(this._location,!1,t))}IsSetToCustomInBatch(t){const s=this._lastBatchValue;return this.IsColorType()?s[0]===Math.fround(t.getR())&&s[1]===Math.fround(t.getG())&&s[2]===Math.fround(t.getB()):s[0]===Math.fround(t)}SetBatchValueCustom(t){const s=this._lastBatchValue;this.IsColorType()?(s[0]=t.getR(),s[1]=t.getG(),s[2]=t.getB()):s[0]=t}IsSetTo1InBatch(t){return this._lastBatchValue[0]===Math.fround(t)}IsSetTo2InBatch(t,s){const a=this._lastBatchValue;return a[0]===Math.fround(t)&&a[1]===Math.fround(s)}SetBatch1(t){this._lastBatchValue[0]=t}SetBatch2(t,s){const a=this._lastBatchValue;a[0]=t,a[1]=s}}; } // ../lib/gfx/webgl/batchJob.js { const C3=self.C3,glMatrix=self.glMatrix,vec4=glMatrix.vec4,mat4=glMatrix.mat4,BATCH_NULL=0,BATCH_DRAW=1,BATCH_SETTEXTURE=2,BATCH_SETBLEND=3,BATCH_SETVIEWPORT=4,BATCH_SETPROJECTION=5,BATCH_SETMODELVIEW=6,BATCH_SETRENDERTARGET=7,BATCH_CLEARSURFACE=8,BATCH_POINTS=9,BATCH_SETPROGRAM=10,BATCH_SETPROGRAMPARAMETERS=11,BATCH_SETPROGRAMCUSTOMPARAMETERS=12,BATCH_INVALIDATEFRAMEBUFFER=13,BATCH_SETPOINTTEXCOORDS=14,BATCH_SETTILEMAPINFO=15,BATCH_BLITFRAMEBUFFER=16,BATCH_STARTQUERY=17,BATCH_ENDQUERY=18,BATCH_SETELLIPSEPARAMS=19,BATCH_SETGRADIENTCOLOR=20,BATCH_CLEARDEPTH=21,BATCH_SETDEPTHENABLED=22,BATCH_SETDEPTHSAMPLINGENABLED=23,BATCH_COPLANAR_STARTSTENCILPASS=24,BATCH_COPLANAR_STARTCOLORPASS=25,BATCH_COPLANAR_RESTORE=26,BATCH_SET_SCISSOR=27,BATCH_SETTILERANDOMIZATIONINFO=28,BATCH_SETCULLFACEMODE=29,BATCH_SETFRONTFACEWINDING=30,BATCH_SETCURRENTMESHDATA=31;C3.Gfx.BatchState=class{constructor(t){this.renderer=t,this.currentMV=mat4.create(),this.currentMatP=mat4.create(),this.currentFramebuffer=null,this.currentFramebufferNoDepth=null,this.isDepthSamplingEnabled=!1,this.currentShader=null,this.currentMeshData=t._GetCurrentMeshData(),this.currentSampler0=null,this.currentSampler1=null,this.pointTexCoords=new C3.Rect,this.clearColor=C3.New(C3.Color,0,0,0,0)}},C3.Gfx.WebGLBatchJob=class{constructor(t){const e=new ArrayBuffer(96);this._type=0,this._batchState=t,this._gl=t.renderer.GetContext(),this._startIndex=0,this._indexCount=0,this._texParam=null,this._mat4param=new Float32Array(e,0,16),this._colorParam=new Float32Array(e,64,4),this._srcOriginRect=new Float32Array(e,80,4),this._shaderParams=[]}InitDraw(t,e){this._type=1,this._startIndex=t,this._indexCount=e}DoDraw(){const t=this._gl,e=this._batchState.currentMeshData;t.drawElements(t.TRIANGLES,this._indexCount,e.IsIndexTypeUint16()?t.UNSIGNED_SHORT:t.UNSIGNED_INT,this._startIndex)}InitSetTexture(t,e){this._type=2,this._texParam=t,this._startIndex=e}DoSetTexture(){const t=this._gl,e=this._texParam,r=this._startIndex,a=this._batchState,s=a.renderer.GetWebGLVersionNumber();let i=null;e?(t.bindTexture(t.TEXTURE_2D,e._GetTexture()),s<2?e._WebGL1SetTextureSampling(t,r):i=e._GetSampler(r)):t.bindTexture(t.TEXTURE_2D,null),s>=2&&a.currentSampler0!==i&&(t.bindSampler(0,i),a.currentSampler0=i)}InitSetGradientColor(t){this._type=20,t.writeToTypedArray(this._colorParam,0)}DoSetGradientColor(){const t=this._colorParam,e=this._batchState.currentShader;e._uColor2.IsUsed()&&e._uColor2.Update4f(t[0],t[1],t[2],t[3])}InitSetBlend(t){this._type=3;const e=this._mat4param;e[0]=t.length;for(let r=0,a=t.length;r=4&&(i=e[3],n=e[4]),6===r&&(o=e[5],_=e[6]),t.blendFuncSeparate(a,s,i,n),t.blendEquationSeparate(o,_)}InitSetViewport(t,e,r,a){this._type=4;const s=this._colorParam;s[0]=t,s[1]=e,s[2]=r,s[3]=a}DoSetViewport(){const t=this._colorParam;this._gl.viewport(t[0],t[1],t[2],t[3])}InitSetProjection(t){this._type=5,mat4.copy(this._mat4param,t)}DoSetProjection(){const t=this._batchState,e=t.renderer._allShaderPrograms,r=t.currentShader,a=this._mat4param;for(let t=0,s=e.length;t=2){const s=e._GetSampler({sampling:a.GetDefaultSampling()});t.currentSampler1!==s&&(r.bindSampler(1,s),t.currentSampler1=s)}else r.activeTexture(r.TEXTURE1),a._WebGL1SetTextureSampling(r,C3.Gfx.RendererBase.SamplingModeToNumber(a.GetDefaultSampling())-1),r.activeTexture(r.TEXTURE0)}e._uPixelSize.IsUsed()&&e._uPixelSize.Update2f(a[0],a[1]),e._uDestStart.IsUsed()&&e._uDestStart.Update2f(a[2],a[3]),e._uDestEnd.IsUsed()&&e._uDestEnd.Update2f(a[4],a[5]),e._uDevicePixelRatio.IsUsed()&&e._uDevicePixelRatio.Update1f(this._indexCount),e._uLayerScale.IsUsed()&&e._uLayerScale.Update1f(a[6]),e._uLayerAngle.IsUsed()&&e._uLayerAngle.Update1f(a[7]),e._uSrcStart.IsUsed()&&e._uSrcStart.Update2f(a[12],a[13]),e._uSrcEnd.IsUsed()&&e._uSrcEnd.Update2f(a[14],a[15]),e._uSrcOriginStart.IsUsed()&&e._uSrcOriginStart.Update2f(i[0],i[1]),e._uSrcOriginEnd.IsUsed()&&e._uSrcOriginEnd.Update2f(i[2],i[3]),e._uLayoutStart.IsUsed()&&e._uLayoutStart.Update2f(s[0],s[1]),e._uLayoutEnd.IsUsed()&&e._uLayoutEnd.Update2f(s[2],s[3]),e._uSeconds.IsUsed()&&e._uSeconds.Update1f(this._startIndex)}InitSetProgramCustomParameters(){this._type=12}DoSetProgramCustomParameters(){const t=this._batchState.currentShader._uCustomParameters,e=this._shaderParams;for(let r=0,a=t.length;r{const e=t.font.GetName();for(const t of allRendererTexts)(t.IsBBCodeEnabled()||C3.equalsNoCase(t.GetFontName(),e))&&(t._SetWordWrapChanged(),t._ClearMeasurementCache())});let didCheckFoundBoundingBoxSupport=!1,supportsFontBoundingBoxMeasurements=!1;C3.Gfx.RendererText=class{#t=1;constructor(t,e){e=Object.assign({},DEFAULT_OPTS,e),this._renderer=t,this._fontName="Arial",this._fontSize=16,this._fontSizeScale=1,this._lineHeight=0,this._isBold=!1,this._isItalic=!1,this._colorStr="black",this._isBBcodeEnabled=!1,this._iconSet=null,this._iconSmoothing=!0,this.onloadfont=null,this._alreadyLoadedFonts=new Set,this._horizontalAlign="left",this._verticalAlign="top",this._text="",this._bbString=null,this._wrappedText=C3.New(C3.WordWrap),this._wrapMode="word",this._textDirection="ltr",this._wordWrapChanged=!1,this._textLayoutChanged=!1,this._drawChanged=!1,this._canvasContentChanged=!1,this._forceRecreateTexture=!1,this._drawMaxCharCount=-1,this._drawCharCount=0,this._cssWidth=0,this._cssHeight=0,this._width=0,this._height=0,this._zoom=1,this._textCanvas=null,this._textContext=null,this._measureContext=null,this._measureContextTop=null,this._lastCanvasWidth=-1,this._lastCanvasHeight=-1,this._lastTextCanvasFont="",this._lastMeasureCanvasFont="",this._lastTextCanvasFillStyle="",this._lastTextCanvasOpacity=1,this._lastTextCanvasLineWidth=1,this._measureTextCallback=t=>this._MeasureText(t),this._measurementCache=new Map,this._measurementCacheIdleTimeout=new C3.IdleTimeout(()=>this._ClearMeasurementCache(!0),2),this._texture=null,this._enableMipMap=!0,this.#t=e.textureAnisotropy,this._rcTex=new C3.Rect,this._scaleFactor=1,this._textureTimeout=new C3.IdleTimeout(()=>{this.ReleaseTexture(),this._SetTextCanvasSize(8,8),this._SetDrawChanged()},e.timeout),this.ontextureupdate=null,this._wasReleased=!1,allRendererTexts.add(this)}Release(){this.onloadfont=null,this._alreadyLoadedFonts.clear(),this._iconSet=null,this._bbString=null,this._textCanvas=null,this._textContext=null,this._measureContext=null,this._measureContextTop=null,this._measureTextCallback=null,this._ClearMeasurementCache(),this._measurementCacheIdleTimeout.Release(),this._textureTimeout.Release(),this.ontextureupdate=null,this.ReleaseTexture(),this._wrappedText.Clear(),this._wrappedText=null,this._renderer=null,this._wasReleased=!0,allRendererTexts.delete(this)}_SetDrawChanged(){this._drawChanged=!0}_SetTextLayoutChanged(){this._SetDrawChanged(),this._textLayoutChanged=!0}_SetWordWrapChanged(){this._SetTextLayoutChanged(),this._wordWrapChanged=!0}SetBBCodeEnabled(t){if(t=!!t,this._isBBcodeEnabled===t)return;this._isBBcodeEnabled=t;const e=this._isBBcodeEnabled?"alphabetic":"top";this._textContext&&(this._textContext.textBaseline=e),this._measureContext&&(this._measureContext.textBaseline=e),this._ClearMeasurementCache(),this._SetWordWrapChanged()}IsBBCodeEnabled(){return this._isBBcodeEnabled}SetIconSet(t){this._iconSet!==t&&(this._iconSet=t,this._wrappedText.SetIconSet(t),this._iconSet&&this._iconSet.IsLoading()&&this._iconSet.LoadContent().then(()=>this._SetDrawChanged()),this._SetWordWrapChanged())}SetIconSmoothing(t){t=!!t,this._iconSmoothing!==t&&(this._iconSmoothing=t,this._SetDrawChanged())}SetFontName(t){t||(t="serif"),this._fontName!==t&&(this._fontName=t,this._ClearMeasurementCache(),this._SetWordWrapChanged())}GetFontName(){return this._fontName}SetFontSize(t){t<.1&&(t=.1),this._fontSize!==t&&(this._fontSize=t,this._ClearMeasurementCache(),this._SetWordWrapChanged())}GetFontSize(){return this._fontSize}SetFontSizeScale(t){this._fontSizeScale!==t&&(this._fontSizeScale=t,this._ClearMeasurementCache(),this._SetWordWrapChanged())}SetLineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this._SetTextLayoutChanged())}GetLineHeight(){return this._lineHeight}SetBold(t){t=!!t,this._isBold!==t&&(this._isBold=t,this._ClearMeasurementCache(),this._SetWordWrapChanged())}IsBold(){return this._isBold}SetItalic(t){t=!!t,this._isItalic!==t&&(this._isItalic=t,this._ClearMeasurementCache(),this._SetWordWrapChanged())}IsItalic(){return this._isItalic}SetDrawMaxCharacterCount(t){t=Math.floor(t),this._drawMaxCharCount!==t&&(this._drawMaxCharCount=t,this._SetDrawChanged())}GetDrawMaxCharacterCount(){return this._drawMaxCharCount}_GetFontString(t,e){let i=[];(this._isBold||e.HasStyleTag("b"))&&i.push("bold"),(this._isItalic||e.HasStyleTag("i"))&&i.push("italic");const s=e.GetStyleTag("size"),a=(s?parseFloat(s.param):this._fontSize)*this._fontSizeScale;t?i.push(a+"pt"):i.push(a*this.GetDrawScale()+"pt");let n=this._fontName;const h=e.GetStyleTag("font");return h&&h.param&&(n=h.param,this.onloadfont&&!this._alreadyLoadedFonts.has(n)&&(this.onloadfont(n),this._alreadyLoadedFonts.add(n))),n&&(GENERIC_FONT_FAMILIES.has(n)?i.push(n):i.push('"'+n+'"')),i.join(" ")}SetColor(t){t instanceof C3.Color&&(t=t.getCssRgb()),this._colorStr!==t&&(this._colorStr=t,this._SetDrawChanged())}SetColorRgb(t,e,i){tempColor.setRgb(t,e,i),this.SetColor(tempColor)}SetHorizontalAlignment(t){if(!VALID_HORIZ_ALIGNMENTS.has(t))throw new Error("invalid horizontal alignment");this._horizontalAlign!==t&&(this._horizontalAlign=t,this._SetTextLayoutChanged())}GetHorizontalAlignment(){return this._horizontalAlign}SetVerticalAlignment(t){if(!VALID_VERT_ALIGNMENTS.has(t))throw new Error("invalid vertical alignment");this._verticalAlign!==t&&(this._verticalAlign=t,this._SetTextLayoutChanged())}GetVerticalAlignment(){return this._verticalAlign}SetWordWrapMode(t){if(!VALID_WORD_WRAP_MODES.has(t))throw new Error("invalid word wrap mode");this._wrapMode!==t&&(this._wrapMode=t,this._ClearMeasurementCache(),this._SetWordWrapChanged())}GetWordWrapMode(){return this._wrapMode}SetTextDirection(t){if(!VALID_TEXT_DIRECTIONS.has(t))throw new Error("invalid text direction");this._textDirection!==t&&(this._textDirection=t,this._textContext&&(this._textContext.direction=this._textDirection),this._measureContext&&(this._measureContext.direction=this._textDirection),this._ClearMeasurementCache(),this._SetWordWrapChanged())}GetTextDirection(){return this._textDirection}SetText(t){this._text!==t&&(this._text=t,this._ClearMeasurementCache(),this._SetWordWrapChanged())}GetText(){return this._text}GetDrawScale(){return this._scaleFactor*this._zoom*self.devicePixelRatio}SetMipMapEnabled(t){t=!!t,this._enableMipMap!==t&&(this._enableMipMap=t,this._forceRecreateTexture=!0)}IsMipMapEnabled(){return this._enableMipMap}SetTextureAnisotropy(t){this.#t!==t&&(this.#t=t,this._forceRecreateTexture=!0)}GetTextureAnisotropy(){return this.#t}SetSize(t,e,i){if(void 0===i&&(i=1),t<=0||t<=0)return;if(this._cssWidth===t&&this._cssHeight===e&&this._zoom===i)return;const s=this._cssWidth;this._cssWidth=t,this._cssHeight=e,this._zoom=i;const a=self.devicePixelRatio;this._width=this._cssWidth*this._zoom*a,this._height=this._cssHeight*this._zoom*a;const n=Math.max(this._width,this._height),h=Math.min(this._renderer.GetMaxTextureSize(),4096);let r=1;n>h&&(r=h/n,this._width=Math.min(this._width*r,h),this._height=Math.min(this._height*r,h)),this._scaleFactor=r,this._cssWidth!==s?this._SetWordWrapChanged():this._SetTextLayoutChanged()}GetWidth(){return this._width}GetHeight(){return this._height}GetZoom(){return this._zoom}GetTextWidth(){return this._UpdateTextMeasurements(),this._wrappedText.GetMaxLineWidth()}GetTextHeight(){return this._UpdateTextMeasurements(),this._wrappedText.GetTotalLineHeight()+this._wrappedText.GetLineCount()*(this._lineHeight+4)-this._lineHeight}GetLengthInGraphemes(){this._UpdateTextMeasurements();let t=0;for(const e of this._wrappedText.GetLines())for(const i of e.fragments())t+=i.GetLength();return t}HitTestFragment(t,e){this._UpdateTextMeasurements();const i=this.GetDrawScale(),s=this._wrappedText.GetLines();for(const a of s){const s=a.GetFontBoundingBoxDescent()*i;if(e>=a.GetPosY()-a.GetHeight()*i+s&&e=e.GetPosX()&&t1e3){let t=0;for(const e of i.keys())if(i.delete(e),t++,t>=10)break}}_MeasureText(t){const e=t.IsText()?t.GetCharacterArray().join(""):" ",i=this._GetFontString(!0,t),s=i+"|"+e,a=this._measurementCache;let n=a.get(s);if(n)return a.delete(s),a.set(s,n),n;this._SetMeasureFontString(i);const h=this._measureContext.measureText(e);let r=0;if(this._isBBcodeEnabled&&this._SupportsFontBoundingBoxMeasurements()){const t=this._measureContextTop.measureText(e);r=h["fontBoundingBoxAscent"]-t["fontBoundingBoxAscent"]}const o=t.GetStyleTag("size"),_=(o?parseFloat(o.param):this._fontSize)*this._fontSizeScale;return n={width:h.width,height:ptToPx(_),fontBoundingBoxAscent:h["fontBoundingBoxAscent"]||0,fontBoundingBoxDescent:h["fontBoundingBoxDescent"]||0,topToAlphabeticDistance:r},this._AddToMeasurementCache(s,n),n}_SetDrawFontString(t){this._lastTextCanvasFont!==t&&(this._lastTextCanvasFont=t,this._textContext.font=t)}_SetDrawCanvasColor(t){this._lastTextCanvasFillStyle!==t&&(this._lastTextCanvasFillStyle=t,this._textContext.fillStyle=t,this._textContext.strokeStyle=t)}_SetDrawCanvasOpacity(t){this._lastTextCanvasOpacity!==t&&(this._lastTextCanvasOpacity=t,this._textContext.globalAlpha=t)}_SetDrawCanvasLineWith(t){this._lastTextCanvasLineWidth!==t&&(this._lastTextCanvasLineWidth=t,this._textContext.lineWidth=t)}_LayoutText(){const t=this.GetDrawScale(),e=(4+this._lineHeight)*t;let i=0;const s=this._wrappedText.GetLines();if(0===s.length)return;for(const t of s){t.SetPosX(NaN),t.SetPosY(NaN);for(const e of t.fragments())e.SetPosX(NaN),e.SetPosY(NaN)}const a=this._isBBcodeEnabled&&this._SupportsFontBoundingBoxMeasurements();let n=s[0].GetHeight()*t;if("center"===this._verticalAlign){const h=s.reduce((i,s)=>i+s.GetHeight()*t+e,0)-e;i=Math.max(this._height/2-h/2,0),a&&(n=s[0].GetTopToAlphabeticDistance()*t)}else if("bottom"===this._verticalAlign){const n=s.reduce((i,s)=>i+s.GetHeight()*t+e,0)-this._lineHeight*t,h=a?s.at(-1).GetFontBoundingBoxDescent()*t:0;i=this._height-n-h-2}for(let a=0,h=s.length;a0&&i>this._height-4*t)break}else if(a>0&&i>=this._height-r)break;o>=0&&this._LayoutTextLine(h,i,t),this._isBBcodeEnabled||(i+=r),i+=e}}_LayoutTextLine(t,e,i){let s=0;"center"===this._horizontalAlign?s=Math.floor((this._width-t.GetWidth()*i)/2):"right"===this._horizontalAlign&&(s=this._width-t.GetWidth()*i),t.SetPosX(s),t.SetPosY(e);for(const a of"ltr"===this._textDirection?t.fragments():t.fragmentsReverse())this._LayoutFragment(a,s,e,i),s+=a.GetWidth()*i}_LayoutFragment(t,e,i,s){const a=t.GetStyleTag("offsetx");e+=a?getOffsetParam(a.param,t.GetHeight())*s:0;const n=t.GetStyleTag("offsety");if(i+=n?getOffsetParam(n.param,t.GetHeight())*s:0,t.IsIcon()){const e=t.GetStyleTag("iconoffsety");i+=e?getOffsetParam(e.param,t.GetHeight())*s:.2*t.GetHeight()*s}t.SetPosX(e),t.SetPosY(i)}_DrawTextToCanvas(){if(!this._drawChanged)return;this._SetTextCanvasSize(Math.max(C3.nextHighestPowerOfTwo(Math.ceil(this._width)),128),Math.max(C3.nextHighestPowerOfTwo(Math.ceil(this._height)),64)),this._textContext.imageSmoothingEnabled=this._iconSmoothing,this._textContext.imageSmoothingQuality="high",this._drawCharCount=0;const t=this.GetDrawScale(),e=this._wrappedText.GetLines();for(const i of e)this._DrawTextLine(i,t);this._drawChanged=!1,this._canvasContentChanged=!0}_DrawTextLine(t,e){const i=t.GetPosX(),s=t.GetPosY();if(Number.isFinite(i)&&Number.isFinite(s))for(const i of"ltr"===this._textDirection?t.fragments():t.fragmentsReverse())this._DrawFragment(i,e,t.GetHeight())}_DrawFragment(t,e,i){const s=this._textContext,a=t.GetPosX(),n=t.GetPosY();if(!Number.isFinite(a)||!Number.isFinite(n))return;const h=i/16;let r=t.GetWidth()*e;const o=t.GetHeight()*e,_=t.GetHeight()/16,l=(4+this._lineHeight)*e;let d=t.IsText()?t.GetCharacterArray():null;if(-1!==this._drawMaxCharCount){if(this._drawCharCount>=this._drawMaxCharCount)return;t.IsText()&&this._drawCharCount+d.length>this._drawMaxCharCount&&(d=d.slice(0,this._drawMaxCharCount-this._drawCharCount),r=this._MeasureText(t).width*e),this._drawCharCount+=t.GetLength()}const x=t.GetStyleTag("background"),C=t.HasStyleTag("u"),u=t.HasStyleTag("s");if(t.IsText()&&C3.IsCharArrayAllWhitespace(d)&&!x&&!C&&!u||t.HasStyleTag("hide"))return;const c=t.GetStyleTag("color"),g=t.GetStyleTag("opacity");this._SetDrawCanvasOpacity(g?parseFloat(g.param)/100:1),x&&(this._SetDrawCanvasColor(x.param),s.fillRect(a,n-o,r,o+l));const S=t.GetStyleTag("linethickness"),T=S?parseFloat(S.param):1,p=t.HasStyleTag("stroke");if(p&&this._SetDrawCanvasLineWith(.5*_*T*this.GetDrawScale()),t.IsText()){const e=d.join("");if(this._SetDrawFontString(this._GetFontString(!1,t)),!p){this._SetDrawCanvasLineWith(.5*_*T*this.GetDrawScale());const i=t.GetStyleTag("outlineback");i&&(this._SetDrawCanvasColor(i.param),this._FillOrStrokeText(!0,e,a,n,r))}if(this._SetDrawCanvasColor(c?c.param:this._colorStr),this._FillOrStrokeText(p,e,a,n,r),!p){this._SetDrawCanvasLineWith(.5*_*T*this.GetDrawScale());const i=t.GetStyleTag("outline");i&&(this._SetDrawCanvasColor(i.param),this._FillOrStrokeText(!0,e,a,n,r))}}else if(t.IsIcon()&&t.GetWidth()>0){const e=t.GetDrawable(this._iconSet);e&&s.drawImage(e,a,n-o,r,o)}if(this._SetDrawCanvasColor(c?c.param:this._colorStr),C&&fillOrStrokeRect(s,p,a,n+e*h,r,e*h*T),u){const t=e*_,i=n-o/4+t/2;s.fillRect(a,i-t*T/2,r,t*T)}}_FillOrStrokeText(t,e,i,s,a){"rtl"===this._textDirection&&(i+=a),t?"Gecko"===C3.Platform.BrowserEngine?this._textContext.strokeText(e,i,s,a):this._textContext.strokeText(e,i,s):"Gecko"===C3.Platform.BrowserEngine?this._textContext.fillText(e,i,s,a):this._textContext.fillText(e,i,s)}_UpdateTexture(){this._renderer.IsContextLost()||(this._texture&&!this._forceRecreateTexture||(this.ReleaseTexture(),this._texture=this._renderer.CreateDynamicTexture(this._textCanvas.width,this._textCanvas.height,{mipMap:this._enableMipMap,mipMapQuality:"high",anisotropy:this.#t,isWebGPUFastUpdate:!this._enableMipMap}),this._forceRecreateTexture=!1),this._renderer.UpdateTexture(this._textCanvas,this._texture),this._rcTex.set(0,0,this._width/this._texture.GetWidth(),this._height/this._texture.GetHeight()),this._canvasContentChanged=!1,this.ontextureupdate&&this.ontextureupdate())}GetTexRect(){return this._rcTex}ReleaseTexture(){this._texture&&(this._renderer.IsContextLost()||this._renderer.DeleteTexture(this._texture),this._texture=null)}static OnContextLost(){for(const t of allRendererTexts)t.ReleaseTexture()}static GetAll(){return allRendererTexts.values()}}; } // ../lib/gfx/webgl/query.js { const C3=self.C3;class WebGLRealTimeElapsedQuery{constructor(e){this._gl=e.GetContext(),this._version=e.GetWebGLVersionNumber(),this._timerExt=e._GetDisjointTimerQueryExtension(),this._query=null,this._isActive=!1,this._hasResult=!1,this._result=0,1===this._version?this._query=this._timerExt["createQueryEXT"]():this._query=this._gl["createQuery"]()}Release(){this._DeleteQueryObject(),this._gl=null,this._timerExt=null,this._hasResult=!1}_DeleteQueryObject(){this._query&&(1===this._version?this._timerExt["deleteQueryEXT"](this._query):this._gl["deleteQuery"](this._query),this._query=null)}BeginTimeElapsed(){if(this._isActive)throw new Error("query already active");1===this._version?this._timerExt["beginQueryEXT"](this._timerExt["TIME_ELAPSED_EXT"],this._query):this._gl["beginQuery"](this._timerExt["TIME_ELAPSED_EXT"],this._query),this._isActive=!0}EndTimeElapsed(){if(!this._isActive)throw new Error("query not active");1===this._version?this._timerExt["endQueryEXT"](this._timerExt["TIME_ELAPSED_EXT"]):this._gl["endQuery"](this._timerExt["TIME_ELAPSED_EXT"]),this._isActive=!1}CheckForResult(){if(!this._query||this._hasResult||this._isActive)return;let e=!1;e=1===this._version?this._timerExt["getQueryObjectEXT"](this._query,this._timerExt["QUERY_RESULT_AVAILABLE_EXT"]):this._gl["getQueryParameter"](this._query,this._gl["QUERY_RESULT_AVAILABLE"]);const t=this._gl.getParameter(this._timerExt["GPU_DISJOINT_EXT"]);e&&!t&&(1===this._version?this._result=this._timerExt["getQueryObjectEXT"](this._query,this._timerExt["QUERY_RESULT_EXT"]):this._result=this._gl["getQueryParameter"](this._query,this._gl["QUERY_RESULT"]),this._result/=1e9,this._hasResult=!0),(e||t)&&this._DeleteQueryObject()}HasResult(){return this._hasResult}GetResult(){if(!this._hasResult)throw new Error("no result available");return this._result}}C3.Gfx.WebGLTimeElapsedQuery=class{constructor(e){this._renderer=e,this._frameNumber=e.GetFrameNumber(),this._isActive=!1,this._parentQuery=null,this._isNested=!1,this._realQuery=null,this._queries=[]}Release(){for(const e of this._queries)e instanceof WebGLRealTimeElapsedQuery&&e.Release();C3.clearArray(this._queries),this._parentQuery=null,this._realQuery=null,this._renderer=null}BeginTimeElapsed(){if(this._isActive)throw new Error("query already active");const e=this._renderer._GetTimeQueryStack();e.length>0?(this._isNested=!0,this._parentQuery=e.at(-1),this._parentQuery._EndReal(),this._parentQuery._queries.push(this)):(this._isNested=!1,this._parentQuery=null),this._isActive=!0,e.push(this),this._StartReal()}EndTimeElapsed(){if(!this._isActive)throw new Error("query not active");if(this._renderer._GetTimeQueryStack().pop()!==this)throw new Error("can only end most nested query");this._isActive=!1,this._EndReal(),this._parentQuery&&(this._parentQuery._StartReal(),this._parentQuery=null)}_StartReal(){this._realQuery=C3.New(WebGLRealTimeElapsedQuery,this._renderer),this._queries.push(this._realQuery),this._realQuery.BeginTimeElapsed()}_EndReal(){this._realQuery.EndTimeElapsed(),this._realQuery=null}CheckForResult(){for(const e of this._queries)e.CheckForResult()}IsNested(){return this._isNested}HasResult(){return this._queries.every(e=>e.HasResult())}GetResult(){return this._queries.reduce((e,t)=>e+t.GetResult(),0)}GetFrameNumber(){return this._frameNumber}}; } // ../lib/gfx/webgl/queryResultBuffer.js { const C3=self.C3;C3.Gfx.WebGLQueryResultBuffer=class{constructor(e,r=1e3){this._renderer=e,this._maxQueries=r,this._buffer=[],this._renderer._AddQueryResultBuffer(this)}Release(){this.Clear(),this._renderer._RemoveQueryResultBuffer(this),this._renderer=null}Clear(){for(const e of this._buffer)e.Release();C3.clearArray(this._buffer)}AddTimeElapsedQuery(){const e=new C3.Gfx.WebGLTimeElapsedQuery(this._renderer);if(this._buffer.push(e),this._buffer.length>this._maxQueries){this._buffer.shift().Release()}return e}CheckForResults(e){for(const r of this._buffer){if(r.GetFrameNumber()>=e)return;if(r.IsNested())return;r.CheckForResult()}}GetFrameRangeResultSum(e,r){if(r<=e)return NaN;let t=0;for(const s of this._buffer){if(s.GetFrameNumber()>=r)break;if(!(s.GetFrameNumber()0&&this._buffer.splice(0,r));t.Release()}}}; } // ../lib/gfx/webgl/meshData.js { const C3=globalThis.C3,assert=globalThis.assert,SIZEOF_F32=4,SIZEOF_F16=2,SIZEOF_U32=4,SIZEOF_U16=2;C3.Gfx.MeshDataWebGL=class extends C3.Gfx.MeshData{#e=null;#t=null;#s=null;#r=null;#i=null;#o=!1;#f=!1;#n=!1;#a=!1;constructor(e,t,s,r){super(e,t,s,r),this.#o=!!r.staticPositions,this.#f=!!r.staticTexCoords,this.#n=!!r.staticColors,this.#a=!!r.staticIndices}CreateGPUResources(){if(super.CreateGPUResources(),this.IsSmall())return;const e=this.GetRenderer(),t=e.GetContext();e.GetWebGLVersionNumber()<2?this.#i=e._GetVAOExtension()["createVertexArrayOES"]():this.#i=t.createVertexArray(),e._BindVAO(this.#i),this.#e=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.#e),t.bufferData(t.ARRAY_BUFFER,this.positions.byteLength,this.#o?t.STATIC_DRAW:t.DYNAMIC_DRAW),t.enableVertexAttribArray(0),t.vertexAttribPointer(0,3,t.FLOAT,!1,0,0),this.#t=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.#t),t.bufferData(t.ARRAY_BUFFER,this.texCoords.byteLength,this.#f?t.STATIC_DRAW:t.DYNAMIC_DRAW),t.enableVertexAttribArray(1),t.vertexAttribPointer(1,2,t.FLOAT,!1,0,0),this.#s=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.#s),t.bufferData(t.ARRAY_BUFFER,this.colors.byteLength,this.#n?t.STATIC_DRAW:t.DYNAMIC_DRAW),t.enableVertexAttribArray(2),t.vertexAttribPointer(2,4,e.IsColorDataF16()?t["HALF_FLOAT"]:t.FLOAT,!1,0,0),this.#r=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.#r),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.indices.byteLength,this.#a?t.STATIC_DRAW:t.DYNAMIC_DRAW),e._BindVAO(null)}WriteGPUData(){const e=this.GetRenderer(),t=e.GetContext();let s=!1,r=this.GetPendingBufferUpdate("positions"),i=r.GetPendingChange();if(i&&(t.bindBuffer(t.ARRAY_BUFFER,this.#e),t.bufferSubData(t.ARRAY_BUFFER,3*i.start*4,this.positions.subarray(3*i.start,3*i.end)),r.Reset()),r=this.GetPendingBufferUpdate("texCoords"),i=r.GetPendingChange(),i&&(t.bindBuffer(t.ARRAY_BUFFER,this.#t),t.bufferSubData(t.ARRAY_BUFFER,2*i.start*4,this.texCoords.subarray(2*i.start,2*i.end)),r.Reset()),r=this.GetPendingBufferUpdate("colors"),i=r.GetPendingChange(),i){const s=e.IsColorDataF16()?2:4;t.bindBuffer(t.ARRAY_BUFFER,this.#s),t.bufferSubData(t.ARRAY_BUFFER,4*i.start*s,this.colors.subarray(4*i.start,4*i.end)),r.Reset()}if(r=this.GetPendingBufferUpdate("indices"),i=r.GetPendingChange(),i){e._BindVAO(this.#i),s=!0;const o=this.IsIndexTypeUint16()?2:4;t.bufferSubData(t.ELEMENT_ARRAY_BUFFER,i.start*o,this.indices.subarray(i.start,i.end)),r.Reset()}return s}_GetVAO(){return this.#i}ReleaseGPUResources(){super.ReleaseGPUResources();const e=this.GetRenderer(),t=e.GetContext();this.#i&&(e.GetWebGLVersionNumber()<2?e._GetVAOExtension()["deleteVertexArrayOES"](this.#i):t.deleteVertexArray(this.#i),this.#i=null),this.#e&&(t.deleteBuffer(this.#e),this.#e=null),this.#t&&(t.deleteBuffer(this.#t),this.#t=null),this.#s&&(t.deleteBuffer(this.#s),this.#s=null),this.#r&&(t.deleteBuffer(this.#r),this.#r=null)}OnContextLost(){this.#e=null,this.#t=null,this.#s=null,this.#r=null,this.#i=null}}; } // ../lib/gfx/webgl/webglRenderer.js { const C3=self.C3,assert=self.assert,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,mat4=glMatrix.mat4,DEFAULT_WEBGLRENDERER_OPTS={powerPreference:"default",enableGpuProfiling:!0,alpha:!1,depth:!1,canSampleDepth:!1,maxWebGLVersion:2,failIfMajorPerformanceCaveat:!1},VALID_POWER_PREFERENCES=new Set(["default","low-power","high-performance"]),MAX_POINTS=8e3,LAST_POINT=7996,defaultTexCoordsQuad=new C3.Quad2D(0,0,1,0,1,1,0,1),tmpProjection=mat4.create(),tmpModelView=mat4.create(),tmpQuad=new C3.Quad2D,tmpRect=new C3.Rect;let loseContextExtension=null;C3.isDebug&&(self.debug_lose_webgl_context=function(){loseContextExtension?loseContextExtension.loseContext():console.warn("WEBGL_lose_context not supported")},self.debug_restore_webgl_context=function(){loseContextExtension?loseContextExtension.restoreContext():console.warn("WEBGL_lose_context not supported")}),C3.Gfx.WebGLRenderer=class extends C3.Gfx.RendererBase{#t=new Set;#e=new C3.Gfx.DynamicMeshData(this);#i=this.#e._GetMeshData();#r=this.#i;#s=null;#a=new Set;#h=!1;#n=0;#o=new Set;#l=-1;#u=0;constructor(t,e){if(super(e),e=Object.assign({},DEFAULT_WEBGLRENDERER_OPTS,e),!VALID_POWER_PREFERENCES.has(e.powerPreference))throw new Error("invalid power preference");const i={"alpha":!!e.alpha,"depth":!1,"antialias":!1,"powerPreference":e.powerPreference,"failIfMajorPerformanceCaveat":!!e.failIfMajorPerformanceCaveat};let r=null,s=0;if(e.maxWebGLVersion>=2&&(r=t.getContext("webgl2",i),s=2),r||(r=t.getContext("webgl",i),s=1),!r)throw new Error("renderer-unavailable (could not get WebGL context)");this._gl=r,this._attribs=r.getContextAttributes(),this._versionString=r.getParameter(r.VERSION),this._version=s,this._viewport=vec4.create(),this._didChangeTransform=!1,this._bbProjectionMatrix=mat4.create(),this._usesDepthBuffer=!!e.depth,this._canSampleDepth=!(!e.depth||!e.canSampleDepth),this._isDepthEnabled=this._usesDepthBuffer,this._isDepthSamplingEnabled=!1,this._depthBuffer=null,this._isAutoSizeDepthBuffer=!0,this._depthBufferWidth=0,this._depthBufferHeight=0,this.#h=this._version>=2&&void 0!==globalThis["Float16Array"],this._pointBuffer=null,this._pointData=new Float32Array(32e3),this._pointPtr=0,this._lastProgram=null,this._spDeviceTransformTextureFill=null,this._batch=[],this._batchPtr=0,this._topOfBatch=0,this._currentRenderTarget=null,this._lastPointZ=0,this._batchState=C3.New(C3.Gfx.BatchState,this),this._lastColor=this.#e.GetDefaultColor(),this._lastTexture0=null,this._lastTexture1=null,this._lastBlendMode=0,this._lastPointTexCoords=new C3.Rect,this._lastScissorRect=C3.New(C3.Rect,0,0,-1,-1),this._coplanarMode=0,this._lastCullFace=0,this._lastFrontFaceWinding=0,this._maxTextureSize=-1,this._minPointSize=0,this._maxPointSize=0,this._unmaskedVendor="(unavailable)",this._unmaskedRenderer="(unavailable)",this._extensions=[],this._isInitialisingAfterContextRestored=!1,this._parallelShaderCompileExt=null,this._anisotropicExt=null,this._conservativeDepthExt=null,this._depthTextureExt=null,this._fragDepthExt=null,this._stdDerivativesExt=null,this._textureLodExt=null,this._blendMinMaxExt=null,this._maxAnisotropy=0,this._isGpuProfilingEnabled=!!e.enableGpuProfiling,this._timerExt=null,this._allQueryResultBuffers=new Set,this._timeQueryStack=[]}IsWebGL(){return!0}async InitState(){super.InitState();const t=this._gl;this._lastColor.setRgba(1,1,1,1),this._lastTexture0=null,this._lastTexture1=null,this._pointPtr=0,C3.clearArray(this._batch),this._batchPtr=0,this._topOfBatch=0,this._lastProgram=null,this._currentRenderTarget=null,this._lastPointTexCoords.set(0,0,1,1),this._lastPointZ=0;const e=this._batchState;e.currentShader=null,e.currentFramebuffer=null,e.currentFramebufferNoDepth=null,e.clearColor.setRgba(0,0,0,0),e.pointTexCoords.set(0,0,1,1),e.currentSampler0=null,e.currentSampler1=null,t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT),t.enable(t.BLEND),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.blendEquationSeparate(t.FUNC_ADD,t.FUNC_ADD),this._lastBlendMode=0,1===this._version?this._blendMinMaxExt=t.getExtension("EXT_blend_minmax"):this._blendMinMaxExt=null,this._InitBlendModes(t),t.cullFace(t.BACK),t.disable(t.CULL_FACE),this._lastCullFace=0,t.frontFace(t.CW),this._lastFrontFaceWinding=0,t.disable(t.STENCIL_TEST),t.disable(t.DITHER),this._usesDepthBuffer?(t.enable(t.DEPTH_TEST),t.depthMask(!0),t.depthFunc(t.LEQUAL)):(t.disable(t.DEPTH_TEST),t.depthMask(!1)),this.GetWebGLVersionNumber()>=2?this.#u=t.getParameter(t["MAX_CLIENT_WAIT_TIMEOUT_WEBGL"]):this.#u=0,this._isDepthEnabled=this._usesDepthBuffer,this._isDepthSamplingEnabled=!1,this.GetWebGLVersionNumber()<2&&(this.#s=t.getExtension("OES_vertex_array_object"),t.getExtension("OES_element_index_uint"),this._fragDepthExt=t.getExtension("EXT_frag_depth"),this._stdDerivativesExt=t.getExtension("OES_standard_derivatives"),this._textureLodExt=t.getExtension("EXT_shader_texture_lod")),this.#e.CreateGPUResources(),this._BindVAO(null);this._pointBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this._pointBuffer),t.bufferData(t.ARRAY_BUFFER,this._pointData.byteLength,t.DYNAMIC_DRAW),t.enableVertexAttribArray(3),t.vertexAttribPointer(3,4,t.FLOAT,!1,0,0),this._BindVAO(this.#i._GetVAO()),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,null),this._maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE);const i=t.getParameter(t.ALIASED_POINT_SIZE_RANGE);this._minPointSize=i[0],this._maxPointSize=i[1],this._maxPointSize>2048&&(this._maxPointSize=2048),this._extensions=t.getSupportedExtensions();const r=t.getExtension("WEBGL_debug_renderer_info");if(r&&(this._unmaskedVendor=t.getParameter(r["UNMASKED_VENDOR_WEBGL"]),this._unmaskedRenderer=t.getParameter(r["UNMASKED_RENDERER_WEBGL"])),this._parallelShaderCompileExt=t.getExtension("KHR_parallel_shader_compile"),this._version>=2&&("Chromium"!==C3.Platform.BrowserEngine||C3.Platform.BrowserVersionNumber>=135)&&(this._conservativeDepthExt=t.getExtension("EXT_conservative_depth")),C3.isDebug&&(loseContextExtension=t.getExtension("WEBGL_lose_context")),this._isGpuProfilingEnabled&&(1===this.GetWebGLVersionNumber()?this._timerExt=t.getExtension("EXT_disjoint_timer_query"):this._timerExt=t.getExtension("EXT_disjoint_timer_query_webgl2")||t.getExtension("EXT_disjoint_timer_query")),this._anisotropicExt=t.getExtension("EXT_texture_filter_anisotropic"),this._anisotropicExt?this._maxAnisotropy=t.getParameter(this._anisotropicExt["MAX_TEXTURE_MAX_ANISOTROPY_EXT"]):this._maxAnisotropy=0,this.GetWebGLVersionNumber()<2&&this._usesDepthBuffer&&this._canSampleDepth&&(this._depthTextureExt=t.getExtension("WEBGL_depth_texture"),!this._depthTextureExt))throw new Error("no depth texture support");const s=C3.Gfx.WebGLShaderProgram,a=s.GetDefaultVertexShaderSource(!1);let h=s.GetTextureFillFragmentShaderSource_WebGL1_NoFragDepth(),n=a,o=s.GetPointFragmentShaderSource_WebGL1_NoFragDepth(),l=s.GetPointVertexShaderSource_WebGL1(),u=s.GetTilemapFragmentShaderSource_WebGL1_NoFragDepth(),_=s.GetDefaultVertexShaderSource(!0),d=!1;this._usesDepthBuffer&&(this.GetWebGLVersionNumber()<2?this._fragDepthExt&&(h=s.GetTextureFillFragmentShaderSource_WebGL1_FragDepthEXT(),o=s.GetPointFragmentShaderSource_WebGL1_FragDepthEXT(),u=s.GetTilemapFragmentShaderSource_WebGL1_FragDepthEXT(),d=!0):(n=s.GetDefaultVertexShaderSource_WebGL2(),h=s.GetTextureFillFragmentShaderSource_WebGL2(this._SupportsConservativeDepth()),o=s.GetPointFragmentShaderSource_WebGL2(this._SupportsConservativeDepth()),l=s.GetPointVertexShaderSource_WebGL2(),u=s.GetTilemapFragmentShaderSource_WebGL2(this._SupportsConservativeDepth()),_=s.GetDefaultVertexShaderSource_WebGL2(!0)));const c=s.GetTileRandomizationFragmentShaderSource(this.GetWebGLVersionNumber(),d,this._stdDerivativesExt&&this._textureLodExt,this._SupportsConservativeDepth()),p=this.GetWebGLVersionNumber()>=2?s.GetDefaultVertexShaderSource_WebGL2():a,f=[[h,n,""],[h,n,""],[o,l,""],[s.GetColorFillFragmentShaderSource(),a,""],[s.GetLinearGradientFillFragmentShaderSource(),a,""],[s.GetPenumbraFillFragmentShaderSource(),a,""],[s.GetHardEllipseFillFragmentShaderSource(),a,""],[s.GetHardEllipseOutlineFragmentShaderSource(),a,""],[s.GetSmoothEllipseFillFragmentShaderSource(),a,""],[s.GetSmoothEllipseOutlineFragmentShaderSource(),a,""],[s.GetSmoothLineFillFragmentShaderSource(),a,""],[u,_,""],[c,p,""]],E=await Promise.all(f.map(t=>this.CreateShaderProgram({src:t[0],vertexSrc:t[1],name:t[2]})));this._spTextureFill=E[0],this._spDeviceTransformTextureFill=E[1],this._spPoints=E[2],this._spColorFill=E[3],this._spLinearGradientFill=E[4],this._spPenumbraFill=E[5],this._spHardEllipseFill=E[6],this._spHardEllipseOutline=E[7],this._spSmoothEllipseFill=E[8],this._spSmoothEllipseOutline=E[9],this._spSmoothLineFill=E[10],this._spTilemapFill=E[11],this._spTileRandomization=E[12],this.SetTextureFillMode()}async CreateShaderProgram(t){const e=await C3.Gfx.WebGLShaderProgram.Create(this,t);return this._AddShaderProgram(e),e}ResetLastProgram(){this._lastProgram=null}SetSize(t,e,i){if(this._width===t&&this._height===e&&!i)return;this.EndBatch();const r=this._gl,s=this._batchState;this._width=t,this._height=e,this._SetViewport(0,0,t,e),this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,t/e),this.SetProjectionMatrix(this._bbProjectionMatrix),this._spDeviceTransformTextureFill&&(r.useProgram(this._spDeviceTransformTextureFill.GetShaderProgram()),this._spDeviceTransformTextureFill._UpdateDeviceTransformUniforms(this._matP),this._lastProgram=this._spDeviceTransformTextureFill,this._batchState.currentShader=this._spDeviceTransformTextureFill),r.bindTexture(r.TEXTURE_2D,null),r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,null),r.activeTexture(r.TEXTURE0),this._lastTexture0=null,this._lastTexture1=null,this._usesDepthBuffer&&this._isAutoSizeDepthBuffer&&this._SetDepthBufferSize(this._width,this._height),this._currentRenderTarget&&this._currentRenderTarget._Resize(this._width,this._height),r.bindFramebuffer(r.FRAMEBUFFER,null),this._currentRenderTarget=null,s.currentFramebuffer=null,s.currentFramebufferNoDepth=null}_SetDepthBufferSize(t,e){const i=this._gl;this._depthBuffer&&this._depthBufferWidth===t&&this._depthBufferHeight===e||(this._canSampleDepth?(this._depthBuffer&&i.deleteTexture(this._depthBuffer),this._depthBuffer=i.createTexture(),i.bindTexture(i.TEXTURE_2D,this._depthBuffer),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),this.GetWebGLVersionNumber()>=2?i.texImage2D(i.TEXTURE_2D,0,i.DEPTH24_STENCIL8,t,e,0,i.DEPTH_STENCIL,i.UNSIGNED_INT_24_8,null):this._depthTextureExt&&i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_STENCIL,t,e,0,i.DEPTH_STENCIL,this._depthTextureExt["UNSIGNED_INT_24_8_WEBGL"],null),i.bindTexture(i.TEXTURE_2D,null)):(this._depthBuffer&&i.deleteRenderbuffer(this._depthBuffer),this._depthBuffer=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,this._depthBuffer),i.renderbufferStorage(i.RENDERBUFFER,this._version>=2?i.DEPTH24_STENCIL8:i.DEPTH_STENCIL,t,e),i.bindRenderbuffer(i.RENDERBUFFER,null)),this._depthBufferWidth=t,this._depthBufferHeight=e)}SetFixedSizeDepthBuffer(t,e){this._usesDepthBuffer&&(this._isAutoSizeDepthBuffer=!1,this._SetDepthBufferSize(t,e))}SetAutoSizeDepthBuffer(){this._usesDepthBuffer&&(this._isAutoSizeDepthBuffer=!0,this._SetDepthBufferSize(this._width,this._height))}_SetViewport(t,e,i,r){const s=this._viewport;if(s[0]===t&&s[1]===e&&s[2]===i&&s[3]===r)return;this.PushBatch().InitSetViewport(t,e,i,r),vec4.set(s,t,e,i,r),this._topOfBatch=0}SetFovY(t){super.SetFovY(t),this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,this._width/this._height)}SetNearZ(t){super.SetNearZ(t),this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,this._width/this._height)}SetFarZ(t){super.SetFarZ(t),this.CalculatePerspectiveMatrix(this._bbProjectionMatrix,this._width/this._height)}SetProjectionMatrix(t){if(mat4.exactEquals(this._matP,t))return;this.PushBatch().InitSetProjection(t),mat4.copy(this._matP,t),this._topOfBatch=0,this._didChangeTransform=!0}SetDefaultRenderTargetProjectionState(){let t,e,i;const r=this._currentRenderTarget;null===r?(t=this._bbProjectionMatrix,e=this.GetWidth(),i=this.GetHeight()):(t=r.GetProjectionMatrix(),e=r.GetWidth(),i=r.GetHeight()),this.SetProjectionMatrix(t),this._SetViewport(0,0,e,i)}SetModelViewMatrix(t){if(mat4.exactEquals(this._matMV,t))return;this.PushBatch().InitSetModelView(t),mat4.copy(this._matMV,t),this._topOfBatch=0,this._didChangeTransform=!0}ResetDidChangeTransformFlag(){this._didChangeTransform=!1}DidChangeTransform(){return this._didChangeTransform}GetBatchState(){return this._batchState}PushBatch(){const t=this._batch;return this._batchPtr===t.length&&t.push(new C3.Gfx.WebGLBatchJob(this._batchState)),t[this._batchPtr++]}EndBatch(){0!==this._batchPtr&&(this.IsContextLost()||(this._WriteBuffers(),this._ExecuteBatch(),this._batchPtr=0,this._pointPtr=0,this._topOfBatch=0))}_WriteBuffers(){const t=this._gl;this.#e.WriteGPUData(),this._pointPtr>0&&(t.bindBuffer(t.ARRAY_BUFFER,this._pointBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this._pointData.subarray(0,this._pointPtr)));const e=this._GetCurrentBoundVAO();let i=!1;for(const t of this.#a)t!==this.#i&&t.WriteGPUData()&&(i=!0);this.#a.clear(),i&&this._BindVAO(e)}_ExecuteBatch(){const t=this._batch;for(let e=0,i=this._batchPtr;e=7996&&this.EndBatch();let s=this._pointPtr;const a=this._baseZ+this._currentZ;if(2===this._topOfBatch&&this._lastPointZ===a)this._batch[this._batchPtr-1]._indexCount++;else{this.PushBatch().InitPoints(s,a,this._lastColor),this._topOfBatch=2,this._lastPointZ=a}const h=this._pointData;h[s++]=t,h[s++]=e,h[s++]=i,h[s++]=r,this._pointPtr=s}CreateMeshData(t,e,i){const r=new C3.Gfx.MeshDataWebGL(this,t,e,i);return this.#t.add(r),r}_ReleaseMeshData(t){this.EndBatch(),this.#t.delete(t)}DrawMesh(t,e,i,r){const s=C3.Gfx.DynamicMeshData.GetMaxVertices(),a=C3.Gfx.DynamicMeshData.GetMaxIndices();if(t.length%3!=0)throw new Error("vertex buffer length not multiple of 3");if(t.length>3*s)throw new Error(`too many vertices (${t.length/3}, limit ${s})`);if(i.length%3!=0)throw new Error("index buffer length not multiple of 3");if(i.length>a)throw new Error(`too many indices (${i.length}, limit ${a})`);this.#_(t.length,i.length),this.#e.WriteMesh(t,e,i,r)}DrawMeshData(t,e=0,i=t.GetIndexCount()){if(t.IsSmall())if(0===e&&i===t.GetIndexCount())this.#_(t.GetVertexCount(),t.GetIndexCount()),this.#e.WriteMesh(t.positions,t.texCoords,t.indices,t.colors);else{const{minIndex:r,maxIndex:s}=C3.Gfx.DynamicMeshData.CalculatePartialIndexRange(t.indices,e,i),a=r,h=s+1;this.#_(h-a,i),this.#e.WriteMesh(t.positions.subarray(3*a,3*h),t.texCoords.subarray(2*a,2*h),t.indices.subarray(e,e+i),t.colors.subarray(4*a,4*h),r)}else{this.#c(t),this.#a.add(t);const r=t.IsIndexTypeUint16()?2:4;this.PushBatch().InitDraw(e*r,i),this._topOfBatch=0}}#d(){this.#c(this.#i)}#c(t){if(this.#r===t)return;this.PushBatch().InitSetCurrentMeshData(t),this.#r=t,this._topOfBatch=0}_GetCurrentMeshData(){return this.#r}_BindVAO(t){this.GetWebGLVersionNumber()<2?this.#s["bindVertexArrayOES"](t):this._gl.bindVertexArray(t)}_GetCurrentBoundVAO(){const t=this._gl;return this.GetWebGLVersionNumber()<2?t.getParameter(this.#s["VERTEX_ARRAY_BINDING_OES"]):t.getParameter(t.VERTEX_ARRAY_BINDING)}SetProgram(t){if(this._lastProgram===t)return;this.PushBatch().InitSetProgram(t),this._lastProgram=t,this._topOfBatch=0,this._currentStateGroup=null}GetProgram(){return this._lastProgram}SetDeviceTransformTextureFillMode(){this.SetProgram(this._spDeviceTransformTextureFill)}SetGradientColor(t){this.PushBatch().InitSetGradientColor(t),this._topOfBatch=0}SetEllipseParams(t,e,i=1){this.PushBatch().InitSetEllipseParams(t,e,i),this._topOfBatch=0}SetTilemapInfo(t,e,i,r,s,a,h){if(this._lastProgram!==this._spTilemapFill)throw new Error("must set tilemap fill mode first");this.PushBatch().InitSetTilemapInfo(t,e,i,r,s,a,h),this._topOfBatch=0}SetTileRandomizationInfo(t,e,i,r,s,a,h){if(this._lastProgram!==this._spTileRandomization)throw new Error("must set tile randomization mode first");this.PushBatch().InitSetTileRandomizationInfo(t,e,i,r,s,a,h),this._topOfBatch=0}SetProgramParameters(t,e,i,r,s,a,h,n,o,l,u){const _=this._lastProgram;if(u%=10800,!_._hasAnyOptionalUniforms||_.AreOptionalUniformsAlreadySetInBatch(e,i,r,s,a,h,n,o,l,u))return;const d=this.PushBatch();d.InitSetProgramParameters(),_.SetOptionalUniformsInBatch(e,i,r,s,a,h,n,o,l,u);const c=d._mat4param;c[0]=a,c[1]=h,e.writeToTypedArray(c,2),c[6]=o,c[7]=l,i.writeToTypedArray(c,12);const p=d._colorParam;s.writeToTypedArray(p,0);const f=p[1];p[1]=p[3],p[3]=f,r.writeToTypedArray(d._srcOriginRect,0),d._startIndex=u,d._indexCount=n,_._uSamplerBack.IsUsed()?d._texParam=t?t.GetTexture():null:d._texParam=null,this._topOfBatch=0}SetProgramCustomParameters(t){const e=this._lastProgram;if(0===t.length||e.AreCustomParametersAlreadySetInBatch(t))return;const i=this.PushBatch();i.InitSetProgramCustomParameters(),e.SetCustomParametersInBatch(t),C3.shallowAssignArray(i._shaderParams,t),this._topOfBatch=0}ClearRgba(t,e,i,r){this.PushBatch().InitClearSurface2(t,e,i,r),this._topOfBatch=0}Clear(t){this.PushBatch().InitClearSurface(t),this._topOfBatch=0}Start(){}Finish(){super.Finish(),this._gl.flush()}ClearDepth(){if(!this._usesDepthBuffer||!this._currentRenderTarget||!this._currentRenderTarget.HasDepthBuffer())return;this.PushBatch().InitClearDepth(this._isDepthEnabled),this._topOfBatch=0}SetDepthEnabled(t){if(t=!!t,this._isDepthEnabled===t)return;if(!this._usesDepthBuffer)return;this._isDepthEnabled=t;this.PushBatch().InitSetDepthEnabled(t),this._topOfBatch=0}IsDepthEnabled(){return this._isDepthEnabled}_GetDepthBuffer(){return this._depthBuffer}_CanSampleDepth(){return this._canSampleDepth}SetDepthSamplingEnabled(t){if(t=!!t,!this._canSampleDepth)return;if(this._isDepthSamplingEnabled===t)return;if(t&&this.IsDepthEnabled())throw new Error("depth still enabled");this._isDepthSamplingEnabled=t;this.PushBatch().InitSetDepthSamplingEnabled(t),this._topOfBatch=0}SetScissorRect(t,e,i,r,s=0){if(t=Math.floor(t),e=Math.floor(e),i=Math.floor(i),r=Math.floor(r),this._lastScissorRect.equalsWH(t,e,i,r))return;this._lastScissorRect.setWH(t,e,i,r);e=(s||this.GetRenderTargetSize(this.GetRenderTarget())[1])-e-r;this.PushBatch().InitSetScissor(!0,t,e,i,r),this._topOfBatch=0}RemoveScissorRect(){if(-1===this._lastScissorRect.getRight())return;this._lastScissorRect.set(0,0,-1,-1);this.PushBatch().InitSetScissor(!1,0,0,0,0),this._topOfBatch=0}CheckForQueryResults(){for(const t of this._allQueryResultBuffers)t.CheckForResults(this._frameNumber)}IsContextLost(){return!this._gl||this._gl.isContextLost()||this._isInitialisingAfterContextRestored}OnContextLost(){super.OnDeviceOrContextLost(),C3.Gfx.WebGLRendererTexture.OnContextLost(),C3.Gfx.WebGLRenderTarget.OnContextLost(),C3.Gfx.RendererText.OnContextLost();for(const t of this._allQueryResultBuffers)t.Clear();this.#e.OnContextLost();for(const t of this.#t)t!==this.#i&&t.OnContextLost();this._extensions=[],this.#s=null,this._timerExt=null,this._parallelShaderCompileExt=null,this._conservativeDepthExt=null,this._anisotropicExt=null,this._depthTextureExt=null,this._fragDepthExt=null,this._stdDerivativesExt=null,this._textureLodExt=null,this._maxAnisotropy=0,this._unmaskedVendor="(unavailable)",this._unmaskedRenderer="(unavailable)",this._lastProgram=null,this._spDeviceTransformTextureFill=null,this._depthBuffer=null;for(const t of this._stateGroups.values())t.OnContextLost()}async OnContextRestored(){this._isInitialisingAfterContextRestored=!0,await this.InitState(),this._isInitialisingAfterContextRestored=!1;for(const t of this._stateGroups.values())t.OnContextRestored(this);for(const t of this.#t)t!==this.#i&&t.OnContextRestored();this.SetSize(this._width,this._height,!0)}CreateStaticTexture(t,e){if(this.IsContextLost())throw new Error("context lost");this.EndBatch();const i=C3.New(C3.Gfx.WebGLRendererTexture,this);return i._CreateStatic(t,e),i}async CreateStaticTextureAsync(t,e){if(this.IsContextLost())throw new Error("context lost");if(e=Object.assign({},e),C3.Supports.ImageBitmapOptions){let i=await createImageBitmap(t,{"premultiplyAlpha":"premultiply"});const r=e.wrapX&&"clamp-to-edge"!==e.wrapX||e.wrapY&&"clamp-to-edge"!==e.wrapY,s=C3.isPOT(i.width)&&C3.isPOT(i.height);return this.SupportsNPOTTextures()||s||!r?e.premultiplyAlpha=!1:C3.Supports.ImageBitmapOptionsResize?(i=await createImageBitmap(t,{"premultiplyAlpha":"premultiply","resizeWidth":C3.nextHighestPowerOfTwo(i.width),"resizeHeight":C3.nextHighestPowerOfTwo(i.height)}),e.premultiplyAlpha=!1):i=await createImageBitmap(t,{"premultiplyAlpha":"none"}),await C3.Asyncify(()=>this.CreateStaticTexture(i,e))}if(t instanceof Blob){if("undefined"==typeof Image)throw new Error("texture upload variant not supported in worker");const e=await C3.BlobToImage(t);t=e}return await C3.Asyncify(()=>this.CreateStaticTexture(t,e))}CreateDynamicTexture(t,e,i){this.EndBatch();const r=C3.New(C3.Gfx.WebGLRendererTexture,this);return r._CreateDynamic(t,e,i),r}UpdateTexture(t,e,i){this.EndBatch(),e._Update(t,i)}DeleteTexture(t){t&&(t.SubtractReference(),t.GetReferenceCount()>0||(this.EndBatch(),t===this._lastTexture0&&(this._gl.bindTexture(this._gl.TEXTURE_2D,null),this._lastTexture0=null),t===this._lastTexture1&&(this._gl.activeTexture(this._gl.TEXTURE1),this._gl.bindTexture(this._gl.TEXTURE_2D,null),this._gl.activeTexture(this._gl.TEXTURE0),this._lastTexture1=null),t._Delete()))}_GetTextureWrapMode(t){const e=this._gl;if("clamp-to-edge"===t)return e.CLAMP_TO_EDGE;if("repeat"===t)return e.REPEAT;if("mirror-repeat"===t)return e.MIRRORED_REPEAT;throw new Error("invalid wrap mode")}_CreateSampler(t,e,i,r){if(this.GetWebGLVersionNumber()<2)throw new Error("not supported");const s=this._gl,a=s.createSampler();if(s.samplerParameteri(a,s.TEXTURE_WRAP_S,this._GetTextureWrapMode(t)),s.samplerParameteri(a,s.TEXTURE_WRAP_T,this._GetTextureWrapMode(e)),"nearest"===i)s.samplerParameteri(a,s.TEXTURE_MIN_FILTER,s.NEAREST),s.samplerParameteri(a,s.TEXTURE_MAG_FILTER,s.NEAREST);else if("bilinear"===i)s.samplerParameteri(a,s.TEXTURE_MIN_FILTER,s.LINEAR_MIPMAP_NEAREST),s.samplerParameteri(a,s.TEXTURE_MAG_FILTER,s.LINEAR);else if("trilinear"===i){s.samplerParameteri(a,s.TEXTURE_MIN_FILTER,s.LINEAR_MIPMAP_LINEAR),s.samplerParameteri(a,s.TEXTURE_MAG_FILTER,s.LINEAR);const t=this._GetAnisotropicExtension();t&&r>1&&s.samplerParameteri(a,t["TEXTURE_MAX_ANISOTROPY_EXT"],Math.min(r,this._GetMaxAnisotropy()))}return a}SetTexturesAnisotropy(t,e){e||(e=C3.Gfx.WebGLRendererTexture.allTextures()),this.EndBatch();for(const i of e)i._SetAnisotropy(t)}CreateRenderTarget(t){let e=this._width,i=this._height,r=!0;if(t&&("number"==typeof t.width&&(e=Math.floor(t.width),r=!1),"number"==typeof t.height&&(i=Math.floor(t.height),r=!1)),e<=0||i<=0)throw new Error("invalid size");this.EndBatch();const s=C3.New(C3.Gfx.WebGLRenderTarget,this);return s._Create(e,i,Object.assign({isDefaultSize:r},t)),this._currentRenderTarget=null,this._batchState.currentFramebuffer=null,this._batchState.currentFramebufferNoDepth=null,s}SetRenderTarget(t,e=!0){if(t===this._currentRenderTarget)return;t&&t.IsDefaultSize()&&t._Resize(this._width,this._height);this.PushBatch().InitSetRenderTarget(t),this._currentRenderTarget=t,this._topOfBatch=0,e&&this.SetDefaultRenderTargetProjectionState(),t&&this._lastTexture0===t.GetTexture()&&this.SetTexture(null)}GetRenderTarget(){return this._currentRenderTarget}GetRenderTargetSize(t){return t?[t.GetWidth(),t.GetHeight()]:[this._width,this._height]}CopyRenderTarget(t,e="stretch"){if(this._version<2||this._currentRenderTarget&&this._currentRenderTarget.GetMultisampling()>0)this.SetCopyBlend(),this.ResetColor(),this.DrawRenderTarget(t,e);else{this.PushBatch().InitBlitFramebuffer(t,this._currentRenderTarget,e),this._topOfBatch=0}}DrawRenderTarget(t,e="stretch"){const i=t.GetTexture();if(!i)throw new Error("not a texture-backed render target");this.SetTexture(i),this.FullscreenQuad(e,i)}InvalidateRenderTarget(t){if(this._version<2)return;this.PushBatch().InitInvalidateFramebuffer(t._GetFramebuffer()),this._topOfBatch=0}DeleteRenderTarget(t){this.SetRenderTarget(null),this.EndBatch();const e=t.GetTexture();e===this._lastTexture0&&(this._gl.bindTexture(this._gl.TEXTURE_2D,null),this._lastTexture0=null),e===this._lastTexture1&&(this._gl.activeTexture(this._gl.TEXTURE1),this._gl.bindTexture(this._gl.TEXTURE_2D,null),this._gl.activeTexture(this._gl.TEXTURE0),this._lastTexture1=null),t._Delete()}async ReadBackRenderTargetToImageData(t,e,i){this.EndBatch();const r=this._currentRenderTarget;let s,a,h;t?(s=t.GetWidth(),a=t.GetHeight(),h=t._GetFramebuffer()):(s=this.GetWidth(),a=this.GetHeight(),h=null);let n=0,o=0,l=s,u=a;if(i){n=C3.clamp(Math.floor(i.getLeft()),0,s-1),o=C3.clamp(Math.floor(i.getTop()),0,a-1);let t=i.width();t=0===t?s-n:C3.clamp(Math.floor(t),0,s-n);let e=i.height();e=0===e?a-o:C3.clamp(Math.floor(e),0,a-o),l=t,u=e,o=a-(o+u)}const _=this._gl;_.bindFramebuffer(_.FRAMEBUFFER,h);const d=()=>{_.bindFramebuffer(_.FRAMEBUFFER,null),this._currentRenderTarget=null,this._batchState.currentFramebuffer=null,this._batchState.currentFramebufferNoDepth=null,this.SetRenderTarget(r)};let c;if(!e&&this.GetWebGLVersionNumber()>=2){_.bindFramebuffer(_.READ_FRAMEBUFFER,h);const t=_.createBuffer(),e=l*u*4,i=_["PIXEL_PACK_BUFFER"];_.bindBuffer(i,t),_.bufferData(i,e,_["STREAM_READ"]),_.readPixels(n,o,l,u,_.RGBA,_.UNSIGNED_BYTE,0),_.bindFramebuffer(_.READ_FRAMEBUFFER,null),_.bindBuffer(i,null),d(),await this.WaitForSubmittedWorkDone(),c=new ImageData(l,u),_.bindBuffer(i,t),_["getBufferSubData"](i,0,new Uint8Array(c.data.buffer),0,e),_.bindBuffer(i,null),_.deleteBuffer(t)}else c=new ImageData(l,u),_.readPixels(n,o,l,u,_.RGBA,_.UNSIGNED_BYTE,new Uint8Array(c.data.buffer)),d();return c}CoplanarStartStencilPass(){this.SetDepthEnabled(!0);this.PushBatch().InitCoplanarStartStencilPass(),this._topOfBatch=0,this._coplanarMode=1}CoplanarStartColorPass(t=!1){this.SetDepthEnabled(t);this.PushBatch().InitCoplanarStartColorPass(),this._topOfBatch=0,this._coplanarMode=2}IsCoplanarColorPass(){return 2===this._coplanarMode}CoplanarRestoreStandardRendering(t=!0){this.SetDepthEnabled(t);this.PushBatch().InitCoplanarRestore(),this._topOfBatch=0,this._coplanarMode=0}StartQuery(t){if(!this.SupportsGPUProfiling())return;this.PushBatch().InitStartQuery(t),this._topOfBatch=0}EndQuery(t){if(!this.SupportsGPUProfiling())return;this.PushBatch().InitEndQuery(t),this._topOfBatch=0}async WaitForSubmittedWorkDone(){if(this.GetWebGLVersionNumber()<2)return;const t=this._gl,e=t["fenceSync"](t["SYNC_GPU_COMMANDS_COMPLETE"],0);await this._WaitForObjectReady(()=>{const i=t["clientWaitSync"](e,t["SYNC_FLUSH_COMMANDS_BIT"],Math.min(1e6,this.#u));return i===t["ALREADY_SIGNALED"]||i===t["CONDITION_SATISFIED"]}),t["deleteSync"](e)}_WaitForObjectReady(t){const e=new Promise(e=>this.#o.add({resolve:e,checkFunc:t}));return-1===this.#l&&(this.#l=self.requestAnimationFrame(()=>this.#p())),e}#p(){this.#l=-1,this._CheckPendingPolls(),this.#o.size>0&&(this.#l=self.requestAnimationFrame(()=>this.#p()))}_CheckPendingPolls(){for(const t of this.#o)t.checkFunc()&&(t.resolve(),this.#o.delete(t))}GetEstimatedBackBufferMemoryUsage(){return this._width*this._height*(this._attribs["alpha"]?4:3)}GetEstimatedRenderBufferMemoryUsage(){let t=0;for(const e of C3.Gfx.WebGLRenderTarget.allRenderTargets())e.GetTexture()||(t+=e.GetEstimatedMemoryUsage());return t}GetEstimatedTextureMemoryUsage(){let t=0;for(const e of C3.Gfx.WebGLRendererTexture.allTextures())t+=e.GetEstimatedMemoryUsage();return t}GetWebGLVersionString(){return this._versionString}GetWebGLVersionNumber(){return this._version}IsColorDataF16(){return this.#h}GetDisplayName(){return"webgl"+this.GetWebGLVersionNumber()}SupportsNPOTTextures(){return this.GetWebGLVersionNumber()>=2}GetMaxTextureSize(){return this._maxTextureSize}GetMinPointSize(){return this._minPointSize}GetMaxPointSize(){return this._maxPointSize}GetUnmaskedVendor(){return this._unmaskedVendor}GetUnmaskedRenderer(){return this._unmaskedRenderer}GetWebGLExtensionsAnalyticsString(){if(this.GetWebGLVersionNumber()>=2)return"webgl2";{const t=[];return this._fragDepthExt&&t.push("EXT_frag_depth"),this._stdDerivativesExt&&t.push("OES_standard_derivatives"),this._textureLodExt&&t.push("EXT_shader_texture_lod"),t.length>0?"webgl1:"+t.join(","):"webgl1:none"}}GetExtensions(){return this._extensions}_GetVAOExtension(){return this.#s}SupportsGPUProfiling(){return!!this._timerExt}_GetDisjointTimerQueryExtension(){return this._timerExt}_GetParallelShaderCompileExtension(){return this._parallelShaderCompileExt}_SupportsConservativeDepth(){return!!this._conservativeDepthExt}_GetAnisotropicExtension(){return this._anisotropicExt}_GetMaxAnisotropy(){return this._maxAnisotropy}_AddQueryResultBuffer(t){this._allQueryResultBuffers.add(t)}_RemoveQueryResultBuffer(t){this._allQueryResultBuffers.delete(t)}_GetTimeQueryStack(){return this._timeQueryStack}GetContext(){return this._gl}_InitBlendModes(t){let e=t.FUNC_ADD,i=t.FUNC_ADD;this._version>=2?(e=t.MAX,i=t.MIN):this._blendMinMaxExt&&(e=this._blendMinMaxExt["MAX_EXT"],i=this._blendMinMaxExt["MIN_EXT"]),this._InitBlendModeData([["normal",[t.ONE,t.ONE_MINUS_SRC_ALPHA]],["additive",[t.ONE,t.ONE]],["xor",[t.ONE,t.ONE_MINUS_SRC_ALPHA]],["copy",[t.ONE,t.ZERO]],["destination-over",[t.ONE_MINUS_DST_ALPHA,t.ONE]],["source-in",[t.DST_ALPHA,t.ZERO]],["destination-in",[t.ZERO,t.SRC_ALPHA]],["source-out",[t.ONE_MINUS_DST_ALPHA,t.ZERO]],["destination-out",[t.ZERO,t.ONE_MINUS_SRC_ALPHA]],["source-atop",[t.DST_ALPHA,t.ONE_MINUS_SRC_ALPHA]],["destination-atop",[t.ONE_MINUS_DST_ALPHA,t.SRC_ALPHA]],["lighten",[t.ONE,t.ONE,t.ONE,t.ONE,e,e]],["darken",[t.ONE,t.ONE,t.ONE,t.ONE,i,i]],["multiply",[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA]],["screen",[t.ONE,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_ALPHA]]])}CreateWebGLText(){return this.CreateRendererText()}}; } // ../lib/gfx/webgpu/webgpuRenderer.js { const C3=globalThis.C3,glMatrix=globalThis.glMatrix,vec3=glMatrix.vec3,mat4=glMatrix.mat4,assert=globalThis.assert,GPUBufferUsage=globalThis["GPUBufferUsage"],GPUShaderStage=globalThis["GPUShaderStage"],GPUMapMode=globalThis["GPUMapMode"],GPUTextureUsage=globalThis["GPUTextureUsage"],DEFAULT_WEBGPURENDERER_OPTS={powerPreference:"default",depth:!1,failIfMajorPerformanceCaveat:!1,canSampleBackbuffer:!1,usesBackgroundBlending:!1,canSampleDepth:!1,isMultiTexturingAllowed:!0,forceCompatibilityMode:!1},MAX_POINTS=16384,LAST_POINT_PTR=65520,FLAG_IN_DRAW=1,FLAG_DRAWING_POINTS=2,FLAG_SCISSOR_ENABLED=4,FLAG_SCISSOR_CHANGED=8,FLAG_DRAW_STATE_CHANGED=16,FLAG_BUFFERS_CHANGED=32,FLAG_PIPELINE_CHANGED=64,FLAG_TEX_BINDGROUP_CHANGED=128,FLAG_BACKTEX_BINDGROUP_CHANGED=256,FLAG_DEPTHTEX_BINDGROUP_CHANGED=512,FLAG_TRANSFORM_CHANGED=1024,FLAG_VERTEX_UNIFORM_CHANGED=2048,FLAG_FRAG_UNIFORM_CHANGED=4096,FLAG_FRAG_C3PARAMS_CHANGED=8192,FLAG_BUFFER_BINDGROUP_CHANGED=16384,FLAG_DID_ADD_COMMAND=32768,FLAG_CONTEXT_LOST=65536,FLAG_MULTITEXTURE_ALLOWED=1<<17,FLAG_MULTITEXTURE_ENABLED=1<<18,FLAG_MULTITEXTURE_ACTIVE=1<<19,FLAG_USE_DEPTH_BUFFER=1<<20,FLAG_DEPTH_ENABLED=1<<21,FLAG_RENDERTARGET_HAS_DEPTH=1<<22,FLAG_CLEAR_DEPTH=1<<23,FLAG_COPLANAR_STENCIL_PASS=1<<24,FLAG_COPLANAR_COLOR_PASS=1<<25,FLAG_CLEAR_STENCIL=1<<26,FLAG_AUTOSIZE_DEPTH_BUFFER=1<<27,FLAG_SUPPORTS_TIMESTAMP_QUERY=1<<28,FLAG_SUPPORTS_F16=1<<29,FLAG_COLOR_DATA_F16=1<<30,FLAG_USE_NORMALIZED_COORDS=1,FLAG_DID_CHANGE_TRANSFORM=2,CHANGED_FLAGS_MASK=17392,END_DRAW_FLAGS_MASK=17401,NEW_RENDERPASS_FLAGS=50160,CHANGED_UNIFORM_BUFFER_MASK=15360,SIZEOF_U32=4,SIZEOF_F32=4,defaultTexCoordsQuad=new C3.Quad2D(0,0,1,0,1,1,0,1),tempVec2=C3.New(C3.Vector2),tempRect=C3.New(C3.Rect),tempRect2=C3.New(C3.Rect),tempQuad=C3.New(C3.Quad2D);C3.Gfx.WebGPURenderer=class extends C3.Gfx.RendererBase{#e=null;#t=null;#r=null;#i=null;#a=!1;#s=new Set;#n=new C3.Gfx.DynamicMeshData(this,{texIndices:!0});#u=this.#n._GetMeshData();#h=this.#u;#o=new Set;#l=null;#d=!1;#f=-1;#_=-1;#c=new Set;#p=new Set;#m=0;#g=0;constructor(e){super(e),this.#e=Object.assign({},DEFAULT_WEBGPURENDERER_OPTS,e),this._canvas=null,this._presentCtx=null,this._swapChainFormat="",this._swapChainTexture=null,this._swapChainTexView=null,this._viewportWidth=0,this._viewportHeight=0,this._matTransform=mat4.create(),this._depthBuffer=null,this._nullDepthBuffer=null,this._depthBufferView=null,this._nullDepthBufferView=null,this._depthBufferBindGroup=null,this._nullDepthBufferBindGroup=null,this._depthBufferWidth=0,this._depthBufferHeight=0,this._vertexUniformBuffer=null,this._fragmentUniformBuffer=null,this._fragmentC3ParamsBuffer=null,this._fragmentDefaultCustomParamsBuffer=null,this._pointsIndexBuffer=null,this._pointBuffer=null,this._vertexUniformBufferLayout=C3.Gfx.WebGPUShaderProgram.GetVertexUniformBufferLayout(),this._vertexUniformBufferSize=C3.Gfx.WebGPUShaderProgram.GetVertexUniformBufferSize(),this._vertexUniformArrayBuffer=null,this._vertexUniformf32=null,this._fragUniformBufferLayout=C3.Gfx.WebGPUShaderProgram.GetFragmentUniformBufferLayout(),this._fragUniformBufferSize=C3.Gfx.WebGPUShaderProgram.GetFragmentUniformBufferSize(),this._fragUniformArrayBuffer=null,this._fragUniformf32=null,this._fragC3ParamsLayout=C3.Gfx.WebGPUShaderProgram.GetFragmentC3ParamsBufferLayout(),this._fragC3ParamsSize=C3.Gfx.WebGPUShaderProgram.GetFragmentC3ParamsBufferSize(),this._fragC3ParamsArrayBuffer=null,this._fragC3Paramsf32=null,this._fragC3Paramsu32=null;C3.Gfx.DynamicMeshData.GetMaxVertices();this._pointData=new Float32Array(65536),this._currentMultiTextureIndex=0,this._currentColor=this.#n.GetDefaultColor(),this._pointPtr=0,this._bufferManager=C3.New(C3.Gfx.WebGPUBufferManager,this),this._flags=65536,this._flags2=0,this._drawFirstIndex=0,this._drawIndexCount=0,this._vertexUniformUpdateStart=0,this._vertexUniformUpdateEnd=0,this._fragUniformUpdateStart=0,this._fragUniformUpdateEnd=0,this._fragC3ParamsUpdateStart=0,this._fragC3ParamsUpdateEnd=0,this._scissorRect=C3.New(C3.Rect,0,0,0,0),this._currentColor2=C3.New(C3.Color,1,1,1,1),this._currentPointColor=C3.New(C3.Color,1,1,1,1),this._currentPointTexCoords=C3.New(C3.Rect,0,0,0,0),this._currentVertexZElevation=0,this._textureFormat="",this._bufferBindGroupLayout=null,this._defaultBufferBindGroup=null,this._textureBindGroupLayout=null,this._backTextureBindGroupLayout=null,this._depthTextureBindGroupLayout=null,this._nullTexture=null,this._currentTexture=null,this._currentTextureBindGroup=null,this._currentBackTexture=null,this._currentBackTextureBindGroup=null,this._currentDepthTextureBindGroup=null,this._currentBufferBindGroup=null,this._mipmapGeneratorPipeline=null,this._availableMultiTextures=new Set,this._nonFullMultiTexGroups=new Set,this._maxTextureSize=8192,this._pipelineLayout=null,this._defaultVertexModule=null,this._normVertexModule=null,this._currentProgram=null,this._currentBlendMode=0,this._currentMultisampleCount=0,this._currentCullFace=0,this._currentFrontFaceWinding=0,this._mipmapGeneratorProgram=null,this._spSingleTextureFill=null,this._commandEncoder=null,this._currentRenderPass=null,this._commandBuffers=[],this._backbufferRenderTarget=null,this._currentRenderTarget=null,this._canSampleBackbuffer=!1,this._usesBackgroundBlending=!1,this._canSampleDepth=!1,this.ondevicelost=null,this.ondevicerestored=null,this._InitBlendModes()}IsWebGPU(){return!0}_SetFlag(e,t){t?this._flags|=e:this._flags&=~e}_IsFlagSet(e){return 0!==(this._flags&e)}_SetFlag2(e,t){t?this._flags2|=e:this._flags2&=~e}_IsFlagSet2(e){return 0!==(this._flags2&e)}async Create(e){if(!navigator["gpu"])throw new Error("renderer-unavailable (WebGPU not supported)");const t=this.#e;t.depth&&(this._flags|=1048576),t.isMultiTexturingAllowed&&(this._flags|=131072),this._canSampleBackbuffer=!!t.canSampleBackbuffer,this._usesBackgroundBlending=!!t.usesBackgroundBlending,this._canSampleDepth=!(!t.depth||!t.canSampleDepth),this.#t={"featureLevel":"compatibility"},"default"!==t.powerPreference&&(this.#t["powerPreference"]=t.powerPreference),this._canvas=e,await this.#x()}async#x(){for(this.#i=null,await this._TryGetDeviceOnCurrentAdapter();!this.#i;)this.#r=null,await this._TryGetDeviceOnCurrentAdapter();await this.InitState()}async _TryGetDeviceOnCurrentAdapter(){if(!this.#r){if(this.#r=await navigator["gpu"]["requestAdapter"](this.#t),!this.#r)throw new Error("renderer-unavailable (no WebGPU adapter available)");const e=this.#r["info"];if(this.#e.failIfMajorPerformanceCaveat&&e["isFallbackAdapter"])throw new Error("renderer-unavailable (WebGPU provided fallback adapter)");if("adreno-7xx"===e["architecture"])throw new Error("WebGPU disabled on adreno-7xx devices - see https://issues.chromium.org/issues/329702056");if("intel"===e["vendor"]&&("gen-7"===e["architecture"]||"gen7"===e["architecture"]||"gen-9"===e["architecture"]||"gen9"===e["architecture"]))throw new Error("WebGPU disabled on Intel Gen7 and Gen9 GPUs - see https://issues.chromium.org/issues/462468373");if("img-tec"===e["vendor"]&&("d-series"===e["architecture"]||"rogue"===e["architecture"]))throw new Error("WebGPU disabled on img-tec d-series GPUs - see https://github.com/Scirra/Construct-bugs/issues/8996")}const e=[];this.#r["features"].has("core-features-and-limits")&&!this.#e.forceCompatibilityMode&&e.push("core-features-and-limits"),this.#r["features"].has("timestamp-query")&&e.push("timestamp-query"),this.#r["features"].has("shader-f16")&&e.push("shader-f16");const t={"requiredFeatures":e,"requiredLimits":{"maxTextureDimension2D":this.#r["limits"]["maxTextureDimension2D"]}};if(e.includes("core-features-and-limits")||(t["requiredLimits"]["maxStorageBuffersInVertexStage"]=1),this.#i=await this.#r["requestDevice"](t),!this.#i)return null;this.#a=!this.#i["features"]["has"]("core-features-and-limits"),this._maxTextureSize=this.#i["limits"]["maxTextureDimension2D"],this._SetFlag(268435456,this.#i["features"].has("timestamp-query")),this._SetFlag(536870912,this.#i["features"].has("shader-f16")),this._SetFlag(1073741824,this._IsFlagSet(536870912)&&void 0!==globalThis["Float16Array"]),this.#i["lost"].then(e=>this._OnDeviceLost(e)),this._SetFlag(65536,!1)}async _OnDeviceLost(e){console.log("[WebGPU] Device lost: ",e),super.OnDeviceOrContextLost(),this._bufferManager.OnContextLost(),C3.Gfx.WebGPURendererTexture.OnContextLost(),C3.Gfx.WebGPURenderTarget.OnContextLost(),C3.Gfx.RendererText.OnContextLost(),this.#n.OnContextLost();for(const e of this.#s)e!==this.#u&&e.OnContextLost();this._swapChainFormat="",this._swapChainTexture=null,this._swapChainTexView=null,this._depthBuffer=null,this._depthBufferView=null,this._nullDepthBuffer=null,this._nullDepthBufferView=null,this._depthBufferBindGroup=null,this._nullDepthBufferBindGroup=null,this._pointsIndexBuffer=null,this._pointBuffer=null,this._vertexUniformBuffer=null,this._fragmentUniformBuffer=null,this._fragmentC3ParamsBuffer=null,this._fragmentDefaultCustomParamsBuffer=null,this._defaultBufferBindGroup=null,this._bufferBindGroupLayout=null,this._currentBufferBindGroup=null,this._textureBindGroupLayout=null,this._backTextureBindGroupLayout=null,this._depthTextureBindGroupLayout=null,this._pipelineLayout=null,this._currentProgram=null,this._nullTexture=null,this._currentTexture=null,this._currentTextureBindGroup=null,this._currentBackTexture=null,this._currentBackTextureBindGroup=null,this._currentDepthTextureBindGroup=null,this._defaultVertexModule=null,this._normVertexModule=null,this._backbufferRenderTarget=null,this._currentRenderTarget=null,this._mipmapGeneratorPipeline=null,this.#l=null,this._mipmapGeneratorProgram=null,this._spSingleTextureFill=null,this._availableMultiTextures.clear(),this._nonFullMultiTexGroups.clear();for(const e of this._stateGroups.values())e.OnContextLost();this.#i=null,this.#r=null,this._flags|=65536,this.ondevicelost&&this.ondevicelost(),await this.#x();for(const e of this._stateGroups.values())e.OnContextRestored(this);for(const e of this.#s)e!==this.#u&&e.OnContextRestored();this.SetSize(this._width,this._height,!0),this.ondevicerestored&&this.ondevicerestored()}async InitState(){super.InitState();const e=this.#i;this._swapChainFormat=navigator["gpu"]["getPreferredCanvasFormat"](),this._swapChainTexture=null,this._swapChainTexView=null;let t=GPUTextureUsage["RENDER_ATTACHMENT"];this._canSampleBackbuffer&&(t|=GPUTextureUsage["TEXTURE_BINDING"]),this._usesBackgroundBlending&&(t|=GPUTextureUsage["COPY_SRC"]),this._swapChainFormat.startsWith("rgba8")||this._swapChainFormat.startsWith("bgra8")?this._textureFormat=this._swapChainFormat:this._textureFormat="rgba8unorm",this._flags&=1880227840,this._flags|=15360,this._flags2=0,this.SupportsGPUProfiling()&&(this.#l=new C3.Gfx.WebGPUTimeQuerySet(this)),this._IsFlagSet(1048576)&&(this._flags|=140509184),this._currentBlendMode=0,this._currentCullFace=0,this._currentFrontFaceWinding=0,this._currentMultisampleCount=0,this._currentColor.setRgba(1,1,1,1),this._currentColor2.setRgba(1,1,1,1),this._currentPointColor.setRgba(1,1,1,1),this._vertexUniformArrayBuffer=new ArrayBuffer(this._vertexUniformBufferSize),this._vertexUniformf32=new Float32Array(this._vertexUniformArrayBuffer),this._fragUniformArrayBuffer=new ArrayBuffer(this._fragUniformBufferSize),this._fragUniformf32=new Float32Array(this._fragUniformArrayBuffer),this._fragC3ParamsArrayBuffer=new ArrayBuffer(this._fragC3ParamsSize),this._fragC3Paramsf32=new Float32Array(this._fragC3ParamsArrayBuffer),this._fragC3Paramsu32=new Uint32Array(this._fragC3ParamsArrayBuffer),this.#n.CreateGPUResources(),this._pointsIndexBuffer=e["createBuffer"]({"label":"pointsindexbuffer","size":196608,"usage":GPUBufferUsage["INDEX"],"mappedAtCreation":!0});const r=this._pointsIndexBuffer["getMappedRange"]();this._FillPointsIndexBuffer(r),this._pointsIndexBuffer["unmap"](),this._pointBuffer=e["createBuffer"]({"label":"pointbuffer","size":this._pointData.byteLength,"usage":GPUBufferUsage["VERTEX"]|GPUBufferUsage["STORAGE"]|GPUBufferUsage["COPY_DST"]}),this._bufferBindGroupLayout=e["createBindGroupLayout"]({"label":"bufferbindgrouplayout","entries":[{"binding":0,"visibility":GPUShaderStage["VERTEX"],"buffer":{"type":"uniform","minBindingSize":this._vertexUniformBufferSize}},{"binding":1,"visibility":GPUShaderStage["FRAGMENT"],"buffer":{"type":"uniform","minBindingSize":this._fragUniformBufferSize}},{"binding":3,"visibility":GPUShaderStage["VERTEX"],"buffer":{"type":"read-only-storage","minBindingSize":this._pointData.byteLength}},{"binding":4,"visibility":GPUShaderStage["FRAGMENT"],"buffer":{"type":"uniform","minBindingSize":this._fragC3ParamsSize}},{"binding":5,"visibility":GPUShaderStage["FRAGMENT"],"buffer":{"type":"uniform"}}]});const i=[],a=C3.Gfx.WebGPUMultiTextureGroup.GetMultiTextureLimit();for(let e=0;e","code":s._PreprocessVertexShaderCode(s.GetDefaultVertexShaderSource(u),n)}),this._defaultVertexModule["getCompilationInfo"]().then(e=>s.ReportShaderCompilationInfo("","vertex",e)),this._normVertexModule=e["createShaderModule"]({"label":"","code":s._PreprocessVertexShaderCode(s.GetNormalizedVertexShaderSource(u),n)}),this._normVertexModule["getCompilationInfo"]().then(e=>s.ReportShaderCompilationInfo("","vertex",e));const h=await Promise.all([s.Create(this,{name:"",src:s.GetMultiTextureFillFragmentShaderSource(!1,u),srcFragDepth:s.GetMultiTextureFillFragmentShaderSource(!0,u),vertexSrc:s.GetTextureFillVertexShaderSource(u),normVertexSrc:s.GetNormalizedTextureFillVertexShaderSource(u)}),s.Create(this,{name:"",src:s.GetSingleTextureFillFragmentShaderSource(!1,u),srcFragDepth:s.GetSingleTextureFillFragmentShaderSource(!0,u),vertexSrc:s.GetTextureFillVertexShaderSource(u),normVertexSrc:s.GetNormalizedTextureFillVertexShaderSource(u)}),s.Create(this,{name:"",src:s._GetMipmapGeneratorFragmentSource(),vertexSrc:s._GetMipmapGeneratorVertexSource()}),s.Create(this,{name:"",src:s._GetPointFragmentSource(!1),srcFragDepth:s._GetPointFragmentSource(!0),vertexSrc:s._GetPointVertexSource()}),s.Create(this,{name:"",src:s._GetTilemapFragmentShaderSource(!1),srcFragDepth:s._GetTilemapFragmentShaderSource(!0)}),s.Create(this,{name:"",src:s._GetColorFillFragmentShaderSource()}),s.Create(this,{name:"",src:s._GetLinearGradientFillFragmentShaderSource()}),s.Create(this,{name:"",src:s._GetPenumbraFillFragmentShaderSource()}),s.Create(this,{name:"",src:s._GetHardEllipseFillFragmentShaderSource()}),s.Create(this,{name:"",src:s._GetHardEllipseOutlineFragmentShaderSource()}),s.Create(this,{name:"",src:s._GetSmoothEllipseFillFragmentShaderSource()}),s.Create(this,{name:"",src:s._GetSmoothEllipseOutlineFragmentShaderSource()}),s.Create(this,{name:"",src:s.GetTileRandomizationFragmentShaderSource(!1),srcFragDepth:s.GetTileRandomizationFragmentShaderSource(!0)}),s.Create(this,{name:"",src:s._GetSmoothLineFillFragmentShaderSource()})]);this._spTextureFill=h[0],this._spSingleTextureFill=h[1],this._mipmapGeneratorProgram=h[2],this._spPoints=h[3],this._spTilemapFill=h[4],this._spColorFill=h[5],this._spLinearGradientFill=h[6],this._spPenumbraFill=h[7],this._spHardEllipseFill=h[8],this._spHardEllipseOutline=h[9],this._spSmoothEllipseFill=h[10],this._spSmoothEllipseOutline=h[11],this._spTileRandomization=h[12],this._spSmoothLineFill=h[13];for(const e of h)this._AddShaderProgram(e);131072&this._flags?(this._flags|=786432,this._currentProgram=this._spTextureFill):this._currentProgram=this._spSingleTextureFill,this._mipmapGeneratorPipeline=this._mipmapGeneratorProgram._GetMipmapGeneratorPipeline(),this._vertexUniformBuffer=e["createBuffer"]({"label":"vertexuniformbuffer","size":this._vertexUniformBufferSize,"usage":GPUBufferUsage["UNIFORM"]|GPUBufferUsage["COPY_DST"]}),this._fragmentUniformBuffer=e["createBuffer"]({"label":"fragmentuniformbuffer","size":this._fragUniformBufferSize,"usage":GPUBufferUsage["UNIFORM"]|GPUBufferUsage["COPY_DST"]}),this._fragmentC3ParamsBuffer=e["createBuffer"]({"label":"fragmentc3paramsuniformbuffer","size":this._fragC3ParamsSize,"usage":GPUBufferUsage["UNIFORM"]|GPUBufferUsage["COPY_DST"]}),this._fragmentDefaultCustomParamsBuffer=e["createBuffer"]({"label":"fragmentdefaultcustomparamsbuffer","size":16,"usage":GPUBufferUsage["UNIFORM"]|GPUBufferUsage["COPY_DST"]}),this._vertexUniformUpdateStart=0,this._vertexUniformUpdateEnd=this._vertexUniformBufferSize,this._UpdateTransformUniform(),this._UpdatePointTexCoordsUniform(),this._UpdateZElevationUniform(),this._fragUniformUpdateStart=0,this._fragUniformUpdateEnd=this._fragUniformBufferSize,this._UpdateColor2Uniform(),this._UpdatePointColorUniform(),this._defaultBufferBindGroup=this._CreateBufferBindGroup(this._fragmentDefaultCustomParamsBuffer),this._currentBufferBindGroup=this._defaultBufferBindGroup;const o=C3.CreateCanvas(32,32);o.getContext("2d"),this._nullTexture=await this.CreateStaticTextureAsync(o),this._currentTexture=null,this._currentTextureBindGroup=this._nullTexture._GetOwnTextureBindGroup(0),this._currentMultiTextureIndex=0,this._currentBackTexture=null,this._currentBackTextureBindGroup=this._nullTexture._GetBackTextureBindGroup(0),this._nullTexture._DisableMultiTexture(),this._nullDepthBuffer=this.#i["createTexture"]({"label":"nulldepthbuffer","size":[8,8,1],"format":this._GetDepthBufferFormat(),"usage":GPUTextureUsage["TEXTURE_BINDING"]}),this._nullDepthBufferView=this._nullDepthBuffer["createView"]({"label":"nulldepthbufferview","aspect":"depth-only"}),this._nullDepthBufferBindGroup=this.#i["createBindGroup"]({"label":"nulldepthbufferbindgroup","layout":this._depthTextureBindGroupLayout,"entries":[{"binding":0,"resource":this._GetSampler({sampling:"nearest"})},{"binding":1,"resource":this._nullDepthBufferView}]}),this._currentDepthTextureBindGroup=this._nullDepthBufferBindGroup,this._backbufferRenderTarget=C3.New(C3.Gfx.WebGPURenderTarget,this,!0),this._backbufferRenderTarget.GetTexture()._BackbufferTextureSetProperties(t,this._swapChainFormat),this._currentRenderTarget=this._backbufferRenderTarget,this._CreateCommandEncoder(),this._presentCtx||(this._presentCtx=this._canvas.getContext("webgpu")),this._presentCtx["configure"]({"device":e,"format":this._swapChainFormat,"usage":t,"alphaMode":"premultiplied"})}_CreateBufferBindGroup(e){return this.#i["createBindGroup"]({"layout":this._bufferBindGroupLayout,"entries":[{"binding":0,"resource":{"buffer":this._vertexUniformBuffer}},{"binding":1,"resource":{"buffer":this._fragmentUniformBuffer}},{"binding":3,"resource":{"buffer":this._pointBuffer}},{"binding":4,"resource":{"buffer":this._fragmentC3ParamsBuffer}},{"binding":5,"resource":{"buffer":e}}]})}_FillPointsIndexBuffer(e){const t=new Uint16Array(e);let r=0,i=t.length,a=0;for(;r1&&(a["maxAnisotropy"]=i)),this.#i["createSampler"](a)}SetTexturesAnisotropy(e,t){t||(t=C3.Gfx.WebGPURendererTexture.allTextures()),this.EndBatch();for(const r of t)r._SetAnisotropy(e);for(const e of C3.Gfx.WebGPUMultiTextureGroup.all())e.DeleteBindGroups()}_GetMipmapGeneratorPipeline(){return this._mipmapGeneratorPipeline}CreateDynamicTexture(e,t,r){this.EndBatch();const i=C3.New(C3.Gfx.WebGPURendererTexture,this);return i._CreateDynamic(e,t,r),i}UpdateTexture(e,t,r){return t._Update(e,r)}DeleteTexture(e){e&&(e.SubtractReference(),e.GetReferenceCount()>0||(this.IsContextLost()||(this.EndBatch(),this._currentTexture===e&&this.SetTexture(null),this._currentBackTexture===e&&this.SetBackTexture(null)),e._Delete()))}_SetMultiTextureAvailable(e,t){this.IsContextLost()||(t?this._availableMultiTextures.add(e):this._availableMultiTextures.delete(e))}_SetMultiTextureGroupNonFull(e,t){t?this._nonFullMultiTexGroups.add(e):this._nonFullMultiTexGroups.delete(e)}_TryCreateMultiTextureGroup(e){const t=[e],r=C3.Gfx.WebGPUMultiTextureGroup.GetMultiTextureLimit();for(const e of this._nonFullMultiTexGroups)e.Release();for(const i of this._availableMultiTextures){if(t.length>=r)break;i!==e&&t.push(i)}t.length<2||C3.New(C3.Gfx.WebGPUMultiTextureGroup,this,t)}Start(e="bilinear"){this._backbufferRenderTarget.SetDefaultSampling(e),this._UpdateSwapChainTexture()}Restart(){this._UpdateSwapChainTexture()}_UpdateSwapChainTexture(){this._swapChainTexture=this._presentCtx["getCurrentTexture"](),this._swapChainTexView=this._swapChainTexture["createView"]({"label":"swapchaintextureview"}),this._backbufferRenderTarget.GetTexture()._BackbufferTextureStartFrame()}Finish(){null===this._currentRenderPass&&this._backbufferRenderTarget._IsAwaitingClear()&&this._BeginRenderPass(),super.Finish(),this._bufferManager.MaybeCollectUnusedBuffers(this._frameNumber),this._backbufferRenderTarget.GetTexture()._BackbufferTextureEndFrame(),this._swapChainTexture=null,this._swapChainTexView=null}_CreateCommandEncoder(){this._commandEncoder=this.#i["createCommandEncoder"](),this._flags&=-32769}StartFrameTiming(e){if(!this.SupportsGPUProfiling())throw new Error("GPU profiling not supported");this.#d=!1,this.#c.clear(),this.#p.clear(),this.#l.SetQueryCount(e)}FinishFrameTiming(){return this.#l.GetResult(new Set([...this.#p]))}StartMeasuringRenderPassTime(e,t){if(this.SupportsGPUProfiling()){if(e<0||t<0||e===t)throw new Error("invalid timestamp index");this._MaybeEndRenderPass(),this.#d=!0,this.#f=e,this.#_=t}}StopMeasuringRenderPassTime(){this.#d&&(this._MaybeEndRenderPass(),this.#d=!1)}#G(e,t){this.#S();const r=this.#n;if(r.CanFit(e,t)){if(1&this._flags)return void(this._drawIndexCount+=t)}else this.EndBatch();null===this._currentRenderPass&&this._BeginRenderPass(),this._flags|=1,this._drawFirstIndex=r.GetIndexPtr(),this._drawIndexCount=t}_MaybeEndDrawBatch(){const e=this._flags,t=this._flags2;if(!(1&e))return;const r=this._currentRenderPass;if(16&e){const t=this._currentRenderTarget;r["setViewport"](0,0,t.GetWidth(),t.GetHeight(),0,1),50331648&e&&r["setStencilReference"](1),4&e&&this._DoSetRenderPassScissorRect(r,this._scissorRect,t)}if(32&e&&(2&e?r["setIndexBuffer"](this._pointsIndexBuffer,"uint16"):this.#h.WebGPUInitRenderPassIndexBuffer(r),this.#h.WebGPUInitRenderPassVertexBuffers(r)),64&e){let i=0;1&t?i=4:16777216&e?i=2:33554432&e?i=3:6291456&~e||(i=1),r["setPipeline"](this._currentProgram.GetRenderPipelineForState(this._currentBlendMode,i,this._currentCullFace,this._currentFrontFaceWinding,this._currentMultisampleCount))}if(16384&e&&r["setBindGroup"](0,this._currentBufferBindGroup),128&e&&r["setBindGroup"](1,this._currentTextureBindGroup),256&e&&r["setBindGroup"](2,this._currentBackTextureBindGroup),512&e&&r["setBindGroup"](3,this._currentDepthTextureBindGroup),8&e){const t=this._currentRenderTarget;4&e?this._DoSetRenderPassScissorRect(r,this._scissorRect,t):r["setScissorRect"](0,0,t.GetWidth(),t.GetHeight())}r["drawIndexed"](this._drawIndexCount,1,this._drawFirstIndex,0,0),this._flags&=-17402}_DoSetRenderPassScissorRect(e,t,r){const i=r.GetWidth(),a=r.GetHeight();let s=C3.clamp(t.getLeft(),0,i),n=C3.clamp(t.getTop(),0,a),u=C3.clamp(t.getRight(),s,i),h=C3.clamp(t.getBottom(),n,a);Number.isNaN(s)&&(s=0),Number.isNaN(n)&&(n=0),Number.isNaN(u)&&(u=i),Number.isNaN(h)&&(h=a),e["setScissorRect"](s,n,u-s,h-n)}_BeginRenderPass(){const e=this._flags;15360&e&&this._WriteUniformBuffers();let t=null;t=16777216&e?this._GetCoplanarStencilRenderPassOpts():33554432&e?this._GetCoplanarColorRenderPassOpts():this._GetStandardRenderPassOpts(),this._currentRenderPass=this._commandEncoder["beginRenderPass"](t),this._flags|=50160}_GetStandardRenderPassOpts(){const e=this._flags,t=this._currentRenderTarget,r={"colorAttachments":[{"view":t._GetTextureView(),"loadOp":t._IsAwaitingClear()?"clear":"load","clearValue":t._GetClearColor().toJSON(),"storeOp":"store"}]};return this._MaybeSetTimestampRenderPassOption(r),t._SetIsAwaitingClear(!1),6291456&~e||(r["depthStencilAttachment"]={"view":this._depthBufferView,"depthLoadOp":8388608&e?"clear":"load","depthClearValue":1,"depthStoreOp":"store","stencilLoadOp":"clear","stencilClearValue":0,"stencilStoreOp":"discard"},this._flags&=-8388609),r}_GetCoplanarStencilRenderPassOpts(){const e=this._flags,t={"colorAttachments":[],"depthStencilAttachment":{"view":this._depthBufferView,"depthLoadOp":8388608&e?"clear":"load","depthClearValue":1,"depthStoreOp":"store","stencilLoadOp":67108864&e?"clear":"load","stencilClearValue":0,"stencilStoreOp":"store"}};return this._MaybeSetTimestampRenderPassOption(t),this._flags&=-75497473,t}_GetCoplanarColorRenderPassOpts(){const e=this._currentRenderTarget,t={"view":e._GetTextureView(),"loadOp":e._IsAwaitingClear()?"clear":"load","clearValue":e._GetClearColor().toJSON(),"storeOp":"store"},r={"view":this._depthBufferView,"depthReadOnly":!0};C3.Platform.IsAppleOS?(r["stencilLoadOp"]="load",r["stencilStoreOp"]="store"):r["stencilReadOnly"]=!0;const i={"colorAttachments":[t],"depthStencilAttachment":r};return this._MaybeSetTimestampRenderPassOption(i),e._SetIsAwaitingClear(!1),i}_MaybeSetTimestampRenderPassOption(e){if(!this.#d)return;const t={"querySet":this.#l._GetQuerySet(),"endOfPassWriteIndex":this.#_};this.#p.add(this.#_),this.#c.has(this.#f)||(t["beginningOfPassWriteIndex"]=this.#f,this.#c.add(this.#f),this.#p.add(this.#f)),e["timestampWrites"]=t}_MaybeDoPendingClearRenderPass(e){if(!e._IsAwaitingClear())return;this._MaybeEndRenderPass();this._commandEncoder["beginRenderPass"]({"colorAttachments":[{"view":e._GetTextureView(),"loadOp":"clear","clearValue":e._GetClearColor().toJSON(),"storeOp":"store"}]})["end"](),this._flags|=32768,e._SetIsAwaitingClear(!1)}_MaybeEndRenderPass(){null!==this._currentRenderPass&&(this._MaybeEndDrawBatch(),this._currentRenderPass["end"](),this._currentRenderPass=null)}EndBatch(e=!1){this._MaybeEndRenderPass(),this.#l&&this.#l.GetQueryCount()>0&&e&&(this.#l.Resolve(this._commandEncoder),this._flags|=32768),32768&this._flags&&(this._commandBuffers.push(this._commandEncoder["finish"]()),this._CreateCommandEncoder()),0!==this._commandBuffers.length&&(this._WriteBuffers(),this.#i["queue"]["submit"](this._commandBuffers),C3.clearArray(this._commandBuffers),this._bufferManager.AfterSubmit())}WaitForSubmittedWorkDone(){return this.#i?this.#i["queue"]["onSubmittedWorkDone"]():Promise.resolve()}_WriteBuffers(){const e=this.#i["queue"],t=!!(131072&this._flags);this.#n.WriteGPUData(t),this._pointPtr>0&&(e["writeBuffer"](this._pointBuffer,0,this._pointData.buffer,0,4*this._pointPtr),this._pointPtr=0);for(const e of this.#o)e!==this.#u&&e.WriteGPUData(t);this.#o.clear()}_UpdateTransformUniform(){this._flags|=1024,this._flags2|=2,this._MarkVertexUniformBufferRangeChanged(this._vertexUniformBufferLayout.transform)}_UpdatePointTexCoordsUniform(){const e=this._vertexUniformBufferLayout.pointTex;this._currentPointTexCoords.writeToTypedArray(this._vertexUniformf32,e.offset/4),this._MarkVertexUniformBufferRangeChanged(e)}_UpdateZElevationUniform(){const e=this._vertexUniformBufferLayout.zElevation;this._vertexUniformf32[e.offset/4]=this._currentVertexZElevation,this._MarkVertexUniformBufferRangeChanged(e)}_MarkVertexUniformBufferRangeChanged(e){const t=e.offset,r=e.end;2048&this._flags?(this._vertexUniformUpdateStart=Math.min(this._vertexUniformUpdateStart,t),this._vertexUniformUpdateEnd=Math.max(this._vertexUniformUpdateEnd,r)):(this._flags|=2048,this._vertexUniformUpdateStart=t,this._vertexUniformUpdateEnd=r,this._MaybeEndRenderPass())}_UpdateColor2Uniform(){this._UpdateFragmentUniformColor(this._currentColor2,this._fragUniformBufferLayout.color2)}_UpdatePointColorUniform(){this._UpdateFragmentUniformColor(this._currentPointColor,this._fragUniformBufferLayout.pointColor)}_UpdateFragmentUniformColor(e,t){e.writeToTypedArray(this._fragUniformf32,t.offset/4),this._MarkFragUniformBufferRangeChanged(t)}_UpdateFragmentUniformVec2(e,t){e.writeToTypedArray(this._fragUniformf32,t.offset/4),this._MarkFragUniformBufferRangeChanged(t)}_MarkFragUniformBufferRangeChanged(e){const t=e.offset,r=e.end;4096&this._flags?(this._fragUniformUpdateStart=Math.min(this._fragUniformUpdateStart,t),this._fragUniformUpdateEnd=Math.max(this._fragUniformUpdateEnd,r)):(this._flags|=4096,this._fragUniformUpdateStart=t,this._fragUniformUpdateEnd=r,this._MaybeEndRenderPass())}_MaybeUpdateFragmentC3ParamsFloat(e,t){this._fragC3Paramsf32[t.offset/4]!==Math.fround(e)&&(this._fragC3Paramsf32[t.offset/4]=e,this._MarkFragC3ParamsRangeChanged(t))}_MaybeUpdateFragmentC3ParamsUint(e,t){this._fragC3Paramsu32[t.offset/4]!==e&&(this._fragC3Paramsu32[t.offset/4]=e,this._MarkFragC3ParamsRangeChanged(t))}_MaybeUpdateFragmentC3ParamsRect(e,t){e.equalsF32Array(this._fragC3Paramsf32,t.offset/4)||(e.writeToTypedArray(this._fragC3Paramsf32,t.offset/4),this._MarkFragC3ParamsRangeChanged(t))}_MarkFragC3ParamsRangeChanged(e){const t=e.offset,r=e.end;8192&this._flags?(this._fragC3ParamsUpdateStart=Math.min(this._fragC3ParamsUpdateStart,t),this._fragC3ParamsUpdateEnd=Math.max(this._fragC3ParamsUpdateEnd,r)):(this._flags|=8192,this._fragC3ParamsUpdateStart=t,this._fragC3ParamsUpdateEnd=r,this._MaybeEndRenderPass())}_WriteUniformBuffers(){const e=this._flags;1024&e&&(mat4.multiply(this._matTransform,this._matP,this._matMV),this._vertexUniformf32.set(this._matTransform,this._vertexUniformBufferLayout.transform.offset/4)),2048&e&&this._bufferManager.UpdateBufferSubData(this._commandEncoder,this._vertexUniformBuffer,this._vertexUniformArrayBuffer,this._vertexUniformUpdateStart,this._vertexUniformUpdateEnd-this._vertexUniformUpdateStart),4096&e&&this._bufferManager.UpdateBufferSubData(this._commandEncoder,this._fragmentUniformBuffer,this._fragUniformArrayBuffer,this._fragUniformUpdateStart,this._fragUniformUpdateEnd-this._fragUniformUpdateStart),8192&e&&this._bufferManager.UpdateBufferSubData(this._commandEncoder,this._fragmentC3ParamsBuffer,this._fragC3ParamsArrayBuffer,this._fragC3ParamsUpdateStart,this._fragC3ParamsUpdateEnd-this._fragC3ParamsUpdateStart),this._flags=-15361&e|32768}CreateRenderTarget(e){let t=this._width,r=this._height,i=!0;if(e&&("number"==typeof e.width&&(t=Math.floor(e.width),i=!1),"number"==typeof e.height&&(r=Math.floor(e.height),i=!1)),t<=0||r<=0)throw new Error("invalid size");this.EndBatch();const a=C3.New(C3.Gfx.WebGPURenderTarget,this);return a._Create(t,r,Object.assign({isDefaultSize:i},e)),a}SetRenderTarget(e,t=!0){null===e&&(e=this._backbufferRenderTarget),this._currentRenderTarget!==e&&(this._MaybeEndRenderPass(),this._currentRenderTarget=e,this._SetFlag(4194304,e.HasDepthBuffer()),e.IsDefaultSize()&&!e.IsBackBuffer()&&e._Resize(this._width,this._height),t&&this.SetDefaultRenderTargetProjectionState(),this._currentTexture===e.GetTexture()&&this.SetTexture(null))}InvalidateRenderTarget(e){}GetRenderTarget(){return this._currentRenderTarget===this._backbufferRenderTarget?null:this._currentRenderTarget}GetRenderTargetSize(e){return null===e?[this._width,this._height]:[e.GetWidth(),e.GetHeight()]}GetBackbufferRenderTarget(){return this._backbufferRenderTarget}DeleteRenderTarget(e){this.EndBatch(),this._currentRenderTarget===e&&this.SetRenderTarget(null);const t=e.GetTexture();this._currentTexture===t&&this.SetTexture(null),this._currentBackTexture===t&&this.SetBackTexture(null),e._Delete()}async ReadBackRenderTargetToImageData(e,t,r){this._MaybeDoPendingClearRenderPass(e),this.EndBatch(),null===e&&(e=this._backbufferRenderTarget);const i=this.#i,a=e.GetWidth(),s=e.GetHeight();let n=0,u=0,h=a,o=s;if(r){n=C3.clamp(Math.floor(r.getLeft()),0,a-1),u=C3.clamp(Math.floor(r.getTop()),0,s-1);let e=r.width();e=0===e?a-n:C3.clamp(Math.floor(e),0,a-n);let t=r.height();t=0===t?s-u:C3.clamp(Math.floor(t),0,s-u),h=e,o=t}const l=i["createCommandEncoder"](),d=e.GetTexture();let f=d._GetTexture(),_=null;"rgba8unorm"===d._GetFormat()?d.CanReadPixels()||C3.NotYetImplemented():(_=this._ConvertTextureFormat(d,"rgba8unorm",l),f=_);const c=4*h,p=256*Math.ceil(c/256),m=i["createBuffer"]({"size":p*o,"usage":GPUBufferUsage["MAP_READ"]|GPUBufferUsage["COPY_DST"]});l["copyTextureToBuffer"]({"texture":f,"origin":[n,u,0]},{"buffer":m,"bytesPerRow":p},[h,o,1]);const g=l["finish"]();i["queue"]["submit"]([g]),_&&_["destroy"](),await m["mapAsync"](self["GPUMapMode"]["READ"]);const x=m["getMappedRange"]().slice(0);let G;if(p===c)G=new ImageData(new Uint8ClampedArray(x),h,o);else{const e=new ArrayBuffer(c*o),t=new Uint8Array(e);for(let e=0;e=2?4:1}SetRenderingToMultisampleCount(e){e=this._ClampToSupportedMultisampleValues(e),this._currentMultisampleCount!==e&&(this._MaybeEndDrawBatch(),this._currentMultisampleCount=e,this._flags|=64)}SetBlendMode(e){e!==this._currentBlendMode&&(this._MaybeEndDrawBatch(),this._currentBlendMode=e,this._currentStateGroup=null,this._flags|=64)}SetNamedBlendMode(e){this.SetBlendMode(this.NamedBlendToNumber(e))}SetAlphaBlend(){this.SetBlendMode(0)}SetCopyBlend(){this.SetBlendMode(3)}SetColorRgba(e,t,r,i){const a=this._currentColor;a.equalsRgba(e,t,r,i)||(a.setRgba(e,t,r,i),this._currentStateGroup=null)}SetOpacity(e){const t=this._currentColor;t.getA()!==e&&(t.setA(e),this._currentStateGroup=null)}GetOpacity(){return this._currentColor.getA()}SetColor(e){const t=this._currentColor;t.equals(e)||(t.set(e),this._currentStateGroup=null)}ResetColor(){this.SetColorRgba(1,1,1,1)}GetColor(){return this._currentColor}SetCullFaceMode(e){e!==this._currentCullFace&&(this._MaybeEndDrawBatch(),this._currentCullFace=e,this._currentStateGroup=null,this._flags|=64)}GetCullFaceMode(){return this._currentCullFace}SetFrontFaceWinding(e){e!==this._currentFrontFaceWinding&&(this._MaybeEndDrawBatch(),this._currentFrontFaceWinding=e,this._currentStateGroup=null,this._flags|=64)}GetFrontFaceWinding(){return this._currentFrontFaceWinding}Rect(e){this.Rect2(e.getLeft(),e.getTop(),e.getRight(),e.getBottom())}Rect2(e,t,r,i){this.Quad2(e,t,r,t,r,i,e,i)}Quad(e){this.Quad4(e,defaultTexCoordsQuad)}Quad2(e,t,r,i,a,s,n,u){this.#G(4,6);const h=this.#n.WriteQuad2(this._baseZ+this._currentZ,e,t,r,i,a,s,n,u);524288&this._flags&&this.#n.WriteTexIndicesForQuad(h,this._currentMultiTextureIndex)}Quad3(e,t){this.#G(4,6);const r=this.#n.WriteQuad3(this._baseZ+this._currentZ,e,t);524288&this._flags&&this.#n.WriteTexIndicesForQuad(r,this._currentMultiTextureIndex)}Quad4(e,t){this.#G(4,6);const r=this.#n.WriteQuad4(this._baseZ+this._currentZ,e,t);524288&this._flags&&this.#n.WriteTexIndicesForQuad(r,this._currentMultiTextureIndex)}Quad5(e,t,r){this.#G(4,6);const i=this.#n.WriteQuad5(this._baseZ+this._currentZ,e,t,r);524288&this._flags&&this.#n.WriteTexIndicesForQuad(i,this._currentMultiTextureIndex)}Quad3D(e,t,r,i,a,s,n,u,h,o,l,d,f){this.#G(4,6);const _=this.#n.WriteQuad3D(this._baseZ+this._currentZ,e,t,r,i,a,s,n,u,h,o,l,d,f);524288&this._flags&&this.#n.WriteTexIndicesForQuad(_,this._currentMultiTextureIndex)}Quad3D2(e,t,r,i,a,s,n,u,h,o,l,d,f){this.#G(4,6);const _=this.#n.WriteQuad3D2(this._baseZ+this._currentZ,e,t,r,i,a,s,n,u,h,o,l,d,f);524288&this._flags&&this.#n.WriteTexIndicesForQuad(_,this._currentMultiTextureIndex)}Quad3D3(e,t,r,i,a,s,n,u,h,o,l,d,f,_){this.#G(4,6);const c=this.#n.WriteQuad3D3(this._baseZ+this._currentZ,e,t,r,i,a,s,n,u,h,o,l,d,f,_);524288&this._flags&&this.#n.WriteTexIndicesForQuad(c,this._currentMultiTextureIndex)}Quad3D4(e,t){this.#G(4,6);const r=this.#n.WriteQuad3D4(this._baseZ+this._currentZ,e,t);524288&this._flags&&this.#n.WriteTexIndicesForQuad(r,this._currentMultiTextureIndex)}CreateMeshData(e,t,r){r=Object.assign({},r,{texIndices:!0});const i=new C3.Gfx.MeshDataWebGPU(this,e,t,r);return this.#s.add(i),i}_ReleaseMeshData(e){this.EndBatch(),this.#s.delete(e)}DrawMesh(e,t,r,i){const a=C3.Gfx.DynamicMeshData.GetMaxVertices(),s=C3.Gfx.DynamicMeshData.GetMaxIndices();if(e.length%3!=0)throw new Error("vertex buffer length not multiple of 3");if(e.length>3*a)throw new Error(`too many vertices (${e.length/3}, limit ${a})`);if(r.length%3!=0)throw new Error("index buffer length not multiple of 3");if(r.length>s)throw new Error(`too many indices (${r.length}, limit ${s})`);this.#G(e.length,r.length);const n=this.#n.WriteMesh(e,t,r,i);524288&this._flags&&this.#n.FillTexIndices(n,Math.floor(e.length/3),this._currentMultiTextureIndex)}DrawMeshData(e,t=0,r=e.GetIndexCount()){if(e.IsSmall())if(0===t&&r===e.GetIndexCount()){this.#G(e.GetVertexCount(),e.GetIndexCount());const t=this.#n.WriteMesh(e.positions,e.texCoords,e.indices,e.colors);524288&this._flags&&this.#n.FillTexIndices(t,e.GetVertexCount(),this._currentMultiTextureIndex)}else{const{minIndex:i,maxIndex:a}=C3.Gfx.DynamicMeshData.CalculatePartialIndexRange(e.indices,t,r),s=i,n=a+1,u=n-s;this.#G(u,r);const h=this.#n.WriteMesh(e.positions.subarray(3*s,3*n),e.texCoords.subarray(2*s,2*n),e.indices.subarray(t,t+r),e.colors.subarray(4*s,4*n),i);524288&this._flags&&this.#n.FillTexIndices(h,u,this._currentMultiTextureIndex)}else 524288&this._flags&&e.FillTexIndices(this._currentMultiTextureIndex),this.#T(e),this.#o.add(e),null===this._currentRenderPass&&this._BeginRenderPass(),this._flags|=1,this._drawFirstIndex=t,this._drawIndexCount=r,this._MaybeEndDrawBatch()}#S(){this.#T(this.#u)}#T(e){this.#h!==e&&(this._MaybeEndDrawBatch(),this.#h=e,this._flags|=32)}_GetCurrentMeshData(){return this.#h}StartRenderingPoints(e){this._currentPointTexCoords.equals(e)||(this._currentPointTexCoords.copy(e),this._UpdatePointTexCoordsUniform());const t=this._baseZ+this._currentZ;this._currentVertexZElevation!==t&&(this._currentVertexZElevation=t,this._UpdateZElevationUniform()),this._currentPointColor.equals(this._currentColor)||(this._currentPointColor.copy(this._currentColor),this._UpdatePointColorUniform()),this.SetProgram(this.GetPointsRenderingProgram()),this._drawIndexCount=0,this._flags|=34}FinishRenderingPoints(){this._drawIndexCount>0&&this._MaybeEndDrawBatch(),this._flags&=-3,this._flags|=32}Point(e,t,r,i){let a=this._pointPtr;a>65520&&(this.EndBatch(),a=0),1&this._flags?this._drawIndexCount+=6:(null===this._currentRenderPass&&this._BeginRenderPass(),this._flags|=1,this._drawFirstIndex=a/4*6,this._drawIndexCount=6);const s=this._pointData;s[a++]=e,s[a++]=t,s[a++]=r,s[a++]=i,this._pointPtr=a}SetGradientColor(e){this._currentColor2.equals(e)||(this._currentColor2.copy(e),this._UpdateColor2Uniform())}SetEllipseParams(e,t,r=1){const i=this._fragUniformBufferLayout,a=this._fragUniformf32;tempVec2.set(e,t),tempVec2.equalsF32Array(a,i.pixelSize.offset/4)||this._UpdateFragmentUniformVec2(tempVec2,i.pixelSize),a[i.outlineThickness.offset/4]!==Math.fround(r)&&(a[i.outlineThickness.offset/4]=r,this._MarkFragUniformBufferRangeChanged(i.outlineThickness))}SetTilemapInfo(e,t,r,i,a,s,n){const u=this._fragUniformBufferLayout,h=this._fragUniformf32;e.equalsF32Array(h,u.srcRect.offset/4)||(e.writeToTypedArray(h,u.srcRect.offset/4),this._MarkFragUniformBufferRangeChanged(u.srcRect)),tempVec2.set(i/t,a/r),tempVec2.equalsF32Array(h,u.tileSize.offset/4)||this._UpdateFragmentUniformVec2(tempVec2,u.tileSize),tempVec2.set(s/t,n/r),tempVec2.equalsF32Array(h,u.tileSpacing.offset/4)||this._UpdateFragmentUniformVec2(tempVec2,u.tileSpacing)}SetTileRandomizationInfo(e,t,r,i,a,s,n){const u=this._fragUniformBufferLayout,h=this._fragUniformf32;tempVec2.set(r,i),tempVec2.equalsF32Array(h,u.tileSize.offset/4)||this._UpdateFragmentUniformVec2(tempVec2,u.tileSize),h[u.outlineThickness.offset/4]!==Math.fround(a)&&(h[u.outlineThickness.offset/4]=a,this._MarkFragUniformBufferRangeChanged(u.outlineThickness)),tempVec2.set(s,n),tempVec2.equalsF32Array(h,u.tileSpacing.offset/4)||this._UpdateFragmentUniformVec2(tempVec2,u.tileSpacing)}SetProgramParameters(e,t,r,i,a,s,n,u,h,o,l){const d=this._fragC3ParamsLayout,f=this._currentProgram;l%=10800,f.BlendsBackground()&&this.SetBackTexture(e),f.UsesAnyC3ParamRect()&&(this._MaybeUpdateFragmentC3ParamsRect(t,d.destRect),this._MaybeUpdateFragmentC3ParamsRect(r,d.srcRect),this._MaybeUpdateFragmentC3ParamsRect(i,d.srcOriginRect),this._MaybeUpdateFragmentC3ParamsRect(a,d.layoutRect)),this._MaybeUpdateFragmentC3ParamsFloat(u,d.devicePixelRatio),this._MaybeUpdateFragmentC3ParamsFloat(h,d.layerScale),this._MaybeUpdateFragmentC3ParamsFloat(o,d.layerAngle),this._MaybeUpdateFragmentC3ParamsFloat(l,d.seconds),this._MaybeUpdateFragmentC3ParamsFloat(this.GetNearZ(),d.zNear),this._MaybeUpdateFragmentC3ParamsFloat(this.GetFarZ(),d.zFar)}SetProgramCustomParameters(e){e&&(e.IsChanged()&&(this._MaybeEndRenderPass(),e.UpdateBuffer(this._commandEncoder)),this._SetBufferBindGroup(e.GetBufferBindGroup()))}SetProgramParameter_IsSrcTexRotated(e){this._MaybeUpdateFragmentC3ParamsUint(e?1:0,this._fragC3ParamsLayout.isSrcTexRotated)}_SetBufferBindGroup(e){e!==this._currentBufferBindGroup&&(this._MaybeEndDrawBatch(),this._currentBufferBindGroup=e,this._flags|=16384)}_OnBufferBindGroupDestroyed(e){this._currentBufferBindGroup===e&&this._SetBufferBindGroup(this._defaultBufferBindGroup)}CopyRenderTarget(e){if(e._IsAwaitingClear())return this._currentRenderTarget._SetIsAwaitingClear(!0),void this._currentRenderTarget._GetClearColor().set(e._GetClearColor());e.GetMultisampling()>=2&&this._currentRenderTarget.GetMultisampling()<2?this._ResolveMultisampledRenderTarget(e):(this.ClearRgba(0,0,0,0),this.SetCopyBlend(),this.ResetColor(),this.DrawRenderTarget(e))}DrawRenderTarget(e){this._MaybeDoPendingClearRenderPass(e);const t=e.GetTexture();this.SetTexture(t),this.FullscreenQuad()}FullscreenQuad(){const e=this.IsNormalizedCoordsProgramVariant();e||this.SetNormalizedCoordsProgramVariant(!0),this.SetCurrentZ(0);const t=tempQuad,r=tempRect;t.set(0,-1,0,-1,2,1,0,1),r.set(0,-1,2,1),this.Quad3(t,r),e||this.SetNormalizedCoordsProgramVariant(!1)}_ResolveMultisampledRenderTarget(e){this._MaybeDoPendingClearRenderPass(e),this._MaybeEndRenderPass();this._commandEncoder["beginRenderPass"]({"colorAttachments":[{"view":e.GetTexture()._GetTextureView(),"resolveTarget":this._currentRenderTarget.GetTexture()._GetTextureView(),"loadOp":"load","storeOp":"store"}]})["end"](),this._flags|=32768}CoplanarStartStencilPass(){this._MaybeEndRenderPass(),this.SetDepthEnabled(!0),this._flags|=83886080}CoplanarStartColorPass(e=!1){this._MaybeEndRenderPass(),this.SetDepthEnabled(e),this._flags&=-16777217,this._flags|=33554432}IsCoplanarColorPass(){return this._IsFlagSet(33554432)}CoplanarRestoreStandardRendering(e=!0){this._MaybeEndRenderPass(),this.SetDepthEnabled(e),this._flags&=-33554433}_InitBlendModes(){this._InitBlendModeData([["normal",["one","one-minus-src-alpha"]],["additive",["one","one"]],["xor",["one","one-minus-src-alpha"]],["copy",["one","zero"]],["destination-over",["one-minus-dst-alpha","one"]],["source-in",["dst-alpha","zero"]],["destination-in",["zero","src-alpha"]],["source-out",["one-minus-dst-alpha","zero"]],["destination-out",["zero","one-minus-src-alpha"]],["source-atop",["dst-alpha","one-minus-src-alpha"]],["destination-atop",["one-minus-dst-alpha","src-alpha"]],["lighten",["one","one","one","one","max","max"]],["darken",["one","one","one","one","min","min"]],["multiply",["dst","one-minus-src-alpha","one","one-minus-src-alpha"]],["screen",["one","one-minus-src","one","one-minus-src-alpha"]]])}GetAvailableAdapterFeatures(){return this.#r?[...this.#r["features"]]:[]}GetAdapterInfo(){return this.#r?this.#r["info"]:null}IsCompatibilityMode(){return this.#a}GetAdapterInfoString(){const e=this.GetAdapterInfo();let t="unknown",r="unknown";e&&(t=e["vendor"]||"unknown",r=e["architecture"]||"unknown");const i=[];e&&(e["device"]&&i.push(e["device"]),e["description"]&&i.push(e["description"]),e["type"]&&i.push(e["type"]),e["backend"]&&i.push(e["backend"])),this.IsCompatibilityMode()&&i.push("compatibility mode");return t+"/"+r+(i.length>0?` (${i.join(", ")})`:"")}}; } // ../lib/gfx/webgpu/bufferManager.js { const C3=self.C3,ENABLE_RECYCLING=!0;C3.Gfx.WebGPUBufferManager=class{constructor(e){this._renderer=e,this._buffers=new Map,this._recycleAfterSubmit=[],this._releaseAfterSubmit=[],this._destroyAfterSubmit=[],this._totalBufferCount=0,this._totalBufferSize=0,this._totalCreated=0,this._totalReleased=0,this._totalReturned=0,this._totalRecycled=0}GetRenderer(){return this._renderer}OnContextLost(){this._buffers.clear(),C3.clearArray(this._recycleAfterSubmit),C3.clearArray(this._releaseAfterSubmit),C3.clearArray(this._destroyAfterSubmit)}_RoundBufferSizeClass(e){return Math.max(C3.nextHighestPowerOfTwo(e),16)}GetRecyclableBuffer(e){this._totalReturned++;const t=this._RoundBufferSizeClass(e);{const e=this._buffers.get(t);if(void 0!==e&&e.length>0){const r=e.pop();return r.MarkInUse(),0===e.length&&this._buffers.delete(t),r}}return this._totalBufferCount++,this._totalBufferSize+=t,this._totalCreated++,C3.New(C3.Gfx.WebGPURecyclableBuffer,this,t)}_AddRecycledBuffer(e){this._totalRecycled++;const t=e.GetSize(),r=this._buffers.get(t);void 0===r?this._buffers.set(t,[e]):r.push(e)}_DestroyAfterSubmit(e){this._destroyAfterSubmit.push(e)}AfterSubmit(){for(const e of this._recycleAfterSubmit)e.Recycle();C3.clearArray(this._recycleAfterSubmit);for(const e of this._releaseAfterSubmit)this._totalBufferCount--,this._totalBufferSize-=e.GetSize(),e.Release();C3.clearArray(this._releaseAfterSubmit);for(const e of this._destroyAfterSubmit)e["destroy"]();C3.clearArray(this._destroyAfterSubmit)}MaybeCollectUnusedBuffers(e){e%30==0&&this._CollectUnusedBuffers(e)}_CollectUnusedBuffers(e){for(const[t,r]of this._buffers.entries()){let s=0;for(let t=0,f=r.length;t,\n\tpointColor \t\t\t: vec4,\n\ttileSize\t\t\t: vec2,\n\ttileSpacing\t\t\t: vec2,\n\tsrcRectStart\t\t: vec2,\n\tsrcRectEnd\t\t\t: vec2,\n\tpixelSize\t\t\t: vec2,\n\toutlineThickness\t: f32\n};\n@binding(1) @group(0) var uniforms : Uniforms;\n",fubLayout={color2:{offset:0,size:16,end:0},pointColor:{offset:16,size:16,end:0},tileSize:{offset:32,size:8,end:0},tileSpacing:{offset:40,size:8,end:0},srcRect:{offset:48,size:16,end:0},srcRectStart:{offset:48,size:8,end:0},srcRectEnd:{offset:56,size:8,end:0},pixelSize:{offset:64,size:8,end:0},outlineThickness:{offset:72,size:4,end:0}};UpdateLayoutEndValues(fubLayout);const fubSize=fubLayout.outlineThickness.end,c3ParamsUniformBufferDeclaration="\nstruct C3Params {\n\tsrcStart\t\t\t: vec2,\n\tsrcEnd\t\t\t\t: vec2,\n\tsrcOriginStart\t\t: vec2,\n\tsrcOriginEnd\t\t: vec2,\n\tlayoutStart\t\t\t: vec2,\n\tlayoutEnd\t\t\t: vec2,\n\tdestStart\t\t\t: vec2,\n\tdestEnd\t\t\t\t: vec2,\n\tdevicePixelRatio\t: f32,\n\tlayerScale\t\t\t: f32,\n\tlayerAngle\t\t\t: f32,\n\tseconds\t\t\t\t: f32,\n\tzNear\t\t\t\t: f32,\n\tzFar\t\t\t\t: f32,\n\tisSrcTexRotated\t\t: u32\n};\n@binding(4) @group(0) var c3Params : C3Params;\n\nfn c3_srcToNorm(p : vec2) -> vec2\n{\n\treturn (p - c3Params.srcStart) / (c3Params.srcEnd - c3Params.srcStart);\n}\n\nfn c3_normToSrc(p : vec2) -> vec2\n{\n\treturn fma(p, c3Params.srcEnd - c3Params.srcStart, c3Params.srcStart);\n}\n\nfn c3_clampToSrc(p : vec2) -> vec2\n{\n\treturn clamp(p, min(c3Params.srcStart, c3Params.srcEnd), max(c3Params.srcStart, c3Params.srcEnd));\n}\n\nfn c3_srcOriginToNorm(p : vec2) -> vec2\n{\n\treturn (p - c3Params.srcOriginStart) / (c3Params.srcOriginEnd - c3Params.srcOriginStart);\n}\n\nfn c3_normToSrcOrigin(p : vec2) -> vec2\n{\n\treturn fma(p, c3Params.srcOriginEnd - c3Params.srcOriginStart, c3Params.srcOriginStart);\n}\n\nfn c3_clampToSrcOrigin(p : vec2) -> vec2\n{\n\treturn clamp(p, min(c3Params.srcOriginStart, c3Params.srcOriginEnd), max(c3Params.srcOriginStart, c3Params.srcOriginEnd));\n}\n\nfn c3_getLayoutPos(p : vec2) -> vec2\n{\n\treturn fma(p - c3Params.srcOriginStart, (c3Params.layoutEnd - c3Params.layoutStart) / (c3Params.srcOriginEnd - c3Params.srcOriginStart), c3Params.layoutStart);\n}\n\nfn c3_srcToDest(p : vec2) -> vec2\n{\n\treturn fma(p - c3Params.srcStart, (c3Params.destEnd - c3Params.destStart) / (c3Params.srcEnd - c3Params.srcStart), c3Params.destStart);\n}\n\nfn c3_clampToDest(p : vec2) -> vec2\n{\n\treturn clamp(p, min(c3Params.destStart, c3Params.destEnd), max(c3Params.destStart, c3Params.destEnd));\n}\n\nfn c3_linearizeDepth(depthSample : f32) -> f32\n{\n\treturn c3Params.zNear * c3Params.zFar / (c3Params.zFar + depthSample * (c3Params.zNear - c3Params.zFar));\n}\n",C3PARAMS_TERMS_REFERENCING_SRC_RECTS=["srcStart","srcEnd","srcOriginStart","srcOriginEnd","c3_srcToNorm","c3_normToSrc","c3_clampToSrc","c3_srcOriginToNorm","c3_normToSrcOrigin","c3_clampToSrcOrigin","c3_getLayoutPos","c3_srcToDest"],C3PARAMS_TERMS_REFERENCING_OTHER_RECTS=["layoutStart","layoutEnd","destStart","destEnd","c3_clampToDest"],c3ParamsLayout={srcRect:{offset:0,size:16,end:0},srcStart:{offset:0,size:8,end:0},srcEnd:{offset:8,size:8,end:0},srcOriginRect:{offset:16,size:16,end:0},srcOriginStart:{offset:16,size:8,end:0},srcOriginEnd:{offset:24,size:8,end:0},layoutRect:{offset:32,size:16,end:0},layoutStart:{offset:32,size:8,end:0},layoutEnd:{offset:40,size:8,end:0},destRect:{offset:48,size:16,end:0},destStart:{offset:48,size:8,end:0},destEnd:{offset:56,size:8,end:0},devicePixelRatio:{offset:64,size:4,end:0},layerScale:{offset:68,size:4,end:0},layerAngle:{offset:72,size:4,end:0},seconds:{offset:76,size:4,end:0},zNear:{offset:80,size:4,end:0},zFar:{offset:84,size:4,end:0},isSrcTexRotated:{offset:88,size:4,end:0}};UpdateLayoutEndValues(c3ParamsLayout);const c3ParamsSize=c3ParamsLayout.isSrcTexRotated.end;function GetFragmentInputStructDeclaration(t){return`\nstruct FragmentInput {\n\t@location(0) worldPos : vec3,\n\t@location(1) fragUV : vec2,\n\t@location(2) fragColor : vec4<${t?"f16":"f32"}>,\n\t@builtin(position) fragPos : vec4\n};\n\nfn c3_getBackUV(fragPos : vec2, texBack : texture_2d) -> vec2\n{\n\treturn fragPos / vec2(textureDimensions(texBack));\n}\n\nfn c3_getDepthUV(fragPos : vec2, texDepth : texture_depth_2d) -> vec2\n{\n\treturn fragPos / vec2(textureDimensions(texDepth));\n}\n`}const fragmentOutputStructDeclaration="\nstruct FragmentOutput {\n\t@location(0) color : vec4\n};\n",shaderCustomParamSizes=new Map([["float",4],["percent",4],["color",12]]),shaderCustomParamAlignSizes=new Map([["float",4],["percent",4],["color",16]]),c3WGSLUtilityFunctionsLib="\nfn c3_premultiply(c : vec4) -> vec4\n{\n\treturn vec4(c.rgb * c.a, c.a);\n}\n\nfn c3_unpremultiply(c : vec4) -> vec4\n{\n\tif (c.a == 0.0)\n\t{\n\t\treturn vec4(0.0);\n\t}\n\t\n\treturn vec4(c.rgb / c.a, c.a);\n}\n\nfn c3_grayscale(rgb : vec3) -> f32\n{\n\treturn dot(rgb, vec3(0.299, 0.587, 0.114));\n}\n\nfn c3_getPixelSize(t : texture_2d) -> vec2\n{\n\treturn vec2(1.0) / vec2(textureDimensions(t));\n}\n\nfn c3_clamp2(v : vec2, l : f32, u : f32) -> vec2\n{\n\treturn clamp(v, vec2(l), vec2(u));\n}\n\nfn c3_mod(x : f32, y : f32) -> f32\n{\n\treturn x - y * floor(x / y);\n}\n\nfn c3_mod2(x : vec2, y : vec2) -> vec2\n{\n\treturn x - y * floor(x / y);\n}\n\nfn c3_RGBtoHSL(color : vec3) -> vec3\n{\n\tvar hsl : vec3 = vec3(0.0);\n\t\n\tvar fmin : f32 = min(min(color.r, color.g), color.b);\n\tvar fmax : f32 = max(max(color.r, color.g), color.b);\n\tvar delta : f32 = fmax - fmin;\n\n\thsl.z = (fmax + fmin) / 2.0;\n\n\tif (delta == 0.0)\n\t{\n\t\thsl.x = 0.0;\n\t\thsl.y = 0.0;\n\t}\n\telse \n\t{\n\t\tif (hsl.z < 0.5)\n\t\t{\n\t\t\thsl.y = delta / (fmax + fmin);\n\t\t}\n\t\telse\n\t\t{\n\t\t\thsl.y = delta / (2.0 - fmax - fmin);\n\t\t}\n\t\t\n\t\tvar dR : f32 = (((fmax - color.r) / 6.0) + (delta / 2.0)) / delta;\n\t\tvar dG : f32 = (((fmax - color.g) / 6.0) + (delta / 2.0)) / delta;\n\t\tvar dB : f32 = (((fmax - color.b) / 6.0) + (delta / 2.0)) / delta;\n\n\t\tif (color.r == fmax)\n\t\t{\n\t\t\thsl.x = dB - dG;\n\t\t}\n\t\telse if (color.g == fmax)\n\t\t{\n\t\t\thsl.x = (1.0 / 3.0) + dR - dB;\n\t\t}\n\t\telse if (color.b == fmax)\n\t\t{\n\t\t\thsl.x = (2.0 / 3.0) + dG - dR;\n\t\t}\n\n\t\tif (hsl.x < 0.0)\n\t\t{\n\t\t\thsl.x = hsl.x + 1.0;\n\t\t}\n\t\telse if (hsl.x > 1.0)\n\t\t{\n\t\t\thsl.x = hsl.x - 1.0;\n\t\t}\n\t}\n\n\treturn hsl;\n}\n\nfn c3_hueToRGB(f1 : f32, f2 : f32, hue_ : f32) -> f32\n{\n\tvar hue : f32 = hue_;\n\tif (hue < 0.0)\n\t{\n\t\thue = hue + 1.0;\n\t}\n\telse if (hue > 1.0)\n\t{\n\t\thue = hue - 1.0;\n\t}\n\t\t\n\tvar ret : f32;\n\t\n\tif ((6.0 * hue) < 1.0)\n\t{\n\t\tret = f1 + (f2 - f1) * 6.0 * hue;\n\t}\n\telse if ((2.0 * hue) < 1.0)\n\t{\n\t\tret = f2;\n\t}\n\telse if ((3.0 * hue) < 2.0)\n\t{\n\t\tret = f1 + (f2 - f1) * ((2.0 / 3.0) - hue) * 6.0;\n\t}\n\telse\n\t{\n\t\tret = f1;\n\t}\n\t\n\treturn ret;\n}\n\nfn c3_HSLtoRGB(hsl : vec3) -> vec3\n{\n\tvar rgb : vec3 = vec3(hsl.z);\n\t\n\tif (hsl.y != 0.0)\n\t{\n\t\tvar f2 : f32;\n\t\t\n\t\tif (hsl.z < 0.5)\n\t\t{\n\t\t\tf2 = hsl.z * (1.0 + hsl.y);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tf2 = (hsl.z + hsl.y) - (hsl.y * hsl.z);\n\t\t}\n\t\t\t\n\t\tvar f1 : f32 = 2.0 * hsl.z - f2;\n\t\t\n\t\trgb.r = c3_hueToRGB(f1, f2, hsl.x + (1.0 / 3.0));\n\t\trgb.g = c3_hueToRGB(f1, f2, hsl.x);\n\t\trgb.b = c3_hueToRGB(f1, f2, hsl.x - (1.0 / 3.0));\n\t}\n\t\n\treturn rgb;\n}\n";function HashPipelineState(t,e,n,r,a){return t<<10|e<<7|n<<5|r<<4|a}C3.Gfx.WebGPUShaderProgram=class extends C3.Gfx.ShaderProgramBase{constructor(t,e){if(super(t,e),this._fragmentModule=e.fragmentModule,this._fragmentModuleFragDepth=e.fragmentModuleFragDepth,this._vertexModule=e.vertexModule,this._normVertexModule=e.normVertexModule,this._renderPipelineMap=new Map,this._mipmapPipelineMap=new Map,this._usesAnyC3ParamRect=!1,this._usesIsSrcTexRotated=!1,this._parameters=[],this._customParamsByteSize=0,e.parameters){let t=0;for(const n of e.parameters){const e=n[2];if(!shaderCustomParamSizes.has(e))throw new Error(`unrecognized effect param type '${e}'`);const r=shaderCustomParamSizes.get(e),a=shaderCustomParamAlignSizes.get(e),i=t%a;0!==i&&(t+=a-i),this._parameters.push({type:e,offset:t,size:r,end:t+r}),t+=r}this._customParamsByteSize=16*Math.ceil(t/16)}}static async Create(t,e){const n=t._GetDevice(),r=e.name,a=t.SupportsF16(),i=t.IsColorDataF16(),o=e.src,u=C3.Gfx.WebGPUShaderProgram._PreprocessFragmentShaderCode(o,a,i),f=n["createShaderModule"]({"label":r,"code":u});let c,s=null;if(e.srcFragDepth){const t=C3.Gfx.WebGPUShaderProgram._PreprocessFragmentShaderCode(e.srcFragDepth,a,i);s=n["createShaderModule"]({"label":r,"code":t})}f["getCompilationInfo"]().then(t=>C3.Gfx.WebGPUShaderProgram.ReportShaderCompilationInfo(r,"fragment",t));const l=C3.Gfx.WebGPUShaderProgram._PreprocessVertexShaderCode(e.vertexSrc,a);let p;l?(c=n["createShaderModule"]({"label":r,"code":l}),c["getCompilationInfo"]().then(t=>C3.Gfx.WebGPUShaderProgram.ReportShaderCompilationInfo(r,"vertex",t))):c=t._GetDefaultVertexModule();const d=C3.Gfx.WebGPUShaderProgram._PreprocessVertexShaderCode(e.normVertexSrc,a);d?(p=n["createShaderModule"]({"label":r,"code":d}),p["getCompilationInfo"]().then(t=>C3.Gfx.WebGPUShaderProgram.ReportShaderCompilationInfo(r,"vertex (norm)",t))):p=t._GetNormalizedVertexModule();const m=C3.New(C3.Gfx.WebGPUShaderProgram,t,Object.assign({fragmentModule:f,fragmentModuleFragDepth:s,vertexModule:c,normVertexModule:p},e));if(m._usesAnySrcRectOrPixelSize=o.includes("%%C3PARAMS_STRUCT%%")&&C3PARAMS_TERMS_REFERENCING_SRC_RECTS.some(t=>o.includes(t)),m._usesAnyC3ParamRect=m._usesAnySrcRectOrPixelSize||o.includes("%%C3PARAMS_STRUCT%%")&&C3PARAMS_TERMS_REFERENCING_OTHER_RECTS.some(t=>o.includes(t)),m._usesIsSrcTexRotated=o.includes("%%C3PARAMS_STRUCT%%")&&o.includes("isSrcTexRotated"),""!==r){const e=m._CreateRenderPipelineAsync(0,0,0,0,0);let n=null;t.UsesDepthBuffer()&&(n=m._CreateRenderPipelineAsync(0,1,0,0,0));const[r,a]=await Promise.all([e,n]);m._renderPipelineMap.set(HashPipelineState(0,0,0,0,0),r),a&&m._renderPipelineMap.set(HashPipelineState(0,1,0,0,0),a)}return m}static _PreprocessShaderCode(t,e){if(!t)return t;let n="";return n=e?"enable f16;\nalias f16or32 = f16;\n":"alias f16or32 = f32;\n",n+t}static _PreprocessFragmentShaderCode(t,e,n){return t=C3.Gfx.WebGPUShaderProgram._PreprocessShaderCode(t,e),C3.StringSubstituteMap(t,{"%%SAMPLERFRONT_BINDING%%":"@binding(0) @group(1)","%%TEXTUREFRONT_BINDING%%":"@binding(1) @group(1)","%%SAMPLERBACK_BINDING%%":"@binding(0) @group(2)","%%TEXTUREBACK_BINDING%%":"@binding(1) @group(2)","%%SAMPLERDEPTH_BINDING%%":"@binding(0) @group(3)","%%TEXTUREDEPTH_BINDING%%":"@binding(1) @group(3)","%%SHADERPARAMS_BINDING%%":"@binding(5) @group(0)","%%FRAGMENTINPUT_STRUCT%%":GetFragmentInputStructDeclaration(n),"%%FRAGMENTOUTPUT_STRUCT%%":fragmentOutputStructDeclaration,"%%C3PARAMS_STRUCT%%":c3ParamsUniformBufferDeclaration,"%%C3_UTILITY_FUNCTIONS%%":c3WGSLUtilityFunctionsLib})}static _PreprocessVertexShaderCode(t,e){return C3.Gfx.WebGPUShaderProgram._PreprocessShaderCode(t,e)}static ReportShaderCompilationInfo(t,e,n){for(const r of n["messages"]){const n=`[WebGPU] Message (${r["type"]}) compiling ${e} shader '${t}': ${r["message"]} (line ${r["lineNum"]}, pos ${r["linePos"]})`;"error"===r.type?console.error(n):"warning"===r.type?console.warn(n):console.log(n)}}Release(){this._fragmentModule=null,this._fragmentModuleFragDepth=null,this._vertexModule=null,this._normVertexModule=null,this._renderPipelineMap.clear(),this._mipmapPipelineMap.clear(),super.Release()}_GetDevice(){return this._renderer._GetDevice()}_GetPipelineLayout(){return this._renderer._GetPipelineLayout()}GetRenderer(){return this._renderer}UsesAnyC3ParamRect(){return this._usesAnyC3ParamRect}UsesIsSrcTexRotated(){return this._usesIsSrcTexRotated}GetParameterCount(){return this._parameters.length}GetParameterType(t){return t<0||t>=this._parameters.length?null:this._parameters[t].type}GetCustomParametersByteSize(){return this._customParamsByteSize}_GetCustomParameterInfo(t){return this._parameters[t]}_GetRenderPipelineDescriptor(t,e,n,r,a){const i=this._renderer,o=i.IsColorDataF16(),u=i._GetBlendParametersByIndex(t);let f=u[0],c=u[1],s=f,l=c,p="add",d="add";u.length>=4&&(s=u[2],l=u[3]),6===u.length&&(p=u[4],d=u[5]);let m="none";switch(n){case 1:m="back";break;case 2:m="front"}const g={"label":`${this.GetName()} blendMode ${t} variant ${e} multisampleCount ${a}`,"layout":this._GetPipelineLayout(),"primitive":{"cullMode":m,"frontFace":0===r?"cw":"ccw"},"vertex":{"module":4===e?this._normVertexModule:this._vertexModule,"entryPoint":"main","buffers":[{"arrayStride":12,"attributes":[{"shaderLocation":0,"offset":0,"format":"float32x3"}]},{"arrayStride":8,"attributes":[{"shaderLocation":1,"offset":0,"format":"float32x2"}]},{"arrayStride":4*(o?2:4),"attributes":[{"shaderLocation":2,"offset":0,"format":o?"float16x4":"float32x4"}]},{"arrayStride":4,"attributes":[{"shaderLocation":3,"offset":0,"format":"uint32"}]}]},"fragment":{"module":this._fragmentModule,"entryPoint":"main","targets":[{"format":i.GetSwapChainFormat(),"blend":{"color":{"srcFactor":f,"dstFactor":c,"operation":p},"alpha":{"srcFactor":s,"dstFactor":l,"operation":d}}}]}};if(a>=2&&(g["multisample"]={"count":a}),1===e)g["fragment"]["module"]=this._fragmentModuleFragDepth||this._fragmentModule,g["depthStencil"]={"format":i._GetDepthBufferFormat(),"depthWriteEnabled":!0,"depthCompare":"less-equal"};else if(2===e){g["fragment"]["module"]=this._fragmentModuleFragDepth||this._fragmentModule,g["fragment"]["targets"]=[];const t={"compare":"always","failOp":"keep","depthFailOp":"keep","passOp":"replace"};g["depthStencil"]={"format":i._GetDepthBufferFormat(),"depthWriteEnabled":!0,"depthCompare":"less-equal","stencilFront":t,"stencilBack":t,"stencilReadMask":1,"stencilWriteMask":1}}else if(3===e){g["fragment"]["module"]=this._fragmentModuleFragDepth||this._fragmentModule;const t={"compare":"equal","failOp":"keep","depthFailOp":"keep","passOp":"keep"};g["depthStencil"]={"format":i._GetDepthBufferFormat(),"depthWriteEnabled":!1,"depthCompare":"always","stencilFront":t,"stencilBack":t,"stencilReadMask":1,"stencilWriteMask":0}}return g}_CreateRenderPipeline(t,e,n,r,a){return this._GetDevice()["createRenderPipeline"](this._GetRenderPipelineDescriptor(t,e,n,r,a))}_CreateRenderPipelineAsync(t,e,n,r,a){return this._GetDevice()["createRenderPipelineAsync"](this._GetRenderPipelineDescriptor(t,e,n,r,a))}GetRenderPipelineForState(t,e,n,r,a){const i=HashPipelineState(t,e,n,r,a);let o=this._renderPipelineMap.get(i);return o||(o=this._CreateRenderPipeline(t,e,n,r,a),this._renderPipelineMap.set(i,o),o)}static GetVertexUniformBufferLayout(){return vubLayout}static GetVertexUniformBufferSize(){return 16*Math.ceil(vubSize/16)}static GetFragmentUniformBufferLayout(){return fubLayout}static GetFragmentUniformBufferSize(){return 16*Math.ceil(fubSize/16)}static GetFragmentC3ParamsBufferLayout(){return c3ParamsLayout}static GetFragmentC3ParamsBufferSize(){return 16*Math.ceil(c3ParamsSize/16)}static GetDefaultVertexShaderSource(t){const e=t?"f16":"f32";return`\n\t\t${vertexUniformBufferDeclaration}\n\n\t\tstruct VertexInput {\n\t\t\t@location(0) position : vec3,\n\t\t\t@location(1) uv : vec2,\n\t\t\t@location(2) color : vec4<${e}>,\n\t\t\t@location(3) texIndex : u32\n\t\t};\n\n\t\tstruct VertexOutput {\n\t\t\t@builtin(position) Position : vec4,\n\t\t\t@location(0) worldPos : vec3,\n\t\t\t@location(1) fragUV : vec2,\n\t\t\t@location(2) fragColor : vec4<${e}>,\n\t\t\t@location(3) @interpolate(flat, either) texIndex : u32\n\t\t};\n\n\t\t@vertex\n\t\tfn main(input : VertexInput) -> VertexOutput {\n\t\t\tvar output : VertexOutput;\n\t\t\toutput.Position = uniforms.transform * vec4(input.position, 1.0);\n\t\t\toutput.worldPos = input.position;\n\t\t\toutput.fragUV = input.uv;\n\t\t\toutput.fragColor = input.color;\n\t\t\toutput.texIndex = input.texIndex;\n\t\t\treturn output;\n\t\t}`}static GetNormalizedVertexShaderSource(t){const e=t?"f16":"f32";return`\n\t\tstruct VertexInput {\n\t\t\t@location(0) position : vec3,\n\t\t\t@location(1) uv : vec2,\n\t\t\t@location(2) color : vec4<${e}>,\n\t\t\t@location(3) texIndex : u32\n\t\t};\n\n\t\tstruct VertexOutput {\n\t\t\t@builtin(position) Position : vec4,\n\t\t\t@location(0) worldPos : vec3,\n\t\t\t@location(1) fragUV : vec2,\n\t\t\t@location(2) fragColor : vec4<${e}>,\n\t\t\t@location(3) @interpolate(flat, either) texIndex : u32\n\t\t};\n\n\t\t@vertex\n\t\tfn main(input : VertexInput) -> VertexOutput {\n\t\t\tvar output : VertexOutput;\n\t\t\tvar p = input.position;\n\t\t\tp.y = 1.0 - p.y;\n\t\t\toutput.Position = vec4(p.xy * 2.0 - 1.0, p.z, 1.0);\n\t\t\toutput.worldPos = input.position;\n\t\t\toutput.fragUV = input.uv;\n\t\t\toutput.texIndex = input.texIndex;\n\t\t\toutput.fragColor = input.color;\n\t\t\treturn output;\n\t\t}`}static GetTextureFillVertexShaderSource(t){const e=t?"f16":"f32";return`\n\t\t${vertexUniformBufferDeclaration}\n\n\t\tstruct VertexInput {\n\t\t\t@location(0) position : vec3,\n\t\t\t@location(1) uv : vec2,\n\t\t\t@location(2) color : vec4<${e}>,\n\t\t\t@location(3) texIndex : u32\n\t\t};\n\n\t\tstruct VertexOutput {\n\t\t\t@builtin(position) Position : vec4,\n\t\t\t@location(0) worldPos : vec3,\n\t\t\t@location(1) fragUV : vec2,\n\t\t\t@location(2) fragColor : vec4<${e}>,\n\t\t\t@location(3) @interpolate(flat, either) texIndex : u32\n\t\t};\n\n\t\t@vertex\n\t\tfn main(input : VertexInput) -> VertexOutput {\n\t\t\tvar output : VertexOutput;\n\t\t\toutput.Position = uniforms.transform * vec4(input.position, 1.0);\n\t\t\toutput.worldPos = input.position;\n\t\t\toutput.fragUV = input.uv;\n\t\t\toutput.fragColor = input.color;\n\t\t\toutput.texIndex = input.texIndex;\n\t\t\treturn output;\n\t\t}`}static GetNormalizedTextureFillVertexShaderSource(t){const e=t?"f16":"f32";return`\n\t\tstruct VertexInput {\n\t\t\t@location(0) position : vec3,\n\t\t\t@location(1) uv : vec2,\n\t\t\t@location(2) color : vec4<${e}>,\n\t\t\t@location(3) texIndex : u32\n\t\t};\n\n\t\tstruct VertexOutput {\n\t\t\t@builtin(position) Position : vec4,\n\t\t\t@location(0) worldPos : vec3,\n\t\t\t@location(1) fragUV : vec2,\n\t\t\t@location(2) fragColor : vec4<${e}>,\n\t\t\t@location(3) @interpolate(flat, either) texIndex : u32\n\t\t};\n\n\t\t@vertex\n\t\tfn main(input : VertexInput) -> VertexOutput {\n\t\t\tvar output : VertexOutput;\n\t\t\tvar p = input.position;\n\t\t\tp.y = 1.0 - p.y;\n\t\t\toutput.Position = vec4(p.xy * 2.0 - 1.0, p.z, 1.0);\n\t\t\toutput.worldPos = input.position;\n\t\t\toutput.fragUV = input.uv;\n\t\t\toutput.fragColor = input.color;\n\t\t\toutput.texIndex = input.texIndex;\n\t\t\treturn output;\n\t\t}`}static GetMultiTextureFillFragmentShaderSource(t,e){return`\n\t\t@binding(0) @group(1) var sampler0 : sampler;\n\t\t@binding(1) @group(1) var texture0 : texture_2d;\n\t\t@binding(2) @group(1) var sampler1 : sampler;\n\t\t@binding(3) @group(1) var texture1 : texture_2d;\n\t\t@binding(4) @group(1) var sampler2 : sampler;\n\t\t@binding(5) @group(1) var texture2 : texture_2d;\n\t\t@binding(6) @group(1) var sampler3 : sampler;\n\t\t@binding(7) @group(1) var texture3 : texture_2d;\n\t\t@binding(8) @group(1) var sampler4 : sampler;\n\t\t@binding(9) @group(1) var texture4 : texture_2d;\n\t\t@binding(10) @group(1) var sampler5 : sampler;\n\t\t@binding(11) @group(1) var texture5 : texture_2d;\n\t\t@binding(12) @group(1) var sampler6 : sampler;\n\t\t@binding(13) @group(1) var texture6 : texture_2d;\n\t\t@binding(14) @group(1) var sampler7 : sampler;\n\t\t@binding(15) @group(1) var texture7 : texture_2d;\n\t\t@binding(16) @group(1) var sampler8 : sampler;\n\t\t@binding(17) @group(1) var texture8 : texture_2d;\n\t\t@binding(18) @group(1) var sampler9 : sampler;\n\t\t@binding(19) @group(1) var texture9 : texture_2d;\n\t\t@binding(20) @group(1) var sampler10 : sampler;\n\t\t@binding(21) @group(1) var texture10 : texture_2d;\n\t\t@binding(22) @group(1) var sampler11 : sampler;\n\t\t@binding(23) @group(1) var texture11 : texture_2d;\n\t\t@binding(24) @group(1) var sampler12 : sampler;\n\t\t@binding(25) @group(1) var texture12 : texture_2d;\n\t\t@binding(26) @group(1) var sampler13 : sampler;\n\t\t@binding(27) @group(1) var texture13 : texture_2d;\n\n\t\tstruct FragmentInput {\n\t\t\t@location(1) fragUV : vec2,\n\t\t\t@location(2) fragColor : vec4<${e?"f16":"f32"}>,\n\t\t\t@location(3) @interpolate(flat, either) texIndex : u32,\n\t\t\t${t?"@builtin(position) fragPos: vec4":""}\n\t\t};\n\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4,\n\t\t\t${t?"@builtin(frag_depth) fragDepth: f32":""} \n\t\t};\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\tvar texXy : vec2 = input.fragUV.xy;\n\t\t\tvar texIndex : u32 = input.texIndex;\n\t\t\tvar c : vec4;\n\n\t\t\tlet dx = dpdx(texXy);\n\t\t\tlet dy = dpdy(texXy);\n\t\t\t\n\t\t\tif (texIndex <= 6)\n\t\t\t{\n\t\t\t\tif (texIndex <= 2)\n\t\t\t\t{\n\t\t\t\t\tif (texIndex == 0)\t\t\t{\tc = textureSampleGrad(texture0, sampler0, texXy, dx, dy);\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (texIndex == 1)\t\t{\tc = textureSampleGrad(texture1, sampler1, texXy, dx, dy);\t}\n\t\t\t\t\t\telse\t\t\t\t\t{\tc = textureSampleGrad(texture2, sampler2, texXy, dx, dy);\t}\n\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (texIndex <= 4)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (texIndex == 3)\t\t{\tc = textureSampleGrad(texture3, sampler3, texXy, dx, dy);\t}\n\t\t\t\t\t\telse\t\t\t\t\t{\tc = textureSampleGrad(texture4, sampler4, texXy, dx, dy);\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (texIndex <= 5)\t\t{\tc = textureSampleGrad(texture5, sampler5, texXy, dx, dy);\t}\n\t\t\t\t\t\telse\t\t\t\t\t{\tc = textureSampleGrad(texture6, sampler6, texXy, dx, dy);\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif (texIndex <= 9)\n\t\t\t\t{\n\t\t\t\t\tif (texIndex == 7)\t\t\t{\tc = textureSampleGrad(texture7, sampler7, texXy, dx, dy);\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (texIndex == 8)\t\t{\tc = textureSampleGrad(texture8, sampler8, texXy, dx, dy);\t}\n\t\t\t\t\t\telse\t\t\t\t\t{\tc = textureSampleGrad(texture9, sampler9, texXy, dx, dy);\t}\n\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (texIndex <= 11)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (texIndex == 10)\t\t{\tc = textureSampleGrad(texture10, sampler10, texXy, dx, dy);\t}\n\t\t\t\t\t\telse\t\t\t\t\t{\tc = textureSampleGrad(texture11, sampler11, texXy, dx, dy);\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif (texIndex == 12)\t\t{\tc = textureSampleGrad(texture12, sampler12, texXy, dx, dy);\t}\n\t\t\t\t\t\telse\t\t\t\t\t{\tc = textureSampleGrad(texture13, sampler13, texXy, dx, dy);\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\toutput.color = c * vec4(input.fragColor);\n\t\t\t${t?"output.fragDepth = select(input.fragPos.z, 1.0, output.color.a == 0.0);":""}\n\t\t\treturn output;\n\t\t}`}static GetSingleTextureFillFragmentShaderSource(t,e){return`\n\t\t@binding(0) @group(1) var sampler0 : sampler;\n\t\t@binding(1) @group(1) var texture0 : texture_2d;\n\n\t\tstruct FragmentInput {\n\t\t\t@location(1) fragUV : vec2,\n\t\t\t@location(2) fragColor : vec4<${e?"f16":"f32"}>,\n\t\t\t${t?"@builtin(position) fragPos: vec4":""}\n\t\t};\n\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4,\n\t\t\t${t?"@builtin(frag_depth) fragDepth: f32":""} \n\t\t};\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\toutput.color = textureSample(texture0, sampler0, input.fragUV) * vec4(input.fragColor);\n\t\t\t${t?"output.fragDepth = select(input.fragPos.z, 1.0, output.color.a == 0.0);":""}\n\t\t\treturn output;\n\t\t}`}static _GetMipmapGeneratorVertexSource(){return"\n\t\tstruct VertexInput {\n\t\t\t@builtin(vertex_index) VertexIndex : u32\n\t\t};\n\t\t\n\t\tstruct VertexOutput {\n\t\t\t@builtin(position) Position : vec4,\n\t\t\t@location(0) fragUV : vec2\n\t\t};\n\n\t\t@vertex\n\t\tfn main(input : VertexInput) -> VertexOutput {\n\n\t\t\tvar pos : array, 4> = array, 4>(\n\t\t\t\tvec2(-1.0, 1.0),\n\t\t\t\tvec2(1.0, 1.0),\n\t\t\t\tvec2(-1.0, -1.0),\n\t\t\t\tvec2(1.0, -1.0));\n\t\t\t\n\t\t\tvar output : VertexOutput;\n\t\t\tvar p : vec2 = pos[input.VertexIndex];\n\t\t\toutput.Position = vec4(p, 0.0, 1.0);\n\t\t\toutput.fragUV = p / 2.0 + 0.5;\n\t\t\treturn output;\n\t\t}"}static _GetMipmapGeneratorFragmentSource(){return"\n\t\t@binding(0) @group(0) var sampler0 : sampler;\n\t\t@binding(1) @group(0) var texture0 : texture_2d;\n\n\t\tstruct FragmentInput {\n\t\t\t@location(0) fragUV : vec2\n\t\t};\n\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4\n\t\t};\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\toutput.color = textureSample(texture0, sampler0, vec2(input.fragUV.x, 1.0 - input.fragUV.y));\n\t\t\treturn output;\n\t\t}"}_GetMipmapGeneratorPipeline(t){t||(t=this._renderer.GetTextureFormat());let e=this._mipmapPipelineMap.get(t);return e||(e=this._GetDevice()["createRenderPipeline"]({"label":"","layout":"auto","vertex":{"module":this._vertexModule,"entryPoint":"main"},"primitive":{"topology":"triangle-strip","stripIndexFormat":"uint16"},"fragment":{"module":this._fragmentModule,"entryPoint":"main","targets":[{"format":t,"blend":{"color":{"srcFactor":"one","dstFactor":"zero"},"alpha":{"srcFactor":"one","dstFactor":"zero"}}}]}}),this._mipmapPipelineMap.set(t,e)),e}static _GetPointVertexSource(){return`\n\t\t${vertexUniformBufferDeclaration}\n\n\t\tstruct PointData {\n\t\t\tdata : array>\n\t\t};\n\t\t@binding(3) @group(0) var pointBuffer : PointData;\n\n\t\tstruct VertexInput {\n\t\t\t@builtin(vertex_index) VertexIndex : u32\n\t\t};\n\n\t\tstruct VertexOutput {\n\t\t\t@builtin(position) Position : vec4,\n\t\t\t@location(0) fragUV : vec2,\n\t\t\t@location(1) pointOpacity : f32\n\t\t};\n\n\t\t@vertex\n\t\tfn main(input : VertexInput) -> VertexOutput {\n\n\t\t\tvar normPos : array, 4> = array, 4>(\n\t\t\t\tvec2(-0.5, -0.5),\n\t\t\t\tvec2(0.5, -0.5),\n\t\t\t\tvec2(0.5, 0.5),\n\t\t\t\tvec2(-0.5, 0.5));\n\t\t\t\n\t\t\tvar output : VertexOutput;\n\t\t\tvar p : vec2 = normPos[input.VertexIndex % u32(4)];\n\t\t\tvar pointData : vec4 = pointBuffer.data[input.VertexIndex / u32(4)];\n\n\t\t\tvar size : f32 = pointData.z;\n\t\t\toutput.Position = uniforms.transform * vec4(p * size + pointData.xy, uniforms.zElevation, 1.0);\n\t\t\toutput.pointOpacity = pointData.w;\n\n\t\t\tvar pointTexMin : vec2 = min(uniforms.pointTexStart, uniforms.pointTexEnd);\n\t\t\tvar pointTexMax : vec2 = max(uniforms.pointTexStart, uniforms.pointTexEnd);\n\t\t\tvar pn : vec2 = p + vec2(0.5, 0.5);\n\t\t\tvar pointCoord : vec2 = select(vec2(1.0 - pn.y, pn.x), pn, uniforms.pointTexEnd.x > uniforms.pointTexStart.x);\n\n\t\t\toutput.fragUV = mix(pointTexMin, pointTexMax, pointCoord);\n\t\t\treturn output;\n\t\t}`}static _GetPointFragmentSource(t){return`\n\t\t${fragmentUniformBufferDeclaration}\n\n\t\t%%SAMPLERFRONT_BINDING%% var sampler0 : sampler;\n\t\t%%TEXTUREFRONT_BINDING%% var texture0 : texture_2d;\n\n\t\tstruct FragmentInput {\n\t\t\t@location(0) fragUV : vec2,\n\t\t\t@location(1) pointOpacity : f32,\n\t\t\t@builtin(position) fragPos : vec4\n\t\t};\n\t\t\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4,\n\t\t\t${t?"@builtin(frag_depth) fragDepth: f32":""} \n\t\t};\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\toutput.color = textureSample(texture0, sampler0, input.fragUV) * uniforms.pointColor * input.pointOpacity;\n\t\t\t${t?"output.fragDepth = select(input.fragPos.z, 1.0, output.color.a == 0.0);":""}\n\t\t\treturn output;\n\t\t}`}static _GetTilemapFragmentShaderSource(t){return`\n\t\t${fragmentUniformBufferDeclaration}\n\n\t\t%%SAMPLERFRONT_BINDING%% var sampler0 : sampler;\n\t\t%%TEXTUREFRONT_BINDING%% var texture0 : texture_2d;\n\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4,\n\t\t\t${t?"@builtin(frag_depth) fragDepth: f32":""} \n\t\t};\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\tvar halfPixelSize : vec2 = vec2(0.5, 0.5) / vec2(textureDimensions(texture0));\n\n\t\t\tvar tile : vec2 = floor(input.fragUV);\n\t\t\tvar tex : vec2 = fract(input.fragUV);\n\t\t\tvar tileOrigin : vec2 = uniforms.srcRectStart + tile * (uniforms.tileSize + uniforms.tileSpacing);\n\t\t\tvar lowerBound : vec2 = tileOrigin + halfPixelSize;\n\t\t\tvar upperBound : vec2 = tileOrigin + uniforms.tileSize - halfPixelSize;\n\n\t\t\toutput.color = textureSampleLevel(texture0, sampler0, clamp(tex, lowerBound, upperBound), 0.0) * vec4(input.fragColor);\n\t\t\t${t?"output.fragDepth = select(input.fragPos.z, 1.0, output.color.a == 0.0);":""}\n\t\t\treturn output;\n\t\t}`}static GetTileRandomizationFragmentShaderSource(t){return`\n${fragmentUniformBufferDeclaration}\n\n%%SAMPLERFRONT_BINDING%% var sampler0 : sampler;\n%%TEXTUREFRONT_BINDING%% var texture0 : texture_2d;\n\n%%FRAGMENTINPUT_STRUCT%%\n\nstruct FragmentOutput {\n\t@location(0) color : vec4,\n\t${t?"@builtin(frag_depth) fragDepth: f32":""} \n};\n\n%%C3_UTILITY_FUNCTIONS%%\n\nconst PI : f32 = 3.1415926;\n\nfn cospVec4(a : vec4, b : vec4, x : f32) -> vec4\n{\n\treturn (a + b + (a - b) * cos(x * PI)) / 2.0;\n}\n\nfn randVec3(seed : vec2) -> vec3\n{\n\treturn vec3(\n\t\tfract(sin(dot(seed.xy, vec2(12.9898,78.233))) * 43758.5453),\n\t\tfract(sin(dot(seed.yx, vec2(12.9898,-78.233))) * 43758.5453),\n\t\tfract(sin(dot(seed.xy, vec2(-12.9898,-78.233))) * 43758.5453));\n}\n\nfn sampleTile(tile : vec2, uv : vec2, ddx : vec2, ddy : vec2) -> vec4\n{\n\tvar posRandom = uniforms.tileSize;\n\tvar angleRandom = uniforms.outlineThickness;\n\tvar pixelSize = c3_getPixelSize(texture0);\n\t\n\tvar rand = (randVec3(round(tile)) - 0.5) * 2.0;\n\t\n\tvar angle = angleRandom * rand.z * PI;\n\tvar sin_a = sin(angle);\n\tvar cos_a = cos(angle);\n\tvar aspect = pixelSize.x / pixelSize.y;\n\n\tvar mid = tile + vec2(0.5, 0.5);\n\tvar dp = uv - mid;\n\tdp.x /= aspect;\n\tvar r = vec2(dp.x * cos_a - dp.y * sin_a,\n\t\t\t\t\t dp.y * cos_a + dp.x * sin_a);\n\tr.x *= aspect;\n\n\tvar p = mid + r + (posRandom * rand.xy / 2.0);\n\t\n\treturn textureSampleGrad(texture0, sampler0, p, ddx, ddy);\n}\n\n@fragment\nfn main(input : FragmentInput) -> FragmentOutput\n{\n\tvar output : FragmentOutput;\n\t\n\tvar blendMarginX = uniforms.tileSpacing.x;\n\tvar blendMarginY = uniforms.tileSpacing.y;\n\t\n\tvar tile = floor(input.fragUV);\n\tvar tex = fract(input.fragUV);\n\tvar ddx = dpdx(input.fragUV);\n\tvar ddy = dpdy(input.fragUV);\n\t\n\tvar curTile = sampleTile(tile, input.fragUV, ddx, ddy);\n\t\n\tvar inLeftMargin = (tex.x < blendMarginX);\n\tvar inRightMargin = (tex.x > 1.0 - blendMarginX);\n\tvar inTopMargin = (tex.y < blendMarginY);\n\tvar inBottomMargin = (tex.y > 1.0 - blendMarginY);\n\t\n\tif (inLeftMargin)\n\t{\n\t\tvar leftTile = sampleTile(tile + vec2(-1.0, 0.0), input.fragUV, ddx, ddy);\n\t\tvar leftMix = (tex.x / (blendMarginX * 2.0)) + 0.5;\n\t\tvar leftMixedTile = cospVec4(leftTile, curTile, leftMix);\n\t\t\n\t\tif (inTopMargin)\n\t\t{\n\t\t\tvar topTile = sampleTile(tile + vec2(0.0, -1.0), input.fragUV, ddx, ddy);\n\t\t\tvar topLeftTile = sampleTile(tile + vec2(-1.0, -1.0), input.fragUV, ddx, ddy);\n\t\t\tvar topLeftMixedTile = cospVec4(topLeftTile, topTile, leftMix);\n\t\t\t\n\t\t\toutput.color = cospVec4(topLeftMixedTile, leftMixedTile, (tex.y / (blendMarginY * 2.0)) + 0.5);\n\t\t}\n\t\telse if (inBottomMargin)\n\t\t{\n\t\t\tvar bottomTile = sampleTile(tile + vec2(0.0, 1.0), input.fragUV, ddx, ddy);\n\t\t\tvar bottomLeftTile = sampleTile(tile + vec2(-1.0, 1.0), input.fragUV, ddx, ddy);\n\t\t\tvar bottomLeftMixedTile = cospVec4(bottomLeftTile, bottomTile, leftMix);\n\t\t\t\n\t\t\toutput.color = cospVec4(leftMixedTile, bottomLeftMixedTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));\n\t\t}\n\t\telse\n\t\t{\n\t\t\toutput.color = leftMixedTile;\n\t\t}\n\t}\n\telse if (inRightMargin)\n\t{\n\t\tvar rightTile = sampleTile(tile + vec2(1.0, 0.0), input.fragUV, ddx, ddy);\n\t\tvar rightMix = (tex.x - (1.0 - blendMarginX)) / (blendMarginX * 2.0);\n\t\tvar rightMixedTile = cospVec4(curTile, rightTile, rightMix);\n\t\t\n\t\tif (inTopMargin)\n\t\t{\n\t\t\tvar topTile = sampleTile(tile + vec2(0.0, -1.0), input.fragUV, ddx, ddy);\n\t\t\tvar topRightTile = sampleTile(tile + vec2(1.0, -1.0), input.fragUV, ddx, ddy);\n\t\t\tvar topRightMixedTile = cospVec4(topTile, topRightTile, rightMix);\n\t\t\t\n\t\t\toutput.color = cospVec4(topRightMixedTile, rightMixedTile, (tex.y / (blendMarginY * 2.0)) + 0.5);\n\t\t}\n\t\telse if (inBottomMargin)\n\t\t{\n\t\t\tvar bottomTile = sampleTile(tile + vec2(0.0, 1.0), input.fragUV, ddx, ddy);\n\t\t\tvar bottomRightTile = sampleTile(tile + vec2(1.0, 1.0), input.fragUV, ddx, ddy);\n\t\t\tvar bottomRightMixedTile = cospVec4(bottomTile, bottomRightTile, rightMix);\n\t\t\t\n\t\t\toutput.color = cospVec4(rightMixedTile, bottomRightMixedTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));\n\t\t}\n\t\telse\n\t\t{\n\t\t\toutput.color = rightMixedTile;\n\t\t}\n\t}\n\telse if (inTopMargin)\n\t{\n\t\tvar topTile = sampleTile(tile + vec2(0.0, -1.0), input.fragUV, ddx, ddy);\n\t\toutput.color = cospVec4(topTile, curTile, (tex.y / (blendMarginY * 2.0)) + 0.5);\n\t}\n\telse if (inBottomMargin)\n\t{\n\t\tvar bottomTile = sampleTile(tile + vec2(0.0, 1.0), input.fragUV, ddx, ddy);\n\t\toutput.color = cospVec4(curTile, bottomTile, (tex.y - (1.0 - blendMarginY)) / (blendMarginY * 2.0));\n\t}\n\telse\n\t{\n\t\toutput.color = curTile;\n\t}\n\t\n\toutput.color *= vec4(input.fragColor);\n\t${t?"output.fragDepth = select(input.fragPos.z, 1.0, output.color.a == 0.0);":""}\n\treturn output;\n}\n`}static _GetColorFillFragmentShaderSource(){return"\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t%%FRAGMENTOUTPUT_STRUCT%%\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\toutput.color = vec4(input.fragColor);\n\t\t\treturn output;\n\t\t}"}static _GetLinearGradientFillFragmentShaderSource(){return`\n\t\t${fragmentUniformBufferDeclaration}\n\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t%%FRAGMENTOUTPUT_STRUCT%%\n\n\t\tfn fromLinear(linearRGB : vec3) -> vec3\n\t\t{\n\t\t\tvar cutoff : vec3 = (linearRGB < vec3(0.0031308));\n\t\t\tvar higher : vec3 = vec3(1.055) * pow(abs(linearRGB), vec3(1.0/2.4)) - 0.055;\n\t\t\tvar lower : vec3 = linearRGB * 12.92;\n\t\t\treturn select(higher, lower, cutoff);\n\t\t}\n\n\t\tfn toLinear(sRGB : vec3) -> vec3\n\t\t{\n\t\t\tvar cutoff : vec3 = (sRGB < vec3(0.04045));\n\t\t\tvar higher : vec3 = pow(abs((sRGB + 0.055) / 1.055), vec3(2.4));\n\t\t\tvar lower : vec3 = sRGB / 12.92;\n\t\t\treturn select(higher, lower, cutoff);\n\t\t}\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\tvar linearGrad : vec3 = mix(toLinear(vec3(input.fragColor.rgb)), toLinear(uniforms.color2.rgb), vec3(input.fragUV.x));\n\n\t\t\tvar a : f32 = mix(f32(input.fragColor.a), uniforms.color2.a, input.fragUV.x);\n\t\t\toutput.color = vec4(fromLinear(linearGrad) * a, a);\n\t\t\treturn output;\n\t\t}\n\t\t`}static _GetPenumbraFillFragmentShaderSource(){return`\n\t\t${fragmentUniformBufferDeclaration}\n\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t%%FRAGMENTOUTPUT_STRUCT%%\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\tvar grad : f32 = input.fragUV.x / (1.0 - input.fragUV.y);\n\t\t\toutput.color = vec4(input.fragColor) * (1.0 - (cos(grad * 3.141592653589793) + 1.0) / 2.0);\n\t\t\treturn output;\n\t\t}\n\t\t`}static _GetHardEllipseFillFragmentShaderSource(){return"\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t%%FRAGMENTOUTPUT_STRUCT%%\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\tvar diff : vec2 = input.fragUV - 0.5;\n\t\t\tvar diffSq : vec2 = diff * diff;\n\n\t\t\tvar f : f32 = step(diffSq.x + diffSq.y, 0.25);\n\n\t\t\toutput.color = vec4(input.fragColor) * f;\n\t\t\treturn output;\n\t\t}"}static _GetHardEllipseOutlineFragmentShaderSource(){return`\n\t\t${fragmentUniformBufferDeclaration}\n\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t%%FRAGMENTOUTPUT_STRUCT%%\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\tvar diff : vec2 = input.fragUV - 0.5;\n\t\t\tvar diffSq : vec2 = diff * diff;\n\t\t\tvar distSq : f32 = diffSq.x + diffSq.y;\n\t\t\tvar norm : vec2 = normalize(diff);\n\t\t\tvar halfNorm : vec2 = norm * 0.5;\n\n\t\t\tvar innerF : f32 = step(distSq, 0.25);\n\n\t\t\tvar innerEdge : vec2 = halfNorm - uniforms.pixelSize * norm * uniforms.outlineThickness;\n\t\t\tvar innerEdgeSq : vec2 = innerEdge * innerEdge;\n\t\t\tvar outerF : f32 = step(innerEdgeSq.x + innerEdgeSq.y, distSq);\n\t\t\t\n\t\t\toutput.color = vec4(input.fragColor) * innerF * outerF;\n\t\t\treturn output;\n\t\t}`}static _GetSmoothEllipseFillFragmentShaderSource(){return`\n\t\t${fragmentUniformBufferDeclaration}\n\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t%%FRAGMENTOUTPUT_STRUCT%%\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\tvar diff : vec2 = input.fragUV - 0.5;\n\t\t\tvar diffSq : vec2 = diff * diff;\n\t\t\tvar norm : vec2 = normalize(diff);\n\t\t\tvar halfNorm : vec2 = norm * 0.5;\n\t\t\tvar halfNormSq : vec2 = halfNorm * halfNorm;\n\n\t\t\tvar innerEdge : vec2 = halfNorm - uniforms.pixelSize * norm;\n\t\t\tvar innerEdgeSq : vec2 = innerEdge * innerEdge;\n\n\t\t\tvar f : f32 = smoothstep(halfNormSq.x + halfNormSq.y, innerEdgeSq.x + innerEdgeSq.y, diffSq.x + diffSq.y);\n\n\t\t\toutput.color = vec4(input.fragColor) * f;\n\t\t\treturn output;\n\t\t}`}static _GetSmoothEllipseOutlineFragmentShaderSource(){return`\n\t\t${fragmentUniformBufferDeclaration}\n\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t%%FRAGMENTOUTPUT_STRUCT%%\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\tvar diff : vec2 = input.fragUV - 0.5;\n\t\t\tvar diffSq : vec2 = diff * diff;\n\t\t\tvar distSq : f32 = diffSq.x + diffSq.y;\n\t\t\tvar norm : vec2 = normalize(diff);\n\t\t\tvar halfNorm : vec2 = norm * 0.5;\n\t\t\tvar halfNormSq : vec2 = halfNorm * halfNorm;\n\n\t\t\tvar pxNorm : vec2 = uniforms.pixelSize * norm;\n\t\t\tvar innerEdge1 : vec2 = halfNorm - pxNorm;\n\t\t\tvar innerEdge1Sq : vec2 = innerEdge1 * innerEdge1;\n\n\t\t\tvar innerF : f32 = smoothstep(halfNormSq.x + halfNormSq.y, innerEdge1Sq.x + innerEdge1Sq.y, distSq);\n\n\t\t\tvar innerEdge2 : vec2 = halfNorm - pxNorm * uniforms.outlineThickness;\n\t\t\tvar innerEdge2Sq : vec2 = innerEdge2 * innerEdge2;\n\t\t\tvar innerEdge3 : vec2 = halfNorm - pxNorm * (uniforms.outlineThickness + 1.0);\n\t\t\tvar innerEdge3Sq : vec2 = innerEdge3 * innerEdge3;\n\n\t\t\tvar outerF : f32 = smoothstep(innerEdge3Sq.x + innerEdge3Sq.y, innerEdge2Sq.x + innerEdge2Sq.y, distSq);\n\t\t\t\n\t\t\toutput.color = vec4(input.fragColor) * innerF * outerF;\n\t\t\treturn output;\n\t\t}`}static _GetSmoothLineFillFragmentShaderSource(){return"\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t%%FRAGMENTOUTPUT_STRUCT%%\n\n\t\t@fragment\n\t\tfn main(input : FragmentInput) -> FragmentOutput {\n\t\t\tvar output : FragmentOutput;\n\t\t\tvar f : f32 = 1.0 - abs(input.fragUV.y - 0.5) * 2.0;\n\t\t\toutput.color = vec4(input.fragColor) * f;\n\t\t\treturn output;\n\t\t}"}}; } // ../lib/gfx/webgpu/texture.js { const C3=self.C3,VALID_WRAP_MODES=new Set(["clamp-to-edge","repeat","mirror-repeat"]),GPUTextureUsage=self["GPUTextureUsage"],DEFAULT_CREATE_OPTIONS={wrapX:"clamp-to-edge",wrapY:"clamp-to-edge",defaultSampling:"trilinear",anisotropy:1,mipMap:!0,isRenderTarget:!1,isSampled:!1,canReadPixels:!1,canUpdate:!1,multisampling:0,isWebGPUFastUpdate:!1,width:-1,height:-1},TEXTURE_FORMAT_SIZE_DATA=[[1,["r8unorm","r8snorm","r8uint","r8sint","stencil8"]],[2,["r16uint","r16sint","r16float","rg8unorm","rg8snorm","rg8uint","rg8sint","depth16unorm"]],[3,["depth24plus"]],[4,["r32uint","r32sint","r32float","rg16uint","rg16sint","rg16float","rgba8unorm","rgba8unorm-srgb","rgba8snorm","rgba8uint","rgba8sint","bgra8unorm","bgra8unorm-srgb","rgb9e5ufloat","rgb10a2uint","rgb10a2unorm","rg11b10ufloat","depth24plus-stencil8","depth32float"]],[8,["rg32uint","rg32sint","rg32float","rgba16uint","rgba16sint","rgba16float"]],[16,["rgba32uint","rgba32sint","rgba32float"]],[5,["depth32float-stencil8"]]],TEXTURE_FORMAT_SIZE_MAP=new Map;for(const[e,t]of TEXTURE_FORMAT_SIZE_DATA)for(const r of t)TEXTURE_FORMAT_SIZE_MAP.set(r,e);const allTextures=new Set,UPDATE_DEFAULT_OPTIONS={premultiplyAlpha:!0,flipY:!1};C3.Gfx.WebGPURendererTexture=class{#e=null;#t=null;#r="trilinear";#i=2;#s=[null,null,null];#a=[null,null,null];constructor(e,t){this._renderer=e,this._texture=null,this._format="",this._width=0,this._height=0,this._isStatic=!0,this._wrapX="clamp-to-edge",this._wrapY="clamp-to-edge",this._anisotropy=1,this._isMipMapped=!1,this._refCount=0,this._isRenderTarget=!1,this._isSampled=!1,this._canReadPixels=!1,this._canUpdate=!1,this._isFastUpdate=!1,this._multisampling=0,this._usage=0,this._multiTextureEnabled=!0,this._multiTextureGroup=null,this._multiTextureIndex=0,this._isForBackbuffer=!!t,this._isForBackbuffer&&(this._format=this._renderer.GetSwapChainFormat(),this._isRenderTarget=!0,this._isSampled=this._renderer._CanSampleBackbuffer())}_InitFromOpts(e){if(this._wrapX=e.wrapX,this._wrapY=e.wrapY,this._anisotropy=e.anisotropy,this._isMipMapped=!!e.mipMap&&this._renderer.AreMipmapsEnabled(),this.SetDefaultSampling(e.defaultSampling),this._isRenderTarget=!!e.isRenderTarget,this._isSampled=!!e.isSampled,this._canReadPixels=!!e.canReadPixels,this._canUpdate=!!e.canUpdate,this._isFastUpdate=!!e.isWebGPUFastUpdate,this._multisampling=this._renderer._ClampToSupportedMultisampleValues(e.multisampling),!VALID_WRAP_MODES.has(this._wrapX)||!VALID_WRAP_MODES.has(this._wrapY))throw new Error("invalid wrap mode");if(this._multisampling>=2&&this._isSampled)throw new Error("invalid use of multisampling");this._CreateGPUResources(),this._refCount=1}_CreateGPUResources(){const e=this._renderer._GetDevice();this._usage=0,this._isRenderTarget?(this._usage=GPUTextureUsage["RENDER_ATTACHMENT"],this._isSampled&&(this._usage|=GPUTextureUsage["TEXTURE_BINDING"]),this._canUpdate&&(this._usage|=GPUTextureUsage["COPY_DST"]),this._format=this._renderer.GetSwapChainFormat()):(this._usage=GPUTextureUsage["COPY_DST"]|GPUTextureUsage["TEXTURE_BINDING"],this._isFastUpdate&&(this._usage|=GPUTextureUsage["RENDER_ATTACHMENT"]),this._format=this._renderer.GetTextureFormat()),this._canReadPixels&&(this._usage|=GPUTextureUsage["COPY_SRC"]),this._texture=e["createTexture"]({"size":[this._width,this._height,1],"mipLevelCount":this._GetMipLevelCount(),"format":this._format,"usage":this._usage,"sampleCount":this._multisampling>=2?this._multisampling:1}),this.#e=this._texture["createView"](),this._isMipMapped?this.#t=this._texture["createView"]({"mipLevelCount":1}):this.#t=this.#e,this._CanMultiTexture()&&this._SetMultiTextureAvailable(!0),allTextures.add(this)}_GetSampler(e){const t=C3.Gfx.RendererBase.SamplingNumberToMode(e+1);return this._renderer._GetSampler({wrapX:this._wrapX,wrapY:this._wrapY,sampling:t,anisotropy:this._anisotropy})}#u(e){if(this._isRenderTarget&&!this._isSampled)throw new Error("cannot create bind group");const t=this._renderer,r=t._GetDevice(),i=this._GetSampler(e),s=this._GetTextureView(e),a=[],u=C3.Gfx.WebGPUMultiTextureGroup.GetMultiTextureLimit();for(let e=0;e0)throw new Error("texture still has references");if(!this._texture)throw new Error("already deleted texture");this._DeleteGPUResources()}_DisableMultiTexture(){this._multiTextureEnabled=!1,this._SetMultiTextureAvailable(!1)}_CanMultiTexture(){return this._isStatic&&this._multiTextureEnabled&&!this._isRenderTarget}_SetMultiTextureAvailable(e){this._renderer._SetMultiTextureAvailable(this,e)}_SetMultiTextureGroup(e,t){if(this._multiTextureGroup)throw new Error("already in a group");this._multiTextureGroup=e,this._multiTextureIndex=t,this._SetMultiTextureAvailable(!1)}_ClearMultiTextureGroup(){this._multiTextureGroup=null,this._multiTextureIndex=0,this._CanMultiTexture()&&this._SetMultiTextureAvailable(!0)}_GetOwnTextureBindGroup(e){return this.#s[e]||(this.#s[e]=this.#u(e)),this.#s[e]}_GetBackTextureBindGroup(e){return this.#a[e]||(this.#a[e]=this.#n(e)),this.#a[e]}_GetMultiTextureBindGroup(e){return null!==this._multiTextureGroup?this._multiTextureGroup._GetBindGroup(e):this._CanMultiTexture()?(this._renderer._TryCreateMultiTextureGroup(this),null!==this._multiTextureGroup?this._multiTextureGroup._GetBindGroup(e):null):null}_GetMultiTextureIndex(){return this._multiTextureIndex}GetWidth(){return this._isForBackbuffer?this._renderer.GetWidth():this._width}GetHeight(){return this._isForBackbuffer?this._renderer.GetHeight():this._height}GetRenderer(){return this._renderer}_GetTexture(){return this._texture}_GetTextureView(e=0){return 0===e?this.#t:this.#e}_GetFormat(){return this._format}GetDefaultSampling(){return this.#r}SetDefaultSampling(e){if(!C3.Gfx.RendererBase.IsValidSamplingMode(e)||"auto"===e)throw new Error("invalid sampling");"trilinear"!==e||this._isMipMapped||(e="bilinear"),this.#r=e,this.#i=C3.Gfx.RendererBase.SamplingModeToNumber(this.#r)-1}_GetDefaultSamplingIndex(){return this.#i}_SetAnisotropy(e){this._anisotropy=e,this.#s.fill(null),this.#a.fill(null)}IsRenderTarget(){return this._isRenderTarget}IsSampled(){return this._isSampled}CanReadPixels(){return this._canReadPixels}AddReference(){this._refCount++}SubtractReference(){if(this._refCount<=0)throw new Error("no more references");this._refCount--}GetReferenceCount(){return this._refCount}_GetUsage(){return this._usage}_BackbufferTextureSetProperties(e,t){this._usage=e,this._format=t}_BackbufferTextureStartFrame(){const e=this._renderer;this._texture=e._GetSwapChainTexture(),this.#e=e._GetSwapChainTexView(),this.#t=this.#e,this.#a.fill(null)}_BackbufferTextureEndFrame(){this._texture=null,this.#e=null,this.#t=null,this.#a.fill(null)}GetEstimatedMemoryUsage(){let e=this.GetWidth()*this.GetHeight()*C3.Gfx.WebGPURendererTexture.GetFormatByteSize(this._GetFormat());return this._isMipMapped&&(e+=Math.floor(e/3)),e}static OnContextLost(){}static allTextures(){return allTextures.values()}static GetFormatByteSize(e){const t=TEXTURE_FORMAT_SIZE_MAP.get(e);return"number"==typeof t?t:NaN}}; } // ../lib/gfx/webgpu/multiTextureGroup.js { const C3=self.C3,allMultiTextureGroups=new Set;C3.Gfx.WebGPUMultiTextureGroup=class{#e=[null,null,null];constructor(e,t){if(t.length<2)throw new Error("invalid multi-texture group");this._renderer=e,this._textures=t;for(let e=0,r=t.length;e=2&&r.isSampled)throw new Error("invalid use of multisampling");this._rendererTexture=this._renderer.CreateDynamicTexture(e,t,{defaultSampling:r.defaultSampling,mipMap:!1,isRenderTarget:!0,isSampled:r.isSampled,canReadPixels:r.canReadPixels,canUpdate:r.canUpdate,multisampling:this._multisampling}),this._CalculateProjection(),allRenderTargets.add(this)}_Delete(){allRenderTargets.delete(this),this._rendererTexture._DeleteGPUResources(),this._rendererTexture=null,this._renderer=null}_Resize(e,t){if(e===this.GetWidth()&&t===this.GetHeight())return;const r=this._rendererTexture.GetDefaultSampling(),i=this._rendererTexture.IsSampled(),s=this._rendererTexture.CanReadPixels();this._rendererTexture._DeleteGPUResources(),this._rendererTexture=null,this._rendererTexture=this._renderer.CreateDynamicTexture(e,t,{defaultSampling:r,mipMap:!1,isRenderTarget:!0,isSampled:i,canReadPixels:s}),this._CalculateProjection()}_GetTextureView(){return this._isBackBuffer?this._renderer._GetSwapChainTexView():this._rendererTexture._GetTextureView(this._rendererTexture._GetDefaultSamplingIndex())}_CalculateProjection(){this._renderer.CalculatePerspectiveMatrix(this._projectionMatrix,this.GetWidth()/this.GetHeight()),this._lastFov=this._renderer.GetFovY(),this._lastNearZ=this._renderer.GetNearZ(),this._lastFarZ=this._renderer.GetFarZ()}IsDefaultSize(){return this._isDefaultSize}IsBackBuffer(){return this._isBackBuffer}SetDefaultSampling(e){this._rendererTexture.SetDefaultSampling(e)}GetDefaultSampling(){return this._rendererTexture.GetDefaultSampling()}HasDepthBuffer(){return this._depth}GetWidth(){return this._isBackBuffer?this._renderer.GetWidth():this._rendererTexture.GetWidth()}GetHeight(){return this._isBackBuffer?this._renderer.GetHeight():this._rendererTexture.GetHeight()}GetTexture(){if(this._rendererTexture)return this._rendererTexture;throw new Error("no texture")}GetRenderer(){return this._renderer}GetMultisampling(){return this._multisampling}GetProjectionMatrix(){return this._renderer.GetFovY()===this._lastFov&&this._renderer.GetNearZ()===this._lastNearZ&&this._renderer.GetFarZ()===this._lastFarZ||this._CalculateProjection(),this._projectionMatrix}IsSampled(){return this._rendererTexture.IsSampled()}CanReadPixels(){return this._rendererTexture.CanReadPixels()}IsCompatibleWithOptions(e){return!!(e=Object.assign({},DEFAULT_RENDERTARGET_OPTIONS,e)).isSampled===this.IsSampled()&&(!!e.canReadPixels===this.CanReadPixels()&&(!!e.depth===this.HasDepthBuffer()&&("number"==typeof e.width||"number"==typeof e.height?!this.IsDefaultSize()&&this.GetWidth()===Math.floor(e.width)&&this.GetHeight()===Math.floor(e.height):this.IsDefaultSize())))}_SetIsAwaitingClear(e){this._isAwaitingClear=!!e}_IsAwaitingClear(){return this._isAwaitingClear}_GetClearColor(){return this._clearColor}static OnContextLost(){}static allRenderTargets(){return allRenderTargets.values()}}; } // ../lib/gfx/webgpu/timeQuerySet.js { const C3=self.C3;C3.Gfx.WebGPUTimeQuerySet=class{#e;#r=0;#t=null;#s=null;#u=null;constructor(e){this.#e=e}SetQueryCount(e){if(e!==this.#r&&(this.#r=e,this.#t&&this.#t["destroy"](),this.#s&&this.#s["destroy"](),this.#u&&this.#u["destroy"](),this.#r>0)){const e=this.#e._GetDevice();this.#t=e["createQuerySet"]({"count":this.#r,"type":"timestamp"});const r=globalThis["GPUBufferUsage"];this.#s=e["createBuffer"]({"size":this.#f(),"usage":r["QUERY_RESOLVE"]|r["COPY_SRC"]}),this.#u=this.#i()}}GetQueryCount(){return this.#r}#i(){const e=this.#e._GetDevice(),r=globalThis["GPUBufferUsage"];return e["createBuffer"]({"size":this.#f(),"usage":r["COPY_DST"]|r["MAP_READ"]})}#f(){return 8*this.#r}_GetQuerySet(){return this.#t}Resolve(e){e["resolveQuerySet"](this.#t,0,this.#r,this.#s,0),e["copyBufferToBuffer"](this.#s,0,this.#u,0,this.#f())}async GetResult(e){const r=this.#u;this.#u=this.#i();const t=this.#f();await r["mapAsync"](globalThis["GPUMapMode"]["READ"],0,t);const s=r["getMappedRange"](0,t),u=new BigUint64Array(s.slice(0));r["destroy"]();for(let r=0,t=u.length;r=1?this._GetRenderTarget():null,this._renderTargets[2]=2===this._numTempSurfacesRequired?this._GetRenderTarget():null,r.sampling&&(this._renderTargets[1]&&this._renderTargets[1].SetDefaultSampling(r.sampling),this._renderTargets[2]&&this._renderTargets[2].SetDefaultSampling(r.sampling));for(const t of this._steps){const r=this._GetRenderTargetForId(t.GetSrcTargetId()),s=this._GetRenderTargetForId(t.GetDestTargetId());e.IsWebGPU()?t.Run_WebGPU(e,r,s):t.Run_WebGL(e,r,s)}e.SetTexture(null),this._renderTargets[1]&&this._ReleaseRenderTarget(this._renderTargets[1]),this._renderTargets[2]&&this._ReleaseRenderTarget(this._renderTargets[2]),this._renderTargets.fill(null),this._OnAfterEndEffectChain(e),this._destRenderTarget=null,this._backTex=null,this._contentObject=null,this._contextObject=null,this._cbDrawContentHook=null}}_CalculateDrawSizeAndRectangles(e,t){const[r,s]=this._manager.GetDrawSize(e);this._SetDrawSize(e,r,s),this._CalculateRectangles(t)}_SetDrawSize(e,t,r){if(t<=0||r<=0)throw new Error("invalid draw size");this._drawWidth===t&&this._drawHeight===r||this._CalculateDeviceTransformMatrices(e,t,r,0,0,this._projectionMatrix,this._modelViewMatrix),this._drawWidth=t,this._drawHeight=r}_CalculateDeviceTransformMatrices(e,t,r,s,i,a,n){const h=t/2+s,c=r/2+i;e.CalculatePerspectiveMatrix(a,t/r);const o=e.CalculateLookAtModelView2(h,c,e.GetDefaultCameraZ(r),h,c,0,r);mat4.copy(n,o)}_CalculateRectangles(e){if(this._layoutRect.copy(e.layoutRect),e.drawSurfaceRect?this._drawSurfaceRect.copy(e.drawSurfaceRect):this._drawSurfaceRect.set(0,0,this._drawWidth,this._drawHeight),this._canUseFastPath){const t=e.compositOffX??0,r=e.compositOffY??0;this._drawSurfaceRect.offset(-t,-r)}this._rcTexOriginal.copy(this._drawSurfaceRect),this._rcTexOriginal.divide(this._drawWidth,this._drawHeight);const t=this._layerScale*this._devicePixelRatio;this._drawSurfaceRect.inflate(this._boxExtendHorizontal*t,this._boxExtendVertical*t),this._rcTexDest.copy(this._drawSurfaceRect),this._rcTexDest.divide(this._drawWidth,this._drawHeight),this._drawSurfaceRect.clampBoth(0,0,this._drawWidth,this._drawHeight),this._rcTexBounce.copy(this._drawSurfaceRect),this._rcTexBounce.divide(this._drawWidth,this._drawHeight)}_OnBeforeStartEffectChain(e){if(this._depthEnabledAtStart=e.IsDepthEnabled(),this._coplanarColorPassAtStart=e.IsCoplanarColorPass(),this._useFullSurface)e.SetDepthEnabled(!1),this._isAnyShaderDepthSampling&&e.SetDepthSamplingEnabled(!0);else{if(tempRect.copy(this._drawSurfaceRect),e.IsWebGL()){const e=this._layerScale*this._devicePixelRatio;tempRect.inflate(Math.max(this._boxExtendHorizontal,1)*e,Math.max(this._boxExtendVertical,1)*e),tempRect.roundOuter(),tempRect.clamp(0,0,this._drawWidth,this._drawHeight)}else tempRect.roundOuter();e.SetScissorRect(tempRect.getLeft(),tempRect.getTop(),tempRect.width(),tempRect.height(),this._drawHeight)}}_OnAfterEffectChainDrawContent(e){e.ResetColor(),this._useFullSurface||(this._coplanarColorPassAtStart?e.CoplanarRestoreStandardRendering(!1):e.SetDepthEnabled(!1),this._isAnyShaderDepthSampling&&e.SetDepthSamplingEnabled(!0)),e.IsWebGPU()&&e.SetNormalizedCoordsProgramVariant(!0)}_OnAfterEndEffectChain(e){e.SetDepthSamplingEnabled(!1),this._coplanarColorPassAtStart?e.CoplanarStartColorPass(this._depthEnabledAtStart):e.SetDepthEnabled(this._depthEnabledAtStart),this._useFullSurface||e.RemoveScissorRect(),e.IsWebGPU()&&e.SetNormalizedCoordsProgramVariant(!1),this._didChangeTransform=e.DidChangeTransform()}_ClampRcTexDest(){this._rcTexDest.clamp(0,0,1,1)}_GetRenderTargetForId(e){return e<0?null:this._renderTargets[e]}_GetRenderTarget(){return this._manager.GetRenderTarget(this)}_GetDestRenderTarget(){return this._destRenderTarget}_ReleaseRenderTarget(e){this._manager.ReleaseRenderTarget(e,this)}_GetShaderProgramAt(e){return this._shaderProgramList[e]}_DrawContent(e){this._cbDrawContentHook?this._cbDrawContentHook(this,e,()=>this._cbDrawContent(e,this)):this._cbDrawContent(e,this),this._canUseFastPath||this._OnAfterEffectChainDrawContent(e)}_IsRenderTargetSameSizeAndOffset(e){if(this._useFullSurface)return!0;if(0!==this._compositOffX||0!==this._compositOffY||0!==this._compositRtWidth||0!==this._compositRtHeight)return!1;const[t,r]=e.GetRenderTargetSize(e.GetRenderTarget());return t===this._drawWidth&&r===this._drawHeight}_SetDeviceTransform(e,t){let r=this._projectionMatrix,s=this._modelViewMatrix;if(t&&!this._IsRenderTargetSameSizeAndOffset(e)){let t,i;r=tempMat4a,s=tempMat4b,0!==this._compositRtWidth&&0!==this._compositRtHeight?[t,i]=[this._compositRtWidth,this._compositRtHeight]:[t,i]=e.GetRenderTargetSize(e.GetRenderTarget()),this._CalculateDeviceTransformMatrices(e,t,i,this._compositOffX,this._compositOffY,r,s),this._useFullSurface||e.RemoveScissorRect()}e.SetProjectionMatrix(r),e.SetModelViewMatrix(s)}_Redraw(){this._manager.Redraw(this)}_GetShaderParameters(e,t){return this._cbGetShaderParameters(this._shaderProgramIndices[e],t)}_SetProgramParameters(e,t){let r=this._rcTexDest,s=this._rcTexBounce,i=this._rcTexOriginal;e.IsWebGL()&&(tempRect2.copy(r),tempRect2.flipAround(1),r=tempRect2,tempRect3.copy(s),tempRect3.flipAround(1),s=tempRect3,tempRect4.copy(i),tempRect4.flipAround(1),i=tempRect4),this._DoSetProgramParameters(e,t,s,i,r,1/this._drawWidth,1/this._drawHeight)}_SetFirstBounceProgramParameters(e,t){let r=this._rcTexBounce,s=this._rcTexOriginal,i=1/this._drawWidth,a=1/this._drawHeight;if(this._cbGetSourceTextureInfo){let{srcTexRect:e,srcWidth:t,srcHeight:n}=this._cbGetSourceTextureInfo(this._contentObject);e||(tempRect.set(0,0,0,0),e=tempRect),t||(t=this._drawWidth),n||(n=this._drawHeight),r=e,s=e,i=1/t,a=1/n}else e.IsWebGL()&&(tempRect3.copy(r),tempRect3.flipAround(1),r=tempRect3,tempRect4.copy(s),tempRect4.flipAround(1),s=tempRect4);let n=this._rcTexDest;e.IsWebGL()&&(n=tempRect2,n.copy(this._rcTexDest),n.flipAround(1)),this._DoSetProgramParameters(e,t,r,s,n,i,a),e.IsWebGPU()&&this._isAnyIsSrcTexRotated&&e.SetProgramParameter_IsSrcTexRotated(this._isSourceTextureRotated)}_GetBackTex(e){return this._isAnyShaderBackgroundBlending?e.IsWebGPU()?this._UseCopyTextureBackgroundSampling()?this._backTex:this._destRenderTarget.GetTexture():this._destRenderTarget:null}_DoSetProgramParameters(e,t,r,s,i,a,n){e.SetProgramParameters(this._GetBackTex(e),i,r,s,this._layoutRect,a,n,this._devicePixelRatio,this._layerScale,this._layerAngle,this._time),e.SetProgramCustomParameters(this._GetShaderParameters(t,e))}_Render_FastPath(e,t){const r=this._shaderProgramList[0],s=e.IsDepthEnabled(),i=r.UsesDepth();i&&(e.SetDepthEnabled(!1),e.SetDepthSamplingEnabled(!0),this._rcTexDest.set(0,0,1,1),this._rcTexOriginal.set(0,0,1,1)),e.SetProgram(r),e.SetBlendMode(this._blendMode),e.SetRenderTarget(this._destRenderTarget),e.ResetCullState();let a=0,n=1;if(this._rcTexOriginal.set(0,0,1,1),r.UsesAnySrcRectOrPixelSize()&&this._cbGetSourceTextureInfo){const{srcTexRect:e,srcWidth:t,srcHeight:r}=this._cbGetSourceTextureInfo(this._contentObject);e&&this._rcTexOriginal.copy(e),a=Number.isFinite(t)?1/t:0,n=Number.isFinite(r)?1/r:0}else{const[t,r]=this._manager.GetDrawSize(e);a=1/t,n=1/r}t.layoutRect?this._layoutRect.copy(t.layoutRect):this._layoutRect.set(0,0,0,0),e.SetProgramParameters(this._GetBackTex(e),this._rcTexDest,this._rcTexOriginal,this._rcTexOriginal,this._layoutRect,a,n,this._devicePixelRatio,this._layerScale,this._layerAngle,this._time),e.SetProgramCustomParameters(this._GetShaderParameters(0,e)),e.IsWebGPU()&&this._isAnyIsSrcTexRotated&&e.SetProgramParameter_IsSrcTexRotated(this._isSourceTextureRotated),e.SetBaseZ(0),this._DrawContent(e),i&&(e.SetDepthSamplingEnabled(!1),e.SetDepthEnabled(s))}_UseCopyTextureBackgroundSampling(){return this._useCopyTextureBackgroundSampling}_UseRenderTargetBackgroundSampling(){return!this._useCopyTextureBackgroundSampling}IsAnyShaderBackgroundBlending(){return this._isAnyShaderBackgroundBlending}CanSkipCalculatingDrawSurfaceRect(){return!!this._canUseFastPath&&!this._UseCopyTextureBackgroundSampling()}UseFullSurface(){return this._useFullSurface}GetContentObject(){return this._contentObject}GetContextObject(){return this._contextObject}_GetBlendMode(){return this._blendMode}_UpdateOwnProjection(){return this._updateOwnProjection}DidChangeTransform(){return this._didChangeTransform}_GetDrawSurfaceRect(){return this._drawSurfaceRect}_GetRcTexBounce(){return this._rcTexBounce}_ShouldInvalidateRenderTargets(){return this._invalidateRenderTargets}async DebugLogRenderTargetContents(e,t,r){}}; } // ../lib/gfx/effectCompositor/step.js { const C3=self.C3;C3.Gfx.EffectChain.Step=class{constructor(t,e,r,s=-1){this._effectChain=t,this._srcTargetId=e,this._destTargetId=r,this._index=s}GetEffectChain(){return this._effectChain}GetSrcTargetId(){return this._srcTargetId}GetDestTargetId(){return this._destTargetId}GetIndex(){return this._index}GetShaderProgram(){return this.GetEffectChain()._GetShaderProgramAt(this.GetIndex())}Run_WebGL(t,e,r){}Run_WebGPU(t,e,r){}}; } // ../lib/gfx/effectCompositor/preDrawStep.js { const C3=self.C3;C3.Gfx.EffectChain.Step.PreDraw=class extends C3.Gfx.EffectChain.Step{constructor(e,t,a,n){super(e,t,a,n)}Run_WebGL(e,t,a){const n=this.GetEffectChain();e.SetAlphaBlend(),e.ResetCullState(),e.SetTextureFillMode(),e.SetRenderTarget(a,n._UpdateOwnProjection()),e.ClearRgba(0,0,0,0),n._DrawContent(e),n._ClampRcTexDest()}Run_WebGPU(e,t,a){const n=this.GetEffectChain();e.SetAlphaBlend(),e.ResetCullState(),e.SetTextureFillMode(),e.SetRenderTarget(a,!1),e.ClearRgba(0,0,0,0),n._DrawContent(e),n._ClampRcTexDest()}}; } // ../lib/gfx/effectCompositor/postDrawStep.js { const C3=self.C3,tempRect=C3.New(C3.Rect),tempQuad=C3.New(C3.Quad2D);C3.Gfx.EffectChain.Step.PostDraw=class extends C3.Gfx.EffectChain.Step{constructor(e,t,r,a){super(e,t,r,a)}Run_WebGL(e,t,r){const a=this.GetEffectChain();e.SetTextureFillMode(),e.SetRenderTarget(r),a._SetDeviceTransform(e,!0),e.SetBlendMode(a._GetBlendMode()),e.SetTexture(t.GetTexture()),tempQuad.setFromRect(a._GetDrawSurfaceRect()),tempRect.copy(a._GetRcTexBounce()),tempRect.flipAround(1),e.Quad3(tempQuad,tempRect),a._ShouldInvalidateRenderTargets()&&e.InvalidateRenderTarget(t)}Run_WebGPU(e,t,r){const a=this.GetEffectChain();e.SetTextureFillMode(),e.SetRenderTarget(r,!1),a._IsRenderTargetSameSizeAndOffset(e)?tempQuad.setFromRect(a._GetRcTexBounce()):(e.SetNormalizedCoordsProgramVariant(!1),a._SetDeviceTransform(e,!0),tempQuad.setFromRect(a._GetDrawSurfaceRect())),e.SetBackTexture(null),e.SetBlendMode(a._GetBlendMode()),e.SetTexture(t.GetTexture()),a.UseFullSurface()?e.FullscreenQuad():e.Quad3(tempQuad,a._GetRcTexBounce())}}; } // ../lib/gfx/effectCompositor/firstBounceStep.js { const C3=self.C3;C3.Gfx.EffectChain.Step.FirstBounce=class extends C3.Gfx.EffectChain.Step{constructor(e,t,r,a){super(e,t,r,a)}Run_WebGL(e,t,r){const a=this.GetEffectChain();e.SetRenderTarget(r,a._UpdateOwnProjection()),e.ClearRgba(0,0,0,0),e.SetCopyBlend(),e.SetProgram(this.GetShaderProgram()),a._SetFirstBounceProgramParameters(e,this.GetIndex()),a._DrawContent(e),a._ClampRcTexDest()}Run_WebGPU(e,t,r){const a=this.GetEffectChain();e.SetRenderTarget(r,!1),e.ClearRgba(0,0,0,0),e.SetCopyBlend(),e.SetProgram(this.GetShaderProgram()),a._SetFirstBounceProgramParameters(e,this.GetIndex()),a._DrawContent(e),a._ClampRcTexDest()}}; } // ../lib/gfx/effectCompositor/bounceStep.js { const C3=self.C3,tempRect=C3.New(C3.Rect),tempQuad=C3.New(C3.Quad2D);C3.Gfx.EffectChain.Step.Bounce=class extends C3.Gfx.EffectChain.Step{constructor(e,t,r,a){super(e,t,r,a)}Run_WebGL(e,t,r){const a=this.GetEffectChain();e.SetRenderTarget(r);const d=0===this.GetDestTargetId();d?e.SetBlendMode(a._GetBlendMode()):(e.ClearRgba(0,0,0,0),e.SetCopyBlend()),e.SetProgram(this.GetShaderProgram()),a._SetProgramParameters(e,this.GetIndex()),e.SetTexture(t.GetTexture()),a._SetDeviceTransform(e,d),tempQuad.setFromRect(a._GetDrawSurfaceRect()),tempRect.copy(a._GetRcTexBounce()),tempRect.flipAround(1),e.Quad3(tempQuad,tempRect),a._ShouldInvalidateRenderTargets()&&e.InvalidateRenderTarget(t)}Run_WebGPU(e,t,r){const a=this.GetEffectChain();e.SetRenderTarget(r,!1);0===this.GetDestTargetId()?(e.SetBlendMode(a._GetBlendMode()),e.SetBackTexture(null),a._IsRenderTargetSameSizeAndOffset(e)?tempQuad.setFromRect(a._GetRcTexBounce()):(e.SetNormalizedCoordsProgramVariant(!1),a._SetDeviceTransform(e,!0),tempQuad.setFromRect(a._GetDrawSurfaceRect()))):(e.ClearRgba(0,0,0,0),e.SetCopyBlend(),tempQuad.setFromRect(a._GetRcTexBounce())),e.SetProgram(this.GetShaderProgram()),a._SetProgramParameters(e,this.GetIndex()),e.SetTexture(t.GetTexture()),a.UseFullSurface()?e.FullscreenQuad():e.Quad3(tempQuad,a._GetRcTexBounce())}}; } // interfaces/IRuntime.js { const C3=self.C3,C3X=self.C3X;let runtime=null;const keysDownByKey=new Set,loggedDeprecationIds=new Set;function SortZOrderList(e,t){const r=e[0]-t[0];if(0!==r)return r;return e[1]-t[1]}const tempZOrderList=[],tempInstances=[];let didWarnInAlertPolyfill=!1;const VALID_FRAMERATE_MODES=new Set(["vsync","fixed","unlimited-tick","unlimited-frame"]),ANISOTROPIC_FILTERING_MODES=new Map([["auto",4],["off",1],["2x",2],["3x",3],["4x",4],["8x",8],["16x",16]]);self.IRuntime=class{constructor(e){runtime=e,Object.defineProperties(this,{assets:{value:runtime.GetAssetManager().GetIAssetManager(),writable:!1},collisions:{value:runtime.GetCollisionEngine().GetICollisionEngine(),writable:!1},objects:{value:{},writable:!1},globalVars:{value:{},writable:!1},projectName:{value:runtime.GetProjectName(),writable:!1},projectVersion:{value:runtime.GetProjectVersion(),writable:!1},projectId:{value:runtime.GetAppId(),writable:!1},projectUniqueId:{value:runtime.GetProjectUniqueId(),writable:!1},exportDate:{value:new Date(runtime.GetExportTimestamp()),writable:!1},storage:{value:new self.IStorage(runtime),writable:!1},isInWorker:{value:runtime.IsInWorker(),writable:!1},viewportWidth:{value:runtime.GetOriginalViewportWidth(),writable:!1},viewportHeight:{value:runtime.GetOriginalViewportHeight(),writable:!1},platformInfo:{value:new self.IPlatformInfo(e),writable:!1},sdk:{value:new self.ISDKUtils(e),writable:!1}}),runtime.UserScriptDispatcher().addEventListener("keydown",e=>{keysDownByKey.has(e["key"])?e.stopPropagation():keysDownByKey.add(e["key"])}),runtime.UserScriptDispatcher().addEventListener("keyup",e=>keysDownByKey.delete(e["key"])),runtime.Dispatcher().addEventListener("window-blur",()=>keysDownByKey.clear()),runtime.IsInWorker()&&(self["alert"]=e=>(didWarnInAlertPolyfill||(didWarnInAlertPolyfill=!0,console.warn("[Construct] alert() was called from a Web Worker, because the project 'Use worker' setting is enabled. This method is not normally available in a Web Worker. Construct has implemented the alert for you, but note that other features may be missing in worker mode. You may wish to disable 'Use worker', or use a more convenient function like console.log(). For more information please refer to the scripting section of the manual.")),this.alert(e)))}_InitObjects(e){Object.defineProperties(this.objects,e)}_InitGlobalVars(e){Object.defineProperties(this.globalVars,e)}addEventListener(e,t){runtime.UserScriptDispatcher().addEventListener(e,t)}removeEventListener(e,t){runtime.UserScriptDispatcher().removeEventListener(e,t)}callFunction(e,...t){C3X.RequireString(e);const r=runtime.GetEventSheetManager(),n=r.GetFunctionBlockByName(e);if(!n)throw new Error(`cannot find function name '${e}'`);if(!n.IsEnabled())return n.GetDefaultReturnValue();if(t.lengthe.GetILayout())}goToLayout(e){const t=runtime.GetLayoutManager();let r=null;if("number"!=typeof e&&"string"!=typeof e)throw new TypeError("expected string or number");if(r=t.GetLayout(e),!r)throw new Error("invalid layout");t.IsPendingChangeMainLayout()||t.ChangeMainLayout(r)}get keyboard(){const e=runtime._GetCommonScriptInterfaces().keyboard;if(!e)throw new Error("runtime.keyboard used but Keyboard object missing - add it to your project first");return e}get mouse(){const e=runtime._GetCommonScriptInterfaces().mouse;if(!e)throw new Error("runtime.mouse used but Mouse object missing - add it to your project first");return e}get touch(){const e=runtime._GetCommonScriptInterfaces().touch;if(!e)throw new Error("runtime.touch used but Touch object missing - add it to your project first");return e}get timelineController(){const e=runtime._GetCommonScriptInterfaces().timelineController;if(!e)throw new Error("runtime.timelineController used but Timeline Controller object missing - add it to your project first");return e}get renderer(){return runtime.GetCanvasManager().GetIRenderer()}invokeDownload(e,t){C3X.RequireString(e),C3X.RequireString(t),runtime.InvokeDownload(e,t)}getInstanceByUid(e){C3X.RequireFiniteNumber(e);const t=runtime.GetInstanceByUID(e);return t?t.GetInterfaceClass():null}sortZOrder(e,t){C3X.RequireFunction(t);const r=runtime.GetCurrentLayout();for(const t of e){const e=runtime._UnwrapIWorldInstance(t),r=e.GetWorldInfo();r.IsDestroyed()||(tempZOrderList.push([r.GetLayer().GetIndex(),r.GetZIndex()]),tempInstances.push(e))}if(0===tempZOrderList.length)return;tempZOrderList.sort(SortZOrderList),tempInstances.sort((e,r)=>t(e.GetInterfaceClass(),r.GetInterfaceClass()));let n=!1;for(let e=0,t=tempZOrderList.length;el._UnwrapIObjectClass(n)):[l._UnwrapIObjectClass(n)];const t=C3.Rect.FromObject(e),o=[];return collisionEngine.GetObjectClassesCollisionCandidates(null,i,t,o),o.map(n=>n.GetInterfaceClass())}}; } // interfaces/other/IPlatformInfo.js { const C3=self.C3,C3X=self.C3X;let runtime=null;const osMap=new Map([["Windows","windows"],["macOS","macos"],["Linux","linux"],["Chrome OS","chrome-os"],["Android","android"],["iOS","ios"]]),browserMap=new Map([["Chrome","chrome"],["Chromium","chromium"],["Edge","edge"],["Opera","opera"],["Firefox","firefox"],["Safari","safari"]]),browserEngineMap=new Map([["Chromium","chromium"],["Gecko","gecko"],["WebKit","webkit"]]);self.IPlatformInfo=class{constructor(e){runtime=e,Object.defineProperties(this,{isMobile:{value:C3.Platform.IsMobile,writable:!1},os:{value:osMap.get(C3.Platform.OS)||"unknown",writable:!1},osVersion:{value:C3.Platform.OSVersion,writable:!1},browser:{value:browserMap.get(C3.Platform.Browser)||"unknown",writable:!1},browserVersion:{value:C3.Platform.BrowserVersion,writable:!1},browserEngine:{value:browserEngineMap.get(C3.Platform.BrowserEngine)||"unknown",writable:!1}})}get exportType(){let e=runtime.GetExportType();return runtime.IsWindowsWebView2()?e="windows-webview2":"cordova"===e?e="Android"===C3.Platform.OS?"cordova-android":"cordova-ios":"playable-ad-single-file"!==e&&"playable-ad-zip"!==e||(e="playable-ad"),e}get renderer(){return runtime.GetCanvasManager().GetRendererString()}get rendererDetail(){return runtime.GetCanvasManager().GetRendererDetailString()}get canvasClientX(){return runtime.GetCanvasManager().GetCanvasClientX()}get canvasClientY(){return runtime.GetCanvasManager().GetCanvasClientY()}get canvasCssWidth(){return runtime.GetCanvasManager().GetCssWidth()}get canvasCssHeight(){return runtime.GetCanvasManager().GetCssHeight()}get canvasDeviceWidth(){return runtime.GetCanvasManager().GetDeviceWidth()}get canvasDeviceHeight(){return runtime.GetCanvasManager().GetDeviceHeight()}get devicePixelRatio(){return runtime.GetDevicePixelRatio()}}; } // interfaces/other/IStorage.js { const C3=self.C3,C3X=self.C3X;self.IStorage=class{constructor(e){this._storage=e._GetProjectStorage()}getItem(e){return C3X.RequireString(e),this._storage.getItem(e)}setItem(e,t){return C3X.RequireString(e),this._storage.setItem(e,t)}removeItem(e){return C3X.RequireString(e),this._storage.removeItem(e)}clear(){return this._storage.clear()}keys(){return this._storage.keys()}}; } // interfaces/util/IAABB3D.js { const C3=globalThis.C3,C3X=globalThis.C3X;globalThis.IAABB3D=class t{#t;constructor(t,a,b,s,e,o){this.#t=new C3.AABB3D(t??0,a??0,b??0,s??0,e??0,o??0),t instanceof C3.AABB3D&&this.#t.copy(t)}clone(){return new t(this.left,this.top,this.back,this.right,this.bottom,this.front)}copy(t){this.#t.set(t.left,t.top,t.back,t.right,t.bottom,t.front)}set(t,a,b,s,e,o){this.#t.set(t,a,b,s,e,o)}set left(t){this.#t.setLeft(t)}get left(){return this.#t.getLeft()}set top(t){this.#t.setTop(t)}get top(){return this.#t.getTop()}set back(t){this.#t.setBack(t)}get back(){return this.#t.getBack()}set right(t){this.#t.setRight(t)}get right(){return this.#t.getRight()}set bottom(t){this.#t.setBottom(t)}get bottom(){return this.#t.getBottom()}set front(t){this.#t.setFront(t)}get front(){return this.#t.getFront()}}; } // interfaces/objects/IPlugin.js { const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.IPlugin=class{#e;constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e,Object.defineProperties(this,{runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},id:{value:e.GetID(),writable:!1},isSingleGlobal:{value:e.IsSingleGlobal(),writable:!1},isWorldType:{value:e.IsWorldType(),writable:!1},isHTMLElementType:{value:e.IsHTMLElementType(),writable:!1},isRotatable:{value:e.IsRotatable(),writable:!1},hasEffects:{value:e.HasEffects(),writable:!1},is3d:{value:e.Is3D(),writable:!1},supportsHierarchies:{value:e.SupportsSceneGraph(),writable:!1},supportsMesh:{value:e.SupportsMesh(),writable:!1}}),e.GetRuntime()._MapScriptInterface(this,e)}static getByConstructor(e){if(!e)return null;const t=C3.AddonManager.GetPluginByConstructorFunction(e);return t?t.GetIPlugin():null}getSingleGlobalObjectType(){return this.#e.GetSingleGlobalObjectClass().GetIObjectClass()}getSingleGlobalInstance(){return this.#e.GetSingleGlobalInstance().GetInterfaceClass()}}; } // interfaces/objects/IObjectClass.js { const C3=globalThis.C3,C3X=globalThis.C3X,internalApiToken=C3._GetInternalAPIToken();globalThis.IObjectClass=class{#e;constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e,Object.defineProperties(this,{name:{value:e.GetName(),writable:!1},runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},plugin:{value:e.GetPlugin().GetIPlugin(),writable:!1}}),e.GetRuntime()._MapScriptInterface(this,e)}addEventListener(e,t){C3X.RequireString(e),C3X.RequireFunction(t),this.#e.UserScriptDispatcher().addEventListener(e,t)}removeEventListener(e,t){C3X.RequireString(e),C3X.RequireFunction(t),this.#e.UserScriptDispatcher().removeEventListener(e,t)}getAllInstances(){return[...this.instances()]}getFirstInstance(){return C3.first(this.instances())}getPickedInstances(){return[...this.pickedInstances()]}getFirstPickedInstance(){return C3.first(this.pickedInstances())}getPairedInstance(e){const t=this.#e,n=t.GetRuntime()._UnwrapIInstance(e),s=t.GetPairedInstance(n);return s?s.GetInterfaceClass():null}*instances(){for(const e of this.#e.instancesIncludingPendingCreate())yield e.GetInterfaceClass()}*pickedInstances(){for(const e of this.#e.GetCurrentSol().GetInstances())yield e.GetInterfaceClass()}callCustomAction(e,t,...n){C3X.RequireString(e);const s=this.#e,i=s.GetRuntime(),r=i.GetEventSheetManager(),a=r.GetCustomActionBlockByName(s,e);if(!a)throw new Error(`cannot find '${this.name}' custom action '${e}'`);if(!a.IsEnabled())return null;if(n.length0){const e={pickObjectClass:s,pickInstances:l},t=c.RunAsExpressionOrJSFunctionCall(o,a.IsCopyPicked(),0,null,e,...n);u.push(t)}if(r.size>0)for(const[t,s]of r){const i=t.GetOwnCustomActionByName(e).GetEventBlock(),r=[...new Set([...o,...i.GetSolModifiers()])],c={pickObjectClass:t,pickInstances:s},l=i.RunAsExpressionOrJSFunctionCall(r,a.IsCopyPicked(),0,null,c,...n);u.push(l)}return Promise.all(u)}{const e={pickObjectClass:a.GetObjectClass(),pickInstances:(Array.isArray(t)?t:[...t]).map(e=>i._UnwrapIInstance(e))},s=c.RunAsExpressionOrJSFunctionCall(o,a.IsCopyPicked(),0,null,e,...n);return s instanceof Promise?s:Promise.resolve()}}}; } // interfaces/objects/IObjectType.js { const C3=globalThis.C3,C3X=globalThis.C3X,internalApiToken=C3._GetInternalAPIToken();globalThis.IObjectType=class extends globalThis.IObjectClass{#e;constructor(){super();const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e}setInstanceClass(e){C3X.RequireFunction(e);const t=this.#e;if(t.GetInstanceCount()>0)throw new Error("setInstanceClass() called too late, because instances have already been created - call in runOnStartup");t._SetUserScriptInstanceClass(e)}createInstance(e,t,n,a,s){if(C3X.RequireNumber(t),C3X.RequireNumber(n),"number"!=typeof e&&"string"!=typeof e)throw new TypeError("invalid layer parameter");const r=this.#e,i=r.GetRuntime(),l=i.GetMainRunningLayout().GetLayer(e);if(!l)throw new Error("invalid layer");const c=i.CreateInstance(r,l,t,n,a,s);a&&l.SortAndAddInstancesByZIndex(c);const o=i.GetEventSheetManager();return o.BlockFlushingInstances(!0),c._TriggerOnCreatedOnSelfAndRelated(),o.BlockFlushingInstances(!1),o.IsInEventEngine()||i.GetLayoutManager().IsEndingLayout()||i.FlushPendingInstances(),c.GetInterfaceClass()}getAllFamilies(){return this.#e.GetFamilies().map(e=>e.GetIObjectClass())}*families(){for(const e of this.#e.GetFamilies())yield e.GetIObjectClass()}isInFamily(e){return C3X.RequireInstanceOf(e,globalThis.IFamily),e.hasObjectType(this)}}; } // interfaces/objects/IFamily.js { const C3=globalThis.C3,C3X=globalThis.C3X,IObjectType=globalThis.IObjectType,internalApiToken=C3._GetInternalAPIToken();globalThis.IFamily=class extends globalThis.IObjectClass{#e;constructor(){super();const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e}getAllObjectTypes(){return this.#e.GetFamilyMembers().map(e=>e.GetIObjectClass())}*objectTypes(){for(const e of this.#e.GetFamilyMembers())yield e.GetIObjectClass()}hasObjectType(e){C3X.RequireInstanceOf(e,IObjectType);const t=this.#e,s=t.GetRuntime()._UnwrapIObjectClass(e);return t.FamilyHasMember(s)}}; } // interfaces/layouts/ILayout.js { const C3=self.C3,C3X=self.C3X,VALID_WHERE_STRINGS=["above","below","top-sublayer","bottom-sublayer"];self.ILayout=class{#e;constructor(e){this.#e=e;const t=[],r=e.GetEffectList(),i=r.GetAllEffectTypes().length;for(let e=0;ee.GetILayer())}*allLayers(){for(const e of this.#e.allLayers())yield e.GetILayer()}addLayer(e,t,r){const i=this.#e,n=self.ILayer;C3X.RequireString(e),C3X.RequireOptionalInstanceOf(t,n);const a=t?i.GetRuntime()._UnwrapScriptInterface(t):null,s=VALID_WHERE_STRINGS.indexOf(r);if(s<0)throw new Error("invalid location");i.AddLayer(e,a,s)}moveLayer(e,t,r){const i=this.#e,n=i.GetRuntime(),a=self.ILayer;C3X.RequireInstanceOf(e,a);const s=n._UnwrapScriptInterface(e);if(!s)throw new Error("invalid layer");C3X.RequireOptionalInstanceOf(t,a);const o=t?n._UnwrapScriptInterface(t):null,l=VALID_WHERE_STRINGS.indexOf(r);if(l<0)throw new Error("invalid location");i.MoveLayer(s,o,l)}removeLayer(e){const t=this.#e,r=self.ILayer;C3X.RequireInstanceOf(e,r);const i=t.GetRuntime()._UnwrapScriptInterface(e);if(!i)throw new Error("invalid layer");const n=i.GetRuntime();t.RemoveLayer(i),n.GetEventSheetManager().IsInEventEngine()||n.FlushPendingInstances()}removeAllDynamicLayers(){const e=this.#e,t=e.GetRuntime();e.RemoveAllDynamicLayers(),t.GetEventSheetManager().IsInEventEngine()||t.FlushPendingInstances()}setVanishingPoint(e,t){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(t),this.#e.SetVanishingPointXY(e,t)}getVanishingPoint(){return this.#e.GetVanishingPoint()}set projection(e){C3X.RequireString(e);const t=this.#e;if("perspective"===e)t.SetPerspectiveProjection();else{if("orthographic"!==e)throw new Error("invalid projection");t.SetOrthographicProjection()}}get projection(){return this.#e.IsOrthographicProjection()?"orthographic":"perspective"}}; } // interfaces/layouts/ILayer.js { const C3=self.C3,C3X=self.C3X,BLEND_MODE_TO_INDEX=new Map([["normal",0],["additive",1],["copy",3],["destination-over",4],["source-in",5],["destination-in",6],["source-out",7],["destination-out",8],["source-atop",9],["destination-atop",10],["lighten",11],["darken",12],["multiply",13],["screen",14]]),INDEX_TO_BLEND_MODE=new Map([...BLEND_MODE_TO_INDEX.entries()].map(e=>[e[1],e[0]])),VALID_RENDERING_MODES=new Set(["2d","3d"]),tempColor=C3.New(C3.Color);self.ILayer=class{#e;constructor(e){this.#e=e;const t=[],r=e.GetEffectList(),i=r.GetAllEffectTypes().length;for(let e=0;ee.GetInterfaceClass()):[]}*otherContainerInstances(){const e=this.#e;if(e.IsInContainer())for(const t of e.siblings())yield t.GetInterfaceClass()}get uid(){return this.#e.GetUID()}get iid(){return this.#e.GetIID()}get templateName(){return this.#e.GetTemplateName()}set timeScale(e){C3X.RequireFiniteNumber(e),this.#e.SetTimeScale(e)}get timeScale(){return this.#e.GetActiveTimeScale()}restoreTimeScale(){this.#e.RestoreTimeScale()}get dt(){const e=this.#e;return e.GetRuntime().GetDt(e)}hasTag(e){return C3X.RequireString(e),this.#e.HasTag(e)}hasTags(...e){C3X.RequireArray(e);const t=new Set(e.map(e=>e.toLowerCase())),i=this.#e.GetLowercaseTagsSet();return t.isSubsetOf(i)}setAllTags(e){this.#e.SetTagsSet(C3.ensureSet(e))}getAllTags(){return new Set(this.#e.GetTagsSet())}signal(e){C3X.RequireString(e);const t=this.#e;t.GetRuntime().GetEventSheetManager().InstanceSignal(t,e)}waitForSignal(e){C3X.RequireString(e);const t=this.#e;return t.GetRuntime().GetEventSheetManager().WaitForInstanceSignal(t,e)}callCustomAction(e,...t){return this.objectType.callCustomAction(e,[this],...t)}}; } // interfaces/sdk/ISDKInstanceBase.js { const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.ISDKInstanceBase=class extends self.IInstance{#e;#t=!1;#n=null;#i=!1;#r=null;#s;#o;constructor(e){super(),this.#e=C3.AddonManager._GetInitObject2(internalApiToken),this.#t=!1,this.#n=null,this.#i=!1,this.#r=null,this.#s=e?.domComponentId,this.#o=e?.wrapperComponentId}_release(){this._setTicking(!1),this._setTicking2(!1),super._release()}_getInitProperties(){return C3.AddonManager._GetInitProperties()}_trigger(e){const t=this.#e;t.GetRuntime().Trigger(e,t)}_triggerAsync(e){const t=this.#e;return t.GetRuntime().TriggerAsync(e,t)}_addDOMMessageHandler(e,t){if(C3X.RequireString(e),C3X.RequireFunction(t),!this.#s)throw new Error("no DOM component id set");this.#e.GetRuntime().AddDOMComponentMessageHandler(this.#s,e,t)}_addDOMMessageHandlers(e){C3X.RequireArray(e);for(const[t,n]of e)this._addDOMMessageHandler(t,n)}_postToDOM(e,t){if(C3X.RequireString(e),!this.#s)throw new Error("no DOM component id set");this.#e.GetRuntime().PostComponentMessageToDOM(this.#s,e,t)}_postToDOMAsync(e,t){if(C3X.RequireString(e),!this.#s)throw new Error("no DOM component id set");return this.#e.GetRuntime().PostComponentMessageToDOMAsync(this.#s,e,t)}_postToDOMMaybeSync(e,t){if(!this.#e.GetRuntime().IsInWorker())return window["c3_runtimeInterface"]["_OnMessageFromRuntime"]({"type":"event","component":this.#s,"handler":e,"data":t,"responseId":null});this._postToDOM(e,t)}_setTicking(e){if(e=!!e,this.#t===e)return;this.#t=e;const t=this.#e.GetRuntime();if(e){if(!this.#n)if(this.#e.GetRuntime().IsDebug()){const e=globalThis.C3Debugger,t=this.plugin;this.#n=()=>{const n=performance.now();this._tick(),e.AddIndividualPluginTickTime(t,performance.now()-n)}}else this.#n=()=>this._tick();t.Dispatcher().addEventListener("tick",this.#n)}else t.Dispatcher().removeEventListener("tick",this.#n)}_isTicking(){return this.#t}_tick(){}_setTicking2(e){if(e=!!e,this.#i===e)return;this.#i=e;const t=this.#e.GetRuntime();if(e){if(!this.#r)if(this.#e.GetRuntime().IsDebug()){const e=globalThis.C3Debugger,t=this.plugin;this.#r=()=>{const n=performance.now();this._tick2(),e.AddIndividualPluginTickTime(t,performance.now()-n)}}else this.#r=()=>this._tick2();t.Dispatcher().addEventListener("tick2",this.#r)}else t.Dispatcher().removeEventListener("tick2",this.#r)}_isTicking2(){return this.#i}_tick2(){}_getDebuggerProperties(){return[]}_saveToJson(){return null}_loadFromJson(e){}_isWrapperExtensionAvailable(){if(!this.#o)throw new Error("no wrapper component id set");return this.#e.GetRuntime().HasWrapperComponentId(this.#o)}_addWrapperExtensionMessageHandler(e,t){if(C3X.RequireString(e),C3X.RequireFunction(t),!this.#o)throw new Error("no wrapper component id set");this.#e.GetRuntime().AddWrapperExtensionMessageHandler(this.#o,e,t)}_addWrapperMessageHandlers(e){C3X.RequireArray(e);for(const[t,n]of e)this._addWrapperExtensionMessageHandler(t,n)}_sendWrapperExtensionMessage(e,t){if(!this.#o)throw new Error("no wrapper component id set");this.runtime.sdk.sendWrapperExtensionMessage(this.#o,e,t)}_sendWrapperExtensionMessageAsync(e,t){if(!this.#o)throw new Error("no wrapper component id set");return this.runtime.sdk.sendWrapperExtensionMessageAsync(this.#o,e,t)}}; } // interfaces/objects/IWorldInstance.js { const C3=self.C3,C3X=self.C3X,IInstance=self.IInstance,ILayer=self.ILayer,tempAABB3D=new C3.AABB3D,tempQuad=new C3.Quad2D,map=new WeakMap,internalApiToken=C3._GetInternalAPIToken(),BLEND_MODE_TO_INDEX=new Map([["normal",0],["additive",1],["copy",3],["destination-over",4],["source-in",5],["destination-in",6],["source-out",7],["destination-out",8],["source-atop",9],["destination-atop",10],["lighten",11],["darken",12],["multiply",13],["screen",14]]),INDEX_TO_BLEND_MODE=new Map([...BLEND_MODE_TO_INDEX.entries()].map(t=>[t[1],t[0]])),tempColor=C3.New(C3.Color);function MakeIWorldInstanceClass(t){return class extends t{#t;#e;constructor(t){super(t);const e=C3.AddonManager._GetInitObject2(internalApiToken),i=e.GetWorldInfo();this.#t=e,this.#e=i,map.set(this,e);const n=[],r=i.GetInstanceEffectList();if(r){const t=i.GetObjectClass().GetEffectList().GetAllEffectTypes().length;for(let e=0;et.GetInterfaceClass())}static getByConstructor(t){if(!t)return null;const e=C3.AddonManager.GetBehaviorByConstructorFunction(t);return e?e.GetIBehavior():null}}; } // interfaces/objects/IEffectInstance.js { const C3=self.C3,C3X=self.C3X,tempColor=C3.New(C3.Color);self.IEffectInstance=class{#e;constructor(e,t){this.#e=e;const i={index:{value:t,writable:!1}};Object.defineProperties(this,i)}get name(){return this.#e.GetAllEffectTypes()[this.index].GetName()}get isActive(){return this.#e.IsEffectIndexActive(this.index)}set isActive(e){e=!!e;const t=this.#e;t.IsEffectIndexActive(this.index)!==e&&(t.SetEffectIndexActive(this.index,e),t.UpdateActiveEffects(),t.GetRuntime().UpdateRender())}setParameter(e,t){C3X.RequireFiniteNumber(e),e=Math.floor(+e);const i=this.#e,r=i.GetEffectParameter(this.index,e);if(null===r)throw new RangeError("invalid index");if(r instanceof C3.Color){if(!Array.isArray(t)||t.length<3)throw new TypeError("expected array with 3 elements");tempColor.setRgb(t[0],t[1],t[2]),t=tempColor}else if("number"!=typeof t)throw new TypeError("expected number");i.SetEffectParameter(this.index,e,t)&&i.IsEffectIndexActive(this.index)&&i.GetRuntime().UpdateRender()}getParameter(e){C3X.RequireFiniteNumber(e),e=Math.floor(+e);const t=this.#e.GetEffectParameter(this.index,e);if(null===t)throw new RangeError("invalid index");return t instanceof C3.Color?[t.getR(),t.getG(),t.getB()]:t}}; } // interfaces/objects/IAnimation.js { const C3=self.C3,C3X=self.C3X;self.IAnimation=class{#e;constructor(e){this.#e=e,Object.defineProperties(this,{name:{value:e.GetName(),writable:!1}})}get speed(){return this.#e.GetSpeed()}get isLooping(){return this.#e.IsLooping()}get repeatCount(){return this.#e.GetRepeatCount()}get repeatTo(){return this.#e.GetRepeatTo()}get isPingPong(){return this.#e.IsPingPong()}get frameCount(){return this.#e.GetFrameCount()}getFrames(){return this.#e.GetFrames().map(e=>e.GetIAnimationFrame())}*frames(){for(const e of this.#e.GetFrames())yield e.GetIAnimationFrame()}}; } // interfaces/objects/IImageInfo.js { const C3=self.C3,C3X=self.C3X;self.IImageInfo=class{#t;constructor(t){this.#t=t}static _Unwrap(t){return t.#t}get width(){return this.#t.GetWidth()}get height(){return this.#t.GetHeight()}getSize(){const t=this.#t;return[t.GetWidth(),t.GetHeight()]}getTexture(t){return t.getTextureForImageInfo(this)}getTexRect(){return this.#t.GetTexRect().toDOMRect()}}; } // interfaces/objects/IAnimationFrame.js { const C3=self.C3,C3X=self.C3X;self.IAnimationFrame=class extends self.IImageInfo{#t;constructor(t){super(t.GetImageInfo()),this.#t=t,Object.defineProperties(this,{duration:{value:t.GetDuration(),writable:!1},originX:{value:t.GetOriginX(),writable:!1},originY:{value:t.GetOriginY(),writable:!1}})}getOrigin(){const t=this.#t;return[t.GetOriginX(),t.GetOriginY()]}getImagePointCount(){return this.#t.GetImagePointCount()}getImagePointX(t){return this.getImagePoint(t)[0]}getImagePointY(t){return this.getImagePoint(t)[1]}getImagePoint(t){const e=this.#t;let i=null;if("number"==typeof t)i=e.GetImagePointByIndex(Math.floor(t));else{if("string"!=typeof t)throw new TypeError("expected string or number");i=e.GetImagePointByName(t)}return i?[i.GetX(),i.GetY()]:this.getOrigin()}getPolyPointCount(){const t=this.#t.GetCollisionPoly();return t?t.pointCount():0}getPolyPointX(t){return this.getPolyPoint(t)[0]}getPolyPointY(t){return this.getPolyPoint(t)[1]}getPolyPoint(t){C3X.RequireFiniteNumber(t),t=Math.floor(t);const e=this.#t.GetCollisionPoly();if(!e||t<0||t>=e.pointCount())return[0,0];const i=e.pointsArr();return[i[2*t],i[2*t+1]]}get tag(){return this.#t.GetTag()}}; } // interfaces/other/ITimelineStateBase.js { const C3=self.C3,C3X=self.C3X,map=new WeakMap;function GetTimelineState(e){const t=map.get(e);if(t.IsReleased())throw new Error("timeline/tween was released and is no longer valid");return t}self.ITimelineStateBase=class{constructor(e){map.set(this,e),e.GetRuntime()._MapScriptInterface(this,e)}pause(){GetTimelineState(this).Stop()}resume(){GetTimelineState(this).Resume()}stop(){GetTimelineState(this).Reset()}hasTags(e){return GetTimelineState(this).HasTags(e)}set time(e){C3X.RequireFiniteNumber(e),GetTimelineState(this).SetTime(e)}get time(){return GetTimelineState(this).GetTime()}set totalTime(e){C3X.RequireFiniteNumber(e),GetTimelineState(this).SetTotalTime(e)}get totalTime(){return GetTimelineState(this).GetTotalTime()}set isLooping(e){GetTimelineState(this).SetLoop(!!e)}get isLooping(){return GetTimelineState(this).GetLoop()}set isPingPong(e){GetTimelineState(this).SetPingPong(!!e)}get isPingPong(){return GetTimelineState(this).GetPingPong()}set playbackRate(e){C3X.RequireFiniteNumber(e),GetTimelineState(this).SetPlaybackRate(e)}get playbackRate(){return GetTimelineState(this).GetPlaybackRate()}get progress(){const e=GetTimelineState(this);return e.GetTime()/e.GetTotalTime()}get tags(){return GetTimelineState(this).GetTags()}get finished(){return GetTimelineState(this).GetPlayPromise()}get isPlaying(){return GetTimelineState(this).IsPlaying()}get isPaused(){return GetTimelineState(this).IsPaused()}get isReleased(){return map.get(this).IsReleased()}}; } // interfaces/other/ITimelineState.js { const C3=self.C3,C3X=self.C3X,map=new WeakMap;let easeToIndexFunc=null;function GetTimelineState(e){const t=map.get(e);if(t.IsReleased())throw new Error("timeline was released and is no longer valid");return t}self.ITimelineState=class extends self.ITimelineStateBase{constructor(e){super(e),map.set(this,e);const t={name:{value:e.GetName(),writable:!1}};Object.defineProperties(this,t)}}; } // interfaces/other/ITweenState.js { const C3=self.C3,C3X=self.C3X,map=new WeakMap,behInstMap=new WeakMap;let easeToIndexFunc=null;function GetTweenState(e){const t=map.get(e);if(t.IsReleased())throw new Error("tween was released and is no longer valid");return t}self.ITweenState=class extends self.ITimelineStateBase{constructor(e,t,n){super(e),easeToIndexFunc||(easeToIndexFunc=n.easeToIndexFunc),map.set(this,e),t&&behInstMap.set(this,t)}stop(){const e=GetTweenState(this);behInstMap.get(this).ReleaseTween(e)}setEase(e){C3X.RequireString(e);const t=self.Ease.GetEaseFromIndex(easeToIndexFunc(e));GetTweenState(this).SetEase(t)}get instance(){const e=GetTweenState(this).GetInstance();return e?e.GetInterfaceClass():null}get isDestroyOnComplete(){return GetTweenState(this).GetDestroyInstanceOnComplete()}set isDestroyOnComplete(e){GetTweenState(this).SetDestroyInstanceOnComplete(!!e)}get finished(){const e=GetTweenState(this);return e.GetPlayPromise().then(()=>new Promise(t=>{e.IsComplete()&&t()}))}get released(){return GetTweenState(this).GetReleasePromise()}get value(){const e=GetTweenState(this);if("value"!==e.GetId())throw new Error("not a value tween");return e.GetPropertyTrack("value").GetSourceAdapterValue()}}; } // interfaces/sdk/ISDKPluginBase.js { const C3=self.C3,C3X=self.C3X;self.ISDKPluginBase=class extends self.IPlugin{constructor(){super()}}; } // interfaces/sdk/ISDKDOMPluginBase.js { const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.ISDKDOMPluginBase=class extends self.ISDKPluginBase{#e;#n;#t=0;#s=new Map;constructor(e){if(super(),this.#e=C3.AddonManager._GetInitObject2(internalApiToken),!e?.domComponentId)throw new Error("no DOM component ID specified");this.#n=e.domComponentId,this._addElementMessageHandler("elem-focused",e=>e._onElemFocused()),this._addElementMessageHandler("elem-blurred",e=>{e&&e._onElemBlurred()})}_addElement(e){const n=this.#t++;return this.#s.set(n,e),n}_removeElement(e){this.#s.delete(e)}_addElementMessageHandler(e,n){this.#e.GetRuntime().AddDOMComponentMessageHandler(this.#n,e,e=>{const t=this.#s.get(e["elementId"]);n(t,e)})}_addElementMessageHandlers(e){C3X.RequireArray(e);for(const[n,t]of e)this._addElementMessageHandlers(n,t)}}; } // interfaces/sdk/ISDKObjectTypeBase.js { const C3=self.C3,C3X=self.C3X,map=new WeakMap,internalApiToken=C3._GetInternalAPIToken();self.ISDKObjectTypeBase=class extends self.IObjectType{#e;constructor(){super(),this.#e=C3.AddonManager._GetInitObject2(internalApiToken)}_onCreate(){}getImageInfo(){return this.#e.GetImageInfo().GetIImageInfo()}_loadTextures(e){}_releaseTextures(e){}_onDynamicTextureLoadComplete(){}_preloadTexturesWithInstances(e){}}; } // interfaces/sdk/ISDKWorldInstanceBase.js { const C3=self.C3,C3X=self.C3X,map=new WeakMap,internalApiToken=C3._GetInternalAPIToken();self.ISDKWorldInstanceBase=class extends self.IWorldInstanceSDKBase{#e;#t=null;#r=null;constructor(e){super(e),this.#e=C3.AddonManager._GetInitObject2(internalApiToken)}_release(){if(super._release(),this.#t){const e=this.#e.GetRuntime().Dispatcher();e.removeEventListener("renderercontextlost",this.#t),e.removeEventListener("renderercontextrestored",this.#r),this.#t=null,this.#r=null}}_handleRendererContextLoss(){if(this.#t)return;this.#t=()=>this._onRendererContextLost(),this.#r=()=>this._onRendererContextRestored();const e=this.#e.GetRuntime().Dispatcher();e.addEventListener("renderercontextlost",this.#t),e.addEventListener("renderercontextrestored",this.#r)}_onRendererContextLost(){}_onRendererContextRestored(){}_draw(e){}_isOriginalSizeKnown(){return!1}_getOriginalSize(){}_rendersToOwnZPlane(){return!0}_setMustMitigateZFighting(){this.#e.SetMustMitigateZFighting()}_mustPreDraw(){return!1}}; } // interfaces/sdk/ISDKDOMInstanceBase.js { const C3=self.C3,C3X=self.C3X,tempRect=C3.New(C3.Rect),map=new WeakMap,internalApiToken=C3._GetInternalAPIToken();self.ISDKDOMInstanceBase=class extends self.ISDKWorldInstanceBase{#e=-1;#t=!0;#s=!1;#i=!1;#n=-.2;#o=C3.New(C3.Rect,0,0,-1,-1);#l=0;#a=0;#h=-1;#d=-1;#m=!1;constructor(e){if(!e?.domComponentId)throw new Error("no DOM component ID specified");super(e);const t=C3.AddonManager._GetInitObject2(internalApiToken);map.set(this,t),this.#e=this.plugin._addElement(this);const s=t.GetRuntime().GetCanvasManager();this.#l=s.GetLastWidth(),this.#a=s.GetLastHeight(),this._setTicking(!0)}_release(){super._release(),this.plugin._removeElement(this.#e),this._postToDOMElement("destroy"),this.#e=-1,map.delete(this)}_getElementInDOMMode(){if(map.get(this).GetRuntime().IsInWorker())throw new Error("not valid in worker mode");return this._postToDOMElementMaybeSync("get-element")}_postToDOMElement(e,t){t||(t={}),t["elementId"]=this.#e,this._postToDOM(e,t)}_postToDOMElementMaybeSync(e,t){return t||(t={}),t["elementId"]=this.#e,this._postToDOMMaybeSync(e,t)}_postToDOMElementAsync(e,t){return t||(t={}),t["elementId"]=this.#e,this._postToDOMAsync(e,t)}_createElement(e){e||(e={});const t=map.get(this).GetWorldInfo();e["elementId"]=this.#e,e["isVisible"]=t.IsVisible(),e["htmlIndex"]=t.GetLayer().GetHTMLIndex(),e["htmlZIndex"]=t.GetHTMLZIndex(),Object.assign(e,this._getElementState()),this.#t=!!e["isVisible"],this._postToDOMMaybeSync("create",e),this._updatePosition(!0)}setElementVisible(e){e=!!e,this.#t!==e&&(this.#t=e,this._postToDOMElement("set-visible",{"isVisible":e}))}_tick(){this._updatePosition(!1)}_shouldPreserveElement(){const e=map.get(this).GetRuntime().GetCanvasManager().GetFullscreenMode();return"Android"===C3.Platform.OS&&("scale-inner"===e||"integer-scale-inner"===e||"scale-outer"===e||"integer-scale-outer"===e||"crop"===e)}_updatePosition(e){const t=map.get(this);if(t.IsDestroyed())return;const s=t.GetWorldInfo(),i=s.GetLayer(),n=s.GetBoundingBox();let[o,l]=i.LayerToCanvasCss(n.getLeft(),n.getTop()),[a,h]=i.LayerToCanvasCss(n.getRight(),n.getBottom());const d=t.GetRuntime().GetCanvasManager(),m=d.GetCssWidth(),r=d.GetCssHeight();if(!s.IsVisible()||!i.IsVisible())return void this.setElementVisible(!1);if(!this._shouldPreserveElement()&&(a<=0||h<=0||o>=m||l>=r))return void this.setElementVisible(!1);tempRect.set(o,l,a,h);const c=d.GetLastWidth(),u=d.GetLastHeight(),p=i.GetHTMLIndex(),M=s.GetHTMLZIndex();if(!e&&tempRect.equals(this.#o)&&this.#l===c&&this.#a===u&&this.#h===p&&this.#d===M)return void this.setElementVisible(!0);this.#o.copy(tempRect),this.#l=c,this.#a=u,this.#h=p,this.#d=M,this.setElementVisible(!0);let I=null;this.#i&&(I=i.GetDisplayScale()+this.#n),this._postToDOMElement("update-position",{"left":Math.round(this.#o.getLeft()),"top":Math.round(this.#o.getTop()),"width":Math.round(this.#o.width()),"height":Math.round(this.#o.height()),"htmlIndex":p,"htmlZIndex":M,"fontSize":I})}focusElement(){this._postToDOMElementMaybeSync("focus",{"focus":!0})}blurElement(){this._postToDOMElementMaybeSync("focus",{"focus":!1})}_onElemFocused(){this.#s=!0}_onElemBlurred(){this.#s=!1}isElementFocused(){return this.#s}setElementCSSStyle(e,t){this.postToDOMElement("set-css-style",{"prop":C3.CSSToCamelCase(e),"val":t})}setElementAttribute(e,t){this.postToDOMElement("set-attribute",{"name":e,"val":t})}removeElementAttribute(e){this.postToDOMElement("remove-attribute",{"name":e})}_updateElementState(){this.#m||(this.#m=!0,Promise.resolve().then(()=>{this.#m=!1,this._postToDOMElement("update-state",this._getElementState())}))}_getElementState(){}_getElementId(){return this.#e}}; } // interfaces/sdk/ISDKBehaviorBase.js { const C3=self.C3,C3X=self.C3X;self.ISDKBehaviorBase=class extends self.IBehavior{constructor(){super()}}; } // interfaces/sdk/ISDKBehaviorTypeBase.js { const C3=self.C3,C3X=self.C3X;self.ISDKBehaviorTypeBase=class extends globalThis.IBehaviorType{constructor(){super()}_onCreate(){}}; } // interfaces/sdk/ISDKBehaviorInstanceBase.js { const C3=self.C3,C3X=self.C3X,map=new WeakMap,internalApiToken=C3._GetInternalAPIToken();self.ISDKBehaviorInstanceBase=class extends self.IBehaviorInstance{#i=!1;#t=!1;#e=!1;constructor(){super(),map.set(this,C3.AddonManager._GetInitObject2(internalApiToken))}_release(){super._release(),this._setTicking(!1),this._setTicking2(!1),this._setPostTicking(!1),map.delete(this)}_getInitProperties(){return C3.AddonManager._GetInitProperties()}_postCreate(){}_trigger(i){const t=map.get(this);t.GetRuntime().Trigger(i,t.GetObjectInstance(),t.GetBehaviorType())}_triggerAsync(i){const t=map.get(this);return t.GetRuntime().TriggerAsync(i,t.GetObjectInstance(),t.GetBehaviorType())}_setTicking(i){if(i=!!i,this.#i===i)return;this.#i=i;const t=map.get(this).GetRuntime();i?t._AddBehInstToTick(this):t._RemoveBehInstToTick(this)}_isTicking(){return this.#i}_tick(){}_setTicking2(i){if(i=!!i,this.#t===i)return;this.#t=i;const t=map.get(this).GetRuntime();i?t._AddBehInstToTick2(this):t._RemoveBehInstToTick2(this)}_isTicking2(){return this.#t}_tick2(){}_setPostTicking(i){if(i=!!i,this.#e===i)return;this.#e=i;const t=map.get(this).GetRuntime();i?t._AddBehInstToPostTick(this):t._RemoveBehInstToPostTick(this)}_isPostTicking(){return this.#e}_postTick(){}_getDebuggerProperties(){return[]}_saveToJson(){return null}_loadFromJson(i){}}; } // interfaces/sdk/ISDKUtils.js { const C3=self.C3,C3X=self.C3X;let runtime=null;self.ISDKUtils=class{constructor(e){runtime=e,Object.defineProperties(this,{constructVersionCode:{value:runtime.GetConstructVersionCode(),writable:!1}})}updateRender(){runtime.UpdateRender()}addLoadPromise(e){runtime.AddLoadPromise(e)}isWrapperExtensionAvailable(e){return C3X.RequireString(e),runtime.HasWrapperComponentId(e)}sendWrapperExtensionMessage(e,n,t){C3X.RequireString(e),C3X.RequireString(n),C3X.RequireOptionalArray(t),runtime.SendWrapperExtensionMessage(e,n,t)}sendWrapperExtensionMessageAsync(e,n,t){return C3X.RequireString(e),C3X.RequireString(n),C3X.RequireOptionalArray(t),runtime.SendWrapperExtensionMessageAsync(e,n,t)}createLoopingConditionContext(e){return C3X.RequireOptionalString(e),new self.ILoopingConditionContext(runtime,e)}set isAutoSuspendEnabled(e){runtime._SetAutoSuspendEnabled(!!e)}get isAutoSuspendEnabled(){return runtime._IsAutoSuspendEnabled()}setSuspended(e){runtime.SetSuspended(!!e)}getObjectClassBySid(e){C3X.RequireNumber(e);const n=runtime.GetObjectClassBySID(e);return n?n.GetIObjectClass():null}}; } // interfaces/sdk/ILoopingConditionContext.js { const C3=self.C3,C3X=self.C3X;self.ILoopingConditionContext=class{#e;#t;#o;#n;#s;#r;constructor(e,t){this.#e=e;const o=e.GetEventSheetManager(),n=e.GetCurrentEvent();this.#t=n,this.#o=n.GetSolModifiers();const s=e.GetEventStack();this.#n=s.GetCurrentStackFrame(),this.#s=s.Push(n);const r=o.GetLoopStack().Push();this.#r=r,t&&r.SetName(t),e.SetDebuggingEnabled(!1)}retrigger(){const e=this.#e.GetEventSheetManager(),t=this.#o,o=this.#r;e.PushCopySol(t),this.#t.Retrigger(this.#n,this.#s),e.PopSol(t),o.SetIndex(o.GetIndex()+1)}get isStopped(){return this.#r.IsStopped()}release(){const e=this.#e,t=e.GetEventStack(),o=e.GetEventSheetManager().GetLoopStack();e.SetDebuggingEnabled(!0),o.Pop(),t.Pop()}}; } // interfaces/gfx/IRenderer.js { const C3=globalThis.C3,C3X=globalThis.C3X;function IsStaticTextureDataType(e){return e instanceof ImageBitmap||"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas}const CULL_MODE_ARR=["none","back","front"],FRONT_FACE_WINDING_ARR=["cw","ccw"],DEFAULT_MESHDATA_OPTS={debugLabel:""};globalThis.IRenderer=class{#e;#r;constructor(e,r){this.#e=e,this.#r=r}setAlphaBlendMode(){this.#r.SetAlphaBlend()}setBlendMode(e){this.#r.SetNamedBlendMode(e)}setColorFillMode(){this.#r.SetColorFillMode()}setTextureFillMode(){this.#r.SetTextureFillMode()}setSmoothLineFillMode(){this.#r.SetSmoothLineFillMode()}setColor(e){this.#r.SetColorRgba(e[0],e[1],e[2],e[3])}setColorRgba(e,r,t,n){this.#r.SetColorRgba(e,r,t,n)}resetColor(){this.#r.ResetColor()}setOpacity(e){this.#r.SetOpacity(e)}setCurrentZ(e){this.#r.SetCurrentZ(e)}getCurrentZ(){return this.#r.GetCurrentZ()}setCullFaceMode(e){const r=CULL_MODE_ARR.indexOf(e);if(-1===r)throw new Error("invalid cull mode");this.#r.SetCullFaceMode(r)}getCullFaceMode(){return CULL_MODE_ARR[this.#r.GetCullFaceMode()]}setFrontFaceWinding(e){const r=FRONT_FACE_WINDING_ARR.indexOf(e);if(-1===r)throw new Error("invalid front face winding");this.#r.SetFrontFaceWinding(r)}getFrontFaceWinding(){return FRONT_FACE_WINDING_ARR[this.#r.GetFrontFaceWinding()]}rect(e){this.#r.Rect2(e.left,e.top,e.right,e.bottom)}rect2(e,r,t,n){this.#r.Rect2(e,r,t,n)}quad(e){this.#r.Quad(C3.Quad2D.fromDOMQuad(e))}quad2(e,r,t,n,a,i,d,s){this.#r.Quad2(e,r,t,n,a,i,d,s)}quad3(e,r){this.#r.Quad3(C3.Quad2D.fromDOMQuad(e),C3.Rect.fromDOMRect(r))}quad4(e,r){this.#r.Quad4(C3.Quad2D.fromDOMQuad(e),C3.Quad2D.fromDOMQuad(r))}quad5(e,r,t){this.#r.Quad5(C3.Quad2D.fromDOMQuad(e),C3.Quad2D.fromDOMQuad(r),t)}quad3D(e,r,t,n,a,i,d,s,o,u,l,h,c){this.#r.Quad3D(e,r,t,n,a,i,d,s,o,u,l,h,C3.Rect.fromDOMRect(c))}quad3D2(e,r,t,n,a,i,d,s,o,u,l,h,c){this.#r.Quad3D2(e,r,t,n,a,i,d,s,o,u,l,h,C3.Quad2D.fromDOMQuad(c))}quad3D3(e,r,t,n,a,i,d,s,o,u,l,h,c,p){this.#r.Quad3D3(e,r,t,n,a,i,d,s,o,u,l,h,C3.Quad2D.fromDOMQuad(c),p)}drawMesh(e,r,t,n){this.#r.DrawMesh(e,r,t,n)}createMeshData(e,r,t){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(r),t=Object.assign({},DEFAULT_MESHDATA_OPTS,t);const n=this.#r.CreateMeshData(e,r,{debugLabel:t.debugLabel});n.CreateGPUResources();const a=new globalThis.IMeshData(n);return this.#e._MapScriptInterface(a,n),a}drawMeshData(e,r=0,t=e.indexCount){const n=this.#e._UnwrapScriptInterface(e);this.#r.DrawMeshData(n,r,t)}convexPoly(e){this.#r.ConvexPoly(e)}line(e,r,t,n){this.#r.Line(e,r,t,n)}texturedLine(e,r,t,n,a,i){this.#r.TexturedLine(e,r,t,n,a,i)}lineRect(e,r,t,n){this.#r.LineRect(e,r,t,n)}lineRect2(e){this.#r.LineRect2(C3.Rect.fromDOMRect(e))}lineQuad(e){this.#r.LineQuad(C3.Quad2D.fromDOMQuad(e))}pushLineWidth(e){this.#r.PushLineWidth(e)}popLineWidth(){this.#r.PopLineWidth()}pushLineCap(e){this.#r.PushLineCap(e)}popLineCap(){this.#r.PopLineCap()}setTexture(e,r="auto"){C3X.RequireOptionalInstanceOf(e,globalThis.ITexture);const t=e?this.#e._UnwrapScriptInterface(e):null;this.#r.SetTexture(t,C3.Gfx.RendererBase.SamplingModeToNumber(r))}loadTextureForImageInfo(e,r){const t=globalThis.IImageInfo._Unwrap(e);if(!t)throw new Error("invalid IImageInfo");return t.LoadStaticTexture(this.#r,{wrapX:r?.wrapX??"clamp-to-edge",wrapY:r?.wrapY??"clamp-to-edge",defaultSampling:r?.defaultSampling??r?.sampling??"trilinear",mipMap:r?.mipMap??!0})}releaseTextureForImageInfo(e){const r=globalThis.IImageInfo._Unwrap(e);if(!r)throw new Error("invalid IImageInfo");r.ReleaseTexture()}getTextureForImageInfo(e){const r=globalThis.IImageInfo._Unwrap(e);if(!r)throw new Error("invalid IImageInfo");const t=r.GetTexture();return globalThis.ITexture.GetInterface(this.#e,t)}createStaticTexture(e,r){if(!IsStaticTextureDataType(e))throw new TypeError("invalid texture data");const t=this.#r.CreateStaticTexture(e,{wrapX:r?.wrapX??"clamp-to-edge",wrapY:r?.wrapY??"clamp-to-edge",defaultSampling:r?.defaultSampling??r?.sampling??"trilinear",mipMap:r?.mipMap??!0});return globalThis.ITexture.GetInterface(this.#e,t)}createDynamicTexture(e,r,t){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(r);const n=this.#r.CreateDynamicTexture(e,r,{wrapX:t?.wrapX??"clamp-to-edge",wrapY:t?.wrapY??"clamp-to-edge",defaultSampling:t?.defaultSampling??t?.sampling??"trilinear",mipMap:t?.mipMap??!0});return globalThis.ITexture.GetInterface(this.#e,n)}updateTexture(e,r,t){C3X.RequireInstanceOf(r,globalThis.ITexture);const n=this.#e._UnwrapScriptInterface(r);this.#r.UpdateTexture(e,n,{premultiplyAlpha:t?.premultiplyAlpha??!0})}deleteTexture(e){C3X.RequireInstanceOf(e,globalThis.ITexture);const r=this.#e._UnwrapScriptInterface(e);this.#r.DeleteTexture(r)}createRendererText(){const e=this.#r.CreateRendererText();return new globalThis.IRendererText(this.#e,e)}setDeviceTransform(){this.#e.GetCanvasManager().SetDeviceTransform(this.#r)}setLayerTransform(e){C3X.RequireInstanceOf(e,globalThis.ILayer);this.#e._UnwrapScriptInterface(e)._SetTransform(this.#r)}}; } // interfaces/gfx/ITexture.js { const C3=globalThis.C3,C3X=globalThis.C3X,reverseMap=new WeakMap;globalThis.ITexture=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t,reverseMap.set(t,this),e._MapScriptInterface(this,t),Object.defineProperties(this,{width:{value:t.GetWidth(),writable:!1},height:{value:t.GetHeight(),writable:!1},defaultSampling:{value:t.GetDefaultSampling(),writable:!1}})}static GetInterface(e,t){if(!t)return null;const r=reverseMap.get(t);return r||new globalThis.ITexture(e,t)}}; } // interfaces/gfx/IRendererText.js { const C3=globalThis.C3,C3X=globalThis.C3X;globalThis.IRendererText=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t,e._MapScriptInterface(this,t)}release(){this.#t.Release()}set fontFace(e){C3X.RequireString(e),this.#t.SetFontName(e)}get fontFace(){return this.#t.GetFontName()}set sizePt(e){C3X.RequireFiniteNumber(e),this.#t.SetFontSize(e)}get sizePt(){return this.#t.GetFontSize()}set lineHeight(e){C3X.RequireFiniteNumber(e),this.#t.SetLineHeight(e)}get lineHeight(){return this.#t.GetLineHeight()}set isBold(e){this.#t.SetBold(e)}get isBold(){return this.#t.IsBold()}set isItalic(e){this.#t.SetItalic(e)}get isItalic(){return this.#t.IsItalic()}setColor(e){C3X.RequireArray(e),this.setColorRgb(e[0],e[1],e[2])}setColorRgb(e,t,r){this.#t.SetColorRgb(e,t,r)}setCssColor(e){C3X.RequireString(e),this.#t.SetColor(e)}set horizontalAlign(e){this.#t.SetHorizontalAlignment(e)}get horizontalAlign(){return this.#t.GetHorizontalAlignment()}set verticalAlign(e){this.#t.SetVerticalAlignment(e)}get verticalAlign(){return this.#t.GetVerticalAlignment()}set wordWrapMode(e){this.#t.SetWordWrapMode(e)}get wordWrapMode(){return this.#t.GetWordWrapMode()}set textDirection(e){this.#t.SetTextDirection(e)}get textDirection(){return this.#t.GetTextDirection()}set text(e){C3X.RequireString(e),this.#t.SetText(e)}get text(){return this.#t.GetText()}setSize(e,t,r){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(t),C3X.RequireFiniteNumber(r),this.#t.SetSize(e,t,r)}getTexture(){const e=this.#t.GetTexture();return globalThis.ITexture.GetInterface(this.#e,e)}getTexRect(){return this.#t.GetTexRect().toDOMRect()}setTextureUpdateCallback(e){C3X.RequireFunction(e),this.#t.ontextureupdate=e}releaseTexture(){this.#t.ReleaseTexture()}get textWidth(){return this.#t.GetTextWidth()}get textHeight(){return this.#t.GetTextHeight()}}; } // interfaces/gfx/IMeshData.js { const C3=globalThis.C3,C3X=globalThis.C3X;globalThis.IMeshData=class{#e;constructor(e){this.#e=e,Object.defineProperties(this,{vertexCount:{value:e.GetVertexCount(),writable:!1},indexCount:{value:e.GetIndexCount(),writable:!1},positions:{value:e.positions,writable:!1},texCoords:{value:e.texCoords,writable:!1},colors:{value:e.colors,writable:!1},indices:{value:e.indices,writable:!1},debugLabel:{value:e.GetDebugLabel(),writable:!1}})}markDataChanged(e,a,t){this.#e.MarkDataChanged(e,a,t)}markAllVertexDataChanged(e=0,a=this.vertexCount){this.#e.MarkAllVertexDataChanged(e,a)}markIndexDataChanged(e=0,a=this.indexCount){this.#e.MarkIndexDataChanged(e,a)}fillColor(e,a,t,l){this.#e.FillColor(e,a,t,l)}release(){this.#e.Release()}}; } // assets/assetManager.js { const C3=self.C3,VALID_LOAD_POLICIES=new Set(["local","remote"]),EXT_TO_TYPE=new Map([["mp4","video/mp4"],["webm","video/webm"],["m4a","audio/mp4"],["mp3","audio/mpeg"],["js","application/javascript"],["wasm","application/wasm"],["svg","image/svg+xml"],["html","text/html"]]);function GetTypeFromFileExtension(e){if(!e)return"";const t=e.split(".");if(t.length<2)return"";const s=t.at(-1).toLowerCase();return EXT_TO_TYPE.get(s)||""}function AddScript(e){return new Promise((t,s)=>{const i=document.createElement("script");i.onload=t,i.onerror=s,i.async=!1,i.type="module",i.src=e,document.head.appendChild(i)})}C3.AssetManager=class extends C3.DefendedBase{constructor(e,t){super();const s=t["exportType"];this._runtime=e,this._cordovaBlobUrlCache=new Map,this._isCordova="cordova"===s,this._isiOSCordova=!!t["isiOSCordova"],this._swClientId=t["swClientId"],this._supportedAudioFormats=t["supportedAudioFormats"]||{},this._audioFiles=new Map,this._preloadSounds=!1,this._scriptSubfolder=t["scriptFolder"],this._mediaSubfolder="",this._fontsSubfolder="",this._iconsSubfolder="",this._fileMap=t["fileMap"]||new Map,this._fileMapBlobUrls=new Map,this._exportedFileList=[];const i="html5"===s||"scirra-arcade"===s||"instant-games"===s;this._defaultLoadPolicy=i?"remote":"local",this._imageAssetsMap=new Map,this._webFonts=[],this._loadPromises=[],this._hasFinishedInitialLoad=!1,this._totalAssetSizeToLoad=0,this._assetSizeLoaded=0,this._lastLoadProgress=0,this._hasHadErrorLoading=!1,this._loadingRateLimiter=C3.New(C3.RateLimiter,()=>this._FireLoadingProgressEvent(),50),this._localPromiseThrottle=C3.New(C3.PromiseThrottle,Math.max(C3.hardwareConcurrency,8)),this._remotePromiseThrottle=C3.New(C3.PromiseThrottle,20),this._iAssetManager=new self.IAssetManager(this)}Release(){for(const e of this._imageAssetsMap.values())e.Release();this._imageAssetsMap.clear(),C3.clearArray(this._loadPromises),this._runtime=null}GetRuntime(){return this._runtime}GetScriptSubfolder(){return this._scriptSubfolder}_SetMediaSubfolder(e){this._mediaSubfolder=e}GetMediaSubfolder(){return this._mediaSubfolder}_SetFontsSubfolder(e){this._fontsSubfolder=e}GetFontsSubfolder(){return this._fontsSubfolder}_SetIconsSubfolder(e){this._iconsSubfolder=e}GetIconsSubfolder(){return this._iconsSubfolder}_SetExportedFileList(e){this._exportedFileList=e}GetExportedFileList(){return this._exportedFileList}FetchBlob(e,t){return t=t||this._defaultLoadPolicy,C3.IsRelativeURL(e)?"playable-ad-single-file"===this._runtime.GetExportType()?self["c3_runtimeInterface"]["_PlayableAdFetchBlob"](e):"local"===t?this._localPromiseThrottle.Add(()=>C3.FetchBlob(e)):this._remotePromiseThrottle.Add(()=>C3.FetchBlob(e)):C3.FetchBlob(e)}FetchArrayBuffer(e){return C3.IsRelativeURL(e)?"playable-ad-single-file"===this._runtime.GetExportType()?C3.BlobToArrayBuffer(self["c3_runtimeInterface"]["_PlayableAdFetchBlob"](e)):"local"===this._defaultLoadPolicy?this._localPromiseThrottle.Add(()=>C3.FetchArrayBuffer(e)):this._remotePromiseThrottle.Add(()=>C3.FetchArrayBuffer(e)):C3.FetchArrayBuffer(e)}FetchText(e){return C3.IsRelativeURL(e)?"playable-ad-single-file"===this._runtime.GetExportType()?C3.BlobToString(self["c3_runtimeInterface"]["_PlayableAdFetchBlob"](e)):"local"===this._defaultLoadPolicy?this._localPromiseThrottle.Add(()=>C3.FetchText(e)):this._remotePromiseThrottle.Add(()=>C3.FetchText(e)):C3.FetchText(e)}async FetchJson(e){const t=await this.FetchText(e);return JSON.parse(t)}GetMediaFileUrl(e){let t=this._mediaSubfolder+e;return"Gecko"===C3.Platform.BrowserEngine&&"preview"===this._runtime.GetExportType()&&(t=this._GetLocalBlobURLFromFileMap(t)),t}GetProjectFileUrl(e){return"playable-ad-single-file"===this._runtime.GetExportType()&&C3.IsRelativeURL(e)?URL.createObjectURL(self["c3_runtimeInterface"]["_PlayableAdFetchBlob"](e)):e}GetProjectFileIframeUrl(e){if(C3.IsAbsoluteURL(e)||"preview"!==this._runtime.GetExportType()||!this._swClientId||!e)return e;try{const t=new URL(e,location.href);return t.searchParams.set("__c3_client_id",this._swClientId),t.toString()}catch(t){return console.warn("Invalid iframe URL: "+e),e}}_GetImageAssetKey(e,t){return(t?"true":"false")+"|"+e}LoadImage(e){const t=!!e.isTiled;if(e.loadPolicy&&!VALID_LOAD_POLICIES.has(e.loadPolicy))throw new Error("invalid load policy");const s=this._GetImageAssetKey(e.url,t);let i=this._imageAssetsMap.get(s);return i||(i=C3.New(C3.ImageAsset,this,{url:e.url,size:e.size||0,loadPolicy:e.loadPolicy||this._defaultLoadPolicy,isTiled:t}),this._imageAssetsMap.set(s,i),this._hasFinishedInitialLoad||(this._totalAssetSizeToLoad+=i.GetSize(),this._loadPromises.push(i.Load().then(()=>this._AddLoadedSize(i.GetSize())))),i)}_ReleaseImageAsset(e){const t=this._GetImageAssetKey(e.GetURL(),e.IsTiled());this._imageAssetsMap.delete(t)}async WaitForAllToLoad(e){try{await Promise.all(this._loadPromises),this._lastLoadProgress=1,e&&0===this._totalAssetSizeToLoad&&this._FireLoadingProgressEvent()}catch(e){console.error("Error loading: ",e),this._hasHadErrorLoading=!0,this._FireLoadingProgressEvent()}}SetInitialLoadFinished(){this._hasFinishedInitialLoad=!0}HasHadErrorLoading(){return this._hasHadErrorLoading}_AddLoadedSize(e){this._assetSizeLoaded+=e,this._loadingRateLimiter.Call()}_FireLoadingProgressEvent(){const e=C3.New(C3.Event,"loadingprogress");0===this._totalAssetSizeToLoad?this._lastLoadProgress=1:this._lastLoadProgress=C3.clamp(this._assetSizeLoaded/this._totalAssetSizeToLoad,0,1),e.progress=this._lastLoadProgress,this._runtime.Dispatcher().dispatchEvent(e),this._runtime.DispatchUserScriptEvent(C3.New(C3.Event,"loadingprogress"))}GetLoadProgress(){return this._lastLoadProgress}GetImageLoadProgress(){return this._runtime.GetSystemPlugin().GetImageLoadingProgress()}_SetWebFonts(e){C3.shallowAssignArray(this._webFonts,e),this._webFonts.length&&this._loadPromises.push(this._LoadWebFonts())}async _LoadWebFonts(){const e=[],t=[];for(const[s,i,o]of this._webFonts)this._totalAssetSizeToLoad+=o,e.push(this._LoadWebFont(s,i,t).then(()=>this._AddLoadedSize(o)));await Promise.all(e),this._runtime.IsInWorker()&&t.length>0&&await this._runtime.PostComponentMessageToDOMAsync("runtime","load-webfonts",{"webfonts":t})}async _LoadWebFont(e,t,s){try{let i=this.GetProjectFileUrl(t);"Gecko"===C3.Platform.BrowserEngine&&(e=`'${e}'`),("Gecko"===C3.Platform.BrowserEngine&&"preview"===this._runtime.GetExportType()||"playable-ad-single-file"===this._runtime.GetExportType())&&(i=this._GetLocalBlobURLFromFileMap(i));const o=new FontFace(e,`url('${i}')`);this._runtime.IsInWorker()?self.fonts.add(o):document.fonts.add(o),await o.load(),this._runtime.IsInWorker()&&s.push({name:e,url:i})}catch(t){console.warn(`[C3 runtime] Failed to load web font '${e}': `,t)}}IsAudioFormatSupported(e){return!!this._supportedAudioFormats[e]}_SetAudioFiles(e,t){this._preloadSounds=!!t;for(const[t,s,i]of e)this._audioFiles.set(t,{fileName:t,formats:s.map(e=>({type:e[0],fileExtension:e[1],fullName:t+e[1],fileSize:e[2]})),isMusic:i})}GetPreferredAudioFile(e){const t=this._audioFiles.get(e);if(!t)return null;let s=null;for(const e of t.formats)if(s||"audio/webm; codecs=opus"!==e.type||(s=e),this.IsAudioFormatSupported(e.type))return e;return s}GetProjectAudioFileUrl(e){const t=this.GetPreferredAudioFile(e);return t?{url:this.GetMediaFileUrl(t.fullName),type:t.type}:null}GetAudioToPreload(){if(this._preloadSounds){const e=[];for(const t of this._audioFiles.values()){if(t.isMusic)continue;const s=this.GetPreferredAudioFile(t.fileName);s&&e.push({originalUrl:t.fileName,url:this.GetMediaFileUrl(s.fullName),type:s.type,fileSize:s.fileSize})}return e}return[]}_GetLocalBlobFromFileMap(e){return"preview"===this._runtime.GetExportType()&&(e=new URL(e,location.href).toString()),this._fileMap.get(e)||null}_GetLocalBlobURLFromFileMap(e){let t=this._fileMapBlobUrls.get(e);if(t)return t;const s=this._GetLocalBlobFromFileMap(e);return s?(t=URL.createObjectURL(s),this._fileMapBlobUrls.set(e,t),t):e}GetIAssetManager(){return this._iAssetManager}async LoadScripts(...e){const t=e.map(e=>this.GetProjectFileUrl(e));if(this._runtime.IsInWorker())if(1===e.length){const t=e[0];await import(new URL(t,location.href).toString())}else{const t=e.map(e=>`import "${new URL(e,location.href).toString()}";`).join("\n"),s=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));await import(s)}else await Promise.all(t.map(e=>AddScript(e)))}async CompileWebAssembly(e){if(WebAssembly.compileStreaming){const t=this.GetProjectFileUrl(e);return await WebAssembly.compileStreaming(fetch(t))}{const t=await C3.FetchArrayBuffer(e);return await WebAssembly.compile(t)}}async LoadStyleSheet(e){const t=this.GetProjectFileUrl(e);return await this._runtime.PostComponentMessageToDOMAsync("runtime","add-stylesheet",{"url":t})}}; } // assets/asset.js { const C3=self.C3;C3.Asset=class extends C3.DefendedBase{constructor(s,i){super(),this._assetManager=s,this._runtime=s.GetRuntime(),this._url=i.url||"",this._size=i.size,this._loadPolicy=i.loadPolicy,this._blob=i.blob||null,this._isLoaded=!!this._blob,this._loadPromise=null}Release(){this._loadPromise=null,this._assetManager=null,this._runtime=null,this._blob=null}GetURL(){return this._url}GetSize(){return this._size}Load(){return"local"===this._loadPolicy||this._blob?(this._isLoaded=!0,Promise.resolve()):(this._loadPromise||(this._loadPromise=this._assetManager.FetchBlob(this._url,this._loadPolicy).then(s=>(this._isLoaded=!0,this._loadPromise=null,this._blob=s,s)).catch(s=>{console.error("Error loading resource: ",s),this._loadPromise=null})),this._loadPromise)}IsLoaded(){return this._isLoaded}GetBlob(){return this._blob?Promise.resolve(this._blob):this._loadPromise?this._loadPromise:this._assetManager.FetchBlob(this._url,this._loadPolicy)}}; } // assets/imageAsset.js { const C3=self.C3,promiseThrottle=new C3.PromiseThrottle,allImageAssets=new Set;C3.ImageAsset=class extends C3.Asset{constructor(e,t){super(e,t),this._texturePromise=null,this._webglTexture=null,this._refCount=0,this._imageWidth=-1,this._imageHeight=-1,this._isTiled=!!t.isTiled,allImageAssets.add(this)}Release(){if(0!==this._refCount)throw new Error("released image asset which still has references");this._assetManager._ReleaseImageAsset(this),this._texturePromise=null,allImageAssets.delete(this),super.Release()}static OnRendererContextLost(){for(const e of allImageAssets)e._texturePromise=null,e._webglTexture=null,e._refCount=0}LoadStaticTexture(e,t){return t=t||{},this._refCount++,this._webglTexture?Promise.resolve(this._webglTexture):(this._texturePromise||(t.anisotropy=this._runtime.GetCanvasManager().GetTextureAnisotropy(),this._texturePromise=this._DoLoadStaticTexture(e,t)),this._texturePromise)}async _DoLoadStaticTexture(e,t){try{const s=await this.GetBlob();return 0===this._refCount?(this._texturePromise=null,null):await promiseThrottle.Add(async()=>{const r=await e.CreateStaticTextureAsync(s,t);return this._texturePromise=null,0===this._refCount?(e.DeleteTexture(r),null):(this._webglTexture=r,this._imageWidth=r.GetWidth(),this._imageHeight=r.GetHeight(),this._webglTexture)})}catch(e){throw console.error("Failed to load texture: ",e),e}}ReleaseTexture(){if(this._refCount<=0)throw new Error("texture released too many times");if(this._refCount--,0===this._refCount&&this._webglTexture){this._webglTexture.GetRenderer().DeleteTexture(this._webglTexture),this._webglTexture=null}}IncRefCount(){this._refCount++}GetRefCount(){return this._refCount}DecRefCount(){this._refCount--}GetTexture(){return this._webglTexture}GetWidth(){return this._imageWidth}GetHeight(){return this._imageHeight}IsTiled(){return this._isTiled}async LoadToDrawable(){const e=await this.GetBlob();return C3.Supports.ImageBitmap?await createImageBitmap(e):await C3.BlobToImage(e)}}; } // layouts/renderCell.js { const C3=self.C3,assert=self.assert;function SortByInstLastCachedZIndex(e,s){return e.GetWorldInfo()._GetLastCachedZIndex()-s.GetWorldInfo()._GetLastCachedZIndex()}C3.RenderCell=class extends C3.DefendedBase{constructor(e,s,n){super(),this._grid=e,this._x=s,this._y=n,this._instances=[],this._isSorted=!0,this._pendingRemoval=new Set,this._isAnyPendingRemoval=!1}Release(){C3.clearArray(this._instances),this._pendingRemoval.clear(),this._grid=null}Reset(){C3.clearArray(this._instances),this._isSorted=!0,this._pendingRemoval.clear(),this._isAnyPendingRemoval=!1}SetChanged(){this._isSorted=!1}IsEmpty(){return!this._instances.length||!(this._instances.length>this._pendingRemoval.size)&&(this._FlushPending(),!0)}Insert(e){if(this._pendingRemoval.has(e))return this._pendingRemoval.delete(e),void(0===this._pendingRemoval.size&&(this._isAnyPendingRemoval=!1));this._instances.push(e),this._isSorted=1===this._instances.length}Remove(e){this._pendingRemoval.add(e),this._isAnyPendingRemoval=!0,this._pendingRemoval.size>=50&&this._FlushPending()}_FlushPending(){this._isAnyPendingRemoval&&(this._instances.length!==this._pendingRemoval.size?(C3.arrayRemoveAllInSet(this._instances,this._pendingRemoval),this._pendingRemoval.clear(),this._isAnyPendingRemoval=!1):this.Reset())}_EnsureSorted(){this._isSorted||(this._instances.sort(SortByInstLastCachedZIndex),this._isSorted=!0)}Dump(e){this._FlushPending(),this._EnsureSorted(),this._instances.length&&e.push(this._instances)}}; } // layouts/renderGrid.js { const C3=self.C3;C3.RenderGrid=class extends C3.DefendedBase{constructor(e,t){super(),this._cellWidth=e,this._cellHeight=t,this._cells=C3.New(C3.PairMap)}Release(){this._cells.Release(),this._cells=null}GetCell(e,t,l){let o=this._cells.Get(e,t);return o||(l?(o=C3.New(C3.RenderCell,this,e,t),this._cells.Set(e,t,o),o):null)}XToCell(e){return Math.floor(e/this._cellWidth)}YToCell(e){return Math.floor(e/this._cellHeight)}Update(e,t,l){if(t)for(let o=t.getLeft(),s=t.getRight();o<=s;++o)for(let s=t.getTop(),i=t.getBottom();s<=i;++s){if(l&&l.containsPoint(o,s))continue;const t=this.GetCell(o,s,!1);t&&(t.Remove(e),t.IsEmpty()&&this._cells.Delete(o,s))}if(l)for(let o=l.getLeft(),s=l.getRight();o<=s;++o)for(let s=l.getTop(),i=l.getBottom();s<=i;++s)t&&t.containsPoint(o,s)||this.GetCell(o,s,!0).Insert(e)}QueryRange(e,t){let l=this.XToCell(e.getLeft());const o=this.YToCell(e.getTop()),s=this.XToCell(e.getRight()),i=this.YToCell(e.getBottom());for(;l<=s;++l)for(let e=o;e<=i;++e){const o=this.GetCell(l,e,!1);o&&o.Dump(t)}}MarkRangeChanged(e){let t=e.getLeft();const l=e.getTop(),o=e.getRight(),s=e.getBottom();for(;t<=o;++t)for(let e=l;e<=s;++e){const l=this.GetCell(t,e,!1);l&&l.SetChanged()}}}; } // layouts/layer.js { const C3=self.C3,assert=self.assert,tmpRect=new C3.Rect,tmpQuad=new C3.Quad2D,renderCellArr=[],tmpDestRect=new C3.Rect,tmpSrcRect=new C3.Rect,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,mat4=glMatrix.mat4,tempMat4=mat4.create(),tempVec3=vec3.create(),tempVec4=vec4.create(),camVector=vec3.create(),lookVector=vec3.create(),upVector=vec3.create(),tempVec2=C3.New(C3.Vector2),tempRect=C3.New(C3.Rect);function SortByInstLastCachedZIndex(e,t){return e.GetWorldInfo()._GetLastCachedZIndex()-t.GetWorldInfo()._GetLastCachedZIndex()}function SortByInstZ(e,t){const s=e.GetWorldInfo(),a=t.GetWorldInfo();return s.GetZ()-s.GetDepth()*s.GetOriginZ()-(a.GetZ()-a.GetDepth()*a.GetOriginZ())}const tempInstancesByCameraDist=[],DEFAULT_LAYER_OPTIONS={name:"",sid:-1,isDynamic:!1,isVisible:!0,isInteractive:!0,isHTMLElementsLayer:!1,backgroundColor:[1,1,1,1],isTransparent:!0,parallax:[1,1],opacity:1,isForceOwnTexture:!1,renderAs3d:!1,useCameraDistanceDrawOrder:!1,useRenderCells:!1,scaleRate:1,blendMode:0,zElevation:0,samplingMode:"auto",initialInstancesData:[],effectListData:[],subLayersData:[]},allInitialGlobalInstances=new Map,on_global_instance_destroy=e=>{if(!e.instance.GetObjectClass().IsGlobal())return;const t=e.instance.GetUID();allInitialGlobalInstances.has(t)&&(allInitialGlobalInstances.delete(t),allInitialGlobalInstances.size||e.instance.GetRuntime().Dispatcher().removeEventListener("instancedestroy",on_global_instance_destroy))};class LayerCoplanarManagerMethods extends C3.Gfx.CoplanarManagerMethods{ShouldDrawInstance(e){const t=e.GetWorldInfo();return t.IsVisible()&&t.IsInViewport3D(t.GetLayer()._GetViewFrustum())}GetInstanceBaseZ(e){const t=e.GetWorldInfo();return t.GetTotalZ()-t.GetDepth()*t.GetOriginZ()}GetInstanceDepth(e){return e.GetWorldInfo().GetDepth()}InstanceRendersToOwnZPlane(e){return e.RendersToOwnZPlane()}InstanceMustMitigateZFighting(e){return e.MustMitigateZFighting()}SetInstanceDrawBackFaceOnly(e,t){e.GetWorldInfo()._SetDrawBackFaceOnly(t)}SetInstanceDrawNonBackFacesOnly(e,t){e.GetWorldInfo()._SetDrawNonBackFacesOnly(t)}DrawInstance(e,t,s,a,i){const r=a.GetWorldInfo(),n=r.GetLayer();i?n._DrawInstanceMaybeWithEffects(a,r,e,s):n._DrawInstance(a,r,e)}}const layerCoplanarManager=new C3.Gfx.CoplanarManager(new LayerCoplanarManagerMethods);C3.Layer=class extends C3.DefendedBase{#e="auto";#t="trilinear";constructor(e,t,s){super(),s=Object.assign({},DEFAULT_LAYER_OPTIONS,s),this._layout=e,this._runtime=e.GetRuntime(),this._parentLayer=t,this._name=s.name,this._index=-1,this._isHTMLElementsLayer=!!s.isHTMLElementsLayer,this._htmlIndex=-1,this._sid=s.sid,this._isDynamic=!!s.isDynamic,this._isVisible=!!s.isVisible,this._isInteractive=!!s.isInteractive,this._backgroundColor=C3.New(C3.Color),this._backgroundColor.setFromJSON(s.backgroundColor),this._isTransparent=!!s.isTransparent,this._parallaxX=s.parallax[0],this._parallaxY=s.parallax[1],this._color=C3.New(C3.Color,1,1,1,s.opacity),this._premultipliedColor=C3.New(C3.Color),this._isForceOwnTexture=!!s.isForceOwnTexture,this._renderAs3d=!!s.renderAs3d,this._useCameraDistanceDrawOrder=!!s.useCameraDistanceDrawOrder,this._useRenderCells=!!s.useRenderCells,this._scaleRate=s.scaleRate,this._blendMode=s.blendMode,this._curRenderTarget=null,this.#e=s.samplingMode,this._scale=1,this._zElevation=s.zElevation,this._angle=0,this._scrollX=0,this._scrollY=0,this._hasOwnScrollPosition=!1,this._viewport=C3.New(C3.Rect),this._viewportZ0=C3.New(C3.Rect),this._viewport3D=C3.New(C3.Rect),this._isViewportChanged=!0,this._projectionMatrix=mat4.create(),this._isProjectionMatrixChanged=!0,this._modelViewMatrix=mat4.create(),this._isMVMatrixChanged=!0,this._viewFrustum=C3.New(C3.Gfx.ViewFrustum),this._isViewFrustumChanged=!0,this._startupInitialInstances=[],this._initialInstancesData=s.initialInstancesData,this._initialInstances=[],this._createdGlobalUids=[],this._initialUIDsToInstanceData=new Map,this._instances=[],this._zIndicesUpToDate=!1,this._htmlZIndicesUpToDate=!1,this._anyInstanceZElevated=!1;const a=this._runtime.GetCanvasManager();this._effectList=C3.New(C3.EffectList,this,s.effectListData),this._effectChain=C3.New(C3.Gfx.EffectChain,a.GetEffectChainManager(),{drawContent:(e,t)=>{const s=t.GetContentObject(),i=s.GetRenderTarget();e.SetColor(s.GetPremultipliedColor()),e.DrawRenderTarget(i),e.InvalidateRenderTarget(i),a.ReleaseAdditionalRenderTarget(i)},getShaderParameters:e=>this.GetEffectList()._GetEffectChainShaderParametersForIndex(e)}),this._needsRebuildEffectChainSteps=!0,this._wasDefaultColor=!0,this._renderGrid=null,this._lastRenderList=[],this._isRenderListUpToDate=!1,this._lastRenderCells=C3.New(C3.Rect,0,0,-1,-1),this._curRenderCells=C3.New(C3.Rect,0,0,-1,-1),this._iLayer=new self.ILayer(this),this._userScriptDispatcher=C3.New(C3.Event.Dispatcher),this._UpdatePremultipliedColor(),this.UsesRenderCells()&&(this._renderGrid=C3.New(C3.RenderGrid,this._runtime.GetOriginalViewportWidth(),this._runtime.GetOriginalViewportHeight())),this._subLayers=s.subLayersData.map(e=>C3.Layer.CreateFromExportData(this._layout,this,e))}_InitInitialInstances(){for(const e of this._initialInstancesData){const t=this._runtime.GetObjectClassByIndex(e[1]);this._layout._AddInitialObjectClass(t),t.GetDefaultInstanceData()||(t.SetDefaultInstanceData(e),t._SetDefaultLayerIndex(this._index)),this._initialInstances.push(e),this._initialUIDsToInstanceData.set(e[2],e)}C3.shallowAssignArray(this._startupInitialInstances,this._initialInstances),this._initialInstancesData=null}static CreateFromExportData(e,t,s){return C3.New(C3.Layer,e,t,{name:s[0],sid:s[2],isVisible:s[3],isInteractive:s[13],isHTMLElementsLayer:s[19],backgroundColor:s[4].map(e=>e/255),isTransparent:s[5],parallax:[s[6],s[7]],opacity:s[8],isForceOwnTexture:s[9],renderAs3d:s[17],useCameraDistanceDrawOrder:s[18],useRenderCells:s[10],scaleRate:s[11],blendMode:s[12],zElevation:s[16],initialInstancesData:s[14],effectListData:s[15],samplingMode:s[20],subLayersData:s[21]})}Release(){for(const e of this._subLayers)e.Release();C3.clearArray(this._subLayers);for(const e of this._instances)this._runtime.DestroyInstance(e);C3.clearArray(this._instances),this._effectList.Release(),this._effectList=null,this._effectChain.Release(),this._effectChain=null,this._iLayer=null,this._parentLayer=null,this._layout=null,this._runtime=null}WasReleased(){return!this._layout}GetInitialInstanceData(e){return this._initialUIDsToInstanceData.get(e)}CreateInitialInstances(e){const t=this._layout.IsFirstVisit(),s=this._initialInstances;let a=0;for(let i=0,r=s.length;i=0&&e.add(s)}let t=-1;for(const s of this._instances){const a=s.GetWorldInfo();if(!(a._GetLastCachedZIndex()>=0)){for(++t;e.has(t);)++t;a._SetZIndex(t)}}}this._instances.sort(SortByInstLastCachedZIndex)}_Start(){}_End(){for(const e of this._instances)e.GetObjectClass().IsGlobal()||this._runtime.DestroyInstance(e);this._runtime.FlushPendingInstances(),C3.clearArray(this._instances),this._anyInstanceZElevated=!1,this.SetZIndicesChanged()}RecreateInitialObjects(e,t,s,a,i,r){const n=this._runtime.GetEventSheetManager(),l=this._runtime.GetAllObjectClasses(),o=e.IsFamily(),h=[],c=[];for(const e of this._initialInstances){const t=e[0][15],s=t?.[3]||-1;-1!==s&&(c.includes(s)||c.push(s))}for(const d of this._initialInstances){const _=d[0],u=_[0],p=_[1],G=_[15],f=G?.[3]||-1;if(r&&c.includes(f))continue;if(!t.containsPoint(u,p))continue;const I=l[d[1]];if(I!==e){if(!o)continue;if(!e.FamilyHasMember(I))continue}let m=i;if(!m){const e=this._runtime.GetCurrentLayout();this.GetLayout()===e?m=this:(m=e.GetLayerByName(this.GetName()),m||(m=e.GetLayerByIndex(this.GetIndex())))}const C=this._runtime.CreateInstanceFromData(d,m,!1,void 0,void 0,!1,r,void 0,r);r&&m.SortAndAddInstancesByZIndex(C);const y=C.GetWorldInfo();y.OffsetXY(s,a),y.SetBboxChanged(),n.BlockFlushingInstances(!0),C._TriggerOnCreatedOnSelfAndRelated(),n.BlockFlushingInstances(!1),h.push(C)}return h}GetInstanceCount(){return this._instances.length}GetLayout(){return this._layout}GetName(){return this._name}_SetIndex(e){this._index=e}GetIndex(){return this._index}_SetHTMLIndex(e){this._htmlIndex=e}GetHTMLIndex(){return this._htmlIndex}IsHTMLElementsLayer(){return this._isHTMLElementsLayer}SetIsHTMLElementsLayer(e){e=!!e,this._isHTMLElementsLayer!==e&&(this._isHTMLElementsLayer=e,this._layout._ReindexAndUpdateAllLayers(),this._runtime.UpdateRender())}_GetSiblingIndex(){let e=-1;const t=this.GetParentLayer();return e=t?t.GetSubLayers().indexOf(this):this.GetLayout()._GetRootLayers().indexOf(this),e}GetSID(){return this._sid}GetRuntime(){return this._runtime}IsDynamic(){return this._isDynamic}HasAnyDynamicParentLayer(){for(const e of this.parentLayers())if(e.IsDynamic())return!0;return!1}GetDevicePixelRatio(){return this._runtime.GetDevicePixelRatio()}GetEffectList(){return this._effectList}GetEffectChain(){return this._MaybeRebuildEffectChainSteps(),this._effectChain}_MaybeRebuildEffectChainSteps(){const e=this.HasDefaultColor();if(!this._needsRebuildEffectChainSteps&&e===this._wasDefaultColor&&!this._effectChain.NeedsRebuild())return;const t=this.GetEffectList().GetActiveEffectTypes();this._effectChain.BuildSteps(t.map(e=>e.GetShaderProgram()),{indexMap:t.map(e=>e.GetIndex()),forcePreDraw:!e,useFullSurface:!0}),this._needsRebuildEffectChainSteps=!1,this._wasDefaultColor=e}UpdateActiveEffects(){this.GetEffectList().UpdateActiveEffects(),this._needsRebuildEffectChainSteps=!0}UsesCameraDistanceDrawOrder(){return this._useCameraDistanceDrawOrder}UsesRenderCells(){return this._useRenderCells&&!this.UsesCameraDistanceDrawOrder()}GetRenderGrid(){return this._renderGrid}SetRenderListStale(){this._isRenderListUpToDate=!1}IsVisible(){for(const e of this.selfAndParentLayers())if(!e._IsVisibleFlagSet())return!1;return!0}_IsVisibleFlagSet(){return this._isVisible}SetVisible(e){e=!!e,this._isVisible!==e&&(this._isVisible=e,this._runtime.UpdateRender())}SetInteractive(e){this._isInteractive=!!e}IsInteractive(){return this._isInteractive}IsSelfAndParentsInteractive(){for(const e of this.selfAndParentLayers())if(!e.IsInteractive())return!1;return!0}SetOwnScrollPositionEnabled(e){if(e=!!e,this._hasOwnScrollPosition!==e){if(this._hasOwnScrollPosition=e,e){const e=this.GetLayout();this._scrollX=e.GetScrollX(),this._scrollY=e.GetScrollY()}this._SetMVMatrixChanged(),this._runtime.UpdateRender()}}IsOwnScrollPositionEnabled(){return this._hasOwnScrollPosition}SetScrollX(e){const t=this.GetLayout(),s=t.GetScrollLeftBound(),a=t.GetScrollRightBound();e>a&&(e=a),ea&&(e=a),e0}_GetInstances(){return this._instances}_GetInstancesInDrawOrder(){if(this.RendersIn3DMode()&&this.UsesCameraDistanceDrawOrder()){C3.shallowAssignArray(tempInstancesByCameraDist,this._GetInstances());const e=this.GetLayout();return tempInstancesByCameraDist.sort((t,s)=>e.SortInstancesByCameraDistance(t,s)),tempInstancesByCameraDist}return this._UpdateZIndices(),this._GetInstances()}_AppendAllInstancesIncludingSubLayersInDrawOrder(e){C3.appendArray(e,this._GetInstancesInDrawOrder());for(const t of this._subLayers)t.IsVisible()&&t.GetOpacity()>0&&t._AppendAllInstancesIncludingSubLayersInDrawOrder(e)}GetBackgroundColor(){return this._backgroundColor}IsTransparent(){return this._isTransparent}SetTransparent(e){e=!!e,this._isTransparent!==e&&(this._isTransparent=e,this._runtime.UpdateRender())}IsForceOwnTexture(){return this._isForceOwnTexture}SetForceOwnTexture(e){e=!!e,this._isForceOwnTexture!==e&&(this._isForceOwnTexture=e,this._runtime.UpdateRender())}SetRenderAs3D(e){e=!!e,this._renderAs3d!==e&&(this._renderAs3d=e,this._SetMVMatrixChanged(),this._runtime.UpdateRender())}IsRenderAs3D(){return this._renderAs3d}RendersIn2DMode(){return!this.GetRuntime().Uses3DFeatures()||!this._renderAs3d}RendersIn3DMode(){return!this.RendersIn2DMode()}Has3DCamera(){return this.RendersIn3DMode()&&this.GetLayout().Is3DCameraEnabled()}SelfAndAllSubLayersHave3DCamera(){if(!this.Has3DCamera())return!1;for(const e of this._subLayers)if(!e.SelfAndAllSubLayersHave3DCamera())return!1;return!0}SetBlendMode(e){this._blendMode!==e&&(this._blendMode=e,this._runtime.UpdateRender())}GetBlendMode(){return this._blendMode}IsRootLayer(){return!this._parentLayer}GetParentLayer(){return this._parentLayer}_SetParentLayer(e){this._parentLayer=e,this._UpdateActiveSamplingModes()}GetSubLayers(){return this._subLayers}HasAnySubLayers(){return this._subLayers.length>0}_AddSubLayer(e,t=!0){t?this._subLayers.push(e):this._subLayers.unshift(e)}_InsertSubLayer(e,t,s){let a=this._subLayers.indexOf(t);if(-1===a)throw new Error("cannot find layer to insert by");s&&++a,this._subLayers.splice(a,0,e)}_RemoveSubLayer(e){const t=this._subLayers.indexOf(e);if(-1===t)throw new Error("cannot find layer to remove");this._subLayers.splice(t,1)}HasAnyVisibleSubLayer(){for(const e of this._subLayers)if(e.ShouldDraw())return!0;return!1}*selfAndAllSubLayers(){for(const e of this._subLayers)yield*e.selfAndAllSubLayers();yield this}*parentLayers(){let e=this.GetParentLayer();for(;e;)yield e,e=e.GetParentLayer()}*selfAndParentLayers(){yield this,yield*this.parentLayers()}HasParentLayer(e){for(const t of this.parentLayers())if(t===e)return!0;return!1}IsTransformCompatibleWith(e){return this===e||this._parallaxX===e._parallaxX&&this._parallaxY===e._parallaxY&&this._scale===e._scale&&this._scaleRate===e._scaleRate&&this._angle===e._angle&&this.GetScrollX()===e.GetScrollX()&&this.GetScrollY()===e.GetScrollY()}SaveTransform(){return{"parallaxX":this.GetParallaxX(),"parallaxY":this.GetParallaxY(),"scale":this.GetOwnScale(),"scaleRate":this.GetScaleRate(),"angle":this.GetOwnAngle(),"hasOwnScroll":this.IsOwnScrollPositionEnabled(),"scrollX":this.GetScrollX(),"scrollY":this.GetScrollY()}}RestoreTransform(e){this.SetParallax(e["parallaxX"],e["parallaxY"]),this.SetOwnScale(e["scale"]),this.SetScaleRate(e["scaleRate"]),this.SetAngle(e["angle"]),this.SetOwnScrollPositionEnabled(e["hasOwnScroll"]),this.SetScrollX(e["scrollX"]),this.SetScrollY(e["scrollY"]),this._MaybeUpdateViewport()}_RemoveAllInstancesInSet(e){if(0===e.size)return;C3.arrayRemoveAllInSet(this._instances,e)>0&&(this._MaybeResetAnyInstanceZElevatedFlag(),this.SetZIndicesChanged())}SetZIndicesChanged(e){this._zIndicesUpToDate=!1,this._isRenderListUpToDate=!1,e&&!e.GetObjectClass().GetPlugin().IsHTMLElementType()||(this._htmlZIndicesUpToDate=!1)}_UpdateZIndices(){if(!this._zIndicesUpToDate){if(this._instances.sort(SortByInstZ),this.UsesRenderCells())for(let e=0,t=this._instances.length;e[...e.selfAndAllSubLayers()]).flat();let t=0;for(const s of e){for(const e of s._GetInstances())e.GetObjectClass().GetPlugin().IsHTMLElementType()&&e.GetWorldInfo()._SetHTMLZIndex(t++);s._SetHTMLZIndicesUpToDate()}}_SetHTMLZIndicesUpToDate(){this._htmlZIndicesUpToDate=!0}_GetHTMLLayerDOMState(){return{"isVisible":this.IsVisible(),"opacity":this.GetOpacity(),"isInteractive":this.IsInteractive()}}MoveInstanceAdjacent(e,t,s){const a=e.GetWorldInfo(),i=t.GetWorldInfo();if(a.GetLayer()!==this||i.GetLayer()!==this)throw new Error("can't arrange Z order unless both objects on this layer");const r=a.GetZIndex();let n=i.GetZIndex();return r!==n+(s?1:-1)&&(C3.arrayRemove(this._instances,r),r1;)e=this._MergeAllSortedZArrays_pass(e);return e[0]}_GetRenderCellInstancesToDraw(){return this._UpdateZIndices(),C3.clearArray(renderCellArr),this._renderGrid.QueryRange(this.GetViewport(),renderCellArr),renderCellArr.length?1===renderCellArr.length?renderCellArr[0]:this._MergeAllSortedZArrays(renderCellArr):[]}ShouldDraw(){return this.IsVisible()&&this.GetOpacity()>0&&this._DrawsAnyContentInSelfOrSubLayers()}_DrawsAnyContentInSelfOrSubLayers(){if(this.HasInstances()||!this.IsTransparent()||this._userScriptDispatcher.HasAnyHandlerFor("beforedraw")||this._userScriptDispatcher.HasAnyHandlerFor("afterdraw"))return!0;for(const e of this._subLayers)if(e._DrawsAnyContentInSelfOrSubLayers())return!0;return!1}UsesOwnTexture(){return this.IsForceOwnTexture()||!this.HasDefaultColor()||0!==this.GetBlendMode()||this._effectList.HasAnyActiveEffect()}SelfOrAnySubLayerUsesOwnTexture(){if(this.UsesOwnTexture())return!0;for(const e of this._subLayers)if(e.SelfOrAnySubLayerUsesOwnTexture())return!0;return!1}GetRenderTarget(){return this._curRenderTarget}Get2DScaleFactorToZ(e){if(this._layout.IsOrthographicProjection())return 1;{const t=this.Get3DCameraZ();return t/(t-e)}}GetResolutionScaleFactorToZ(e){const t=this._runtime.GetRenderScale();if(this._layout.IsOrthographicProjection())return t;{const s=this.Get3DCameraZ();return this.GetDefaultCameraZ()/Math.abs(s-e)*t}}_SetMVMatrixChanged(){this._isMVMatrixChanged=!0,this._isViewFrustumChanged=!0,this._isViewportChanged=!0}_GetModelViewMatrix(e){return this._isMVMatrixChanged&&(this._CalculateModelViewMatrix(e,this._modelViewMatrix,0,0,null),this._isMVMatrixChanged=!1),this._modelViewMatrix}Get2DCameraZ(e){return this.GetDefaultCameraZ(e)/this.GetNormalScale()}Get3DCameraZ(){return this.Has3DCamera()?this.GetLayout().Get3DCameraPosition()[2]:this.Get2DCameraZ()}GetCameraPosition(){if(this.Has3DCamera()){const e=this.GetLayout().Get3DCameraPosition();return[e[0],e[1],e[2]]}return this._Get2DCameraPosition()}_Get2DCameraPosition(e=0,t=0,s=0){const a=this._runtime,i=this.GetLayout(),r=a.GetParallaxXOrigin(),n=a.GetParallaxYOrigin();let l=(this.GetScrollX()-r)*this._parallaxX+r,o=(this.GetScrollY()-n)*this._parallaxY+n;a.IsPixelRoundingEnabled()&&(l=Math.round(l),o=Math.round(o));let h=l+e,c=o+t;const d=i.IsOrthographicProjection()?this.GetDefaultCameraZ(s):this.Get2DCameraZ(s),[_,u]=this._GetVanishingPoint();if(.5!==_||.5!==u){const e=this.GetDefaultCameraZ(s)/d;let t=(_-.5)*a.GetViewportWidth()/e,i=(u-.5)*a.GetViewportHeight()/e;const r=this.GetAngle();0!==r&&(tempVec2.set(t,i),tempVec2.rotate(r),t=tempVec2.getX(),i=tempVec2.getY()),h+=t,c+=i}return[h,c,d]}_CalculateModelViewMatrix(e,t,s,a,i){const r=this._runtime,n=r.GetCanvasManager(),l=this.GetLayout();if(this.Has3DCamera()){vec3.copy(camVector,l.Get3DCameraPosition()),vec3.copy(lookVector,l.Get3DCameraLookAt()),vec3.copy(upVector,l.Get3DCameraUpVector());const e=r.GetParallaxXOrigin(),t=r.GetParallaxYOrigin(),s=lookVector[0]-camVector[0],a=lookVector[1]-camVector[1],i=lookVector[2]-camVector[2];camVector[0]=(camVector[0]-e)*this._parallaxX+e,camVector[1]=(camVector[1]-t)*this._parallaxY+t,camVector[2]*=Math.max(this._parallaxX,this._parallaxY),lookVector[0]=camVector[0]+s,lookVector[1]=camVector[1]+a,lookVector[2]=camVector[2]+i}else{let[e,t,r]=this._Get2DCameraPosition(s,a,i);"high"!==n.GetCurrentFullscreenScalingQuality()||"integer-scale-inner"!==n.GetCurrentFullscreenMode()&&"integer-scale-outer"!==n.GetCurrentFullscreenMode()?"low"!==n.GetCurrentFullscreenScalingQuality()&&"integer-scale-inner"!==n.GetCurrentFullscreenMode()&&"integer-scale-outer"!==n.GetCurrentFullscreenMode()||"nearest"!==this.GetActiveSampling()||(n.GetDrawWidth()%2==1&&(e+=.5),n.GetDrawHeight()%2==1&&(t+=.5)):(e+=.01,t+=.01),vec3.set(camVector,e,t,r),vec3.set(lookVector,e,t,r-100);const l=this.GetAngle();0===l?vec3.set(upVector,0,1,0):vec3.set(upVector,Math.sin(l),Math.cos(l),0)}e.CalculateLookAtModelView(t,camVector,lookVector,upVector,i||r.GetViewportHeight())}_SetProjectionMatrixChanged(){this._isProjectionMatrixChanged=!0,this._isViewFrustumChanged=!0,this._isViewportChanged=!0}_GetProjectionMatrix(e){return this._isProjectionMatrixChanged&&(this._CalculateProjectionMatrix(e),this._isProjectionMatrixChanged=!1),this._projectionMatrix}_CalculateProjectionMatrix(e){const t=this._runtime.GetCanvasManager(),[s,a]=this._GetVanishingPoint();if(this._layout.IsOrthographicProjection()){let s=1;e.IsZAxisScaleRegular()&&(s=t.GetDisplayScale()),e.CalculateOrthographicMatrix(this._projectionMatrix,t.GetDrawWidth(),t.GetDrawHeight(),s)}else if(.5===s&&.5===a)mat4.copy(this._projectionMatrix,t.GetDefaultProjectionMatrix());else{const i=t.GetDrawWidth(),r=t.GetDrawHeight();e.CalculatePerspectiveMatrix(this._projectionMatrix,i/r,s,a)}}_SetTransform(e,t=!0,s=0,a=0,i=0){t&&e.SetProjectionMatrix(this._GetProjectionMatrix(e));let r=null;0===s&&0===a&&0===i?r=this._GetModelViewMatrix(e):(this._CalculateModelViewMatrix(e,tempMat4,s,a,i),r=tempMat4),e.SetModelViewMatrix(r)}PrepareForDraw(e){this._SetTransform(e),e.SetBaseZ(this.GetZElevation())}_MaybeStartWebGLProfiling(e){let t=null;if(e.IsWebGL()&&this._runtime.IsGPUProfiling()){const s=this._runtime.GetCanvasManager().GetLayerTimingsBuffer(this);s&&(t=s.AddTimeElapsedQuery(),e.StartQuery(t))}return t}_MaybeStartWebGPUProfiling(e){if(e.IsWebGPU()&&this._runtime.IsGPUProfiling()){const t=2*(this.GetIndex()+1);e.StartMeasuringRenderPassTime(t,t+1)}}_FireDrawEvent(e,t){if(this._userScriptDispatcher.HasAnyHandlerFor(t)){e.SetTextureFillMode(),e.SetTexture(null),e.SetAlphaBlend(),e.ResetCullState(),e.SetColorRgba(1,1,1,1),e.SetBaseZ(this.GetZElevation()),e.SetCurrentZ(0);const s=new C3.Event(t);s.renderer=this._runtime.GetCanvasManager().GetIRenderer(),this.DispatchUserScriptEvent(s)}}Draw(e,t,s){const a=this._runtime.GetCanvasManager(),i=this.UsesOwnTexture();let r=null;const n=this._MaybeStartWebGLProfiling(e);if(this._MaybeStartWebGPUProfiling(e),i){const t={isSampled:!0,canReadPixels:!!e.IsWebGPU()&&this._runtime.UsesAnyBackgroundBlending()};"low"===a.GetCurrentFullscreenScalingQuality()&&(t.width=a.GetDrawWidth(),t.height=a.GetDrawHeight()),r=this._runtime.GetAdditionalRenderTarget(t),r.SetDefaultSampling(this.GetActiveSampling()),this._curRenderTarget=r,e.SetRenderTarget(r),this.IsTransparent()&&e.ClearRgba(0,0,0,0)}else this._curRenderTarget=t,e.SetRenderTarget(t);if(this.IsTransparent()||e.Clear(this._backgroundColor),this._layout._DrawLayerList(e,this._curRenderTarget,this._subLayers,i&&this.IsTransparent()),this._MaybeStartWebGPUProfiling(e),this._SetTransform(e),e.SetBaseZ(this.GetZElevation()),e.SetDepthEnabled(this.RendersIn3DMode()),this._FireDrawEvent(e,"beforedraw"),this.GetNormalScale()>Number.EPSILON){this._UpdateZIndices();const t=this.UsesRenderCells()&&0===this.GetZElevation()&&!this._anyInstanceZElevated;this.Has3DCamera()?this._DrawInstances_3DCamera(e):t?this._DrawInstances_RenderCells(e):this._DrawInstances(e,this._GetInstancesInDrawOrder())}this._FireDrawEvent(e,"afterdraw"),e.SetBaseZ(0),e.SetCurrentZ(0),i&&(e.SetDepthEnabled(!1),this._DrawLayerOwnTextureToRenderTarget(e,r,t,s)),n&&e.EndQuery(n),this._curRenderTarget=null}_DrawInstances(e,t){const s=this.GetViewport(),a=this._curRenderTarget,i=this.GetLayout().IsOrthographicProjection(),r=this.GetLayout().HasVanishingPointOutsideViewport();let n=null;for(let l=0,o=t.length;l=this.Get2DCameraZ())return null;let[h,c]=this.LayerToDrawSurface(s,a,n),[d,_]=this.LayerToDrawSurface(i,r,n);if(0!==this.GetAngle()||o||this.Has3DCamera()){const[e,t]=this.LayerToDrawSurface(i,a,n),[u,p]=this.LayerToDrawSurface(s,r,n);if(o){const[n,o]=this.LayerToDrawSurface(s,a,l),[G,f]=this.LayerToDrawSurface(i,a,l),[I,m]=this.LayerToDrawSurface(i,r,l),[C,y]=this.LayerToDrawSurface(s,r,l);let S=Math.min(h,d,e,u,n,G,I,C);d=Math.max(h,d,e,u,n,G,I,C),h=S,S=Math.min(c,_,t,p,o,f,m,y),_=Math.max(c,_,t,p,o,f,m,y),c=S}else{let s=Math.min(h,d,e,u);d=Math.max(h,d,e,u),h=s,s=Math.min(c,_,t,p),_=Math.max(c,_,t,p),c=s}}return tmpRect.set(h,c,d,_),tmpRect}_GetViewFrustum(){return this._isViewFrustumChanged&&(this._UpdateViewFrustum(),this._isViewFrustumChanged=!1),this._viewFrustum}_UpdateViewFrustum(){const e=this._runtime.GetRenderer(),t=this._GetProjectionMatrix(e),s=this._GetModelViewMatrix(e);this._viewFrustum.CalculatePlanes(s,t)}#a(e,t,s){return this._GetViewFrustum().IsBehindNearPlane(e,t,s)}_SaveToJson(){return{"d":this.IsDynamic(),"s":this.GetOwnScale(),"a":this.GetOwnAngle(),"v":this._IsVisibleFlagSet(),"i":this.IsInteractive(),"fot":this.IsForceOwnTexture(),"html":this.IsHTMLElementsLayer(),"bc":this._backgroundColor.toJSON(),"t":this.IsTransparent(),"sx":this._scrollX,"sy":this._scrollY,"hosp":this._hasOwnScrollPosition,"px":this.GetParallaxX(),"py":this.GetParallaxY(),"c":this._color.toJSON(),"sr":this.GetScaleRate(),"samp":this.GetSamplingMode(),"fx":this._effectList.SaveToJson(),"cg":this._createdGlobalUids}}_LoadFromJson(e){this._isDynamic=!!e["d"],this._scale=e["s"],this._angle=e["a"],this._isVisible=!!e["v"],this._isInteractive=!e.hasOwnProperty("i")||e["i"],this._isHTMLElementsLayer=!!e["html"],this._backgroundColor.setFromJSON(e["bc"]),this._isTransparent=!!e["t"],e.hasOwnProperty("fot")&&(this._isForceOwnTexture=!!e["fot"]),e.hasOwnProperty("sx")&&(this._scrollX=e["sx"]),e.hasOwnProperty("sy")&&(this._scrollY=e["sy"]),e.hasOwnProperty("hosp")&&(this._hasOwnScrollPosition=!!e["hosp"]),this._parallaxX=e["px"],this._parallaxY=e["py"],this._color.setFromJSON(e["c"]),this._UpdatePremultipliedColor(),this._scaleRate=e["sr"],this.#e=e["samp"]??"auto",C3.shallowAssignArray(this._createdGlobalUids,e["cg"]),C3.shallowAssignArray(this._initialInstances,this._startupInitialInstances);const t=new Set(this._createdGlobalUids);let s=0;for(let e=0,a=this._initialInstances.length;e(e.GetWorldInfo().GetSceneGraphZIndex()??0)-(t.GetWorldInfo().GetSceneGraphZIndex()??0)),void(s&&this._instances.forEach((e,t)=>e.GetWorldInfo()._SetZIndex(t)));if(e.HasChildren()){const t=[...e.allChildren()];t.push(e),t.sort((e,t)=>(e.GetWorldInfo().GetSceneGraphZIndex()??0)-(t.GetWorldInfo().GetSceneGraphZIndex()??0));for(const e of t)if(e.IsInContainer())for(const s of e.siblings()){if(t.includes(s))continue;const e=[...s.allChildren()];e.push(s),e.sort((e,t)=>(e.GetWorldInfo().GetSceneGraphZIndex()??0)-(t.GetWorldInfo().GetSceneGraphZIndex()??0)),e&&e.length&&t.splice(t.length,0,...e)}for(const e of t)e.GetPlugin().IsWorldType()&&this._AddInstance(e,!0);s&&this._instances.forEach((e,t)=>e.GetWorldInfo()._SetZIndex(t))}else{if(e.GetPlugin().IsWorldType()&&this._AddInstance(e,!0),!e.IsInContainer())return void(s&&this._instances.forEach((e,t)=>e.GetWorldInfo()._SetZIndex(t)));for(const t of e.siblings()){const e=[...t.allChildren()];if(e.push(t),e.sort((e,t)=>(e.GetWorldInfo().GetSceneGraphZIndex()??0)-(t.GetWorldInfo().GetSceneGraphZIndex()??0)),e&&e.length)for(const t of e)t.GetPlugin().IsWorldType()&&this._AddInstance(t,!0)}s&&this._instances.forEach((e,t)=>e.GetWorldInfo()._SetZIndex(t))}}}; } // layouts/layout.js { const C3=self.C3,C3Debugger=self.C3Debugger,assert=self.assert,tempDestRect=C3.New(C3.Rect),tempSrcRect=C3.New(C3.Rect),tempLayoutRect=C3.New(C3.Rect),tempColor=C3.New(C3.Color),glMatrix=self.glMatrix,vec3=glMatrix.vec3,tempRender3dList=[],tempInstanceList=[];function vec3EqualsXYZ(e,t,s,n){return e[0]===Math.fround(t)&&e[1]===Math.fround(s)&&e[2]===Math.fround(n)}function SortByInstZ(e,t){const s=e.GetWorldInfo(),n=t.GetWorldInfo();return s.GetZ()-s.GetDepth()*s.GetOriginZ()-(n.GetZ()-n.GetDepth()*n.GetOriginZ())}class LayoutCoplanarManagerMethods extends C3.Gfx.CoplanarManagerMethods{ShouldDrawInstance(e){const t=e.GetWorldInfo();return t.IsVisible()&&t.IsInViewport3D(t.GetLayer()._GetViewFrustum())}GetInstanceBaseZ(e){const t=e.GetWorldInfo();return t.GetTotalZ()-t.GetDepth()*t.GetOriginZ()}GetInstanceDepth(e){return e.GetWorldInfo().GetDepth()}InstanceRendersToOwnZPlane(e){return e.RendersToOwnZPlane()}InstanceMustMitigateZFighting(e){return e.MustMitigateZFighting()}SetInstanceDrawBackFaceOnly(e,t){e.GetWorldInfo()._SetDrawBackFaceOnly(t)}SetInstanceDrawNonBackFacesOnly(e,t){e.GetWorldInfo()._SetDrawNonBackFacesOnly(t)}DrawInstance(e,t,s,n,a){super.DrawInstance(e,t,s,n,a);const i=n.GetWorldInfo(),r=i.GetLayer();a?r._DrawInstanceMaybeWithEffects(n,i,e,s):r._DrawInstance(n,i,e)}GetInstanceLayer(e){return e.GetWorldInfo().GetLayer()}PrepareLayerForDraw(e,t){e.PrepareForDraw(t)}}const layoutCoplanarManager=new C3.Gfx.CoplanarManager(new LayoutCoplanarManagerMethods);C3.Layout=class extends C3.DefendedBase{#e="auto";#t="trilinear";#s=!1;constructor(e,t,s){super(),this._layoutManager=e,this._runtime=e.GetRuntime(),this._name=s[0],this._originalWidth=s[1],this._originalHeight=s[2],this._width=s[1],this._height=s[2],this._isUnboundedScrolling=!!s[3],this._isOrthographicProjection=!!s[4],this._vanishingPointX=s[5],this._vanishingPointY=s[6],this.#e=s[7],this._eventSheetName=s[8],this._eventSheet=null,this._sid=s[9],this._index=t,this._scrollX=0,this._scrollY=0,this._scale=1,this._angle=0,this._initialObjectClasses=new Set,this._textureLoadedTypes=new Set,this._textureLoadPendingPromises=new Set,this._createdInstances=[],this._createdPersistedInstances=[],this._createdPersistedInstancesToDataMap=new Map,this._createdPersistedIndexToInstanceMap=new Map,this._initialNonWorld=[],this._is3dCameraEnabled=!1,this._cam3dposition=vec3.create(),this._cam3dlook=vec3.create(),this._cam3dup=vec3.create(),this._rootLayers=[],this._allLayersFlat=[],this._layersByName=new Map,this._layersBySid=new Map,this._pendingSetHTMLLayerCount=-1;const n=this._runtime.GetCanvasManager();this._effectList=C3.New(C3.EffectList,this,s[12]),this._effectChain=C3.New(C3.Gfx.EffectChain,n.GetEffectChainManager(),{drawContent:(e,t)=>{const s=t.GetContentObject().GetRenderTarget();e.ResetColor(),e.DrawRenderTarget(s),e.InvalidateRenderTarget(s),n.ReleaseAdditionalRenderTarget(s)},getShaderParameters:e=>this.GetEffectList()._GetEffectChainShaderParametersForIndex(e)}),this._needsRebuildEffectChainSteps=!0,this._wasFullScreenQualityLow=!1,this._curRenderTarget=null,this._persistData={},this._persistedIntances=new Map,this._isFirstVisit=!0,this._iLayout=new self.ILayout(this),this._userScriptDispatcher=C3.New(C3.Event.Dispatcher);for(const e of s[10])this._rootLayers.push(C3.Layer.CreateFromExportData(this,null,e));this._ReindexLayers();for(const e of this.allLayers())e._InitInitialInstances();for(const e of s[11]){const t=this._runtime.GetObjectClassByIndex(e[1]);if(!t)throw new Error("missing nonworld object class");t.GetDefaultInstanceData()||t.SetDefaultInstanceData(e),this._initialNonWorld.push(e),this._AddInitialObjectClass(t)}}Release(){for(const e of this._allLayersFlat)e.Release();C3.clearArray(this._allLayersFlat),this._textureLoadPendingPromises.clear(),this._eventSheet=null,this._layoutManager=null,this._runtime=null}GetRuntime(){return this._runtime}GetName(){return this._name}GetSID(){return this._sid}GetIndex(){return this._index}GetEffectList(){return this._effectList}GetEffectChain(){return this._MaybeRebuildEffectChainSteps(),this._effectChain}_MaybeRebuildEffectChainSteps(){const e="low"===this._runtime.GetCanvasManager().GetCurrentFullscreenScalingQuality();if(!this._needsRebuildEffectChainSteps&&this._wasFullScreenQualityLow===e&&!this._effectChain.NeedsRebuild())return;const t=this.GetEffectList().GetActiveEffectTypes();this._effectChain.BuildSteps(t.map(e=>e.GetShaderProgram()),{indexMap:t.map(e=>e.GetIndex()),forcePostDraw:e,useFullSurface:!0}),this._needsRebuildEffectChainSteps=!1,this._wasFullScreenQualityLow=e}UpdateActiveEffects(){this.GetEffectList().UpdateActiveEffects(),this._needsRebuildEffectChainSteps=!0}GetMinLayerScale(){let e=this._allLayersFlat[0].GetNormalScale();for(let t=1,s=this._allLayersFlat.length;ts&&(e=s),es&&(e=s),e1||t<0||t>1}SetPerspectiveProjection(){this._isOrthographicProjection&&(this._isOrthographicProjection=!1,this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}SetOrthographicProjection(){this._isOrthographicProjection||(this._isOrthographicProjection=!0,this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}IsOrthographicProjection(){return this._isOrthographicProjection}IsPerspectiveProjection(){return!this.IsOrthographicProjection()}SetSamplingMode(e){if(!C3.Gfx.RendererBase.IsValidSamplingMode(e))throw new Error(`invalid sampling mode '${e}'`);this.#e!==e&&(this.#e=e,this._runtime.UpdateRender(),this._UpdateActiveSamplingModes())}GetSamplingMode(){return this.#e}_UpdateActiveSamplingModes(){let e=this._runtime.GetSamplingMode();const t=this.GetSamplingMode();"auto"!==t&&(e=t),this.#t=e;for(const e of this._rootLayers)e._UpdateActiveSamplingModes()}GetActiveSampling(){return this.#t}Set3DCameraEnabled(e){e=!!e,this._is3dCameraEnabled!==e&&(this._is3dCameraEnabled=e,this.Set3DCameraChanged())}Is3DCameraEnabled(){return this._is3dCameraEnabled}Set3DCameraOrientation(e,t,s,n,a,i,r,o,l){vec3EqualsXYZ(this._cam3dposition,e,t,s)&&vec3EqualsXYZ(this._cam3dlook,n,a,i)&&vec3EqualsXYZ(this._cam3dup,r,o,l)||(vec3.set(this._cam3dposition,e,t,s),vec3.set(this._cam3dlook,n,a,i),vec3.set(this._cam3dup,r,o,l),this.Set3DCameraChanged())}Set3DCameraChanged(){this._SetAllLayersMVChanged(),this._runtime.UpdateRender()}Get3DCameraPosition(){return this._cam3dposition}Get3DCameraLookAt(){return this._cam3dlook}Get3DCameraUpVector(){return this._cam3dup}GetScale(){return this._scale}SetScale(e){this._scale!==e&&(this._scale=e,this._SetAllLayersMVChanged(),this.BoundScrolling(),this._runtime.UpdateRender())}SetAngle(e){e=C3.clampAngle(e),this._angle!==e&&(this._angle=e,this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}GetAngle(){return this._angle}GetWidth(){return this._width}SetWidth(e){!isFinite(e)||e<1||(this._width=e)}GetHeight(){return this._height}SetHeight(e){!isFinite(e)||e<1||(this._height=e)}GetEventSheet(){return this._eventSheet}_GetRootLayers(){return this._rootLayers}*allLayers(){for(const e of this._rootLayers)yield*e.selfAndAllSubLayers()}GetLayers(){return this._allLayersFlat}GetLayerCount(){return this._allLayersFlat.length}GetLayer(e){return"number"==typeof e?this.GetLayerByIndex(e):this.GetLayerByName(e.toString())}GetLayerByIndex(e){return e=C3.clamp(Math.floor(e),0,this._allLayersFlat.length-1),this._allLayersFlat[e]}GetLayerByName(e){return this._layersByName.get(e.toLowerCase())||null}HasLayerByName(e){return!!this.GetLayerByName(e)}GetLayerBySID(e){return this._layersBySid.get(e)||null}_SetAllLayersProjectionChanged(){for(const e of this._allLayersFlat)e._SetProjectionMatrixChanged()}_SetAllLayersMVChanged(){for(const e of this._allLayersFlat)e._SetMVMatrixChanged()}AddLayer(e,t,s){if(this.HasLayerByName(e))throw new Error(`layer name '${e}' already in use`);if(!t&&s<2)throw new Error("invalid insert position");const n=s>=2?t:t.GetParentLayer(),a=C3.New(C3.Layer,this,n,{name:e,sid:Math.floor(1e15*Math.random()),isDynamic:!0});this._InsertLayer(a,t,s),this.GetRuntime().UpdateRender(),this._ReindexAndUpdateAllLayers()}MoveLayer(e,t,s){if(!t&&s<2)throw new Error("invalid insert position");e===t&&s<2||(this._RemoveLayer(e),this._InsertLayer(e,t,s),this.GetRuntime().UpdateRender(),this._ReindexAndUpdateAllLayers())}RemoveLayer(e){if(this._RemoveLayer(e)){const t=this._runtime.GetEventSheetManager();t.BlockFlushingInstances(!0),e.Release(),t.BlockFlushingInstances(!1),this.GetRuntime().UpdateRender(),this._ReindexAndUpdateAllLayers()}}RemoveAllDynamicLayers(){const e=new Set;for(const t of this.allLayers())t.IsDynamic()&&!t.HasAnyDynamicParentLayer()&&e.add(t);if(0===e.size)return;const t=this._runtime.GetEventSheetManager();t.BlockFlushingInstances(!0);for(const t of e)this._RemoveLayer(t),t.Release();t.BlockFlushingInstances(!1),this.GetRuntime().UpdateRender(),this._ReindexAndUpdateAllLayers()}_InsertLayer(e,t,s){if(s>=2)if(t){if(t===e||t.HasParentLayer(e))throw new Error(`cannot move layer '${e.GetName()}' to sub-layer of itself`);t._AddSubLayer(e,2===s),e._SetParentLayer(t)}else 2===s?this._rootLayers.push(e):this._rootLayers.unshift(e),e._SetParentLayer(null);else{const n=t.GetParentLayer();if(n){if(t.HasParentLayer(e))throw new Error(`cannot move layer '${e.GetName()}' to sub-layer of itself`);n._InsertSubLayer(e,t,0===s),e._SetParentLayer(n)}else{let n=this._rootLayers.indexOf(t);if(-1===n)throw new Error("cannot find layer to insert by");0===s&&++n,this._rootLayers.splice(n,0,e),e._SetParentLayer(null)}}}_RemoveLayer(e){const t=e.GetParentLayer();if(t)return t._RemoveSubLayer(e),!0;if(this._rootLayers.length>1){const t=this._rootLayers.indexOf(e);if(-1===t)throw new Error("cannot find layer to remove");return this._rootLayers.splice(t,1),!0}return!1}_ReindexLayers(){this._allLayersFlat=[...this.allLayers()],this._layersByName.clear(),this._layersBySid.clear();for(let e=0,t=this._allLayersFlat.length;ee)break}return t}SaveTransform(){return{"scrollX":this.GetScrollX(),"scrollY":this.GetScrollY(),"scale":this.GetScale(),"angle":this.GetAngle(),"vpX":this.GetVanishingPointX(),"vpY":this.GetVanishingPointY()}}RestoreTransform(e){this.SetScrollX(e["scrollX"]),this.SetScrollY(e["scrollY"]),this.SetScale(e["scale"]),this.SetAngle(e["angle"]),this.SetVanishingPointXY(e["vpX"],e["vpY"])}GetLayoutBackgroundColor(){let e=this._rootLayers.filter(e=>e.ShouldDraw())[0];for(;e;){if(!e.IsTransparent())return tempColor.copyRgb(e.GetBackgroundColor()),tempColor.setA(1),tempColor;if(e.UsesOwnTexture())return tempColor.setRgba(0,0,0,0),tempColor;e=e.GetSubLayers().filter(e=>e.ShouldDraw())[0]}return tempColor.setRgba(0,0,0,0),tempColor}IsFirstVisit(){return this._isFirstVisit}_GetInitialObjectClasses(){return[...this._initialObjectClasses]}_AddInitialObjectClass(e){if(e.IsInContainer())for(const t of e.GetContainer().GetObjectTypes())this._initialObjectClasses.add(t);else this._initialObjectClasses.add(e)}_GetTextureLoadedObjectTypes(){return[...this._textureLoadedTypes]}_Load(e,t){if(e===this||!t)return Promise.resolve();e&&(C3.CopySet(this._textureLoadedTypes,e._textureLoadedTypes),e._textureLoadedTypes.clear());const s=[];for(const e of this._initialObjectClasses)this._textureLoadedTypes.has(e)||(s.push(e.LoadTextures(t)),this._textureLoadedTypes.add(e));return Promise.all(s)}async MaybeLoadTexturesFor(e){if(e.IsFamily())throw new Error("cannot load textures for family");const t=this._runtime.GetRenderer();if(!t||t.IsContextLost()||this._textureLoadedTypes.has(e))return;this._textureLoadedTypes.add(e);const s=e.LoadTextures(t);this._AddPendingTextureLoadPromise(s),await s,e.OnDynamicTextureLoadComplete(),this._runtime.UpdateRender()}_AddPendingTextureLoadPromise(e){this._textureLoadPendingPromises.add(e),e.then(()=>this._textureLoadPendingPromises.delete(e)).catch(()=>this._textureLoadPendingPromises.delete(e))}WaitForPendingTextureLoadsToComplete(){return Promise.all([...this._textureLoadPendingPromises])}MaybeUnloadTexturesFor(e){if(e.IsFamily()||e.GetInstanceCount()>0)throw new Error("cannot unload textures");const t=this._runtime.GetRenderer();t&&this._textureLoadedTypes.has(e)&&(this._textureLoadedTypes.delete(e),e.ReleaseTextures(t))}UnloadUnusedTextures(e,t=!1){const s=this._runtime.GetRenderer();s&&e.ReleaseUnusedTextures(s)}_Unload(e,t){if(e!==this&&t)for(const t of this._textureLoadedTypes)t.IsGlobal()||e._initialObjectClasses.has(t)||(t.ReleaseTextures(),this._textureLoadedTypes.delete(t))}_OnRendererContextLost(){this._textureLoadedTypes.clear()}async _StartRunning(e){const t=this._runtime,s=this._layoutManager,n=t.GetEventSheetManager();this._eventSheetName&&(this._eventSheet=n.GetEventSheetByName(this._eventSheetName),this._eventSheet._UpdateDeepIncludes()),s._SetMainRunningLayout(this),this._width=this._originalWidth,this._height=this._originalHeight,this._scrollX=t.GetOriginalViewportWidth()/2,this._scrollY=t.GetOriginalViewportHeight()/2,this.BoundScrolling(),this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged(),this._ReindexHTMLLayers(),await this._runtime.GetCanvasManager().SetHTMLLayerCount(this.GetHTMLLayerCount(),!0),this._MoveGlobalObjectsToThisLayout(e),this._runtime.SetUsingCreatePromises(!0),this.#s=!0,this._CreateInitialInstances(),this._isFirstVisit||this._CreatePersistedInstances(),this._CreateAndLinkContainerInstances(this._createdInstances),this._CreateAndLinkContainerInstances(this._createdPersistedInstances),this._CreateInitialNonWorldInstances(),s.ClearPendingChangeLayout(),t.FlushPendingInstances(),this._runtime.SetUsingCreatePromises(!1);const a=this._runtime.GetCreatePromises();if(await Promise.all(a),C3.clearArray(a),!t.IsLoadingState()){for(const e of this._createdInstances)e.SetupInitialSceneGraphConnections();for(const e of this._createdPersistedInstances)e.SetupPersistedSceneGraphConnections(this._createdPersistedInstancesToDataMap,this._createdPersistedIndexToInstanceMap);for(const[e,t]of Object.entries(this._persistData)){const s=this._runtime.GetObjectClassBySID(parseInt(e,10));s&&!s.IsFamily()&&s.HasPersistBehavior()&&C3.clearArray(t)}for(const e of this._createdInstances)e._TriggerOnCreated();for(const e of this._createdPersistedInstances)e._TriggerOnCreated();for(const e of this._createdInstances)e.HasParent()||e._OnHierarchyReady();for(const e of this._createdPersistedInstances)e.HasParent()||e._OnHierarchyReady()}C3.clearArray(this._createdInstances),C3.clearArray(this._createdPersistedInstances),this._createdPersistedInstancesToDataMap.clear(),this._createdPersistedIndexToInstanceMap.clear(),await Promise.all([...this._initialObjectClasses].map(e=>e.PreloadTexturesWithInstances(this._runtime.GetRenderer()))),this.#s=!1,this._UpdateActiveSamplingModes(),e&&(t.Dispatcher().dispatchEvent(new C3.Event("beforefirstlayoutstart")),await t.DispatchUserScriptEventAsyncWait(new C3.Event("beforeprojectstart"))),await this.DispatchRuntimeUserScriptEventAsyncWait(new C3.Event("beforeanylayoutstart")),t.Dispatcher().dispatchEvent(new C3.Event("beforelayoutstart")),await this.DispatchUserScriptEventAsyncWait(new C3.Event("beforelayoutstart")),t.IsLoadingState()||await t.TriggerAsync(C3.Plugins.System.Cnds.OnLayoutStart,null,null),t.Dispatcher().dispatchEvent(new C3.Event("afterlayoutstart")),await this.DispatchUserScriptEventAsyncWait(new C3.Event("afterlayoutstart")),await this.DispatchRuntimeUserScriptEventAsyncWait(new C3.Event("afteranylayoutstart")),e&&(t.Dispatcher().dispatchEvent(new C3.Event("afterfirstlayoutstart")),await t.DispatchUserScriptEventAsyncWait(new C3.Event("afterprojectstart"))),n._RunQueuedTriggers(s),await this.WaitForPendingTextureLoadsToComplete(),this._isFirstVisit=!1}IsCreatingInitialInstances(){return this.#s}_MoveGlobalObjectsToThisLayout(e){for(const e of this._runtime.GetAllObjectClasses())if(!e.IsFamily()&&e.IsWorldType())for(const t of e.GetInstances()){const e=t.GetWorldInfo(),s=e.GetLayer(),n=s.GetName(),a=this.GetLayerByName(n);if(a)e._SetLayer(a,!0),a._MaybeAddInstance(t);else{const n=C3.clamp(s.GetIndex(),0,this._allLayersFlat.length-1),a=this._allLayersFlat[n];e._SetLayer(a,!0),a._MaybeAddInstance(t)}}if(!e)for(const e of this._allLayersFlat)e._SortInstancesByLastCachedZIndex(!1)}_CreateInitialInstances(){for(const e of this._allLayersFlat)e.CreateInitialInstances(this._createdInstances),e._Start()}_CreatePersistedInstances(){let e=!1;for(const[t,s]of Object.entries(this._persistData)){const n=this._runtime.GetObjectClassBySID(parseInt(t,10));if(n&&!n.IsFamily()&&n.HasPersistBehavior())for(const t of s){let s=null;if(n.IsWorldType()&&(s=t.hasOwnProperty("instJson")?this.GetLayerBySID(t["instJson"]["w"]["l"]):this.GetLayerBySID(t["w"]["l"]),!s))continue;const a=this._runtime.CreateInstanceFromData(n,s,!1,0,0,!0);t.hasOwnProperty("instJson")?a.LoadFromJson(t["instJson"]):a.LoadFromJson(t),e=!0,this._createdPersistedInstances.push(a),t.hasOwnProperty("instJson")&&(this._createdPersistedInstancesToDataMap.set(a,t),this._createdPersistedIndexToInstanceMap.set(t["index"],a))}}for(const e of this._allLayersFlat)e._SortInstancesByLastCachedZIndex(!0),e.SetZIndicesChanged();e&&(this._runtime.FlushPendingInstances(),this._runtime._RefreshUidMap())}_CreateAndLinkContainerInstances(e){for(const t of e){if(!t.IsInContainer())continue;const s=t.GetWorldInfo(),n=t.GetIID();for(const a of t.GetObjectClass().GetContainer().objectTypes()){if(a===t.GetObjectClass())continue;const i=a.GetInstances();if(i.length>n)t._AddSibling(i[n]);else{let n;n=s?this._runtime.CreateInstanceFromData(a,s.GetLayer(),!0,s.GetX(),s.GetY(),!0):this._runtime.CreateInstanceFromData(a,null,!0,0,0,!0),this._runtime.FlushPendingInstances(),a._UpdateIIDs(),t._AddSibling(n),e.push(n)}}}}_CreateInitialNonWorldInstances(){for(const e of this._initialNonWorld){this._runtime.GetObjectClassByIndex(e[1]).IsInContainer()||this._runtime.CreateInstanceFromData(e,null,!0)}}_CreateGlobalNonWorlds(){const e=[],t=this._initialNonWorld;let s=0;for(let n=0,a=t.length;ne.ShouldDraw());for(let s=0,i=a.length;s=2||1===tempRender3dList.length&&tempRender3dList[0].HasAnyVisibleSubLayer()){this.#n(e,t,tempRender3dList),s+=tempRender3dList.length,C3.clearArray(tempRender3dList);continue}C3.clearArray(tempRender3dList)}r.Draw(e,t,n&&0===s),++s}}_DrawLayoutOwnTextureToRenderTarget(e,t){const s=this._effectList.GetActiveEffectTypes(),n=this._runtime;0===s.length?(e.SetRenderTarget(null),e.SetTextureFillMode(),e.CopyRenderTarget(t),e.InvalidateRenderTarget(t),n.ReleaseAdditionalRenderTarget(t)):(tempLayoutRect.set(0,0,n.GetViewportWidth(),n.GetViewportHeight()),this.GetEffectChain().Render(e,null,{contentObject:this,blendMode:3,sampling:this.GetActiveSampling(),devicePixelRatio:this._runtime.GetEffectDevicePixelRatioParam(),layerScale:this._runtime.GetEffectLayerScaleParam()*this.GetScale(),layerAngle:this.GetAngle(),layoutRect:tempLayoutRect,drawSurfaceRect:null,invalidateRenderTargets:!0}))}SortInstancesByCameraDistance(e,t){const s=this.Get3DCameraPosition(),n=s[0],a=s[1],i=s[2],r=e.GetWorldInfo(),o=t.GetWorldInfo(),l=r.GetX()-n,h=r.GetY()-a,c=r.GetZ()-i,d=o.GetX()-n,u=o.GetY()-a,_=o.GetZ()-i;return d*d+u*u+_*_-(l*l+h*h+c*c)}#n(e,t,s){const n=s[0],a=n._MaybeStartWebGLProfiling(e);n._MaybeStartWebGPUProfiling(e),s[0].IsTransparent()||(tempColor.copyRgb(s[0].GetBackgroundColor()),tempColor.setA(1),e.Clear(tempColor)),e.SetDepthEnabled(!0);const i=tempInstanceList;let r=!0,o=!0;for(const t of s)t.UsesCameraDistanceDrawOrder()?r=!1:o=!1,t._UpdateZIndices(),t._AppendAllInstancesIncludingSubLayersInDrawOrder(i),t._FireDrawEvent(e,"beforedraw");r?i.sort(SortByInstZ):o&&i.sort((e,t)=>this.SortInstancesByCameraDistance(e,t)),layoutCoplanarManager.DrawCoplanar(e,null,t,i);for(const t of s)t._FireDrawEvent(e,"afterdraw");a&&e.EndQuery(a),C3.clearArray(i)}_SaveToJson(){const e={"sx":this.GetScrollX(),"sy":this.GetScrollY(),"s":this.GetScale(),"a":this.GetAngle(),"w":this.GetWidth(),"h":this.GetHeight(),"ortho":this.IsOrthographicProjection(),"vpX":this.GetVanishingPointX(),"vpY":this.GetVanishingPointY(),"samp":this.GetSamplingMode(),"fv":this._isFirstVisit,"persist":this._persistData,"fx":this._effectList.SaveToJson(),"layers":{},"dynamicLayers":[]};for(const t of this._allLayersFlat)if(t.IsDynamic()){const s=t.GetParentLayer();e["dynamicLayers"].push({"sid":t.GetSID(),"name":t.GetName(),"parentSid":s?s.GetSID():null,"siblingIndex":t._GetSiblingIndex(),"data":t._SaveToJson()})}else e["layers"][t.GetSID().toString()]=t._SaveToJson();return e}_LoadFromJson(e){this._scrollX=e["sx"],this._scrollY=e["sy"],this._scale=e["s"],this._angle=e["a"],this._width=e["w"],this._height=e["h"],this._isOrthographicProjection=!!e["ortho"],e.hasOwnProperty("vpX")&&(this._vanishingPointX=e["vpX"]),e.hasOwnProperty("vpY")&&(this._vanishingPointY=e["vpY"]),this.#e=e["samp"]??"auto",this._isFirstVisit=!!e["fv"],this._persistData=e["persist"],this._effectList.LoadFromJson(e["fx"]),this._needsRebuildEffectChainSteps=!0;for(const[t,s]of Object.entries(e["layers"])){const e=parseInt(t,10),n=this.GetLayerBySID(e);n&&n._LoadFromJson(s)}if(e.hasOwnProperty("dynamicLayers")){this.RemoveAllDynamicLayers(),this._runtime.FlushPendingInstances();const t=new Map,s=e["dynamicLayers"];for(let e=s.length-1;e>=0;--e){const n=s[e],a=n["sid"],i=n["name"],r=n["parentSid"],o=n["siblingIndex"],l=n["data"];if(this._ReindexLayers(),this.HasLayerByName(i)||this.GetLayerBySID(a))continue;let h,c;if(null===r)h=null,c=this._rootLayers;else{if(h=this.GetLayerBySID(r),!h)continue;c=h.GetSubLayers()}const d=C3.New(C3.Layer,this,h,{name:i,sid:a,isDynamic:!0});c.push(d);let u=t.get(c);u||(u=[],t.set(c,u)),u.push({layer:d,siblingIndex:o}),d._LoadFromJson(l)}for(const[e,s]of t){s.sort((e,t)=>e.siblingIndex-t.siblingIndex);for(const t of s){const s=t.layer,n=t.siblingIndex;let a=e.indexOf(s);e.splice(a,1),e.splice(n,0,s)}}}this._ReindexAndUpdateAllLayers(),this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged()}GetILayout(){return this._iLayout}UserScriptDispatcher(){return this._userScriptDispatcher}DispatchUserScriptEvent(e){e.layout=this.GetILayout();const t=this._runtime,s=t.IsDebug()&&!t.GetEventSheetManager().IsInEventEngine();s&&C3Debugger.StartMeasuringScriptTime(),this._userScriptDispatcher.dispatchEvent(e),s&&C3Debugger.AddScriptTime()}DispatchUserScriptEventAsyncWait(e){return e.layout=this.GetILayout(),this._userScriptDispatcher.dispatchEventAndWaitAsync(e)}DispatchRuntimeUserScriptEventAsyncWait(e){return e.layout=this.GetILayout(),this._runtime.DispatchUserScriptEventAsyncWait(e)}_LogLayerTree(){this._LogLayerList(this._rootLayers)}_LogLayerList(e,t=0){const s=e.slice(0);s.reverse();for(const e of s)console.log(`${"\t".repeat(t)}- ${e.GetName()}`),this._LogLayerList(e.GetSubLayers(),t+1)}}; } // layouts/layoutManager.js { const C3=self.C3;C3.LayoutManager=class extends C3.DefendedBase{#t;#n=[];#u=new Map;#a=new Map;#i=null;#e=[];#s=null;#o=0;#y=null;constructor(t){super(),this.#t=t}Release(){this.#t=null,this.#i=null,this.#s=null,this.#y=null,C3.clearArray(this.#n),this.#u.clear(),this.#a.clear(),C3.clearArray(this.#e)}Create(t){const n=C3.New(C3.Layout,this,this.#n.length,t);this.#n.push(n),this.#u.set(n.GetName().toLowerCase(),n),this.#a.set(n.GetSID(),n)}GetRuntime(){return this.#t}SetFirstLayout(t){this.#s=t}GetFirstLayout(){if(this.#s)return this.#s;if(this.#n.length)return this.#n[0];throw new Error("no first layout")}GetLayoutByName(t){return this.#u.get(t.toLowerCase())||null}GetLayoutBySID(t){return this.#a.get(t)||null}GetLayoutByIndex(t){return t=C3.clamp(Math.floor(t),0,this.#n.length-1),this.#n[t]}GetLayout(t){return"number"==typeof t?this.GetLayoutByIndex(t):this.GetLayoutByName(t.toString())}GetAllLayouts(){return this.#n}_SetMainRunningLayout(t){this.#i=t}GetMainRunningLayout(){return this.#i}_AddRunningSubLayout(t){if(this.#e.includes(t))throw new Error("layout already running");this.#e.push(t)}_RemoveRunningSubLayout(t){const n=this.#e.indexOf(t);if(-1===n)throw new Error("layout not running");this.#e.splice(n,1)}*runningLayouts(){this.#i&&(yield this.#i),this.#e.length&&(yield*this.#e)}IsLayoutRunning(t){return this.#i===t||this.#e.includes(t)}SetIsEndingLayout(t){if(t)this.#o++;else{if(this.#o<=0)throw new Error("already unset");this.#o--}}IsEndingLayout(){return this.#o>0}ChangeMainLayout(t){this.#y=t}ClearPendingChangeLayout(){this.#y=null}IsPendingChangeMainLayout(){return!!this.#y}GetPendingChangeMainLayout(){return this.#y}SetAllLayerProjectionChanged(){const t=this.GetMainRunningLayout();t&&t._SetAllLayersProjectionChanged()}SetAllLayerMVChanged(){const t=this.GetMainRunningLayout();t&&t._SetAllLayersMVChanged()}}; } // timelines/timelineManager.js { const C3=self.C3,NAMES_REGEXP=new RegExp("<(.+?)>","g");C3.TimelineManager=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e,this._timelineDataManager=C3.New(C3.TimelineDataManager),this._pluginInstance=null,this._timelines=[],this._timelinesByName=new Map,this._objectClassToTimelineMap=new Map,this._timelinesCreatedByTemplate=new Map,this._scheduledTimelines=[],this._playingTimelines=[],this._markedForRemovalTimelines=[],this._hasRuntimeListeners=!1,this._changingLayout=!1,this._isTickingTimelines=!1,this._tickFunc=()=>this._OnTick(),this._tick2Func=()=>this._OnTick2(),this._beforeLayoutChange=()=>this._OnBeforeChangeLayout(),this._layoutChange=()=>this._OnAfterChangeLayout(),this._instanceDestroy=e=>this._OnInstanceDestroy(e.instance),this._beforeLoad=e=>this._OnBeforeLoad(),this._afterLoad=e=>this._OnAfterLoad(),this._afterLayoutStart=e=>this._OnAfterLayoutStart(),this._destroyedWhileLoadingState=[],this._renderChange=0}Release(){this.RemoveRuntimeListeners(),this._tickFunc=null,this._tick2Func=null,this._beforeLayoutChange=null,this._layoutChange=null,this._instanceDestroy=null,this._afterLoad=null;for(const e of this._timelines)e.Stop(),e.Release();C3.clearArray(this._timelines),this._timelines=null,this._timelineDataManager.Release(),this._timelineDataManager=null,C3.clearArray(this._scheduledTimelines),this._scheduledTimelines=null,C3.clearArray(this._playingTimelines),this._playingTimelines=null,C3.clearArray(this._markedForRemovalTimelines),this._markedForRemovalTimelines=null,this._timelinesByName.clear(),this._timelinesByName=null,this._objectClassToTimelineMap.clear(),this._objectClassToTimelineMap=null,this._timelinesCreatedByTemplate.clear(),this._timelinesCreatedByTemplate=null,C3.clearArray(this._destroyedWhileLoadingState),this._destroyedWhileLoadingState=null,this._runtime=null}AddRuntimeListeners(){const e=this._runtime.Dispatcher();e.addEventListener("pretick",this._tickFunc),e.addEventListener("tick2",this._tick2Func),e.addEventListener("beforelayoutchange",this._beforeLayoutChange),e.addEventListener("layoutchange",this._layoutChange),e.addEventListener("instancedestroy",this._instanceDestroy),e.addEventListener("beforeload",this._beforeLoad),e.addEventListener("afterload",this._afterLoad),e.addEventListener("afterlayoutstart",this._afterLayoutStart)}RemoveRuntimeListeners(){const e=this._runtime.Dispatcher();e.removeEventListener("pretick",this._tickFunc),e.removeEventListener("tick2",this._tick2Func),e.removeEventListener("beforelayoutchange",this._beforeLayoutChange),e.removeEventListener("layoutchange",this._layoutChange),e.removeEventListener("instancedestroy",this._instanceDestroy),e.removeEventListener("beforeload",this._beforeLoad),e.removeEventListener("afterload",this._afterLoad),e.removeEventListener("afterlayoutstart",this._afterLayoutStart)}Create(e){this._timelineDataManager.Add(e);const i=C3.TimelineState.CreateInitial(e,this);this.Add(i),this.SetTimelineObjectClassesToMap(i),this._timelinesCreatedByTemplate.set(i.GetName(),0)}CreateFromTemplate(e){const i=this.GetTimelineDataManager(),t=e.GetTemplateName(),s=i.Get(t),n=C3.TimelineState.CreateFromTemplate(`${t}:${this._timelinesCreatedByTemplate.get(t)}`,s,this);return this._IncreaseTemplateTimelinesCount(t),this.Add(n),this._runtime.IsDebug()&&globalThis.C3Debugger.TimelineCreated(n),n}GetCreatedTemplateTimelinesCount(e){return this._timelinesCreatedByTemplate.get(e)}_IncreaseTemplateTimelinesCount(e){this._timelinesCreatedByTemplate.set(e,this._timelinesCreatedByTemplate.get(e)+1)}_SetCreatedTemplateTimelinesCount(){for(const e of this._timelines){if(e.IsTemplate())continue;const i=e.GetTemplateName();this._IncreaseTemplateTimelinesCount(i)}}_ClearCreatedTemplateTimelinesCount(){for(const e of this._timelinesCreatedByTemplate.keys())this._timelinesCreatedByTemplate.set(e,0)}Add(e){this._timelines.push(e),this._timelinesByName.set(e.GetName().toLowerCase(),e)}Remove(e){e.Removed(),e.IsTemplate()||(C3.arrayFindRemove(this._timelines,e),C3.arrayFindRemove(this._scheduledTimelines,e),C3.arrayFindRemove(this._playingTimelines,e),C3.arrayFindRemove(this._markedForRemovalTimelines,e),this._timelinesByName.delete(e.GetName().toLowerCase()),this.RemoveTimelineFromObjectClassMap(e),this._runtime.IsDebug()&&globalThis.C3Debugger.TimelineDestroyed(e),e.IsReleased()||e.Release())}Trigger(e){this._runtime.Trigger(e,this._pluginInstance,null)}GetRuntime(){return this._runtime}GetTimelineDataManager(){return this._timelineDataManager}SetPluginInstance(e){this._pluginInstance=e}GetPluginInstance(){return this._pluginInstance}*GetTimelines(){for(const e of this._timelines)yield e}*GetPlayingTimelines(){for(const e of this._playingTimelines)yield e}SetTimelineObjectClassToMap(e,i){this._objectClassToTimelineMap.has(e)||this._objectClassToTimelineMap.set(e,new Set),this._objectClassToTimelineMap.get(e).add(i)}SetTimelineObjectClassesToMap(e){for(const i of e.GetObjectClasses())this.SetTimelineObjectClassToMap(i,e)}RemoveTimelineFromObjectClassMap(e){for(const[i,t]of this._objectClassToTimelineMap.entries())t.has(e)&&(t.delete(e),0===t.size&&this._objectClassToTimelineMap.delete(i))}GetTimelinesForObjectClass(e){if(this._objectClassToTimelineMap.has(e))return this._objectClassToTimelineMap.get(e)}GetTimelineOfTemplateForInstances(e,i){if(i)for(const t of this._timelines){if(i.every(e=>t.HasTrackInstance(e.instance,e.trackId))&&t.GetName().includes(e.GetName()))return t}}GetTimelineByName(e){return this._timelinesByName.get(e.toLowerCase())||null}GetScheduledOrPlayingTimelineByName(e){for(const i of this._scheduledTimelines)if(i.GetName()===e)return i;for(const i of this._playingTimelines)if(i.GetName()===e)return i;return null}*GetTimelinesByName(e){if(NAMES_REGEXP.test(e)){let i;NAMES_REGEXP.lastIndex=0;const t=new Set;do{if(i=NAMES_REGEXP.exec(e),i){const e=i[1].split(",");for(const i of e)t.add(i)}}while(i);for(const e of t.values()){const i=this.GetTimelineByName(e);i&&(yield i)}t.clear()}else{const i=this.GetTimelineByName(e);i&&(yield i)}}*GetTimelinesByTags(e){for(const i of this._timelines)i.HasTags(e)&&(yield i)}AddScheduledTimeline(e){this._scheduledTimelines.includes(e)||this._scheduledTimelines.push(e),this._MaybeEnableRuntimeListeners()}RemovePlayingTimeline(e){C3.arrayFindRemove(this._playingTimelines,e),this._MaybeDisableRuntimeListeners()}ScheduleTimeline(e){this._playingTimelines.includes(e)?(e.SetPlaying(!0),e.SetScheduled(!1),e.SetMarkedForRemoval(!1)):(e.SetPlaying(!1),e.SetScheduled(!0),e.SetMarkedForRemoval(!1),this._scheduledTimelines.includes(e)||this._scheduledTimelines.push(e)),this._MaybeEnableRuntimeListeners()}DeScheduleTimeline(e){e.SetPlaying(!1),e.SetScheduled(!1),e.ResolvePlayPromise(),C3.arrayFindRemove(this._scheduledTimelines,e),this._MaybeDisableRuntimeListeners()}CompleteTimeline(e){e.SetPlaying(!1),e.SetScheduled(!1),this._playingTimelines.includes(e)&&(e.SetMarkedForRemoval(!0),this._markedForRemovalTimelines.push(e),C3.arrayFindRemove(this._playingTimelines,e)),this._scheduledTimelines.includes(e)&&e.SetMarkedForRemoval(!0)}CompleteTimelineBeforeChangeOfLayout(e){e.SetPlaying(!1),e.SetScheduled(!1),e.SetMarkedForRemoval(!1),e.SetPlaybackRate(1),C3.arrayFindRemove(this._playingTimelines,e)}CompleteTimelineAndResolve(e){this.CompleteTimeline(e),e.ResolvePlayPromise()}_OnTick(){const e=this.GetRuntime();if(e.IsLoadingState())return;if(!this._hasRuntimeListeners)return;if(this._changingLayout)return;let i=0;for(e.IsDebug()&&(i=performance.now()),this._isTickingTimelines=!0;this._scheduledTimelines.length;){const e=this._scheduledTimelines.pop();e.IsMarkedForRemoval()?(e.SetInitialStateForce(),this._markedForRemovalTimelines.push(e)):(e.SetInitialState(),this._playingTimelines.push(e)),0!==e.GetRenderChange()&&(this._renderChange=1)}const t=this._runtime._GetDtFast(),s=this._runtime.GetDt1(),n=this._runtime.GetTimeScale();for(let e=this._playingTimelines.length-1;e>=0;e--){const i=this._playingTimelines[e];i&&i.Tick(t,n,s)}this._isTickingTimelines=!1,e.IsDebug()&&globalThis.C3Debugger.AddTweensAndTimelinesTime(performance.now()-i),0!==this._renderChange&&e.UpdateRender()}_OnTick2(){const e=this.GetRuntime();if(e.IsLoadingState())return;if(!this._hasRuntimeListeners)return;if(this._changingLayout)return;let i,t=0;e.IsDebug()&&(t=performance.now());for(let e=0,t=this._markedForRemovalTimelines.length;ee))this._MaybeExecuteTimelineFinishTriggers(e),this.Remove(e);for(const e of this._playingTimelines.map(e=>e))this._MaybeExecuteTimelineFinishTriggers(e),this.Remove(e)}_OnAfterLoad(){for(const e of this._destroyedWhileLoadingState)this._OnInstanceDestroy(e);C3.clearArray(this._destroyedWhileLoadingState);for(const e of this._timelines)e._OnAfterLoad()}_OnAfterLayoutStart(){const e=this._runtime.GetLayoutManager().GetMainRunningLayout();if(e)for(const i of this._timelines){const t=i.GetStartOnLayout();t&&(e.GetName()===t&&this.ScheduleTimeline(i))}}_SaveToJson(){return{"timelinesJson":this._SaveTimelinesToJson(),"scheduledTimelinesJson":this._SaveScheduledTimelinesToJson(),"playingTimelinesJson":this._SavePlayingTimelinesToJson(),"markedForRemovalTimelinesJson":this._SaveMarkedForRemovalTimelinesToJson(),"hasRuntimeListeners":this._hasRuntimeListeners,"changingLayout":this._changingLayout,"isTickingTimelines":this._isTickingTimelines}}_LoadFromJson(e){e&&(this._ClearCreatedTemplateTimelinesCount(),this._LoadTimelinesFromJson(e["timelinesJson"]),this._LoadScheduledTimelinesFromJson(e["scheduledTimelinesJson"]),this._LoadPlayingTimelinesFromJson(e["playingTimelinesJson"]),this._LoadMarkedForRemovalTimelinesFromJson(e["markedForRemovalTimelinesJson"]),this._hasRuntimeListeners=!e["hasRuntimeListeners"],this._changingLayout=!!e["changingLayout"],this._isTickingTimelines=!!e["isTickingTimelines"],this._SetCreatedTemplateTimelinesCount(),this._MaybeEnableRuntimeListeners(),this._MaybeDisableRuntimeListeners())}_SaveTimelinesToJson(){return this._timelines.map(e=>e._SaveToJson())}_LoadTimelinesFromJson(e){for(const i of e){let e=this.GetTimelineByName(i["name"]);if(e)e._LoadFromJson(i);else{const t=this._GetTemplateNameFromJson(i);if(!t)continue;const s=this.GetTimelineByName(t);e=this.CreateFromTemplate(s),e._LoadFromJson(i)}e.HasTracks()||this.Remove(e)}}_GetTemplateNameFromJson(e){const i=e["name"].split(":");return i&&2===i.length?i[0]:null}_SaveScheduledTimelinesToJson(){return this._SaveTimelines(this._scheduledTimelines)}_LoadScheduledTimelinesFromJson(e){this._LoadTimelines(e,this._scheduledTimelines)}_SavePlayingTimelinesToJson(){return this._SaveTimelines(this._playingTimelines)}_LoadPlayingTimelinesFromJson(e){this._LoadTimelines(e,this._playingTimelines)}_SaveMarkedForRemovalTimelinesToJson(){return this._SaveTimelines(this._markedForRemovalTimelines)}_LoadMarkedForRemovalTimelinesFromJson(e){this._LoadTimelines(e,this._markedForRemovalTimelines)}_IsTimelineInJson(e,i){if(!i)return!1;for(const t of i)if(t===e.GetName())return!0;return!1}_SaveTimelines(e){return e.map(e=>e.GetName())}_LoadTimelines(e,i){const t=new Set;for(const s of i)this._IsTimelineInJson(s,e)||t.add(s);if(C3.arrayRemoveAllInSet(i,t),e){const t=e=>i=>i.GetName()===e;for(const s of e){const e=this.GetTimelineByName(s);if(e){i.find(t(s))||i.push(e)}}}}}; } // timelines/timelineInfo.js { const C3=self.C3,STEPS=100,LENGTH_STEP_SIZE=.01,BEZIER_STEP_SIZE=25,REFINE_ITERATIONS=20,LOOKUP_STEPS_FROM_LAST=5,TANGENT_RESULT=[0,0],MAP_RESULT=[0,0],SHORT_PROJECTION_RESULT=[0,0],PROJECTION_RESULT=[0,0,0,0,0],REFINE_LUT=new Array(4),REFINE_LUT_OBJECTS=[{x:0,y:0,t:0,distance:0},{x:0,y:0,t:0,distance:0},{x:0,y:0,t:0,distance:0}],REFINE_RESULT={x:0,y:0,t:0,distance:0};C3.TimelineInfo=class{constructor(t,i){this._initialized=!1,this._timeline=t,this._segments=[];let e=null;if(e=i?this._timeline.GetTrackById(i):C3.first(this._timeline.GetTracks()),!e)return;const s=e.GetPropertyTrack("offsetX"),_=e.GetPropertyTrack("offsetY");if(!s||!_)return;this._xTrack=s,this._yTrack=_;const h=s.GetPropertyKeyframeDataItemArrayIncludingDisabled(),n=_.GetPropertyKeyframeDataItemArrayIncludingDisabled();for(let t=1,i=Math.min(h.length,n.length);ti&&_--;const h=this._arcLengths[_];return h===i?_/this._len:(_+(i-h)/(this._arcLengths[_+1]-h))/this._len}_X(t){return this._initialized?self.Ease.GetRuntimeEase("cubicbezier")(t,this._aX+this._originX,this._bX+this._originX,this._cX+this._originX,this._dX+this._originX):NaN}_Y(t){return this._initialized?self.Ease.GetRuntimeEase("cubicbezier")(t,this._aY+this._originY,this._bY+this._originY,this._cY+this._originY,this._dY+this._originY):NaN}_GenerateLUT(t){if(t=t||100,this._lut.length>=t)return this._lut;this._lut=new Array(t),t++;for(let i=0;i=e.length);s++){const n=e[s],r=n.x-t,a=n.y-i;n.distance=r*r+a*a,n.distance<_&&(_=n.distance,h=s)}for(let s=this._lutIndex;s>this._lutIndex-5&&!(s<0);s--){const n=e[s],r=n.x-t,a=n.y-i;n.distance=r*r+a*a,n.distance<_&&(_=n.distance,h=s)}}return this._lutIndex=h,h}_FindClosestFromLUTWithRange(t,i,e,s,_=Number.MAX_SAFE_INTEGER){let h=0;if(isNaN(this._lutIndex))for(let n=0;n<100;n++){const r=e[n],a=r.x-t,c=r.y-i;r.distance=a*a+c*c,r.t>=s[0]&&r.t<=s[1]&&r.distance<_&&(_=r.distance,h=n)}else{for(let n=this._lutIndex;n=e.length);n++){const r=e[n],a=r.x-t,c=r.y-i;r.distance=a*a+c*c,r.t>=s[0]&&r.t<=s[1]&&r.distance<_&&(_=r.distance,h=n)}for(let n=this._lutIndex;n>this._lutIndex-5&&!(n<0);n--){const r=e[n],a=r.x-t,c=r.y-i;r.distance=a*a+c*c,r.t>=s[0]&&r.t<=s[1]&&r.distance<_&&(_=r.distance,h=n)}}return this._lutIndex=h,h}_RefineProjection(t,i,e,s){let _=e[s],h=1,n=Number.MAX_SAFE_INTEGER;t:do{const h=e.length;let r=0===s?0:s-1,a=s===h-1?h-1:s+1,c=e[r].t,l=(e[a].t-c)/4;if(l<.001)break;REFINE_LUT[0]=e[r];for(let e=1;e<=2;e++){const h=c+e*l,r=h**2,a=h**3,o=this._x1Factor*h,d=this._x2Factor*r,u=this._x3Factor*a,O=this._y1Factor*h,T=this._y2Factor*r,E=this._y3Factor*a,R=this._aXO+o+d+u,g=this._aYO+O+T+E,N=R-t,I=g-i,S=N*N+I*I;if(S0}GetStatus(){return this.IsPlaying()?"playing":this.IsPaused()?"paused":this.IsComplete()?"complete":"other"}GetPlayPromise(){return this._playPromise||(this._playPromise=new Promise(t=>{this._playResolve=t})),this._playPromise}ResolvePlayPromise(){this._playPromise&&(this._playResolve(),this._playPromise=null,this._playResolve=null)}SetTags(t){this._tags=C3.TimelineState._GetTagArray(t),this._tagsChanged=!0}GetTags(){return this._tags}GetStringTags(){return this._tagsChanged&&(this._stringTags=this._tags.join(" ")),this._tagsChanged=!1,this._stringTags}HasTags(t){if(!this._tags)return!1;if(!this._tags.length)return!1;const e=C3.TimelineState._GetTagArray(t);return!!e&&(!!e.length&&e.every(C3.TimelineState._HasTag,this))}OnStarted(){C3.Plugins.Timeline&&this.constructor===C3.TimelineState&&(C3.Plugins.Timeline.Cnds.PushTriggerTimeline(this),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineStarted),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineStartedByName),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineStartedByTags),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnAnyTimelineStarted),C3.Plugins.Timeline.Cnds.PopTriggerTimeline())}OnCompleted(){this._completedTick=this._runtime.GetTickCount()}FinishTriggers(){this._finishedTriggers||(this._finishedTriggers=!0,C3.Plugins.Timeline&&this.constructor===C3.TimelineState&&(C3.Plugins.Timeline.Cnds.PushTriggerTimeline(this),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineFinished),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineFinishedByName),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimelineFinishedByTags),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnAnyTimelineFinished),C3.Plugins.Timeline.Cnds.PopTriggerTimeline()))}SetPlaying(t){this._isPlaying=t}IsCompletedTick(){return this._completedTick===this._runtime.GetTickCount()}IsPlaying(t=!1){return!!this.IsCompletedTick()||(!(!this.IsScheduled()||t)||this._isPlaying)}_IsPlaying(){return this.IsPlaying(!0)}IsPaused(){return this._IsPaused()}_IsPaused(){return!this.IsReleased()&&(!this.IsScheduled()&&(!this._IsPlaying()&&!this.IsComplete()))}SetScheduled(t){this._isScheduled=t}IsScheduled(){return this._isScheduled}SetComplete(t){this._complete=t;const e=this.GetLoop(),i=this.GetPingPong();if(e||i){if(e&&!i);else if(!e&&i){const t=this.GetTime();1===this._pingPongState&&(t<=0||t>=this.GetTotalTime())&&(this._complete=!0)}}else{const t=this.GetTime();(t<=0||t>=this.GetTotalTime())&&(this._complete=!0)}}IsComplete(){return this._complete}IsReleased(){return this._released}SetMarkedForRemoval(t){this._markedForRemoval=t}IsMarkedForRemoval(){return this._markedForRemoval}SetImplicitPause(t){this._implicitPause=t}IsImplicitPause(){return this._implicitPause}SetIsTemplate(t){this._isTemplate=!!t}IsTemplate(){return this._isTemplate}InitialStateSet(){return this._initialStateSet}GetTime(){return this._playheadTime}SetTime(t){if(t=Number(t),!C3.IsFiniteNumber(t))return;const e=this.GetTime();this._SetTime(t),this.SetComplete(!1),this.IsComplete()||this.SetImplicitPause(!0),(this._IsPlaying()||this.IsScheduled()||!this._initialStateSet)&&(this._IsPlaying()||this.IsScheduled()||this._initialStateSet?this._IsPlaying()?this.Stop():this.IsScheduled()&&(this._timelineManager.DeScheduleTimeline(this),this.SetInitialStateFromSetTime()):this.SetInitialStateFromSetTime()),this._SetUpdateStateBefore(),this._Interpolate(this.GetTime(),!1,!0,!0,e),this._SetUpdateStateAfter(),this._renderChange&&this.GetRuntime().UpdateRender(),this._OnSetTime()}_SetTime(t){C3.IsFiniteNumber(t)||(t=this.GetTotalTime()),t<0?this._playheadTime=0:t>=this.GetTotalTime()?this._playheadTime=this.GetTotalTime():this._playheadTime=t}_SetTimeAndReset(t){C3.IsFiniteNumber(t)||(t=this.GetTotalTime()),t<0?this._playheadTime=0:t>=this.GetTotalTime()?this._playheadTime=this.GetTotalTime():this._playheadTime=t;for(const t of this._tracks)t.SetResetState()}_OnSetTime(){C3.Plugins.Timeline&&this.constructor===C3.TimelineState&&(C3.Plugins.Timeline.Cnds.PushTriggerTimeline(this),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimeSet),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimeSetByName),this._timelineManager.Trigger(C3.Plugins.Timeline.Cnds.OnTimeSetByTags),C3.Plugins.Timeline.Cnds.PopTriggerTimeline())}_CanResume(){if(this.GetLoop())return!0;if(this.GetPingPong()&&1===this._pingPongState){if(this.IsForwardPlayBack()){if(this.GetTime()>=this.GetTotalTime())return!1}else if(this.GetTime()<=0)return!1}else if(!this.GetLoop()&&!this.GetPingPong())if(this.IsForwardPlayBack()){if(this.GetTime()>=this.GetTotalTime())return!1}else if(this.GetTime()<=0)return!1;return!0}Resume(){this.IsReleased()||this._CanResume()&&this.Play(!0)}Play(t=!1){return!this.IsReleased()&&(!this.IsScheduled()&&(this._IsPlaying()&&this.IsCompletedTick()?this._SchedulePlayingTimeline():!this._IsPlaying()&&(!!(this.IsComplete()||t||this.IsImplicitPause())&&this._ScheduleStoppedTimeline())))}_SchedulePlayingTimeline(){return this.SetImplicitPause(!1),this._timelineManager.RemovePlayingTimeline(this),this._timelineManager.ScheduleTimeline(this),this.GetPlayPromise(),!0}_ScheduleStoppedTimeline(){return this.SetImplicitPause(!1),this._timelineManager.ScheduleTimeline(this),this.GetPlayPromise(),!0}Stop(t=!1){this.IsReleased()||(this.SetComplete(t),this._timelineManager.CompleteTimeline(this),this.IsComplete()&&this.ResolvePlayPromise())}Reset(t=!0,e=!1){if(this.IsReleased())return;if(!this._IsPlaying()&&this.IsScheduled())return this._timelineManager.DeScheduleTimeline(this);if(this.IsComplete())return;this.Stop(!0),this.IsForwardPlayBack()?this._SetTime(0):this._SetTime(this.GetTotalTime());const i=this.GetTime();this._SetUpdateStateBefore(),e?this._InterpolateBeforeChangeLayout(i):this._Interpolate(i,!1,!1,!0),t&&this._OnSetTime(),this._SetUpdateStateAfter(),this._renderChange&&t&&this.GetRuntime().UpdateRender()}ResetBeforeChangeLayout(){this.Reset(!1,!0)}_InterpolateBeforeChangeLayout(t){this._Interpolate(t,!1,!1,!0,NaN,!1,!0)}_OnBeforeChangeLayout(){return!!this.IsReleased()||!(!this.GetRuntime().IsLoadingState()&&this.HasValidGlobalTracks())&&(this._timelineManager.CompleteTimelineBeforeChangeOfLayout(this),this.GetRuntime().IsLoadingState()||this.ResetBeforeChangeLayout(),!0)}SetInitialStateFromSetTime(){this.SetInitialState(!0)}SetInitialStateForce(){this.SetInitialState(!1,!0),this.SetPlaying(!1),this.SetScheduled(!1)}SetInitialState(t=!1,e=!1){if(!this.IsMarkedForRemoval()||e)if(t){this._finishedTriggers=!1,this._initialStateSet=!0,this._firstTick=!0,this._SetUpdateStateBefore();for(const t of this._tracks)t.SetInitialState();this._SetUpdateStateAfter()}else if(this.SetPlaying(!0),this.SetScheduled(!1),this.OnStarted(),this.IsComplete()){this._completedTick=-1,0!==this._pingPongState&&(this._playbackRate=Math.abs(this._playbackRate)),this._pingPongState=0,this._resumePingPongState=-1,this._currentRepeatCount=1,this._complete=!1,this._finishedTriggers=!1,this._initialStateSet=!0,this._firstTick=!0,this.IsForwardPlayBack()?this._SetTime(0):this._SetTime(this.GetTotalTime()),this._SetUpdateStateBefore();for(const t of this._tracks)t.SetInitialState();this._SetUpdateStateAfter()}else{-1!==this._resumePingPongState&&(this._pingPongState=this._resumePingPongState),this._firstTick=!0,this._finishedTriggers=!1,this._SetUpdateStateBefore();for(const t of this._tracks)t.SetResumeState();this._SetUpdateStateAfter()}}GetRenderChange(){return this._renderChange}_SetUpdateStateBefore(){this._hasNestedContent=0;for(const t of this._tracks)t.IsNested()&&(this._hasNestedContent=1)}_SetUpdateStateAfter(){this._renderChange=0;for(const t of this._tracks)t._SetUpdateState(),0===this._renderChange&&1===t.GetRenderChange()&&(this._renderChange=1),this._beforeAndAfterTracks||1!==t.GetNeedsBeforeAndAfter()||(this._beforeAndAfterTracks||(this._beforeAndAfterTracks=[]),this._beforeAndAfterTracksLength=this._beforeAndAfterTracks.push(t))}Tick(t,e,i){if(this.GetUseSystemTimescale()){if(0===t&&0===this._lastDelta)return;this._lastDelta=t,t=i}else{if(0===i&&0===this._lastDelta)return;this._lastDelta=i,t=i,e=1}const s=this._playheadTime+this._overshoot,a=s+t*e*this._playbackRate,n=this._timelineDataItem._totalTime;a<0?(this._playheadTime=0,this._overshoot=-a):a>=n?(this._playheadTime=n,this._overshoot=this._playheadTime-a):(this._playheadTime=a,this._overshoot=0);let r=!1,h=!1;const l=this.GetLoop(),o=this.GetPingPong();let m;l||o?l&&!o?this._playbackRate>0?this._playheadTime>=n&&this._SetTimeAndReset(0):this._playheadTime<=0&&this._SetTimeAndReset(n):!l&&o?this._playbackRate>0?this._playheadTime>=n&&(this._SetTime(n),this.SetPlaybackRate(-1*this.GetPlaybackRate()),h=!0,1===this._pingPongState?this._currentRepeatCount0?this._playheadTime>=n&&(this._SetTime(n),this.SetPlaybackRate(-1*this.GetPlaybackRate()),h=!0,this._pingPongState++,C3.wrap(this._pingPongState,0,2)):this._playheadTime<=0&&(this._SetTime(0),this.SetPlaybackRate(-1*this.GetPlaybackRate()),h=!0,this._pingPongState++,C3.wrap(this._pingPongState,0,2))):this._playbackRate>0?this._playheadTime>=n&&(this._currentRepeatCount0?t.BeforeInterpolate(e):t.BeforeInterpolate(this._playheadTime)}if(1===this._hasNestedContent)for(m=0;m<_;m++){const t=this._tracks[m],e=t.GetStartOffset();this._playheadTime-e<0&&s-e>0?t.Interpolate(e,!0,!1,h,this._firstTick,!1):t.Interpolate(this._playheadTime,!0,!1,h,this._firstTick,!1)}else for(m=0;m<_;m++)this._tracks[m].Interpolate(this._playheadTime,!0,!1,h,this._firstTick,!1);if(!this.IsPlaying()&&this._stoppedKeyframeDataItem){const t=this._stoppedKeyframeDataItem.GetTime()+this._stoppedKeyframeDataItem.GetKeyframeData().GetTrackDataItem().GetStartOffset(),e=this._playheadTime-t;this._playheadTime-=e,0!==this._overshoot&&(this._overshoot-=e),this._stoppedKeyframeDataItem=null}for(m=0;m0?t.AfterInterpolate(e):t.AfterInterpolate(this._playheadTime)}this._firstTick&&(this._firstTick=!1)}SetStoppedOnKeyframe(t){this._stoppedKeyframeDataItem=t}GetStoppedOnKeyframe(){return this._stoppedKeyframeDataItem}_GetTrackStartTime(t,e,i,s=!1){let a=t;if("number"==typeof e&&!isNaN(e)){const t=this.GetTime()-i.GetStartOffset(),n=e-i.GetStartOffset();t<0&&n>0&&(a=i.GetStartOffset(),s&&this._SetTime(a))}return a}_Interpolate(t,e=!1,i=!1,s=!1,a=NaN,n=!1,r=!1){for(const e of this._tracks){const s=this._GetTrackStartTime(t,a,e);e.BeforeInterpolate(s,i)}for(const n of this._tracks){const h=this._GetTrackStartTime(t,a,n,!0);n.Interpolate(h,e,i,s,this._firstTick,r)}for(const e of this._tracks){const s=this._GetTrackStartTime(t,a,e);e.AfterInterpolate(s,i)}this._firstTick&&n&&(this._firstTick=!1)}AddTrack(){const t=this._timelineDataItem.GetTrackData().AddEmptyTrackDataItem(),e=C3.TrackState.Create(this,t);return this._tracksLength=this._tracks.push(e),e}Removed(){if(!this.IsReleased())for(const t of this._tracks)t.TimelineRemoved()}CleanCaches(){for(const t of this._tracks)t.CleanCaches()}*GetInstances(){for(const t of this._tracks){t.GetInstance()&&(yield t.GetInstance())}}ClearTrackInstances(){for(const t of this._tracks)t.ClearInstance()}SetTrackInstance(t,e,i){if(e){if("number"==typeof i&&i>=0){const t=this._tracks[i];if(!t)return;return t.SetInstance(e),void this._timelineManager.SetTimelineObjectClassToMap(e.GetObjectClass(),this)}for(const i of this._tracks)if(i.IsInstanceTrack()){if(t){if(i.GetId()!==t)continue;i.SetInstance(e),this._timelineManager.SetTimelineObjectClassToMap(e.GetObjectClass(),this);break}if(!i.HasInstance()){i.SetInstance(e),this._timelineManager.SetTimelineObjectClassToMap(e.GetObjectClass(),this);break}}}}HasTrackInstance(t,e){for(const i of this._tracks)if(i.IsInstanceTrack())if(e){if(e===i.GetId()&&t===i.GetInstance())return!0}else if(t===i.GetInstance())return!0;return!1}HasValidTracks(){return this._tracks.some(t=>!t.IsInstanceTrack()||t.CanInstanceBeValid())}HasValidGlobalTracks(){return this._tracks.some(t=>{if(t.IsInstanceTrack()){if(!t.CanInstanceBeValid())return!1;const e=t.GetObjectClass();return!!e&&e.IsGlobal()}return!1})}GetPropertyTrack(t){for(const e of this.GetTracks())for(const i of e.GetPropertyTracks())if(i.GetPropertyName()===t)return i}GetTrackFromInstance(t){for(const e of this._tracks)if(t===e.GetInstance())return e;return null}GetKeyframeWithTags(t){let e=t?t.split(" "):[];const i=new Set(e.map(t=>t.toLowerCase().trim()));e=[...i.values()];for(const t of this.GetTracks())for(const i of t.GetKeyframeDataItems()){if(e.every(t=>i.HasTag(t)))return i}}GetObjectClasses(){const t=[];for(const e of this.GetTracks())t.push(e.GetObjectClass());return t.filter(t=>t)}_OnAfterLoad(){for(const t of this.GetTracks())t._OnAfterLoad()}_SaveToJson(){return{"tracksJson":this._SaveTracksToJson(),"name":this._name,"playheadTime":this.GetTime(),"playbackRate":this._playbackRate,"pingPongState":this._pingPongState,"resumePingPongState":this._resumePingPongState,"currentRepeatCount":this._currentRepeatCount,"isPlaying":this._isPlaying,"isScheduled":this._isScheduled,"initialStateSet":this._initialStateSet,"finishedTriggers":this._finishedTriggers,"complete":this._complete,"released":this._released,"markedForRemoval":this._markedForRemoval,"completedTick":this._completedTick,"implicitPause":this._implicitPause,"isTemplate":this._isTemplate,"tags":this._tags.join(" "),"stringTags":this._stringTags,"tagsChanged":this._tagsChanged,"firstTick":this._firstTick}}_LoadFromJson(t){t&&(this._LoadTracksFromJson(t["tracksJson"]),this._name=t["name"],this._playheadTime=t["playheadTime"],this._playbackRate=t["playbackRate"],this._pingPongState=t["pingPongState"],this._resumePingPongState=t.hasOwnProperty("resumePingPongState")?t["resumePingPongState"]:-1,this._currentRepeatCount=t["currentRepeatCount"],this._isPlaying=!!t["isPlaying"],this._isScheduled=!!t["isScheduled"],this._initialStateSet=!!t["initialStateSet"],this._finishedTriggers=!!t.hasOwnProperty("finishedTriggers")&&!!t["finishedTriggers"],this._complete=!!t["complete"],this._released=!!t["released"],this._markedForRemoval=!!t["markedForRemoval"],this._completedTick=t["completedTick"],this._implicitPause=!!t["implicitPause"],this._isTemplate=!!t["isTemplate"],this._tags=t["tags"].split(" "),this._stringTags=t["stringTags"],this._tagsChanged=!!t["tagsChanged"],this._firstTick=!!t["firstTick"])}_SaveTracksToJson(){return this._tracks.map(t=>t._SaveToJson())}_LoadTracksFromJson(t){this.ClearTrackInstances(),t.forEach((t,e)=>{this._tracks[e]._LoadFromJson(t)}),this._tracks.filter(t=>t.CanInstanceBeValid())}static _HasTag(t){const e=this.GetTags();return""===t?1===e.length&&""===e[0]:e.map(t=>t.toLowerCase()).includes(t.toLowerCase())}static _GetTagArray(t){if(C3.IsArray(t))return t.slice(0);if(C3.IsString(t))return t.split(" ");throw new Error("invalid tags")}GetITimelineState(){return this._iTimelineState||(this._iTimelineState=C3.New(self.ITimelineState,this)),this._iTimelineState}}; } // timelines/state/trackState.js { const C3=self.C3,INSTANCE_TRACK=0,VALUE_TRACK=1,AUDIO_TRACK=2;C3.TrackState=class extends C3.DefendedBase{constructor(t,e){super(),this._timeline=t,this._trackDataItem=e,this._trackData=e.GetTrackData(),this._instanceUid=NaN,this._objectClassIndex=NaN,this._instance=null,this._worldInfo=null,this._cleared=!1,this._isNested=e.GetStartOffset()>0,this._initialStateOfNestedSet=!1,this._endStateOfNestedSet=!1,this._instanceUidToLoad=NaN,this._lastKeyframeDataItem=null,this._keyframeDataItems=this._trackDataItem.GetKeyframeData().GetKeyframeDataItemArray(),this._propertyTracks=[],this.CreatePropertyTrackStates(),this._worldInfoChange=0,this._renderChange=0,this._needsBeforeAndAfter=0,this._lastTime=NaN,this._keyframeReachedOnCurrentTick=null}static Create(t,e){return C3.New(C3.TrackState,t,e)}Release(){this._keyframeDataItems=null;for(const t of this._propertyTracks)t.Release();C3.clearArray(this._propertyTracks),this._propertyTracks=null,this._timeline=null,this._instance=null,this._worldInfo=null,this._trackDataItem=null,this._lastKeyframeDataItem=null}CreatePropertyTrackStates(){for(const t of this._trackDataItem.GetPropertyTrackData().propertyTrackDataItems())this._propertyTracks.push(C3.PropertyTrackState.Create(this,t))}TimelineRemoved(){for(const t of this._propertyTracks)t.TimelineRemoved()}CleanCaches(){for(const t of this._propertyTracks)t.CleanCaches();this._instance=null,this._worldInfo=null}GetTimeline(){return this._timeline}GetRuntime(){return this._timeline.GetRuntime()}GetKeyframeDataItems(){return this._keyframeDataItems||(this._keyframeDataItems=this._trackDataItem.GetKeyframeData().GetKeyframeDataItemArray()),this._keyframeDataItems}GetPropertyTracks(){return this._propertyTracks}GetPropertyTrack(t){for(let e=0;et.GetNeedsBeforeAndAfter())&&(this._needsBeforeAndAfter=1),this._lastKeyframeDataItem=t?this._GetLastKeyFrameBeforeTime(e):this._GetFirstKeyFrameAfterTime(e),this._initialStateOfNestedSet=!1,this._endStateOfNestedSet=!1,this._lastTime=NaN,this.Interpolate(e),this.OnInitialKeyframeReached(this._lastKeyframeDataItem)}GetCurrentKeyframeInterval(){const t=this.GetLastKeyframe(),e=this.GetNextKeyframe();let a,s;return this._timeline.IsForwardPlayBack()?(a={GetTime:()=>t.GetTime()+this.GetStartOffset(),GetTags:()=>t.GetTagsString()||""},s={GetTime:()=>e?e.GetTime()+this.GetStartOffset():this.GetLocalTotalTime(),GetTags:()=>e?.GetTagsString()||""}):(a={GetTime:()=>e?e.GetTime()+this.GetStartOffset():this.GetLocalTotalTime(),GetTags:()=>e?.GetTagsString()||""},s={GetTime:()=>t.GetTime()+this.GetStartOffset(),GetTags:()=>t.GetTagsString()||""}),[a,s]}GetLastKeyframe(){const t=this._timeline.GetTime()-this.GetStartOffset();return this._timeline.IsForwardPlayBack()?this._GetLastKeyFrameBeforeTime(t):this._GetFirstKeyFrameAfterTime(t)}GetNextKeyframe(){return this._timeline.IsForwardPlayBack()?this.GetLastKeyframe().GetNext():this.GetLastKeyframe().GetLast()}SetResumeState(){if(this.MaybeGetInstance(),!this.IsInstanceValid()&&this.IsInstanceTrack())return;const t=this._timeline.IsForwardPlayBack(),e=this._timeline.GetTime()-this.GetStartOffset();this._lastKeyframeDataItem=t?this._GetLastKeyFrameBeforeTime(e):this._GetFirstKeyFrameAfterTime(e),this._lastTime=NaN;for(const t of this._propertyTracks)t.SetResumeState(e)}SetEndState(){if(!this.GetTimeline().IsComplete()&&(this.MaybeGetInstance(),(this.IsInstanceValid()||!this.IsInstanceTrack())&&!this._isNested)){const t=this._timeline.GetTime();t>=this.GetStartOffset()+this.GetLocalTotalTime()?this.Interpolate(this.GetLocalTotalTime(),!0,!1,!0,!1,!1,!0):t<=0&&this.Interpolate(0,!0,!1,!0,!1,!1,!0)}}_SetUpdateState(){for(let t=0,e=this._propertyTracks.length;tthis.GetLocalTotalTime())return;for(const t of this._propertyTracks)t.SetInitialState();this._initialStateOfNestedSet=!0}MaybeSetEndStateOfNestedTrack(t,e){if(!e)return;if(!this._isNested)return;if(this._endStateOfNestedSet)return;if(this.GetTimeline().IsForwardPlayBack()){if(t>=this.GetLocalTotalTime()){for(const t of this._propertyTracks)t.Interpolate(this.GetLocalTotalTime(),!1,!0);this._endStateOfNestedSet=!0}}else if(t<=0){for(const t of this._propertyTracks)t.Interpolate(0,!1,!0);this._endStateOfNestedSet=!0}}MaybeTriggerKeyframeReachedConditions(t,e,a){if(this._keyframeReachedOnCurrentTick=null,a)return;if(!e)return;if(!C3.Plugins.Timeline)return;const s=this.GetTimeline();if(s.IsForwardPlayBack()){const e=this._lastKeyframeDataItem.GetNext(),a=this._lastKeyframeDataItem.GetTime(),r=e?e.GetTime():s.GetTotalTime();(t<=a||t>=r)&&(this._lastKeyframeDataItem=this._trackData.GetFirstKeyFrameDataItemLowerOrEqualThan(t,this._trackDataItem),e&&this.OnKeyframeReached(this._lastKeyframeDataItem,!1,t))}else{if(!this._trackData.GetFirstKeyFrameDataItemHigherOrEqualThan(t,this._trackDataItem))return;this._lastKeyframeDataItem||(this._lastKeyframeDataItem=this._trackData.GetFirstKeyFrameDataItemHigherOrEqualThan(t,this._trackDataItem));const e=this._lastKeyframeDataItem.GetLast(),a=this._lastKeyframeDataItem.GetTime(),s=e?e.GetTime():0;(t>=a||t<=s)&&(this._lastKeyframeDataItem=this._trackData.GetFirstKeyFrameDataItemHigherOrEqualThan(t,this._trackDataItem),this._lastKeyframeDataItem&&this.OnKeyframeReached(this._lastKeyframeDataItem))}}_GetLastKeyFrameBeforeTime(t){const e=this._trackData.GetKeyFrameDataItemAtTime(t,this._trackDataItem);return e||this._trackData.GetFirstKeyFrameDataItemLowerOrEqualThan(t,this._trackDataItem)}_GetFirstKeyFrameAfterTime(t){const e=this._trackData.GetKeyFrameDataItemAtTime(t,this._trackDataItem);return e||this._trackData.GetFirstKeyFrameDataItemHigherOrEqualThan(t,this._trackDataItem)}OnKeyframeReached(t,e=!1,a){if(!C3.Plugins.Timeline)return;const s=this.GetTimeline(),r=s.GetTimelineManager();C3.Plugins.Timeline.Cnds.PushTriggerTimeline(s),C3.Plugins.Timeline.Cnds.PushTriggerKeyframe(t),r.Trigger(C3.Plugins.Timeline.Cnds.OnAnyKeyframeReached),r.Trigger(C3.Plugins.Timeline.Cnds.OnKeyframeReached),s.IsPlaying()||e||s.SetStoppedOnKeyframe(t),C3.Plugins.Timeline.Cnds.PopTriggerTimeline(s),C3.Plugins.Timeline.Cnds.PopTriggerKeyframe(t),this._keyframeReachedOnCurrentTick=t}WasKeyframeReachedOnCurrentTick(){return this._keyframeReachedOnCurrentTick}OnInitialKeyframeReached(t){this.OnKeyframeReached(t,!0)}AddKeyframe(){return this._trackDataItem.GetKeyframeData().AddEmptyKeyframeDataItem()}AddPropertyTrack(){const t=this._trackDataItem.GetPropertyTrackData().AddEmptyPropertyTrackDataItem(),e=C3.PropertyTrackState.Create(this,t);return this._propertyTracks.push(e),e}DeleteKeyframes(t){this._trackDataItem.GetKeyframeData().DeleteKeyframeDataItems(t)}DeletePropertyKeyframes(t){for(const e of this._propertyTracks)e.DeletePropertyKeyframes(t)}SaveState(){for(const t of this._propertyTracks)t.SaveState()}CompareInitialStateWithCurrent(){if(this.MaybeGetInstance(),this.IsInstanceValid()||!this.IsInstanceTrack())for(const t of this._propertyTracks)t.CompareInitialStateWithCurrent()}CompareSaveStateWithCurrent(){if(this.MaybeGetInstance(),!this.IsInstanceValid()&&this.IsInstanceTrack())return;let t=!1;for(const e of this._propertyTracks){const a=e.CompareSaveStateWithCurrent();!t&&a&&(t=!0)}if(t){const t=this.AddKeyframe();t.SetTime(this.GetTimeline().GetTime()),t.SetEase("noease"),t.SetEnable(!0),t.SetTags("")}}_OnAfterLoad(){isNaN(this._instanceUidToLoad)||this._LoadInstanceFromJson(this._instanceUidToLoad),this._instanceUidToLoad=NaN}_SaveToJson(){const t=this.GetInstance(),e=t?t.GetUID():this.GetInstanceUID();return{"propertyTracksJson":this._SavePropertyTracksToJson(),"lastKeyframeDataItemJson":this._SaveLastKeyframeDataItemToJson(),"initialStateOfNestedSet":this._initialStateOfNestedSet,"endStateOfNestedSet":this._endStateOfNestedSet,"instanceUid":e,"cleared":this._cleared}}_LoadFromJson(t){if(t){this._LoadPropertyTracksFromJson(t["propertyTracksJson"]),this._LoadLastKeyframeDataItemFromJson(t["lastKeyframeDataItemJson"]),this._instanceUidToLoad=t["instanceUid"],this._initialStateOfNestedSet=!1,t.hasOwnProperty["initialStateOfNestedSet"]&&(this._initialStateOfNestedSet=t["initialStateOfNestedSet"]),this._endStateOfNestedSet=!1,t.hasOwnProperty["endStateOfNestedSet"]&&(this._endStateOfNestedSet=t["endStateOfNestedSet"]),this._cleared=!!t.hasOwnProperty("cleared")&&t["cleared"];for(const t of this._propertyTracks)0===this._worldInfoChange&&1===t.GetWorldInfoChange()&&(this._worldInfoChange=1),0===this._renderChange&&1===t.GetRenderChange()&&(this._renderChange=1);this._needsBeforeAndAfter=0,this._propertyTracks.some(t=>t.GetNeedsBeforeAndAfter())&&(this._needsBeforeAndAfter=1)}}_SaveLastKeyframeDataItemToJson(){return this._trackDataItem.GetKeyframeData().GetKeyframeDataItemIndex(this._lastKeyframeDataItem)}_SavePropertyTracksToJson(){return this._propertyTracks.map(t=>t._SaveToJson())}_LoadPropertyTracksFromJson(t){t.forEach((t,e)=>{this._propertyTracks[e]._LoadFromJson(t)})}_LoadInstanceFromJson(t){if(!C3.IsFiniteNumber(t))return;const e=this.GetRuntime().GetInstanceByUID(t);if(!e)return;this.GetTimeline().SetTrackInstance(this._trackDataItem.GetId(),e,this.GetTrackIndexInTimeline())}_LoadLastKeyframeDataItemFromJson(t){const e=this._trackDataItem.GetKeyframeData();this._lastKeyframeDataItem=e.GetKeyframeDataItemFromIndex(t)}}; } // timelines/state/propertyTrackState.js { const C3=self.C3;C3.PropertyTrackState=class extends C3.DefendedBase{constructor(e,t){super(),this._track=e,this._propertyTrackDataItem=t,this._propertyTrackData=t.GetPropertyTrackData(),this._worldInfoChange=0,this._renderChange=0,this._needsBeforeAndAfter=0,this._sourceAdapter=this.GetSourceAdapter(),this._propertyKeyframeDataItems=this._propertyTrackDataItem.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray(),this._lastPropertyKeyframeDataItem=null,this._absoluteValueObject=null}static Create(e,t){return C3.New(C3.PropertyTrackState,e,t)}Release(){this._track=null,this._sourceAdapter&&(this._sourceAdapter.Release(),this._sourceAdapter=null),this._propertyKeyframeDataItems=null,this._propertyTrackDataItem=null,this._propertyTrackData=null}GetWorldInfoChange(){return this._worldInfoChange}GetRenderChange(){return this._renderChange}GetNeedsBeforeAndAfter(){return this._needsBeforeAndAfter}HasAbsoluteValueObject(){return!!this._absoluteValueObject}SetAbsoluteValueObject(e){this._absoluteValueObject=e}GetAbsoluteValueObject(){return this._absoluteValueObject}GetTrack(){return this._track}GetPropertyTrackDataItem(){return this._propertyTrackDataItem}GetPropertyTrackData(){return this._propertyTrackData}GetTimeline(){return this._track.GetTimeline()}GetRuntime(){return this._track.GetRuntime()}GetInstance(){return this._track.GetInstance()}GetSourceAdapter(){if(this._sourceAdapter)return this._sourceAdapter;let e;switch(this._propertyTrackDataItem.GetSourceAdapterId()){case"behavior":e=new C3.PropertyTrackState.BehaviorSourceAdapter(this);break;case"effect":e=new C3.PropertyTrackState.EffectSourceAdapter(this),this._renderChange=1;break;case"instance-variable":e=new C3.PropertyTrackState.InstanceVariableSourceAdapter(this);break;case"plugin":e=new C3.PropertyTrackState.PluginSourceAdapter(this),this._renderChange=1;break;case"world-instance":e=new C3.PropertyTrackState.PropertySourceAdapter(this),this._renderChange=1,this._worldInfoChange=1;break;case"value":e=new C3.PropertyTrackState.ValueSourceAdapter(this);break;case"audio":e=new C3.PropertyTrackState.AudioSourceAdapter(this)}return this._sourceAdapter=e,this._sourceAdapter}GetSourceAdapterId(){return this._propertyTrackDataItem.GetSourceAdapterId()}SetSourceAdapterId(e){this._propertyTrackDataItem.SetSourceAdapterId(e)}GetSourceAdapterArgs(){return this._propertyTrackDataItem.GetSourceAdapterArguments()}SetSourceAdapterArgs(e){this._propertyTrackDataItem.SetSourceAdapterArguments(e)}GetSourceAdapterValue(){return this.GetSourceAdapter().GetValue()}GetPropertyName(){return this._propertyTrackDataItem.GetProperty()}SetPropertyName(e){this._propertyTrackDataItem.SetProperty(e)}GetPropertyType(){return this._propertyTrackDataItem.GetType()}SetPropertyType(e){this._propertyTrackDataItem.SetType(e)}GetPropertyKeyframeType(){return this.GetPropertyTrackData().GetFirstPropertyKeyframeDataItem(this._propertyTrackDataItem).GetType()}GetMin(){return this._propertyTrackDataItem.GetMin()}SetMin(e){this._propertyTrackDataItem.SetMin(e)}GetMax(){return this._propertyTrackDataItem.GetMax()}SetMax(e){this._propertyTrackDataItem.SetMax(e)}GetEnable(){return this._propertyTrackDataItem.GetEnable()}SetEnable(e){this._propertyTrackDataItem.SetEnable(e)}GetInterpolationMode(){return this._propertyTrackDataItem.GetInterpolationMode()}SetInterpolationMode(e){this._propertyTrackDataItem.SetInterpolationMode(e)}GetResultMode(){return this._propertyTrackDataItem.GetResultMode()}SetResultMode(e){this._propertyTrackDataItem.SetResultMode(e)}SetEase(e){for(const t of this.GetPropertyKeyframeDataItems())t.SetEase(e)}CanHavePropertyKeyframes(){return this._propertyTrackDataItem.CanHavePropertyKeyframes()}GetPropertyKeyframeDataItems(){return this._propertyKeyframeDataItems||(this._propertyKeyframeDataItems=this._propertyTrackDataItem.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray()),this._propertyKeyframeDataItems}GetPropertyKeyframeDataItemArrayIncludingDisabled(){return this._propertyTrackDataItem.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArrayIncludingDisabled()}GetPropertyKeyFrameDataItemAtTime(e){return this._propertyTrackData.GetPropertyKeyFrameDataItemAtTime(e,this._propertyTrackDataItem)}GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e){return this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem)}GetPropertyKeyframeDataItemPairForTime(e){let t,r=this._propertyTrackData.GetPropertyKeyFrameDataItemAtTime(e,this._propertyTrackDataItem);return r?t=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherThan(e,this._propertyTrackDataItem):(r=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem),t=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(e,this._propertyTrackDataItem)),{start:r,end:t}}*GetPropertyKeyframeValues(){for(const e of this.GetPropertyKeyframeDataItems())yield e.GetValueWithResultMode()}*GetPropertyKeyframeTimes(){for(const e of this.GetPropertyKeyframeDataItems())yield e.GetTime()}TimelineRemoved(){this.GetSourceAdapter().TimelineRemoved()}CleanCaches(){this.GetSourceAdapter().CleanCaches()}GetCurrentState(){return this.GetSourceAdapter().GetCurrentState()}SetResetState(){this.GetSourceAdapter().SetResetState()}SetInitialState(e){this.GetSourceAdapter().SetInitialState(),this._lastPropertyKeyframeDataItem=this._GetLastPropertyKeyFrameBeforeTime(e),this._SetUpdateState()}SetResumeState(e){this.GetSourceAdapter().SetResumeState(),this._lastPropertyKeyframeDataItem=this._GetLastPropertyKeyFrameBeforeTime(e)}_SetUpdateState(){const e=this.GetTrack();if(this._needsBeforeAndAfter=0,e.IsInstanceTrack()){const t=this.GetTimeline(),r=e.GetInstance(),a=this.GetSourceAdapter(),o=this.GetPropertyName();if(a.MayNeedBeforeAndAfterInterpolate()){const e=t.GetSimilarPropertyTracks(r,a,o,this);e&&e.length&&(this._needsBeforeAndAfter=1)}else this._needsBeforeAndAfter=0}}_GetLastPropertyKeyFrameBeforeTime(e){const t=this.GetTimeline(),r=this._propertyTrackData.GetPropertyKeyFrameDataItemAtTime(e,this._propertyTrackDataItem);return r||(t.IsForwardPlayBack()?this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem):this._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(e,this._propertyTrackDataItem))}BeforeInterpolate(e,t){let r,a;if(t)r=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem);else{if(this._lastPropertyKeyframeDataItem){const t=this.GetTimeline(),r=this._lastPropertyKeyframeDataItem.GetNext(),a=this._lastPropertyKeyframeDataItem.GetTime(),o=r?r.GetTime():t.GetTotalTime();(e<=a||e>=o)&&(this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem))}else this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem);r=this._lastPropertyKeyframeDataItem}r&&(a=r.GetNext()),this._sourceAdapter.BeforeInterpolate(r,a)}Interpolate(e,t=!1,r=!1,a=!1){let o,s,p=!1;if(t)o=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem);else{if(this._lastPropertyKeyframeDataItem){const t=this.GetTimeline(),r=this._lastPropertyKeyframeDataItem.GetNext(),a=this._lastPropertyKeyframeDataItem.GetTime(),o=r?r.GetTime():t.GetTotalTime();(e<=a||e>=o)&&(this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem),p=!0)}else this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem),p=!0;o=this._lastPropertyKeyframeDataItem}o&&(s=o.GetNext()),this._sourceAdapter.Interpolate(e,o,s,t,r,a,p)}GetInterpolatedValue(e){if(this._lastPropertyKeyframeDataItem){const t=this.GetTimeline(),r=this._lastPropertyKeyframeDataItem.GetNext(),a=this._lastPropertyKeyframeDataItem.GetTime(),o=r?r.GetTime():t.GetTotalTime();(e<=a||e>=o)&&(this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem))}else this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem);const t=this._lastPropertyKeyframeDataItem,r=t.GetNext();return this._sourceAdapter.GetInterpolatedValue(e,t,r)}GetInterpolatedValueFast(e,t,r){return this._sourceAdapter.GetInterpolatedValue(e,t,r)}AfterInterpolate(e,t){let r,a;if(t)r=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem);else{if(this._lastPropertyKeyframeDataItem){const t=this.GetTimeline(),r=this._lastPropertyKeyframeDataItem.GetNext(),a=this._lastPropertyKeyframeDataItem.GetTime(),o=r?r.GetTime():t.GetTotalTime();(e<=a||e>=o)&&(this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem))}else this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,this._propertyTrackDataItem);r=this._lastPropertyKeyframeDataItem}r&&(a=r.GetNext()),this._sourceAdapter.AfterInterpolate(r,a)}static GetStartPropertyKeyframeForTime(e,t){const r=t.GetPropertyTrackDataItem();return t._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(e,r)}static GetEndPropertyKeyframeForTime(e,t){const r=t.GetPropertyTrackDataItem();return t._propertyTrackData.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(e,r)}static GetPropertyKeyframeValueWithPlaybackDirection(e,t,r){return t?r.GetTimeline().IsForwardPlayBack()?e.GetValueWithResultMode():t.GetValueWithResultMode():e.GetValueWithResultMode()}AddPropertyKeyframe(){const e=this._propertyTrackDataItem.GetPropertyKeyframeData().AddEmptyPropertyKeyframeDataItem();return this._lastPropertyKeyframeDataItem=null,e}DeletePropertyKeyframes(e){this._lastPropertyKeyframeDataItem=null;this._propertyTrackDataItem.GetPropertyKeyframeData().DeletePropertyKeyframeDataItems(e)}SaveState(){this.GetSourceAdapter().SaveState()}CompareInitialStateWithCurrent(){if(this.GetSourceAdapter().CompareInitialStateWithCurrent()){const e=this._propertyTrackData.GetFirstPropertyKeyframeDataItem(this._propertyTrackDataItem),t=this.GetSourceAdapter().GetCurrentState();e.SetAbsoluteValue(t)}}CompareSaveStateWithCurrent(){const e=this.GetSourceAdapter().CompareSaveStateWithCurrent();return e&&this.AddPropertyKeyframeAtCurrentTime(),this.GetSourceAdapter().ClearSaveState(),e}AddPropertyKeyframeAtCurrentTime(){const e=this.GetTimeline().GetTime(),t=this.GetSourceAdapter(),r=C3.PropertyTrackState.GetStartPropertyKeyframeForTime(e,this),a=this.AddPropertyKeyframe();a.SetType(r.GetType()),a.SetTime(e),a.SetEase(r.GetEase()),a.SetEnable(!0),a.SetValue(t.GetValueAtTime()),a.SetAbsoluteValue(t.GetCurrentState())}_SaveToJson(){return{"sourceAdapterJson":this.GetSourceAdapter()._SaveToJson()}}_LoadFromJson(e){e&&this.GetSourceAdapter()._LoadFromJson(e["sourceAdapterJson"])}}; } // timelines/state/propertySourceAdapters/propertySourceAdapter.js { const C3=self.C3,NS=C3.PropertyTrackState;NS.PropertySourceAdapter=class{constructor(e){this._propertyTrack=e,this._propertyAdapter=null,this.GetPropertyAdapter()}Release(){this._propertyAdapter&&(this._propertyAdapter.Release(),this._propertyAdapter=null),this._propertyTrack=null}MayNeedBeforeAndAfterInterpolate(){return this._propertyAdapter.MayNeedBeforeAndAfterInterpolate()}GetPropertyTrack(){return this._propertyTrack}TimelineRemoved(){this._propertyAdapter&&this._propertyAdapter.TimelineRemoved()}CleanCaches(){this._propertyAdapter&&this._propertyAdapter.CleanCaches()}GetPropertyAdapter(){return this._propertyAdapter||(this._propertyAdapter=this._CreatePropertyAdapter()),this._propertyAdapter}GetEditorIndex(){}GetIndex(){return this.GetEditorIndex()}GetTarget(){}SetResetState(){this.GetPropertyAdapter().SetResetState()}SetInitialState(){this.GetPropertyAdapter().SetInitialState()}SetResumeState(){this.GetPropertyAdapter().SetResumeState()}BeforeInterpolate(e,t){this._propertyAdapter.BeforeChangeProperty(e,t)}Interpolate(e,t,r,p,a,o,n){let s;switch(this._propertyTrack.GetPropertyKeyframeType()){case"numeric":s=NS.NumericTypeAdapter.Interpolate(e,t,r,this._propertyTrack);break;case"angle":s=NS.AngleTypeAdapter.Interpolate(e,t,r,this._propertyTrack);break;case"boolean":s=NS.BooleanTypeAdapter.Interpolate(e,t,r,this._propertyTrack);break;case"color":s=NS.ColorTypeAdapter.Interpolate(e,t,r,this._propertyTrack);break;case"text":s=NS.TextTypeAdapter.Interpolate(e,t,r,this._propertyTrack);break;case"map":s=NS.MapTypeAdapter.Interpolate(e,t,r,this._propertyTrack)}this._propertyAdapter.ChangeProperty(e,s,t,r,p,a,o,n)}GetInterpolatedValue(e,t,r){switch(this._propertyTrack.GetPropertyKeyframeType()){case"numeric":return NS.NumericTypeAdapter.Interpolate(e,t,r,this._propertyTrack);case"angle":return NS.AngleTypeAdapter.Interpolate(e,t,r,this._propertyTrack);case"boolean":return NS.BooleanTypeAdapter.Interpolate(e,t,r,this._propertyTrack);case"color":return NS.ColorTypeAdapter.Interpolate(e,t,r,this._propertyTrack);case"text":return NS.TextTypeAdapter.Interpolate(e,t,r,this._propertyTrack);case"map":return NS.MapTypeAdapter.Interpolate(e,t,r,this._propertyTrack)}}AfterInterpolate(e,t){this._propertyAdapter.AfterChangeProperty(e,t)}SaveState(){this.GetPropertyAdapter().SetSaveState()}ClearSaveState(){this.GetPropertyAdapter().ClearSaveState()}GetCurrentState(){return this.GetPropertyAdapter().GetCurrentState()}CompareInitialStateWithCurrent(){return this.GetPropertyAdapter().CompareInitialStateWithCurrent()}CompareSaveStateWithCurrent(){return this.GetPropertyAdapter().CompareSaveStateWithCurrent()}GetValueAtTime(){const e=this._propertyTrack,t=e.GetTrack().GetTimeline().GetTime(),r=NS.GetStartPropertyKeyframeForTime(t,e),p=r.GetNext();switch(e.GetPropertyKeyframeType()){case"numeric":return NS.NumericTypeAdapter.Interpolate(t,r,p,e);case"angle":return NS.AngleTypeAdapter.Interpolate(t,r,p,e);case"boolean":return NS.BooleanTypeAdapter.Interpolate(t,r,p,e);case"color":return NS.ColorTypeAdapter.Interpolate(t,r,p,e);case"text":return NS.TextTypeAdapter.Interpolate(t,r,p,e);case"map":return NS.MapTypeAdapter.Interpolate(t,r,p,e)}}_CreatePropertyAdapter(){const e=this._propertyTrack;switch(e.CanHavePropertyKeyframes()?e.GetPropertyKeyframeType():""){case"combo":case"boolean":case"text":case"string":case"map":return new NS.PropertyInterpolationAdapter.NoInterpolationAdapter(this);case"numeric":case"number":case"angle":return"combo"===this._propertyTrack.GetPropertyType()?new NS.PropertyInterpolationAdapter.NoInterpolationAdapter(this):new NS.PropertyInterpolationAdapter.NumericInterpolationAdapter(this);case"color":case"offsetColor":return new NS.PropertyInterpolationAdapter.ColorInterpolationAdapter(this);default:return new NS.PropertyInterpolationAdapter.NumericInterpolationAdapter(this)}}_SaveToJson(){return{"propertyAdapterJson":this.GetPropertyAdapter()._SaveToJson()}}_LoadFromJson(e){e&&this.GetPropertyAdapter()._LoadFromJson(e["propertyAdapterJson"])}}; } // timelines/state/propertySourceAdapters/instanceVariableSourceAdapter.js { const C3=self.C3,INDEX=0;class InstanceVariableSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(e){super(e),this._updatedIndex=NaN}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0]}GetIndex(){return this._updatedIndex?this._updatedIndex:super.GetIndex()}GetTarget(){return this._propertyTrack.GetTrack().GetInstance()}UpdateInstanceVariableIndex(e){this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0]!==e&&(this._updatedIndex=e)}Interpolate(e,t,r,a,n,d,p){this.GetPropertyAdapter().CanChange(t.GetValue())&&super.Interpolate(e,t,r,a,n,d,p)}GetInterpolatedValue(e,t,r){if(this.GetPropertyAdapter().CanChange(t.GetValue()))return super.GetInterpolatedValue(e,t,r)}_SaveToJson(){return Object.assign(super._SaveToJson(),{"index":this._updatedIndex})}_LoadFromJson(e){e&&(super._LoadFromJson(e),this._updatedIndex=e["index"])}}C3.PropertyTrackState.InstanceVariableSourceAdapter=InstanceVariableSourceAdapter; } // timelines/state/propertySourceAdapters/behaviorSourceAdapter.js { const C3=self.C3,SID=0,INDEX=1,NAME=2;class BehaviorSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(e){super(e),this._sid=NaN}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[1]}GetTarget(){const e=this._propertyTrack.GetPropertyTrackDataItem(),t=this._propertyTrack.GetTrack(),r=this._sid?this._sid:e.GetSourceAdapterArguments()[0],a=t.GetInstance(),s=a.GetBehaviorIndexBySID(r);return a.GetBehaviorInstances()[s].GetSdkInstance()}GetBehaviorType(e){const t=this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[2];return e.GetBehaviorTypeByName(t)}UpdateBehaviorTypeSid(e){this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0]!==e&&(this._sid=e)}Interpolate(e,t,r,a,s,o,p){const c=this._propertyTrack.GetTrack().GetInstance();this.GetBehaviorType(c.GetObjectClass())&&super.Interpolate(e,t,r,a,s,o,p)}GetInterpolatedValue(e,t,r){const a=this._propertyTrack.GetTrack().GetInstance();if(this.GetBehaviorType(a.GetObjectClass()))return super.GetInterpolatedValue(e,t,r)}_SaveToJson(){return Object.assign(super._SaveToJson(),{"sid":this._sid})}_LoadFromJson(e){e&&(super._LoadFromJson(e),this._sid=e["sid"])}}C3.PropertyTrackState.BehaviorSourceAdapter=BehaviorSourceAdapter; } // timelines/state/propertySourceAdapters/effectSourceAdapter.js { const C3=self.C3,NAME=0,INDEX=1;class EffectSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(e){super(e)}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[1]}GetTarget(){const e=this._propertyTrack.GetTrack().GetWorldInfo().GetInstanceEffectList(),t=e.GetEffectList(),r=this.GetEffectType(t).GetIndex();return e.IsEffectIndexActive(r)?e.GetEffectParametersForIndex(r):null}GetEffectType(e){const t=this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0];return e.GetEffectTypeByName(t)}Interpolate(e,t,r,c,f,a,s){this._IsEffectActive()&&super.Interpolate(e,t,r,c,f,a,s)}GetInterpolatedValue(e,t,r){if(this._IsEffectActive())return super.GetInterpolatedValue(e,t,r)}_IsEffectActive(){const e=this._propertyTrack.GetTrack().GetWorldInfo().GetInstanceEffectList(),t=e.GetEffectList(),r=this.GetEffectType(t);if(!r)return;const c=r.GetIndex();return e.IsEffectIndexActive(c)}}C3.PropertyTrackState.EffectSourceAdapter=EffectSourceAdapter; } // timelines/state/propertySourceAdapters/pluginSourceAdapter.js { const C3=self.C3,INDEX=0,UNIQUE_PROPERTIES=1,SPRITE_START_FROM_UNIQUE_PROPERTY=0;class PluginSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(t){super(t),this._optionalCallbacksRelative=null,this._optionalCallbacksAbsolute=null,this._forceNextChange=!1}GetEditorIndex(){return this._propertyTrack.GetPropertyTrackDataItem().GetSourceAdapterArguments()[0]}GetTarget(){return this._propertyTrack.GetTrack().GetInstance().GetSdkInstance()}Interpolate(t,e,a,i,r,s,n){const o=this._propertyTrack.GetTrack();o.GetObjectClass().GetPlugin()===o.GetInstance().GetObjectClass().GetPlugin()&&super.Interpolate(t,e,a,i,r,s,n)}GetInterpolatedValue(t,e,a){const i=this._propertyTrack.GetTrack();if(i.GetObjectClass().GetPlugin()===i.GetInstance().GetObjectClass().GetPlugin())return super.GetInterpolatedValue(t,e,a)}_IsTimelineChunkDiscreteLike(t,e){if(!e)return!0;if(t?.GetValueWithResultMode()===e?.GetValueWithResultMode())return!0;const a=this._propertyTrack?.GetInterpolationMode();return"discrete"===a}_WasKeyframeReached(t,e,a){const i=t.WasKeyframeReachedOnCurrentTick();if(!i)return!1;return this._propertyTrack.GetTimeline().IsForwardPlayBack()?i.GetTime()===e.GetTime():i.GetTime()===a.GetTime()}SetResetState(){this.GetPropertyAdapter().SetResetState();const t=this._propertyTrack.GetTrack().GetObjectClass().GetPlugin();this._forceNextChange=!1,C3.Plugins.Sprite&&t instanceof C3.Plugins.Sprite&&"initial-animation"===this._propertyTrack.GetPropertyName()&&(this._forceNextChange=!0)}ForceChanges(){const t=this._forceNextChange;return this._forceNextChange=!1,t}GetOptionalCallbacks(t,e){const a=this._propertyTrack.GetTrack(),i=a.GetObjectClass().GetPlugin();if(C3.Plugins.Sprite&&i instanceof C3.Plugins.Sprite){if("initial-frame"===this._propertyTrack.GetPropertyName()||"initial-animation"===this._propertyTrack.GetPropertyName())switch(this._propertyTrack.GetResultMode()){case"relative":return this._optionalCallbacksRelative?(this._optionalCallbacksRelative.startFrom=t.GetAddOn("initial-animation")?.GetStartFrom()??0,this._optionalCallbacksRelative.keyframeReached=this._WasKeyframeReached(a,t,e),this._optionalCallbacksRelative.isChunkDiscreteLike=this._IsTimelineChunkDiscreteLike(t,e),this._optionalCallbacksRelative):(this._optionalCallbacksRelative={onFrameChange:(t,e,i,r,s)=>{if(e!==r){const i=r/e,s=a.GetPropertyTrack("offsetWidth"),n=a.GetPropertyTrack("offsetScaleX");if(s||n){const o=s?.GetSourceAdapter()?.GetPropertyAdapter(),l=n?.GetSourceAdapter()?.GetPropertyAdapter();if(t.HasParent()&&t.GetTransformWithParentWidth())l&&l.SetOriginalSizeProperty(r),t.SetWidth(this.GetNewWidth(r,e,t,a,o,l));else{const e=r*((t._GetSceneGraphInfo()?._GetStartWidth()??this.GetInstanceOriginalWidth(t,a))/this.GetInstanceOriginalWidth(t,a));l&&l.SetOriginalSizeProperty(r);const s=o?.GetChangeAccumulatorProperty()??0,n=l?.GetChangeAccumulatorProperty()??0;t.SetWidth(e+(s+n*i))}}else t.SetWidth(t.GetWidth()*i)}if(i!==s){const e=s/i,r=a.GetPropertyTrack("offsetHeight"),n=a.GetPropertyTrack("offsetScaleY");if(r||n){const o=r?.GetSourceAdapter()?.GetPropertyAdapter(),l=n?.GetSourceAdapter()?.GetPropertyAdapter();if(t.HasParent()&&t.GetTransformWithParentHeight())l&&l.SetOriginalSizeProperty(s),t.SetHeight(this.GetNewHeight(s,i,t,a,o,l));else{const i=s*((t._GetSceneGraphInfo()?._GetStartHeight()??this.GetInstanceOriginalHeight(t,a))/this.GetInstanceOriginalHeight(t,a));l&&l.SetOriginalSizeProperty(s);const r=o?.GetChangeAccumulatorProperty()??0,n=l?.GetChangeAccumulatorProperty()??0;t.SetHeight(i+(r+n*e))}}else t.SetHeight(t.GetHeight()*e)}},startFrom:t.GetAddOn("initial-animation")?.GetStartFrom()??0,keyframeReached:this._WasKeyframeReached(a,t,e),isChunkDiscreteLike:this._IsTimelineChunkDiscreteLike(t,e)},this._optionalCallbacksRelative);case"absolute":return this._optionalCallbacksAbsolute?(this._optionalCallbacksAbsolute.startFrom=t.GetAddOn("initial-animation")?.GetStartFrom()??0,this._optionalCallbacksAbsolute.keyframeReached=this._WasKeyframeReached(a,t,e),this._optionalCallbacksAbsolute.isChunkDiscreteLike=this._IsTimelineChunkDiscreteLike(t,e),this._optionalCallbacksAbsolute):(this._optionalCallbacksAbsolute={startFrom:t.GetAddOn("initial-animation")?.GetStartFrom()??0,keyframeReached:this._WasKeyframeReached(a,t,e),isChunkDiscreteLike:this._IsTimelineChunkDiscreteLike(t,e)},this._optionalCallbacksAbsolute)}}else if(C3.Plugins.Model3D&&i instanceof C3.Plugins.Model3D)switch(this._propertyTrack.GetResultMode()){case"relative":return this._optionalCallbacksRelative?(this._optionalCallbacksRelative.relative=!0,this._optionalCallbacksRelative.absolute=!1,this._optionalCallbacksRelative):(this._optionalCallbacksRelative={relative:!0,absolute:!1},this._optionalCallbacksRelative);case"absolute":return this._optionalCallbacksAbsolute?(this._optionalCallbacksAbsolute.relative=!1,this._optionalCallbacksAbsolute.absolute=!0,this._optionalCallbacksAbsolute):(this._optionalCallbacksAbsolute={relative:!1,absolute:!0},this._optionalCallbacksAbsolute)}}GetLastPropertyKeyframeValue(t,e,a,i=0){const r=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(!r)return i;const s=r.GetPropertyTrack(a);if(!s)return i;const n=s.GetPropertyTrackDataItem().GetPropertyKeyframeData();if(!n)return i;const o=n.GetLastPropertyKeyframeDataItem();return o?o.GetValue():i}GetInstanceOriginalWidth(t,e){const a=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(a)return a.GetOriginalSize()[0];const i=t.GetInstance();return i.IsOriginalSizeKnown()?i.GetOriginalSize()[0]:t._GetSceneGraphInfo()._GetStartWidth()}GetInstanceOriginalHeight(t,e){const a=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(a)return a.GetOriginalSize()[1];const i=t.GetInstance();return i.IsOriginalSizeKnown()?i.GetOriginalSize()[1]:t._GetSceneGraphInfo()._GetStartHeight()}GetNewWidth(t,e,a,i,r,s){const n=a._GetSceneGraphInfo()._GetStartWidth(),o=n/a.GetParent()._GetSceneGraphInfo()._GetStartWidth();let l=1;const c=s?.GetAbsoluteScaleXOffsetProperty()??0;if(0!==c){const t=n/this.GetInstanceOriginalWidth(a,i);l=(t+c)/(0===t?Number.EPSILON:t)}const h=n*(t/e);let G=r?.GetAbsoluteWidthOffsetProperty()??0;G+=h-n;const p=(n+G)/(0===n?Number.EPSILON:n);return a.GetParent().GetWidth()*o*l*p}GetNewHeight(t,e,a,i,r,s){const n=a._GetSceneGraphInfo()._GetStartHeight(),o=n/a.GetParent()._GetSceneGraphInfo()._GetStartHeight();let l=1;const c=s?.GetAbsoluteScaleYOffsetProperty()??0;if(0!==c){const t=n/this.GetInstanceOriginalHeight(a,i);l=(t+c)/(0===t?Number.EPSILON:t)}const h=n*(t/e);let G=r?.GetAbsoluteHeightOffsetProperty()??0;G+=h-n;const p=(n+G)/(0===n?Number.EPSILON:n);return a.GetParent().GetHeight()*o*l*p}}C3.PropertyTrackState.PluginSourceAdapter=PluginSourceAdapter; } // timelines/state/propertySourceAdapters/valueSourceAdapter.js { const C3=self.C3;class ValueSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(t){super(t),this._value=0,this._init=!1}MayNeedBeforeAndAfterInterpolate(){return!1}SetInitialState(){const t=this._propertyTrack.GetPropertyTrackData();let e=this._propertyTrack.GetPropertyTrackDataItem();e=t.GetFirstPropertyKeyframeDataItem(e),this._value=e.GetValueWithResultMode()}SetResumeState(){}GetValue(){return this._init||this._propertyTrack.Interpolate(0),this._value}Interpolate(t,e,r,a,i,o,u){this._value=C3.PropertyTrackState.NumericTypeAdapter.Interpolate(t,e,r,this._propertyTrack),this._init=!0}SaveState(){}ClearSaveState(){}GetCurrentState(){return this._value}CompareInitialStateWithCurrent(){return!1}CompareSaveStateWithCurrent(){return!1}_SaveToJson(){return{"value":this._value,"init":this._init}}_LoadFromJson(t){t&&(this._value=t["value"],this._init=!t.hasOwnProperty("init")||t["init"])}}C3.PropertyTrackState.ValueSourceAdapter=ValueSourceAdapter; } // timelines/state/propertySourceAdapters/audioSourceAdapter.js { const C3=self.C3,PROJECT_FILE=0,PROJECT_FILE_NAME=0,PROJECT_FILE_TYPE=1,START_OFFSET=1,AUDIO_DURATION=2,AUDIO_TAG=3;class AudioSourceAdapter extends C3.PropertyTrackState.PropertySourceAdapter{constructor(t){super(t),this._audioPlaybackStarted=!1,this._sdkInstance=null,this._actions=null,this._expressions=null,this._timeline=this._propertyTrack.GetTimeline(),this._track=this._propertyTrack.GetTrack(),this._sourceAdapterArgs=this._propertyTrack.GetSourceAdapterArgs(),this._fileArgs=this._sourceAdapterArgs[0],this._startOffsetTime=this._sourceAdapterArgs[1],this._sourceAdapterArgs[3]?this._audioTag=this._sourceAdapterArgs[3]:this._audioTag=Math.random().toString(36).slice(2),this._pauseTime=NaN,this._pauseVolume=NaN,this._volume=NaN,this._audioSource=null,this._Initialize()}Release(){super.Release(),this._sdkInstance=null,this._actions=null,this._expressions=null,this._timeline=null,this._track=null,this._sourceAdapterArgs=null,this._fileArgs=null,this._audioSource=null}_Initialize(){if(!self.C3.Plugins.Audio)return;const t=this._propertyTrack.GetRuntime().GetSingleGlobalObjectClassByCtor(self.C3.Plugins.Audio);t&&(this._sdkInstance=t.GetSingleGlobalInstance().GetSdkInstance()),this._actions=self.C3.Plugins.Audio.Acts,this._expressions=self.C3.Plugins.Audio.Exps}_MaybeSetAudioSource(){if(this._audioSource)return;const t=this._propertyTrack.GetTrack().GetPropertyTrack("audioSource");t&&(this._audioSource=t.GetSourceAdapter())}_GetPauseVolume(){const t=this._propertyTrack.GetTrack().GetPropertyTrack("volume");return t?t.GetSourceAdapter()._pauseVolume:this._pauseVolume}TimelineRemoved(){super.TimelineRemoved(),this._audioPlaybackStarted=!1,this._sdkInstance&&(this._expressions&&(this._pauseTime=this._expressions.PlaybackTime.call(this._sdkInstance,this._audioTag),this._pauseVolume=this._expressions.Volume.call(this._sdkInstance,this._audioTag)),this._actions&&this._actions.Stop.call(this._sdkInstance,this._audioTag))}GetAudioTag(){return this._audioTag}GetVolume(){return this._volume}SetVolume(t){this._volume=t}SetInitialState(){super.SetInitialState(),this._pauseTime=NaN,this._audioPlaybackStarted=!1}SetResumeState(){super.SetResumeState();const t=this._propertyTrack.GetTimeline().GetTime();switch(this._pauseTime=t-this._startOffsetTime,this._propertyTrack.GetPropertyName()){case"audioSource":break;case"volume":this._pauseVolume=this._propertyTrack.GetInterpolatedValue(t)}this._audioPlaybackStarted=!1}Interpolate(t,e,s,i,a,o,r){if(this._sdkInstance)switch(this._propertyTrack.GetPropertyName()){case"audioSource":{if(!this._timeline.IsForwardPlayBack())return;if(i)return void(this._actions&&this._actions.Stop.call(this._sdkInstance,this._audioTag));if(t{const t=this._propertyTrack.GetPropertyTrackDataItem();return this._propertyTrack.GetPropertyTrackData().GetFirstPropertyKeyframeDataItem(t)},()=>{const t=this._propertyTrack.GetPropertyTrackDataItem();return this._propertyTrack.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(t)}).GetAbsoluteValue()}_CurrentKeyframeGetter(){const t=this._propertyTrack.GetTimeline().GetTime()-this._propertyTrack.GetTrack().GetStartOffset();return this._PickTimelinePlaybackMode(()=>{const e=this._propertyTrack.GetPropertyTrackDataItem();return this._propertyTrack.GetPropertyTrackData().GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,e)},()=>{const e=this._propertyTrack.GetPropertyTrackDataItem(),r=this._propertyTrack.GetPropertyTrackData(),a=r.GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(t,e);return a||r.GetLastPropertyKeyframeDataItem(e)}).GetAbsoluteValue()}_PickTimelinePlaybackMode(t,e){return this._propertyTrack.GetTimeline().IsForwardPlayBack()?t():e()}_PickResultMode(t,e){return"relative"===this._propertyTrack.GetResultMode()?t():e()}_PickFirstAbsoluteUpdate(t,e){return this.GetFirstAbsoluteUpdate()?(this.SetFirstAbsoluteUpdate(!1),t()):e()}_GetAbsoluteInitialValue(t){}_GetIndex(){return this._sourceAdapter.GetIndex()}_GetTarget(){return this._target||(this._target=this._sourceAdapter.GetTarget()),this._target}_PickSource(t,e,r,a,s,o){switch(this._propertyTrack.GetSourceAdapterId()){case"behavior":return t();case"effect":return e();case"instance-variable":return r();case"plugin":return a();case"world-instance":return s();case"audio":return o()}}_SaveToJson(){return{"firstAbsoluteUpdate":this._firstAbsoluteUpdate,"saveState":this._saveState}}_LoadFromJson(t){t&&(this._firstAbsoluteUpdate=t["firstAbsoluteUpdate"],this._saveState=t["saveState"])}_GetPropertyKeyframeStubs(t,e=!1){const r=[];for(const a of t){const t=a.GetTrack().GetStartOffset();for(const s of a.GetPropertyKeyframeDataItems())e&&0===s.GetTime()?r.push({time:t+s.GetTime(),value:s.GetAbsoluteValue()}):e||r.push({time:t+s.GetTime(),value:s.GetAbsoluteValue()})}return r.sort((t,e)=>t.time-e.time)}_GetLastPropertyKeyframeStub(t,e,r){return this._GetPropertyKeyframeStubLowerThanPlayhead(e,r)}_GetPropertyKeyframeStubLowerThanPlayhead(t,e){for(let r=e.length-1;r>=0;r--){if(e[r].time<=t)return e[r]}return null}}; } // timelines/state/propertyInterpolationAdapters/colorInterpolationAdapter.js { const C3=self.C3,TMP_COLORS_MAP=new Map,TMP_COLOR=[0,0,0];class ColorInterpolationAdapter extends C3.PropertyTrackState.PropertyInterpolationAdapter{constructor(e){super(e)}SetResetState(){}SetInitialState(){}SetResumeState(){}GetCurrentState(){const e=this._propertyTrack.GetSourceAdapterId(),t=this._GetTarget(),r=this._GetIndex();switch(e){case"behavior":case"plugin":return this._ToColorArray(t.GetPropertyValueByIndex(r));case"effect":return this._ToColorArray(t[r]);case"world-instance":return this._ToColorArray(this._Getter())}}CompareInitialStateWithCurrent(){const e=this._FirstKeyframeGetter();return!this._CompareColors(e,this._Getter())}CompareSaveStateWithCurrent(){return!C3.IsNullOrUndefined(this._saveState)&&!this._CompareColors(this._saveState,this._Getter())}_CompareColors(e,t){return e=this._GetColorFromArray(e),t=this._GetColorFromArray(t),e.equalsIgnoringAlpha(t)}_FirstKeyframeGetter(){const e=super._FirstKeyframeGetter();return this._GetColorFromArray(e)}_CurrentKeyframeGetter(){const e=super._CurrentKeyframeGetter();return this._GetColorFromArray(e)}_GetAbsoluteInitialValue(e){}_ToColorArray(e){return C3.IsInstanceOf(e,C3.Color)?e.toArray().slice(0,3):e.slice(0,3)}_GetColorFromArray(e){return C3.IsInstanceOf(e,C3.Color)?e:new C3.Color(e[0],e[1],e[2],1)}CanChange(e){return!0}MayNeedBeforeAndAfterInterpolate(){return!0}BeforeChangeProperty(){const e=this._propertyTrack.GetTimeline(),t=this._propertyTrack.GetInstance(),r=this._propertyTrack.GetSourceAdapter(),o=e.GetSimilarPropertyTracks(t,r,this._property,this._propertyTrack);if(o&&o.length>1){TMP_COLORS_MAP.has(t)||TMP_COLORS_MAP.set(t,new Map);const e=TMP_COLORS_MAP.get(t),r=this._propertyTrack.GetSourceAdapterId();e.has(r)||e.set(r,new Map);const o=e.get(r);o.has(this._property)||o.set(this._property,{used:!1,color:new C3.Color(0,0,0,1)})}}_GetTmpColor(e,t,r){const o=TMP_COLORS_MAP.get(e).get(t).get(r);return o.used=!0,o.color}ChangeProperty(e,t,r,o,s,a,n,i){const p=this._propertyTrack.GetTimeline(),_=this._propertyTrack.GetTrack(),c=this._propertyTrack.GetInstance(),l=this._propertyTrack.GetSourceAdapter(),h=this._propertyTrack.GetSourceAdapterId(),C=this._property,y=p.GetSimilarPropertyTracks(c,l,C,this._propertyTrack);if(y&&y.length>1){const e=this._GetPropertyKeyframeStubs(y,!0),r=this._GetLastPropertyKeyframeStub(p,p.GetTime(),e);if(r){const e=_.GetStartOffset(),o=r.time-e;if(0===o)this._GetTmpColor(c,h,this._property).addRgb(t[0],t[1],t[2]);else{if(o<0)return;const e=t[0],r=t[1],s=t[2],a=this._propertyTrack.Interpolate(o,!1,!0),n=C3.Color.DiffChannel(e,a[0]),i=C3.Color.DiffChannel(r,a[1]),p=C3.Color.DiffChannel(s,a[2]);this._GetTmpColor(c,h,this._property).addRgb(n,i,p)}}}else this._Setter(t[0],t[1],t[2])}AfterChangeProperty(){const e=this._propertyTrack.GetInstance();if(!TMP_COLORS_MAP.has(e))return;const t=TMP_COLORS_MAP.get(e),r=this._propertyTrack.GetSourceAdapterId();if(!t.has(r))return;const o=t.get(r);if(!o.has(this._property))return;const s=o.get(this._property),a=s.used,n=s.color;a&&this._Setter(n.getR(),n.getG(),n.getB()),0===o.size&&t.delete(r),0===t.size&&TMP_COLORS_MAP.delete(e)}_Getter(){const e=this._propertyTrack.GetSourceAdapterId(),t=this._GetTarget(),r=this._GetIndex();switch(e){case"behavior":case"plugin":return this._GetColorFromArray(t.GetPropertyValueByIndex(r));case"effect":return t[r].clone();case"world-instance":return this.GetWorldInfo().GetUnpremultipliedColor().clone()}}_Setter(e,t,r){const o=this._propertyTrack.GetSourceAdapterId(),s=this._GetTarget(),a=this._GetIndex();switch(o){case"behavior":case"plugin":TMP_COLOR[0]=e,TMP_COLOR[1]=t,TMP_COLOR[2]=r,s.SetPropertyValueByIndex(a,TMP_COLOR);break;case"effect":s[a].setRgb(e,t,r);break;case"world-instance":this.GetWorldInfo().SetUnpremultipliedColorRGB(e,t,r)}}_SaveToJson(){}_LoadFromJson(e){}}C3.PropertyTrackState.PropertyInterpolationAdapter.ColorInterpolationAdapter=ColorInterpolationAdapter; } // timelines/state/propertyInterpolationAdapters/noInterpolationAdapter.js { const C3=self.C3,NS=C3.PropertyTrackState;class NoInterpolationAdapter extends C3.PropertyTrackState.PropertyInterpolationAdapter{constructor(e){super(e)}SetResetState(){}SetInitialState(){}SetResumeState(){}GetCurrentState(){return this._Getter()}CompareInitialStateWithCurrent(){return this._FirstKeyframeGetter()!==this.GetCurrentState()}CompareSaveStateWithCurrent(){return!C3.IsNullOrUndefined(this._saveState)&&this._saveState!==this.GetCurrentState()}MayNeedBeforeAndAfterInterpolate(){return!1}ChangeProperty(e,t,r,a,s,n,i,o){const c=this._propertyTrack,p=c.GetTrack(),h=c.GetSourceAdapterId(),l=c.GetTimeline(),u=p.GetInstance(),S=c.GetSourceAdapter(),G=this._property,d=l.GetSimilarPropertyTracks(u,S,G,c);if(d&&d.length>1){const r=this._GetPropertyKeyframeStubs(d),a=e+p.GetStartOffset(),s=this._GetLastPropertyKeyframeStub(l,a,r);s&&(t=s.value)}switch(c.GetPropertyKeyframeType()){case"numeric":if(!NS.NumericTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,h))return;this._Setter(t,r,a);break;case"angle":if(!NS.AngleTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,h))return;this._Setter(t,r,a);break;case"boolean":if(!NS.BooleanTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,h))return;this._Setter(t,r,a);break;case"color":if(!NS.ColorTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,h))return;this._Setter(t,r,a);break;case"text":{const e=this._ForceChanges();if(!NS.TextTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,h)&&!e)return;this._Setter(t,r,a);break}case"map":{const e=this._ForceChanges();if(!NS.MapTypeAdapter.WillChange(this._GetIndex(),this._GetTarget(),t,h)&&!e)return;this._Setter(t,r,a);break}}}_ForceChanges(){switch(this._propertyTrack.GetSourceAdapterId()){case"behavior":case"effect":case"instance-variable":return!1;case"plugin":return this.GetSourceAdapter().ForceChanges()}return!1}_Getter(){const e=this._propertyTrack.GetSourceAdapterId(),t=this._GetTarget(),r=this._GetIndex();switch(e){case"behavior":case"plugin":return t.GetPropertyValueByIndex(r);case"effect":return t[r];case"instance-variable":return t.GetInstanceVariableValue(r)}}_Setter(e,t,r){const a=this._propertyTrack.GetSourceAdapterId(),s=this._GetTarget(),n=this._GetIndex();switch(a){case"behavior":s.SetPropertyValueByIndex(n,e);break;case"effect":s[n]=e;break;case"instance-variable":s.SetInstanceVariableValue(n,e);break;case"plugin":s.SetPropertyValueByIndex(n,e,this.GetSourceAdapter().GetOptionalCallbacks(t,r))}}}C3.PropertyTrackState.PropertyInterpolationAdapter.NoInterpolationAdapter=NoInterpolationAdapter; } // timelines/state/propertyInterpolationAdapters/numericInterpolationAdapter.js { const C3=self.C3,NS=C3.PropertyTrackState.PropertyInterpolationAdapter,INSTANCE_FUNC_MAP=new Map,add=(t,e,a,r,i,s=!1,o=null,n=null)=>{INSTANCE_FUNC_MAP.set(t,{setter:e,absolute_setter:a,getter:r,round:i,fRound:s,init:o,reset:n})},get_original_size=(t,e)=>{const a=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(a)return a.GetOriginalSize()[0];const r=t.GetInstance();return r.IsOriginalSizeKnown()?r.GetOriginalSize()[0]:t._GetSceneGraphInfo()._GetStartWidth()},get_last_property_keyframe_value=(t,e,a,r=0)=>{const i=e.GetTimeline().GetTrackFromInstance(t.GetInstance());if(!i)return r;const s=i.GetPropertyTrack(a);if(!s)return r;const o=s.GetPropertyTrackDataItem().GetPropertyKeyframeData();if(!o)return r;const n=o.GetLastPropertyKeyframeDataItem();return n?n.GetValue():r},get_parents=t=>{const e=[];let a=t.GetParent();for(;a;)e.push(a),a=a.GetParent();return e.reverse(),e};add("offsetX",(t,e,a,r)=>{"relative"===r._propertyTrack.GetResultMode()?t.OffsetX(e,a.GetTimeline().GetTransformWithSceneGraph()):t.OffsetX(e)},(t,e)=>t.SetX(e),t=>t.GetX(),!0),add("offsetY",(t,e,a,r)=>{"relative"===r._propertyTrack.GetResultMode()?t.OffsetY(e,a.GetTimeline().GetTransformWithSceneGraph()):t.OffsetY(e)},(t,e)=>t.SetY(e),t=>t.GetY(),!0),add("offsetZElevation",(t,e)=>t.OffsetZ(e),(t,e)=>t.SetZ(e),t=>t.GetZ(),!0),add("offsetWidth",(t,e,a,r,i=!1,s=!0)=>{if(0===e)return;const o="relative"===r._propertyTrack.GetResultMode(),n=1===r._typeAdapter.GetType();if((o||n)&&t.HasParent()&&t.GetTransformWithParentWidth()){if(isNaN(r._absoluteToFactor)){const e=get_parents(t);let a;if(n){a=e[e.length-1].GetWidth()}else{a=e[e.length-1]._GetSceneGraphInfo()._GetStartWidth()}r._absoluteToFactor=0===a?Number.EPSILON:a}if(i)return;r._absoluteWidthOffset+=e;const a=e/r._absoluteToFactor;t.OffsetWidth(a,s),r._changeAccumulator+=a}else t.OffsetWidth(e),r._changeAccumulator+=e},(t,e)=>t.SetWidth(e),t=>t.GetWidth(),!0,!1,null,t=>{t._changeAccumulator=0,t._absoluteWidthOffset=0}),add("offsetHeight",(t,e,a,r,i=!1,s=!0)=>{if(0===e)return;const o="relative"===r._propertyTrack.GetResultMode(),n=1===r._typeAdapter.GetType();if((o||n)&&t.HasParent()&&t.GetTransformWithParentHeight()){if(isNaN(r._absoluteToFactor)){const e=get_parents(t);let a;if(n){a=e[e.length-1].GetHeight()}else{a=e[e.length-1]._GetSceneGraphInfo()._GetStartHeight()}r._absoluteToFactor=0===a?Number.EPSILON:a}if(i)return;r._absoluteHeightOffset+=e;const a=e/r._absoluteToFactor;t.OffsetHeight(a,s),r._changeAccumulator+=a}else t.OffsetHeight(e),r._changeAccumulator+=e},(t,e)=>t.SetHeight(e),t=>t.GetHeight(),!0,!1,null,t=>{t._changeAccumulator=0,t._absoluteHeightOffset=0}),add("offsetAngle",(t,e,a,r,i)=>{t.OffsetAngle(e)},(t,e)=>t.SetAngle(e),t=>t.GetAngle(),!1,!0),add("offsetOpacity",(t,e,a,r,i)=>{e/=r._opacityFactor?r._opacityFactor:1;const s=t.GetOpacity()+e;if(0===r._clampAccumulator)s>1?r._clampAccumulator+=s-1:s<0&&(r._clampAccumulator+=s),t.OffsetOpacity(e);else{const a=t.GetOpacity()+e;e>0&&r._clampAccumulator>0?a>1&&(r._clampAccumulator+=a-1):e>0&&r._clampAccumulator<0?(r._clampAccumulator+=e,r._clampAccumulator>0&&(t.OffsetOpacity(r._clampAccumulator),r._clampAccumulator=0)):e<0&&r._clampAccumulator>0?(r._clampAccumulator+=e,r._clampAccumulator<0&&(t.OffsetOpacity(r._clampAccumulator),r._clampAccumulator=0)):e<0&&r._clampAccumulator<0&&a<0&&(r._clampAccumulator+=a)}},(t,e)=>{t.SetOpacity(e)},t=>t.GetOpacity(),!1,!0,(t,e,a)=>{switch(t._clampAccumulator=0,t._propertyTrack.GetResultMode()){case"relative":{t._propertyTrack.GetPropertyTrackData();const e=t._propertyTrack.GetPropertyTrackDataItem().GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray();let a=t.GetWorldInfo().GetOpacity(),r=a;for(const i of e){const e=i.GetTime();r=a+t._propertyTrack.GetInterpolatedValue(e),r=C3.clamp(r,0,1)}t._totalForewardOpacityDelta=a-r,t._totalForewardOpacityDelta=Math.round(100*(t._totalForewardOpacityDelta+Number.EPSILON))/100,r=a;for(let a=e.length-1;a>=0;a--){const i=e[a].GetTime();r-=t._propertyTrack.GetInterpolatedValue(i),r=C3.clamp(r,0,1)}t._totalBackwardOpacityDelta=r,t._totalBackwardOpacityDelta=Math.round(100*(t._totalBackwardOpacityDelta+Number.EPSILON))/100;break}}const r="relative"===t._propertyTrack.GetResultMode(),i=1===t._typeAdapter.GetType();if((r||i)&&e.HasParent()&&e.GetTransformWithParentOpacity()){const r=get_parents(e);let i=r[0]._GetSceneGraphInfo().GetStartOpacity();i+=get_last_property_keyframe_value(r[0],a,"offsetOpacity");for(let t=1;t{switch(t._propertyTrack.GetResultMode()){case"relative":{t._clampAccumulator=0;const e=t.GetWorldInfo();let a=e.GetOpacity();a=Math.round(100*(a+Number.EPSILON))/100,t._propertyTrack.GetTimeline().IsForwardPlayBack()?(e.SetOpacity(a+t._totalForewardOpacityDelta),t._lastValue=0):(e.SetOpacity(a-t._totalBackwardOpacityDelta),t._lastValue=t.GetSourceAdapter().GetValueAtTime());break}}}),add("offsetOriginX",(t,e)=>t.OffsetOriginX(e),(t,e)=>t.SetOriginX(e),t=>t.GetOriginX(),!1),add("offsetOriginY",(t,e)=>t.OffsetOriginY(e),(t,e)=>t.SetOriginY(e),t=>t.GetOriginY(),!1),add("offsetScaleX",(t,e,a,r)=>{if(0===e)return;const i=t.GetWidth()<0?-1:1;if(r._absoluteScaleXOffset+=e,"relative"===r._propertyTrack.GetResultMode()&&t.HasParent()&&t.GetTransformWithParentWidth()){const s=get_last_property_keyframe_value(t,a,"offsetWidth"),o=isNaN(r._originalSize)?a.GetOriginalSize()[0]:r._originalSize,n=(o+s/(t._GetSceneGraphInfo()._GetStartWidth()/o))*i*e;isNaN(r._absoluteToFactor)&&INSTANCE_FUNC_MAP.get("offsetWidth").setter(t,1,a,r,!0);const l=n/r._absoluteToFactor;t.OffsetWidth(l,!0),r._changeAccumulator+=l}else{const s=(isNaN(r._originalSize)?a.GetOriginalSize()[0]:r._originalSize)*i*e;t.OffsetWidth(s),r._changeAccumulator+=s}},(t,e,a)=>{t.SetWidth(a.GetOriginalSize()[0]*e)},(t,e)=>{const a=t.GetWidth()<0?-1:1;if(t.GetTransformWithParentWidth()){const r=t.GetParent(),i=e.GetTimeline().GetTrackFromInstance(r.GetInstance());let s=NaN;if(i)s=r.GetWidth()/i.GetOriginalSize()[0];else{const t=r.GetInstance();s=t.IsOriginalSizeKnown()?r.GetWidth()/t.GetOriginalSize()[0]:1}return t.GetWidth()*a/(e.GetOriginalSize()[0]*s)}return t.GetWidth()*a/e.GetOriginalSize()[0]},!1,!1,null,t=>{t._changeAccumulator=0,t._originalSize=NaN,t._absoluteScaleXOffset=0}),add("offsetScaleY",(t,e,a,r)=>{if(0===e)return;const i=t.GetHeight()<0?-1:1;if(r._absoluteScaleYOffset+=e,"relative"===r._propertyTrack.GetResultMode()&&t.HasParent()&&t.GetTransformWithParentHeight()){const s=get_last_property_keyframe_value(t,a,"offsetHeight"),o=isNaN(r._originalSize)?a.GetOriginalSize()[1]:r._originalSize,n=(o+s/(t._GetSceneGraphInfo()._GetStartHeight()/o))*i*e;isNaN(r._absoluteToFactor)&&INSTANCE_FUNC_MAP.get("offsetHeight").setter(t,1,a,r,!0);const l=n/r._absoluteToFactor;t.OffsetHeight(l,!0),r._changeAccumulator+=l}else{const s=(isNaN(r._originalSize)?a.GetOriginalSize()[1]:r._originalSize)*i*e;t.OffsetHeight(s),r._changeAccumulator+=s}},(t,e,a)=>{t.SetHeight(a.GetOriginalSize()[1]*e)},(t,e)=>{const a=t.GetHeight()<0?-1:1;if(t.GetTransformWithParentHeight()){const r=t.GetParent(),i=e.GetTimeline().GetTrackFromInstance(r.GetInstance());let s=NaN;if(i)s=r.GetHeight()/i.GetOriginalSize()[1];else{const t=r.GetInstance();s=t.IsOriginalSizeKnown()?r.GetHeight()/t.GetOriginalSize()[1]:1}return t.GetHeight()*a/(e.GetOriginalSize()[1]*s)}return t.GetHeight()*a/e.GetOriginalSize()[1]},!1,!1,null,t=>{t._changeAccumulator=0,t._originalSize=NaN,t._absoluteScaleYOffset=0});class NumericInterpolationAdapter extends C3.PropertyTrackState.PropertyInterpolationAdapter{constructor(t){super(t),this._lastValue=0,this._clampAccumulator=0,this._totalForewardOpacityDelta=0,this._totalBackwardOpacityDelta=0,this._opacityFactor=NaN,this._absoluteToFactor=NaN,this._changeAccumulator=0,this._originalSize=NaN,this._absoluteWidthOffset=0,this._absoluteScaleXOffset=0,this._absoluteHeightOffset=0,this._absoluteScaleYOffset=0,this._angleReflectMirrorOrFlip=void 0,this._angleReflectMirrorAndFlip=void 0,this._instance_getter=null,this._instance_setter=null,this._instance_absolute_setter=null,this._reset_action=null,this._init_action=null,this._source_adapter_getter=null,this._source_adapter_setter=null,this._source_adapter_absolute_setter=null,this._round=!1,this._fRound=!1,C3.IsInstanceOf(this._propertyTrack.GetTimeline(),C3.TweenState)?this._typeAdapter=new C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTween(this):this._typeAdapter=new C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTimeline(this);const e=this._propertyTrack.GetPropertyName();switch(this._propertyTrack.GetSourceAdapterId()){case"world-instance":{const t=INSTANCE_FUNC_MAP.get(e);this._instance_getter=t.getter,this._instance_setter=t.setter,this._instance_absolute_setter=t.absolute_setter,this._round=t.round,this._fRound=t.fRound,this._init_action=t.init,this._reset_action=t.reset;break}case"audio":this._source_adapter_getter=t.Getter,this._source_adapter_setter=t.Setter,this._source_adapter_absolute_setter=t.AbsoluteSetter,this._round=!!t.DoesRounding(),this._fRound=!1}}Release(){this._typeAdapter=null,this._instance_getter=null,this._instance_setter=null,this._instance_absolute_setter=null,this._reset_action=null,this._init_action=null,this._source_adapter_getter=null,this._source_adapter_setter=null,this._source_adapter_absolute_setter=null,super.Release()}MayNeedBeforeAndAfterInterpolate(){return this._typeAdapter.MayNeedBeforeAndAfterInterpolate()}GetLastValue(){return this._lastValue}SetLastValue(t){this._lastValue=t}SetResetState(){this._reset_action&&this._reset_action(this)}SetInitialState(){const t=this._typeAdapter.SetInitialState();if("number"==typeof t&&(this._lastValue=t),this._init_action){const t=this.GetWorldInfo(),e=this._propertyTrack.GetTrack();this._init_action(this,t,e)}}SetResumeState(){const t=this._typeAdapter.SetResumeState();"number"==typeof t&&(this._lastValue=t)}GetCurrentState(){return this._Getter()}CompareInitialStateWithCurrent(){return this._FirstKeyframeGetter()!==this.GetCurrentState()}CompareSaveStateWithCurrent(){return!C3.IsNullOrUndefined(this._saveState)&&this._saveState!==this.GetCurrentState()}BeforeChangeProperty(t,e){this._typeAdapter.BeforeChangeProperty(t,e)}ChangeProperty(t,e,a,r,i,s,o,n){return this._typeAdapter.ChangeProperty(t,e,a,r,i,s,o,n)}AfterChangeProperty(t,e){this._typeAdapter.AfterChangeProperty(t,e)}_Getter(){const t=this._GetTarget(),e=this._GetIndex(),a=this.GetWorldInfo(),r=this._propertyTrack.GetTrack();switch(this._propertyTrack.GetSourceAdapterId()){case"behavior":case"plugin":return t.GetPropertyValueByIndex(e);case"effect":return t[e];case"instance-variable":return t.GetInstanceVariableValue(e);case"world-instance":return this._instance_getter(a,r);case"audio":return this._source_adapter_getter.call(this.GetSourceAdapter(),a,r)}}_Setter(t,e,a,r=!0){const i=this._GetTarget(),s=this._GetIndex(),o=this.GetWorldInfo(),n=this._propertyTrack.GetTrack();switch(this._propertyTrack.GetSourceAdapterId()){case"behavior":i.OffsetPropertyValueByIndex(s,t);break;case"effect":i[s]+=t;break;case"instance-variable":i.SetInstanceVariableOffset(s,t);break;case"plugin":i.OffsetPropertyValueByIndex(s,t,this.GetSourceAdapter().GetOptionalCallbacks(e,a));break;case"world-instance":this._instance_setter(o,t,n,this,!1,r);break;case"audio":this._source_adapter_setter.call(this.GetSourceAdapter(),o,t,n,this)}}_SetterAbsolute(t,e,a,r,i){let s=this._propertyTrack.GetInterpolationMode();if(s="default"===s?"continuous":s,"discrete"===s&&!e)return;if("discrete"===s&&a){const t=this._propertyTrack.GetTimeline().GetTime();if(!this._propertyTrack.GetPropertyKeyFrameDataItemAtTime(t))return}const o=this._GetTarget(),n=this._GetIndex(),l=this.GetWorldInfo(),c=this._propertyTrack.GetTrack();switch(this._propertyTrack.GetSourceAdapterId()){case"behavior":o.SetPropertyValueByIndex(n,t);break;case"effect":o[n]=t;break;case"instance-variable":o.SetInstanceVariableValue(n,t);break;case"plugin":o.SetPropertyValueByIndex(n,t,this.GetSourceAdapter().GetOptionalCallbacks(r,i));break;case"world-instance":this._instance_absolute_setter(l,t,c);break;case"audio":this._source_adapter_absolute_setter.call(this.GetSourceAdapter(),l,t,c)}}_MaybeEnsureValue(t,e,a,r,i,s,o,n){this._typeAdapter._MaybeEnsureValue(t,e,a,r,i,s,o,n)}_AddDelta(t,e,a,r,i){if("angle"===this._propertyTrack.GetPropertyType())t=C3.toDegrees(t);const s=(t.toString().split(".")[1]||"").length,o=this._Getter();let n;if(0===s)if(this._round)n=Math.round(o);else if(this._fRound)if("angle"===this._propertyTrack.GetPropertyType())n=C3.toRadians(Math.round(C3.toDegrees(o)));else n=Number(C3.toFixed(o,2));else n=o;else n=this._round?Number(C3.toFixed(o,s)):(this._fRound,o);switch(this._Setter(n-o,e,a,!1),this._propertyTrack.GetPropertyName()){case"offsetWidth":case"offsetScaleX":{const t=this.GetWorldInfo(),e=t.GetWidth(),a=Number(C3.toFixed(e,2));t.OffsetWidth(a-e);break}case"offsetHeight":case"offsetScaleY":{const t=this.GetWorldInfo(),e=t.GetHeight(),a=Number(C3.toFixed(e,2));t.OffsetHeight(a-e);break}}}_SaveToJson(){return Object.assign(super._SaveToJson(),{"v":this._lastValue,"a":this._clampAccumulator,"fod":this._totalForewardOpacityDelta,"bod":this._totalBackwardOpacityDelta,"of":this._opacityFactor,"sf":this._absoluteToFactor,"armorf":this._angleReflectMirrorOrFlip,"armandf":this._angleReflectMirrorAndFlip,"ca":this._changeAccumulator,"os":this._originalSize,"awo":this._absoluteWidthOffset,"aho":this._absoluteHeightOffset,"asxo":this._absoluteScaleXOffset,"asyo":this._absoluteScaleYOffset})}_LoadFromJson(t){t&&(super._LoadFromJson(t),this._lastValue=t["v"],this._clampAccumulator=t["a"],this._totalForewardOpacityDelta=C3.IsFiniteNumber(t["fod"])?t["fod"]:0,this._totalBackwardOpacityDelta=C3.IsFiniteNumber(t["bod"])?t["bod"]:0,this._opacityFactor=C3.IsFiniteNumber(t["of"])?t["of"]:NaN,this._absoluteToFactor=C3.IsFiniteNumber(t["sf"])?t["sf"]:NaN,this._angleReflectMirrorOrFlip=C3.IsFiniteNumber(t["armorf"])?t["armorf"]:void 0,this._angleReflectMirrorAndFlip=C3.IsFiniteNumber(t["armandf"])?t["armandf"]:void 0,this._changeAccumulator=C3.IsFiniteNumber(t["ca"])?t["ca"]:0,this._originalSize=C3.IsFiniteNumber(t["os"])?t["os"]:NaN,this._absoluteWidthOffset=C3.IsFiniteNumber(t["awo"])?t["awo"]:0,this._absoluteHeightOffset=C3.IsFiniteNumber(t["aho"])?t["aho"]:0,this._absoluteScaleXOffset=C3.IsFiniteNumber(t["asxo"])?t["asxo"]:0,this._absoluteScaleYOffset=C3.IsFiniteNumber(t["asyo"])?t["asyo"]:0)}SetOriginalSizeProperty(t){this._originalSize=t}GetChangeAccumulatorProperty(){return this._changeAccumulator}GetAbsoluteWidthOffsetProperty(){return this._absoluteWidthOffset}GetAbsoluteHeightOffsetProperty(){return this._absoluteHeightOffset}GetAbsoluteScaleXOffsetProperty(){return this._absoluteScaleXOffset}GetAbsoluteScaleYOffsetProperty(){return this._absoluteScaleYOffset}}C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapter=NumericInterpolationAdapter; } // timelines/state/propertyInterpolationAdapters/numericInterpolationAdapterForTimeline.js { const C3=self.C3;class AbsoluteValueObject{constructor(e){this._used=!1,this._value=0,this._propertyKeyframeReached=!1,this._endState=!1,this._propertyTracks=e;for(let e=0,t=this._propertyTracks.length;ee._PickTimelinePlaybackMode(()=>0,()=>e.GetSourceAdapter().GetValueAtTime()),()=>{})}SetResumeState(){}MayNeedBeforeAndAfterInterpolate(){this._numericInterpolationAdapter;switch(this._numericInterpolationAdapter.GetPropertyTrack().GetResultMode()){case"relative":return!1;case"absolute":return!0}}BeforeChangeProperty(e,t){this._numericInterpolationAdapter;const r=this._numericInterpolationAdapter.GetPropertyTrack(),a=r.GetPropertyName();switch(r.GetResultMode()){case"relative":break;case"absolute":if(r.HasAbsoluteValueObject()){r.GetAbsoluteValueObject().Reset()}else{const e=r.GetTimeline(),t=r.GetInstance(),s=r.GetSourceAdapter(),o=e.GetSimilarPropertyTracks(t,s,a,r);o&&o.length>1&&new AbsoluteValueObject(o)}}}ChangeProperty(e,t,r,a,s,o,i,n){const l=this._numericInterpolationAdapter,u=this._numericInterpolationAdapter.GetPropertyTrack();switch(u.GetResultMode()){case"relative":{const i=l.GetLastValue();l._Setter(t-i,r,a),o&&this._MaybeEnsureValue(e,r,a,s,i,t),l.SetLastValue(t);break}case"absolute":{const e=u.GetTimeline(),s=u.GetTrack();u.GetInstance(),u.GetSourceAdapter();if(u.HasAbsoluteValueObject()){const r=u.GetAbsoluteValueObject(),a=r.GetPropertyTracks(),o=l._GetPropertyKeyframeStubs(a,!0),c=l._GetLastPropertyKeyframeStub(e,e.GetTime(),o);if(c){const e=s.GetStartOffset(),a=c.time-e;if(0===a)r.SetEndState(i),r.SetPropertyKeyframeReached(n),r.SetUsed(),r.SetValue(r.GetValue()+t);else{if(a<0)return;const e=u.GetInterpolatedValue(a);r.SetEndState(i),r.SetPropertyKeyframeReached(n),r.SetUsed(),r.SetValue(r.GetValue()+(t-e))}}}else l._SetterAbsolute(t,n,i,r,a);break}}}AfterChangeProperty(e,t){const r=this._numericInterpolationAdapter,a=this._numericInterpolationAdapter.GetPropertyTrack();switch(a.GetResultMode()){case"relative":break;case"absolute":if(a.HasAbsoluteValueObject()){const s=a.GetAbsoluteValueObject();s.GetUsed()&&r._SetterAbsolute(s.GetValue(),s.GetPropertyKeyframeReached(),s.GetEndState(),e,t)}}}_MaybeEnsureValue(e,t,r,a,s,o){const i=this._numericInterpolationAdapter;a||(t&&e===t.GetTime()?i._AddDelta(t.GetValueWithResultMode(),t,r):r&&e===r.GetTime()?i._AddDelta(r.GetValueWithResultMode(),t,r):o-s===0&&i._AddDelta(t.GetValueWithResultMode(),t,r))}}C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTimeline=NumericInterpolationAdapterForTimeline; } // timelines/state/propertyInterpolationAdapters/numericInterpolationAdapterForTween.js { const C3=self.C3;class NumericInterpolationAdapterForTween{constructor(e){this._numericInterpolationAdapter=e}Release(){this._numericInterpolationAdapter=null}GetType(){return 1}SetInitialState(){const e=this._numericInterpolationAdapter;return e.SetFirstAbsoluteUpdate(!0),this._GetAbsoluteInitialValue(e._FirstKeyframeGetter())}SetResumeState(){const e=this._numericInterpolationAdapter;if(e._FirstKeyframeGetter()!==e._CurrentKeyframeGetter())return e.SetFirstAbsoluteUpdate(!0),this._GetAbsoluteInitialValue(e._CurrentKeyframeGetter())}MayNeedBeforeAndAfterInterpolate(){return!1}BeforeChangeProperty(){}ChangeProperty(e,t,r,a,n,i,o,l){const s=this._numericInterpolationAdapter,u=s.GetLastValue();switch(s.GetPropertyTrack().GetResultMode()){case"relative":s._Setter(t-u,r,a),i&&this._MaybeEnsureValue(e,r,a,n,u,t,!1,o);break;case"absolute":s.GetFirstAbsoluteUpdate()?(s.SetFirstAbsoluteUpdate(!1),s._Setter(u,r,a)):0===e&&0===s.GetPropertyTrack().GetTimeline().GetTotalTime()?s._SetterAbsolute(t,!0,!1,r,a):(s._Setter(t-u,r,a),i&&this._MaybeEnsureValue(e,r,a,n,u,t,this._ForceEndValue(),o))}s.SetLastValue(t)}AfterChangeProperty(){}_GetAbsoluteInitialValue(e){return e-this._numericInterpolationAdapter.GetCurrentState()}_ForceEndValue(){const e=this._numericInterpolationAdapter,t=e.GetWorldInfo().GetInstance(),r=e.GetPropertyTrack().GetRuntime().GetTimelineManager();let a=0;for(const e of r.GetPlayingTimelines())0===e.GetType()?e.HasTrackInstance(t)&&a++:1===e.GetType()&&e.GetInstance()===t&&a++;return a<=1}_MaybeEnsureValue(e,t,r,a,n,i,o,l){const s=this._numericInterpolationAdapter;a?t&&e===t.GetTime()?s._AddDelta(t.GetValueWithResultMode(),t,r,o,l):r&&e===r.GetTime()?s._AddDelta(r.GetValueWithResultMode(),t,r,o,l):r||s._AddDelta(t.GetValueWithResultMode(),t,r,o,l):t&&e===t.GetTime()?s._AddDelta(t.GetValueWithResultMode(),t,r,o,l):r&&e===r.GetTime()?s._AddDelta(r.GetValueWithResultMode(),t,r,o,l):i-n===0&&s._AddDelta(t.GetValueWithResultMode(),t,r,o,l)}}C3.PropertyTrackState.PropertyInterpolationAdapter.NumericInterpolationAdapterForTween=NumericInterpolationAdapterForTween; } // timelines/state/propertyTypeAdapters/numericTypeAdapter.js { const C3=self.C3,Ease=self.Ease;C3.PropertyTrackState.NumericTypeAdapter=class{constructor(){}static WillChange(e,t,a,r){let n;switch(r){case"behavior":case"plugin":n=t.GetPropertyValueByIndex(e);break;case"effect":n=t[e];break;case"instance-variable":n=t.GetInstanceVariableValue(e)}return n!==a}static Interpolate(e,t,a,r){if(!a){const e=r.GetPropertyTrackDataItem();return r.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(e).GetValueWithResultMode()}let n=r.GetInterpolationMode();if("default"===n&&(n="continuous"),"combo"===r.GetPropertyType()&&(n="discrete"),"discrete"===n)return C3.PropertyTrackState.GetPropertyKeyframeValueWithPlaybackDirection(t,a,r);if("continuous"===n||"step"===n){const s=r.GetTimeline().GetStep();if("step"===n&&0!==s){const t=1/s;e=Math.floor(e*t)/t}const c=t.GetValueWithResultMode(),i=a.GetValueWithResultMode(),o=t.GetAddOn("cubic-bezier"),l=a.GetAddOn("cubic-bezier"),u=o&&o.GetStartEnable()&&l&&l.GetEndEnable();if(!u&&c===i)return c;const G=t.GetTime(),p=a.GetTime();"step"===n&&0!==s&&(e=C3.clamp(e,G,p));const y=C3.normalize(e,G,p),b=t.GetEase();let d;if(u){const e=p-G;d=Ease.GetRuntimeEase(b)(e*y,0,1,e),d=Ease.GetRuntimeEase("cubicbezier")(d,c,c+o.GetStartAnchor(),i+l.GetEndAnchor(),i)}else d=Ease.GetRuntimeEase(b)((p-G)*y,c,i-c,p-G);return"integer"===r.GetPropertyType()?Math.floor(d):d}}}; } // timelines/state/propertyTypeAdapters/angleTypeAdapter.js { const C3=self.C3;C3.PropertyTrackState.AngleTypeAdapter=class{constructor(){}static WillChange(e,t,a,r){let s;switch(r){case"behavior":case"plugin":s=t.GetPropertyValueByIndex(e);break;case"effect":s=t[e];break;case"instance-variable":s=t.GetInstanceVariableValue(e)}return s!==a}static Interpolate(e,t,a,r){if(!a){const e=r.GetPropertyTrackDataItem();return r.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(e).GetValueWithResultMode()}let s=r.GetInterpolationMode();if("default"===s&&(s="continuous"),"combo"===r.GetPropertyType()&&(s="discrete"),"discrete"===s)return C3.PropertyTrackState.GetPropertyKeyframeValueWithPlaybackDirection(t,a,r);if("continuous"===s||"step"===s){const n=r.GetTimeline().GetStep();if("step"===s&&0!==n){const t=1/n;e=Math.floor(e*t)/t}const c=t.GetTime(),o=a.GetTime(),i=t.GetValueWithResultMode(),l=a.GetValueWithResultMode();"step"===s&&0!==n&&(e=C3.clamp(e,c,o));const u=t.GetAddOn("angle");if(!u){if(i===l)return i;const a=C3.normalize(e,c,o),r=self.Ease.GetRuntimeEase(t.GetEase());return C3.angleLerp(i,l,r(a,0,1,1))}{const a=u.GetRevolutions();if(i===l&&0===a)return i;const r=C3.normalize(e,c,o),s=self.Ease.GetRuntimeEase(t.GetEase())(r,0,1,1);switch(u.GetDirection()){case"closest":return C3.angleLerp(i,l,s,a);case"clockwise":return C3.angleLerpClockwise(i,l,s,a);case"anti-clockwise":return C3.angleLerpAntiClockwise(i,l,s,a)}}}}}; } // timelines/state/propertyTypeAdapters/booleanTypeAdapter.js { const C3=self.C3;C3.PropertyTrackState.BooleanTypeAdapter=class{constructor(){}static WillChange(e,t,a,r){let c;switch(r){case"behavior":case"plugin":c=t.GetPropertyValueByIndex(e);break;case"effect":c=t[e];break;case"instance-variable":c=t.GetInstanceVariableValue(e)}return!!c!=!!a}static Interpolate(e,t,a,r){if(!a){const e=r.GetPropertyTrackDataItem();return r.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(e).GetValueWithResultMode()?1:0}return C3.PropertyTrackState.GetPropertyKeyframeValueWithPlaybackDirection(t,a,r)?1:0}}; } // timelines/state/propertyTypeAdapters/colorTypeAdapter.js { const C3=self.C3,TEMP_COLOR_ARRAY=[0,0,0],TEMP_COLOR_ARRAY_2=[0,0,0],TEMP_COLOR_ARRAY_3=[0,0,0];C3.PropertyTrackState.ColorTypeAdapter=class{constructor(){}static WillChange(R,e,_,t){let A;switch(t){case"behavior":case"plugin":A=e.GetPropertyValueByIndex(R);break;case"effect":A=e[R];break;case"instance-variable":A=e.GetInstanceVariableValue(R)}return Array.isArray(_)?(TEMP_COLOR_ARRAY[0]=_[0],TEMP_COLOR_ARRAY[1]=_[1],TEMP_COLOR_ARRAY[2]=_[2]):(TEMP_COLOR_ARRAY_3.parseCommaSeparatedRgb(_),TEMP_COLOR_ARRAY[0]=Math.floor(255*TEMP_COLOR_ARRAY_3.getR()),TEMP_COLOR_ARRAY[1]=Math.floor(255*TEMP_COLOR_ARRAY_3.getG()),TEMP_COLOR_ARRAY[2]=Math.floor(255*TEMP_COLOR_ARRAY_3.getB())),Array.isArray(A)?(TEMP_COLOR_ARRAY_2[0]=A[0],TEMP_COLOR_ARRAY_2[1]=A[1],TEMP_COLOR_ARRAY_2[2]=A[2]):(TEMP_COLOR_ARRAY_3.parseCommaSeparatedRgb(A),TEMP_COLOR_ARRAY_2[0]=Math.floor(255*TEMP_COLOR_ARRAY_3.getR()),TEMP_COLOR_ARRAY_2[1]=Math.floor(255*TEMP_COLOR_ARRAY_3.getG()),TEMP_COLOR_ARRAY_2[2]=Math.floor(255*TEMP_COLOR_ARRAY_3.getB())),TEMP_COLOR_ARRAY[0]!==TEMP_COLOR_ARRAY_2[0]||(TEMP_COLOR_ARRAY[1]!==TEMP_COLOR_ARRAY_2[1]||TEMP_COLOR_ARRAY[2]!==TEMP_COLOR_ARRAY_2[2])}static Interpolate(R,e,_,t){if(!_){const R=t.GetPropertyTrackDataItem(),e=t.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(R).GetValueWithResultMode();return TEMP_COLOR_ARRAY[0]=e[0],TEMP_COLOR_ARRAY[1]=e[1],TEMP_COLOR_ARRAY[2]=e[2],TEMP_COLOR_ARRAY}let A=t.GetInterpolationMode();if("default"===A&&(A="continuous"),"discrete"===A){const R=C3.PropertyTrackState.GetPropertyKeyframeValueWithPlaybackDirection(e,_,t);return TEMP_COLOR_ARRAY[0]=R[0],TEMP_COLOR_ARRAY[1]=R[1],TEMP_COLOR_ARRAY[2]=R[2],TEMP_COLOR_ARRAY}if("continuous"===A||"step"===A){const O=t.GetTimeline().GetStep();if("step"===A&&0!==O){const e=1/O;R=Math.floor(R*e)/e}const a=e.GetTime(),r=_.GetTime(),M=e.GetValueWithResultMode(),C=_.GetValueWithResultMode();"step"===A&&0!==O&&(R=C3.clamp(R,a,r));const P=C3.normalize(R,a,r),T=e.GetEase(),o=M[0],E=M[1],L=M[2],Y=C[0],s=C[1],l=C[2],i=self.Ease.GetRuntimeEase(T),c=r-a,n=c*P;return TEMP_COLOR_ARRAY[0]=o===Y?o:i(n,o,Y-o,c),TEMP_COLOR_ARRAY[1]=E===s?E:i(n,E,s-E,c),TEMP_COLOR_ARRAY[2]=L===l?L:i(n,L,l-L,c),TEMP_COLOR_ARRAY}}}; } // timelines/state/propertyTypeAdapters/textTypeAdapter.js { const C3=self.C3;C3.PropertyTrackState.TextTypeAdapter=class{constructor(){}static WillChange(e,t,a,r){let c;switch(r){case"behavior":case"plugin":c=t.GetPropertyValueByIndex(e);break;case"effect":c=t[e];break;case"instance-variable":c=t.GetInstanceVariableValue(e)}return c!==a}static Interpolate(e,t,a,r){if(!a){const e=r.GetPropertyTrackDataItem();return r.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(e).GetValueWithResultMode()}return C3.PropertyTrackState.GetPropertyKeyframeValueWithPlaybackDirection(t,a,r)}}; } // timelines/state/propertyTypeAdapters/mapTypeAdapter.js { const C3=self.C3;C3.PropertyTrackState.MapTypeAdapter=class{constructor(){}static WillChange(e,t,r,a){let s;switch(a){case"behavior":case"plugin":s=t.GetPropertyValueByIndex(e);break;case"effect":s=t[e];break;case"instance-variable":s=t.GetInstanceVariableValue(e)}return this.#e(s,r)}static Interpolate(e,t,r,a){if(!r){const e=a.GetPropertyTrackDataItem();return a.GetPropertyTrackData().GetLastPropertyKeyframeDataItem(e).GetValueWithResultMode()}return C3.PropertyTrackState.GetPropertyKeyframeValueWithPlaybackDirection(t,r,a)}static#e(e,t){if(e.size!==t.size)return!0;for(const[r,a]of e)if(!t.has(r)||t.get(r)!==a)return!0;return!1}}; } // timelines/data/timelineDataManager.js { const C3=self.C3;C3.TimelineDataManager=class{constructor(){this._timelineDataItems=new Map}Release(){for(const e of this._timelineDataItems.values())e.Release();this._timelineDataItems.clear(),this._timelineDataItems=null}Add(e){const a=new C3.TimelineDataItem(e),t=a.GetName();this._timelineDataItems.set(t,a)}Get(e){return this._timelineDataItems.get(e)}GetNameId(){return 0}static _CreateDataItems(e,a,t,s){if(a)for(const i of a)C3.TimelineDataManager._CreateDataItem("create",i,e,t,s)}static _CreateDataItemsIncludingDisabled(e,a,t,s){if(a)for(const i of a)C3.TimelineDataManager._CreateDataItem("create-including-disabled",i,e,t,s)}static _LoadDataItemsFromJson(e,a,t,s){e.length?a.forEach((a,t)=>{e[t]._LoadFromJson(a)}):a.forEach(a=>{C3.TimelineDataManager._CreateDataItem("load",a,e,t,s)})}static _CreateDataItem(e,a,t,s,i){let n;if("function"==typeof s)switch(e){case"load":n=new s(null,i);break;case"create":case"create-including-disabled":n=new s(a,i)}else if("object"==typeof s){const t=a[s.prop],c=s.map.get(t);switch(e){case"load":n=new c(null,i);break;case"create":case"create-including-disabled":n=new c(a,i)}}switch(e){case"load":n._LoadFromJson(a),t.push(n);break;case"create":if("function"==typeof n.GetEnable&&!n.GetEnable())return n.Release();t.push(n);break;case"create-including-disabled":t.push(n)}}}; } // timelines/data/timelineData.js { const C3=self.C3,NAME=0,TOTAL_TIME=1,STEP=2,INTERPOLATION_MODE=3,RESULT_MODE=4,TRACKS=5,LOOP=6,PING_PONG=7,REPEAT_COUNT=8,START_ON_LAYOUT=9,TRANSFORM_WITH_SCENE_GRAPH=10,USE_SYSTEM_TIMESCALE=11;C3.TimelineDataItem=class{constructor(t){this._name="",this._totalTime=NaN,this._step=0,this._interpolationMode="default",this._resultMode="default",this._loop=!1,this._pingPong=!1,this._repeatCount=1,this._trackData=null,this._startOnLayout="",this._transformWithSceneGraph=!1,this._useSystemTimescale=!0,t&&(this._name=t[0],this._totalTime=t[1],this._step=t[2],this._interpolationMode=t[3],this._resultMode=t[4],this._loop=!!t[6],this._pingPong=!!t[7],this._repeatCount=t[8],this._startOnLayout=t[9],this._transformWithSceneGraph=!!t[10],this._useSystemTimescale=!!t[11],this._trackData=new C3.TrackData(t[5],this))}Release(){this._trackData.Release(),this._trackData=null}GetTrackData(){return this._trackData||(this._trackData=new C3.TrackData(null,this)),this._trackData}GetName(){return this._name}SetName(t){this._name=t}GetTotalTime(){return this._totalTime}SetTotalTime(t){this._totalTime=t}GetStep(){return this._step}SetStep(t){this._step=t}GetInterpolationMode(){return this._interpolationMode}SetInterpolationMode(t){this._interpolationMode=t}GetResultMode(){return this._resultMode}SetResultMode(t){this._resultMode=t}GetLoop(){return this._loop}SetLoop(t){this._loop=t}GetPingPong(){return this._pingPong}SetPingPong(t){this._pingPong=t}GetRepeatCount(){return this._repeatCount}SetRepeatCount(t){this._repeatCount=t}GetStartOnLayout(){return this._startOnLayout}GetTransformWithSceneGraph(){return this._transformWithSceneGraph}GetUseSystemTimescale(){return this._useSystemTimescale}_SaveToJson(){return{"trackDataJson":this._trackData._SaveToJson(),"name":this._name,"totalTime":this._totalTime,"step":this._step,"interpolationMode":this._interpolationMode,"resultMode":this._resultMode,"loop":this._loop,"pingPong":this._pingPong,"repeatCount":this._repeatCount,"startOnLayout":this._startOnLayout,"transformWithSceneGraph":!!this._transformWithSceneGraph,"useSystemTimescale":this._useSystemTimescale}}_LoadFromJson(t){t&&(this.GetTrackData()._LoadFromJson(t["trackDataJson"]),this._name=t["name"],this._totalTime=t["totalTime"],this._step=t["step"],this._interpolationMode=t["interpolationMode"],this._resultMode=t["resultMode"],this._loop=t["loop"],this._pingPong=t["pingPong"],this._repeatCount=t["repeatCount"],this._startOnLayout=t["startOnLayout"],this._transformWithSceneGraph=!!t["transformWithSceneGraph"],this._useSystemTimescale=!!t["useSystemTimescale"])}}; } // timelines/data/trackData.js { const C3=self.C3,WI_DATA=0,OC_INDEX=1,WI_UID=2,INTERPOLATION_MODE=1,RESULT_MODE=2,ENABLED=3,KEYFRAMES=4,PROPERTY_TRACKS=5,ID=6,NESTED_DATA=7,START_OFFSET=0,LOCAL_TOTAL_TIME=1,WI_ADDITIONAL_DATA=8,ORIGINAL_WIDTH=0,ORIGINAL_HEIGHT=1,TRACK_TYPE=9,TRACK_NAME=10;class TrackDataItem{constructor(t,a){this._trackData=a,this._instanceData=null,this._additionalInstanceData=null,this._instanceUid=NaN,this._objectClassIndex=NaN,this._interpolationMode="default",this._resultMode="default",this._enabled=!1,this._keyframeData=null,this._propertyTrackData=null,this._id="",this._nestedData=null,this._startOffset=0,this._localTotalTime=this._trackData.GetTimelineDataItem().GetTotalTime(),this._type=0,this._name="",t&&(t[0]&&(this._instanceData=t[0],this._instanceUid=t[0][2],this._objectClassIndex=t[0][1]),this._interpolationMode=t[1],this._resultMode=t[2],this._enabled=!!t[3],t[6]&&(this._id=t[6]),t[7]&&(this._nestedData=t[7],this._startOffset=t[7][0],this._localTotalTime=t[7][1]),t[8]&&(this._additionalInstanceData=t[8]),t[8]&&(this._additionalInstanceData=t[8]),t[9]&&(this._type=t[9]),t[10]&&(this._name=t[10]),this._keyframeData=new C3.KeyframeData(t[4],this),this._propertyTrackData=new C3.PropertyTrackData(t[5],this))}Release(){this._instanceData=null,this._trackData=null,this._keyframeData&&(this._keyframeData.Release(),this._keyframeData=null),this._propertyTrackData&&(this._propertyTrackData.Release(),this._propertyTrackData=null),this._nestedData=null}GetTrackData(){return this._trackData}GetKeyframeData(){return this._keyframeData||(this._keyframeData=new C3.KeyframeData(null,this)),this._keyframeData}GetPropertyTrackData(){return this._propertyTrackData||(this._propertyTrackData=new C3.PropertyTrackData(null,this)),this._propertyTrackData}GetInstanceData(){return this._instanceData}GetObjectClassIndex(){return this._objectClassIndex}SetObjectClassIndex(t){this._objectClassIndex=t}GetInstanceUID(){return this._instanceUid}SetInstanceUID(t){this._instanceUid=t}GetInterpolationMode(){return this._interpolationMode}SetInterpolationMode(t){this._interpolationMode=t}GetResultMode(){return this._resultMode}SetResultMode(t){this._resultMode=t}GetEnable(){return this._enabled}SetEnable(t){this._enabled=!!t}GetId(){return this._id}GetStartOffset(){return this._startOffset}GetLocalTotalTime(){return this._localTotalTime}SetLocalTotalTime(t){this._localTotalTime=t}GetOriginalSize(){return[this.GetOriginalWidth(),this.GetOriginalHeight(),0]}GetOriginalWidth(){return this._additionalInstanceData[0]}SetOriginalWidth(t){this._additionalInstanceData||(this._additionalInstanceData=[]),this._additionalInstanceData[0]=t}GetOriginalHeight(){return this._additionalInstanceData||(this._additionalInstanceData=[]),this._additionalInstanceData[1]}SetOriginalHeight(t){this._additionalInstanceData||(this._additionalInstanceData=[]),this._additionalInstanceData[1]=t}GetType(){return this._type}GetName(){return this._name}_SaveToJson(){return{"keyframeDataJson":this._keyframeData._SaveToJson(),"propertyTrackDataJson":this._propertyTrackData._SaveToJson(),"instanceData":this._instanceData,"additionalInstanceData":this._additionalInstanceData,"instanceUid":this._instanceUid,"objectClassIndex":this._objectClassIndex,"interpolationMode":this._interpolationMode,"resultMode":this._resultMode,"enabled":this._enabled,"id":this._id,"nestedData":this._nestedData,"type":this._type,"name":this._name}}_LoadFromJson(t){t&&(this._instanceData=t["instanceData"],this._instanceUid=t["instanceUid"],this._objectClassIndex=t["objectClassIndex"],this._interpolationMode=t["interpolationMode"],this._resultMode=t["resultMode"],this._enabled=t["enabled"],this._id=t["id"],this._type=t["type"]?t["type"]:0,this._name=t["name"]?t["name"]:"",this._localTotalTime=this._trackData.GetTimelineDataItem().GetTotalTime(),t["nestedData"]&&(this._nestedData=t["nestedData"],this._startOffset=this._nestedData[0],this._localTotalTime=this._nestedData[1]),t["additionalInstanceData"]&&(this._additionalInstanceData=t["additionalInstanceData"]),this.GetKeyframeData()._LoadFromJson(t["keyframeDataJson"]),this.GetPropertyTrackData()._LoadFromJson(t["propertyTrackDataJson"]))}}C3.TrackData=class{constructor(t,a){this._timelineDataItem=a,this._trackDataItems=[],C3.TimelineDataManager._CreateDataItems(this._trackDataItems,t,TrackDataItem,this)}Release(){this._timelineDataItem=null;for(const t of this._trackDataItems)t.Release();C3.clearArray(this._trackDataItems),this._trackDataItems=null}GetTimelineDataItem(){return this._timelineDataItem}AddEmptyTrackDataItem(){const t=new TrackDataItem(null,this);return this._trackDataItems.push(t),t}GetFirstKeyframeDataItem(t){return t.GetKeyframeData().GetKeyframeDataItemArray()[0]}GetLastKeyframeDataItem(t){return t.GetKeyframeData().GetKeyframeDataItemArray().at(-1)}GetKeyFrameDataItemAtTime(t,a){const e=a.GetKeyframeData().GetKeyframeDataItemArray(),i=e.length;for(let a=0;at)return i}}GetFirstKeyFrameDataItemHigherOrEqualThan(t,a){const e=a.GetKeyframeData().GetKeyframeDataItemArray(),i=e.length;for(let a=0;a=t)return i}}GetFirstKeyFrameDataItemLowerOrEqualThan(t,a){const e=a.GetKeyframeData().GetKeyframeDataItemArray();for(let a=e.length-1;a>=0;a--){const i=e[a];if(i.GetTime()<=t)return i}}*trackDataItems(){for(const t of this._trackDataItems)yield t}_SaveToJson(){return{"trackDataItemsJson":this._trackDataItems.map(t=>t._SaveToJson())}}_LoadFromJson(t){t&&C3.TimelineDataManager._LoadDataItemsFromJson(this._trackDataItems,t["trackDataItemsJson"],TrackDataItem,this)}}; } // timelines/data/propertyTrackData.js { const C3=self.C3,SOURCE_DATA=0,SOURCE=0,PROPERTY=1,TYPE=2,MIN=3,MAX=4,INTERPOLATION_MODE=5,RESULT_MODE=6,ENABLED=7,PROPERTY_KEYFRAMES=8,CAN_HAVE_PROPERTY_KEYFRAMES=9;class PropertyTrackDataItem{constructor(t,e){this._propertyTrackData=e,this._sourceAdapterId="",this._sourceAdapterArguments=null,this._property=null,this._type=null,this._min=NaN,this._max=NaN,this._interpolationMode="default",this._resultMode="default",this._enabled=!1,this._propertyKeyframeData=null,this._canHavePropertyKeyframes=!0,t&&(this._sourceAdapterId=t[0][0],this._sourceAdapterArguments=t[0].slice(1),this._property=t[1],this._type=t[2],this._min=t[3],this._max=t[4],this._interpolationMode=t[5],this._resultMode=t[6],this._enabled=!!t[7],this._propertyKeyframeData=new C3.PropertyKeyframeData(t[8],this),this._canHavePropertyKeyframes=t[9])}Release(){this._propertyKeyframeData.Release(),this._propertyKeyframeData=null,this._propertyTrackData=null,this._sourceAdapterArguments=null}GetPropertyTrackData(){return this._propertyTrackData}GetPropertyKeyframeData(){return this._propertyKeyframeData||(this._propertyKeyframeData=new C3.PropertyKeyframeData(null,this)),this._propertyKeyframeData}GetSourceAdapterId(){return this._sourceAdapterId}SetSourceAdapterId(t){this._sourceAdapterId=t}GetSourceAdapterArguments(){return this._sourceAdapterArguments}SetSourceAdapterArguments(t){this._sourceAdapterArguments=t}GetProperty(){return this._property}SetProperty(t){this._property=t}GetType(){return this._type}SetType(t){this._type=t}GetMin(){return this._min}SetMin(t){this._min=t}GetMax(){return this._max}SetMax(t){this._max=t}GetInterpolationMode(){return this._interpolationMode}SetInterpolationMode(t){this._interpolationMode=t}GetResultMode(){return this._resultMode}SetResultMode(t){this._resultMode=t}GetEnable(){return this._enabled}SetEnable(t){this._enabled=!!t}CanHavePropertyKeyframes(){return!!this._canHavePropertyKeyframes}_SaveToJson(){return{"propertyKeyframeDataJson":this._propertyKeyframeData._SaveToJson(),"sourceAdapterId":this._sourceAdapterId,"sourceAdapterArguments":this._sourceAdapterArguments,"property":this._property,"type":this._type,"min":this._min,"max":this._max,"interpolationMode":this._interpolationMode,"resultMode":this._resultMode,"enabled":this._enabled,"canHavePropertyKeyframes":this._canHavePropertyKeyframes}}_LoadFromJson(t){t&&(this._sourceAdapterId=t["sourceAdapterId"],this._sourceAdapterArguments=t["sourceAdapterArguments"],this._property=t["property"],this._type=t["type"],this._min=t["min"],this._max=t["max"],this._interpolationMode=t["interpolationMode"],this._resultMode=t["resultMode"],this._enabled=t["enabled"],this._canHavePropertyKeyframes=t["canHavePropertyKeyframes"],this.GetPropertyKeyframeData()._LoadFromJson(t["propertyKeyframeDataJson"]))}}C3.PropertyTrackData=class{constructor(t,e){this._trackDataItem=e,this._propertyTrackDataItems=[],C3.TimelineDataManager._CreateDataItems(this._propertyTrackDataItems,t,PropertyTrackDataItem,this)}Release(){this._trackDataItem=null;for(const t of this._propertyTrackDataItems)t.Release();C3.clearArray(this._propertyTrackDataItems),this._propertyTrackDataItems=null}GetTrackDataItem(){return this._trackDataItem}AddEmptyPropertyTrackDataItem(){const t=new PropertyTrackDataItem(null,this);return this._propertyTrackDataItems.push(t),t}GetFirstPropertyKeyframeDataItem(t){return t.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray()[0]}GetLastPropertyKeyframeDataItem(t){return t.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray().at(-1)}GetPropertyKeyFrameDataItemAtTime(t,e){const r=e.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray(),a=r.length;for(let e=0;et)return a}}GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(t,e){const r=e.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray(),a=r.length;for(let e=0;e=t)return a}}GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,e){const r=e.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray();for(let e=r.length-1;e>=0;e--){const a=r[e];if(a.GetTime()<=t)return a}}*propertyTrackDataItems(){for(const t of this._propertyTrackDataItems)yield t}_SaveToJson(){return{"propertyTrackDataItemsJson":this._propertyTrackDataItems.map(t=>t._SaveToJson())}}_LoadFromJson(t){t&&C3.TimelineDataManager._LoadDataItemsFromJson(this._propertyTrackDataItems,t["propertyTrackDataItemsJson"],PropertyTrackDataItem,this)}}; } // timelines/data/keyframeData.js { const C3=self.C3,TIME=0,EASE=1,ENABLE=2,TAGS=3;class KeyframeDataItem{constructor(e,t){if(this._keyframeData=t,this._time=-1,this._ease="noease",this._enable=!1,this._tags=null,this._lowerTags=null,!e)return;this._time=e[0],this._ease=e[1],this._enable=!!e[2];const a=e[3];this._tags=a?a.split(" "):[],this._lowerTags=new Set(this._tags.map(e=>e.toLowerCase())),this._next=null,this._last=null}Release(){this._keyframeData=null,C3.clearArray(this._tags),this._tags=null,this._lowerTags.clear(),this._lowerTags=null,this._next=null}GetKeyframeData(){return this._keyframeData}GetNext(){return this._next}SetNext(e){this._next=e}GetLast(){return this._last}SetLast(e){this._last=e}GetTime(){return this._time}SetTime(e){this._time=e,this._keyframeData._LinkKeyframeDataItems()}GetEase(){return this._ease}SetEase(e){this._ease=e}GetEnable(){return this._enable}SetEnable(e){this._enable=!!e}GetTags(){return this._tags}SetTags(e){this._tags=e?e.split(" "):[],this._lowerTags=new Set(this._tags.map(e=>e.toLowerCase()))}GetLowerTags(){return this._lowerTags}GetTagsString(){return Array.from(this._lowerTags).join(",").trim()}HasTag(e){return this._lowerTags.has(e.toLowerCase())}_SaveToJson(){return{"time":this._time,"ease":this._ease,"enable":this._enable,"tags":this._tags}}_LoadFromJson(e){e&&(this._time=e["time"],this._ease=e["ease"],this._enable=e["enable"],this._tags=e["tags"],this._lowerTags=new Set(this._tags.map(e=>e.toLowerCase())))}}C3.KeyframeData=class{constructor(e,t){this._trackDataItem=t,this._keyframeDataItems=[],C3.TimelineDataManager._CreateDataItems(this._keyframeDataItems,e,KeyframeDataItem,this),this._LinkKeyframeDataItems()}Release(){this._trackDataItem=null;for(const e of this._keyframeDataItems)e.Release();C3.clearArray(this._keyframeDataItems),this._keyframeDataItems=null}_LinkKeyframeDataItems(){this._keyframeDataItems.sort((e,t)=>e.GetTime()-t.GetTime());for(let e=0;ee.GetTime()-t.GetTime())}GetKeyframeDataItemIndex(e){return this._keyframeDataItems.indexOf(e)}GetKeyframeDataItemFromIndex(e){return this._keyframeDataItems[e]}*keyframeDataItems(){for(const e of this._keyframeDataItems)yield e}*keyframeDataItemsReverse(){for(let e=this._keyframeDataItems.length-1;e>=0;e--)yield this._keyframeDataItems[e]}_SaveToJson(){return{"keyframeDataItemsJson":this._keyframeDataItems.map(e=>e._SaveToJson())}}_LoadFromJson(e){e&&(C3.TimelineDataManager._LoadDataItemsFromJson(this._keyframeDataItems,e["keyframeDataItemsJson"],KeyframeDataItem,this),this._LinkKeyframeDataItems())}}; } // timelines/data/propertyKeyframeData.js { const C3=self.C3,VALUE_DATA=0,VALUE_DATA_VALUE=0,VALUE_DATA_ABSOLUTE_VALUE=1,VALUE_DATA_TYPE=2,TIME=1,EASE=2,ENABLE=3,ADDONS=4,PATH_MODE=5;class PropertyKeyframeDataItem{constructor(e,t){this._propertyKeyframeData=t,this._value=null,this._aValue=null,this._type="",this._time=NaN,this._ease="noease",this._enable=!1,this._addonData=null,this._addonInstance=void 0,this._pathMode="line",e&&(this._value=e[0][0],this._aValue=e[0][1],this._type=e[0][2],"map"===this._type&&(this._value=new Map(this._value),this._aValue=new Map(this._aValue)),this._time=e[1],this._ease=e[2],this._enable=!!e[3],this._pathMode=e[5],this._addonData=null,e[4]&&(this._addonData=new C3.AddonData(e[4],this)),this._next=null,this._prev=null)}Release(){this._propertyKeyframeData=null,this._addonData&&(this._addonData.Release(),this._addonData=null),this._next=null,this._prev=null}GetAddonData(){return this._addonData}SetNext(e){this._next=e}GetNext(){return this._next}SetPrevious(e){this._prev=e}GetPrevious(){return this._prev}GetValue(){return this._value}SetValue(e){"color"===this._type&&C3.IsFiniteNumber(e)?(this._value[0]=C3.GetRValue(e),this._value[1]=C3.GetGValue(e),this._value[2]=C3.GetBValue(e)):this._value=e}GetAbsoluteValue(){return this._aValue}SetAbsoluteValue(e){"color"===this._type&&C3.IsFiniteNumber(e)?(this._aValue[0]=C3.GetRValue(e),this._aValue[1]=C3.GetGValue(e),this._aValue[2]=C3.GetBValue(e)):this._aValue=e}GetValueWithResultMode(){const e=this._propertyKeyframeData.GetPropertyTrackDataItem().GetResultMode();return"relative"===e?this.GetValue():"absolute"===e?this.GetAbsoluteValue():void 0}GetType(){return this._type}SetType(e){this._type=e}GetTime(){return this._time}SetTime(e){this._time=e,this._propertyKeyframeData._LinkPropertyKeyframeDataItems()}GetEase(){return this._ease}SetEase(e){this._ease=e}GetEnable(){return this._enable}SetEnable(e){this._enable=!!e}GetPathMode(){return this._pathMode}GetAddOn(e){if(!this._addonData)return;if(this._addonInstance||null===this._addonInstance)return this._addonInstance;const t=this._addonData.GetAddDataItemArray();if(!t)return this._addonInstance=null,this._addonInstance;const a=t.length;for(let r=0;re.GetTime()-t.GetTime());for(let t=0;t=0&&a.SetPrevious(e[t-1])}e=this._propertyKeyframeDataItemsIncludingDisabled,e.sort((e,t)=>e.GetTime()-t.GetTime());for(let t=0;t=0&&a.SetPrevious(e[t-1])}}AddEmptyPropertyKeyframeDataItem(){const e=new PropertyKeyframeDataItem(null,this);return this._propertyKeyframeDataItems.push(e),this._LinkPropertyKeyframeDataItems(),e}DeletePropertyKeyframeDataItems(e){for(const t of this._propertyKeyframeDataItems){if(!e(t))continue;const a=this._propertyKeyframeDataItems.indexOf(t);-1!==a&&(t.Release(),this._propertyKeyframeDataItems.splice(a,1))}this.SortPropertyKeyFrameDataItems(),this._LinkPropertyKeyframeDataItems()}SortPropertyKeyFrameDataItems(){this._propertyKeyframeDataItems.sort((e,t)=>e.GetTime()-t.GetTime())}GetPropertyTrackDataItem(){return this._propertyTrackDataItem}GetPropertyKeyframeDataItemCount(){return this._propertyKeyframeDataItems.length}GetLastPropertyKeyframeDataItem(){return this._propertyKeyframeDataItems[this._propertyKeyframeDataItems.length-1]}GetPropertyKeyframeDataItemArray(){return this._propertyKeyframeDataItems}GetPropertyKeyframeDataItemArrayIncludingDisabled(){return this._propertyKeyframeDataItemsIncludingDisabled}*propertyKeyframeDataItems(){for(const e of this._propertyKeyframeDataItems)yield e}*propertyKeyframeDataItemsReverse(){for(let e=this._propertyKeyframeDataItems.length-1;e>=0;e--)yield this._propertyKeyframeDataItems[e]}_SaveToJson(){const e=this._propertyKeyframeDataItems,t=this._propertyKeyframeDataItemsIncludingDisabled;return{"propertyKeyframeDataItemsJson":e.map(e=>e._SaveToJson()),"propertyKeyframeDataItemsIncludingDisabledJson":t.map(e=>e._SaveToJson())}}_LoadFromJson(e){e&&(C3.TimelineDataManager._LoadDataItemsFromJson(this._propertyKeyframeDataItems,e["propertyKeyframeDataItemsJson"],PropertyKeyframeDataItem,this),C3.TimelineDataManager._LoadDataItemsFromJson(this._propertyKeyframeDataItemsIncludingDisabled,e["propertyKeyframeDataItemsIncludingDisabledJson"],PropertyKeyframeDataItem,this),this._LinkPropertyKeyframeDataItems())}}; } // timelines/data/propertyKeyframeAddonData.js { const C3=self.C3,ADDON_ID=0,ADDON_DATA=1;class AddonDataItem{constructor(t,a){this._addonData=a,this._id=t[0],this._data=t[1]}Release(){this._addonData=null,this._data=null}GetAddonData(){return this._addonData}GetId(){return this._id}_SaveToJson(){return{"id":this._id,"data":this._data}}_LoadFromJson(t){t&&(this._id=t["id"],this._data=t["data"])}}const START_ANCHOR=0,START_ENABLE=1,END_ANCHOR=2,END_ENABLE=3;class AddonDataCubicBezierItem extends AddonDataItem{constructor(t,a){super(t,a),this._startAnchor=this._data[0],this._startEnable=!!this._data[1],this._endAnchor=this._data[2],this._endEnable=!!this._data[3]}Release(){super.Release()}GetStartAnchor(){return this._startAnchor}GetStartEnable(){return this._startEnable}GetEndAnchor(){return this._endAnchor}GetEndEnable(){return this._endEnable}_SaveToJson(){return Object.assign(super._SaveToJson(),{"startAnchor":this._startAnchor,"startEnable":!!this._startEnable,"endAnchor":this._endAnchor,"endEnable":!!this._endEnable})}_LoadFromJson(t){t&&(super._LoadFromJson(t),this._startAnchor=t["startAnchor"],this._startEnable=!!t["startEnable"],this._endAnchor=t["endAnchor"],this._endEnable=!!t["endEnable"])}}const DIRECTION=0,REVOLUTIONS=1;class AddonDataAngleItem extends AddonDataItem{constructor(t,a){super(t,a),this._direction=this._data[0],this._revolutions=this._data[1]}Release(){super.Release()}GetDirection(){return this._direction}GetRevolutions(){return this._revolutions}_SaveToJson(){return Object.assign(super._SaveToJson(),{"direction":this._direction,"revolutions":this._revolutions})}_LoadFromJson(t){t&&(super._LoadFromJson(t),this._direction=t["direction"],this._revolutions=t["revolutions"])}}const START_FROM=0;class AddonDataInitialAnimationItem extends AddonDataItem{constructor(t,a){super(t,a),this._startFrom=this._data[0]}Release(){super.Release()}GetStartFrom(){return this._startFrom}_SaveToJson(){return Object.assign(super._SaveToJson(),{"startFrom":this._startFrom})}_LoadFromJson(t){t&&(super._LoadFromJson(t),this._startFrom=t["startFrom"])}}C3.AddonData=class{constructor(t,a){this._propertyKeyframeDataItem=a,this._addonDataItems=[],C3.TimelineDataManager._CreateDataItems(this._addonDataItems,t,{prop:0,map:new Map([["cubic-bezier",AddonDataCubicBezierItem],["angle",AddonDataAngleItem],["initial-animation",AddonDataInitialAnimationItem]])},this)}Release(){this._propertyKeyframeDataItem=null;for(const t of this._addonDataItems)t.Release();C3.clearArray(this._addonDataItems),this._addonDataItems=null}GetPropertyKeyframeDataItem(){return this._propertyKeyframeDataItem}GetAddDataItemArray(){return this._addonDataItems}*addonDataItems(){for(const t of this._addonDataItems)yield t}_SaveToJson(){return{"addonDataItemsJson":this._addonDataItems.map(t=>t._SaveToJson())}}_LoadFromJson(t){t&&C3.TimelineDataManager._LoadDataItemsFromJson(this._addonDataItems,t["addonDataItemsJson"],{prop:"id",map:new Map([["cubic-bezier",AddonDataCubicBezierItem],["angle",AddonDataAngleItem],["initial-animation",AddonDataInitialAnimationItem]])},this)}}; } // timelines/tweens/tweenState.js { const C3=self.C3,INITIAL_VALUE_MODE_START_VALUE="start-value",INITIAL_VALUE_MODE_CURRENT_STATE="current-state",PING_PONG_BEGIN=0,PING_PONG_END=1;let createdTweens=0;C3.TweenState=class extends C3.TimelineState{constructor(e,t){super("tween-"+createdTweens++,e,t),this._id="",this._destroyInstanceOnComplete=!1,this._initialValueMode="start-value",this._instance=null,this._on_completed_callbacks=null,this._on_started_callbacks=null,this._releasePromise=null,this._releaseResolve=null,this._behInst=null,this._track=null,this._iTweenState=null}Release(){this.IsReleased()||(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensReleased),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweensReleased),this.ResolveReleasePromise(),super.Release(),this._instance=null,this._on_completed_callbacks=null,this._on_started_callbacks=null,this._behInst=null,this._track=null,this._releasePromise=null,this._releaseResolve=null)}FireReleaseEvent(e){const t=C3.New(C3.Event,"tweenstatereleased");t.tweenState=this,e.dispatchEvent(t)}GetType(){return 1}CreateTrackStates(){for(const e of this._timelineDataItem.GetTrackData().trackDataItems())this._tracks.push(C3.TweenTrackState.Create(this,e));this._track=this._tracks[0]}AddTrack(){const e=this._timelineDataItem.GetTrackData().AddEmptyTrackDataItem(),t=C3.TweenTrackState.Create(this,e);return this._tracks.push(t),this._CacheTrack(),t}_CacheTrack(){this._track=this._tracks[0]}GetPropertyTrack(e){return this._track.GetPropertyTracks()[0]}SetPropertyType(e){this._propertyType=e}GetInstance(){const e=this.GetTracks();if(!e||!e.length)return;const t=e[0];if(this._track=t,!t)return;const s=t.GetInstance();return t.IsInstanceValid()?s:void 0}SetBehaviorInstance(e){this._behInst=e}GetReleasePromise(){return this._releasePromise||(this._releasePromise=new Promise(e=>{this._releaseResolve=e})),this._releasePromise}ResolveReleasePromise(){this._releasePromise&&(this._releaseResolve&&this._releaseResolve(),this._releasePromise=null,this._releaseResolve=null)}AddStartedCallback(e){this._on_started_callbacks||(this._on_started_callbacks=[]),this._on_started_callbacks.push(e)}AddCompletedCallback(e){this._on_completed_callbacks||(this._on_completed_callbacks=[]),this._on_completed_callbacks.push(e)}RemoveStartedCallback(e){if(!this._on_started_callbacks)return;const t=this._on_started_callbacks.indexOf(e);-1!==t&&this._on_started_callbacks.splice(t,1)}RemoveCompletedCallback(e){if(!this._on_completed_callbacks)return;const t=this._on_completed_callbacks.indexOf(e);-1!==t&&this._on_completed_callbacks.splice(t,1)}SetStartValue(e,t){for(const s of this._tracks)for(const n of s._propertyTracks){if(n.GetPropertyName()!==t)continue;const s=n.GetPropertyTrackData(),i=n.GetPropertyTrackDataItem(),a=s.GetFirstPropertyKeyframeDataItem(i);a.SetValue(e),a.SetAbsoluteValue(e)}}_GetPropertyTrackState(e){for(const t of this._tracks)for(const s of t._propertyTracks)if(s.GetPropertyName()===e)return s}BeforeSetEndValues(e){let t=!1;for(const s of e){const e=this._GetPropertyTrackState(s);e&&(this.SetStartValue(e.GetCurrentState(),s),t=!0)}if(t){if(this.IsForwardPlayBack()){const e=this.GetTotalTime()-this.GetTime();this.SetTotalTime(e);for(const t of this._tracks)t.SetLocalTotalTime(e);this._SetTime(0)}else{const e=this.GetTime();this.SetTotalTime(e);for(const t of this._tracks)t.SetLocalTotalTime(e);this._SetTime(e)}this.SetInitialStateFromSetTime()}}SetEndValue(e,t){const s=this._GetPropertyTrackState(t);if(!s)return;const n=s.GetPropertyTrackData(),i=s.GetPropertyTrackDataItem(),a=n.GetLastPropertyKeyframeDataItem(i);a.SetTime(this.GetTotalTime()),a.SetValue(e),a.SetAbsoluteValue(e)}SetId(e){this._id=e}GetId(){return this._id}SetInitialValueMode(e){this._initialValueMode=e}GetInitialValueMode(){return this._initialValueMode}SetDestroyInstanceOnComplete(e){this._destroyInstanceOnComplete=e}GetDestroyInstanceOnComplete(){return this._destroyInstanceOnComplete}OnStarted(){if(this._on_started_callbacks)for(const e of this._on_started_callbacks)e(this);if(!this.IsComplete())for(const e of this._tracks)e.CompareSaveStateWithCurrent()}OnCompleted(){this._completedTick=this._runtime.GetTickCount()}FinishTriggers(){if(!this._finishedTriggers&&(this._finishedTriggers=!0,this._on_completed_callbacks))for(const e of this._on_completed_callbacks)e(this)}SetTime(e){this._DeleteIntermediateKeyframes(),super.SetTime(e)}_SetTimeAndReset(e){C3.IsFiniteNumber(e)||(e=this.GetTotalTime()),e<0?this._playheadTime=0:e>=this.GetTotalTime()?this._playheadTime=this.GetTotalTime():this._playheadTime=e,this._track.SetResetState()}SetInitialState(e){if(!this.InitialStateSet()&&"current-state"===this.GetInitialValueMode())for(const e of this._tracks)e.CompareInitialStateWithCurrent();super.SetInitialState(e)}Stop(e=!1){if(super.Stop(e),!this.IsComplete())for(const e of this._tracks)e.SaveState()}Reset(e=!0,t=!1){this._DeleteIntermediateKeyframes(),super.Reset(e,t)}_DeleteIntermediateKeyframes(){for(const e of this._tracks){const t=e=>{const t=e.GetTime(),s=this.GetTotalTime();return 0!==t&&t!==s};e.DeleteKeyframes(t),e.DeletePropertyKeyframes(t)}}_OnBeforeChangeLayout(){if(this.IsReleased())return!0;const e=this.GetInstance();return(!e||!e.GetObjectClass().IsGlobal())&&(this._timelineManager.CompleteTimelineBeforeChangeOfLayout(this),this.ResetBeforeChangeLayout(),!0)}Tick(e,t,s){if(this._instance||(this._instance=this.GetInstance()),!this._instance||this._instance.IsDestroyed())return this.Stop(!0),void this.OnCompleted();const n=this._instance.GetTimeScale();if(-1!==n&&(e=s*n),0===e&&0===this._lastDelta)return;this._lastDelta=e;const i=this._playheadTime+this._overshoot+e*this._playbackRate,a=this._timelineDataItem._totalTime;i<0?(this._playheadTime=0,this._overshoot=-i):i>=a?(this._playheadTime=a,this._overshoot=this._playheadTime-i):(this._playheadTime=i,this._overshoot=0);let r=!1,o=!1;const h=this.GetLoop(),l=this.GetPingPong();if(h||l?h&&!l?this._playbackRate>0?this._playheadTime>=a&&(this._SetTimeAndReset(0),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),o=!0):this._playheadTime<=0&&(this._SetTimeAndReset(a),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),o=!0):!h&&l?this._playbackRate>0?this._playheadTime>=a&&(this._SetTime(a),this.SetPlaybackRate(-1*this.GetPlaybackRate()),o=!0,1===this._pingPongState?this._currentRepeatCount0?this._playheadTime>=a&&(this._SetTime(a),this.SetPlaybackRate(-1*this.GetPlaybackRate()),o=!0,0===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)),1===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)),this.IsPlaying()?(this._pingPongState++,this._pingPongState=C3.wrap(this._pingPongState,0,2)):(this._resumePingPongState=this._pingPongState+1,this._resumePingPongState=C3.wrap(this._resumePingPongState,0,2))):this._playheadTime<=0&&(this._SetTime(0),this.SetPlaybackRate(-1*this.GetPlaybackRate()),o=!0,0===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)),1===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)),this.IsPlaying()?(this._pingPongState++,this._pingPongState=C3.wrap(this._pingPongState,0,2)):(this._resumePingPongState=this._pingPongState+1,this._resumePingPongState=C3.wrap(this._resumePingPongState,0,2)))):this._playbackRate>0?this._playheadTime>=a&&(this._currentRepeatCountt.GetNeedsBeforeAndAfter())&&(this._needsBeforeAndAfter=1),this._lastKeyframeDataItem=this._GetLastKeyFrameBeforeTime(t),this._initialStateOfNestedSet=!1,this._endStateOfNestedSet=!1,this.Interpolate(t)}BeforeInterpolate(){}Interpolate(t,r=!1,e=!1,s=!1,a=!1,o=!1,i=!1){if(this._instance||this.GetInstance(),!this._instance)return;return!this._instance.IsDestroyed()&&((!o||!this.GetObjectClass().IsGlobal())&&(this._thirdPropertyTrack?(this._firstPropertyTrack.Interpolate(t,e,s,i),this._secondPropertyTrack.Interpolate(t,e,s,i),this._thirdPropertyTrack.Interpolate(t,e,s,i)):this._secondPropertyTrack?(this._firstPropertyTrack.Interpolate(t,e,s,i),this._secondPropertyTrack.Interpolate(t,e,s,i)):this._firstPropertyTrack.Interpolate(t,e,s,i),void(0!==this._firstPropertyTrack.GetWorldInfoChange()&&(this._worldInfo||(this._worldInfo=this._instance.GetWorldInfo()),this._worldInfo&&this._worldInfo.SetBboxChanged()))))}AfterInterpolate(){}_LoadFromJson(t){super._LoadFromJson(t),this._CachePropertyTracks()}}; } // timelines/tweens/tweenPropertyTrackState.js { const C3=self.C3;C3.TweenPropertyTrackState=class extends C3.PropertyTrackState{constructor(t,e){super(t,e),this._basic=!1}static Create(t,e){return C3.New(C3.TweenPropertyTrackState,t,e)}Interpolate(t,e=!1,r=!1,a=!1){let s,o;if(this._basic)s=this._propertyKeyframeDataItems[0],o=this._propertyKeyframeDataItems[1];else if(e)s=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,this._propertyTrackDataItem),o=s.GetNext();else{if(this._lastPropertyKeyframeDataItem){const e=this.GetTimeline(),r=this._lastPropertyKeyframeDataItem.GetNext(),a=this._lastPropertyKeyframeDataItem.GetTime(),s=r?r.GetTime():e.GetTotalTime();(t<=a||t>=s)&&(this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,this._propertyTrackDataItem))}else this._lastPropertyKeyframeDataItem=this._propertyTrackData.GetFirstPropertyKeyFrameDataItemLowerOrEqualThan(t,this._propertyTrackDataItem);s=this._lastPropertyKeyframeDataItem,o=s.GetNext()}this._sourceAdapter.Interpolate(t,s,o,e,r,a)}AddPropertyKeyframe(){const t=this._propertyTrackDataItem.GetPropertyKeyframeData().AddEmptyPropertyKeyframeDataItem();return this._lastPropertyKeyframeDataItem=null,this._basic=this.GetPropertyKeyframeDataItems().length<=2,t}DeletePropertyKeyframes(t){this._lastPropertyKeyframeDataItem=null;this._propertyTrackDataItem.GetPropertyKeyframeData().DeletePropertyKeyframeDataItems(t),this._basic=this.GetPropertyKeyframeDataItems().length<=2}_SaveToJson(){return{"sourceAdapterJson":this.GetSourceAdapter()._SaveToJson(),"basic":this._basic}}_LoadFromJson(t){t&&(this.GetSourceAdapter()._LoadFromJson(t["sourceAdapterJson"]),this._basic=t["basic"])}}; } // timelines/transitions/transition.js { const C3=self.C3,Ease=self.Ease,NAME=0,TRANSITION_KEYFRAMES=1,LINEAR=2;C3.Transition=class extends C3.DefendedBase{constructor(e,t=!0){super(),this._name=e[0],this._linear=e[2],this._transitionKeyframes=[];for(const t of e[1]){const e=C3.TransitionKeyframe.Create(this,t);this._transitionKeyframes.push(e)}for(let e=0;ethis.Interpolate(e,t,a,s),null,{transition:this})}static Create(e){return C3.New(C3.Transition,e)}Release(){for(const e of this._transitionKeyframes)e.Release();C3.clearArray(this._transitionKeyframes),this._transitionKeyframes=null,this._precalculatedSamples.clear(),this._precalculatedSamples=null,this._transitionKeyframeCache.clear(),this._transitionKeyframeCache=null}MakeLinear(e){this._linear=!!e}GetTransitionKeyFrameAt(e){const t=this._transitionKeyframeCache.get(e);if(t)return t;for(const t of this._transitionKeyframes)if(t.GetValueX()===e)return this._transitionKeyframeCache.set(e,t),t}GetFirstTransitionKeyFrameLowerOrEqualThan(e){for(let t=this._transitionKeyframes.length-1;t>=0;t--){const a=this._transitionKeyframes[t],s=a.GetValueX();if(s<=e){let t=a;if(sthis._OnInstanceDestroy(e.instance)}Release(){if(this.RemoveRuntimeListeners(),this._templateDataMap){for(const e of this._templateDataMap.values())e.clear();this._templateDataMap.clear()}this._templateDataMap=null,this._runtime=null}Create(e){if(this._templateDataMap||(this._templateDataMap=new Map),!e)return;const t=e[0][17][0],a=e[1];this._templateDataMap.has(a)||this._templateDataMap.set(a,new Map);this._templateDataMap.get(a).set(t,e)}AddRuntimeListeners(){const e=this._runtime.Dispatcher();e&&e.addEventListener("instancedestroy",this._instanceDestroy)}RemoveRuntimeListeners(){const e=this._runtime.Dispatcher();e&&e.removeEventListener("instancedestroy",this._instanceDestroy)}HasTemplates(){return!!this._templateDataMap&&0!==this._templateDataMap.size}GetTemplateData(e,t){let a=0;if(a=e instanceof C3.ObjectClass?e.GetIndex():e,!this._templateDataMap.has(a))return;const s=this._templateDataMap.get(a).get(t);return s?JSON.parse(JSON.stringify(s)):void 0}MapInstanceToTemplateName(e,t){this._instanceToTemplateNameMap||(this._instanceToTemplateNameMap=new WeakMap),this._instanceToTemplateNameMap.has(e)||this._instanceToTemplateNameMap.set(e,t)}GetInstanceTemplateName(e){if(!this._instanceToTemplateNameMap)return"";const t=this._instanceToTemplateNameMap.get(e);return t||""}_OnInstanceDestroy(e){this._instanceToTemplateNameMap&&this._instanceToTemplateNameMap.has(e)&&this._instanceToTemplateNameMap.delete(e)}}; } // flowcharts/flowchartManager.js { const C3=self.C3;C3.FlowchartManager=class{constructor(a){this._runtime=a,this._flowchartDataManager=new C3.FlowchartDataManager}Release(){this._flowchartDataManager.Release(),this._flowchartDataManager=null,this._runtime=null}GetRuntime(){return this._runtime}Create(a){this._flowchartDataManager.Add(a)}GetFlowchartDataItemByName(a){return this._flowchartDataManager.Get(a)}HasFlowcharts(){return this._flowchartDataManager.HasFlowcharts()}}; } // flowcharts/state/flowchartState.js { const C3=self.C3;C3.FlowchartState=class{constructor(t,e,r,a,o,h,s){this._runtime=o.GetRuntime(),this._flowchartManager=o,this._flowchartName=t,this._startNodeTag=r,this._flowchartDataItem=a,this._tag=e,this._pluginInstance=h,this._pluginUID=s??h.GetInstance().GetUID(),this._SetStartFlowchartNode(),this._currentFlowchartNodeId=this._startFlowchartNode?.GetFlowchartId()??-1,this._previousFlowchartNodeIds=[],this._previousFlowchartState=null,this._previousFlowchartStateStartNodeId=NaN,this._referenceFlowchartStates=null,this._currentReferenceFlowchartState=null,this._rootFlowchartState=null,this._previousFlowchartStateTag="",this._referenceFlowchartStatesJson=null,this._currentReferenceFlowchartStateTag="",this._rootFlowchartStateTag="",this._triggerCount=0,this._markForRelease=!1,this._released=!1}Release(){this._released||(C3.clearArray(this._previousFlowchartNodeIds),this._previousFlowchartNodeIds=null,this._runtime=null,this._flowchartManager=null,this._flowchartDataItem=null,this._pluginInstance=null,this._previousFlowchartState=null,this._previousFlowchartStateStartNodeId=NaN,this._referenceFlowchartStates&&this._referenceFlowchartStates.clear(),this._referenceFlowchartStates=null,this._currentReferenceFlowchartState=null,this._rootFlowchartState=null,this._previousFlowchartStateTag="",this._referenceFlowchartStatesJson=null,this._currentReferenceFlowchartStateTag="",this._rootFlowchartStateTag="",this._released=!0)}WasReleased(){return this._released}GetFlowchartManager(){return this._flowchartManager}GetRuntime(){return this._runtime}GetName(){return this._flowchartName}GetFlowchartDataItem(){return this._flowchartDataItem}GetTag(){return this._tag}GetPluginInstance(){return this._pluginInstance||(this._pluginInstance=this._runtime.GetInstanceByUID(this._pluginUID).GetSdkInstance()),this._pluginInstance}GetCurrentNode(){return this.GetFlowchartElementById(this._currentFlowchartNodeId)}GetCurrentNodeTag(){const t=this.GetCurrentNode();return t?t.GetTag():""}GetCurrentNodeTags(){const t=this.GetCurrentNode();return t?t.GetTags():[]}CurrentNodeHasTags(t){const e=this.GetCurrentNodeTags();if(!e)return!1;if(!e.length)return!1;const r=C3.FlowchartState._GetTagArray(t);return!(!r||!r.length)&&r.every(C3.FlowchartState._HasTag,e)}CurrentNodeCompareTags(t,e){const r=this.GetCurrentNodeTags();if(!r)return!1;if(!r.length)return!1;const a=C3.FlowchartState._GetTagArray(t);return!(!a||!a.length)&&a.every(t=>C3.FlowchartState._CompareTag.call(r,t,e))}static _HasTag(t){const e=this;return""===t?1===e.length&&""===e[0]:e.map(t=>t.trim().toLowerCase()).includes(t.trim().toLowerCase())}static _GetTagArray(t){return t.trim().split(" ")}static _CompareTag(t,e){const r=this;return""===t?1===r.length&&""===r[0]:r.some(r=>C3.compare(r.trim(),e,t.trim()))}GetCurrentNodeParent(t){const e=this.GetCurrentNode();if(e){if(C3.IsFiniteNumber(t)){const r=e.GetParentFlowchartIds(),a=r?r[t]:void 0;if(C3.IsFiniteNumber(a))return this.GetFlowchartElementById(a)}if("string"==typeof t)for(const r of e.GetParentFlowchartIds()){const e=this.GetFlowchartElementById(r);if(e.HasTags(t))return this.GetFlowchartElementById(e.GetFlowchartId())}}}GetCurrentNodeParentTag(t){const e=this.GetCurrentNodeParent(t);return e?e.GetTag():""}GetCurrentNodeParentTags(t){const e=this.GetCurrentNodeParent(t);return e?e.GetTags():""}GetCurrentNodeParentIndex(t){const e=this.GetCurrentNode();if(!e)return-1;const r=e.GetParentFlowchartIds();if(!r)return-1;const a=this.GetCurrentNodeParent(t);return a?r.indexOf(a.GetFlowchartId()):-1}GetCurrentNodeParentCount(){const t=this.GetCurrentNode();if(!t)return 0;const e=t.GetParentFlowchartIds();return e?e.length:0}GetFlowchartElementById(t){return this._flowchartDataItem.GetFlowchartElementById(t)}Reset(){this._GetRootFlowchartState()._Reset(!0)}_Reset(t){if(this._GetReferenceFlowchartStates()){for(const[t,e]of this._GetReferenceFlowchartStates().entries())e._Reset(!1);this._GetReferenceFlowchartStates().clear()}if(this._referenceFlowchartStates=null,this._previousFlowchartState=null,this._previousFlowchartStateStartNode=null,this._currentReferenceFlowchartState=null,this._previousFlowchartStateTag="",this._referenceFlowchartStatesJson=null,this._currentReferenceFlowchartStateTag="",this._rootFlowchartStateTag="",this._previousFlowchartNodeIds=[],t){this._flowchartManager.SetCurrentFlowchartState(this);const t=this._startFlowchartNode.GetFlowchartId();t!==this._currentFlowchartNodeId&&this._GotoFlowchartNode(t)}else this._currentFlowchartNodeId=this._startFlowchartNode.GetFlowchartId()}GetCurrentNodeOutputCount(){const t=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);return t?t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItemCount():0}IsIndexOfDefaultOutput(t){return!(t<0)&&t===this.GetDefaultOutputIndex()}GetDefaultOutputIndex(){const t=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);if(!t)return-1;let e=t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDefault();return e?t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems().indexOf(e):-1}GetCurrentNodeOutputNameAt(t){const e=this._GetFlowchartNodeOutputAt(t);return e?e.GetName():""}GetCurrentNodeOutputValueAt(t){let e;return C3.IsFiniteNumber(t)&&(e=this._GetFlowchartNodeOutputAt(t)),"string"==typeof t&&(e=this._GetFlowchartNodeOutputByName(t)),"number"!=typeof t&&"string"!=typeof t&&console.warn("[Flowcharts] unexpected argument type in GetCurrentNodeOutputValueAt expression"),e?e.GetValue():""}_MaybeByPassNodes(t,e){if(t.GetEnable())return t.GetFlowchartId();{const r=t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDefault();if(!r)return e.GetFlowchartId();const a=r.GetConnectedFlowchartNodeFlowchartId();if(!C3.IsFiniteNumber(a))return e.GetFlowchartId();const o=this.GetFlowchartElementById(a);return o?this._MaybeByPassNodes(o,e):e.GetFlowchartId()}}_MaybeByPassNodesInReferenceFlowchart(t,e){if(t.GetEnable()){if("reference"===t.GetType()){const e=t.GetReferenceFlowchartName(),r=t.GetReferenceFlowchartStartNodeTag(),a=this._flowchartManager.GetFlowchartDataItemByName(e);if(!a)return[-1,null];const o=a.GetFlowchartNodeByTags(r);return o?this._MaybeByPassNodesInReferenceFlowchart(o,a):this._MaybeByPassNodesInReferenceFlowchart(a.GetFlowchartStartNode(),a)}return[t.GetFlowchartId(),e]}{const r=t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDefault();if(!r)return[-1,null];const a=r.GetConnectedFlowchartNodeFlowchartId();if(!C3.IsFiniteNumber(a))return[-1,null];const o=e.GetFlowchartElementById(a);return o?this._MaybeByPassNodesInReferenceFlowchart(o,e):[-1,null]}}_ProcessAllByPasses(t,e){let r=this.GetFlowchartElementById(t);if(r){if(!r.GetEnable()){const e=this.GetFlowchartElementById(this._currentFlowchartNodeId);t=this._MaybeByPassNodes(r,e)}if(C3.IsFiniteNumber(t)&&t!==this._currentFlowchartNodeId)if(r=this.GetFlowchartElementById(t),"reference"===r.GetType()){const a=r.GetReferenceFlowchartName(),o=r.GetReferenceFlowchartStartNodeTag(),h=this._flowchartManager.GetFlowchartDataItemByName(a);let s=h.GetFlowchartNodeByTags(o);if(s){const r=this._MaybeByPassNodesInReferenceFlowchart(s,h);if(-1===r[0])return;e(this._currentFlowchartNodeId,t,r[1],r[0])}else e(this._currentFlowchartNodeId,t)}else e(this._currentFlowchartNodeId,t)}}GotoNextFlowchartNode(t){let e;if(C3.IsFiniteNumber(t)&&(e=this._GetFlowchartNodeOutputAt(t)),"string"==typeof t&&(e=this._GetFlowchartNodeOutputByName(t)),!e)return;let r=e.GetConnectedFlowchartNodeFlowchartId();C3.IsFiniteNumber(r)&&this._ProcessAllByPasses(r,(t,e,r,a)=>{this._previousFlowchartNodeIds.push(t),this._GotoFlowchartNode(e,r,a)})}GotoNextFlowchartNodeDefault(){const t=this._GetFlowchartNodeOutputDefault();if(!t)return;const e=t.GetConnectedFlowchartNodeFlowchartId();C3.IsFiniteNumber(e)&&this._ProcessAllByPasses(e,(t,e,r,a)=>{this._previousFlowchartNodeIds.push(t),this._GotoFlowchartNode(e,r,a)})}GotoAnyFlowchartNode(t){const e=this._flowchartDataItem.GetFlowchartNodeByTags(t);if(!e)return;const r=e.GetFlowchartId();C3.IsFiniteNumber(r)&&this._ProcessAllByPasses(r,(t,e,r,a)=>{this._previousFlowchartNodeIds.push(t),this._GotoFlowchartNode(e,r,a)})}GotoPreviousFlowchartNode(){const t=this._previousFlowchartNodeIds.pop();C3.IsFiniteNumber(t)?this._GotoFlowchartNode(t):this._GetPreviousFlowchartState()&&(this._flowchartManager.SetCurrentFlowchartState(this._GetPreviousFlowchartState(),!0,!1,!1),this._GetPreviousFlowchartState()._GotoFlowchartNode(this._GetPreviousFlowchartStateStartNodeId()),this._GetRootFlowchartState()._SetCurrentReferenceFlowchart(this._GetPreviousFlowchartState()))}GotoParentFlowchartNode(t){if(!this.GetCurrentNode())return;const e=this.GetCurrentNodeParent(t);if(e){if(!e.GetEnable())return;const t=e.GetFlowchartId();if(!C3.IsFiniteNumber(t))return;this._previousFlowchartNodeIds.push(this._currentFlowchartNodeId),this._GotoFlowchartNode(e.GetFlowchartId())}}HasOutput(t){if(C3.IsFiniteNumber(t)){return!!this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId).GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems()[t]}if("string"==typeof t){const e=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId).GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems();for(let r=0;r0}PushIsTriggerState(){this._triggerCount++}PopIsTriggerState(){this._triggerCount--,0===this._triggerCount&&this._markForRelease&&this._flowchartManager.RemoveFlowchartState(this)}_GotoFlowchartNode(t,e,r){const a=this._currentFlowchartNodeId,o=this.GetPluginInstance().GetInstance();this.PushIsTriggerState(),this._flowchartManager.PushFlowchartState(this),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeAnyNodeChange,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeTaggedNodeChange,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeAnyNodeChangeInFlowchart,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeTaggedNodeChangeInFlowchart,o),this._currentFlowchartNodeId=t;let h=this.GetFlowchartElementById(this._currentFlowchartNodeId);if("dictionary"===h.GetType())this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChange,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChange,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChangeInFlowchart,o),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChangeInFlowchart,o);if(this._flowchartManager.PopFlowchartState(),this.PopIsTriggerState(),!this.WasReleased()&&(h=this.GetFlowchartElementById(this._currentFlowchartNodeId),"reference"===h.GetType())){const t=e?e.GetName():h.GetReferenceFlowchartName();if(this._HasReferenceFlowchartState(h)){this._previousFlowchartNodeIds.pop();const t=this._GetReferenceFlowchartState(h);this._flowchartManager.SetCurrentFlowchartState(t,!0,!0,!1),t._SetPreviousFlowchart(this,a);this._GetRootFlowchartState()._SetCurrentReferenceFlowchart(t)}else{const e="number"==typeof r?r:h.GetReferenceFlowchartStartNodeTag();if(t){this._previousFlowchartNodeIds.pop();let r=h.GetReferenceFlowchartTag();if(r){let t=this._flowchartManager.GetFlowchartState(r);for(;t;)r=C3.IncrementNumberAtEndOf(r),t=this._flowchartManager.GetFlowchartState(r)}else{r=`${t}-ref`;let e=this._flowchartManager.GetFlowchartState(r);for(;e;)r=C3.IncrementNumberAtEndOf(r),e=this._flowchartManager.GetFlowchartState(r)}const o=this._flowchartManager.AddFlowchartState(t,e,r,this._pluginInstance,!0);o._SetPreviousFlowchart(this,a),this._SetReferenceFlowchartState(h,o);const s=this._GetRootFlowchartState();o._SetRootFlowchartState(s),s._SetCurrentReferenceFlowchart(o)}}}}_GetFlowchartNodeOutputDefault(){const t=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);return t?t.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDefault():null}_GetFlowchartNodeOutputAt(t){const e=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);if(!e)return null;const r=e.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItems();if(!r)return null;const a=r[t];return a||null}_GetFlowchartNodeOutputByName(t){const e=this._flowchartDataItem.GetFlowchartElementById(this._currentFlowchartNodeId);if(!e)return null;const r=e.GetFlowchartNodeOutputData().GetFlowchartNodeOutputDataItemByName(t);return r||null}_SetStartFlowchartNode(t){if("number"==typeof t){let e=this.GetFlowchartElementById(t);e||(e=this._flowchartDataItem.GetFlowchartStartNode()),this._startFlowchartNode=e}else if("number"==typeof this._startNodeTag){let t=this.GetFlowchartElementById(this._startNodeTag);t||(t=this._flowchartDataItem.GetFlowchartStartNode()),this._startFlowchartNode=t}else{let t=this._flowchartDataItem.GetFlowchartNodeByTags(this._startNodeTag);t||(t=this._flowchartDataItem.GetFlowchartStartNode()),this._startFlowchartNode=t}}_SaveToJson(){return this._markForRelease?null:{"flowchartName":this._flowchartName,"flowchartTag":this._tag,"startNodeTag":this._startNodeTag,"currentNodeId":this._currentFlowchartNodeId,"previousNodeIds":this._previousFlowchartNodeIds,"pluginUID":this._pluginInstance.GetInstance().GetUID(),"reference":{"previousFlowchartTag":this._GetPreviousFlowchartState()?this._GetPreviousFlowchartState().GetTag():"","previousStartNodeId":C3.IsFiniteNumber(this._GetPreviousFlowchartStateStartNodeId())?this._GetPreviousFlowchartStateStartNodeId():NaN,"referencesJson":this._GetFlowchartReferencesJson(),"currentReferenceFlowchartTag":this.GetCurrentReferenceFlowchart()?this.GetCurrentReferenceFlowchart().GetTag():"","rootFlowchartTag":this._GetRootFlowchartState()?this._GetRootFlowchartState().GetTag():""}}}_GetFlowchartReferencesJson(){if(!this._HasReferenceFlowchartStates())return null;const t=[];for(const[e,r]of this._GetReferenceFlowchartStates().entries())t.push({"flowchartElementId":e.GetFlowchartId(),"flowchartStateTag":r.GetTag()});return t.length?t:null}_LoadFromJson(t){if(t){if(this._flowchartName=t["flowchartName"],this._tag=t["flowchartTag"],this._startNodeTag=t["startNodeTag"],this._currentFlowchartNodeId=t["currentNodeId"],this._previousFlowchartNodeIds=t["previousNodeIds"],this._pluginUID=t["pluginUID"],t.hasOwnProperty("reference")){const e=t["reference"];this._previousFlowchartStateTag=e["previousFlowchartTag"],this._previousFlowchartStateStartNodeId=e["previousStartNodeId"],this._referenceFlowchartStatesJson=e["referencesJson"],this._currentReferenceFlowchartStateTag=e["currentReferenceFlowchartTag"],this._rootFlowchartStateTag=e["rootFlowchartTag"]}this._SetStartFlowchartNode()}}_GetPreviousFlowchartState(){return"string"==typeof this._previousFlowchartStateTag&&this._previousFlowchartStateTag&&(this._previousFlowchartState=this._flowchartManager.GetFlowchartState(this._previousFlowchartStateTag),this._previousFlowchartStateTag=""),this._previousFlowchartState}_GetPreviousFlowchartStateStartNodeId(){return this._previousFlowchartStateStartNodeId}_SetPreviousFlowchart(t,e){this._previousFlowchartState=t,this._previousFlowchartStateStartNodeId=e}GetCurrentReferenceFlowchart(){return"string"==typeof this._currentReferenceFlowchartStateTag&&this._currentReferenceFlowchartStateTag&&(this._currentReferenceFlowchartState=this._flowchartManager.GetFlowchartState(this._currentReferenceFlowchartStateTag),this._currentReferenceFlowchartStateTag=""),this._currentReferenceFlowchartState}_SetCurrentReferenceFlowchart(t){this._currentReferenceFlowchartState=t,this._currentReferenceFlowchartState===this&&(this._currentReferenceFlowchartState=null)}_GetRootFlowchartState(){return"string"==typeof this._rootFlowchartStateTag&&this._rootFlowchartStateTag&&(this._rootFlowchartState=this._flowchartManager.GetFlowchartState(this._rootFlowchartStateTag),this._rootFlowchartStateTag=""),this._rootFlowchartState?this._rootFlowchartState:this}_SetRootFlowchartState(t){this._rootFlowchartState=t}_HasReferenceFlowchartStates(){return this._RebuildReferenceFlowchartStates(),!!this._referenceFlowchartStates}_HasReferenceFlowchartState(t){return this._RebuildReferenceFlowchartStates(),this._referenceFlowchartStates&&this._referenceFlowchartStates.has(t)}_RebuildReferenceFlowchartStates(){if(this._referenceFlowchartStatesJson){this._referenceFlowchartStates&&this._referenceFlowchartStates.clear(),this._referenceFlowchartStates||(this._referenceFlowchartStates=new Map);for(const t of this._referenceFlowchartStatesJson){const e=this._flowchartManager.GetFlowchartState(t["flowchartStateTag"]),r=e.GetFlowchartElementById(t["flowchartElementId"]);this._referenceFlowchartStates.set(r,e)}this._referenceFlowchartStatesJson=null}}_GetReferenceFlowchartStates(){return this._RebuildReferenceFlowchartStates(),this._referenceFlowchartStates}_GetReferenceFlowchartState(t){return this._RebuildReferenceFlowchartStates(),this._referenceFlowchartStates.get(t)}_SetReferenceFlowchartState(t,e){this._referenceFlowchartStates||(this._referenceFlowchartStates=new Map),this._referenceFlowchartStates.set(t,e)}}; } // flowcharts/state/flowchartStateManager.js { const C3=self.C3;C3.FlowchartStateManager=class{constructor(t){this._runtime=t,this._flowchartStates=new Map,this._currentFlowchartState=null,this._flowchartStateStack=[],this._on_after_load=()=>this._OnAfterLoad(),this._loadJson=null}Release(){C3.clearArray(this._flowchartStateStack),this._flowchartStateStack=null,this._flowchartStates.clear(),this._flowchartStates=null,this._currentFlowchartState=null,this._runtime=null,this._loadJson=null}GetRuntime(){return this._runtime}GetFlowchartDataItemByName(t){return this._runtime.GetFlowchartManager().GetFlowchartDataItemByName(t)}AddFlowchartState(t,e,a,r,h,s){const o=this._runtime.GetFlowchartManager().GetFlowchartDataItemByName(t);if(!o)return void console.warn(`[Flowcharts] no flowchart found with name '${t}'`);if(this._flowchartStates.has(a)){const t=this._flowchartStates.get(a);t&&this.RemoveFlowchartState(t)}const n=new C3.FlowchartState(t,a,e,o,this,r,s);return this._flowchartStates.set(a,n),h&&this.SetCurrentFlowchartState(n,!0),n}RemoveFlowchartState(t){if(t.MarkForRelease(),t.IsInTriggerState())return;const e=t.GetTag();this._flowchartStates.delete(e),t.Release(),this._currentFlowchartState===t&&(this._currentFlowchartState=null)}ResetFlowchartState(t){t.Reset()}GetFlowchartState(t){return this._flowchartStates.get(t)}PushFlowchartState(t){this._flowchartStateStack.push(t)}PopFlowchartState(){this._flowchartStateStack.pop()}SetCurrentFlowchartState(t,e=!1,a=!1,r=!0){if(r){const e=t.GetCurrentReferenceFlowchart();t=e||t}t!==this._currentFlowchartState&&(this._TriggerBeforeFlowchartChange(),this._TriggerAfterFlowchartChange(t,e,a))}GetCurrentFlowchartState(t){return"string"==typeof t?this.GetFlowchartState(t):this._flowchartStateStack.length?this._flowchartStateStack[this._flowchartStateStack.length-1]:this._currentFlowchartState}_TriggerBeforeFlowchartChange(){if(!this._currentFlowchartState)return;if(this._currentFlowchartState.WasReleased())return;const t=this._currentFlowchartState.GetPluginInstance().GetInstance();this._currentFlowchartState.PushIsTriggerState(),this.PushFlowchartState(this._currentFlowchartState),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnBeforeFlowchartChange,t),this.PopFlowchartState(),this._currentFlowchartState.PopIsTriggerState()}_TriggerAfterFlowchartChange(t,e=!1,a=!1){if(this._currentFlowchartState=t,!this._currentFlowchartState)return;if(this._currentFlowchartState.WasReleased())return;const r=this._currentFlowchartState.GetPluginInstance().GetInstance();this._currentFlowchartState.PushIsTriggerState(),this.PushFlowchartState(this._currentFlowchartState),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnFlowchartChange,r),!0!==a&&"number"!=typeof a||this._currentFlowchartState._SetStartFlowchartNode(a),e&&(this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChange,r),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChange,r),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnAnyNodeChangeInFlowchart,r),this._runtime.Trigger(C3.Plugins.Flowchart.Cnds.OnTaggedNodeChangeInFlowchart,r)),this.PopFlowchartState(),this._currentFlowchartState.PopIsTriggerState()}_SaveToJson(){return{"flowchartJsonObjects":[...this._flowchartStates.values()].map(t=>t._SaveToJson()),"currentFlowchartTag":this._currentFlowchartState?this._currentFlowchartState.GetTag():null}}_LoadFromJson(t){if(!t)return;this._loadJson=t;const e=new Map;for(const t of this._loadJson["flowchartJsonObjects"]){const a=t["flowchartTag"];if(this._flowchartStates.has(a)){const r=this._flowchartStates.get(a);r._LoadFromJson(t),e.set(a,r)}else{const a=this.AddFlowchartState(t["flowchartName"],t["startNodeTag"],t["flowchartTag"],null,!1,t["pluginUID"]);a._LoadFromJson(t),e.set(t["flowchartTag"],a)}}for(const[t,a]of this._flowchartStates.entries())e.has(t)||a.Release();this._flowchartStates.clear(),this._flowchartStates=e,this._runtime.IsLoadingState()?this._runtime.Dispatcher().addEventListener("afterload",this._on_after_load):this._OnAfterLoad()}_OnAfterLoad(){this._runtime.Dispatcher().removeEventListener("afterload",this._on_after_load);const t=this._flowchartStates.get(this._loadJson["currentFlowchartTag"]);t&&this.SetCurrentFlowchartState(t,!0),this._loadJson=null}}; } // flowcharts/data/flowchartDataManager.js { const C3=self.C3;C3.FlowchartDataManager=class{constructor(){this._flowchartDataItems=new Map}Release(){for(const t of this._flowchartDataItems.values())t.Release();this._flowchartDataItems.clear(),this._flowchartDataItems=null}Add(t){const a=new C3.FlowchartDataItem(t),s=a.GetName();this._flowchartDataItems.set(s,a)}Get(t){return this._flowchartDataItems.get(t)}HasFlowcharts(){return!!this._flowchartDataItems.size}static CreateDataItems(t,a,s,e){if(a)for(const o of a){const a=new s(o,e);t.push(a)}}}; } // flowcharts/data/flowchartData.js { const C3=self.C3,NAME=0,NODES=1;C3.FlowchartDataItem=class{constructor(t){this._name=t[0],this._flowchartNodeData=new C3.FlowchartNodeData(t[1],this)}Release(){this._flowchartNodeData.Release(),this._flowchartNodeData=null}GetFlowchartNodeData(){return this._flowchartNodeData}GetFlowchartElementById(t){return this._flowchartNodeData.GetFlowchartElementById(t)}GetFlowchartNodeByTags(t){return this._flowchartNodeData.GetFlowchartNodeByTags(t)}GetFlowchartStartNode(){return this._flowchartNodeData.GetFlowchartStartNode()}GetName(){return this._name}}; } // flowcharts/data/flowchartNodeData.js { const C3=self.C3,FLOWCHART_ID=0,TAG=1,PARENT_FLOWCHART_IDS=2,PARENT_OUTPUT_FLOWCHART_IDS=3,CHILDREN_FLOWCHART_IDS=4,OUTPUTS=5,IS_START=6,TYPE=7,DICTIONARY_ENABLE=8,REFERENCE_FLOWCHART=8,REFERENCE_FLOWCHART_START_NODE=9,REFERENCE_FLOWCHART_TAG=10,REFERENCE_FLOWCHART_ENABLE=11;class FlowchartNodeDataItem{constructor(t,e){this._flowchartNodeData=e,this._type=t[7],this._flowchartId=t[0],this._tag=t[1],this._tag?this._tags=this._tag.trim().split(" ").map(t=>t.trim()):this._tags=[],this._parentFlowchartIds=t[2],this._parentOutputFlowchartIds=null,this._childrenFlowchartIds=null,this._enable=!1,"dictionary"===this._type&&(this._parentOutputFlowchartIds=t[3],this._childrenFlowchartIds=t[4],this._enable=t[8]),this._isStart=t[6],this._referenceFlowchartName=null,this._referenceFlowchartStartNodeTag=null,this._referenceFlowchartTag=null,"reference"===this._type&&(this._referenceFlowchartName=t[8],this._referenceFlowchartStartNodeTag=t[9],this._referenceFlowchartTag=t[10],this._enable=t[11]),this._flowchartNodeOutputData=new C3.FlowchartNodeOutputData(t[5],this)}Release(){this._flowchartNodeData=null}GetFlowchartNodeData(){return this._flowchartNodeData}GetFlowchartNodeOutputData(){return this._flowchartNodeOutputData}GetFlowchartId(){return this._flowchartId}GetTag(){return this._tag}GetTags(){return this._tags}HasTags(t){if(!this._tags)return!1;if(!this._tags.length)return!1;const e=C3.FlowchartState._GetTagArray(t);return!(!e||!e.length)&&e.every(C3.FlowchartState._HasTag,this._tags)}GetIsStart(){return this._isStart}SetIsStart(t){this._isStart=!!t}CanBeStartNode(){if("dictionary"===this._type)return!0;if("reference"===this._type)return!1;throw new Error(`unexpected flowchart node type: ${this._type}`)}GetParentFlowchartIds(){return this._parentFlowchartIds}GetParentOutputFlowchartIds(){return this._parentOutputFlowchartIds}GetChildrenFlowchartIds(){return this._childrenFlowchartIds}GetType(){return this._type}GetEnable(){return this._enable}GetReferenceFlowchartName(){return this._referenceFlowchartName}GetReferenceFlowchartStartNodeTag(){return this._referenceFlowchartStartNodeTag}GetReferenceFlowchartTag(){return this._referenceFlowchartTag}}C3.FlowchartNodeData=class{constructor(t,e){this._flowchartDataItem=e,this._flowchartNodeItems=[],this._flowchartNodeItemsIdMap=new Map,this._flowchartNodeItemsTagMap=new Map,this._flowchartNodeStartItem=null,C3.FlowchartDataManager.CreateDataItems(this._flowchartNodeItems,t,FlowchartNodeDataItem,this);for(const t of this._flowchartNodeItems){const e=t.GetFlowchartId(),a=t.GetTag(),r=t.GetTags(),s=t.GetIsStart();if(this._flowchartNodeItemsIdMap.set(e,t),a)for(const e of r)this._flowchartNodeItemsTagMap.has(e)||this._flowchartNodeItemsTagMap.set(e,new Set),this._flowchartNodeItemsTagMap.get(e).add(t);s&&(this._flowchartNodeStartItem=t);const o=t.GetFlowchartNodeOutputData();for(const t of o.flowchartNodeOutputDataItems()){const e=t.GetFlowchartId();this._flowchartNodeItemsIdMap.set(e,t)}}this._flowchartNodeStartItem||this._SetStartNodeIfMissing()}Release(){this._flowchartDataItem=null;for(const t of this._flowchartNodeItems)t.Release();C3.clearArray(this._flowchartNodeItems),this._flowchartNodeItems=null}GetFlowchartDataItem(){return this._flowchartDataItem}GetFlowchartElementById(t){return this._flowchartNodeItemsIdMap.get(t)}GetFlowchartNodeByTags(t){if(!t||!t.length)return null;const e=[];for(const a of t.trim().split(" ")){let t=this._flowchartNodeItemsTagMap.get(a.trim())??new Set;if(0===t.size)return null;e.push(t)}return[...e.reduce((t,e)=>e.sizee.every(e=>e.has(t)))[0]}GetFlowchartStartNode(){return this._flowchartNodeStartItem}*flowchartNodeDataItems(){for(const t of this._flowchartNodeItems)yield t}_SetStartNodeIfMissing(){let t=0;for(const e of this.flowchartNodeDataItems())e.GetIsStart()&&t++;if(0===t){for(const t of this.flowchartNodeDataItems())if(t.CanBeStartNode()&&!t.GetIsStart())return void t.SetIsStart(!0)}else{if(1===t)return;if(t>1){let t=!0;for(const e of this.flowchartNodeDataItems())e.CanBeStartNode()&&(e.GetIsStart()&&t?t=!1:e.GetIsStart()&&!t&&e.SetIsStart(!1))}}for(const t of this.flowchartNodeDataItems())if(t.CanBeStartNode()&&t.GetIsStart())return void(this._flowchartNodeStartItem=t)}}; } // flowcharts/data/flowchartNodeOutputData.js { const C3=self.C3,FLOWCHART_ID=0,NAME=1,VALUE=2,CONNECTED_FLOWCHART_NODE_FLOWCHART_ID=3,ENABLE=4,DEFAULT=5;class FlowchartNodeDataOutputItem{constructor(t,e){this._flowchartNodeOutputData=e,this._flowchartId=t[0],this._name=t[1],this._value=t[2],this._connectedFlowchartNodeFlowchartId=t[3],this._enable=t[4],this._default=t[5]}Release(){this._flowchartNodeOutputData=null}GetFlowchartNodeOutputData(){return this._flowchartNodeOutputData}GetFlowchartId(){return this._flowchartId}GetName(){return this._name}GetValue(){return this._value}GetConnectedFlowchartNodeFlowchartId(){return this._connectedFlowchartNodeFlowchartId}GetEnable(){return this._enable}GetDefault(){return this._default}}C3.FlowchartNodeOutputData=class{constructor(t,e){this._flowchartDataNodeItem=e,this._flowchartNodeOutputItems=[],this._flowchartNodeOutputItemsNameMap=new Map,C3.FlowchartDataManager.CreateDataItems(this._flowchartNodeOutputItems,t,FlowchartNodeDataOutputItem,this),this._enabledFlowchartNodeOutputItems=this._flowchartNodeOutputItems.filter(t=>t.GetEnable());for(const t of this._enabledFlowchartNodeOutputItems)this._flowchartNodeOutputItemsNameMap.set(t.GetName(),t)}Release(){this._flowchartDataNodeItem=null;for(const t of this._flowchartNodeOutputItems)t.Release();C3.clearArray(this._flowchartNodeOutputItems),this._flowchartNodeOutputItems=null,C3.clearArray(this._enabledFlowchartNodeOutputItems),this._enabledFlowchartNodeOutputItems=null}GetFlowchartNodeDataItem(){return this._flowchartDataNodeItem}GetFlowchartNodeOutputDataItemCount(){return this._enabledFlowchartNodeOutputItems.length}GetFlowchartNodeOutputDataItems(){return this._enabledFlowchartNodeOutputItems}GetFlowchartNodeOutputDataItemByName(t){return this._flowchartNodeOutputItemsNameMap.get(t)}GetFlowchartNodeOutputDefault(){for(const t of this._enabledFlowchartNodeOutputItems)if(t.GetDefault())return t}*flowchartNodeOutputDataItems(){for(const t of this._enabledFlowchartNodeOutputItems)yield t}}; } // models3d/model3dManager.js { const C3=self.C3;C3.Model3dManager=class{#e;#t=new Map;constructor(e){this.#e=e}Release(){for(const e of this.#t.values())e.Release();this.#t.clear(),this.#t=null,this._runtime=null}GetRuntime(){return this._runtime}Create(e){const t=new C3.Model3dDataItem(e,this.#e);this.#t.set(t.GetName(),t)}*GetModel3dDataItems(){yield*this.#t.values()}GetModel3dDataItemByName(e){return this.#t.get(e)}HasModels3d(){return this.#t.size}static CreateDataItems(e,t,s,d){if(t)for(const l of t){const t=new s(l,d);e.push(t)}}}; } // models3d/model3dData.js { const C3=self.C3,NAME=0,OFFSET=1,ROTATION=2,SCALE=3;C3.Model3dDataItem=class{#e;#t=null;#s=null;#a=null;#i=null;#n=null;#o=null;#l=null;#r=null;#h=!1;constructor(e,t){this.#e=e[0],this.#r=(async()=>{const e=new C3.ZipFile;try{const s=await t.GetAssetManager().FetchBlob(`3dmodels/${this.#e}.zip`);await e.LoadFromBlob(s,t);const a=await e.ReadBlob(e.GetEntry(`${this.#e}.bin`)),i=await a.arrayBuffer(),n=new C3.Model3dBinaryBlobSerializer,o=await n.Deserialize(i);this.#t=new C3.Model3dAnimationData(o["animations"],this),this.#s=new C3.Model3dMeshData(o["meshes"],this),this.#a=new C3.Model3dObjectData(o["objects"],this),this.#i=new C3.Model3dObjectData(o["bones"],this),await this.#s.OnCreate(),this.#h=!0}finally{e.Release()}})(),this.#n=new globalThis.Float32Array(C3.toArrayLike(e[1])),this.#o=new globalThis.Float32Array(C3.toArrayLike(e[2])),this.#l=new globalThis.Float32Array(C3.toArrayLike(e[3]))}Release(){this.#t.Release(),this.#t=null,this.#s.Release(),this.#s=null,this.#a.Release(),this.#a=null,this.#i.Release(),this.#i=null}IsReady(){return this.#r}Resolved(){return this.#h}GetName(){return this.#e}GetAnimations(){return this.#t.GetAnimationsMap()}GetMeshes(){return this.#s.GetMeshesMap()}GetObjects(){return this.#a.GetObjectsMap()}GetBones(){return this.#i.GetObjectsMap()}*GetTextures(){for(const e of this.GetMeshes().values())yield e.GetModel3dTexture()}GetObjectById(e){if(this.GetMeshes())for(const t of this.GetMeshes().values())if(t.GetId()===e)return t;if(this.GetObjects())for(const t of this.GetObjects().values())if(t.GetId()===e)return t;if(this.GetBones())for(const t of this.GetBones().values())if(t.GetId()===e)return t}GetOffset(){return this.#n}GetRotation(){return this.#o}GetScale(){return this.#l}}; } // models3d/model3dAnimationData.js { const C3=self.C3;C3.Model3dAnimationDataItem=class{#t;#a;#e;#i;constructor(t){this.#t=t["id"],this.#a=t["name"],this.#e=t["duration"],this.#i=t["tracks"].map(t=>new TrackDataItem(t))}Release(){for(const t of this.#i)t.Release();this.#i=null}GetId(){return this.#t}GetName(){return this.#a}GetDuration(){return this.#e}GetTracks(){return this.#i}};class TrackDataItem{#s;#a;#n;#o;#r;#m;constructor(t){this.#s=t["type"],this.#a=t["name"],this.#n=new globalThis.Float32Array(C3.toArrayLike(t["times"])),this.#o=new globalThis.Float32Array(C3.toArrayLike(t["values"])),this.#r=t["interpolation"],this.#m=t["lookup-id"]}Release(){this.#n=null,this.#o=null}GetType(){return this.#s}GetName(){return this.#a}GetTimes(){return this.#n}GetValues(){return this.#o}GetInterpolation(){return this.#r}GetLookupUUID(){return this.#m}static get STEP_INTERPOLATION(){return"step"}static get LINEAR_INTERPOLATION(){return"linear"}static get CUBIC_SPLINE_INTERPOLATION(){return"cubic-spline"}}C3.Model3dAnimationData=class{#l;#h;#d;constructor(t,a){this.#l=a,this.#h=[],C3.Model3dManager.CreateDataItems(this.#h,t,C3.Model3dAnimationDataItem,this)}Release(){this.#l=null;for(const t of this.#h)t.Release();C3.clearArray(this.#h),this.#h=null,this.#d&&this.#d.clear(),this.#d=null}GetModel3dDataItem(){return this.#l}GetAnimationsMap(){if(this.#d)return this.#d;this.#d=new Map;for(const t of this.#h)this.#d.set(t.GetName(),t);return this.#d}}; } // models3d/model3dObjectData.js { const C3=self.C3;C3.Model3dObjectDataItem=class{#t;#e;#a;#i;#s;#r;#n;#o;constructor(t){this.#t=t["id"],this.#e=t["parent-id"],this.#a=t["name"],this.#i=new globalThis.Float32Array(C3.toArrayLike(t["position"])),this.#s=new globalThis.Float32Array(C3.toArrayLike(t["quaternion"])),this.#r=new globalThis.Float32Array(C3.toArrayLike(t["scale"])),this.#n=new globalThis.Float32Array(C3.toArrayLike(t["bind-matrix"])),this.#o=new globalThis.Float32Array(C3.toArrayLike(t["bind-inverse-matrix"]))}Release(){this.#i=null,this.#s=null,this.#r=null,this.#n=null,this.#o=null}GetId(){return this.#t}GetParentId(){return this.#e}GetName(){return this.#a}GetPosition(){return this.#i}GetQuaternion(){return this.#s}GetScale(){return this.#r}GetBindMatrix(){return this.#n}GetBindMatrixInverse(){return this.#o}},C3.Model3dObjectData=class{#l;#d;#h;constructor(t,e){this.#l=e,this.#d=[],C3.Model3dManager.CreateDataItems(this.#d,t,C3.Model3dObjectDataItem,this)}Release(){this.#l=null;for(const t of this.#d)t.Release();C3.clearArray(this.#d),this.#d=null,this.#h&&this.#h.clear(),this.#h=null}GetModel3dDataItem(){return this.#l}GetObjectsMap(){if(this.#h)return this.#h;this.#h=new Map;for(const t of this.#d)this.#h.set(t.GetName(),t);return this.#h}}; } // models3d/model3dMeshData.js { const C3=self.C3;C3.Model3dMeshDataItem=class extends C3.Model3dObjectDataItem{#t;#e;#a;#s;#n;#i;#r;#o;#d;#h;#l;#D;#m;#u;constructor(t,e){super(t),this.#u=e,t["vertex-data"]&&(this.#t=new globalThis.Float32Array(C3.toArrayLike(t["vertex-data"]))),t["uv-data"]&&(this.#e=new globalThis.Float32Array(C3.toArrayLike(t["uv-data"]))),t["index-data"]&&(this.#a=new globalThis.Float32Array(C3.toArrayLike(t["index-data"]))),this.#s=t["is-skinned"],t["skin-index-data"]&&(this.#n=new globalThis.Float32Array(C3.toArrayLike(t["skin-index-data"]))),t["skin-weigth-data"]&&(this.#i=new globalThis.Float32Array(C3.toArrayLike(t["skin-weigth-data"]))),t["color-data"]&&(this.#r=new globalThis.Float32Array(C3.toArrayLike(t["color-data"]))),t["render-type"]&&(this.#D=t["render-type"]),t["bones-data"]&&(this.#o=t["bones-data"].map(t=>new Bone(t))),this.#d=t["bone-inverse-matrices"],t["bone-bind-data"]&&(this.#h=t["bone-bind-data"].map(t=>new Bone(t))),this.#l=new C3.Model3dTextureDataItem(t["texture"])}Release(){if(super.Release(),this.#t=null,this.#e=null,this.#a=null,this.#n=null,this.#i=null,this.#r=null,this.#o)for(const t of this.#o)t.Release();if(this.#o=null,this.#d=null,this.#h)for(const t of this.#h)t.Release();this.#h=null,this.#m&&this.#m.clear(),this.#m=null,this.#l&&this.#l.Release()}OnCreate(){for(const t of this.#u.GetAnimations().values()){const e=t.GetTracks(),a=e.some(t=>{const e=this.#u.GetObjectById(t.GetLookupUUID());if(!e)return!1;let a=this;for(;a;){if(a.GetId()===e.GetId())return!0;const t=a.GetParentId();a=t?this.#u.GetObjectById(t):null}return!1});let s=!1;if(this.#o)for(const t of this.#o)s||=e.some(e=>{const a=this.#u.GetObjectById(e.GetLookupUUID());return!(!a||a.GetId()!==t.GetId())});(a||s)&&(this.#m||(this.#m=new Map),this.#m.set(t.GetName(),t))}}GetAnimationsMap(){return this.#m}GetVertexData(){return this.#t}GetUVData(){return this.#e}GetIndexData(){return this.#a}IsSkinned(){return this.#s}GetSkinIndexData(){return this.#n}GetSkinWeigthData(){return this.#i}GetColorData(){return this.#r}GetRenderType(){return this.#D}GetBoneData(){return this.#o}GetBoneInverseMatricesData(){return this.#d}GetBoneBindPoseData(){return this.#h}GetModel3dTexture(){return this.#l}};class Bone{#I;#c;#x;#M;#b;#p;#G;#k;constructor(t){this.#I=t["id"],this.#c=t["parent-id"],this.#x=t["index"],this.#M=t["parent-index"],this.#b=t["name"],this.#p=new globalThis.Float32Array(C3.toArrayLike(t["position"])),this.#G=new globalThis.Float32Array(C3.toArrayLike(t["quaternion"])),this.#k=new globalThis.Float32Array(C3.toArrayLike(t["scale"]))}Release(){this.#p=null,this.#G=null,this.#k=null}GetId(){return this.#I}GetParentId(){return this.#c}GetIndex(){return this.#x}GetParentIndex(){return this.#M}GetName(){return this.#b}GetPosition(){return this.#p}GetQuaternion(){return this.#G}GetScale(){return this.#k}}C3.Model3dMeshData=class{#u;#y;#C;constructor(t,e){this.#u=e,this.#y=[],C3.Model3dManager.CreateDataItems(this.#y,t,C3.Model3dMeshDataItem,e)}Release(){this.#u=null;for(const t of this.#y)t.Release();C3.clearArray(this.#y),this.#y=null,this.#C&&this.#C.clear(),this.#C=null}GetModel3dDataItem(){return this.#u}GetMeshesMap(){if(this.#C)return this.#C;this.#C=new Map;for(const t of this.#y)this.#C.set(t.GetName(),t);return this.#C}OnCreate(){for(const t of this.#y)t.OnCreate()}}; } // models3d/model3dTextureData.js { const C3=self.C3,uniqueTextureDataItems=new Map;C3.Model3dTextureDataItem=class{#e;#t;#r;#s;#a;#i;#h;#o;#u;#n;#I;#m;#d;#T;constructor(e){uniqueTextureDataItems.has(e["url"])?this.#T=uniqueTextureDataItems.get(e["url"]):(this.#o=new C3.ImageInfo,this.#o.LoadData(e),uniqueTextureDataItems.set(e["url"],this));const t=e["color"];this.#e=e["url"],this.#t=e["name"],this.#r=e["color"]?new C3.Color(t[0],t[1],t[2],t[3]):null,this.#s=e["wrap-x"],this.#a=e["wrap-y"],this.#i=e["has-content"],this.#h=e["content-type"],this.#u=!1,this.#n=!1,this.#I=!1,this.#m=!1}Release(){this.#T||(this.#o.Release(),uniqueTextureDataItems.delete(this.#e)),this.#o=null,this.#T=null}HasContent(){return this.#i}GetContentType(){return this.#h}GetColor(){return this.#r}GetOpacity(){return this.#r?this.#r.getA():1}GetImageInfo(){return this.#T?this.#T.GetImageInfo():this.#o}GetSpriteSheetWidth(){if(this.#T)return this.#T.GetSpriteSheetWidth();const e=this.GetImageInfo().GetSheetWidth();return-1===e?NaN:e}GetSpriteSheetHeight(){if(this.#T)return this.#T.GetSpriteSheetHeight();const e=this.#o.GetSheetHeight();return-1===e?NaN:e}GetSpriteSheetOffsetX(){return this.#T?this.#T.GetSpriteSheetOffsetX():this.#o.GetOffsetX()}GetSpriteSheetOffsetY(){return this.#T?this.#T.GetSpriteSheetOffsetY():this.#o.GetOffsetY()}GetWidthInSpriteSheet(){return this.#T?this.#T.GetWidthInSpriteSheet():this.#o.GetWidth()}GetHeightInSpriteSheet(){return this.#T?this.#T.GetHeightInSpriteSheet():this.#o.GetHeight()}IsContentReady(){return this.#T?this.#T.IsContentReady():this.#n&&!this.#u}IsLoadingTexture(){return this.#T?this.#T.IsLoadingTexture():this.#I}LoadAsset(e,t){if(this.#T)return this.#T.LoadAsset(e,t);!this.#m&&this.HasContent()&&this.#o.LoadAsset(e,t),this.#m=!0}GetTexture(e,t,r){if(this.#T)return this.#T.GetTexture(e,t,r);if(!this.HasContent()||this.#u)return null;if(this.#n)return this.#o.GetTexture();if(!this.#I&&!this.#n){this.LoadAsset(e,r),r?(r.wrapX=this.#s,r.wrapY=this.#a):r={wrapX:this.#s,wrapY:this.#a},this.#I=!0;const s=this.#o.GetImageAsset(),a=s.IsLoaded()?s.GetBlob():this.#o.GetImageAsset().Load();this.#d=a.then(()=>this.#o.LoadStaticTexture(t,r)).then(e=>{this.#u=!1,this.#I=!1,this.#n=!0}).catch(e=>{this.#u=!0,this.#I=!1,this.#n=!1})}return this.#o.GetTexture()}ReleaseTexture(){if(this.#T)return this.#T.ReleaseTexture();!this.#I&&this.#o&&this.#o.ReleaseTexture(),this.#u=!1,this.#I=!1,this.#n=!1}HasTexture(){return this.#T?this.#T.HasTexture():!!this.#o&&!!this.#o?.GetImageAsset()?.GetTexture()}HadTextureError(){return this.#T?this.#T.HadTextureError():this.#u}IsReady(){return this.#d}}; } // events/stacks/solStack.js { const C3=self.C3;C3.SolStack=class extends C3.DefendedBase{constructor(t){super(),this._objectClass=t,this._stack=[],this._stack.push(C3.New(C3.Sol,this)),this._index=0,this._current=this._stack[0]}Release(){for(const t of this._stack)t.Release();C3.clearArray(this._stack),this._current=null,this._objectClass=null}GetObjectClass(){return this._objectClass}GetCurrentSol(){return this._current}GetOneBelowCurrentSol(){return this._stack[this._index-1]}Clear(){this.GetCurrentSol().Clear()}PushClean(){const t=this._stack,s=++this._index;if(s===t.length){const s=C3.New(C3.Sol,this);t.push(s),this._current=s}else{const e=t[s];e.Reset(),this._current=e}}PushCopy(){const t=this._stack,s=++this._index;s===t.length&&t.push(C3.New(C3.Sol,this));const e=t[s];e.Copy(t[s-1]),this._current=e}Pop(){this._current=this._stack[--this._index]}RemoveInstances(t){const s=this._stack;for(let e=0,n=s.length;e=0}GetCurrent(){return this._stack[this._index]}Push(){if(++this._index,this._index===this._stack.length){const t=C3.New(C3.Loop,this);return this._stack.push(t),t}{const t=this._stack[this._index];return t.Reset(),t}}Pop(){--this._index}FindByName(t){const e=this._stack;for(let s=this._index;s>=0;--s){const n=e[s];if(n.GetName()===t)return n}return null}_GetStack(){return this._stack.slice(0,this._index+1)}}; } // events/stacks/loop.js { const C3=self.C3;C3.Loop=class extends C3.DefendedBase{constructor(e){super(),this._loopStack=e,this._name="",this._index=0,this._isStopped=!1,this._end=NaN}Reset(){this._name="",this._index=0,this._isStopped=!1,this._end=NaN}SetName(e){this._name=e}GetName(){return this._name}SetIndex(e){this._index=e}GetIndex(){return this._index}Stop(){this._isStopped=!0}IsStopped(){return this._isStopped}SetEnd(e){this._end=e}GetEnd(){return this._end}}; } // events/stacks/arrayStack.js { const C3=self.C3;C3.ArrayStack=class extends C3.DefendedBase{constructor(){super(),this._stack=[],this._index=-1}Release(){C3.clearArray(this._stack)}GetCurrent(){return this._stack[this._index]}Push(){if(++this._index,this._index===this._stack.length){const s=[];return this._stack.push(s),s}return this._stack[this._index]}Pop(){--this._index}}; } // events/eventSheetManager.js { const C3=self.C3,assert=self.assert;function SortSolArray(t,e){return t.GetIndex()-e.GetIndex()}function IsSolArrayIdentical(t,e){for(let s=0,n=t.length;sthis._InvokeFunctionFromJS(t,e)}Release(){this.ClearAllScheduledWaits(),this._eventStack.Release(),this._eventStack=null,this._localVarStack.Release(),this._localVarStack=null,C3.clearArray(this._queuedTriggers),C3.clearArray(this._queuedDebugTriggers),this._runtime=null,C3.clearArray(this._allSheets),this._sheetsByName.clear()}Create(t){const e=C3.New(C3.EventSheet,this,t);this._allSheets.push(e),this._sheetsByName.set(e.GetName().toLowerCase(),e)}_AddTriggerToPostInit(t){this._triggersToPostInit.push(t)}_PostInit(){for(const t of this._customActionBlocksMap.values())t._CheckOverrideState();for(const t of this._functionBlocksByName.values())t._PostInit();for(const t of this._customActionBlocksMap.values())t._PostInit();for(const t of this._allSheets)t._PostInit();for(const t of this._allSheets)t._UpdateDeepIncludes();for(const t of this._triggersToPostInit)t._PostInit(!1);C3.clearArray(this._triggersToPostInit),this._localVarStack._SetInitialValues(this._localVarInitialValues)}GetRuntime(){return this._runtime}GetEventSheetByName(t){return this._sheetsByName.get(t.toLowerCase())||null}_RegisterGroup(t){this._allGroups.push(t),this._groupsByName.set(t.GetGroupName(),t)}_RegisterEventBlock(t){this._blocksBySid.set(t.GetSID(),t)}_RegisterCondition(t){this._cndsBySid.set(t.GetSID(),t)}_RegisterAction(t){this._actsBySid.set(t.GetSID(),t)}_RegisterFunctionBlock(t){switch(t.GetFunctionType()){case 0:this._functionBlocksByName.set(t.GetFunctionName().toLowerCase(),t);break;case 1:this._customActionBlocksMap.set(t.GetFunctionName().toLowerCase(),t)}}_RegisterEventVariable(t){this._eventVarsBySid.set(t.GetSID(),t),t.IsGlobal()?this._allGlobalVars.push(t):this._allLocalVars.push(t)}_DeduplicateSolModifierList(t){t.length>=2&&t.sort(SortSolArray);let e=this._allUniqueSolModifiers.get(t.length);e||(e=[],this._allUniqueSolModifiers.set(t.length,e));for(let s=0,n=e.length;sn=t);return this._queuedDebugTriggers.push([t,e,s,n]),i}*_RunQueuedDebugTriggersGen(){if(this._runtime.HitBreakpoint())throw new Error("should not be in breakpoint");const t=this._runtime.GetLayoutManager();for(;this._queuedDebugTriggers.length;){const[e,s,n,i]=this._queuedDebugTriggers.shift();i(yield*this._DebugTrigger(t,e,s,n))}}async RunQueuedDebugTriggersAsync(){for(const t of this._RunQueuedDebugTriggersGen())await this._runtime.DebugBreak(t)}_FastTrigger(t,e,s,n){let i=!1;const r=t.GetMainRunningLayout(),o=r.GetEventSheet();if(!o)return;this._executingTriggerDepth++,this._runtime.PushCurrentLayout(r);const a=o.deepIncludes();for(let t=0,r=a.length;t0}_IncTriggerDepth(){return++this._executingTriggerDepth}_DecTriggerDepth(){--this._executingTriggerDepth}IsRunningEvents(){return this._runningEventsDepth>0}IsInEventEngine(){return this.IsRunningEvents()||this.IsInTrigger()}_RunQueuedTriggers(t){for(const[e,s,n]of this._queuedTriggers)this._Trigger(t,e,s,n);C3.clearArray(this._queuedTriggers)}BlockFlushingInstances(t){t?this._blockFlushingDepth++:this._blockFlushingDepth--}IsFlushingBlocked(){return this._blockFlushingDepth>0}ClearSol(t){for(let e=0,s=t.length;et.ShouldRelease());for(const e of t)e.Release()}ClearAllScheduledWaits(){for(const t of this._scheduledWaits)t.Release();C3.clearArray(this._scheduledWaits)}_OnInstancesReleased(t){for(const e of this._scheduledWaits)e.RemoveInstances(t);for(const e of t){const t=this._instSignals.get(e);if(this._instSignals.delete(e),t)for(const{resolve:e}of t.signalPromises.values())e(!0)}}AddAsyncActionPromise(t){this._asyncActionPromises.push({promise:t,triggerDepth:this.GetTriggerDepth()})}ClearAsyncActionPromises(){C3.clearArray(this._asyncActionPromises)}GetPromiseForAllAsyncActions(){const t=this.GetTriggerDepth(),e=Promise.all(this._asyncActionPromises.filter(e=>e.triggerDepth===t).map(t=>t.promise));return this._asyncActionPromises=this._asyncActionPromises.filter(e=>e.triggerDeptht=e);return this._signalPromises.set(e,{promise:s,resolve:t}),s}}GetCurrentSignalTag(){if(0===this._signalTags.length)throw new Error("not in a signal");return this._signalTags.at(-1)}_GetInstanceSignalState(t){let e=this._instSignals.get(t);return e||(e={signalTags:[],signalPromises:new Map},this._instSignals.set(t,e)),e}InstanceSignal(t,e){const s=this._GetInstanceSignalState(t),n=e.toLowerCase();s.signalTags.push(n),this._runtime.Trigger(t.GetPlugin().GetConstructor().Cnds.OnInstanceSignal,t),s.signalTags.pop();for(const e of this._runtime.GetEventSheetManager().scheduledWaits())e.IsInstanceSignals()&&e.GetSignalTag()===n&&e.SetInstanceSignalled(t);const i=s.signalPromises.get(n);i&&(i.resolve(!1),s.signalPromises.delete(n)),0===s.signalTags.length&&0===s.signalPromises.size&&this._instSignals.delete(t)}WaitForInstanceSignal(t,e){const s=this._GetInstanceSignalState(t),n=e.toLowerCase(),i=s.signalPromises.get(n);if(i)return i.promise;{let t=null;const e=new Promise(e=>t=e);return s.signalPromises.set(n,{promise:e,resolve:t}),e}}GetCurrentInstanceSignalTag(t){const e=this._GetInstanceSignalState(t);if(!e||0===e.signalTags.length)throw new Error("not in a signal");return e.signalTags.at(-1)}_SaveToJson(){return{"groups":this._SaveGroupsToJson(),"cnds":this._SaveCndsToJson(),"acts":this._SaveActsToJson(),"vars":this._SaveVarsToJson(),"waits":this._SaveScheduledWaitsToJson()}}_LoadFromJson(t){this._LoadGroupsFromJson(t["groups"]),this._LoadCndsFromJson(t["cnds"]),this._LoadActsFromJson(t["acts"]),this._LoadVarsFromJson(t["vars"]),this._LoadScheduledWaitsFromJson(t["waits"])}_SaveGroupsToJson(){const t={};for(const e of this.GetAllGroups())t[e.GetSID().toString()]=e.IsGroupActive();return t}_LoadGroupsFromJson(t){for(const[e,s]of Object.entries(t)){const t=parseInt(e,10),n=this.GetEventGroupBySID(t);n&&n.SetGroupActive(s)}}_SaveCndsToJson(){const t={};for(const[e,s]of this._cndsBySid){const n=s._SaveToJson();n&&(t[e.toString()]=n)}return t}_LoadCndsFromJson(t){const e=new Map;for(const[s,n]of Object.entries(t))e.set(parseInt(s,10),n);for(const[t,s]of this._cndsBySid)s._LoadFromJson(e.get(t)||null)}_SaveActsToJson(){const t={};for(const[e,s]of this._actsBySid){const n=s._SaveToJson();n&&(t[e.toString()]=n)}return t}_LoadActsFromJson(t){const e=new Map;for(const[s,n]of Object.entries(t))e.set(parseInt(s,10),n);for(const[t,s]of this._actsBySid)s._LoadFromJson(e.get(t)||null)}_SaveVarsToJson(){const t={};for(const[e,s]of this._eventVarsBySid)s.IsConstant()||!s.IsGlobal()&&!s.IsStatic()||(t[e.toString()]=s.GetValue());return t}_LoadVarsFromJson(t){for(const[e,s]of Object.entries(t)){const t=parseInt(e,10),n=this.GetEventVariableBySID(t);n&&n.SetValue(s)}}_SaveScheduledWaitsToJson(){return this._scheduledWaits.filter(t=>!t.IsPromise()).map(t=>t._SaveToJson())}_LoadScheduledWaitsFromJson(t){this.ClearAllScheduledWaits();for(const e of t){const t=C3.ScheduledWait._CreateFromJson(this,e);t&&this._scheduledWaits.push(t)}}_GetPerfRecords(){return[...this._runtime.GetLayoutManager().runningLayouts()].map(t=>t.GetEventSheet()).filter(t=>t).map(t=>t._GetPerfRecord())}FindFirstFunctionBlockParent(t){for(;t;){const e=t.GetScopeParent();if(e instanceof C3.FunctionBlock)return e;t=e}return null}_InvokeFunctionFromJS(t,e){Array.isArray(e)||(e=[]);const s=this.GetFunctionBlockByName(t.toLowerCase());if(!s)return null;if(!s.IsEnabled())return s.GetDefaultReturnValue();const n=s.GetFunctionParameters();if(e.length1;g&&r.GetLocalVarStack().Push();const h=l.Push(t);if(e){t.GetConditions()[s].GetObjectClass().GetCurrentSol().SetSinglePicked(e),e.IsInContainer()&&e.SetSiblingsSinglePicked()}let _=!0;if(t.GetParent()){const e=t.GetTriggerParents();for(let t=0,s=e.length;t1;c&&r.GetLocalVarStack().Push();const u=l.Push(t);if(e){t.GetConditions()[s].GetObjectClass().GetCurrentSol().SetSinglePicked(e),e.IsInContainer()&&e.SetSiblingsSinglePicked()}let g=!0;if(t.GetParent()){const e=t.GetTriggerParents();for(let t=0,s=e.length;t0){let t=!1;for(const e of this._actions)e._PostInit(),e.HasReturnType()&&(t=!0);t?(this._RunActions=this._RunActions_ReturnValue,this._DebugRunActions=this._DebugRunActions_ReturnValue):(this._RunActions=this._RunActions_Fast,this._DebugRunActions=this._DebugRunActions_Fast)}const e=this._subEvents;for(let t=0,n=e.length;tt.DebugCanRunFast()),t.canRunAllActionsFast=this._actions.every(t=>t.DebugCanRunFast()),t.canRunAllSubEventsFast=this._subEvents.every(t=>t.DebugCanRunFast()),t.canRunSelfFast=t.canRunAllConditionsFast&&t.canRunAllActionsFast&&t.canRunAllSubEventsFast}_UpdateCanRunFastRecursive(){let t=this;do{t._UpdateCanRunFast(),t=t.GetParent()}while(t)}_IdentifyTopLevelGroup(){if(!this.IsGroup())return;let t=this.GetParent();for(this._isTopLevelGroup=!0;t;){if(!t.IsGroup()){this._isTopLevelGroup=!1;break}t=t.GetParent()}}_IdentifySolModifiersIncludingParents(){const t=this._runtime.GetAllObjectClasses();if(this._solModifiers===t)this._solModifiersIncludingParents=t;else{this._solModifiersIncludingParents=C3.cloneArray(this._solModifiers);let t=this.GetParent();for(;t;){for(const e of t._solModifiers)this._AddParentSolModifier(e);t=t.GetParent()}const e=this.GetEventSheetManager();this._solModifiers=e._DeduplicateSolModifierList(this._solModifiers),this._solModifiersIncludingParents=e._DeduplicateSolModifierList(this._solModifiersIncludingParents)}}_IdentifyTriggerParents(){if(!this.HasAnyTriggeredCondition())return;this._triggerParents=[];let t=this.GetParent();for(;t;)this._triggerParents.push(t),t=t.GetParent();this._triggerParents.reverse()}SetSolWriterAfterCnds(){this._isSolWriterAfterCnds=!0,this._parent&&this._parent.SetSolWriterAfterCnds()}IsSolWriterAfterCnds(){return this._isSolWriterAfterCnds}GetSolModifiers(){return this._solModifiers}GetSolModifiersIncludingParents(){return this._hasGotSolModifiersIncludingParents||(this._hasGotSolModifiersIncludingParents=!0,this._IdentifySolModifiersIncludingParents()),this._solModifiersIncludingParents}HasSolModifier(t){return this._solModifiers.includes(t)}GetTriggerParents(){return this._triggerParents}GetEventSheet(){return this._eventSheet}GetEventSheetManager(){return this._eventSheet.GetEventSheetManager()}GetRuntime(){return this._runtime}GetParent(){return this._parent}_SetScopeParent(t){this._scopeParent=t}GetScopeParent(){return this._scopeParent||this._parent}GetDisplayNumber(){return this._displayNumber}IsDebugBreakable(){return this._debugData&&this._debugData.isBreakable}IsDebugBreakpoint(){return this.IsDebugBreakable()&&this._debugData.isBreakpoint}_SetDebugBreakpoint(t){this._debugData.isBreakpoint=!!t,this._UpdateCanRunFastRecursive()}IsGroup(){return this._isGroup}IsTopLevelGroup(){return this._isTopLevelGroup}IsElseBlock(){return this._isElseBlock}HasElseBlock(){return this._hasElseBlock}GetGroupName(){return this._groupName}IsGroupActive(){return this._isGroupActive}ResetInitialActivation(){this.SetGroupActive(this._isInitiallyActive)}SetGroupActive(t){if(t=!!t,!this._isGroup)throw new Error("not a group");if(this._isGroupActive!==t){this._isGroupActive=t;for(const t of this._containedIncludes)t.UpdateActive();if(this._containedIncludes.length){const t=this._runtime.GetCurrentLayout().GetEventSheet();t&&t._UpdateDeepIncludes()}}}GetSID(){return this._sid}IsOrBlock(){return this._isOrBlock}IsTrigger(){return this._conditions.length&&this._conditions[0].IsTrigger()}IsForFunctionBlock(){return this._scopeParent&&this._scopeParent instanceof C3.FunctionBlock}HasAnyTriggeredCondition(){return this.IsForFunctionBlock()||this._conditions.some(t=>t.IsTrigger())}GetConditions(){return this._conditions}GetConditionCount(){return this._conditions.length}GetConditionAt(t){if((t=Math.floor(t))<0||t>=this._conditions.length)throw new RangeError("invalid condition index");return this._conditions[t]}GetConditionByDebugIndex(t){return this.GetConditionAt(t)}IsFirstConditionOfType(t){let e=t.GetIndex();if(0===e)return!0;--e;const n=t.IsSystemOrSingleGlobalCondition()?t.GetFirstObjectParameterObjectClass():t.GetObjectClass();for(;e>=0;--e){const t=this._conditions[e];if(n===t.GetObjectClass()||t.IsSystemOrSingleGlobalCondition()&&t.GetFirstObjectParameterObjectClass()===n)return!1}return!0}GetActions(){return this._actions}GetActionCount(){return this._actions.length}GetActionAt(t){if((t=Math.floor(t))<0||t>=this._actions.length)throw new RangeError("invalid action index");return this._actions[t]}GetActionByDebugIndex(t){t=Math.floor(t);const e=this._actions.find(e=>e.GetDebugIndex()===t);if(!e)throw new RangeError("invalid action debug index");return e}_HasActionIndex(t){return(t=Math.floor(t))>=0&&tt instanceof C3.EventVariable)}RunPreTrigger(t){t.SetCurrentEvent(this);const e=this._conditions;let n=0===e.length;for(let s=0,i=e.length;s0)if(n){const n=e.map(t=>t.Get(0));t.GetLocalVarStack().Push(),this._scopeParent.SetFunctionParameters(n)}else this._scopeParent.EvaluateFunctionParameters(e);else n&&t.GetLocalVarStack().Push()}#t(t,e,n,s){let i=null;if(e.copyFromObjectClass){const t=n?e.copyFromObjectClass.GetCurrentSol():e.copyFromObjectClass.GetSolStack().GetOneBelowCurrentSol(),s=e.copyToObjectClass.GetCurrentSol();s.SetArrayPicked(t.GetInstances()),s.ClearElseInstances(),n||e.copyToObjectClass.ApplySolToContainer()}else if(e.pickObjectClass){const t=e.pickObjectClass.GetCurrentSol();t.SetArrayPicked(e.pickInstances),t.ClearElseInstances()}return e.pushCleanSolDynamic&&(i=t.PushCleanSolDynamic(s)),i}RunAsFunctionCall(t,e,n,s){let i,o;const r=t.length>0;let u=null;const l=this._runtime,a=this._eventStack,h=l.GetEventSheetManager(),c=this._scopeParent,_=c.IsAsync(),d=h._IncTriggerDepth()>1;this._EvaluateFunctionCallParameters(h,e,d),r&&(n?h.PushCopySol(t):h.PushCleanSol(t)),null!==s&&(u=this.#t(h,s,n,t));const g=a.Push(this);return n&&g.SetDynamicSolModifiers(t),this._CheckParentsOKToRun(g)&&(g.SetCurrentEvent(this),_&&([o,i]=c.StartAsyncFunctionCall()),this._RunAndBlock(g),_&&c.MaybeFinishAsyncFunctionCall(o)),a.Pop(),d&&h.GetLocalVarStack().Pop(),null!==u&&h.PopSol(u),r&&h.PopSol(t),h._DecTriggerDepth(),i}*DebugRunAsFunctionCall(t,e,n,s){let i,o;(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())&&(yield this);const r=t.length>0;let u=null;const l=this._runtime,a=this._eventStack,h=l.GetEventSheetManager(),c=this._scopeParent,_=c.IsAsync(),d=h._IncTriggerDepth()>1;this._EvaluateFunctionCallParameters(h,e,d),r&&(n?h.PushCopySol(t):h.PushCleanSol(t)),null!==s&&(u=this.#t(h,s,n,t));const g=a.Push(this);return n&&g.SetDynamicSolModifiers(t),(yield*this._DebugCheckParentsOKToRun(g))&&(g.SetCurrentEvent(this),_&&([o,i]=c.StartAsyncFunctionCall()),yield*this._DebugRunAndBlock(g),_&&c.MaybeFinishAsyncFunctionCall(o)),a.Pop(),d&&h.GetLocalVarStack().Pop(),null!==u&&h.PopSol(u),r&&h.PopSol(t),h._DecTriggerDepth(),i}RunAsMappedFunctionCall(t,e){const n=this.GetSolModifiersIncludingParents(),s=n.length>0,i=this._runtime,o=this._eventStack,r=i.GetEventSheetManager(),u=r._IncTriggerDepth()>1;u&&r.GetLocalVarStack().Push(),this._scopeParent.SetFunctionParameters(t),s&&(e?r.PushCopySol(n):r.PushCleanSol(n));const l=o.Push(this);this._CheckParentsOKToRun(l)&&(l.SetCurrentEvent(this),this._RunAndBlock(l)),o.Pop(),u&&r.GetLocalVarStack().Pop(),s&&r.PopSol(n),r._DecTriggerDepth()}*DebugRunAsMappedFunctionCall(t,e){(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())&&(yield this);const n=this.GetSolModifiersIncludingParents(),s=n.length>0,i=this._runtime,o=this._eventStack,r=i.GetEventSheetManager(),u=r._IncTriggerDepth()>1;u&&r.GetLocalVarStack().Push(),this._scopeParent.SetFunctionParameters(t),s&&(e?r.PushCopySol(n):r.PushCleanSol(n));const l=o.Push(this);(yield*this._DebugCheckParentsOKToRun(l))&&(l.SetCurrentEvent(this),yield*this._DebugRunAndBlock(l)),o.Pop(),u&&r.GetLocalVarStack().Pop(),s&&r.PopSol(n),r._DecTriggerDepth()}RunAsExpressionOrJSFunctionCall(t,e,n,s,i,...o){let r,u;const l=t.length>0;let a=null;const h=this._runtime,c=this._eventStack,_=h.GetEventSheetManager(),d=this._scopeParent,g=d.IsAsync(),S=_._IncTriggerDepth()>1;S&&_.GetLocalVarStack().Push(),o.length>0&&this._scopeParent.SetFunctionParameters(o),l&&(e?_.PushCopySol(t):_.PushCleanSol(t)),null!==i&&(a=this.#t(_,i,e,t));const R=c.Push(this);return R.InitCallFunctionExpression(n,s),e&&R.SetDynamicSolModifiers(t),c.PushExpFunc(R),h.SetDebuggingEnabled(!1),this._CheckParentsOKToRun(R)&&(R.SetCurrentEvent(this),g&&([u,r]=d.StartAsyncFunctionCall()),this._RunAndBlock(R),g&&d.MaybeFinishAsyncFunctionCall(u)),h.SetDebuggingEnabled(!0),c.Pop(),c.PopExpFunc(),S&&_.GetLocalVarStack().Pop(),null!==a&&_.PopSol(a),l&&_.PopSol(t),_._DecTriggerDepth(),r||R.GetFunctionReturnValue()}}; } // events/eventScript.js { const C3=self.C3,EMPTY_SOL_MODIFIERS=[];let hadUserScriptException=!1;C3.EventScript=class extends C3.DefendedBase{constructor(e,t,i){super();const r=e.GetRuntime(),n=e.GetEventSheetManager();this._eventSheet=e,this._eventSheetManager=n,this._runtime=e.GetRuntime(),this._parent=t;const s=r.GetObjectReference(i[1]);this._func=s,this._displayNumber=i[2],this._eventSheet._RegisterEventByDisplayNumber(this,this._displayNumber),this._debugData=r.IsDebug()?{isBreakpoint:i[3][0],isBreakable:i[3][1]}:null}static Create(e,t,i){return C3.New(C3.EventScript,e,t,i)}_PostInit(){const e=this._func,t=this._runtime.GetEventSheetManager()._GetLocalVariablesScriptInterface(this);this._func=e.bind(null,this._runtime.GetIRuntime(),t)}GetParent(){return this._parent}GetScopeParent(){return this._parent}GetEventSheet(){return this._eventSheet}GetDisplayNumber(){return this._displayNumber}IsDebugBreakable(){return this._debugData&&this._debugData.isBreakable}IsDebugBreakpoint(){return this.IsDebugBreakable()&&this._debugData.isBreakpoint}_SetDebugBreakpoint(e){this._debugData.isBreakpoint=!!e}IsElseBlock(){return!1}GetSolModifiers(){return EMPTY_SOL_MODIFIERS}GetSolModifiersIncludingParents(){return this._parent?this._parent.GetSolModifiersIncludingParents():EMPTY_SOL_MODIFIERS}Run(e){e.SetCurrentEvent(this),this._eventSheetManager.AddAsyncActionPromise(this._RunUserScript())}async _RunUserScript(){try{await this._func()}catch(e){console.error(`Unhandled exception running script %c${this.GetEventSheet().GetName()}, event ${this.GetDisplayNumber()}:`,"font-size: 1.2em; font-weight: bold;",e),self.C3Debugger&&self.C3Debugger._SetLastErrorScript(this),hadUserScriptException||(console.info("%cTip:%c run this to highlight in Construct the last script that had an error: %cgoToLastErrorScript()","font-weight: bold; text-decoration: underline","","font-weight: bold"),hadUserScriptException=!0)}}*DebugRun(e){e.SetCurrentEvent(this),(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this.Run(e)}DebugCanRunFast(){return!this.IsDebugBreakpoint()&&!this._runtime.DebugBreakNext()}static HadUserScriptException(){return hadUserScriptException}static SetHadUserScriptException(){hadUserScriptException=!0}}; } // events/functionBlock.js { const C3=self.C3,assert=self.assert;C3.FunctionBlock=class extends C3.DefendedBase{constructor(t,e,s){super(),this._eventSheet=t,this._runtime=t.GetRuntime(),this._parent=e,this._functionType=0,this._functionName="",this._returnType=0,this._functionParameters=[],this._isEnabled=!0,this._aceName="",this._objectClass=null,this._hasOverrides=!1,this._innerLocalVariables=[],this._isCopyPicked=!1,this._isAsync=!1,this._nextAsyncId=0,this._currentAsyncId=-1,this._asyncMap=new Map,this._eventBlock=C3.EventBlock.Create(t,e,s),this._eventBlock._SetScopeParent(this)}InitFunctionBlock(t){this._functionType=0,this._functionName=t[0],this._returnType=t[1],this._functionParameters=t[2].map(t=>C3.EventVariable.Create(this._eventSheet,this,t)),this._isEnabled=t[3],this._isAsync=t[4],this._isCopyPicked=t[5]}InitCustomACEBlock(t){this._functionType=1,this._aceName=t[1],this._objectClass=this._runtime.GetObjectClassByIndex(t[2]),this._eventBlock._AddSolModifier(this._objectClass),this._functionName=this._objectClass.GetName()+"."+this._aceName,this._returnType=t[3],this._functionParameters=t[4].map(t=>C3.EventVariable.Create(this._eventSheet,this,t)),this._isEnabled=t[5],this._isAsync=t[6],this._isCopyPicked=t[7],this._objectClass.AddCustomAction(this)}static CreateFunctionBlock(t,e,s){const n=C3.New(C3.FunctionBlock,t,e,s),i=s[1];return n.InitFunctionBlock(i),n}static CreateCustomACEBlock(t,e,s){const n=C3.New(C3.FunctionBlock,t,e,s),i=s[1];return n.InitCustomACEBlock(i),n}_CheckOverrideState(){if(this._objectClass&&this._objectClass.IsFamily())for(const t of this._objectClass.GetFamilyMembers())if(t.HasOwnCustomActionByName(this._aceName)){this._hasOverrides=!0;break}}_PostInit(){for(const t of this._functionParameters)t._PostInit();this._eventBlock._PostInit(!1)}GetFunctionType(){return this._functionType}_GetAllLocalVariablesInScope(){return this._functionParameters}GetFunctionParameters(){return this._functionParameters}GetFunctionParameterCount(){return this._functionParameters.length}_RegisterLocalVariable(t){this._innerLocalVariables.push(t)}_GetAllInnerLocalVariables(){return this._innerLocalVariables}EvaluateFunctionParameters(t){const e=this._functionParameters;for(let s=0,n=e.length;st.GetValue())}GetParent(){return this._parent}GetScopeParent(){return this._parent}GetFunctionName(){return this._functionName}GetACEName(){return this._aceName}HasCustomACEOverrides(){return this._hasOverrides}GetReturnType(){return this._returnType}GetObjectClass(){return this._objectClass}IsEnabled(){return this._isEnabled}GetDefaultReturnValue(){switch(this._returnType){case 0:return null;case 2:return"";default:return 0}}GetEventBlock(){return this._eventBlock}IsCopyPicked(){return this._isCopyPicked}IsAsync(){return this._isAsync}StartAsyncFunctionCall(){const t=this._nextAsyncId++;let e;this._currentAsyncId=t;const s=new Promise(t=>e=t);return this._asyncMap.set(t,{resolve:e,pauseCount:0}),[t,s]}MaybeFinishAsyncFunctionCall(t){const e=this._asyncMap.get(t);0===e.pauseCount&&(e.resolve(),this._asyncMap.delete(t)),this._currentAsyncId=-1}PauseCurrentAsyncFunction(){return this._asyncMap.get(this._currentAsyncId).pauseCount++,this._currentAsyncId}ResumeAsyncFunction(t){this._currentAsyncId=t;this._asyncMap.get(t).pauseCount--}RunAsFamilyCustomActionWithOverrides(t,e){const s=new Map,n=[];for(const t of this._objectClass.GetCurrentSol().GetInstances()){const e=t.GetObjectClass();if(e.HasOwnCustomActionByName(this._aceName)){const n=s.get(e);Array.isArray(n)?n.push(t):s.set(e,[t])}else n.push(t)}if(n.length>0&&this._eventBlock.RunAsFunctionCall(t,e,this._isCopyPicked,{pickObjectClass:this._objectClass,pickInstances:n}),s.size>0)for(const[n,i]of s){const s=n.GetOwnCustomActionByName(this._aceName).GetEventBlock(),a=[...new Set([...t,...s.GetSolModifiers()])];s.RunAsFunctionCall(a,e,this._isCopyPicked,{pickObjectClass:n,pickInstances:i})}}*DebugRunAsFamilyCustomActionWithOverrides(t,e){const s=new Map,n=[];for(const t of this._objectClass.GetCurrentSol().GetInstances()){const e=t.GetObjectClass();if(e.HasOwnCustomActionByName(this._aceName)){const n=s.get(e);Array.isArray(n)?n.push(t):s.set(e,[t])}else n.push(t)}if(n.length>0&&(yield*this._eventBlock.DebugRunAsFunctionCall(t,e,this._isCopyPicked,{pickObjectClass:this._objectClass,pickInstances:n})),s.size>0)for(const[n,i]of s){const s=n.GetOwnCustomActionByName(this._aceName).GetEventBlock(),a=[...new Set([...t,...s.GetSolModifiers()])];yield*s.DebugRunAsFunctionCall(a,e,this._isCopyPicked,{pickObjectClass:n,pickInstances:i})}}}; } // events/eventVariable.js { const C3=self.C3,EMPTY_SOL_MODIFIERS=[];C3.EventVariable=class extends C3.DefendedBase{constructor(t,e,s){super();const i=t.GetEventSheetManager();this._eventSheet=t,this._eventSheetManager=i,this._runtime=t.GetRuntime(),this._parent=e,this._localVarStack=i.GetLocalVarStack(),this._name=s[1],this._type=s[2],this._initialValue=s[3],this._isStatic=!!s[4],this._isConstant=!!s[5],this._isFunctionParameter=e instanceof C3.FunctionBlock,this._sid=s[6],this._jsPropName=this._runtime.GetJsPropName(s[8]),this._scriptSetter=t=>this._ScriptSetValue(t),this._scriptGetter=()=>this.GetTypedValue(),this._hasSingleValue=!this._parent||this._isStatic||this._isConstant,this._value=this._initialValue,this._localIndex=-1,this.IsBoolean()&&(this._value=this._value?1:0),!this.IsLocal()||this.IsStatic()||this.IsConstant()||(this._localIndex=i._GetNextLocalVarIndex(this)),i._RegisterEventVariable(this)}static Create(t,e,s){return C3.New(C3.EventVariable,t,e,s)}_PostInit(){if(this.IsLocal()&&!this.IsStatic()&&!this.IsConstant()&&!this.IsFunctionParameter()){const t=this._eventSheetManager.FindFirstFunctionBlockParent(this);t&&t._RegisterLocalVariable(this)}}GetName(){return this._name}GetJsPropName(){return this._jsPropName}GetParent(){return this._parent}GetScopeParent(){return this.GetParent()}IsGlobal(){return!this.GetParent()}IsLocal(){return!this.IsGlobal()}IsFunctionParameter(){return this._isFunctionParameter}IsStatic(){return this._isStatic}IsConstant(){return this._isConstant}IsNumber(){return 0===this._type}IsString(){return 1===this._type}IsBoolean(){return 2===this._type}IsElseBlock(){return!1}GetSID(){return this._sid}GetInitialValue(){return this._initialValue}GetSolModifiers(){return EMPTY_SOL_MODIFIERS}Run(t){!this.IsLocal()||this.IsStatic()||this.IsConstant()||this.SetValue(this.GetInitialValue())}DebugCanRunFast(){return!0}*DebugRun(t){this.Run(t)}SetValue(t){this.IsNumber()?"number"!=typeof t&&(t=parseFloat(t)):this.IsString()?"string"!=typeof t&&(t=t.toString()):this.IsBoolean()&&(t=t?1:0),this._hasSingleValue?this._value=t:this._localVarStack.GetCurrent()[this._localIndex]=t}_ScriptSetValue(t){if(this.IsConstant())throw new Error(`assignment to constant event variable '${this.GetName()}'`);this.SetValue(t)}GetValue(){return this._hasSingleValue?this._value:this._localVarStack.GetCurrent()[this._localIndex]}GetTypedValue(){let t=this.GetValue();return this.IsBoolean()&&(t=!!t),t}ResetToInitialValue(){this._value=this._initialValue}_GetScriptInterfaceDescriptor(){return{configurable:!1,enumerable:!0,get:this._scriptGetter,set:this._scriptSetter}}}; } // events/eventInclude.js { const C3=self.C3,assert=self.assert,EMPTY_SOL_MODIFIERS=[];C3.EventInclude=class extends C3.DefendedBase{constructor(e,t,n){super();const s=e.GetEventSheetManager();this._eventSheet=e,this._eventSheetManager=s,this._runtime=e.GetRuntime(),this._parent=t,this._includeSheet=null,this._includeSheetName=n[1],this._isActive=!0}static Create(e,t,n){return C3.New(C3.EventInclude,e,t,n)}_PostInit(){this._includeSheet=this._eventSheetManager.GetEventSheetByName(this._includeSheetName),this._eventSheet._AddShallowInclude(this);let e=this.GetParent();for(;e;)e instanceof C3.EventBlock&&e.IsGroup()&&e._AddContainedInclude(this),e=e.GetParent();this.UpdateActive(),this._runtime.IsDebug()&&this._eventSheet._GetPerfRecord().children.push(this._includeSheet._GetPerfRecord())}GetParent(){return this._parent}GetSolModifiers(){return EMPTY_SOL_MODIFIERS}GetIncludeSheet(){return this._includeSheet}Run(e){const t=!!this.GetParent(),n=this._runtime.GetAllObjectClasses();t&&this._eventSheetManager.PushCleanSol(n),this._includeSheet.Run(),t&&this._eventSheetManager.PopSol(n)}*DebugRun(e){const t=!!this.GetParent(),n=this._runtime.GetAllObjectClasses();t&&this._eventSheetManager.PushCleanSol(n),yield*this._includeSheet.DebugRun(),t&&this._eventSheetManager.PopSol(n)}DebugCanRunFast(){return!1}IsActive(){return this._isActive}UpdateActive(){let e=this.GetParent();for(;e;){if(e instanceof C3.EventBlock&&e.IsGroup()&&!e.IsGroupActive())return void(this._isActive=!1);e=e.GetParent()}this._isActive=!0}}; } // events/expNode.js { const C3=self.C3,assert=self.assert;C3.ExpNode=class extends C3.DefendedBase{constructor(e){super(),this._owner=e,this._runtime=e.GetRuntime()}_PostInit(){}static CreateNode(e,t){const s=t[0],n=[BehaviorExpressionNode,ObjectExpressionNode,InstVarExpressionNode,EventVarExpNode,SystemExpressionExpNode,CallFunctionExpressionExpNode];return C3.New(n[s],e,t)}};class SystemExpressionExpNode extends C3.ExpNode{constructor(e,t){super(e),this._systemPlugin=this._runtime.GetSystemPlugin(),this._func=this._runtime.GetObjectReference(t[1]),this._func!==C3.Plugins.System.Exps.random&&this._func!==C3.Plugins.System.Exps.choose||this._owner.SetVariesPerInstance()}GetBoundMethod(){return this._systemPlugin._GetBoundACEMethod(this._func,this._systemPlugin)}}class CallFunctionExpressionExpNode extends C3.ExpNode{constructor(e,t){super(e),this._functionBlock=null,this._functionName=t[1],this._owner.SetVariesPerInstance()}_PostInit(){const e=this._runtime.GetEventSheetManager();this._functionBlock=e.GetFunctionBlockByName(this._functionName),this._functionName=null;const t=this._owner.GetEventBlock(),s=this._functionBlock.GetEventBlock();this._combinedSolModifiers=[...new Set([...t.GetSolModifiersIncludingParents(),...s.GetSolModifiersIncludingParents()])],this._combinedSolModifiers=e._DeduplicateSolModifierList(this._combinedSolModifiers)}GetBoundMethod(){const e=this._functionBlock;if(e.IsEnabled()){const t=e.GetEventBlock();return C3.EventBlock.prototype.RunAsExpressionOrJSFunctionCall.bind(t,this._combinedSolModifiers,e.IsCopyPicked(),e.GetReturnType(),e.GetDefaultReturnValue(),null)}{const t=e.GetDefaultReturnValue();return()=>t}}}function WrapIndex(e,t){return e>=t?e%t:e<0?(e<=-t&&(e%=t),e<0&&(e+=t),e):e}class ObjectExpressionNode extends C3.ExpNode{constructor(e,t){super(e),this._objectClass=this._runtime.GetObjectClassByIndex(t[1]),this._func=this._runtime.GetObjectReference(t[2]),this._returnsString=!!t[3],this._eventStack=this._runtime.GetEventSheetManager().GetEventStack(),this._owner._MaybeVaryFor(this._objectClass)}GetBoundMethod(){return this._objectClass.GetPlugin()._GetBoundACEMethod(this._func,this._objectClass.GetSingleGlobalInstance().GetSdkInstance())}ExpObject(...e){const t=this._objectClass,s=t.GetCurrentSol().GetExpressionInstances(),n=s.length;if(0===n)return this._returnsString?"":0;const r=WrapIndex(this._owner.GetSolIndex(),n);return this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(t),this._func.apply(s[r].GetSdkInstance(),e)}ExpObject_InstExpr(e,...t){const s=this._objectClass,n=s.GetInstances(),r=n.length;if(0===r||"number"!=typeof e)return this._returnsString?"":0;const i=WrapIndex(e,r);return this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(s),this._func.apply(n[i].GetSdkInstance(),t)}}class InstVarExpressionNode extends C3.ExpNode{constructor(e,t){super(e),this._objectClass=this._runtime.GetObjectClassByIndex(t[1]),this._varIndex=t[3],this._returnsString=!!t[2],this._owner._MaybeVaryFor(this._objectClass)}ExpInstVar(){const e=this._objectClass.GetCurrentSol().GetExpressionInstances(),t=e.length;if(0===t)return this._returnsString?"":0;return e[WrapIndex(this._owner.GetSolIndex(),t)]._GetInstanceVariableValueUnchecked(this._varIndex)}ExpInstVar_Family(){const e=this._objectClass,t=e.GetCurrentSol().GetExpressionInstances(),s=t.length;if(0===s)return this._returnsString?"":0;const n=t[WrapIndex(this._owner.GetSolIndex(),s)],r=n.GetObjectClass().GetFamilyInstanceVariableOffset(e.GetFamilyIndex());return n._GetInstanceVariableValueUnchecked(this._varIndex+r)}ExpInstVar_InstExpr(e){const t=this._objectClass,s=t.GetInstances(),n=s.length;if(0===n||"number"!=typeof e)return this._returnsString?"":0;const r=s[WrapIndex(e,n)];let i=0;return t.IsFamily()&&(i=r.GetObjectClass().GetFamilyInstanceVariableOffset(t.GetFamilyIndex())),r._GetInstanceVariableValueUnchecked(this._varIndex+i)}}class BehaviorExpressionNode extends C3.ExpNode{constructor(e,t){super(e),this._objectClass=this._runtime.GetObjectClassByIndex(t[1]),this._behaviorType=this._objectClass.GetBehaviorTypeByName(t[2]),this._behaviorIndex=this._objectClass.GetBehaviorIndexByName(t[2]),this._func=this._runtime.GetObjectReference(t[3]),this._returnsString=!!t[4],this._eventStack=this._runtime.GetEventSheetManager().GetEventStack(),this._owner._MaybeVaryFor(this._objectClass)}ExpBehavior(...e){const t=this._objectClass,s=t.GetCurrentSol().GetExpressionInstances(),n=s.length;if(0===n)return this._returnsString?"":0;const r=WrapIndex(this._owner.GetSolIndex(),n);this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(t);const i=s[r];let o=0;return t.IsFamily()&&(o=i.GetObjectClass().GetFamilyBehaviorOffset(t.GetFamilyIndex())),this._func.apply(i.GetBehaviorInstances()[this._behaviorIndex+o].GetSdkInstance(),e)}ExpBehavior_InstExpr(e,...t){const s=this._objectClass,n=s.GetInstances(),r=n.length;if(0===r||"number"!=typeof e)return this._returnsString?"":0;const i=WrapIndex(e,r);this._eventStack.GetCurrentStackFrame().SetExpressionObjectClass(s);const o=n[i];let a=0;return s.IsFamily()&&(a=o.GetObjectClass().GetFamilyBehaviorOffset(s.GetFamilyIndex())),this._func.apply(o.GetBehaviorInstances()[this._behaviorIndex+a].GetSdkInstance(),t)}}class EventVarExpNode extends C3.ExpNode{constructor(e,t){super(e),this._eventVar=null,this._eventVarSid=t[1]}_PostInit(){this._eventVar=this._runtime.GetEventSheetManager().GetEventVariableBySID(this._eventVarSid)}GetVar(){return this._eventVar}} } // events/parameter.js { const C3=self.C3,assert=self.assert;function GetExpressionFunc(t){const e=self.C3_ExpressionFuncs[t];if(!e)throw new Error("invalid expression number");return e}C3.Parameter=class extends C3.DefendedBase{constructor(t,e,s){super(),this._owner=t,this._index=s,this._type=e,this.Get=null,this._variesPerInstance=!1,this._isConstant=!1}static Create(t,e,s){const r=e[0],n=[ExpressionParameter,StringExpressionParameter,FileParameter,ComboParameter,ObjectParameter,LayerExpressionParameter,LayoutParameter,ExpressionParameter,ComboParameter,ComboParameter,InstVarParameter,EventVarParameter,FileParameter,VariadicParameter,StringExpressionParameter,TimelineParameter,BooleanParameter,FunctionParameter,EaseParameter,TilemapBrushParameter,TemplateExpressionParameter,FlowchartParameter,Model3dParameter];return C3.New(n[r],t,r,s,e)}_PostInit(){}SetVariesPerInstance(){this._variesPerInstance=!0}_MaybeVaryFor(t){this._variesPerInstance||t&&(t.GetPlugin().IsSingleGlobal()||(this._variesPerInstance=!0))}VariesPerInstance(){return this._variesPerInstance}GetIndex(){return this._index}GetRuntime(){return this._owner.GetRuntime()}GetEventBlock(){return this._owner.GetEventBlock()}IsConstant(){return this._isConstant}IsObjectParameter(){return 4===this._type}};class ExpressionParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._solIndex=0;const n=r[1];this._expressionNumber=n[0],this._numberedNodes=[],this._expressionFunc=null;for(let t=1,e=n.length;t=this._numberedNodes.length)throw new RangeError("invalid numbered node");return this._numberedNodes[t]}_PostInit(){for(const t of this._numberedNodes)t._PostInit();const t=GetExpressionFunc(this._expressionNumber);this._numberedNodes.length?this._expressionFunc=t(this):this._expressionFunc=t}GetSolIndex(){return this._solIndex}GetExpression(t){return this._solIndex=t,this._expressionFunc()}}class StringExpressionParameter extends ExpressionParameter{constructor(t,e,s,r){super(t,e,s,r),this.Get=this.GetStringExpression,14===e&&(this.GetEventBlock().SetAllSolModifiers(),this._owner instanceof C3.Action&&this.GetEventBlock().SetSolWriterAfterCnds())}GetStringExpression(t){this._solIndex=t;const e=this._expressionFunc();return"string"==typeof e?e:""}_GetFastTriggerValue(){return GetExpressionFunc(this._expressionNumber)()}}class LayerExpressionParameter extends ExpressionParameter{constructor(t,e,s,r){super(t,e,s,r),t.GetImplementationSdkVersion()>=2?this.Get=this.GetILayer:this.Get=this.GetLayer,this._isConstant=!1}GetLayer(t){this._solIndex=t;const e=this._expressionFunc();return this.GetRuntime().GetCurrentLayout().GetLayer(e)}GetILayer(t){const e=this.GetLayer(t);return e?e.GetILayer():null}}class ComboParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._combo=r[1],this.Get=this.GetCombo,this._isConstant=!0}GetCombo(){return this._combo}}class BooleanParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._bool=r[1],this.Get=this.GetBoolean,this._isConstant=!0}GetBoolean(){return this._bool}}class ObjectParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._objectClass=this.GetRuntime().GetObjectClassByIndex(r[1]),t.GetImplementationSdkVersion()>=2?this.Get=this.GetIObjectClass:this.Get=this.GetObjectClass;const n=this.GetEventBlock();n._AddSolModifier(this._objectClass),this._owner instanceof C3.Action?n.SetSolWriterAfterCnds():n.GetParent()&&n.GetParent().SetSolWriterAfterCnds(),this._isConstant=!0}GetObjectClass(){return this._objectClass}GetIObjectClass(){return this._objectClass?this._objectClass.GetIObjectClass():null}}class LayoutParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._layout=this.GetRuntime().GetLayoutManager().GetLayoutByName(r[1]),t.GetImplementationSdkVersion()>=2?this.Get=this.GetILayout:this.Get=this.GetLayout,this._isConstant=!0}GetLayout(){return this._layout}GetILayout(){return this._layout?this._layout.GetILayout():null}}class TimelineParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._timeline=this.GetRuntime().GetTimelineManager().GetTimelineByName(r[1]),t.GetImplementationSdkVersion()>=2?this.Get=this.GetITimelineState:this.Get=this.GetTimeline,this._isConstant=!0}GetTimeline(){return this._timeline}GetITimelineState(){return this._timeline?this._timeline.GetITimelineState():null}}class FileParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._fileInfo=r[1],this.Get=this.GetFile,this._isConstant=!0}GetFile(){return this._fileInfo}}class InstVarParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._instVarIndex=r[1];const n=this._owner.GetObjectClass();this._owner instanceof C3.Condition&&this._owner.IsStatic()?(this.Get=this.GetInstanceVariable,this._isConstant=!0):n&&n.IsFamily()?(this.Get=this.GetFamilyInstanceVariable,this.SetVariesPerInstance()):(this.Get=this.GetInstanceVariable,this._isConstant=!0)}GetInstanceVariable(){return this._instVarIndex}GetFamilyInstanceVariable(t){t=t||0;const e=this._owner.GetObjectClass(),s=e.GetCurrentSol(),r=s.GetInstances();let n=null;if(r.length)n=r[t%r.length].GetObjectClass();else if(s.HasAnyElseInstances()){const e=s.GetElseInstances();n=e[t%e.length].GetObjectClass()}else{if(!(e.GetInstanceCount()>0))return 0;{const s=e.GetInstances();n=s[t%s.length].GetObjectClass()}}return this._instVarIndex+n.GetFamilyInstanceVariableOffset(e.GetFamilyIndex())}}class EventVarParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._eventVarSid=r[1],this._eventVar=null,t.GetImplementationSdkVersion()>=2?this.Get=this.GetIEventVariable:this.Get=this.GetEventVariable,this._isConstant=!0}_PostInit(){this._eventVar=this.GetRuntime().GetEventSheetManager().GetEventVariableBySID(this._eventVarSid)}GetEventVariable(){return this._eventVar}GetIEventVariable(){return null}}class FunctionParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._functionBlockName=r[1],this._functionBlock=null,t.GetImplementationSdkVersion()>=2?this.Get=this.GetIFunction:this.Get=this.GetFunction,this._isConstant=!0}_PostInit(){this._functionBlock=this.GetRuntime().GetEventSheetManager().GetFunctionBlockByName(this._functionBlockName),this._functionBlockName=null}GetFunction(){return this._functionBlock}GetIFunction(){return null}}class VariadicParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._subParams=[],this._variadicRet=[],this._isConstant=!0;for(let t=1,e=r.length;t0,this._isFastTrigger=2===e[3],this._isLooping=!!e[4],this._isInverted=!!e[5],this._isStatic=!!e[6],this._sid=e[7],this._isInOrBlock=this._eventBlock.IsOrBlock(),this._objectClass=null,this._behaviorType=null,this._behaviorIndex=-1,this._systemPlugin=null,this.Run=noop,this.DebugRun=noop,this._parameters=[],this._results=[],this._anyParamVariesPerInstance=!1,this._savedData=null,this._unsavedData=null,this._debugData=this._runtime.IsDebug()?{isBreakpoint:e[8][0],canDebug:e[8][1]}:null,-1===e[0]?this._systemPlugin=this._runtime.GetSystemPlugin():(this._objectClass=this._runtime.GetObjectClassByIndex(e[0]),e[2]&&(this._behaviorType=this._objectClass.GetBehaviorTypeByName(e[2]),this._behaviorIndex=this._objectClass.GetBehaviorIndexByName(e[2])),this._eventBlock.GetParent()&&this._eventBlock.GetParent().SetSolWriterAfterCnds()),10===e.length){let t=e[9];for(let e of t)this._parameters.push(C3.Parameter.Create(this,e,this._parameters.length)),this._results.push(0)}0===this._parameters.length&&(this._parameters=EMPTY_PARAMS_ARRAY,this._results=EMPTY_PARAMS_ARRAY),this._eventBlock.GetEventSheetManager()._RegisterCondition(this)}static Create(t,e,s){return C3.New(C3.Condition,t,e,s)}_PostInit(){for(const t of this._parameters)t._PostInit(),t.VariesPerInstance()&&(this._anyParamVariesPerInstance=!0);this._isFastTrigger?(this.Run=this._RunFastTrigger,this.DebugRun=this._DebugRunFastTrigger):this._systemPlugin?(this._SetSystemRunMethod(),this.DebugRun=this._DebugRunSystem):this._objectClass.GetPlugin().IsSingleGlobal()?(this._SetSingleGlobalRunMethod(),this.DebugRun=this._DebugRunSingleGlobal):this._isStatic?(this.Run=this._RunStatic,this.DebugRun=this._DebugRunStatic):(this.Run=this._RunObject,this.DebugRun=this._DebugRunObject)}_SetSystemRunMethod(){const t=this._systemPlugin,e=this._systemPlugin;this._SetRunMethodForBoundFunc(t,e,this._RunSystem)}_SetSingleGlobalRunMethod(){const t=this._objectClass.GetPlugin(),e=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();this._SetRunMethodForBoundFunc(t,e,this._RunSingleGlobal)}_SetRunMethodForBoundFunc(t,e,s){const n=this._func,i=this._isInverted,r=this._parameters;if(0===r.length){const s=t._GetBoundACEMethod(n,e);this.Run=i?function(){return C3.xor(s(),i)}:s}else if(1===r.length){const s=r[0];if(!i&&s.IsConstant())this.Run=t._GetBoundACEMethod_1param(n,e,s.Get(0));else{const r=t._GetBoundACEMethod(n,e);this.Run=function(){return C3.xor(r(s.Get(0)),i)}}}else if(2===r.length){const s=r[0],a=r[1];if(!i&&s.IsConstant()&&a.IsConstant())this.Run=t._GetBoundACEMethod_2params(n,e,s.Get(0),a.Get(0));else{const r=t._GetBoundACEMethod(n,e);this.Run=function(){return C3.xor(r(s.Get(0),a.Get(0)),i)}}}else if(3===r.length){const s=r[0],a=r[1],h=r[2];if(!i&&s.IsConstant()&&a.IsConstant()&&h.IsConstant())this.Run=t._GetBoundACEMethod_3params(n,e,s.Get(0),a.Get(0),h.Get(0));else{const r=t._GetBoundACEMethod(n,e);this.Run=function(){return C3.xor(r(s.Get(0),a.Get(0),h.Get(0)),i)}}}else this.Run=s}GetSID(){return this._sid}_GetFunc(){return this._func}GetObjectClass(){return this._objectClass}GetBehaviorType(){return this._behaviorType}GetImplementationAddon(){return this._behaviorType?this._behaviorType.GetBehavior():this._objectClass?this._objectClass.GetPlugin():null}GetImplementationSdkVersion(){const t=this.GetImplementationAddon();return t?t.GetSdkVersion():1}GetEventBlock(){return this._eventBlock}GetRuntime(){return this._runtime}GetIndex(){return this._index}GetDebugIndex(){return this.GetIndex()}IsTrigger(){return this._isTrigger}IsFastTrigger(){return this._isFastTrigger}IsInverted(){return this._isInverted}IsLooping(){return this._isLooping}IsStatic(){return this._isStatic}IsBreakpoint(){return this._debugData.isBreakpoint}IsSystemCondition(){return!!this._systemPlugin}IsSystemOrSingleGlobalCondition(){return this.IsSystemCondition()||this._objectClass.GetPlugin().IsSingleGlobal()}GetFirstObjectParameterObjectClass(){for(const t of this._parameters)if(t.IsObjectParameter())return t.GetObjectClass();return null}_SetBreakpoint(t){this._debugData.isBreakpoint=!!t,this._eventBlock._UpdateCanRunFastRecursive()}_DebugReturnsGenerator(){return this._debugData.canDebug}DebugCanRunFast(){return!this.IsBreakpoint()&&!this._runtime.DebugBreakNext()&&!this._DebugReturnsGenerator()}GetSavedDataMap(){return this._savedData||(this._savedData=new Map),this._savedData}GetUnsavedDataMap(){return this._unsavedData||(this._unsavedData=new Map),this._unsavedData}_RunSystem(){const t=this._results;return EvalParams(this._parameters,t),C3.xor(this._func.apply(this._systemPlugin,t),this._isInverted)}*_DebugRunSystem(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);let e=this._func.apply(this._systemPlugin,t);return C3.IsIterator(e)&&(e=yield*e),C3.xor(e,this._isInverted)}return this.Run()}_RunSingleGlobal(){const t=this._results;EvalParams(this._parameters,t);const e=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();return C3.xor(this._func.apply(e,t),this._isInverted)}*_DebugRunSingleGlobal(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);const e=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();let s=this._func.apply(e,t);return C3.IsIterator(s)&&(s=yield*s),C3.xor(s,this._isInverted)}return this.Run()}_RunFastTrigger(){return!0}*_DebugRunFastTrigger(){return(this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),!0}_GetStaticConditionThis(){return this._behaviorType?this._behaviorType.GetBehavior().GetSdkVersion()>=2?this._behaviorType.GetIBehaviorType():this._behaviorType:this._objectClass.GetPlugin().GetSdkVersion()>=2?this._objectClass.GetIObjectClass():this._objectClass}_RunStatic(){const t=this._results;EvalParams(this._parameters,t);const e=this._func.apply(this._GetStaticConditionThis(),t);return this._objectClass.ApplySolToContainer(),e}*_DebugRunStatic(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);let e=this._func.apply(this._GetStaticConditionThis(),t);return C3.IsIterator(e)&&(e=yield*e),this._objectClass.ApplySolToContainer(),e}return this.Run()}_RunObject(){const t=this._parameters,e=this._results,s=this._objectClass.GetCurrentSol();for(let s=0,n=t.length;s=0,a=e.GetInstances(),h=this._anyParamVariesPerInstance,o=this._results,l=this._func,u=this._isInverted,_=this._isInOrBlock&&!this._isTrigger;t.ClearArrays();for(let e=0,c=a.length;e=0,h=this._anyParamVariesPerInstance,o=this._results,l=this._func,u=this._isInverted,_=this._isInOrBlock&&!this._isTrigger,c=t._GetOwnInstances(),g=t._GetOwnElseInstances(),d=_&&!this._eventBlock.IsFirstConditionOfType(this),I=d?g:c;let G=0,b=!1;for(let t=0,e=I.length;t=0,h=this._results,o=this._func,l=this._isInverted;for(let e=0,u=t.length;e[t[0].GetUID(),t[1].GetUID(),t[2]])),t[e]=n}return{"ex":t}}_LoadFromJson(t){if(this._savedData&&(this._savedData.clear(),this._savedData=null),!t)return;const e=this._runtime,s=t["ex"];if(s){const t=this.GetSavedDataMap();t.clear();for(const[n,i]of Object.entries(s)){let s=i;"collmemory"===n&&(s=C3.New(C3.PairMap,i.map(t=>[e.GetInstanceByUID(t[0]),e.GetInstanceByUID(t[1]),t[2]]).filter(t=>t[0]&&t[1]))),t.set(n,s)}}}}; } // events/action.js { const C3=self.C3,assert=self.assert;function EvalParams(t,e){for(let s=0,n=t.length;s=4?e[3]:-1,this._actionType=e.length>=5?255&e[4]:0,this._flags=e.length>=5?e[4]>>8:0,this._func=null,this._objectClass=null,this._behaviorType=null,this._behaviorIndex=-1,this._systemPlugin=null,this._callFunctionName="",this._callCustomAceObjectClass=null,this._callEventBlock=null,this.Run=noop,this.DebugRun=noop,this._parameters=[],this._results=[],this._anyParamVariesPerInstance=!1;const i=-3===e[0],a=i?e[2]:e[5];if(this._debugData=n.IsDebug()||i?{isBreakpoint:a[0],canDebug:a[1],index:a[2]}:null,-1===e[0])this._systemPlugin=n.GetSystemPlugin(),this._func=n.GetObjectReference(e[1]);else if(-2===e[0])this._callFunctionName=e[1];else if(i){const t=n.GetObjectReference(e[1]);this._func=t,this.Run=this.RunUserScript,this.DebugRun=this.DebugRunUserScript,this._flags|=8}else this._objectClass=n.GetObjectClassByIndex(e[0]),4&this._flags?(this._callFunctionName=e[1],this._callCustomAceObjectClass=n.GetObjectClassByIndex(e[2])):(e[2]&&(this._behaviorType=this._objectClass.GetBehaviorTypeByName(e[2]),this._behaviorIndex=this._objectClass.GetBehaviorIndexByName(e[2])),this._func=n.GetObjectReference(e[1]));if(7===e.length){const t=e[6];for(const e of t)this._parameters.push(C3.Parameter.Create(this,e,this._parameters.length)),this._results.push(0)}0===this._parameters.length&&(this._parameters=EMPTY_PARAMS_ARRAY,this._results=EMPTY_PARAMS_ARRAY),this.CanPickAnyObjectClass()&&(this._eventBlock.SetAllSolModifiers(),this._eventBlock.SetSolWriterAfterCnds()),this._eventBlock.GetEventSheetManager()._RegisterAction(this)}static Create(t,e,s){return C3.New(C3.Action,t,e,s)}_PostInit(){for(const t of this._parameters)t._PostInit(),t.VariesPerInstance()&&(this._anyParamVariesPerInstance=!0);if(this._systemPlugin)this._SetSystemRunMethod(),this.DebugRun=this._DebugRunSystem;else if(this._callFunctionName)4&this._flags?this._SetCallCustomActionRunMethod():this._SetCallFunctionRunMethod(),this._callFunctionName="",this._callCustomAceObjectClass=null;else if(this.Run===this.RunUserScript){const t=this._func,e=this._runtime.GetEventSheetManager()._GetLocalVariablesScriptInterface(this._eventBlock);this._func=t.bind(null,this._runtime.GetIRuntime(),e)}else this._behaviorType?this.IsAsync()?(this.Run=this._RunBehavior_Async,this.DebugRun=this._DebugRunBehavior_Async):(this.Run=this._RunBehavior,this.DebugRun=this._DebugRunBehavior):this._objectClass.GetPlugin().IsSingleGlobal()?(this._SetSingleGlobalRunMethod(),this.DebugRun=this._DebugRunSingleGlobal):this.IsStatic()?(this.Run=this._RunObject_Static,this.DebugRun=this._DebugRunObject_Static):this.IsAsync()?(this.Run=this._RunObject_Async,this.DebugRun=this._DebugRunObject_Async):this.CallBeforeAfterHooks()?(this.Run=this._RunObject_BeforeAfterHooks,this.DebugRun=this._DebugRunObject_BeforeAfterHooks):this._parameters.length?this._parameters.every(t=>t.VariesPerInstance())?(this.Run=this._RunObject_AllParamsVary,this.DebugRun=this._DebugRunObject_AllParamsVary):this._anyParamVariesPerInstance?(this.Run=this._RunObject_SomeParamsVary,this.DebugRun=this._DebugRunObject_SomeParamsVary):this._parameters.every(t=>t.IsConstant())?(EvalParams(this._parameters,this._results),this.Run=this._RunObject_ParamsConst,this.DebugRun=this._DebugRunObject_ParamsConst):(this.Run=this._RunObject_ParamsDontVary,this.DebugRun=this._DebugRunObject_ParamsDontVary):(this.Run=this._RunObject_ParamsConst,this.DebugRun=this._DebugRunObject_ParamsConst)}_SetSystemRunMethod(){const t=this._systemPlugin,e=this._systemPlugin;this._SetRunMethodForBoundFunc(t,e,this._RunSystem)}_SetSingleGlobalRunMethod(){const t=this._objectClass.GetPlugin(),e=this._objectClass.GetSingleGlobalInstance().GetSdkInstance();this._SetRunMethodForBoundFunc(t,e,this._RunSingleGlobal)}_SetCallFunctionRunMethod(){const t=this._eventBlock.GetEventSheetManager(),e=t.GetFunctionBlockByName(this._callFunctionName);if(e.IsEnabled()){const s=!!(2&this._flags);this._callEventBlock=e.GetEventBlock();let n=[...new Set([...this._eventBlock.GetSolModifiersIncludingParents(),...this._callEventBlock.GetSolModifiersIncludingParents()])];n=t._DeduplicateSolModifierList(n);const i=!e.IsCopyPicked()&&this._HasCopyPickedParent()?{pushCleanSolDynamic:!0}:null;if(this.Run=C3.EventBlock.prototype.RunAsFunctionCall.bind(this._callEventBlock,n,this._parameters,s,i),this._runtime.IsDebug()){const t=this;this.DebugRun=function*(){(t.IsBreakpoint()||t._runtime.DebugBreakNext())&&(yield t);return yield*t._callEventBlock.DebugRunAsFunctionCall(n,t._parameters,s,i)}}else this.DebugRun=noopGenerator}else this.Run=noop,this.DebugRun=noopGenerator}_SetCallCustomActionRunMethod(){const t=this._eventBlock.GetEventSheetManager(),e=t.GetCustomActionBlockByName(this._callCustomAceObjectClass,this._callFunctionName);if(e.IsEnabled()){const s=!!(2&this._flags);this._callEventBlock=e.GetEventBlock();let n=[...new Set([...this._eventBlock.GetSolModifiersIncludingParents(),...this._callEventBlock.GetSolModifiersIncludingParents(),this._objectClass,e.GetObjectClass()])];n=t._DeduplicateSolModifierList(n);const i=!this._objectClass.IsFamily()&&!e.GetObjectClass().IsFamily(),a=!this._objectClass.IsFamily()&&e.GetObjectClass().IsFamily(),r=this._objectClass.IsFamily();let o=null;if(!e.IsCopyPicked()&&this._HasCopyPickedParent()&&(o=o||{},o.pushCleanSolDynamic=!0),!a&&s||(o=o||{},o.copyFromObjectClass=this._objectClass,o.copyToObjectClass=e.GetObjectClass()),i||a||r&&!e.HasCustomACEOverrides()?this.Run=C3.EventBlock.prototype.RunAsFunctionCall.bind(this._callEventBlock,n,this._parameters,s,o):r&&(this.Run=C3.FunctionBlock.prototype.RunAsFamilyCustomActionWithOverrides.bind(e,n,this._parameters)),this._runtime.IsDebug()){const t=this;i||a||r&&!e.HasCustomACEOverrides()?this.DebugRun=function*(){(t.IsBreakpoint()||t._runtime.DebugBreakNext())&&(yield t);return yield*t._callEventBlock.DebugRunAsFunctionCall(n,t._parameters,s,o)}:r&&(this.DebugRun=function*(){(t.IsBreakpoint()||t._runtime.DebugBreakNext())&&(yield t);return yield*e.DebugRunAsFamilyCustomActionWithOverrides(n,t._parameters)})}else this.DebugRun=noopGenerator}else this.Run=noop,this.DebugRun=noopGenerator}_SetRunMethodForBoundFunc(t,e,s){const n=this._func,i=this._parameters;if(0===i.length)this.Run=t._GetBoundACEMethod(n,e);else if(1===i.length){const s=i[0];if(s.IsConstant())this.Run=t._GetBoundACEMethod_1param(n,e,s.Get(0));else{const i=t._GetBoundACEMethod(n,e);this.Run=function(){return i(s.Get(0))}}}else if(2===i.length){const s=i[0],a=i[1];if(s.IsConstant()&&a.IsConstant())this.Run=t._GetBoundACEMethod_2params(n,e,s.Get(0),a.Get(0));else{const i=t._GetBoundACEMethod(n,e);this.Run=function(){return i(s.Get(0),a.Get(0))}}}else if(3===i.length){const s=i[0],a=i[1],r=i[2];if(s.IsConstant()&&a.IsConstant()&&r.IsConstant())this.Run=t._GetBoundACEMethod_3params(n,e,s.Get(0),a.Get(0),r.Get(0));else{const i=t._GetBoundACEMethod(n,e);this.Run=function(){return i(s.Get(0),a.Get(0),r.Get(0))}}}else this.Run=s}GetSID(){return this._sid}IsAsync(){return!!(8&this._flags)}CanBailOut(){return!!(16&this._flags)}CallBeforeAfterHooks(){return 1===this._actionType}IsStatic(){return 2===this._actionType}CanPickAnyObjectClass(){return!!(1&this._flags)}HasReturnType(){return this.IsAsync()||this.CanBailOut()}GetObjectClass(){return this._objectClass}GetImplementationAddon(){return this._behaviorType?this._behaviorType.GetBehavior():this._objectClass?this._objectClass.GetPlugin():null}GetImplementationSdkVersion(){const t=this.GetImplementationAddon();return t?t.GetSdkVersion():1}GetEventBlock(){return this._eventBlock}_HasCopyPickedParent(){let t=this._eventBlock;do{if(t instanceof C3.FunctionBlock&&t.IsCopyPicked())return!0;t=t.GetScopeParent()}while(t);return!1}GetRuntime(){return this._runtime}GetIndex(){return this._index}GetDebugIndex(){return this._debugData.index}IsBreakpoint(){return this._debugData.isBreakpoint}_SetBreakpoint(t){this._debugData.isBreakpoint=!!t,this._eventBlock._UpdateCanRunFastRecursive()}_DebugReturnsGenerator(){return this._debugData.canDebug}DebugCanRunFast(){return!this.IsBreakpoint()&&!this._runtime.DebugBreakNext()&&!this._DebugReturnsGenerator()}_RunSystem(){const t=this._results;return EvalParams(this._parameters,t),this._func.apply(this._systemPlugin,t)}*_DebugRunSystem(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);return yield*this._func.apply(this._systemPlugin,t)}return this.Run()}_RunSingleGlobal(){const t=this._results;return EvalParams(this._parameters,t),this._func.apply(this._objectClass.GetSingleGlobalInstance().GetSdkInstance(),t)}*_DebugRunSingleGlobal(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);return yield*this._func.apply(this._objectClass.GetSingleGlobalInstance().GetSdkInstance(),t)}return this.Run()}_RunObject_ParamsConst(){const t=this._results,e=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=e.length;s=2?this._behaviorType.GetIBehaviorType():this._behaviorType:this._objectClass.GetPlugin().GetSdkVersion()>=2?this._objectClass.GetIObjectClass():this._objectClass}_RunObject_Static(){const t=this._results;return EvalParams(this._parameters,t),this._func.apply(this._GetStaticActionThis(),t)}*_DebugRunObject_Static(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);let e=this._func.apply(this._GetStaticActionThis(),t);return C3.IsIterator(e)&&(e=yield*e),e}return this._RunObject_Static()}_RunBehavior(){const t=this._objectClass,e=t.IsFamily(),s=t.GetFamilyIndex(),n=this._parameters,i=this._anyParamVariesPerInstance,a=this._results,r=this._func,o=this._behaviorIndex,l=t.GetCurrentSol().GetInstances();for(let t=0,e=n.length;te.GetWidth()||n.getTop()>e.GetHeight()},AnySDK.PickDistance=function(t,e,n,o){const s=GetObjectClass(this).GetCurrentSol(),i=s.GetInstances();if(0===i.length)return!1;const r=[];let a=0;for(let s=0,l=i.length;sa?(a=u,C3.clearArray(r),r.push(l)):o&&u===a&&r.push(l)}return o?s.SetArrayPicked(r):s.PickOne(r[0]),!0},SDKv1.SetX=function(t){const e=this.GetWorldInfo();e.GetX()!==t&&(e.SetX(t),e.SetBboxChanged())},SDKv2.SetX=function(t){this.x=+t},SDKv1.SetY=function(t){const e=this.GetWorldInfo();e.GetY()!==t&&(e.SetY(t),e.SetBboxChanged())},SDKv2.SetY=function(t){this.y=+t},SDKv1.SetZ=function(t){const e=this.GetWorldInfo();e.GetZ()!==t&&(e.SetZ(t),e.SetBboxChanged())},SDKv2.SetZ=function(t){this.z=t},SDKv1.SetPos=function(t,e){const n=this.GetWorldInfo();n.EqualsXY(t,e)||(n.SetXY(t,e),n.SetBboxChanged())},SDKv2.SetPos=function(t,e){this.setPosition(t,e)},SDKv1.SetPos3D=function(t,e,n){const o=this.GetWorldInfo();o.EqualsXYZ(t,e,n)||(o.SetXYZ(t,e,n),o.SetBboxChanged())},SDKv2.SetPos3D=function(t,e,n){this.setPosition3d(t,e,n)},AnySDK.SetPosToObject=function(t,e){if(!(t=GetObjectClass(t)))return;const n=GetInst(this),o=t.GetPairedInstance(n);if(!o)return;const[s,i]=o.GetImagePoint(e),r=n.GetWorldInfo();r.GetX()===s&&r.GetY()===i||(r.SetXY(s,i),r.SetBboxChanged())},AnySDK.MoveForward=function(t){if(0===t)return;const e=GetWorldInfo(this);e.OffsetXY(e.GetCosAngle()*t,e.GetSinAngle()*t),e.SetBboxChanged()},SDKv1.MoveAtAngle=function(t,e){if(0===e)return;const n=this.GetWorldInfo();t=C3.toRadians(t),n.OffsetXY(Math.cos(t)*e,Math.sin(t)*e),n.SetBboxChanged()},SDKv2.MoveAtAngle=function(t,e){0!==e&&(t=C3.toRadians(t),this.offsetPosition(Math.cos(t)*e,Math.sin(t)*e))},SDKv1.GetX=function(){return this.GetWorldInfo().GetX()},SDKv2.GetX=function(){return this.x},SDKv1.GetY=function(){return this.GetWorldInfo().GetY()},SDKv2.GetY=function(){return this.y},SDKv1.GetZ=function(){return this.GetWorldInfo().GetZ()},SDKv2.GetZ=function(){return this.z},SDKv1.GetTotalZ=function(){return this.GetWorldInfo().GetTotalZ()},SDKv2.GetTotalZ=function(){return this.totalZ},AnySDK.GetDt=function(){return runtime.GetDt(GetInst(this))},SDKv1.CompareWidth=function(t,e){return C3.compare(this.GetWorldInfo().GetWidth(),t,e)},SDKv2.CompareWidth=function(t,e){return C3.compare(this.width,t,e)},SDKv1.CompareHeight=function(t,e){return C3.compare(this.GetWorldInfo().GetHeight(),t,e)},SDKv2.CompareHeight=function(t,e){return C3.compare(this.height,t,e)},SDKv1.CompareDepth=function(t,e){return C3.compare(this.GetWorldInfo().GetDepth(),t,e)},SDKv2.CompareDepth=function(t,e){return C3.compare(this.depth,t,e)},SDKv1.SetWidth=function(t){const e=this.GetWorldInfo();e.GetWidth()!==t&&(e.SetWidth(t),e.SetBboxChanged())},SDKv2.SetWidth=function(t){this.width=t},SDKv1.SetHeight=function(t){const e=this.GetWorldInfo();e.GetHeight()!==t&&(e.SetHeight(t),e.SetBboxChanged())},SDKv2.SetHeight=function(t){this.height=t},SDKv1.SetDepth=function(t){const e=this.GetWorldInfo();e.GetDepth()!==t&&(e.SetDepth(t),e.SetBboxChanged())},SDKv2.SetDepth=function(t){this.depth=t},SDKv1.SetSize=function(t,e){const n=GetWorldInfo(this);n.GetWidth()===t&&n.GetHeight()===e||(n.SetSize(t,e),n.SetBboxChanged())},SDKv2.SetSize=function(t,e){this.setSize(t,e)},SDKv1.SetSize3D=function(t,e,n){const o=GetWorldInfo(this);o.GetWidth()===t&&o.GetHeight()===e&&o.GetDepth()===n||(o.SetSize(t,e),o.SetDepth(n),o.SetBboxChanged())},SDKv2.SetSize3D=function(t,e,n){this.setSize3d(t,e,n)},SDKv1.GetWidth=function(){return this.GetWorldInfo().GetWidth()},SDKv2.GetWidth=function(){return this.width},SDKv1.GetHeight=function(){return this.GetWorldInfo().GetHeight()},SDKv2.GetHeight=function(){return this.height},SDKv1.GetDepth=function(){return this.GetWorldInfo().GetDepth()},SDKv2.GetDepth=function(){return this.depth},AnySDK.GetBboxLeft=function(){return GetWorldInfo(this).GetBoundingBox().getLeft()},AnySDK.GetBboxTop=function(){return GetWorldInfo(this).GetBoundingBox().getTop()},AnySDK.GetBboxBack=function(){return GetWorldInfo(this).GetBoundingBox().getBack()},AnySDK.GetBboxRight=function(){return GetWorldInfo(this).GetBoundingBox().getRight()},AnySDK.GetBboxBottom=function(){return GetWorldInfo(this).GetBoundingBox().getBottom()},AnySDK.GetBboxFront=function(){return GetWorldInfo(this).GetBoundingBox().getFront()},AnySDK.GetBboxMidX=function(){return GetWorldInfo(this).GetBoundingBox().midX()},AnySDK.GetBboxMidY=function(){return GetWorldInfo(this).GetBoundingBox().midY()},AnySDK.GetBboxMidZ=function(){return GetWorldInfo(this).GetBoundingBox().midZ()},AnySDK.IsAngleWithin=function(t,e){return C3.angleDiff(GetWorldInfo(this).GetAngle(),C3.toRadians(e))<=C3.toRadians(t)},AnySDK.IsAngleClockwiseFrom=function(t){return C3.angleClockwise(GetWorldInfo(this).GetAngle(),C3.toRadians(t))},AnySDK.IsBetweenAngles=function(t,e){const n=C3.toRadians(t),o=C3.toRadians(e),s=GetWorldInfo(this).GetAngle();return!C3.angleClockwise(o,n)?!(!C3.angleClockwise(s,n)&&C3.angleClockwise(s,o)):C3.angleClockwise(s,n)&&!C3.angleClockwise(s,o)},SDKv1.SetAngle=function(t){const e=this.GetWorldInfo(),n=C3.clampAngle(C3.toRadians(t));isNaN(n)||e.GetAngle()===n||(e.SetAngle(n),e.SetBboxChanged())},SDKv2.SetAngle=function(t){this.angleDegrees=t},AnySDK.RotateClockwise=function(t){if(isNaN(t)||0===t)return;const e=GetWorldInfo(this);e.SetAngle(e.GetAngle()+C3.toRadians(t)),e.SetBboxChanged()},AnySDK.RotateCounterclockwise=function(t){if(isNaN(t)||0===t)return;const e=GetWorldInfo(this);e.SetAngle(e.GetAngle()-C3.toRadians(t)),e.SetBboxChanged()},AnySDK.RotateTowardAngle=function(t,e){const n=GetWorldInfo(this),o=n.GetAngle(),s=C3.angleRotate(o,C3.toRadians(e),C3.toRadians(t));isNaN(s)||o===s||(n.SetAngle(s),n.SetBboxChanged())},AnySDK.RotateTowardPosition=function(t,e,n){const o=GetWorldInfo(this),s=o.GetAngle(),i=e-o.GetX(),r=n-o.GetY(),a=Math.atan2(r,i),l=C3.angleRotate(s,a,C3.toRadians(t));isNaN(l)||s===l||(o.SetAngle(l),o.SetBboxChanged())},AnySDK.SetTowardPosition=function(t,e){const n=GetWorldInfo(this),o=n.GetAngle(),s=t-n.GetX(),i=e-n.GetY(),r=Math.atan2(i,s);isNaN(r)||o===r||(n.SetAngle(r),n.SetBboxChanged())},SDKv1.GetAngle=function(){return C3.toDegrees(this.GetWorldInfo().GetAngle())},SDKv2.GetAngle=function(){return this.angleDegrees},AnySDK.CompareOpacity=function(t,e){return C3.compare(C3.roundToDp(100*GetWorldInfo(this).GetOpacity(),6),t,e)},SDKv1.IsVisible=function(){return this.GetWorldInfo().IsVisible()},SDKv2.IsVisible=function(){return this.isVisible},AnySDK.SetVisible=function(t){const e=GetWorldInfo(this);t=2===t?!e.IsVisible():0!==t,e.IsVisible()!==t&&(e.SetVisible(t),runtime.UpdateRender())},AnySDK.SetOpacity=function(t){const e=C3.clamp(t/100,0,1),n=GetWorldInfo(this);if(n.GetTransformWithParentOpacity()){if(n._GetSceneGraphInfo().GetOwnOpacity()===e)return}else if(n.GetOpacity()===e)return;n.SetOpacity(e),runtime.UpdateRender()},AnySDK.SetDefaultColor=function(t){tempColor.setFromRgbValue(t);const e=GetWorldInfo(this);e.GetUnpremultipliedColor().equalsIgnoringAlpha(tempColor)||(e.SetUnpremultipliedColor(tempColor),runtime.UpdateRender())},AnySDK.GetColor=function(){const t=GetWorldInfo(this).GetUnpremultipliedColor();return C3.PackRGBAEx(t.getR(),t.getG(),t.getB(),t.getA())},AnySDK.GetOpacity=function(){return C3.roundToDp(100*GetWorldInfo(this).GetOpacity(),6)},AnySDK.SetSampling=function(t){GetWorldInfo(this).SetSamplingMode(C3.Gfx.RendererBase.SamplingNumberToMode(t))},AnySDK.IsOnLayer=function(t){return!!(t=GetLayer(t))&&GetWorldInfo(this).GetLayer()===t},AnySDK.PickTopBottom=function(t){const e=GetObjectClass(this).GetCurrentSol(),n=e.GetInstances();if(!n.length)return!1;let o=n[0];for(let e=1,s=n.length;el||a===l&&i.GetZIndex()>r.GetZIndex())&&(o=s):(aCollMemory_RemoveInstance(d,t.instance)));const h=r.GetCurrentSol(),I=t.GetCurrentSol(),C=h.GetInstances();let m=null;for(let e=0;eCollMemory_RemoveInstance(h,t.instance)));const I=a.GetCurrentSol(),C=t.GetCurrentSol(),m=I.GetInstances();let g=null;for(let e=0;e0&&(r=r.concat(e))}if(0===r.length)return!1;const a=i.IsSelectAll()?null:new Set(r),l=new Set;for(let n=0,o=s.length;n0&&(r=r.concat(e))}if(0===r.length)return!1;const a=i.IsSelectAll()?null:new Set(r),l=new Set;for(let n=0,o=s.length;n0&&(a=a.concat(e))}if(0===a.length)return!1;const l=r.IsSelectAll()?null:new Set(a),c=[];for(let o=0,s=i.length;ol?(l=S,C3.clearArray(a),a.push(c)):n&&S===l&&a.push(c)}return n?s.SetArrayPicked(a):s.PickOne(a[0]),!0},AnySDK.PickByUID=function(t){const e=GetObjectClass(this);return e.GetRuntime().GetCurrentCondition().IsInverted()?PickByUID_Inverted(e,t):PickByUID_Normal(e,t)},AnySDK.HasTags=function(t){const e=GetInst(this);if(t.includes(" ")){return new Set(C3.splitStringAndNormalize(t.toLowerCase())).isSubsetOf(e.GetLowercaseTagsSet())}return!t||e.HasTag(t)},AnySDK.Tags=function(){return GetInst(this).GetTagsString()},AnySDK.TagsCount=function(){return GetInst(this).GetTagsSet().size},AnySDK.TagAt=function(t){return GetInst(this).GetTagAt(t)},AnySDK.ChangeTags=function(t,e){const n=C3.splitStringAndNormalize(e),o=GetInst(this);if(2===t)return void o.SetTagsSet(new Set(n));if(0===n.length)return;const s=new Set(o.GetTagsSet());if(0===t)for(const t of n)s.add(t);else if(1===t)for(const t of n){if(!s.delete(t)){const e=t.toLowerCase();for(const t of s)if(t.toLowerCase()===e){s.delete(t);break}}}o.SetTagsSet(s)},AnySDK.Destroy=function(){runtime.DestroyInstance(GetInst(this))},AnySDK.OnCreated=function(){return!0},AnySDK.OnDestroyed=function(){return!0},SDKv1.SetInstanceVar=function(t,e){this.GetInstance().SetInstanceVariableValue(t,e)},SDKv2.SetInstanceVar=function(t,e){GetInst_SDKv2(this).SetInstanceVariableValue(t,e)},SDKv1.AddInstanceVar=function(t,e){const n=this.GetInstance(),o=n.GetInstanceVariableValue(t);"number"==typeof o&&"number"!=typeof e?e=parseFloat(e):"string"==typeof o&&"string"!=typeof e&&(e=e.toString()),n.SetInstanceVariableValue(t,o+e)},SDKv2.AddInstanceVar=function(t,e){const n=GetInst_SDKv2(this),o=n.GetInstanceVariableValue(t);"number"==typeof o&&"number"!=typeof e?e=parseFloat(e):"string"==typeof o&&"string"!=typeof e&&(e=e.toString()),n.SetInstanceVariableValue(t,o+e)},SDKv1.SubInstanceVar=function(t,e){const n=this.GetInstance(),o=n.GetInstanceVariableValue(t);"number"==typeof o&&("number"!=typeof e&&(e=parseFloat(e)),n.SetInstanceVariableValue(t,o-e))},SDKv2.SubInstanceVar=function(t,e){const n=GetInst_SDKv2(this),o=n.GetInstanceVariableValue(t);"number"==typeof o&&("number"!=typeof e&&(e=parseFloat(e)),n.SetInstanceVariableValue(t,o-e))},SDKv1.SetBoolInstanceVar=function(t,e){this.GetInstance().SetInstanceVariableValue(t,e?1:0)},SDKv2.SetBoolInstanceVar=function(t,e){GetInst_SDKv2(this).SetInstanceVariableValue(t,e?1:0)},SDKv1.ToggleBoolInstanceVar=function(t){const e=this.GetInstance();e.SetInstanceVariableValue(t,0===e.GetInstanceVariableValue(t)?1:0)},SDKv2.ToggleBoolInstanceVar=function(t){const e=GetInst_SDKv2(this);e.SetInstanceVariableValue(t,0===e.GetInstanceVariableValue(t)?1:0)},AnySDK.LoadFromJsonString=function(t){let e;try{e=JSON.parse(t)}catch(t){return void console.error("Failed to load from JSON string: ",t)}const n=GetInst(this),o="state";runtime.ClearIntancesNeedingAfterLoad(),n._OnBeforeLoad(o),n.LoadFromJson(e,o);const s=n.GetWorldInfo();s&&s._UpdateActiveSamplingMode(),runtime.DoAfterLoad(o,{setFromJson:!0})},AnySDK.AsJSON=function(){return JSON.stringify(GetInst(this).SaveToJson("state"))},AnySDK.ObjectTypeName=function(){return GetInst(this).GetObjectClass().GetName()},AnySDK.Count=function(){const t=runtime.GetCurrentEventStackFrame().GetExpressionObjectClass();let e=t.GetInstanceCount();for(const n of runtime.instancesPendingCreateForObjectClass(t))++e;return e},AnySDK.PickedCount=function(){return runtime.GetCurrentEventStackFrame().GetExpressionObjectClass().GetCurrentSol().GetInstances().length},SDKv1.GetIID=function(){return this.GetInstance().GetIID()},SDKv2.GetIID=function(){return GetInst_SDKv2(this).GetIID()},SDKv1.GetUID=function(){return this.GetInstance().GetUID()},SDKv2.GetUID=function(){return GetInst_SDKv2(this).GetUID()},AnySDK.OnInstanceSignal=function(t){const e=GetInst(this);return t.toLowerCase()===runtime.GetEventSheetManager().GetCurrentInstanceSignalTag(e)},AnySDK.InstanceSignal=function(t){const e=GetInst(this);runtime.GetEventSheetManager().InstanceSignal(e,t)},AnySDK.InstanceWaitForSignal=function(t){const e=GetObjectClass(this);return runtime.GetEventSheetManager().AddScheduledWait().InitInstanceSignals(e.GetCurrentSol().GetInstances(),t),!0},AnySDK.TemplateName=function(){return GetInst(this).GetTemplateName()},C3.AddCommonACEs=function(t,e,n){const o=t[1],s=t[3],i=t[4],r=t[5],a=t[6],l=t[7],c=t[8],u=t[22],S=t[10],f=t[11],G=t[12],d=t[13],h=t[14],I=t[15],C=t[16],m=t[18],g=t[23],D=e.Cnds,p=e.Acts,y=e.Exps,A=Object.assign({},AnySDK,n>=2?SDKv2:SDKv1);s&&(D.CompareX=A.CompareX,D.CompareY=A.CompareY,D.IsOnScreen=A.IsOnScreen,D.IsOutsideLayout=A.IsOutsideLayout,D.PickDistance=A.PickDistance,p.SetX=A.SetX,p.SetY=A.SetY,p.SetPos=A.SetPos,p.SetPosToObject=A.SetPosToObject,p.MoveForward=A.MoveForward,p.MoveAtAngle=A.MoveAtAngle,y.X=A.GetX,y.Y=A.GetY,y.dt=A.GetDt),g&&(D.CompareZ=A.CompareZ,p.SetPos3D=A.SetPos3D,p.SetZ=A.SetZ,y.Z=A.GetZ,y.TotalZ=A.GetTotalZ,y.ZElevation=A.GetZ,y.TotalZElevation=A.GetTotalZ),i&&(D.CompareWidth=A.CompareWidth,D.CompareHeight=A.CompareHeight,p.SetWidth=A.SetWidth,p.SetHeight=A.SetHeight,p.SetSize=A.SetSize,y.Width=A.GetWidth,y.Height=A.GetHeight,y.BBoxLeft=A.GetBboxLeft,y.BBoxTop=A.GetBboxTop,y.BBoxBack=A.GetBboxBack,y.BBoxRight=A.GetBboxRight,y.BBoxBottom=A.GetBboxBottom,y.BBoxFront=A.GetBboxFront,y.BBoxMidX=A.GetBboxMidX,y.BBoxMidY=A.GetBboxMidY,y.BBoxMidZ=A.GetBboxMidZ,m&&(D.CompareDepth=A.CompareDepth,p.SetDepth=A.SetDepth,p.SetSize3D=A.SetSize3D,y.Depth=A.GetDepth)),r&&(D.AngleWithin=A.IsAngleWithin,D.IsClockwiseFrom=A.IsAngleClockwiseFrom,D.IsBetweenAngles=A.IsBetweenAngles,p.SetAngle=A.SetAngle,p.RotateClockwise=A.RotateClockwise,p.RotateCounterclockwise=A.RotateCounterclockwise,p.RotateTowardAngle=A.RotateTowardAngle,p.RotateTowardPosition=A.RotateTowardPosition,p.SetTowardPosition=A.SetTowardPosition,y.Angle=A.GetAngle),a&&(D.IsVisible=A.IsVisible,D.CompareOpacity=A.CompareOpacity,p.SetVisible=A.SetVisible,p.SetOpacity=A.SetOpacity,p.SetDefaultColor=A.SetDefaultColor,y.Opacity=A.GetOpacity,y.ColorValue=A.GetColor),u&&(p.SetSampling=A.SetSampling),l&&(D.IsOnLayer=A.IsOnLayer,D.PickTopBottom=A.PickTopBottom,p.MoveToTop=A.MoveToTop,p.MoveToBottom=A.MoveToBottom,p.MoveToLayer=A.MoveToLayer,p.ZMoveToObject=A.ZMoveToObject,y.LayerNumber=A.LayerNumber,y.LayerName=A.LayerName,y.ZIndex=A.ZIndex),c&&(D.IsEffectEnabled=A.IsEffectEnabled,p.SetEffectEnabled=A.SetEffectEnabled,p.SetEffectParam=A.SetEffectParam),d&&(D.OnHierarchyReady=A.OnHierarchyReady,D.HasParent=A.HasParent,D.HasChildren=A.HasChildren,D.PickParent=A.PickParent,D.PickChildren=A.PickChildren,D.PickNthChild=A.PickNthChild,D.CompareChildCount=A.CompareChildCount,p.AddChild=A.AddChild,p.RemoveChild=A.RemoveChild,p.RemoveFromParent=A.RemoveFromParent,y.ParentUID=A.ParentUID,y.ChildCount=A.ChildCount,y.AllChildCount=A.AllChildCount),h&&(p.SetMeshSize=A.SetMeshSize,p.SetMeshPoint=A.SetMeshPoint,y.MeshColumns=A.MeshColumns,y.MeshRows=A.MeshRows),S&&(D.IsVisible=A.IsVisible,p.SetVisible=A.SetElementVisible,p.SetCSSStyle=A.SetElementCSSStyle,p.SetElemAttribute=A.SetElementAttribute,p.RemoveElemAttribute=A.RemoveElementAttribute),f&&(D.IsFocused=A.IsElementFocused,p.SetFocus=A.SetElementFocus,p.SetBlur=A.SetElementBlur),G&&(D.IsEnabled=A.IsElementEnabled,p.SetEnabled=A.SetElementEnabled),I&&(D.OnCollision=A.OnCollision,D.IsOverlapping=A.IsOverlapping,D.IsOverlappingOffset=A.IsOverlappingOffset,e.FinishCollisionCondition=FinishCollisionCondition),o||(D.CompareInstanceVar=A.CompareInstanceVar,D.IsBoolInstanceVarSet=A.IsBoolInstanceVarSet,D.PickInstVarHiLow=A.PickInstVarHiLow,D.PickByUID=A.PickByUID,D.HasTags=A.HasTags,p.SetInstanceVar=A.SetInstanceVar,p.AddInstanceVar=A.AddInstanceVar,p.SubInstanceVar=A.SubInstanceVar,p.SetBoolInstanceVar=A.SetBoolInstanceVar,p.ToggleBoolInstanceVar=A.ToggleBoolInstanceVar,p.ChangeTags=A.ChangeTags,D.OnCreated=A.OnCreated,D.OnDestroyed=A.OnDestroyed,p.Destroy=A.Destroy,p.LoadFromJsonString||(p.LoadFromJsonString=A.LoadFromJsonString),y.AsJSON||(y.AsJSON=A.AsJSON),y.Count=A.Count,y.PickedCount=A.PickedCount,y.IID=A.GetIID,y.UID=A.GetUID,y.ObjectTypeName=A.ObjectTypeName,y.Tags=A.Tags,y.TagsCount=A.TagsCount,y.TagAt=A.TagAt,D.OnInstanceSignal=A.OnInstanceSignal,p.InstanceSignal=A.InstanceSignal,p.InstanceWaitForSignal=A.InstanceWaitForSignal),C&&(y.TemplateName=A.TemplateName)}; } // events/scheduledWait.js { const C3=self.C3;C3.ScheduledWait=class extends C3.DefendedBase{constructor(t){super(),this._eventSheetManager=t,this._type="",this._time=-1,this._signalTag="",this._isSignalled=!1,this._event=null,this._actIndex=0,this._triggerDepth=0,this._solModifiers=[],this._dynamicSolModifiers=null,this._sols=new Map,this._pendingInstances=null,this._callingFunctionBlock=null,this._asyncId=-1,this._functionParameters=null,this._functionInnerLocalVars=null,this._shouldRelease=!1}Release(){this._type="",this._time=-1,this._signalTag="",this._event=null,this._callingFunctionBlock=null,this._functionParameters=null,this._functionInnerLocalVars=null,this._asyncId=-1,C3.clearArray(this._solModifiers),this._dynamicSolModifiers&&(this._dynamicSolModifiers.clear(),this._dynamicSolModifiers=null);for(const t of this._sols.values())t.Release();this._sols.clear(),this._pendingInstances=null}_Init(){const t=this._eventSheetManager,e=t.GetRuntime().GetAllObjectClasses(),s=t.GetCurrentEventStackFrame();this._event=s.GetCurrentEvent(),this._actIndex=s.GetActionIndex()+1,this._triggerDepth=t.GetTriggerDepth();const i=t.FindFirstFunctionBlockParent(this._event);i&&(this._callingFunctionBlock=i,this._functionParameters=i.CaptureFunctionParameters(),this._functionInnerLocalVars=i._GetAllInnerLocalVariables().map(t=>t.GetValue()),i.IsAsync()&&(this._asyncId=i.PauseCurrentAsyncFunction()));for(const t of e){const e=t.GetCurrentSol();e.IsSelectAll()&&!this._event.HasSolModifier(t)||(this._solModifiers.push(t),this._sols.set(t,C3.New(C3.SolState,e)))}const n=t.GetDynamicSolModifiersSet();this._dynamicSolModifiers=n.size>0?n:null}InitTimer(t){this._type="timer",this._Init(),this._time=this._eventSheetManager.GetRuntime().GetGameTime()+t}InitWallTimer(t){this._type="walltimer",this._Init(),this._time=this._eventSheetManager.GetRuntime().GetWallTime()+t}InitSignal(t){this._type="signal",this._Init(),this._signalTag=t.toLowerCase()}InitInstanceSignals(t,e){this._type="instance-signals",this._Init(),this._signalTag=e.toLowerCase(),this._pendingInstances=new Set(t)}InitPromise(t){this._type="promise",this._Init(),t.then(()=>this.SetSignalled()).catch(t=>{console.warn("[C3 runtime] Promise rejected in 'Wait for previous actions to complete': ",t),this.SetSignalled()})}IsTimer(){return"timer"===this._type}IsWallTimer(){return"walltimer"===this._type}IsSignal(){return"signal"===this._type}IsInstanceSignals(){return"instance-signals"===this._type}IsPromise(){return"promise"===this._type}GetSignalTag(){return this._signalTag}IsSignalled(){return this._isSignalled}SetSignalled(){this._isSignalled=!0}SetInstanceSignalled(t){this._pendingInstances.delete(t),0===this._pendingInstances.size&&this.SetSignalled()}_ShouldRun(){return this.IsTimer()?this._time<=this._eventSheetManager.GetRuntime().GetGameTime():this.IsWallTimer()?this._time<=this._eventSheetManager.GetRuntime().GetWallTime():this.IsSignalled()}_RestoreState(t){t._Restore(this._event,this._actIndex),this._eventSheetManager._SetTriggerDepth(this._triggerDepth);for(const[t,e]of this._sols.entries()){const s=t.GetCurrentSol();e._Restore(s)}this._dynamicSolModifiers&&t.SetDynamicSolModifiers([...this._dynamicSolModifiers]);const e=this._callingFunctionBlock;e&&(e.SetFunctionParameters(this._functionParameters),e._GetAllInnerLocalVariables().map((t,e)=>t.SetValue(this._functionInnerLocalVars[e])),e.IsAsync()&&e.ResumeAsyncFunction(this._asyncId))}_Run(t){this._RestoreState(t),this._event._ResumeActionsAndSubEvents(t),this._callingFunctionBlock&&this._callingFunctionBlock.IsAsync()&&this._callingFunctionBlock.MaybeFinishAsyncFunctionCall(this._asyncId),this._eventSheetManager.ClearSol(this._solModifiers),this._shouldRelease=!0}async _DebugRun(t){this._RestoreState(t);for(const e of this._event._DebugResumeActionsAndSubEvents(t))await this._eventSheetManager.GetRuntime().DebugBreak(e);this._callingFunctionBlock&&this._callingFunctionBlock.IsAsync()&&this._callingFunctionBlock.MaybeFinishAsyncFunctionCall(this._asyncId),this._eventSheetManager.ClearSol(this._solModifiers),this._shouldRelease=!0}ShouldRelease(){return this._shouldRelease}RemoveInstances(t){for(const e of this._sols.values())e.RemoveInstances(t);if("instance-signals"===this._type){for(const e of t)this._pendingInstances.delete(e);0===this._pendingInstances.size&&this.SetSignalled()}}_SaveToJson(){const t={},e={"wt":this._type,"t":this._time,"st":this._signalTag,"s":this._isSignalled,"ev":this._event.GetSID(),"sm":this._solModifiers.map(t=>t.GetSID()),"dsm":this._dynamicSolModifiers?[...this._dynamicSolModifiers].map(t=>t.GetSID()):null,"sols":t};this._event._HasActionIndex(this._actIndex)&&(e["act"]=this._event.GetActionAt(this._actIndex).GetSID());for(const[e,s]of this._sols)t[e.GetSID().toString()]=s._SaveToJson();return"instance-signals"===this._type&&(e["pi"]=[...this._pendingInstances].map(t=>t.GetUID())),e}static _CreateFromJson(t,e){const s=t.GetRuntime(),i=t.GetEventBlockBySID(e["ev"]);if(!i)return null;let n=0;if(e.hasOwnProperty("act")){const s=t.GetActionBySID(e["act"]);if(!s)return null;n=s.GetIndex()}const a=C3.New(C3.ScheduledWait,t);a._time=e["t"],e.hasOwnProperty("wt")?a._type=e["wt"]:a._type=-1===a._time?"signal":"timer",a._signalTag=e["st"],a._isSignalled=e["s"],a._event=i,a._actIndex=n;for(const t of e["sm"]){const e=s.GetObjectClassBySID(t);e&&a._solModifiers.push(e)}if(Array.isArray(e["dsm"]))for(const t of e["dsm"]){const e=s.GetObjectClassBySID(t);e&&(a._dynamicSolModifiers||(a._dynamicSolModifiers=new Set),a._dynamicSolModifiers.add(e))}for(const[i,n]of Object.entries(e["sols"])){const e=parseInt(i,10),l=s.GetObjectClassBySID(e);if(!l)continue;const o=C3.New(C3.SolState,null);o._LoadFromJson(t,n),a._sols.set(l,o)}if("instance-signals"===a._type){a._pendingInstances=new Set;for(const t of e["pi"]){const e=s.GetInstanceByUID(t);e&&a._pendingInstances.add(e)}}return a}}; } // events/solState.js { const C3=self.C3;C3.SolState=class extends C3.DefendedBase{constructor(s){super(),this._objectClass=null,this._isSelectAll=!0,this._instances=[],s&&(this._objectClass=s.GetObjectClass(),this._isSelectAll=s.IsSelectAll(),C3.shallowAssignArray(this._instances,s._GetOwnInstances()))}Release(){this._objectClass=null,C3.clearArray(this._instances)}_Restore(s){s._SetSelectAll(this._isSelectAll),C3.shallowAssignArray(s._GetOwnInstances(),this._instances)}RemoveInstances(s){C3.arrayRemoveAllInSet(this._instances,s)}_SaveToJson(){return{"sa":this._isSelectAll,"insts":this._instances.map(s=>s.GetUID())}}_LoadFromJson(s,e){const t=s.GetRuntime();this._isSelectAll=!!e["sa"],C3.clearArray(this._instances);for(const s of e["insts"]){const e=t.GetInstanceByUID(s);e&&this._instances.push(e)}}}; } // sdk/sdkPluginBase.js { const C3=self.C3;function GetNextParamMap(t,e){let s=t.get(e);return s||(s=new Map,t.set(e,s)),s}C3.SDKPluginBase=class extends C3.DefendedBase{#t=!1;#e=!1;constructor(t){super(),this._runtime=t.runtime,this._id=t.id,this._name=t.name??"",this._isSingleGlobal=!!t.isSingleGlobal,this._isWorldType=!!t.isWorld,this._isRotatable=!!t.isRotatable,this._mustPredraw=!!t.mustPredraw,this._hasEffects=!!t.hasEffects,this._supportsSceneGraph=!!t.supportsSceneGraph,this._supportsMesh=!!t.supportsMesh,this._isHTMLElementType=!!t.isHTMLElementType,this._is3d=!!t.is3d,this._sdkVersion=t.sdkVersion,this.#t=t.supportsZElevation,this.#e=t.supportsChangingSampling,this._exportData=t.exportData,this._singleGlobalObjectClass=null,this._boundACEMethodCache=new Map,this._boundACEMethodCache_1param=new Map,this._boundACEMethodCache_2params=new Map,this._boundACEMethodCache_3params=new Map,this._scriptInterfaceClass=t.scriptInterfaceClass,this._iPlugin=null}Release(){this._runtime=null}GetRuntime(){return this._runtime}GetID(){return this._id}GetName(){return this._name}OnCreate(){}GetConstructor(){return this.GetSdkVersion()>=2?this._iPlugin.constructor:this.constructor}GetSdkVersion(){return this._sdkVersion}GetScriptInterfaceClass(t=!1){let e=this._scriptInterfaceClass;return t&&"function"!=typeof e&&this.GetSdkVersion()>=2&&(e=globalThis.ISDKPluginBase),e}GetExportData(){return this._exportData}IsSingleGlobal(){return this._isSingleGlobal}IsWorldType(){return this._isWorldType}IsHTMLElementType(){return this._isHTMLElementType}Is3D(){return this._is3d}IsRotatable(){return this._isRotatable}MustPreDraw(){return this._mustPredraw}HasEffects(){return this._hasEffects}SupportsSceneGraph(){return this._supportsSceneGraph}SupportsMesh(){return this._supportsMesh}SupportsZElevation(){return this.#t}SupportsChangingSampling(){return this.#e}_GetBoundACEMethod(t,e){if(!e)throw new Error("missing 'this' binding");let s=this._boundACEMethodCache.get(t);return s||(s=t.bind(e),this._boundACEMethodCache.set(t,s),s)}_GetBoundACEMethod_1param(t,e,s){if(!e)throw new Error("missing 'this' binding");const i=GetNextParamMap(this._boundACEMethodCache_1param,t);let n=i.get(s);return n||(n=t.bind(e,s),i.set(s,n),n)}_GetBoundACEMethod_2params(t,e,s,i){if(!e)throw new Error("missing 'this' binding");const n=GetNextParamMap(this._boundACEMethodCache_2params,t),r=GetNextParamMap(n,s);let a=r.get(i);return a||(a=t.bind(e,s,i),r.set(i,a),a)}_GetBoundACEMethod_3params(t,e,s,i,n){if(!e)throw new Error("missing 'this' binding");const r=GetNextParamMap(this._boundACEMethodCache_3params,t),a=GetNextParamMap(r,s),o=GetNextParamMap(a,i);let l=o.get(n);return l||(l=t.bind(e,s,i,n),o.set(n,l),l)}_SetSingleGlobalObjectClass(t){if(!this.IsSingleGlobal())throw new Error("must be single-global plugin");this._singleGlobalObjectClass=t}GetSingleGlobalObjectClass(){if(!this.IsSingleGlobal())throw new Error("must be single-global plugin");return this._singleGlobalObjectClass}GetSingleGlobalInstance(){if(!this.IsSingleGlobal())throw new Error("must be single-global plugin");return this._singleGlobalObjectClass.GetSingleGlobalInstance()}_InitScriptInterface(){const t=this.GetSdkVersion();C3.AddonManager._PushInitObject(this,t);const e=this.GetScriptInterfaceClass(!0);if(e){if(this._iPlugin=new e,!(this._iPlugin instanceof self.IPlugin))throw new TypeError("plugin class must derive from IPlugin")}else this._iPlugin=new self.IPlugin;C3.AddonManager._PopInitObject(t)}GetIPlugin(){return this._iPlugin}}; } // sdk/sdkDOMPluginBase.js { const C3=self.C3;C3.SDKDOMPluginBase=class extends C3.SDKPluginBase{constructor(e,s){super(e),this._domComponentId=s,this._nextElementId=0,this._instMap=new Map,this.AddElementMessageHandler("elem-focused",e=>e._OnElemFocused()),this.AddElementMessageHandler("elem-blurred",e=>{e&&e._OnElemBlurred()})}Release(){super.Release()}_AddElement(e){const s=this._nextElementId++;return this._instMap.set(s,e),s}_RemoveElement(e){this._instMap.delete(e)}AddElementMessageHandler(e,s){this._runtime.AddDOMComponentMessageHandler(this._domComponentId,e,e=>{const t=this._instMap.get(e["elementId"]);s(t,e)})}}; } // sdk/sdkTypeBase.js { const C3=self.C3;C3.SDKTypeBase=class extends C3.DefendedBase{constructor(e){super(),this._objectClass=e,this._runtime=e.GetRuntime(),this._plugin=e.GetPlugin()}Release(){this._objectClass=null,this._runtime=null,this._plugin=null}GetObjectClass(){return this._objectClass}GetRuntime(){return this._runtime}GetPlugin(){return this._plugin}GetImageInfo(){return this._objectClass.GetImageInfo()}OnCreate(){}FinishCondition(e){}BeforeRunAction(e){}AfterRunAction(e){}LoadTextures(e){}ReleaseTextures(){}ReleaseUnusedTextures(){}OnDynamicTextureLoadComplete(){}PreloadTexturesWithInstances(e){}LoadTilemapData(){}GetScriptInterfaceClass(){return null}DispatchScriptEvent(e,t,s){const n=C3.New(C3.Event,e,t);n.objectClass=this,s&&Object.assign(n,s),this.GetObjectClass().DispatchUserScriptEvent(n)}}; } // sdk/sdkInstanceBase.js { const C3=self.C3;C3.SDKInstanceBase=class extends C3.DefendedBase{constructor(e,t){super(),this._inst=e,this._domComponentId=t,this._wrapperComponentId=null,this._runtime=e.GetRuntime(),this._objectClass=this._inst.GetObjectClass(),this._sdkType=this._objectClass.GetSdkType(),this._tickFunc=null,this._tick2Func=null,this._isTicking=!1,this._isTicking2=!1,this._disposables=null,this._wasReleased=!1}Release(){this._wasReleased=!0,this._StopTicking(),this._StopTicking2(),this._tickFunc=null,this._tick2Func=null,this._disposables&&(this._disposables.Release(),this._disposables=null),this._inst=null,this._runtime=null,this._objectClass=null,this._sdkType=null}WasReleased(){return this._wasReleased}GetInstance(){return this._inst}GetRuntime(){return this._runtime}GetObjectClass(){return this._objectClass}GetPlugin(){return this._sdkType.GetPlugin()}GetSdkType(){return this._sdkType}GetScriptInterface(){return this._inst.GetInterfaceClass()}Trigger(e){return this._runtime.Trigger(e,this._inst,null)}DebugTrigger(e){return this._runtime.DebugTrigger(e,this._inst,null)}TriggerAsync(e){return this._runtime.TriggerAsync(e,this._inst,null)}FastTrigger(e,t){return this._runtime.FastTrigger(e,this._inst,t)}DebugFastTrigger(e,t){return this._runtime.DebugFastTrigger(e,this._inst,t)}ScheduleTriggers(e){return this._runtime.ScheduleTriggers(e)}AddDOMMessageHandler(e,t){this._runtime.AddDOMComponentMessageHandler(this._domComponentId,e,t)}AddDOMMessageHandlers(e){for(const[t,i]of e)this.AddDOMMessageHandler(t,i)}PostToDOM(e,t){this._runtime.PostComponentMessageToDOM(this._domComponentId,e,t)}PostToDOMAsync(e,t){return this._runtime.PostComponentMessageToDOMAsync(this._domComponentId,e,t)}_PostToDOMMaybeSync(e,t){if(!this._runtime.IsInWorker())return window["c3_runtimeInterface"]["_OnMessageFromRuntime"]({"type":"event","component":this._domComponentId,"handler":e,"data":t,"responseId":null});this.PostToDOM(e,t)}SetWrapperExtensionComponentId(e){if(!e)throw new Error("cannot set empty component id");this._wrapperComponentId=e}IsWrapperExtensionAvailable(){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");return this._runtime.HasWrapperComponentId(this._wrapperComponentId)}AddWrapperExtensionMessageHandler(e,t){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");this._runtime.AddWrapperExtensionMessageHandler(this._wrapperComponentId,e,t)}AddWrapperExtensionMessageHandlers(e){for(const[t,i]of e)this.AddWrapperExtensionMessageHandler(t,i)}SendWrapperExtensionMessage(e,t){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");this._runtime.SendWrapperExtensionMessage(this._wrapperComponentId,e,t)}SendWrapperExtensionMessageAsync(e,t){if(!this._wrapperComponentId)throw new Error("wrapper extension component id not set");return this._runtime.SendWrapperExtensionMessageAsync(this._wrapperComponentId,e,t)}Tick(){}Tick2(){}_StartTicking(){if(!this._isTicking){if(!this._tickFunc)if(this._runtime.IsDebug()){const e=globalThis.C3Debugger,t=this.GetPlugin();this._tickFunc=()=>{const i=performance.now();this.Tick(),e.AddIndividualPluginTickTime(t,performance.now()-i)}}else this._tickFunc=()=>this.Tick();this._runtime.Dispatcher().addEventListener("tick",this._tickFunc),this._isTicking=!0}}_StopTicking(){this._isTicking&&(this._runtime.Dispatcher().removeEventListener("tick",this._tickFunc),this._isTicking=!1)}IsTicking(){return this._isTicking}_StartTicking2(){if(!this._isTicking2){if(!this._tick2Func)if(this._runtime.IsDebug()){const e=globalThis.C3Debugger,t=this.GetPlugin();this._tick2Func=()=>{const i=performance.now();this.Tick2(),e.AddIndividualPluginTickTime(t,performance.now()-i)}}else this._tick2Func=()=>this.Tick2();this._runtime.Dispatcher().addEventListener("tick2",this._tick2Func),this._isTicking2=!0}}_StopTicking2(){this._isTicking2&&(this._runtime.Dispatcher().removeEventListener("tick2",this._tick2Func),this._isTicking2=!1)}IsTicking2(){return this._isTicking2}GetDebuggerProperties(){return[]}SaveToJson(){return null}LoadFromJson(e){}GetPropertyValueByIndex(e){}SetPropertyValueByIndex(e,t){}OffsetPropertyValueByIndex(e,t,i){if(0===t)return;const n=this.GetPropertyValueByIndex(e);if("number"!=typeof n)throw new Error("expected number");this.SetPropertyValueByIndex(e,n+t,i)}SetPropertyColorOffsetValueByIndex(e,t,i,n){}CallAction(e,...t){e.call(this,...t)}CallExpression(e,...t){return e.call(this,...t)}GetScriptInterfaceClass(){return null}DispatchScriptEvent(e,t,i){if(!this._inst.HasScriptInterface())return;const n=this.GetScriptInterface(),s=C3.New(C3.Event,e,t);s.instance=n,i&&Object.assign(s,i),n.dispatchEvent(s)}MustPreDraw(){return!1}}; } // sdk/sdkWorldInstanceBase.js { const C3=self.C3;C3.SDKWorldInstanceBase=class extends C3.SDKInstanceBase{constructor(e,t){super(e,t),this._worldInfo=e.GetWorldInfo(),this._renderercontextlost_handler=null,this._renderercontextrestored_handler=null}Release(){if(this._renderercontextlost_handler){const e=this._runtime.Dispatcher();e.removeEventListener("renderercontextlost",this._renderercontextlost_handler),e.removeEventListener("renderercontextrestored",this._renderercontextrestored_handler),this._renderercontextlost_handler=null,this._renderercontextrestored_handler=null}this._worldInfo=null,super.Release()}HandleWebGLContextLoss(){this.HandleRendererContextLoss()}OnWebGLContextLost(){}OnWebGLContextRestored(){}HandleRendererContextLoss(){if(this._renderercontextlost_handler)return;this._renderercontextlost_handler=()=>this.OnRendererContextLost(),this._renderercontextrestored_handler=()=>this.OnRendererContextRestored();const e=this._runtime.Dispatcher();e.addEventListener("renderercontextlost",this._renderercontextlost_handler),e.addEventListener("renderercontextrestored",this._renderercontextrestored_handler)}OnRendererContextLost(){this.OnWebGLContextLost()}OnRendererContextRestored(){this.OnWebGLContextRestored()}GetWorldInfo(){return this._worldInfo}IsOriginalSizeKnown(){return!1}GetOriginalSize(){if(!this.IsOriginalSizeKnown())throw new Error("original size not known");const e=this.GetCurrentImageInfo();if(e)return[e.GetWidth(),e.GetHeight(),0]}GetCurrentImageInfo(){return null}GetCurrentSurfaceSize(){const e=this.GetCurrentImageInfo();if(e){const t=e.GetTexture();if(t)return[t.GetWidth(),t.GetHeight()]}return[100,100]}GetCurrentTexRect(){const e=this.GetCurrentImageInfo();return e?e.GetTexRect():null}GetCurrentTexQuad(){const e=this.GetCurrentImageInfo();return e?e.GetTexQuad():null}IsCurrentTexRotated(){const e=this.GetCurrentImageInfo();return!!e&&e.IsRotated()}GetImagePoint(e){const t=this._inst.GetWorldInfo();return[t.GetX(),t.GetY(),t.GetTotalZ()]}LoadTilemapData(e,t,r){}TestPointOverlapTile(e,t){}RendersToOwnZPlane(){return!0}}; } // sdk/sdkDOMInstanceBase.js { const C3=self.C3,tempRect=C3.New(C3.Rect);C3.SDKDOMInstanceBase=class extends C3.SDKWorldInstanceBase{constructor(e,t){super(e,t),this._elementId=this.GetPlugin()._AddElement(this),this._isElementShowing=!0,this._elemHasFocus=!1,this._autoFontSize=!1,this._autoFontSizeOffset=-.2,this._lastRect=C3.New(C3.Rect,0,0,-1,-1);const s=this._runtime.GetCanvasManager();this._lastWindowWidth=s.GetLastWidth(),this._lastWindowHeight=s.GetLastHeight(),this._lastHTMLIndex=-1,this._lastHTMLZIndex=-1,this._isPendingUpdateState=!1,this._StartTicking()}Release(){this.GetPlugin()._RemoveElement(this._elementId),this.PostToDOMElement("destroy"),this._elementId=-1,super.Release()}_GetElementInDOMMode(){if(this._runtime.IsInWorker())throw new Error("not valid in worker mode");return this._PostToDOMElementMaybeSync("get-element")}PostToDOMElement(e,t){t||(t={}),t["elementId"]=this._elementId,this.PostToDOM(e,t)}_PostToDOMElementMaybeSync(e,t){return t||(t={}),t["elementId"]=this._elementId,this._PostToDOMMaybeSync(e,t)}PostToDOMElementAsync(e,t){return t||(t={}),t["elementId"]=this._elementId,this.PostToDOMAsync(e,t)}CreateElement(e){e||(e={});const t=this.GetWorldInfo();e["elementId"]=this._elementId,e["isVisible"]=t.IsVisible(),e["htmlIndex"]=t.GetLayer().GetHTMLIndex(),e["htmlZIndex"]=t.GetHTMLZIndex(),Object.assign(e,this.GetElementState()),this._isElementShowing=!!e["isVisible"],this._PostToDOMMaybeSync("create",e),this._UpdatePosition(!0)}SetElementVisible(e){e=!!e,this._isElementShowing!==e&&(this._isElementShowing=e,this.PostToDOMElement("set-visible",{"isVisible":e}))}Tick(){this._UpdatePosition(!1)}_ShouldPreserveElement(){const e=this._runtime.GetCanvasManager().GetFullscreenMode();return"Android"===C3.Platform.OS&&("scale-inner"===e||"integer-scale-inner"===e||"scale-outer"===e||"integer-scale-outer"===e||"crop"===e)}_UpdatePosition(e){if(this.GetInstance().IsDestroyed())return;const t=this.GetWorldInfo(),s=t.GetLayer(),i=t.GetBoundingBox();let[n,l]=s.LayerToCanvasCss(i.getLeft(),i.getTop()),[o,h]=s.LayerToCanvasCss(i.getRight(),i.getBottom());const a=this._runtime.GetCanvasManager(),d=a.GetCssWidth(),m=a.GetCssHeight();if(!t.IsVisible()||!s.IsVisible())return void this.SetElementVisible(!1);if(!this._ShouldPreserveElement()&&(o<=0||h<=0||n>=d||l>=m))return void this.SetElementVisible(!1);tempRect.set(n,l,o,h);const r=a.GetLastWidth(),_=a.GetLastHeight(),c=s.GetHTMLIndex(),u=t.GetHTMLZIndex();if(!e&&tempRect.equals(this._lastRect)&&this._lastWindowWidth===r&&this._lastWindowHeight===_&&this._lastHTMLIndex===c&&this._lastHTMLZIndex===u)return void this.SetElementVisible(!0);this._lastRect.copy(tempRect),this._lastWindowWidth=r,this._lastWindowHeight=_,this._lastHTMLIndex=c,this._lastHTMLZIndex=u,this.SetElementVisible(!0);let M=null;this._autoFontSize&&(M=s.GetDisplayScale()+this._autoFontSizeOffset),this._PostToDOMElementMaybeSync("update-position",{"left":Math.round(this._lastRect.getLeft()),"top":Math.round(this._lastRect.getTop()),"width":Math.round(this._lastRect.width()),"height":Math.round(this._lastRect.height()),"htmlIndex":c,"htmlZIndex":u,"fontSize":M})}FocusElement(){this._PostToDOMElementMaybeSync("focus",{"focus":!0})}BlurElement(){this._PostToDOMElementMaybeSync("focus",{"focus":!1})}_OnElemFocused(){this._elemHasFocus=!0}_OnElemBlurred(){this._elemHasFocus=!1}IsElementFocused(){return this._elemHasFocus}SetElementCSSStyle(e,t){this.PostToDOMElement("set-css-style",{"prop":C3.CSSToCamelCase(e),"val":t})}SetElementAttribute(e,t){this.PostToDOMElement("set-attribute",{"name":e,"val":t})}RemoveElementAttribute(e){this.PostToDOMElement("remove-attribute",{"name":e})}UpdateElementState(){this._isPendingUpdateState||(this._isPendingUpdateState=!0,Promise.resolve().then(()=>{this._isPendingUpdateState=!1,this.PostToDOMElement("update-state",this.GetElementState())}))}GetElementState(){}GetElementId(){return this._elementId}}; } // sdk/sdkBehaviorBase.js { const C3=self.C3,IBehavior=self.IBehavior;C3.SDKBehaviorBase=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e.runtime,this._id=e.id,this._name=e.name??"",this._myObjectClasses=C3.New(C3.ArraySet),this._myInstances=C3.New(C3.ArraySet),this._sdkVersion=e.sdkVersion,this._scriptInterfaceClass=e.scriptInterfaceClass,this._iBehavior=null}Release(){this._myInstances.Release(),this._myObjectClasses.Release(),this._runtime=null}GetRuntime(){return this._runtime}GetID(){return this._id}GetName(){return this._name}OnCreate(){}GetSdkVersion(){return this._sdkVersion}GetScriptInterfaceClass(e=!1){let s=this._scriptInterfaceClass;return e&&"function"!=typeof s&&this.GetSdkVersion()>=2&&(s=globalThis.ISDKBehaviorBase),s}_AddObjectClass(e){this._myObjectClasses.Add(e)}GetObjectClasses(){return this._myObjectClasses.GetArray()}_AddInstance(e){this._myInstances.Add(e)}_RemoveInstance(e){this._myInstances.Delete(e)}GetInstances(){return this._myInstances.GetArray()}_InitScriptInterface(){const e=this.GetSdkVersion();C3.AddonManager._PushInitObject(this,e);const s=this.GetScriptInterfaceClass(!0);if(s){if(this._iBehavior=new s,!(this._iBehavior instanceof IBehavior))throw new TypeError("behavior class must derive from IBehavior")}else this._iBehavior=new IBehavior;C3.AddonManager._PopInitObject(e)}GetIBehavior(){return this._iBehavior}}; } // sdk/sdkBehaviorTypeBase.js { const C3=self.C3;C3.SDKBehaviorTypeBase=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e.GetRuntime(),this._behaviorType=e,this._objectClass=e.GetObjectClass(),this._behavior=e.GetBehavior(),this._behavior._AddObjectClass(this._objectClass)}Release(){this._runtime=null,this._behaviorType=null,this._objectClass=null,this._behavior=null}OnCreate(){}GetBehaviorType(){return this._behaviorType}GetObjectClass(){return this._objectClass}GetRuntime(){return this._runtime}GetBehavior(){return this._behavior}}; } // sdk/sdkBehaviorInstanceBase.js { const C3=self.C3;C3.SDKBehaviorInstanceBase=class extends C3.DefendedBase{constructor(t,i){super(),this._behInst=t,this._domComponentId=i,this._inst=t.GetObjectInstance(),this._runtime=t.GetRuntime(),this._behaviorType=t.GetBehaviorType(),this._sdkType=this._behaviorType.GetSdkType(),this._isTicking=!1,this._isTicking2=!1,this._isPostTicking=!1,this._disposables=null}Release(){this._StopTicking(),this._StopTicking2(),this._StopPostTicking(),this._disposables&&(this._disposables.Release(),this._disposables=null),this._behInst=null,this._inst=null,this._runtime=null,this._behaviorType=null,this._sdkType=null}GetBehavior(){return this._behaviorType.GetBehavior()}GetBehaviorInstance(){return this._behInst}GetObjectInstance(){return this._inst}GetObjectClass(){return this._inst.GetObjectClass()}GetWorldInfo(){return this._inst.GetWorldInfo()}GetRuntime(){return this._runtime}GetBehaviorType(){return this._behaviorType}GetSdkType(){return this._sdkType}GetScriptInterface(){return this._behInst.GetScriptInterface()}Trigger(t){return this._runtime.Trigger(t,this._inst,this._behaviorType)}DebugTrigger(t){return this._runtime.DebugTrigger(t,this._inst,this._behaviorType)}TriggerAsync(t){return this._runtime.TriggerAsync(t,this._inst,this._behaviorType)}PostCreate(){}Tick(){}Tick2(){}PostTick(){}_StartTicking(){this._isTicking||(this._runtime._AddBehInstToTick(this),this._isTicking=!0)}_StopTicking(){this._isTicking&&(this._runtime._RemoveBehInstToTick(this),this._isTicking=!1)}IsTicking(){return this._isTicking}_StartTicking2(){this._isTicking2||(this._runtime._AddBehInstToTick2(this),this._isTicking2=!0)}_StopTicking2(){this._isTicking2&&(this._runtime._RemoveBehInstToTick2(this),this._isTicking2=!1)}IsTicking2(){return this._isTicking2}_StartPostTicking(){this._isPostTicking||(this._runtime._AddBehInstToPostTick(this),this._isPostTicking=!0)}_StopPostTicking(){this._isPostTicking&&(this._runtime._RemoveBehInstToPostTick(this),this._isPostTicking=!1)}IsPostTicking(){return this._isPostTicking}GetDebuggerProperties(){return[]}AddDOMMessageHandler(t,i){this._runtime.AddDOMComponentMessageHandler(this._domComponentId,t,i)}OnSpriteFrameChanged(t,i){}SaveToJson(){return null}LoadFromJson(t){}GetPropertyValueByIndex(t){}SetPropertyValueByIndex(t,i){}OffsetPropertyValueByIndex(t,i){if(0===i)return;const e=this.GetPropertyValueByIndex(t);if("number"!=typeof e)throw new Error("expected number");this.SetPropertyValueByIndex(t,e+i)}SetPropertyColorOffsetValueByIndex(t,i,e,s){}CallAction(t,...i){t.call(this,...i)}CallExpression(t,...i){return t.call(this,...i)}GetScriptInterfaceClass(){return null}DispatchScriptEvent(t,i,e){if(!this._behInst.HasScriptInterface())return;const s=this.GetScriptInterface(),n=C3.New(C3.Event,t,i);n.behaviorInstance=s,n.instance=s.instance,e&&Object.assign(n,e),s.dispatchEvent(n)}}; } // objects/addonManager.js { const C3=self.C3;C3.Plugins={},C3.Behaviors={};const internalApiToken=C3._GetInternalAPIToken();function ValidateInternalAPIToken(t){if(t!==internalApiToken)throw new Error("invalid internal API token")}let initObjectStack=[],initObjectStack2=[],initPropertiesStack=[],originalPushInitObject=null,originalPopInitObject=null,originalGetInitObject=null,originalGetInitObject2=null;const pluginsByCtor=new Map,behaviorsByCtor=new Map;C3.AddonManager=class extends C3.DefendedBase{#t=null;#e=[];#i=null;#n=[];#r=new Map;#o=null;#s=null;#a;constructor(t,e){super(),this.#t=t,this.#a=new Set(e)}CreatePlugin(t){const e=t[19],i=this.#t.GetObjectReference(t[0]);if(!i)throw new Error("missing plugin");C3.AddCommonACEs(t,i,e);const n=e>=2?C3.SDKPluginBase:i,r=C3.New(n,{runtime:this.#t,isSingleGlobal:t[1],isWorld:t[2],isRotatable:t[5],hasEffects:t[8],mustPredraw:t[9],supportsSceneGraph:t[13],supportsMesh:t[14],isHTMLElementType:t[17],is3d:t[18],sdkVersion:e,id:t[20],name:t[21],scriptInterfaceClass:e>=2?i:null,supportsChangingSampling:t[22],supportsZElevation:t[23],exportData:t[24]});r.OnCreate(),this.#e.push(r),pluginsByCtor.set(i,r)}CreateSystemPlugin(){this.#i=C3.New(C3.Plugins.System,{runtime:this.#t,isSingleGlobal:!0}),this.#i.OnCreate()}CreateBehavior(t){const e=t[1],i=t[2],n=t[3],r=this.#t.GetObjectReference(t[0]);if(!r)throw new Error("missing behavior");this.#r.set(r,()=>{const t=e>=2?C3.SDKBehaviorBase:r,o=C3.New(t,{runtime:this.#t,id:i,name:n,sdkVersion:e,scriptInterfaceClass:e>=2?r:null});o.OnCreate(),this.#n.push(o),behaviorsByCtor.set(r,o),!this.#o&&C3.Behaviors.solid&&o instanceof C3.Behaviors.solid?this.#o=o:!this.#s&&C3.Behaviors.jumpthru&&o instanceof C3.Behaviors.jumpthru&&(this.#s=o),o._InitScriptInterface()})}_DelayCreateBehavior(t){const e=this.#r.get(t);e&&(e(),this.#r.delete(t))}static _PushInitObject(t,e=1){if(C3.AddonManager._PushInitObject!==originalPushInitObject)throw new Error("invalid method");1===e&&initObjectStack.push(t),initObjectStack2.push(t)}static _PopInitObject(t=1){if(C3.AddonManager._PopInitObject!==originalPopInitObject)throw new Error("invalid method");1===t&&initObjectStack.pop(),initObjectStack2.pop()}static _GetInitObject(){if(C3.AddonManager._GetInitObject!==originalGetInitObject)throw new Error("invalid method");if(0===initObjectStack.length)throw new Error("no init object set");return initObjectStack.at(-1)}static _GetInitObject2(t){if(C3.AddonManager._GetInitObject2!==originalGetInitObject2)throw new Error("invalid method");if(ValidateInternalAPIToken(t),0===initObjectStack2.length)throw new Error("no init object set");return initObjectStack2.at(-1)}static _PushInitProperties(t){initPropertiesStack.push(t)}static _PopInitProperties(){initPropertiesStack.pop()}static _GetInitProperties(){if(0===initPropertiesStack.length)throw new Error("no init properties set");return initPropertiesStack.at(-1)}_InitAddonScriptInterfaces(){for(const t of this.#e)t._InitScriptInterface()}static GetPluginByConstructorFunction(t){return pluginsByCtor.get(t)||null}static GetBehaviorByConstructorFunction(t){return behaviorsByCtor.get(t)||null}GetSystemPlugin(){return this.#i}GetSolidBehavior(){return this.#o}GetJumpthruBehavior(){return this.#s}HasWrapperComponentId(t){return this.#a.has(t)}},originalPushInitObject=C3.AddonManager._PushInitObject,originalPopInitObject=C3.AddonManager._PopInitObject,originalGetInitObject=C3.AddonManager._GetInitObject,originalGetInitObject2=C3.AddonManager._GetInitObject2; } // objects/imageInfo.js { const C3=self.C3,allImageInfos=new Set;C3.ImageInfo=class extends C3.DefendedBase{constructor(){super(),this._generation=0,this._url="",this._size=0,this._offsetX=0,this._offsetY=0,this._width=0,this._height=0,this._isRotated=!1,this._hasMetaData=!1,this._imageAsset=null,this._textureState="",this._rcTex=C3.New(C3.Rect),this._quadTex=C3.New(C3.Quad2D),this._blobUrl="",this._iImageInfo=new self.IImageInfo(this),allImageInfos.add(this)}Release(){this.ReleaseTexture(),this._imageAsset&&0===this._imageAsset.GetRefCount()&&this._imageAsset.Release(),this._imageAsset=null,allImageInfos.delete(this),this.ReleaseBlobURL()}static OnRendererContextLost(){for(const t of allImageInfos)t._textureState="",t._rcTex.set(0,0,0,0),t._quadTex.setFromRect(t._rcTex)}LoadData(t){this._url=t[0]??t["url"],this._size=t[1]??t["size"],this._offsetX=t[2]??t["offset-x"],this._offsetY=t[3]??t["offset-y"],this._width=t[4]??t["width"],this._height=t[5]??t["height"],this._isRotated=t[6]??t["rotated"],this._hasMetaData=!0}LoadDynamicAsset(t,e,s){if(s=!!s,this._imageAsset)throw new Error("already loaded asset");this._url=e;const i={isTiled:s};return C3.IsAbsoluteURL(e)&&(i.loadPolicy="remote"),this.LoadAsset(t,i),this._imageAsset.Load()}LoadDynamicBlobAsset(t,e){if(this._imageAsset)throw new Error("already loaded asset");this._url="",this._size=e.size,this._imageAsset=C3.New(C3.ImageAsset,t.GetAssetManager(),{blob:e,size:this._size,loadPolicy:"local"})}ReplaceWith(t){if(t===this)throw new Error("cannot replace with self");this._generation++,this.ReleaseTexture(),this._url=t._url,this._size=t._size,this._offsetX=t._offsetX,this._offsetY=t._offsetY,this._width=t._width,this._height=t._height,this._isRotated=t._isRotated,this._hasMetaData=t._hasMetaData,this._imageAsset=t._imageAsset,this._textureState=t._textureState,this._rcTex=t._rcTex,this._quadTex=t._quadTex,this.ReleaseBlobURL()}GetURL(){return this._url}GetSize(){return this._size}GetOffsetX(){return this._offsetX}GetOffsetY(){return this._offsetY}IsRotated(){return this._isRotated}GetWidth(){return this._width}GetHeight(){return this._height}GetSheetWidth(){return this._imageAsset.GetWidth()}GetSheetHeight(){return this._imageAsset.GetHeight()}LoadAsset(t,e){if(this._imageAsset)throw new Error("already got asset");e=Object.assign({},e,{url:this.GetURL(),size:this.GetSize()}),this._imageAsset=t.LoadImage(e)}IsLoaded(){return this._imageAsset&&this._imageAsset.IsLoaded()}async LoadStaticTexture(t,e){if(!this._imageAsset)throw new Error("no asset");if(this._textureState)throw new Error("already loaded texture");const s=this._generation;this._textureState="loading";const i=await this._imageAsset.LoadStaticTexture(t,e);if(this._generation!==s)return null;if(!i)return this._textureState="",null;this._textureState="loaded",this._hasMetaData||(this._width=i.GetWidth(),this._height=i.GetHeight(),this._hasMetaData=!0);const h=this._isRotated?this._height:this._width,a=this._isRotated?this._width:this._height;return this._rcTex.set(this._offsetX,this._offsetY,this._offsetX+h,this._offsetY+a),this._rcTex.divide(i.GetWidth(),i.GetHeight()),this._quadTex.setFromRect(this._rcTex),this._isRotated&&this._quadTex.rotatePointsAnticlockwise(),i}ReleaseTexture(){this._textureState&&(this._imageAsset&&this._imageAsset.ReleaseTexture(),this._textureState="",this._rcTex.set(0,0,0,0),this._quadTex.setFromRect(this._rcTex))}GetTexture(){return this._imageAsset&&"loaded"===this._textureState?this._imageAsset.GetTexture():null}GetTexRect(){return this._rcTex}GetTexQuad(){return this._quadTex}GetIImageInfo(){return this._iImageInfo}GetImageAsset(){return this._imageAsset}async ExtractImageToCanvas(t){t||(t=await this._imageAsset.LoadToDrawable()),this._hasMetaData||(this._width=t.width,this._height=t.height,this._hasMetaData=!0);const e=C3.CreateCanvas(this._width,this._height),s=e.getContext("2d");return this._isRotated?(s.rotate(Math.PI/-2),s.translate(-this._height,0),s.drawImage(t,this._offsetX,this._offsetY,this._height,this._width,0,0,this._height,this._width)):s.drawImage(t,this._offsetX,this._offsetY,this._width,this._height,0,0,this._width,this._height),e}async ExtractImageToBlobURL(t){if(this._blobUrl)return this._blobUrl;const e=await this.ExtractImageToCanvas(t),s=await C3.CanvasToBlob(e);return this._blobUrl=URL.createObjectURL(s),this._blobUrl}ReleaseBlobURL(){this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl="")}}; } // objects/animationInfo.js { const C3=self.C3;C3.AnimationInfo=class extends C3.DefendedBase{constructor(e){super(),this._name=e[0],this._speed=e[1],this._isLooping=!!e[2],this._repeatCount=e[3],this._repeatTo=e[4],this._isPingPong=!!e[5],this._sid=e[6],this._frames=e[7].map(e=>C3.New(C3.AnimationFrameInfo,e)),this._iAnimation=new self.IAnimation(this)}static CreateDynamic(e,t){const r=C3.New(C3.AnimationInfo,[t,0,!1,0,0,!1,Math.floor(1e15*Math.random()),[]]);return r._frames.push(C3.AnimationFrameInfo.CreateDynamic(e)),r}Release(){for(const e of this._frames)e.Release();C3.clearArray(this._frames)}LoadAllAssets(e){for(const t of this._frames)t.GetImageInfo().LoadAsset(e)}LoadAllTextures(e,t){return Promise.all(this._frames.map(r=>r.GetImageInfo().LoadStaticTexture(e,t)))}ReleaseAllTextures(){for(const e of this._frames)e.GetImageInfo().ReleaseTexture()}GetName(){return this._name}GetSID(){return this._sid}GetFrameCount(){return this._frames.length}GetFrames(){return this._frames}GetFrameAt(e){if((e=Math.floor(e))<0||e>=this._frames.length)throw new RangeError("invalid frame");return this._frames[e]}InsertFrameAt(e,t){(t=Math.floor(t))<0?this._frames.unshift(e):t>=this._frames.length?this._frames.push(e):this._frames.splice(t,0,e)}RemoveFrameAt(e){if((e=Math.floor(e))<0||e>=this._frames.length)throw new RangeError("invalid frame");this._frames[e].Release(),this._frames.splice(e,1)}GetFrameIndexByTag(e){for(let t=0,r=this._frames.length;t{const t=atob("iVBORw0KGgoAAAANSUhEUgAAAGQAAABkAQMAAABKLAcXAAAAAXNSR0IArs4c6QAAAANQTFRFAAAAp3o92gAAAAF0Uk5TAEDm2GYAAAATSURBVBgZYxgFo2AUjIJRQFcAAAV4AAHcRQIbAAAAAElFTkSuQmCC"),i=new Uint8Array(t.length);for(let e=0,n=t.length;eC3.New(C3.ImagePoint,this,t)),this._imagePointsByName=new Map;for(const t of this._imagePoints)this._imagePointsByName.set(t.GetName().toLowerCase(),t);this._collisionPoly=null;const i=t[11];i.length>=6&&(this._collisionPoly=C3.New(C3.CollisionPoly,i)),this._tag=t[12]?t[12]:"",this._iAnimationFrame=new self.IAnimationFrame(this)}static CreateDynamic(t){const i=C3.New(C3.AnimationFrameInfo,["",0,0,0,100,100,!1,1,0,0,[],[],""]);return i._imageInfo.LoadDynamicBlobAsset(t,EMPTY_IMAGE_BLOB),i}Release(){this._collisionPoly&&(this._collisionPoly.Release(),this._collisionPoly=null),this._imageInfo.Release(),this._imageInfo=null}GetImageInfo(){return this._imageInfo}GetDuration(){return this._duration}GetOriginX(){return this._origin.getX()}GetOriginY(){return this._origin.getY()}GetCollisionPoly(){return this._collisionPoly}GetImagePointByName(t){return this._imagePointsByName.get(t.toLowerCase())||null}GetImagePointByIndex(t){return(t=Math.floor(t))<0||t>=this._imagePoints.length?null:this._imagePoints[t]}GetImagePointCount(){return this._imagePoints.length}GetTag(){return this._tag}GetIAnimationFrame(){return this._iAnimationFrame}}; } // objects/imagePoint.js { const C3=self.C3;C3.ImagePoint=class extends C3.DefendedBase{constructor(e,t){super(),this._afi=e,this._name=t[0],this._pos=C3.New(C3.Vector2,t[1],t[2])}Release(){}GetName(){return this._name}GetX(){return this._pos.getX()}GetY(){return this._pos.getY()}GetVec2(){return this._pos}}; } // objects/objectClass.js { const C3=globalThis.C3,C3Debugger=globalThis.C3Debugger,IObjectClass=globalThis.IObjectClass,IObjectType=globalThis.IObjectType,IFamily=globalThis.IFamily,assert=globalThis.assert;C3.ObjectClass=class extends C3.DefendedBase{constructor(t,e,s){super();const i=t.GetObjectReference(s[1]);this._runtime=t,this._plugin=C3.AddonManager.GetPluginByConstructorFunction(i),this._sdkType=null,this._instSdkCtor=i.Instance,this._index=e,this._sid=s[11],this._name=s[0],this._jsPropName=this._runtime.GetJsPropName(s[14]),this._isGlobal=!!s[9],this._isFamily=!!s[2],this._isOnLoaderLayout=!!s[10],this._instVars=s[3].map(e=>({sid:e[0],type:e[1],name:e[2],jsPropName:t.GetJsPropName(e[3])})),this._behaviorsCount=s[4],this._effectsCount=s[5],this._isWorldType=this._plugin.IsWorldType(),this._dispatcher=C3.New(C3.Event.Dispatcher),this._effectList=null;const[n,a]=t.GetCollisionEngine().GetCollisionCellSize();if(this._collisionGrid=C3.New(C3.SparseGrid,n,a),this._anyCollisionCellChanged=!0,this._familyMembers=null,this._familyMembersSet=null,this._familyIndex=-1,this._families=null,this._familiesSet=null,this._familyInstVarMap=null,this._familyBehaviorMap=null,this._familyEffectMap=null,this._isInContainer=!1,this._container=null,this._behaviorTypes=s[8].map(t=>C3.BehaviorType.Create(this,t)),this._behaviorTypesIncludingInherited=[],this._behaviorsByName=new Map,this._behaviorNameToIndex=new Map,this._usedBehaviorCtors=new Set,this._customActionMap=new Map,this._solStack=C3.New(C3.SolStack,this),this._defaultInstanceData=null,this._defaultLayerIndex=0,this._isContained=!1,this._container=null,this._imageInfo=null,this._animations=null,this._animationsByName=null,this._animationsBySid=null,this._textureRefCount=0,this._savedData=new Map,this._instances=[],this._worldInfosByLayer=new Map,this._iidsStale=!0,this._plugin.HasEffects()&&(this._effectList=C3.New(C3.EffectList,this,s[12])),s[6]&&(this._imageInfo=C3.New(C3.ImageInfo),this._imageInfo.LoadData(s[6])),s[7]){this._animations=s[7].map(t=>C3.New(C3.AnimationInfo,t)),this._animationsByName=new Map,this._animationsBySid=new Map;for(const t of this._animations)this._animationsByName.set(t.GetName().toLowerCase(),t),this._animationsBySid.set(t.GetSID(),t)}this._isFamily?(this._familyMembers=[],this._familyMembersSet=new Set,this._familyIndex=this._runtime._GetNextFamilyIndex()):(this._families=[],this._familiesSet=new Set,this._familyInstVarMap=[],this._familyBehaviorMap=[],this._familyEffectMap=[]);const r=this._plugin.GetSdkVersion();if(r<2&&(this._sdkType=C3.New(i.Type,this,s[15]),!(this._sdkType instanceof C3.SDKTypeBase)))throw new Error("v1 sdk type must derive from SDKTypeBase");let o;if(this._iObjectClass=null,this._instanceUserScriptClass=null,this._userScriptDispatcher=C3.New(C3.Event.Dispatcher),C3.AddonManager._PushInitObject(this,r),r>=2?(o=i.Type,o||(o=globalThis.ISDKObjectTypeBase)):o=this._sdkType.GetScriptInterfaceClass(),o&&!this._isFamily){if(this._iObjectClass=new o(r<2?this:null),r<2&&!(this._iObjectClass instanceof IObjectType))throw new TypeError("script interface class must derive from IObjectType");if(r>=2&&!(this._iObjectClass instanceof globalThis.ISDKObjectTypeBase))throw new TypeError("script interface class must derive from ISDKObjectTypeBase")}else{const t=this._isFamily?IFamily:IObjectType;this._iObjectClass=new t}if(C3.AddonManager._PopInitObject(r),s[13]){const t=s[13];if(t){const e=t[0],s=t[1],i=t[2];this._sdkType.LoadTilemapData(e,s,i)}}this._runtime.UsesLoaderLayout()&&!this._isFamily&&!this._isOnLoaderLayout&&this._isWorldType||this.OnCreate(),this._plugin.IsSingleGlobal()&&(this._plugin._SetSingleGlobalObjectClass(this),this._CreateSingleGlobalInstance(s)),this._loadInstancesJson=null}static Create(t,e,s){return C3.New(C3.ObjectClass,t,e,s)}Release(){if(this._dispatcher.Release(),this._dispatcher=null,this._imageInfo&&(this._imageInfo.Release(),this._imageInfo=null),this._animations){for(const t of this._animations)t.Release();C3.clearArray(this._animations),this._animationsByName.clear(),this._animationsBySid.clear()}this._loadInstancesJson=null,this._solStack.Release(),this._solStack=null,this._savedData.clear(),this._container=null,this._runtime=null}_LoadFamily(t){for(let e=1,s=t.length;e0}async LoadTextures(t){this._isFamily||(this._textureRefCount++,1===this._textureRefCount&&(this._sdkType?await this._sdkType.LoadTextures(t):await this._iObjectClass._loadTextures(this._runtime.GetCanvasManager().GetIRenderer())))}ReleaseTextures(){if(!this._isFamily){if(this._textureRefCount--,this._textureRefCount<0)throw new Error("released textures too many times");0===this._textureRefCount&&(this._sdkType?this._sdkType.ReleaseTextures():this._iObjectClass._releaseTextures(this._runtime.GetCanvasManager().GetIRenderer()))}}ReleaseUnusedTextures(){this._sdkType.ReleaseUnusedTextures()}OnDynamicTextureLoadComplete(){if(this._isFamily)throw new Error("not applicable to family");this._sdkType?this._sdkType.OnDynamicTextureLoadComplete():this._iObjectClass._onDynamicTextureLoadComplete()}async PreloadTexturesWithInstances(t){this._isFamily||(this._sdkType?await this._sdkType.PreloadTexturesWithInstances(t):await this._iObjectClass._preloadTexturesWithInstances(this._runtime.GetCanvasManager().GetIRenderer()))}GetRuntime(){return this._runtime}GetPlugin(){return this._plugin}GetInstanceSdkCtor(){return this._instSdkCtor}GetName(){return this._name}GetJsPropName(){return this._jsPropName}GetIndex(){return this._index}GetSID(){return this._sid}IsFamily(){return this._isFamily}IsGlobal(){return this._isGlobal}IsWorldType(){return this._isWorldType}GetFamilyIndex(){return this._familyIndex}GetBehaviorTypes(){return this._behaviorTypes}GetBehaviorTypesCount(){return this._behaviorsCount}UsesBehaviorByCtor(t){return t&&this._usedBehaviorCtors.has(t)}GetInstanceVariablesCount(){return this._instVars.length}GetInstanceVariableSIDs(){return this._instVars.map(t=>t.sid)}GetInstanceVariableIndexBySID(t){return this._instVars.findIndex(e=>e.sid===t)}GetInstanceVariableIndexByName(t){return this._instVars.findIndex(e=>e.name===t)}_GetAllInstanceVariableNames(){return this._instVars.map(t=>t.name)}_GetAllInstanceVariableJsPropNames(){return this._instVars.map(t=>t.jsPropName)}GetInstanceVariableType(t){if((t=Math.floor(t))<0||t>=this._instVars.length)throw new RangeError("invalid instance variable index");return this._instVars[t].type}GetInstanceVariableName(t){if((t=Math.floor(t))<0||t>=this._instVars.length)throw new RangeError("invalid instance variable index");return this._instVars[t].name}GetEffectTypesCount(){return this._effectsCount}GetBehaviorTypesIncludingInherited(){return this._behaviorTypesIncludingInherited}GetBehaviorTypeByName(t){return this._behaviorsByName.get(t.toLowerCase())||null}GetBehaviorIndexByName(t){const e=this._behaviorNameToIndex.get(t.toLowerCase());return void 0===e?-1:e}GetEffectList(){return this._effectList}HasEffects(){return this._plugin.HasEffects()}UsesEffects(){return this._effectList&&this._effectList.HasAnyEffectType()}GetSolStack(){return this._solStack}GetCurrentSol(){return this._solStack.GetCurrentSol()}GetImageInfo(){return this._imageInfo}SetDefaultInstanceData(t){this._defaultInstanceData=t}GetDefaultInstanceData(){return this._defaultInstanceData}_SetDefaultLayerIndex(t){this._defaultLayerIndex=t}GetDefaultLayerIndex(){return this._defaultLayerIndex}GetAnimations(){return this._animations}GetAnimationCount(){return this._animations.length}GetFamilies(){return this._families}BelongsToFamily(t){return this._familiesSet.has(t)}GetFamilyMembers(){return this._familyMembers}FamilyHasMember(t){return this._familyMembersSet.has(t)}GetFamilyBehaviorOffset(t){return this._familyBehaviorMap[t]}GetFamilyInstanceVariableOffset(t){return this._familyInstVarMap[t]}AddCustomAction(t){this._customActionMap.set(t.GetACEName().toLowerCase(),t)}HasOwnCustomActionByName(t){return!!this.GetOwnCustomActionByName(t)}GetOwnCustomActionByName(t){const e=this._customActionMap.get(t.toLowerCase());return e&&e.IsEnabled()?e:null}GetAllAnimations(){return this._animations}GetAnimationByName(t){if(!this._animations)throw new Error("no animations");return this._animationsByName.get(t.toLowerCase())||null}GetAnimationBySID(t){if(!this._animations)throw new Error("no animations");return this._animationsBySid.get(t)||null}AddAnimation(t){if(this.GetAnimationByName(t))throw new Error(`animation name '${t}' already exists`);const e=C3.AnimationInfo.CreateDynamic(this.GetRuntime(),t);return this._animations.push(e),this._animationsByName.set(e.GetName().toLowerCase(),e),this._animationsBySid.set(e.GetSID(),e),e}RemoveAnimation(t){const e=this.GetAnimationByName(t);if(!e)throw new Error(`animation name '${t}' does not exist`);if(1===this._animations.length)throw new Error("cannot remove last animation");const s=this._animations.indexOf(e);this._animations.splice(s,1),this._animationsByName.delete(e.GetName().toLowerCase()),this._animationsBySid.delete(e.GetSID()),e.Release()}GetFirstAnimation(){if(!this._animations)throw new Error("no animations");return this._animations[0]}GetFirstAnimationFrame(){return this.GetFirstAnimation().GetFrameAt(0)}GetDefaultInstanceSize(){if(this._animations){const t=this.GetFirstAnimationFrame().GetImageInfo();return[t.GetWidth(),t.GetHeight()]}return this._imageInfo?[this._imageInfo.GetWidth(),this._imageInfo.GetHeight()]:[100,100]}GetSingleGlobalInstance(){if(!this._plugin.IsSingleGlobal())throw new Error("not a single-global plugin");return this._instances[0]}GetInstances(){return this._instances}*instances(){yield*this._instances}*instancesIncludingPendingCreate(){yield*this._instances,yield*this._runtime.instancesPendingCreateForObjectClass(this)}GetInstanceCount(){return this._instances.length}_AddInstance(t){this._instances.push(t)}_SetIIDsStale(){this._iidsStale=!0}_UpdateIIDs(){if(!this._iidsStale||this._isFamily)return;const t=this._instances;let e=0;for(let s=t.length;e0?e[t.GetIID()%e.length]:null}*allCorrespondingInstances(t,e){const s=this.GetCurrentSol().GetInstances(),i=s.length,n=e.GetCurrentSol(),a=e.GetCurrentSol().GetInstances(),r=a.length;let o=t.GetIID();!e.IsFamily()&&n.IsSelectAll()||(o=a.indexOf(t));const h=Math.ceil(i/r),l=i%r;let _=0,c=0;0===l||ot.SaveToJson())};return this._savedData&&this._savedData.size&&(t["ex"]=C3.ToSuperJSON(this._savedData)),t}_LoadFromJson(t,e){this._savedData&&(this._savedData.clear(),this._savedData=null);const s=t["ex"];s&&(this._savedData=C3.FromSuperJSON(s));const i=this._instances,n=t["instances"];for(let t=0,e=Math.min(i.length,n.length);te.IsWorldType())}}; } // objects/instance.js { const C3=self.C3,C3Debugger=self.C3Debugger,IInstance=self.IInstance,originalAddonManager=C3.AddonManager,EMPTY_ARRAY=[],EMPTY_SET=new Set;let nextPuid=0;const savedDataMaps=new WeakMap,FLAG_DESTROYED=1,FLAG_TILEMAP=2,FLAG_MUST_PREDRAW=4,FLAG_SOLID_ENABLED=8,FLAG_SOLID_USES_INSTANCE_TAGS=16,FLAG_JUMPTHRU_ENABLED=32,FLAG_MUST_MITIGATE_Z_FIGHTING=32,FLAG_IS_DRAWING_WITH_EFFECTS=64;C3.Instance=class extends C3.DefendedBase{#t=null;constructor(t){if(C3.AddonManager!==originalAddonManager)throw new Error("invalid addon manager");super(),this._runtime=t.runtime,this._objectType=t.objectType,this._worldInfo=null,this._sdkInst=null,this._iScriptInterface=null,this._iid=0,this._uid=t.uid,this._puid=nextPuid++,this._flags=0;const e=C3.splitStringAndNormalize(t.tags);e.length>0&&this.SetTagsSet(new Set(e)),this._instVarValues=EMPTY_ARRAY,this._behaviorInstances=EMPTY_ARRAY;const s=this._objectType.GetBehaviorTypesIncludingInherited();s.length>0&&(this._behaviorInstances=s.map((t,e)=>C3.New(C3.BehaviorInstance,{runtime:this._runtime,behaviorType:t,instance:this,index:e}))),this._siblings=this._objectType.IsInContainer()?[]:null,this._timeScale=-1,this._dispatcher=null;const n=this.GetPlugin();if(n.MustPreDraw()&&(this._flags|=4),n.IsWorldType())if(this._worldInfo=C3.New(C3.WorldInfo,this,t.layer),t.worldData)this._worldInfo.Init(t.worldData);else{this._worldInfo.InitNoData();const[t,e]=this._objectType.GetDefaultInstanceSize();this._worldInfo.SetSize(t,e),this.GetObjectClass().UsesEffects()&&this._worldInfo.GetInstanceEffectList().LoadDefaultEffectParameters()}t.instVarData?this._LoadInstanceVariableData(t.instVarData):this._LoadDefaultInstanceVariables()}Release(){if(this._iScriptInterface&&(this._iScriptInterface._release(),this._iScriptInterface=null),this._behaviorInstances.length>0){for(const t of this._behaviorInstances)t.Release();C3.clearArray(this._behaviorInstances)}this._sdkInst&&(this._sdkInst.Release(),this._sdkInst=null);const t=savedDataMaps.get(this);t&&(t.clear(),savedDataMaps.delete(this)),this._siblings&&C3.clearArray(this._siblings),this._dispatcher&&(this._dispatcher.Release(),this._dispatcher=null),this.#t&&(this.#t.originalTags.clear(),this.#t.lowercaseTags.clear()),this.#t=null,this._runtime=null,this._objectType=null,this._instVarValues.length>0&&C3.clearArray(this._instVarValues),this._worldInfo&&(this._worldInfo.Release(),this._worldInfo=null)}_LoadInstanceVariableData(t){t.length>0&&(this._instVarValues=[],C3.shallowAssignArray(this._instVarValues,t))}_LoadDefaultInstanceVariables(){const t=this._objectType.GetInstanceVariablesCount();if(0===t)return;this._instVarValues=[];const e=[0,0,""];for(let s=0;s{const n=s||e.GetObjectClass(),i=t.get(n);i?i.add(e):t.set(n,new Set([e]))};if(n(this,e),this.IsInContainer())for(const t of this.siblings())n(t);if(s)for(const t of this.allChildren())n(t)}VerifySupportsSceneGraph(){if(!this.GetPlugin().SupportsSceneGraph())throw new Error("object does not support scene graph")}HasParent(){return null!==this.GetParent()}GetParent(){const t=this.GetWorldInfo();if(!t)return null;const e=t.GetParent();return e?e.GetInstance():null}GetTopParent(){const t=this.GetWorldInfo();if(!t)return null;const e=t.GetTopParent();return e?e.GetInstance():null}*parents(){const t=this.GetWorldInfo();if(t)for(const e of t.parents())yield e.GetInstance()}HasChild(t){if(!t)return!1;for(const e of this.children())if(e===t)return!0;return!1}HasChildren(){const t=this.GetWorldInfo();return!!t&&t.HasChildren()}GetChildrenOfObjectClass(t){const e=this.GetWorldInfo();if(!e)return[];const s=t.GetName();return e.GetChildren().map(t=>t.GetInstance()).filter(t=>t.GetObjectClass().GetName()===s)}GetChildren(){const t=this.GetWorldInfo();return t?t.GetChildren().map(t=>t.GetInstance()):[]}*children(){const t=this.GetWorldInfo();if(t)for(const e of t.children())yield e.GetInstance()}*allChildren(){const t=this.GetWorldInfo();if(t)for(const e of t.allChildren())yield e.GetInstance()}GetChildCount(){const t=this.GetWorldInfo();return t?t.GetChildCount():0}GetParentCount(){return[...this.parents()].length}GetAllChildCount(){const t=this.GetWorldInfo();return t?t.GetAllChildCount():0}GetChildAt(t){const e=this.GetWorldInfo();if(!e)return null;const s=e.GetChildAt(t);return s?s.GetInstance():null}GetIndexInParent(){const t=this.GetWorldInfo();if(!t)return NaN;const e=t.GetParent();return e?e.GetChildIndex(t):NaN}HasChildWithUID(t){for(const e of this.GetWorldInfo().GetChildren())if(e.GetInstance().GetUID()===t)return!0;return!1}AddChild(t,e){this.VerifySupportsSceneGraph(),t.VerifySupportsSceneGraph(),this.GetWorldInfo().AddChild(t.GetWorldInfo(),e||{})}RemoveChild(t){const e=this.GetWorldInfo();e&&e.RemoveChild(t.GetWorldInfo())}GetDestroyWithParent(){const t=this.GetWorldInfo();return!!t&&t.GetDestroyWithParent()}SetupInitialSceneGraphConnections(){const t=this.GetWorldInfo();if(!t)return;const e=t.GetSceneGraphChildrenExportData();if(e)for(const t of e){const e=this._runtime.GetInstanceByUID(t[2]);if(e){const s=t[3];this.AddChild(e,{transformX:!!(1&s),transformY:!!(s>>1&1),transformZ:!!(s>>6&1),transformWidth:!!(s>>2&1),transformHeight:!!(s>>3&1),transformAngle:!!(s>>4&1),destroyWithParent:!!(s>>5&1),transformOpacity:!!(s>>7&1),transformVisibility:!!(s>>8&1)})}}}SetupPersistedSceneGraphConnections(t,e){const s=t.get(this);if(s)for(const t of s["sceneGraphJson"]["children"]){const s=e.get(t["index"]);if(!s)continue;const n=t["flags"];this.AddChild(s,{transformX:!!(1&n),transformY:!!(n>>1&1),transformZ:!!(n>>6&1),transformWidth:!!(n>>2&1),transformHeight:!!(n>>3&1),transformAngle:!!(n>>4&1),destroyWithParent:!!(n>>5&1),transformOpacity:!!(n>>7&1),transformVisibility:!!(n>>8&1)})}}GetTemplateName(){const t=this._runtime.GetTemplateManager();return t?t.GetInstanceTemplateName(this):""}IsInContainer(){return null!==this._siblings}_ClearSiblings(){C3.clearArray(this._siblings)}_AddSibling(t){this._siblings.push(t)}GetSiblings(){return this._siblings}HasSibling(t){return!!this.GetSibling(t)}GetSibling(t){const e=this.siblings();if(null===e||0===e.length)return!1;for(const s of e)if(s.GetObjectClass()===t)return s;return null}siblings(){return this._siblings}SetSiblingsSinglePicked(){for(const t of this.siblings())t.GetObjectClass().GetCurrentSol().SetSinglePicked(t)}_PushSiblingsToSolInstances(){for(const t of this.siblings())t.GetObjectClass().GetCurrentSol()._PushInstance(t)}_SetSiblingsToSolInstancesIndex(t){for(const e of this.siblings())e.GetObjectClass().GetCurrentSol()._GetOwnInstances()[t]=e}_PushSiblingsToSolElseInstances(){for(const t of this.siblings())t.GetObjectClass().GetCurrentSol()._PushElseInstance(t)}_SetSiblingsToSolElseInstancesIndex(t){for(const e of this.siblings())e.GetObjectClass().GetCurrentSol()._GetOwnElseInstances()[t]=e}GetPlugin(){return this._objectType.GetPlugin()}_SetIID(t){this._iid=t}GetIID(){return this._objectType._UpdateIIDs(),this._iid}GetUID(){return this._uid}SetUID(t){this._uid=t}GetPUID(){return this._puid}SetTagsSet(t){if(this.#t&&(this.#t.originalTags.clear(),this.#t.lowercaseTags.clear()),0===t.size)this.#t=null;else{this.#t||(this.#t={originalTags:new Set,lowercaseTags:new Set});for(const e of t){const t=e.toLowerCase();this.#t.lowercaseTags.has(t)||(this.#t.originalTags.add(e),this.#t.lowercaseTags.add(t))}}}GetTagsSet(){return this.#t?this.#t.originalTags:EMPTY_SET}GetLowercaseTagsSet(){return this.#t?this.#t.lowercaseTags:EMPTY_SET}_GetLowercaseTagsSetMaybeNull(){return this.#t?this.#t.lowercaseTags:null}HasTag(t){return!!this.#t&&this.#t.lowercaseTags.has(t.toLowerCase())}GetTagsString(){return Array.from(this.GetTagsSet()).join(" ")}GetTagAt(t){t=Math.floor(t);for(const e of this.GetTagsSet()){if(0===t)return e;--t}return""}GetBehaviorInstances(){return this._behaviorInstances}GetBehaviorInstanceFromCtor(t){if(!t)return null;for(const e of this._behaviorInstances)if(e.GetBehavior()instanceof t)return e;return null}GetBehaviorSdkInstanceFromCtor(t){if(!t)return null;const e=this.GetBehaviorInstanceFromCtor(t);return e?e.GetSdkInstance():null}GetBehaviorIndexBySID(t){const e=this._behaviorInstances;for(let s=0,n=e.length;s=e.length)throw new RangeError("invalid instance variable");return e[t]}_GetInstanceVariableValueUnchecked(t){return this._instVarValues[t]}_GetInstanceVariableTypedValue(t){const e=this._instVarValues[t];return 0===this._objectType.GetInstanceVariableType(t)?!!e:e}SetInstanceVariableValue(t,e){t|=0;const s=this._instVarValues;if(t<0||t>=s.length)throw new RangeError("invalid instance variable");switch(this._objectType.GetInstanceVariableType(t)){case 0:s[t]=e?1:0;break;case 1:s[t]="number"==typeof e?e:parseFloat(e);break;case 2:s[t]="string"==typeof e?e:e.toString();break;default:throw new Error("unknown instance variable type")}}SetInstanceVariableOffset(t,e){if(0===e)return;t|=0;const s=this._instVarValues;if(t<0||t>=s.length)throw new RangeError("invalid instance variable");const n=s[t];if("number"!=typeof n)throw"boolean"==typeof n?new Error("can not set offset of boolean variable"):"string"==typeof n?new Error("can not set offset of string variable"):new Error("unknown instance variable type");s[t]+="number"==typeof e?e:parseFloat(e)}GetSavedDataMap(){let t=savedDataMaps.get(this);return t||(t=new Map,savedDataMaps.set(this,t),t)}_HasAnyCreateDestroyHandler(t){const e=this.GetObjectClass();if(e.UserScriptDispatcher().HasAnyHandlerFor(t))return!0;for(const s of e.GetFamilies())if(s.UserScriptDispatcher().HasAnyHandlerFor(t))return!0;return!!this._runtime.UserScriptDispatcher().HasAnyHandlerFor(t)}_TriggerOnCreatedOnSelfAndRelated(t=void 0){const e=t??new Set;if(e.has(this))return;e.add(this);const s=this.GetWorldInfo();if(s&&s.HasChildren())for(const t of this.allChildren())if(e.add(t),t.IsInContainer())for(const s of t.siblings())e.add(s);if(this.IsInContainer())for(const t of this.siblings())t._TriggerOnCreatedOnSelfAndRelated(e);if(!t){for(const t of e.values())t._TriggerOnCreated();this._OnHierarchyReady()}}_OnCreatedCommon(){this._objectType._GetUserScriptInstanceClass()&&this.GetInterfaceClass();for(const t of this._behaviorInstances)t.PostCreate()}_OnCreatedForLoadingSavegame(){this._OnCreatedCommon()}_TriggerOnCreated(){if(this._OnCreatedCommon(),this._HasAnyCreateDestroyHandler("instancecreate")){const t=this.GetObjectClass(),e=new C3.Event("instancecreate");e.instance=this.GetInterfaceClass(),t.DispatchUserScriptEvent(e);for(const s of t.GetFamilies())s.DispatchUserScriptEvent(e);this._runtime.DispatchUserScriptEvent(e)}this._runtime.Trigger(this.GetPlugin().GetConstructor().Cnds.OnCreated,this,null)}_OnHierarchyReady(){if(this.GetPlugin().SupportsSceneGraph()){if(this.DispatchUserScriptEvent(new C3.Event("hierarchyready")),this._HasAnyCreateDestroyHandler("hierarchyready")){const t=this.GetObjectClass(),e=new C3.Event("hierarchyready");e.instance=this.GetInterfaceClass(),t.DispatchUserScriptEvent(e);for(const s of t.GetFamilies())s.DispatchUserScriptEvent(e);this._runtime.DispatchUserScriptEvent(e)}this._runtime.Trigger(this.GetPlugin().GetConstructor().Cnds.OnHierarchyReady,this,null)}}_TriggerOnDestroyed(){this._runtime.Trigger(this.GetPlugin().GetConstructor().Cnds.OnDestroyed,this,null)}_FireDestroyedScriptEvents(t){if(this._iScriptInterface){const e=new C3.Event("destroy");e.isEndingLayout=t,this.DispatchUserScriptEvent(e)}if(!this._HasAnyCreateDestroyHandler("instancedestroy"))return;const e=this.GetObjectClass(),s=new C3.Event("instancedestroy");s.instance=this.GetInterfaceClass(),s.isEndingLayout=t,e.DispatchUserScriptEvent(s);for(const t of e.GetFamilies())t.DispatchUserScriptEvent(s);this._runtime.DispatchUserScriptEvent(s)}_GetDebuggerProperties(){return this._sdkInst?this._sdkInst.GetDebuggerProperties():this._iScriptInterface._getDebuggerProperties()}SaveToJson(t="full",e=null){const s={};"full"===t?s["uid"]=this.GetUID():s["c3"]=!0;const n=this.GetTagsSet();if(n.size>0&&(s["tags"]=Array.from(n)),"visual-state"!==t){const e=savedDataMaps.get(this);if(e&&e.size&&(s["ex"]=C3.ToSuperJSON(e)),-1!==this.GetTimeScale()&&(s["mts"]=this.GetTimeScale()),this._objectType.GetInstanceVariablesCount()>0){const t={},e=this._objectType.GetInstanceVariableSIDs();for(let s=0,n=this._instVarValues.length;s=this._instVarValues.length)continue;let i=e;null===i&&(i=NaN),this._instVarValues[n]=i}}if(this.GetPlugin().IsWorldType()){const n=t["w"];if(n){const t=n["l"];if(this._worldInfo.GetLayer().GetSID()!==t){const s=this._worldInfo.GetLayer(),n=s.GetLayout().GetLayerBySID(t);n?(this._worldInfo._SetLayer(n),s._RemoveInstance(this,!0),n._AddInstance(this,!0),n.SetZIndicesChanged(this),this._worldInfo.SetBboxChanged()):"full"===e&&this._runtime.DestroyInstance(this)}this._worldInfo._LoadFromJson(n,e,s)}}if("visual-state"!==e){const s=t["behs"];if(s)for(const[t,n]of Object.entries(s)){const s=parseInt(t,10),i=this.GetBehaviorIndexBySID(s);i<0||i>=this._behaviorInstances.length||this._behaviorInstances[i].LoadFromJson(n,e)}}const n=t["data"];n&&(this._sdkInst?this._sdkInst.LoadFromJson(n,e):this._iScriptInterface._loadFromJson(n))}MoveToLayerWithSID(t){if(this._worldInfo.GetLayer().GetSID()===t)return;const e=this._worldInfo.GetLayer(),s=e.GetLayout().GetLayerBySID(t);s&&(this._worldInfo._SetLayer(s),e._RemoveInstance(this,!0),s._AddInstance(this,!0),s.SetZIndicesChanged(this),this._worldInfo.SetBboxChanged())}GetInterfaceClass(){return this._iScriptInterface||this._InitUserScriptInterface()}HasScriptInterface(){return!!this._iScriptInterface}_InitUserScriptInterface(t,e){const s=this._worldInfo?t?self.ISDKWorldInstanceBase:self.IWorldInstance:t?self.ISDKInstanceBase:self.IInstance,n=t||this._sdkInst.GetScriptInterfaceClass(),i=this._objectType._GetUserScriptInstanceClass(),r=i||n||s,a=this.GetPlugin().GetSdkVersion();if(C3.AddonManager._PushInitObject(this,a),C3.AddonManager._PushInitProperties(e),this._iScriptInterface=new r,C3.AddonManager._PopInitProperties(),C3.AddonManager._PopInitObject(a),n&&!(this._iScriptInterface instanceof s))throw new TypeError(`script interface class '${n.name}' does not extend the right base class '${s.name}'`);if(i){const t=n||s;if(!(this._iScriptInterface instanceof t))throw new TypeError(`setInstanceClass(): class '${i.name}' does not extend the right base class - check it extends the right class, e.g. globalThis.InstanceType.MyObjectName`)}return this._iScriptInterface}_GetInstVarsScriptDescriptor(t){if(0===this._instVarValues.length)return;const e={},s=this._objectType._GetAllInstanceVariableJsPropNames();for(let t=0,n=s.length;t{if(e.instance!==this._parent.GetInstance())return;t.GetRuntime().Dispatcher().removeEventListener("instancecreate",this._on_instance_create);const n=this._parent.GetInstance();this._originalSizeKnown=!!n.IsOriginalSizeKnown(),this._originalSizeKnown?[this._originalWidth,this._originalHeight]=n.GetOriginalSize():(this._originalWidth=NaN,this._originalHeight=NaN)}}Release(){this._parent=null,this._tmpSceneGraphChildren=null,this._tmpSceneGraphChildrenIndexes=null,this._indexInParent=NaN,this._originalSizeKnown=!1,this._originalWidth=NaN,this._originalHeight=NaN,C3.clearArray(this._children)}SetParent(t){if(this._ownOpacity=this._owner.GetOpacity(),this._startOpacity=this._ownOpacity,this._parent=t,this._parentStartAngle=t?t.GetAngle():0,this._parent){const t=this._owner.GetRuntime();if(this._parent.GetInstance().GetPlugin().GetSdkVersion()<2){const e=this._parent.GetInstance().GetSdkInstance();e?(this._originalSizeKnown=!!e.IsOriginalSizeKnown(),this._originalSizeKnown?[this._originalWidth,this._originalHeight]=e.GetOriginalSize():(this._originalWidth=NaN,this._originalHeight=NaN)):this._parent.GetInstance().IsDestroyed()||t.Dispatcher().addEventListener("instancecreate",this._on_instance_create)}else{const t=this._parent.GetInstance();this._originalSizeKnown=t.IsOriginalSizeKnown(),this._originalSizeKnown?[this._originalWidth,this._originalHeight]=t.GetOriginalSize():(this._originalWidth=NaN,this._originalHeight=NaN)}}else this._originalSizeKnown=!1,this._originalWidth=NaN,this._originalHeight=NaN}GetParent(){return this._parent}HasChildren(){return this._children.length>0}GetChildren(){return this._children}_MaybeSortChildren(){this.HasChildren()&&1!==this._children.length&&(this._tmpSceneGraphChildrenIndexes?this._children.sort((t,e)=>{const n=this._tmpSceneGraphChildrenIndexes.get(t.GetInstance()),s=this._tmpSceneGraphChildrenIndexes.get(e.GetInstance());return C3.IsFiniteNumber(n)&&C3.IsFiniteNumber(s)?n-s:0}):this._children.sort((t,e)=>{const n=t._GetSceneGraphInfo()._GetIndexInParent(),s=e._GetSceneGraphInfo()._GetIndexInParent();return C3.IsFiniteNumber(n)&&C3.IsFiniteNumber(s)?n-s:0}))}_GetIndexInParent(){return this._indexInParent}GetStartScaleX(){return this._startScaleX}SetStartScaleX(t){this._startScaleX=t}GetStartScaleY(){return this._startScaleY}SetStartScaleY(t){this._startScaleY=t}GetStartOpacity(){return this._startOpacity}GetOwnOpacity(){return this._ownOpacity}SetOwnOpacity(t){this._ownOpacity=t}_GetStartWidth(){return 0===this._startWidth?Number.EPSILON:this._startWidth}_GetStartHeight(){return 0===this._startHeight?Number.EPSILON:this._startHeight}GetParentScaleX(){if(this._owner.GetTransformWithParentWidth()){const t=this._parent;let e=t.GetWidth(),n=t._GetSceneGraphInfo()._GetStartWidth();return 0===e&&(e=Number.EPSILON),n===Number.EPSILON&&e===Number.EPSILON?1:n===Number.EPSILON&&e!==Number.EPSILON&&this._originalSizeKnown?1+e/this._originalWidth:e/n}return 1}GetParentScaleY(){if(this._owner.GetTransformWithParentHeight()){const t=this._parent;let e=t.GetHeight(),n=t._GetSceneGraphInfo()._GetStartHeight();return 0===e&&(e=Number.EPSILON),n===Number.EPSILON&&e===Number.EPSILON?1:n===Number.EPSILON&&e!==Number.EPSILON&&this._originalSizeKnown?1+e/this._originalHeight:e/n}return 1}GetParentStartAngle(){return 0}_SaveToJsonProperties(){return{"sw":this._startWidth,"sh":this._startHeight,"sx":this._startScaleX,"sy":this._startScaleY,"psa":this._parentStartAngle,"oo":this._ownOpacity,"so":this._startOpacity,"pi":this._owner.GetInstance().GetIndexInParent()}}_SaveToJson(t,e=null){const n=this._SaveToJsonProperties();return e&&e["selfOnly"]?Object.assign(n,{"p":null,"c":[]}):Object.assign(n,{"p":this._GetParentJson(t),"c":this._GetChildrenJson(t)})}_GetFlagsString(t){let e="";return t.GetTransformWithParentX()&&(e+="x"),t.GetTransformWithParentY()&&(e+="y"),t.GetTransformWithParentZ()&&(e+="z"),t.GetTransformWithParentWidth()&&(e+="w"),t.GetTransformWithParentHeight()&&(e+="h"),t.GetTransformWithParentAngle()&&(e+="a"),t.GetDestroyWithParent()&&(e+="d"),t.GetTransformWithParentOpacity()&&(e+="o"),t.GetTransformWithParentVisibility()&&(e+="v"),e}_GetParentJson(t){return this._parent?!this._parent.GetInstance()||this._parent.GetInstance().IsDestroyed()?null:this._GetInstanceJson(this._parent,this._owner,t):null}_GetChildrenJson(t){return this._children.map(e=>this._GetInstanceJson(e,e,t)).filter(t=>t)}_GetInstanceJson(t,e,n){const s=t.GetInstance();if(s&&s.IsDestroyed())return null;const i={};return i["uid"]=s.GetUID(),i["f"]=this._GetFlagsString(e),i["offsets"]=e._SaveSceneGraphPropertiesToJson(),i["data"]=C3.SceneGraphInfo.GetSceneGraphInstanceDataFromInstance(s),i["oci"]=s.GetObjectClass().GetIndex(),"state"===n?(i["inst"]=s.SaveToJson("full",{"selfOnly":!0}),i["instIndex"]=NaN):(i["instIndex"]=s.GetObjectClass().GetInstances().indexOf(s),i["inst"]=null),i}_LoadFromJson(t){this._startWidth=t["sw"],this._startHeight=t["sh"],this._startScaleX=t["sx"],this._startScaleY=t["sy"],this._parentStartAngle=t["psa"],this._ownOpacity=t["oo"],this._startOpacity=t["so"],this._indexInParent=C3.IsFiniteNumber(t["pi"])?t["pi"]:NaN}_SetTmpSceneGraphChildren(t,e,n,s){if(!t&&!e)if(s?.setFromJson){if(this._tmpSceneGraphChildren)for(const t of this._tmpSceneGraphChildren)t.IsDestroyed()||t.HasParent()||t.GetRuntime().DestroyInstance(t)}else if(this._tmpSceneGraphChildren)for(const t of this._tmpSceneGraphChildren)if(n["c"]&&n["c"].length){if(!n["c"].some(e=>e["uid"]===t.GetUID()))continue;t.IsDestroyed()||t.HasParent()||t.GetRuntime().DestroyInstance(t)}this._tmpSceneGraphChildren=t,this._tmpSceneGraphChildrenIndexes=e}_GetInstanceByUID(t){const e=this._owner.GetRuntime();return updatedInstances.has(t)?updatedInstances.get(t):e.GetInstanceByUID(t)}_OnAfterLoad(t,e){const n=this._owner,s=n.GetRuntime(),i=e?.processedWorldInfo??new Set;if(t["p"]&&!this._parent){const a=t["p"]["uid"],r=this._GetInstanceByUID(a);if(r){const a=r.GetWorldInfo();if(r.HasChild(n.GetInstance()))this._parent=a;else{r.HasChildWithUID(n.GetInstance().GetUID())?(s.DestroyInstance(n.GetInstance()),s._RemoveInstanceFromUIDMap(n.GetInstance().GetUID()),updatedInstances.delete(n.GetInstance().GetUID())):r.AddChild(n.GetInstance(),this._GetFlagsObj(t["p"]["f"])),i.has(n)||(n._LoadSceneGraphPropertiesFromJson(t["p"]["offsets"]),this._LoadInstancePropertiesFromJson(r,t["p"],e),this._UpdateUIDInstanceMap(r,r.GetUID(),n.GetRuntime(),e)),i.add(n);r.GetWorldInfo()._GetSceneGraphInfo()._MaybeSortChildren()}}else if(C3.IsFiniteNumber(t["p"]["oci"])){const i=s.CreateInstance(s.GetObjectClassByIndex(t["p"]["oci"]),n.GetLayer(),0,0,!0);if(i){const a=this._GetInstanceData(t["p"],s);a&&i.LoadFromJson(a);const r=i.GetWorldInfo(),h=!!e?.setFromJson;r.GetLayer().SortAndAddInstancesByZIndex(i,!1,h),i.AddChild(n.GetInstance(),this._GetFlagsObj(t["p"]["f"])),updatedInstances.set(i.GetUID(),i),this._UpdateUIDInstanceMap(i,i.GetUID(),s,e);i.GetWorldInfo()._GetSceneGraphInfo()._MaybeSortChildren()}}}const a=[];for(const e of t["c"]){const t=e["uid"],n=this._GetInstanceByUID(t);n&&a.push(n)}let r=0;for(const h of t["c"]){const o=h["uid"],c=this._GetInstanceByUID(o);if(c){if(this._tmpSceneGraphChildren){if(this._tmpSceneGraphChildren.includes(c)){const s=c;if(s.GetObjectClass()!==c.GetObjectClass()){r++;continue}if(s.IsDestroyed()){r++;continue}const h=t["c"][r];if(!e?.setFromJson&&this._HasAllChildrenOfType(s,a,n)){if(n.GetInstance().GetChildAt(r)){const a=s.GetObjectClass().GetIndex(),o=h["oci"],c=n.GetInstance().GetChildAt(r).GetObjectClass().GetIndex();if(a!==o||o!==c){this._RefreshAllChildren(t["c"],n,i,e);break}this._UpdateInstance(r,h,n,i,e)}else this._UpdateInstance(r,h,n,i,e);r++;continue}if(s.HasParent()&&s.GetParent()!==n.GetInstance()){const t=this._CreateNewChildInstance(h,e);this._AddAndSetChildInstance(t,h,i,e),r++;continue}this._AddAndSetChildInstance(s.GetWorldInfo(),h,i,e,!0),r++;continue}if(this._tmpSceneGraphChildren[r]){const s=this._tmpSceneGraphChildren[r];if(s.GetObjectClass()!==c.GetObjectClass()){r++;continue}if(s.IsDestroyed()){r++;continue}const h=t["c"][r];if(!e?.setFromJson&&this._HasAllChildrenOfType(s,a,n)){if(n.GetInstance().GetChildAt(r)){const a=s.GetObjectClass().GetIndex(),o=h["oci"],c=n.GetInstance().GetChildAt(r).GetObjectClass().GetIndex();if(a!==o||o!==c){this._RefreshAllChildren(t["c"],n,i,e);break}this._UpdateInstance(r,h,n,i,e)}else this._UpdateInstance(r,h,n,i,e);r++;continue}if(s.HasParent()&&s.GetParent()!==n.GetInstance()){const t=this._CreateNewChildInstance(h,e);this._AddAndSetChildInstance(t,h,i,e),r++;continue}this._AddAndSetChildInstance(s.GetWorldInfo(),h,i,e,!0),r++;continue}}const s=c.GetObjectClass();if(this._GetInstancesOfObjectClassCount(a,s)===n.GetInstance().GetChildrenOfObjectClass(s).length){for(const t of n.GetInstance().GetChildren()){if(t.GetObjectClass()!==s)continue;const n=t.GetWorldInfo();if(n&&!i.has(n)){i.add(n),n._LoadSceneGraphPropertiesFromJson(h["offsets"]),this._LoadInstancePropertiesFromJson(t,h,e);break}}r++;continue}if(c.HasParent()&&c.GetParent()!==n.GetInstance()){const t=this._CreateNewChildInstance(h,e);this._AddAndSetChildInstance(t,h,i,e),r++;continue}this._AddAndSetChildInstance(c.GetWorldInfo(),h,i,e)}else if(this._tmpSceneGraphChildren&&this._tmpSceneGraphChildren[r]){const o=this._tmpSceneGraphChildren[r],c=s.GetObjectClassByIndex(this._GetObjectClassIndex(h));if(o.GetObjectClass()!==c){r++;continue}if(o.IsDestroyed()){r++;continue}const d=t["c"][r];if(!e?.setFromJson&&this._HasAllChildrenOfType(o,a,n)){if(n.GetInstance().GetChildAt(r)){const s=o.GetObjectClass().GetIndex(),a=d["oci"],h=n.GetInstance().GetChildAt(r).GetObjectClass().GetIndex();if(s!==a||a!==h){this._RefreshAllChildren(t["c"],n,i,e);break}this._UpdateInstance(r,d,n,i,e)}else this._UpdateInstance(r,d,n,i,e);r++;continue}if(o.HasParent()&&o.GetParent()!==n.GetInstance()){const t=this._CreateNewChildInstance(d,e);this._AddAndSetChildInstance(t,d,i,e),r++;continue}this._AddAndSetChildInstance(o.GetWorldInfo(),d,i,e)}else{const t=this._CreateNewChildInstance(h,e);this._AddAndSetChildInstance(t,h,i,e)}r++}}_RefreshAllChildren(t,e,n,s){const i=e.GetRuntime();for(const t of e.GetInstance().children())t&&!t.IsDestroyed()&&(i.DestroyInstance(t),i._RemoveInstanceFromUIDMap(t.GetUID()),updatedInstances.delete(t.GetUID()));this._tmpSceneGraphChildren&&(this._tmpSceneGraphChildren=[]),this._tmpSceneGraphChildrenIndexes&&(this._tmpSceneGraphChildrenIndexes=new WeakMap);Object.assign({},s,{"assignZIndex":!1});for(const e of t){const t=this._CreateNewChildInstance(e,s);this._AddAndSetChildInstance(t,e,n,s),this._tmpSceneGraphChildren.push(t.GetInstance()),this._tmpSceneGraphChildrenIndexes.set(t.GetInstance(),this._tmpSceneGraphChildren.length-1)}e._GetSceneGraphInfo()._MaybeSortChildren()}_HasAllChildrenOfType(t,e,n){const s=t.GetObjectClass();return this._GetInstancesOfObjectClassCount(e,s)===n.GetInstance().GetChildrenOfObjectClass(s).length}_UpdateInstance(t,e,n,s,i){const a=n.GetInstance().GetChildAt(t);if(!a)return;const r=a.GetWorldInfo();r&&(s.has(r)||(r._LoadSceneGraphPropertiesFromJson(e["offsets"]),this._LoadInstancePropertiesFromJson(a,e,i)),s.add(r))}_GetFlagsObj(t){const e={};return e.transformX=t.includes("x"),e.transformY=t.includes("y"),e.transformZ=t.includes("z"),e.transformWidth=t.includes("w"),e.transformHeight=t.includes("h"),e.transformAngle=t.includes("a"),e.destroyWithParent=t.includes("d"),e.transformOpacity=t.includes("o"),e.transformVisibility=t.includes("v"),e}_GetObjectClassIndex(t){return C3.IsFiniteNumber(t["oci"])?t["oci"]:t[1]}_CreateNewChildInstance(t,e){if(!C3.IsFiniteNumber(t["oci"]))return;const n=this._owner,s=n.GetRuntime();let i;const a=!e.hasOwnProperty("createHierarchy")||e["createHierarchy"];if(i=t["data"]?s.CreateInstanceFromData(t["data"],n.GetLayer(),!1,0,0,!1,a):s.CreateInstance(s.GetObjectClassByIndex(t["oci"]),n.GetLayer(),0,0,a),!i)return;const r=this._GetInstanceData(t,s);r&&i.LoadFromJson(r);const h=i.GetWorldInfo(),o=!!e?.setFromJson;return h.GetLayer().SortAndAddInstancesByZIndex(i,!0,o),h}_UpdateUIDInstanceMap(t,e,n,s){if(this._GetInstanceByUID(e)&&!s?.setFromJson){const s=this._GetInstanceByUID(e);s!==t&&n.DestroyInstance(s)}n._RemoveInstanceFromUIDMap(e),n._MapInstanceByUID(e,t)}_AddAndSetChildInstance(t,e,n,s,i=!0){const a=this._owner,r=a.AddChild(t,this._GetFlagsObj(e["f"]));r&&i?(n.has(t)||(t._LoadSceneGraphPropertiesFromJson(e["offsets"]),this._LoadInstancePropertiesFromJson(t.GetInstance(),e,s)),n.add(t)):r&&(updatedInstances.set(t.GetInstance().GetUID(),t.GetInstance()),this._UpdateUIDInstanceMap(t.GetInstance(),e["uid"],a.GetRuntime(),s)),this._MaybeSortChildren()}_LoadInstancePropertiesFromJson(t,e,n){let s=this._GetInstanceData(e,this._owner.GetRuntime());if(!s)return;const i=!n.hasOwnProperty("clearChildren")||n["clearChildren"],a=!n.hasOwnProperty("assignZIndex")||n["assignZIndex"],r=t.GetRuntime();if(updatedInstances.set(t.GetUID(),t),s=JSON.parse(JSON.stringify(s)),i&&t.GetUID()!==s["uid"]){for(const e of t.children())e&&!e.IsDestroyed()&&(r.DestroyInstance(e),r._RemoveInstanceFromUIDMap(e.GetUID()),updatedInstances.delete(e.GetUID()));if(s["w"]?.["sgi"]&&s["w"]["sgi"]["c"]?.length)for(const e of s["w"]["sgi"]["c"]){const s=Object.assign({},n,{"clearChildren":!1,"createHierarchy":!1}),i=this._CreateNewChildInstance(e,s);updatedInstances.set(i.GetInstance().GetUID(),i.GetInstance()),t.AddChild(i.GetInstance(),this._GetFlagsObj(e["f"])),i._LoadSceneGraphPropertiesFromJson(e["offsets"]),this._LoadInstancePropertiesFromJson(i.GetInstance(),e,s)}}const h=s["w"]?.["zi"],o=s["w"]?.["l"];s["w"]=null,t.LoadFromJson(s),n?.setFromJson||(C3.IsFiniteNumber(h)&&a&&t.GetWorldInfo()._SetZIndex(h),C3.IsFiniteNumber(o)&&t.MoveToLayerWithSID(o)),this._UpdateUIDInstanceMap(t,s["uid"],r,n)}_GetInstancesOfObjectClassCount(t,e){return t.filter(t=>t.GetObjectClass().GetName()===e.GetName()).length}_GetInstanceData(t,e){if(C3.IsFiniteNumber(t["instIndex"])){const n=e.GetObjectClassByIndex(t["oci"])._GetLoadInstancesJson();return n?n[t["instIndex"]]:null}return C3.IsString(t["inst"])?JSON.parse(t["inst"]):t["inst"]?t["inst"]:void 0}static GetSceneGraphInstanceDataFromInstance(t){let e=t.GetWorldInfo().GetLayer().GetInitialInstanceData(t.GetUID());if(!e)return null;e=JSON.parse(JSON.stringify(e));const n=[];for(const e of[...t.GetChildren()]){const t=e.GetWorldInfo();n.push([t.GetLayout().GetSID(),t.GetLayer().GetIndex(),e.GetUID(),C3.SceneGraphInfo._GetFlagsNumber(t),e.GetObjectClass().IsInContainer()?1:0,t.GetZIndex(),C3.SceneGraphInfo.GetSceneGraphInstanceDataFromInstance(e)])}return C3.IsArray(e[0][14])?e[0][14][1]=n:(e[0][14]=[],e[0][14][0]=C3.SceneGraphInfo._GetDefaultFlagsNumber(),e[0][14][1]=n,e[0][14][2]=t.GetWorldInfo().GetZIndex()),e}static _GetFlagsNumber(t){let e=0;return e|=Number(t.GetTransformWithParentVisibility())<<8,e|=Number(t.GetTransformWithParentOpacity())<<7,e|=Number(t.GetDestroyWithParent())<<5,e|=Number(t.GetTransformWithParentAngle())<<4,e|=Number(t.GetTransformWithParentHeight())<<3,e|=Number(t.GetTransformWithParentWidth())<<2,e|=Number(t.GetTransformWithParentZ())<<6,e|=Number(t.GetTransformWithParentY())<<1,e|=Number(t.GetTransformWithParentX())|0,e}static _GetDefaultFlagsNumber(t){let e=0;return e|=256,e|=128,e|=64,e|=32,e|=16,e|=8,e|=4,e|=2,e|=1,511}static ClearUpdatedInstances(){updatedInstances.clear()}}; } // objects/worldInfo.js { const C3=self.C3,glMatrix=self.glMatrix,vec3=glMatrix.vec3,vec4=glMatrix.vec4,tempRect=new C3.Rect,tempRect2=new C3.Rect,tempQuad=C3.New(C3.Quad2D),bboxChangeEvent=C3.New(C3.Event,"bboxchange",!1),tempColor=C3.New(C3.Color,0,0,0,0),tempCollisionPoly=C3.New(C3.CollisionPoly),DEFAULT_COLOR=C3.New(C3.Color,1,1,1,1),DEFAULT_RENDER_CELLS=C3.New(C3.Rect,0,0,-1,-1),DEFAULT_COLLISION_CELLS=C3.New(C3.Rect,0,0,-1,-1),VALID_SET_MESH_POINT_MODES=new Set(["absolute","relative"]),EMPTY_ARRAY=[];let enableUpdateRendererStateGroup=!0;const FLAG_IS_VISIBLE=1,FLAG_BBOX_CHANGED=2,FLAG_ENABLE_BBOX_CHANGED_EVENT=4,FLAG_COLLISION_ENABLED=8,FLAG_COLLISION_CELL_CHANGED=16,FLAG_SOLID_FILTER_INCLUSIVE=32,FLAG_HAS_ANY_ACTIVE_EFFECT=64,FLAG_IS_ROTATABLE=128,FLAG_DESTROYED=256,FLAG_DESTROY_WITH_PARENT=512,FLAG_TRANSFORM_WITH_PARENT_X=1024,FLAG_TRANSFORM_WITH_PARENT_Y=2048,FLAG_TRANSFORM_WITH_PARENT_Z=32768,FLAG_TRANSFORM_WITH_PARENT_W=4096,FLAG_TRANSFORM_WITH_PARENT_H=8192,FLAG_TRANSFORM_WITH_PARENT_A=16384,FLAG_TRANSFORM_WITH_PARENT_OPACITY=1<<22,FLAG_TRANSFORM_WITH_PARENT_VISIBILITY=1<<23,MASK_ALL_SCENE_GRAPH_FLAGS=12647936,FLAG_MESH_CHANGED=65536,FLAG_PHYSICS_BODY_CHANGED=1<<17,FLAG_SIN_COS_ANGLE_CHANGED=1<<18,FLAG_USE_POINTS_SHADER_PROGRAM=1<<19,FLAG_DRAW_BACK_FACE_ONLY=1<<20,FLAG_DRAW_NON_BACK_FACES_ONLY=1<<21,FLAG_ENABLE_BACK_FACE_CULLING=1<<24,FLAG_BLEND_MODE_BIT_OFFSET=26,FLAG_BLEND_MODE_MASK=31<<26,sceneGraphExportDataMap=new WeakMap,sceneGraphZIndexMap=new WeakMap;C3.WorldInfo=class extends C3.DefendedBase{#t=NaN;#e=NaN;#s=NaN;#i=0;#n=0;constructor(t,e){super(),this._inst=t,this._objectClass=t.GetObjectClass(),this._runtime=t.GetRuntime(),this._layer=e,this._objectClass._OnWorldInstanceLayerChanged(this,null,e),this._zIndex=-1,this._htmlZIndex=-1,this._flags=196635,this._objectClass.GetPlugin().IsRotatable()&&(this._flags|=128),this._x=NaN,this._y=NaN,this._z=NaN,this._w=NaN,this._h=NaN,this._depth=NaN,this._a=NaN,this._sinA=NaN,this._cosA=NaN,this._boundingBox=new C3.AABB3D,this._boundingQuad=new C3.Quad2D,this._collisionCells=DEFAULT_COLLISION_CELLS,this._renderCells=DEFAULT_RENDER_CELLS,this._sourceCollisionPoly=null,this._transformedPolyInfo=null,this._solidFilterTags=null,this._color=DEFAULT_COLOR,this._colorPremultiplied=DEFAULT_COLOR,this._stateGroup=null,this._instanceEffectList=null,this._inst.GetObjectClass().UsesEffects()&&(this._instanceEffectList=C3.New(C3.InstanceEffectList,this._inst,this)),this._sceneGraphInfo=null,this._tmpSceneGraphChildren=null,this._tmpSceneGraphChildrenIndexes=null,this._tmpHierarchyPosition=-1,this._meshInfo=null}_MarkDestroyed(){this._flags|=256}IsDestroyed(){return!!(256&this._flags)}Release(){if(this._objectClass._OnWorldInstanceLayerChanged(this,this._layer,null),this._stateGroup&&(this._runtime.GetRenderer().ReleaseStateGroup(this._stateGroup),this._stateGroup=null),this._sourceCollisionPoly=null,this._transformedPolyInfo&&(this._transformedPolyInfo.poly.Release(),this._transformedPolyInfo=null),this._solidFilterTags&&(this._solidFilterTags.clear(),this._solidFilterTags=null),this.ReleaseMesh(),this._instanceEffectList&&this._instanceEffectList.Release(),this.HasParent()&&this.GetParent().RemoveChild(this),this.HasChildren()){const t=[...this.GetChildren()];for(const e of t)this.RemoveChild(e)}this._ReleaseSceneGraphInfo(),this._ReleaseTmpSceneGraphInfo(),sceneGraphExportDataMap.delete(this),sceneGraphZIndexMap.delete(this),this._inst=null,this._objectClass=null,this._runtime=null,this._layer=null}Init(t){if(enableUpdateRendererStateGroup=!1,this.SetXYZ(t[0],t[1],t[2]),this.SetSize(t[3],t[4]),this._depth=t[5],this.IsRotatable()?this.SetAngle(t[6]):this._a=0,tempColor.setFromJSON(t[7]),this._SetColor(tempColor),this.SetOriginX(t[8]),this.SetOriginY(t[9]),this.SetOriginZ(t[10]),this.SetBlendMode(t[11]),this.#i=t[12],this._instanceEffectList&&this._instanceEffectList._LoadEffectParameters(t[13]),t[15]&&sceneGraphExportDataMap.set(this,{childrenData:t[15][1],zIndexData:t[15][2]}),t[16]){const e=t[16];this.CreateMesh(e[0],e[1]);const s=this.GetSourceMesh(),i=e[2];for(let t=0,e=i.length;t=e.length?null:e[t]}GetChildIndex(t){if(!t)return NaN;const e=this.GetChildren();if(!e)return NaN;for(let s=0;s":t.GetTextureFillShaderProgram()||"",this._stateGroup=t.AcquireStateGroup(e,this.GetBlendMode(),this._colorPremultiplied,this.GetZ(),this.IsBackFaceCulling()?1:0,0)}GetRendererStateGroup(){return this._stateGroup}HasDefaultColor(){return this._color===DEFAULT_COLOR}SetBlendMode(t){if((t|=0)<0||t>31)throw new RangeError("invalid blend mode");this.GetBlendMode()!==t&&(this._flags=-2080374785&this._flags|t<<26,this._UpdateRendererStateGroup())}GetBlendMode(){return(2080374784&this._flags)>>26}_SetLayer(t,e){const s=e&&this._layer!==t;s&&this._RemoveFromRenderCells(),this._objectClass._OnWorldInstanceLayerChanged(this,this._layer,t),this._layer=t,s&&this._UpdateRenderCell(),0!==this.GetZ()&&this._layer._SetAnyInstanceZElevated(),this._UpdateActiveSamplingMode()}GetLayer(){return this._layer}GetLayout(){return this.GetLayer().GetLayout()}_SetZIndex(t){this._zIndex=0|t}GetZIndex(){return this._layer._UpdateZIndices(),this._zIndex}_SetHTMLZIndex(t){this._htmlZIndex=0|t}GetHTMLZIndex(){return this._layer._UpdateHTMLZIndices(),this._htmlZIndex}_GetLastCachedZIndex(){return this._zIndex}_SetFlag(t,e){e?this._flags|=t:this._flags&=~t}IsVisible(){return!!(1&this._flags)}SetVisible(t){if(this._SetFlag(1,t),this.HasChildren())for(const e of this.GetChildren())e.GetTransformWithParentVisibility()&&e.SetVisible(t)}IsCollisionEnabled(){return!!(8&this._flags)}SetCollisionEnabled(t){t=!!t,this.IsCollisionEnabled()!==t&&(this._SetFlag(8,t),t?this.SetBboxChanged():this._RemoveFromCollisionCells())}SetSolidCollisionFilter(t,e){this._SetFlag(32,t),this._solidFilterTags&&this._solidFilterTags.clear();for(const t of e)this._solidFilterTags||(this._solidFilterTags=new Set),this._solidFilterTags.add(t.toLowerCase());this._solidFilterTags&&0===this._solidFilterTags.size&&(this._solidFilterTags=null)}IsSolidCollisionAllowed(t){const e=t._IsSolidUsingInstanceTags()?t._GetLowercaseTagsSetMaybeNull():t.GetSavedDataMap().get("solidTags"),s=!!(32&this._flags),i=this._solidFilterTags;if(!e||!i)return!s;for(const t of i)if(e.has(t))return s;return!s}SetBboxChanged(){if(this._flags|=65554,this._objectClass._SetAnyCollisionCellChanged(!0),this._runtime.UpdateRender(),this._layer.UsesRenderCells()&&(this.CalculateBbox(this._boundingBox,this._boundingQuad,!0),this._flags&=-3,this._UpdateRenderCell()),4&this._flags&&this._inst.Dispatcher().dispatchEvent(bboxChangeEvent),null!==this._sceneGraphInfo){const t=this._sceneGraphInfo.GetChildren();for(let e=0,s=t.length;e=s.Get2DCameraZ())&&(s.GetViewportForZ(e,tempRect),tempRect.intersectsAABB3D(t))}IsInViewport3D(t){return t.ContainsAABB(this.GetBoundingBox())}IsInViewport2(){const t=this.GetLayer();if(t.Has3DCamera())return this.IsInViewport3D(t._GetViewFrustum());{const e=t.GetLayout();return this.IsInViewport(t.GetViewport(),e.HasVanishingPointOutsideViewport(),e.IsOrthographicProjection())}}_SetDrawBackFaceOnly(t){this._SetFlag(1048576,t)}_SetDrawNonBackFacesOnly(t){this._SetFlag(2097152,t)}IsDrawBackFaceOnly(){return!!(1048576&this._flags)}IsDrawNonBackFacesOnly(){return!!(2097152&this._flags)}SetBackFaceCulling(t){(t=!!t)!==this.IsBackFaceCulling()&&(this._SetFlag(16777216,t),this._UpdateRendererStateGroup())}IsBackFaceCulling(){return!!(16777216&this._flags)}SetSourceCollisionPoly(t){this._sourceCollisionPoly=t,this._DiscardTransformedCollisionPoly(),this.HasMesh()&&(this._meshInfo.meshPoly=null)}GetSourceCollisionPoly(){return this._sourceCollisionPoly}HasOwnCollisionPoly(){return null!==this._sourceCollisionPoly||this.HasMesh()}GetTransformedCollisionPoly(){return this._GetCustomTransformedCollisionPolyPrecalc(this.GetWidth(),this.GetHeight(),this.GetAngle(),this.GetSinAngle(),this.GetCosAngle())}GetCustomTransformedCollisionPoly(t,e,s){let i=0,n=1;return 0!==s&&(i=Math.sin(s),n=Math.cos(s)),this._GetCustomTransformedCollisionPolyPrecalc(t,e,s,i,n)}_GetCustomTransformedCollisionPolyPrecalc(t,e,s,i,n){let r=this._transformedPolyInfo;null===r&&(r={poly:C3.New(C3.CollisionPoly),width:NaN,height:NaN,angle:NaN},this._transformedPolyInfo=r);const h=r.poly;if(r.width===t&&r.height===e&&r.angle===s)return h;const a=this._sourceCollisionPoly;if(this.HasMesh()){const s=this.GetOriginX(),r=this.GetOriginY(),o=this.GetSourceMesh();let l=this._meshInfo.meshPoly;l||(a?(tempCollisionPoly.copy(a),tempCollisionPoly.offset(s,r)):tempCollisionPoly.setDefaultPoints(),l=o.InsertPolyMeshVertices(tempCollisionPoly),this._meshInfo.meshPoly=l),o.TransformCollisionPoly(l,h),h.offset(-s,-r),h.transformPrecalc(t,e,i,n)}else a?(h.copy(a),h.transformPrecalc(t,e,i,n)):h.setFromQuad(this.GetBoundingQuad(),-this.GetX(),-this.GetY());return r.width=t,r.height=e,r.angle=s,h}_DiscardTransformedCollisionPoly(){this.SetPhysicsBodyChanged(!0);const t=this._transformedPolyInfo;null!==t&&(t.width=NaN)}CreateMesh(t,e,s){if(t=Math.floor(t),e=Math.floor(e),!this.GetInstance().GetPlugin().SupportsMesh())throw new Error("object does not support mesh");let i=null;if(s&&this._meshInfo?.sourceMesh&&(i=new C3.Gfx.DeformMesh(this._meshInfo.sourceMesh.GetHSize(),this._meshInfo.sourceMesh.GetVSize()),i.CopyFrom(this._meshInfo.sourceMesh)),this.ReleaseMesh(),this._meshInfo={sourceMesh:C3.New(C3.Gfx.DeformMesh,t,e),transformedMesh:C3.New(C3.Gfx.DeformMesh,t,e),meshPoly:null},i){const t=i.GetHSize()/this._meshInfo.sourceMesh.GetHSize(),e=i.GetVSize()/this._meshInfo.sourceMesh.GetVSize();this._meshInfo.sourceMesh.CopyFrom(i,t,e),i.Release()}this.SetMeshChanged(!0)}HasMesh(){return null!==this._meshInfo}GetSourceMesh(){if(!this.HasMesh())throw new Error("no mesh");return this._meshInfo.sourceMesh}GetTransformedMesh(){if(!this.HasMesh())throw new Error("no mesh");return this._meshInfo.transformedMesh}SetMeshChanged(t){this._SetFlag(65536,t)}IsMeshChanged(){return!!(65536&this._flags)}SetPhysicsBodyChanged(t){this._SetFlag(131072,t)}IsPhysicsBodyChanged(){return!!(131072&this._flags)}#r(t){const e=this._meshInfo.sourceMesh,s=Math.min(e.GetMinX(),0),i=Math.min(e.GetMinY(),0),n=Math.max(e.GetMaxX(),1),r=Math.max(e.GetMaxY(),1),h=t.width(),a=t.height();t.offsetLeft(s*h),t.offsetTop(i*a),t.offsetRight((n-1)*h),t.offsetBottom((r-1)*a),this._depth=Math.max(e.GetMaxZ(),0)-Math.min(e.GetMinZ(),0)}#h(t){const e=this._meshInfo.sourceMesh,s=Math.min(e.GetMinZ(),0),i=Math.max(e.GetMaxZ(),1);t.offsetBack(s),t.offsetFront(i)}ReleaseMesh(){this._meshInfo&&(this._meshInfo.sourceMesh.Release(),this._meshInfo.transformedMesh.Release(),this._meshInfo=null,this._DiscardTransformedCollisionPoly())}SetMeshPoint(t,e,s){t=Math.floor(t),e=Math.floor(e);const i=s.mode||"absolute";if(!VALID_SET_MESH_POINT_MODES.has(i))throw new Error("invalid mode");const n="relative"===i;let r=s.x,h=s.y;const a=s.z;let o="number"==typeof s.u?s.u:n?0:-1,l="number"==typeof s.v?s.v:n?0:-1;if(!this.HasMesh())return!1;const _=this.GetSourceMesh(),c=_.GetMeshPointAt(t,e);if(null===c)return!1;let G=!1;return"number"==typeof a&&c.GetZ()!==a&&(c.SetZ(a),G=!0),n&&(r+=t/(_.GetHSize()-1),h+=e/(_.GetVSize()-1)),-1!==o||n?(n&&(o+=t/(_.GetHSize()-1)),o=C3.clamp(o,0,1)):o=c.GetU(),-1!==l||n?(n&&(l+=e/(_.GetVSize()-1)),l=C3.clamp(l,0,1)):l=c.GetV(),c.GetX()===r&&c.GetY()===h&&c.GetU()===o&&c.GetV()===l?G:(c.SetX(r),c.SetY(h),c.SetU(o),c.SetV(l),this._DiscardTransformedCollisionPoly(),!0)}HasTilemap(){return this._inst.HasTilemap()}ContainsPoint(t,e){return!!this.GetBoundingBox().containsPoint2d(t,e)&&(!!this.GetBoundingQuad().containsPoint(t,e)&&(this.HasTilemap()?this._inst.GetSdkInstance().TestPointOverlapTile(t,e):!this.HasOwnCollisionPoly()||this.GetTransformedCollisionPoly().containsPoint(t-this.GetX(),e-this.GetY())))}_IsCollisionCellChanged(){return!!(16&this._flags)}_UpdateCollisionCell(){if(!this._IsCollisionCellChanged()||!this.IsCollisionEnabled()||this.IsDestroyed())return;const t=this.GetBoundingBox(),e=this._objectClass._GetCollisionCellGrid(),s=this._collisionCells;if(tempRect.set(e.XToCell(t.getLeft()),e.YToCell(t.getTop()),e.XToCell(t.getRight()),e.YToCell(t.getBottom())),s.equals(tempRect))return;const i=this._inst;s===DEFAULT_COLLISION_CELLS?(e.Update(i,null,tempRect),this._collisionCells=C3.New(C3.Rect,tempRect)):(e.Update(i,s,tempRect),s.copy(tempRect)),this._flags&=-17}_SetCollisionCellChanged(){this._flags|=16}_RemoveFromCollisionCells(){const t=this._collisionCells;t!==DEFAULT_COLLISION_CELLS&&(this._objectClass._GetCollisionCellGrid().Update(this._inst,t,null),this._collisionCells=DEFAULT_COLLISION_CELLS)}_UpdateRenderCell(){const t=this.GetLayer();if(!t.UsesRenderCells()||this.IsDestroyed())return;const e=t.GetRenderGrid(),s=this.GetBoundingBox(),i=this._renderCells;if(tempRect.set(e.XToCell(s.getLeft()),e.YToCell(s.getTop()),e.XToCell(s.getRight()),e.YToCell(s.getBottom())),i.equals(tempRect))return;const n=this._inst;i===DEFAULT_RENDER_CELLS?(e.Update(n,null,tempRect),this._renderCells=C3.New(C3.Rect,tempRect)):(e.Update(n,i,tempRect),i.copy(tempRect)),t.SetRenderListStale()}_RemoveFromRenderCells(){const t=this._renderCells;t!==DEFAULT_RENDER_CELLS&&(this.GetLayer().GetRenderGrid().Update(this._inst,t,null),this._renderCells=DEFAULT_RENDER_CELLS)}GetRenderCellRange(){return this._renderCells}ZOrderMoveToTop(){if(this.IsDestroyed())return;const t=this._inst,e=this._layer,s=e._GetInstances();s.length&&s.at(-1)===t||(e._RemoveInstance(t,!1),e._AddInstance(t,!1),this._runtime.UpdateRender())}ZOrderMoveToBottom(){if(this.IsDestroyed())return;const t=this._inst,e=this._layer,s=e._GetInstances();s.length&&s[0]===t||(e._RemoveInstance(t,!1),e._PrependInstance(t,!1),this._runtime.UpdateRender())}ZOrderMoveToLayer(t){if(this.IsDestroyed())return;const e=this._inst,s=this._layer;if(s.GetLayout()!==t.GetLayout())throw new Error("layer from different layout");t!==s&&(s._RemoveInstance(e,!0),this._SetLayer(t),t._AddInstance(e,!0),this._runtime.UpdateRender())}ZOrderMoveAdjacentToInstance(t,e){if(this.IsDestroyed())return;const s=this._inst;let i=!1;const n=this._layer;if(t.GetUID()===s.GetUID())return;const r=t.GetWorldInfo();if(!r)throw new Error("expected world instance");const h=r.GetLayer();n.GetIndex()!==h.GetIndex()&&(n._RemoveInstance(s,!0),this._SetLayer(h),h._AddInstance(s,!0),i=!0);const a=h.MoveInstanceAdjacent(s,t,!!e);(i||a)&&this._runtime.UpdateRender()}GetInstanceEffectList(){return this._instanceEffectList}_SetHasAnyActiveEffect(t){this._SetFlag(64,t)}HasAnyActiveEffect(){return!!(64&this._flags)}_SaveToJson(t,e=null){const s={"x":this.GetX(),"y":this.GetY(),"w":this.GetWidth(),"h":this.GetHeight(),"l":this.GetLayer().GetSID(),"zi":this.GetZIndex()};0!==this.GetZ()&&(s["ze"]=this.GetZ()),0!==this.GetDepth()&&(s["d"]=this.GetDepth()),0!==this.GetAngle()&&(s["a"]=this._GetAngleNoReflect()),this.HasDefaultColor()||(s["c"]=this._color.toJSON()),.5!==this.GetOriginX()&&(s["oX"]=this.GetOriginX()),.5!==this.GetOriginY()&&(s["oY"]=this.GetOriginY()),0!==this.GetOriginZ()&&(s["oZ"]=this.GetOriginZ()),0!==this.GetBlendMode()&&(s["bm"]=this.GetBlendMode()),this.IsVisible()||(s["v"]=this.IsVisible()),"auto"!==this.GetSamplingMode()&&(s["samp"]=this.GetSamplingMode()),this.IsCollisionEnabled()||(s["ce"]=this.IsCollisionEnabled()),this.IsBboxChangeEventEnabled()&&(s["be"]=this.IsBboxChangeEventEnabled()),this._instanceEffectList&&(s["fx"]=this._instanceEffectList._SaveToJson());const i=!!(32&this._flags);return i&&(s["sfi"]=i),this._solidFilterTags&&(s["sft"]=[...this._solidFilterTags].join(" ")),this._sceneGraphInfo&&"visual-state"!==t&&(s["sgi"]=this._sceneGraphInfo._SaveToJson(t,e),sceneGraphExportDataMap.has(this)&&(s["sgcd"]=sceneGraphExportDataMap.get(this).childrenData,s["sgzid"]=sceneGraphExportDataMap.get(this).zIndexData)),this.HasMesh()&&(s["mesh"]=this.GetSourceMesh().SaveToJson()),s}_SaveSceneGraphPropertiesToJson(){return{"x":this._x,"y":this._y,"z":this._z,"w":this._w,"h":this._h,"d":this._depth,"a":this._a,"sgi":this._GetSceneGraphInfo()?this._GetSceneGraphInfo()._SaveToJsonProperties():null}}_LoadSceneGraphPropertiesFromJson(t){t&&(this._x=t["x"],this._y=t["y"],this._z=t["z"],this._w=t["w"],this._h=t["h"],t.hasOwnProperty("d")&&(this._depth=t["d"]),this._a=t["a"],t["sgi"]&&this._GetSceneGraphInfo()&&this._GetSceneGraphInfo()._LoadFromJson(t["sgi"]),this._MarkSinCosAngleChanged(),this.SetBboxChanged())}_SetupSceneGraphConnectionsOnChangeOfLayout(){this._ReleaseTmpSceneGraphInfo(),this._ResetAllSceneGraphState(),this._CreateSceneGraphInfo(null),this._sceneGraphInfo&&this._sceneGraphInfo._SetTmpSceneGraphChildren(this._tmpSceneGraphChildren,this._tmpSceneGraphChildrenIndexes)}_OnBeforeLoad(t){"visual-state"!==t&&this._ResetAllSceneGraphState()}_OnAfterLoad(t,e="full",s=null){if(t.hasOwnProperty("sgi")&&"visual-state"!==e){if(this.IsDestroyed())return;this._sceneGraphInfo._OnAfterLoad(t["sgi"],s)}}_OnAfterLoad2(t,e="full",s=null){if("visual-state"!==e)if(this.IsDestroyed())this._ReleaseTmpSceneGraphInfo();else{if(t.hasOwnProperty("sgi"))this._sceneGraphInfo._SetTmpSceneGraphChildren(null,null,t["sgi"],s);else if(s?.setFromJson&&this._tmpSceneGraphChildren)for(const t of this._tmpSceneGraphChildren)t.IsDestroyed()||this._runtime.DestroyInstance(t);this._ReleaseTmpSceneGraphInfo(),this.SetBboxChanged()}}_LoadFromJson(t,e,s=null){if(enableUpdateRendererStateGroup=!1,this.SetX(t["x"]),this.SetY(t["y"]),this.SetZ(t.hasOwnProperty("ze")?t["ze"]:0),this.SetWidth(t["w"]),this.SetHeight(t["h"]),this.SetDepth(t["d"]??0),this._SetZIndex(t["zi"]),this.SetAngle(t.hasOwnProperty("a")?t["a"]:0),t.hasOwnProperty("c")?tempColor.setFromJSON(t["c"]):t.hasOwnProperty("o")?(tempColor.copyRgb(this._color),tempColor.a=t["o"]):tempColor.setRgba(1,1,1,1),this._SetColor(tempColor),this.SetOriginX(t["oX"]??.5),this.SetOriginY(t["oY"]??.5),this.SetOriginZ(t["oZ"]??0),this.SetBlendMode(t["bm"]??0),this.SetVisible(t["v"]??!0),this.#i=C3.Gfx.RendererBase.SamplingModeToNumber(t["samp"]??"auto"),this.SetCollisionEnabled(!t.hasOwnProperty("ce")||t["ce"]),this.SetBboxChangeEventEnabled(!!t.hasOwnProperty("be")&&t["be"]),this.SetSolidCollisionFilter(!!t.hasOwnProperty("sfi")&&t["sfi"],t.hasOwnProperty("sft")?t["sft"]:""),this._instanceEffectList&&t.hasOwnProperty("fx")&&this._instanceEffectList._LoadFromJson(t["fx"]),t.hasOwnProperty("sgi")&&"visual-state"!==e){this._CreateSceneGraphInfo(null);const e=this._sceneGraphInfo,s=t["sgi"];e._LoadFromJson(s),e._SetTmpSceneGraphChildren(this._tmpSceneGraphChildren,this._tmpSceneGraphChildrenIndexes),this._SetSceneGraphExportData(t["sgcd"],t["sgzid"])}if(t.hasOwnProperty("mesh")){const e=t["mesh"];this.CreateMesh(e["cols"],e["rows"]),this.GetSourceMesh().LoadFromJson(e)}else this.ReleaseMesh();this.SetBboxChanged(),enableUpdateRendererStateGroup=!0,this._UpdateRendererStateGroup(),"visual-state"!==e&&this._runtime.AddInstanceNeedingAfterLoad(this.GetInstance(),t)}_SetSceneGraphExportData(t,e){t&&C3.IsFiniteNumber(e)&&sceneGraphExportDataMap.set(this,{childrenData:t,zIndexData:e})}}; } // objects/behaviorType.js { const C3=self.C3;C3.BehaviorType=class extends C3.DefendedBase{constructor(e,t){super();const s=e.GetRuntime(),i=s.GetObjectReference(t[1]);s.GetAddonManager()._DelayCreateBehavior(i),this._runtime=s,this._objectClass=e,this._behavior=C3.AddonManager.GetBehaviorByConstructorFunction(i),this._sdkType=null,this._iBehaviorType=null,this._instSdkCtor=i.Instance,this._sid=t[2],this._name=t[0],this._jsPropName=this._runtime.GetJsPropName(t[3]);const r=this._behavior.GetSdkVersion();if(r<2&&(this._sdkType=C3.New(i.Type,this),!(this._sdkType instanceof C3.SDKBehaviorTypeBase)))throw new Error("v1 sdk type must derive from SDKBehaviorBase");if(C3.AddonManager._PushInitObject(this,r),r>=2){const e=i.Type??globalThis.ISDKBehaviorTypeBase;if(this._iBehaviorType=new e,!(this._iBehaviorType instanceof globalThis.ISDKBehaviorTypeBase))throw new Error("script interface class must derive from ISDKBehaviorTypeBase")}else this._iBehaviorType=new globalThis.IBehaviorType;C3.AddonManager._PopInitObject(r),this.OnCreate()}static Create(e,t){return C3.New(C3.BehaviorType,e,t)}Release(){this._runtime=null,this._behavior=null,this._sdkType&&(this._sdkType.Release(),this._sdkType=null),this._instSdkCtor=null}GetSdkType(){return this._sdkType}OnCreate(){this._sdkType?this._sdkType.OnCreate():this._iBehaviorType&&this._iBehaviorType._onCreate()}GetRuntime(){return this._runtime}GetObjectClass(){return this._objectClass}GetBehavior(){return this._behavior}GetInstanceSdkCtor(){return this._instSdkCtor}GetName(){return this._name}GetSID(){return this._sid}GetIBehaviorType(){return this._iBehaviorType}GetJsPropName(){return this._jsPropName}}; } // objects/behaviorInstance.js { const C3=self.C3,IBehaviorInstance=self.IBehaviorInstance;C3.BehaviorInstance=class extends C3.DefendedBase{constructor(t){super(),this._runtime=t.runtime,this._behaviorType=t.behaviorType,this._behavior=this._behaviorType.GetBehavior(),this._inst=t.instance,this._index=t.index,this._sdkInst=null,this._iScriptInterface=null,this._behavior._AddInstance(this._inst)}Release(){this._iScriptInterface&&(this._iScriptInterface._release(),this._iScriptInterface=null),this._behavior._RemoveInstance(this._inst),this._sdkInst&&(this._sdkInst.Release(),this._sdkInst=null),this._runtime=null,this._behaviorType=null,this._behavior=null,this._inst=null}_CreateSdkInstance(t){if(this._sdkInst)throw new Error("already got sdk instance");if(this.GetBehavior().GetSdkVersion()<2){if(this._sdkInst=C3.New(this._behaviorType.GetInstanceSdkCtor(),this,t),!(this._sdkInst instanceof C3.SDKBehaviorInstanceBase))throw new Error("v1 sdk type must derive from SDKBehaviorInstanceBase")}else{const e=this.GetBehavior().GetScriptInterfaceClass();this._InitScriptInterface(e.Instance,t)}}GetSdkInstance(){return this._sdkInst??this._iScriptInterface}GetObjectInstance(){return this._inst}GetRuntime(){return this._runtime}GetBehaviorType(){return this._behaviorType}GetBehavior(){return this._behavior}_GetIndex(){return this._index}PostCreate(){this._sdkInst?this._sdkInst.PostCreate():this._iScriptInterface._postCreate()}OnSpriteFrameChanged(t,e){this._sdkInst&&this._sdkInst.OnSpriteFrameChanged(t,e)}_GetDebuggerProperties(){return this._sdkInst?this._sdkInst.GetDebuggerProperties():this._iScriptInterface._getDebuggerProperties()}SaveToJson(t="full"){return this._sdkInst?this._sdkInst.SaveToJson(t):this._iScriptInterface._saveToJson(t)}LoadFromJson(t,e="full"){if(this._sdkInst)return this._sdkInst.LoadFromJson(t,e);this._iScriptInterface._loadFromJson(t,e)}static SortByTickSequence(t,e,s){const n=globalThis.ISDKBehaviorInstanceBase;let i,r;i=e instanceof n?t._UnwrapScriptInterface(e):e.GetBehaviorInstance(),r=s instanceof n?t._UnwrapScriptInterface(s):s.GetBehaviorInstance();const a=i.GetObjectInstance(),h=r.GetObjectInstance(),c=a.GetObjectClass().GetIndex(),o=h.GetObjectClass().GetIndex();if(c!==o)return c-o;const I=a.GetPUID(),_=h.GetPUID();return I!==_?I-_:i._GetIndex()-r._GetIndex()}_InitScriptInterface(t,e){const s=IBehaviorInstance,n=t??this._sdkInst.GetScriptInterfaceClass(),i=n||s,r=this.GetBehavior().GetSdkVersion();if(C3.AddonManager._PushInitObject(this,r),C3.AddonManager._PushInitProperties(e),this._iScriptInterface=new i,C3.AddonManager._PopInitProperties(),C3.AddonManager._PopInitObject(r),n&&!(this._iScriptInterface instanceof s))throw new TypeError(`script interface class '${n.name}' does not extend the right base class '${s.name}'`);return this._iScriptInterface}GetScriptInterface(){return this._iScriptInterface||this._InitScriptInterface()}HasScriptInterface(){return!!this._iScriptInterface}}; } // objects/effectList.js { const C3=self.C3;C3.EffectList=class extends C3.DefendedBase{constructor(e,t){super(),this._owner=e,this._allEffectTypes=[],this._activeEffectTypes=[],this._effectTypesByName=new Map,this._effectParams=[],this._effectParamBuffers=[],this._allInstanceEffectLists=new Set,this._preservesOpaqueness=!0;for(const e of t){const t=C3.New(C3.EffectType,this,e,this._allEffectTypes.length);this._allEffectTypes.push(t),this._effectTypesByName.set(t.GetName().toLowerCase(),t),e.length>=3&&this._effectParams.push(this._LoadSingleEffectParameters(t,e[2]))}this.GetRuntime()._AddEffectList(this)}Release(){this.GetRuntime()._RemoveEffectList(this);for(const e of this._effectParamBuffers)e.Release();C3.clearArray(this._effectParamBuffers),C3.clearArray(this._allEffectTypes),C3.clearArray(this._activeEffectTypes),this._effectTypesByName.clear(),C3.clearArray(this._effectParams),this._owner=null}_AddInstanceEffectList(e){this._allInstanceEffectLists.add(e)}_RemoveInstanceEffectList(e){this._allInstanceEffectLists.delete(e)}_InitRenderer(e){e.IsWebGPU()&&(this._effectParamBuffers=this._allEffectTypes.map(e=>{const t=e.GetShaderProgram();return t.GetCustomParametersByteSize()>0?C3.New(C3.Gfx.WebGPUEffectCustomParamsBuffer,t):null}),this._UpdateAllEffectParamBuffers());for(const t of this._allInstanceEffectLists)t._InitRenderer(e)}PrependEffectTypes(e){if(e.length){this._allEffectTypes=e.concat(this._allEffectTypes);for(const t of e)this._effectTypesByName.set(t.GetName().toLowerCase(),t);for(let e=0,t=this._allEffectTypes.length;e0}GetEffectTypeByName(e){return this._effectTypesByName.get(e.toLowerCase())||null}GetEffectTypeByIndex(e){if((e=Math.floor(+e))<0||e>=this._allEffectTypes.length)throw new RangeError("invalid effect type index");return this._allEffectTypes[e]}IsEffectIndexActive(e){return this.GetEffectTypeByIndex(e).IsActive()}SetEffectIndexActive(e,t){this.GetEffectTypeByIndex(e).SetActive(t)}GetActiveEffectTypes(){return this._activeEffectTypes}HasAnyActiveEffect(){return this._activeEffectTypes.length>0}PreservesOpaqueness(){return this._preservesOpaqueness}GetEffectParametersForIndex(e){return this._effectParams[e]}_GetEffectChainShaderParametersForIndex(e){return e=this._effectParams.length)return null;const s=this._effectParams[e];return t<0||t>=s.length?null:s[t]}SetEffectParameter(e,t,s){if(e<0||e>=this._effectParams.length)return!1;const f=this._effectParams[e];if(t<0||t>=f.length)return!1;const r=f[t];if(r instanceof C3.Color){if(r.equalsIgnoringAlpha(s))return!1;r.copyRgb(s)}else{if(r===s)return!1;f[t]=s}return e({"name":e.GetName(),"active":e.IsActive(),"params":C3.EffectList.SaveFxParamsToJson(this._effectParams[e.GetIndex()])}))}LoadFromJson(e){for(const t of e){const e=this.GetEffectTypeByName(t["name"]);e&&(e.SetActive(t["active"]),this._effectParams[e.GetIndex()]=C3.EffectList.LoadFxParamsFromJson(t["params"]))}this.UpdateActiveEffects(),this._UpdateAllEffectParamBuffers()}}; } // objects/effectType.js { const C3=self.C3;C3.EffectType=class extends C3.DefendedBase{constructor(e,t,r){super(),this._effectList=e,this._id=t[0],this._name=t[1],this._index=r,this._shaderProgram=null,this._isActive=!0}Release(){this._effectList=null,this._shaderProgram=null}Clone(e){const t=C3.New(C3.EffectType,e,[this._id,this._name],-1);return t._shaderProgram=this._shaderProgram,t._isActive=this._isActive,t}_InitRenderer(e){const t=e.GetShaderProgramByName(this._id);if(!t)throw new Error("failed to find shader program '"+this._id+"'");this._shaderProgram=t}GetEffectList(){return this._effectList}GetName(){return this._name}_SetIndex(e){this._index=e}GetIndex(){return this._index}GetOwner(){return this._effectList.GetOwner()}GetRuntime(){return this._effectList.GetRuntime()}SetActive(e){this._isActive=!!e}IsActive(){return this._isActive}GetShaderProgram(){return this._shaderProgram}GetDefaultParameterValues(){const e=[];for(let t=0,r=this._shaderProgram.GetParameterCount();t{const s=t.GetContentObject(),f=s.GetWorldInfo();e.SetColor(f.GetPremultipliedColor()),e.SetCurrentZ(f.GetTotalZ()),s.Draw(e),e.SetCurrentZ(0)},getSourceTextureInfo:e=>{const t=e.GetCurrentTexRect(),[s,f]=e.GetCurrentSurfaceSize();return{srcTexRect:t,srcWidth:s,srcHeight:f}},getShaderParameters:e=>this._GetEffectChainShaderParametersForIndex(e)}),this._activeEffectFlags=[],this._activeEffectTypes=[],this._preservesOpaqueness=!0,this._effectParams=[],this._effectParamBuffers=[],this._InitRenderer(e.GetRuntime().GetRenderer());for(let e=0,t=this._effectList.GetAllEffectTypes().length;e{const t=e.GetShaderProgram();return t.GetCustomParametersByteSize()>0?C3.New(C3.Gfx.WebGPUEffectCustomParamsBuffer,t):null}))}_LoadEffectParameters(e){let t=0;for(const s of e)this._effectParams.push(this._LoadSingleEffectParameters(t,s)),++t;this._UpdateAllEffectParamBuffers(),this.UpdateActiveEffects()}_LoadSingleEffectParameters(e,t){this._activeEffectFlags[e]=t[0];const s=t.slice(1);for(let e=0,t=s.length;ee.GetShaderProgram()),{indexMap:this._activeEffectTypes.map(e=>e.GetIndex()),forcePreDraw:!s||i,is3D:f,isSourceTextureRotated:r,isRotatedOrNegativeSizeInstance:a}),this._needsRebuildSteps=!1,this._wasDefaultColor=s,this._was3D=f,this._wasRotatedOrNegativeSize=a,this._wasTexRotated=r,this._wasMustPreDraw=i)}GetActiveEffectTypes(){return this._activeEffectTypes}GetEffectParametersForIndex(e){return this._effectParams[e]}_GetEffectChainShaderParametersForIndex(e){return e=this._effectParams.length)return null;const s=this._effectParams[e];return t<0||t>=s.length?null:s[t]}SetEffectParameter(e,t,s){if(e<0||e>=this._effectParams.length)return!1;const f=this._effectParams[e];if(t<0||t>=f.length)return!1;const a=f[t];if(a instanceof C3.Color){if(a.equalsIgnoringAlpha(s))return!1;a.copyRgb(s)}else{if(a===s)return!1;f[t]=s}return ee.GetShaderProgram().BlendsBackground())}IsEffectIndexActive(e){return this._activeEffectFlags[e]}SetEffectIndexActive(e,t){this._activeEffectFlags[e]=!!t}GetAllEffectTypes(){return this._effectList.GetAllEffectTypes()}_SaveToJson(){return this._effectList.GetAllEffectTypes().map(e=>({"name":e.GetName(),"active":this._activeEffectFlags[e.GetIndex()],"params":C3.EffectList.SaveFxParamsToJson(this._effectParams[e.GetIndex()])}))}_LoadFromJson(e){for(const t of e){const e=this._effectList.GetEffectTypeByName(t["name"]);e&&(this._activeEffectFlags[e.GetIndex()]=t["active"],this._effectParams[e.GetIndex()]=C3.EffectList.LoadFxParamsFromJson(t["params"]))}this.UpdateActiveEffects(),this._UpdateAllEffectParamBuffers()}}; } // collisions/collisionEngine.js { const C3=self.C3,tempCandidates=[],tileCollRectCandidates=[],tempJumpthruRet=[],tempPolyA=C3.New(C3.CollisionPoly),tempPolyB=C3.New(C3.CollisionPoly),tempQuad=C3.New(C3.Quad2D),tempRect=C3.New(C3.Rect),tempRect2=C3.New(C3.Rect);let tempPolyC=null,tempRect3=null,tempQuadB=null;C3.CollisionEngine=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e,this._collisionCellWidth=0,this._collisionCellHeight=0,this._registeredCollisions=[],this._collisionCheckCount=0,this._collisionCheckSec=0,this._polyCheckCount=0,this._polyCheckSec=0,this._iCollisionEngine=new self.ICollisionEngine(this)}Release(){this._runtime=null}GetRuntime(){return this._runtime}GetICollisionEngine(){return this._iCollisionEngine}_Update1sStats(){this._collisionCheckSec=this._collisionCheckCount,this._collisionCheckCount=0,this._polyCheckSec=this._polyCheckCount,this._polyCheckCount=0}Get1secCollisionChecks(){return this._collisionCheckSec}Get1secPolyChecks(){return this._polyCheckSec}RegisterCollision(e,t){const s=e.GetWorldInfo(),n=t.GetWorldInfo();s&&n&&s.IsCollisionEnabled()&&n.IsCollisionEnabled()&&this._registeredCollisions.push([e,t])}AddRegisteredCollisionCandidates(e,t,s){for(const[n,l]of this._registeredCollisions){let o=null;if(e===n)o=l;else{if(e!==l)continue;o=n}o.BelongsToObjectClass(t)&&(s.includes(o)||s.push(o))}}CheckRegisteredCollision(e,t){if(!this._registeredCollisions.length)return!1;for(const[s,n]of this._registeredCollisions)if(e===s&&t===n||e===n&&t===s)return!0;return!1}ClearRegisteredCollisions(){C3.clearArray(this._registeredCollisions)}TestOverlap(e,t){if(!e||!t||e===t)return!1;const s=e.GetWorldInfo(),n=t.GetWorldInfo();if(!s.IsCollisionEnabled()||!n.IsCollisionEnabled())return!1;this._collisionCheckCount++;const l=s.GetLayer(),o=n.GetLayer();return l.IsTransformCompatibleWith(o)?this._TestOverlap_SameLayers(s,n):this._TestOverlap_DifferentLayers(s,n)}_TestOverlap_SameLayers(e,t){if(!e.GetBoundingBox().intersectsAABB3DIgnoringZ(t.GetBoundingBox()))return!1;if(this._polyCheckCount++,!e.GetBoundingQuad().intersectsQuad(t.GetBoundingQuad()))return!1;if(e.HasTilemap()&&t.HasTilemap())return!1;if(e.HasTilemap())return this.TestTilemapOverlap(e,t);if(t.HasTilemap())return this.TestTilemapOverlap(t,e);if(!e.HasOwnCollisionPoly()&&!t.HasOwnCollisionPoly())return!0;const s=e.GetTransformedCollisionPoly(),n=t.GetTransformedCollisionPoly();return s.intersectsPoly(n,t.GetX()-e.GetX(),t.GetY()-e.GetY())}_TestOverlap_DifferentLayers(e,t){const s=e.HasTilemap(),n=t.HasTilemap();if(s&&!n)return this.TestTilemapOverlapDifferentLayers(e,t);if(n&&!s)return this.TestTilemapOverlapDifferentLayers(t,e);if(n||s)return!1;{const s=e.GetLayer(),n=t.GetLayer();tempPolyA.copy(e.GetTransformedCollisionPoly()),tempPolyB.copy(t.GetTransformedCollisionPoly());const l=tempPolyA.pointsArr();for(let t=0,n=l.length;t{const[n,l]=i.CanvasCssToLayer(r,t,s,e.GetTotalZ());return e.ContainsPoint(n,l)})),a){if(s)return!1;n._PushInstance(l)}else o&&n._PushElseInstance(l)}}else{let e,r=!1;o&&!l.IsFirstConditionOfType(this._runtime.GetCurrentCondition())?this._runtime.IsCurrentConditionFirst()&&!n._GetOwnElseInstances().length&&n._GetOwnInstances().length?e=n._GetOwnInstances():(e=n._GetOwnElseInstances(),r=!0):e=n._GetOwnInstances();let a=0;for(let l=0,c=e.length;l{const[s,n]=i.CanvasCssToLayer(d,e,t,C.GetTotalZ());return C.ContainsPoint(s,n)})),u){if(s)return!1;r?n._PushInstance(c):e[a++]=c}else r?e[a++]=c:o&&n._PushElseInstance(c)}s||(e.length=a)}return e.ApplySolToContainer(),i.Release(),!!s||n.HasAnyInstances()}_ObjectClassCanUseCollisionCells(e,t){if(!e)return!0;for(const s of t.layersHasInstancesOn())if(!e.IsTransformCompatibleWith(s))return!1;return!0}GetCollisionCandidates(e,t,s,n){if(t.IsFamily())for(const l of t.GetFamilyMembers())this._ObjectClassCanUseCollisionCells(e,l)?(l._UpdateAllCollisionCells(),l._GetCollisionCellGrid().QueryRange(s,n)):C3.appendArray(n,l.GetInstances());else this._ObjectClassCanUseCollisionCells(e,t)?(t._UpdateAllCollisionCells(),t._GetCollisionCellGrid().QueryRange(s,n)):C3.appendArray(n,t.GetInstances())}GetObjectClassesCollisionCandidates(e,t,s,n){for(const l of t)this.GetCollisionCandidates(e,l,s,n)}GetSolidCollisionCandidates(e,t,s){const n=this._runtime.GetSolidBehavior();n&&this.GetObjectClassesCollisionCandidates(e,n.GetObjectClasses(),t,s)}GetJumpthruCollisionCandidates(e,t,s){const n=this._runtime.GetJumpthruBehavior();n&&this.GetObjectClassesCollisionCandidates(e,n.GetObjectClasses(),t,s)}IsSolidCollisionAllowed(e,t){return e._IsSolidEnabled()&&(!t||t.GetWorldInfo().IsSolidCollisionAllowed(e))}TestOverlapSolid(e){const t=e.GetWorldInfo();this.GetSolidCollisionCandidates(t.GetLayer(),t.GetBoundingBox(),tempCandidates);for(const t of tempCandidates)if(this.IsSolidCollisionAllowed(t,e)&&this.TestOverlap(e,t))return C3.clearArray(tempCandidates),t;return C3.clearArray(tempCandidates),null}TestRectOverlapSolid(e,t){this.GetSolidCollisionCandidates(null,e,tempCandidates);for(const s of tempCandidates)if(this.IsSolidCollisionAllowed(s,t)&&this.TestRectOverlap(e,s))return C3.clearArray(tempCandidates),s;return C3.clearArray(tempCandidates),null}TestOverlapJumpthru(e,t){let s=null;t&&(s=tempJumpthruRet,C3.clearArray(s));const n=e.GetWorldInfo();this.GetJumpthruCollisionCandidates(n.GetLayer(),n.GetBoundingBox(),tempCandidates);for(const n of tempCandidates)if(n._IsJumpthruEnabled()&&this.TestOverlap(e,n)){if(!t)return C3.clearArray(tempCandidates),n;s.push(n)}return C3.clearArray(tempCandidates),s}PushOut(e,t,s,n,l){n=n||50;const o=e.GetWorldInfo(),i=o.GetX(),r=o.GetY();for(let a=0;a0){const t=Math.PI;this.hitNormal=C3.clampAngle(this.hitNormal+t),this.normalX=-this.normalX,this.normalY=-this.normalY}}TestInstanceSegment(t,i,s,h,e){const n=C3.rayIntersect(this.x1,this.y1,this.x2,this.y2,i,s,h,e);n>=0&&n[this.GetDrawWidth(),this.GetDrawHeight()],getRenderTarget:()=>this.GetEffectCompositorRenderTarget(),releaseRenderTarget:e=>this.ReleaseEffectCompositorRenderTarget(e),getTime:()=>this.GetRuntime().GetGameTime(),redraw:()=>this.GetRuntime().UpdateRender()}),this._gpuTimeStartFrame=0,this._gpuTimeEndFrame=0,this._gpuLastUtilisation=NaN,this._gpuFrameTimingsBuffer=null,this._layersGpuProfile=new Map,this._gpuCurUtilisation=NaN,this._webgpuTimingPromises=new Map,this._snapshotFormat="",this._snapshotQuality=1,this._snapshotArea=C3.New(C3.Rect),this._snapshotUrl="",this._snapshotPromise=null,this._snapshotResolve=null,this._isPastingToDrawingCanvas=0,this._loaderStartTime=0,this._rafId=-1,this._loadingProgress=0,this._loadingprogress_handler=e=>this._loadingProgress=e.progress,this._percentText=null,this._splashTextures={logo:null,powered:null,website:null},this._splashFrameNumber=0,this._splashFadeInFinishTime=0,this._splashFadeOutStartTime=0,this._splashState="fade-in",this._splashDoneResolve=null,this._splashDonePromise=new Promise(e=>this._splashDoneResolve=e)}_SetGPUPowerPreference(e){this._gpuPreference=e}_SetWebGPUEnabled(e){this._isWebGPUEnabled=!!e}_SetZAxisScale(e){this._zAxisScale=e}GetZAxisScale(){return this._zAxisScale}_SetInitFieldOfView(e){this._initFieldOfView=e}_SetZDistances(e,t){this._zNear=e,this._zFar=t}_SetMinimumRendererCapabilities(e){this.#e=!!e}_SetMultitexturingMode(e){this._multitexturingMode=e}async CreateCanvas(e){let t=e["canvas"];this._canvasLayers.push({canvas:t,ctx:null}),this._runtime.AddDOMComponentMessageHandler("runtime","window-resize",e=>this._OnWindowResize(e)),this._runtime.AddDOMComponentMessageHandler("runtime","fullscreenchange",e=>this._OnFullscreenChange(e)),this._runtime.AddDOMComponentMessageHandler("runtime","fullscreenerror",e=>this._OnFullscreenError(e)),t.addEventListener("webglcontextlost",e=>this._OnWebGLContextLost(e)),t.addEventListener("webglcontextrestored",e=>this._OnWebGLContextRestored(e)),this._isDocumentFullscreen=!!e["isFullscreen"],this._cssDisplayMode=e["cssDisplayMode"];const i=navigator["gpu"]&&this._isWebGPUEnabled;let s=!1;if(i)try{await this._InitWebGPUContext(!0)}catch(e){this._MaybeLogRendererError("WebGPU",e),this._webgpuRenderer=null}if(!this.GetRenderer())try{await this._InitWebGLContext(!0)}catch(e){this._MaybeLogRendererError("WebGL",e),this._webglRenderer=null}if(this.GetRenderer()||(s=!0),!this.GetRenderer()&&i)try{await this._InitWebGPUContext(!1)}catch(e){this._MaybeLogRendererError("WebGPU",e),this._webgpuRenderer=null}if(!this.GetRenderer())try{await this._InitWebGLContext(!1)}catch(e){this._MaybeLogRendererError("WebGL",e),this._webglRenderer=null}const r=this.GetRenderer();if(!r)throw new Error("failed to acquire a renderer - check WebGL or WebGPU is supported");r.SetHasMajorPerformanceCaveat(s),this._webgpuRenderer&&(this._webgpuRenderer.ondevicelost=()=>this._OnWebGPUDeviceLost(),this._webgpuRenderer.ondevicerestored=()=>this._OnWebGPUDeviceRestored()),"normalized"===this._zAxisScale?r.SetZAxisScaleNormalized():(r.SetZAxisScaleRegular(),r.SetFovY(this._initFieldOfView)),this.SetSize(e["windowInnerWidth"],e["windowInnerHeight"],!0),await this._InitRenderer()}_MaybeLogRendererError(e,t){t&&"string"==typeof t.message&&t.message.startsWith("renderer-unavailable")||console.error(`Error creating ${e} renderer: `,t)}async _InitWebGPUContext(e){let t=!0;"no"===this._multitexturingMode?t=!1:"auto"===this._multitexturingMode&&(t=C3.Platform.IsDesktop);const i={nearZ:this._zNear,farZ:this._zFar,powerPreference:this._gpuPreference,depth:this._runtime.Uses3DFeatures(),failIfMajorPerformanceCaveat:e,usesBackgroundBlending:this._runtime.UsesAnyBackgroundBlending(),canSampleBackbuffer:this._runtime.UsesAnyCrossSampling(),canSampleDepth:this._runtime.UsesAnyDepthSampling(),isMultiTexturingAllowed:t};this.#e&&(i.forceCompatibilityMode=!0),this._webgpuRenderer=new C3.Gfx.WebGPURenderer(i),await this._webgpuRenderer.Create(this._canvasLayers[0].canvas)}async _InitWebGLContext(e){const t={alpha:!0,powerPreference:this._gpuPreference,enableGpuProfiling:"xbox-uwp-webview2"!==this._runtime.GetExportType(),depth:this._runtime.Uses3DFeatures(),canSampleDepth:this._runtime.UsesAnyDepthSampling(),failIfMajorPerformanceCaveat:e,nearZ:this._zNear,farZ:this._zFar};this.#e&&(t.maxWebGLVersion=1),this._webglRenderer=C3.New(C3.Gfx.WebGLRenderer,this._canvasLayers[0].canvas,t),await this._webglRenderer.InitState()}async _InitWebGPU(){if(this._shaderData){const e=[];for(const[t,i]of Object.entries(this._shaderData)){i.src=i.wgsl;const s=C3.Gfx.WebGPUShaderProgram.GetDefaultVertexShaderSource(this._webgpuRenderer.IsColorDataF16());e.push(this._webgpuRenderer.CreateShaderProgram(Object.assign({vertexSrc:s,name:t},i)))}await Promise.all(e)}}async _InitWebGL(){if(this._shaderData){const e=[];for(const[t,i]of Object.entries(this._shaderData)){let s;if(i.glslWebGL2&&this._webglRenderer.GetWebGLVersionNumber()>=2)i.src=i.glslWebGL2,s=C3.Gfx.WebGLShaderProgram.GetDefaultVertexShaderSource_WebGL2();else{if(!i.glsl)throw new Error(`shader '${t}' does not support WebGL 1`);i.src=i.glsl,s=C3.Gfx.WebGLShaderProgram.GetDefaultVertexShaderSource()}e.push(this._webglRenderer.CreateShaderProgram(Object.assign({vertexSrc:s,name:t},i)))}await Promise.all(e),this._webglRenderer.ResetLastProgram(),this._webglRenderer.SetTextureFillMode()}this._webglRenderer.SupportsGPUProfiling()&&(this._gpuFrameTimingsBuffer=C3.New(C3.Gfx.WebGLQueryResultBuffer,this._webglRenderer))}async _InitRenderer(){this._webgpuRenderer?await this._InitWebGPU():this._webglRenderer&&await this._InitWebGL();const e=this.GetRenderer();e.SetMipmapsEnabled(this._enableMipmaps),e.SupportsGPUProfiling()&&(this._gpuLastUtilisation=0);for(const t of this._runtime._GetAllEffectLists()){for(const i of t.GetAllEffectTypes())i._InitRenderer(e);t._InitRenderer(e),t.UpdateActiveEffects()}this._iRenderer=new self.IRenderer(this._runtime,e)}Release(){this._runtime=null,this._webglRenderer=null,this._canvasLayers.length=0}IsInWorker(){return this._runtime.IsInWorker()}_OnWindowResize(e){const t=this._runtime;if(t.IsExportToVideo())return;const i=e["devicePixelRatio"];this.IsInWorker()&&(self.devicePixelRatio=i),t._SetDevicePixelRatio(i),this._isDocumentFullscreen=!!e["isFullscreen"],this._cssDisplayMode=e["cssDisplayMode"],this.SetSize(e["innerWidth"],e["innerHeight"]),t.UpdateRender();const s=new C3.Event("window-resize");s.data=e,t.Dispatcher().dispatchEventAndWaitAsyncSequential(s);const r=new C3.Event("resize");r.cssWidth=this.GetCssWidth(),r.cssHeight=this.GetCssHeight(),r.deviceWidth=this.GetDeviceWidth(),r.deviceHeight=this.GetDeviceHeight(),t.DispatchUserScriptEvent(r),this._runtime.GetCurrentLayout()?.BoundScrolling(),t.IsDebug()&&(t.HitBreakpoint()||self.C3Debugger.IsDebuggerPaused())&&t.Render()}_OnFullscreenChange(e){this._isDocumentFullscreen=!!e["isFullscreen"],this.SetSize(e["innerWidth"],e["innerHeight"],!0),this._runtime.UpdateRender()}_OnFullscreenError(e){this._isDocumentFullscreen=!!e["isFullscreen"],this.SetSize(e["innerWidth"],e["innerHeight"],!0),this._runtime.UpdateRender()}SetSize(e,t,i=!1){if(e=Math.floor(e),t=Math.floor(t),e<=0||t<=0)throw new Error("invalid size");if(this._windowInnerWidth===e&&this._windowInnerHeight===t&&!i)return;this._windowInnerWidth=e,this._windowInnerHeight=t;const s=this.GetCurrentFullscreenMode();"letterbox-scale"===s?this._CalculateLetterboxScale(e,t):"letterbox-integer-scale"===s?this._CalculateLetterboxIntegerScale(e,t):"off"===s?this._CalculateFixedSizeCanvas(e,t):this._CalculateFullsizeCanvas(e,t),this._UpdateFullscreenScalingQuality(s);for(const{canvas:e}of this._canvasLayers)e.width=this._canvasDeviceWidth,e.height=this._canvasDeviceHeight;this._runtime.PostComponentMessageToDOM("canvas","update-size",{"marginLeft":this._canvasCssOffsetX,"marginTop":this._canvasCssOffsetY,"styleWidth":this._canvasCssWidth,"styleHeight":this._canvasCssHeight,"displayScale":this.GetDisplayScale()});const r=this.GetRenderer();r.SetSize(this._canvasDeviceWidth,this._canvasDeviceHeight,!0);for(const e of this._availableAdditionalRenderTargets)r.DeleteRenderTarget(e);C3.clearArray(this._availableAdditionalRenderTargets),this.UpdateDefaultProjectionMatrix();const a=this._runtime.GetLayoutManager();a.SetAllLayerProjectionChanged(),a.SetAllLayerMVChanged()}UpdateDefaultProjectionMatrix(){this.GetRenderer().CalculatePerspectiveMatrix(this._defaultProjectionMatrix,this.GetDrawWidth()/this.GetDrawHeight())}GetDefaultProjectionMatrix(){return this._defaultProjectionMatrix}_CalculateLetterboxScale(e,t){const i=this._runtime.GetDevicePixelRatio(),s=this._runtime.GetOriginalViewportWidth(),r=this._runtime.GetOriginalViewportHeight(),a=s/r;if(e/t>a){const i=t*a;this._canvasCssWidth=Math.round(i),this._canvasCssHeight=t,this._canvasCssOffsetX=Math.floor((e-this._canvasCssWidth)/2),this._canvasCssOffsetY=0}else{const i=e/a;this._canvasCssWidth=e,this._canvasCssHeight=Math.round(i),this._canvasCssOffsetX=0,this._canvasCssOffsetY=Math.floor((t-this._canvasCssHeight)/2)}this._canvasDeviceWidth=Math.round(this._canvasCssWidth*i),this._canvasDeviceHeight=Math.round(this._canvasCssHeight*i),this._runtime.SetViewportSize(s,r)}_CalculateLetterboxIntegerScale(e,t){const i=this._runtime.GetDevicePixelRatio();1!==i&&(e+=1,t+=1);const s=this._runtime.GetOriginalViewportWidth(),r=this._runtime.GetOriginalViewportHeight(),a=s/r;let n;if(e/t>a){n=t*a*i/s}else{n=e/a*i/r}n>1?n=Math.floor(n):n<1&&(n=1/Math.ceil(1/n)),this._canvasDeviceWidth=Math.round(s*n),this._canvasDeviceHeight=Math.round(r*n),this._canvasCssWidth=this._canvasDeviceWidth/i,this._canvasCssHeight=this._canvasDeviceHeight/i,this._canvasCssOffsetX=Math.max(Math.floor((e-this._canvasCssWidth)/2),0),this._canvasCssOffsetY=Math.max(Math.floor((t-this._canvasCssHeight)/2),0),this._runtime.SetViewportSize(s,r)}_CalculateFullsizeCanvas(e,t){const i=this._runtime.GetDevicePixelRatio();this._canvasCssWidth=e,this._canvasCssHeight=t,this._canvasDeviceWidth=Math.round(this._canvasCssWidth*i),this._canvasDeviceHeight=Math.round(this._canvasCssHeight*i),this._canvasCssOffsetX=0,this._canvasCssOffsetY=0;const s=this.GetDisplayScale();this._runtime.SetViewportSize(this._canvasCssWidth/s,this._canvasCssHeight/s)}_CalculateFixedSizeCanvas(e,t){const i=this._runtime.GetDevicePixelRatio();this._canvasCssWidth=this._runtime.GetViewportWidth(),this._canvasCssHeight=this._runtime.GetViewportHeight(),this._canvasDeviceWidth=Math.round(this._canvasCssWidth*i),this._canvasDeviceHeight=Math.round(this._canvasCssHeight*i),this.IsDocumentFullscreen()?(this._canvasCssOffsetX=Math.floor((e-this._canvasCssWidth)/2),this._canvasCssOffsetY=Math.floor((t-this._canvasCssHeight)/2)):(this._canvasCssOffsetX=0,this._canvasCssOffsetY=0),this._runtime.SetViewportSize(this._runtime.GetViewportWidth(),this._runtime.GetViewportHeight())}_UpdateFullscreenScalingQuality(e){if("high"===this._wantFullscreenScalingQuality)this._drawWidth=this._canvasDeviceWidth,this._drawHeight=this._canvasDeviceHeight,this._fullscreenScalingQuality="high";else{let t,i;if("off"===this.GetCurrentFullscreenMode()?(t=this._runtime.GetViewportWidth(),i=this._runtime.GetViewportHeight()):(t=this._runtime.GetOriginalViewportWidth(),i=this._runtime.GetOriginalViewportHeight()),this._canvasDeviceWidthe&&(this._drawHeight=this._drawWidth/s)}else if("scale-outer"===e){const e=t/i,s=this._windowInnerWidth/this._windowInnerHeight;s>e?this._drawWidth=this._drawHeight*s:ss||("scale-inner"===e||"integer-scale-inner"===e)&&re.IsHTMLElementsLayer()).map(e=>e._GetHTMLLayerDOMState()),"immediate":t,"marginLeft":this._canvasCssOffsetX,"marginTop":this._canvasCssOffsetY,"styleWidth":this._canvasCssWidth,"styleHeight":this._canvasCssHeight};let s;if(s=this.IsInWorker()?await this._runtime.PostComponentMessageToDOMAsync("canvas","set-html-layer-count",i):self["c3_runtimeInterface"]["_OnSetHTMLLayerCount"](i),e=this._canvasLayers.length)return;const t=this.GetMainCanvas(),i=this._canvasLayers[e].ctx;this.#i()?i["transferFromImageBitmap"](t["transferToImageBitmap"]()):(i.globalCompositeOperation="copy",i.drawImage(t,0,0))}GetAdditionalRenderTarget(e){e.depth=this._runtime.Uses3DFeatures();const t=this._availableAdditionalRenderTargets,i=t.findIndex(t=>t.IsCompatibleWithOptions(e));let s;return-1!==i?(s=t[i],t.splice(i,1)):s=this.GetRenderer().CreateRenderTarget(e),this._usedAdditionalRenderTargets.add(s),s}ReleaseAdditionalRenderTarget(e){if(!this._usedAdditionalRenderTargets.has(e))throw new Error("render target not in use");this._usedAdditionalRenderTargets.delete(e),this._availableAdditionalRenderTargets.push(e)}GetEffectCompositorRenderTarget(){const e={};return"low"===this.GetCurrentFullscreenScalingQuality()&&(e.width=this.GetDrawWidth(),e.height=this.GetDrawHeight()),this.GetAdditionalRenderTarget(e)}ReleaseEffectCompositorRenderTarget(e){this.ReleaseAdditionalRenderTarget(e)}*activeLayersGpuProfiles(){for(const e of this._runtime.GetLayoutManager().runningLayouts())for(const t of e.GetLayers()){const e=this._layersGpuProfile.get(t);e&&(yield e)}}GetLayerTimingsBuffer(e){if(!this.GetRenderer().SupportsGPUProfiling())return null;let t=this._layersGpuProfile.get(e);return t||(t={layer:e,name:e.GetName(),timingsBuffer:C3.New(C3.Gfx.WebGLQueryResultBuffer,this._webglRenderer),curUtilisation:0,lastTotalUtilisation:0,lastSelfUtilisation:0},this._layersGpuProfile.set(e,t)),t.timingsBuffer}_Update1sFrameRange(){const e=this.GetRenderer();if(e.SupportsGPUProfiling()&&0===this._gpuTimeEndFrame){this._gpuTimeEndFrame=e.GetFrameNumber(),this._gpuCurUtilisation=NaN;for(const e of this.activeLayersGpuProfiles())e.curUtilisation=NaN}}_UpdateTick(){this._webglRenderer&&this._webglRenderer.SupportsGPUProfiling()&&this._UpdateTick_WebGL(),this._webgpuRenderer&&this._webgpuRenderer.SupportsGPUProfiling()&&this._UpdateTick_WebGPU()}_UpdateTick_WebGL(){if(isNaN(this._gpuCurUtilisation)&&(this._gpuCurUtilisation=this._gpuFrameTimingsBuffer.GetFrameRangeResultSum(this._gpuTimeStartFrame,this._gpuTimeEndFrame),!isNaN(this._gpuCurUtilisation))){if(this._runtime.IsDebug())for(const e of this.activeLayersGpuProfiles())if(e.curUtilisation=e.timingsBuffer.GetFrameRangeResultSum(this._gpuTimeStartFrame,this._gpuTimeEndFrame),isNaN(e.curUtilisation))return;if(this._gpuFrameTimingsBuffer.DeleteAllBeforeFrameNumber(this._gpuTimeEndFrame),this._gpuLastUtilisation=Math.min(this._gpuCurUtilisation,1),this._runtime.IsDebug()){const e=new Map;for(const t of this.activeLayersGpuProfiles())t.timingsBuffer.DeleteAllBeforeFrameNumber(this._gpuTimeEndFrame),t.lastTotalUtilisation=Math.min(t.curUtilisation,1),e.set(t.layer,t.lastTotalUtilisation);for(const t of this.activeLayersGpuProfiles()){const i=t.layer,s=(e.get(i)||0)-i.GetSubLayers().reduce((t,i)=>t+(e.get(i)||0),0);t.lastSelfUtilisation=C3.clamp(s,0,1)}const t=this._runtime.GetMainRunningLayout(),i=this._gpuLastUtilisation-t._GetRootLayers().reduce((t,i)=>t+(e.get(i)||0),0);self.C3Debugger.UpdateGPUProfile(C3.clamp(i,0,1),this._gpuLastUtilisation,[...this.activeLayersGpuProfiles()])}this._gpuTimeStartFrame=this._gpuTimeEndFrame,this._gpuTimeEndFrame=0}}GetGPUFrameTimingsBuffer(){return this._gpuFrameTimingsBuffer}_UpdateTick_WebGPU(){if(0===this._gpuTimeEndFrame)return;const e=[];for(let t=this._gpuTimeStartFrame;ti&&(i=h);const o=Number(h-n)/1e9;s[r]+=o}r+=Number(i-t)/1e9}if(this._gpuLastUtilisation=C3.clamp(r,0,1),this._runtime.IsDebug()){const e=i.GetLayers(),t=new Map;for(let i=0,r=Math.min(e.length,s.length-1);ie+(t.get(i)||0),0);a.set(e,s),r.push({name:e.GetName(),lastSelfUtilisation:C3.clamp(i,0,1),lastTotalUtilisation:C3.clamp(s,0,1)})}const n=this._gpuLastUtilisation-i._GetRootLayers().reduce((e,t)=>e+(a.get(t)||0),0);self.C3Debugger.UpdateGPUProfile(C3.clamp(n,0,1),this._gpuLastUtilisation,r)}}_AddWebGPUFrameTimingResultPromise(e){this._webgpuTimingPromises.set(this._webgpuRenderer.GetFrameNumber(),e)}_GetRendererThrottlePromise(){const e=this.GetRenderer();if(e.GetFrameNumber()%8!=0)return null;const t=this.#t;return this.#t=e.WaitForSubmittedWorkDone(),t}GetGPUUtilisation(){return this._gpuLastUtilisation}SnapshotCanvas(e,t,i,s,r,a){return this._snapshotFormat=e,this._snapshotQuality=t,this._snapshotArea.setWH(i,s,r,a),this._snapshotPromise||(this._snapshotPromise=new Promise(e=>{this._snapshotResolve=e})),this._snapshotPromise}_MaybeTakeSnapshot(){if(!this._snapshotFormat)return;let e=this.GetMainCanvas();const t=this._snapshotArea,i=C3.clamp(Math.floor(t.getLeft()),0,e.width),s=C3.clamp(Math.floor(t.getTop()),0,e.height);let r=t.width();r=0===r?e.width-i:C3.clamp(Math.floor(r),0,e.width-i);let a=t.height();if(a=0===a?e.height-s:C3.clamp(Math.floor(a),0,e.height-s),(0!==i||0!==s||r!==e.width||a!==e.height)&&r>0&&a>0){const t=C3.CreateCanvas(r,a);t.getContext("2d").drawImage(e,i,s,r,a,0,0,r,a),e=t}C3.CanvasToBlob(e,this._snapshotFormat,this._snapshotQuality).then(e=>{this._snapshotUrl&&URL.revokeObjectURL(this._snapshotUrl),this._snapshotUrl=URL.createObjectURL(e),this._snapshotPromise=null,this._snapshotResolve(e)}),this._snapshotFormat="",this._snapshotQuality=1}GetCanvasSnapshotUrl(){return this._snapshotUrl}SetIsPastingToDrawingCanvas(e){e?this._isPastingToDrawingCanvas++:this._isPastingToDrawingCanvas--}IsPastingToDrawingCanvas(){return this._isPastingToDrawingCanvas>0}InitLoadingScreen(e){const t=this.GetRenderer();if(2===e)this._percentText=C3.New(C3.Gfx.RendererText,this.GetRenderer()),this._percentText.SetFontName("Arial"),this._percentText.SetFontSize(16),this._percentText.SetHorizontalAlignment("center"),this._percentText.SetVerticalAlignment("center"),this._percentText.SetSize(300,200);else if(0===e){const e=this._runtime.GetLoadingLogoAsset();e&&e.LoadStaticTexture(t).catch(e=>console.warn("[C3 runtime] Failed to create texture for loading logo: ",e))}else 4===e&&(this._LoadSvgSplashImage("splash-images/splash-logo.svg").then(e=>{"done"===this._splashState?t.DeleteTexture(e):this._splashTextures.logo=e}).catch(e=>console.warn("Failed to load splash image: ",e)),this._LoadBitmapSplashImage("splash-images/splash-poweredby-512.png").then(e=>{"done"===this._splashState?t.DeleteTexture(e):this._splashTextures.powered=e}).catch(e=>console.warn("Failed to load splash image: ",e)),this._LoadBitmapSplashImage("splash-images/splash-website-512.png").then(e=>{"done"===this._splashState?t.DeleteTexture(e):this._splashTextures.website=e}).catch(e=>console.warn("Failed to load splash image: ",e)))}async _LoadSvgSplashImage(e){e=new URL(e,this._runtime.GetRuntimeBaseURL()).toString();const t=await C3.FetchBlob(e),i=await this._runtime.RasterSvgImage(t,2048,2048);return await this.GetRenderer().CreateStaticTextureAsync(i,{mipMapQuality:"high"})}async _LoadBitmapSplashImage(e){e=new URL(e,this._runtime.GetRuntimeBaseURL()).toString();const t=await C3.FetchBlob(e);return await this.GetRenderer().CreateStaticTextureAsync(t,{mipMapQuality:"high"})}HideCordovaSplashScreen(){this._runtime.PostComponentMessageToDOM("runtime","hide-cordova-splash")}StartLoadingScreen(){this._loaderStartTime=Date.now(),this._runtime.Dispatcher().addEventListener("loadingprogress",this._loadingprogress_handler),this._rafId=requestAnimationFrame(()=>this._DrawLoadingScreen());3!==this._runtime.GetLoaderStyle()&&this.HideCordovaSplashScreen()}async EndLoadingScreen(){const e=this.GetRenderer();this._loadingProgress=1;const t=this._runtime.GetLoaderStyle();4===t&&await this._splashDonePromise,this._splashDoneResolve=null,this._splashDonePromise=null,-1!==this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=-1),this._runtime.Dispatcher().removeEventListener("loadingprogress",this._loadingprogress_handler),this._loadingprogress_handler=null,this._percentText&&(this._percentText.Release(),this._percentText=null),this._runtime.ReleaseLoadingLogoAsset(),e.Start(),this._splashTextures.logo&&(e.DeleteTexture(this._splashTextures.logo),this._splashTextures.logo=null),this._splashTextures.powered&&(e.DeleteTexture(this._splashTextures.powered),this._splashTextures.powered=null),this._splashTextures.website&&(e.DeleteTexture(this._splashTextures.website),this._splashTextures.website=null),e.ClearRgba(0,0,0,0),e.Finish(),this._splashState="done",this._gpuTimeStartFrame=e.GetFrameNumber(),3===t&&this.HideCordovaSplashScreen()}_DrawLoadingScreen(){if(-1===this._rafId)return;const e=this.GetRenderer();e.Start(),this._rafId=-1;const t=this._runtime.GetAssetManager().HasHadErrorLoading(),i=this._runtime.GetLoaderStyle();if(3!==i&&(this.SetCssTransform(e),e.ClearRgba(0,0,0,0),e.ResetColor(),e.SetTextureFillMode(),e.SetTexture(null)),0===i)this._DrawProgressBarAndLogoLoadingScreen(t);else if(1===i)this._DrawProgressBarLoadingScreen(t,120,0);else if(2===i)this._DrawPercentTextLoadingScreen(t);else if(3===i)C3.noop();else{if(4!==i)throw new Error("invalid loader style");this._DrawSplashLoadingScreen(t)}e.Finish(),this._rafId=requestAnimationFrame(()=>this._DrawLoadingScreen())}_DrawPercentTextLoadingScreen(e){e?this._percentText.SetColorRgb(1,0,0):this._percentText.SetColorRgb(.6,.6,.6),this._percentText.SetText(Math.round(100*this._loadingProgress)+"%");const t=this._canvasCssWidth/2,i=this._canvasCssHeight/2;tempQuad.setRect(t-150,i-100,t+150,i+100);const s=this.GetRenderer();s.SetTexture(this._percentText.GetTexture()),s.Quad3(tempQuad,this._percentText.GetTexRect())}_DrawProgressBarLoadingScreen(e,t,i){const s=this.GetRenderer();s.SetColorFillMode(),e?s.SetColorRgba(1,0,0,1):s.SetColorRgba(.118,.565,1,1);const r=this._canvasCssWidth/2,a=this._canvasCssHeight/2,n=t/2;tempRect.setWH(r-n,a-4+i,Math.floor(t*this._loadingProgress),8),s.Rect(tempRect),tempRect.setWH(r-n,a-4+i,t,8),tempRect.offset(-.5,-.5),tempRect.inflate(.5,.5),s.SetColorRgba(0,0,0,1),s.LineRect2(tempRect),tempRect.inflate(1,1),s.SetColorRgba(1,1,1,1),s.LineRect2(tempRect)}_DrawProgressBarAndLogoLoadingScreen(e){const t=this.GetRenderer(),i=this._runtime.GetLoadingLogoAsset();if(!i)return void this._DrawProgressBarLoadingScreen(e,120,0);const s=i.GetTexture();if(!s)return void this._DrawProgressBarLoadingScreen(e,120,0);const r=s.GetWidth(),a=s.GetHeight(),n=this._canvasCssWidth/2,h=this._canvasCssHeight/2,o=r/2,l=a/2;tempQuad.setRect(n-o,h-l,n+o,h+l),t.SetTexture(s),t.Quad(tempQuad),this._DrawProgressBarLoadingScreen(e,r,l+16)}_DrawSplashLoadingScreen(e){const t=this.GetRenderer(),i=this._splashTextures.logo,s=this._splashTextures.powered,r=this._splashTextures.website,a=Date.now();0===this._splashFrameNumber&&(this._loaderStartTime=a);const n=this._runtime.IsPreview()||this._runtime.IsFBInstantAvailable()&&!this._runtime.IsCordova(),h=n?0:200,o=n?0:3e3;let l=1;"fade-in"===this._splashState?l=Math.min((a-this._loaderStartTime)/300,1):"fade-out"===this._splashState&&(l=Math.max(1-(a-this._splashFadeOutStartTime)/300,0)),t.SetColorFillMode(),t.SetColorRgba(.231*l,.251*l,.271*l,l),tempRect.set(0,0,this._canvasCssWidth,this._canvasCssHeight),t.Rect(tempRect);const c=Math.ceil(this._canvasCssWidth),d=Math.ceil(this._canvasCssHeight);let _,u;this._canvasCssHeight>256?(t.SetColorRgba(.302*l,.334*l,.365*l,l),_=c,u=Math.max(.005*d,2),tempRect.setWH(0,.8*d-u/2,_,u),t.Rect(tempRect),e?t.SetColorRgba(l,0,0,l):t.SetColorRgba(.161*l,.953*l,.816*l,l),_=c*this._loadingProgress,tempRect.setWH(.5*c-_/2,.8*d-u/2,_,u),t.Rect(tempRect),t.SetColorRgba(l,l,l,l),t.SetTextureFillMode(),s&&(_=1.5*C3.clamp(.22*d,105,.6*c),u=_/8,tempRect.setWH(.5*c-_/2,.2*d-u/2,_,u),t.SetTexture(s),t.Rect(tempRect)),i&&(_=Math.min(.395*d,.95*c),u=_,tempRect.setWH(.5*c-_/2,.485*d-u/2,_,u),t.SetTexture(i),t.Rect(tempRect)),r&&(_=1.5*C3.clamp(.22*d,105,.6*c),u=_/8,tempRect.setWH(.5*c-_/2,.868*d-u/2,_,u),t.SetTexture(r),t.Rect(tempRect))):(t.SetColorRgba(.302*l,.334*l,.365*l,l),_=c,u=Math.max(.005*d,2),tempRect.setWH(0,.85*d-u/2,_,u),t.Rect(tempRect),e?t.SetColorRgba(l,0,0,l):t.SetColorRgba(.161*l,.953*l,.816*l,l),_=c*this._loadingProgress,tempRect.setWH(.5*c-_/2,.85*d-u/2,_,u),t.Rect(tempRect),t.SetColorRgba(l,l,l,l),t.SetTextureFillMode(),i&&(_=.55*d,u=_,tempRect.setWH(.5*c-_/2,.45*d-u/2,_,u),t.SetTexture(i),t.Rect(tempRect))),this._splashFrameNumber++,"fade-in"===this._splashState&&a-this._loaderStartTime>=300&&this._splashFrameNumber>=2&&(this._splashState="wait",this._splashFadeInFinishTime=a),"wait"===this._splashState&&a-this._splashFadeInFinishTime>=o&&this._loadingProgress>=1&&(this._splashState="fade-out",this._splashFadeOutStartTime=a),("fade-out"===this._splashState&&a-this._splashFadeOutStartTime>=300+h||n&&this._loadingProgress>=1&&a-this._loaderStartTime<500)&&this._splashDoneResolve()}}; } // runtime.js { const C3=globalThis.C3,C3X=globalThis.C3X,C3Debugger=globalThis.C3Debugger,assert=globalThis.assert,ISDKBehaviorInstanceBase=globalThis.ISDKBehaviorInstanceBase,DEFAULT_RUNTIME_OPTS={"messagePort":null,"runtimeBaseUrl":"","headless":!1,"hasDom":!0,"isInWorker":!1,"useAudio":!0,"exportType":""};let ife=!0;function CreateRuntime(e){return new C3.Runtime(e)}function InitRuntime(e,t){return e.Init(t)}C3.Runtime=class extends C3.DefendedBase{#e="trilinear";#t=new WeakMap;#s={"pretick":C3.New(C3.Event,"pretick",!1),"tick":C3.New(C3.Event,"tick",!1),"tick2":C3.New(C3.Event,"tick2",!1),"instancecreate":C3.New(C3.Event,"instancecreate",!1),"instancedestroy":C3.New(C3.Event,"instancedestroy",!1),"beforelayoutchange":C3.New(C3.Event,"beforelayoutchange",!1),"layoutchange":C3.New(C3.Event,"layoutchange",!1),"beforerender":C3.New(C3.Event,"beforerender",!1),"beforerender2":C3.New(C3.Event,"beforerender2",!1),"afterrender":C3.New(C3.Event,"afterrender",!1)};#i;#n;#a;#r;#o;#h;#d;#l;#c;#g;#u;#m;#_=new WeakMap;#p=[];#f="vsync";#S=-1;#C=-1;#v=-1;#I=30;#T=-1e3;#M=!1;#b=null;#y=null;#G="";#w=null;#D=null;constructor(e){e=Object.assign({},DEFAULT_RUNTIME_OPTS,e),super(),this._messagePort=e["messagePort"],this._runtimeBaseUrl=e["runtimeBaseUrl"],this._previewUrl=e["previewUrl"],this._isHeadless=!!e["headless"],this._hasDom=!!e["hasDom"],this._isInWorker=!!e["isInWorker"],ife=e["ife"],this._useAudio=!!e["useAudio"],this._exportType=e["exportType"],this._isiOSCordova=!!e["isiOSCordova"],this._isiOSWebView=!!e["isiOSWebView"],this._isWindowsWebView2=!!e["isWindowsWebView2"],this._isAnyWebView2Wrapper=!!e["isAnyWebView2Wrapper"],this._isFBInstantAvailable=!!e["isFBInstantAvailable"],this._isDebug=!("preview"!==this._exportType||!e["isDebug"]),this._breakpointsEnabled=this._isDebug,this._isDebugging=this._isDebug,this._debuggingDisabled=0,this._additionalLoadPromises=[],this._additionalCreatePromises=[],this._isUsingCreatePromises=!1,this._projectName="",this._projectVersion="",this._projectUniqueId="",this._appId="",this._exportTimestamp=0,this._originalViewportWidth=0,this._originalViewportHeight=0,this._devicePixelRatio=self.devicePixelRatio,this._parallaxXorigin=0,this._parallaxYorigin=0,this._viewportWidth=0,this._viewportHeight=0,this._loaderStyle=0,this._usesLoaderLayout=!1,this._isLoading=!0,this._usesAnyBackgroundBlending=!1,this._usesAnyCrossSampling=!1,this._usesAnyDepthSampling=!1,this._loadingLogoAsset=null,this.#n=C3.New(C3.AssetManager,this,e),this.#a=C3.New(C3.LayoutManager,this),this.#r=C3.New(C3.EventSheetManager,this),this.#o=C3.New(C3.AddonManager,this,e["wrapperComponentIds"]),this.#h=C3.New(C3.CollisionEngine,this),this.#d=C3.New(C3.TimelineManager,this),this.#l=C3.New(C3.TransitionManager,this),this.#c=C3.New(C3.TemplateManager,this),this.#g=C3.New(C3.FlowchartManager,this),C3.Model3dManager&&(this.#u=C3.New(C3.Model3dManager,this)),this._textIconManager=C3.New(C3.TextIconManager,{getIconSetMeta:e=>this._GetTextIconSetMeta(e),getIconSetContent:e=>this._GetTextIconSetContent(e)}),this._iconChangeHandlers=new Map,this._allObjectClasses=[],this._objectClassesByName=new Map,this._objectClassesBySid=new Map,this._familyCount=0,this._allContainers=[],this._allEffectLists=new Set,this._currentLayoutStack=[],this._instancesPendingCreate=[],this._instancesPendingDestroy=new Map,this._hasPendingInstances=!1,this._isFlushingPendingInstances=!1,this._objectCount=0,this._nextUid=0,this._instancesByUid=new Map,this._instancesPendingRelease=new Set,this._instancesPendingReleaseAffectedObjectClasses=new Set,this._objectReferenceTable=[],this._jsPropNameTable=[],this._uses3dFeatures=!1,this._isPixelRoundingEnabled=!1,this._needRender=!0,this._pauseOnBlur=!1,this._isPausedOnBlur=!1,this._exportToVideo=null,this._tickCallbacks={normal:e=>{this.#S=-1,this.#C=-1,this.#v=-1,this.Tick(e)},tickOnly:e=>{this.#C=-1,this.Tick(e,!1,"skip-render")},renderOnly:()=>{this.#S=-1,this.Render()}},this._tickCount=0,this._tickCountNoSave=0,this._hasStarted=!1,this._isInTick=!1,this._hasStartedTicking=!1,this._isLayoutFirstTick=!0,this._isAutoSuspendEnabled=!0,this._isPageVisibilitySuspended=!1,this._suspendCount=0,this._scheduleTriggersThrottle=new C3.PromiseThrottle(1),this._randomNumberCallback=()=>Math.random(),this._startTime=0,this._lastTickTime=0,this._dtRaw=0,this._dt1=0,this._dt=0,this._timeScale=1,this._maxDt=1/30,this._minDt=0,this._gameTime=C3.New(C3.KahanSum),this._gameTimeRaw=C3.New(C3.KahanSum),this._wallTime=C3.New(C3.KahanSum),this._instanceTimes=new Map,this._fpsFrameCount=-1,this._fpsLastTime=0,this._fps=0,this._tpsTickCount=-1,this._tps=0,this._mainThreadTimeCounter=0,this._mainThreadTime=0,this._dispatcher=C3.New(C3.Event.Dispatcher),this._domEventHandlers=new Map,this._pendingResponsePromises=new Map,this._nextDomResponseId=0,this._didRequestDeviceOrientationEvent=!1,this._didRequestDeviceMotionEvent=!1,this._isReadyToHandleEvents=!1,this._waitingToHandleEvents=[],this.#s["instancecreate"].instance=null,this.#s["instancedestroy"].instance=null,this._userScriptDispatcher=C3.New(C3.Event.Dispatcher),this._userScriptEventObjects=null;const t=(e,t)=>C3.BehaviorInstance.SortByTickSequence(this,e,t);this._behInstsToTick=C3.New(C3.RedBlackSet,t),this._behInstsToPostTick=C3.New(C3.RedBlackSet,t),this._behInstsToTick2=C3.New(C3.RedBlackSet,t),this.#m=C3.New(C3.JobSchedulerRuntime,this,e["jobScheduler"]),e["canvas"]&&(this.#i=C3.New(C3.CanvasManager,this)),this._messagePort.onmessage=e=>this["_OnMessageFromDOM"](e.data),this.AddDOMComponentMessageHandler("runtime","visibilitychange",e=>this._OnVisibilityChange(e)),this.AddDOMComponentMessageHandler("runtime","wrapper-extension-message",e=>this._OnWrapperExtensionMessage(e)),this.AddDOMComponentMessageHandler("runtime","get-remote-preview-status-info",()=>this._GetRemotePreviewStatusInfo()),this.AddDOMComponentMessageHandler("runtime","js-invoke-function",e=>this._InvokeFunctionFromJS(e)),this.AddDOMComponentMessageHandler("runtime","go-to-last-error-script",self["goToLastErrorScript"]),this.AddDOMComponentMessageHandler("runtime","offline-audio-render-completed",e=>this._OnOfflineAudioRenderCompleted(e)),this.AddDOMComponentMessageHandler("runtime","advert-message",e=>this._OnAdvertMessage(e)),this._dispatcher.addEventListener("window-blur",e=>this._OnWindowBlur(e)),this._dispatcher.addEventListener("window-focus",()=>this._OnWindowFocus()),this.#d.AddRuntimeListeners(),this.#c.AddRuntimeListeners(),this._iRuntime=null,this._constructVersionCode=0,this._commonScriptInterfaces={keyboard:null,mouse:null,touch:null,timelineController:null}}Release(){C3.clearArray(this._allObjectClasses),this._objectClassesByName.clear(),this._objectClassesBySid.clear(),this.#a.Release(),this.#a=null,this.#r.Release(),this.#r=null,this.#o.Release(),this.#o=null,this.#n.Release(),this.#n=null,this.#h.Release(),this.#h=null,this.#d.Release(),this.#d=null,this.#l.Release(),this.#l=null,this.#c.Release(),this.#c=null,this.#g.Release(),this.#g=null,this._textIconManager.Release(),this._textIconManager=null,this.#u&&(this.#u.Release(),this.#u=null),this.#i&&(this.#i.Release(),this.#i=null),this._dispatcher.Release(),this._dispatcher=null,this._tickEvent=null}"_OnMessageFromDOM"(e){const t=e["type"];if("event"===t)this._OnEventFromDOM(e);else{if("result"!==t)throw new Error(`unknown message '${t}'`);this._OnResultFromDOM(e)}}_OnEventFromDOM(e){if(!this._isReadyToHandleEvents)return void this._waitingToHandleEvents.push(e);const t=e["component"],s=e["handler"],i=e["data"],n=e["dispatchOpts"],a=!(!n||!n["dispatchRuntimeEvent"]),r=!(!n||!n["dispatchUserScriptEvent"]),o=e["responseId"];if("runtime"===t){if(a){const e=new C3.Event(s);e.data=i,this._dispatcher.dispatchEventAndWaitAsyncSequential(e)}if(r){const e=new C3.Event(s,!0);if(i)for(const[t,s]of Object.entries(i))e[t]=s;this.DispatchUserScriptEvent(e)}}const h=this._domEventHandlers.get(t);if(!h)return void(a||r||console.warn(`[Runtime] No DOM event handlers for component '${t}'`));const d=h.get(s);if(!d)return void(a||r||console.warn(`[Runtime] No DOM handler '${s}' for component '${t}'`));let l=null;try{l=d(i)}catch(e){return console.error(`Exception in '${t}' handler '${s}':`,e),void(null!==o&&this._PostResultToDOM(o,!1,""+e))}null!==o&&(l&&l.then?l.then(e=>this._PostResultToDOM(o,!0,e)).catch(e=>{console.error(`Rejection from '${t}' handler '${s}':`,e),this._PostResultToDOM(o,!1,""+e)}):this._PostResultToDOM(o,!0,l))}_PostResultToDOM(e,t,s){this._messagePort.postMessage({"type":"result","responseId":e,"isOk":t,"result":s})}_OnResultFromDOM(e){const t=e["responseId"],s=e["isOk"],i=e["result"],n=this._pendingResponsePromises.get(t);s?n.resolve(i):n.reject(i),this._pendingResponsePromises.delete(t)}AddDOMComponentMessageHandler(e,t,s){let i=this._domEventHandlers.get(e);if(i||(i=new Map,this._domEventHandlers.set(e,i)),i.has(t))throw new Error(`[Runtime] Component '${e}' already has handler '${t}'`);i.set(t,s)}PostComponentMessageToDOM(e,t,s,i){this._messagePort.postMessage({"type":"event","component":e,"handler":t,"data":s,"responseId":null},i)}PostComponentMessageToDOMAsync(e,t,s,i){const n=this._nextDomResponseId++,a=new Promise((e,t)=>{this._pendingResponsePromises.set(n,{resolve:e,reject:t})});return this._messagePort.postMessage({"type":"event","component":e,"handler":t,"data":s,"responseId":n},i),a}SendWrapperExtensionMessage(e,t,s,i=-1){this.PostComponentMessageToDOM("runtime","send-wrapper-extension-message",{"componentId":e,"messageId":t,"params":s,"asyncId":i})}SendRawWrapperExtensionMessage(e){this.PostComponentMessageToDOM("runtime","send-raw-wrapper-extension-message",e)}SendWrapperExtensionMessageAsync(e,t,s){const i=this._nextDomResponseId++,n=new Promise((e,t)=>{this._pendingResponsePromises.set(i,{resolve:e,reject:t})});return this.SendWrapperExtensionMessage(e,t,s,i),n}_OnWrapperExtensionMessage(e){if(-1!==e["asyncId"]){const t=e["asyncId"];this._pendingResponsePromises.get(t).resolve(e["params"]),this._pendingResponsePromises.delete(t)}else this._OnEventFromDOM({"component":"wrapper-extension:"+e["componentId"],"handler":e["messageId"],"data":e["params"],"responseId":null})}AddWrapperExtensionMessageHandler(e,t,s){this.AddDOMComponentMessageHandler("wrapper-extension:"+e,t,s)}HasWrapperComponentId(e){return this.#o.HasWrapperComponentId(e)}PostToDebugger(e){if(!this.IsDebug())throw new Error("not in debug mode");this.PostComponentMessageToDOM("runtime","post-to-debugger",e)}async Init(e){C3.CommonACES_SetRuntime(this),this.IsDebug()?await C3Debugger.Init(this):self.C3Debugger&&self.C3Debugger.InitPreview(this);const t=await this.#n.FetchJson("data.json");if(await this._LoadDataJson(t),await this._InitialiseCanvas(e),this.IsPreview()||console.info("%cMade with Construct, the game and animation creation tool. Visit: https://www.construct.net","font-weight: bold"),this.GetWebGLRenderer()){const e=this.GetWebGLRenderer();console.info(`[C3 runtime] Hosted in ${this.IsInWorker()?"worker":"DOM"}, rendering with WebGL ${e.GetWebGLVersionNumber()} [${e.GetUnmaskedRenderer()}]`)}else this.GetWebGPURenderer()&&console.info(`[C3 runtime] Hosted in ${this.IsInWorker()?"worker":"DOM"}, rendering with WebGPU [${this.GetWebGPURenderer().GetAdapterInfoString()}]`);this.GetRenderer().HasMajorPerformanceCaveat()&&console.warn("[C3 runtime] The renderer indicates a major performance caveat. Software rendering may be in use. This can result in significantly degraded performance."),this._isReadyToHandleEvents=!0;for(const e of this._waitingToHandleEvents)this._OnEventFromDOM(e);C3.clearArray(this._waitingToHandleEvents),this.#i&&this.#i.StartLoadingScreen();for(const t of e["runOnStartupFunctions"])this._additionalLoadPromises.push(this._RunOnStartupFunction(t));if(await Promise.all([this.#n.WaitForAllToLoad(!1),...this._additionalLoadPromises]),C3.clearArray(this._additionalLoadPromises),!this.#n.HasHadErrorLoading())return this.#i&&await this.#i.EndLoadingScreen(),await this._dispatcher.dispatchEventAndWaitAsync(new C3.Event("beforeruntimestart")),await this.Start(),this._messagePort.postMessage({"type":"runtime-ready"}),this;this.#i&&this.#i.HideCordovaSplashScreen()}async _RunOnStartupFunction(e){try{await e(this._iRuntime)}catch(e){console.error("[C3 runtime] Error in runOnStartup function: ",e)}}async _LoadDataJson(e){const t=e["project"];this._projectName=t[0],this._projectVersion=t[16],this._projectUniqueId=t[31],this._appId=t[38],this._exportTimestamp=t[36];const s=t[39]||"loading-logo.png";this._isPixelRoundingEnabled=!!t[9],this._originalViewportWidth=this._viewportWidth=t[10],this._originalViewportHeight=this._viewportHeight=t[11],this.#h._InitCollisionCellSize(this._originalViewportWidth,this._originalViewportHeight),this._parallaxXorigin=this._originalViewportWidth/2,this._parallaxYorigin=this._originalViewportHeight/2;const[i,n]=t[37];this.#f=i,this.#I=n,this._uses3dFeatures=!!t[40],this.#e=t[14],this._usesAnyBackgroundBlending=t[15],this._usesAnyCrossSampling=t[42],this._usesAnyDepthSampling=t[17],this._usesLoaderLayout=!!t[18],this._loaderStyle=t[19],this._nextUid=t[21],this._pauseOnBlur=t[22],this._constructVersionCode=t[51];const a=this.#n;a._SetAudioFiles(t[7],t[25]),a._SetMediaSubfolder(t[8]),a._SetFontsSubfolder(t[32]),a._SetIconsSubfolder(t[28]),a._SetWebFonts(t[29]),a._SetExportedFileList(t[45]),0===this._loaderStyle&&s&&(this._loadingLogoAsset=a.LoadImage({url:s})),this.#i&&(this.#i.SetFullscreenMode(C3.CanvasManager._FullscreenModeNumberToString(t[12])),this.#i.SetFullscreenScalingQuality(t[23]?"high":"low"),this.#i.SetMipmapsEnabled(0!==t[24]),this.#i._SetGPUPowerPreference(t[34]),this.#i._SetTextureAnisotropy(t[41]),this.#i._SetWebGPUEnabled(t[13]),this.#i._SetZAxisScale(t[30]),this.#i._SetZDistances(t[46],t[47]),this.#i._SetInitFieldOfView(t[26]),this.#i._SetMinimumRendererCapabilities(t[48]),this.#i._SetMultitexturingMode(t[50]));const r=t[43];r&&await this._LoadExportToVideoData(r),this._InitScriptInterfaces(),this.#o.CreateSystemPlugin(),this._objectReferenceTable=self.C3_GetObjectRefTable();const o=t[2];for(const e of o[1])this.#o.CreateBehavior(e);for(const e of o[0])this.#o.CreatePlugin(e);if(this._objectReferenceTable=self.C3_GetObjectRefTable(),this._LoadJsPropNameTable(),this.#o._InitAddonScriptInterfaces(),this.#u){for(const e of t[52])this.#u.Create(e);this.#u.HasModels3d()||(this.#u.Release(),this.#u=null)}for(const e of t[3]){const t=C3.ObjectClass.Create(this,this._allObjectClasses.length,e);this._allObjectClasses.push(t),this._objectClassesByName.set(t.GetName().toLowerCase(),t),this._objectClassesBySid.set(t.GetSID(),t)}for(const e of t[4]){this._allObjectClasses[e[0]]._LoadFamily(e)}for(const e of t[27]){const t=e.map(e=>this._allObjectClasses[e]);this._allContainers.push(C3.New(C3.Container,this,t))}this._InitObjectsScriptInterface();for(const e of this._allObjectClasses)e._OnAfterCreate();for(const e of t[5])this.#a.Create(e);const h=t[1];if(h){const e=this.#a.GetLayoutByName(h);e&&this.#a.SetFirstLayout(e)}for(const e of t[35])this.#l.Create(e);for(const e of t[33])this.#d.Create(e);for(const e of t[44])this.#c.Create(e);this.#c.HasTemplates()||(this.#c.Release(),this.#c=null);for(const e of t[49])this.#g.Create(e);this.#g.HasFlowcharts()||(this.#g.Release(),this.#g=null);for(const e of t[6])this.#r.Create(e);this.#r._PostInit(),this._InitGlobalVariableScriptInterface(),C3.clearArray(this._objectReferenceTable),this.FlushPendingInstances();let d="any";const l=t[20];1===l?d="portrait":2===l&&(d="landscape"),this.PostComponentMessageToDOM("runtime","set-target-orientation",{"targetOrientation":d})}async _LoadExportToVideoData(e){const t=e["format"];"image-sequence"===t?this._exportToVideo=new self.C3ExportToImageSequence(this,e):"image-sequence-gif"===t?this._exportToVideo=new self.C3ExportToGIF(this,e):"webm"===t?this._exportToVideo=new self.C3ExportToWebMVideo(this,e):"mp4"===t&&(this._exportToVideo=new self.C3ExportToMP4Video(this,e)),this.#f="unlimited-frame",this.#i.SetFullscreenMode("off"),this._devicePixelRatio=1,self.devicePixelRatio=1,await this.PostComponentMessageToDOMAsync("runtime","set-exporting-to-video",{"message":this._exportToVideo.GetExportingMessageForPercent(0),"duration":this._exportToVideo.GetDuration()})}GetLoaderStyle(){return this._loaderStyle}IsExportToVideo(){return null!==this._exportToVideo}GetExportVideoDuration(){return this._exportToVideo.GetDuration()}GetExportVideoFramerate(){return this._exportToVideo.GetFramerate()}_InitExportToVideo(){return this._exportToVideo.Init({width:this.#i.GetDeviceWidth(),height:this.#i.GetDeviceHeight()})}_ExportToVideoAddFrame(){const e=this._tickCount/this.GetExportVideoFramerate();return this._exportToVideo.AddFrame(this.#i.GetMainCanvas(),e)}_ExportToVideoAddKeyframe(){this._exportToVideo&&this._exportToVideo.AddKeyframe()}_OnOfflineAudioRenderCompleted(e){this._exportToVideo.OnOfflineAudioRenderCompleted(e)}_OnAdvertMessage(e){const t=C3.New(C3.Event,"advertevent");t.advertType=e["advertType"],t.advertAction=e["advertAction"],t.advertData=e["advertData"],this._dispatcher.dispatchEvent(t)}_ExportToVideoFinish(){return this._exportToVideo.Finish()}IsFBInstantAvailable(){return this._isFBInstantAvailable}IsLoading(){return this._isLoading}AddLoadPromise(e){this._additionalLoadPromises.push(e)}SetUsingCreatePromises(e){this._isUsingCreatePromises=!!e}AddCreatePromise(e){this._isUsingCreatePromises&&this._additionalCreatePromises.push(e)}GetCreatePromises(){return this._additionalCreatePromises}_GetNextFamilyIndex(){return this._familyCount++}GetFamilyCount(){return this._familyCount}_AddEffectList(e){this._allEffectLists.add(e)}_RemoveEffectList(e){this._allEffectLists.delete(e)}_GetAllEffectLists(){return this._allEffectLists}async _InitialiseCanvas(e){this.#i&&(await this.#i.CreateCanvas(e),this.#i.InitLoadingScreen(this._loaderStyle))}async Start(){this._hasStarted=!0,this._startTime=Date.now();let e=null;const t=new Promise(t=>e=t);if(this._usesLoaderLayout){for(const e of this._allObjectClasses)e.IsFamily()||e.IsOnLoaderLayout()||!e.IsWorldType()||e.OnCreate();(async()=>{await this.#n.WaitForAllToLoad(!0),await t,this._isLoading=!1,this._OnLoadFinished()})()}else this._isLoading=!1;this.#n.SetInitialLoadFinished(),this.IsDebug()&&C3Debugger.RuntimeInit(ife);for(const e of this.#a.GetAllLayouts())e._CreateGlobalNonWorlds();this.IsExportToVideo()&&await this._InitExportToVideo();const s=this.#a.GetFirstLayout();await s._Load(null,this.GetRenderer()),await s._StartRunning(!0),this._fpsLastTime=performance.now(),e(),this._usesLoaderLayout||this._OnLoadFinished();(await this.PostComponentMessageToDOMAsync("runtime","before-start-ticking"))["isSuspended"]&&!this.IsExportToVideo()?(this._suspendCount++,this._isPageVisibilitySuspended=!0):this.Tick()}_OnLoadFinished(){this.Trigger(C3.Plugins.System.Cnds.OnLoadFinished,null,null),this.PostComponentMessageToDOM("runtime","register-sw")}GetObjectReference(e){e=Math.floor(e);const t=this._objectReferenceTable;if(e<0||e>=t.length)throw new Error("invalid object reference");return t[e]}_LoadJsPropNameTable(){for(const e of self.C3_JsPropNameTable){const t=C3.first(Object.keys(e));this._jsPropNameTable.push(t)}}GetJsPropName(e){e=Math.floor(e);const t=this._jsPropNameTable;if(e<0||e>=t.length)throw new Error("invalid prop reference");return t[e]}HasDOM(){return this._hasDom}IsHeadless(){return this._isHeadless}IsInWorker(){return this._isInWorker}GetRuntimeBaseURL(){return this._runtimeBaseUrl}GetPreviewURL(){return this._previewUrl}GetEventSheetManager(){return this.#r}GetEventStack(){return this.#r.GetEventStack()}GetCurrentEventStackFrame(){return this.#r.GetCurrentEventStackFrame()}GetCurrentEvent(){return this.#r.GetCurrentEvent()}GetCurrentCondition(){return this.#r.GetCurrentCondition()}IsCurrentConditionFirst(){return 0===this.GetCurrentEventStackFrame().GetConditionIndex()}GetCurrentAction(){return this.#r.GetCurrentAction()}GetAddonManager(){return this.#o}GetSystemPlugin(){return this.#o.GetSystemPlugin()}GetObjectClassByIndex(e){if((e=Math.floor(e))<0||e>=this._allObjectClasses.length)throw new RangeError("invalid index");return this._allObjectClasses[e]}GetObjectClassByName(e){return this._objectClassesByName.get(e.toLowerCase())||null}GetObjectClassBySID(e){return this._objectClassesBySid.get(e)||null}GetSingleGlobalObjectClassByCtor(e){const t=C3.AddonManager.GetPluginByConstructorFunction(e);return t?t.GetSingleGlobalObjectClass():null}GetAllObjectClasses(){return this._allObjectClasses}*allInstances(){for(const e of this._allObjectClasses)e.IsFamily()||(yield*e.instances())}Dispatcher(){return this._dispatcher}UserScriptDispatcher(){return this._userScriptDispatcher}DispatchUserScriptEvent(e){e.runtime=this.GetIRuntime();const t=this.IsDebug()&&!this.#r.IsInEventEngine();t&&C3Debugger.StartMeasuringScriptTime(),this._userScriptDispatcher.dispatchEvent(e),t&&C3Debugger.AddScriptTime()}DispatchUserScriptEventAsyncWait(e){return e.runtime=this.GetIRuntime(),this._userScriptDispatcher.dispatchEventAndWaitAsync(e)}GetOriginalViewportWidth(){return this._originalViewportWidth}GetOriginalViewportHeight(){return this._originalViewportHeight}SetOriginalViewportSize(e,t){if(this._originalViewportWidth===e&&this._originalViewportHeight===t)return;this._originalViewportWidth=e,this._originalViewportHeight=t;const s=this.GetLayoutManager();s.SetAllLayerProjectionChanged(),s.SetAllLayerMVChanged()}GetViewportWidth(){return this._viewportWidth}GetViewportHeight(){return this._viewportHeight}SetViewportSize(e,t){if(this._viewportWidth===e&&this._viewportHeight===t)return;this._viewportWidth=e,this._viewportHeight=t;const s=this.GetLayoutManager();s.SetAllLayerProjectionChanged(),s.SetAllLayerMVChanged()}_SetDevicePixelRatio(e){this.IsExportToVideo()||(this._devicePixelRatio=e)}GetDevicePixelRatio(){return this._devicePixelRatio}GetParallaxXOrigin(){return this._parallaxXorigin}GetParallaxYOrigin(){return this._parallaxYorigin}GetCanvasManager(){return this.#i}GetDrawWidth(){return this.#i?this.#i.GetDrawWidth():this._viewportWidth}GetDrawHeight(){return this.#i?this.#i.GetDrawHeight():this._viewportHeight}GetRenderScale(){return this.#i?this.#i.GetRenderScale():1}GetDisplayScale(){return this.#i?this.#i.GetDisplayScale():1}GetEffectLayerScaleParam(){return this.#i?this.#i.GetEffectLayerScaleParam():1}GetEffectDevicePixelRatioParam(){return this.#i?this.#i.GetEffectDevicePixelRatioParam():1}GetCanvasClientX(){return this.#i?this.#i.GetCanvasClientX():0}GetCanvasClientY(){return this.#i?this.#i.GetCanvasClientY():0}GetCanvasCssWidth(){return this.#i?this.#i.GetCssWidth():0}GetCanvasCssHeight(){return this.#i?this.#i.GetCssHeight():0}GetFullscreenMode(){return this.#i?this.#i.GetFullscreenMode():"off"}GetAdditionalRenderTarget(e){return this.#i?this.#i.GetAdditionalRenderTarget(e):null}ReleaseAdditionalRenderTarget(e){this.#i&&this.#i.ReleaseAdditionalRenderTarget(e)}UsesAnyBackgroundBlending(){return this._usesAnyBackgroundBlending}UsesAnyCrossSampling(){return this._usesAnyCrossSampling}UsesAnyDepthSampling(){return this._usesAnyDepthSampling}GetGPUUtilisation(){return this.#i?this.#i.GetGPUUtilisation():NaN}GetFramerateMode(){return this.#f}_SetFramerateMode(e){this.#f!==e&&(this.#f=e,-1===this.#S&&-1===this.#C&&-1===this.#v||(this._CancelAnimationFrame(),this._RequestAnimationFrame()))}_SetFixedFramerate(e){e=C3.clamp(e,1,1e3),this.#I!==e&&(this.#I=e,"fixed"===this.GetFramerateMode()&&(this._CancelAnimationFrame(),this.#T=performance.now(),this._RequestAnimationFrame()))}GetFixedFramerate(){return this.#I}SetSamplingMode(e){if(!C3.Gfx.RendererBase.IsValidSamplingMode(e)||"auto"===e)throw new Error(`invalid sampling mode '${e}'`);this.#e!==e&&(this.#e=e,this.#E(),this.UpdateRender())}GetSamplingMode(){return this.#e}#E(){for(const e of this.GetLayoutManager().GetAllLayouts())e._UpdateActiveSamplingModes()}UsesLoaderLayout(){return this._usesLoaderLayout}GetLoadingLogoAsset(){return this._loadingLogoAsset}ReleaseLoadingLogoAsset(){this._loadingLogoAsset&&(this._loadingLogoAsset.ReleaseTexture(),this._loadingLogoAsset.Release(),this._loadingLogoAsset=null)}GetLayoutManager(){return this.#a}GetMainRunningLayout(){return this.#a.GetMainRunningLayout()}GetTimelineManager(){return this.#d}GetTemplateManager(){return this.#c}GetFlowchartManager(){return this.#g}GetModel3dManager(){return this.#u}GetAssetManager(){return this.#n}LoadImage(e){return this.#n.LoadImage(e)}CreateInstance(e,t,s,i,n,a){if(a&&this.#c){if(e instanceof C3.ObjectClass&&e.IsFamily()){const r=e.GetFamilyMembers(),o=Math.floor(this.Random()*r.length);return this.CreateInstance(r[o],t,s,i,n,a)}const r=this.#c.GetTemplateData(e,a);if(r){const e=this.CreateInstanceFromData(r,t,!1,s,i,!1,n,void 0,n);return this.#c.MapInstanceToTemplateName(e,a),e}}return this.CreateInstanceFromData(e,t,!1,s,i,!1,n,void 0,n)}CreateInstanceFromData(e,t,s,i,n,a,r,o,h){let d=null,l=null;if(e instanceof C3.ObjectClass){if(l=e,l.IsFamily()){const e=l.GetFamilyMembers();l=e[Math.floor(this.Random()*e.length)]}d=l.GetDefaultInstanceData()}else d=e,l=this.GetObjectClassByIndex(d[1]);const c=l.GetPlugin().IsWorldType();if(this._isLoading&&c&&!l.IsOnLoaderLayout())return null;const g=t;let u;c||(t=null),u=s&&!a&&d&&!this._instancesByUid.has(d[2])?d[2]:this._nextUid++;const m=d?d[0]:null,_=C3.New(C3.Instance,{runtime:this,objectType:l,layer:t,worldData:m,instVarData:d?d[3]:null,uid:u,tags:d?d[6]:null});this._instancesByUid.set(u,_);let p=null;if(c&&(p=_.GetWorldInfo(),void 0!==i&&void 0!==n&&(p.SetX(i),p.SetY(n)),l._SetAnyCollisionCellChanged(!0)),t&&(h||t._AddInstance(_,!0),t.GetLayout().MaybeLoadTexturesFor(l)),this._objectCount++,l.IsInContainer()&&!s&&!a){const e=new Set;for(const t of l.GetContainer().objectTypes()){if(t===l)continue;const s=this._MaybeGetChildInstanceForObjectTypeData(t,p,e);if(s){const e=this.CreateInstanceFromData(s,g,!1,p?p.GetX():i,p?p.GetY():n,!0,!1,void 0,h);_._AddSibling(e)}else{const e=this.CreateInstanceFromData(t,g,!1,p?p.GetX():i,p?p.GetY():n,!0,!1,void 0,h);_._AddSibling(e)}}for(const e of _.siblings()){e._AddSibling(_);for(const t of _.siblings())e!==t&&e._AddSibling(t)}}if(c&&!s&&r&&this._CreateChildInstancesFromData(_,m,p,t,i,n,h),l.IsInContainer()&&!s&&!a&&r)for(const e of _.siblings()){const s=e.GetWorldInfo();if(!s)continue;const i=e.GetPlugin(),n=e.GetObjectClass().GetDefaultInstanceData()[0];i.IsWorldType()?this._CreateChildInstancesFromData(e,n,s,t,s.GetX(),s.GetY(),h):this._CreateChildInstancesFromData(e,n,s,t,void 0,void 0,h)}if(!a&&r){void 0===i&&(i=m[0]),void 0===n&&(n=m[1]);const e=p.GetTopParent(),t=i-p.GetX()+e.GetX(),s=n-p.GetY()+e.GetY();e.SetXY(t,s)}l._SetIIDsStale();const f=d?C3.cloneArray(d[5]):null,S=d?d[4].map(e=>C3.cloneArray(e)):null,C=c&&m&&m[14];if(C&&_._SetHasTilemap(),_._CreateSdkInstance(f,S),C){const e=m[14];_.GetSdkInstance().LoadTilemapData(e[2],e[0],e[1])}this._instancesPendingCreate.push(_),this._hasPendingInstances=!0,this.IsDebug()&&C3Debugger.InstanceCreated(_);const v=this.#s["instancecreate"];return v.instance=_,this._dispatcher.dispatchEvent(v),_}_GetInstanceData(e){const t=e[0],s=e[1],i=e[2],n=e[6];if(n)return n;return this.#a.GetLayoutBySID(t).GetLayer(s).GetInitialInstanceData(i)}_MaybeGetChildInstanceForObjectTypeData(e,t,s){const i=t?.GetSceneGraphChildrenExportData()??[];for(const t of i){const i=this._GetInstanceData(t),n=!!t[4],a=this.GetObjectClassByIndex(i[1]);if(!s.has(i)&&(e===a&&n))return s.add(i),i}}_CreateChildInstancesFromData(e,t,s,i,n,a,r){const o=s.GetSceneGraphZIndexExportData(),h=s.GetSceneGraphChildrenExportData();if(e.GetWorldInfo().SetSceneGraphZIndex(o),!h)return;void 0===n&&(n=t[0]),void 0===a&&(a=t[1]);const d=new Set,l=t[0],c=t[1];for(const t of h){const s=t[0],o=t[1],h=t[2],g=t[3],u=!!t[4],m=t[5],_=t[6];let p;if(_)p=_;else{p=this.#a.GetLayoutBySID(s).GetLayer(o).GetInitialInstanceData(h)}const f=this.GetObjectClassByIndex(p[1]),S=e.HasSibling(f),C=d.has(f);if(S&&!C&&u){const t=e.GetSibling(f);t.GetWorldInfo().Init(p[0]);const s=n+p[0][0]-l,i=a+p[0][1]-c;t.GetWorldInfo().SetXY(s,i),t.GetWorldInfo().SetSceneGraphZIndex(m),e.AddChild(t,{transformX:!!(1&g),transformY:!!(g>>1&1),transformZ:!!(g>>6&1),transformWidth:!!(g>>2&1),transformHeight:!!(g>>3&1),transformAngle:!!(g>>4&1),destroyWithParent:!!(g>>5&1),transformOpacity:!!(g>>7&1),transformVisibility:!!(g>>8&1)}),d.add(f)}else{const t=n+p[0][0]-l,s=a+p[0][1]-c,o=this.CreateInstanceFromData(p,i,!1,t,s,!1,!0,e,r);o.GetWorldInfo().SetSceneGraphZIndex(m),e.AddChild(o,{transformX:!!(1&g),transformY:!!(g>>1&1),transformZ:!!(g>>6&1),transformWidth:!!(g>>2&1),transformHeight:!!(g>>3&1),transformAngle:!!(g>>4&1),destroyWithParent:!!(g>>5&1),transformOpacity:!!(g>>7&1),transformVisibility:!!(g>>8&1)})}}}DestroyInstance(e){if(this._instancesPendingRelease.has(e))return;const t=e.GetObjectClass();let s=this._instancesPendingDestroy.get(t);if(s){if(s.has(e))return;s.add(e)}else s=new Set,s.add(e),this._instancesPendingDestroy.set(t,s);if(this.IsDebug()&&C3Debugger.InstanceDestroyed(e),e._MarkDestroyed(),this._hasPendingInstances=!0,e.IsInContainer())for(const t of e.siblings())this.DestroyInstance(t);for(const t of e.children())t.GetDestroyWithParent()&&this.DestroyInstance(t);if(!this.#a.IsEndingLayout()&&!this.#M){const t=this.GetEventSheetManager();t.BlockFlushingInstances(!0),e._TriggerOnDestroyed(),t.BlockFlushingInstances(!1)}e._FireDestroyedScriptEvents(this.#a.IsEndingLayout())}FlushPendingInstances(){this._hasPendingInstances&&(this._isFlushingPendingInstances=!0,this._FlushInstancesPendingCreate(),this._FlushInstancesPendingDestroy(),this._isFlushingPendingInstances=!1,this._hasPendingInstances=!1,this.UpdateRender())}_FlushInstancesPendingCreate(){for(const e of this._instancesPendingCreate){const t=e.GetObjectClass();t._AddInstance(e);for(const s of t.GetFamilies())s._AddInstance(e),s._SetIIDsStale()}C3.clearArray(this._instancesPendingCreate)}_FlushInstancesPendingDestroy(){this._dispatcher.SetDelayRemoveEventsEnabled(!0);for(const[e,t]of this._instancesPendingDestroy.entries())this._FlushInstancesPendingDestroyForObjectClass(e,t),t.clear();this._instancesPendingDestroy.clear(),this._dispatcher.SetDelayRemoveEventsEnabled(!1)}_FlushInstancesPendingDestroyForObjectClass(e,t){for(const e of t){const t=this.#s["instancedestroy"];t.instance=e,this._dispatcher.dispatchEvent(t),this._instancesByUid.delete(e.GetUID()),this._instanceTimes.delete(e);const s=e.GetWorldInfo();s&&(s._RemoveFromCollisionCells(),s._RemoveFromRenderCells(),s._MarkDestroyed()),this._instancesPendingRelease.add(e),this._objectCount--}C3.arrayRemoveAllInSet(e.GetInstances(),t),e._SetIIDsStale(),this._instancesPendingReleaseAffectedObjectClasses.add(e);for(const s of e.GetFamilies())C3.arrayRemoveAllInSet(s.GetInstances(),t),s._SetIIDsStale(),this._instancesPendingReleaseAffectedObjectClasses.add(s);if(e.GetPlugin().IsWorldType()){const e=new Set([...t].map(e=>e.GetWorldInfo().GetLayer()));for(const s of e)s._RemoveAllInstancesInSet(t)}}_GetInstancesPendingCreate(){return this._instancesPendingCreate}*instancesPendingCreateForObjectClass(e){for(const t of this._GetInstancesPendingCreate())e.IsFamily()?t.GetObjectClass().BelongsToFamily(e)&&(yield t):t.GetObjectClass()===e&&(yield t)}_GetNewUID(){return this._nextUid++}_MapInstanceByUID(e,t){this._instancesByUid.set(e,t)}_SetAutoSuspendEnabled(e){e=!!e,this._isAutoSuspendEnabled!==e&&(this._isAutoSuspendEnabled=!!e,this._isAutoSuspendEnabled&&this._isPageVisibilitySuspended&&(this.SetSuspended(!1),this._isPageVisibilitySuspended=!1))}_IsAutoSuspendEnabled(){return this._isAutoSuspendEnabled}_OnRendererContextLost(){this._dispatcher.dispatchEvent(C3.New(C3.Event,"renderercontextlost")),this.SetSuspended(!0);for(const e of this._allObjectClasses)!e.IsFamily()&&e.HasLoadedTextures()&&e.ReleaseTextures();const e=this.GetMainRunningLayout();e&&e._OnRendererContextLost(),C3.ImageInfo.OnRendererContextLost(),C3.ImageAsset.OnRendererContextLost()}async _OnRendererContextRestored(){await this.GetMainRunningLayout()._Load(null,this.GetRenderer()),this._dispatcher.dispatchEvent(C3.New(C3.Event,"renderercontextrestored")),this.SetSuspended(!1),this.UpdateRender()}_OnVisibilityChange(e){if(!this._isAutoSuspendEnabled)return;const t=e["hidden"];this.SetSuspended(t),this._isPageVisibilitySuspended=t,t||this.UpdateRender()}_OnWindowBlur(e){this.IsPreview()&&this._pauseOnBlur&&!C3.Platform.IsMobile&&(e.data["parentHasFocus"]||(this.SetSuspended(!0),this._isPausedOnBlur=!0))}_OnWindowFocus(){this._isPausedOnBlur&&(this.SetSuspended(!1),this._isPausedOnBlur=!1)}_RequestAnimationFrame(){const e=this._tickCallbacks;if("vsync"===this.#f)-1===this.#S&&(this.#S=globalThis.requestAnimationFrame(e.normal));else if("fixed"===this.#f){if(-1===this.#v){const t=1e3/this.#I;this.#T+=t;const s=performance.now();let i=0;this.#Te.normal(performance.now()),i)}}else"unlimited-tick"===this.#f?(-1===this.#C&&(this.#C=C3.RequestUnlimitedAnimationFrame(e.tickOnly)),-1===this.#S&&(this.#S=globalThis.requestAnimationFrame(e.renderOnly))):-1===this.#C&&(this.#C=C3.RequestUnlimitedAnimationFrame(e.normal))}_CancelAnimationFrame(){-1!==this.#S&&(globalThis.cancelAnimationFrame(this.#S),this.#S=-1),-1!==this.#C&&(C3.CancelUnlimitedAnimationFrame(this.#C),this.#C=-1),-1!==this.#v&&(globalThis.clearTimeout(this.#v),this.#v=-1)}IsSuspended(){return this._suspendCount>0}SetSuspended(e){if(this.IsExportToVideo())return;const t=this.IsSuspended();this._suspendCount+=e?1:-1,this._suspendCount<0&&(this._suspendCount=0);const s=this.IsSuspended();if(!t&&s)console.log("[Construct] Suspending"),this._CancelAnimationFrame(),this._dispatcher.dispatchEvent(C3.New(C3.Event,"suspend")),this.DispatchUserScriptEvent(C3.New(C3.Event,"suspend")),this.Trigger(C3.Plugins.System.Cnds.OnSuspend,null,null);else if(t&&!s){console.log("[Construct] Resuming");const e=performance.now();this._lastTickTime=e,this._fpsLastTime=e,this._fpsFrameCount=0,this._fps=0,this._tpsTickCount=0,this._tps=0,this._mainThreadTime=0,this._mainThreadTimeCounter=0,this._dispatcher.dispatchEvent(C3.New(C3.Event,"resume")),this.DispatchUserScriptEvent(C3.New(C3.Event,"resume")),this.Trigger(C3.Plugins.System.Cnds.OnResume,null,null),this.HitBreakpoint()||this.Tick(e)}}_AddBehInstToTick(e){this._behInstsToTick.Add(e)}_AddBehInstToPostTick(e){this._behInstsToPostTick.Add(e)}_AddBehInstToTick2(e){this._behInstsToTick2.Add(e)}_RemoveBehInstToTick(e){this._behInstsToTick.Remove(e)}_RemoveBehInstToPostTick(e){this._behInstsToPostTick.Remove(e)}_RemoveBehInstToTick2(e){this._behInstsToTick2.Remove(e)}_CallBehaviorTickMethod(e,t){const s=t?performance.now():0;let i;return e instanceof ISDKBehaviorInstanceBase?(i=e._tick(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.behavior,performance.now()-s)):(i=e.Tick(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.GetBehavior(),performance.now()-s)),i}_BehaviorTick(){const e=this.IsDebug();this._behInstsToTick.SetQueueingEnabled(!0);for(const t of this._behInstsToTick)this._CallBehaviorTickMethod(t,e);this._behInstsToTick.SetQueueingEnabled(!1)}_CallBehaviorPostTickMethod(e,t){const s=t?performance.now():0;let i;return e instanceof ISDKBehaviorInstanceBase?(i=e._postTick(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.behavior,performance.now()-s)):(i=e.PostTick(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.GetBehavior(),performance.now()-s)),i}_BehaviorPostTick(){const e=this.IsDebug();this._behInstsToPostTick.SetQueueingEnabled(!0);for(const t of this._behInstsToPostTick)this._CallBehaviorPostTickMethod(t,e);this._behInstsToPostTick.SetQueueingEnabled(!1)}_CallBehaviorTick2Method(e,t){const s=t?performance.now():0;let i;return e instanceof ISDKBehaviorInstanceBase?(i=e._tick2(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.behavior,performance.now()-s)):(i=e.Tick2(),t&&C3Debugger.AddIndividualBehaviorTickTime(e.GetBehavior(),performance.now()-s)),i}_BehaviorTick2(){const e=this.IsDebug();this._behInstsToTick2.SetQueueingEnabled(!0);for(const t of this._behInstsToTick2)this._CallBehaviorTick2Method(t,e);this._behInstsToTick2.SetQueueingEnabled(!1)}*_DebugBehaviorTick(){const e=this.IsDebug();this._behInstsToTick.SetQueueingEnabled(!0);for(const t of this._behInstsToTick){const s=this._CallBehaviorTickMethod(t,e);C3.IsIterator(s)&&(yield*s)}this._behInstsToTick.SetQueueingEnabled(!1)}*_DebugBehaviorPostTick(){const e=this.IsDebug();this._behInstsToPostTick.SetQueueingEnabled(!0);for(const t of this._behInstsToPostTick){const s=this._CallBehaviorPostTickMethod(t,e);C3.IsIterator(s)&&(yield*s)}this._behInstsToPostTick.SetQueueingEnabled(!1)}*_DebugBehaviorTick2(){const e=this.IsDebug();this._behInstsToTick2.SetQueueingEnabled(!0);for(const t of this._behInstsToTick2){const s=this._CallBehaviorTick2Method(t,e);C3.IsIterator(s)&&(yield*s)}this._behInstsToTick2.SetQueueingEnabled(!1)}async Tick(e,t,s){this._hasStartedTicking=!0;const i="background-wake"===s,n="background-wake"!==s&&"skip-render"!==s,a=this.GetLayoutManager(),r=this.GetCanvasManager();if(!this._hasStarted||this.IsSuspended()&&!t&&!i)return;const o=performance.now();this._isInTick=!0,this._MeasureDt(e||0),this._tpsTickCount++,this._ReleasePendingInstances();const h=this.Step_BeforePreTick();this.IsDebugging()&&await h;const d=this._dispatcher.dispatchEventAndWait_AsyncOptional(this.#s["pretick"]);d instanceof Promise&&await d,this.DispatchUserScriptEvent(this._userScriptEventObjects["pretick"]);const l=this.Step_AfterPreTick();this.IsDebugging()&&await l,this.#L()&&await this.#R(),a.IsPendingChangeMainLayout()&&await this._MaybeChangeLayout();const c=this.Step_RunEventsEtc();this.IsDebugging()&&await c;const g=a.GetMainRunningLayout(),u=g._GetPendingSetHTMLLayerCount();let m=!1;if(-1!==u&&(g._ResetPendingHTMLLayerCount(),r.GetHTMLLayerCount()!==u)){const e=this.GetCanvasManager().SetHTMLLayerCount(u);this.IsInWorker()&&(m=!0,await e)}if(this.PostComponentMessageToDOM("canvas","update-html-layer-dom-state",{"layersDomState":g._GetRootLayers().filter(e=>e.IsHTMLElementsLayer()).map(e=>e._GetHTMLLayerDOMState())}),n&&this.Render(),m&&this.PostComponentMessageToDOM("canvas","cleanup-html-layers"),this.IsExportToVideo()&&(await this._ExportToVideoAddFrame(),this.GetGameTime()>=this.GetExportVideoDuration()))this._ExportToVideoFinish();else{if(!this.IsSuspended()&&!i){if("unlimited-frame"===this.GetFramerateMode()){const e=this.#i._GetRendererThrottlePromise();if(e){const t=this.GetRenderer(),s=t.IsWebGL();let i=!1;if(s){const e=()=>{t._CheckPendingPolls(),i||C3.RequestUnlimitedAnimationFrame(e,"background")};e()}await e,i=!0}}this._RequestAnimationFrame()}this._tickCount++,this._tickCountNoSave++,this._isInTick=!1,this._mainThreadTimeCounter+=performance.now()-o}}async Step_BeforePreTick(){const e=this.#r,t=this.IsDebug();this.FlushPendingInstances(),e.BlockFlushingInstances(!0),this.PushCurrentLayout(this.GetMainRunningLayout()),t&&C3Debugger.StartMeasuringTime(),this.IsDebugging()?await e.DebugRunScheduledWaits():e.RunScheduledWaits(),t&&C3Debugger.AddEventsTime(),this.PopCurrentLayout(),e.BlockFlushingInstances(!1),this.FlushPendingInstances(),e.BlockFlushingInstances(!0)}async Step_AfterPreTick(){const e=this.#r,t=this.IsDebug(),s=this.IsDebugging(),i=this._dispatcher,n=this.#s,a=this._userScriptEventObjects;t&&C3Debugger.StartMeasuringTime(),s?await this.DebugIterateAndBreak(this._DebugBehaviorTick()):this._BehaviorTick(),s?await this.DebugIterateAndBreak(this._DebugBehaviorPostTick()):this._BehaviorPostTick(),t&&C3Debugger.AddBehaviorTotalTickTime(),t&&C3Debugger.StartMeasuringTime(),s?await this.DebugFireGeneratorEventAndBreak(n["tick"]):i.dispatchEvent(n["tick"]),t&&C3Debugger.AddPluginTotalTickTime(),e.BlockFlushingInstances(!1),this.DispatchUserScriptEvent(a["tick"])}async Step_RunEventsEtc(){const e=this.#r,t=this._dispatcher,s=this.#s,i=this._userScriptEventObjects,n=this.IsDebug(),a=this.IsDebugging();n&&C3Debugger.StartMeasuringTime(),a?await e.DebugRunEvents(this.#a):e.RunEvents(this.#a),n&&C3Debugger.AddEventsTime(),this.#h.ClearRegisteredCollisions(),this._ReleasePendingInstances(),this._isLayoutFirstTick=!1,e.BlockFlushingInstances(!0),n&&C3Debugger.StartMeasuringTime(),a?await this.DebugIterateAndBreak(this._DebugBehaviorTick2()):this._BehaviorTick2(),n&&C3Debugger.AddBehaviorTotalTickTime(),n&&C3Debugger.StartMeasuringTime(),a?await this.DebugFireGeneratorEventAndBreak(s["tick2"]):t.dispatchEvent(s["tick2"]),n&&C3Debugger.AddPluginTotalTickTime(),e.BlockFlushingInstances(!1),this.DispatchUserScriptEvent(i["tick2"]),a&&await e.RunQueuedDebugTriggersAsync(),this.FlushPendingInstances(),this._ReleasePendingInstances()}_ReleasePendingInstances(){if(0===this._instancesPendingRelease.size)return;const e=this._dispatcher;e.SetDelayRemoveEventsEnabled(!0);for(const e of this._instancesPendingReleaseAffectedObjectClasses)e.GetSolStack().RemoveInstances(this._instancesPendingRelease);this._instancesPendingReleaseAffectedObjectClasses.clear(),this.#r._OnInstancesReleased(this._instancesPendingRelease);for(const e of this._instancesPendingRelease)e.Release();this._instancesPendingRelease.clear(),e.SetDelayRemoveEventsEnabled(!1)}async _MaybeChangeLayout(){const e=this.GetLayoutManager();let t=0;for(;e.IsPendingChangeMainLayout()&&t++<10;)await this._DoChangeLayout(e.GetPendingChangeMainLayout())}_MeasureDt(e){let t=0;if(this.IsExportToVideo())t=1/this.GetExportVideoFramerate(),this._dtRaw=t,this._dt1=t;else if("fixed"===this.GetFramerateMode())t=1/this.GetFixedFramerate(),this._dtRaw=t,this._dt1=t;else if(0!==this._lastTickTime){t=Math.max(e-this._lastTickTime,0)/1e3,t>.5&&(t=0),this._dtRaw=t,this._dt1=C3.clamp(t,this._minDt,this._maxDt)}this._lastTickTime=e,this._dt=this._dt1*this._timeScale,this._gameTime.Add(this._dt),this._gameTimeRaw.Add(t*this._timeScale),this._wallTime.Add(this._dt1);for(const[e,t]of this._instanceTimes)t.Add(this._dt1*e.GetTimeScale());this.#i&&this.#i._UpdateTick(),e-this._fpsLastTime>=1e3&&(this._fpsLastTime+=1e3,e-this._fpsLastTime>=1e3&&(this._fpsLastTime=e),this._fps=this._fpsFrameCount,this._fpsFrameCount=0,this._tps=this._tpsTickCount,this._tpsTickCount=0,this._mainThreadTime=Math.min(this._mainThreadTimeCounter/1e3,1),this._mainThreadTimeCounter=0,this.#i&&this.#i._Update1sFrameRange(),this.#h._Update1sStats(),this.IsDebug()&&C3Debugger.Update1sPerfStats())}_SetTrackingInstanceTime(e,t){if(t){if(!this._instanceTimes.has(e)){const t=C3.New(C3.KahanSum);t.Copy(this._gameTime),this._instanceTimes.set(e,t)}}else this._instanceTimes.delete(e)}_GetInstanceGameTime(e){const t=this._instanceTimes.get(e);return t?t.Get():this.GetGameTime()}async _DoChangeLayout(e){const t=this._dispatcher,s=this.GetLayoutManager().GetMainRunningLayout();await s._StopRunning(),s._Unload(e,this.GetRenderer()),s===e&&this.#r.ClearAllScheduledWaits(),this.#h.ClearRegisteredCollisions(),this._ReleasePendingInstances(),t.dispatchEvent(this.#s["beforelayoutchange"]),C3.Asyncify.SetHighThroughputMode(!0),await e._Load(s,this.GetRenderer()),C3.Asyncify.SetHighThroughputMode(!1),await e._StartRunning(!1),t.dispatchEvent(this.#s["layoutchange"]),this.UpdateRender(),this._isLayoutFirstTick=!0,this.FlushPendingInstances(),this._ExportToVideoAddKeyframe()}UpdateRender(){this._needRender=!0}GetWebGLRenderer(){return this.#i?this.#i.GetWebGLRenderer():null}GetWebGPURenderer(){return this.#i?this.#i.GetWebGPURenderer():null}GetRenderer(){return this.#i?this.#i.GetRenderer():null}Render(){const e=this.#i;if(!e||e.IsRendererContextLost())return;const t=this.GetRenderer(),s=t.SupportsGPUProfiling(),i=s&&t.IsWebGL(),n=s&&t.IsWebGPU();if(i&&t.CheckForQueryResults(),!this._needRender&&!this.IsExportToVideo()&&"unlimited-frame"!==this.GetFramerateMode())return void t.IncrementFrameNumber();const a=this.#a.GetMainRunningLayout();this._fpsFrameCount++;let r="nearest";this.UsesAnyCrossSampling()&&"nearest"!==a.GetActiveSampling()&&(r="bilinear"),t.Start(r);const o=this.IsDebug();o&&C3Debugger.StartMeasuringTime(),this._needRender=!1;let h=null;i&&(h=e.GetGPUFrameTimingsBuffer().AddTimeElapsedQuery(),t.StartQuery(h)),n&&(t.StartFrameTiming(2*(1+a.GetLayerCount())),t.StartMeasuringRenderPassTime(0,1)),this.Uses3DFeatures()&&"low"===e.GetCurrentFullscreenScalingQuality()?t.SetFixedSizeDepthBuffer(e.GetDrawWidth(),e.GetDrawHeight()):t.SetAutoSizeDepthBuffer(),this._Render(this.GetRenderer(),a),h&&t.EndQuery(h),n&&t.StopMeasuringRenderPassTime(),t.Finish(),n&&this.#i._AddWebGPUFrameTimingResultPromise(t.FinishFrameTiming()),o&&(C3Debugger.AddDrawCallsTime(),C3Debugger.UpdateInspectHighlight()),e&&e._MaybeTakeSnapshot()}_NeedsHTMLLayerCompositing(e){return"low"===this.GetCanvasManager().GetCurrentFullscreenScalingQuality()||e.IsWebGL()&&(this.UsesAnyBackgroundBlending()||this.Uses3DFeatures())}_Render(e,t){e.SetTextureFillMode(),e.SetAlphaBlend(),e.ResetCullState(),e.SetColorRgba(1,1,1,1),e.SetRenderTarget(null),e.SetTexture(null),e.SetDepthEnabled(this.Uses3DFeatures()),this.Dispatcher().dispatchEvent(this.#s["beforerender"]),this.Dispatcher().dispatchEvent(this.#s["beforerender2"]),this._NeedsHTMLLayerCompositing(e)&&t._MaybeStartDrawToOwnTexture(e);const s=t.GetHTMLLayerCount();for(let i=1;ithis.DeleteTextIconSet(e);this._iconChangeHandlers.set(e,t),e.Dispatcher().addEventListener("animationframeimagechange",t)}const t=this._textIconManager.GetIconSet(e);return t.HasLoaded()||t.LoadContent().then(()=>this.UpdateRender()),t}DeleteTextIconSet(e){this._textIconManager.DeleteIconSet(e)}_GetTextIconSetMeta(e){const t=[];for(const s of e.GetAnimations())for(const e of s.GetFrames()){const s=e.GetImageInfo();t.push({source:e,width:s.GetWidth(),height:s.GetHeight(),tag:e.GetTag()})}return{icons:t}}async _GetTextIconSetContent(e){const t=C3.New(C3.PromiseThrottle),s=[],i=new Map;for(const n of e.GetAnimations())for(const e of n.GetFrames()){const n=e.GetImageInfo().GetImageAsset();i.has(n)||(i.set(n,null),s.push(t.Add(async()=>{const e=await n.LoadToDrawable();i.set(n,e)})))}await Promise.all(s);const n=[];for(const s of e.GetAnimations())for(const e of s.GetFrames())n.push(t.Add(async()=>{const t=e.GetImageInfo(),s=i.get(t.GetImageAsset()),n=await t.ExtractImageToCanvas(s);return{drawable:await createImageBitmap(n)}}));const a=await Promise.all(n);for(const e of i.values())e instanceof ImageBitmap&&e["close"]&&e["close"]();return{icons:a}}SaveToSlot(e){return new Promise((t,s)=>{this.#b={slotName:e,isToString:!1,resolve:t,reject:s}})}SaveToJsonString(){return new Promise((e,t)=>{this.#b={slotName:"",isToString:!0,resolve:e,reject:t}})}LoadFromSlot(e){return new Promise((t,s)=>{this.#y={slotName:e,fromString:"",resolve:t,reject:s}})}LoadFromJsonString(e){return new Promise((t,s)=>{this.#y={slotName:"",fromString:e,resolve:t,reject:s}})}GetLastSaveJsonString(){return this.#G}#L(){return!(!this.#b&&!this.#y)}async#R(){if(this.#b?.slotName&&(this.FlushPendingInstances(),await this.#P(),this.#A()),this.#y?.slotName&&(await this.#k(),this.#A(),this.IsDebug()&&C3Debugger.StepIfPausedInDebugger()),this.#b?.isToString){const e=this.#b.resolve,t=await this._SaveToJsonString();this.DispatchUserScriptEvent(this._CreateUserScriptEvent("savecomplete",{jsonString:t})),this.#G=t,await this.TriggerAsync(C3.Plugins.System.Cnds.OnSaveComplete,null),this.#G="",e(t),this.#A()}if(this.#y?.fromString){this.FlushPendingInstances();const e=this.#y.resolve,t=this.#y.reject;try{const t=this.#y.fromString;await this._DoLoadFromJsonString(t),this.DispatchUserScriptEvent(this._CreateUserScriptEvent("loadcomplete",{jsonString:t})),this.#G=t,await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadComplete,null),this.#G="",e(t)}catch(e){console.error("[Construct] Failed to load state from JSON string: ",e),this.DispatchUserScriptEvent(this._CreateUserScriptEvent("loaderror",{error:e})),await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadFailed,null),t(e)}this.#A()}}#A(){this.#b=null,this.#y=null}_GetProjectStorage(){return this.#w||(this.#w=localforage.createInstance({name:"c3-localstorage-"+this.GetProjectUniqueId(),description:this.GetProjectName()})),this.#w}_GetSavegamesStorage(){return this.#D||(this.#D=localforage.createInstance({name:"c3-savegames-"+this.GetProjectUniqueId(),description:this.GetProjectName()})),this.#D}async#P(){const e=this.#b.slotName,t=this.#b.resolve,s=this.#b.reject,i=await this._SaveToJsonString();try{await this._GetSavegamesStorage().setItem(e,i),console.log("[Construct] Saved state to storage ("+i.length+" chars)"),this.DispatchUserScriptEvent(this._CreateUserScriptEvent("savecomplete",{jsonString:i})),this.#G=i,await this.TriggerAsync(C3.Plugins.System.Cnds.OnSaveComplete,null),this.#G="",t(i)}catch(e){console.error("[Construct] Failed to save state to storage: ",e),this.DispatchUserScriptEvent(this._CreateUserScriptEvent("saveerror",{error:e})),await this.TriggerAsync(C3.Plugins.System.Cnds.OnSaveFailed,null),s(e)}}async#k(){const e=this.#y.slotName,t=this.#y.resolve,s=this.#y.reject;try{const s=await this._GetSavegamesStorage().getItem(e);if(!s)throw new Error("empty slot");console.log("[Construct] Loaded state from storage ("+s.length+" chars)"),await this._DoLoadFromJsonString(s),this.DispatchUserScriptEvent(this._CreateUserScriptEvent("loadcomplete",{jsonString:s})),this.#G=s,await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadComplete,null),this.#G="",t(s)}catch(e){console.error("[Construct] Failed to load state from storage: ",e),this.DispatchUserScriptEvent(this._CreateUserScriptEvent("loaderror",{error:e})),await this.TriggerAsync(C3.Plugins.System.Cnds.OnLoadFailed,null),s(e)}}async _SaveToJsonString(){const e={"c3save":!0,"version":1,"rt":{"time":this.GetGameTime(),"timeRaw":this.GetGameTimeRaw(),"walltime":this.GetWallTime(),"timescale":this.GetTimeScale(),"tickcount":this.GetTickCount(),"next_uid":this._nextUid,"running_layout":this.GetMainRunningLayout().GetSID(),"start_time_offset":Date.now()-this._startTime,"samplingMode":this.GetSamplingMode()},"types":{},"layouts":{},"events":this.#r._SaveToJson(),"timelines":this.#d._SaveToJson(),"user_script_data":null};for(const t of this._allObjectClasses)t.IsFamily()||t.HasNoSaveBehavior()||(e["types"][t.GetSID().toString()]=t._SaveToJson());for(const t of this.#a.GetAllLayouts())e["layouts"][t.GetSID().toString()]=t._SaveToJson();const t=this._CreateUserScriptEvent("save",{saveData:null});return await this.DispatchUserScriptEventAsyncWait(t),e["user_script_data"]=t.saveData,JSON.stringify(e)}IsLoadingState(){return this.#M}async _DoLoadFromJsonString(e){const t=this.GetLayoutManager(),s=JSON.parse(e);if(s["c2save"])throw new Error("C2 saves are incompatible with C3 runtime");if(!s["c3save"])throw new Error("not valid C3 save data");if(s["version"]>1)throw new Error("C3 save data from future version");this.ClearIntancesNeedingAfterLoad(),this._dispatcher.dispatchEvent(C3.New(C3.Event,"beforeload"));for(const e of this.allInstances()){e.GetObjectClass().HasNoSaveBehavior()||e._OnBeforeLoad()}const i=s["rt"];this._gameTime.Set(i["time"]),i.hasOwnProperty("timeRaw")&&this._gameTimeRaw.Set(i["timeRaw"]),this._wallTime.Set(i["walltime"]),this._timeScale=i["timescale"],this._tickCount=i["tickcount"],this._startTime=Date.now()-i["start_time_offset"],i.hasOwnProperty("samplingMode")&&(this.#e=i["samplingMode"]);const n=i["running_layout"];this.#M=!0;let a=!1;if(n!==this.GetMainRunningLayout().GetSID()){const e=t.GetLayoutBySID(n);if(!e)return;await this._DoChangeLayout(e),a=!0}for(const[e,i]of Object.entries(s["layouts"])){const s=parseInt(e,10),n=t.GetLayoutBySID(s);n&&n._LoadFromJson(i)}const r=new Set;for(const[e,t]of Object.entries(s["types"])){const s=parseInt(e,10),i=this.GetObjectClassBySID(s);!i||i.IsFamily()||i.HasNoSaveBehavior()||i._LoadFromJson(t,r)}for(const e of this.#a.GetAllLayouts())for(const t of e.allLayers())t._LoadFromJsonAfterInstances();if(this.FlushPendingInstances(),this._RefreshUidMap(),this.#M=!1,a){for(const e of this.allInstances())e.SetupInitialSceneGraphConnections();for(const[e,t]of Object.entries(s["types"])){const s=parseInt(e,10),i=this.GetObjectClassBySID(s);!i||i.IsFamily()||i.HasNoSaveBehavior()||i._SetupSceneGraphConnectionsOnChangeOfLayout(t)}}this._nextUid=i["next_uid"],this.#r._LoadFromJson(s["events"]);for(const e of this._allObjectClasses)if(!e.IsFamily()&&e.IsInContainer())for(const t of e.GetInstances()){const s=t.GetIID();t._ClearSiblings();for(const i of e.GetContainer().objectTypes()){if(i===e)continue;const n=i.GetInstances();if(s<0||s>=n.length)throw new Error("missing sibling instance");t._AddSibling(n[s])}}this.#d._LoadFromJson(s["timelines"]),t.SetAllLayerProjectionChanged(),t.SetAllLayerMVChanged();for(const e of r)e._OnCreatedForLoadingSavegame();this.DoAfterLoad(),this.#E(),this._dispatcher.dispatchEvent(C3.New(C3.Event,"afterload")),this.DispatchUserScriptEvent(this._CreateUserScriptEvent("afterload"));for(const e of Object.keys(s["types"])){const t=parseInt(e,10),s=this.GetObjectClassBySID(t);s&&s._ClearLoadInstancesJson()}await this.DispatchUserScriptEventAsyncWait(this._CreateUserScriptEvent("load",{saveData:s["user_script_data"]})),this.UpdateRender()}SortOnTmpHierarchyPosition(e,t){return t.GetWorldInfo().GetTmpHierarchyPosition()-e.GetWorldInfo().GetTmpHierarchyPosition()}AddInstanceNeedingAfterLoad(e,t){e.GetWorldInfo()&&(this.#_.has(e)||(this.#_.set(e,t),this.#p.push(e)))}ClearIntancesNeedingAfterLoad(){this.#_=new WeakMap,C3.clearArray(this.#p),C3.SceneGraphInfo.ClearUpdatedInstances()}DoAfterLoad(e="full",t=null){this.#p.sort(this.SortOnTmpHierarchyPosition),t||(t={}),t.processedWorldInfo=new Set;const s=this.#p.length;for(const s of this.#p)s._OnAfterLoad(this.#_.get(s),e,t);for(const s of this.#p)s._OnAfterLoad2(this.#_.get(s),e,t);if(this.ClearIntancesNeedingAfterLoad(),s){this.FlushPendingInstances(),this._RefreshUidMap();for(const e of this.#a.GetAllLayouts())for(const t of e.allLayers())t._SortInstancesByLastCachedZIndex(),t.SetZIndicesChanged()}}async AddJobWorkerScripts(e){const t=e.map(e=>new URL(e,location.href).toString());this.#m.ImportScriptsToJobWorkers(t)}AddJobWorkerBlob(e,t){this.#m.SendBlobToJobWorkers(e,t)}AddJobWorkerBuffer(e,t){this.#m.SendBufferToJobWorkers(e,t)}AddJob(e,t,s,i){return this.#m.AddJob(e,t,s,null,null,i)}BroadcastJob(e,t,s,i){return this.#m.BroadcastJob(e,t,s,i)}GetMaxNumJobWorkers(){return this.#m.GetMaxNumWorkers()}InvokeDownload(e,t){this.PostComponentMessageToDOM("runtime","invoke-download",{"url":e,"filename":t})}async RasterSvgImage(e,t,s,i,n,a){if(i=i||t,n=n||s,this.IsInWorker()){return(await this.PostComponentMessageToDOMAsync("runtime","raster-svg-image",{"blob":e,"imageWidth":t,"imageHeight":s,"surfaceWidth":i,"surfaceHeight":n,"imageBitmapOpts":a}))["imageBitmap"]}{const r=await self["C3_RasterSvgImageBlob"](e,t,s,i,n);return a?await self.createImageBitmap(r,a):r}}async GetSvgImageSize(e){return this.IsInWorker()?await this.PostComponentMessageToDOMAsync("runtime","get-svg-image-size",{"blob":e}):await self["C3_GetSvgImageSize"](e)}RequestDeviceOrientationEvent(){this._didRequestDeviceOrientationEvent||(this._didRequestDeviceOrientationEvent=!0,this.PostComponentMessageToDOM("runtime","enable-device-orientation"))}RequestDeviceMotionEvent(){this._didRequestDeviceMotionEvent||(this._didRequestDeviceMotionEvent=!0,this.PostComponentMessageToDOM("runtime","enable-device-motion"))}Random(){return this._randomNumberCallback()}SetRandomNumberGeneratorCallback(e){this._randomNumberCallback=e}_GetRemotePreviewStatusInfo(){const e=this.GetRenderer();return{"fps":this.GetFramesPerSecond(),"tps":this.GetTicksPerSecond(),"cpu":this.GetMainThreadTime(),"gpu":this.GetGPUUtilisation(),"layout":this.GetMainRunningLayout()?this.GetMainRunningLayout().GetName():"","renderer":e.IsWebGL()?e.GetUnmaskedRenderer():e.GetAdapterInfoString()}}HitBreakpoint(){return!!this.IsDebug()&&C3Debugger.HitBreakpoint()}DebugBreak(e){return this.IsDebugging()?C3Debugger.DebugBreak(e):Promise.resolve()}DebugBreakNext(){return!!this.IsDebugging()&&C3Debugger.BreakNext()}SetDebugBreakpointsEnabled(e){this._breakpointsEnabled=!!e,this._UpdateDebuggingFlag()}AreDebugBreakpointsEnabled(){return this._breakpointsEnabled}IsDebugging(){return this._isDebugging}SetDebuggingEnabled(e){e?this._debuggingDisabled--:this._debuggingDisabled++,this._UpdateDebuggingFlag()}_UpdateDebuggingFlag(){this._isDebugging=this.IsDebug()&&this._breakpointsEnabled&&0===this._debuggingDisabled}IsCPUProfiling(){return this.IsDebug()&&C3Debugger.IsCPUProfiling()}IsGPUProfiling(){return this.IsDebug()&&this.GetRenderer().SupportsGPUProfiling()&&C3Debugger.IsGPUProfiling()}async DebugIterateAndBreak(e){if(e)for(const t of e)await this.DebugBreak(t)}DebugFireGeneratorEventAndBreak(e){return this.DebugIterateAndBreak(this._dispatcher.dispatchGeneratorEvent(e))}_InvokeFunctionFromJS(e){return this.#r._InvokeFunctionFromJS(e["name"],e["params"])}_GetHTMLLayerWrapElement(e){if(this.IsInWorker())throw new Error("not supported in worker mode");return self["c3_runtimeInterface"]["_GetHTMLWrapElement"](e)}GetIRuntime(){return this._iRuntime}GetConstructVersionCode(){return this._constructVersionCode}_CreateUserScriptEvent(e,t){const s=C3.New(C3.Event,e,!1);return s.runtime=this._iRuntime,t&&Object.assign(s,t),s}_InitScriptInterfaces(){this._iRuntime=new self.IRuntime(this),this._userScriptEventObjects={"pretick":this._CreateUserScriptEvent("pretick"),"tick":this._CreateUserScriptEvent("tick"),"tick2":this._CreateUserScriptEvent("tick2")}}_InitObjectsScriptInterface(){const e={};for(const t of this._allObjectClasses)e[t.GetJsPropName()]={value:t.GetIObjectClass(),enumerable:!0,writable:!1};this._iRuntime._InitObjects(e)}_InitGlobalVariableScriptInterface(){const e={};for(const t of this.GetEventSheetManager().GetAllGlobalVariables())e[t.GetJsPropName()]=t._GetScriptInterfaceDescriptor();this._iRuntime._InitGlobalVars(e)}_GetCommonScriptInterfaces(){return this._commonScriptInterfaces}_MapScriptInterface(e,t){this.#t.set(e,t)}_UnwrapScriptInterface(e){return this.#t.get(e)}_UnwrapIObjectClass(e){if(!(e instanceof self.IObjectClass))throw new TypeError("expected IObjectClass");const t=this._UnwrapScriptInterface(e);if(!(t&&t instanceof C3.ObjectClass))throw new Error("invalid IObjectClass");return t}_UnwrapIInstance(e){if(!(e instanceof self.IInstance))throw new TypeError("expected IInstance");const t=this._UnwrapScriptInterface(e);if(!(t&&t instanceof C3.Instance))throw new Error("invalid IInstance");return t}_UnwrapIWorldInstance(e){C3X.RequireIWorldInstance(e);const t=this._UnwrapScriptInterface(e);if(!(t&&t instanceof C3.Instance))throw new Error("invalid IInstance");return t}},globalThis["C3_SetInitFunctions"](CreateRuntime,InitRuntime); } // workers/jobSchedulerRuntime.js { const C3=self.C3;C3.JobSchedulerRuntime=class extends C3.DefendedBase{constructor(r,e){super(),this._runtime=r,this._jobPromises=new Map,this._nextJobId=0,this._inputPort=e["inputPort"],e["outputPort"].onmessage=r=>this._OnJobWorkerMessage(r),this._maxNumWorkers=e["maxNumWorkers"],this._jobWorkerCount=1,this._isCreatingWorker=!1,this._hadErrorCreatingWorker=!1}GetMaxNumWorkers(){return this._maxNumWorkers}ImportScriptsToJobWorkers(r){this._inputPort.postMessage({"type":"_import_scripts","scripts":r})}SendBlobToJobWorkers(r,e){this._inputPort.postMessage({"type":"_send_blob","blob":r,"id":e})}SendBufferToJobWorkers(r,e){this._inputPort.postMessage({"type":"_send_buffer","buffer":r,"id":e},[r])}AddJob(r,e,o,s,t,i){if(o||(o=[]),"number"==typeof i&&(i=Math.floor(i))<=0)throw new Error("invalid maxWorkerNum");const n=this._nextJobId++,a={"type":r,"isBroadcast":!1,"maxWorkerNum":i,"jobId":n,"params":e,"transferables":o},_=new Promise((r,e)=>{this._jobPromises.set(n,{resolve:r,progress:s,reject:e,cancelled:!1,maxWorkerNum:i})});return t&&t.SetAction(()=>this._CancelJob(n)),this._inputPort.postMessage(a,o),this._MaybeCreateExtraWorker(),_}BroadcastJob(r,e,o,s){if(o||(o=[]),"number"==typeof s&&(s=Math.floor(s))<=0)throw new Error("invalid maxWorkerNum");const t={"type":r,"isBroadcast":!0,"maxWorkerNum":s,"jobId":this._nextJobId++,"params":e,"transferables":o};this._inputPort.postMessage(t,o)}_CancelJob(r){const e=this._jobPromises.get(r);e&&(e.cancelled=!0,e.resolve=null,e.progress=null,e.reject=null,this._inputPort.postMessage({"type":"_cancel","jobId":r}))}_OnJobWorkerMessage(r){const e=r.data,o=e["type"],s=e["jobId"];switch(o){case"result":this._OnJobResult(s,e["result"]);break;case"progress":this._OnJobProgress(s,e["progress"]);break;case"error":this._OnJobError(s,e["error"]);break;case"ready":this._OnJobWorkerReady();break;default:throw new Error(`unknown message from worker '${o}'`)}}_OnJobResult(r,e){const o=this._jobPromises.get(r);if(!o)throw new Error("invalid job ID");o.cancelled||o.resolve(e),this._jobPromises.delete(r)}_OnJobProgress(r,e){const o=this._jobPromises.get(r);if(!o)throw new Error("invalid job ID");!o.cancelled&&o.progress&&o.progress(e)}_OnJobError(r,e){const o=this._jobPromises.get(r);if(!o)throw new Error("invalid job ID");o.cancelled||o.reject(e),this._jobPromises.delete(r)}_OnJobWorkerReady(){this._isCreatingWorker&&(this._isCreatingWorker=!1,this._jobWorkerCount++,this._jobWorkerCount(r.maxWorkerNum||1/0)-(e.maxWorkerNum||1/0));for(const o of e){r<(o.maxWorkerNum||1/0)&&r++}return r}async _MaybeCreateExtraWorker(){if(!(this._jobWorkerCount>=this._maxNumWorkers||this._isCreatingWorker||this._hadErrorCreatingWorker||this._GetWorkerCountNeededForPendingJobs()<=this._jobWorkerCount))try{this._isCreatingWorker=!0;(await this._runtime.PostComponentMessageToDOMAsync("runtime","create-job-worker"))["outputPort"].onmessage=r=>this._OnJobWorkerMessage(r)}catch(r){this._hadErrorCreatingWorker=!0,this._isCreatingWorker=!1,console.error(`[Construct] Failed to create job worker; stopping creating any more (created ${this._jobWorkerCount} so far)`,r)}}}; } // scripts/shaders.js { self["C3_Shaders"] = {}; self["C3_Shaders"]["grayscale"] = { glsl: "varying mediump vec2 vTex;\nuniform lowp sampler2D samplerFront;\nuniform lowp float intensity;\nvoid main(void)\n{\nlowp vec4 front = texture2D(samplerFront, vTex);\nlowp float gray = front.r * 0.299 + front.g * 0.587 + front.b * 0.114;\ngl_FragColor = mix(front, vec4(gray, gray, gray, front.a), intensity);\n}", glslWebGL2: "", wgsl: "%%SAMPLERFRONT_BINDING%% var samplerFront : sampler;\n%%TEXTUREFRONT_BINDING%% var textureFront : texture_2d;\nstruct ShaderParams {\nintensity : f32\n};\n%%SHADERPARAMS_BINDING%% var shaderParams : ShaderParams;\n%%C3_UTILITY_FUNCTIONS%%\n%%FRAGMENTINPUT_STRUCT%%\n%%FRAGMENTOUTPUT_STRUCT%%\n@fragment\nfn main(input : FragmentInput) -> FragmentOutput\n{\nvar front : vec4 = textureSample(textureFront, samplerFront, input.fragUV);\nvar gray : f32 = c3_grayscale(front.rgb);\nvar output : FragmentOutput;\noutput.color = mix(front, vec4(gray, gray, gray, front.a), shaderParams.intensity);\nreturn output;\n}", blendsBackground: false, usesDepth: false, extendBoxHorizontal: 0, extendBoxVertical: 0, crossSampling: false, mustPreDraw: false, preservesOpaqueness: true, supports3dDirectRendering: false, animated: false, parameters: [["intensity",0,"percent"]] }; } // scripts/plugins/system/c3runtime/runtime.js { {const e=self.C3;let t=null,n="",r="",a=[],i="",s="",o="";const u=e.New(e.ArrayStack);function ForEachOrdered_SortInstances(e,t){const n=e[1],r=t[1];if("number"==typeof n&&"number"==typeof r)return n-r;{const e=""+n,t=""+r;return et?1:0}}e.Plugins.System=class extends e.SDKPluginBase{constructor(e){super(e),this._loopStack=this._runtime.GetEventSheetManager().GetLoopStack(),this._eventStack=this._runtime.GetEventSheetManager().GetEventStack(),this._imagesLoadingTotal=0,this._imagesLoadingComplete=0,this._functionMaps=new Map}Release(){super.Release()}UpdateRender(){this._runtime.UpdateRender()}Trigger(e){this._runtime.Trigger(e,null,null)}GetRegex(e,a){return t&&e===n&&a===r||(t=new RegExp(e,a),n=e,r=a),t.lastIndex=0,t}GetRegexMatches(e,t,n){if(e===i&&t===s&&n===o)return a;const r=this.GetRegex(t,n);return a=e.match(r),i=e,s=t,o=n,a}async _LoadTexturesForObjectClasses(t,n){if(!n.length)return;this._imagesLoadingTotal+=n.length;const r=[];for(const e of n)r.push(t.MaybeLoadTexturesFor(e));await e.PromiseAllWithProgress(r,()=>{this._imagesLoadingComplete++}),this._imagesLoadingComplete++,this._imagesLoadingComplete===this._imagesLoadingTotal&&(this._imagesLoadingComplete=0,this._imagesLoadingTotal=0,this._runtime.Trigger(e.Plugins.System.Cnds.OnImageLoadingComplete,null,null))}GetImageLoadingProgress(){return 0===this._imagesLoadingTotal?1:this._imagesLoadingComplete/this._imagesLoadingTotal}_UnloadTexturesForObjectClasses(e,t){for(const n of t)0===n.GetInstanceCount()&&e.MaybeUnloadTexturesFor(n)}_UnloadUnusedTextures(e,t){for(const n of t)e.UnloadUnusedTextures(n)}_GetForEachStack(){return u}_Repeat(e){const t=this._runtime.GetEventSheetManager(),n=t.GetEventStack(),r=n.GetCurrentStackFrame(),a=r.GetCurrentEvent(),i=a.GetSolModifiers(),s=r.IsSolModifierAfterCnds(),o=n.Push(a),u=t.GetLoopStack(),l=u.Push();if(l.SetEnd(e),s)for(let n=0;n=n&&!h.IsStopped();--e)r.PushCopySol(o),h.SetIndex(e),s.Retrigger(i,l),r.PopSol(o);else for(let e=t;e>=n&&!h.IsStopped();--e)h.SetIndex(e),s.Retrigger(i,l);else if(u)for(let e=t;e<=n&&!h.IsStopped();++e)r.PushCopySol(o),h.SetIndex(e),s.Retrigger(i,l),r.PopSol(o);else for(let e=t;e<=n&&!h.IsStopped();++e)h.SetIndex(e),s.Retrigger(i,l);return a.Pop(),c.Pop(),!1}*_DebugFor(e,t,n){const r=this._runtime.GetEventSheetManager(),a=r.GetEventStack(),i=a.GetCurrentStackFrame(),s=i.GetCurrentEvent(),o=s.GetSolModifiers(),u=i.IsSolModifierAfterCnds(),l=a.Push(s),c=r.GetLoopStack(),h=c.Push();if(h.SetName(e),h.SetEnd(n),n=n&&!h.IsStopped();--e)r.PushCopySol(o),h.SetIndex(e),yield*s.DebugRetrigger(i,l),r.PopSol(o);else for(let e=t;e>=n&&!h.IsStopped();--e)h.SetIndex(e),yield*s.DebugRetrigger(i,l);else if(u)for(let e=t;e<=n&&!h.IsStopped();++e)r.PushCopySol(o),h.SetIndex(e),yield*s.DebugRetrigger(i,l),r.PopSol(o);else for(let e=t;e<=n&&!h.IsStopped();++e)h.SetIndex(e),yield*s.DebugRetrigger(i,l);return a.Pop(),c.Pop(),!1}_ForEach(t){const n=t.GetCurrentSol(),r=n.GetInstances();if(0===r.length)return!1;const a=this._runtime.GetEventSheetManager(),i=a.GetEventStack(),s=i.GetCurrentStackFrame(),o=s.GetCurrentEvent(),l=o.GetSolModifiers(),c=s.IsSolModifierAfterCnds(),h=i.Push(o),g=a.GetLoopStack(),d=g.Push(),S=t.IsInContainer(),p=u.Push();if(e.shallowAssignArray(p,r),d.SetEnd(p.length),c)for(let e=0,n=p.length;e!0,OnLayoutStart:()=>!0,OnLayoutEnd:()=>!0,OnSuspend:()=>!0,OnResume:()=>!0,IsSuspended(){return this._runtime.IsSuspended()},Else(){const e=this._runtime.GetCurrentEventStackFrame();return!e.GetElseBranchRan()&&!e.GetLastEventTrue()},TriggerOnce(){const e=this._runtime.GetCurrentCondition().GetSavedDataMap();let t=e.get("TriggerOnce_lastTick");void 0===t&&(t=-1,e.set("TriggerOnce_lastTick",-1));const n=this._runtime.GetTickCount();return e.set("TriggerOnce_lastTick",n),this._runtime.IsLayoutFirstTick()||t!==n-1},Every(e){const t=this._runtime.GetCurrentCondition().GetSavedDataMap(),n=t.get("Every_lastTime")||0,r=this._runtime.GetGameTime();t.has("Every_seconds")||t.set("Every_seconds",e);const a=t.get("Every_seconds");return r>=n+a?(t.set("Every_lastTime",n+a),r>=t.get("Every_lastTime")+.04&&t.set("Every_lastTime",r),t.set("Every_seconds",e),!0):(rh.Platform.IsMobile,OnLoadFinished:()=>!0,OnCanvasSnapshot:()=>!0,EffectsSupported:()=>!0,OnSaveComplete:()=>!0,OnSaveFailed:()=>!0,OnLoadComplete:()=>!0,OnLoadFailed:()=>!0,ObjectUIDExists(e){return!!this._runtime.GetInstanceByUID(e)},IsOnPlatform(e){switch(e){case 0:return"browser"===h.Platform.Context;case 1:return"iOS"===h.Platform.OS;case 2:return"Android"===h.Platform.OS;case 8:return"cordova"===h.Platform.Context;case 9:return"scirra-arcade"===this._runtime.GetExportType();case 13:return"windows-uwp"===this._runtime.GetExportType();default:return!1}},RegexTest(e,t,n){return this.GetRegex(t,n).test(e)},Compare:(e,t,n)=>h.compare(e,t,n),CompareBetween:(e,t,n)=>e>=t&&e<=n,CompareVar:(e,t,n)=>h.compare(e.GetValue(),t,n),CompareBoolVar:e=>!!e.GetValue(),CompareTime(e,t){const n=this._runtime.GetGameTime();if(0===e){const e=this._runtime.GetCurrentCondition().GetSavedDataMap();return!e.get("CompareTime_executed")&&n>=t&&(e.set("CompareTime_executed",!0),!0)}return h.compare(n,e,t)},IsNaN:e=>isNaN(e),AngleWithin:(e,t,n)=>h.angleDiff(h.toRadians(e),h.toRadians(n))<=h.toRadians(t),IsClockwiseFrom:(e,t)=>h.angleClockwise(h.toRadians(e),h.toRadians(t)),IsBetweenAngles(e,t,n){let r=h.toRadians(e),a=h.toRadians(t),i=h.toRadians(n);return!h.angleClockwise(i,a)?!(!h.angleClockwise(r,a)&&h.angleClockwise(r,i)):h.angleClockwise(r,a)&&!h.angleClockwise(r,i)},IsValueType:(e,t)=>"number"==typeof e?0===t:1===t,EvaluateExpression:e=>!!e,OnSignal(e){return e.toLowerCase()===this._runtime.GetEventSheetManager().GetCurrentSignalTag()},PickByComparison(e,t,n,r){if(!e)return!1;const a=this._GetForEachStack(),i=a.Push(),s=e.GetCurrentSol();h.shallowAssignArray(i,s.GetInstances()),s.IsSelectAll()&&h.clearArray(s._GetOwnElseInstances());const o=this._runtime.GetCurrentCondition();let u=0;for(let e=0,a=i.length;eu?(u=n,h.clearArray(o),o.push(a)):r&&n===u&&o.push(a)}return r?a.SetArrayPicked(o):a.PickOne(o[0]),e.ApplySolToContainer(),!0},PickNth(e,t){if(!e)return!1;const n=e.GetCurrentSol(),r=n.GetInstances();if((t=Math.floor(t))>=r.length)return!1;const a=r[t];return n.PickOne(a),e.ApplySolToContainer(),!0},PickRandom(e){if(!e)return!1;const t=e.GetCurrentSol(),n=t.GetInstances(),r=Math.floor(this._runtime.Random()*n.length);if(r>=n.length)return!1;const a=n[r];return t.PickOne(a),e.ApplySolToContainer(),!0},PickAll(e){if(!e)return!1;if(!e.GetInstanceCount())return!1;return e.GetCurrentSol()._SetSelectAll(!0),e.ApplySolToContainer(),!0},PickOverlappingPoint(e,t,n){if(!e)return!1;const r=e.GetCurrentSol(),a=r.GetInstances(),i=this._runtime.GetCurrentEvent().IsOrBlock(),s=this._runtime.GetCurrentCondition().IsInverted();r.IsSelectAll()?(h.shallowAssignArray(g,a),r.ClearArrays(),r._SetSelectAll(!1)):i?(h.shallowAssignArray(g,r._GetOwnElseInstances()),h.clearArray(r._GetOwnElseInstances())):(h.shallowAssignArray(g,r._GetOwnInstances()),h.clearArray(r._GetOwnInstances()));for(let e=0,a=g.length;e=0;--a){const i=r[a];if(t){if(i.GetObjectClass().BelongsToFamily(e)){n=i;break}}else if(i.GetObjectClass()===e){n=i;break}}if(!n){const t=e.GetInstances();t.length&&(n=t.at(-1))}if(!n)return!1;return e.GetCurrentSol().PickOne(n),e.ApplySolToContainer(),!0},Repeat(e){return this._runtime.IsDebugging()?this._DebugRepeat(e):this._Repeat(e)},While(){return this._runtime.IsDebugging()?this._DebugWhile():this._While()},For(e,t,n){return this._runtime.IsDebugging()?this._DebugFor(e,t,n):this._For(e,t,n)},ForEach(e){return this._runtime.IsDebugging()?this._DebugForEach(e):this._ForEach(e)},ForEachOrdered(e,t,n){return this._runtime.IsDebugging()?this._DebugForEachOrdered(e,n):this._ForEachOrdered(e,n)},LayerVisible:e=>!!e&&e.IsVisible(),LayerInteractive:e=>!!e&&e.IsSelfAndParentsInteractive(),LayerIsHTML:e=>!!e&&e.IsHTMLElementsLayer(),LayerEmpty:e=>!!e&&!e.GetInstanceCount(),LayerCmpOpacity:(e,t,n)=>!!e&&h.compare(100*e.GetOpacity(),t,n),LayerNameExists(e){const t=this._runtime.GetMainRunningLayout();return!!t&&t.HasLayerByName(e)},OnImageLoadingComplete:()=>!0,IsLoadingImages(){return this._imagesLoadingTotal>0},TemplateExists(e,t){const n=this._runtime.GetTemplateManager();return!!n&&(!!t&&!!n.GetTemplateData(e,t))}}}{const d=self.C3;function SortZOrderList(e,t){const n=e[0]-t[0];if(0!==n)return n;return e[1]-t[1]}function SortInstancesByValue(e,t){return e[1]-t[1]}const S=[],p=[],m=d.New(d.Rect),G=d.New(d.Color),y=[];d.Plugins.System.Acts={SetVar(e,t){e.SetValue(t)},AddVar(e,t){e.IsNumber()&&"number"!=typeof t&&(t=parseFloat(t)),e.SetValue(e.GetValue()+t)},SubVar(e,t){e.IsNumber()&&e.SetValue(e.GetValue()-t)},SetBoolVar(e,t){e.SetValue(!!t)},ToggleBoolVar(e){e.SetValue(!e.GetValue())},ResetEventVar(e){e.SetValue(e.GetInitialValue())},ResetGlobals(e){this._runtime.GetEventSheetManager().ResetAllGlobalsToInitialValue(e)},CreateObject(e,t,n,r,a,i){if(!e||!t)return;const s=this._runtime.CreateInstance(e,t,n,r,a,i);if(!s)return;a&&t.SortAndAddInstancesByZIndex(s);const o=this._runtime.GetEventSheetManager();o.BlockFlushingInstances(!0),s._TriggerOnCreatedOnSelfAndRelated(),o.BlockFlushingInstances(!1);const u=new Map;s.CollectInstancesToPick(u,e,a);for(const[e,t]of u)e.GetCurrentSol().SetSetPicked(t)},CreateObjectByName(e,t,n,r,a,i){if(!e||!t)return;const s=this._runtime.GetObjectClassByName(e);s&&d.Plugins.System.Acts.CreateObject.call(this,s,t,n,r,a,i)},RecreateInitialObjects(e,t,n,r,a,i,s,o,u,l,c){if(!e)return;const h=this._runtime.GetCurrentLayout();let g=h;if(i){const e=this._runtime.GetLayoutManager().GetLayoutByName(i);if(!e)return;g=e}let d=null;if(("number"!=typeof s||s>=0)&&(d=g.GetLayer(s),!d))return;let S=null;if(("number"!=typeof o||o>=0)&&(S=h.GetLayer(o),!S))return;m.set(t,n,r,a);const p=g.RecreateInitialObjects(e,m,d,S,u,l,c);e.GetCurrentSol().SetArrayPicked(p),e.ApplySolToContainer()},StopLoop(){const e=this._loopStack;e.IsInLoop()&&e.GetCurrent().Stop()},SetGroupActive(e,t){const n=this._runtime.GetEventSheetManager().GetEventGroupByName(e);n&&(0===t?n.SetGroupActive(!1):1===t?n.SetGroupActive(!0):n.SetGroupActive(!n.IsGroupActive()))},SetTimescale(e){this._runtime.SetTimeScale(e)},SetObjectTimescale(e,t){if(t<0&&(t=0),!e)return;const n=e.GetCurrentSol().GetInstances();for(const e of n)e.SetTimeScale(t)},RestoreObjectTimescale(e){if(!e)return;const t=e.GetCurrentSol().GetInstances();for(const e of t)e.RestoreTimeScale()},Wait(e,t){if(e<0)return;const n=this._runtime.GetEventSheetManager().AddScheduledWait();return t?n.InitTimer(e):n.InitWallTimer(e),!0},WaitForSignal(e){return this._runtime.GetEventSheetManager().AddScheduledWait().InitSignal(e),!0},WaitForPreviousActions(){const e=this._runtime.GetEventSheetManager();return e.AddScheduledWait().InitPromise(e.GetPromiseForAllAsyncActions()),!0},Signal(e){this._runtime.GetEventSheetManager().Signal(e)},async SnapshotCanvas(e,t,n,r,a,i){const s=this._runtime.GetCanvasManager();s&&(this.UpdateRender(),await s.SnapshotCanvas(0===e?"image/png":"image/jpeg",t/100,n,r,a,i),await this._runtime.TriggerAsync(d.Plugins.System.Cnds.OnCanvasSnapshot,null))},SetCanvasSize(e,t){if(e<=0||t<=0)return;this._runtime.SetViewportSize(e,t),this._runtime.GetCurrentLayout().BoundScrolling();const n=this._runtime.GetCanvasManager();n&&("off"===n.GetCurrentFullscreenMode()||this._runtime.SetOriginalViewportSize(e,t),n.SetSize(n.GetLastWidth(),n.GetLastHeight(),!0),this._runtime.UpdateRender())},SetFullscreenQuality(e){const t=this._runtime.GetCanvasManager();t&&"off"!==t.GetCurrentFullscreenMode()&&(t.SetFullscreenScalingQuality(0!==e?"high":"low"),t.SetSize(t.GetLastWidth(),t.GetLastHeight(),!0))},SaveState(e){return this._runtime.SaveToSlot(e)},SaveStateJSON(){return this._runtime.SaveToJsonString()},LoadState(e){return this._runtime.LoadFromSlot(e)},LoadStateJSON(e){return this._runtime.LoadFromJsonString(e)},SetHalfFramerateMode(e){},ResetPersisted(){for(const e of this._runtime.GetLayoutManager().GetAllLayouts())e.ResetPersistData()},SetPixelRounding(e){this._runtime.SetPixelRoundingEnabled(0!==e)},SetProjectSampling(e){this._runtime.SetSamplingMode(d.Gfx.RendererBase.SamplingNumberToMode(e+1))},SetAnisotropicFiltering(e){const t=this._runtime.GetCanvasManager();t&&t.SetAnisotropicFiltering([4,1,2,3,4,8,18][e])},SetFramerateMinMax(e,t){this._runtime.SetMaxDt(1/e),this._runtime.SetMinDt(1/t)},SetDeltaTimeMinMax(e,t){this._runtime.SetMinDt(e),this._runtime.SetMaxDt(t)},SetFramerateMode(e,t){this._runtime._SetFramerateMode(["vsync","fixed","unlimited-tick","unlimited-frame"][e]),this._runtime._SetFixedFramerate(t)},SortZOrderByInstVar(e,t){if(!e)return;const n=e.GetCurrentSol().GetInstances(),r=S,a=p,i=this._runtime.GetCurrentLayout(),s=e.IsFamily(),o=e.GetFamilyIndex();for(let e=0,i=n.length;e0;c&&(s.IsCopyPicked()?o.PushCopySol(l):o.PushCleanSol(l));const h=[],g=o.FindFirstFunctionBlockParent(u);if(g){const e=g.GetFunctionParameters();for(let t=n,r=e.length;te.toString(),len:e=>"string"==typeof e?e.length:0,random(e,t){return void 0===t?this._runtime.Random()*e:this._runtime.Random()*(t-e)+e},choose(...e){return e[Math.floor(this._runtime.Random()*e.length)]},chooseindex:(e,...t)=>("number"!=typeof e&&(e=0),t[e=f.clamp(Math.floor(e),0,t.length-1)]),pi:()=>Math.PI,infinity:()=>1/0,sqrt:e=>Math.sqrt(e),abs:e=>Math.abs(e),round:e=>Math.round(e),roundtodp(e,t){t=Math.max(Math.floor(t),0);const n=Math.pow(10,t);return Math.round((e+Number.EPSILON)*n)/n},floor:e=>Math.floor(e),ceil:e=>Math.ceil(e),sign:e=>Math.sign(e),sin:e=>Math.sin(f.toRadians(e)),cos:e=>Math.cos(f.toRadians(e)),tan:e=>Math.tan(f.toRadians(e)),asin:e=>f.toDegrees(Math.asin(e)),acos:e=>f.toDegrees(Math.acos(e)),atan:e=>f.toDegrees(Math.atan(e)),exp:e=>Math.exp(e),ln:e=>Math.log(e),log10:e=>Math.log10(e),max(...e){let t=e[0];"number"!=typeof t&&(t=0);for(let n=1,r=e.length;nr&&(t=r))}return t},clamp:(e,t,n)=>f.clamp(e,t,n),distance:(e,t,n,r)=>f.distanceTo(e,t,n,r),distance3d:(e,t,n,r,a,i)=>f.distanceTo3d(e,t,n,r,a,i),angle:(e,t,n,r)=>f.toDegrees(f.angleTo(e,t,n,r)),lerp:(e,t,n)=>f.lerp(e,t,n),unlerp:(e,t,n)=>f.unlerp(e,t,n),qarp:(e,t,n,r)=>f.qarp(e,t,n,r),cubic:(e,t,n,r,a)=>f.cubic(e,t,n,r,a),cosp:(e,t,n)=>f.cosp(e,t,n),anglediff:(e,t)=>f.toDegrees(f.angleDiff(f.toRadians(e),f.toRadians(t))),anglelerp:(e,t,n)=>f.toDegrees(f.angleLerp(f.toRadians(e),f.toRadians(t),n)),anglerotate:(e,t,n)=>f.toDegrees(f.angleRotate(f.toRadians(e),f.toRadians(t),f.toRadians(n))),setbit:(e,t,n)=>(e|=0)&~(1<<(t|=0))|(n=0!==n?1:0)<(e|=0)^1<<(t|=0),getbit:(e,t)=>(e|=0)&1<<(t|=0)?1:0,newline:()=>"\n",uppercase:e=>"string"==typeof e?e.toUpperCase():"",lowercase:e=>"string"==typeof e?e.toLowerCase():"",left:(e,t)=>"string"==typeof e?e.substr(0,t):"",mid:(e,t,n)=>"string"!=typeof e?"":n<0?e.substr(t):e.substr(t,n),right:(e,t)=>"string"==typeof e?e.substr(Math.max(e.length-t,0)):"",trim:e=>"string"==typeof e?e.trim():"",tokenat(e,t,n){if("string"!=typeof e||"string"!=typeof n)return"";let r=e.split(n);return(t=Math.floor(t))<0||t>=r.length?"":r[t]},tokencount:(e,t)=>"string"==typeof e&&"string"==typeof t&&e.length?e.split(t).length:0,find:(e,t)=>"string"==typeof e&&"string"==typeof t?e.search(new RegExp(f.EscapeRegex(t),"i")):-1,findcase:(e,t)=>"string"==typeof e&&"string"==typeof t?e.search(new RegExp(f.EscapeRegex(t),"")):-1,replace:(e,t,n)=>"string"==typeof e&&"string"==typeof t&&"string"==typeof n?e.replace(new RegExp(f.EscapeRegex(t),"gi"),n):"string"==typeof e?e:"",stringsub(e,...t){let n=e;for(let e=0,r=t.length;e=a.length?"":a[r]},zeropad(e,t){let n=e<0?"-":"";e<0&&(e=-e);const r=t-e.toString().length;return n+="0".repeat(Math.max(r,0)),n+e.toString()},urlencode:e=>encodeURIComponent(e),urldecode:e=>decodeURIComponent(e),dt(){return this._runtime._GetDtFast()},wallclockdt(){return this._runtime.GetDt1()},timescale(){return this._runtime.GetTimeScale()},wallclocktime(){return(Date.now()-this._runtime.GetStartTime())/1e3},unixtime:()=>Date.now(),time(){return this._runtime.GetGameTime()},tickcount(){return this._runtime.GetTickCount()},objectcount(){return this._runtime.GetObjectCount()},fps(){return this._runtime.GetFramesPerSecond()},cpuutilisation(){return this._runtime.GetMainThreadTime()},gpuutilisation(){return this._runtime.GetGPUUtilisation()},windowwidth(){return this._runtime.GetCanvasManager().GetDeviceWidth()},windowheight(){return this._runtime.GetCanvasManager().GetDeviceHeight()},originalwindowwidth(){return this._runtime.GetOriginalViewportWidth()},originalwindowheight(){return this._runtime.GetOriginalViewportHeight()},originalviewportwidth(){return this._runtime.GetOriginalViewportWidth()},originalviewportheight(){return this._runtime.GetOriginalViewportHeight()},scrollx(){return this._runtime.GetCurrentLayout().GetScrollX()},scrolly(){return this._runtime.GetCurrentLayout().GetScrollY()},layoutname(){return this._runtime.GetCurrentLayout().GetName()},layoutscale(){return this._runtime.GetCurrentLayout().GetScale()},layoutangle(){return f.toDegrees(this._runtime.GetCurrentLayout().GetAngle())},layoutwidth(){return this._runtime.GetCurrentLayout().GetWidth()},layoutheight(){return this._runtime.GetCurrentLayout().GetHeight()},vanishingpointx(){return 100*this._runtime.GetCurrentLayout().GetVanishingPointX()},vanishingpointy(){return 100*this._runtime.GetCurrentLayout().GetVanishingPointY()},viewportleft(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().getLeft():0},viewporttop(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().getTop():0},viewportright(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().getRight():0},viewportbottom(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().getBottom():0},viewportwidth(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().width():0},viewportheight(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetViewport3D().height():0},viewportmidx(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);if(t){const e=t.GetViewport3D();return(e.getLeft()+e.getRight())/2}return 0},viewportmidy(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);if(t){const e=t.GetViewport3D();return(e.getTop()+e.getBottom())/2}return 0},canvastolayerx(e,t,n){const r=this._runtime.GetCurrentLayout().GetLayer(e);return r?r.CanvasCssToLayer(t,n)[0]:0},canvastolayery(e,t,n){const r=this._runtime.GetCurrentLayout().GetLayer(e);return r?r.CanvasCssToLayer(t,n)[1]:0},layertocanvasx(e,t,n){const r=this._runtime.GetCurrentLayout().GetLayer(e);return r?r.LayerToCanvasCss(t,n)[0]:0},layertocanvasy(e,t,n){const r=this._runtime.GetCurrentLayout().GetLayer(e);return r?r.LayerToCanvasCss(t,n)[1]:0},layertolayerx(e,t,n,r){const a=this._runtime.GetCurrentLayout(),i=a.GetLayer(e),s=a.GetLayer(t);if(!i||!s||i===s)return n;const[o,u]=i.LayerToCanvasCss(n,r);return s.CanvasCssToLayer(o,u)[0]},layertolayery(e,t,n,r){const a=this._runtime.GetCurrentLayout(),i=a.GetLayer(e),s=a.GetLayer(t);if(!i||!s||i===s)return r;const[o,u]=i.LayerToCanvasCss(n,r);return s.CanvasCssToLayer(o,u)[1]},layerscale(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetOwnScale():0},layerangle(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?f.toDegrees(t.GetOwnAngle()):0},layeropacity(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?100*t.GetOpacity():0},layerscalerate(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetScaleRate():0},layerscrollx(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetScrollX():0},layerscrolly(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetScrollY():0},layerparallaxx(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?100*t.GetParallaxX():0},layerparallaxy(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?100*t.GetParallaxY():0},layerzelevation(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetZElevation():0},layerindex(e){const t=this._runtime.GetCurrentLayout().GetLayer(e);return t?t.GetIndex():-1},canvassnapshot(){const e=this._runtime.GetCanvasManager();return e?e.GetCanvasSnapshotUrl():""},loopindex(e){const t=this._loopStack;if(!t.IsInLoop())return 0;if(e){const n=t.FindByName(e);return n?n.GetIndex():0}return t.GetCurrent().GetIndex()},savestatejson(){return this._runtime.GetLastSaveJsonString()},callmapped(e,t,...n){const r=this._GetFunctionMap(e.toLowerCase(),!1);if(!r)return console.warn(`[Construct] Call mapped function: map name '${e}' not found; returning 0`),0;let a=r.strMap.get(t.toLowerCase());if(!a){if(!r.defaultFunc)return console.warn(`[Construct] Call mapped function: no function associated with map '${e}' string '${t}'; returning 0 (consider setting a default)`),0;a=r.defaultFunc}const i=a.GetReturnType(),s=a.GetDefaultReturnValue();if(0===i)return console.warn(`[Construct] Call mapped function: map '${e}' string '${t}' has no return type so cannot be called from an expression; returning 0`),0;if(!a.IsEnabled())return s;const o=this._runtime.GetEventSheetManager(),u=o.GetCurrentEvent().GetSolModifiersIncludingParents(),l=u.length>0;l&&(a.IsCopyPicked()?o.PushCopySol(u):o.PushCleanSol(u));const c=a.GetFunctionParameters();for(let e=n.length,t=c.length;ef.PackRGB(e,t,n),rgbex:(e,t,n)=>f.PackRGBEx(e/100,t/100,n/100),rgba:(e,t,n,r)=>f.PackRGBAEx(e/100,t/100,n/100,r/100),rgbex255:(e,t,n)=>f.PackRGBEx(e/255,t/255,n/255),rgba255:(e,t,n,r)=>f.PackRGBAEx(e/255,t/255,n/255,r/255),hexcolor:e=>(C.setRgba(0,0,0,1),C.parseHexString(e),f.PackRGBAEx(C.getR(),C.getG(),C.getB(),C.getA())),colortohexstring:e=>(C.setFromRgbValue(e),C.toHexString(1!==C.getA())),projectname(){return this._runtime.GetProjectName()},projectversion(){return this._runtime.GetProjectVersion()},projectid(){return this._runtime.GetAppId()},projectuniqueid(){return this._runtime.GetProjectUniqueId()},currenteventsheetname(){return this._runtime.GetCurrentEvent().GetEventSheet().GetName()},currenteventnumber(){return this._runtime.GetCurrentEvent().GetDisplayNumber()},projectfilecount(){return this._runtime.GetAssetManager().GetExportedFileList().length},projectfilenameat(e){e=Math.floor(e);const t=this._runtime.GetAssetManager().GetExportedFileList();return e<0||e>=t.length?"":t[e].name}}} } // scripts/plugins/Sprite/c3runtime/runtime.js { {const t=self.C3;t.Plugins.Sprite=class extends t.SDKPluginBase{constructor(t){super(t)}Release(){super.Release()}}}{const t=self.C3,e=self.C3X,n=[];t.Plugins.Sprite.Type=class extends t.SDKTypeBase{constructor(t){super(t),this._animations=t.GetAnimations()}Release(){t.clearArray(this._animations),super.Release()}OnCreate(){for(const t of this._animations)t.LoadAllAssets(this._runtime)}LoadTextures(t){return Promise.all(this._animations.map(e=>e.LoadAllTextures(t)))}ReleaseTextures(){for(const t of this._animations)t.ReleaseAllTextures()}OnDynamicTextureLoadComplete(){this._UpdateAllCurrentTexture()}_UpdateAllCurrentTexture(){for(const t of this._objectClass.instancesIncludingPendingCreate())t.GetSdkInstance()._UpdateCurrentTexture()}FinishCondition(e){t.Plugins.Sprite.FinishCollisionCondition(this,e)}BeforeRunAction(t){n.push({objectClass:null,createHierarchy:!1,instances:[]})}_SpawnPickInstance(t,e,i){const r=n.at(-1);r.objectClass=t,r.createHierarchy=i,r.instances.push(e)}AfterRunAction(t){const e=n.pop(),i=e.objectClass,r=e.createHierarchy;if(!i)return;const a=new Map;for(const t of e.instances)t.CollectInstancesToPick(a,i,r);for(const[t,e]of a)t.GetCurrentSol().SetSetPicked(e)}_AddAnimation(t){const e=this.GetObjectClass().AddAnimation(t),n=this.GetRuntime();return e.GetFrameAt(0).GetImageInfo().LoadStaticTexture(n.GetRenderer()).then(()=>this._UpdateAllCurrentTexture()),e}_RemoveAnimation(t){for(const e of this._objectClass.instancesIncludingPendingCreate())e.GetSdkInstance()._OnAnimationRemoved(t);this.GetObjectClass().RemoveAnimation(t)}_AddAnimationFrame(e,n){const i=this._objectClass.GetAnimationByName(e);if(!i)throw new Error(`cannot find animation name '${e}'`);let r=i.FrameTagOrIndexToIndex(n);r<0&&(r+=i.GetFrameCount()+1);const a=t.AnimationFrameInfo.CreateDynamic(this.GetRuntime());i.InsertFrameAt(a,r);const s=this.GetRuntime();a.GetImageInfo().LoadStaticTexture(s.GetRenderer()).then(()=>this._UpdateAllCurrentTexture());for(const t of this._objectClass.instancesIncludingPendingCreate())t.GetSdkInstance()._OnAnimationFramesChanged();return a}_RemoveAnimationFrame(t,e){const n=this._objectClass.GetAnimationByName(t);if(!n)throw new Error(`cannot find animation name '${t}'`);if(1===n.GetFrameCount())throw new Error(`cannot remove last frame from animation '${t}'`);let i=n.FrameTagOrIndexToIndex(e);i<0&&(i+=n.GetFrameCount()),n.RemoveFrameAt(i);for(const t of this._objectClass.instancesIncludingPendingCreate())t.GetSdkInstance()._OnAnimationFramesChanged()}GetScriptInterfaceClass(){return self.ISpriteObjectType}};const i=new WeakMap;self.ISpriteObjectType=class extends self.IObjectType{constructor(t){super(t),i.set(this,t.GetSdkType())}getAnimation(t){e.RequireString(t);const n=i.get(this).GetObjectClass().GetAnimationByName(t);return n?n.GetIAnimation():null}getAllAnimations(){return i.get(this).GetObjectClass().GetAllAnimations().map(t=>t.GetIAnimation())}addAnimation(t){return e.RequireString(t),i.get(this)._AddAnimation(t).GetIAnimation()}removeAnimation(t){e.RequireString(t),i.get(this)._RemoveAnimation(t)}addAnimationFrame(t,n){if(e.RequireString(t),"number"!=typeof n&&"string"!=typeof n)throw new TypeError("invalid insert location");return i.get(this)._AddAnimationFrame(t,n).GetIAnimationFrame()}removeAnimationFrame(t,n){if(e.RequireString(t),"number"!=typeof n&&"string"!=typeof n)throw new TypeError("invalid insert location");i.get(this)._RemoveAnimationFrame(t,n)}}}{const t=self.C3,e=self.C3X,n=0,i=1,r=2,a=3,s=t.New(t.Quad2D),o=t.New(t.Vector2),m=1,h=2,u=4;t.Plugins.Sprite.Instance=class extends t.SDKWorldInstanceBase{constructor(e,s){super(e);let o=!0,u="",c=0,l=!0;s&&(o=!!s[n],u=s[i],c=s[r],l=s[a]),this._currentAnimation=this._objectClass.GetAnimationByName(u)||this._objectClass.GetAnimations()[0],this._currentFrameIndex=t.clamp(c,0,this._currentAnimation.GetFrameCount()-1),this._currentAnimationFrame=this._currentAnimation.GetFrameAt(this._currentFrameIndex);const d=this._currentAnimationFrame.GetImageInfo();this._currentTexture=d.GetTexture(),this._currentRcTex=d.GetTexRect(),this._currentQuadTex=d.GetTexQuad(),this.HandleRendererContextLoss(),e.SetFlag(h,!0),e.SetFlag(m,this._currentAnimation.GetSpeed()>=0),this._currentAnimationSpeed=Math.abs(this._currentAnimation.GetSpeed()),this._currentAnimationRepeatTo=this._currentAnimation.GetRepeatTo(),this._animationTimer=t.New(t.KahanSum),this._frameStartTime=0,this._animationRepeats=0,this._animTriggerName="",this._changeAnimFrameIndex=-1,this._changeAnimationName="",this._changeAnimationFrom=0;const g=this.GetWorldInfo();this._bquadRef=g.GetBoundingQuad(),g.SetVisible(o),g.SetCollisionEnabled(l),g.SetOriginX(this._currentAnimationFrame.GetOriginX()),g.SetOriginY(this._currentAnimationFrame.GetOriginY()),g.SetSourceCollisionPoly(this._currentAnimationFrame.GetCollisionPoly()),g.SetBboxChanged(),1===this._objectClass.GetAnimationCount()&&1===this._objectClass.GetAnimations()[0].GetFrameCount()||0===this._currentAnimationSpeed||this._StartTicking()}Release(){this._currentAnimation=null,this._currentAnimationFrame=null,this._currentTexture=null,this._animationTimer=null,super.Release()}GetCurrentImageInfo(){return this._currentAnimationFrame.GetImageInfo()}IsOriginalSizeKnown(){return!0}OnRendererContextLost(){this._currentTexture=null}OnRendererContextRestored(){this._UpdateCurrentTexture()}Draw(t){const e=this._currentTexture;if(null===e)return;const n=this.GetWorldInfo();t.SetTexture(e,n.GetActiveSampling()),n.HasMesh()?this._DrawMesh(n,t):this._DrawStandard(n,t)}_DrawStandard(t,e){let n=this._bquadRef;this._runtime.IsPixelRoundingEnabled()&&(n=t.PixelRoundQuad(n)),e.Quad4(n,this._currentQuadTex)}_DrawMesh(t,e){const n=t.GetTransformedMesh();if(t.IsMeshChanged()){t.CalculateBbox(null,s,!1);let e=s;this._runtime.IsPixelRoundingEnabled()&&(e=t.PixelRoundQuad(e)),n.CalculateTransformedMesh(t.GetSourceMesh(),e,this._currentQuadTex),t.SetMeshChanged(!1)}n.Draw(e,t.GetTotalZ())}GetAnimationTime(){return this._animationTimer.Get()}IsAnimationPlaying(){return this._inst.GetFlag(h)}SetAnimationPlaying(t){this._inst.SetFlag(h,t)}IsPlayingForwards(){return this._inst.GetFlag(m)}SetPlayingForwards(t){this._inst.SetFlag(m,t)}IsInAnimationTrigger(){return this._inst.GetFlag(u)}SetInAnimationTrigger(t){this._inst.SetFlag(u,t)}Tick(){this._changeAnimationName&&this._DoChangeAnimation(),this._changeAnimFrameIndex>=0&&this._DoChangeAnimFrame();const e=this._currentAnimationSpeed;if(!this.IsAnimationPlaying()||0===e)return void this._StopTicking();const n=this._runtime.GetDt(this._inst);this._animationTimer.Add(n);const i=this.GetAnimationTime(),r=this._currentAnimationFrame,a=r.GetDuration()/e;if(i=m&&(c?(this.SetPlayingForwards(!1),this._currentFrameIndex=m-2):u?this._currentFrameIndex=o:(this._animationRepeats++,this._animationRepeats>=h?this._FinishAnimation(!1):this._currentFrameIndex=o)),this._currentFrameIndex<0&&(c?(this._currentFrameIndex=1,this.SetPlayingForwards(!0),u||(this._animationRepeats++,this._animationRepeats>=h&&this._FinishAnimation(!0))):u?this._currentFrameIndex=o:(this._animationRepeats++,this._animationRepeats>=h?this._FinishAnimation(!0):this._currentFrameIndex=o)),this._currentFrameIndex=t.clamp(this._currentFrameIndex,0,m-1);const l=s.GetFrameAt(this._currentFrameIndex);i>this._frameStartTime+l.GetDuration()/e&&(this._frameStartTime=i),this._OnFrameChanged(r,l)}_FinishAnimation(e){this._currentFrameIndex=e?0:this._currentAnimation.GetFrameCount()-1,this.SetAnimationPlaying(!1),this._animTriggerName=this._currentAnimation.GetName(),this.SetInAnimationTrigger(!0),this.DispatchScriptEvent("animationend",!1,{animationName:this._animTriggerName}),this.Trigger(t.Plugins.Sprite.Cnds.OnAnyAnimFinished),this.Trigger(t.Plugins.Sprite.Cnds.OnAnimFinished),this.SetInAnimationTrigger(!1),this._animationRepeats=0}_OnFrameChanged(e,n,i){if(e===n)return;const r=this.GetWorldInfo(),a=e.GetImageInfo(),s=n.GetImageInfo(),o=a.GetWidth(),m=a.GetHeight(),h=s.GetWidth(),u=s.GetHeight();i&&i.onFrameChange?i.onFrameChange(r,o,m,h,u):(o!==h&&r.SetWidth(r.GetWidth()*(h/o)),m!==u&&r.SetHeight(r.GetHeight()*(u/m))),r.SetOriginX(n.GetOriginX()),r.SetOriginY(n.GetOriginY()),r.SetSourceCollisionPoly(n.GetCollisionPoly()),r.SetBboxChanged(),this._currentAnimationFrame=n,this._currentTexture=s.GetTexture(),this._currentRcTex=s.GetTexRect(),this._currentQuadTex=s.GetTexQuad();const c=this.GetInstance().GetBehaviorInstances();for(let t=0,i=c.length;t1&&this._currentAnimationSpeed>0&&this._StartTicking()}_GetAnimFrame(){return this._currentFrameIndex}_GetAnimFrameTag(){return this._currentAnimationFrame.GetTag()}_SetAnimSpeed(t){this._currentAnimationSpeed=Math.abs(t),this.SetPlayingForwards(t>=0),this._currentAnimationSpeed>0&&this._StartTicking()}_GetAnimSpeed(){return this.IsPlayingForwards()?this._currentAnimationSpeed:-this._currentAnimationSpeed}_SetAnimRepeatToFrame(e){"string"==typeof e&&-1===(e=this._currentAnimation.GetFrameIndexByTag(e))||(e=t.clamp(Math.floor(e),0,this._currentAnimation.GetFrameCount()-1),this._currentAnimationRepeatTo=e)}_GetAnimRepeatToFrame(){return this._currentAnimationRepeatTo}_DoChangeAnimation(e){const n=this._currentAnimationFrame,i=this._objectClass.GetAnimationByName(this._changeAnimationName);if(this._changeAnimationName="",!i)return;if(i===this._currentAnimation&&this.IsAnimationPlaying())return;this._currentAnimation=i,this.SetPlayingForwards(i.GetSpeed()>=0),this._currentAnimationSpeed=Math.abs(i.GetSpeed()),this._currentAnimationRepeatTo=i.GetRepeatTo(),this._currentFrameIndex=t.clamp(this._currentFrameIndex,0,this._currentAnimation.GetFrameCount()-1),1===this._changeAnimationFrom&&(this._currentFrameIndex=0),this.SetAnimationPlaying(!0),this._frameStartTime=this.GetAnimationTime();const r=this._currentAnimation.GetFrameAt(this._currentFrameIndex);this._OnFrameChanged(n,r,e)}_DoChangeAnimFrame(e){const n=this._currentAnimationFrame,i=this._currentFrameIndex;if(this._currentFrameIndex=t.clamp(Math.floor(this._changeAnimFrameIndex),0,this._currentAnimation.GetFrameCount()-1),this._changeAnimFrameIndex=-1,!e&&i===this._currentFrameIndex)return;const r=this._currentAnimation.GetFrameAt(this._currentFrameIndex);this._OnFrameChanged(n,r),this._frameStartTime=this.GetAnimationTime()}_UpdateCurrentTexture(){const t=this._currentAnimationFrame.GetImageInfo();this._currentTexture=t.GetTexture(),this._currentRcTex=t.GetTexRect(),this._currentQuadTex=t.GetTexQuad(),this.GetWorldInfo().SetMeshChanged(!0)}GetTexture(){return this._currentTexture}GetTexRect(){return this._currentRcTex}GetTexQuad(){return this._currentQuadTex}GetImagePointCount(){return this._currentAnimationFrame.GetImagePointCount()}GetImagePoint(t){const e=this._currentAnimationFrame,n=this.GetWorldInfo();let i=null;if("string"==typeof t)i=e.GetImagePointByName(t);else{if("number"!=typeof t)throw new TypeError("expected string or number");i=e.GetImagePointByIndex(t-1)}let r=n.GetTotalZ();if(!i)return[n.GetX(),n.GetY(),r];if(o.copy(i.GetVec2()),n.HasMesh()){const[t,e,i]=n.GetSourceMesh().TransformPoint(o.getX(),o.getY());o.set(t,e),r+=i}return o.offset(-e.GetOriginX(),-e.GetOriginY()),o.scale(n.GetWidth(),n.GetHeight()),o.rotate(n.GetAngle()),o.offset(n.GetX(),n.GetY()),[o.getX(),o.getY(),r]}GetCollisionPolyPointCount(){return this.GetWorldInfo().GetTransformedCollisionPoly().pointCount()}GetCollisionPolyPoint(t){t=Math.floor(t);const e=this.GetWorldInfo(),n=e.GetTransformedCollisionPoly(),i=n.pointCount();if(t===i&&(t=0),t<0||t>=i)return[0,0];const r=n.pointsArr();return[r[2*t+0]+e.GetX(),r[2*t+1]+e.GetY()]}GetDebuggerProperties(){const e=t.Plugins.Sprite.Acts,n="plugins.sprite.debugger.animation-properties";return[{title:n+".title",properties:[{name:n+".current-animation",value:this._currentAnimation.GetName(),onedit:t=>this.CallAction(e.SetAnim,t,0)},{name:n+".current-frame",value:this._currentFrameIndex,onedit:t=>this.CallAction(e.SetAnimFrame,t)},{name:n+".is-playing",value:this.IsAnimationPlaying(),onedit:t=>t?this.CallAction(e.StartAnim,0):this.CallAction(e.StopAnim)},{name:n+".speed",value:this._currentAnimationSpeed,onedit:t=>this.CallAction(e.SetAnimSpeed,t)},{name:n+".repeats",value:this._animationRepeats,onedit:t=>this._animationRepeats=t}]}]}SaveToJson(){const t={"a":this._currentAnimation.GetSID()};0!==this._frameStartTime&&(t["fs"]=this._frameStartTime);const e=this.GetAnimationTime();0!==e&&(t["at"]=e),0!==this._currentFrameIndex&&(t["f"]=this._currentFrameIndex),0!==this._currentAnimationSpeed&&(t["cas"]=this._currentAnimationSpeed),1!==this._animationRepeats&&(t["ar"]=this._animationRepeats),0!==this._currentAnimationRepeatTo&&(t["rt"]=this._currentAnimationRepeatTo),this.IsAnimationPlaying()||(t["ap"]=this.IsAnimationPlaying()),this.IsPlayingForwards()||(t["af"]=this.IsPlayingForwards());const n=this.GetWorldInfo();return n.IsCollisionEnabled()&&(t["ce"]=n.IsCollisionEnabled()),t}LoadFromJson(e){const n=this.GetObjectClass().GetAnimationBySID(e["a"]);n&&(this._currentAnimation=n),this._frameStartTime=e.hasOwnProperty("fs")?e["fs"]:0,this._animationTimer.Set(e.hasOwnProperty("at")?e["at"]:0);const i=e.hasOwnProperty("f")?e["f"]:0;this._currentFrameIndex=t.clamp(i,0,this._currentAnimation.GetFrameCount()-1),this._currentAnimationSpeed=e.hasOwnProperty("cas")?e["cas"]:0,this._animationRepeats=e.hasOwnProperty("ar")?e["ar"]:1;const r=e.hasOwnProperty("rt")?e["rt"]:0;this._currentAnimationRepeatTo=t.clamp(r,0,this._currentAnimation.GetFrameCount()-1),this.SetAnimationPlaying(!e.hasOwnProperty("ap")||!!e["ap"]),this.SetPlayingForwards(!e.hasOwnProperty("af")||!!e["af"]);const a=this._currentAnimation.GetFrameAt(this._currentFrameIndex);this._currentAnimationFrame=a,this._UpdateCurrentTexture();const s=this.GetWorldInfo();s.SetOriginX(a.GetOriginX()),s.SetOriginY(a.GetOriginY()),s.SetSourceCollisionPoly(a.GetCollisionPoly()),s.SetCollisionEnabled(!!e["ce"]),this.IsAnimationPlaying()&&this._StartTicking()}GetPropertyValueByIndex(e){const n=this.GetWorldInfo();switch(e){case a:return n.IsCollisionEnabled();case r:return t.clamp(this._currentFrameIndex,0,this._currentAnimation.GetFrameCount()-1);case i:return this._currentAnimation.GetName()}}SetPropertyValueByIndex(e,n,s){const o=this.GetWorldInfo();switch(e){case a:o.SetCollisionEnabled(!!n);break;case r:if(s.isChunkDiscreteLike){if(!s.keyframeReached)return;{const e=this._currentAnimation.GetFrameCount()-1,i=n=t.clamp(n,0,e),r=this._currentAnimation.GetFrameAt(this._currentFrameIndex),a=this._currentAnimation.GetFrameAt(i);this._OnFrameChanged(r,a,s),this._currentFrameIndex=t.clamp(i,0,e)}}else{this.SetAnimationPlaying(!1);const e=this._currentAnimation.GetFrameCount()-1,i=n=t.clamp(n,0,e),r=this._currentAnimation.GetFrameAt(this._currentFrameIndex),a=this._currentAnimation.GetFrameAt(i);this._OnFrameChanged(r,a,s),this._currentFrameIndex=t.clamp(i,0,e)}break;case i:this._changeAnimationName=n,this._changeAnimationFrom=s?.startFrom??0,this._DoChangeAnimation(s);this._currentAnimation.GetFrameCount()>1&&this._currentAnimation.GetSpeed()>0?this._StartTicking():this._StopTicking();break}}GetScriptInterfaceClass(){return self.ISpriteInstance}};const c=new WeakMap,l=new Map([["current-frame",0],["beginning",1]]);self.ISpriteInstance=class extends self.IWorldInstance{constructor(){super(),c.set(this,self.IInstance._GetInitInst().GetSdkInstance())}getImagePointCount(){return c.get(this).GetImagePointCount()}getImagePointX(t){return this.getImagePoint(t)[0]}getImagePointY(t){return this.getImagePoint(t)[1]}getImagePointZ(t){return this.getImagePoint(t)[2]}getImagePoint(t){if("string"!=typeof t&&"number"!=typeof t)throw new TypeError("expected string or number");return c.get(this).GetImagePoint(t)}getPolyPointCount(){return c.get(this).GetCollisionPolyPointCount()}getPolyPointX(t){return e.RequireFiniteNumber(t),c.get(this).GetCollisionPolyPoint(t)[0]}getPolyPointY(t){return e.RequireFiniteNumber(t),c.get(this).GetCollisionPolyPoint(t)[1]}getPolyPoint(t){return e.RequireFiniteNumber(t),c.get(this).GetCollisionPolyPoint(t)}stopAnimation(){c.get(this).SetAnimationPlaying(!1)}startAnimation(t="current-frame"){e.RequireString(t);const n=l.get(t);if(void 0===n)throw new Error("invalid mode");c.get(this)._StartAnim(n)}setAnimation(t,n="beginning"){e.RequireString(t),e.RequireString(n);const i=l.get(n);if(void 0===i)throw new Error("invalid mode");const r=c.get(this);if(!r.GetObjectClass().GetAnimationByName(t))throw new Error(`animation name "${t}" does not exist`);r._SetAnim(t,i)}getAnimation(t){e.RequireString(t);const n=c.get(this).GetObjectClass().GetAnimationByName(t);return n?n.GetIAnimation():null}get animation(){return c.get(this)._GetCurrentAnimation().GetIAnimation()}get animationName(){return c.get(this)._GetCurrentAnimationName()}set animationFrame(t){e.RequireFiniteNumber(t),c.get(this)._SetAnimFrame(t)}get animationFrame(){return c.get(this)._GetAnimFrame()}set animationFrameTag(t){e.RequireString(t),c.get(this)._SetAnimFrame(t)}get animationFrameTag(){return c.get(this)._GetAnimFrameTag()}set animationSpeed(t){e.RequireFiniteNumber(t),c.get(this)._SetAnimSpeed(t)}get animationSpeed(){return c.get(this)._GetAnimSpeed()}set animationRepeatToFrame(t){e.RequireFiniteNumber(t),c.get(this)._SetAnimRepeatToFrame(t)}get animationRepeatToFrame(){return c.get(this)._GetAnimRepeatToFrame()}get imageWidth(){return c.get(this).GetCurrentImageInfo().GetWidth()}get imageHeight(){return c.get(this).GetCurrentImageInfo().GetHeight()}getImageSize(){const t=c.get(this).GetCurrentImageInfo();return[t.GetWidth(),t.GetHeight()]}async replaceCurrentAnimationFrame(n){e.RequireInstanceOf(n,Blob);const i=c.get(this),r=i.GetRuntime(),a=i.GetCurrentImageInfo(),s=t.New(t.ImageInfo);if(s.LoadDynamicBlobAsset(r,n),await s.LoadStaticTexture(r.GetRenderer()),i.WasReleased())return void s.Release();a.ReplaceWith(s);const o=i.GetSdkType();o._UpdateAllCurrentTexture(),o.GetObjectClass().Dispatcher().dispatchEvent(new t.Event("animationframeimagechange")),r.UpdateRender()}setSolidCollisionFilter(e,n){"string"==typeof n&&(n=t.splitStringAndNormalize(n)),c.get(this).GetWorldInfo().SetSolidCollisionFilter(!!e,n)}}}{const t=self.C3;t.Plugins.Sprite.Cnds={IsAnimPlaying(e){return t.equalsNoCase(this._GetCurrentAnimationName(),e)},CompareFrame(e,n){return t.compare(this._currentFrameIndex,e,n)},CompareFrameTag(e,n){if("string"!=typeof n)return!1;const i=this._currentAnimationFrame.GetTag();return t.compare(i.toLowerCase(),e,n.toLowerCase())},CompareAnimSpeed(e,n){return t.compare(this._GetAnimSpeed(),e,n)},OnAnimFinished(e){return t.equalsNoCase(this._animTriggerName,e)},OnAnyAnimFinished:()=>!0,OnFrameChanged:()=>!0,IsMirrored(){return this.GetWorldInfo().GetWidth()<0},IsFlipped(){return this.GetWorldInfo().GetHeight()<0},OnURLLoaded:()=>!0,OnURLFailed:()=>!0,IsCollisionEnabled(){return this.GetWorldInfo().IsCollisionEnabled()}}}{const t=self.C3;t.Plugins.Sprite.Acts={Spawn(t,e,n,i,r){if(!t||!e)return;const[a,s]=this.GetImagePoint(n),o=this._runtime.CreateInstance(t,e,a,s,i,r);if(!o)return;if(i&&e.SortAndAddInstancesByZIndex(o),t.GetPlugin().IsRotatable()){const t=o.GetWorldInfo();t.SetAngle(this.GetWorldInfo().GetAngle()),t.SetBboxChanged()}const m=this._runtime.GetEventSheetManager();m.BlockFlushingInstances(!0),o._TriggerOnCreatedOnSelfAndRelated(),m.BlockFlushingInstances(!1),t!==this._runtime.GetCurrentAction().GetObjectClass()&&this._sdkType._SpawnPickInstance(t,o,i)},StopAnim(){this.SetAnimationPlaying(!1)},StartAnim(t){this._StartAnim(t)},SetAnim(t,e){this._SetAnim(t,e)},SetAnimFrame(t){this._SetAnimFrame(t)},SetAnimSpeed(t){this._SetAnimSpeed(t)},SetAnimRepeatToFrame(t){this._SetAnimRepeatToFrame(t)},AddRemoveAnimation(t,e){try{0===t?this.GetSdkType()._AddAnimation(e):this.GetSdkType()._RemoveAnimation(e)}catch(e){console.error(`[Construct] Error ${0===t?"adding":"removing"} animation: `,e)}},AddRemoveAnimationFrame(t,e,n){try{0===t?this.GetSdkType()._AddAnimationFrame(e,n):this.GetSdkType()._RemoveAnimationFrame(e,n)}catch(e){console.error(`[Construct] Error ${0===t?"adding":"removing"} animation frame: `,e)}},SetMirrored(t){const e=this.GetWorldInfo(),n=e.GetWidth(),i=Math.abs(n)*(0===t?-1:1);n!==i&&(e.SetWidth(i),e.SetBboxChanged())},SetFlipped(t){const e=this.GetWorldInfo(),n=e.GetHeight(),i=Math.abs(n)*(0===t?-1:1);n!==i&&(e.SetHeight(i),e.SetBboxChanged())},SetScale(t){const e=this._currentAnimationFrame.GetImageInfo(),n=this.GetWorldInfo(),i=n.GetWidth()<0?-1:1,r=n.GetHeight()<0?-1:1,a=e.GetWidth()*t*i,s=e.GetHeight()*t*r;n.GetWidth()===a&&n.GetHeight()===s||(n.SetSize(a,s),n.SetBboxChanged())},async LoadURL(e,n,i){const r=this._currentAnimationFrame.GetImageInfo(),a=this.GetWorldInfo(),s=this._runtime,o=this._sdkType;if(r.GetURL()===e)return 0===n&&(a.SetSize(r.GetWidth(),r.GetHeight()),a.SetBboxChanged()),void this.Trigger(t.Plugins.Sprite.Cnds.OnURLLoaded);const m=t.New(t.ImageInfo);try{if(await m.LoadDynamicAsset(s,e),!m.IsLoaded())throw new Error("image failed to load");if(this.WasReleased())return void m.Release();await m.LoadStaticTexture(s.GetRenderer())}catch(e){return console.error("Load image from URL failed: ",e),void(this.WasReleased()||this.Trigger(t.Plugins.Sprite.Cnds.OnURLFailed))}this.WasReleased()?m.Release():(r.ReplaceWith(m),o._UpdateAllCurrentTexture(),o.GetObjectClass().Dispatcher().dispatchEvent(new t.Event("animationframeimagechange")),s.UpdateRender(),0===n&&(a.SetSize(r.GetWidth(),r.GetHeight()),a.SetBboxChanged()),await this.TriggerAsync(t.Plugins.Sprite.Cnds.OnURLLoaded))},SetCollisions(t){this.GetWorldInfo().SetCollisionEnabled(t)},SetSolidCollisionFilter(e,n){this.GetWorldInfo().SetSolidCollisionFilter(0===e,t.splitStringAndNormalize(n))},SetEffect(t){this.GetWorldInfo().SetBlendMode(t),this._runtime.UpdateRender()}}}self.C3.Plugins.Sprite.Exps={AnimationFrame(){return this._GetAnimFrame()},AnimationFrameTag(){return this._GetAnimFrameTag()},AnimationFrameCount(){return this._currentAnimation.GetFrameCount()},AnimationName(){return this._currentAnimation.GetName()},AnimationSpeed(){return this._GetAnimSpeed()},OriginalAnimationSpeed(){return this._currentAnimation.GetSpeed()},ImagePointX(t){return this.GetImagePoint(t)[0]},ImagePointY(t){return this.GetImagePoint(t)[1]},ImagePointZ(t){return this.GetImagePoint(t)[2]},ImagePointCount(){return this.GetImagePointCount()},ImageWidth(){return this.GetCurrentImageInfo().GetWidth()},ImageHeight(){return this.GetCurrentImageInfo().GetHeight()},PolyPointXAt(t){return this.GetCollisionPolyPoint(t)[0]},PolyPointYAt(t){return this.GetCollisionPolyPoint(t)[1]},PolyPointCount(){return this.GetCollisionPolyPointCount()}}; } // scripts/plugins/Touch/c3runtime/runtime.js { {const t=self.C3;t.Plugins.Touch=class extends t.SDKPluginBase{constructor(t){super(t)}Release(){super.Release()}}}{const e=self.C3,s=self.C3X;e.Plugins.Touch.Type=class extends e.SDKTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}GetScriptInterfaceClass(){return self.ITouchObjectType}};let i=null;function GetTouchSdkInstance(){return i.GetSingleGlobalInstance().GetSdkInstance()}self.ITouchObjectType=class extends self.IObjectType{constructor(t){super(t),i=t,t.GetRuntime()._GetCommonScriptInterfaces().touch=this}requestPermission(t){s.RequireString(t);const e=GetTouchSdkInstance();if("orientation"===t)return e._RequestPermission(0);if("motion"===t)return e._RequestPermission(1);throw new Error("invalid type")}}}{const n=self.C3,r="touch";n.Plugins.Touch.Instance=class extends n.SDKInstanceBase{constructor(t,e){super(t,r),this._touches=new Map,this._useMouseInput=!1,this._isMouseDown=!1,this._orientCompassHeading=0,this._orientAlpha=0,this._orientBeta=0,this._orientGamma=0,this._accX=0,this._accY=0,this._accZ=0,this._accWithGX=0,this._accWithGY=0,this._accWithGZ=0,this._triggerIndex=0,this._triggerId=0,this._triggerPermission=0,this._curTouchX=0,this._curTouchY=0,this._getTouchIndex=0,this._triggerType=0,this._permissionPromises=[],e&&(this._useMouseInput=e[0]),this.AddDOMMessageHandler("permission-result",t=>this._OnPermissionResult(t));const s=this.GetRuntime().Dispatcher();this._disposables=new n.CompositeDisposable(n.Disposable.From(s,"pointerdown",t=>this._OnPointerDown(t.data)),n.Disposable.From(s,"pointermove",t=>this._OnPointerMove(t.data)),n.Disposable.From(s,"pointerup",t=>this._OnPointerUp(t.data,!1)),n.Disposable.From(s,"pointercancel",t=>this._OnPointerUp(t.data,!0)),n.Disposable.From(s,"deviceorientation",t=>this._OnDeviceOrientation(t.data)),n.Disposable.From(s,"deviceorientationabsolute",t=>this._OnDeviceOrientationAbsolute(t.data)),n.Disposable.From(s,"devicemotion",t=>this._OnDeviceMotion(t.data)),n.Disposable.From(s,"tick2",t=>this._OnTick2()),n.Disposable.From(s,"advertevent",t=>this._OnAdvertEvent(t)))}Release(){this._touches.clear(),super.Release()}_OnPointerDown(t){if("mouse"===t["pointerType"]){if(!this._useMouseInput)return;this._isMouseDown=!0}const e=t["pointerId"];if(this._touches.has(e))return;const s=t["pageX"]-this._runtime.GetCanvasClientX(),i=t["pageY"]-this._runtime.GetCanvasClientY(),r=performance.now(),o=this._touches.size;this._triggerIndex=o,this._triggerId=e;const h=n.New(n.Plugins.Touch.TouchInfo);h.Init(r,s,i,e,o),this._touches.set(e,h),this.Trigger(n.Plugins.Touch.Cnds.OnNthTouchStart),this.Trigger(n.Plugins.Touch.Cnds.OnTouchStart),this._curTouchX=s,this._curTouchY=i,this._triggerType=0,this.Trigger(n.Plugins.Touch.Cnds.OnTouchObject)}_OnPointerMove(t){if("mouse"===t["pointerType"]&&!this._isMouseDown)return;const e=this._touches.get(t["pointerId"]);if(!e)return;const s=performance.now();if(s-e.GetTime()<2)return;const i=t["pageX"]-this._runtime.GetCanvasClientX(),n=t["pageY"]-this._runtime.GetCanvasClientY();e.Update(s,i,n,t["width"],t["height"],t["pressure"])}_OnPointerUp(t,e){if("mouse"===t["pointerType"]){if(!this._isMouseDown)return;this._isMouseDown=!1}const s=performance.now(),i=t["pointerId"],r=this._touches.get(i);if(r){if(this._triggerIndex=r.GetStartIndex(),this._triggerId=r.GetId(),!e){const e=t["pageX"]-this._runtime.GetCanvasClientX(),s=t["pageY"]-this._runtime.GetCanvasClientY();this._curTouchX=e,this._curTouchY=s,this._triggerType=1,this.Trigger(n.Plugins.Touch.Cnds.OnTouchObject)}if(this.Trigger(n.Plugins.Touch.Cnds.OnNthTouchEnd),this.Trigger(n.Plugins.Touch.Cnds.OnTouchEnd),!e){const t=r.ShouldTriggerTap(s);"single-tap"===t?(this.Trigger(n.Plugins.Touch.Cnds.OnTapGesture),this._curTouchX=r.GetX(),this._curTouchY=r.GetY(),this.Trigger(n.Plugins.Touch.Cnds.OnTapGestureObject)):"double-tap"===t&&(this.Trigger(n.Plugins.Touch.Cnds.OnDoubleTapGesture),this._curTouchX=r.GetX(),this._curTouchY=r.GetY(),this.Trigger(n.Plugins.Touch.Cnds.OnDoubleTapGestureObject))}r.Release(),this._touches.delete(i)}}_OnAdvertEvent(t){"banner"===t.advertType&&"visibility"===t.advertAction&&this._OnPointerCancel()}_OnPointerCancel(){if(this._touches&&0!==this._touches.size){for(const t of this._touches.values())this._triggerIndex=t.GetStartIndex(),this._triggerId=t.GetId(),this.Trigger(n.Plugins.Touch.Cnds.OnNthTouchEnd),this.Trigger(n.Plugins.Touch.Cnds.OnTouchEnd),t.Release();this._touches.clear()}}_RequestPermission(t){return this._PostToDOMMaybeSync("request-permission",{"type":t}),new Promise((e,s)=>{this._permissionPromises.push({type:t,resolve:e,reject:s})})}_OnPermissionResult(t){const e=t["result"],s=t["type"];this._triggerPermission=s;const i=this._permissionPromises.filter(t=>t.type===s);for(const t of i)t.resolve(e?"granted":"denied");this._permissionPromises=this._permissionPromises.filter(t=>t.type!==s),e?(this.Trigger(n.Plugins.Touch.Cnds.OnPermissionGranted),0===s?this._runtime.RequestDeviceOrientationEvent():this._runtime.RequestDeviceMotionEvent()):this.Trigger(n.Plugins.Touch.Cnds.OnPermissionDenied)}_OnDeviceOrientation(t){"number"==typeof t["webkitCompassHeading"]?this._orientCompassHeading=t["webkitCompassHeading"]:t["absolute"]&&(this._orientCompassHeading=t["alpha"]),this._orientAlpha=t["alpha"],this._orientBeta=t["beta"],this._orientGamma=t["gamma"]}_OnDeviceOrientationAbsolute(t){this._orientCompassHeading=t["alpha"]}_OnDeviceMotion(t){const e=t["acceleration"];e&&(this._accX=e["x"],this._accY=e["y"],this._accZ=e["z"]);const s=t["accelerationIncludingGravity"];s&&(this._accWithGX=s["x"],this._accWithGY=s["y"],this._accWithGZ=s["z"])}_OnTick2(){const t=performance.now();let e=0;for(const s of this._touches.values())s.GetTime()<=t-50&&s._SetLastTime(t),s.ShouldTriggerHold(t)&&(this._triggerIndex=s.GetStartIndex(),this._triggerId=s.GetId(),this._getTouchIndex=e,this.Trigger(n.Plugins.Touch.Cnds.OnHoldGesture),this._curTouchX=s.GetX(),this._curTouchY=s.GetY(),this.Trigger(n.Plugins.Touch.Cnds.OnHoldGestureObject),this._getTouchIndex=0),++e}_GetTouchByIndex(t){t=Math.floor(t);for(const e of this._touches.values()){if(0===t)return e;--t}return null}_IsClientPosOnCanvas(t,e){return t>=0&&e>=0&&t({name:"$"+t.GetId(),value:t.GetX()+", "+t.GetY()}))}]}}}{const o=self.C3;o.Plugins.Touch.Cnds={OnTouchStart:()=>!0,OnTouchEnd:()=>!0,IsInTouch(){return this._touches.size>0},OnTouchObject(t,e){return!!t&&(e===this._triggerType&&(!!this._IsClientPosOnCanvas(this._curTouchX,this._curTouchY)&&this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,[[this._curTouchX,this._curTouchY]],!1)))},IsTouchingObject(t){if(!t)return!1;const e=this._runtime.GetCurrentCondition().IsInverted(),s=[...this._touches.values()].filter(t=>this._IsClientPosOnCanvas(t.GetX(),t.GetY())).map(t=>[t.GetX(),t.GetY()]);return o.xor(this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,s,e),e)},CompareTouchSpeed(t,e,s){const i=this._GetTouchByIndex(t);return!!i&&o.compare(i.GetSpeed(),e,s)},OrientationSupported:()=>!0,MotionSupported:()=>!0,CompareOrientation(t,e,s){this._runtime.RequestDeviceOrientationEvent();let i=0;return i=0===t?this._orientAlpha:1===t?this._orientBeta:this._orientGamma,o.compare(i,e,s)},CompareAcceleration(t,e,s){this._runtime.RequestDeviceMotionEvent();let i=0;return i=0===t?this._accWithGX:1===t?this._accWithGY:2===t?this._accWithGZ:3===t?this._accX:4===t?this._accY:this._accZ,o.compare(i,e,s)},OnNthTouchStart(t){return(t=Math.floor(t))===this._triggerIndex},OnNthTouchEnd(t){return(t=Math.floor(t))===this._triggerIndex},HasNthTouch(t){return t=Math.floor(t),this._touches.size>=t+1},OnHoldGesture:()=>!0,OnTapGesture:()=>!0,OnDoubleTapGesture:()=>!0,OnHoldGestureObject(t){return!!t&&(!!this._IsClientPosOnCanvas(this._curTouchX,this._curTouchY)&&this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,[[this._curTouchX,this._curTouchY]],!1))},OnTapGestureObject(t){return!!t&&(!!this._IsClientPosOnCanvas(this._curTouchX,this._curTouchY)&&this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,[[this._curTouchX,this._curTouchY]],!1))},OnDoubleTapGestureObject(t){return!!t&&(!!this._IsClientPosOnCanvas(this._curTouchX,this._curTouchY)&&this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(t,[[this._curTouchX,this._curTouchY]],!1))},OnPermissionGranted(t){return this._triggerPermission===t},OnPermissionDenied(t){return this._triggerPermission===t}}}self.C3.Plugins.Touch.Acts={RequestPermission(t){this._RequestPermission(t)}};{const h=self.C3;h.Plugins.Touch.Exps={TouchCount(){return this._touches.size},X(t){const e=this._GetTouchByIndex(this._getTouchIndex);return e?e.GetPositionForLayer(this._runtime.GetCurrentLayout(),t,!0):0},Y(t){const e=this._GetTouchByIndex(this._getTouchIndex);return e?e.GetPositionForLayer(this._runtime.GetCurrentLayout(),t,!1):0},XAt(t,e){const s=this._GetTouchByIndex(t);return s?s.GetPositionForLayer(this._runtime.GetCurrentLayout(),e,!0):0},YAt(t,e){const s=this._GetTouchByIndex(t);return s?s.GetPositionForLayer(this._runtime.GetCurrentLayout(),e,!1):0},XForID(t,e){const s=this._touches.get(t);return s?s.GetPositionForLayer(this._runtime.GetCurrentLayout(),e,!0):0},YForID(t,e){const s=this._touches.get(t);return s?s.GetPositionForLayer(this._runtime.GetCurrentLayout(),e,!1):0},AbsoluteX(){const t=this._GetTouchByIndex(0);return t?t.GetX():0},AbsoluteY(){const t=this._GetTouchByIndex(0);return t?t.GetY():0},AbsoluteXAt(t){const e=this._GetTouchByIndex(t);return e?e.GetX():0},AbsoluteYAt(t){const e=this._GetTouchByIndex(t);return e?e.GetY():0},AbsoluteXForID(t){const e=this._touches.get(t);return e?e.GetX():0},AbsoluteYForID(t){const e=this._touches.get(t);return e?e.GetY():0},SpeedAt(t){const e=this._GetTouchByIndex(t);return e?e.GetSpeed():0},SpeedForID(t){const e=this._touches.get(t);return e?e.GetSpeed():0},AngleAt(t){const e=this._GetTouchByIndex(t);return e?h.toDegrees(e.GetAngle()):0},AngleForID(t){const e=this._touches.get(t);return e?h.toDegrees(e.GetAngle()):0},CompassHeading(){return this._runtime.RequestDeviceOrientationEvent(),this._orientCompassHeading},Alpha(){return this._runtime.RequestDeviceOrientationEvent(),this._orientAlpha},Beta(){return this._runtime.RequestDeviceOrientationEvent(),this._orientBeta},Gamma(){return this._runtime.RequestDeviceOrientationEvent(),this._orientGamma},AccelerationXWithG(){return this._runtime.RequestDeviceMotionEvent(),this._accWithGX},AccelerationYWithG(){return this._runtime.RequestDeviceMotionEvent(),this._accWithGY},AccelerationZWithG(){return this._runtime.RequestDeviceMotionEvent(),this._accWithGZ},AccelerationX(){return this._runtime.RequestDeviceMotionEvent(),this._accX},AccelerationY(){return this._runtime.RequestDeviceMotionEvent(),this._accY},AccelerationZ(){return this._runtime.RequestDeviceMotionEvent(),this._accZ},TouchIndex(){return this._triggerIndex},TouchID(){return this._triggerId},WidthForID(t){const e=this._touches.get(t);return e?e.GetWidth():0},HeightForID(t){const e=this._touches.get(t);return e?e.GetHeight():0},PressureForID(t){const e=this._touches.get(t);return e?e.GetPressure():0}}} } // scripts/plugins/Touch/c3runtime/touchInfo.js { const C3=self.C3,GESTURE_HOLD_THRESHOLD=15,GESTURE_HOLD_TIMEOUT=500,GESTURE_TAP_TIMEOUT=333,GESTURE_DOUBLETAP_THRESHOLD=25;let lastTapX=-1e3,lastTapY=-1e3,lastTapTime=-1e4;C3.Plugins.Touch.TouchInfo=class extends C3.DefendedBase{constructor(){super(),this._pointerId=0,this._startIndex=0,this._startTime=0,this._time=0,this._lastTime=0,this._startX=0,this._startY=0,this._x=0,this._y=0,this._lastX=0,this._lastY=0,this._width=0,this._height=0,this._pressure=0,this._hasTriggeredHold=!1,this._isTooFarForHold=!1}Release(){}Init(t,s,i,e,h){this._pointerId=e,this._startIndex=h,this._time=t,this._lastTime=t,this._startTime=t,this._startX=s,this._startY=i,this._x=s,this._y=i,this._lastX=s,this._lastY=i}Update(t,s,i,e,h,_){this._lastTime=this._time,this._time=t,this._lastX=this._x,this._lastY=this._y,this._x=s,this._y=i,this._width=e,this._height=h,this._pressure=_,!this._isTooFarForHold&&C3.distanceTo(this._startX,this._startY,this._x,this._y)>=15&&(this._isTooFarForHold=!0)}GetId(){return this._pointerId}GetStartIndex(){return this._startIndex}GetTime(){return this._time}_SetLastTime(t){this._lastTime=t}GetX(){return this._x}GetY(){return this._y}GetSpeed(){const t=C3.distanceTo(this._x,this._y,this._lastX,this._lastY),s=(this._time-this._lastTime)/1e3;return s>0?t/s:0}GetAngle(){return C3.angleTo(this._lastX,this._lastY,this._x,this._y)}GetWidth(){return this._width}GetHeight(){return this._height}GetPressure(){return this._pressure}ShouldTriggerHold(t){return!this._hasTriggeredHold&&(t-this._startTime>=500&&!this._isTooFarForHold&&C3.distanceTo(this._startX,this._startY,this._x,this._y)<15&&(this._hasTriggeredHold=!0,!0))}ShouldTriggerTap(t){return this._hasTriggeredHold?"":t-this._startTime<=333&&!this._isTooFarForHold&&C3.distanceTo(this._startX,this._startY,this._x,this._y)<15?t-lastTapTime<=666&&C3.distanceTo(lastTapX,lastTapY,this._x,this._y)<25?(lastTapX=-1e3,lastTapY=-1e3,lastTapTime=-1e4,"double-tap"):(lastTapX=this._x,lastTapY=this._y,lastTapTime=t,"single-tap"):""}GetPositionForLayer(t,s,i){if(void 0===s){return t.GetLayerByIndex(0).CanvasCssToLayer_DefaultTransform(this._x,this._y)[i?0:1]}{const e=t.GetLayer(s);return e?e.CanvasCssToLayer(this._x,this._y)[i?0:1]:0}}}; } // scripts/plugins/LocalStorage/c3runtime/runtime.js { {const e=self.C3;e.Plugins.LocalStorage=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const t=self.C3;t.Plugins.LocalStorage.Type=class extends t.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const s=self.C3,r="localstorage";s.Plugins.LocalStorage.Instance=class extends s.SDKInstanceBase{constructor(e,t){super(e,r),this._currentKey="",this._lastValue="",this._keyNamesList=[],this._errorMessage="",this._isPersistent=!1,this._pendingGets=0,this._pendingSets=0,this._isInMemoryOnly=!1,t&&(this._isInMemoryOnly=t[0]);const s=this._runtime._GetProjectStorage();this._storage=null,this._isInMemoryOnly?this._storage=s.createInstance({forceInMemoryFallback:!0}):this._storage=s,this._debugCache=new Map,this._isLoadingDebugCache=!1,this._runtime.AddLoadPromise(this._Init())}async _Init(){const e=await Promise.race([this.PostToDOMAsync("init"),s.Wait(3e3)]);e&&(this._isPersistent=e["isPersistent"])}Release(){super.Release()}async _TriggerStorageError(e){this._errorMessage=this._GetErrorString(e),await this.TriggerAsync(s.Plugins.LocalStorage.Cnds.OnError)}_GetErrorString(e){return e?"string"==typeof e?e:"string"==typeof e.message?e.message:"string"==typeof e.name?e.name:"string"==typeof e.data?e.data:"unknown error":"unknown error"}GetDebuggerProperties(){return this._isLoadingDebugCache||this._DebugCacheStorage(),[{title:"plugins.localstorage.name",properties:[...this._debugCache.entries()].map(e=>({name:"$"+e[0],value:e[1],onedit:t=>this._storage.setItem(e[0],t)}))}]}async _DebugCacheStorage(){this._isLoadingDebugCache=!0;try{const e=await this._storage.keys();e.sort((e,t)=>{const s=e.toLowerCase(),r=t.toLowerCase();return sthis._storage.getItem(e)));this._debugCache.clear();for(let s=0,r=e.length;s!0,OnItemGet(e){return this._currentKey===e},OnAnyItemGet:()=>!0,OnItemRemoved(e){return this._currentKey===e},OnAnyItemRemoved:()=>!0,OnCleared:()=>!0,OnAllKeyNamesLoaded:()=>!0,OnError:()=>!0,OnItemExists(e){return this._currentKey===e},OnItemMissing(e){return this._currentKey===e},CompareKey(e,t){return i.compare(this._currentKey,e,t)},CompareValue(e,t){return i.compare(this._lastValue,e,t)},IsProcessingSets(){return this._pendingSets>0},IsProcessingGets(){return this._pendingGets>0},OnAllSetsComplete:()=>!0,OnAllGetsComplete:()=>!0,IsPersistent(){return this._isPersistent}}}{const a=self.C3;function IsExpressionType(e){return"string"==typeof e||"number"==typeof e}a.Plugins.LocalStorage.Acts={async SetItem(e,t){this._pendingSets++;try{const s=await this._storage.setItem(e,t);await this.ScheduleTriggers(async()=>{this._currentKey=e,this._lastValue=s,await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemSet),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemSet)})}catch(e){await this._TriggerStorageError(e)}finally{this._pendingSets--,0===this._pendingSets&&await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllSetsComplete)}},async SetBinaryItem(e,t){if(!t)return;const s=t.GetFirstPicked(this._inst);if(!s)return;const r=s.GetSdkInstance();if(!r)return;const i=r.GetArrayBufferReadOnly();this._pendingSets++;try{await this._storage.setItem(e,i),await this.ScheduleTriggers(async()=>{this._currentKey=e,this._lastValue="",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemSet),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemSet)})}catch(e){await this._TriggerStorageError(e)}finally{this._pendingSets--,0===this._pendingSets&&await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllSetsComplete)}},async GetItem(e){this._pendingGets++;try{const t=await this._storage.getItem(e);await this.ScheduleTriggers(async()=>{this._currentKey=e,this._lastValue=IsExpressionType(t)?t:"",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemGet),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemGet)})}catch(e){await this._TriggerStorageError(e)}finally{this._pendingGets--,0===this._pendingGets&&await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllGetsComplete)}},async GetBinaryItem(e,t){if(!t)return;const s=t.GetFirstPicked(this._inst);if(!s)return;const r=s.GetSdkInstance();this._pendingGets++;try{let t=await this._storage.getItem(e);t=t instanceof ArrayBuffer?t:new ArrayBuffer(0),await this.ScheduleTriggers(async()=>{this._lastValue="",this._currentKey=e,r.SetArrayBufferTransfer(t),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemGet),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemGet)})}catch(e){await this._TriggerStorageError(e)}finally{this._pendingGets--,0===this._pendingGets&&await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllGetsComplete)}},async CheckItemExists(e){try{const t=await this._storage.getItem(e);await this.ScheduleTriggers(async()=>{this._currentKey=e,null==t?(this._lastValue="",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemMissing)):(this._lastValue=IsExpressionType(t)?t:"",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemExists))})}catch(e){await this._TriggerStorageError(e)}},async RemoveItem(e){try{await this._storage.removeItem(e),await this.ScheduleTriggers(async()=>{this._currentKey=e,this._lastValue="",await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAnyItemRemoved),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnItemRemoved)})}catch(e){await this._TriggerStorageError(e)}},async ClearStorage(){try{await this._storage.clear(),await this.ScheduleTriggers(async()=>{this._currentKey="",this._lastValue="",a.clearArray(this._keyNamesList),await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnCleared)})}catch(e){await this._TriggerStorageError(e)}},async GetAllKeyNames(){try{const e=await this._storage.keys();await this.ScheduleTriggers(async()=>{this._keyNamesList=e,await this.TriggerAsync(a.Plugins.LocalStorage.Cnds.OnAllKeyNamesLoaded)})}catch(e){await this._TriggerStorageError(e)}},async RequestPersistent(){const e=await this.PostToDOMAsync("request-persistent");e["isOk"]&&(this._isPersistent=e["isPersistent"])},LoadMemoryFromJSON(e){if(!this._isInMemoryOnly)return;let t;try{t=JSON.parse(e)}catch(e){return void console.error("[Local Storage] Failed to parse memory storage JSON: ",e)}t&&t["is-c3-storage"]&&Array.isArray(t["items"])||console.error("[Local Storage] Failed to load memory storage JSON: invalid data"),this._storage.SetMemoryStorage(new Map(t["items"]))}}}self.C3.Plugins.LocalStorage.Exps={ItemValue(){return this._lastValue},Key(){return this._currentKey},KeyCount(){return this._keyNamesList.length},KeyAt(e){return(e=Math.floor(e))<0||e>=this._keyNamesList.length?"":this._keyNamesList[e]},ErrorMessage(){return this._errorMessage},MemoryStorageAsJSON(){return this._isInMemoryOnly?JSON.stringify({"is-c3-storage":!0,"items":[...this._storage.GetMemoryStorage()]}):""}}; } // scripts/plugins/Audio/c3runtime/runtime.js { {const t=self.C3,e=[];t.Plugins.Audio=class extends t.SDKPluginBase{constructor(t){super(t)}_AddActionPromise(t){e.push(t)}static async WaitForAllActionPromises(){await Promise.all(e),t.clearArray(e)}Release(){super.Release()}}}{const s=self.C3,i=self.C3X;s.Plugins.Audio.Type=class extends s.SDKTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}GetScriptInterfaceClass(){return self.IAudioObjectType}};let a=null;function GetAudioSdkInstance(){return a.GetSingleGlobalInstance().GetSdkInstance()}function GetAudioDOMInterface(){if(self["C3Audio_DOMInterface"])return self["C3Audio_DOMInterface"];throw new Error("audio scripting API cannot be used here - make sure the project is using DOM mode, not worker mode")}self.IAudioObjectType=class extends self.IObjectType{constructor(t){super(t),a=t}get audioContext(){return GetAudioDOMInterface()["GetAudioContextExtern"]()}get destinationNode(){return GetAudioDOMInterface()["GetDestinationNodeExtern"]()}get isSilent(){return GetAudioSdkInstance()._IsSilent()}set isSilent(t){GetAudioSdkInstance()._SetSilent(t)}get masterVolume(){return GetAudioSdkInstance()._GetMasterVolume()}set masterVolume(t){i.RequireFiniteNumber(t),GetAudioSdkInstance()._SetMasterVolume(t)}stopAll(){GetAudioSdkInstance()._StopAll()}}}{const n=self.C3,r="audio",o=["interactive","balanced","playback"];n.Plugins.Audio.Instance=class extends n.SDKInstanceBase{constructor(t,e){super(t,r),this._nextPlayTime=0,this._nextPlayOffset=0,this._triggerTags=[],this._enableMultiTags=!0,this._timeScaleMode=0,this._saveLoadMode=0,this._playInBackground=!1,this._panningModel=1,this._distanceModel=1,this._listenerPos=[this._runtime.GetViewportWidth()/2,this._runtime.GetViewportHeight()/2,600],this._listenerForwardVec=[0,0,-1],this._listenerUpVec=[0,1,0],this._referenceDistance=600,this._maxDistance=1e4,this._rolloffFactor=1,this._listenerInst=null,this._loadListenerUid=-1,this._masterVolume=1,this._isSilent=!1,this._sampleRate=0,this._audioContextState="suspended",this._outputLatency=0,this._effectCount=new Map,this._preloadTotal=0,this._preloadCount=0,this._bufferMetadata=new Map,this._remoteUrls=new Map;let s="interactive";e&&(this._timeScaleMode=e[0],this._saveLoadMode=e[1],this._playInBackground=e[2],s=o[e[3]],this._enableMultiTags=e[4],this._panningModel=e[5],this._distanceModel=e[6],this._listenerPos[2]=e[7],this._referenceDistance=e[8],this._maxDistance=e[9],this._rolloffFactor=e[10]),this._lastAIState=[],this._lastFxState=[],this._lastAnalysersData=[],this.AddDOMMessageHandlers([["state",t=>this._OnUpdateState(t)],["audiocontext-state",t=>this._OnAudioContextStateChanged(t)],["fxstate",t=>this._OnUpdateFxState(t)],["trigger",t=>this._OnTrigger(t)],["buffer-metadata",t=>this._OnBufferMetadata(t)]]);const i=this.GetRuntime().Dispatcher();this._disposables=new n.CompositeDisposable(n.Disposable.From(i,"instancedestroy",t=>this._OnInstanceDestroyed(t.instance)),n.Disposable.From(i,"afterload",()=>this._OnAfterLoad()),n.Disposable.From(i,"suspend",()=>this._OnSuspend()),n.Disposable.From(i,"resume",()=>this._OnResume()));const a=this._runtime.GetExportType(),l="Safari"===n.Platform.Browser,h=this._runtime.IsiOSWebView()||"macos-wkwebview"===a,u="playable-ad-single-file"===a,c="cordova"===a&&"Android"===n.Platform.OS,d=l||h||u||c;this._runtime.AddLoadPromise(this.PostToDOMAsync("create-audio-context",{"preloadList":this._runtime.GetAssetManager().GetAudioToPreload().map(t=>({"originalUrl":t.originalUrl,"url":t.url,"type":t.type,"fileSize":t.fileSize})),"timeScaleMode":this._timeScaleMode,"latencyHint":s,"panningModel":this._panningModel,"distanceModel":this._distanceModel,"refDistance":this._referenceDistance,"maxDistance":this._maxDistance,"rolloffFactor":this._rolloffFactor,"listenerPos":this._listenerPos,"usePlayMusicAsSoundWorkaround":d}).then(t=>{this._sampleRate=t["sampleRate"],this._audioContextState=t["audioContextState"],this._outputLatency=t["outputLatency"]})),this._StartTicking()}Release(){this._listenerInst=null,super.Release()}_SplitTags(t){return this._enableMultiTags?t.split(" ").filter(t=>!!t):t?[t]:[]}_MatchTagLists(t,e){for(const s of e){let e=!1;for(const i of t)if(n.equalsNoCase(i,s)){e=!0;break}if(!e)return!1}return!0}_MatchTagListToStr(t,e){return this._MatchTagLists(t,this._SplitTags(e))}_AddActionPromise(t){this.GetPlugin()._AddActionPromise(t)}_OnInstanceDestroyed(t){this._listenerInst===t&&(this._listenerInst=null)}DbToLinearNoCap(t){return Math.pow(10,t/20)}DbToLinear(t){const e=this.DbToLinearNoCap(t);return isFinite(e)?Math.max(Math.min(e,1),0):0}LinearToDbNoCap(t){return Math.log(t)/Math.log(10)*20}LinearToDb(t){return this.LinearToDbNoCap(Math.max(Math.min(t,1),0))}_GetScheduledPlayInfo(){let t=0;const e=!!self["C3_GetAudioContextCurrentTime"];return t=e?this._nextPlayTime:this._nextPlayOffset,this._nextPlayTime=0,this._nextPlayOffset=0,{playOffset:t,isTrueClock:e}}_OnSuspend(){this._playInBackground||this.PostToDOM("set-suspended",{"isSuspended":!0})}_OnResume(){this._playInBackground||this.PostToDOM("set-suspended",{"isSuspended":!1})}_OnUpdateState(t){const e=t["tickCount"];this._outputLatency=t["outputLatency"];const s=this._lastAIState.filter(t=>t.hasOwnProperty("placeholder")&&(t["placeholder"]>e||-1===t["placeholder"]));this._lastAIState=t["audioInstances"],this._lastAnalysersData=t["analysers"],s.length>0&&n.appendArray(this._lastAIState,s)}_OnBufferMetadata(t){this._bufferMetadata.set(t["originalUrl"],{duration:t["duration"]})}_OnAudioContextStateChanged(t){this._audioContextState=t["audioContextState"]}GetAudioContextState(){return this._runtime.IsExportToVideo()?"running":this._audioContextState}_OnUpdateFxState(t){this._lastFxState=t["fxstate"]}_GetFirstAudioStateByTags(t){const e=this._SplitTags(t);for(const t of this._lastAIState)if(this._MatchTagLists(t["tags"],e))return t;return null}_IsTagPlaying(t){const e=this._SplitTags(t);return this._lastAIState.some(t=>this._MatchTagLists(t["tags"],e)&&t["isPlaying"])}_MaybeMarkAsPlaying(t,e,s,i,a){if(this._IsTagPlaying(e))return null;const n=this._bufferMetadata.get(t),r={"tags":this._SplitTags(e),"duration":n?n.duration:0,"volume":a,"isPlaying":!0,"playbackTime":0,"playbackRate":1,"uid":-1,"bufferOriginalUrl":t,"bufferUrl":"","bufferType":"","isMusic":s,"isLooping":i,"isMuted":!1,"resumePosition":0,"pan":null,"placeholder":-1};return this._lastAIState.push(r),r}_MaybeMarkAsStopped(t){const e=this._SplitTags(t);for(const t of this._lastAIState)this._MatchTagLists(t["tags"],e)&&(t["isPlaying"]=!1)}async _OnTrigger(t){const e=t["type"];this._triggerTags=t["tags"];const s=t["aiid"];if("ended"===e){for(const t of this._lastAIState)if(t["aiid"]===s){t["isPlaying"]=!1;break}await this.TriggerAsync(n.Plugins.Audio.Cnds.OnEnded)}else"fade-ended"===e&&await this.TriggerAsync(n.Plugins.Audio.Cnds.OnFadeEnded)}_MatchTriggerTag(t){return this._MatchTagListToStr(this._triggerTags,t)}Tick(){const t={"timeScale":this._runtime.GetTimeScale(),"gameTime":this._runtime.GetGameTimeRaw(),"instPans":this.GetInstancePans(),"tickCount":this._runtime.GetTickCountNoSave()};if(this._listenerInst){const e=this._listenerInst.GetWorldInfo();this._listenerPos[0]=e.GetX(),this._listenerPos[1]=e.GetY(),t["listenerPos"]=this._listenerPos,t["listenerOrientation"]=[...this._listenerForwardVec,...this._listenerUpVec]}this.PostToDOM("tick",t)}rotatePtAround(t,e,s,i,a){if(0===s)return[t,e];const n=Math.sin(s),r=Math.cos(s),o=(t-=i)*n;return t=t*r-(e-=a)*n,e=e*r+o,[t+=i,e+=a]}GetInstancePans(){return this._lastAIState.filter(t=>-1!==t["uid"]).map(t=>this._runtime.GetInstanceByUID(t["uid"])).filter(t=>t).map(t=>{const e=t.GetWorldInfo(),s=e.GetLayer().GetAngle(),[i,a]=this.rotatePtAround(e.GetX(),e.GetY(),-s,this._listenerPos[0],this._listenerPos[1]);return{"uid":t.GetUID(),"x":i,"y":a,"z":e.GetTotalZ(),"angle":e.GetAngle()-s}})}GetAnalyserData(t,e){for(const s of this._lastAnalysersData)if(s.index===e&&n.equalsNoCase(s["tag"],t))return s;return null}_IncrementEffectCount(t){for(const e of this._SplitTags(t)){const t=e.toLowerCase();this._effectCount.set(t,(this._effectCount.get(t)||0)+1)}}_IsSilent(){return this._isSilent}_SetSilent(t){t=!!t,this._isSilent!==t&&(this._isSilent=t,this.PostToDOM("set-silent",{"isSilent":t}))}_GetMasterVolume(){return this._masterVolume}_SetMasterVolume(t){this._masterVolume!==t&&(this._masterVolume=t,this.PostToDOM("set-master-volume",{"vol":t}))}_StopAll(){this.PostToDOM("stop-all");for(const t of this._lastAIState)t["isPlaying"]=!1}_ShouldSave(t){return!t.hasOwnProperty("placeholder")&&(3!==this._saveLoadMode&&((!t["isMusic"]||1!==this._saveLoadMode)&&!(!t["isMusic"]&&2===this._saveLoadMode)))}SaveToJson(){return{"isSilent":this._isSilent,"masterVolume":this._masterVolume,"listenerZ":this._listenerPos[2],"listenerForwardVec":this._listenerForwardVec,"listenerUpVec":this._listenerUpVec,"listenerUid":this._listenerInst?this._listenerInst.GetUID():-1,"remoteUrls":[...this._remoteUrls.entries()],"playing":this._lastAIState.filter(t=>this._ShouldSave(t)),"effects":this._lastFxState,"analysers":this._lastAnalysersData}}LoadFromJson(t){if(this._isSilent=t["isSilent"],this._masterVolume=t["masterVolume"],this._listenerPos[2]=t["listenerZ"],this._listenerInst=null,this._loadListenerUid=t["listenerUid"],t.hasOwnProperty("listenerForwardVec")?this._listenerForwardVec=t["listenerForwardVec"]:this._listenerForwardVec=[0,0,-1],t.hasOwnProperty("listenerUpVec")?this._listenerUpVec=t["listenerUpVec"]:this._listenerUpVec=[0,1,0],this._remoteUrls.clear(),t["remoteUrls"])for(const[e,s]of t["remoteUrls"])this._remoteUrls.set(e,s);this._lastAIState=t["playing"];for(const t of this._lastAIState)t.hasOwnProperty("tag")&&!t.hasOwnProperty("tags")&&(t["tags"]=[t["tag"]].filter(t=>!!t));this._lastFxState=t["effects"],this._lastAnalysersData=t["analysers"]}_OnAfterLoad(){if(-1!==this._loadListenerUid&&(this._listenerInst=this._runtime.GetInstanceByUID(this._loadListenerUid),this._loadListenerUid=-1,this._listenerInst)){const t=this._listenerInst.GetWorldInfo();this._listenerPos[0]=t.GetX(),this._listenerPos[1]=t.GetY()}for(const t of this._lastAIState){const e=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t["bufferOriginalUrl"]);e?(t["bufferUrl"]=e.url,t["bufferType"]=e.type):t["bufferUrl"]=null}for(const t of Object.values(this._lastFxState))for(const e of t)if(e.hasOwnProperty("bufferOriginalUrl")){const t=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e["bufferOriginalUrl"]);t&&(e["bufferUrl"]=t.url,e["bufferType"]=t.type)}this.PostToDOM("load-state",{"saveLoadMode":this._saveLoadMode,"timeScale":this._runtime.GetTimeScale(),"gameTime":this._runtime.GetGameTimeRaw(),"listenerPos":this._listenerPos,"listenerOrientation":[...this._listenerForwardVec,...this._listenerUpVec],"isSilent":this._isSilent,"masterVolume":this._masterVolume,"playing":this._lastAIState.filter(t=>null!==t["bufferUrl"]),"effects":this._lastFxState})}GetDebuggerProperties(){const t=[];for(const[e,s]of Object.entries(this._lastFxState))t.push({name:"$"+e,value:s.map(t=>t["type"]).join(", ")});const e="plugins.audio.debugger";return[{title:e+".tag-effects",properties:t},{title:e+".currently-playing",properties:[{name:e+".currently-playing-count",value:this._lastAIState.length},...this._lastAIState.map((t,e)=>({name:"$#"+e,value:`${t["bufferOriginalUrl"]} ("${t["tags"]}") ${Math.round(10*t["playbackTime"])/10} / ${Math.round(10*t["duration"])/10}`}))]}]}}}self.C3.Plugins.Audio.Cnds={OnEnded(t){return this._MatchTriggerTag(t)},OnFadeEnded(t){return this._MatchTriggerTag(t)},PreloadsComplete(){return this._preloadCount===this._preloadTotal},AdvancedAudioSupported:()=>!0,IsSilent(){return this._IsSilent()},IsAnyPlaying(){for(const t of this._lastAIState)if(t["isPlaying"])return!0;return!1},IsTagPlaying(t){return this._IsTagPlaying(t)}};{const l=self.C3,h=["lowpass","highpass","bandpass","lowshelf","highshelf","peaking","notch","allpass"];l.Plugins.Audio.Acts={Play(t,e,s,i,a){const n=l.Plugins.Audio.Acts._DoPlay.call(this,t,e,s,i,a);return this._AddActionPromise(n),n},PlayFromTimeline(t,e,s,i){l.Plugins.Audio.Acts._DoPlay.call(this,t,0,e,0,s,i)},async _DoPlay(t,e,s,i,a,n){if(this._isSilent)return;const r=t[1],o=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);if(!o)return;const{playOffset:h,isTrueClock:u}=this._GetScheduledPlayInfo(),c=this._MaybeMarkAsPlaying(t[0],a,r,0!==e,this.DbToLinear(s));try{await this.PostToDOMAsync("play",{"originalUrl":t[0],"url":o.url,"type":o.type,"isMusic":r,"tags":this._SplitTags(a),"isLooping":0!==e,"vol":this.DbToLinear(s),"stereoPan":l.clamp(i/100,-1,1),"pos":n||0,"off":h,"trueClock":u})}finally{c&&(c["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayAtPosition(t,e,s,i,a,n,r,o,h,u,c){if(this._isSilent)return;const d=t[1],_=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);if(!_)return;const{playOffset:f,isTrueClock:p}=this._GetScheduledPlayInfo(),g=this._MaybeMarkAsPlaying(t[0],c,d,0!==e,this.DbToLinear(s));try{await this.PostToDOMAsync("play",{"originalUrl":t[0],"url":_.url,"type":_.type,"isMusic":d,"tags":this._SplitTags(c),"isLooping":0!==e,"vol":this.DbToLinear(s),"pos":0,"off":f,"trueClock":p,"panning":{"x":i,"y":a,"z":n,"angle":l.toRadians(r),"innerAngle":l.toRadians(o),"outerAngle":l.toRadians(h),"outerGain":this.DbToLinear(u)}})}finally{g&&(g["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayAtObject(t,e,s,i,a,n,r,o){if(this._isSilent)return;if(!i)return;const h=i.GetFirstPicked();if(!h||!h.GetWorldInfo())return;const u=h.GetWorldInfo(),c=u.GetLayer().GetAngle(),[d,_]=this.rotatePtAround(u.GetX(),u.GetY(),-c,this._listenerPos[0],this._listenerPos[1]),f=t[1],p=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);if(!p)return;const{playOffset:g,isTrueClock:y}=this._GetScheduledPlayInfo(),m=this._MaybeMarkAsPlaying(t[0],o,f,0!==e,this.DbToLinear(s));try{await this.PostToDOMAsync("play",{"originalUrl":t[0],"url":p.url,"type":p.type,"isMusic":f,"tags":this._SplitTags(o),"isLooping":0!==e,"vol":this.DbToLinear(s),"pos":0,"off":g,"trueClock":y,"panning":{"x":d,"y":_,"z":u.GetTotalZ(),"angle":u.GetAngle()-c,"innerAngle":l.toRadians(a),"outerAngle":l.toRadians(n),"outerGain":this.DbToLinear(r),"uid":h.GetUID()}})}finally{m&&(m["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayByName(t,e,s,i,a,n){if(this._isSilent)return;const r=1===t,o=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());if(!o)return;const{playOffset:h,isTrueClock:u}=this._GetScheduledPlayInfo(),c=this._MaybeMarkAsPlaying(e,n,r,0!==s,this.DbToLinear(i));try{await this.PostToDOMAsync("play",{"originalUrl":e,"url":o.url,"type":o.type,"isMusic":r,"tags":this._SplitTags(n),"isLooping":0!==s,"vol":this.DbToLinear(i),"stereoPan":l.clamp(a/100,-1,1),"pos":0,"off":h,"trueClock":u})}finally{c&&(c["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayAtPositionByName(t,e,s,i,a,n,r,o,h,u,c,d){if(this._isSilent)return;const _=1===t,f=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());if(!f)return;const{playOffset:p,isTrueClock:g}=this._GetScheduledPlayInfo(),y=this._MaybeMarkAsPlaying(e,d,_,0!==s,this.DbToLinear(i));try{await this.PostToDOMAsync("play",{"originalUrl":e,"url":f.url,"type":f.type,"isMusic":_,"tags":this._SplitTags(d),"isLooping":0!==s,"vol":this.DbToLinear(i),"pos":0,"off":p,"trueClock":g,"panning":{"x":a,"y":n,"z":r,"angle":l.toRadians(o),"innerAngle":l.toRadians(h),"outerAngle":l.toRadians(u),"outerGain":this.DbToLinear(c)}})}finally{y&&(y["placeholder"]=this._runtime.GetTickCountNoSave())}},async PlayAtObjectByName(t,e,s,i,a,n,r,o,h){if(this._isSilent)return;if(this._isSilent)return;if(!a)return;const u=a.GetFirstPicked();if(!u||!u.GetWorldInfo())return;const c=u.GetWorldInfo(),d=c.GetLayer().GetAngle(),[_,f]=this.rotatePtAround(c.GetX(),c.GetY(),-d,this._listenerPos[0],this._listenerPos[1]),p=1===t,g=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());if(!g)return;const{playOffset:y,isTrueClock:m}=this._GetScheduledPlayInfo(),T=this._MaybeMarkAsPlaying(e,h,p,0!==s,this.DbToLinear(i));try{await this.PostToDOMAsync("play",{"originalUrl":e,"url":g.url,"type":g.type,"isMusic":p,"tags":this._SplitTags(h),"isLooping":0!==s,"vol":this.DbToLinear(i),"pos":0,"off":y,"trueClock":m,"panning":{"x":_,"y":f,"z":c.GetTotalZ(),"angle":c.GetAngle()-d,"innerAngle":l.toRadians(n),"outerAngle":l.toRadians(r),"outerGain":this.DbToLinear(o),"uid":u.GetUID()}})}finally{T&&(T["placeholder"]=this._runtime.GetTickCountNoSave())}},SetLooping(t,e){this.PostToDOM("set-looping",{"tags":this._SplitTags(t),"isLooping":0===e})},SetMuted(t,e){this.PostToDOM("set-muted",{"tags":this._SplitTags(t),"isMuted":0===e})},SetVolume(t,e){this.PostToDOM("set-volume",{"tags":this._SplitTags(t),"vol":this.DbToLinear(e)})},FadeVolume(t,e,s,i){this.PostToDOM("fade-volume",{"tags":this._SplitTags(t),"vol":this.DbToLinear(e),"duration":s,"stopOnEnd":0===i})},SetStereoPan(t,e){this.PostToDOM("set-stereo-pan",{"tags":this._SplitTags(t),"p":l.clamp(e/100,-1,1)})},async Preload(t){const e=t[1],s=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);s&&(this._preloadTotal++,await this.PostToDOMAsync("preload",{"originalUrl":t[0],"url":s.url,"type":s.type,"isMusic":e}),this._preloadCount++)},async PreloadByName(t,e){const s=1===t,i=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());i&&(this._preloadTotal++,await this.PostToDOMAsync("preload",{"originalUrl":e,"url":i.url,"type":i.type,"isMusic":s}),this._preloadCount++)},SetPlaybackRate(t,e){this.PostToDOM("set-playback-rate",{"tags":this._SplitTags(t),"rate":Math.max(e,0)})},Stop(t){this._MaybeMarkAsStopped(t),this.PostToDOM("stop",{"tags":this._SplitTags(t)})},StopAll(){this._StopAll()},SetPaused(t,e){this.PostToDOM("set-paused",{"tags":this._SplitTags(t),"paused":0===e})},Seek(t,e){this.PostToDOM("seek",{"tags":this._SplitTags(t),"pos":e})},SetSilent(t){2===t&&(t=this._IsSilent()?1:0),this._SetSilent(0===t)},SetMasterVolume(t){const e=this.DbToLinear(t);this._SetMasterVolume(e)},AddFilterEffect(t,e,s,i,a,n,r){const o=h[e];this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"filter","tags":this._SplitTags(t),"params":[o,s,i,a,n,l.clamp(r/100,0,1)]})},AddDelayEffect(t,e,s,i){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"delay","tags":this._SplitTags(t),"params":[e,this.DbToLinear(s),l.clamp(i/100,0,1)]})},AddFlangerEffect(t,e,s,i,a,n){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"flanger","tags":this._SplitTags(t),"params":[e/1e3,s/1e3,i,a/100,l.clamp(n/100,0,1)]})},AddPhaserEffect(t,e,s,i,a,n,r){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"phaser","tags":this._SplitTags(t),"params":[e,s,i,a,n,l.clamp(r/100,0,1)]})},AddConvolutionEffect(t,e,s,i){const a=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e[0]);a&&(this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"convolution","tags":this._SplitTags(t),"bufferOriginalUrl":e[0],"bufferUrl":a.url,"bufferType":a.type,"params":[0===s,l.clamp(i/100,0,1)]}))},AddGainEffect(t,e){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"gain","tags":this._SplitTags(t),"params":[this.DbToLinear(e)]})},AddStereoPanEffect(t,e){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"stereopan","tags":this._SplitTags(t),"params":[l.clamp(e/100,-1,1)]})},AddMuteEffect(t){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"gain","tags":this._SplitTags(t),"params":[0]})},AddTremoloEffect(t,e,s){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"tremolo","tags":this._SplitTags(t),"params":[e,l.clamp(s/100,0,1)]})},AddRingModEffect(t,e,s){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"ringmod","tags":this._SplitTags(t),"params":[e,l.clamp(s/100,0,1)]})},AddDistortionEffect(t,e,s,i,a,n){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"distortion","tags":this._SplitTags(t),"params":[this.DbToLinearNoCap(e),this.DbToLinearNoCap(s),i,this.DbToLinearNoCap(a),l.clamp(n/100,0,1)]})},AddCompressorEffect(t,e,s,i,a,n){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"compressor","tags":this._SplitTags(t),"params":[e,s,i,a/1e3,n/1e3]})},AddAnalyserEffect(t,e,s){this._IncrementEffectCount(t),this.PostToDOM("add-effect",{"type":"analyser","tags":this._SplitTags(t),"params":[e,s]})},RemoveEffects(t){const e=this._SplitTags(t);for(const t of e)this._effectCount.set(t.toLowerCase(),0);this.PostToDOM("remove-effects",{"tags":e}),this._lastFxState={}},SetEffectParameter(t,e,s,i,a,n){this.PostToDOM("set-effect-param",{"tags":this._SplitTags(t),"index":Math.floor(e),"param":s,"value":i,"ramp":a,"time":n})},SetListenerObject(t){if(!t)return;const e=t.GetFirstPicked();e&&e.GetWorldInfo()&&(this._listenerInst=e)},SetListenerZ(t){this._listenerPos[2]=t},SetListenerOrientation(t,e,s,i,a,n){this._listenerForwardVec[0]=t,this._listenerForwardVec[1]=e,this._listenerForwardVec[2]=-s,this._listenerUpVec[0]=i,this._listenerUpVec[1]=a,this._listenerUpVec[2]=-n},ScheduleNextPlay(t){this._nextPlayTime=Math.max(t,0),this._nextPlayOffset=Math.max(t-performance.now()/1e3,0)},UnloadAudio(t){const e=t[1],s=this._runtime.GetAssetManager().GetProjectAudioFileUrl(t[0]);s&&this.PostToDOM("unload",{"url":s.url,"type":s.type,"isMusic":e})},UnloadAudioByName(t,e){const s=1===t,i=this._runtime.GetAssetManager().GetProjectAudioFileUrl(e)||this._remoteUrls.get(e.toLowerCase());i&&this.PostToDOM("unload",{"url":i.url,"type":i.type,"isMusic":s})},UnloadAll(){this.PostToDOM("unload-all")},AddRemoteURL(t,e,s){this._remoteUrls.set(s.toLowerCase(),{url:t,type:e})}}}{const u=self.C3;u.Plugins.Audio.Exps={Duration(t){const e=this._GetFirstAudioStateByTags(t);return e?e["duration"]:0},PlaybackTime(t){const e=this._GetFirstAudioStateByTags(t);return e?e["playbackTime"]:0},PlaybackRate(t){const e=this._GetFirstAudioStateByTags(t);return e?e["playbackRate"]:0},Volume(t){const e=this._GetFirstAudioStateByTags(t);return e?this.LinearToDb(e["volume"]):0},MasterVolume(){return this.LinearToDb(this._GetMasterVolume())},EffectCount(t){return this._effectCount.get(t.toLowerCase())||0},AnalyserFreqBinCount(t,e){const s=this.GetAnalyserData(t,Math.floor(e));return s?s["binCount"]:0},AnalyserFreqBinAt(t,e,s){const i=this.GetAnalyserData(t,Math.floor(e));return i?(s=Math.floor(s))<0||s>=i["binCount"]?0:i["freqBins"][s]:0},AnalyserPeakLevel(t,e){const s=this.GetAnalyserData(t,Math.floor(e));return s?s["peak"]:0},AnalyserRMSLevel(t,e){const s=this.GetAnalyserData(t,Math.floor(e));return s?s["rms"]:0},SampleRate(){return this._sampleRate},CurrentTime:()=>self["C3_GetAudioContextCurrentTime"]?self["C3_GetAudioContextCurrentTime"]():performance.now()/1e3,OutputLatency(){return this._outputLatency},NormalizedVolume(t,e){return 0===(t=u.clamp(+t,0,100)/100)?-1/0:t<.1?this.LinearToDb(u.lerp(0,this.DbToLinear(e),10*t)):u.lerp(e,0,(t-.1)/.9)}}} } // scripts/plugins/Function/c3runtime/runtime.js { {const n=self.C3;n.Plugins.Function=class extends n.SDKPluginBase{constructor(n){super(n)}Release(){super.Release()}}}{const n=self.C3;n.Plugins.Function.Type=class extends n.SDKTypeBase{constructor(n){super(n)}Release(){super.Release()}OnCreate(){}}}{const n=self.C3;class t{constructor(){this.name="",this.retVal=0,this.params=[]}}n.Plugins.Function.Instance=class extends n.SDKInstanceBase{constructor(n,t){super(n),this._isPreview=this._runtime.IsPreview(),this._funcStackPtr=-1,this._funcStack=[];const e=(n,t)=>this._InvokeFromJS(n,t);self["c2_callFunction"]=e,self["c3_callFunction"]=e}Release(){super.Release()}Push(){const n=this._funcStack,e=++this._funcStackPtr;return e===n.length&&n.push(new t),n[e]}Pop(){--this._funcStackPtr}GetCurrent(){const n=this._funcStackPtr;return n<0?null:this._funcStack[n]}GetOneAbove(){const n=this._funcStack;if(!n.length)return null;return n[Math.min(this._funcStackPtr+1,n.length-1)]}_CallFunction(t,e){const s=this.Push();s.name=t.toLowerCase(),s.retVal=0,n.shallowAssignArray(s.params,e);const o=this.FastTrigger(n.Plugins.Function.Cnds.OnFunction,s.name);this._isPreview&&!o&&console.warn(`[Construct] Function object: called function '${t}' but no event was triggered. Is the function call spelt incorrectly or no longer used?`),this.Pop()}*_DebugCallFunction(t,e){const s=this.Push();s.name=t.toLowerCase(),s.retVal=0,n.shallowAssignArray(s.params,e);const o=yield*this.DebugFastTrigger(n.Plugins.Function.Cnds.OnFunction,s.name);this._isPreview&&!o&&console.warn(`[Construct] Function object: called function '${t}' but no event was triggered. Is the function call spelt incorrectly or no longer used?`),this.Pop()}_InvokeFromJS(t,e){const s=this.Push();return s.name=t.toLowerCase(),s.retVal=0,s.params=(e||[]).map(n=>"number"==typeof n||"string"==typeof n?n:"boolean"==typeof n&&n?1:0),this.FastTrigger(n.Plugins.Function.Cnds.OnFunction,s.name),this.Pop(),s.retVal}}}{const n=self.C3;n.Plugins.Function.Cnds={OnFunction:n=>!0,CompareParam(t,e,s){const o=this.GetCurrent();if(!o)return this._isPreview&&console.warn("[Construct] Function object: used 'Compare parameter' condition when not in a function call"),!1;const r=o.params;let i=0;return(t=Math.floor(t))<0||t>=r.length?this._isPreview&&console.warn(`[Construct] Function object: in function '${o.name}', compared parameter out of bounds (accessed index ${t} of ${r.length})`):i=r[t],n.compare(i,e,s)}}}self.C3.Plugins.Function.Acts={CallFunction(n,t){if(this._runtime.IsDebugging())return this._DebugCallFunction(n,t);this._CallFunction(n,t)},SetReturnValue(n){const t=this.GetCurrent();t?t.retVal=n:this._isPreview&&console.warn("[Construct] Function object: used 'Set return value' when not in a function call")},CallExpression(n){}};{const n=self.C3;n.Plugins.Function.Exps={ReturnValue(){const n=this.GetOneAbove();return n?n.retVal:0},ParamCount(){const n=this.GetCurrent();return n?n.params.length:(this._isPreview&&console.warn("[Construct] Function object: used 'ParamCount' expression when not in a function call"),0)},Param(n){n=Math.floor(n);const t=this.GetCurrent();if(t){const e=t.params;return n>=0&&nthis._runtime.UpdateRender(),this._animationframeimagechange_handler=()=>this._OnIconObjectClassImageChanged(),this._pendingUpdateIconSet=!1,this._didUpdateTextCanvas=!1,this._beforerender_handler=()=>this._OnBeforeRender(),this._beforerender2_handler=()=>this._OnBeforeRender2(),i){this._text=i[r],this._enableBBcode=!!i[s],this._faceName=i[n],this._ptSize=i[a],this._lineHeightOffset=i[o],this._isBold=!!i[h],this._isItalic=!!i[_],this._horizontalAlign=i[d],this._verticalAlign=i[c],this._wrapMode=m[i[g]],this._textDirection=i[u],this._SetIconObjectClass(this._runtime.GetObjectClassBySID(i[T]));const e=i[l];this._color.setRgb(e[0],e[1],e[2]),this.GetWorldInfo().SetVisible(i[S]),this._readAloud=!!i[p]}this._UpdateTextSettings(),this._UpdateScreenReaderText(),this._runtime.Dispatcher().addEventListener("beforerender",this._beforerender_handler),this._runtime.Dispatcher().addEventListener("beforerender2",this._beforerender2_handler)}Release(){this._runtime.Dispatcher().removeEventListener("beforerender2",this._beforerender2_handler),this._beforerender2_handler=null,this._runtime.Dispatcher().removeEventListener("beforerender",this._beforerender_handler),this._beforerender_handler=null,this._SetIconObjectClass(null),this._CancelTypewriter(),this._screenReaderText&&(this._screenReaderText.Release(),this._screenReaderText=null),this._rendererText.Release(),this._rendererText=null,super.Release()}_UpdateTextSettings(){const e=this._rendererText;e.SetText(this._text),e.SetBBCodeEnabled(this._enableBBcode),this._rendererText.IsBBCodeEnabled()&&this._iconObjectClass?this._rendererText.SetIconSet(this.GetRuntime().GetTextIconSet(this._iconObjectClass)):this._rendererText.SetIconSet(null),e.SetFontName(this._faceName),e.SetLineHeight(this._lineHeightOffset),e.SetBold(this._isBold),e.SetItalic(this._isItalic),e.SetColor(this._color),e.SetHorizontalAlignment(x[this._horizontalAlign]),e.SetVerticalAlignment(G[this._verticalAlign]),e.SetWordWrapMode(this._wrapMode),e.SetTextDirection(f[this._textDirection])}_UpdateTextSize(){const e=this.GetWorldInfo();this._rendererText.SetText(this._text),this._rendererText.SetFontSize(this._ptSize),this._rendererText.SetFontSizeScale(e.GetSceneGraphScale());const t=e.GetLayer();let i;"auto"===this._resolutionMode?(i=t.GetResolutionScaleFactorToZ(e.GetTotalZ()),this._rendererText.SetMipMapEnabled(!1)):"fixed"===this._resolutionMode&&(i=this._fixedScaleFactor,this._rendererText.SetMipMapEnabled(!0)),e.HasMesh()&&i!==this._rendererText.GetZoom()&&e.SetMeshChanged(!0),this._rendererText.SetSize(e.GetWidth(),e.GetHeight(),i)}_SetIconObjectClass(t){t&&(t.IsFamily()||t.GetPlugin().constructor!==e.Plugins.Sprite)||t!==this._iconObjectClass&&(this._iconObjectClass&&this._iconObjectClass.Dispatcher().removeEventListener("animationframeimagechange",this._animationframeimagechange_handler),this._iconObjectClass=t,this._iconObjectClass&&this._iconObjectClass.Dispatcher().addEventListener("animationframeimagechange",this._animationframeimagechange_handler),this._UpdateTextSettings(),this._isHtmlStringUpToDate=!1,this._runtime.UpdateRender())}_OnIconObjectClassImageChanged(){this._runtime.DeleteTextIconSet(this._iconObjectClass),this._runtime.UpdateRender(),this._pendingUpdateIconSet=!0}_UpdateScreenReaderText(){if(this._readAloud){let t=this._text;this._enableBBcode&&(t=e.BBString.StripAnyTags(t)),this._screenReaderText?this._screenReaderText.SetText(t):this._screenReaderText=e.New(e.ScreenReaderText,this._runtime,t)}else this._screenReaderText&&(this._screenReaderText.Release(),this._screenReaderText=null)}_OnBeforeRender(){this._didUpdateTextCanvas=!1;const e=this.GetWorldInfo(),t=e.GetLayer(),i=e.GetLayout();e.IsVisible()&&t.IsVisible()&&e.IsInViewport(t.GetViewport(),i.HasVanishingPointOutsideViewport(),i.IsOrthographicProjection())&&(this._UpdateTextForDraw(),this._didUpdateTextCanvas=this._rendererText.MaybeUpdateCanvas())}_OnBeforeRender2(){this._didUpdateTextCanvas&&this._rendererText.GetTexture()}_UpdateTextForDraw(){this._UpdateTextSize(),this._rendererText.SetIconSmoothing(1!==this.GetWorldInfo().GetActiveSampling()),this._pendingUpdateIconSet&&(this._pendingUpdateIconSet=!1,this._rendererText.IsBBCodeEnabled()&&this._iconObjectClass&&this._rendererText.SetIconSet(this.GetRuntime().GetTextIconSet(this._iconObjectClass)))}Draw(e){this._rendererText.SetTextureAnisotropy(this._runtime.GetCanvasManager().GetTextureAnisotropy());const t=this._runtime.GetCanvasManager().IsPastingToDrawingCanvas();t&&this._UpdateTextForDraw();const i=this._rendererText.GetTexture();if(!i)return;const r=this.GetWorldInfo(),s=r.GetLayer();if(0!==r.GetAngle()||0!==s.GetAngle()||0!==r.GetTotalZ()||r.HasMesh()||!s.RendersIn2DMode()||t)e.SetTexture(i,r.GetActiveSampling()),r.HasMesh()?this._DrawMesh(r,e):this._DrawStandard(r,e);else{const t=r.GetBoundingQuad(),[n,a]=s.LayerToDrawSurface(t.getTlx(),t.getTly()),[o,h]=s.LayerToDrawSurface(t.getBrx(),t.getBry()),_=n-Math.round(n),l=a-Math.round(a);w.set(n,a,o,h),w.offset(-_,-l),I.setFromRect(w);const[d,c]=e.GetRenderTargetSize(e.GetRenderTarget());e.IsWebGL()?this._runtime.GetCanvasManager().SetDeviceTransform(e,d,c):(e.SetNormalizedCoordsProgramVariant(!0),I.divide(d,c)),e.SetTexture(i,r.GetActiveSampling()),e.Quad3(I,this._rendererText.GetTexRect()),e.IsWebGL()?s._SetTransform(e):e.SetNormalizedCoordsProgramVariant(!1)}}_DrawStandard(e,t){let i=e.GetBoundingQuad();this._runtime.IsPixelRoundingEnabled()&&(i=this._PixelRoundQuad(i)),t.Quad3(i,this._rendererText.GetTexRect())}_DrawMesh(e,t){const i=e.GetTransformedMesh();if(e.IsMeshChanged()){e.CalculateBbox(null,I,!1);let t=I;this._runtime.IsPixelRoundingEnabled()&&(t=this._PixelRoundQuad(t)),i.CalculateTransformedMesh(e.GetSourceMesh(),t,this._rendererText.GetTexRect()),e.SetMeshChanged(!1)}i.Draw(t,e.GetTotalZ())}_PixelRoundQuad(e){const t=e.getTlx()-Math.round(e.getTlx()),i=e.getTly()-Math.round(e.getTly());return 0===t&&0===i?e:(I.copy(e),I.offset(-t,-i),I)}GetCurrentSurfaceSize(){const e=this._rendererText.GetTexture();return e?[e.GetWidth(),e.GetHeight()]:[100,100]}GetCurrentTexRect(){return this._rendererText.GetTexRect()}IsCurrentTexRotated(){return!1}SaveToJson(){const e={"t":this._text,"c":this._color.toJSON(),"fn":this._faceName,"ps":this._ptSize};return this._enableBBcode&&(e["bbc"]=this._enableBBcode),0!==this._horizontalAlign&&(e["ha"]=this._horizontalAlign),0!==this._verticalAlign&&(e["va"]=this._verticalAlign),"word"!==this._wrapMode&&(e["wr"]=this._wrapMode),0!==this._lineHeightOffset&&(e["lho"]=this._lineHeightOffset),this._isBold&&(e["b"]=this._isBold),this._isItalic&&(e["i"]=this._isItalic),-1!==this._typewriterEndTime&&(e["tw"]={"st":this._typewriterStartTime,"en":this._typewriterEndTime,"l":this._typewriterLength}),this._iconObjectClass&&(e["ioc"]=this._iconObjectClass.GetSID()),"fixed"===this._resolutionMode&&(e["fs"]=this._fixedScaleFactor),e}LoadFromJson(e){if(this._CancelTypewriter(),this._text=e["t"],this._color.setFromJSON(e["c"]),this._faceName=e["fn"],this._ptSize=e["ps"],this._enableBBcode=!!e.hasOwnProperty("bbc")&&e["bbc"],this._horizontalAlign=e.hasOwnProperty("ha")?e["ha"]:0,this._verticalAlign=e.hasOwnProperty("va")?e["va"]:0,e.hasOwnProperty("wr")){const t=e["wr"];this._wrapMode="boolean"==typeof t?t?"word":"character":t}else this._wrapMode="word";if(this._lineHeightOffset=e.hasOwnProperty("lho")?e["lho"]:0,this._isBold=!!e.hasOwnProperty("b")&&e["b"],this._isItalic=!!e.hasOwnProperty("i")&&e["i"],e.hasOwnProperty("tw")){const t=e["tw"];this._typewriterStartTime=t["st"],this._typewriterEndTime=t["en"],this._typewriterLength=t["l"]}if(e.hasOwnProperty("ioc")){const t=this.GetRuntime().GetObjectClassBySID(e["ioc"]);t&&this._SetIconObjectClass(t)}else this._SetIconObjectClass(null);e.hasOwnProperty("fs")?(this._resolutionMode="fixed",this._fixedScaleFactor=e["fs"]):this._resolutionMode="auto",this._UpdateTextSettings(),this._UpdateScreenReaderText(),this._isHtmlStringUpToDate=!1,-1!==this._typewriterEndTime&&this._StartTicking()}GetPropertyValueByIndex(e){switch(e){case r:return this.GetText();case s:return this._enableBBcode;case n:return this._GetFontFace();case a:return this._GetFontSize();case o:return this._GetLineHeight();case h:return this._IsBold();case _:return this._IsItalic();case l:return i[0]=this._color.getR(),i[1]=this._color.getG(),i[2]=this._color.getB(),i;case d:return this._GetHAlign();case c:return this._GetVAlign();case g:return this._GetWrapMode();case p:return this._IsReadAloud()}}SetPropertyValueByIndex(e,t){switch(e){case r:this._SetText(t);break;case s:if(this._enableBBcode===!!t)return;this._enableBBcode=!!t,this._UpdateTextSettings();break;case n:this._SetFontFace(t);break;case a:this._SetFontSize(t);break;case o:this._SetLineHeight(t);break;case h:this._SetBold(t);break;case _:this._SetItalic(t);break;case l:const e=this._color,i=t;if(e.getR()===i[0]&&e.getG()===i[1]&&e.getB()===i[2])return;this._color.setRgb(i[0],i[1],i[2]),this._UpdateTextSettings();break;case d:this._SetHAlign(t);break;case c:this._SetVAlign(t);break;case g:this._SetWrapMode(t)}}SetPropertyColorOffsetValueByIndex(e,t,i,r){if((0!==t||0!==i||0!==r)&&e===l)this._color.addRgb(t,i,r),this._UpdateTextSettings()}_SetText(e){this._text!==e&&(this._text=e,this._UpdateScreenReaderText(),this._isHtmlStringUpToDate=!1,this._runtime.UpdateRender())}GetText(){return this._text}_StartTypewriter(e,t){this._SetText(e),this._UpdateTextSize(),this._typewriterStartTime=this._runtime.GetWallTime(),this._typewriterEndTime=this._typewriterStartTime+t/this.GetInstance().GetActiveTimeScale(),this._typewriterLength=this._rendererText.GetLengthInGraphemes(),this._rendererText.SetDrawMaxCharacterCount(0),this._StartTicking()}_CancelTypewriter(){this._typewriterStartTime=-1,this._typewriterEndTime=-1,this._typewriterLength=0,this._rendererText.SetDrawMaxCharacterCount(-1),this._StopTicking()}_FinishTypewriter(){-1!==this._typewriterEndTime&&(this._CancelTypewriter(),this.Trigger(e.Plugins.Text.Cnds.OnTypewriterTextFinished),this._runtime.UpdateRender())}_SetFontFace(e){this._faceName!==e&&(this._faceName=e,this._rendererText.SetFontName(e),this._runtime.UpdateRender())}_GetFontFace(){return this._faceName}_SetBold(e){e=!!e,this._isBold!==e&&(this._isBold=e,this._rendererText.SetBold(e),this._runtime.UpdateRender())}_IsBold(){return this._isBold}_SetItalic(e){e=!!e,this._isItalic!==e&&(this._isItalic=e,this._rendererText.SetItalic(e),this._runtime.UpdateRender())}_IsItalic(){return this._isItalic}_SetFontSize(e){this._ptSize!==e&&(this._ptSize=e,this._runtime.UpdateRender())}_GetFontSize(){return this._ptSize}_SetFontColor(e){this._color.equalsIgnoringAlpha(e)||(this._color.copyRgb(e),this._rendererText.SetColor(this._color),this._runtime.UpdateRender())}_GetFontColor(){return this._color}_SetLineHeight(e){this._lineHeightOffset!==e&&(this._lineHeightOffset=e,this._UpdateTextSettings(),this._runtime.UpdateRender())}_GetLineHeight(){return this._lineHeightOffset}_SetHAlign(e){this._horizontalAlign!==e&&(this._horizontalAlign=e,this._UpdateTextSettings(),this._runtime.UpdateRender())}_GetHAlign(){return this._horizontalAlign}_SetVAlign(e){this._verticalAlign!==e&&(this._verticalAlign=e,this._UpdateTextSettings(),this._runtime.UpdateRender())}_GetVAlign(){return this._verticalAlign}_SetWrapModeByIndex(e){this._SetWrapMode(m[e])}_SetWrapMode(e){this._wrapMode!==e&&(this._wrapMode=e,this._UpdateTextSettings(),this._runtime.UpdateRender())}_GetWrapMode(){return this._wrapMode}_SetTextDirection(e){this._textDirection!==e&&(this._textDirection=e,this._UpdateTextSettings(),this._runtime.UpdateRender())}_GetTextDirection(){return this._textDirection}_SetReadAloud(e){this._readAloud=!!e,this._UpdateScreenReaderText()}_IsReadAloud(){return this._readAloud}_SetResolutionMode(e){this._resolutionMode!==e&&(this._resolutionMode=e,this._runtime.UpdateRender())}_GetResolutionMode(){return this._resolutionMode}_SetFixedScaleFactor(e){this._fixedScaleFactor!==e&&(this._fixedScaleFactor=e,"fixed"===this._resolutionMode&&this._runtime.UpdateRender())}_GetFixedScaleFactor(){return this._fixedScaleFactor}_GetTextWidth(){return this._UpdateTextSize(),this._rendererText.GetTextWidth()}_GetTextHeight(){return this._UpdateTextSize(),this._rendererText.GetTextHeight()}_GetTagAtPosition(e,t){this._UpdateTextSize();const i=this.GetWorldInfo();y.set(e-i.GetX(),t-i.GetY()),y.rotate(-i.GetAngle()),y.offset(i.GetWidth()*i.GetOriginX(),i.GetHeight()*i.GetOriginY()),y.divide(i.GetWidth(),i.GetHeight()),y.scale(this._rendererText.GetWidth(),this._rendererText.GetHeight());const r=this._rendererText.HitTestFragment(y.getX(),y.getY());if(r){const e=r.GetStyleTag("tag");if(e)return e.param}return""}_HasTagAtPosition(t,i,r){const s=this._GetTagAtPosition(i,r);return s&&e.equalsNoCase(t,s)}_GetTagPosition(e,t){this._UpdateTextSize(),t=Math.floor(t);const i=this._rendererText.FindFragmentWithTag(e,t);if(!i)return null;const r=this.GetWorldInfo(),s=this._rendererText.GetDrawScale(),n=i.GetPosX(),a=i.GetPosY()-(i.GetHeight()-i.GetFontBoundingBoxDescent())*s,o=i.GetWidth()*s/this._rendererText.GetWidth()*r.GetWidth(),h=i.GetHeight()*s/this._rendererText.GetHeight()*r.GetHeight();return y.set(n,a),y.divide(this._rendererText.GetWidth(),this._rendererText.GetHeight()),y.scale(r.GetWidth(),r.GetHeight()),y.offset(-r.GetWidth()*r.GetOriginX(),-r.GetHeight()*r.GetOriginY()),y.rotate(r.GetAngle()),y.offset(r.GetX(),r.GetY()),{x:y.getX(),y:y.getY(),width:o,height:h}}_GetTagCount(e){return this._UpdateTextSize(),this._rendererText.CountFragmentsWithTag(e)}_GetHTMLCloseTag(e){let t=R.get(e);return null===t?"":(t||(t="span"),``)}_GetHTMLOpenTag(e,t){let i=R.get(e);if(null===i)return"";switch(i||(i="span"),e){case"color":return`<${i} style="color: ${t}">`;case"font":return`<${i} style="font-family: '${t}'">`;case"opacity":return`<${i} style="opacity: ${t}%">`;case"size":return`<${i} style="font-size: ${t}pt">`;case"background":return`<${i} style="background-color: ${t}">`;case"hide":return`<${i} style="visibility: hidden">`;case"class":return`<${i} class="${t}">`;case"tag":return`<${i} data-tag="${t}">`;default:return`<${i}>`}}async _UpdateHTMLString(){if(this._isHtmlStringUpToDate)return this._htmlString;const t=new e.BBString(this._text,{noEscape:!0}).toFragmentList(),i=new Map;let r='`;const n=this._iconObjectClass?this.GetRuntime().GetTextIconSet(this._iconObjectClass):null;if(this._iconObjectClass){const r=e.New(e.PromiseThrottle),s=[],a=new Map;for(const e of t)if(e.IsIcon()){const t=e.GetTextIcon(n);if(t){const e=t.GetSource().GetImageInfo().GetImageAsset();if(a.has(e))continue;a.set(e,null),s.push(r.Add(async()=>{const t=await e.LoadToDrawable();a.set(e,t)}))}}await Promise.all(s);const o=[];for(const e of t)if(e.IsIcon()){const t=e.GetTextIcon(n);if(t){const e=t.GetSource(),s=e.GetImageInfo().GetImageAsset();o.push(r.Add(async()=>{const r=await e.GetImageInfo().ExtractImageToBlobURL(a.get(s));i.set(t,r)}))}}await Promise.all(o);for(const e of a.values())e instanceof ImageBitmap&&e["close"]&&e["close"]()}const a=new Map;for(const s of t){const t=s.GetStyleMap();let o=[...a.keys()];o.reverse();for(const e of o)t.has(e)&&t.get(e)===a.get(e)||(a.delete(e),r+=this._GetHTMLCloseTag(e));for(const[e,i]of t)a.has(e)||(a.set(e,i),r+=this._GetHTMLOpenTag(e,i));if(s.IsText()&&(r+=e.ReplaceAll(e.EscapeHTML(s.GetCharacterArray().join("")),"\n","
")),s.IsIcon()&&n){const e=s.GetTextIcon(n);if(e){const n=i.get(e);if(n){const i=[];let a="0.2em";const o=t.get("iconoffsety");if(o){let e=o.trim();a=e.endsWith("%")?parseFloat(e)/100+"em":e+"px"}i.push(`top: ${a}`),1===this.GetWorldInfo().GetActiveSampling()&&i.push("image-rendering: pixelated"),r+=``}}}}const o=[...a.keys()];o.reverse();for(const e of o)r+=this._GetHTMLCloseTag(e);return r+="
",this._htmlString=r,this._isHtmlStringUpToDate=!0,this._htmlString}Tick(){const t=this._runtime.GetWallTime();if(t>=this._typewriterEndTime)this._CancelTypewriter(),this.Trigger(e.Plugins.Text.Cnds.OnTypewriterTextFinished),this._runtime.UpdateRender();else{let i=e.relerp(this._typewriterStartTime,this._typewriterEndTime,t,0,this._typewriterLength);i=Math.floor(i),i!==this._rendererText.GetDrawMaxCharacterCount()&&(this._rendererText.SetDrawMaxCharacterCount(i),this._runtime.UpdateRender())}}GetDebuggerProperties(){const e="plugins.text";return[{title:e+".name",properties:[{name:e+".properties.text.name",value:this.GetText(),onedit:e=>this._SetText(e)},{name:e+".properties.font.name",value:this._GetFontFace(),onedit:e=>this._SetFontFace(e)},{name:e+".properties.size.name",value:this._GetFontSize(),onedit:e=>this._SetFontSize(e)},{name:e+".properties.line-height.name",value:this._GetLineHeight(),onedit:e=>this._SetLineHeight(e)},{name:e+".properties.bold.name",value:this._IsBold(),onedit:e=>this._SetBold(e)},{name:e+".properties.italic.name",value:this._IsItalic(),onedit:e=>this._SetItalic(e)},{name:e+".debugger.text-width",value:this._GetTextWidth()},{name:e+".debugger.text-height",value:this._GetTextHeight()}]}]}GetScriptInterfaceClass(){return self.ITextInstance}};const C=new WeakMap,F=new Map([["left",0],["center",1],["right",2]]),A=new Map([["top",0],["center",1],["bottom",2]]),M=["ltr","rtl"];new Set(["auto","fixed"]);self.ITextInstance=class extends self.IWorldInstance{constructor(){super(),C.set(this,self.IInstance._GetInitInst().GetSdkInstance())}get text(){return C.get(this).GetText()}set text(e){t.RequireString(e);const i=C.get(this);i._CancelTypewriter(),i._SetText(e)}typewriterText(e,i){t.RequireString(e),t.RequireFiniteNumber(i);const r=C.get(this);r._CancelTypewriter(),r._StartTypewriter(e,i)}typewriterFinish(){C.get(this)._FinishTypewriter()}set fontFace(e){t.RequireString(e),C.get(this)._SetFontFace(e)}get fontFace(){return C.get(this)._GetFontFace()}set isBold(e){C.get(this)._SetBold(e)}get isBold(){return C.get(this)._IsBold()}set isItalic(e){C.get(this)._SetItalic(e)}get isItalic(){return C.get(this)._IsItalic()}set sizePt(e){t.RequireFiniteNumber(e),C.get(this)._SetFontSize(e)}get sizePt(){return C.get(this)._GetFontSize()}set fontColor(e){if(t.RequireArray(e),e.length<3)throw new Error("expected 3 elements");b.setRgb(e[0],e[1],e[2]),C.get(this)._SetFontColor(b)}get fontColor(){const e=C.get(this)._GetFontColor();return[e.getR(),e.getG(),e.getB()]}set lineHeight(e){t.RequireFiniteNumber(e),C.get(this)._SetLineHeight(e)}get lineHeight(){return C.get(this)._GetLineHeight()}set horizontalAlign(e){t.RequireString(e);const i=F.get(e);if(void 0===i)throw new Error("invalid mode");C.get(this)._SetHAlign(i)}get horizontalAlign(){return x[C.get(this)._GetHAlign()]}set verticalAlign(e){t.RequireString(e);const i=A.get(e);if(void 0===i)throw new Error("invalid mode");C.get(this)._SetVAlign(i)}get verticalAlign(){return G[C.get(this)._GetVAlign()]}set wordWrapMode(e){if(!m.includes(e))throw new Error("invalid mode");C.get(this)._SetWrapMode(e)}get wordWrapMode(){return C.get(this)._GetWrapMode()}set textDirection(e){t.RequireString(e);const i=M.indexOf(e);if(-1===i)throw new Error("invalid text direction");C.get(this)._SetTextDirection(i)}get textDirection(){return M[C.get(this)._GetTextDirection()]}set readAloud(e){C.get(this)._SetReadAloud(!!e)}get readAloud(){return C.get(this)._IsReadAloud()}setFixedResolutionMode(e){t.RequireFiniteNumber(e);const i=C.get(this);i._SetResolutionMode("fixed"),i._SetFixedScaleFactor(e)}setAutoResolutionMode(){C.get(this)._SetResolutionMode("auto")}get textWidth(){return C.get(this)._GetTextWidth()}get textHeight(){return C.get(this)._GetTextHeight()}getTextSize(){const e=C.get(this);return[e._GetTextWidth(),e._GetTextHeight()]}hasTagAtPosition(e,i,r){return t.RequireString(e),t.RequireFiniteNumber(i),t.RequireFiniteNumber(r),C.get(this)._HasTagAtPosition(e,i,r)}getTagAtPosition(e,i){return t.RequireFiniteNumber(e),t.RequireFiniteNumber(i),C.get(this)._GetTagAtPosition(e,i)}getTagPositionAndSize(e,i=0){return t.RequireString(e),t.RequireFiniteNumber(i),C.get(this)._GetTagPosition(e,i)}getTagCount(e){return t.RequireString(e),C.get(this)._GetTagCount(e)}changeIconSet(e){const t=C.get(this),i=t.GetRuntime()._UnwrapIObjectClass(e);t._SetIconObjectClass(i)}getAsHtmlString(){return C.get(this)._UpdateHTMLString()}}}{const e=self.C3;e.Plugins.Text.Cnds={CompareText(t,i){return i?this._text===t:e.equalsNoCase(this._text,t)},IsRunningTypewriterText(){return-1!==this._typewriterEndTime},OnTypewriterTextFinished:()=>!0,HasTagAtPosition(e,t,i){return this._HasTagAtPosition(e,t,i)}}}{const e=self.C3,t=e.New(e.Color);e.Plugins.Text.Acts={SetText(e){this._CancelTypewriter(),"number"==typeof e&&e<1e9&&(e=Math.round(1e10*e)/1e10),this._SetText(e.toString())},AppendText(e){this._CancelTypewriter(),"number"==typeof e&&e<1e9&&(e=Math.round(1e10*e)/1e10),(e=e.toString())&&this._SetText(this._text+e)},TypewriterText(e,t){this._CancelTypewriter(),"number"==typeof e&&e<1e9&&(e=Math.round(1e10*e)/1e10),this._StartTypewriter(e.toString(),t)},SetFontFace(e,t){let i=!1,r=!1;switch(t){case 1:i=!0;break;case 2:r=!0;break;case 3:i=!0,r=!0}e===this._faceName&&i===this._isBold&&r===this._isItalic||(this._SetFontFace(e),this._SetBold(i),this._SetItalic(r))},SetFontSize(e){this._SetFontSize(e)},SetFontColor(e){t.setFromRgbValue(e),t.clamp(),this._SetFontColor(t)},SetWebFont(e,t){console.warn("[Text] 'Set web font' action is deprecated and no longer has any effect")},SetEffect(e){this.GetWorldInfo().SetBlendMode(e),this._runtime.UpdateRender()},TypewriterFinish(){this._FinishTypewriter()},SetLineHeight(e){this._SetLineHeight(e)},SetHAlign(e){this._SetHAlign(e)},SetVAlign(e){this._SetVAlign(e)},SetWrapping(e){this._SetWrapModeByIndex(e)},SetTextDirection(e){this._SetTextDirection(e)},ChangeIconSet(e){this._SetIconObjectClass(e)},UpdateHTML(){return this._UpdateHTMLString()},SetReadAloud(e){this._SetReadAloud(e)},SetResolutionMode(e,t){this._SetResolutionMode(["auto","fixed"][e]),this._SetFixedScaleFactor(t)}}}{const e=self.C3;e.Plugins.Text.Exps={Text(){return this._text},PlainText(){return this._enableBBcode?e.BBString.StripAnyTags(this._text):this._text},FaceName(){return this._faceName},FaceSize(){return this._ptSize},TextWidth(){return this._GetTextWidth()},TextHeight(){return this._GetTextHeight()},LineHeight(){return this._lineHeightOffset},TagAtPosition(e,t){return this._GetTagAtPosition(e,t)},TagCount(e){return this._GetTagCount(e)},TagX(e,t){const i=this._GetTagPosition(e,t);return i?i.x:0},TagY(e,t){const i=this._GetTagPosition(e,t);return i?i.y:0},TagWidth(e,t){const i=this._GetTagPosition(e,t);return i?i.width:0},TagHeight(e,t){const i=this._GetTagPosition(e,t);return i?i.height:0},AsHTML(){return this._htmlString}}} } // scripts/plugins/Particles/c3runtime/runtime.js { {const e=self.C3;e.Plugins.Particles=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const t=self.C3;t.Plugins.Particles.Type=class extends t.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){this.GetImageInfo().LoadAsset(this._runtime)}LoadTextures(e){return this.GetImageInfo().LoadStaticTexture(e)}ReleaseTextures(){this.GetImageInfo().ReleaseTexture()}}}{const i=self.C3,n=self.C3X,a=0,r=1,s=2,o=3,c=4,l=5,S=6,d=7,p=8,G=9,m=10,u=11,h=12,g=13,R=14,I=15,y=16,_=17,E=18,P=19,f=20,b=0,C=1,O=new i.Rect,w=new i.AABB3D;i.Plugins.Particles.Instance=class extends i.SDKWorldInstanceBase{constructor(e,t){super(e),this._isFirstTick=!0;const n=i.New(self.ParticleEngine);this._particleEngine=n,n.ononeshotfinish=()=>this._OnOneShotFinish(),this._spawnObjectClass=null,this._particleUpdateCallback=(e,t,i,n,a,r)=>this._OnParticleUpdate(e,t,i,n,a,r),this._particleDestroyCallback=e=>this._OnParticleDestroy(e),this._hasAnyDefaultParticle=!0;let b=!0;t&&(n.SetRate(t[a]),n.SetSprayCone(i.toRadians(t[r])),n.SetSprayType(t[s]?"one-shot":"continuous-spray"),this._SetParticleObjectClass(this._runtime.GetObjectClassBySID(t[o])),b=t[c],n.SetInitSpeed(t[l]),n.SetInitSize(t[S]),n.SetInitOpacity(t[d]/100),n.SetGrowRate(t[p]),n.SetInitXRandom(t[G]),n.SetInitYRandom(t[m]),n.SetInitSpeedRandom(t[u]),n.SetInitSizeRandom(t[h]),n.SetGrowRandom(t[g]),n.SetAcceleration(t[R]),n.SetGravity(t[I]),n.SetLifeAngleRandom(t[y]),n.SetLifeSpeedRandom(t[_]),n.SetLifeOpacityRandom(t[E]),n.SetDestroyModeIndex(t[P]),n.SetTimeout(t[f])),this._UpdateEngineParameters(),this._spawnObjectClass&&(this._hasAnyDefaultParticle=!1),"one-shot"===n.GetSprayType()?n.CreateOneShotSpray():n.SetSpraying(!0);const C=this.GetWorldInfo();C.SetVisible(b),C.SetBboxChangeEventEnabled(!0),this._inst.Dispatcher().addEventListener("bboxchange",()=>{w.setFromRect(this._particleEngine.GetBoundingBox()),C.OverwriteBoundingBox(w)}),this.GetRuntime().GetRenderer().IsWebGPU()&&C.SetUsePointsShaderProgram(),this._afterLoad=e=>this._OnAfterLoad(e),this.GetRuntime().Dispatcher().addEventListener("afterload",this._afterLoad),this._StartTicking()}Release(){this.GetRuntime().Dispatcher().removeEventListener("afterload",this._afterLoad),this._afterLoad=null,this._particleEngine.Release(),this._particleEngine=null,this._particleUpdateCallback=null,this._particleDestroyCallback=null,super.Release()}GetParticleEngine(){return this._particleEngine}_SetRate(e){this._particleEngine.SetRate(e),"one-shot"===this._particleEngine.GetSprayType()&&this._isFirstTick&&this._particleEngine.SetParticleCount(e)}_SetParticleObjectClass(e){e===this.GetObjectClass()&&(e=null),e!==this._spawnObjectClass&&(this._spawnObjectClass=e,this._particleEngine.onparticlecreate=e?e=>this._OnParticleCreate(e):null,this._spawnObjectClass||(this._hasAnyDefaultParticle=!0))}_UpdateEngineParameters(){const e=this._particleEngine,t=this.GetWorldInfo();e.SetMasterOpacity(t.GetOpacity()),e.SetPixelRounding(this._runtime.IsPixelRoundingEnabled()),e.SetSpawnX(t.GetX()),e.SetSpawnY(t.GetY()),e.SetSpawnAngle(t.GetAngle()),e.SetInitSizeScale(Math.abs(t.GetSceneGraphScale()))}_OnOneShotFinish(){this._runtime.DestroyInstance(this._inst)}Draw(e){if(!this._hasAnyDefaultParticle)return;const t=this._objectClass.GetImageInfo(),i=t.GetTexture();if(!i)return;const n=this.GetWorldInfo(),a=n.GetLayer(),r=O;this._runtime.GetCanvasManager().IsPastingToDrawingCanvas()?r.set(-1/0,-1/0,1/0,1/0):a.Has3DCamera()?a.CalculateViewport3D(n.GetTotalZ(),r):a.GetViewportForZ(n.GetTotalZ(),r),e.SetTexture(i,n.GetActiveSampling());const s=a.Get2DScaleFactorToZ(n.GetTotalZ());this._particleEngine.SetParticleScale(a.GetRenderScale()*s),this._particleEngine.Draw(e,t.GetTexQuad(),r,a.Has3DCamera())}SaveToJson(){const e=this._particleEngine;return{"r":e.GetRate(),"sc":e.GetSprayCone(),"st":e.GetSprayType(),"isp":e.GetInitSpeed(),"isz":e.GetInitSize(),"io":e.GetInitOpacity(),"gr":e.GetGrowRate(),"xr":e.GetInitXRandom(),"yr":e.GetInitYRandom(),"spr":e.GetInitSpeedRandom(),"szr":e.GetInitSizeRandom(),"grnd":e.GetGrowRandom(),"acc":e.GetAcceleration(),"g":e.GetGravity(),"lar":e.GetLifeAngleRandom(),"lsr":e.GetLifeSpeedRandom(),"lor":e.GetLifeOpacityRandom(),"dm":e.GetDestroyModeIndex(),"to":e.GetTimeout(),"s":e.IsSpraying(),"pcc":e._GetCreateCounter(),"ft":this._isFirstTick,"soc":this._spawnObjectClass?this._spawnObjectClass.GetSID():null,"p":e.GetParticles().map(e=>e.toJSON())}}LoadFromJson(e,t){const i=this._particleEngine;if(i.SetRate(e["r"]),i.SetSprayCone(e["sc"]),i.SetSprayType(e["st"]),i.SetInitSpeed(e["isp"]),i.SetInitSize(e["isz"]),i.SetInitOpacity(e["io"]),i.SetGrowRate(e["gr"]),i.SetInitXRandom(e["xr"]),i.SetInitYRandom(e["yr"]),i.SetInitSpeedRandom(e["spr"]),i.SetInitSizeRandom(e["szr"]),i.SetGrowRandom(e["grnd"]),i.SetAcceleration(e["acc"]),i.SetGravity(e["g"]),i.SetLifeAngleRandom(e["lar"]),i.SetLifeSpeedRandom(e["lsr"]),i.SetLifeOpacityRandom(e["lor"]),i.SetDestroyModeIndex(e["dm"]),i.SetTimeout(e["to"]),i.SetSpraying(e["s"]),i._SetCreateCounter(e["pcc"]),this._isFirstTick=e["ft"],e.hasOwnProperty("soc")){const t=this.GetRuntime().GetObjectClassBySID(e["soc"]);t&&this._SetParticleObjectClass(t)}const n=e["p"];i.SetParticleCount(n.length,!1);const a=i.GetParticles();for(let e=0,t=a.length;e0;)this._particleEngine.Tick(t),e-=t;this._particleEngine.IsSpraying()&&this._runtime.UpdateRender(),this.GetWorldInfo().SetBboxChanged(),this._isFirstTick=!1}_OnParticleCreate(e,t){let i;"number"==typeof t&&(i=this._runtime.GetInstanceByUID(t)),i&&i.GetObjectClass()!==this._spawnObjectClass&&(i=null),i||(i=this._runtime.CreateInstance(this._spawnObjectClass,this.GetWorldInfo().GetLayer(),e.GetX(),e.GetY()));const n=i.GetWorldInfo();return n.SetSize(e.GetSize(),e.GetSize()),n.SetAngle(e.GetAngle()),n.SetOpacity(e.GetOpacity()),n.SetUnpremultipliedColor(this.GetWorldInfo().GetUnpremultipliedColor()),n.SetBboxChanged(),n.ZOrderMoveAdjacentToInstance(this.GetInstance(),!0),i._TriggerOnCreated(),e.SetUpdateCallback(this._particleUpdateCallback),e.SetDestroyCallback(this._particleDestroyCallback),i}_OnParticleUpdate(e,t,i,n,a,r){if(e.IsDestroyed())return;const s=e.GetWorldInfo();s.OffsetXY(t,i),s.SetSize(s.GetWidth()+n,s.GetHeight()+n),s.SetAngle(s.GetAngle()+a),s.SetOpacity(s.GetOpacity()+r),s.SetBboxChanged()}_OnParticleDestroy(e){e.IsDestroyed()||this._runtime.DestroyInstance(e)}GetPropertyValueByIndex(e){const t=this._particleEngine;switch(e){case a:return t.GetRate();case r:return i.toDegrees(t.GetSprayCone());case s:return"one-shot"===t.GetSprayType()?C:b;case l:return t.GetInitSpeed();case S:return t.GetInitSize();case d:return 100*t.GetInitOpacity();case p:return t.GetGrowRate();case G:return t.GetInitXRandom();case m:return t.GetInitYRandom();case u:return t.GetInitSpeedRandom();case h:return t.GetInitSizeRandom();case g:return t.GetGrowRandom();case R:return t.GetAcceleration();case I:return t.GetGravity();case y:return t.GetLifeAngleRandom();case _:return t.GetLifeSpeedRandom();case E:return t.GetLifeOpacityRandom();case P:return t.GetDestroyModeIndex();case f:return t.GetTimeout()}}SetPropertyValueByIndex(e,t){const n=this._particleEngine;switch(e){case a:n.SetRate(t);break;case r:n.SetSprayCone(i.toRadians(t));break;case s:n.SetSprayType(t?"one-shot":"continuous-spray");break;case l:n.SetInitSpeed(t);break;case S:n.SetInitSize(t);break;case d:n.SetInitOpacity(t/100);break;case p:n.SetGrowRate(t);break;case G:n.SetInitXRandom(t);break;case m:n.SetInitYRandom(t);break;case u:n.SetInitSpeedRandom(t);break;case h:n.SetInitSizeRandom(t);break;case g:n.SetGrowRandom(t);break;case R:n.SetAcceleration(t);break;case I:n.SetGravity(t);break;case y:n.SetLifeAngleRandom(t);break;case _:n.SetLifeSpeedRandom(t);break;case E:n.SetLifeOpacityRandom(t);break;case P:n.SetDestroyModeIndex(t);break;case f:n.SetTimeout(t)}}GetDebuggerProperties(){const e="plugins.particles",t=e+".properties",n=e+".debugger",a=this._particleEngine;return[{title:e+".name",properties:[{name:n+".particle-count",value:a.GetParticleCount()},{name:t+".type.name",value:[t+".type.items."+a.GetSprayType()]},{name:n+".is-spraying",value:a.IsSpraying(),onedit:e=>a.SetSpraying(e)},{name:t+".rate.name",value:a.GetRate(),onedit:e=>a.SetRate(e)},{name:t+".spray-cone.name",value:i.toDegrees(a.GetSprayCone()),onedit:e=>a.SetSprayCone(i.toRadians(e))},{name:t+".speed.name",value:a.GetInitSpeed(),onedit:e=>a.SetInitSpeed(e)},{name:t+".size.name",value:a.GetInitSize(),onedit:e=>a.SetInitSize(e)},{name:t+".opacity.name",value:a.GetInitOpacity(),onedit:e=>a.SetInitOpacity(e)},{name:t+".grow-rate.name",value:a.GetGrowRate(),onedit:e=>a.SetGrowRate(e)},{name:t+".x-randomiser.name",value:a.GetInitXRandom(),onedit:e=>a.SetInitXRandom(e)},{name:t+".y-randomiser.name",value:a.GetInitYRandom(),onedit:e=>a.SetInitYRandom(e)},{name:t+".initial-speed-randomiser.name",value:a.GetInitSpeedRandom(),onedit:e=>a.SetInitSpeedRandom(e)},{name:t+".size-randomiser.name",value:a.GetInitSizeRandom(),onedit:e=>a.SetInitSizeRandom(e)},{name:t+".grow-rate-randomiser.name",value:a.GetGrowRandom(),onedit:e=>a.SetGrowRandom(e)},{name:t+".acceleration.name",value:a.GetAcceleration(),onedit:e=>a.SetAcceleration(e)},{name:t+".gravity.name",value:a.GetGravity(),onedit:e=>a.SetGravity(e)},{name:t+".angle-randomiser.name",value:a.GetLifeAngleRandom(),onedit:e=>a.SetLifeAngleRandom(e)},{name:t+".life-speed-randomiser.name",value:a.GetLifeSpeedRandom(),onedit:e=>a.SetLifeSpeedRandom(e)},{name:t+".opacity-randomiser.name",value:a.GetLifeOpacityRandom(),onedit:e=>a.SetLifeOpacityRandom(e)},{name:t+".timeout.name",value:a.GetTimeout(),onedit:e=>a.SetTimeout(e)}]}]}GetScriptInterfaceClass(){return self.IParticlesInstance}};const D=new WeakMap;function GetParticleEngine(e){return D.get(e).GetParticleEngine()}self.IParticlesInstance=class extends self.IWorldInstance{constructor(){super(),D.set(this,self.IInstance._GetInitInst().GetSdkInstance())}set isSpraying(e){GetParticleEngine(this).SetSpraying(!!e)}get isSpraying(){return GetParticleEngine(this).IsSpraying()}set rate(e){n.RequireFiniteNumber(e),D.get(this)._SetRate(e)}get rate(){return GetParticleEngine(this).GetRate()}set sprayCone(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetSprayCone(e)}get sprayCone(){return GetParticleEngine(this).GetSprayCone()}set initSpeed(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetInitSpeed(e)}get initSpeed(){return GetParticleEngine(this).GetInitSpeed()}set initSize(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetInitSize(e)}get initSize(){return GetParticleEngine(this).GetInitSize()}set initOpacity(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetInitOpacity(e)}get initOpacity(){return GetParticleEngine(this).GetInitOpacity()}set initXRandom(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetInitXRandom(e)}get initXRandom(){return GetParticleEngine(this).GetInitXRandom()}set initYRandom(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetInitYRandom(e)}get initYRandom(){return GetParticleEngine(this).GetInitYRandom()}set initSpeedRandom(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetInitSpeedRandom(e)}get initSpeedRandom(){return GetParticleEngine(this).GetInitSpeedRandom()}set initSizeRandom(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetInitSizeRandom(e)}get initSizeRandom(){return GetParticleEngine(this).GetInitSizeRandom()}set initGrowRate(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetGrowRate(e)}get initGrowRate(){return GetParticleEngine(this).GetGrowRate()}set initGrowRandom(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetGrowRandom(e)}get initGrowRandom(){return GetParticleEngine(this).GetGrowRandom()}set acceleration(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetAcceleration(e)}get acceleration(){return GetParticleEngine(this).GetAcceleration()}set gravity(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetGravity(e)}get gravity(){return GetParticleEngine(this).GetGravity()}set lifeAngleRandom(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetLifeAngleRandom(e)}get lifeAngleRandom(){return GetParticleEngine(this).GetLifeAngleRandom()}set lifeSpeedRandom(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetLifeSpeedRandom(e)}get lifeSpeedRandom(){return GetParticleEngine(this).GetLifeSpeedRandom()}set lifeOpacityRandom(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetLifeOpacityRandom(e)}get lifeOpacityRandom(){return GetParticleEngine(this).GetLifeOpacityRandom()}set timeout(e){n.RequireFiniteNumber(e),GetParticleEngine(this).SetTimeout(e)}get timeout(){return GetParticleEngine(this).GetTimeout()}fastForward(e){n.RequireFiniteNumber(e),D.get(this)._FastForward(e)}setParticleObjectClass(e){const t=D.get(this);e?t._SetParticleObjectClass(t.GetRuntime()._UnwrapIObjectClass(e)):t._SetParticleObjectClass(null)}}}self.C3.Plugins.Particles.Cnds={IsSpraying(){return this._particleEngine.IsSpraying()}};{const T=self.C3;T.Plugins.Particles.Acts={SetSpraying(e){this._particleEngine.SetSpraying(0!==e)},SetRate(e){this._SetRate(e)},SetParticleObject(e){this._SetParticleObjectClass(e)},UnsetParticleObject(){this._SetParticleObjectClass(null)},SetSprayCone(e){this._particleEngine.SetSprayCone(T.toRadians(e))},SetInitSpeed(e){this._particleEngine.SetInitSpeed(e)},SetInitSize(e){this._particleEngine.SetInitSize(e)},SetInitOpacity(e){this._particleEngine.SetInitOpacity(e/100)},SetGrowRate(e){this._particleEngine.SetGrowRate(e)},SetXRandomiser(e){this._particleEngine.SetInitXRandom(e)},SetYRandomiser(e){this._particleEngine.SetInitYRandom(e)},SetSpeedRandomiser(e){this._particleEngine.SetInitSpeedRandom(e)},SetSizeRandomiser(e){this._particleEngine.SetInitSizeRandom(e)},SetGrowRateRandomiser(e){this._particleEngine.SetGrowRandom(e)},SetParticleAcc(e){this._particleEngine.SetAcceleration(e)},SetGravity(e){this._particleEngine.SetGravity(e)},SetAngleRandomiser(e){this._particleEngine.SetLifeAngleRandom(e)},SetLifeSpeedRandomiser(e){this._particleEngine.SetLifeSpeedRandom(e)},SetOpacityRandomiser(e){this._particleEngine.SetLifeOpacityRandom(e)},SetTimeout(e){this._particleEngine.SetTimeout(e)},FastForward(e){this._FastForward(e)},SetEffect(e){this.GetWorldInfo().SetBlendMode(e),this._runtime.UpdateRender()}}}{const A=self.C3;A.Plugins.Particles.Exps={ParticleCount(){return this._particleEngine.GetParticleCount()},Rate(){return this._particleEngine.GetRate()},SprayCone(){return A.toDegrees(this._particleEngine.GetSprayCone())},InitSpeed(){return this._particleEngine.GetInitSpeed()},InitSize(){return this._particleEngine.GetInitSize()},InitOpacity(){return 100*this._particleEngine.GetInitOpacity()},InitGrowRate(){return this._particleEngine.GetGrowRate()},XRandom(){return this._particleEngine.GetInitXRandom()},YRandom(){return this._particleEngine.GetInitYRandom()},InitSizeRandom(){return this._particleEngine.GetInitSizeRandom()},InitSpeedRandom(){return this._particleEngine.GetInitSpeedRandom()},InitGrowRandom(){return this._particleEngine.GetGrowRandom()},ParticleAcceleration(){return this._particleEngine.GetAcceleration()},Gravity(){return this._particleEngine.GetGravity()},ParticleAngleRandom(){return this._particleEngine.GetLifeAngleRandom()},ParticleSpeedRandom(){return this._particleEngine.GetLifeSpeedRandom()},ParticleOpacityRandom(){return this._particleEngine.GetLifeOpacityRandom()},Timeout(){return this._particleEngine.GetTimeout()}}} } // scripts/plugins/Particles/particleEngine.js { const C3=self.C3,inactiveParticles=[],MAX_RECYCLE_PARTICLES=1e3,VALID_SPRAY_TYPES=new Set(["continuous-spray","one-shot"]),DESTROY_MODES=["fade-to-invisible","timeout-expired","particle-stopped"],tempRect=C3.New(C3.Rect);self.ParticleEngine=class{constructor(){this._rate=0,this._sprayCone=0,this._sprayType="continuous-spray",this._isSpraying=!1,this._masterOpacity=0,this._isPixelRounding=!1,this._spawnX=0,this._spawnY=0,this._spawnAngle=0,this._initSpeed=0,this._initSize=0,this._initSizeScale=1,this._initOpacity=0,this._growRate=0,this._xRandom=0,this._yRandom=0,this._initSpeedRandom=0,this._initSizeRandom=0,this._growRandom=0,this._acceleration=0,this._gravity=0,this._lifeAngleRandom=0,this._lifeSpeedRandom=0,this._lifeOpacityRandom=0,this._destroyMode=0,this._timeout=0,this._createCounter=0,this._particleScale=1,this.ononeshotfinish=null,this.onparticlecreate=null,this._particles=[],this._boundingBox=new C3.Rect,this._color=new C3.Color,this._devicePixelRatio=globalThis.devicePixelRatio||1}Release(){this.Cancel(),C3.clearArray(this._particles),this._particles=null,this.ononeshotfinish=null,this.onparticlecreate=null,this._boundingBox=null,this._color=null}Cancel(){const t=this._particles;for(let e=0,i=t.length;e1e3&&C3.truncateArray(inactiveParticles,1e3),this._isSpraying=!1}CreateOneShotSpray(){for(let t=0,e=this._rate;t1e3&&C3.truncateArray(inactiveParticles,1e3)}else if(t>i.length){const n=t-i.length;for(let t=0;t1e3&&C3.truncateArray(inactiveParticles,1e3)}_MaybeFinishOneShot(){"one-shot"===this._sprayType&&0===this._particles.length&&this._isSpraying&&(this.ononeshotfinish&&this.ononeshotfinish(),this._isSpraying=!1)}Draw(t,e,i,n){this._devicePixelRatio=globalThis.devicePixelRatio||1,tempRect.set(e.getTlx(),e.getTly(),e.getBrx(),e.getBry()),t.StartRenderingPoints(tempRect),this._color.copy(t.GetColor());const s=this._particles;for(let r=0,a=s.length;r=1&&(2===e.GetDestroyModeIndex()?this._speed>0:this._aget.GetMaxPointSize()||nthis._SetImageOffsetX(e)},{name:e+".image-offset-y.name",value:this._GetImageOffsetY(),onedit:e=>this._SetImageOffsetY(e)},{name:e+".image-scale-x.name",value:100*this._GetImageScaleX(),onedit:e=>this._SetImageScaleX(e/100)},{name:e+".image-scale-y.name",value:100*this._GetImageScaleY(),onedit:e=>this._SetImageScaleY(e/100)},{name:e+".image-angle.name",value:i.toDegrees(this._GetImageAngle()),onedit:e=>this._SetImageAngle(i.toRadians(e))}]},{title:e+".tile-randomization.name",properties:[{name:e+".enable-tile-randomization.name",value:this._IsTileRandomizationEnabled(),onedit:e=>this._SetTileRandomizationEnabled(e)},{name:e+".x-random.name",value:100*this._GetTileXRandom(),onedit:e=>this._SetTileXRandom(e/100)},{name:e+".y-random.name",value:100*this._GetTileYRandom(),onedit:e=>this._SetTileYRandom(e/100)},{name:e+".angle-random.name",value:100*this._GetTileAngleRandom(),onedit:e=>this._SetTileAngleRandom(e/100)},{name:e+".blend-margin-x.name",value:100*this._GetTileBlendMarginX(),onedit:e=>this._SetTileBlendMarginX(e/100)},{name:e+".blend-margin-y.name",value:100*this._GetTileBlendMarginY(),onedit:e=>this._SetTileBlendMarginY(e/100)}]}]}GetPropertyValueByIndex(e){switch(e){case s:return this._GetImageOffsetX();case r:return this._GetImageOffsetY();case l:return this._GetImageScaleX();case g:return this._GetImageScaleY();case m:return this._GetImageAngle();case d:return this._IsTileRandomizationEnabled();case h:return this._GetTileXRandom();case o:return this._GetTileYRandom();case _:return this._GetTileAngleRandom();case u:return this._GetTileBlendMarginX();case R:return this._GetTileBlendMarginY()}}SetPropertyValueByIndex(e,t){switch(e){case s:this._SetImageOffsetX(t);break;case r:this._SetImageOffsetY(t);break;case l:this._SetImageScaleX(t);break;case g:this._SetImageScaleY(t);break;case m:this._SetImageAngle(t);break;case d:this._SetTileRandomizationEnabled(!!t);break;case h:this._SetTileXRandom(t);break;case o:this._SetTileYRandom(t);break;case _:this._SetTileAngleRandom(t);break;case u:this._SetTileBlendMarginX(t);break;case R:this._SetTileBlendMarginY(t)}}GetScriptInterfaceClass(){return globalThis.ITiledBackgroundInstance}},globalThis.ITiledBackgroundInstance=class extends globalThis.IWorldInstance{#e;constructor(){super(),this.#e=globalThis.IInstance._GetInitInst().GetSdkInstance()}set imageOffsetX(e){a.RequireFiniteNumber(e),this.#e._SetImageOffsetX(e)}get imageOffsetX(){return this.#e._GetImageOffsetX()}set imageOffsetY(e){a.RequireFiniteNumber(e),this.#e._SetImageOffsetY(e)}get imageOffsetY(){return this.#e._GetImageOffsetY()}setImageOffset(e,t){a.RequireFiniteNumber(e),a.RequireFiniteNumber(t);const i=this.#e;i._SetImageOffsetX(e),i._SetImageOffsetY(t)}getImageOffset(){const e=this.#e;return[e._GetImageOffsetX(),e._GetImageOffsetY()]}set imageScaleX(e){a.RequireFiniteNumber(e),this.#e._SetImageScaleX(e)}get imageScaleX(){return this.#e._GetImageScaleX()}set imageScaleY(e){a.RequireFiniteNumber(e),this.#e._SetImageScaleY(e)}get imageScaleY(){return this.#e._GetImageScaleY()}setImageScale(e,t){a.RequireFiniteNumber(e),a.RequireFiniteNumber(t);const i=this.#e;i._SetImageScaleX(e),i._SetImageScaleY(t)}getImageScale(){const e=this.#e;return[e._GetImageScaleX(),e._GetImageScaleY()]}set imageAngle(e){a.RequireFiniteNumber(e),this.#e._SetImageAngle(e)}get imageAngle(){return this.#e._GetImageAngle()}set imageAngleDegrees(e){a.RequireFiniteNumber(e),this.#e._SetImageAngle(i.toRadians(e))}get imageAngleDegrees(){return i.toDegrees(this.#e._GetImageAngle())}get imageWidth(){return this.#e.GetCurrentImageInfo().GetWidth()}get imageHeight(){return this.#e.GetCurrentImageInfo().GetHeight()}getImageSize(){const e=this.#e.GetCurrentImageInfo();return[e.GetWidth(),e.GetHeight()]}set enableTileRandomization(e){this.#e._SetTileRandomizationEnabled(!!e)}get enableTileRandomization(){return this.#e._IsTileRandomizationEnabled()}set tileXRandom(e){a.RequireFiniteNumber(e),this.#e._SetTileXRandom(e)}get tileXRandom(){return this.#e._GetTileXRandom()}set tileYRandom(e){a.RequireFiniteNumber(e),this.#e._SetTileYRandom(e)}get tileYRandom(){return this.#e._GetTileYRandom()}setTileRandom(e,t){a.RequireFiniteNumber(e),a.RequireFiniteNumber(t);const i=this.#e;i._SetTileXRandom(e),i._SetTileYRandom(t)}getTileRandom(){const e=this.#e;return[e._GetTileXRandom(),e._GetTileYRandom()]}set tileAngleRandom(e){a.RequireFiniteNumber(e),this.#e._SetTileAngleRandom(e)}get tileAngleRandom(){return this.#e._GetTileAngleRandom()}set tileBlendMarginX(e){a.RequireFiniteNumber(e),this.#e._SetTileBlendMarginX(e)}get tileBlendMarginX(){return this.#e._GetTileBlendMarginX()}set tileBlendMarginY(e){a.RequireFiniteNumber(e),this.#e._SetTileBlendMarginY(e)}get tileBlendMarginY(){return this.#e._GetTileBlendMarginY()}setTileBlendMargin(e,t){a.RequireFiniteNumber(e),a.RequireFiniteNumber(t);const i=this.#e;i._SetTileBlendMarginX(e),i._SetTileBlendMarginY(t)}getTileBlendMargin(){const e=this.#e;return[e._GetTileBlendMarginX(),e._GetTileBlendMarginY()]}async replaceImage(e){a.RequireInstanceOf(e,Blob);const t=this.#e,n=t.GetRuntime(),s=i.New(i.ImageInfo);s.LoadDynamicBlobAsset(n,e),await s.LoadStaticTexture(n.GetRenderer(),{wrapX:t.GetSdkType().GetWrapModeX(),wrapY:t.GetSdkType().GetWrapModeY()}),t.WasReleased()?s.Release():(t._ReleaseOwnImage(),t._ownImageInfo=s,n.UpdateRender())}}}self.C3.Plugins.TiledBg.Cnds={OnURLLoaded:()=>!0,OnURLFailed:()=>!0,IsTileRandomizationEnabled(){return this._IsTileRandomizationEnabled()}};{const c=self.C3;c.Plugins.TiledBg.Acts={SetImageOffsetX(e){this._SetImageOffsetX(e)},SetImageOffsetY(e){this._SetImageOffsetY(e)},SetImageScaleX(e){this._SetImageScaleX(e/100)},SetImageScaleY(e){this._SetImageScaleY(e/100)},SetImageAngle(e){this._SetImageAngle(c.toRadians(e))},SetTileRandomizationEnabled(e){this._SetTileRandomizationEnabled(e)},SetTilePosRandom(e,t){this._SetTileXRandom(e/100),this._SetTileYRandom(t/100)},SetTileAngleRandom(e){this._SetTileAngleRandom(e/100)},SetTileBlendMargin(e,t){this._SetTileBlendMarginX(e/100),this._SetTileBlendMarginY(t/100)},SetEffect(e){this.GetWorldInfo().SetBlendMode(e),this._runtime.UpdateRender()},async LoadURL(e,t){if(this._ownImageInfo&&this._ownImageInfo.GetURL()===e)return;const i=this._runtime,a=c.New(c.ImageInfo);try{if(await a.LoadDynamicAsset(i,e,!0),!a.IsLoaded())throw new Error("image failed to load");if(this.WasReleased())return a.Release(),null;if(!await a.LoadStaticTexture(i.GetRenderer(),{wrapX:this.GetSdkType().GetWrapModeX(),wrapY:this.GetSdkType().GetWrapModeY()}))return}catch(e){return console.error("Load image from URL failed: ",e),void(this.WasReleased()||this.Trigger(c.Plugins.TiledBg.Cnds.OnURLFailed))}this.WasReleased()?a.Release():(this._ReleaseOwnImage(),this._ownImageInfo=a,i.UpdateRender(),await this.TriggerAsync(c.Plugins.TiledBg.Cnds.OnURLLoaded))}}}{const T=self.C3;T.Plugins.TiledBg.Exps={ImageWidth(){return this.GetCurrentImageInfo().GetWidth()},ImageHeight(){return this.GetCurrentImageInfo().GetHeight()},ImageOffsetX(){return this._imageOffsetX},ImageOffsetY(){return this._imageOffsetY},ImageScaleX(){return 100*this._imageScaleX},ImageScaleY(){return 100*this._imageScaleY},ImageAngle(){return T.toDegrees(this._imageAngle)},TileXRandom(){return 100*this._GetTileXRandom()},TileYRandom(){return 100*this._GetTileYRandom()},TileAngleRandom(){return 100*this._GetTileAngleRandom()},TileBlendMarginX(){return 100*this._GetTileBlendMarginX()},TileBlendMarginY(){return 100*this._GetTileBlendMarginY()}}} } // scripts/behaviors/Physics/c3runtime/runtime.js { {const t=self.C3,e=self.C3X;let i=null,s=null,n=[],o=null,r=null;const a="Physics_DisabledCollisions";function SetObjectTypeCollisionsEnabled(t,e,i){const s=t.GetSavedDataMap(),n=e.GetSavedDataMap();if(i){const i=s.get(a);i&&i.delete(e.GetSID());const o=n.get(a);o&&o.delete(t.GetSID())}else{let i=s.get(a);i||(i=new Set,s.set(a,i));let o=n.get(a);o||(o=new Set,n.set(a,o)),i.add(e.GetSID()),o.add(t.GetSID())}}t.Behaviors.Physics=class extends t.SDKBehaviorBase{constructor(t){super(t),r=this,this._world=null,this._worldG=10,this._worldScale=.02,this._worldManifold=null,this._lastUpdateTick=-1,this._steppingMode=1,this._velocityIterations=8,this._positionIterations=3,this._allCollisionsEnabled=!0,this._runtime.AddLoadPromise(this._LoadBox2DWasm())}GetScriptInterfaceClass(){return self.IPhysicsBehavior}async _LoadBox2DWasm(){const t=this._runtime.GetAssetManager().GetProjectFileUrl("box2d.wasm");await new Promise(e=>{self["Box2DWasmModule"]({"wasmBinaryFile":t}).then(t=>{o=t,this._InitBox2DWorld(),e()})})}_InitBox2DWorld(){const e=this._runtime.GetCollisionEngine();i=t.Behaviors.Physics.GetVec2(0,0),s=t.Behaviors.Physics.GetVec2(0,0),this._world=new o["b2World"](t.Behaviors.Physics.GetTempVec2A(0,this._worldG),!0);const n=new o["JSContactListener"];n["BeginContact"]=i=>{const s=o["wrapPointer"](i,o["b2Contact"]),n=t.Behaviors.Physics.Instance.LookupBehInstFromBody(s["GetFixtureA"]()["GetBody"]()),r=t.Behaviors.Physics.Instance.LookupBehInstFromBody(s["GetFixtureB"]()["GetBody"]());e.RegisterCollision(n.GetObjectInstance(),r.GetObjectInstance())},n["EndContact"]=()=>{},n["PreSolve"]=()=>{},n["PostSolve"]=()=>{},this._world["SetContactListener"](n);const r=new o["JSContactFilter"];r["ShouldCollide"]=(e,i)=>{if(this._allCollisionsEnabled)return!0;const s=o["wrapPointer"](e,o["b2Fixture"]),n=o["wrapPointer"](i,o["b2Fixture"]),r=t.Behaviors.Physics.Instance.LookupBehInstFromBody(s["GetBody"]()),l=t.Behaviors.Physics.Instance.LookupBehInstFromBody(n["GetBody"]()),h=r.GetObjectInstance().GetObjectClass(),_=l.GetObjectInstance().GetObjectClass(),c=h.GetSID(),d=_.GetSID(),u=h.GetSavedDataMap().get(a);if(u&&u.has(d))return!1;const y=_.GetSavedDataMap().get(a);return(!y||!y.has(c))&&r._CheckCollisionAllowed(l)},this._world["SetContactFilter"](r),this._worldManifold=new o["b2WorldManifold"]}Release(){super.Release()}GetBox2D(){return o}GetWorld(){return this._world}GetWorldScale(){return this._worldScale}GetSteppingMode(){return this._steppingMode}SetSteppingMode(t){this._steppingMode=t}SetLastUpdateTick(t){this._lastUpdateTick=t}GetLastUpdateTick(){return this._lastUpdateTick}SetVelocityIterations(t){this._velocityIterations=Math.max(t,1)}GetVelocityIterations(){return this._velocityIterations}SetPositionIterations(t){this._positionIterations=Math.max(t,1)}GetPositionIterations(){return this._positionIterations}SetIterations(t,e){this.SetVelocityIterations(t),this.SetPositionIterations(e)}GetGravity(){return this._worldG}SetGravity(e){e!==this._worldG&&(this._world["SetGravity"](t.Behaviors.Physics.GetTempVec2A(0,e)),this._worldG=e,this._WakeUpAllPhysicsBodies())}_WakeUpAllPhysicsBodies(){for(const e of this.GetInstances()){const i=t.Behaviors.Physics.Instance.LookupBehInstFromInst(e);if(!i)continue;const s=i.GetBody();s&&s["SetAwake"](!0)}}DisableShouldCollideFastPath(){this._allCollisionsEnabled=!1}SetCollisionsEnabled(t,e,i){if(i=!!i,t&&e){if(e.IsFamily())for(const s of e.GetFamilyMembers())SetObjectTypeCollisionsEnabled(t,s,i);else SetObjectTypeCollisionsEnabled(t,e,i);this.DisableShouldCollideFastPath()}}GetWorldManifold(){return this._worldManifold}static GetPhysicsCollisionKey(){return a}static GetVec2(t,e){if(n.length){const i=n.pop();return i["set_x"](t),i["set_y"](e),i}return new(0,o["b2Vec2"])(t,e)}static FreeVec2(t){n.push(t)}static GetTempVec2A(t,e){return i["set_x"](t),i["set_y"](e),i}static GetTempVec2B(t,e){return s["set_x"](t),s["set_y"](e),s}static CreatePolygonShape(t){const e=new(0,o["b2PolygonShape"]),i=o["_malloc"](8*t.length);let s=0;for(let e=0;e>2]=t[e]["get_x"](),o["HEAPF32"][i+(s+4)>>2]=t[e]["get_y"](),s+=8;const n=o["wrapPointer"](i,o["b2Vec2"]);return e["Set"](n,t.length),o["_free"](i),e}};const l=["fixed","variable"];self.IPhysicsBehavior=class extends self.IBehavior{constructor(){super()}set worldGravity(t){e.RequireFiniteNumber(t),r.SetGravity(t)}get worldGravity(){return r.GetGravity()}set steppingMode(t){const e=l.indexOf(t);if(e<0)throw new Error("invalid stepping mode");r.SetSteppingMode(l[e])}get steppingMode(){return l[r.GetSteppingMode()]}set velocityIterations(t){e.RequireFiniteNumber(t),r.SetVelocityIterations(t)}get velocityIterations(){return r.GetVelocityIterations()}set positionIterations(t){e.RequireFiniteNumber(t),r.SetPositionIterations(t)}get positionIterations(){return r.GetPositionIterations()}setCollisionsEnabled(t,e,i){const s=r.GetRuntime(),n=s._UnwrapIObjectClass(t),o=s._UnwrapIObjectClass(e);i=!!i,r.SetCollisionsEnabled(n,o,i)}}}{const h=self.C3;h.Behaviors.Physics.Type=class extends h.SDKBehaviorTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}}}{const _=self.C3,c=self.C3X,d=self.IBehaviorInstance,u=(self.assert,0),y=1,p=2,g=3,m=4,b=5,G=6,I=7,S=8,C=9,f=10,A=11,v=new WeakMap,D=new WeakMap,B=new WeakMap;function CollisionTagsAllowCollision(t,e,i){for(const s of e)if(t.has(s))return i;return!i}const F=-2147483648,w=1073741824,P=536870912,T=3758096384,M=_.Behaviors.Physics.GetTempVec2A,R=_.Behaviors.Physics.GetTempVec2B,E=_.New(_.Quad2D);_.Behaviors.Physics.Instance=class extends _.SDKBehaviorInstanceBase{constructor(t,e){super(t);const i=this.GetBehavior(),s=this.GetWorldInfo();this._box2d=i.GetBox2D(),this._world=i.GetWorld(),this._worldScale=i.GetWorldScale(),this._isImmovable=!1,this._collisionMask=0,this._actualCollisionMask=0,this._preventRotation=!1,this._density=1,this._friction=.5,this._restitution=.2,this._linearDamping=0,this._angularDamping=.01,this._isBullet=!1,this._isEnabled=!0,this._body=null,this._fixtures=[],this._myJoints=[],this._myCreatedJoints=[],this._joiningMe=new Set,this._lastKnownX=s.GetX(),this._lastKnownY=s.GetY(),this._lastKnownAngle=s.GetAngle(),this._lastWidth=0,this._lastHeight=0,this._lastTickOverride=!1,this._collisionFilterTags=new Set,this._isCollisionFilterInclusive=!1,e&&(this._isImmovable=!!e[u],this._collisionMask=e[y],this._SetCollisionFilter(0===e[g],_.splitStringAndNormalize(e[p])),this._preventRotation=!!e[m],this._density=e[b],this._friction=e[G],this._restitution=e[I],this._linearDamping=e[S],this._angularDamping=e[C],this._isBullet=!!e[f],this._isEnabled=!!e[A]);const n=this._runtime.Dispatcher();this._disposables=new _.CompositeDisposable(_.Disposable.From(n,"instancedestroy",t=>this._OnInstanceDestroyed(t.instance)),_.Disposable.From(n,"beforeload",()=>this._OnBeforeLoad()),_.Disposable.From(n,"afterload",()=>this._OnAfterLoad())),D.set(this._inst,this),this._isEnabled&&this._StartTicking()}PostCreate(){this._CreateBody()}Release(){this._DestroyMyJoints(),_.clearArray(this._myCreatedJoints),this._joiningMe.clear(),this._body&&(this._DestroyFixtures(),this._world["DestroyBody"](this._body),this._body=null),super.Release()}_CreateFixture(t){if(!this._body)return;const e=this._body["CreateFixture"](t);return this._fixtures.push(e),e}_DestroyFixtures(){if(this._body){for(const t of this._fixtures)this._body["DestroyFixture"](t);_.clearArray(this._fixtures)}}_GetBoundingQuadExcludingMesh(){const t=this.GetWorldInfo();return t.HasMesh()?(t.CalculateBbox(null,E,!1),E):t.GetBoundingQuad()}_Destroy(t){this._box2d["destroy"](t)}_CreateBody(){if(!this._isEnabled)return;const t=this._box2d["b2FixtureDef"],e=this._box2d["b2BodyDef"],i=this.GetWorldInfo(),s=i.HasOwnCollisionPoly();if(this._actualCollisionMask=this._collisionMask,s||this._inst.HasTilemap()||0!==this._actualCollisionMask||(this._actualCollisionMask=1),!this._body){const t=new e;t["set_type"](this._isImmovable?0:2);let s=i.GetX()*this._worldScale,n=i.GetY()*this._worldScale;if(2===this._actualCollisionMask){const t=this._GetBoundingQuadExcludingMesh();s=t.midX()*this._worldScale,n=t.midY()*this._worldScale}t["set_position"](R(s,n)),t["set_angle"](i.GetAngle()),t["set_fixedRotation"](this._preventRotation),t["set_linearDamping"](this._linearDamping),t["set_angularDamping"](this._angularDamping),t["set_bullet"](this._isBullet),this._body=this._world["CreateBody"](t),this._Destroy(t),v.set(this._body,this)}this._DestroyFixtures();const n=new t;n["set_density"](this._density),n["set_friction"](this._friction),n["set_restitution"](this._restitution);const o=Math.max(Math.abs(i.GetWidth()),1),r=Math.max(Math.abs(i.GetHeight()),1);0===this._actualCollisionMask?this._inst.HasTilemap()?this._CreateTilemapFixtures(n):this._CreatePolygonFixture(n,o,r):1===this._actualCollisionMask?this._CreateBoundingBoxFixture(n,i,o,r):this._CreateCircleFixture(n,o,r),this._lastWidth=i.GetWidth(),this._lastHeight=i.GetHeight(),i.SetPhysicsBodyChanged(!1),this._Destroy(n)}_CreateBoundingBoxFixture(t,e,i,s){const n=new(0,this._box2d["b2PolygonShape"]),o=i*this._worldScale,r=s*this._worldScale;let a=e.GetOriginX(),l=e.GetOriginY();e.GetWidth()<0&&(a=1-a),e.GetHeight()<0&&(l=1-l);const h=(.5-a)*o,c=(.5-l)*r,d=_.Behaviors.Physics.GetVec2(h,c);n["SetAsBox"](o/2,r/2,d,0),t["set_shape"](n),this._CreateFixture(t),this._Destroy(n),_.Behaviors.Physics.FreeVec2(d)}_CreateCircleFixture(t,e,i){const s=new(0,this._box2d["b2CircleShape"]);s["set_m_radius"](Math.min(e,i)*this._worldScale*.5),t["set_shape"](s),this._CreateFixture(t),this._Destroy(s)}_CreatePolygonFixture(t,e,i){const s=this.GetWorldInfo(),n=s.GetWidth()<0,o=s.GetHeight()<0,r=this._worldScale,a=s.GetCustomTransformedCollisionPoly(n?-e:e,o?-i:i,0).pointsArr(),l=a.length/2,h=[];for(let t=0;t0&&(t["cft"]=[...this._collisionFilterTags]),this._isEnabled){const e=this._body["GetLinearVelocity"]();t["vx"]=e["get_x"](),t["vy"]=e["get_y"](),t["om"]=this._body["GetAngularVelocity"]()}return t}_OnBeforeLoad(){this._DestroyMyJoints(),_.clearArray(this._myCreatedJoints),this._joiningMe.clear()}LoadFromJson(t){this._DestroyBody(),this._isEnabled=t["e"],t.hasOwnProperty("im")&&(this._isImmovable=!!t["im"]),this._preventRotation=t["pr"],this._density=t["d"],this._friction=t["fr"],this._restitution=t["re"],this._linearDamping=t["ld"],this._angularDamping=t["ad"],this._isBullet=t["b"],this._myCreatedJoints=t["mcj"];const e=!!t["cfi"],i=t["cft"]??[];this._SetCollisionFilter(e,i);const s=this.GetWorldInfo();this._lastKnownX=s.GetX(),this._lastKnownY=s.GetY(),this._lastKnownAngle=s.GetAngle(),this._lastWidth=s.GetWidth(),this._lastHeight=s.GetHeight(),this._isEnabled&&(this._CreateBody(),this._body["SetLinearVelocity"](M(t["vx"],t["vy"])),this._body["SetAngularVelocity"](t["om"]),0===t["vx"]&&0===t["vy"]&&0===t["om"]||this._body["SetAwake"](!0),this._myCreatedJoints=t["mcj"]),this._isEnabled?this._StartTicking():this._StopTicking()}_OnAfterLoad(){this._isEnabled&&this._RecreateMyJoints()}Tick(){if(!this._isEnabled)return;const t=this._runtime,e=this.GetBehavior();let i=0;0===e.GetSteppingMode()?i=t.GetTimeScale()/60:(i=t.GetDt(this._inst),i>1/30&&(i=1/30));const s=t.GetTickCountNoSave();s>e.GetLastUpdateTick()&&t.GetTimeScale()>0&&(0!==i&&this._world["Step"](i,e.GetVelocityIterations(),e.GetPositionIterations()),this._world["ClearForces"](),e.SetLastUpdateTick(s)),this._UpdateBodyToMatchInstance(!0)}_UpdateBodyToMatchInstance(t){const e=this._inst.GetWorldInfo(),i=this._worldScale;(e.GetWidth()!==this._lastWidth||e.GetHeight()!==this._lastHeight||e.IsPhysicsBodyChanged())&&this._CreateBody();const s=this._body,n=e.GetX(),o=e.GetY(),r=n-this._lastKnownX,a=o-this._lastKnownY,l=Math.abs(r)>.001||Math.abs(a)>.001,h=e.GetAngle()!==this._lastKnownAngle;let _=n,c=o;if(2===this._actualCollisionMask){const t=this._GetBoundingQuadExcludingMesh();_=t.midX(),c=t.midY()}l?(h?s["SetTransform"](M(_*i,c*i),e.GetAngle()):s["SetTransform"](M(_*i,c*i),s["GetAngle"]()),t&&(s["SetLinearVelocity"](M(r,a)),this._lastTickOverride=!0),s["SetAwake"](!0)):t&&this._lastTickOverride&&(this._lastTickOverride=!1,s["SetLinearVelocity"](M(0,0)),s["SetTransform"](M(_*i,c*i),s["GetAngle"]())),!l&&h&&(s["SetTransform"](s["GetPosition"](),e.GetAngle()),s["SetAwake"](!0));const d=s["GetPosition"](),u=d["get_x"]()/i,y=d["get_y"]()/i,p=s["GetAngle"]();if((u!==e.GetX()||y!==e.GetY()||p!==e.GetAngle())&&(e.SetXY(u,y),e.SetAngle(p),e.SetBboxChanged(),2===this._actualCollisionMask)){const t=this._GetBoundingQuadExcludingMesh(),i=t.midX()-e.GetX(),s=t.midY()-e.GetY();0===i&&0===s||(e.OffsetXY(-i,-s),e.SetBboxChanged())}this._lastKnownX=e.GetX(),this._lastKnownY=e.GetY(),this._lastKnownAngle=e.GetAngle()}GetPropertyValueByIndex(t){switch(t){case m:return this._IsPreventRotate();case b:return this._GetDensity();case G:return this._GetFriction();case I:return this._GetElasticity();case S:return this._GetLinearDamping();case C:return this._GetAngularDamping();case f:return this._IsBullet();case A:return this._IsEnabled()}}SetPropertyValueByIndex(t,e){switch(t){case m:this._SetPreventRotate(e);break;case b:this._SetDensity(e);break;case G:this._SetFriction(e);break;case I:this._SetElasticity(e);break;case S:this._SetLinearDamping(e);break;case C:this._SetAngularDamping(e);break;case f:this._SetBullet(e);break;case A:this._SetEnabled(e)}}_SetEnabled(t){t=!!t,this._isEnabled&&!t?(this._RemoveOtherInstanceJointsToMe(),this._DestroyBody(),this._isEnabled=!1,this._StopTicking()):!this._isEnabled&&t&&(this._isEnabled=!0,this._CreateBody(),this._StartTicking())}_IsEnabled(){return this._isEnabled}GetDebuggerProperties(){const t="behaviors.physics",e=[{name:t+".properties.enabled.name",value:this._IsEnabled(),onedit:t=>this._SetEnabled(t)},{name:t+".properties.immovable.name",value:this._IsImmovable(),onedit:t=>this._SetImmovable(t)},{name:t+".properties.collision-filter-tags.name",value:[...this._GetCollisionFilterTagSet()].join(" "),onedit:t=>this._SetFilterTags(_.splitStringAndNormalize(t))},{name:t+".debugger.collision-filter-inclusive",value:this._IsCollisionFilterInclusive(),onedit:t=>this._SetFilterInclusive(t)},{name:t+".properties.density.name",value:this._GetDensity(),onedit:t=>this._SetDensity(t)},{name:t+".properties.friction.name",value:this._GetFriction(),onedit:t=>this._SetFriction(t)},{name:t+".properties.elasticity.name",value:this._GetElasticity(),onedit:t=>this._SetElasticity(t)},{name:t+".properties.linear-damping.name",value:this._GetLinearDamping(),onedit:t=>this._SetLinearDamping(t)},{name:t+".properties.angular-damping.name",value:this._GetAngularDamping(),onedit:t=>this._SetAngularDamping(t)}];return this._isEnabled&&(e.push({name:t+".debugger.is-sleeping",value:!this._IsAwake()}),e.push({name:t+".debugger.velocity-x",value:this._GetVelocityX(),onedit:t=>this._SetVelocity(t,this._GetVelocityY())}),e.push({name:t+".debugger.velocity-y",value:this._GetVelocityY(),onedit:t=>this._SetVelocity(this._GetVelocityX(),t)}),e.push({name:t+".debugger.angular-velocity",value:_.toDegrees(this._GetAngularVelocity()),onedit:t=>this._SetAngularVelocity(_.toRadians(t))}),e.push({name:t+".debugger.mass",value:this._GetMass()})),[{title:"$"+this.GetBehaviorType().GetName(),properties:e}]}_ApplyForce(t,e,i){const[s,n]=this._GetInstImagePoint(i);this._DoApplyForce(t,e,s,n)}_ApplyForceToward(t,e,i,s){const[n,o]=this._GetInstImagePoint(s),r=_.angleTo(n,o,e,i);this._DoApplyForce(Math.cos(r)*t,Math.sin(r)*t,n,o)}_ApplyForceAtAngle(t,e,i){const[s,n]=this._GetInstImagePoint(i);this._DoApplyForce(Math.cos(e)*t,Math.sin(e)*t,s,n)}_DoApplyForce(t,e,i,s){if(!this._isEnabled)return;const n=this._worldScale;this._body["ApplyForce"](M(t,e),R(i*n,s*n),!0)}_ApplyImpulse(t,e,i){const[s,n]=this._GetInstImagePoint(i);this._DoApplyImpulse(t,e,s,n)}_ApplyImpulseToward(t,e,i,s){const[n,o]=this._GetInstImagePoint(s),r=_.angleTo(n,o,e,i);this._DoApplyImpulse(Math.cos(r)*t,Math.sin(r)*t,n,o)}_ApplyImpulseAtAngle(t,e,i){const[s,n]=this._GetInstImagePoint(i);this._DoApplyImpulse(Math.cos(e)*t,Math.sin(e)*t,s,n)}_DoApplyImpulse(t,e,i,s){if(!this._isEnabled)return;const n=this._worldScale;this._body["ApplyLinearImpulse"](M(t,e),R(i*n,s*n),!0);const o=this.GetWorldInfo();this._lastKnownX=o.GetX(),this._lastKnownY=o.GetY(),this._lastTickOverride=!1}_ApplyTorque(t){this._isEnabled&&this._body["ApplyTorque"](t,!0)}_ApplyTorqueToAngle(t,e){const i=_.angleClockwise(this.GetWorldInfo().GetAngle(),e)?-1:1;this._ApplyTorque(t*i)}_ApplyTorqueToPosition(t,e,i){const s=this.GetWorldInfo(),n=_.angleTo(s.GetX(),s.GetY(),e,i),o=_.angleClockwise(s.GetAngle(),n)?-1:1;this._ApplyTorque(t*o)}_SetAngularVelocity(t){this._isEnabled&&(this._body["SetAngularVelocity"](t),this._body["SetAwake"](!0))}_GetAngularVelocity(){return this._isEnabled?this._body["GetAngularVelocity"]():0}_SetVelocity(t,e){if(!this._isEnabled)return;const i=this._worldScale;this._body["SetLinearVelocity"](M(t*i,e*i)),this._body["SetAwake"](!0);const s=this.GetWorldInfo();this._lastKnownX=s.GetX(),this._lastKnownY=s.GetY(),this._lastTickOverride=!1}_GetVelocity(){if(!this._isEnabled)return[0,0];const t=this._worldScale,e=this._body["GetLinearVelocity"]();return[e["get_x"]()/t,e["get_y"]()/t]}_GetVelocityX(){return this._isEnabled?this._body["GetLinearVelocity"]()["get_x"]()/this._worldScale:0}_GetVelocityY(){return this._isEnabled?this._body["GetLinearVelocity"]()["get_y"]()/this._worldScale:0}_Teleport(t,e){if(!this._isEnabled)return;const i=this._worldScale;this._body["SetTransform"](M(t*i,e*i),this._body["GetAngle"]());const s=this.GetWorldInfo();s.SetXY(t,e),s.SetBboxChanged(),this._lastKnownX=s.GetX(),this._lastKnownY=s.GetY()}_SetDensity(t){if(this._isEnabled&&this._density!==t){this._density=t;for(const e of this._fixtures)e["SetDensity"](t);this._body["ResetMassData"]()}}_GetDensity(){return this._isEnabled?this._density:0}_SetFriction(t){if(this._isEnabled&&this._friction!==t){this._friction=t;for(const e of this._fixtures)e["SetFriction"](t);if(this._body)for(let t=this._body["GetContactList"]();this._box2d["getPointer"](t);t=t["get_next"]()){const e=t["get_contact"]();e&&e["ResetFriction"]()}}}_GetFriction(){return this._isEnabled?this._friction:0}_SetElasticity(t){if(this._isEnabled&&this._restitution!==t){this._restitution=t;for(const e of this._fixtures)e["SetRestitution"](t)}}_GetElasticity(){return this._isEnabled?this._restitution:0}_SetLinearDamping(t){this._isEnabled&&this._linearDamping!==t&&(this._linearDamping=t,this._body["SetLinearDamping"](t))}_GetLinearDamping(){return this._isEnabled?this._linearDamping:0}_SetAngularDamping(t){this._isEnabled&&this._angularDamping!==t&&(this._angularDamping=t,this._body["SetAngularDamping"](t))}_GetAngularDamping(){return this._isEnabled?this._angularDamping:0}_SetImmovable(t){this._isEnabled&&(t=!!t,this._isImmovable!==t&&(this._isImmovable=t,this._body["SetType"](this._isImmovable?0:2),this._body["SetAwake"](!0)))}_IsImmovable(){return this._isImmovable}_SetPreventRotate(t){this._isEnabled&&(t=!!t,this._preventRotation!==t&&(this._preventRotation=t,this._body["SetFixedRotation"](this._preventRotation),this._body["SetAngularVelocity"](0),this._body["SetAwake"](!0)))}_IsPreventRotate(){return this._preventRotation}_SetBullet(t){this._isEnabled&&(t=!!t,this._isBullet!==t&&(this._isBullet=t,this._body["SetBullet"](this._isBullet),this._body["SetAwake"](!0)))}_IsBullet(){return this._isBullet}_SetAwake(t){this._isEnabled&&this._body["SetAwake"](!!t)}_IsAwake(){return!!this._isEnabled&&this._body["IsAwake"]()}_GetMass(){return this._isEnabled?this._body["GetMass"]()/this._worldScale:0}_GetCenterOfMassX(){return this._isEnabled?this._body["GetWorldCenter"]()["get_x"]()/this._worldScale:0}_GetCenterOfMassY(){return this._isEnabled?this._body["GetWorldCenter"]()["get_y"]()/this._worldScale:0}_GetCenterOfMass(){if(!this._isEnabled)return[0,0];const t=this._body["GetWorldCenter"](),e=this._worldScale;return[t["get_x"]()/e,t["get_y"]()/e]}_GetContactCount(){if(!this._isEnabled)return 0;let t=0;for(let e=this._body["GetContactList"]();this._box2d["getPointer"](e);e=e["get_next"]()){const i=e["get_contact"]();if(!i)continue;t+=i["GetManifold"]()["get_pointCount"]()}return t}_GetContactPositionAt(t){if(t=Math.floor(t),!this._isEnabled)return[0,0];let e=0;for(let i=this._body["GetContactList"]();this._box2d["getPointer"](i);i=i["get_next"]()){const s=i["get_contact"]();if(!s)continue;const n=s["GetManifold"]()["get_pointCount"]();if(t>=e&&t0)&&this.GetBehavior().DisableShouldCollideFastPath()}_GetCollisionFilterTagSet(){return this._collisionFilterTags}_IsCollisionFilterInclusive(){return this._isCollisionFilterInclusive}_CheckCollisionAllowed(t){return CollisionTagsAllowCollision(this._inst.GetLowercaseTagsSet(),t._collisionFilterTags,t._isCollisionFilterInclusive)&&CollisionTagsAllowCollision(t._inst.GetLowercaseTagsSet(),this._collisionFilterTags,this._isCollisionFilterInclusive)}GetScriptInterfaceClass(){return self.IPhysicsBehaviorInstance}};const x=new WeakMap;function UnwrapIWorldInstance(t,e){return x.get(t).GetRuntime()._UnwrapIWorldInstance(e)}self.IPhysicsBehaviorInstance=class extends d{constructor(){super(),x.set(this,d._GetInitInst().GetSdkInstance())}get isEnabled(){return x.get(this)._IsEnabled()}set isEnabled(t){x.get(this)._SetEnabled(t)}applyForce(t,e,i=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),x.get(this)._ApplyForce(t,e,i)}applyForceTowardPosition(t,e,i,s=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),c.RequireFiniteNumber(i),x.get(this)._ApplyForceToward(t,e,i,s)}applyForceAtAngle(t,e,i=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),x.get(this)._ApplyForceAtAngle(t,e,i)}applyImpulse(t,e,i=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),x.get(this)._ApplyImpulse(t,e,i)}applyImpulseTowardPosition(t,e,i,s=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),c.RequireFiniteNumber(i),x.get(this)._ApplyImpulseToward(t,e,i,s)}applyImpulseAtAngle(t,e,i=0){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),x.get(this)._ApplyImpulseAtAngle(t,e,i)}applyTorque(t){c.RequireFiniteNumber(t),x.get(this)._ApplyTorque(t)}applyTorqueToAngle(t,e){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),x.get(this)._ApplyTorqueToAngle(t,e)}applyTorqueToPosition(t,e,i){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),c.RequireFiniteNumber(i),x.get(this)._ApplyTorqueToPosition(t,e,i)}set angularVelocity(t){c.RequireFiniteNumber(t),x.get(this)._SetAngularVelocity(t)}get angularVelocity(){return x.get(this)._GetAngularVelocity()}setVelocity(t,e){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),x.get(this)._SetVelocity(t,e)}getVelocityX(){return x.get(this)._GetVelocityX()}getVelocityY(){return x.get(this)._GetVelocityY()}getVelocity(){return x.get(this)._GetVelocity()}teleport(t,e){c.RequireFiniteNumber(t),c.RequireFiniteNumber(e),x.get(this)._Teleport(t,e)}set density(t){c.RequireFiniteNumber(t),x.get(this)._SetDensity(t)}get density(){return x.get(this)._GetDensity()}set friction(t){c.RequireFiniteNumber(t),x.get(this)._SetFriction(t)}get friction(){return x.get(this)._GetFriction()}set elasticity(t){c.RequireFiniteNumber(t),x.get(this)._SetElasticity(t)}get elasticity(){return x.get(this)._GetElasticity()}set linearDamping(t){c.RequireFiniteNumber(t),x.get(this)._SetLinearDamping(t)}get linearDamping(){return x.get(this)._GetLinearDamping()}set angularDamping(t){c.RequireFiniteNumber(t),x.get(this)._SetAngularDamping(t)}get angularDamping(){return x.get(this)._GetAngularDamping()}set isImmovable(t){x.get(this)._SetImmovable(t)}get isImmovable(){return x.get(this)._IsImmovable()}set isPreventRotation(t){x.get(this)._SetPreventRotate(t)}get isPreventRotation(){return x.get(this)._IsPreventRotate()}set isBullet(t){x.get(this)._SetBullet(t)}get isBullet(){return x.get(this)._IsBullet()}get mass(){return x.get(this)._GetMass()}getCenterOfMassX(){return x.get(this)._GetCenterOfMassX()}getCenterOfMassY(){return x.get(this)._GetCenterOfMassY()}getCenterOfMass(){return x.get(this)._GetCenterOfMass()}getContactCount(){return x.get(this)._GetContactCount()}getContactX(t){return c.RequireFiniteNumber(t),x.get(this)._GetContactPositionAt(t)[0]}getContactY(t){return c.RequireFiniteNumber(t),x.get(this)._GetContactPositionAt(t)[1]}getContact(t){return c.RequireFiniteNumber(t),x.get(this)._GetContactPositionAt(t)}set isAwake(t){x.get(this)._SetAwake(!!t)}get isAwake(){return x.get(this)._IsAwake()}get isSleeping(){return this.runtime._logDeprecationWarning("IPhysicsBehaviorInstance.isSleeping","IPhysicsBehaviorInstance 'isSleeping' property is deprecated. Use 'isAwake' instead."),!x.get(this)._IsAwake()}createDistanceJoint(t,e,i,s,n){c.RequireFiniteNumber(s),c.RequireFiniteNumber(n);const o=UnwrapIWorldInstance(this,e);x.get(this)._CreateDistanceJoint(t,o,i,s,n)}createRevoluteJoint(t,e){const i=UnwrapIWorldInstance(this,e);x.get(this)._CreateRevoluteJoint(t,i)}createLimitedRevoluteJoint(t,e,i,s){c.RequireFiniteNumber(i),c.RequireFiniteNumber(s);const n=UnwrapIWorldInstance(this,e);x.get(this)._CreateLimitedRevoluteJoint(t,n,i,s)}createPrismaticJoint(t,e,i,s,n,o,r,a,l){const h=UnwrapIWorldInstance(this,e);x.get(this)._CreatePrismaticJoint(t,h,i,s,n,o,r,a,l)}removeAllJoints(){x.get(this)._RemoveJoints()}setCollisionFilter(t,e){"string"==typeof e&&(e=_.splitStringAndNormalize(e)),x.get(this)._SetCollisionFilter(t,e)}}}{const k=self.C3;k.Behaviors.Physics.Cnds={IsSleeping(){return!this._IsAwake()},IsImmovable(){return this._IsImmovable()},CompareVelocity(t,e,i){if(!this._isEnabled)return!1;let s=0;if(0===t)s=this._GetVelocityX();else if(1===t)s=this._GetVelocityY();else{const[t,e]=this._GetVelocity();s=Math.hypot(t,e)}return k.compare(s,e,i)},CompareAngularVelocity(t,e){if(!this._isEnabled)return!1;const i=k.toDegrees(this._GetAngularVelocity());return k.compare(i,t,e)},CompareMass(t,e){if(!this._isEnabled)return!1;const i=this._GetMass();return k.compare(i,t,e)},IsEnabled(){return this._IsEnabled()}}}{const J=self.C3;J.Behaviors.Physics.Acts={ApplyForce(t,e,i){this._ApplyForce(t,e,i)},ApplyForceToward(t,e,i,s){this._ApplyForceToward(t,e,i,s)},ApplyForceAtAngle(t,e,i){this._ApplyForceAtAngle(t,J.toRadians(e),i)},ApplyImpulse(t,e,i){this._ApplyImpulse(t,e,i)},ApplyImpulseToward(t,e,i,s){this._ApplyImpulseToward(t,e,i,s)},ApplyImpulseAtAngle(t,e,i){this._ApplyImpulseAtAngle(t,J.toRadians(e),i)},ApplyTorque(t){this._ApplyTorque(J.toRadians(t))},ApplyTorqueToAngle(t,e){this._ApplyTorqueToAngle(J.toRadians(t),J.toRadians(e))},ApplyTorqueToPosition(t,e,i){this._ApplyTorqueToPosition(J.toRadians(t),e,i)},SetAngularVelocity(t){this._SetAngularVelocity(J.toRadians(t))},CreateDistanceJoint(t,e,i,s,n){if(!e)return;const o=e.GetFirstPicked(this._inst);this._CreateDistanceJoint(t,o,i,s,n)},CreateRevoluteJoint(t,e){if(!e)return;const i=e.GetFirstPicked(this._inst);this._CreateRevoluteJoint(t,i)},CreateLimitedRevoluteJoint(t,e,i,s){if(!e)return;const n=e.GetFirstPicked(this._inst);this._CreateLimitedRevoluteJoint(t,n,J.toRadians(i),J.toRadians(s))},CreatePrismaticJoint(t,e,i,s,n,o,r,a,l){if(!e)return;const h=e.GetFirstPicked(this._inst);this._CreatePrismaticJoint(t,h,J.toRadians(i),s,n,o,r,J.toRadians(a),l)},RemoveJoints(){this._RemoveJoints()},SetWorldGravity(t){this.GetBehavior().SetGravity(t)},SetSteppingMode(t){this.GetBehavior().SetSteppingMode(t)},SetIterations(t,e){this.GetBehavior().SetIterations(t,e)},SetVelocity(t,e){this._SetVelocity(t,e)},Teleport(t,e){this._Teleport(t,e)},SetDensity(t){this._SetDensity(t)},SetFriction(t){this._SetFriction(t)},SetElasticity(t){this._SetElasticity(t)},SetLinearDamping(t){this._SetLinearDamping(t)},SetAngularDamping(t){this._SetAngularDamping(t)},SetImmovable(t){this._SetImmovable(t)},EnableCollisions(t,e){this.GetBehavior().SetCollisionsEnabled(this.GetObjectClass(),t,0!==e)},SetPreventRotate(t){this._SetPreventRotate(0!==t)},SetBullet(t){this._SetBullet(0!==t)},SetAwake(t){this._SetAwake(!!t)},SetEnabled(t){this._SetEnabled(0!==t)},SetCollisionFilter(t,e){this._SetCollisionFilter(0===t,J.splitStringAndNormalize(e))}}}{const V=self.C3;V.Behaviors.Physics.Exps={VelocityX(){return this._GetVelocityX()},VelocityY(){return this._GetVelocityY()},AngularVelocity(){return V.toDegrees(this._GetAngularVelocity())},Mass(){return this._GetMass()},CenterOfMassX(){return this._GetCenterOfMassX()},CenterOfMassY(){return this._GetCenterOfMassY()},Density(){return this._GetDensity()},Friction(){return this._GetFriction()},Elasticity(){return this._GetElasticity()},LinearDamping(){return this._GetLinearDamping()},AngularDamping(){return this._GetAngularDamping()},ContactCount(){return this._GetContactCount()},ContactXAt(t){return this._GetContactPositionAt(t)[0]},ContactYAt(t){return this._GetContactPositionAt(t)[1]}}} } // scripts/behaviors/Physics/c3runtime/separator.js { const C3=self.C3,b2Separator={};C3.Behaviors.Physics.Separator=b2Separator;const GetVec2=C3.Behaviors.Physics.GetVec2,FreeVec2=C3.Behaviors.Physics.FreeVec2;function CloneVec2(e){return GetVec2(e["get_x"](),e["get_y"]())}function SplitConvexPolysOver8Points(e){const t=[];for(const r of e)r.length<=8?t.push(r):t.push.apply(t,SplitConvexPoly(r));return t}function SplitConvexPoly(e){const t=[];t.push(e.splice(0,8));const r=t[0][0];let n=t[0][7];for(;e.length;){const a=e.splice(0,Math.min(e.length,6));let o=a.at(-1);a.push(CloneVec2(r)),a.push(CloneVec2(n)),t.push(a),n=o}return t}b2Separator.det=function(e,t,r,n,a,o){return e*n+r*o+a*t-t*r-n*a-o*e},b2Separator.hitRay=function(e,t,r,n,a,o,s,g){const p=r-e,i=n-t,c=s-a,h=g-o,_=(c*(o-t)-h*(a-e))/(i*c-p*h),u=e+_*p,l=t+_*i,y=b2Separator.isOnSegment(r,n,e,t,u,l),f=b2Separator.isOnSegment(u,l,a,o,s,g);return y&&f?GetVec2(u,l):null},b2Separator.isOnSegment=function(e,t,r,n,a,o){return(r+.1>=e&&e>=a-.1||r-.1<=e&&e<=a+.1)&&(n+.1>=t&&t>=o-.1||n-.1<=t&&t<=o+.1)&&b2Separator.isOnLine(e,t,r,n,a,o)},b2Separator.isOnLine=function(e,t,r,n,a,o){if(Math.abs(a-r)>.1){const s=(o-n)/(a-r)*(e-r)+n;return Math.abs(s-t)<.1}return Math.abs(e-r)<.1},b2Separator.pointsMatch=function(e,t,r,n){return Math.abs(r-e)<.1&&Math.abs(n-t)<.1},b2Separator.Separate=function(e,t){if(3===e.length)return[e.map(e=>GetVec2(e["get_x"](),e["get_y"]()))];const r=b2Separator.calcShapes(e);let n=[];for(let e=0,a=r.length;e=.001*t)n.push(o);else for(let e=0,t=o.length;e=c)return[];b2Separator.isOnSegment(o["get_x"](),o["get_y"](),p[M]["get_x"](),p[M]["get_y"](),t["get_x"](),t["get_y"]())||O.push(p[v]);break}O.push(p[v]),M=v,v-1<0?v=c-1:v--}for(O.reverse(),M=-1,v=b;;){if(v===V){if(M<0||M>=c)return[];v!==V||b2Separator.isOnSegment(a["get_x"](),a["get_y"](),p[M]["get_x"](),p[M]["get_y"](),r["get_x"](),r["get_y"]())||P.push(p[v]);break}P.push(p[v]),M=v,v+1>c-1?v=0:v++}F.push(O,P),F.shift();break}m&&G.push(F.shift())}return G}; } // scripts/behaviors/Tween/c3runtime/runtime.js { {const e=self.C3;e.Behaviors.Tween=class extends e.SDKBehaviorBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.Tween.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,s=e.Behaviors.Tween,t=0;s.Instance=class extends e.SDKBehaviorInstanceBase{constructor(e,s){super(e),this._allowMultiple=!1,this._enabled=!0,s&&(this._allowMultiple=!1,this._enabled=!!s[t]),this._activeTweens=new Map,this._disabledTweens=[],this._waitingForReleaseTweens=new Map,this._finishingTween=null,this._activeTweensJson=null,this._disabledTweensJson=null,this._waitingForReleaseTweensJson=null,this._finishingTweenName="",this._triggerTweens=[],this._afterLoad=e=>this._OnAfterLoad(),this.GetRuntime().Dispatcher().addEventListener("afterload",this._afterLoad)}Release(){this.GetRuntime().Dispatcher().removeEventListener("afterload",this._afterLoad),this._afterLoad=null,this._finishingTween&&(this.ReleaseAndCompleteTween(this._finishingTween),this._finishingTween=null),this.ReleaseAndCompleteTweens(),this._tweens=null,this.ClearDisabledList(),this._disabledTweens=null,this._ReleaseWaitingTweens(),this._waitingForReleaseTweens=null,this._triggerTweens=null,super.Release()}PushTriggerTween(e){this._triggerTweens.push(e)}PopTriggerTween(){this._triggerTweens.pop()}GetTriggerTween(){return this._triggerTweens[this._triggerTweens.length-1]}SetEnabled(e){this._enabled=!!e,e?this._waitingForReleaseTweens&&this._waitingForReleaseTweens.size&&this._StartTicking2():this._StopTicking2();for(const s of this.AllTweens())e?this.IsInDisabledList(s)&&s.Resume():((s.IsPlaying()||s.IsScheduled())&&this.AddToDisabledList(s),s.Stop());e&&this.ClearDisabledList()}IsEnabled(){return this._enabled}AddToDisabledList(e){this._disabledTweens.push(e)}IsInDisabledList(e){return this._disabledTweens.includes(e)}ClearDisabledList(){e.clearArray(this._disabledTweens)}GetFinishingTween(){return this._finishingTween}IsInstanceValid(){const e=this.GetObjectInstance();return!!e&&!e.IsDestroyed()}GetTween(e,s,t=!1){const n=s?this.PropertyTweens(s,t):this.AllTweens(t);if(n&&n.length)for(const s of n)if(s.HasTags(e))return s}CheckTweensWithTags(e,s){for(const t of this._activeTweens.values())for(const n of t)if(!n.IsReleased()&&n.HasTags(e)&&s(n))return!0;for(const t of this._waitingForReleaseTweens.values())for(const n of t)if(!n.IsReleased()&&n.HasTags(e)&&s(n))return!0;return!1}CheckTweens(e){for(const s of this._activeTweens.values())for(const t of s)if(!t.IsReleased()&&e(t))return!0;for(const s of this._waitingForReleaseTweens.values())for(const t of s)if(!t.IsReleased()&&e(t))return!0;return!1}GetTweenIncludingWaitingForRelease(e,s){return this.GetTween(e,s,!0)}*GetTweens(e,s,t=!1){const n=s?this.PropertyTweens(s,t):this.AllTweens(t);if(n&&n.length)for(const s of n)s.HasTags(e)&&(yield s)}*GetTweensIncludingWaitingForRelease(e,s){yield*this.GetTweens(e,s,!0)}PropertyTweens(e,s){if(s){let s=this._activeTweens.get(e),t=this._waitingForReleaseTweens.get(e);return s||(s=[]),t||(t=[]),s.concat(t).filter(e=>e).filter(e=>!e.IsReleased())}{let s=this._activeTweens.get(e);return s||(s=[]),s.filter(e=>e).filter(e=>!e.IsReleased())}}AllTweens(e){if(e){const e=[...this._activeTweens.values()].flat(),s=[...this._waitingForReleaseTweens.values()].flat();return e.concat(s).filter(e=>e).filter(e=>!e.IsReleased())}return[...this._activeTweens.values()].flat().filter(e=>e).filter(e=>!e.IsReleased())}AllTweensIncludingWaitingForRelease(){return this.AllTweens(!0)}SaveToJson(e="full"){return{"s":!1,"e":!!this._enabled,"at":this._SaveActiveTweensToJson(),"dt":this._SaveDisabledTweensToJson(),"wt":this._SaveWaitingForReleaseTweensToJson(),"ft":this._SaveFinishingTweenToJson()}}LoadFromJson(e,s="full"){e&&(this._activeTweensJson=e["at"],this._disabledTweensJson=e["dt"],this._waitingForReleaseTweensJson=e["wt"],this._finishingTweenName=e["ft"],this._allowMultiple=!1,this._enabled=!!e["e"],"state"===s&&this._OnAfterLoad())}_OnAfterLoad(){const s=this.GetRuntime().GetTimelineManager();if(this._PopulateTweenMap(this._activeTweensJson,this._activeTweens,s),this._disabledTweensJson){e.clearArray(this._disabledTweens);for(const e of this._disabledTweensJson)this._PopulateTweenArray(this._disabledTweens,e,s)}this._PopulateTweenMap(this._waitingForReleaseTweensJson,this._waitingForReleaseTweens,s),this._finishingTween=this._GetTween(this._finishingTweenName,s),this._enabled?this._waitingForReleaseTweens&&this._waitingForReleaseTweens.size&&this._StartTicking2():this._StopTicking2()}_PopulateTweenMap(s,t,n){if(s)for(const i in s){let a=t.get(i);a?e.clearArray(a):a=[];const r=s[i];for(const s of r){if(this._PopulateTweenArray(a,s["name"],n))this._LoadTweenFromJson(s["name"],s,n);else{const t=e.TweenState.Build({runtime:this.GetRuntime(),json:s});e.TweenState.SetInstanceUID(t,this.GetObjectInstance().GetUID()),t.AddCompletedCallback(e=>this._FinishTriggers(e)),t.SetBehaviorInstance(this),n.AddScheduledTimeline(t),this._PopulateTweenArray(a,t,n)}}t.set(i,a)}}_GetTween(e,s){return s.GetScheduledOrPlayingTimelineByName(e)}_PopulateTweenArray(e,s,t){if("string"!=typeof s)return!!e.push(s);{const n=this._GetTween(s,t);if(n)return!!e.push(n)}return!1}_LoadTweenFromJson(s,t,n){if("string"==typeof s){const i=this._GetTween(s,n);i&&(i._LoadFromJson(t),e.TweenState.SetInstanceUID(i,this.GetObjectInstance().GetUID()),e.TweenState.SetBehaviorInstance(i,this))}else s._LoadFromJson(t),e.TweenState.SetInstanceUID(s,this.GetObjectInstance().GetUID()),e.TweenState.SetBehaviorInstance(s,this)}_SaveActiveTweensToJson(){const e={};for(const[s,t]of this._activeTweens)e[s]=t.filter(e=>!e.IsReleased()).map(e=>e._SaveToJson());return e}_SaveDisabledTweensToJson(){return this._disabledTweens.filter(e=>!e.IsReleased()).map(e=>e.GetName())}_SaveWaitingForReleaseTweensToJson(){const e={};for(const[s,t]of this._waitingForReleaseTweens)e[s]=t.map(e=>e._SaveToJson());return e}_SaveFinishingTweenToJson(){return this._finishingTween?this._finishingTween.GetName():""}Tick2(){this._ReleaseWaitingTweens()}CreateTween(t){const n=s.Config.GetPropertyTracksConfig(t.property,t.startValue,t.endValue,t.ease,t.resultMode,this.GetObjectInstance()),i=s.Maps.GetPropertyFromIndex(t.property);s.Maps.IsValueId(i)||this.ReleaseTweens(t.property);const a=e.TweenState.Build({runtime:this.GetRuntime(),id:i,tags:t.tags,time:t.time,instance:this.GetObjectInstance(),releaseOnComplete:!!t.releaseOnComplete,loop:!!t.loop,pingPong:!!t.pingPong,repeatCount:t.repeatCount,initialValueMode:t.initialValueMode,propertyTracksConfig:n});return a.AddCompletedCallback(e=>this._FinishTriggers(e)),a.SetBehaviorInstance(this),this._AddTween(a,t.property),a}_MaybeRemoveFromActiveTweenMap(e){const s=e.GetId();if(this._activeTweens.has(s)){const t=this._activeTweens.get(s);if(t){const s=t.indexOf(e);-1!==s&&t.splice(s,1)}}}ReleaseTween(e,s=!1){this._MaybeRemoveFromActiveTweenMap(e),e.IsReleased()||this._IsInWaitingList(e)||(e.Stop(s),this._AddToWaitingList(e))}ReleaseTweens(t,n=!1){if(e.IsFiniteNumber(t)){const i=s.Maps.GetPropertyFromIndex(t);if(!this._activeTweens.has(i))return;const a=this._activeTweens.get(i),r=this.GetFinishingTween();for(const e of a)e!==r&&(e.IsReleased()||this._IsInWaitingList(e)||(e.Stop(n),e.Release()));e.clearArray(a)}else{const s=this.GetFinishingTween();for(const e of this.AllTweens())e!==s&&(e.IsReleased()||this._IsInWaitingList(e)||(e.Stop(n),e.Release()));for(const s of this._activeTweens.keys())e.clearArray(this._activeTweens.get(s)),this._activeTweens.delete(s);this._activeTweens.clear()}}ReleaseAndCompleteTween(e){this.ReleaseTween(e,!0)}ReleaseAndCompleteTweens(){this.ReleaseTweens(NaN,!0)}GetPropertyValueByIndex(e){if(e===t)return this._enabled}SetPropertyValueByIndex(e,s){if(e===t)this._enabled=!!s}_GetBehaviorType(e){const s=e.GetInstance().GetBehaviorInstances();for(const e of s){const s=e.GetBehaviorType();if(s.GetInstanceSdkCtor()===this.constructor)return s}}Trigger(e,s,t,n){return this._runtime?super.Trigger(e):s.Trigger(e,t,n)}_FinishTriggers(e){let t,n;if(this._finishingTween=e,s.Cnds.SetFinishingTween(e),this.GetRuntime())t=this._inst,n=this._runtime,this.Trigger(s.Cnds.OnTweensFinished),this.Trigger(s.Cnds.OnAnyTweensFinished),this.ReleaseTween(e);else{if(t=e.GetInstance(),!t)return;if(t&&t.IsDestroyed())return;n=t.GetRuntime();const i=this._GetBehaviorType(e);this.Trigger(s.Cnds.OnTweensFinished,n,t,i),this.Trigger(s.Cnds.OnAnyTweensFinished,n,t,i),e.Stop()}this._finishingTween=null,s.Cnds.SetFinishingTween(null),e.GetDestroyInstanceOnComplete()&&n.DestroyInstance(t)}_AddTween(e,t){const n=s.Maps.GetPropertyFromIndex(t);this._activeTweens.has(n)||this._activeTweens.set(n,[]);this._activeTweens.get(n).push(e)}_AddToWaitingList(e){const s=e.GetId();this._waitingForReleaseTweens.has(s)||this._waitingForReleaseTweens.set(s,[]),this._waitingForReleaseTweens.get(s).push(e),this.IsTicking2()||this._StartTicking2()}_IsInWaitingList(e){const s=e.GetId();return!!this._waitingForReleaseTweens.has(s)&&this._waitingForReleaseTweens.get(s).includes(e)}_ReleaseWaitingTweens(){if(this._waitingForReleaseTweens.size){for(const s of this._waitingForReleaseTweens.values()){for(const e of s)e.IsReleased()||e.Release();e.clearArray(s)}this._waitingForReleaseTweens.clear(),this.IsTicking2()&&this._StopTicking2()}}GetDebuggerProperties(){return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:"behaviors.tween.properties.enabled.name",value:this.IsEnabled(),onedit:e=>this.SetEnabled(e)}]}]}GetScriptInterfaceClass(){return self.ITweenBehaviorInstance}}}{const e=self.C3;let s=null;e.Behaviors.Tween.Cnds={OnAnyTweenLoop:()=>!0,OnTweensLoop(e){const s=this.GetTriggerTween();return!!s&&s.HasTags(e)},OnAnyTweenPingPong(e){const s=this.GetTriggerTween();return!!s&&(s.GetPingPongState()===e||2===e)},OnTweensPingPong(e,s){const t=this.GetTriggerTween();return!!t&&((t.GetPingPongState()===s||2===s)&&t.HasTags(e))},OnTweensReleased(e){return this.GetTriggerTween().HasTags(e)},OnAnyTweensReleased:()=>!0,SetFinishingTween(e){s=e},OnTweensFinished:e=>s.HasTags(e),OnAnyTweensFinished:()=>!0,IsPlaying(s){return this.CheckTweensWithTags(s,e.TweenState.IsPlaying)},IsAnyPlaying(){return this.CheckTweens(e.TweenState.IsPlaying)},IsPaused(s){return this.CheckTweensWithTags(s,e.TweenState.IsPaused)},IsAnyPaused(){return this.CheckTweens(e.TweenState.IsPaused)},IsPingPong(s,t){return 0===t?this.CheckTweensWithTags(s,e.TweenState.IsPing):1===t&&this.CheckTweensWithTags(s,e.TweenState.IsPong)},IsAnyPingPong(s){return 0===s?this.CheckTweens(e.TweenState.IsPing):1===s&&this.CheckTweens(e.TweenState.IsPong)}}}{const e=self.C3,s=self.Ease,t=e.Behaviors.Tween;t.Acts={SetEnabled(e){this.SetEnabled(!!e)},async TweenOneProperty(...e){if(!this.IsEnabled()||!this.IsInstanceValid())return;const s=this.CreateTween(t.TweenArguments.OneProperty(this,...e));s.Play()&&await s.GetPlayPromise()},async TweenTwoProperties(...e){if(!this.IsEnabled()||!this.IsInstanceValid())return;const s=this.CreateTween(t.TweenArguments.TwoProperties(this,...e));s.Play()&&await s.GetPlayPromise()},async TweenThreeProperties(...e){if(!this.IsEnabled()||!this.IsInstanceValid())return;const s=this.CreateTween(t.TweenArguments.ThreeProperties(this,...e));s.Play()&&await s.GetPlayPromise()},async TweenValue(...e){if(!this.IsEnabled()||!this.IsInstanceValid())return;const s=this.CreateTween(t.TweenArguments.ValueProperty(this,...e));s.Play()&&await s.GetPlayPromise()},PauseTweens(e){if(this.IsEnabled()&&this.IsInstanceValid())for(const s of this.GetTweens(e))s.Stop()},PauseAllTweens(){if(this.IsEnabled()&&this.IsInstanceValid())for(const e of this.AllTweens())e.Stop()},ResumeTweens(e){if(this.IsEnabled()&&this.IsInstanceValid())for(const s of this.GetTweens(e))s.Resume()},ResumeAllTweens(){if(this.IsEnabled()&&this.IsInstanceValid())for(const e of this.AllTweens())e.Resume()},StopTweens(e){if(this.IsEnabled()&&this.IsInstanceValid())for(const s of this.GetTweens(e))this.ReleaseTween(s)},StopAllTweens(){if(this.IsEnabled()&&this.IsInstanceValid())for(const e of this.AllTweens())this.ReleaseTween(e)},SetOnePropertyTweensEndValue(s,t,n){if(!this.IsEnabled()||!this.IsInstanceValid())return;const i=e.Behaviors.Tween.Maps.GetSinglePropertyFromIndex(t);for(const e of this.GetTweens(s))e.BeforeSetEndValues([i]),e.SetEndValue(n,i)},SetTwoPropertiesTweensEndValue(s,t,n,i){if(!this.IsEnabled()||!this.IsInstanceValid())return;const a=e.Behaviors.Tween.Maps.GetRealProperties(t);for(const e of this.GetTweens(s))e.BeforeSetEndValues(a),e.SetEndValue(n,a[0]),e.SetEndValue(i,a[1])},SetThreePropertiesTweensEndValue(s,t,n,i,a){if(!this.IsEnabled()||!this.IsInstanceValid())return;const r=e.Behaviors.Tween.Maps.GetRealProperties(t);for(const e of this.GetTweens(s))e.BeforeSetEndValues(r),e.SetEndValue(n,r[0]),e.SetEndValue(i,r[1]),e.SetEndValue(a,r[2])},SetValuePropertyTweensStartValue(e,s){if(this.IsEnabled()&&this.IsInstanceValid())for(const t of this.GetTweens(e,"value"))t.SetStartValue(s,"value")},SetValuePropertyTweensEndValue(e,s){if(this.IsEnabled()&&this.IsInstanceValid())for(const t of this.GetTweens(e,"value"))t.BeforeSetEndValues(["value"]),t.SetEndValue(s,"value")},SetTweensEase(e,t){if(!this.IsEnabled()||!this.IsInstanceValid())return;const n=s.GetEaseFromIndex(t);for(const s of this.GetTweens(e))s.SetEase(n)},SetAllTweensEase(e){if(!this.IsEnabled()||!this.IsInstanceValid())return;const t=s.GetEaseFromIndex(e);for(const e of this.AllTweens())e.SetEase(t)},SetTweensTime(e,s){if(this.IsEnabled()&&this.IsInstanceValid())for(const t of this.GetTweens(e))t.SetTime(s)},SetAllTweensTime(e){if(this.IsEnabled()&&this.IsInstanceValid())for(const s of this.AllTweens())s.SetTime(e)},SetTweensPlaybackRate(e,s){if(this.IsEnabled()&&this.IsInstanceValid())for(const t of this.GetTweens(e))t.SetPlaybackRate(s)},SetAllTweensPlaybackRate(e){if(this.IsEnabled()&&this.IsInstanceValid())for(const s of this.AllTweens())s.SetPlaybackRate(e)},SetTweensDestroyOnComplete(e,s){if(this.IsEnabled()&&this.IsInstanceValid())for(const t of this.GetTweens(e))t.SetDestroyInstanceOnComplete(!!s)},SetAllTweensDestroyOnComplete(e){if(this.IsEnabled()&&this.IsInstanceValid())for(const s of this.AllTweens())s.SetDestroyInstanceOnComplete(!!e)}}}self.C3.Behaviors.Tween.Exps={Time(e){const s=this.GetTweenIncludingWaitingForRelease(e);return s?s.GetTime():0},Progress(e){const s=this.GetTweenIncludingWaitingForRelease(e);return s?s.GetTime()/s.GetTotalTime():0},PlaybackRate(e){const s=this.GetTweenIncludingWaitingForRelease(e);return s?s.GetPlaybackRate():0},Value(e){const s=this.GetTweenIncludingWaitingForRelease(e,"value");return s?s.GetPropertyTrack("value").GetSourceAdapterValue():0},Tags(){let e=this.GetFinishingTween();return e?e.GetStringTags():(e=this.GetTriggerTween(),e?e.GetStringTags():"")}}; } // scripts/behaviors/Tween/c3runtime/maps.js { const C3=self.C3,Ease=self.Ease,TRIO_PROPERTIES=["position3"],PAIR_PROPERTIES=["position","size","scale"],SINGLE_PROPERTIES=["offsetX","offsetY","offsetZElevation","offsetWidth","offsetHeight","offsetAngle","offsetOpacity","offsetColor","offsetScaleX","offsetScaleY"],VALUE_PROPERTIES=["value"],PROPERTY_INDEX_TO_NAME=[].concat(TRIO_PROPERTIES).concat(PAIR_PROPERTIES).concat(SINGLE_PROPERTIES).concat(VALUE_PROPERTIES),PROPERTY_PAIR_TO_REAL_PROPERTIES={"position":["offsetX","offsetY"],"size":["offsetWidth","offsetHeight"],"scale":["offsetScaleX","offsetScaleY"]},PROPERTY_TRIO_TO_REAL_PROPERTIES={"position3":["offsetX","offsetY","offsetZElevation"]},ALL_REAL_PROPERTIES=Object.assign({},PROPERTY_INDEX_TO_NAME.reduce((t,e)=>Object.assign({},t,{[e]:[e]}),{}),PROPERTY_PAIR_TO_REAL_PROPERTIES,PROPERTY_TRIO_TO_REAL_PROPERTIES);C3.Behaviors.Tween.Maps=class{constructor(){}static GetEases(){return[...Ease.GetRuntimeEaseNames()]}static GetEaseFromIndex(t){return[...Ease.GetRuntimeEaseNames()][t]}static GetPropertyFromIndex(t){return PROPERTY_INDEX_TO_NAME[t]}static GetPropertyIndexFromName(t){return PROPERTY_INDEX_TO_NAME.indexOf(t)}static GetTrioPropertyFromIndex(t){return TRIO_PROPERTIES[t]}static GetPairPropertyFromIndex(t){return PAIR_PROPERTIES[t]}static GetSinglePropertyFromIndex(t){return SINGLE_PROPERTIES[t]}static GetValuePropertyFromIndex(t){return VALUE_PROPERTIES[t]}static GetTrioProperties(t){return PROPERTY_TRIO_TO_REAL_PROPERTIES[t]}static GetPairProperties(t){return PROPERTY_PAIR_TO_REAL_PROPERTIES[t]}static GetRealProperties(t){return C3.IsString(t)?ALL_REAL_PROPERTIES[t]:ALL_REAL_PROPERTIES[PROPERTY_INDEX_TO_NAME[t]]}static IsTrioId(t){return!!PROPERTY_TRIO_TO_REAL_PROPERTIES[t]}static IsPairId(t){return!!PROPERTY_PAIR_TO_REAL_PROPERTIES[t]}static IsColorId(t){return"offsetColor"===t}static IsAngleId(t){return"offsetAngle"===t}static IsOpacityId(t){return"offsetOpacity"===t}static IsValueId(t){return"value"===t}}; } // scripts/behaviors/Tween/c3runtime/tweenConfig.js { const C3=self.C3,NAMESPACE=C3.Behaviors.Tween,TWEEN_CONFIGURATIONS=new Map;NAMESPACE.Config=class{constructor(){}static GetPropertyTracksConfig(e,t,r,o,a,s){0===TWEEN_CONFIGURATIONS.size&&this._CreateConfigObjects();const n=NAMESPACE.PropertyTypes.Pick(e);let i=TWEEN_CONFIGURATIONS.get(n);return C3.IsFiniteNumber(e)&&(e=NAMESPACE.Maps.GetPropertyFromIndex(e)),this._GetConfig(i,e,t,r,o,a,s)}static TransformValue(e,t){return C3.Behaviors.Tween.GetPropertyTracksConfig(e).valueGetter(t)}static _CreateConfigObjects(){const e=NAMESPACE.PropertyTypes,t=NAMESPACE.ValueGetters;this._AddConfigObject(e.TRIO,this._GetTrioConfig,t._GetPropertyValue),this._AddConfigObject(e.PAIR,this._GetPairConfig,t._GetPropertyValue),this._AddConfigObject(e.COLOR,this._GetColorConfig,t._GetColorPropertyValue),this._AddConfigObject(e.ANGLE,this._GetAngleConfig,t._GetPropertyAngleValue),this._AddConfigObject(e.VALUE,this._GetValueConfig,t._GetPropertyValue),this._AddConfigObject(e.OTHER,this._GetCommonConfig,t._GetPropertyValue)}static _AddConfigObject(e,t,r){TWEEN_CONFIGURATIONS.set(e,this._CreateConfigObject(e,t,r))}static _CreateConfigObject(e,t,r){return{name:e,configFunc:t,valueGetter:r}}static _GetConfig(e,t,r,o,a,s,n){return e.configFunc(t,e.valueGetter(r),e.valueGetter(o),a,s,n)}static _GetTrioConfig(e,t,r,o,a,s){return NAMESPACE.Maps.GetTrioProperties(e).map((e,s)=>({sourceId:"world-instance",property:e,type:"float",valueType:"numeric",startValue:t[s],endValue:r[s],ease:NAMESPACE.Maps.GetEaseFromIndex(o),resultMode:a}))}static _GetPairConfig(e,t,r,o,a,s){return NAMESPACE.Maps.GetPairProperties(e).map((e,s)=>({sourceId:"world-instance",property:e,type:"float",valueType:"numeric",startValue:t[s],endValue:r[s],ease:NAMESPACE.Maps.GetEaseFromIndex(o),resultMode:a}))}static _GetColorConfig(e,t,r,o,a,s){return C3.Plugins.Text&&s.GetPlugin()instanceof C3.Plugins.Text?{sourceId:"plugin",sourceArgs:[7],property:"color",type:"color",valueType:"color",startValue:t,endValue:r,ease:NAMESPACE.Maps.GetEaseFromIndex(o),resultMode:a}:{sourceId:"world-instance",property:e,type:"color",valueType:"color",startValue:t,endValue:r,ease:NAMESPACE.Maps.GetEaseFromIndex(o),resultMode:a}}static _GetAngleConfig(e,t,r,o,a,s){return{sourceId:"world-instance",property:e,type:"angle",valueType:"angle",startValue:t,endValue:r,ease:NAMESPACE.Maps.GetEaseFromIndex(o),resultMode:a}}static _GetCommonConfig(e,t,r,o,a,s){return{sourceId:"world-instance",property:e,type:"float",valueType:"numeric",startValue:t,endValue:r,ease:NAMESPACE.Maps.GetEaseFromIndex(o),resultMode:a}}static _GetValueConfig(e,t,r,o,a,s){return{sourceId:"value",property:e,type:"float",valueType:"numeric",startValue:t,endValue:r,ease:NAMESPACE.Maps.GetEaseFromIndex(o),resultMode:a}}}; } // scripts/behaviors/Tween/c3runtime/tweenArguments.js { const C3=self.C3,NAMESPACE=C3.Behaviors.Tween,COMMON_FIXED_ARGS={resultMode:"absolute"},COMMON_VARIABLE_ARGS=Object.assign({},COMMON_FIXED_ARGS,{tags:"",property:"",time:0,ease:0,releaseOnComplete:0,loop:!1,pingPong:!1,repeatCount:1}),ONE_PROPERTY_ARGS=Object.assign({},COMMON_VARIABLE_ARGS,{initialValueMode:"current-state",startValue:0,endValue:0}),TWO_PROPERTIES_ARGS=Object.assign({},COMMON_VARIABLE_ARGS,{initialValueMode:"current-state",startValue:[0,0],endValue:[0,0]}),THREE_PROPERTIES_ARGS=Object.assign({},COMMON_VARIABLE_ARGS,{initialValueMode:"current-state",startValue:[0,0,0],endValue:[0,0,0]}),COLOR_PROPERTY_ARGS=Object.assign({},COMMON_VARIABLE_ARGS,{initialValueMode:"current-state",startValue:[0,0,0],endValue:[0,0,0]}),VALUE_PROPERTY_ARGS=Object.assign({},ONE_PROPERTY_ARGS,{initialValueMode:"start-value"}),X=0,Y=1,Z=2,R=0,G=1,B=2;NAMESPACE.TweenArguments=class{constructor(){}static _SetCommonProperties(e,t,R,E,r,P,a,A){e.tags=t,e.time=R,e.ease=E,e.releaseOnComplete=r,e.loop=P,e.pingPong=a,e.repeatCount=A}static OneProperty(e,t,R,E,r,P,a,A,_,O){const o="string"==typeof R?R:NAMESPACE.Maps.GetSinglePropertyFromIndex(R),s=NAMESPACE.Maps.IsColorId(o)?COLOR_PROPERTY_ARGS:ONE_PROPERTY_ARGS;return this._SetCommonProperties(s,t,r,P,a,A,_,O),NAMESPACE.Maps.IsColorId(o)?(COLOR_PROPERTY_ARGS.endValue[0]=C3.GetRValue(E),COLOR_PROPERTY_ARGS.endValue[1]=C3.GetGValue(E),COLOR_PROPERTY_ARGS.endValue[2]=C3.GetBValue(E),COLOR_PROPERTY_ARGS.property=NAMESPACE.Maps.GetPropertyIndexFromName(o)):NAMESPACE.Maps.IsOpacityId(o)?ONE_PROPERTY_ARGS.endValue=E/100:ONE_PROPERTY_ARGS.endValue=E,s.property=NAMESPACE.Maps.GetPropertyIndexFromName(o),s}static TwoProperties(e,t,R,E,r,P,a,A,_,O,o){this._SetCommonProperties(TWO_PROPERTIES_ARGS,t,P,a,A,_,O,o);const s="string"==typeof R?R:NAMESPACE.Maps.GetPairPropertyFromIndex(R);return TWO_PROPERTIES_ARGS.endValue[0]=E,TWO_PROPERTIES_ARGS.endValue[1]=r,TWO_PROPERTIES_ARGS.property=NAMESPACE.Maps.GetPropertyIndexFromName(s),TWO_PROPERTIES_ARGS}static ThreeProperties(e,t,R,E,r,P,a,A,_,O,o,s){this._SetCommonProperties(THREE_PROPERTIES_ARGS,t,a,A,_,O,o,s);const S="string"==typeof R?R:NAMESPACE.Maps.GetTrioPropertyFromIndex(R);return THREE_PROPERTIES_ARGS.endValue[0]=E,THREE_PROPERTIES_ARGS.endValue[1]=r,THREE_PROPERTIES_ARGS.endValue[2]=P,THREE_PROPERTIES_ARGS.property=NAMESPACE.Maps.GetPropertyIndexFromName(S),THREE_PROPERTIES_ARGS}static ValueProperty(e,t,R,E,r,P,a,A,_,O){return this._SetCommonProperties(VALUE_PROPERTY_ARGS,t,r,P,a,A,_,O),VALUE_PROPERTY_ARGS.startValue=R,VALUE_PROPERTY_ARGS.endValue=E,VALUE_PROPERTY_ARGS.property=NAMESPACE.Maps.GetPropertyIndexFromName("value"),VALUE_PROPERTY_ARGS}}; } // scripts/behaviors/Tween/c3runtime/propertyTypes.js { const C3=self.C3,NAMESPACE=C3.Behaviors.Tween,TYPE_CHECK_OBJECTS=[];NAMESPACE.PropertyTypes=class{constructor(){}static Pick(t){if(0===TYPE_CHECK_OBJECTS.length){const t=TYPE_CHECK_OBJECTS;t.push({checkFunc:NAMESPACE.Maps.IsTrioId,result:this.TRIO}),t.push({checkFunc:NAMESPACE.Maps.IsPairId,result:this.PAIR}),t.push({checkFunc:NAMESPACE.Maps.IsColorId,result:this.COLOR}),t.push({checkFunc:NAMESPACE.Maps.IsAngleId,result:this.ANGLE}),t.push({checkFunc:NAMESPACE.Maps.IsValueId,result:this.VALUE}),t.push({checkFunc:()=>!0,result:this.OTHER})}C3.IsFiniteNumber(t)&&(t=C3.Behaviors.Tween.Maps.GetPropertyFromIndex(t));for(const s of TYPE_CHECK_OBJECTS)if(s.checkFunc(t))return s.result}static get TRIO(){return"trio"}static get PAIR(){return"pair"}static get COLOR(){return"color"}static get ANGLE(){return"angle"}static get VALUE(){return"value"}static get OTHER(){return"other"}}; } // scripts/behaviors/Tween/c3runtime/valueGetters.js { const C3=self.C3,NAMESPACE=C3.Behaviors.Tween;NAMESPACE.ValueGetters=class{constructor(){}static _GetPropertyAngleValue(e){const t=C3.toRadians(parseFloat(e));return C3.clampAngle(t)}static _GetColorPropertyValue(e){return e.slice(0)}static _GetPropertyValue(e){return e}}; } // scripts/behaviors/Tween/c3runtime/scriptInterface.js { const C3=self.C3,C3X=self.C3X,IBehaviorInstance=self.IBehaviorInstance,Ease=self.Ease,NAMESPACE=C3.Behaviors.Tween,map=new WeakMap,TWEEN_PROPERTIES=new Map([["x",{name:"offsetX",type:"one"}],["y",{name:"offsetY",type:"one"}],["z",{name:"offsetZElevation",type:"one"}],["z-elevation",{name:"offsetZElevation",type:"one"}],["width",{name:"offsetWidth",type:"one"}],["height",{name:"offsetHeight",type:"one"}],["angle",{name:"offsetAngle",type:"one"}],["opacity",{name:"offsetOpacity",type:"one"}],["color",{name:"offsetColor",type:"color"}],["x-scale",{name:"offsetScaleX",type:"one"}],["y-scale",{name:"offsetScaleY",type:"one"}],["position",{name:"position",type:"two"}],["size",{name:"size",type:"two"}],["scale",{name:"scale",type:"two"}],["value",{name:"value",type:"value"}],["position-3d",{name:"position3",type:"three"}]]);function getIndexForEase(e){C3X.RequireString(e);const t=Ease.ToInternal(e);let n;if(n=t?Ease.GetIndexForEase(t,null):Ease.GetIndexForEase(e,null),-1===n)throw new Error(`invalid ease name '${e}'`);return n}const TWEEN_OPTS={tags:"",destroyOnComplete:!1,loop:!1,pingPong:!1,repeatCount:1,startValue:0},I_TWEEN_OPTS={easeToIndexFunc:getIndexForEase};function ValidateTags(e,t=!1){if(!(t&&null==e||"string"==typeof e||Array.isArray(e)))throw new Error("invalid tags")}self.ITweenBehaviorInstance=class extends IBehaviorInstance{constructor(){super(),map.set(this,IBehaviorInstance._GetInitInst().GetSdkInstance())}startTween(e,t,n,a,o){const s=map.get(this);if(!s.IsEnabled()||!s.IsInstanceValid())return null;const r=TWEEN_PROPERTIES.get(e);if(!r)throw new Error("invalid tween property");"one"===r.type||"value"===r.type?C3X.RequireNumber(t):(C3X.RequireArray(t),"two"===r.type?(C3X.RequireNumber(t[0]),C3X.RequireNumber(t[1])):("color"===r.type||"three"===r.type)&&(C3X.RequireNumber(t[0]),C3X.RequireNumber(t[1]),C3X.RequireNumber(t[2]))),"angle"===e?t=C3.toDegrees(t):"opacity"===e?t*=100:"color"===e&&(t=C3.PackRGBEx(t[0],t[1],t[2]));const i=getIndexForEase(a);let l;if(C3X.RequireFiniteNumber(n),o=Object.assign({},TWEEN_OPTS,o),"value"===r.type&&C3X.RequireNumber(o.startValue),ValidateTags(o.tags,!0),"one"===r.type||"color"===r.type?l=s.CreateTween(NAMESPACE.TweenArguments.OneProperty(s,o.tags,r.name,t,n,i,!!o.destroyOnComplete,!!o.loop,!!o.pingPong,o.repeatCount)):"two"===r.type?l=s.CreateTween(NAMESPACE.TweenArguments.TwoProperties(s,o.tags,r.name,t[0],t[1],n,i,!!o.destroyOnComplete,!!o.loop,!!o.pingPong,o.repeatCount)):"three"===r.type?l=s.CreateTween(NAMESPACE.TweenArguments.ThreeProperties(s,o.tags,r.name,t[0],t[1],t[2],n,i,!!o.destroyOnComplete,!!o.loop,!!o.pingPong,o.repeatCount)):"value"===r.type&&(l=s.CreateTween(NAMESPACE.TweenArguments.ValueProperty(s,o.tags,o.startValue,t,n,i,!!o.destroyOnComplete,!!o.loop,!!o.pingPong,o.repeatCount))),l.SetBehaviorInstance(s.GetBehaviorInstance().GetSdkInstance()),!l.Play())throw new Error("failed to start tween");return l.GetITweenState(s,I_TWEEN_OPTS)}*allTweens(){const e=map.get(this);for(const t of e.AllTweens())yield t.GetITweenState(e,I_TWEEN_OPTS)}*tweensByTags(e){ValidateTags(e);const t=map.get(this);for(const n of t.GetTweens(e))yield n.GetITweenState(t,I_TWEEN_OPTS)}get isEnabled(){return map.get(this).IsEnabled()}set isEnabled(e){map.get(this).SetEnabled(e)}}; } // scripts/behaviors/Pin/c3runtime/runtime.js { {const t=self.C3;t.Behaviors.Pin=class extends t.SDKBehaviorBase{constructor(t){super(t)}Release(){super.Release()}}}{const t=self.C3;t.Behaviors.Pin.Type=class extends t.SDKBehaviorTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}}}{const t=self.C3;t.Behaviors.Pin.Instance=class extends t.SDKBehaviorInstanceBase{constructor(s,e){super(s),this._pinInst=null,this._pinUid=-1,this._mode="",this._propSet=new Set,this._pinDist=0,this._pinAngle=0,this._pinImagePoint=0,this._dx=0,this._dy=0,this._dWidth=0,this._dHeight=0,this._dAngle=0,this._dz=0,this._lastKnownAngle=0,this._destroy=!1,e&&(this._destroy=e[0]);const i=this._runtime.Dispatcher();this._disposables=new t.CompositeDisposable(t.Disposable.From(i,"instancedestroy",t=>this._OnInstanceDestroyed(t.instance)),t.Disposable.From(i,"afterload",t=>this._OnAfterLoad()))}Release(){this._pinInst=null,super.Release()}_SetPinInst(t){t?(this._pinInst=t,this._StartTicking2()):(this._pinInst=null,this._StopTicking2())}_Pin(s,e,i){if(!s)return;const h=s.GetFirstPicked(this._inst);if(!h)return;this._mode=e,this._SetPinInst(h);const n=this._inst.GetWorldInfo(),a=h.GetWorldInfo();if("properties"===this._mode){const s=this._propSet;s.clear();for(const t of i)s.add(t);this._dx=n.GetX()-a.GetX(),this._dy=n.GetY()-a.GetY(),this._dz=n.GetZ()-a.GetZ(),this._dAngle=n.GetAngle()-a.GetAngle(),this._lastKnownAngle=n.GetAngle(),s.has("x")&&s.has("y")&&(this._pinAngle=t.angleTo(a.GetX(),a.GetY(),n.GetX(),n.GetY())-a.GetAngle(),this._pinDist=t.distanceTo(a.GetX(),a.GetY(),n.GetX(),n.GetY())),s.has("width-abs")?this._dWidth=n.GetWidth()-a.GetWidth():s.has("width-scale")&&(this._dWidth=n.GetWidth()/a.GetWidth()),s.has("height-abs")?this._dHeight=n.GetHeight()-a.GetHeight():s.has("height-scale")&&(this._dHeight=n.GetHeight()/a.GetHeight())}else this._pinDist=t.distanceTo(a.GetX(),a.GetY(),n.GetX(),n.GetY())}SaveToJson(){const t=this._propSet,s=this._mode,e={"uid":this._pinInst&&!this._pinInst.IsDestroyed()?this._pinInst.GetUID():-1,"m":s,"d":this._destroy};return"rope"===s||"bar"===s?e["pd"]=this._pinDist:"properties"===s&&(e["ps"]=[...this._propSet],t.has("imagepoint")?e["ip"]=this._pinImagePoint:t.has("x")&&t.has("y")?(e["pa"]=this._pinAngle,e["pd"]=this._pinDist):(t.has("x")&&(e["dx"]=this._dx),t.has("y")&&(e["dy"]=this._dy)),t.has("angle")&&(e["da"]=this._dAngle,e["lka"]=this._lastKnownAngle),(t.has("width-abs")||t.has("width-scale"))&&(e["dw"]=this._dWidth),(t.has("height-abs")||t.has("height-scale"))&&(e["dh"]=this._dHeight),t.has("z")&&(e["dz"]=this._dz)),e}LoadFromJson(t){const s=t["m"],e=this._propSet;if(e.clear(),this._pinUid=t["uid"],"number"!=typeof s){if(this._mode=s,t.hasOwnProperty("d")&&(this._destroy=!!t["d"]),"rope"===s||"bar"===s)this._pinDist=t["pd"];else if("properties"===s){for(const s of t["ps"])e.add(s);e.has("imagepoint")?this._pinImagePoint=t["ip"]:e.has("x")&&e.has("y")?(this._pinAngle=t["pa"],this._pinDist=t["pd"]):(e.has("x")&&(this._dx=t["dx"]),e.has("y")&&(this._dy=t["dy"])),e.has("angle")&&(this._dAngle=t["da"],this._lastKnownAngle=t["lka"]||0),(e.has("width-abs")||e.has("width-scale"))&&(this._dWidth=t["dw"]),(e.has("height-abs")||e.has("height-scale"))&&(this._dHeight=t["dh"]),e.has("z")&&(this._dz=t["dz"])}}else this._LoadFromJson_Legacy(t)}_LoadFromJson_Legacy(t){const s=this._propSet,e=t["msa"],i=t["tsa"],h=t["pa"],n=t["pd"];switch(t["m"]){case 0:this._mode="properties",s.add("x").add("y").add("angle"),this._pinAngle=h,this._pinDist=n,this._dAngle=e-i,this._lastKnownAngle=t["lka"];break;case 1:this._mode="properties",s.add("x").add("y"),this._pinAngle=h,this._pinDist=n;break;case 2:this._mode="properties",s.add("angle"),this._dAngle=e-i,this._lastKnownAngle=t["lka"];break;case 3:this._mode="rope",this._pinDist=t["pd"];break;case 4:this._mode="bar",this._pinDist=t["pd"]}}_OnAfterLoad(){-1===this._pinUid?this._SetPinInst(null):(this._SetPinInst(this._runtime.GetInstanceByUID(this._pinUid)),this._pinUid=-1)}_OnInstanceDestroyed(t){this._pinInst===t&&(this._SetPinInst(null),this._destroy&&this._runtime.DestroyInstance(this._inst))}Tick2(){const s=this._pinInst;if(!s||s.IsDestroyed())return;const e=s.GetWorldInfo(),i=this._inst.GetWorldInfo(),h=this._mode;let n=!1;if("rope"===h||"bar"===h){const s=t.distanceTo(i.GetX(),i.GetY(),e.GetX(),e.GetY());if(s>this._pinDist||"bar"===h&&sthis._SetSpeed(e.toRadians(t))},{name:t+".properties.acceleration.name",value:e.toDegrees(this._GetAcceleration()),onedit:t=>this._SetAcceleration(e.toRadians(t))},{name:t+".properties.enabled.name",value:this._IsEnabled(),onedit:e=>this._SetEnabled(e)}]}]}GetScriptInterfaceClass(){return self.IRotateBehaviorInstance}};const r=new WeakMap;self.IRotateBehaviorInstance=class extends s{constructor(){super(),r.set(this,s._GetInitInst().GetSdkInstance())}set speed(e){t.RequireFiniteNumber(e),r.get(this)._SetSpeed(e)}get speed(){return r.get(this)._GetSpeed()}set acceleration(e){t.RequireFiniteNumber(e),r.get(this)._SetAcceleration(e)}get acceleration(){return r.get(this)._GetAcceleration()}get isEnabled(){return r.get(this)._IsEnabled()}set isEnabled(e){r.get(this)._SetEnabled(e)}}}self.C3.Behaviors.Rotate.Cnds={IsEnabled(){return this._IsEnabled()}};{const e=self.C3;e.Behaviors.Rotate.Acts={SetSpeed(t){this._SetSpeed(e.toRadians(t))},SetAcceleration(t){this._SetAcceleration(e.toRadians(t))},SetEnabled(e){this._SetEnabled(e)}}}{const e=self.C3;e.Behaviors.Rotate.Exps={Speed(){return e.toDegrees(this._GetSpeed())},Acceleration(){return e.toDegrees(this._GetAcceleration())}}} } // scripts/behaviors/DragnDrop/c3runtime/runtime.js { {const e=self.C3;e.Behaviors.DragnDrop=class extends e.SDKBehaviorBase{constructor(t){super(t);const s=this._runtime.Dispatcher();this._disposables=new e.CompositeDisposable(e.Disposable.From(s,"pointerdown",e=>this._OnPointerDown(e.data)),e.Disposable.From(s,"pointermove",e=>this._OnPointerMove(e.data)),e.Disposable.From(s,"pointerup",e=>this._OnPointerUp(e.data,!1)),e.Disposable.From(s,"pointercancel",e=>this._OnPointerUp(e.data,!0)))}Release(){this._disposables.Release(),this._disposables=null,super.Release()}_OnPointerDown(e){"mouse"===e["pointerType"]&&0!==e["button"]||this._OnInputDown(e["pointerId"].toString(),e["pageX"]-this._runtime.GetCanvasClientX(),e["pageY"]-this._runtime.GetCanvasClientY())}_OnPointerMove(e){1&e["lastButtons"]&&!(1&e["buttons"])?this._OnInputUp(e["pointerId"].toString()):this._OnInputMove(e["pointerId"].toString(),e["pageX"]-this._runtime.GetCanvasClientX(),e["pageY"]-this._runtime.GetCanvasClientY())}_OnPointerUp(e,t){"mouse"===e["pointerType"]&&0!==e["button"]||this._OnInputUp(e["pointerId"].toString())}async _OnInputDown(t,s,n){const a=this.GetInstances();let r=null,i=null,o=0,h=0;for(const t of a){const a=t.GetBehaviorSdkInstanceFromCtor(e.Behaviors.DragnDrop);if(!a.IsEnabled()||a.IsDragging()||t.IsDestroyed())continue;const g=t.GetWorldInfo(),p=g.GetLayer(),[l,d]=p.CanvasCssToLayer(s,n,g.GetTotalZ());if(!p.IsSelfAndParentsInteractive()||!g.ContainsPoint(l,d))continue;if(!r){r=t,i=a,o=l,h=d;continue}const c=r.GetWorldInfo();(p.GetIndex()>c.GetLayer().GetIndex()||p.GetIndex()===c.GetLayer().GetIndex()&&g.GetZIndex()>c.GetZIndex())&&(r=t,i=a,o=l,h=d)}r&&await i._OnDown(t,o,h)}_OnInputMove(t,s,n){const a=this.GetInstances();for(const r of a){const a=r.GetBehaviorSdkInstanceFromCtor(e.Behaviors.DragnDrop);if(!a.IsEnabled()||!a.IsDragging()||a.IsDragging()&&a.GetDragSource()!==t)continue;const i=r.GetWorldInfo(),o=i.GetLayer(),[h,g]=o.CanvasCssToLayer(s,n,i.GetTotalZ());a._OnMove(h,g)}}async _OnInputUp(t){const s=this.GetInstances();for(const n of s){const s=n.GetBehaviorSdkInstanceFromCtor(e.Behaviors.DragnDrop);s.IsDragging()&&s.GetDragSource()===t&&await s._OnUp()}}}}{const e=self.C3;e.Behaviors.DragnDrop.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t=(self.C3X,self.IBehaviorInstance),s=0,n=1;e.Behaviors.DragnDrop.Instance=class extends e.SDKBehaviorInstanceBase{constructor(e,t){super(e),this._isDragging=!1,this._dx=0,this._dy=0,this._dragSource="",this._axes=0,this._isEnabled=!0,t&&(this._axes=t[s],this._isEnabled=t[n])}Release(){super.Release()}SaveToJson(){return{"a":this._axes,"e":this._isEnabled}}LoadFromJson(e){this._axes=e["a"],this._isEnabled=e["e"],this._isDragging=!1}_SetEnabled(e){this._isEnabled=!!e,this._isEnabled||(this._isDragging=!1)}IsEnabled(){return this._isEnabled}_SetAxes(e){this._axes=e}_GetAxes(){return this._axes}_Drop(){this._isDragging&&this._OnUp()}IsDragging(){return this._isDragging}GetDragSource(){return this._dragSource}async _OnDown(t,s,n){const a=this.GetWorldInfo();this._dx=s-a.GetX(),this._dy=n-a.GetY(),this._isDragging=!0,this._dragSource=t,this.DispatchScriptEvent("dragstart"),await this.TriggerAsync(e.Behaviors.DragnDrop.Cnds.OnDragStart)}_OnMove(e,t){const s=this.GetWorldInfo(),n=e-this._dx,a=t-this._dy;0===this._axes?s.GetX()===n&&s.GetY()===a||(s.SetXY(n,a),s.SetBboxChanged()):1===this._axes?s.GetX()!==n&&(s.SetX(n),s.SetBboxChanged()):2===this._axes&&s.GetY()!==a&&(s.SetY(a),s.SetBboxChanged())}async _OnUp(){this._isDragging=!1,this.DispatchScriptEvent("drop"),await this.TriggerAsync(e.Behaviors.DragnDrop.Cnds.OnDrop)}GetPropertyValueByIndex(e){switch(e){case s:return this._GetAxes();case n:return this.IsEnabled()}}SetPropertyValueByIndex(e,t){switch(e){case s:this._SetAxes(t);break;case n:this._SetEnabled(!!t)}}GetDebuggerProperties(){const e="behaviors.dragndrop",t=e+".properties.axes";let s="";return 0===this._axes?s=t+".items.both":1===this._axes?s=t+".items.horizontal-only":2===this._axes&&(s=t+".items.vertical-only"),[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:e+".debugger.is-dragging",value:this.IsDragging()},{name:t+".name",value:[s]},{name:e+".properties.enabled.name",value:this.IsEnabled(),onedit:e=>this._SetEnabled(e)}]}]}GetScriptInterfaceClass(){return self.IDragDropBehaviorInstance}};const a=new WeakMap,r=["both","horizontal","vertical"];self.IDragDropBehaviorInstance=class extends t{constructor(){super(),a.set(this,t._GetInitInst().GetSdkInstance())}set axes(e){const t=r.indexOf(e);if(-1===t)throw new Error("invalid axes");a.get(this)._SetAxes(t)}get axes(){return r[a.get(this)._GetAxes()]}drop(){a.get(this)._Drop()}get isDragging(){return a.get(this).IsDragging()}get isEnabled(){return a.get(this).IsEnabled()}set isEnabled(e){a.get(this)._SetEnabled(e)}}}self.C3.Behaviors.DragnDrop.Cnds={IsDragging(){return this.IsDragging()},OnDragStart:()=>!0,OnDrop:()=>!0,IsEnabled(){return this.IsEnabled()}};self.C3.Behaviors.DragnDrop.Acts={SetEnabled(e){this._SetEnabled(!!e)},SetAxes(e){this._SetAxes(e)},Drop(){this._Drop()}};self.C3.Behaviors.DragnDrop.Exps={}; } // scripts/behaviors/Sin/c3runtime/runtime.js { {const e=self.C3;e.Behaviors.Sin=class extends e.SDKBehaviorBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.Sin.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t=self.C3X,i=self.IBehaviorInstance,s=0,a=1,n=2,h=3,_=4,r=5,o=6,l=7,u=8,d=0,m=1,g=2,v=3,c=4,p=5,G=6,b=7,S=8,V=9,w=0,P=1,M=2,I=3,f=4,k=2*Math.PI,W=Math.PI/2,R=3*Math.PI/2,E=[0,1,8,3,4,2,5,6,9,7];e.Behaviors.Sin.Instance=class extends e.SDKBehaviorInstanceBase{constructor(t,i){super(t),this._i=0,this._movement=0,this._wave=0,this._period=0,this._mag=0,this._isEnabled=!0,this._basePeriod=0,this._basePeriodOffset=0,this._baseMag=0,this._periodRandom=0,this._periodOffsetRandom=0,this._magnitudeRandom=0,this._initialValue=0,this._initialValue2=0,this._lastKnownValue=0,this._lastKnownValue2=0,this._ratio=0,i&&(this._movement=E[i[s]],this._wave=i[a],this._periodRandom=this._runtime.Random()*i[h],this._basePeriod=i[n],this._period=i[n],this._period+=this._periodRandom,this._basePeriodOffset=i[_],0!==this._period&&(this._periodOffsetRandom=this._runtime.Random()*i[r],this._i=i[_]/this._period*k,this._i+=this._periodOffsetRandom/this._period*k),this._magnitudeRandom=this._runtime.Random()*i[l],this._baseMag=i[o],this._mag=i[o],this._mag+=this._magnitudeRandom,this._isEnabled=!!i[u]),this._movement===p&&(this._mag=e.toRadians(this._mag)),this.Init(),this._isEnabled&&this._StartTicking()}Release(){super.Release()}SaveToJson(){return{"i":this._i,"e":this._isEnabled,"mv":this._movement,"w":this._wave,"p":this._period,"mag":this._mag,"iv":this._initialValue,"iv2":this._initialValue2,"r":this._ratio,"lkv":this._lastKnownValue,"lkv2":this._lastKnownValue2}}LoadFromJson(e){this._i=e["i"],this._SetEnabled(e["e"]),this._movement=e["mv"],this._wave=e["w"],this._period=e["p"],this._mag=e["mag"],this._initialValue=e["iv"],this._initialValue2=e["iv2"],this._ratio=e["r"],this._lastKnownValue=e["lkv"],this._lastKnownValue2=e["lkv2"]}Init(){const e=this._inst.GetWorldInfo();switch(this._movement){case d:this._initialValue=e.GetX();break;case m:this._initialValue=e.GetY();break;case g:this._initialValue=e.GetWidth(),this._ratio=e.GetHeight()/e.GetWidth();break;case v:this._initialValue=e.GetWidth();break;case c:this._initialValue=e.GetHeight();break;case p:this._initialValue=e.GetAngle();break;case G:this._initialValue=e.GetOpacity();break;case b:this._initialValue=0;break;case S:this._initialValue=e.GetX(),this._initialValue2=e.GetY();break;case V:this._initialValue=e.GetZ()}this._lastKnownValue=this._initialValue,this._lastKnownValue2=this._initialValue2}WaveFunc(e){switch(e%=k,this._wave){case w:return Math.sin(e);case P:return e<=W?e/W:e<=R?1-2*(e-W)/Math.PI:(e-R)/W-1;case M:return 2*e/k-1;case I:return-2*e/k+1;case f:return ethis._SetEnabled(e)},{name:e+".properties.period.name",value:this._GetPeriod(),onedit:e=>this._SetPeriod(e)},{name:e+".properties.magnitude.name",value:this._GetMagnitude_ConvertAngle(),onedit:e=>this._SetMagnitude_ConvertAngle(e)},{name:e+".debugger.value",value:this.WaveFunc(this._GetPhase())*this._GetMagnitude_ConvertAngle()}]}]}GetScriptInterfaceClass(){return self.ISineBehaviorInstance}};const C=new WeakMap,K=["horizontal","vertical","size","width","height","angle","opacity","value-only","forwards-backwards","z-elevation"],F=["sine","triangle","sawtooth","reverse-sawtooth","square"];self.ISineBehaviorInstance=class extends i{constructor(){super(),C.set(this,i._GetInitInst().GetSdkInstance())}set period(e){t.RequireFiniteNumber(e),C.get(this)._SetPeriod(e)}get period(){return C.get(this)._GetPeriod()}set magnitude(e){t.RequireFiniteNumber(e),C.get(this)._SetMagnitude(e)}get magnitude(){return C.get(this)._GetMagnitude()}set phase(e){C.get(this)._SetPhase(e)}get phase(){return C.get(this)._GetPhase()}set movement(e){t.RequireString(e);const i=K.indexOf(e);if(-1===i)throw new Error("invalid movement");C.get(this)._SetMovement(i)}get movement(){return K[C.get(this)._GetMovement()]}set wave(e){t.RequireString(e);const i=F.indexOf(e);if(-1===i)throw new Error("invalid wave");C.get(this)._SetWave(i)}get wave(){return F[C.get(this)._GetWave()]}get value(){const e=C.get(this);return e.WaveFunc(e._GetPhase())*e._GetMagnitude()}updateInitialState(){C.get(this).Init()}set isEnabled(e){C.get(this)._SetEnabled(!!e)}get isEnabled(){return C.get(this)._IsEnabled()}}}{const e=self.C3;e.Behaviors.Sin.Cnds={IsEnabled(){return this._IsEnabled()},CompareMovement(e){return this._GetMovement()===e},ComparePeriod(t,i){return e.compare(this._GetPeriod(),t,i)},CompareMagnitude(t,i){return e.compare(this._GetMagnitude_ConvertAngle(),t,i)},CompareWave(e){return this._GetWave()===e}}}self.C3.Behaviors.Sin.Acts={SetEnabled(e){this._SetEnabled(0!==e)},SetPeriod(e){this._SetPeriod(e)},SetMagnitude(e){this._SetMagnitude_ConvertAngle(e)},SetMovement(e){this._SetMovement(e)},SetWave(e){this._wave=e},SetPhase(e){const t=2*Math.PI;this._SetPhase(e*t%t)},UpdateInitialState(){this.Init()}};self.C3.Behaviors.Sin.Exps={CyclePosition(){return this._GetPhase()/(2*Math.PI)},Period(){return this._GetPeriod()},Magnitude(){return this._GetMagnitude_ConvertAngle()},Value(){return this.WaveFunc(this._GetPhase())*this._GetMagnitude_ConvertAngle()}}; } // scripts/expTable.js { const C3 = self.C3; function unaryminus(n) { return (typeof n === "number" ? -n : n); } function bothNumbers(a, b) { return typeof a === "number" && typeof b === "number"; } function add(l, r) { if (bothNumbers(l, r)) return l + r; else return l; } function subtract(l, r) { if (bothNumbers(l, r)) return l - r; else return l; } function multiply(l, r) { if (bothNumbers(l, r)) return l * r; else return l; } function divide(l, r) { if (bothNumbers(l, r)) return l / r; else return l; } function mod(l, r) { if (bothNumbers(l, r)) return l % r; else return l; } function pow(l, r) { if (bothNumbers(l, r)) return Math.pow(l, r); else return l; } function and(l, r) { if (typeof l === "string" || typeof r === "string") { // & with either side string does string concatenation let lstr, rstr; if (typeof l === "number") lstr = (Math.round(l * 1e10) / 1e10).toString(); else lstr = l; if (typeof r === "number") rstr = (Math.round(r * 1e10) / 1e10).toString(); else rstr = r; return lstr + rstr; } else { // & with neither side a string does logical AND return (l && r ? 1 : 0); } } function or(l, r) { if (bothNumbers(l, r)) return (l || r ? 1 : 0); else return l; } self.C3_ExpressionFuncs = [ () => "Startup", () => "complete", () => 0, p => { const n0 = p._GetNode(0); return () => n0.ExpObject(); }, () => "Board", () => 1, () => "", p => { const f0 = p._GetNode(0).GetBoundMethod(); return () => f0(12, 13, 14, 15, 16, 17, 18); }, () => "Easy", () => 150, () => "Medium", () => 100, () => "Hard", () => 60, p => { const f0 = p._GetNode(0).GetBoundMethod(); const v1 = p._GetNode(1).GetVar(); const f2 = p._GetNode(2).GetBoundMethod(); const v3 = p._GetNode(3).GetVar(); return () => ((f0(Math.floor((v1.GetValue() / 60)), 2) + ":") + f2(Math.floor((v3.GetValue() % 60)), 2)); }, p => { const v0 = p._GetNode(0).GetVar(); return () => and("Level", v0.GetValue()); }, p => { const f0 = p._GetNode(0).GetBoundMethod(); return () => f0(1, 2); }, p => { const f0 = p._GetNode(0).GetBoundMethod(); return () => f0(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18); }, () => 3, p => { const n0 = p._GetNode(0); return () => (n0.ExpObject(0) + 15); }, p => { const n0 = p._GetNode(0); return () => (n0.ExpObject(0) + 10); }, p => { const n0 = p._GetNode(0); return () => n0.ExpObject(2); }, p => { const n0 = p._GetNode(0); return () => n0.ExpInstVar(); }, p => { const n0 = p._GetNode(0); return () => n0.ExpInstVar_Family(); }, () => "catmove", () => 0.3, () => "for collision", () => 0.2, () => "Blocksunder", () => -15, () => "woodm", () => "touch blocks", p => { const n0 = p._GetNode(0); const n1 = p._GetNode(1); const n2 = p._GetNode(2); const n3 = p._GetNode(3); return () => C3.distanceTo(n0.ExpObject(), n1.ExpObject(), n2.ExpObject(), n3.ExpObject()); }, () => "movetovirtual", () => 0.1, p => { const f0 = p._GetNode(0).GetBoundMethod(); const n1 = p._GetNode(1); return () => (f0() - n1.ExpObject("Center")); }, () => "both", p => { const n0 = p._GetNode(0); const n1 = p._GetNode(1); const f2 = p._GetNode(2).GetBoundMethod(); const v3 = p._GetNode(3).GetVar(); const f4 = p._GetNode(4).GetBoundMethod(); const v5 = p._GetNode(5).GetVar(); return () => C3.distanceTo(n0.ExpObject("Center"), n1.ExpObject("Center"), (f2() - v3.GetValue()), (f4() - v5.GetValue())); }, p => { const f0 = p._GetNode(0).GetBoundMethod(); const v1 = p._GetNode(1).GetVar(); return () => (f0() - v1.GetValue()); }, () => "Center", () => "ver", p => { const n0 = p._GetNode(0); const n1 = p._GetNode(1); const n2 = p._GetNode(2); const f3 = p._GetNode(3).GetBoundMethod(); const v4 = p._GetNode(4).GetVar(); return () => C3.distanceTo(n0.ExpObject("Center"), n1.ExpObject("Center"), n2.ExpObject("Center"), (f3() - v4.GetValue())); }, p => { const n0 = p._GetNode(0); return () => n0.ExpObject("Center"); }, () => "hor", p => { const n0 = p._GetNode(0); const n1 = p._GetNode(1); const f2 = p._GetNode(2).GetBoundMethod(); const v3 = p._GetNode(3).GetVar(); const n4 = p._GetNode(4); return () => C3.distanceTo(n0.ExpObject("Center"), n1.ExpObject("Center"), (f2() - v3.GetValue()), n4.ExpObject("Center")); }, p => { const v0 = p._GetNode(0).GetVar(); return () => (v0.GetValue() - 10); }, p => { const v0 = p._GetNode(0).GetVar(); return () => v0.GetValue(); }, () => -20, () => "ui", p => { const f0 = p._GetNode(0).GetBoundMethod(); const n1 = p._GetNode(1); return () => (f0(n1.ExpObject()) + 50); }, p => { const f0 = p._GetNode(0).GetBoundMethod(); const n1 = p._GetNode(1); return () => (f0(n1.ExpObject()) - 100); }, () => 290, p => { const f0 = p._GetNode(0).GetBoundMethod(); const n1 = p._GetNode(1); return () => (f0(n1.ExpObject()) - 50); }, () => 250, p => { const f0 = p._GetNode(0).GetBoundMethod(); const f1 = p._GetNode(1).GetBoundMethod(); return () => multiply(f0((-1), 1), f1(50, 200)); }, p => { const f0 = p._GetNode(0).GetBoundMethod(); const n1 = p._GetNode(1); return () => f0(n1.ExpObject()); }, p => { const f0 = p._GetNode(0).GetBoundMethod(); return () => f0(99999999); }, () => 1.2, () => -50, () => 200, () => 2, () => "Complete", p => { const n0 = p._GetNode(0); return () => (n0.ExpObject() - 5); }, p => { const n0 = p._GetNode(0); return () => (n0.ExpObject() + 5); }, () => 25, () => 51, p => { const v0 = p._GetNode(0).GetVar(); const v1 = p._GetNode(1).GetVar(); return () => and(v0.GetValue(), v1.GetValue()); }, p => { const v0 = p._GetNode(0).GetVar(); return () => (v0.GetValue() + "_unlocked_level"); }, p => { const f0 = p._GetNode(0).GetBoundMethod(); return () => f0(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50); }, () => "pause", () => "timemode", () => 0.95, () => "sizeback", () => 0.5, () => "help", () => "Sound programming", () => "music", () => "playground", () => -100, () => "audio", p => { const f0 = p._GetNode(0).GetBoundMethod(); return () => f0(); }, p => { const n0 = p._GetNode(0); return () => (n0.ExpInstVar() - 1); }, () => 230, () => "back_line", () => 220, () => -2000, () => -1800, () => "Locked", () => "Open", () => "open", p => { const v0 = p._GetNode(0).GetVar(); const n1 = p._GetNode(1); return () => and(v0.GetValue(), n1.ExpInstVar()); } ]; }