// 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 Y<EPSILON?null:(L*=Y=1/Y,O*=Y,S*=Y,e=Math.sin(r),u=1-(o=Math.cos(r)),s=a[0],i=a[1],c=a[2],l=a[3],$=a[4],h=a[5],f=a[6],M=a[7],m=a[8],d=a[9],v=a[10],b=a[11],p=L*L*u+o,A=O*L*u+S*e,y=S*L*u-O*e,g=L*O*u-S*e,R=O*O*u+o,E=S*O*u+L*e,q=L*S*u+O*e,x=O*S*u-L*e,P=S*S*u+o,t[0]=s*p+$*A+m*y,t[1]=i*p+h*A+d*y,t[2]=c*p+f*A+v*y,t[3]=l*p+M*A+b*y,t[4]=s*g+$*R+m*E,t[5]=i*g+h*R+d*E,t[6]=c*g+f*R+v*E,t[7]=l*g+M*R+b*E,t[8]=s*q+$*x+m*P,t[9]=i*q+h*x+d*P,t[10]=c*q+f*x+v*P,t[11]=l*q+M*x+b*P,a!==t&&(t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15]),t)}function rotateX$3(t,a,r){var n=Math.sin(r),e=Math.cos(r),o=a[4],u=a[5],s=a[6],i=a[7],c=a[8],l=a[9],$=a[10],h=a[11];return a!==t&&(t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15]),t[4]=o*e+c*n,t[5]=u*e+l*n,t[6]=s*e+$*n,t[7]=i*e+h*n,t[8]=c*e-o*n,t[9]=l*e-u*n,t[10]=$*e-s*n,t[11]=h*e-i*n,t}function rotateY$3(t,a,r){var n=Math.sin(r),e=Math.cos(r),o=a[0],u=a[1],s=a[2],i=a[3],c=a[8],l=a[9],$=a[10],h=a[11];return a!==t&&(t[4]=a[4],t[5]=a[5],t[6]=a[6],t[7]=a[7],t[12]=a[12],t[13]=a[13],t[14]=a[14],t[15]=a[15]),t[0]=o*e-c*n,t[1]=u*e-l*n,t[2]=s*e-$*n,t[3]=i*e-h*n,t[8]=o*n+c*e,t[9]=u*n+l*e,t[10]=s*n+$*e,t[11]=i*n+h*e,t}function rotateZ$3(t,a,r){var n=Math.sin(r),e=Math.cos(r),o=a[0],u=a[1],s=a[2],i=a[3],c=a[4],l=a[5],$=a[6],h=a[7];return a!==t&&(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[0]=o*e+c*n,t[1]=u*e+l*n,t[2]=s*e+$*n,t[3]=i*e+h*n,t[4]=c*e-o*n,t[5]=l*e-u*n,t[6]=$*e-s*n,t[7]=h*e-i*n,t}function fromTranslation$1(t,a){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]=a[0],t[13]=a[1],t[14]=a[2],t[15]=1,t}function fromScaling(t,a){return t[0]=a[0],t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a[1],t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=a[2],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function fromRotation$1(t,a,r){var n,e,o,u=r[0],s=r[1],i=r[2],c=Math.hypot(u,s,i);return c<EPSILON?null:(u*=c=1/c,s*=c,i*=c,n=Math.sin(a),o=1-(e=Math.cos(a)),t[0]=u*u*o+e,t[1]=s*u*o+i*n,t[2]=i*u*o-s*n,t[3]=0,t[4]=u*s*o-i*n,t[5]=s*s*o+e,t[6]=i*s*o+u*n,t[7]=0,t[8]=u*i*o+s*n,t[9]=s*i*o-u*n,t[10]=i*i*o+e,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t)}function fromXRotation(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=n,t[6]=r,t[7]=0,t[8]=0,t[9]=-r,t[10]=n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function fromYRotation(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=0,t[2]=-r,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=r,t[9]=0,t[10]=n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function fromZRotation(t,a){var r=Math.sin(a),n=Math.cos(a);return t[0]=n,t[1]=r,t[2]=0,t[3]=0,t[4]=-r,t[5]=n,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 fromRotationTranslation$1(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=n+n,i=e+e,c=o+o,l=n*s,$=n*i,h=n*c,f=e*i,M=e*c,m=o*c,d=u*s,v=u*i,b=u*c;return t[0]=1-(f+m),t[1]=$+b,t[2]=h-v,t[3]=0,t[4]=$-b,t[5]=1-(l+m),t[6]=M+d,t[7]=0,t[8]=h+v,t[9]=M-d,t[10]=1-(l+f),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function fromQuat2(t,a){var r=new ARRAY_TYPE(3),n=-a[0],e=-a[1],o=-a[2],u=a[3],s=a[4],i=a[5],c=a[6],l=a[7],$=n*n+e*e+o*o+u*u;return $>0?(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)<EPSILON&&Math.abs(m-y)<EPSILON&&Math.abs(d-g)<EPSILON?identity$2(t):(l=M-A,$=m-y,h=d-g,e=b*(h*=f=1/Math.hypot(l,$,h))-p*($*=f),o=p*(l*=f)-v*h,u=v*$-b*l,(f=Math.hypot(e,o,u))?(e*=f=1/f,o*=f,u*=f):(e=0,o=0,u=0),s=$*u-h*o,i=h*e-l*u,c=l*o-$*e,(f=Math.hypot(s,i,c))?(s*=f=1/f,i*=f,c*=f):(s=0,i=0,c=0),t[0]=e,t[1]=s,t[2]=l,t[3]=0,t[4]=o,t[5]=i,t[6]=$,t[7]=0,t[8]=u,t[9]=c,t[10]=h,t[11]=0,t[12]=-(e*M+o*m+u*d),t[13]=-(s*M+i*m+c*d),t[14]=-(l*M+$*m+h*d),t[15]=1,t)}function targetTo(t,a,r,n){var e=a[0],o=a[1],u=a[2],s=n[0],i=n[1],c=n[2],l=e-r[0],$=o-r[1],h=u-r[2],f=l*l+$*$+h*h;f>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;s<i;s+=r)t[0]=a[s],t[1]=a[s+1],t[2]=a[s+2],o(t,t,u),a[s]=t[0],a[s+1]=t[1],a[s+2]=t[2];return a}}(),vec3=Object.freeze({__proto__:null,create:create$4,clone:clone$4,length:length$4,fromValues:fromValues$4,copy:copy$4,set:set$4,add:add$4,subtract:subtract$2,multiply:multiply$4,divide:divide$2,ceil:ceil$2,floor:floor$2,min:min$2,max:max$2,round:round$2,scale:scale$4,scaleAndAdd:scaleAndAdd$2,distance:distance$2,squaredDistance:squaredDistance$2,squaredLength:squaredLength$4,negate:negate$2,inverse:inverse$2,normalize:normalize$4,dot:dot$4,cross:cross$2,lerp:lerp$4,slerp:slerp$1,hermite:hermite,bezier:bezier,random:random$3,transformMat4:transformMat4$2,transformMat3:transformMat3$1,transformQuat:transformQuat$1,rotateX:rotateX$2,rotateY:rotateY$2,rotateZ:rotateZ$2,angle:angle$1,zero:zero$2,str:str$4,exactEquals:exactEquals$4,equals:equals$4,sub:sub$2,mul:mul$4,div:div$2,dist:dist$2,sqrDist:sqrDist$2,len:len$4,sqrLen:sqrLen$4,forEach:forEach$2});function create$3(){var t=new ARRAY_TYPE(4);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t}function clone$3(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 fromValues$3(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 copy$3(t,a){return t[0]=a[0],t[1]=a[1],t[2]=a[2],t[3]=a[3],t}function set$3(t,a,r,n,e){return t[0]=a,t[1]=r,t[2]=n,t[3]=e,t}function add$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}function subtract$1(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 multiply$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}function divide$1(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 ceil$1(t,a){return t[0]=Math.ceil(a[0]),t[1]=Math.ceil(a[1]),t[2]=Math.ceil(a[2]),t[3]=Math.ceil(a[3]),t}function floor$1(t,a){return t[0]=Math.floor(a[0]),t[1]=Math.floor(a[1]),t[2]=Math.floor(a[2]),t[3]=Math.floor(a[3]),t}function min$1(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[3]=Math.min(a[3],r[3]),t}function max$1(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[3]=Math.max(a[3],r[3]),t}function round$1(t,a){return t[0]=Math.round(a[0]),t[1]=Math.round(a[1]),t[2]=Math.round(a[2]),t[3]=Math.round(a[3]),t}function scale$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 scaleAndAdd$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}function distance$1(t,a){var r=a[0]-t[0],n=a[1]-t[1],e=a[2]-t[2],o=a[3]-t[3];return Math.hypot(r,n,e,o)}function squaredDistance$1(t,a){var r=a[0]-t[0],n=a[1]-t[1],e=a[2]-t[2],o=a[3]-t[3];return r*r+n*n+e*e+o*o}function length$3(t){var a=t[0],r=t[1],n=t[2],e=t[3];return Math.hypot(a,r,n,e)}function squaredLength$3(t){var a=t[0],r=t[1],n=t[2],e=t[3];return a*a+r*r+n*n+e*e}function negate$1(t,a){return t[0]=-a[0],t[1]=-a[1],t[2]=-a[2],t[3]=-a[3],t}function inverse$1(t,a){return t[0]=1/a[0],t[1]=1/a[1],t[2]=1/a[2],t[3]=1/a[3],t}function normalize$3(t,a){var r=a[0],n=a[1],e=a[2],o=a[3],u=r*r+n*n+e*e+o*o;return u>0&&(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;s<i;s+=r)t[0]=a[s],t[1]=a[s+1],t[2]=a[s+2],t[3]=a[s+3],o(t,t,u),a[s]=t[0],a[s+1]=t[1],a[s+2]=t[2],a[s+3]=t[3];return a}}(),vec4=Object.freeze({__proto__:null,create:create$3,clone:clone$3,fromValues:fromValues$3,copy:copy$3,set:set$3,add:add$3,subtract:subtract$1,multiply:multiply$3,divide:divide$1,ceil:ceil$1,floor:floor$1,min:min$1,max:max$1,round:round$1,scale:scale$3,scaleAndAdd:scaleAndAdd$1,distance:distance$1,squaredDistance:squaredDistance$1,length:length$3,squaredLength:squaredLength$3,negate:negate$1,inverse:inverse$1,normalize:normalize$3,dot:dot$3,cross:cross$1,lerp:lerp$3,random:random$2,transformMat4:transformMat4$1,transformQuat:transformQuat,zero:zero$1,str:str$3,exactEquals:exactEquals$3,equals:equals$3,sub:sub$1,mul:mul$3,div:div$1,dist:dist$1,sqrDist:sqrDist$1,len:len$3,sqrLen:sqrLen$3,forEach:forEach$1});function create$2(){var t=new ARRAY_TYPE(4);return ARRAY_TYPE!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function identity$1(t){return t[0]=0,t[1]=0,t[2]=0,t[3]=1,t}function setAxisAngle(t,a,r){r*=.5;var n=Math.sin(r);return t[0]=n*a[0],t[1]=n*a[1],t[2]=n*a[2],t[3]=Math.cos(r),t}function getAxisAngle(t,a){var r=2*Math.acos(a[3]),n=Math.sin(r/2);return n>EPSILON?(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)<EPSILON)return copy$1(t,a);var e=Math.hypot(r[0],r[1],r[2]);n*=.5;var o=Math.sin(n),u=o*r[0]/e,s=o*r[1]/e,i=o*r[2]/e,c=Math.cos(n),l=a[0],$=a[1],h=a[2],f=a[3];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]=f*c-l*u-$*s-h*i;var M=a[4],m=a[5],d=a[6],v=a[7];return t[4]=M*c+v*u+m*i-d*s,t[5]=m*c+v*s+d*u-M*i,t[6]=d*c+v*i+M*s-m*u,t[7]=v*c-M*u-m*s-d*i,t}function add$1(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}function multiply$1(t,a,r){var n=a[0],e=a[1],o=a[2],u=a[3],s=r[4],i=r[5],c=r[6],l=r[7],$=a[4],h=a[5],f=a[6],M=a[7],m=r[0],d=r[1],v=r[2],b=r[3];return t[0]=n*b+u*m+e*v-o*d,t[1]=e*b+u*d+o*m-n*v,t[2]=o*b+u*v+n*d-e*m,t[3]=u*b-n*m-e*d-o*v,t[4]=n*l+u*s+e*c-o*i+$*b+M*m+h*v-f*d,t[5]=e*l+u*i+o*s-n*c+h*b+M*d+f*m-$*v,t[6]=o*l+u*c+n*i-e*s+f*b+M*v+$*d-h*m,t[7]=u*l-n*s-e*i-o*c+M*b-$*m-h*d-f*v,t}var mul$1=multiply$1;function scale$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}var dot$1=dot$2;function lerp$1(t,a,r,n){var e=1-n;return dot$1(a,r)<0&&(n=-n),t[0]=a[0]*e+r[0]*n,t[1]=a[1]*e+r[1]*n,t[2]=a[2]*e+r[2]*n,t[3]=a[3]*e+r[3]*n,t[4]=a[4]*e+r[4]*n,t[5]=a[5]*e+r[5]*n,t[6]=a[6]*e+r[6]*n,t[7]=a[7]*e+r[7]*n,t}function invert(t,a){var r=squaredLength$1(a);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}function conjugate(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}var length$1=length$2,len$1=length$1,squaredLength$1=squaredLength$2,sqrLen$1=squaredLength$1;function normalize$1(t,a){var r=squaredLength$1(a);if(r>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<i;s+=r)t[0]=a[s],t[1]=a[s+1],o(t,t,u),a[s]=t[0],a[s+1]=t[1];return a}}(),vec2=Object.freeze({__proto__:null,create:create,clone:clone,fromValues:fromValues,copy:copy,set:set,add:add,subtract:subtract,multiply:multiply,divide:divide,ceil:ceil,floor:floor,min:min,max:max,round:round,scale:scale,scaleAndAdd:scaleAndAdd,distance:distance,squaredDistance:squaredDistance,length:length,squaredLength:squaredLength,negate:negate,inverse:inverse,normalize:normalize,dot:dot,cross:cross,lerp:lerp,random:random,transformMat2:transformMat2,transformMat2d:transformMat2d,transformMat3:transformMat3,transformMat4:transformMat4,rotate:rotate,angle:angle,zero:zero,str:str,exactEquals:exactEquals,equals:equals,len:len,sub:sub,mul:mul,div:div,dist:dist,sqrDist:sqrDist,sqrLen:sqrLen,forEach:forEach});globalThis.glMatrix=common,globalThis.glMatrix.mat2=mat2,globalThis.glMatrix.mat2d=mat2d,globalThis.glMatrix.mat3=mat3,globalThis.glMatrix.mat4=mat4,globalThis.glMatrix.quat=quat,globalThis.glMatrix.quat2=quat2,globalThis.glMatrix.vec2=vec2,globalThis.glMatrix.vec3=vec3,globalThis.glMatrix.vec4=vec4;
}

// 3rdparty/poly-decomp.js
{
function lineInt(o,n,t){t=t||0;var e,l,p,g,r,i,y,u=[0,0];return e=o[1][1]-o[0][1],l=o[0][0]-o[1][0],p=e*o[0][0]+l*o[0][1],g=n[1][1]-n[0][1],r=n[0][0]-n[1][0],i=g*n[0][0]+r*n[0][1],scalar_eq(y=e*r-g*l,0,t)||(u[0]=(r*p-l*i)/y,u[1]=(e*i-g*p)/y),u}function lineSegmentsIntersect(o,n,t,e){var l=n[0]-o[0],p=n[1]-o[1],g=e[0]-t[0],r=e[1]-t[1];if(g*p-r*l===0)return!1;var i=(l*(t[1]-o[1])+p*(o[0]-t[0]))/(g*p-r*l),y=(g*(o[1]-t[1])+r*(t[0]-o[0]))/(r*l-g*p);return i>=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))<e}return 0===triangleArea(o,n,t)}function sqdist(o,n){var t=n[0]-o[0],e=n[1]-o[1];return t*t+e*e}function polygonAt(o,n){var t=o.length;return o[n<0?n%t+t:n%t]}function polygonClear(o){o.length=0}function polygonAppend(o,n,t,e){for(var l=t;l<e;l++)o.push(n[l])}function polygonMakeCCW(o){for(var n=0,t=o,e=1;e<o.length;++e)(t[e][1]<t[n][1]||t[e][1]===t[n][1]&&t[e][0]>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)<l))return!1;return!0}function polygonCanSee2(o,n,t){for(var e=0;e!==o.length;++e)if(e!==n&&e!==t&&(e+1)%o.length!==n&&(e+1)%o.length!==t&&lineSegmentsIntersect(polygonAt(o,n),polygonAt(o,t),polygonAt(o,e),polygonAt(o,e+1)))return!1;return!0}function polygonCopy(o,n,t,e){var l=e||[];if(polygonClear(l),n<t)for(var p=n;p<=t;p++)l.push(o[p]);else{for(p=0;p<=t;p++)l.push(o[p]);for(p=n;p<o.length;p++)l.push(o[p])}return l}function polygonGetCutEdges(o){for(var n=[],t=[],e=[],l=[],p=Number.MAX_VALUE,g=0;g<o.length;++g)if(polygonIsReflex(o,g))for(var r=0;r<o.length;++r)if(polygonCanSee(o,g,r)){t=polygonGetCutEdges(polygonCopy(o,g,r,l)),e=polygonGetCutEdges(polygonCopy(o,r,g,l));for(var i=0;i<e.length;i++)t.push(e[i]);t.length<p&&(n=t,p=t.length,n.push([polygonAt(o,g),polygonAt(o,r)]))}return n}function polygonDecomp(o){var n=polygonGetCutEdges(o);return n.length>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;e<n.length;e++)for(var l=n[e],p=0;p<t.length;p++){var g=polygonSlice(t[p],l);if(g){t.splice(p,1),t.push(g[0],g[1]);break}}return t}l=n,e=o.indexOf(l[0]),p=o.indexOf(l[1]);return-1!==e&&-1!==p&&[polygonCopy(o,e,p),polygonCopy(o,p,e)]}function polygonIsSimple(o){var n,t=o;for(n=0;n<t.length-1;n++)for(var e=0;e<n-1;e++)if(lineSegmentsIntersect(t[n],t[n+1],t[e],t[e+1]))return!1;for(n=1;n<t.length-2;n++)if(lineSegmentsIntersect(t[0],t[t.length-1],t[n],t[n+1]))return!1;return!0}function getIntersectionPoint(o,n,t,e,l){l=l||0;var p=n[1]-o[1],g=o[0]-n[0],r=p*o[0]+g*o[1],i=e[1]-t[1],y=t[0]-e[0],u=i*t[0]+y*t[1],s=p*y-i*g;return scalar_eq(s,0,l)?[0,0]:[(y*r-g*u)/s,(p*u-i*r)/s]}function polygonQuickDecomp(o,n,t,e,l,p,g){p=p||100,g=g||0,l=l||25,n=void 0!==n?n:[],t=t||[],e=e||[];var r=[0,0],i=[0,0],y=[0,0],u=0,s=0,A=0,a=0,f=0,c=0,h=0,v=[],m=[],d=o,C=o;if(C.length<3)return n;if(++g>p)return console.warn("quickDecomp: max level ("+p+") reached."),n;for(var R=0;R<o.length;++R)if(polygonIsReflex(d,R)){t.push(d[R]),u=s=Number.MAX_VALUE;for(var q=0;q<o.length;++q)isLeft(polygonAt(d,R-1),polygonAt(d,R),polygonAt(d,q))&&isRightOn(polygonAt(d,R-1),polygonAt(d,R),polygonAt(d,q-1))&&(y=getIntersectionPoint(polygonAt(d,R-1),polygonAt(d,R),polygonAt(d,q),polygonAt(d,q-1)),isRight(polygonAt(d,R+1),polygonAt(d,R),y)&&(A=sqdist(d[R],y))<s&&(s=A,i=y,c=q)),isLeft(polygonAt(d,R+1),polygonAt(d,R),polygonAt(d,q+1))&&isRightOn(polygonAt(d,R+1),polygonAt(d,R),polygonAt(d,q))&&(y=getIntersectionPoint(polygonAt(d,R+1),polygonAt(d,R),polygonAt(d,q),polygonAt(d,q+1)),isLeft(polygonAt(d,R-1),polygonAt(d,R),y)&&(A=sqdist(d[R],y))<u&&(u=A,r=y,f=q));if(c===(f+1)%o.length)y[0]=(i[0]+r[0])/2,y[1]=(i[1]+r[1])/2,e.push(y),R<f?(polygonAppend(v,d,R,f+1),v.push(y),m.push(y),0!==c&&polygonAppend(m,d,c,d.length),polygonAppend(m,d,0,R+1)):(0!==R&&polygonAppend(v,d,R,d.length),polygonAppend(v,d,0,f+1),v.push(y),m.push(y),polygonAppend(m,d,c,R+1));else{if(c>f&&(f+=o.length),a=Number.MAX_VALUE,f<c)return n;for(q=c;q<=f;++q)isLeftOn(polygonAt(d,R-1),polygonAt(d,R),polygonAt(d,q))&&isRightOn(polygonAt(d,R+1),polygonAt(d,R),polygonAt(d,q))&&(A=sqdist(polygonAt(d,R),polygonAt(d,q)))<a&&polygonCanSee2(d,R,q)&&(a=A,h=q%o.length);R<h?(polygonAppend(v,d,R,h+1),0!==h&&polygonAppend(m,d,h,C.length),polygonAppend(m,d,0,R+1)):(0!==R&&polygonAppend(v,d,R,C.length),polygonAppend(v,d,0,h+1),polygonAppend(m,d,h,R+1))}return v.length<m.length?(polygonQuickDecomp(v,n,t,e,l,p,g),polygonQuickDecomp(m,n,t,e,l,p,g)):(polygonQuickDecomp(m,n,t,e,l,p,g),polygonQuickDecomp(v,n,t,e,l,p,g)),n}return n.push(o),n}function polygonRemoveCollinearPoints(o,n){for(var t=0,e=o.length-1;o.length>3&&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<e)throw new RangeError("number outside of range")},C3.RequireAllNumber=function(...e){for(let n of e);},C3.RequireFiniteNumber=function(e){if(!C3.IsFiniteNumber(e))throw new TypeError("expected finite number")},C3.RequireOptionalFiniteNumber=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllFiniteNumber=function(...e){for(let n of e);},C3.IsDataURI=function(e){return!!C3.IsString(e)&&/^data:.+,.+$/i.test(e)},C3.IsString=function(e){return"string"==typeof e},C3.RequireString=function(e){if(!C3.IsString(e))throw new TypeError("expected string")},C3.RequireOptionalString=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllString=function(...e){for(let n of e);},C3.IsSimpleObject=function(e){if("object"!=typeof e||null===e)return!1;let n=Object.getPrototypeOf(e);return n?n.constructor===Object:null===n},C3.RequireSimpleObject=function(e){if(!C3.IsSimpleObject(e))throw new TypeError("expected simple object")},C3.RequireOptionalSimpleObject=function(e){if(!C3.IsNullOrUndefined(e)&&!C3.IsSimpleObject(e))throw new TypeError("expected simple object")},C3.IsObject=function(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)},C3.RequireObject=function(e){if(!C3.IsObject(e))throw new TypeError("expected object")},C3.RequireOptionalObject=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllObject=function(...e){for(let n of e);},C3.IsFileLike=function(e){return C3.WeakIsInstanceOf(e,Blob)&&"string"==typeof e["name"]},C3.RequireFileLike=function(e){if(!C3.IsFileLike(e))throw new TypeError("expected file")},C3.RequireOptionalFileLike=function(e){C3.IsNullOrUndefined(e)},C3.IsArray=function(e){return Array.isArray(e)},C3.RequireArray=function(e){if(!C3.IsArray(e))throw new TypeError("expected array")},C3.RequireOptionalArray=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllArray=function(...e){for(let n of e);},C3.Is2DArray=function(e){return!!C3.IsArray(e)&&(!e.length||!!C3.IsArray(e[0]))},C3.Require2DArray=function(e){if(!C3.Is2DArray(e))throw new TypeError("expected 2d array");for(let n of e)if(!C3.IsArray(n))throw new TypeError("expected 2d array")},C3.RequireOptional2DArray=function(e){C3.IsNullOrUndefined(e)},C3.IsFunction=function(e){return"function"==typeof e},C3.RequireFunction=function(e,n){if(!C3.IsFunction(e))throw new TypeError("expected function");if(!C3.IsNullOrUndefined(n)&&e!==n)throw new TypeError("expected same function reference")},C3.RequireOptionalFunction=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllFunction=function(...e){for(let n of e);},C3.RequireAnyFunction=function(e,...n){if(!C3.IsFunction(e))throw new TypeError("expected function");if(!n.length)throw new Error("missing comparison functions");for(let r of n)if(!C3.IsNullOrUndefined(r)&&e===r)return;throw new TypeError("expected same function reference")},C3.RequireOptionalAllFunction=function(...e){if(!C3.IsNullOrUndefined(e))for(let n of e);},C3.IsInstanceOf=function(e,n){return e instanceof n},C3.IsInstanceOfAny=function(e,...n){for(let r of n)if(C3.IsInstanceOf(e,r))return!0;return!1},C3.RequireInstanceOf=function(e,n){if(!C3.IsInstanceOf(e,n))throw new TypeError("unexpected type")},C3.RequireOptionalInstanceOf=function(e,n){C3.IsNullOrUndefined(e)},C3.RequireAllInstanceOf=function(e,...n){for(let e of n);},C3.RequireAnyInstanceOf=function(e,...n){if(!C3.IsInstanceOfAny(e,...n))throw new TypeError("unexpected type")},C3.RequireAnyOptionalInstanceOf=function(e,...n){if(!C3.IsNullOrUndefined(e)&&!C3.IsInstanceOfAny(e,...n))throw new TypeError("unexpected type")},C3.IsArrayOf=function(e,n){for(let r of e)if(!C3.IsInstanceOf(r,n))return!1;return!0},C3.IsArrayOfFiniteNumbers=function(e){for(let n of e)if(!C3.IsFiniteNumber(n))return!1;return!0},C3.RequireArrayOf=function(e,n){for(let n of e);},C3.RequireOptionalArrayOf=function(e,n){if(!C3.IsNullOrUndefined(e))for(let n of e);},C3.RequireOptionalArrayOfFunctions=function(e,n){if(!C3.IsNullOrUndefined(e))for(let n of e);},C3.RequireArrayOfAny=function(e,...n){for(let n of e);},C3.RequireOptionalArrayOfAny=function(e,...n){if(!C3.IsNullOrUndefined(e))for(let n of e);},C3.IsDOMNode=function(e,n){return!(C3.IsNullOrUndefined(e)||!C3.IsString(e.nodeName))&&(!n||C3.equalsNoCase(e.nodeName,n))},C3.RequireDOMNode=function(e,n){if(C3.IsNullOrUndefined(e)||!C3.IsString(e.nodeName))throw new TypeError("expected DOM node");if(n&&!C3.equalsNoCase(e.nodeName,n))throw new TypeError(`expected DOM '${n}' node`)},C3.RequireOptionalDOMNode=function(e,n){C3.IsNullOrUndefined(e)},C3.IsHTMLElement=function(e,n){return!(C3.IsNullOrUndefined(e)||!C3.IsString(e.tagName))&&(!n||C3.equalsNoCase(e.tagName,n))},C3.RequireHTMLElement=function(e,n){if(C3.IsNullOrUndefined(e)||!C3.IsString(e.tagName))throw new TypeError("expected HTML element");if(n&&!C3.equalsNoCase(e.tagName,n))throw new TypeError(`expected HTML '${n}' element`)},C3.RequireOptionalHTMLElement=function(e,n){C3.IsNullOrUndefined(e)},C3.IsDrawable=function(e){return C3.IsHTMLElement(e,"img")||C3.IsHTMLElement(e,"canvas")||C3.IsHTMLElement(e,"video")||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap},C3.RequireDrawable=function(e){if(!C3.IsDrawable(e))throw new TypeError("expected drawable")},C3.RequireOptionalDrawable=function(e){C3.IsNullOrUndefined(e)},C3.IsDrawableOrImageData=function(e){return e instanceof ImageData||C3.IsDrawable(e)},C3.RequireDrawableOrImageData=function(e){if(!C3.IsDrawableOrImageData(e))throw new TypeError("expected drawable or image data")},C3.RequireOptionalDrawableOrImageData=function(e){if(!C3.IsNullOrUndefined(e)&&!C3.IsDrawableOrImageData(e))throw new TypeError("expected drawable or image data")},C3.IsStringLike=function(e){return"string"==typeof e||C3.HtmlString&&e instanceof C3.HtmlString||e instanceof C3.BBString},C3.RequireStringLike=function(e){if(!C3.IsStringLike(e))throw new TypeError("expected string-like")},C3.RequireOptionalStringLike=function(e){C3.IsNullOrUndefined(e)},C3.RequireAllStringLike=function(...e){for(let n of e);},C3.RequireOverride=function(){throw new Error("must be overridden")},C3.NotYetImplemented=function(){throw new Error("not yet implemented")},C3.IsGeneratorFunction=function(e){return e.constructor===function*(){}.constructor},C3.RequireGeneratorFunction=function(e){if(!C3.IsGeneratorFunction(e))throw new Error("expected generator function")},C3.IsIterable=function(e){return"function"===e[Symbol.iterator]},C3.RequireIterable=function(e){if(!C3.IsIterable(e))throw new Error("expected iterable")},C3.IsDefined=function(e){return!C3.IsNullOrUndefined(e)},C3.IsNullOrUndefined=function(e){return null==e},C3.AreArrayElementsOfSameType=function(e){let n=e[0].constructor;for(let r of e)if(r.constructor!==n)return!1;return n},C3.AreArrayElementsOfType=function(e,n){for(let r of e)if(!(r instanceof n))return!1;return!0};const TypedArray=Object.getPrototypeOf(Uint8Array);C3.IsTypedArray=function(e){return C3.IsInstanceOf(e,TypedArray)},C3.RequireTypedArray=function(e){},C3.WeakRequireTypedArray=function(e){C3.WeakRequireInstanceOf(e,TypedArray)},C3.WeakRequireAnyInstanceOf=function(e,...n){if(!C3.WeakIsAnyInstanceOf(e,...n))throw new TypeError("unexpected type")},C3.WeakIsAnyInstanceOf=function(e,...n){for(const r of n)if(C3.WeakIsInstanceOf(e,r))return!0;return!1},C3.WeakRequireInstanceOf=function(e,n){if(!C3.WeakIsInstanceOf(e,n))throw new TypeError("unexpected type")},C3.WeakIsInstanceOf=function(e,n){for(;e=Object.getPrototypeOf(e);)if(e.constructor.name===n.name)return!0;return!1},C3X.RequireNumber=C3.RequireNumber,C3X.RequireOptionalNumber=C3.RequireOptionalNumber,C3X.RequireFiniteNumber=C3.RequireFiniteNumber,C3X.RequireOptionalFiniteNumber=C3.RequireOptionalFiniteNumber,C3X.RequireString=C3.RequireString,C3X.RequireOptionalString=C3.RequireOptionalString,C3X.RequireObject=C3.RequireObject,C3X.RequireOptionalObject=C3.RequireOptionalObject,C3X.RequireArray=C3.RequireArray,C3X.RequireOptionalArray=C3.RequireOptionalArray,C3X.RequireFunction=C3.RequireFunction,C3X.RequireOptionalFunction=C3.RequireOptionalFunction,C3X.RequireInstanceOf=C3.RequireInstanceOf,C3X.RequireOptionalInstanceOf=C3.RequireOptionalInstanceOf,C3X.IsNullOrUndefined=C3.IsNullOrUndefined;
}

// ../lib/misc/jsutil.js
{
const C3=self.C3,logRafIds=new Map;let measures;function isValidTypeChange(e,t){let r=C3.getType(e),n=C3.getType(t);return"null"===r||"null"===n||"undefined"!==r&&"undefined"!==n&&r===n}C3.ColorLog=function(e,t){console.log(`%c${e}`,`font-weight: bold; color:${t}`)},C3.RafLog=function(e,...t){logRafIds.has(e)||logRafIds.set(e,-1),-1===logRafIds.get(e)&&logRafIds.set(e,requestAnimationFrame(()=>{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?"<boolean>":C3.IsNumber(e)?"<number>":C3.IsString(e)?"<string>":C3.IsArray(e)?"<array>":"symbol"==typeof e?"<"+e.toString()+">":C3.IsFunction(e)?e.name&&"Function"!==e.name?e.name:"<anonymous function>":"object"==typeof e?e.constructor&&e.constructor.name&&"Object"!==e.constructor.name?e.constructor.name:"<anonymous object>":"<unknown>"},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;r<t;r++)yield r};let ctorObjectToProxy=new Map,ctorProxyToObject=new Map,proxyToObject=new WeakMap,releasedObjects=new WeakMap;C3.DefendHandler={};const VALID_GET_MISSING_KEYS=new Set(["then","splice"]);function logDefendedObjectWarning(e){console.warn("[Defence] "+e+" @",C3.GetCallStack())}C3.DefendHandler.get=function(e,t){return t in e||"symbol"==typeof t||VALID_GET_MISSING_KEYS.has(t)||logDefendedObjectWarning(`Accessed missing property '${t}' from defended object '${C3.getName(e)}', returning undefined`),releasedObjects.has(e)&&"symbol"!=typeof t&&!VALID_GET_MISSING_KEYS.has(t)&&logDefendedObjectWarning(`Accessed property '${t}' on a released object '${C3.getName(e)}'\nObject was originally released at: ${releasedObjects.get(e)})\nCall stack at access: `),e[t]},C3.DefendHandler.set=function(e,t,r){return t in e||ctorObjectToProxy.has(e)||logDefendedObjectWarning(`Set non-existent property '${t}' to '${r}' on defended object '${C3.getName(e)}'`),isValidTypeChange(e[t],r)||ctorObjectToProxy.has(e)||logDefendedObjectWarning(`Set '${C3.getType(e[t])}' property '${t}' to type '${C3.getType(r)}' on defended object '${C3.getName(e)}'`),releasedObjects.has(e)&&logDefendedObjectWarning(`Set property '${t}' on a released object '${C3.getName(e)}'\nObject was originally released at: ${releasedObjects.get(e)})\nCall stack at access: `),e[t]=r,!0},C3.DefendHandler.deleteProperty=function(e,t){throw new ReferenceError(`Cannot delete property '${t}' from defended object '${C3.getName(e)}'`)},C3.DefendHandler.defineProperty=function(e,t,r){throw new ReferenceError(`Cannot define property '${t}' on defended object '${C3.getName(e)}'`)},C3.DefendHandler.enumerate=function(e){throw new ReferenceError(`Cannot enumerate defended object '${C3.getName(e)}'`)};let checkRafId=-1;function CheckDefendedObjectsUsedCorrectly(){if(checkRafId=-1,ctorObjectToProxy.size>0||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(t<e){const c=n-(e-t)%r;return c===n?0:c}return e+(t-e)%r},C3.mapToRange=function(t,e,n,r,c){const a=n-e;if(0===a&&0===r)return t;return(t-e)*(c-r)/a+r},C3.normalize=function(t,e,n){return e-n===0?1:(t-e)/(n-e)},C3.clamp=function(t,e,n){return t<e?e:t>n?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(u<l||i>C)return!1;const f=Math.min(e,r),m=Math.max(e,r),h=Math.min(a,o),M=Math.max(a,o);if(m<h||f>M)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(a<f||c>m)return!1;const h=Math.min(u,C),M=Math.max(u,C);if(o<h||s>M)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<C&&C<1.000001?(u*(s-t)+(c-s)*(o-e))/l:2},C3.rayIntersectExtended=function(t,e,n,r,c,a,s,o,i){const u=(s-c)*i,l=(o-a)*i;return C3.rayIntersect(t,e,n,r,c-u,a-l,s+u,o+l)},C3.isPointInTriangleInclusive=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=i*f+u*m,p=l*l+C*C,d=l*f+C*m,v=1/(h*p-M*M),I=(p*g-M*d)*v,T=(h*d-M*g)*v;return I>=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);n<v&&(v=n,vec3.copy(t,l))}}if(vec3.set(o,m,h,c),vec3.set(i,m,h,a),vec3.set(u,C,f,a),C3.segmentIntersectsQuad3d(l,e,n,s,o,i,u)){if(!l)return!0;{const n=vec3.squaredDistance(e,l);n<v&&(v=n,vec3.copy(t,l))}}if(vec3.set(s,m,h,a),vec3.set(i,M,g,c),vec3.set(u,M,g,a),C3.segmentIntersectsQuad3d(l,e,n,s,o,i,u)){if(!l)return!0;{const n=vec3.squaredDistance(e,l);n<v&&(v=n,vec3.copy(t,l))}}if(vec3.set(s,p,d,a),vec3.set(o,M,g,a),vec3.set(i,M,g,c),vec3.set(u,p,d,c),C3.segmentIntersectsQuad3d(l,e,n,s,o,i,u)){if(!l)return!0;{const n=vec3.squaredDistance(e,l);n<v&&(v=n,vec3.copy(t,l))}}if(vec3.set(s,C,f,a),vec3.set(o,m,h,a),vec3.set(i,M,g,a),vec3.set(u,p,d,a),C3.segmentIntersectsQuad3d(l,e,n,s,o,i,u)){if(!l)return!0;{const n=vec3.squaredDistance(e,l);n<v&&(v=n,vec3.copy(t,l))}}return!!t&&v!==1/0},C3.vec3FromArray=function(t,e,n=0){return t[0]=e[n],t[1]=e[n+1],t[2]=e[n+2],t},C3.vec3ToArray=function(t,e,n=0){return e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e},C3.quatFromArray=function(t,e,n=0){return t[0]=e[n],t[1]=e[n+1],t[2]=e[n+2],t[3]=e[n+3],t},C3.quatToEuler=function(t,e,n,r,c,a){let s,o,i;switch(a){case 0:case"xyz":case 3:case"zyx":s=Math.atan2(2*(c*e+n*r),1-2*(e*e+n*n)),o=Math.asin(C3.clamp(2*(c*n-r*e),-1,1)),i=Math.atan2(2*(c*r+e*n),1-2*(n*n+r*r));break;case 1:case"yxz":s=Math.asin(C3.clamp(2*(c*e-n*r),-1,1)),o=Math.atan2(2*(c*n+e*r),1-2*(e*e+n*n)),i=Math.atan2(2*(c*r+e*n),1-2*(e*e+r*r));break;case 2:case"zxy":s=Math.asin(C3.clamp(2*(c*e+n*r),-1,1)),o=Math.atan2(2*(c*n-e*r),1-2*(e*e+n*n)),i=Math.atan2(2*(c*r-e*n),1-2*(e*e+r*r));break;case 4:case"yzx":s=Math.atan2(2*(c*e-n*r),1-2*(e*e+r*r)),o=Math.atan2(2*(c*n-e*r),1-2*(n*n+r*r)),i=Math.asin(C3.clamp(2*(c*r+e*n),-1,1));break;case 5:case"xzy":s=Math.atan2(2*(c*e+n*r),1-2*(e*e+r*r)),o=Math.atan2(2*(c*n+e*r),1-2*(n*n+r*r)),i=Math.asin(C3.clamp(2*(c*r-e*n),-1,1));break;default:throw new Error("Unsupported Euler order")}t[0]=s,t[1]=o,t[2]=i},C3.mat4FromArray=function(t,e,n=0){return t[0]=e[n],t[1]=e[n+1],t[2]=e[n+2],t[3]=e[n+3],t[4]=e[n+4],t[5]=e[n+5],t[6]=e[n+6],t[7]=e[n+7],t[8]=e[n+8],t[9]=e[n+9],t[10]=e[n+10],t[11]=e[n+11],t[12]=e[n+12],t[13]=e[n+13],t[14]=e[n+14],t[15]=e[n+15],t},C3.makeScaleMatrix=function(t,e,n,r,c){return t.identity(e),e[0]=n,e[5]=r,e[10]=c,e},C3.makeTranslateMatrix=function(t,e,n,r,c){return t.identity(e),e[12]=n,e[13]=r,e[14]=c,e};
}

// ../lib/misc/miscutil.js
{
const C3=self.C3;let mainDocument=null,baseHref="";if("undefined"!=typeof document){mainDocument=document;const e=document.querySelector("base");baseHref=e&&e.hasAttribute("href")?e.getAttribute("href"):"",baseHref&&(baseHref.startsWith("/")&&(baseHref=baseHref.substr(1)),baseHref.endsWith("/")||(baseHref+="/"))}C3.GetBaseHref=function(){return baseHref},C3.GetBaseURL=function(){if(!mainDocument)return"";const e=mainDocument.location;return C3.GetPathFromURL(e.origin+e.pathname)+baseHref},C3.GetPathFromURL=function(e){if(!e.length)return e;if(e.endsWith("/")||e.endsWith("\\"))return e;const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return-1===t?"":e.substr(0,t+1)},C3.GetFilenameFromURL=function(e){if(!e.length)return e;if(e.endsWith("/")||e.endsWith("\\"))return"";const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return-1===t?e:e.substr(t+1)},C3.GetFileExtension=function(e){let t=e.lastIndexOf(".");return t<1?"":e.substr(t)},C3.SetFileExtension=function(e,t){const n=e.lastIndexOf(".");return-1===n?e+"."+t:e.substr(0,n+1)+t},C3.GetFileNamePart=function(e){let t=e.lastIndexOf(".");return t<1?e:e.substr(0,t)},C3.NormalizeFileSeparator=function(e){return e.replace(/\\/g,"/")},C3.IsFileExtension=function(e,t){return t===(e?C3.GetFileExtension(e).slice(1):"")},C3.FileNameEquals=function(e,t){let n,r;return C3.IsFileLike(e)&&(n=C3.GetFileNamePart(e["name"])),C3.IsString(e)&&(n=C3.GetFileNamePart(e)),C3.IsFileLike(t)&&(r=C3.GetFileNamePart(t["name"])),C3.IsString(t)&&(r=C3.GetFileNamePart(t)),n===r},C3.ParseFilePath=function(e){e=C3.NormalizeFileSeparator(e);let t=/^\w\:\//.exec(e);t?(t=t[0],"/"!==(e=e.slice(3))[0]&&(e="/"+e)):t="",(e=e.replace(/\/{2,}/g,"/")).length>1&&"/"===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;t<e.length;t++){let n=e[t];C3.truncateArray(n,0)}C3.truncateArray(e,0)}},C3.extendArray=function(e,t,n){t|=0;const r=e.length;if(!(t<=r))for(let a=r;a<t;++a)e.push(n)},C3.resizeArray=function(e,t,n){t|=0;const r=e.length;t<r?C3.truncateArray(e,t):t>r&&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<r;++n)e.push(t[n])},C3.arrayRemove=function(e,t){if((t=Math.floor(t))<0||t>=e.length)return;let n=e.length-1;for(let r=t;r<n;++r)e[r]=e[r+1];C3.truncateArray(e,n)},C3.arrayFindRemove=function(e,t){let n=e.indexOf(t);n>=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<n;++r)if(e[r]!==t[r])return!1;return!0},C3.mapsEqual=function(e,t){if(e.size!==t.size)return!1;for(const[n,r]of e){if(!t.has(n))return!1;if(r!==t.get(n))return!1}return!0},C3.arrayFilterOut=function(e,t){let n=[],r=0;for(let a=0,s=e.length;a<s;++a){let s=e[a];t(s)?n.push(s):(e[r]=s,++r)}return C3.truncateArray(e,r),n},C3.arrayRemoveAllInSet=function(e,t){const n=e.length;let r=0;for(let n=0,a=e.length;n<a;++n){let a=e[n];t.has(a)||(e[r++]=a)}return C3.truncateArray(e,r),n-r},C3.isArrayIndexInBounds=function(e,t){return e===Math.floor(e)&&(e>=0&&e<t.length)},C3.validateArrayIndex=function(e,t){if(!C3.isArrayIndexInBounds(e,t))throw new RangeError("array index out of bounds")},C3.cloneArray=function(e){return e.slice()},C3.deepCloneArray=function(e,t){let n=[];for(let r of e)if(C3.IsObject(r)){let e=t(r);if(!e)throw new Error("missing clone");if(e.constructor!==r.constructor)throw new Error("object is not a clone");n.push(e)}else C3.IsArray(r)?n.push(C3.deepCloneArray(r,t)):n.push(r);return n},C3.clone2DArray=function(e){let t=[];for(let n of e)t.push(n.slice());return t},C3.toArrayLike=function(e){return C3.IsArray(e)||C3.IsTypedArray(e)?e:e?(e.length=Object.keys(e).length,e):void 0},C3.splitStringAndNormalize=function(e,t=" "){return e?e.split(t).map(e=>e.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 e<n;case 3:return e<=n;case 4:return e>n;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<l;++o)a.push(void 0),e[o].then(r=>{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;r<e;++r)n.push(t());else for(let r=0;r<e;++r)n.push(t);return n};
}

// ../lib/misc/color.js
{
const C3=self.C3,HSL_TEST=/([0-9.]+),([0-9.]+)\%?,([0-9.]+)\%?/i,HSLA_TEST=/([0-9.]+),([0-9.]+)\%?,([0-9.]+)\%?,([0-9.])/i;function padTwoDigits(t){return 0===t.length?"00":1===t.length?"0"+t:t}function hueToRGB(t,s,e){return e<0&&(e+=1),e>1&&(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<e?6:0);break;case s:a=(e-t)/(r-i)+2;break;case e:a=(t-s)/(r-i)+4}return Math.round(a/6*360)}static GetSaturation(t,s,e){const r=Math.max(t,s,e),i=Math.min(t,s,e);if(r===i)return 0;const a=r-i,h=(r+i)/2>.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._top<this._bottom?this._left<this._right?this._bottom=this._top+this.width():this._bottom=this._top-this.width():this._left<this._right?this._bottom=this._top-this.width():this._bottom=this._top+this.width()}inflate(t,i){t=+t,i=+i,this._left-=t,this._top-=i,this._right+=t,this._bottom+=i}deflate(t,i){t=+t,i=+i,this._left+=t,this._top+=i,this._right-=t,this._bottom-=i}multiply(t,i){this._left*=t,this._top*=i,this._right*=t,this._bottom*=i}divide(t,i){this._left/=t,this._top/=i,this._right/=t,this._bottom/=i}mirrorAround(t){this._left=+t-this._left,this._right=+t-this._right}flipAround(t){this._top=+t-this._top,this._bottom=+t-this._bottom}rotate90DegreesAround(t,i){const h=this.width(),o=this.height(),s=this.getLeft()+h*t,_=this.getTop()+o*i;this.setWH(s-o*i,_-h*t,o,h)}swapLeftRight(){const t=this._left;this._left=this._right,this._right=t}swapTopBottom(){const t=this._top;this._top=this._bottom,this._bottom=t}shuntY(t){const i=this._top;this._top=+t-this._bottom,this._bottom=+t-i}round(){this._left=Math.round(this._left),this._top=Math.round(this._top),this._right=Math.round(this._right),this._bottom=Math.round(this._bottom)}roundInner(){this._left=Math.ceil(this._left),this._top=Math.ceil(this._top),this._right=Math.floor(this._right),this._bottom=Math.floor(this._bottom)}roundOuter(){this._left=Math.floor(this._left),this._top=Math.floor(this._top),this._right=Math.ceil(this._right),this._bottom=Math.ceil(this._bottom)}floor(){this._left=Math.floor(this._left),this._top=Math.floor(this._top),this._right=Math.floor(this._right),this._bottom=Math.floor(this._bottom)}ceil(){this._left=Math.ceil(this._left),this._top=Math.ceil(this._top),this._right=Math.ceil(this._right),this._bottom=Math.ceil(this._bottom)}clamp(t,i,h,o){this._left=Math.max(this._left,+t),this._top=Math.max(this._top,+i),this._right=Math.min(this._right,+h),this._bottom=Math.min(this._bottom,+o)}clampBoth(t,i,h,o){t=+t,i=+i,h=+h,o=+o,this._left=C3.clamp(this._left,t,h),this._top=C3.clamp(this._top,i,o),this._right=C3.clamp(this._right,t,h),this._bottom=C3.clamp(this._bottom,i,o)}normalize(){this._left>this._right&&this.swapLeftRight(),this._top>this._bottom&&this.swapTopBottom()}intersectsRect(t){return!(t._right<this._left||t._bottom<this._top||t._left>this._right||t._top>this._bottom)}intersectsRectOffset(t,i,h){return!(t._right+i<this._left||t._bottom+h<this._top||t._left+i>this._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._left||t.getBottom()<this._top||t.getLeft()>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._left<this._left&&(this._left=+t._left),t._top<this._top&&(this._top=+t._top),t._right>this._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.#t&&(this.#t=t.getLeft()),t.getTop()<this.#i&&(this.#i=t.getTop()),t.getBack()<this.#h&&(this.#h=t.getBack()),t.getRight()>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.#t||t.getBottom()<this.#i||t.getLeft()>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.#t||t.getBottom()<this.#i||t.getFront()<this.#h||t.getLeft()>this.#s||t.getTop()>this.#o||t.getBack()>this.#e)}intersectsAABB3DIgnoringZ(t){return!(t.getRight()<this.#t||t.getBottom()<this.#i||t.getLeft()>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;o<i;o+=2){const i=t[o],h=t[o+1];i<s&&(s=i),i>r&&(r=i),h<e&&(e=h),h>n&&(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<i;o+=2){const i=o+1,h=n[o]*t,l=n[i]*s;n[o]=h*r-l*e,n[i]=l*r+h*e}this._isBboxChanged=!0}offset(t,s){const e=this._ptsArr;for(let r=0,n=e.length;r<n;r+=2)e[r]+=t,e[r+1]+=s}containsPoint(t,s){const e=this._ptsArr;if(t===e[0]&&s===e[1])return!0;this._updateBbox();const r=this._bbox,n=r.getLeft()-110,o=r.getTop()-101,i=r.getRight()+131,h=r.getBottom()+120;let l=0,a=0,c=0,g=0,_=0,p=0,f=0,u=0;n<t?(l=n,c=t):(l=t,c=n),o<s?(a=o,g=s):(a=s,g=o),i<t?(_=i,f=t):(_=t,f=i),h<s?(p=h,u=s):(p=s,u=h);let C=0,A=0;for(let r=0,d=e.length;r<d;r+=2){const b=(r+2)%d,P=e[r],m=e[r+1],x=e[b],B=e[b+1];C3.segmentsIntersectPreCalc(n,o,t,s,l,c,a,g,P,m,x,B)&&++C,C3.segmentsIntersectPreCalc(i,h,t,s,_,f,p,u,P,m,x,B)&&++A}return C%2==1||A%2==1}intersectsPoly(t,s,e){const r=t._ptsArr,n=this._ptsArr;if(this.containsPoint(r[0]+s,r[1]+e))return!0;if(t.containsPoint(n[0]-s,n[1]-e))return!0;for(let t=0,o=n.length;t<o;t+=2){const i=(t+2)%o,h=n[t],l=n[t+1],a=n[i],c=n[i+1];let g=0,_=0,p=0,f=0;h<a?(g=h,p=a):(g=a,p=h),l<c?(_=l,f=c):(_=c,f=l);for(let t=0,n=r.length;t<n;t+=2){const o=(t+2)%n,i=r[t]+s,u=r[t+1]+e,C=r[o]+s,A=r[o+1]+e;if(C3.segmentsIntersectPreCalc(h,l,a,c,g,p,_,f,i,u,C,A))return!0}}return!1}intersectsSegment(t,s,e,r,n,o){if(this.containsPoint(e-t,r-s))return!0;if(this.containsPoint(n-t,o-s))return!0;let i=0,h=0,l=0,a=0;e<n?(i=e,l=n):(i=n,l=e),r<o?(h=r,a=o):(h=o,a=r);const c=this._ptsArr;for(let g=0,_=c.length;g<_;g+=2){const p=(g+2)%_,f=c[g]+t,u=c[g+1]+s,C=c[p]+t,A=c[p+1]+s;if(C3.segmentsIntersectPreCalc(e,r,n,o,i,l,h,a,f,u,C,A))return!0}return!1}mirror(t){const s=this._ptsArr;for(let e=0,r=s.length;e<r;e+=2)s[e]=2*t-s[e];this._isBboxChanged=!0}flip(t){const s=this._ptsArr;for(let e=0,r=s.length;e<r;e+=2){const r=e+1;s[r]=2*t-s[r]}this._isBboxChanged=!0}diag(){const t=this._ptsArr;for(let s=0,e=t.length;s<e;s+=2){const e=s+1,r=t[s];t[s]=t[e],t[e]=r}this._isBboxChanged=!0}GetMidX(){const t=this._ptsArr;let s=0;for(let e=0,r=t.length;e<r;e+=2)s+=t[e];return s/this.pointCount()}GetMidY(){const t=this._ptsArr;let s=0;for(let e=0,r=t.length;e<r;e+=2)s+=t[e+1];return s/this.pointCount()}GetPointsArray(){return this._ptsArr}GetPointCount(){return this.pointCount()}IsEnabled(){return this._enabled}};
}

// lib/misc/pairMap.js
{
const C3=self.C3;C3.PairMap=class extends C3.DefendedBase{constructor(e){if(super(),this._firstMap=new Map,e)for(const[t,s,r]of e)this.Set(t,s,r)}Release(){this.Clear(),this._firstMap=null}IsEmpty(){return 0===this._firstMap.size}Clear(){const e=this._firstMap;for(const t of e.values())t.clear();e.clear()}Set(e,t,s){const r=this._firstMap;let i=r.get(e);i||(i=new Map,r.set(e,i)),i.set(t,s)}Get(e,t){const s=this._firstMap.get(e);return s?s.get(t):s}Has(e,t){const s=this._firstMap.get(e);return!!s&&s.has(t)}Delete(e,t){const s=this._firstMap,r=s.get(e);if(!r)return!1;const i=r.delete(t);return i&&0===r.size&&s.delete(e),i}DeleteEither(e){const t=this._firstMap,s=t.get(e);s&&(s.clear(),t.delete(e));for(const[s,r]of t.entries())r.delete(e)&&0===r.size&&t.delete(s)}GetSize(){let e=0;for(const t of this._firstMap.values())e+=t.size;return e}*values(){for(const e of this._firstMap.values())yield*e.values()}*keyPairs(){for(const[e,t]of this._firstMap.entries())for(const s of t.keys())yield[e,s]}*entries(){for(const[e,t]of this._firstMap.entries())for(const[s,r]of t.entries())yield[e,s,r]}};
}

// lib/misc/arraySet.js
{
const C3=self.C3;C3.ArraySet=class extends C3.DefendedBase{constructor(){super(),this._set=new Set,this._arr=[],this._needToRebuildArray=!1}Release(){this.Clear()}Clear(){this._set.clear(),C3.clearArray(this._arr),this._needToRebuildArray=!1}Add(e){this._set.has(e)||(this._set.add(e),this._needToRebuildArray||this._arr.push(e))}Has(e){return this._set.has(e)}Delete(e){this._set.delete(e)&&(this._needToRebuildArray=!0)}GetSize(){return this._set.size}IsEmpty(){return 0===this._set.size}GetArray(){return this._needToRebuildArray&&(this._RebuildArray(),this._needToRebuildArray=!1),this._arr}_RebuildArray(){const e=this._arr;C3.clearArray(e);for(const r of this._set)e.push(r)}};
}

// ../lib/misc/ease.js
{
const C3=self.C3,EASE_MAP=new Map,PREDEFINED_EASE_MAP=new Map,CUSTOM_EASE_EDITOR_MAP=new Map,CUSTOM_EASE_DATA_EDITOR_MAP=new Map,CUSTOM_EASE_RUNTIME_MAP=new Map,CUSTOM_EASE_DATA_RUNTIME_MAP=new Map,PRIVATE_EASE_MAP=new Map,BUILT_IN_TRANSITION_MAP=new Map,ALIAS_MAP=new Map;ALIAS_MAP.set("linear","noease"),ALIAS_MAP.set("default","noease");const EASE_TRANSLATION_KEYS=["default","noease","easeinquad","easeoutquad","easeinoutquad","easeincubic","easeoutcubic","easeinoutcubic","easeinquart","easeoutquart","easeinoutquart","easeinquint","easeoutquint","easeinoutquint","easeinsine","easeoutsine","easeinoutsine","easeinexpo","easeoutexpo","easeinoutexpo","easeincirc","easeoutcirc","easeinoutcirc","easeinelastic","easeoutelastic","easeinoutelastic","easeinback","easeoutback","easeinoutback","easeinbounce","easeoutbounce","easeinoutbounce"],SHORT_EASE_TRANSLATION_KEYS=["default","noease","quad","cubic","quart","quint","sine","expo","circ","elastic","back","bounce"],EASE_API2INTERNAL_NAMES=new Map([["linear","noease"],["in-sine","easeinsine"],["out-sine","easeoutsine"],["in-out-sine","easeinoutsine"],["in-elastic","easeinelastic"],["out-elastic","easeoutelastic"],["in-out-elastic","easeinoutelastic"],["in-back","easeinback"],["out-back","easeoutback"],["in-out-back","easeinoutback"],["in-bounce","easeinbounce"],["out-bounce","easeoutbounce"],["in-out-bounce","easeinoutbounce"],["in-cubic","easeincubic"],["out-cubic","easeoutcubic"],["in-out-cubic","easeinoutcubic"],["in-quadratic","easeinquad"],["out-quadratic","easeoutquad"],["in-out-quadratic","easeinoutquad"],["in-quartic","easeinquart"],["out-quartic","easeoutquart"],["in-out-quartic","easeinoutquart"],["in-quintic","easeinquint"],["out-quintic","easeoutquint"],["in-out-quintic","easeinoutquint"],["in-circular","easeincirc"],["out-circular","easeoutcirc"],["in-out-circular","easeinoutcirc"],["in-exponential","easeinexpo"],["out-exponential","easeoutexpo"],["in-out-exponential","easeinoutexpo"]]);self.Ease=class e{constructor(){}static InheritEase(){return"default"}static DefaultEase(){return"noease"}static ToInternal(e){return EASE_API2INTERNAL_NAMES.get(e)}static GetEditorEaseNames(a,...s){let t,i;this._CreateEaseMap(),a?(CUSTOM_EASE_EDITOR_MAP.has(a)||CUSTOM_EASE_EDITOR_MAP.set(a,new Map),t=CUSTOM_EASE_EDITOR_MAP.get(a),i=[...t.keys()].filter(s=>!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;e<SAMPLE_COUNT;++e){const a=calc_bezier(e*SAMPLE_STEP,y,n,E);x.push(a)}return x}};const SAMPLE_COUNT=11,SAMPLE_STEP=1/(SAMPLE_COUNT-1),NEWTON_RAPHSON_ITERATIONS=4,NEWTON_RAPHSON_MIN_SLOPE=.01,SUBDIVISION_PRECISION=1e-7,SUBDIVISION_MAX_ITERATIONS=10,a=(e,a,s,t)=>t-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,t<e)return s;return 0}HasItems(){return!!this._items.length}AddItem(t,e){RequireStringOrNumber(e),this._totalWeight+=t,this._items.push([t,e])}RemoveItem(t,e){RequireStringOrNumber(e);const i=0===t;for(let s=0;s<this._items.length;s++){const r=this._items[s],h=i||r[0]===t,n=r[1]===e;if(h&&n){this._items.splice(s,1),this._totalWeight-=r[0];break}}}asJSON(){return JSON.stringify(this._items)}static fromJSON(t,e){const i=new C3.ProbabilityTable(e),s=JSON.parse(t);for(const t of s){const e=t[0],s=t[1];i.AddItem(e,s)}return i}};
}

// lib/misc/screenReaderText.js
{
const C3=self.C3;let nextId=0;C3.ScreenReaderText=class{constructor(t,e){this._runtime=t,this._text=e,this._id=nextId++,this._runtime.PostComponentMessageToDOM("runtime","screen-reader-text",{"type":"create","id":this._id,"text":this._text})}Release(){this._runtime.PostComponentMessageToDOM("runtime","screen-reader-text",{"type":"release","id":this._id}),this._runtime=null,this._text="",this._id=-1}SetText(t){this._text!==t&&(this._text=t,this._runtime.PostComponentMessageToDOM("runtime","screen-reader-text",{"type":"update","id":this._id,"text":this._text}))}};
}

// ../lib/events/event.js
{
const C3=self.C3;C3.Event=class{constructor(t,e){this.type=t,this.cancelable=!!e,this.defaultPrevented=!1,this.propagationStopped=!1,this.isAsync=!1}preventDefault(){if(!this.cancelable)throw new Error(`event '${this.type}' is not cancelable`);this.defaultPrevented=!0}stopPropagation(){if(!this.cancelable)throw new Error(`event '${this.type}' cannot be stopped`);if(this.isAsync)throw new Error(`cannot stop async event '${this.type}' propagation`);this.propagationStopped=!0}};
}

// ../lib/events/handler.js
{
const C3=self.C3,assert=self.assert;C3.Event.Handler=class extends C3.DefendedBase{#e=null;#s=null;#t=0;#i=null;constructor(){super()}Release(){this.#t>0||(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<e["timeRemaining"]():i-o+n<12));if(-1===callbackId&&workQueue.length){let e=i-o;SetNewCallback(Math.max(16-e,4))}}function DoNextAsyncifiedJob(e){let o;try{o=e.func()}catch(o){return void e.reject(o)}e.resolve(o)}let asyncifyDisabled=C3.QueryString.Has("disable-asyncify");asyncifyDisabled&&console.warn("[Asyncify] Asyncify has been disabled due to disable-asyncify in the query string. Some work will now be done synchronously."),C3.Asyncify=function(e){let o=null;return C3.isDebug&&(o=C3.GetCallStack()),new Promise((i,t)=>{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||e<nextDeadline)&&(nextDeadline=e)}else activeIdleTimeouts.delete(t);if(-1!==nextDeadline){let t=Math.max(nextDeadline-e+100,1e3);timerId=self.setTimeout(CheckActiveIdleTimeouts,t)}}C3.IdleTimeout=class{constructor(e,t){this._callback=e,this._timeout=1e3*t,this._deadline=0,this._isActive=!1}Reset(){let e=C3.FastGetDateNow();this._deadline=e+this._timeout,this._isActive||(activeIdleTimeouts.add(this),this._isActive=!0),-1===timerId?(nextDeadline=this._deadline,timerId=self.setTimeout(CheckActiveIdleTimeouts,this._timeout+100)):this._deadline<nextDeadline&&nextDeadline>e+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 t<e?-1:e<t?1:0},js_cols.RedBlackSet.prototype.clone=function(){var t=new js_cols.RedBlackSet(this.compare);return t.insertAll(this),t},js_cols.RedBlackSet.prototype.clear=function(){this.size=0,this.sentinel=new js_cols.RBnode(this),this.sentinel.color=false,this.root=this.sentinel,this.root.parent=this.sentinel},js_cols.RedBlackSet.prototype.leftRotate=function(t){var e=t.right;t.right=e.left,e.left!=this.sentinel&&(e.left.parent=t),e.parent=t.parent,t.parent==this.sentinel?this.root=e:t==t.parent.left?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e},js_cols.RedBlackSet.prototype.rightRotate=function(t){var e=t.left;t.left=e.right,e.right!=this.sentinel&&(e.right.parent=t),e.parent=t.parent,t.parent==this.sentinel?this.root=e:t==t.parent.right?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e},js_cols.RedBlackSet.prototype.insert=function(t){if(this.contains(t)){this.get_(t).key=t}else{var e=new js_cols.RBnode(this);e.key=t;for(var s=this.sentinel,r=this.root;r!=this.sentinel;)s=r,r=this.compare(e.key,r.key)<0?r.left:r.right;e.parent=s,s==this.sentinel?this.root=e:this.compare(e.key,s.key)<0?s.left=e:s.right=e,e.left=this.sentinel,e.right=this.sentinel,e.color=RED,this.insertFixup(e),this.size++}},js_cols.RedBlackSet.prototype.insertFixup=function(t){for(;t!=this.sentinel&&t!=this.root&&t.parent.color==RED;){var e;if(t.parent==t.parent.parent.left)(e=t.parent.parent.right).color==RED?(t.parent.color=false,e.color=false,t.parent.parent.color=RED,t=t.parent.parent):(t==t.parent.right&&(t=t.parent,this.leftRotate(t)),t.parent.color=false,t.parent.parent.color=RED,t.parent.parent!=this.sentinel&&this.rightRotate(t.parent.parent));else(e=t.parent.parent.left).color==RED?(t.parent.color=false,e.color=false,t.parent.parent.color=RED,t=t.parent.parent):(t==t.parent.left&&(t=t.parent,this.rightRotate(t)),t.parent.color=false,t.parent.parent.color=RED,t.parent.parent!=this.sentinel&&this.leftRotate(t.parent.parent))}this.root.color=false},js_cols.RedBlackSet.prototype.delete_=function(t){var e,s;(s=(e=t.left==this.sentinel||t.right==this.sentinel?t:this.successor_(t)).left!=this.sentinel?e.left:e.right).parent=e.parent,e.parent==this.sentinel?this.root=s:e==e.parent.left?e.parent.left=s:e.parent.right=s,e!=t&&(t.key=e.key),false==e.color&&this.deleteFixup(s),this.size--},js_cols.RedBlackSet.prototype.deleteFixup=function(t){for(;t!=this.root&&false==t.color;){var e;if(t==t.parent.left)(e=t.parent.right).color==RED&&(e.color=false,t.parent.color=RED,this.leftRotate(t.parent),e=t.parent.right),false==e.left.color&&false==e.right.color?(e.color=RED,t=t.parent):(false==e.right.color&&(e.left.color=false,e.color=RED,this.rightRotate(e),e=t.parent.right),e.color=t.parent.color,t.parent.color=false,e.right.color=false,this.leftRotate(t.parent),t=this.root);else(e=t.parent.left).color==RED&&(e.color=false,t.parent.color=RED,this.rightRotate(t.parent),e=t.parent.left),false==e.right.color&&false==e.left.color?(e.color=RED,t=t.parent):(false==e.left.color&&(e.right.color=false,e.color=RED,this.leftRotate(e),e=t.parent.left),e.color=t.parent.color,t.parent.color=false,e.left.color=false,this.rightRotate(t.parent),t=this.root)}t.color=false},js_cols.RedBlackSet.prototype.remove=function(t){var e=this.get_(t);if(e!=this.sentinel){var s=e.key;return this.delete_(e),s}return null},js_cols.RedBlackSet.prototype.removeSwapped=function(t,e){this.remove(e)},js_cols.RedBlackSet.prototype.min=function(t){for(;t.left!=this.sentinel;)t=t.left;return t},js_cols.RedBlackSet.prototype.max=function(t){for(;t.right!=this.sentinel;)t=t.right;return t},js_cols.RedBlackSet.prototype.successor_=function(t){if(t.right!=this.sentinel)return this.min(t.right);for(var e=t.parent;e!=this.sentinel&&t==e.right;)t=e,e=e.parent;return e},js_cols.RedBlackSet.prototype.predeccessor_=function(t){if(t.left!=this.sentinel)return this.max(t.left);for(var e=t.parent;e!=this.sentinel&&t==e.left;)t=e,e=e.parent;return e},js_cols.RedBlackSet.prototype.successor=function(t){if(this.size>0){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;e<t.length;e++)this.insert(t[e]);else if("function"==js_cols.typeOf(t.forEach))t.forEach(this.insert,this);else if("function"==js_cols.typeOf(t.getValues)){var s=t.getValues();for(e=0;e<s.length;e++)this.insert(s[e])}else if("object"==js_cols.typeOf(t))for(var r in t)this.insert(t[r])},js_cols.RedBlackSet.prototype.removeAll=function(t){if("array"==js_cols.typeOf(t))for(var e=0;e<t.length;e++)this.remove(t[e]);else if("function"==js_cols.typeOf(t.forEach))t.forEach(this.removeSwapped,this);else if("function"==js_cols.typeOf(t.getValues)){var s=t.getValues();for(e=0;e<s.length;e++)this.remove(s[e])}else if("object"==js_cols.typeOf(t))for(var r in t)this.remove(t[r])},js_cols.RedBlackSet.prototype.containsAll=function(t){if("array"==js_cols.typeOf(t)){for(var e=0;e<t.length;e++)if(!this.contains(t[e]))return!1;return!0}if("function"==js_cols.typeOf(t.forEach))return t.every(this.contains,this);if("function"==js_cols.typeOf(t.getValues)){var s=t.getValues();for(e=0;e<s.length;e++)if(!this.contains(s[e]))return!1;return!0}if("object"==js_cols.typeOf(t)){for(var r in t)if(!this.contains(t[r]))return!1;return!0}},js_cols.RedBlackSet.prototype.range=function(t,e){var s=[];return this.traverseFromTo(function(t){s.push(t)},t,e),s},js_cols.RedBlackSet.prototype.traverse=function(t,e){if(!this.isEmpty())for(var s=this.min(this.root);s!=this.sentinel;){if(t.call(e,s.key,this))return;s=this.successor_(s)}},js_cols.RedBlackSet.prototype.traverseFrom=function(t,e,s){if(!this.isEmpty())for(var r=this.get_(e);r!=this.sentinel;){if(t.call(s,r.key,this))return;r=this.successor_(r)}},js_cols.RedBlackSet.prototype.traverseTo=function(t,e,s){if(!this.isEmpty())for(var r=this.min(this.root),i=this.get_(e);r!=i;){if(t.call(s,r.key,this))return;r=this.successor_(r)}},js_cols.RedBlackSet.prototype.traverseFromTo=function(t,e,s,r){if(!this.isEmpty())for(var i=this.get_(e),o=this.get_(s);i!=o;){if(t.call(r,i.key,this))return;i=this.successor_(i)}},js_cols.RedBlackSet.prototype.traverseBackwards=function(t,e){if(!this.isEmpty())for(var s=this.max(this.root);s!=this.sentinel;){if(t.call(e,s.key,this))return;s=this.predeccessor_(s)}},js_cols.RedBlackSet.prototype.forEach=function(t,e){if(!this.isEmpty())for(var s=this.min(this.root);s!=this.sentinel;s=this.successor_(s))t.call(e,s.key,s.key,this)},js_cols.RedBlackSet.prototype.some=function(t,e){if(this.isEmpty())return!1;for(var s=this.min(this.root);s!=this.sentinel;s=this.successor_(s))if(t.call(e,s.key,s.key,this))return!0;return!1},js_cols.RedBlackSet.prototype.every=function(t,e){if(this.isEmpty())return!1;for(var s=this.min(this.root);s!=this.sentinel;s=this.successor_(s))if(!t.call(e,s.key,s.key,this))return!1;return!0},js_cols.RedBlackSet.prototype.map=function(t,e){var s=[];if(this.isEmpty())return s;for(var r=this.min(this.root);r!=this.sentinel;r=this.successor_(r))s.push(t.call(e,r.key,r.key,this));return s},js_cols.RedBlackSet.prototype.filter=function(t,e){var s=[];if(this.isEmpty())return s;for(var r=this.min(this.root);r!=this.sentinel;r=this.successor_(r))t.call(e,r.key,r.key,this)&&s.push(r.key);return s},js_cols.RedBlackSet.prototype.getCount=function(){return this.size},js_cols.RedBlackSet.prototype.isEmpty=function(){return 0==this.size},js_cols.RedBlackSet.prototype.isSubsetOf=function(t){var e=js_cols.getCount(t);if(this.getCount()>e)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<r;++t)if(this._queue[t].func===e)return t;return-1}RemoveAndResolve(e,t){const r=this._FindInQueue(e);if(-1===r)throw new Error("cannot find promise to resolve");this._queue[r].resolve(t),this._queue.splice(r,1)}RemoveAndReject(e,t){const r=this._FindInQueue(e);if(-1===r)throw new Error("cannot find promise to reject");this._queue[r].reject(t),this._queue.splice(r,1)}async _MaybeStartNext(){if(!this._queue.length)return;if(this._activeCount>=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(t<s&&r<a){const e=t/r;s/a>e?(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([["&","&amp;"],["<","&lt;"],[">","&gt;"],['"',"&quot;"],["'","&#39;"]]);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,"&","&amp;");return e=C3.ReplaceAll(e,"<","&lt;"),e=C3.ReplaceAll(e,">","&gt;"),C3.ReplaceAll(e,'"',"&quot;")};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<e;){if(n=t.indexOf("\n",n),-1===n)return r;r++,n++}return r},C3.FindAll=function(t,e,n=!1){if(!e)return[];n||(t=t.toLowerCase(),e=e.toLowerCase());const r=e.length;let o=0,i=0,l=[];for(;(i=t.indexOf(e,o))>-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<o;++r){const o=`{${r}}`;if(!t.includes(o))throw new Error(`missing placeholder '${o}' in string substitution`);n=n.replace(o,e[r].toString())}return n},C3.StringSubstituteAllowMissing=function(t,...e){let n=t,r=-1,o=-1;for(let i=0,l=e.length;i<l;++i){const l=`{${i}}`;t.includes(l)?(o=i,n=n.replace(l,e[i].toString())):-1===r&&(r=i)}if(r>=0&&o>=0&&r<o)throw new Error(`missing placeholder '${r}' in string substitution`);return n},C3.StringSubstituteMap=function(t,e){let n=t;for(let[t,r]of Object.entries(e))n=n.replaceAll(t,r.toString());return n},C3.SortAZ=function(t,e){return t>e?1:t<e?-1:0},C3.SortAZCaseInsensitive=function(t,e){let n=t.toLowerCase(),r=e.toLowerCase();return n>r?1:n<r?-1:0};const intlSegmenter=new self["Intl"]["Segmenter"];C3.SplitGraphemes=function(t){if(1===t.length)return[t];const e=[];for(const n of intlSegmenter["segment"](t))e.push(n["segment"]);return e},C3.IterateGraphemes=function*(t){for(const e of intlSegmenter["segment"](t))yield e["segment"]},C3.CountGraphemes=function(t){let e=0;for(const n of intlSegmenter["segment"](t))++e;return e};const KILOBYTE=1024,MEGABYTE=1048576,GIGABYTE=1073741824,TERABYTE=1099511627776;C3.FormatDataSize=function(t,e){let n="common."+(e?"dataRates":"dataSizes")+".";const r=self.langSub;if(t<1024)return r(n+"bytes",t);if(t<1048576){let e=t/1024;return e=e<10?Math.round(10*e)/10:Math.round(e),r(n+"kilobytes",e)}if(t<GIGABYTE){let e=t/1048576;return e=e<10?Math.round(10*e)/10:Math.round(e),r(n+"megabytes",e)}if(t<TERABYTE){let e=t/GIGABYTE;return e=e<10?Math.round(10*e)/10:Math.round(e),r(n+"gigabytes",e)}{let e=t/TERABYTE;return e=e<10?Math.round(10*e)/10:Math.round(e),r(n+"terabytes",e)}};const DEFAULT_FORMATTIME_OPTS={approximate:!1,days:!0,hours:!0,minutes:!0,seconds:!0};C3.FormatTime=function(t,e){e=Object.assign({},DEFAULT_FORMATTIME_OPTS,e),C3.Lang.PushContext("common.time");const n=[],r=self.lang,o=self.langPluralSub;if(e.days){const e=Math.floor(t/86400);e>0&&(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;t<o;++t)n+="0";return n+r},C3.StringToTitleCase=function(t){return t.toLowerCase().replace(/\b\w/g,t=>t.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;r<o;++r)t.charAt(r)!==e.charAt(r)&&++n;return n},C3.StringLevenshteinDistance=function(t,e){if(0===t.length)return e.length;if(0===e.length)return t.length;let n,r,o,i,l,s;for(t.length>e.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?"</span>":`<span class="bbclass${classIndex++}">`: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`<abbr title="${C3.ReplaceAll(n,'"',"&quot;")}">`}}{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`<a href="${linkActions[t]}">`;if("function"==typeof s)return`<a class="bblink${t}">`;throw new TypeError("invalid bbcode link action")}}if(Array.isArray(n)){let t=n[0],i=n[1];return s?"</"+t+">":`<${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,"<br>")),this._htmlstr=t}return this._htmlstr}attachLinkHandlers(t){if(this._linkActions.length)for(let s=0,i=this._linkActions.length;s<i;++s){const i=this._linkActions[s];if("function"!=typeof i)continue;const n=t.querySelector(".bblink"+s);if(!n)throw new Error("unable to attach BBString link handler");n.onclick=i}}equals(t){return t instanceof C3.HtmlString?this.toHTML()===t.toHTML():t instanceof C3.BBString?this._bbstr===t._bbstr:this._bbstr===t}toFragmentList(){if(this._hasParsedFragments)return this._fragments;const t=[],s=this._bbstr,i=[];CUSTOM_BBREGEX.lastIndex=0;let n=0,e=null;for(;null!==(e=CUSTOM_BBREGEX.exec(s));){const r=e.index;if(r>0&&"\\"===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})}}n<s.length&&t.push({text:s.substring(n),styles:i.slice(0)});for(const s of t)s.text&&(s.text=this._ProcessBBCodeEscapeSequences(s.text));return this._fragments=t.map(t=>t.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;n<e;++n){const e=t[n];this.fragments.push(e._Clone())}this.isMeasured=!1}}C3.WordWrap=class{constructor(){this._lines=[],this._iconSet=null,this._lastFitLineState=new CurrentLineState,this._tryLineState=new CurrentLineState,this._hitNewline=!1}GetLines(){return this._lines}GetLineCount(){return this._lines.length}SetIconSet(t){this._iconSet=t}WordWrap(t,e,n,i,s){if("string"==typeof t&&(t=[C3.New(C3.TextFragment,{chArr:C3.SplitGraphemes(t)})]),C3.clearArray(this._lines),!t.length||1===t.length&&t[0].IsText()&&t[0].IsEmpty()||n<2)return;if(1===t.length){const i=t[0];if(i.IsText()&&i.GetLength()<=100&&!i.HasNewLine()){let{width:t,height:r,fontBoundingBoxAscent:h,fontBoundingBoxDescent:o,topToAlphabeticDistance:a}=e(i);if(t+=s,i.SetWidth(t),i.SetHeight(r),i.SetFontBoundingBoxAscent(h||0),i.SetFontBoundingBoxDescent(o||0),i.SetTopToAlphabeticDistance(a||0),t<=n)return void this._AddLine(CurrentLineState.FromSingleFragment(i,t,r,h,o,a))}}let r,h=4;"word"===i?r=this._TokeniseByWord(t):"cjk"===i?(r=this._TokeniseByCJK(t),h=8):(r=this._TokeniseByChar(t),h=8),this._WrapText(r,e,n,h,s)}_TokeniseByWord(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=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(;r<t.length;)r=this._WrapText_Chunk(t,r,e,n,i);if(this._tryLineState.fragments.length>0){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<e;++s){const e=t[s];if(this._IsWordNewLine(e)){this._hitNewline=!0;break}if(i.AddWord(e),!this._IsWordWhitespace(e)&&(++r,r===n))break}return s}_WrapText_RetryChunk(t,e,n,i){const s=this._lastFitLineState,r=this._tryLineState;r.Copy(s);let h=e;for(let e=t.length;h<e;++h){const o=t[h];if(this._IsWordNewLine(o))return this._AddLine(s),h+1;if(r.AddWord(o),!this._IsWordWhitespace(o)||0===s.fragments.length){const o=this._MeasureLine(r.fragments,n);if(r.SetMetrics(o),o.width>=i){let n;return s.fragments.length>0?n=s:(n=r,++h,h<e&&this._IsWordWhitespace(t[h])&&++h),this._AddLine(n),h}s.Copy(r)}}return h}_TrimLinesTrailingWhitespace(t,e){for(const n of this._lines){const i=n._GetFragmentsArray();if(!i.length)continue;let s=i.at(-1);if(s.IsText()){const r=s.GetCharacterArray(),h=r.slice(0);if(WordBreakTrimEnd(h),0===h.length)n.OffsetWidth(-s.GetWidth()),i.pop();else if(h.length<r.length){s.SetCharacterArray(h);const e=t(s).width,i=s.GetWidth()-e;s.SetWidth(e),n.OffsetWidth(-i)}0!==e&&i.length>0&&(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<s;++t){const s=o[t],e=C3.New(C3.TextIcon,this,{index:t,tag:s.tag,source:s.source,width:s.width,height:s.height});this._iconsArray.push(e),s.tag&&this._iconsByTag.set(s.tag.toLowerCase(),e)}}Release(){for(const t of this._iconsArray)t.Release();C3.clearArray(this._iconsArray),this._iconsByTag.clear(),this._textIconManager=null,this._source=null}HasLoaded(){return this._hasStartedLoad}IsLoading(){return this._isLoading}LoadContent(){return this._loadPromise||(this._loadPromise=this._DoLoadContent()),this._loadPromise}async _DoLoadContent(){if(this._hasStartedLoad)return;this._hasStartedLoad=!0,this._isLoading=!0;const t=await this._textIconManager._GetIconSetContent(this._source);if(!this._textIconManager)return;const s=t.icons;for(let t=0,o=Math.min(s.length,this._iconsArray.length);t<o;++t){const o=s[t].drawable;this._iconsArray[t]._SetDrawable(o)}this._isLoading=!1}GetTextIconByIndex(t){return(t=Math.floor(t))<0||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<t;++e)SAMPLING_MODE_TO_NUMBER.set(SAMPLING_MODES[e],e);C3.Gfx.RendererBase=class{#e=new Map;constructor(e){e=Object.assign({},DEFAULT_RENDERERBASE_OPTS,e),this._width=0,this._height=0,this._fovY=C3.toRadians(45),this._tan_fovY_2=Math.tan(this._fovY/2),this._matP=mat4.create(),this._matMV=mat4.create(),this._zAxisScale=!1,this._nearZ=e.nearZ,this._farZ=e.farZ,this._allShaderPrograms=[],this._shaderProgramsByName=new Map,this._spTextureFill=null,this._spPoints=null,this._spTilemapFill=null,this._spTileRandomization=null,this._spColorFill=null,this._spLinearGradientFill=null,this._spPenumbraFill=null,this._spHardEllipseFill=null,this._spHardEllipseOutline=null,this._spSmoothEllipseFill=null,this._spSmoothEllipseOutline=null,this._spSmoothLineFill=null,this._stateGroups=new Map,this._currentStateGroup=null,this._blendModeTable=[],this._namedBlendModeMap=new Map,this._baseZ=0,this._currentZ=0,this._lineWidth=1,this._lineWidthStack=[this._lineWidth],this._lineCap=1,this._lineCapStack=[this._lineCap],this._lineOffset=.5,this._lineOffsetStack=[this._lineOffset],this._frameNumber=0,this._enableMipmaps=!0,this._hasMajorPerformanceCaveat=!1}_ClearState(){this._baseZ=0,this._currentZ=0,this._spTextureFill=null,this._spPoints=null,this._spTilemapFill=null,this._spTileRandomization=null,this._spColorFill=null,this._spLinearGradientFill=null,this._spPenumbraFill=null,this._spHardEllipseFill=null,this._spHardEllipseOutline=null,this._spSmoothEllipseFill=null,this._spSmoothEllipseOutline=null,this._spSmoothLineFill=null,this._ClearAllShaderPrograms(),this.#e.clear()}InitState(){this._ClearState(),this._currentStateGroup=null}OnDeviceOrContextLost(){for(const e of this._allShaderPrograms)e.Release();this._ClearState()}GetWidth(){return this._width}GetHeight(){return this._height}GetDefaultCameraZ(e){return this.IsZAxisScaleNormalized()?100:e/(2*this._GetTanFovYDiv2())}GetZAxisScaleFactor(e){if(this.IsZAxisScaleNormalized()){return e/(2*this._GetTanFovYDiv2())/this.GetDefaultCameraZ(e)}return 1}SetNearZ(e){this._nearZ=e}GetNearZ(){return this._nearZ}SetFarZ(e){this._farZ=e}GetFarZ(){return this._farZ}SetFovY(e){this._fovY=e,this._tan_fovY_2=Math.tan(this._fovY/2)}GetFovY(){return this._fovY}_GetTanFovYDiv2(){return this._tan_fovY_2}SetZAxisScaleNormalized(){this._zAxisScale=!1}SetZAxisScaleRegular(){this._zAxisScale=!0}IsZAxisScaleNormalized(){return!this._zAxisScale}IsZAxisScaleRegular(){return this._zAxisScale}CalculatePerspectiveMatrix(e,t,i=.5,a=.5){const s=this.GetNearZ(),r=this.GetFarZ(),l=this.GetFovY();if(.5===i&&.5===a)this.IsWebGPU()?mat4.perspectiveZO(e,l,t,s,r):mat4.perspective(e,l,t,s,r);else{const l=2*(i=1-i)-2,n=2*i,h=2*a-2,o=2*a,p=this._GetTanFovYDiv2()*s,_=p*t;mat4.frustum(e,l*_,n*_,h*p,o*p,s,r),this.IsWebGPU()&&mat4.mul(e,matWebGLtoWebGPU,e)}}CalculateOrthographicMatrix(e,t,i,a=1){const s=self.devicePixelRatio;let r=1;this.IsZAxisScaleNormalized()&&(r=2*this.GetDefaultCameraZ(i)*s*this._GetTanFovYDiv2()/i);const l=t*r/(2*s*a),n=i*r/(2*s*a),h=-l,o=l,p=-n,_=n;this.IsWebGPU()?mat4.orthoZO(e,h,o,p,_,this.GetNearZ(),this.GetFarZ()):mat4.ortho(e,h,o,p,_,this.GetNearZ(),this.GetFarZ())}CalculateLookAtModelView(e,t,i,a,s){let r=1;this.IsZAxisScaleNormalized()&&(r=200*this._GetTanFovYDiv2()/s);const l=tmpVec3c;vec3.set(l,r,-r,1);const n=tmpVec3a,h=tmpVec3b;vec3.multiply(n,t,l),vec3.multiply(h,i,l),mat4.lookAt(e,n,h,a||defaultUpVector),mat4.scale(e,e,l)}CalculateLookAtModelView2(e,t,i,a,s,r,l){return vec3.set(tmpVec3a,e,t,i),vec3.set(tmpVec3b,a,s,r),this.CalculateLookAtModelView(tempMat4,tmpVec3a,tmpVec3b,defaultUpVector,l),tempMat4}_AddShaderProgram(e){this._allShaderPrograms.push(e),this._shaderProgramsByName.set(e.GetName(),e)}_RemoveShaderProgram(e){const t=this._allShaderPrograms.indexOf(e);-1!==t&&this._allShaderPrograms.splice(t,1),this._shaderProgramsByName.delete(e.GetName())}_ClearAllShaderPrograms(){C3.clearArray(this._allShaderPrograms),this._shaderProgramsByName.clear()}GetShaderProgramByName(e){return this._shaderProgramsByName.get(e)||null}GetTextureFillShaderProgram(){return this._spTextureFill}SetTextureFillMode(){this.SetProgram(this._spTextureFill)}GetPointsRenderingProgram(){return this._spPoints}SetPointsRenderingProgram(){this.SetProgram(this._spPoints)}SetTilemapFillMode(){this.SetProgram(this._spTilemapFill)}SetTileRandomizationMode(){this.SetProgram(this._spTileRandomization)}SetColorFillMode(){this.SetProgram(this._spColorFill)}SetLinearGradientFillMode(){this.SetProgram(this._spLinearGradientFill)}SetPenumbraFillMode(){this.SetProgram(this._spPenumbraFill)}SetHardEllipseFillMode(){this.SetProgram(this._spHardEllipseFill)}SetHardEllipseOutlineMode(){this.SetProgram(this._spHardEllipseOutline)}SetSmoothEllipseFillMode(){this.SetProgram(this._spSmoothEllipseFill)}SetSmoothEllipseOutlineMode(){this.SetProgram(this._spSmoothEllipseOutline)}SetSmoothLineFillMode(){this.SetProgram(this._spSmoothLineFill)}_SetCurrentStateGroup(e){this._currentStateGroup=e}GetCurrentStateGroup(){return this._currentStateGroup}AcquireStateGroup(e,t,i,a,s,r){const l=C3.Gfx.StateGroup.MakeKey(e,t,i,a,s,r);let n=this._stateGroups.get(l);return n||(n=C3.New(C3.Gfx.StateGroup,this,e,t,i,a,s,r),this._stateGroups.set(l,n)),n.AddRef(),n}ReleaseStateGroup(e){e.DecRef(),0===e._GetRefCount()&&(this._currentStateGroup===e&&(this._currentStateGroup=null),this._stateGroups.delete(e.GetKey()),e.Release())}_InitBlendModeData(e){C3.clearArray(this._blendModeTable),this._namedBlendModeMap.clear();let t=0;for(const i of e){const e=i[0],a=i[1];this._blendModeTable.push(a),this._namedBlendModeMap.set(e,t),t++}}_GetBlendParametersByIndex(e){return this._blendModeTable[e]}NamedBlendToNumber(e){const t=this._namedBlendModeMap.get(e);if(void 0===t)throw new Error("invalid blend name");return t}_GetSampler(e){const t=e.wrapX??"clamp-to-edge",i=e.wrapY??"clamp-to-edge",a=e.sampling;let s=e.anisotropy??1;"trilinear"!==a&&(s=1);const r=`${t},${i},${a},${s}`;let l=this.#e.get(r);return l||(l=this._CreateSampler(t,i,a,s),this.#e.set(r,l),l)}static SamplingModeToNumber(e){const t=SAMPLING_MODE_TO_NUMBER.get(e);if("number"!=typeof t)throw new Error("invalid sampling mode");return t}static SamplingNumberToMode(e){if(e<0||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;t<i;t+=2){const i=2*t,l=e[i+2],n=e[i+3],h=e[i+4],o=e[i+5];if(t===a)this.Quad2(s,r,l,n,h,o,h,o);else{const t=e[i+6],a=e[i+7];this.Quad2(s,r,l,n,h,o,t,a)}}}Finish(){this.EndBatch(!0),this._frameNumber++}GetFrameNumber(){return this._frameNumber}IncrementFrameNumber(){this._frameNumber++}SetMipmapsEnabled(e){this._enableMipmaps=!!e}AreMipmapsEnabled(){return this._enableMipmaps}SetHasMajorPerformanceCaveat(e){this._hasMajorPerformanceCaveat=!!e}HasMajorPerformanceCaveat(){return this._hasMajorPerformanceCaveat}IsWebGL(){return!1}IsWebGPU(){return!1}GetEstimatedBackBufferMemoryUsage(){}GetEstimatedRenderBufferMemoryUsage(){}GetEstimatedTextureMemoryUsage(){}GetEstimatedTotalMemoryUsage(){return this.GetEstimatedBackBufferMemoryUsage()+this.GetEstimatedRenderBufferMemoryUsage()+this.GetEstimatedTextureMemoryUsage()}CreateRendererText(){return C3.New(C3.Gfx.RendererText,this)}CreateMeshData(e,t,i){}};
}

// ../lib/gfx/shaderProgramBase.js
{
const C3=self.C3;C3.Gfx.ShaderProgramBase=class{constructor(e,t){this._name=t.name,this._renderer=e,this._extendBoxHorizontal=t.extendBoxHorizontal||0,this._extendBoxVertical=t.extendBoxVertical||0,this._crossSampling=!!t.crossSampling,this._mustPreDraw=!!t.mustPreDraw,this._preservesOpaqueness=!!t.preservesOpaqueness,this._supports3dDirectRendering=!!t.supports3dDirectRendering,this._animated=!!t.animated,this._blendsBackground=!!t.blendsBackground,this._usesDepth=!!t.usesDepth,this._usesAnySrcRectOrPixelSize=!1,this._needsPostDrawOrExtendBox=this._crossSampling||this._blendsBackground||0!==this._extendBoxHorizontal||0!==this._extendBoxVertical}Release(){this._renderer=null}GetRenderer(){return this._renderer}GetName(){return this._name}ExtendsBox(){return 0!==this._extendBoxHorizontal||0!==this._extendBoxVertical}GetBoxExtendHorizontal(){return this._extendBoxHorizontal}GetBoxExtendVertical(){return this._extendBoxVertical}UsesCrossSampling(){return this._crossSampling}MustPreDraw(){return this._mustPreDraw}PreservesOpaqueness(){return this._preservesOpaqueness}Supports3DDirectRendering(){return this._supports3dDirectRendering}IsAnimated(){return this._animated}BlendsBackground(){return this._blendsBackground}UsesDepth(){return this._usesDepth}UsesAnySrcRectOrPixelSize(){return this._usesAnySrcRectOrPixelSize}NeedsPostDrawOrExtendsBox(){return this._needsPostDrawOrExtendBox}UsesIsSrcTexRotated(){return!1}};
}

// ../lib/gfx/stateGroup.js
{
const C3=self.C3;C3.Gfx.StateGroup=class{constructor(e,r,t,s,o,a,i){this._renderer=e,this._refCount=0,this._shaderProgram=null,this._shaderProgramName="",this._blendMode=t,this._color=C3.New(C3.Color),this._color.set(s),this._zElevation=o,this._cullFaceMode=a,this._frontFaceWinding=i,"string"==typeof r?this._shaderProgramName=r:(this._shaderProgram=r,this._shaderProgramName=this._shaderProgram.GetName())}Release(){if(this._refCount>0)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;s<e;++s){const e=[];for(let o=0;o<t;++o){const t=C3.New(C3.Gfx.DeformMeshPoint,this,o,s),n=o/i,a=s/h;t._Init(n,a,n,a),e.push(t)}this.#m.push(e)}}Release(){this.#g&&(this.#g.Release(),this.#g=null),C3.clearArray(this.#m)}CopyFrom(t,e=1,s=1){for(let i=0,h=Math.min(this.GetVSize(),t.GetVSize());i<h;++i)for(let h=0,o=Math.min(this.GetHSize(),t.GetHSize());h<o;++h)this.GetMeshPointAt(h,i).CopyFrom(t.GetMeshPointAt(h,i),e,s);this._SetPointsChanged()}GetHSize(){return this.#l}GetVSize(){return this.#G}GetOwner(){return this.#r}_GetPoints(){return this.#m}_SetPointsChanged(){this.#p=!0,this.#y=!0}#D(){if(!this.#p)return;let t=1/0,e=1/0,s=1/0,i=-1/0,h=-1/0,o=-1/0;for(const n of this.#m)for(const a of n){const n=a.GetX(),r=a.GetY(),l=a.GetZ();t=Math.min(t,n),e=Math.min(e,r),s=Math.min(s,l),i=Math.max(i,n),h=Math.max(h,r),o=Math.max(o,l)}this.#u=t,this.#c=e,this.#M=s,this.#C=i,this.#f=h,this.#d=o,this.#p=!1}GetMinX(){return this.#D(),this.#u}GetMinY(){return this.#D(),this.#c}GetMinZ(){return this.#D(),this.#M}GetMaxX(){return this.#D(),this.#C}GetMaxY(){return this.#D(),this.#f}GetMaxZ(){return this.#D(),this.#d}ApplyZScale(t){for(const e of this.#m)for(const s of e)s.SetZ(s.GetZ()*t)}HasAnyZElevation(){return this.GetMinZ()<0||this.GetMaxZ()>0}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<n;++t){const n=h[t],a=o[t];for(let t=0,h=a.length;t<h;++t){const h=n[t],o=a[t];i?o._Interpolate_TexRect(h,e,s):o._Interpolate_TexQuad(h,e,s)}}this.#y=!0}#S(t){if(this.#g)return;const e=this.#l,s=this.#G,i=e*s,h=(e-1)*(s-1)*6;this.#g=t.CreateMeshData(i,h,{staticIndices:!0,debugLabel:"deformmesh"}),this.#g.CreateGPUResources(),this.#P()}#P(){const t=this.#l,e=this.#G,s=this.#g.indices;let i=0;for(let h=0,o=e-1;h<o;++h){const e=h*t,o=(h+1)*t;for(let h=0,n=t-1;h<n;++h){const t=h+1,n=h+e,a=t+e,r=t+o,l=h+o;s[i++]=n,s[i++]=a,s[i++]=r,s[i++]=n,s[i++]=r,s[i++]=l}}this.#g.MarkIndexDataChanged()}#Z(t){if(!this.#y&&this.#x===t)return;const e=this.#m,s=this.#G,i=this.#g.positions,h=this.#g.texCoords;let o=0,n=0,a=0,r=-1,l=-1,G=-1,m=-1;for(let u=0,c=s;u<c;++u){const s=e[u];for(let e=0,u=s.length;e<u;++e){const u=s[e],c=Math.fround(u.GetX()),M=i[o];i[o++]=c;const C=Math.fround(u.GetY()),f=i[o];i[o++]=C;const d=Math.fround(u.GetZ()+t),p=i[o];i[o++]=d;const g=Math.fround(u.GetU()),y=h[n];h[n++]=g;const x=Math.fround(u.GetV()),z=h[n];h[n++]=x,c===M&&C===f&&d===p||(-1===r?(r=a,l=a+1):l=a+1),g===y&&x===z||(-1===G?(G=a,m=a+1):m=a+1),a++}}-1!==r&&this.#g.MarkDataChanged("positions",r,l),-1!==G&&this.#g.MarkDataChanged("texCoords",G,m),this.#y=!1,this.#x=t}#b(t){if(t.equals(this.#z))return;this.#z.set(t);const e=this.#g.colors,s=t.getR(),i=t.getG(),h=t.getB(),o=t.getA();for(let t=0,n=e.length;t<n;)e[t++]=s,e[t++]=i,e[t++]=h,e[t++]=o;this.#g.MarkDataChanged("colors",0,this.#g.GetVertexCount())}Draw(t,e){this.#S(t),this.#Z(e),this.#b(t.GetColor()),t.DrawMeshData(this.#g)}Outline(t,e){e||(e=(t,e,s)=>[t,e,s]);const s=this.#m;let i=s[0];for(let h=1,o=s.length;h<o;++h){const n=s[h];let a=i[0],r=n[0];for(let s=1,l=n.length;s<l;++s){const G=i[s],m=n[s],[u,c,M]=e(a.GetX(),a.GetY(),a.GetZ()),[C,f,d]=e(G.GetX(),G.GetY(),G.GetZ()),[p,g,y]=e(m.GetX(),m.GetY(),m.GetZ()),[x,z,D]=e(r.GetX(),r.GetY(),r.GetZ());t.Line3D(u,c,M,C,f,d),t.Line3D(u,c,M,p,g,y),t.Line3D(u,c,M,x,z,D),s===l-1&&t.Line3D(C,f,d,p,g,y),h===o-1&&t.Line3D(x,z,D,p,g,y),a=G,r=m}i=n}}InsertPolyMeshVertices(t){const e=.001,s=.99999999,i=t.pointsArr(),h=[],o=this.GetHSize()-1,n=this.GetVSize()-1,a=1/o,r=1/n,l=o-1,G=n-1;let m=i[0],u=i[1],c=C3.clamp(Math.floor(m*o),0,l),M=C3.clamp(Math.floor(u*n),0,G),C=!0,f=0,d=0,p=0;let g=-1;const y=()=>{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;t<x;t+=2){m=i[t],u=i[t+1],h.push(m,u),c=C3.clamp(Math.floor(m*o),0,l),M=C3.clamp(Math.floor(u*n),0,G);const z=(t+2)%x;for(f=i[z],d=i[z+1],g=-1;;){if(h.length>1e6)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<l&&3!==g&&(p=C3.rayIntersectExtended(m,u,f,d,o,i,o,n,e),p>=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<G&&4!==g&&(p=C3.rayIntersectExtended(m,u,f,d,t,n,o,n,e),p>=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<i;t+=2){const i=s[t],h=s[t+1],[o,n]=this.TransformPoint(i,h);e.push(o,n)}return e}TransformPoint(t,e){const s=this.GetHSize()-1,i=this.GetVSize()-1,h=1/s,o=1/i,n=C3.clamp(Math.floor(t*s),0,s-1),a=C3.clamp(Math.floor(e*i),0,i-1),r=n*h,l=a*o,G=(n+1)*h,m=(a+1)*o,u=this.GetMeshPointAt(n,a),c=this.GetMeshPointAt(n+1,a+1),M=C3.isPointInTriangleInclusive(t,e,r,l,G,l,G,m),C=M?r+h:r,f=M?l:l+o,d=this.GetMeshPointAt(n+(M?1:0),a+(M?0:1)),[p,g,y]=C3.triangleCartesianToBarycentric(t,e,r,l,C,f,G,m);return C3.triangleBarycentricToCartesian3d(p,g,y,u.GetX(),u.GetY(),u.GetZ(),d.GetX(),d.GetY(),d.GetZ(),c.GetX(),c.GetY(),c.GetZ())}#T(t){const e=[],s=1e-7;let i=t[0],h=t[1],o=i-t.at(-2),n=h-t.at(-1);for(let a=0,r=t.length;a<r;a+=2){const l=(a+2)%r,G=t[l],m=t[l+1],u=G-i,c=m-h,M=Math.abs(u)<s&&Math.abs(o)<s&&Math.sign(c)===Math.sign(n),C=Math.abs(c)<s&&Math.abs(n)<s&&Math.sign(u)===Math.sign(o);(!M&&!C&&Math.abs(u/o-c/n)>.001||0==u&&0===c)&&e.push(i,h),i=G,h=m,o=u,n=c}e.length>=6&&e.length<t.length&&C3.shallowAssignArray(t,e)}SaveToJson(){return{"cols":this.GetHSize(),"rows":this.GetVSize(),"points":this.#m.map(t=>t.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;t<s;++t){const s=i[t];for(let i=0;i<e;++i){this.GetMeshPointAt(i,t).LoadFromJson(s[i])}}}};
}

// ../lib/gfx/meshData.js
{
const C3=globalThis.C3,assert=globalThis.assert,DEFAULT_MESHDATA_OPTS={staticPositions:!1,staticTexCoords:!1,staticColors:!1,staticIndices:!1,texIndices:!1,debugLabel:""},SMALL_MESH_VERTICES=128,SMALL_MESH_INDICES=1024;class PendingBufferUpdate{#e=!1;#t=0;#n=0;#i=0;SetMaxSize(e){this.#i=e}MarkChanged(e,t){if(e<0||t>this.#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;a<r;)s[a++]=e,s[a++]=t,s[a++]=n,s[a++]=i}FillTexIndices(e){this.#h!==e&&(this.#h=e,this.texIndices.fill(e),this.MarkDataChanged("texIndices",0,this.GetVertexCount()))}};
}

// ../lib/gfx/dynamicMeshData.js
{
const C3=globalThis.C3,assert=globalThis.assert,MAX_VERTICES=65535,MAX_INDICES=393210,defaultTexCoordsQuad=new C3.Quad2D(0,0,1,0,1,1,0,1),DEFAULT_DYNAMICMESHDATA_OPTS={texIndices:!1};C3.Gfx.DynamicMeshData=class{#t;#e=0;#s=0;#i=null;#r=null;#o=null;#a=null;#n=null;#h=new C3.Color(1,1,1,1);constructor(t,e){e=Object.assign({},DEFAULT_DYNAMICMESHDATA_OPTS,e),this.#t=t.CreateMeshData(65535,393210,{texIndices:e.texIndices,debugLabel:"dynamic"})}Release(){this.#t.Release(),this.#t=null,this.#i=null,this.#r=null,this.#o=null,this.#a=null,this.#n=null}_GetMeshData(){return this.#t}CreateGPUResources(){this.#t.CreateGPUResources(),this.#i=this.#t.positions,this.#r=this.#t.texCoords,this.#o=this.#t.texIndices,this.#a=this.#t.colors,this.#n=this.#t.indices}WriteGPUData(t){this.#t.MarkAllVertexDataChanged(0,this.#e),this.#t.MarkIndexDataChanged(0,this.#s),this.#t.WriteGPUData(t),this.#e=0,this.#s=0}ReleaseGPUResources(){this.#t.ReleaseGPUResources(),this.#i=null,this.#r=null,this.#o=null,this.#a=null,this.#n=null}OnContextLost(){this.#t.OnContextLost()}WebGPUInitRenderPassVertexBuffers(t){this.#t.WebGPUInitRenderPassVertexBuffers(t)}WebGPUInitRenderPassIndexBuffer(t){this.#t.WebGPUInitRenderPassIndexBuffer(t)}CanFit(t,e){return this.#e+t<=65535&&this.#s+e<=393210}GetVertexPtr(){return this.#e}GetIndexPtr(){return this.#s}static GetMaxVertices(){return 65535}static GetMaxIndices(){return 393210}GetDefaultColor(){return this.#h}#d(){const t=this.#e;this.#e+=4;let e=this.#s;this.#s+=6;const s=this.#n;return s[e++]=t,s[e++]=t+1,s[e++]=t+2,s[e++]=t,s[e++]=t+2,s[e]=t+3,t}WriteTexIndicesForQuad(t,e){const s=this.#o;s[t++]=e,s[t++]=e,s[t++]=e,s[t]=e}FillTexIndices(t,e,s){this.#o.fill(s,t,t+e)}WriteQuad(t,e){return this.WriteQuad4(t,e,defaultTexCoordsQuad)}WriteQuad2(t,e,s,i,r,o,a,n,h){const d=this.#d(),l=this.#i;let u=3*d;return l[u++]=e,l[u++]=s,l[u++]=t,l[u++]=i,l[u++]=r,l[u++]=t,l[u++]=o,l[u++]=a,l[u++]=t,l[u++]=n,l[u++]=h,l[u]=t,defaultTexCoordsQuad.writeToTypedArray(this.#r,2*d),this.#h.writeToTypedArrayx4(this.#a,4*d),d}WriteQuad3(t,e,s){const i=this.#d();return e.writeToTypedArray3D(this.#i,3*i,t),s.writeAsQuadToTypedArray(this.#r,2*i),this.#h.writeToTypedArrayx4(this.#a,4*i),i}WriteQuad4(t,e,s){const i=this.#d();return e.writeToTypedArray3D(this.#i,3*i,t),s.writeToTypedArray(this.#r,2*i),this.#h.writeToTypedArrayx4(this.#a,4*i),i}WriteQuad5(t,e,s,i){const r=this.#d();return e.writeToTypedArray3D(this.#i,3*r,t),s.writeToTypedArray(this.#r,2*r),this.#a.set(i,4*r),r}WriteQuad3D(t,e,s,i,r,o,a,n,h,d,l,u,c,x){const T=this.#d(),C=this.#i;let D=3*T;return C[D++]=e,C[D++]=s,C[D++]=i+t,C[D++]=r,C[D++]=o,C[D++]=a+t,C[D++]=n,C[D++]=h,C[D++]=d+t,C[D++]=l,C[D++]=u,C[D]=c+t,x.writeAsQuadToTypedArray(this.#r,2*T),this.#h.writeToTypedArrayx4(this.#a,4*T),T}WriteQuad3D2(t,e,s,i,r,o,a,n,h,d,l,u,c,x){const T=this.#d(),C=this.#i;let D=3*T;return C[D++]=e,C[D++]=s,C[D++]=i+t,C[D++]=r,C[D++]=o,C[D++]=a+t,C[D++]=n,C[D++]=h,C[D++]=d+t,C[D++]=l,C[D++]=u,C[D]=c+t,x.writeToTypedArray(this.#r,2*T),this.#h.writeToTypedArrayx4(this.#a,4*T),T}WriteQuad3D3(t,e,s,i,r,o,a,n,h,d,l,u,c,x,T){const C=this.#d(),D=this.#i;let y=3*C;return D[y++]=e,D[y++]=s,D[y++]=i+t,D[y++]=r,D[y++]=o,D[y++]=a+t,D[y++]=n,D[y++]=h,D[y++]=d+t,D[y++]=l,D[y++]=u,D[y]=c+t,x.writeToTypedArray(this.#r,2*C),this.#a.set(T,4*C),this.#h.writeToTypedArrayx4(this.#a,4*C),C}WriteQuad3D4(t,e,s){const i=this.#d();return e.writeToTypedArrayWithZOffset(this.#i,3*i,t),s.writeAsQuadToTypedArray(this.#r,2*i),this.#h.writeToTypedArrayx4(this.#a,4*i),i}WriteMesh(t,e,s,i,r=0){const o=Math.floor(t.length/3),a=this.#e;this.#i.set(t,3*a),this.#r.set(e,2*a);const n=this.#n;if(0===a&&0===r)n.set(s,this.#s);else{let t=this.#s;for(let e=0,i=s.length;e<i;++e)n[t++]=s[e]+a-r}const h=this.#a;if(i)h.set(i,4*a);else{const t=this.#h,e=t.getR(),s=t.getG(),i=t.getB(),r=t.getA();let n=4*a;for(let t=0,a=o;t<a;++t)h[n++]=e,h[n++]=s,h[n++]=i,h[n++]=r}return this.#e+=o,this.#s+=s.length,a}static CalculatePartialIndexRange(t,e,s){let i=t[e],r=t[e];for(let o=e+1,a=e+s;o<a;++o){const e=t[o];i=Math.min(i,e),r=Math.max(r,e)}return{minIndex:i,maxIndex:r}}};
}

// ../lib/gfx/coplanarManager.js
{
const C3=globalThis.C3,coplanarInstances=[],postRenderInstances=[];C3.Gfx.CoplanarManagerMethods=class{#e=null;#n(e,n){const a=this.GetInstanceLayer(e);this.#e!==a&&(this.PrepareLayerForDraw(a,n),this.#e=a)}ShouldDrawInstance(e){}GetInstanceBaseZ(e){}GetInstanceDepth(e){}InstanceRendersToOwnZPlane(e){}InstanceMustMitigateZFighting(e){}SetInstanceDrawBackFaceOnly(e,n){}SetInstanceDrawNonBackFacesOnly(e,n){}DrawInstance(e,n,a,t,s){this.#n(t,e)}GetInstanceLayer(e){}PrepareLayerForDraw(e,n){}_Reset(){this.#e=null}},C3.Gfx.CoplanarManager=class{#a;#t=!0;constructor(e){this.#a=e}GetMethods(){return this.#a}SetEffectsEnabled(e){this.#t=!!e}DrawCoplanar(e,n,a,t){const s=this.#a;for(let r=0,c=t.length;r<c;){const o=t[r];if(!s.ShouldDrawInstance(o)){++r;continue}s.InstanceRendersToOwnZPlane(o)&&0===s.GetInstanceDepth(o)||postRenderInstances.push(o);const l=s.GetInstanceBaseZ(o);coplanarInstances.push(o);let I=r+1;for(;I<c;++I){const e=t[I];if(s.ShouldDrawInstance(e)){if(s.GetInstanceBaseZ(e)!==l)break;s.InstanceRendersToOwnZPlane(e)?(0!==s.GetInstanceDepth(e)&&postRenderInstances.push(e),coplanarInstances.push(e)):postRenderInstances.push(e)}}if(1!==coplanarInstances.length||s.InstanceMustMitigateZFighting(coplanarInstances[0])){this.#s(e,n,a,coplanarInstances);for(let t=0,r=postRenderInstances.length;t<r;++t){const r=postRenderInstances[t];s.SetInstanceDrawNonBackFacesOnly(r,!0),s.DrawInstance(e,n,a,r,this.#t),s.SetInstanceDrawNonBackFacesOnly(r,!1)}}else{s.DrawInstance(e,n,a,coplanarInstances[0],this.#t);for(let t=0,r=postRenderInstances.length;t<r;++t){const r=postRenderInstances[t];r!==o&&s.DrawInstance(e,n,a,r,this.#t)}}r=I,C3.clearArray(coplanarInstances),C3.clearArray(postRenderInstances)}s._Reset()}#s(e,n,a,t){const s=this.#a;e.CoplanarStartStencilPass();for(let r=0,c=t.length;r<c;++r){const c=t[r];s.SetInstanceDrawBackFaceOnly(c,!0),s.DrawInstance(e,n,a,c,!1)}e.CoplanarStartColorPass();for(let r=0,c=t.length;r<c;++r){const c=t[r];s.DrawInstance(e,n,a,c,this.#t),s.SetInstanceDrawBackFaceOnly(c,!1)}e.CoplanarRestoreStandardRendering()}};
}

// ../lib/gfx/webgl/texture.js
{
const C3=self.C3,VALID_PIXEL_FORMATS=new Set(["rgba8","rgb8","rgba4","rgb5_a1","rgb565"]),VALID_MIPMAP_QUALITIES=new Set(["default","low","high"]),VALID_WRAP_MODES=new Set(["clamp-to-edge","repeat","mirror-repeat"]);function GetFormatSpecifiers(e,t){let i,r,a,s;switch(e){case"rgba8":i=t.RGBA8,r=t.RGBA,a=t.RGBA,s=t.UNSIGNED_BYTE;break;case"rgb8":i=t.RGB8,r=t.RGB,a=t.RGB,s=t.UNSIGNED_BYTE;break;case"rgba4":i=t.RGBA4,r=t.RGBA,a=t.RGBA,s=t.UNSIGNED_SHORT_4_4_4_4;break;case"rgb5_a1":i=t.RGB5_A1,r=t.RGBA,a=t.RGBA,s=t.UNSIGNED_SHORT_5_5_5_1;break;case"rgb565":i=t.RGB565,r=t.RGB,a=t.RGB,s=t.UNSIGNED_SHORT_5_6_5;break;default:throw new Error("invalid pixel format")}return{sizedinternalformat:i,internalformat:r,format:a,type:s}}const CREATEFROM_DEFAULT_OPTIONS={wrapX:"clamp-to-edge",wrapY:"clamp-to-edge",defaultSampling:"trilinear",anisotropy:1,pixelFormat:"rgba8",mipMap:!0,mipMapQuality:"default",premultiplyAlpha:!0,isSvg:!1,width:-1,height:-1},UPDATE_DEFAULT_OPTIONS={premultiplyAlpha:!0,flipY:!1},allTextures=new Set;C3.Gfx.WebGLRendererTexture=class{#e="trilinear";#t=2;#i=-1;#r=[null,null,null];constructor(e){this._renderer=e,this._texture=null,this._width=0,this._height=0,this._isStatic=!0,this._wrapX="clamp-to-edge",this._wrapY="clamp-to-edge",this._anisotropy=1,this._pixelFormat="rgba8",this._isMipMapped=!1,this._mipMapQuality="default",this._refCount=0}_CreateStatic(e,t){if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas||e instanceof ImageData||e instanceof ArrayBuffer))throw new Error("invalid texture source");if(t=Object.assign({},CREATEFROM_DEFAULT_OPTIONS,t),this._texture)throw new Error("already created texture");if(this._wrapX=t.wrapX,this._wrapY=t.wrapY,this._anisotropy=t.anisotropy,this._pixelFormat=t.pixelFormat,this._isMipMapped=!!t.mipMap&&this._renderer.AreMipmapsEnabled(),this._mipMapQuality=t.mipMapQuality,this.SetDefaultSampling(t.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");if(this._isStatic=!0,e instanceof ArrayBuffer||null===e||t.isSvg){if(this._width=t.width,this._height=t.height,e instanceof ArrayBuffer&&e.byteLength!==this._width*this._height*4)throw new Error("ArrayBuffer wrong size")}else this._width=e.width,this._height=e.height;if(this._width<=0||this._height<=0)throw new Error("invalid texture data size");if(t.isSvg){const t=C3.CreateCanvas(this._width,this._height);t.getContext("2d").drawImage(e,0,0,this._width,this._height),e=t}const i=C3.isPOT(this._width)&&C3.isPOT(this._height),r=this._renderer.GetMaxTextureSize();if(this._width>r||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="<default-device-transform>"===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<i;++t)if(!this._uCustomParameters[t].IsSetToCustomInBatch(e[t]))return!1;return!0}SetCustomParametersInBatch(e){for(let t=0,i=e.length;t<i;++t)this._uCustomParameters[t].SetBatchValueCustom(e[t])}AreOptionalUniformsAlreadySetInBatch(e,t,i,r,o,n,a,l,s,h){return!this._uSamplerBack.IsUsed()&&(!(this._uPixelSize.IsUsed()&&!this._uPixelSize.IsSetTo2InBatch(o,n))&&(!(this._uDestStart.IsUsed()&&!this._uDestStart.IsSetTo2InBatch(e.getLeft(),e.getTop()))&&(!(this._uDestEnd.IsUsed()&&!this._uDestEnd.IsSetTo2InBatch(e.getRight(),e.getBottom()))&&(!(this._uDevicePixelRatio.IsUsed()&&!this._uDevicePixelRatio.IsSetTo1InBatch(a))&&(!(this._uLayerScale.IsUsed()&&!this._uLayerScale.IsSetTo1InBatch(l))&&(!(this._uLayerAngle.IsUsed()&&!this._uLayerAngle.IsSetTo1InBatch(s))&&(!(this._uSrcStart.IsUsed()&&!this._uSrcStart.IsSetTo2InBatch(t.getLeft(),t.getTop()))&&(!(this._uSrcEnd.IsUsed()&&!this._uSrcEnd.IsSetTo2InBatch(t.getRight(),t.getBottom()))&&(!(this._uSrcOriginStart.IsUsed()&&!this._uSrcOriginStart.IsSetTo2InBatch(i.getLeft(),i.getTop()))&&(!(this._uSrcOriginEnd.IsUsed()&&!this._uSrcOriginEnd.IsSetTo2InBatch(i.getRight(),i.getBottom()))&&(!(this._uLayoutStart.IsUsed()&&!this._uLayoutStart.IsSetTo2InBatch(r.getLeft(),r.getTop()))&&(!(this._uLayoutEnd.IsUsed()&&!this._uLayoutEnd.IsSetTo2InBatch(r.getTop(),r.getBottom()))&&!(this._uSeconds.IsUsed()&&!this._uSeconds.IsSetTo1InBatch(h))))))))))))))}SetOptionalUniformsInBatch(e,t,i,r,o,n,a,l,s,h){this._uSamplerBack.IsUsed()||(this._uPixelSize.IsUsed()&&this._uPixelSize.SetBatch2(o,n),this._uDestStart.IsUsed()&&this._uDestStart.SetBatch2(e.getLeft(),e.getTop()),this._uDestEnd.IsUsed()&&this._uDestEnd.SetBatch2(e.getRight(),e.getBottom()),this._uDevicePixelRatio.IsUsed()&&this._uDevicePixelRatio.SetBatch1(a),this._uLayerScale.IsUsed()&&this._uLayerScale.SetBatch1(l),this._uLayerAngle.IsUsed()&&this._uLayerAngle.SetBatch1(s),this._uSrcStart.IsUsed()&&this._uSrcStart.SetBatch2(t.getLeft(),t.getTop()),this._uSrcEnd.IsUsed()&&this._uSrcEnd.SetBatch2(t.getRight(),t.getBottom()),this._uSrcOriginStart.IsUsed()&&this._uSrcOriginStart.SetBatch2(i.getLeft(),i.getTop()),this._uSrcOriginEnd.IsUsed()&&this._uSrcOriginEnd.SetBatch2(i.getRight(),i.getBottom()),this._uLayoutStart.IsUsed()&&this._uLayoutStart.SetBatch2(r.getLeft(),r.getTop()),this._uLayoutEnd.IsUsed()&&this._uLayoutEnd.SetBatch2(r.getTop(),r.getBottom()),this._uSeconds.IsUsed()&&this._uSeconds.SetBatch1(h))}UpdateMatP(e,t){this._hasCurrentMatP&&!t||this._isDeviceTransform||(this._uMatP.IsUsed()&&this._uMatP.UpdateMatrix4fv(e),this._hasCurrentMatP=!0)}SetMatPStale(){this._hasCurrentMatP=!1}UpdateMatMV(e,t){this._hasCurrentMatMV&&!t||this._isDeviceTransform||(this._uMatMV.IsUsed()&&this._uMatMV.UpdateMatrix4fv(e),this._hasCurrentMatMV=!0)}SetMatMVStale(){this._hasCurrentMatMV=!1}_UpdateDeviceTransformUniforms(e){if(!this._isDeviceTransform)throw new Error("not device transform shader");this._uMatP.UpdateMatrix4fv(e);const t=this._renderer,i=t.GetWidth()/2,r=t.GetHeight()/2,o=t.CalculateLookAtModelView2(i,r,t.GetDefaultCameraZ(t.GetHeight()),i,r,0,t.GetHeight());this._uMatMV.UpdateMatrix4fv(o)}UpdateColor(e){this._uColor.IsUsed()&&this._uColor.Update4f(e[0],e[1],e[2],e[3])}static GetReservedUniformNames(){return RESERVED_UNIFORM_NAMES}static _GetConservativeDepthShaderPrefix(e){return e?"\n#extension GL_EXT_conservative_depth : enable\nlayout (depth_greater) out highp float gl_FragDepth;\n\t":""}static GetDefaultVertexShaderSource(e){const t=e?"highp":"mediump";return["attribute highp vec3 aPos;","varying highp vec3 vWorldPos;",`attribute ${t} vec2 aTex;`,`varying ${t} vec2 vTex;`,"attribute lowp vec4 aColor;","varying lowp vec4 vColor;","uniform highp mat4 matP;","uniform highp mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPos, 1.0);","\tvWorldPos = aPos;","\tvTex = aTex;","\tvColor = aColor;","}"].join("\n")}static GetDefaultVertexShaderSource_WebGL2(e){const t=e?"highp":"mediump";return["#version 300 es","in highp vec3 aPos;","out highp vec3 vWorldPos;",`in ${t} vec2 aTex;`,`out ${t} vec2 vTex;`,"in lowp vec4 aColor;","out lowp vec4 vColor;","uniform highp mat4 matP;","uniform highp mat4 matMV;","void main(void) {","\tgl_Position = matP * matMV * vec4(aPos, 1.0);","\tvWorldPos = aPos;","\tvTex = aTex;","\tvColor = aColor;","}"].join("\n")}static GetTextureFillFragmentShaderSource_WebGL1_NoFragDepth(){return["varying mediump vec2 vTex;","varying lowp vec4 vColor;","uniform lowp sampler2D samplerFront;","void main(void) {","\tgl_FragColor = texture2D(samplerFront, vTex) * vColor;","}"].join("\n")}static GetTextureFillFragmentShaderSource_WebGL1_FragDepthEXT(){return["#extension GL_EXT_frag_depth : enable","varying mediump vec2 vTex;","varying lowp vec4 vColor;","uniform lowp sampler2D samplerFront;","void main(void) {","\tgl_FragColor = texture2D(samplerFront, vTex) * vColor;","\tgl_FragDepthEXT = (gl_FragColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetTextureFillFragmentShaderSource_WebGL2(e){return["#version 300 es",C3.Gfx.WebGLShaderProgram._GetConservativeDepthShaderPrefix(e),"in mediump vec2 vTex;","out lowp vec4 outColor;","in lowp vec4 vColor;","uniform lowp sampler2D samplerFront;","void main(void) {","\toutColor = texture(samplerFront, vTex) * vColor;","\tgl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetTilemapFragmentShaderSource_WebGL1_NoFragDepth(){return["varying highp vec2 vTex;","varying lowp vec4 vColor;","uniform lowp sampler2D samplerFront;","uniform highp vec2 srcStart;","uniform highp vec2 pixelSize;","uniform highp vec2 tileSize;","uniform highp vec2 tileSpacing;","void main(void) {","\thighp vec2 tile = floor(vTex);","\thighp vec2 tex = fract(vTex);","\thighp vec2 tileOrigin = srcStart + tile * (tileSize + tileSpacing);","\thighp vec2 lowerBound = tileOrigin + pixelSize / 2.0;","\thighp vec2 upperBound = tileOrigin + tileSize - pixelSize / 2.0;","\tgl_FragColor = texture2D(samplerFront, clamp(tex, lowerBound, upperBound), -16.0) * vColor;","}"].join("\n")}static GetTilemapFragmentShaderSource_WebGL1_FragDepthEXT(){return["#extension GL_EXT_frag_depth : enable","varying highp vec2 vTex;","varying lowp vec4 vColor;","uniform lowp sampler2D samplerFront;","uniform highp vec2 srcStart;","uniform highp vec2 pixelSize;","uniform highp vec2 tileSize;","uniform highp vec2 tileSpacing;","void main(void) {","\thighp vec2 tile = floor(vTex);","\thighp vec2 tex = fract(vTex);","\thighp vec2 tileOrigin = srcStart + tile * (tileSize + tileSpacing);","\thighp vec2 lowerBound = tileOrigin + pixelSize / 2.0;","\thighp vec2 upperBound = tileOrigin + tileSize - pixelSize / 2.0;","\tgl_FragColor = texture2D(samplerFront, clamp(tex, lowerBound, upperBound), -16.0) * vColor;","\tgl_FragDepthEXT = (gl_FragColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetTilemapFragmentShaderSource_WebGL2(e){return["#version 300 es",C3.Gfx.WebGLShaderProgram._GetConservativeDepthShaderPrefix(e),"in highp vec2 vTex;","out lowp vec4 outColor;","in lowp vec4 vColor;","uniform lowp sampler2D samplerFront;","uniform highp vec2 srcStart;","uniform highp vec2 pixelSize;","uniform highp vec2 tileSize;","uniform highp vec2 tileSpacing;","void main(void) {","\thighp vec2 tile = floor(vTex);","\thighp vec2 tex = fract(vTex);","\thighp vec2 tileOrigin = srcStart + tile * (tileSize + tileSpacing);","\thighp vec2 lowerBound = tileOrigin + pixelSize / 2.0;","\thighp vec2 upperBound = tileOrigin + tileSize - pixelSize / 2.0;","\toutColor = texture(samplerFront, clamp(tex, lowerBound, upperBound), -16.0) * vColor;","\tgl_FragDepth = (outColor.a == 0.0 ? 1.0 : gl_FragCoord.z);","}"].join("\n")}static GetTileRandomizationFragmentShaderSource(e,t,i,r){let o="";return e>=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<a;++r)e[r+1]=t[r]}DoSetBlend(){const t=this._gl,e=this._mat4param,r=e[0],a=e[1],s=e[2];let i=a,n=s,o=t.FUNC_ADD,_=t.FUNC_ADD;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<s;++t){const s=e[t];s===r?s.UpdateMatP(a,!0):s.SetMatPStale()}mat4.copy(t.currentMatP,a)}InitSetModelView(t){this._type=6,mat4.copy(this._mat4param,t)}DoSetModelView(){const t=this._batchState,e=t.renderer._allShaderPrograms,r=t.currentShader,a=this._mat4param;for(let t=0,s=e.length;t<s;++t){const s=e[t];s===r?s.UpdateMatMV(a,!0):s.SetMatMVStale()}mat4.copy(t.currentMV,a)}InitSetRenderTarget(t){this._type=7,this._texParam=t}DoSetRenderTarget(){const t=this._gl,e=this._texParam,r=this._batchState;e?(r.currentFramebuffer=e._GetFramebuffer(),r.currentFramebufferNoDepth=e._GetFramebufferNoDepth(),r.isDepthSamplingEnabled&&r.currentFramebufferNoDepth?t.bindFramebuffer(t.FRAMEBUFFER,r.currentFramebufferNoDepth):t.bindFramebuffer(t.FRAMEBUFFER,r.currentFramebuffer)):(r.currentFramebuffer=null,r.currentFramebufferNoDepth=null,t.bindFramebuffer(t.FRAMEBUFFER,null))}InitClearSurface(t){this._type=8,t.writeToTypedArray(this._mat4param,0)}InitClearSurface2(t,e,r,a){this._type=8;const s=this._mat4param;s[0]=t,s[1]=e,s[2]=r,s[3]=a}DoClearSurface(){const t=this._gl,e=this._mat4param,r=this._batchState.clearColor,a=e[0],s=e[1],i=e[2],n=e[3];r.equalsRgba(a,s,i,n)||(t.clearColor(a,s,i,n),r.setRgba(a,s,i,n)),t.clear(t.COLOR_BUFFER_BIT)}InitSetPointTexCoords(t){this._type=14,t.writeToTypedArray(this._mat4param,0)}DoSetPointTextureCoords(){const t=this._mat4param;this._batchState.pointTexCoords.set(t[0],t[1],t[2],t[3])}InitPoints(t,e,r){this._type=9,this._startIndex=t,this._indexCount=1,this._mat4param[0]=e,r.writeToTypedArray(this._colorParam,0)}DoPoints(){const t=this._gl,e=this._batchState,r=e.renderer,a=r._spPoints;t.useProgram(a._shaderProgram),r._BindVAO(null),a.UpdateMatP(e.currentMatP,!1),a.UpdateMatMV(e.currentMV,!1);const s=e.pointTexCoords;a._uPointTexStart.IsUsed()&&a._uPointTexStart.Update2f(s.getLeft(),s.getTop()),a._uPointTexEnd.IsUsed()&&a._uPointTexEnd.Update2f(s.getRight(),s.getBottom());const i=this._mat4param[0];if(a._uZElevation.IsUsed()&&a._uZElevation.Update1f(i),a._uColor.IsUsed()){const t=this._colorParam;a._uColor.Update4f(t[0],t[1],t[2],t[3])}t.drawArrays(t.POINTS,this._startIndex/4,this._indexCount),t.useProgram(e.currentShader._shaderProgram),r._BindVAO(e.currentMeshData._GetVAO())}InitSetProgram(t){this._type=10,this._texParam=t}DoSetProgram(){const t=this._gl,e=this._batchState,r=this._texParam;e.currentShader=r,t.useProgram(r._shaderProgram),r.UpdateMatP(e.currentMatP,!1),r.UpdateMatMV(e.currentMV,!1)}InitSetProgramParameters(){this._type=11}DoSetProgramParameters(){const t=this._batchState,e=t.currentShader,r=this._gl,a=this._mat4param,s=this._colorParam,i=this._srcOriginRect;if(e._uSamplerBack.IsUsed()){const e=t.renderer,a=this._texParam;if(e._lastTexture1!==a&&(r.activeTexture(r.TEXTURE1),r.bindTexture(r.TEXTURE_2D,a?a._GetTexture():null),e._lastTexture1=a,r.activeTexture(r.TEXTURE0)),a)if(e.GetWebGLVersionNumber()>=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<a;++r){const a=t[r],s=e[r];a.IsColorType()?a.Update3f(s.getR(),s.getG(),s.getB()):a.Update1f(s)}}InitInvalidateFramebuffer(t){this._type=13,this._texParam=t}DoInvalidateFramebuffer(){const t=this._gl,e=this._texParam,r=this._batchState.currentFramebuffer;e!==r&&t.bindFramebuffer(t.FRAMEBUFFER,e),t.invalidateFramebuffer(t.FRAMEBUFFER,[t.COLOR_ATTACHMENT0]),e!==r&&t.bindFramebuffer(t.FRAMEBUFFER,r)}InitBlitFramebuffer(t,e,r){this._type=16;const a=this._mat4param,s=this._batchState.renderer;a[0]=t.GetWidth(),a[1]=t.GetHeight(),a[2]=e?e.GetWidth():s.GetWidth(),a[3]=e?e.GetHeight():s.GetHeight(),a[4]="nearest"!==t.GetDefaultSampling()?1:0,a[5]="stretch"===r;const i=this._shaderParams;C3.clearArray(i),i.push(t._GetFramebuffer()),i.push(e?e._GetFramebuffer():null)}DoBlitFramebuffer(){const t=this._mat4param,e=this._shaderParams,r=this._gl,a=t[0],s=t[1],i=t[2],n=t[3],o=0!==t[4],_=0!==t[5],h=e[0],u=e[1];if(r.bindFramebuffer(r.READ_FRAMEBUFFER,h),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,u),_)r.blitFramebuffer(0,0,a,s,0,0,i,n,r.COLOR_BUFFER_BIT,o?r.LINEAR:r.NEAREST);else{const t=Math.min(a,i),e=Math.min(s,n),o=Math.max(s-n,0),_=Math.max(n-s,0);r.blitFramebuffer(0,o,t,e+o,0,_,t,e+_,r.COLOR_BUFFER_BIT,r.NEAREST)}}InitStartQuery(t){this._type=17,this._texParam=t}DoStartQuery(){this._texParam.BeginTimeElapsed(),this._texParam=null}InitEndQuery(t){this._type=18,this._texParam=t}DoEndQuery(){this._texParam.EndTimeElapsed(),this._texParam=null}InitSetEllipseParams(t,e,r){this._type=19;const a=this._mat4param;a[0]=t,a[1]=e,a[2]=r}DoSetEllipseParams(){const t=this._batchState.currentShader,e=this._mat4param;t._uPixelSize.IsUsed()&&t._uPixelSize.Update2f(e[0],e[1]),t._uOutlineThickness.IsUsed()&&t._uOutlineThickness.Update1f(e[2])}InitSetTilemapInfo(t,e,r,a,s,i,n){this._type=15;const o=this._mat4param;t.writeToTypedArray(o,0),o[4]=1/e,o[5]=1/r,o[6]=a/e,o[7]=s/r,o[8]=i/e,o[9]=n/r}DoSetTilemapInfo(){const t=this._batchState.currentShader,e=this._mat4param;t._uSrcStart.IsUsed()&&t._uSrcStart.Update2f(e[0],e[1]),t._uPixelSize.IsUsed()&&t._uPixelSize.Update2f(e[4],e[5]),t._uTileSize.IsUsed()&&t._uTileSize.Update2f(e[6],e[7]),t._uTileSpacing.IsUsed()&&t._uTileSpacing.Update2f(e[8],e[9])}InitSetTileRandomizationInfo(t,e,r,a,s,i,n){this._type=28;const o=this._mat4param;o[0]=1/t,o[1]=1/e,o[2]=r,o[3]=a,o[4]=s,o[5]=i,o[6]=n}DoSetTileRandomizationInfo(){const t=this._batchState.currentShader,e=this._mat4param;t._uPixelSize.IsUsed()&&t._uPixelSize.Update2f(e[0],e[1]),t._uTileSize.IsUsed()&&t._uTileSize.Update2f(e[2],e[3]),t._uOutlineThickness.IsUsed()&&t._uOutlineThickness.Update1f(e[4]),t._uTileSpacing.IsUsed()&&t._uTileSpacing.Update2f(e[5],e[6])}InitClearDepth(t){this._type=21,this._startIndex=t?1:0}DoClearDepth(){const t=this._gl,e=0!==this._startIndex;e||t.depthMask(!0),t.clear(t.DEPTH_BUFFER_BIT),e||t.depthMask(!1)}InitSetDepthEnabled(t){this._type=22,this._startIndex=t?1:0}DoSetDepthEnabled(){const t=this._gl;0===this._startIndex?(t.disable(t.DEPTH_TEST),t.depthMask(!1)):(t.enable(t.DEPTH_TEST),t.depthMask(!0))}InitSetDepthSamplingEnabled(t){this._type=23,this._startIndex=t?1:0}DoSetDepthSamplingEnabled(){const t=this._gl,e=this._batchState,r=e.renderer,a=0!==this._startIndex;e.isDepthSamplingEnabled=a,t.activeTexture(t.TEXTURE2),a?(e.currentFramebufferNoDepth&&t.bindFramebuffer(t.FRAMEBUFFER,e.currentFramebufferNoDepth),t.bindTexture(t.TEXTURE_2D,r._GetDepthBuffer())):(t.bindTexture(t.TEXTURE_2D,null),e.currentFramebufferNoDepth&&t.bindFramebuffer(t.FRAMEBUFFER,e.currentFramebuffer)),t.activeTexture(t.TEXTURE0)}InitCoplanarStartStencilPass(){this._type=24}DoCoplanarStartStencilPass(){const t=this._gl;t.clear(t.STENCIL_BUFFER_BIT),t.enable(t.STENCIL_TEST),t.stencilFunc(t.ALWAYS,1,1),t.stencilOp(t.KEEP,t.KEEP,t.REPLACE),t.colorMask(!1,!1,!1,!1)}InitCoplanarStartColorPass(){this._type=25}DoCoplanarStartColorPass(){const t=this._gl;t.enable(t.STENCIL_TEST),t.colorMask(!0,!0,!0,!0),t.stencilFunc(t.EQUAL,1,1),t.stencilOp(t.KEEP,t.KEEP,t.KEEP)}InitCoplanarRestore(){this._type=26}DoCoplanarRestore(){const t=this._gl;t.disable(t.STENCIL_TEST)}InitSetScissor(t,e,r,a,s){this._type=27,this._startIndex=t?1:0;const i=this._mat4param;i[0]=e,i[1]=r,i[2]=a,i[3]=s}DoSetScissor(){const t=this._gl,e=this._mat4param;1===this._startIndex?(t.enable(t.SCISSOR_TEST),t.scissor(e[0],e[1],e[2],e[3])):t.disable(t.SCISSOR_TEST)}InitSetCullFaceMode(t){this._type=29,this._startIndex=t}DoSetCullFaceMode(){const t=this._gl,e=this._startIndex;0===e?t.disable(t.CULL_FACE):(t.enable(t.CULL_FACE),1===e?t.cullFace(t.BACK):t.cullFace(t.FRONT))}InitSetFrontFaceWinding(t){this._type=30,this._startIndex=t}DoSetFrontFaceWinding(){const t=this._gl;t.frontFace(0===this._startIndex?t.CW:t.CCW)}InitSetCurrentMeshData(t){this._type=31,this._texParam=t}DoSetCurrentMeshData(){const t=this._batchState,e=t.renderer,r=this._texParam;e._BindVAO(r._GetVAO()),t.currentMeshData=r}Run(){switch(this._type){case 1:return void this.DoDraw();case 2:return void this.DoSetTexture();case 3:return void this.DoSetBlend();case 4:return void this.DoSetViewport();case 5:return void this.DoSetProjection();case 6:return void this.DoSetModelView();case 7:return void this.DoSetRenderTarget();case 8:return void this.DoClearSurface();case 9:return void this.DoPoints();case 10:return void this.DoSetProgram();case 11:return void this.DoSetProgramParameters();case 12:return void this.DoSetProgramCustomParameters();case 13:return void this.DoInvalidateFramebuffer();case 14:return void this.DoSetPointTextureCoords();case 15:return void this.DoSetTilemapInfo();case 16:return void this.DoBlitFramebuffer();case 17:return void this.DoStartQuery();case 18:return void this.DoEndQuery();case 19:return void this.DoSetEllipseParams();case 20:return void this.DoSetGradientColor();case 21:return void this.DoClearDepth();case 22:return void this.DoSetDepthEnabled();case 23:return void this.DoSetDepthSamplingEnabled();case 24:return void this.DoCoplanarStartStencilPass();case 25:return void this.DoCoplanarStartColorPass();case 26:return void this.DoCoplanarRestore();case 27:return void this.DoSetScissor();case 28:return void this.DoSetTileRandomizationInfo();case 29:return void this.DoSetCullFaceMode();case 30:return void this.DoSetFrontFaceWinding();case 31:return void this.DoSetCurrentMeshData()}}};
}

// ../lib/gfx/text.js
{
const C3=self.C3,MAX_TEXTURE_SIZE=4096,EXTRA_LINE_HEIGHT=4,GENERIC_FONT_FAMILIES=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),DEFAULT_OPTS={timeout:60,textureAnisotropy:1},tempColor=new C3.Color(0,0,0,1),VALID_HORIZ_ALIGNMENTS=new Set(["left","center","right"]),VALID_VERT_ALIGNMENTS=new Set(["top","center","bottom"]),VALID_WORD_WRAP_MODES=new Set(["word","cjk","character"]),VALID_TEXT_DIRECTIONS=new Set(["ltr","rtl"]),MEASUREMENT_CACHE_MAX_ENTRIES=1e3,MEASUREMENT_CACHE_DELETE_COUNT=10,MEASUREMENT_CACHE_TIMEOUT=2,allRendererTexts=new Set;function fillOrStrokeRect(t,e,i,s,a,n){e?t.strokeRect(i,s,a,n):t.fillRect(i,s,a,n)}function ptToPx(t){return t*(4/3)}function getOffsetParam(t,e){t=t.trim();const i=parseFloat(t);return isFinite(i)?t.endsWith("%")?e*i/100:i:0}C3.FontManager&&C3.FontManager.addEventListener("fontload",t=>{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<a.GetPosY()+s)for(const e of a.fragments())if(t>=e.GetPosX()&&t<e.GetPosX()+e.GetWidth()*i)return e}return null}*fragmentsWithTag(t){this._UpdateTextMeasurements();const e=this._wrappedText.GetLines();for(const i of e)for(const e of i.fragments()){const i=e.GetStyleTag("tag");i&&C3.equalsNoCase(i.param,t)&&(yield e)}}FindFragmentWithTag(t,e){for(const i of this.fragmentsWithTag(t)){if(0===e)return i;--e}return null}CountFragmentsWithTag(t){let e=0;for(const i of this.fragmentsWithTag(t))++e;return e}MaybeUpdateCanvas(){return!(this._textContext&&!this._drawChanged&&!this._textLayoutChanged&&!this._wordWrapChanged)&&(!(this._wasReleased||this._width<=0||this._height<=0)&&(this._UpdateTextMeasurements(),this._DrawTextToCanvas(),!0))}_MaybeUpdateTexture(){this._wasReleased||this._width<=0||this._height<=0||(this.MaybeUpdateCanvas(),(!this._texture||this._forceRecreateTexture||this._canvasContentChanged)&&this._UpdateTexture())}GetTexture(){return this._textureTimeout.Reset(),this._MaybeUpdateTexture(),this._texture}_SetTextCanvasSize(t,e){this._textCanvas||(this._textCanvas=C3.CreateCanvas(16,16));let i=!1;this._lastCanvasWidth===t&&this._lastCanvasHeight===e||(this._lastCanvasWidth=t,this._lastCanvasHeight=e,this._textCanvas.width=t,this._textCanvas.height=e,i=!0),this._textContext||(this._textContext=this._textCanvas.getContext("2d"),i=!0),i?(this._textContext.textBaseline=this._isBBcodeEnabled?"alphabetic":"top",this._textContext.direction=this._textDirection,this._textContext.font=this._lastTextCanvasFont,this._textContext.fillStyle=this._lastTextCanvasFillStyle,this._textContext.strokeStyle=this._lastTextCanvasFillStyle,this._textContext.globalAlpha=this._lastTextCanvasOpacity,this._textContext.lineWidth=this._lastTextCanvasLineWidth):this._textContext.clearRect(0,0,t,e)}_MaybeCreateMeasureContext(){this._measureContext||(this._measureContext=C3.CreateCanvas(16,16).getContext("2d"),this._measureContextTop=C3.CreateCanvas(16,16).getContext("2d"),this._measureContext.textBaseline=this._isBBcodeEnabled?"alphabetic":"top",this._measureContextTop.textBaseline="top",this._measureContext.direction=this._textDirection,this._measureContextTop.direction=this._textDirection)}_SetMeasureFontString(t){this._lastMeasureCanvasFont!==t&&(this._lastMeasureCanvasFont=t,this._measureContext.font=t,this._measureContextTop.font=t)}_SupportsFontBoundingBoxMeasurements(){if(!didCheckFoundBoundingBoxSupport){didCheckFoundBoundingBoxSupport=!0,this._MaybeCreateMeasureContext();const t=this._measureContext.measureText("test");supportsFontBoundingBoxMeasurements="number"==typeof t["fontBoundingBoxAscent"]&&"number"==typeof t["fontBoundingBoxDescent"]}return supportsFontBoundingBoxMeasurements}_UpdateTextMeasurements(){this._UpdateWordWrap(),this._UpdateTextLayout()}_UpdateWordWrap(){this._wordWrapChanged&&(this._MaybeCreateMeasureContext(),!this._isBBcodeEnabled||this._bbString&&this._bbString.toString()===this._text||(this._bbString=new C3.BBString(this._text,{noEscape:!0})),this._measurementCacheIdleTimeout.Reset(),this._wrappedText.WordWrap(this._isBBcodeEnabled?this._bbString.toFragmentList():this._text,this._measureTextCallback,this._cssWidth,this._wrapMode,0),this._wordWrapChanged=!1)}_UpdateTextLayout(){this._textLayoutChanged&&(this._LayoutText(),this._textLayoutChanged=!1)}_ClearMeasurementCache(t){this._measurementCache.clear(),t||this._measurementCacheIdleTimeout.Cancel()}_AddToMeasurementCache(t,e){const i=this._measurementCache;if(i.set(t,e),i.size>1e3){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;a<h;++a){const h=s[a],r=h.GetHeight()*t,o=i;if(this._isBBcodeEnabled){if(i+=0===a?n:r,a>0&&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()<e)){if(!s.HasResult())return NaN;t+=s.GetResult()}}return t}DeleteAllBeforeFrameNumber(e){for(let r=0,t=this._buffer.length;r<t;++r){const t=this._buffer[r];if(!(t.GetFrameNumber()<e))return void(r>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,"<default>"],[h,n,"<default-device-transform>"],[o,l,"<point>"],[s.GetColorFillFragmentShaderSource(),a,"<fill>"],[s.GetLinearGradientFillFragmentShaderSource(),a,"<lineargradient>"],[s.GetPenumbraFillFragmentShaderSource(),a,"<penumbra>"],[s.GetHardEllipseFillFragmentShaderSource(),a,"<hardellipse>"],[s.GetHardEllipseOutlineFragmentShaderSource(),a,"<hardellipseoutline>"],[s.GetSmoothEllipseFillFragmentShaderSource(),a,"<smoothellipse>"],[s.GetSmoothEllipseOutlineFragmentShaderSource(),a,"<smoothellipseoutline>"],[s.GetSmoothLineFillFragmentShaderSource(),a,"<smoothline>"],[u,_,"<tilemap>"],[c,p,"<tilerandomization>"]],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<i;++e)t[e].Run()}GetOpacity(){return this._lastColor.getA()}SetColorRgba(t,e,i,r){const s=this._lastColor;s.equalsRgba(t,e,i,r)||(s.setRgba(t,e,i,r),this._currentStateGroup=null,2===this._topOfBatch&&(this._topOfBatch=0))}SetOpacity(t){const e=this._lastColor;e.getA()!==t&&(e.setA(t),this._currentStateGroup=null,2===this._topOfBatch&&(this._topOfBatch=0))}SetColor(t){const e=this._lastColor;e.equals(t)||(e.set(t),this._currentStateGroup=null,2===this._topOfBatch&&(this._topOfBatch=0))}ResetColor(){this.SetColorRgba(1,1,1,1)}GetColor(){return this._lastColor}SetTexture(t,e=0){const i=0===e?t?t._GetDefaultSamplingIndex():2:e-1;if(t===this._lastTexture0&&i===this.#n)return;this.PushBatch().InitSetTexture(t,i),this._lastTexture0=t,this.#n=i,this._topOfBatch=0}_ResetLastTexture(){this._lastTexture0=null}SetBlendMode(t){this._lastBlendMode!==t&&(this._lastBlendMode=t,this._SetBlend(this._GetBlendParametersByIndex(t)))}SetNamedBlendMode(t){this.SetBlendMode(this.NamedBlendToNumber(t))}_SetBlend(t){this.PushBatch().InitSetBlend(t),this._topOfBatch=0,this._currentStateGroup=null}IsPremultipliedAlphaBlend(){return 0===this._lastBlendMode}SetAlphaBlend(){this.SetBlendMode(0)}SetCullFaceMode(t){if(this._lastCullFace===t)return;this.PushBatch().InitSetCullFaceMode(t),this._lastCullFace=t,this._topOfBatch=0,this._currentStateGroup=null}GetCullFaceMode(){return this._lastCullFace}SetFrontFaceWinding(t){if(this._lastFrontFaceWinding===t)return;this.PushBatch().InitSetFrontFaceWinding(t),this._lastFrontFaceWinding=t,this._topOfBatch=0,this._currentStateGroup=null}GetFrontFaceWinding(){return this._lastFrontFaceWinding}SetCopyBlend(){this.SetBlendMode(3)}Rect(t){this.Rect2(t.getLeft(),t.getTop(),t.getRight(),t.getBottom())}Rect2(t,e,i,r){this.Quad2(t,e,i,e,i,r,t,r)}#_(t,e){this.#d();const i=this.#e;if(i.CanFit(t,e)||this.EndBatch(),1===this._topOfBatch)this._batch[this._batchPtr-1]._indexCount+=e;else{this.PushBatch().InitDraw(2*i.GetIndexPtr(),e),this._topOfBatch=1}}Quad(t){this.Quad4(t,defaultTexCoordsQuad)}Quad2(t,e,i,r,s,a,h,n){this.#_(4,6),this.#e.WriteQuad2(this._baseZ+this._currentZ,t,e,i,r,s,a,h,n)}Quad3(t,e){this.#_(4,6),this.#e.WriteQuad3(this._baseZ+this._currentZ,t,e)}Quad4(t,e){this.#_(4,6),this.#e.WriteQuad4(this._baseZ+this._currentZ,t,e)}Quad5(t,e,i){this.#_(4,6),this.#e.WriteQuad5(this._baseZ+this._currentZ,t,e,i)}Quad3D(t,e,i,r,s,a,h,n,o,l,u,_,d){this.#_(4,6),this.#e.WriteQuad3D(this._baseZ+this._currentZ,t,e,i,r,s,a,h,n,o,l,u,_,d)}Quad3D2(t,e,i,r,s,a,h,n,o,l,u,_,d){this.#_(4,6),this.#e.WriteQuad3D2(this._baseZ+this._currentZ,t,e,i,r,s,a,h,n,o,l,u,_,d)}Quad3D3(t,e,i,r,s,a,h,n,o,l,u,_,d,c){this.#_(4,6),this.#e.WriteQuad3D3(this._baseZ+this._currentZ,t,e,i,r,s,a,h,n,o,l,u,_,d,c)}Quad3D4(t,e){this.#_(4,6),this.#e.WriteQuad3D4(this._baseZ+this._currentZ,t,e)}FullscreenQuad(t,e){this.SetCurrentZ(0),mat4.copy(tmpProjection,this._matP),mat4.copy(tmpModelView,this._matMV),this.SetDefaultRenderTargetProjectionState();const[i,r]=this.GetRenderTargetSize(this._currentRenderTarget),s=this.CalculateLookAtModelView2(0,0,this.GetDefaultCameraZ(r),0,0,0,r);if(this.SetModelViewMatrix(s),"crop"===t&&this._currentRenderTarget&&e){const t=this._width/2,i=this._height/2,r=e.GetWidth(),s=e.GetHeight(),a=this._currentRenderTarget.GetWidth(),h=this._currentRenderTarget.GetHeight(),n=Math.min(a,r),o=Math.min(h,s),l=Math.max(s-h,0),u=Math.max(h-s,0);tmpRect.set(-t,i-u,-t+n,i-o-u),tmpQuad.setFromRect(tmpRect),tmpRect.set(0,l,n,o+l),tmpRect.divide(r,s),this.Quad3(tmpQuad,tmpRect)}else{const t=i/2,e=r/2;this.Rect2(-t,e,t,-e)}this.SetProjectionMatrix(tmpProjection),this.SetModelViewMatrix(tmpModelView)}StartRenderingPoints(t){if(this._lastPointTexCoords.equals(t))return;this._lastPointTexCoords.copy(t);this.PushBatch().InitSetPointTexCoords(t),this._topOfBatch=0}FinishRenderingPoints(){}Point(t,e,i,r){this._pointPtr>=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<a;++e)i.push({"binding":2*e,"visibility":GPUShaderStage["FRAGMENT"],"sampler":{"type":"filtering"}},{"binding":2*e+1,"visibility":GPUShaderStage["FRAGMENT"],"texture":{"sampleType":"float","viewDimension":"2d"}});this._textureBindGroupLayout=e["createBindGroupLayout"]({"label":"texturebindgrouplayout","entries":i}),this._backTextureBindGroupLayout=e["createBindGroupLayout"]({"label":"backtexturebindgrouplayout","entries":[{"binding":0,"visibility":GPUShaderStage["FRAGMENT"],"sampler":{"type":"filtering"}},{"binding":1,"visibility":GPUShaderStage["FRAGMENT"],"texture":{"sampleType":"float","viewDimension":"2d"}}]}),this._depthTextureBindGroupLayout=e["createBindGroupLayout"]({"label":"depthtexturebindgrouplayout","entries":[{"binding":0,"visibility":GPUShaderStage["FRAGMENT"],"sampler":{"type":"non-filtering"}},{"binding":1,"visibility":GPUShaderStage["FRAGMENT"],"texture":{"sampleType":"depth","viewDimension":"2d"}}]}),this._pipelineLayout=e["createPipelineLayout"]({"bindGroupLayouts":[this._bufferBindGroupLayout,this._textureBindGroupLayout,this._backTextureBindGroupLayout,this._depthTextureBindGroupLayout]});const s=C3.Gfx.WebGPUShaderProgram,n=this.SupportsF16(),u=this.IsColorDataF16();this._defaultVertexModule=e["createShaderModule"]({"label":"<default vertex module>","code":s._PreprocessVertexShaderCode(s.GetDefaultVertexShaderSource(u),n)}),this._defaultVertexModule["getCompilationInfo"]().then(e=>s.ReportShaderCompilationInfo("<default>","vertex",e)),this._normVertexModule=e["createShaderModule"]({"label":"<normalized vertex module>","code":s._PreprocessVertexShaderCode(s.GetNormalizedVertexShaderSource(u),n)}),this._normVertexModule["getCompilationInfo"]().then(e=>s.ReportShaderCompilationInfo("<normalized>","vertex",e));const h=await Promise.all([s.Create(this,{name:"<default>",src:s.GetMultiTextureFillFragmentShaderSource(!1,u),srcFragDepth:s.GetMultiTextureFillFragmentShaderSource(!0,u),vertexSrc:s.GetTextureFillVertexShaderSource(u),normVertexSrc:s.GetNormalizedTextureFillVertexShaderSource(u)}),s.Create(this,{name:"<single-texture-fill>",src:s.GetSingleTextureFillFragmentShaderSource(!1,u),srcFragDepth:s.GetSingleTextureFillFragmentShaderSource(!0,u),vertexSrc:s.GetTextureFillVertexShaderSource(u),normVertexSrc:s.GetNormalizedTextureFillVertexShaderSource(u)}),s.Create(this,{name:"<generate-mipmap>",src:s._GetMipmapGeneratorFragmentSource(),vertexSrc:s._GetMipmapGeneratorVertexSource()}),s.Create(this,{name:"<point>",src:s._GetPointFragmentSource(!1),srcFragDepth:s._GetPointFragmentSource(!0),vertexSrc:s._GetPointVertexSource()}),s.Create(this,{name:"<tilemap>",src:s._GetTilemapFragmentShaderSource(!1),srcFragDepth:s._GetTilemapFragmentShaderSource(!0)}),s.Create(this,{name:"<fill>",src:s._GetColorFillFragmentShaderSource()}),s.Create(this,{name:"<lineargradient>",src:s._GetLinearGradientFillFragmentShaderSource()}),s.Create(this,{name:"<penumbra>",src:s._GetPenumbraFillFragmentShaderSource()}),s.Create(this,{name:"<hardellipse>",src:s._GetHardEllipseFillFragmentShaderSource()}),s.Create(this,{name:"<hardellipseoutline>",src:s._GetHardEllipseOutlineFragmentShaderSource()}),s.Create(this,{name:"<smoothellipse>",src:s._GetSmoothEllipseFillFragmentShaderSource()}),s.Create(this,{name:"<smoothellipseoutline>",src:s._GetSmoothEllipseOutlineFragmentShaderSource()}),s.Create(this,{name:"<tilerandomization>",src:s.GetTileRandomizationFragmentShaderSource(!1),srcFragDepth:s.GetTileRandomizationFragmentShaderSource(!0)}),s.Create(this,{name:"<smoothline>",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(;r<i;)t[r++]=a,t[r++]=a+1,t[r++]=a+2,t[r++]=a,t[r++]=a+2,t[r++]=a+3,a+=4}_GetDevice(){return this.#i}_GetDefaultVertexModule(){return this._defaultVertexModule}_GetNormalizedVertexModule(){return this._normVertexModule}async CreateShaderProgram(e){const t=await C3.Gfx.WebGPUShaderProgram.Create(this,e);return this._AddShaderProgram(t),t}GetDisplayName(){return"webgpu"}GetSwapChainFormat(){return this._swapChainFormat}_GetDepthBufferFormat(){return"depth24plus-stencil8"}_GetSwapChainTexture(){return this._swapChainTexture}_GetSwapChainTexView(){return this._swapChainTexView}_CanSampleBackbuffer(){return this._canSampleBackbuffer}UsesBackgroundBlending(){return this._usesBackgroundBlending}_GetPipelineLayout(){return this._pipelineLayout}_GetTextureBindGroupLayout(){return this._textureBindGroupLayout}_GetBackTextureBindGroupLayout(){return this._backTextureBindGroupLayout}GetTextureFormat(){return this._textureFormat}GetMaxTextureSize(){return this._maxTextureSize}IsContextLost(){return this._IsFlagSet(65536)}SupportsGPUProfiling(){return this._IsFlagSet(268435456)}SupportsF16(){return this._IsFlagSet(536870912)}IsColorDataF16(){return this._IsFlagSet(1073741824)}GetEstimatedBackBufferMemoryUsage(){const e=this.GetWidth()*this.GetHeight();let t=e*C3.Gfx.WebGPURendererTexture.GetFormatByteSize(this._swapChainFormat);return this.UsesDepthBuffer()&&(t+=e*C3.Gfx.WebGPURendererTexture.GetFormatByteSize(this._GetDepthBufferFormat())),t}GetEstimatedRenderBufferMemoryUsage(){let e=0;for(const t of C3.Gfx.WebGPURenderTarget.allRenderTargets())t.IsBackBuffer()||(e+=t.GetTexture().GetEstimatedMemoryUsage());return e}GetEstimatedTextureMemoryUsage(){let e=0;for(const t of C3.Gfx.WebGPURendererTexture.allTextures())t.IsRenderTarget()||(e+=t.GetEstimatedMemoryUsage());return e}SupportsNPOTTextures(){return!0}GetBufferManager(){return this._bufferManager}SetSize(e,t,r){(this._width!==e||this._height!==t||r)&&(this.EndBatch(),this._width=e,this._height=t,this._viewportWidth=e,this._viewportHeight=t,this._backbufferRenderTarget._CalculateProjection(),this.SetProjectionMatrix(this._backbufferRenderTarget.GetProjectionMatrix()),this._currentRenderTarget&&this._currentRenderTarget._Resize(this._width,this._height),this._IsFlagSet(1048576)&&this._IsFlagSet(134217728)&&this._SetDepthBufferSize(e,t))}_SetDepthBufferSize(e,t){if(this._depthBuffer){if(this._depthBufferWidth===e&&this._depthBufferHeight===t)return;this._depthBuffer["destroy"]()}let r=GPUTextureUsage["RENDER_ATTACHMENT"];this._canSampleDepth&&(r|=GPUTextureUsage["TEXTURE_BINDING"]),this._depthBuffer=this.#i["createTexture"]({"label":"depthbuffer","size":[e,t,1],"format":this._GetDepthBufferFormat(),"usage":r}),this._depthBufferView=this._depthBuffer["createView"]({"label":"depthbufferview"}),this._canSampleDepth&&(this._depthBufferBindGroup=this.#i["createBindGroup"]({"label":"depthbufferbindgroup","layout":this._depthTextureBindGroupLayout,"entries":[{"binding":0,"resource":this._GetSampler({sampling:"nearest"})},{"binding":1,"resource":this._depthBuffer["createView"]({"label":"depthbufferview","aspect":"depth-only"})}]})),this._depthBufferWidth=e,this._depthBufferHeight=t}SetFixedSizeDepthBuffer(e,t){this.UsesDepthBuffer()&&(this._SetFlag(134217728,!1),this._SetDepthBufferSize(e,t))}SetAutoSizeDepthBuffer(){this.UsesDepthBuffer()&&(this._SetFlag(134217728,!0),this._SetDepthBufferSize(this._width,this._height))}SetProjectionMatrix(e){mat4.exactEquals(this._matP,e)||(mat4.copy(this._matP,e),this._UpdateTransformUniform())}SetDefaultRenderTargetProjectionState(){this.SetProjectionMatrix(this._currentRenderTarget.GetProjectionMatrix())}SetModelViewMatrix(e){mat4.exactEquals(this._matMV,e)||(mat4.copy(this._matMV,e),this._UpdateTransformUniform())}ResetDidChangeTransformFlag(){this._SetFlag2(2,!1)}DidChangeTransform(){return this._IsFlagSet2(2)}CreateStaticTexture(e,t){if(e&&!C3.Gfx.WebGPURendererTexture.IsGPUImageCopyExternalImageSource(e)){const t=e.width||e.videoWidth,r=e.height||e.videoHeight,i=C3.CreateCanvas(t,r);i.getContext("2d").drawImage(e,0,0,t,r),e=i}this.EndBatch();const r=C3.New(C3.Gfx.WebGPURendererTexture,this);return r._Create(e,t),r}async CreateStaticTextureAsync(e,t){if(C3.Gfx.WebGPURendererTexture.IsGPUImageCopyExternalImageSource(e))return this.CreateStaticTexture(e,t);{if(!C3.Supports.ImageBitmapOptions)throw new Error("no support for ImageBitmapOptions");const r=await createImageBitmap(e,{"premultiplyAlpha":"premultiply"});return this.CreateStaticTexture(r,t)}}_CreateSampler(e,t,r,i){const a={"addressModeU":e,"addressModeV":t,"magFilter":"nearest","minFilter":"nearest","mipmapFilter":"nearest"};return"bilinear"!==r&&"trilinear"!==r||(a["magFilter"]="linear",a["minFilter"]="linear"),"trilinear"===r&&(a["mipmapFilter"]="linear",i>1&&(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<o;++e){const r=e*p,i=e*c;t.set(new Uint8Array(x,r,c),i)}G=new ImageData(new Uint8ClampedArray(e),h,o)}return m["destroy"](),G}_ConvertTextureFormat(e,t,r){const i=this.#i,a=e.GetWidth(),s=e.GetHeight();if(e._GetFormat()===t)throw new Error("no conversion necessary");e.IsSampled()||C3.NotYetImplemented();const n=i["createTexture"]({"size":[a,s,1],"format":t,"usage":GPUTextureUsage["COPY_SRC"]|GPUTextureUsage["RENDER_ATTACHMENT"]}),u=this._mipmapGeneratorProgram._GetMipmapGeneratorPipeline(t),h=u["getBindGroupLayout"](0),o=this._GetSampler({sampling:"nearest"}),l=e._GetTexture()["createView"]({"baseMipLevel":0,"mipLevelCount":1}),d=n["createView"]({"baseMipLevel":0,"mipLevelCount":1}),f=r["beginRenderPass"]({"colorAttachments":[{"view":d,"loadOp":"clear","clearValue":[0,0,0,0],"storeOp":"store"}]}),_=i["createBindGroup"]({"layout":h,"entries":[{"binding":0,"resource":o},{"binding":1,"resource":l}]});return f["setPipeline"](u),f["setBindGroup"](0,_),f["draw"](4),f["end"](),n}SetDepthEnabled(e){1048576&this._flags&&(e=!!e,!!(2097152&this._flags)!==e&&(4194304&this._flags&&this._MaybeEndRenderPass(),this._SetFlag(2097152,e)))}IsDepthEnabled(){return this._IsFlagSet(2097152)}UsesDepthBuffer(){return this._IsFlagSet(1048576)}SetDepthSamplingEnabled(e){if(!this._canSampleDepth)return;if(e&&this.IsDepthEnabled())throw new Error("depth still enabled");const t=e?this._depthBufferBindGroup:this._nullDepthBufferBindGroup;this._currentDepthTextureBindGroup!==t&&(this._MaybeEndDrawBatch(),this._currentDepthTextureBindGroup=t,this._flags|=512)}Clear(e){this._MaybeEndRenderPass(),this._currentRenderTarget._SetIsAwaitingClear(!0),this._currentRenderTarget._GetClearColor().set(e)}ClearRgba(e,t,r,i){this._MaybeEndRenderPass(),this._currentRenderTarget._SetIsAwaitingClear(!0),this._currentRenderTarget._GetClearColor().setRgba(e,t,r,i)}ClearDepth(){5242880&~this._flags||(this._MaybeEndRenderPass(),this._flags|=8388608)}SetScissorRect(e,t,r,i){e=Math.floor(e),t=Math.floor(t),r=Math.floor(r),i=Math.floor(i),4&this._flags&&this._scissorRect.equalsWH(e,t,r,i)||(this._MaybeEndDrawBatch(),this._flags|=12,this._scissorRect.setWH(e,t,r,i))}RemoveScissorRect(){4&this._flags&&(this._MaybeEndDrawBatch(),this._flags&=-5,this._flags|=8)}GetTextureFillShaderProgram(){return 131072&this._flags?this._spTextureFill:this._spSingleTextureFill}SetTextureFillMode(){this.SetProgram(this.GetTextureFillShaderProgram())}SetProgram(e){if(this._currentProgram!==e){if(e===this._spTextureFill&&!(131072&this._flags))throw new Error("cannot set multitexture fill program when multitexturing not allowed");this._MaybeEndDrawBatch(),this._currentProgram=e,this._currentStateGroup=null,this._flags|=64,this._SetMultiTexturingEnabled(e===this._spTextureFill)}}GetProgram(){return this._currentProgram}_SetMultiTexturingEnabled(e){if(e=!!e,!!(262144&this._flags)===e)return;this._SetFlag(262144,e);const t=null===this._currentTexture?this._nullTexture:this._currentTexture;this._ApplyTextureBindGroup(t,this.#m)}_SetMultiTexturingActive(e){e=!!e,!!(524288&this._flags)!==e&&(this._MaybeEndDrawBatch(),this._SetFlag(524288,e),this._SetFlag(64,!0))}SetNormalizedCoordsProgramVariant(e){e=!!e,!!(1&this._flags2)!==e&&(this._MaybeEndDrawBatch(),this._SetFlag2(1,e),this._flags|=64)}IsNormalizedCoordsProgramVariant(){return this._IsFlagSet2(1)}SetTexture(e,t=0){const r=null===e?this._nullTexture:e,i=0===t?r._GetDefaultSamplingIndex():t-1;e===this._currentTexture&&i===this.#m||(this._currentTexture=e,this.#m=i,this._ApplyTextureBindGroup(r,i))}_ApplyTextureBindGroup(e,t){if(262144&this._flags){const r=e._GetMultiTextureBindGroup(t);if(null!==r)return this._SetTextureBindGroup(r),this._currentMultiTextureIndex=e._GetMultiTextureIndex(),void this._SetMultiTexturingActive(!0)}this._SetTextureBindGroup(e._GetOwnTextureBindGroup(t)),this._currentMultiTextureIndex=0,this._SetMultiTexturingActive(!1)}_SetTextureBindGroup(e){e!==this._currentTextureBindGroup&&(this._MaybeEndDrawBatch(),this._currentTextureBindGroup=e,this._flags|=128)}_OnTextureBindGroupChanged(e){this._currentTexture===e&&(this._MaybeEndDrawBatch(),this._currentTextureBindGroup=e._GetOwnTextureBindGroup(this.#m),this._flags|=128)}_OnMultiTextureBindGroupReleased(e){if(this._currentTextureBindGroup!==e)return;this._MaybeEndDrawBatch();const t=null===this._currentTexture?this._nullTexture:this._currentTexture;this._currentTextureBindGroup=t._GetOwnTextureBindGroup(this.#m),this._currentMultiTextureIndex=0,this._flags|=128}SetBackTexture(e,t=0){const r=null===e?this._nullTexture:e,i=0===t?r._GetDefaultSamplingIndex():t-1;e===this._currentBackTexture&&i===this.#g||(this._currentBackTexture=e,this.#g=i,this._MaybeEndDrawBatch(),this._currentBackTextureBindGroup=r._GetBackTextureBindGroup(i),this._flags|=256)}CopyTextureToTexture(e,t,r,i,a,s){const n=e._GetUsage(),u=t._GetUsage();if(0===(n&GPUTextureUsage["COPY_SRC"]))throw new Error("source texture missing COPY_SRC usage");if(0===(u&GPUTextureUsage["COPY_DST"]))throw new Error("destination texture missing COPY_DST usage");if(e===t)throw new Error("invalid destination");const h=Math.min(e.GetWidth(),t.GetWidth()),o=Math.min(e.GetHeight(),t.GetHeight());a=Math.min(a,h-r),s=Math.min(s,o-i),a<=0||s<=0||(this._MaybeEndRenderPass(),this._commandEncoder["copyTextureToTexture"]({"texture":e._GetTexture(),"origin":[r,i]},{"texture":t._GetTexture(),"origin":[r,i]},[a,s]),this._flags|=32768)}_ClampToSupportedMultisampleValues(e){return 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<f;++t){const f=r[t];f._ShouldCollect(e)?(this._totalBufferCount--,this._totalBufferSize-=f.GetSize(),f.Release(),this._totalReleased++):(r[s]=f,++s)}0===s?this._buffers.delete(t):C3.truncateArray(r,s)}this._DebugLogBufferMap()}UpdateBufferSubData(e,t,r,s,f){const i=this.GetRecyclableBuffer(f),u=i.GetBuffer(),l=u["getMappedRange"](0,f);new Uint8Array(l).set(new Uint8Array(r,s,f)),u["unmap"](),e["copyBufferToBuffer"](u,0,t,s,f),this._recycleAfterSubmit.push(i)}_DebugLogBufferMap(){this._totalCreated=0,this._totalReleased=0,this._totalReturned=0,this._totalRecycled=0}};
}

// ../lib/gfx/webgpu/recyclableBuffer.js
{
const C3=self.C3,GPUBufferUsage=self["GPUBufferUsage"],GPUMapMode=self["GPUMapMode"],assert=self.assert,STATE_AVAILABLE=0,STATE_IN_USE=1,STATE_RECYCLING=2;C3.Gfx.WebGPURecyclableBuffer=class{constructor(e,t){this._bufferManager=e,this._state=1,this._size=t,this._buffer=this.GetRenderer()._GetDevice()["createBuffer"]({"mappedAtCreation":!0,"size":t,"usage":GPUBufferUsage["COPY_SRC"]|GPUBufferUsage["MAP_WRITE"]}),this._recycledFrameNumber=0}GetRenderer(){return this._bufferManager.GetRenderer()}GetState(){return this._state}GetSize(){return this._size}GetBuffer(){return this._buffer}MarkInUse(){this._state=1}async Recycle(){this._state=2;try{await this._buffer["mapAsync"](GPUMapMode["WRITE"])}catch(e){return void console.warn("[WebGPU] Error recycling buffer, assuming device was lost: ",e)}this.GetRenderer().IsContextLost()||(this._state=0,this._recycledFrameNumber=this.GetRenderer().GetFrameNumber(),this._bufferManager._AddRecycledBuffer(this))}Discard(){this._state=0}_ShouldCollect(e){return this._recycledFrameNumber<=e-25}Release(){this._buffer["destroy"](),this._buffer=null,this._bufferManager=null}};
}

// ../lib/gfx/webgpu/customParamsBuffer.js
{
const C3=self.C3,assert=self.assert,GPUBufferUsage=self["GPUBufferUsage"];C3.Gfx.WebGPUEffectCustomParamsBuffer=class{constructor(e){const r=e.GetRenderer();this._shaderProgram=e,this._byteSize=e.GetCustomParametersByteSize(),this._arrayBuffer=new ArrayBuffer(this._byteSize),this._f32arr=new Float32Array(this._arrayBuffer),this._isChanged=!1,this._buffer=r._GetDevice()["createBuffer"]({"size":this._byteSize,"usage":GPUBufferUsage["UNIFORM"]|GPUBufferUsage["COPY_DST"]}),this._bufferBindGroup=r._CreateBufferBindGroup(this._buffer)}Release(){this.GetRenderer()._OnBufferBindGroupDestroyed(this._bufferBindGroup),this.GetRenderer().GetBufferManager()._DestroyAfterSubmit(this._buffer),this._buffer=null,this._shaderProgram=null,this._arrayBuffer=null,this._f32arr=null,this._bufferBindGroup=null}GetRenderer(){return this._shaderProgram.GetRenderer()}GetShaderProgram(){return this._shaderProgram}GetBufferBindGroup(){return this._bufferBindGroup}SetParameterValue(e,r){const t=this._shaderProgram._GetCustomParameterInfo(e),s=t.type,f=t.offset/4,a=this._f32arr;if("color"===s){if(r.equalsRGBF32Array(a,f))return;r.writeRGBToTypedArray(a,f),this._isChanged=!0}else{if("float"!==s&&"percent"!==s)throw new Error(`unexpected shader param type '${s}'`);if(a[f]===Math.fround(r))return;a[f]=r,this._isChanged=!0}}IsChanged(){return this._isChanged}UpdateBuffer(e){this.GetRenderer().GetBufferManager().UpdateBufferSubData(e,this._buffer,this._arrayBuffer,0,this._byteSize),this._isChanged=!1}};
}

// ../lib/gfx/webgpu/shaderProgram.js
{
const C3=self.C3,SIZEOF_F32=4,SIZEOF_F16=2,SIZEOF_U32=4,SIZEOF_VEC2_F32=8,SIZEOF_VEC4_F32=16,SIZEOF_MAT4_F32=64;function UpdateLayoutEndValues(t){for(const e of Object.values(t))e.end=e.offset+e.size}const vertexUniformBufferDeclaration="\nstruct Uniforms {\n\ttransform\t\t: mat4x4<f32>,\n\tpointTexStart\t: vec2<f32>,\n\tpointTexEnd\t\t: vec2<f32>,\n\tzElevation\t\t: f32\n};\n@binding(0) @group(0) var<uniform> uniforms : Uniforms;\n",vubLayout={transform:{offset:0,size:64,end:0},pointTex:{offset:64,size:16,end:0},pointTexStart:{offset:64,size:8,end:0},pointTexEnd:{offset:72,size:8,end:0},zElevation:{offset:80,size:4,end:0}};UpdateLayoutEndValues(vubLayout);const vubSize=vubLayout.zElevation.end,fragmentUniformBufferDeclaration="\nstruct Uniforms {\n\tcolor2\t\t\t\t: vec4<f32>,\n\tpointColor \t\t\t: vec4<f32>,\n\ttileSize\t\t\t: vec2<f32>,\n\ttileSpacing\t\t\t: vec2<f32>,\n\tsrcRectStart\t\t: vec2<f32>,\n\tsrcRectEnd\t\t\t: vec2<f32>,\n\tpixelSize\t\t\t: vec2<f32>,\n\toutlineThickness\t: f32\n};\n@binding(1) @group(0) var<uniform> 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<f32>,\n\tsrcEnd\t\t\t\t: vec2<f32>,\n\tsrcOriginStart\t\t: vec2<f32>,\n\tsrcOriginEnd\t\t: vec2<f32>,\n\tlayoutStart\t\t\t: vec2<f32>,\n\tlayoutEnd\t\t\t: vec2<f32>,\n\tdestStart\t\t\t: vec2<f32>,\n\tdestEnd\t\t\t\t: vec2<f32>,\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<uniform> c3Params : C3Params;\n\nfn c3_srcToNorm(p : vec2<f32>) -> vec2<f32>\n{\n\treturn (p - c3Params.srcStart) / (c3Params.srcEnd - c3Params.srcStart);\n}\n\nfn c3_normToSrc(p : vec2<f32>) -> vec2<f32>\n{\n\treturn fma(p, c3Params.srcEnd - c3Params.srcStart, c3Params.srcStart);\n}\n\nfn c3_clampToSrc(p : vec2<f32>) -> vec2<f32>\n{\n\treturn clamp(p, min(c3Params.srcStart, c3Params.srcEnd), max(c3Params.srcStart, c3Params.srcEnd));\n}\n\nfn c3_srcOriginToNorm(p : vec2<f32>) -> vec2<f32>\n{\n\treturn (p - c3Params.srcOriginStart) / (c3Params.srcOriginEnd - c3Params.srcOriginStart);\n}\n\nfn c3_normToSrcOrigin(p : vec2<f32>) -> vec2<f32>\n{\n\treturn fma(p, c3Params.srcOriginEnd - c3Params.srcOriginStart, c3Params.srcOriginStart);\n}\n\nfn c3_clampToSrcOrigin(p : vec2<f32>) -> vec2<f32>\n{\n\treturn clamp(p, min(c3Params.srcOriginStart, c3Params.srcOriginEnd), max(c3Params.srcOriginStart, c3Params.srcOriginEnd));\n}\n\nfn c3_getLayoutPos(p : vec2<f32>) -> vec2<f32>\n{\n\treturn fma(p - c3Params.srcOriginStart, (c3Params.layoutEnd - c3Params.layoutStart) / (c3Params.srcOriginEnd - c3Params.srcOriginStart), c3Params.layoutStart);\n}\n\nfn c3_srcToDest(p : vec2<f32>) -> vec2<f32>\n{\n\treturn fma(p - c3Params.srcStart, (c3Params.destEnd - c3Params.destStart) / (c3Params.srcEnd - c3Params.srcStart), c3Params.destStart);\n}\n\nfn c3_clampToDest(p : vec2<f32>) -> vec2<f32>\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<f32>,\n\t@location(1) fragUV : vec2<f32>,\n\t@location(2) fragColor : vec4<${t?"f16":"f32"}>,\n\t@builtin(position) fragPos : vec4<f32>\n};\n\nfn c3_getBackUV(fragPos : vec2<f32>, texBack : texture_2d<f32>) -> vec2<f32>\n{\n\treturn fragPos / vec2<f32>(textureDimensions(texBack));\n}\n\nfn c3_getDepthUV(fragPos : vec2<f32>, texDepth : texture_depth_2d) -> vec2<f32>\n{\n\treturn fragPos / vec2<f32>(textureDimensions(texDepth));\n}\n`}const fragmentOutputStructDeclaration="\nstruct FragmentOutput {\n\t@location(0) color : vec4<f32>\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<f32>) -> vec4<f32>\n{\n\treturn vec4<f32>(c.rgb * c.a, c.a);\n}\n\nfn c3_unpremultiply(c : vec4<f32>) -> vec4<f32>\n{\n\tif (c.a == 0.0)\n\t{\n\t\treturn vec4<f32>(0.0);\n\t}\n\t\n\treturn vec4<f32>(c.rgb / c.a, c.a);\n}\n\nfn c3_grayscale(rgb : vec3<f32>) -> f32\n{\n\treturn dot(rgb, vec3<f32>(0.299, 0.587, 0.114));\n}\n\nfn c3_getPixelSize(t : texture_2d<f32>) -> vec2<f32>\n{\n\treturn vec2<f32>(1.0) / vec2<f32>(textureDimensions(t));\n}\n\nfn c3_clamp2(v : vec2<f32>, l : f32, u : f32) -> vec2<f32>\n{\n\treturn clamp(v, vec2<f32>(l), vec2<f32>(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<f32>, y : vec2<f32>) -> vec2<f32>\n{\n\treturn x - y * floor(x / y);\n}\n\nfn c3_RGBtoHSL(color : vec3<f32>) -> vec3<f32>\n{\n\tvar hsl : vec3<f32> = vec3<f32>(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<f32>) -> vec3<f32>\n{\n\tvar rgb : vec3<f32> = vec3<f32>(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"),"<generate-mipmap>"!==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<f32>,\n\t\t\t@location(1) uv : vec2<f32>,\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<f32>,\n\t\t\t@location(0) worldPos : vec3<f32>,\n\t\t\t@location(1) fragUV : vec2<f32>,\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<f32>(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<f32>,\n\t\t\t@location(1) uv : vec2<f32>,\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<f32>,\n\t\t\t@location(0) worldPos : vec3<f32>,\n\t\t\t@location(1) fragUV : vec2<f32>,\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<f32>(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<f32>,\n\t\t\t@location(1) uv : vec2<f32>,\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<f32>,\n\t\t\t@location(0) worldPos : vec3<f32>,\n\t\t\t@location(1) fragUV : vec2<f32>,\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<f32>(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<f32>,\n\t\t\t@location(1) uv : vec2<f32>,\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<f32>,\n\t\t\t@location(0) worldPos : vec3<f32>,\n\t\t\t@location(1) fragUV : vec2<f32>,\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<f32>(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<f32>;\n\t\t@binding(2) @group(1) var sampler1 : sampler;\n\t\t@binding(3) @group(1) var texture1 : texture_2d<f32>;\n\t\t@binding(4) @group(1) var sampler2 : sampler;\n\t\t@binding(5) @group(1) var texture2 : texture_2d<f32>;\n\t\t@binding(6) @group(1) var sampler3 : sampler;\n\t\t@binding(7) @group(1) var texture3 : texture_2d<f32>;\n\t\t@binding(8) @group(1) var sampler4 : sampler;\n\t\t@binding(9) @group(1) var texture4 : texture_2d<f32>;\n\t\t@binding(10) @group(1) var sampler5 : sampler;\n\t\t@binding(11) @group(1) var texture5 : texture_2d<f32>;\n\t\t@binding(12) @group(1) var sampler6 : sampler;\n\t\t@binding(13) @group(1) var texture6 : texture_2d<f32>;\n\t\t@binding(14) @group(1) var sampler7 : sampler;\n\t\t@binding(15) @group(1) var texture7 : texture_2d<f32>;\n\t\t@binding(16) @group(1) var sampler8 : sampler;\n\t\t@binding(17) @group(1) var texture8 : texture_2d<f32>;\n\t\t@binding(18) @group(1) var sampler9 : sampler;\n\t\t@binding(19) @group(1) var texture9 : texture_2d<f32>;\n\t\t@binding(20) @group(1) var sampler10 : sampler;\n\t\t@binding(21) @group(1) var texture10 : texture_2d<f32>;\n\t\t@binding(22) @group(1) var sampler11 : sampler;\n\t\t@binding(23) @group(1) var texture11 : texture_2d<f32>;\n\t\t@binding(24) @group(1) var sampler12 : sampler;\n\t\t@binding(25) @group(1) var texture12 : texture_2d<f32>;\n\t\t@binding(26) @group(1) var sampler13 : sampler;\n\t\t@binding(27) @group(1) var texture13 : texture_2d<f32>;\n\n\t\tstruct FragmentInput {\n\t\t\t@location(1) fragUV : vec2<f32>,\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<f32>":""}\n\t\t};\n\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4<f32>,\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<f32> = input.fragUV.xy;\n\t\t\tvar texIndex : u32 = input.texIndex;\n\t\t\tvar c : vec4<f32>;\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<f32>(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<f32>;\n\n\t\tstruct FragmentInput {\n\t\t\t@location(1) fragUV : vec2<f32>,\n\t\t\t@location(2) fragColor : vec4<${e?"f16":"f32"}>,\n\t\t\t${t?"@builtin(position) fragPos: vec4<f32>":""}\n\t\t};\n\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4<f32>,\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<f32>(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<f32>,\n\t\t\t@location(0) fragUV : vec2<f32>\n\t\t};\n\n\t\t@vertex\n\t\tfn main(input : VertexInput) -> VertexOutput {\n\n\t\t\tvar pos : array<vec2<f32>, 4> = array<vec2<f32>, 4>(\n\t\t\t\tvec2<f32>(-1.0, 1.0),\n\t\t\t\tvec2<f32>(1.0, 1.0),\n\t\t\t\tvec2<f32>(-1.0, -1.0),\n\t\t\t\tvec2<f32>(1.0, -1.0));\n\t\t\t\n\t\t\tvar output : VertexOutput;\n\t\t\tvar p : vec2<f32> = pos[input.VertexIndex];\n\t\t\toutput.Position = vec4<f32>(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<f32>;\n\n\t\tstruct FragmentInput {\n\t\t\t@location(0) fragUV : vec2<f32>\n\t\t};\n\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4<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, vec2<f32>(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":"<mipmap generator>","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<vec4<f32>>\n\t\t};\n\t\t@binding(3) @group(0) var<storage> 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<f32>,\n\t\t\t@location(0) fragUV : vec2<f32>,\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<vec2<f32>, 4> = array<vec2<f32>, 4>(\n\t\t\t\tvec2<f32>(-0.5, -0.5),\n\t\t\t\tvec2<f32>(0.5, -0.5),\n\t\t\t\tvec2<f32>(0.5, 0.5),\n\t\t\t\tvec2<f32>(-0.5, 0.5));\n\t\t\t\n\t\t\tvar output : VertexOutput;\n\t\t\tvar p : vec2<f32> = normPos[input.VertexIndex % u32(4)];\n\t\t\tvar pointData : vec4<f32> = pointBuffer.data[input.VertexIndex / u32(4)];\n\n\t\t\tvar size : f32 = pointData.z;\n\t\t\toutput.Position = uniforms.transform * vec4<f32>(p * size + pointData.xy, uniforms.zElevation, 1.0);\n\t\t\toutput.pointOpacity = pointData.w;\n\n\t\t\tvar pointTexMin : vec2<f32> = min(uniforms.pointTexStart, uniforms.pointTexEnd);\n\t\t\tvar pointTexMax : vec2<f32> = max(uniforms.pointTexStart, uniforms.pointTexEnd);\n\t\t\tvar pn : vec2<f32> = p + vec2<f32>(0.5, 0.5);\n\t\t\tvar pointCoord : vec2<f32> = select(vec2<f32>(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<f32>;\n\n\t\tstruct FragmentInput {\n\t\t\t@location(0) fragUV : vec2<f32>,\n\t\t\t@location(1) pointOpacity : f32,\n\t\t\t@builtin(position) fragPos : vec4<f32>\n\t\t};\n\t\t\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4<f32>,\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<f32>;\n\n\t\t%%FRAGMENTINPUT_STRUCT%%\n\t\t\n\t\tstruct FragmentOutput {\n\t\t\t@location(0) color : vec4<f32>,\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<f32> = vec2<f32>(0.5, 0.5) / vec2<f32>(textureDimensions(texture0));\n\n\t\t\tvar tile : vec2<f32> = floor(input.fragUV);\n\t\t\tvar tex : vec2<f32> = fract(input.fragUV);\n\t\t\tvar tileOrigin : vec2<f32> = uniforms.srcRectStart + tile * (uniforms.tileSize + uniforms.tileSpacing);\n\t\t\tvar lowerBound : vec2<f32> = tileOrigin + halfPixelSize;\n\t\t\tvar upperBound : vec2<f32> = tileOrigin + uniforms.tileSize - halfPixelSize;\n\n\t\t\toutput.color = textureSampleLevel(texture0, sampler0, clamp(tex, lowerBound, upperBound), 0.0) * vec4<f32>(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<f32>;\n\n%%FRAGMENTINPUT_STRUCT%%\n\nstruct FragmentOutput {\n\t@location(0) color : vec4<f32>,\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<f32>, b : vec4<f32>, x : f32) -> vec4<f32>\n{\n\treturn (a + b + (a - b) * cos(x * PI)) / 2.0;\n}\n\nfn randVec3(seed : vec2<f32>) -> vec3<f32>\n{\n\treturn vec3<f32>(\n\t\tfract(sin(dot(seed.xy, vec2<f32>(12.9898,78.233))) * 43758.5453),\n\t\tfract(sin(dot(seed.yx, vec2<f32>(12.9898,-78.233))) * 43758.5453),\n\t\tfract(sin(dot(seed.xy, vec2<f32>(-12.9898,-78.233))) * 43758.5453));\n}\n\nfn sampleTile(tile : vec2<f32>, uv : vec2<f32>, ddx : vec2<f32>, ddy : vec2<f32>) -> vec4<f32>\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<f32>(0.5, 0.5);\n\tvar dp = uv - mid;\n\tdp.x /= aspect;\n\tvar r = vec2<f32>(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<f32>(-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<f32>(0.0,  -1.0), input.fragUV, ddx, ddy);\n\t\t\tvar topLeftTile = sampleTile(tile + vec2<f32>(-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<f32>(0.0,  1.0), input.fragUV, ddx, ddy);\n\t\t\tvar bottomLeftTile = sampleTile(tile + vec2<f32>(-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<f32>(0.0, -1.0), input.fragUV, ddx, ddy);\n\t\t\tvar topRightTile = sampleTile(tile + vec2<f32>(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<f32>(0.0, 1.0), input.fragUV, ddx, ddy);\n\t\t\tvar bottomRightTile = sampleTile(tile + vec2<f32>(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<f32>(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<f32>(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<f32>(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<f32>(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<f32>) -> vec3<f32>\n\t\t{\n\t\t\tvar cutoff : vec3<bool> = (linearRGB < vec3<f32>(0.0031308));\n\t\t\tvar higher : vec3<f32> = vec3<f32>(1.055) * pow(abs(linearRGB), vec3<f32>(1.0/2.4)) - 0.055;\n\t\t\tvar lower : vec3<f32> = linearRGB * 12.92;\n\t\t\treturn select(higher, lower, cutoff);\n\t\t}\n\n\t\tfn toLinear(sRGB : vec3<f32>) -> vec3<f32>\n\t\t{\n\t\t\tvar cutoff : vec3<bool> = (sRGB < vec3<f32>(0.04045));\n\t\t\tvar higher : vec3<f32> = pow(abs((sRGB + 0.055) / 1.055), vec3<f32>(2.4));\n\t\t\tvar lower : vec3<f32> = 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<f32> = mix(toLinear(vec3<f32>(input.fragColor.rgb)), toLinear(uniforms.color2.rgb), vec3<f32>(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<f32>(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<f32>(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<f32> = input.fragUV - 0.5;\n\t\t\tvar diffSq : vec2<f32> = diff * diff;\n\n\t\t\tvar f : f32 = step(diffSq.x + diffSq.y, 0.25);\n\n\t\t\toutput.color = vec4<f32>(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<f32> = input.fragUV - 0.5;\n\t\t\tvar diffSq : vec2<f32> = diff * diff;\n\t\t\tvar distSq : f32 = diffSq.x + diffSq.y;\n\t\t\tvar norm : vec2<f32> = normalize(diff);\n\t\t\tvar halfNorm : vec2<f32> = norm * 0.5;\n\n\t\t\tvar innerF : f32 = step(distSq, 0.25);\n\n\t\t\tvar innerEdge : vec2<f32> = halfNorm - uniforms.pixelSize * norm * uniforms.outlineThickness;\n\t\t\tvar innerEdgeSq : vec2<f32> = innerEdge * innerEdge;\n\t\t\tvar outerF : f32 = step(innerEdgeSq.x + innerEdgeSq.y, distSq);\n\t\t\t\n\t\t\toutput.color = vec4<f32>(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<f32> = input.fragUV - 0.5;\n\t\t\tvar diffSq : vec2<f32> = diff * diff;\n\t\t\tvar norm : vec2<f32> = normalize(diff);\n\t\t\tvar halfNorm : vec2<f32> = norm * 0.5;\n\t\t\tvar halfNormSq : vec2<f32> = halfNorm * halfNorm;\n\n\t\t\tvar innerEdge : vec2<f32> = halfNorm - uniforms.pixelSize * norm;\n\t\t\tvar innerEdgeSq : vec2<f32> = 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<f32>(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<f32> = input.fragUV - 0.5;\n\t\t\tvar diffSq : vec2<f32> = diff * diff;\n\t\t\tvar distSq : f32 = diffSq.x + diffSq.y;\n\t\t\tvar norm : vec2<f32> = normalize(diff);\n\t\t\tvar halfNorm : vec2<f32> = norm * 0.5;\n\t\t\tvar halfNormSq : vec2<f32> = halfNorm * halfNorm;\n\n\t\t\tvar pxNorm : vec2<f32> = uniforms.pixelSize * norm;\n\t\t\tvar innerEdge1 : vec2<f32> = halfNorm - pxNorm;\n\t\t\tvar innerEdge1Sq : vec2<f32> = 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<f32> = halfNorm - pxNorm * uniforms.outlineThickness;\n\t\t\tvar innerEdge2Sq : vec2<f32> = innerEdge2 * innerEdge2;\n\t\t\tvar innerEdge3 : vec2<f32> = halfNorm - pxNorm * (uniforms.outlineThickness + 1.0);\n\t\t\tvar innerEdge3Sq : vec2<f32> = 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<f32>(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<f32>(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;e<u;++e)a.push({"binding":2*e,"resource":i},{"binding":2*e+1,"resource":s});return r["createBindGroup"]({"layout":t._GetTextureBindGroupLayout(),"entries":a})}#n(e){if(this._isRenderTarget&&!this._isSampled)throw new Error("cannot create bind group");const t=this._renderer,r=this._renderer._GetDevice(),i=this._GetSampler(e),s=this._GetTextureView(e);return r["createBindGroup"]({"layout":t._GetBackTextureBindGroupLayout(),"entries":[{"binding":0,"resource":i},{"binding":1,"resource":s}]})}_DeleteGPUResources(){allTextures.delete(this),this._multiTextureGroup&&this._multiTextureGroup.Release(),this._SetMultiTextureAvailable(!1),this._texture["destroy"](),this._texture=null,this.#e=null,this.#t=null,this.#s.fill(null),this.#a.fill(null)}static IsGPUImageCopyExternalImageSource(e){return e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas}static IsCreateImageBitmapDataSource(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||e instanceof ImageData}_GetDataSize(e){return[e.width||e.videoWidth,e.height||e.videoHeight]}_Create(e,t){if(e&&!C3.Gfx.WebGPURendererTexture.IsGPUImageCopyExternalImageSource(e))throw new TypeError("invalid texture source");if(t=Object.assign({},DEFAULT_CREATE_OPTIONS,t),this._texture)throw new Error("already created texture");if(this._isStatic=!0,e){const[t,r]=this._GetDataSize(e);this._width=t,this._height=r}else if(this._width=t.width,this._height=t.height,this._width<=0||this._height<=0)throw new Error("invalid texture size");if(this._InitFromOpts(t),this._isRenderTarget||this._isSampled)throw new Error("static texture cannot be render target");e&&this._UploadImage(e)}_UploadImage(e,t=!0){if(this._isMipMapped)this._GenerateMipmaps(e,this._GetMipLevelCount(),t);else if(this._isFastUpdate)this._CopyImageToMipLevel(this._texture,e,0,t);else{const r=this._renderer._GetDevice(),i=r["createCommandEncoder"](),s=r["createTexture"]({"size":[this._width,this._height,1],"mipLevelCount":1,"format":this._format,"usage":GPUTextureUsage["COPY_SRC"]|GPUTextureUsage["COPY_DST"]|GPUTextureUsage["RENDER_ATTACHMENT"]});this._CopyImageToMipLevel(s,e,0,t),i["copyTextureToTexture"]({"texture":s,"mipLevel":0},{"texture":this._texture,"mipLevel":0},[this._width,this._height,1]),r["queue"]["submit"]([i["finish"]()]),s["destroy"]()}}_CopyImageToMipLevel(e,t,r,i=!0){const[s,a]=this._GetDataSize(t);this._renderer._GetDevice()["queue"]["copyExternalImageToTexture"]({"source":t},{"texture":e,"mipLevel":r,"premultipliedAlpha":!!i},[s,a,1])}_GetMipLevelCount(){return this._isMipMapped?Math.floor(Math.log2(Math.max(this._width,this._height))+1):1}_GenerateMipmaps(e,t,r=!0){const i=this._renderer._GetDevice(),s=i["createTexture"]({"size":[this._width,this._height,1],"mipLevelCount":this._GetMipLevelCount(),"format":this._format,"usage":GPUTextureUsage["COPY_DST"]|GPUTextureUsage["COPY_SRC"]|GPUTextureUsage["TEXTURE_BINDING"]|GPUTextureUsage["RENDER_ATTACHMENT"]}),a=this._renderer._GetMipmapGeneratorPipeline(),u=a["getBindGroupLayout"](0),n=this._renderer._GetSampler({sampling:"bilinear"}),h=i["createCommandEncoder"]();this._CopyImageToMipLevel(s,e,0,r),h["copyTextureToTexture"]({"texture":s,"mipLevel":0},{"texture":this._texture,"mipLevel":0},[this._width,this._height,1]);const l=[];for(let e=0;e<t;++e)l.push(s["createView"]({"baseMipLevel":e,"mipLevelCount":1}));let o=this._width,_=this._height;for(let e=1;e<t;++e){o/=2,_/=2;const t=Math.max(Math.floor(o),1),r=Math.max(Math.floor(_),1),p=h["beginRenderPass"]({"colorAttachments":[{"view":l[e],"loadOp":"clear","clearValue":[0,0,0,0],"storeOp":"store"}]}),d=i["createBindGroup"]({"layout":u,"entries":[{"binding":0,"resource":n},{"binding":1,"resource":l[e-1]}]});p["setPipeline"](a),p["setBindGroup"](0,d),p["draw"](4),p["end"](),h["copyTextureToTexture"]({"texture":s,"mipLevel":e},{"texture":this._texture,"mipLevel":e},[t,r,1])}i["queue"]["submit"]([h["finish"]()]),s["destroy"]()}_CreateDynamic(e,t,r){if(r=Object.assign({},DEFAULT_CREATE_OPTIONS,r),this._texture)throw new Error("already created texture");this._isStatic=!1,this._width=e,this._height=t,this._InitFromOpts(r)}async _Update(e,t){if(!C3.Gfx.WebGPURendererTexture.IsGPUImageCopyExternalImageSource(e)&&!C3.Gfx.WebGPURendererTexture.IsCreateImageBitmapDataSource(e))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");if(t=Object.assign({},UPDATE_DEFAULT_OPTIONS,t),(C3.Gfx.WebGPURendererTexture.IsCreateImageBitmapDataSource(e)||t.flipY||!t.premultiplyAlpha)&&(e=await createImageBitmap(e,{"premultiplyAlpha":t.premultiplyAlpha?"premultiply":"none","imageOrientation":t.flipY?"flipY":"none"}),!this._texture))return;this._renderer.EndBatch();const[r,i]=this._GetDataSize(e);this._width===r&&this._height===i||(this._DeleteGPUResources(),this._width=r,this._height=i,this._CreateGPUResources(),this._renderer._OnTextureBindGroupChanged(this)),this._UploadImage(e,t.premultiplyAlpha)}_Delete(){if(this._refCount>0)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<r;++e)t[e]._SetMultiTextureGroup(this,e);t.length<C3.Gfx.WebGPUMultiTextureGroup.GetMultiTextureLimit()&&this._renderer._SetMultiTextureGroupNonFull(this,!0),allMultiTextureGroups.add(this)}Release(){allMultiTextureGroups.delete(this),this._renderer._SetMultiTextureGroupNonFull(this,!1);for(const e of this._textures)e._ClearMultiTextureGroup();this.DeleteBindGroups(),C3.clearArray(this._textures),this._renderer=null}#t(e){const t=this._renderer,r=t._GetDevice(),u=[],i=C3.Gfx.WebGPUMultiTextureGroup.GetMultiTextureLimit();for(let t=0;t<i;++t){const r=this._textures[Math.min(t,this._textures.length-1)];u.push({"binding":2*t,"resource":r._GetSampler(e)},{"binding":2*t+1,"resource":r._GetTextureView(e)})}return r["createBindGroup"]({"layout":t._GetTextureBindGroupLayout(),"entries":u})}DeleteBindGroups(){for(const e of this.#e)e&&this._renderer._OnMultiTextureBindGroupReleased(e);this.#e.fill(null)}_GetBindGroup(e){return this.#e[e]||(this.#e[e]=this.#t(e)),this.#e[e]}static GetMultiTextureLimit(){return 14}static all(){return allMultiTextureGroups.values()}};
}

// ../lib/gfx/webgpu/renderTarget.js
{
const C3=self.C3,glMatrix=self.glMatrix,vec3=glMatrix.vec3,mat4=glMatrix.mat4,DEFAULT_RENDERTARGET_OPTIONS={defaultSampling:"trilinear",alpha:!0,depth:!1,isSampled:!0,canReadPixels:!1,canUpdate:!1,isDefaultSize:!0,multisampling:0},allRenderTargets=new Set;C3.Gfx.WebGPURenderTarget=class{constructor(e,t){this._renderer=e,this._isBackBuffer=!!t,this._depth=!!t&&e.UsesDepthBuffer(),this._rendererTexture=null,this._isDefaultSize=!0,this._multisampling=0,this._isAwaitingClear=!1,this._clearColor=C3.New(C3.Color),this._projectionMatrix=mat4.create(),this._lastFov=0,this._lastNearZ=0,this._lastFarZ=0,this._isBackBuffer&&(this._rendererTexture=C3.New(C3.Gfx.WebGPURendererTexture,e,!0))}_Create(e,t,r){if(r=Object.assign({},DEFAULT_RENDERTARGET_OPTIONS,r),this._rendererTexture)throw new Error("already created render target");if(this._depth=!!r.depth,this._isDefaultSize=!!r.isDefaultSize,this._multisampling=this._renderer._ClampToSupportedMultisampleValues(r.multisampling),this._multisampling>=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<t;++r)e.has(r)||(u[r]=BigInt(0));return u}};
}

// ../lib/gfx/webgpu/meshData.js
{
const C3=globalThis.C3,assert=globalThis.assert,GPUBufferUsage=globalThis["GPUBufferUsage"],SIZEOF_U16=2,SIZEOF_U32=4,SIZEOF_F16=2,SIZEOF_F32=4;C3.Gfx.MeshDataWebGPU=class extends C3.Gfx.MeshData{#e=null;#t=null;#f=null;#s=null;#r=null;WebGPUInitRenderPassVertexBuffers(e){e["setVertexBuffer"](0,this.#e),e["setVertexBuffer"](1,this.#t),e["setVertexBuffer"](2,this.#s),e["setVertexBuffer"](3,this.#f)}WebGPUInitRenderPassIndexBuffer(e){e["setIndexBuffer"](this.#r,this.IsIndexTypeUint16()?"uint16":"uint32")}CreateGPUResources(){if(super.CreateGPUResources(),this.IsSmall())return;const e=this.GetRenderer()._GetDevice(),t=this.GetDebugLabel(),f=t?"-"+t:"";this.#e=e["createBuffer"]({"label":"positionbuffer"+f,"size":this.positions.byteLength,"usage":GPUBufferUsage["VERTEX"]|GPUBufferUsage["COPY_DST"]}),this.#t=e["createBuffer"]({"label":"texcoordbuffer"+f,"size":this.texCoords.byteLength,"usage":GPUBufferUsage["VERTEX"]|GPUBufferUsage["COPY_DST"]}),this.#f=e["createBuffer"]({"label":"texindexbuffer"+f,"size":this.texIndices.byteLength,"usage":GPUBufferUsage["VERTEX"]|GPUBufferUsage["COPY_DST"]}),this.#s=e["createBuffer"]({"label":"colorbuffer"+f,"size":this.colors.byteLength,"usage":GPUBufferUsage["VERTEX"]|GPUBufferUsage["COPY_DST"]}),this.#r=e["createBuffer"]({"label":"indexbuffer"+f,"size":4*Math.ceil(this.indices.byteLength/4),"usage":GPUBufferUsage["INDEX"]|GPUBufferUsage["COPY_DST"]})}WriteGPUData(e){const t=this.GetRenderer(),f=t._GetDevice()["queue"];let s=this.GetPendingBufferUpdate("positions"),r=s.GetPendingChange();if(r){const e=r.end-r.start,t=12;f["writeBuffer"](this.#e,r.start*t,this.positions.buffer,r.start*t,e*t),s.Reset()}if(s=this.GetPendingBufferUpdate("texCoords"),r=s.GetPendingChange(),r){const e=r.end-r.start,t=8;f["writeBuffer"](this.#t,r.start*t,this.texCoords.buffer,r.start*t,e*t),s.Reset()}if(e&&(s=this.GetPendingBufferUpdate("texIndices"),r=s.GetPendingChange(),r)){const e=r.end-r.start;f["writeBuffer"](this.#f,4*r.start,this.texIndices.buffer,4*r.start,4*e),s.Reset()}if(s=this.GetPendingBufferUpdate("colors"),r=s.GetPendingChange(),r){const e=r.end-r.start,i=4*(t.IsColorDataF16()?2:4);f["writeBuffer"](this.#s,r.start*i,this.colors.buffer,r.start*i,e*i),s.Reset()}if(s=this.GetPendingBufferUpdate("indices"),r=s.GetPendingChange(),r){const e=this.IsIndexTypeUint16()?2:4;let t=r.start*e,i=(r.end-r.start)*e;t%4!=0&&(t-=t%4),i%4!=0&&(i+=4-i%4),f["writeBuffer"](this.#r,t,this.indices.buffer,t,i),s.Reset()}}ReleaseGPUResources(){super.ReleaseGPUResources(),this.#e&&(this.#e["destroy"](),this.#e=null),this.#t&&(this.#t["destroy"](),this.#t=null),this.#f&&(this.#f["destroy"](),this.#f=null),this.#s&&(this.#s["destroy"](),this.#s=null),this.#r&&(this.#r["destroy"](),this.#r=null)}OnContextLost(){this.#e=null,this.#t=null,this.#f=null,this.#s=null,this.#r=null}};
}

// ../lib/gfx/effectCompositor/effectChainManager.js
{
const C3=self.C3,DEFAULT_CTOR_OPTS={getDrawSize:null,getRenderTarget:null,releaseRenderTarget:null,getTime:null,redraw:null};C3.Gfx.EffectChainManager=class{constructor(e){e=Object.assign({},DEFAULT_CTOR_OPTS,e),this._cbGetDrawSize=e.getDrawSize,this._cbGetRenderTarget=e.getRenderTarget,this._cbReleaseRenderTarget=e.releaseRenderTarget,this._cbGetTime=e.getTime,this._cbRedraw=e.redraw,this._webgpuBackTexture=null,this._allEffectChains=new Set}_AddEffectChain(e){this._allEffectChains.add(e)}_RemoveEffectChain(e){this._allEffectChains.delete(e)}OnContextLost(){this._webgpuBackTexture=null;for(const e of this._allEffectChains)e.OnContextLost()}GetDrawSize(e){return this._cbGetDrawSize?this._cbGetDrawSize(e):[e.GetWidth(),e.GetHeight()]}GetRenderTarget(e){return this._cbGetRenderTarget(e)}ReleaseRenderTarget(e,t){this._cbReleaseRenderTarget(e,t)}GetTime(){return this._cbGetTime()}Redraw(e){this._cbRedraw(e)}_GetWebGPUBackTexture(e,t,r){return t=Math.floor(t),r=Math.floor(r),!this._webgpuBackTexture||this._webgpuBackTexture.GetWidth()===t&&this._webgpuBackTexture.GetHeight()===r||(e.DeleteTexture(this._webgpuBackTexture),this._webgpuBackTexture=null),null===this._webgpuBackTexture&&(this._webgpuBackTexture=e.CreateStaticTexture(null,{width:t,height:r,mipMap:!1})),this._webgpuBackTexture}};
}

// ../lib/gfx/effectCompositor/effectChain.js
{
const C3=self.C3,assert=self.assert,glMatrix=self.glMatrix,mat4=glMatrix.mat4,tempRect=C3.New(C3.Rect),tempRect2=C3.New(C3.Rect),tempRect3=C3.New(C3.Rect),tempRect4=C3.New(C3.Rect),tempMat4a=mat4.create(),tempMat4b=mat4.create(),DEFAULT_CTOR_OPTS={drawContent:null,getSourceTextureInfo:null,getShaderParameters:null,invalidateRenderTargets:!1},DEFAULT_BUILDSTEPS_OPTS={indexMap:null,forcePreDraw:!1,forcePostDraw:!1,is3D:!1,isSourceTextureRotated:!1,isRotatedOrNegativeSizeInstance:!1,useFullSurface:!1};C3.Gfx.EffectChain=class{constructor(e,t){t=Object.assign({},DEFAULT_CTOR_OPTS,t),this._manager=e,this._cbDrawContent=t.drawContent,this._cbGetSourceTextureInfo=t.getSourceTextureInfo,this._cbGetShaderParameters=t.getShaderParameters,this._cbDrawContentHook=null,this._shaderProgramList=[],this._shaderProgramIndices=[],this._steps=[],this._needsRebuild=!1,this._blendMode=0,this._isAnyShaderAnimated=!1,this._isAnyShaderDepthSampling=!1,this._isAnyShaderBackgroundBlending=!1,this._isAnyShaderCrossSampling=!1,this._isAnyIsSrcTexRotated=!1,this._useCopyTextureBackgroundSampling=!1,this._didChangeTransform=!1,this._depthEnabledAtStart=!1,this._coplanarColorPassAtStart=!1,this._canUseFastPath=!1,this._useFullSurface=!1,this._isSourceTextureRotated=!1,this._numTempSurfacesRequired=0,this._renderTargets=[null,null,null],this._invalidateRenderTargets=!!t.invalidateRenderTargets,this._boxExtendHorizontal=0,this._boxExtendVertical=0,this._drawWidth=0,this._drawHeight=0,this._contentObject=null,this._contextObject=null,this._layoutRect=C3.New(C3.Rect),this._drawSurfaceRect=C3.New(C3.Rect),this._rcTexOriginal=C3.New(C3.Rect),this._rcTexBounce=C3.New(C3.Rect),this._rcTexDest=C3.New(C3.Rect),this._devicePixelRatio=1,this._layerScale=1,this._layerAngle=0,this._time=0,this._destRenderTarget=null,this._backTex=null,this._compositOffX=0,this._compositOffY=0,this._compositRtWidth=0,this._compositRtHeight=0,this._updateOwnProjection=!1,this._projectionMatrix=mat4.create(),this._modelViewMatrix=mat4.create(),this._manager._AddEffectChain(this)}Release(){this._manager._RemoveEffectChain(this),C3.clearArray(this._steps),C3.clearArray(this._shaderProgramList),C3.clearArray(this._shaderProgramIndices),this._contentObject=null,this._contextObject=null,this._cbDrawContent=null,this._cbGetSourceTextureInfo=null,this._cbGetShaderParameters=null}OnContextLost(){this._needsRebuild=!0,C3.clearArray(this._steps),C3.clearArray(this._shaderProgramList),C3.clearArray(this._shaderProgramIndices)}NeedsRebuild(){return this._needsRebuild}BuildSteps(e,t){if(t=Object.assign({},DEFAULT_BUILDSTEPS_OPTS,t),C3.clearArray(this._steps),this._boxExtendHorizontal=0,this._boxExtendVertical=0,this._isAnyShaderAnimated=!1,this._isAnyShaderDepthSampling=!1,this._isAnyShaderBackgroundBlending=!1,this._isAnyShaderCrossSampling=!1,this._isAnyIsSrcTexRotated=!1,this._useCopyTextureBackgroundSampling=!1,this._numTempSurfacesRequired=0,this._isSourceTextureRotated=!!t.isSourceTextureRotated,this._useFullSurface=!!t.useFullSurface,this._needsRebuild=!1,C3.shallowAssignArray(this._shaderProgramList,e),0===e.length)return;if(t.indexMap){if(t.indexMap.length!==e.length)throw new Error("incorrect indexMap length");C3.shallowAssignArray(this._shaderProgramIndices,t.indexMap)}else{C3.clearArray(this._shaderProgramIndices);for(let t=0,r=e.length;t<r;++t)this._shaderProgramIndices.push(t)}for(const t of e)this._boxExtendHorizontal+=t.GetBoxExtendHorizontal(),this._boxExtendVertical+=t.GetBoxExtendVertical(),t.IsAnimated()&&(this._isAnyShaderAnimated=!0),t.UsesDepth()&&(this._isAnyShaderDepthSampling=!0),t.BlendsBackground()&&(this._isAnyShaderBackgroundBlending=!0),t.UsesCrossSampling()&&(this._isAnyShaderCrossSampling=!0),t.UsesIsSrcTexRotated()&&(this._isAnyIsSrcTexRotated=!0);this._useCopyTextureBackgroundSampling=this._ShouldUseCopyTextureBackgroundSampling(e[0].GetRenderer());const r=this._ShouldPreDraw(e[0],t),s=this._ShouldPostDraw(e.at(-1),t);if(1===e.length&&!r&&!s)return void(this._canUseFastPath=!0);this._canUseFastPath=!1;let i=0;r&&(this._numTempSurfacesRequired=1,this._steps.push(C3.New(C3.Gfx.EffectChain.Step.PreDraw,this,-1,1)),i=1);for(let t=0,a=e.length;t<a;++t)if(0!==t||r){let e=1===i?2:1;t!==a-1||s||(e=0),this._numTempSurfacesRequired=Math.max(this._numTempSurfacesRequired,e),this._steps.push(C3.New(C3.Gfx.EffectChain.Step.Bounce,this,i,e,t)),i=e}else this._numTempSurfacesRequired=1,this._steps.push(C3.New(C3.Gfx.EffectChain.Step.FirstBounce,this,-1,1,t)),i=1;s&&this._steps.push(C3.New(C3.Gfx.EffectChain.Step.PostDraw,this,i,0))}_ShouldPreDraw(e,t){return!!(t.forcePreDraw||e.MustPreDraw()||t.is3D&&!e.Supports3DDirectRendering()||e.UsesDepth()&&!this._useFullSurface||0!==this._boxExtendHorizontal||0!==this._boxExtendVertical)||(e.GetRenderer().IsWebGL()?e.BlendsBackground()&&(t.isRotatedOrNegativeSizeInstance||t.isSourceTextureRotated)||e.UsesAnySrcRectOrPixelSize()&&t.isSourceTextureRotated:e.BlendsBackground()&&!this._useCopyTextureBackgroundSampling&&t.isRotatedOrNegativeSizeInstance)}_ShouldPostDraw(e,t){return!!t.forcePostDraw||(e.GetRenderer().IsWebGL()?e.BlendsBackground()||e.UsesCrossSampling():(e.BlendsBackground()||e.UsesCrossSampling())&&this._UseRenderTargetBackgroundSampling())}_ShouldUseCopyTextureBackgroundSampling(e){return e.IsWebGPU()&&this._isAnyShaderBackgroundBlending&&!this._isAnyShaderCrossSampling}Render(e,t,r){e.IsWebGPU()&&null===t&&(t=e.GetBackbufferRenderTarget()),this._destRenderTarget=t,this._contentObject=r.contentObject||null,this._contextObject=r.contextObject||null,this._blendMode=r.blendMode||0,this._devicePixelRatio=r.devicePixelRatio||1,this._layerScale=r.layerScale||1,this._layerAngle=r.layerAngle||0,this._time="number"==typeof r.time?r.time:this._manager.GetTime(),this._didChangeTransform=!1,e.ResetDidChangeTransformFlag(),this._isAnyShaderAnimated&&this._Redraw();let s=!1;if(this._UseCopyTextureBackgroundSampling()&&(this._CalculateDrawSizeAndRectangles(e,r),s=!0,this._backTex=this._manager._GetWebGPUBackTexture(e,this._drawWidth,this._drawHeight),tempRect.copy(this._drawSurfaceRect),tempRect.roundOuter(),e.IsWebGPU()&&e._MaybeDoPendingClearRenderPass(this._destRenderTarget),this._backTex.SetDefaultSampling(this._destRenderTarget.GetTexture().GetDefaultSampling()),e.CopyTextureToTexture(this._destRenderTarget.GetTexture(),this._backTex,tempRect.getLeft(),tempRect.getTop(),tempRect.width(),tempRect.height())),this._canUseFastPath)this._Render_FastPath(e,r);else if(s||this._CalculateDrawSizeAndRectangles(e,r),0!==this._rcTexOriginal.width()||0!==this._rcTexOriginal.height()){e.SetAlphaBlend(),e.ResetCullState(),e.ResetColor(),e.SetBaseZ(0),e.SetCurrentZ(0),this._cbDrawContentHook=r.drawContentHook||null,this._compositOffX=r.compositOffX||0,this._compositOffY=r.compositOffY||0,this._compositRtWidth=r.compositRtWidth||0,this._compositRtHeight=r.compositRtHeight||0,this._updateOwnProjection=!!r.updateOwnProjection,this._OnBeforeStartEffectChain(e),this._renderTargets[0]=t,this._renderTargets[1]=this._numTempSurfacesRequired>=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.length<n.GetFunctionParameterCount())throw new Error(`not enough function parameters passed for '${e}' (${t.length} passed, ${n.GetFunctionParameterCount()} expected)`);const i=n.GetEventBlock();let o=i.GetSolModifiersIncludingParents();const a=r.GetCurrentEvent();if(a){o=o.slice(0);const e=new Set(o);for(const t of a.GetSolModifiersIncludingParents())e.has(t)||(o.push(t),e.add(t));for(const t of r.GetDynamicSolModifiersSet())e.has(t)||(o.push(t),e.add(t))}return i.RunAsExpressionOrJSFunctionCall(o,n.IsCopyPicked(),n.GetReturnType(),n.GetDefaultReturnValue(),null,...t)}setReturnValue(e){const t=runtime.GetEventStack().GetCurrentExpFuncStackFrame();if(!t)throw new Error("not in a function which returns a value");switch(t.GetFunctionReturnType()){case 1:"number"==typeof e&&t.SetFunctionReturnValue(e);break;case 2:"string"==typeof e&&t.SetFunctionReturnValue(e);break;case 3:"number"!=typeof e&&"string"!=typeof e||t.SetFunctionReturnValue(e)}}signal(e){C3X.RequireString(e),runtime.GetEventSheetManager().Signal(e)}waitForSignal(e){return C3X.RequireString(e),runtime.GetEventSheetManager().WaitForSignal(e)}getViewportSize(){return[runtime.GetOriginalViewportWidth(),runtime.GetOriginalViewportHeight()]}get isSuspended(){return runtime.IsSuspended()}get dt(){return runtime.GetDt()}get dtRaw(){return runtime.GetDtRaw()}get gameTime(){return runtime.GetGameTime()}get tickCount(){return runtime.GetTickCount()}get wallTime(){return runtime.GetWallTime()}get timeScale(){return runtime.GetTimeScale()}set timeScale(e){C3X.RequireFiniteNumber(e),runtime.SetTimeScale(e)}get fps(){return this._logDeprecationWarning("IRuntime.fps","IRuntime property 'fps' is deprecated. Use 'framesPerSecond' instead."),runtime.GetFramesPerSecond()}get framesPerSecond(){return runtime.GetFramesPerSecond()}get ticksPerSecond(){return runtime.GetTicksPerSecond()}get cpuUtilisation(){return runtime.GetMainThreadTime()}get gpuUtilisation(){return runtime.GetGPUUtilisation()}get framerateMode(){return runtime.GetFramerateMode()}set framerateMode(e){if(!VALID_FRAMERATE_MODES.has(e))throw new Error("invalid framerate mode");runtime._SetFramerateMode(e)}get fixedFramerate(){return runtime.GetFixedFramerate()}set fixedFramerate(e){C3X.RequireFiniteNumber(e),runtime._SetFixedFramerate(e)}get minDt(){return runtime.GetMinDt()}set minDt(e){C3X.RequireFiniteNumber(e),runtime.SetMinDt(e)}get maxDt(){return runtime.GetMaxDt()}set maxDt(e){runtime.SetMaxDt(e)}set isPixelRoundingEnabled(e){runtime.SetPixelRoundingEnabled(!!e)}get isPixelRoundingEnabled(){return runtime.IsPixelRoundingEnabled()}set sampling(e){runtime.SetSamplingMode(e)}get sampling(){return runtime.GetSamplingMode()}set anisotropicFiltering(e){const t=ANISOTROPIC_FILTERING_MODES.get(e);if("number"!=typeof t)throw new Error("invalid mode");const r=runtime.GetCanvasManager();r&&r.SetAnisotropicFiltering(t)}get anisotropicFiltering(){const e=runtime.GetCanvasManager(),t=e?e.GetTextureAnisotropy():1;for(const[e,r]of ANISOTROPIC_FILTERING_MODES)if(r===t&&"auto"!==e)return e;throw new Error("invalid mode")}get loadingProgress(){return runtime.GetAssetManager().GetLoadProgress()}get imageLoadingProgress(){return runtime.GetAssetManager().GetImageLoadProgress()}random(){return runtime.Random()}get layout(){const e=runtime.GetMainRunningLayout();if(!e)throw new Error("no layout is running - make sure a layout is loaded before accessing");return e.GetILayout()}getLayout(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");return r.GetILayout()}getAllLayouts(){return runtime.GetLayoutManager().GetAllLayouts().map(e=>e.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;e<t;++e){const t=tempInstances[e],i=r.GetLayerByIndex(tempZOrderList[e][0]),o=tempZOrderList[e][1],a=i._GetInstances();a[o]!==t&&(a[o]=t,t.GetWorldInfo()._SetLayer(i,!0),i.SetZIndicesChanged(t),n=!0)}n&&runtime.UpdateRender(),C3.clearArray(tempZOrderList),C3.clearArray(tempInstances)}destroyMultiple(e){for(const t of e){const e=runtime._UnwrapIWorldInstance(t);runtime.DestroyInstance(e)}runtime.GetEventSheetManager().IsInEventEngine()||runtime.GetLayoutManager().IsEndingLayout()||runtime.GetEventSheetManager().IsFlushingBlocked()||runtime.FlushPendingInstances()}saveToSlot(e){return C3X.RequireString(e),runtime.SaveToSlot(e)}saveToJSONString(){return runtime.SaveToJsonString()}loadFromSlot(e){return C3X.RequireString(e),runtime.LoadFromSlot(e)}loadFromJSONString(e){return C3X.RequireString(e),runtime.LoadFromJsonString(e)}async createWorker(e,t){this._logDeprecationWarning("IRuntime.createWorker","IRuntime method 'createWorker' is deprecated. All modern browsers now support nested workers so this method is no longer needed.");const r=new MessageChannel,n=r.port1,i=r.port2;return await runtime.PostComponentMessageToDOMAsync("runtime","script-create-worker",{"url":e,"opts":t,"port2":i},[i]),n}alert(e){return runtime.PostComponentMessageToDOMAsync("runtime","alert",{"message":e+(runtime.IsInWorker()?" [via Web Worker]":"")})}getHTMLLayer(e){return C3X.RequireFiniteNumber(e),runtime._GetHTMLLayerWrapElement(e)}addLoadPromise(e){this._logDeprecationWarning("IRuntime.addLoadPromise","IRuntime method 'addLoadPromise' is deprecated. Use 'runtime.sdk.addLoadPromise' instead."),runtime.AddLoadPromise(e)}async saveCanvasImage(e,t,r){C3X.RequireOptionalString(e),C3X.RequireOptionalNumber(t),C3X.RequireOptionalInstanceOf(r,DOMRect),r||(r=new DOMRect(0,0,0,0));const n=runtime.GetCanvasManager();if(!n)return;runtime.UpdateRender();const i=await n.SnapshotCanvas(e||"image/png",t,r.x,r.y,r.width,r.height);return await runtime.TriggerAsync(C3.Plugins.System.Cnds.OnCanvasSnapshot,null),i}_logDeprecationWarning(e,t){loggedDeprecationIds.has(e)||(console.warn("[Deprecated API] "+t),loggedDeprecationIds.add(e))}};
}

// interfaces/other/IAssetManager.js
{
const C3=self.C3,C3X=self.C3X;let assetManager=null;self.IAssetManager=class{constructor(e){assetManager=e,Object.defineProperties(this,{runtime:{value:assetManager.GetRuntime().GetIRuntime(),writable:!1}})}get isWebMOpusSupported(){return this.runtime._logDeprecationWarning("IAssetManager.isWebMOpusSupported","IAssetManager 'isWebMOpusSupported' property is deprecated. It is always true."),!0}loadImageAsset(e){const t=self.IImageInfo._Unwrap(e);if(!t)throw new Error("invalid IImageInfo");t.LoadAsset(assetManager.GetRuntime())}fetchText(e){return assetManager.FetchText(e)}fetchJson(e){return assetManager.FetchJson(e)}fetchBlob(e){return assetManager.FetchBlob(e)}fetchArrayBuffer(e){return assetManager.FetchArrayBuffer(e)}getProjectFileUrl(e){return Promise.resolve(assetManager.GetProjectFileUrl(e))}getMediaFileUrl(e){return assetManager.GetMediaFileUrl(e)}get mediaFolder(){return assetManager.GetMediaSubfolder()}async decodeWebMOpus(e,t){throw new Error("decodeWebMOpus() is no longer supported - use Web Audio's decodeAudioData() directly as all supported platforms now support WebM Opus")}loadScripts(...e){return assetManager.LoadScripts(...e)}compileWebAssembly(e){return assetManager.CompileWebAssembly(e)}loadStyleSheet(e){return assetManager.LoadStyleSheet(e)}get projectFileList(){return assetManager.GetExportedFileList()}};
}

// interfaces/other/ICollisionEngine.js
{
const C3=self.C3,C3X=self.C3X;let collisionEngine=null;self.ICollisionEngine=class{constructor(n){collisionEngine=n,Object.defineProperties(this,{runtime:{value:collisionEngine.GetRuntime(),writable:!1}})}testOverlap(n,e){const l=collisionEngine.GetRuntime(),i=l._UnwrapIWorldInstance(n),t=l._UnwrapIWorldInstance(e);return collisionEngine.TestOverlap(i,t)}testOverlapAny(n,e){const l=collisionEngine.GetRuntime(),i=l._UnwrapIWorldInstance(n);for(const n of e){const e=l._UnwrapIWorldInstance(n);if(collisionEngine.TestOverlap(i,e))return n}return null}testOverlapSolid(n){const e=collisionEngine.GetRuntime()._UnwrapIWorldInstance(n),l=collisionEngine.TestOverlapSolid(e);return l?l.GetInterfaceClass():null}setCollisionCellSize(n,e){if(C3X.RequireFiniteNumber(n),C3X.RequireFiniteNumber(e),n=Math.floor(n),e=Math.floor(e),n<=0||e<=0)throw new Error("invalid cell size");collisionEngine.SetCollisionCellSize(n,e)}getCollisionCellSize(){return collisionEngine.GetCollisionCellSize()}getCollisionCandidates(n,e){const l=collisionEngine.GetRuntime();let i;i=Array.isArray(n)?n.map(n=>l._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.length<a.GetFunctionParameterCount())throw new Error(`not enough function parameters passed for '${this.name}' custom action '${e}' (${n.length} passed, ${a.GetFunctionParameterCount()} expected)`);const c=a.GetEventBlock();let o=c.GetSolModifiersIncludingParents();const l=r.GetCurrentEvent();if(l){o=o.slice(0);const e=new Set(o);for(const t of l.GetSolModifiersIncludingParents())e.has(t)||(o.push(t),e.add(t));for(const t of r.GetDynamicSolModifiersSet())e.has(t)||(o.push(t),e.add(t))}if(s.IsFamily()&&a.HasCustomACEOverrides()){const r=new Map,l=[];for(const n of t){const t=i._UnwrapIInstance(n),s=t.GetObjectClass();if(s.HasOwnCustomActionByName(e)){const e=r.get(s);Array.isArray(e)?e.push(t):r.set(s,[t])}else l.push(t)}const u=[];if(l.length>0){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;e<i;++e){const i=new self.IEffectInstance(r,e);t.push(i),t[i.name]=i}Object.defineProperties(this,{runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},name:{value:e.GetName(),writable:!1},index:{value:e.GetIndex(),writable:!1},effects:{value:t,writable:!1}})}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)}get width(){return this.#e.GetWidth()}set width(e){C3X.RequireFiniteNumber(e),this.#e.SetWidth(e)}get height(){return this.#e.GetHeight()}set height(e){C3X.RequireFiniteNumber(e),this.#e.SetHeight(e)}setSize(e,t){C3X.RequireFiniteNumber(e),C3X.RequireFiniteNumber(t);const r=this.#e;r.SetWidth(e),r.SetHeight(t)}getSize(){const e=this.#e;return[e.GetWidth(),e.GetHeight()]}set scale(e){C3X.RequireFiniteNumber(e),this.#e.SetScale(e)}get scale(){return this.#e.GetScale()}set angle(e){C3X.RequireFiniteNumber(e),this.#e.SetAngle(e)}get angle(){return this.#e.GetAngle()}set scrollX(e){C3X.RequireNumber(e),this.#e.SetScrollX(e)}get scrollX(){return this.#e.GetScrollX()}set scrollY(e){C3X.RequireNumber(e),this.#e.SetScrollY(e)}get scrollY(){return this.#e.GetScrollY()}set sampling(e){this.#e.SetSamplingMode(e)}get sampling(){return this.#e.GetSamplingMode()}get activeSampling(){return this.#e.GetActiveSampling()}scrollTo(e,t){C3X.RequireNumber(e),C3X.RequireNumber(t);const r=this.#e;r.SetScrollX(e),r.SetScrollY(t)}getScrollPosition(){const e=this.#e;return[e.GetScrollX(),e.GetScrollY()]}get isUnboundedScrolling(){return this.#e.IsUnboundedScrolling()}getLayer(e){const t=this.#e;let r=null;if("number"!=typeof e&&"string"!=typeof e)throw new TypeError("expected string or number");return r=t.GetLayer(e),r?r.GetILayer():null}getAllLayers(){return this.#e.GetLayers().map(e=>e.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;e<i;++e){const i=new self.IEffectInstance(r,e);t.push(i),t[i.name]=i}Object.defineProperties(this,{runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},name:{value:e.GetName(),writable:!1},layout:{value:e.GetLayout().GetILayout(),writable:!1},effects:{value:t,writable:!1}}),e.GetRuntime()._MapScriptInterface(this,e)}addEventListener(e,t){this.#e.UserScriptDispatcher().addEventListener(e,t)}removeEventListener(e,t){this.#e.UserScriptDispatcher().removeEventListener(e,t)}get parentLayer(){const e=this.#e.GetParentLayer();return e?e.GetILayer():null}*parentLayers(){for(const e of this.#e.parentLayers())yield e.GetILayer()}*subLayers(){for(const e of this.#e.GetSubLayers())yield e.GetILayer()}*allSubLayers(){for(const e of this.#e.GetSubLayers())for(const t of e.selfAndAllSubLayers())yield t.GetILayer()}get index(){return this.#e.GetIndex()}get isVisible(){return this.#e._IsVisibleFlagSet()}set isVisible(e){this.#e.SetVisible(e)}get isSelfAndParentsVisible(){return this.#e.IsVisible()}get isInteractive(){return this.#e.IsInteractive()}set isInteractive(e){this.#e.SetInteractive(e)}get isHTMLElementsLayer(){return this.#e.IsHTMLElementsLayer()}set isHTMLElementsLayer(e){this.#e.SetIsHTMLElementsLayer(!!e)}get isSelfAndParentsInteractive(){return this.#e.IsSelfAndParentsInteractive()}get opacity(){return this.#e.GetOpacity()}set opacity(e){e=C3.clamp(+e,0,1),isNaN(e)||this.#e.SetOpacity(e)}set scale(e){C3X.RequireFiniteNumber(e),this.#e.SetOwnScale(e)}get scale(){return this.#e.GetOwnScale()}set scaleRate(e){C3X.RequireFiniteNumber(e),this.#e.SetScaleRate(e)}get scaleRate(){return this.#e.GetScaleRate()}set angle(e){C3X.RequireFiniteNumber(e),this.#e.SetAngle(e)}get angle(){return this.#e.GetOwnAngle()}set parallaxX(e){C3X.RequireFiniteNumber(e),this.#e.SetParallaxX(e)}get parallaxX(){return this.#e.GetParallaxX()}set parallaxY(e){C3X.RequireFiniteNumber(e),this.#e.SetParallaxY(e)}get parallaxY(){return this.#e.GetParallaxY()}set zElevation(e){C3X.RequireFiniteNumber(e),this.#e.SetZElevation(e)}get zElevation(){return this.#e.GetZElevation()}set renderingMode(e){if(!VALID_RENDERING_MODES.has(e))throw TypeError("invalid rendering mode");this.#e.SetRenderAs3D("3d"===e)}get renderingMode(){return this.#e.IsRenderAs3D()?"3d":"2d"}set isTransparent(e){this.#e.SetTransparent(e)}get isTransparent(){return this.#e.IsTransparent()}set isForceOwnTexture(e){this.#e.SetForceOwnTexture(e)}get isForceOwnTexture(){return this.#e.IsForceOwnTexture()}set blendMode(e){C3X.RequireString(e);const t=BLEND_MODE_TO_INDEX.get(e);if("number"!=typeof t)throw new Error("invalid blend mode");this.#e.SetBlendMode(t)}get blendMode(){return INDEX_TO_BLEND_MODE.get(this.#e.GetBlendMode())}set backgroundColor(e){if(C3X.RequireArray(e),e.length<3)throw new Error("expected 3 elements");tempColor.setRgb(e[0],e[1],e[2]);const t=this.#e,r=t.GetBackgroundColor();r.equalsIgnoringAlpha(tempColor)||(r.copyRgb(tempColor),t.GetRuntime().UpdateRender())}get backgroundColor(){const e=this.#e.GetBackgroundColor();return[e.getR(),e.getG(),e.getB()]}set sampling(e){this.#e.SetSamplingMode(e)}get sampling(){return this.#e.GetSamplingMode()}get activeSampling(){return this.#e.GetActiveSampling()}set scrollX(e){C3X.RequireNumber(e);const t=this.#e;t.SetOwnScrollPositionEnabled(!0),t.SetScrollX(e)}get scrollX(){return this.#e.GetScrollX()}set scrollY(e){C3X.RequireNumber(e);const t=this.#e;t.SetOwnScrollPositionEnabled(!0),t.SetScrollY(e)}get scrollY(){return this.#e.GetScrollY()}scrollTo(e,t){C3X.RequireNumber(e),C3X.RequireNumber(t);const r=this.#e;r.SetOwnScrollPositionEnabled(!0),r.SetScrollX(e),r.SetScrollY(t)}getScrollPosition(){const e=this.#e;return[e.GetScrollX(),e.GetScrollY()]}restoreScrollPosition(){this.#e.SetOwnScrollPositionEnabled(!1)}getViewport(){return this.#e.GetViewport().toDOMRect()}cssPxToLayer(e,t,r=0){C3X.RequireNumber(e),C3X.RequireNumber(t),C3X.RequireNumber(r);const i=this.#e,a=i.GetRuntime();return i.CanvasCssToLayer(e-a.GetCanvasClientX(),t-a.GetCanvasClientY(),r)}layerToCssPx(e,t,r=0){C3X.RequireNumber(e),C3X.RequireNumber(t),C3X.RequireNumber(r);const i=this.#e,a=i.GetRuntime(),[s,n]=i.LayerToCanvasCss(e,t,r);return[s+a.GetCanvasClientX(),n+a.GetCanvasClientY()]}drawSurfaceToLayer(e,t,r=0){return C3X.RequireNumber(e),C3X.RequireNumber(t),C3X.RequireNumber(r),this.#e.DrawSurfaceToLayer(e,t,r)}layerToDrawSurface(e,t,r=0){return C3X.RequireNumber(e),C3X.RequireNumber(t),C3X.RequireNumber(r),this.#e.LayerToDrawSurface(e,t,r)}get renderScale(){return this.#e.GetRenderScale()}};
}

// interfaces/objects/IInstance.js
{
const C3=self.C3,C3X=self.C3X,dispatchers=new WeakMap,internalApiToken=C3._GetInternalAPIToken();function GetDispatcher(e){let t=dispatchers.get(e);return t||(t=C3.New(C3.Event.Dispatcher),dispatchers.set(e,t),t)}self.IInstance=class{#e;constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e;const t={runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},objectType:{value:e.GetObjectClass().GetIObjectClass(),writable:!1},plugin:{value:e.GetPlugin().GetIPlugin(),writable:!1}};e._GetInstVarsScriptDescriptor(t),e._GetBehaviorsScriptDescriptor(t),Object.defineProperties(this,t),e.GetRuntime()._MapScriptInterface(this,e)}static _GetInitInst(){return C3.AddonManager._GetInitObject()}_release(){const e=dispatchers.get(this);e&&(e.Release(),dispatchers.delete(this))}addEventListener(e,t,i){C3X.RequireString(e),C3X.RequireFunction(t),GetDispatcher(this).addEventListener(e,t,i)}removeEventListener(e,t,i){C3X.RequireString(e),C3X.RequireFunction(t),GetDispatcher(this).removeEventListener(e,t,i)}dispatchEvent(e){GetDispatcher(this).dispatchEvent(e)}destroy(){const e=this.#e,t=e.GetRuntime();t.DestroyInstance(e),t.GetEventSheetManager().IsInEventEngine()||t.GetLayoutManager().IsEndingLayout()||t.GetEventSheetManager().IsFlushingBlocked()||t.FlushPendingInstances()}getOtherContainerInstances(){const e=this.#e.GetSiblings();return e?e.map(e=>e.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;e<t;++e){const t=new self.IEffectInstance(r,e);n.push(t),n[t.name]=t}}const s={effects:{value:n,writable:!1}};Object.defineProperties(this,s)}get layout(){return this.#e.GetLayout().GetILayout()}get layer(){return this.#e.GetLayer().GetILayer()}get x(){return this.#e.GetX()}set x(t){t=+t;const e=this.#e;isNaN(t)||e.GetX()===t||(e.SetX(t),e.SetBboxChanged())}get y(){return this.#e.GetY()}set y(t){t=+t;const e=this.#e;isNaN(t)||e.GetY()===t||(e.SetY(t),e.SetBboxChanged())}get z(){return this.#e.GetZ()}set z(t){t=+t;this.#t;const e=this.#e;isNaN(t)||e.GetZ()===t||(e.SetZ(t),e.SetBboxChanged())}get totalZ(){return this.#e.GetTotalZ()}get zElevation(){return this.runtime._logDeprecationWarning("IWorldInstance.zElevation","IWorldInstance 'zElevation' property is deprecated. Use 'z' instead."),this.z}set zElevation(t){this.runtime._logDeprecationWarning("IWorldInstance.zElevation","IWorldInstance 'zElevation' property is deprecated. Use 'z' instead."),this.z=t}get totalZElevation(){return this.runtime._logDeprecationWarning("IWorldInstance.totalZElevation","IWorldInstance 'totalZElevation' property is deprecated. Use 'totalZ' instead."),this.totalZ}setPosition(t,e){t=+t,e=+e;const i=this.#e;isNaN(t)||isNaN(e)||i.EqualsXY(t,e)||(i.SetXY(t,e),i.SetBboxChanged())}getPosition(){return this.#e.GetXY()}offsetPosition(t,e){if(t=+t,e=+e,isNaN(t)||isNaN(e)||0===t&&0===e)return;const i=this.#e;i.OffsetXY(t,e),i.SetBboxChanged()}setPosition3d(t,e,i){t=+t,e=+e,i=+i;const n=this.#e;isNaN(t)||isNaN(e)||isNaN(i)||n.EqualsXYZ(t,e,i)||(n.SetXYZ(t,e,i),n.SetBboxChanged())}getPosition3d(){return this.#e.GetXYZ()}offsetPosition3d(t,e,i){if(t=+t,e=+e,i=+i,isNaN(t)||isNaN(e)||isNaN(i)||0===t&&0===e&&0===i)return;const n=this.#e;n.OffsetXYZ(t,e,i),n.SetBboxChanged()}set originX(t){t=+t;const e=this.#e;isNaN(t)||e.GetOriginX()===t||(e.SetOriginX(t),e.SetBboxChanged())}get originX(){return this.#e.GetOriginX()}set originY(t){t=+t;const e=this.#e;isNaN(t)||e.GetOriginY()===t||(e.SetOriginY(t),e.SetBboxChanged())}get originY(){return this.#e.GetOriginY()}setOrigin(t,e){t=+t,e=+e;const i=this.#e;isNaN(t)||isNaN(e)||i.GetOriginX()===t&&i.GetOriginY()===e||(i.SetOriginX(t),i.SetOriginY(e),i.SetBboxChanged())}getOrigin(){const t=this.#e;return[t.GetOriginX(),t.GetOriginY()]}get width(){return this.#e.GetWidth()}set width(t){t=+t;const e=this.#e;isNaN(t)||e.GetWidth()===t||(e.SetWidth(t),e.SetBboxChanged())}get height(){return this.#e.GetHeight()}set height(t){t=+t;const e=this.#e;isNaN(t)||e.GetHeight()===t||(e.SetHeight(t),e.SetBboxChanged())}get depth(){return this.#e.GetDepth()}set depth(t){t=+t;const e=this.#e;isNaN(t)||e.GetDepth()===t||(e.SetDepth(t),e.SetBboxChanged())}setSize(t,e){t=+t,e=+e;const i=this.#e;isNaN(t)||isNaN(e)||i.GetWidth()===t&&i.GetHeight()===e||(i.SetSize(t,e),i.SetBboxChanged())}getSize(){const t=this.#e;return[t.GetWidth(),t.GetHeight()]}setSize3d(t,e,i){t=+t,e=+e,i=+i;const n=this.#e;isNaN(t)||isNaN(e)||isNaN(i)||n.GetWidth()===t&&n.GetHeight()===e&&n.GetDepth()===i||(n.SetSize(t,e),n.SetDepth(i),n.SetBboxChanged())}getSize3d(){const t=this.#e;return[t.GetWidth(),t.GetHeight(),t.GetDepth()]}get angle(){return this.#e.GetAngle()}set angle(t){t=C3.clampAngle(+t);const e=this.#e;isNaN(t)||e.GetAngle()===t||(e.SetAngle(t),e.SetBboxChanged())}get angleDegrees(){return C3.toDegrees(this.angle)}set angleDegrees(t){this.angle=C3.toRadians(t)}getBoundingBox(t){return t?(this.#e.CalculateBbox(tempAABB3D,tempQuad,!1),tempAABB3D.toDOMRect()):this.#e.GetBoundingBox().toDOMRect()}getBoundingBox3d(t){return t?(this.#e.CalculateBbox(tempAABB3D,tempQuad,!1),new globalThis.IAABB3D(tempAABB3D)):new globalThis.IAABB3D(this.#e.GetBoundingBox())}getBoundingQuad(t){return t?(this.#e.CalculateBbox(null,tempQuad,!1),tempQuad.toDOMQuad()):this.#e.GetBoundingQuad().toDOMQuad()}isOnScreen(){return this.#e.IsInViewport2()}get isVisible(){return this.#e.IsVisible()}set isVisible(t){t=!!t;const e=this.#t,i=this.#e;i.IsVisible()!==t&&(i.SetVisible(t),e.GetRuntime().UpdateRender())}get opacity(){return this.#e.GetOpacity()}set opacity(t){t=C3.clamp(+t,0,1);const e=this.#t,i=this.#e;isNaN(t)||i.GetOpacity()===t||(i.SetOpacity(t),e.GetRuntime().UpdateRender())}set colorRgb(t){if(C3X.RequireArray(t),t.length<3)throw new Error("expected 3 elements");tempColor.setRgb(t[0],t[1],t[2]);const e=this.#t,i=this.#e;i.GetUnpremultipliedColor().equalsIgnoringAlpha(tempColor)||(i.SetUnpremultipliedColor(tempColor),e.GetRuntime().UpdateRender())}get colorRgb(){const t=this.#e.GetUnpremultipliedColor();return[t.getR(),t.getG(),t.getB()]}set blendMode(t){C3X.RequireString(t);const e=BLEND_MODE_TO_INDEX.get(t);if("number"!=typeof e)throw new Error("invalid blend mode");const i=this.#t;this.#e.SetBlendMode(e),i.GetRuntime().UpdateRender()}get blendMode(){return INDEX_TO_BLEND_MODE.get(this.#e.GetBlendMode())}set sampling(t){this.#e.SetSamplingMode(t)}get sampling(){return this.#e.GetSamplingMode()}get activeSampling(){return C3.Gfx.RendererBase.SamplingNumberToMode(this.#e.GetActiveSampling())}moveToTop(){this.#e.ZOrderMoveToTop()}moveToBottom(){this.#e.ZOrderMoveToBottom()}moveToLayer(t){C3X.RequireInstanceOf(t,ILayer);const e=this.#t,i=e.GetRuntime()._UnwrapScriptInterface(t);if(!i)throw new Error("invalid layer");e.GetWorldInfo().ZOrderMoveToLayer(i)}moveAdjacentToInstance(t,e){C3X.RequireIWorldInstance(t),this.#e.ZOrderMoveAdjacentToInstance(map.get(t),e)}get zIndex(){return this.#e.GetZIndex()}get isCollisionEnabled(){return this.#e.IsCollisionEnabled()}set isCollisionEnabled(t){this.#e.SetCollisionEnabled(!!t)}containsPoint(t,e){return C3X.RequireNumber(t),C3X.RequireNumber(e),this.#e.ContainsPoint(+t,+e)}testOverlap(t){C3X.RequireIWorldInstance(t);const e=this.#t,i=map.get(t);return e.GetRuntime().GetCollisionEngine().TestOverlap(e,i)}testOverlapSolid(){const t=this.#t,e=t.GetRuntime().GetCollisionEngine().TestOverlapSolid(t);return e?e.GetInterfaceClass():null}getParent(){const t=this.#t.GetParent();return t?t.GetInterfaceClass():null}getTopParent(){const t=this.#t.GetTopParent();return t?t.GetInterfaceClass():null}*parents(){for(const t of this.#t.parents())yield t.GetInterfaceClass()}getChildCount(){return this.#t.GetChildCount()}getChildAt(t){const e=this.#t.GetChildAt(t);return e?e.GetInterfaceClass():null}*children(){for(const t of this.#t.children())yield t.GetInterfaceClass()}*allChildren(){for(const t of this.#t.allChildren())yield t.GetInterfaceClass()}addChild(t,e){C3X.RequireIWorldInstance(t),C3X.RequireOptionalObject(e),e||(e={});const i=this.#t,n=map.get(t);"number"!=typeof e.transformZ&&"number"==typeof e.transformZElevation&&(this.runtime._logDeprecationWarning("IWorldInstance.addChild","IWorldInstance 'addChild' method option 'transformZElevation' is deprecated. Use 'transformZ' instead."),e.transformZ=e.transformZElevation),i.AddChild(n,e)}removeChild(t){C3X.RequireIWorldInstance(t);const e=this.#t,i=map.get(t);e.RemoveChild(i)}removeFromParent(){const t=this.#t;if(!t.HasParent())return;t.GetParent().RemoveChild(t)}getHierarchyOpts(){const t=this.#e;return{transformX:t.GetTransformWithParentX(),transformY:t.GetTransformWithParentY(),transformZ:t.GetTransformWithParentZ(),transformWidth:t.GetTransformWithParentWidth(),transformHeight:t.GetTransformWithParentHeight(),transformAngle:t.GetTransformWithParentAngle(),transformOpacity:t.GetTransformWithParentOpacity(),transformVisibility:t.GetTransformWithParentVisibility(),destroyWithParent:t.GetDestroyWithParent()}}createMesh(t,e,i=!1){C3X.RequireFiniteNumber(t),C3X.RequireFiniteNumber(e),this.#e.CreateMesh(t,e,i)}releaseMesh(){const t=this.#e;t.ReleaseMesh(),t.SetBboxChanged()}setMeshPoint(t,e,i){C3X.RequireFiniteNumber(t),C3X.RequireFiniteNumber(e),C3X.RequireObject(i);const n=this.#e;"number"!=typeof i.z&&"number"==typeof i.zElevation&&(this.runtime._logDeprecationWarning("IWorldInstance.setMeshPoint","IWorldInstance 'setMeshPoint' method option 'zElevation' is deprecated. Use 'z' instead."),i.z=i.zElevation),n.SetMeshPoint(t,e,i)&&n.SetBboxChanged()}getMeshPoint(t,e){let i=NaN,n=NaN,r=NaN,s=NaN,a=NaN;const o=this.#e;if(o.HasMesh()){const l=o.GetSourceMesh().GetMeshPointAt(t,e);null!==l&&(i=l.GetX(),n=l.GetY(),r=l.GetZ(),s=l.GetU(),a=l.GetV())}return{x:i,y:n,z:r,u:s,v:a}}getMeshSize(){const t=this.#e;if(!t.HasMesh())return[0,0];const e=t.GetSourceMesh();return[e.GetHSize(),e.GetVSize()]}}}const IWorldInstance=MakeIWorldInstanceClass(globalThis.IInstance),IWorldInstanceSDKBase=MakeIWorldInstanceClass(globalThis.ISDKInstanceBase);globalThis.IWorldInstance=IWorldInstance,globalThis.IWorldInstanceSDKBase=IWorldInstanceSDKBase,C3X.IsIWorldInstance=function(t){return t instanceof IWorldInstance||t instanceof IWorldInstanceSDKBase},C3X.RequireIWorldInstance=function(t){if(!C3X.IsIWorldInstance(t))throw new TypeError("expected IWorldInstance")};
}

// interfaces/objects/IDOMInstance.js
{
const C3=self.C3,C3X=self.C3X;self.IDOMInstance=class extends self.IWorldInstance{#e;constructor(){super(),this.#e=self.IInstance._GetInitInst()}getElement(){return this.#e.GetSdkInstance()._GetElementInDOMMode()}focus(){this.#e.GetSdkInstance().FocusElement()}blur(){this.#e.GetSdkInstance().BlurElement()}setCssStyle(e,t){C3X.RequireString(e),this.#e.GetSdkInstance().SetElementCSSStyle(e,t)}};
}

// interfaces/objects/IBehaviorInstance.js
{
const C3=self.C3,C3X=self.C3X,dispatchers=new WeakMap,internalApiToken=C3._GetInternalAPIToken();function GetDispatcher(e){let t=dispatchers.get(e);return t||(t=C3.New(C3.Event.Dispatcher),dispatchers.set(e,t),t)}self.IBehaviorInstance=class{#e;constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken);this.#e=e;const t={runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},behavior:{value:e.GetBehavior().GetIBehavior(),writable:!1},behaviorType:{value:e.GetBehaviorType().GetIBehaviorType(),writable:!1}};Object.defineProperties(this,t),e.GetRuntime()._MapScriptInterface(this,e)}static _GetInitInst(){return C3.AddonManager._GetInitObject()}get instance(){return this.#e.GetObjectInstance().GetInterfaceClass()}_release(){const e=dispatchers.get(this);e&&(e.Release(),dispatchers.delete(this))}addEventListener(e,t,i){C3X.RequireString(e),C3X.RequireFunction(t),GetDispatcher(this).addEventListener(e,t,i)}removeEventListener(e,t,i){C3X.RequireString(e),C3X.RequireFunction(t),GetDispatcher(this).removeEventListener(e,t,i)}dispatchEvent(e){GetDispatcher(this).dispatchEvent(e)}};
}

// interfaces/objects/IBehaviorType.js
{
const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.IBehaviorType=class{constructor(){const e=C3.AddonManager._GetInitObject2(internalApiToken),t={runtime:{value:e.GetRuntime().GetIRuntime(),writable:!1},behavior:{value:e.GetBehavior().GetIBehavior(),writable:!1},name:{value:e.GetName(),writable:!1}};Object.defineProperties(this,t)}};
}

// interfaces/objects/IBehavior.js
{
const C3=self.C3,C3X=self.C3X,internalApiToken=C3._GetInternalAPIToken();self.IBehavior=class{#t;constructor(){const t=C3.AddonManager._GetInitObject2(internalApiToken);this.#t=t;const e={runtime:{value:t.GetRuntime().GetIRuntime(),writable:!1},id:{value:t.GetID(),writable:!1}};Object.defineProperties(this,e),t.GetRuntime()._MapScriptInterface(this,t)}getAllInstances(){return this.#t.GetInstances().map(t=>t.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<r;++i){const r=s[i],n=this._runtime.GetObjectClassByIndex(r[1]);let l=!0;if(!n.HasPersistBehavior()||t)if(n.IsGlobal()&&allInitialGlobalInstances.has(r[2]))l=!1;else{const t=this._runtime.CreateInstanceFromData(r,this,!0);e.push(t),n.IsGlobal()&&(allInitialGlobalInstances.size||this._runtime.Dispatcher().addEventListener("instancedestroy",on_global_instance_destroy),allInitialGlobalInstances.set(t.GetUID(),t),l=!1,this._createdGlobalUids.push(t.GetUID()))}l&&(s[a]=s[i],++a)}C3.truncateArray(s,a),this._runtime.FlushPendingInstances(),this.SetZIndicesChanged()}_AddInstance(e,t){if(!e.GetPlugin().IsWorldType())throw new Error("instance is not of world type");const s=e.GetWorldInfo();if(s.GetLayer()!==this)throw new Error("instance added to wrong layer");this._instances.push(e),0!==s.GetZ()&&(this._anyInstanceZElevated=!0),t&&this.UsesRenderCells()&&e.GetWorldInfo().SetBboxChanged(),this.SetZIndicesChanged(e)}_MaybeAddInstance(e){this._instances.includes(e)||(this._instances.push(e),0!==e.GetWorldInfo().GetZ()&&(this._anyInstanceZElevated=!0),this.SetZIndicesChanged(e))}_PrependInstance(e,t){const s=e.GetWorldInfo();if(s.GetLayer()!==this)throw new Error("instance added to wrong layer");this._instances.unshift(e),0!==s.GetZ()&&(this._anyInstanceZElevated=!0),this.SetZIndicesChanged(e),t&&this.UsesRenderCells()&&e.GetWorldInfo().SetBboxChanged()}_RemoveInstance(e,t){const s=this._instances.indexOf(e);s<0||(t&&this.UsesRenderCells()&&e.GetWorldInfo()._RemoveFromRenderCells(),this._instances.splice(s,1),this.SetZIndicesChanged(e),this._MaybeResetAnyInstanceZElevatedFlag())}_SetAnyInstanceZElevated(){this._anyInstanceZElevated=!0}_MaybeResetAnyInstanceZElevatedFlag(){0===this._instances.length&&(this._anyInstanceZElevated=!1)}_SortInstancesByLastCachedZIndex(e){if(e){const e=new Set;for(const t of this._instances){const s=t.GetWorldInfo()._GetLastCachedZIndex();s>=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),e<s&&(e=s),this._scrollX!==e&&(this._scrollX=e,this.IsOwnScrollPositionEnabled()&&(this._SetMVMatrixChanged(),this._runtime.UpdateRender()))}SetScrollY(e){const t=this.GetLayout(),s=t.GetScrollTopBound(),a=t.GetScrollBottomBound();e>a&&(e=a),e<s&&(e=s),this._scrollY!==e&&(this._scrollY=e,this.IsOwnScrollPositionEnabled()&&(this._SetMVMatrixChanged(),this._runtime.UpdateRender()))}GetScrollX(){return this.IsOwnScrollPositionEnabled()?this._scrollX:this.GetLayout().GetScrollX()}GetScrollY(){return this.IsOwnScrollPositionEnabled()?this._scrollY:this.GetLayout().GetScrollY()}GetViewport(){return this._MaybeUpdateViewport(),this._viewport}_GetViewportZ0(){return this._MaybeUpdateViewport(),this._viewportZ0}GetViewport3D(){return this._MaybeUpdateViewport(),this._viewport3D}_GetVanishingPoint(){return this.GetLayout().GetVanishingPoint()}GetDefaultCameraZ(e){return this._runtime.GetDefaultCameraZ(e)}GetViewportForZ(e,t){const s=this._GetViewportZ0();if(0===e)t.copy(s);else{let a=s.midX(),i=s.midY();const r=this.Get2DScaleFactorToZ(e),n=s.width()/r,l=s.height()/r,[o,h]=this._GetVanishingPoint();if(.5!==o||.5!==h){const t=this.Get2DCameraZ(),s=this._runtime,r=this.GetDefaultCameraZ()/t;let n=(o-.5)*s.GetViewportWidth()/r,l=(h-.5)*s.GetViewportHeight()/r;const c=this.GetAngle();0!==c&&(tempVec2.set(n,l),tempVec2.rotate(c),n=tempVec2.getX(),l=tempVec2.getY());const d=C3.unlerp(t,0,e);a+=C3.lerp(n,0,d),i+=C3.lerp(l,0,d)}t.set(a-n/2,i-l/2,a+n/2,i+l/2)}}GetOpacity(){return this._color.getA()}SetOpacity(e){e=C3.clamp(e,0,1),this._color.getA()!==e&&(this._color.setA(e),this._UpdatePremultipliedColor(),this._runtime.UpdateRender())}_UpdatePremultipliedColor(){this._premultipliedColor.copy(this._color),this._premultipliedColor.premultiply()}GetPremultipliedColor(){return this._premultipliedColor}HasDefaultColor(){return this._color.equalsRgba(1,1,1,1)}GetScaleRate(){return this._scaleRate}SetScaleRate(e){this._scaleRate!==e&&(this._scaleRate=e,this._SetMVMatrixChanged(),this._runtime.UpdateRender())}GetParallaxX(){return this._parallaxX}GetParallaxY(){return this._parallaxY}SetParallax(e,t){this._parallaxX===e&&this._parallaxY===t||(this._parallaxX=e,this._parallaxY=t,this._SetMVMatrixChanged(),this._runtime.UpdateRender())}SetParallaxX(e){this.SetParallax(e,this.GetParallaxY())}SetParallaxY(e){this.SetParallax(this.GetParallaxX(),e)}SetZElevation(e){this._zElevation!==e&&(this._zElevation=e,this._runtime.UpdateRender())}GetZElevation(){return this._zElevation}SetAngle(e){e=C3.clampAngle(e),this._angle!==e&&(this._angle=e,this._SetMVMatrixChanged(),this._runtime.UpdateRender())}GetAngle(){return C3.clampAngle(this._layout.GetAngle()+this._angle)}GetOwnAngle(){return this._angle}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;e=this.IsRootLayer()?this.GetLayout().GetActiveSampling():this.GetParentLayer().GetActiveSampling();const t=this.GetSamplingMode();"auto"!==t&&(e=t),this.#t=e;for(const e of this._instances)e.HasParent()||e.GetWorldInfo()._UpdateActiveSamplingMode();for(const e of this._subLayers)e._UpdateActiveSamplingModes()}GetActiveSampling(){return this.#t}HasInstances(){return this._instances.length>0}_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<t;++e){const t=this._instances[e].GetWorldInfo();t._SetZIndex(e),this._renderGrid.MarkRangeChanged(t.GetRenderCellRange())}else for(let e=0,t=this._instances.length;e<t;++e)this._instances[e].GetWorldInfo()._SetZIndex(e);this._zIndicesUpToDate=!0}}_UpdateHTMLZIndices(){if(this._htmlZIndicesUpToDate)return;const e=this._layout.GetRootLayersForHTMLLayer(this.GetHTMLIndex()).map(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),r<n&&n--,s&&n++,n===this._instances.length?this._instances.push(e):this._instances.splice(n,0,e),this.SetZIndicesChanged(e),!0)}_MergeSortedZArrays(e,t){const s=[];let a=0,i=0,r=e.length,n=t.length;for(;a<r&&i<n;){const r=e[a],n=t[i];r.GetWorldInfo()._GetLastCachedZIndex()<n.GetWorldInfo()._GetLastCachedZIndex()?(s.push(r),++a):(s.push(n),++i)}for(;a<r;++a)s.push(e[a]);for(;i<n;++i)s.push(t[i]);return s}_MergeAllSortedZArrays_pass(e){const t=[],s=e.length;for(let a=0;a<s-1;a+=2){const s=e[a],i=e[a+1];t.push(this._MergeSortedZArrays(s,i))}return s%2==1&&t.push(e[s-1]),t}_MergeAllSortedZArrays(e){for(;e.length>1;)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<o;++l){const o=t[l];if(o===n)continue;n=o;const h=o.GetWorldInfo();h.IsVisible()&&h.IsInViewport(s,r,i)&&this._DrawInstanceMaybeWithEffects(o,h,e,a)}}_DrawInstances_3DCamera(e){layerCoplanarManager.DrawCoplanar(e,null,this._curRenderTarget,this._GetInstancesInDrawOrder())}_DrawInstances_RenderCells(e){const t=this._renderGrid,s=this._curRenderCells,a=this._lastRenderCells,i=this.GetViewport();let r;s.set(t.XToCell(i.getLeft()),t.YToCell(i.getTop()),t.XToCell(i.getRight()),t.YToCell(i.getBottom())),this._isRenderListUpToDate&&s.equals(a)?r=this._lastRenderList:(r=this._GetRenderCellInstancesToDraw(),this._isRenderListUpToDate=!0,a.copy(s)),this._DrawInstances(e,r),r!==this._lastRenderList&&C3.shallowAssignArray(this._lastRenderList,r)}_DrawInstanceMaybeWithEffects(e,t,s,a){t.HasAnyActiveEffect()?this._DrawInstanceWithEffectsAndRestore(e,t,s,a):this._DrawInstance(e,t,s)}_DrawInstance(e,t,s){const a=t.GetRendererStateGroup();s.GetCurrentStateGroup()!==a&&a.Apply(),e.Draw(s)}_DrawInstanceWithEffectsAndRestore(e,t,s,a){this._DrawInstanceWithEffects(e,t,s,a,null)&&this._SetTransform(s)}_DrawInstanceWithEffects(e,t,s,a,i){const r=t.GetInstanceEffectList().GetEffectChain();return r.Render(s,a,{contentObject:e,blendMode:t.GetBlendMode(),devicePixelRatio:this._runtime.GetEffectDevicePixelRatioParam(),time:e.GetInstanceGameTime(),layerScale:this._runtime.GetEffectLayerScaleParam()*this.GetNormalScale(),layerAngle:this.GetAngle(),layoutRect:t.GetBoundingBox().toRect(),drawSurfaceRect:r.CanSkipCalculatingDrawSurfaceRect()?null:this.#s(t),drawContentHook:i&&i.drawContentHook,compositOffX:i&&i.compositOffX,compositOffY:i&&i.compositOffY,compositRtWidth:i&&i.compositRtWidth,compositRtHeight:i&&i.compositRtHeight,updateOwnProjection:i&&i.updateOwnProjection}),s.SetBaseZ(this.GetZElevation()),r.DidChangeTransform()}_DrawLayerOwnTextureToRenderTarget(e,t,s,a){const i=this._effectList.GetActiveEffectTypes(),r=this._runtime;0===i.length?(e.SetRenderTarget(s),e.SetTextureFillMode(),a&&0===this._blendMode&&this.HasDefaultColor()?e.CopyRenderTarget(t):(e.SetBlendMode(this._blendMode),e.SetColor(this._premultipliedColor),e.DrawRenderTarget(t)),e.InvalidateRenderTarget(t),r.ReleaseAdditionalRenderTarget(t)):this.GetEffectChain().Render(e,s,{contentObject:this,blendMode:this.GetBlendMode(),devicePixelRatio:r.GetEffectDevicePixelRatioParam(),layerScale:r.GetEffectLayerScaleParam()*this.GetNormalScale(),layerAngle:this.GetAngle(),layoutRect:this.GetViewport(),drawSurfaceRect:null,invalidateRenderTargets:!0})}GetOwnScale(){return this._scale}SetOwnScale(e){this._scale!==e&&(this._scale=e,this._layout.BoundScrolling(),this._SetMVMatrixChanged(),this._runtime.UpdateRender())}GetRenderScale(){return this.GetNormalScale()*this._runtime.GetRenderScale()}GetDisplayScale(){return this.GetNormalScale()*this._runtime.GetDisplayScale()}GetNormalScale(){return(this._scale*this._layout.GetScale()-1)*this._scaleRate+1}_MaybeUpdateViewport(){if(!this._isViewportChanged)return;this._isViewportChanged=!1;const e=this._runtime.GetParallaxXOrigin(),t=this._runtime.GetParallaxYOrigin(),s=(this.GetScrollX()-e)*this._parallaxX+e,a=(this.GetScrollY()-t)*this._parallaxY+t,i=this.GetNormalScale(),r=this._runtime.GetViewportWidth()/i,n=this._runtime.GetViewportHeight()/i;let l=s-r/2,o=a-n/2;this._runtime.IsPixelRoundingEnabled()&&(l=Math.round(l),o=Math.round(o));const h=this._viewportZ0;h.set(l,o,l+r,o+n);const c=this.GetAngle();0!==c&&(tmpRect.copy(h),tmpRect.offset(-h.midX(),-h.midY()),tmpQuad.setFromRotatedRect(tmpRect,c),tmpQuad.getBoundingBox(tmpRect),tmpRect.offset(h.midX(),h.midY()),h.copy(tmpRect));const d=this._zElevation;this.GetViewportForZ(d,this._viewport),this.Has3DCamera()?this.CalculateViewport3D(d,this._viewport3D):this._viewport3D.copy(this._viewport)}CalculateViewport3D(e,t){const s=this._runtime.GetCanvasManager(),a=s.GetCssWidth(),i=s.GetCssHeight(),[r,n]=this.CanvasCssToLayer(0,0,e),[l,o]=this.CanvasCssToLayer(a,0,e),[h,c]=this.CanvasCssToLayer(a,i,e),[d,_]=this.CanvasCssToLayer(0,i,e);let u=Math.min(r,l,h,d),p=Math.min(n,o,c,_),G=Math.max(r,l,h,d),f=Math.max(n,o,c,_);isFinite(u)||(u=-1/0),isFinite(p)||(p=-1/0),isFinite(G)||(G=1/0),isFinite(f)||(f=1/0),t.set(u,p,G,f)}CanvasCssToLayer(e,t,s=0){return this._CanvasToLayer(e,t,s,this.GetDisplayScale())}DrawSurfaceToLayer(e,t,s=0){return this._CanvasToLayer(e,t,s,this.GetRenderScale()*this.GetDevicePixelRatio())}_CanvasToLayer(e,t,s,a){const i=this._runtime,r=i.GetRenderer(),n=this.GetNormalScale(),l=i.GetViewportWidth()/n,o=i.GetViewportHeight()/n,h=tempVec4;vec4.set(h,0,0,l,o),e/=a,t=h[3]-t/a;const c=this._GetProjectionMatrix(r),d=this._GetModelViewMatrix(r),_=tempVec3;return C3.Gfx.UnprojectScreenToXYPlane(e,t,s,d,c,h,_)?[_[0],_[1]]:[NaN,NaN]}CanvasCssToLayer_DefaultTransform(e,t){const s=this._scale,a=this._scaleRate,i=this._parallaxX,r=this._parallaxY,n=this._angle,l=this.Has3DCamera();l&&this.GetLayout().Set3DCameraEnabled(!1),this._scale=1,this._scaleRate=1,this._parallaxX=1,this._parallaxY=1,this._angle=0,this._SetMVMatrixChanged();const o=this.CanvasCssToLayer(e,t);return this._scale=s,this._scaleRate=a,this._parallaxX=i,this._parallaxY=r,this._angle=n,this._SetMVMatrixChanged(),l&&this.GetLayout().Set3DCameraEnabled(!0),o}LayerToCanvasCss(e,t,s=0){return this._LayerToCanvas(e,t,s,this.GetDisplayScale())}LayerToDrawSurface(e,t,s=0){return this._LayerToCanvas(e,t,s,this.GetRenderScale()*this.GetDevicePixelRatio())}_LayerToCanvas(e,t,s,a){const i=this._runtime,r=i.GetRenderer(),n=this.GetNormalScale(),l=i.GetViewportWidth()/n,o=i.GetViewportHeight()/n,h=tempVec4;vec4.set(h,0,0,l,o);const c=this._GetProjectionMatrix(r),d=this._GetModelViewMatrix(r),_=tempVec3;return C3.Gfx.Project(e,t,s,d,c,h,_)?[_[0]*a,(h[3]-_[1])*a]:[NaN,NaN]}_GetLayerToDrawSurfaceScale(e,t){return e*=this.GetRenderScale()*this.GetDevicePixelRatio(),0!==t&&(e*=this.Get2DScaleFactorToZ(t)),e}#s(e){const t=e.GetBoundingBox(),s=t.getLeft(),a=t.getTop(),i=t.getRight(),r=t.getBottom(),n=t.getBack(),l=t.getFront(),o=n!==l;if(this.Has3DCamera()){if(this.#a(s,a,n)||this.#a(i,a,n)||this.#a(i,r,n)||this.#a(s,r,n))return null;if(o&&(this.#a(s,a,l)||this.#a(i,a,l)||this.#a(i,r,l)||this.#a(s,r,l)))return null}else if(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<a;++e)t.has(this._initialInstances[e][2])||(this._initialInstances[s]=this._initialInstances[e],++s);C3.truncateArray(this._initialInstances,s),this._effectList.LoadFromJson(e["fx"]),this._needsRebuildEffectChainSteps=!0}_LoadFromJsonAfterInstances(){this._SortInstancesByLastCachedZIndex(!1),this.SetZIndicesChanged(),this._SetMVMatrixChanged(),this._SetProjectionMatrixChanged()}GetILayer(){return this._iLayer}UserScriptDispatcher(){return this._userScriptDispatcher}DispatchUserScriptEvent(e){e.layer=this.GetILayer(),this._userScriptDispatcher.dispatchEvent(e)}SortAndAddInstancesByZIndex(e,t=!1,s=!1){if(this._instances.includes(e))return t&&this._instances.sort((e,t)=>(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;t<s;++t){const s=this._allLayersFlat[t];0===s.GetParallaxX()&&0===s.GetParallaxY()||(e=Math.min(e,s.GetNormalScale()))}return e}_GetScrollBoundMarginHorizontal(){return.5*this._runtime.GetViewportWidth()/this.GetMinLayerScale()}_GetScrollBoundMarginVertical(){return.5*this._runtime.GetViewportHeight()/this.GetMinLayerScale()}GetScrollLeftBound(){return this.IsUnboundedScrolling()?-1/0:this._GetScrollBoundMarginHorizontal()}GetScrollRightBound(){return this.IsUnboundedScrolling()?1/0:this.GetWidth()-this._GetScrollBoundMarginHorizontal()}GetScrollTopBound(){return this.IsUnboundedScrolling()?-1/0:this._GetScrollBoundMarginVertical()}GetScrollBottomBound(){return this.IsUnboundedScrolling()?1/0:this.GetHeight()-this._GetScrollBoundMarginVertical()}SetScrollX(e){const t=this.GetScrollLeftBound(),s=this.GetScrollRightBound();e>s&&(e=s),e<t&&(e=t),this._scrollX!==e&&(this._scrollX=e,this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}GetScrollX(){return this._scrollX}SetScrollY(e){const t=this.GetScrollTopBound(),s=this.GetScrollBottomBound();e>s&&(e=s),e<t&&(e=t),this._scrollY!==e&&(this._scrollY=e,this._SetAllLayersMVChanged(),this._runtime.UpdateRender())}GetScrollY(){return this._scrollY}IsUnboundedScrolling(){return this._isUnboundedScrolling}BoundScrolling(){this.SetScrollX(this.GetScrollX()),this.SetScrollY(this.GetScrollY());for(const e of this._allLayersFlat)e.IsOwnScrollPositionEnabled()&&(e.SetScrollX(e.GetScrollX()),e.SetScrollY(e.GetScrollY()))}SetVanishingPointXY(e,t){this._vanishingPointX===e&&this._vanishingPointY===t||(this._vanishingPointX=e,this._vanishingPointY=t,this.IsPerspectiveProjection()&&(this._SetAllLayersProjectionChanged(),this._SetAllLayersMVChanged(),this._runtime.UpdateRender()))}GetVanishingPointX(){return this.IsOrthographicProjection()?.5:this._vanishingPointX}GetVanishingPointY(){return this.IsOrthographicProjection()?.5:this._vanishingPointY}GetVanishingPoint(){return[this.GetVanishingPointX(),this.GetVanishingPointY()]}HasVanishingPointOutsideViewport(){const e=this.GetVanishingPointX(),t=this.GetVanishingPointY();return e<0||e>1||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;e<t;++e){const t=this._allLayersFlat[e];t._SetIndex(e),this._layersByName.set(t.GetName().toLowerCase(),t),this._layersBySid.set(t.GetSID(),t)}}_ReindexHTMLLayers(){let e=0;for(const t of this._rootLayers){for(const s of t.selfAndAllSubLayers())s._SetHTMLIndex(e);t.IsHTMLElementsLayer()&&e++}}GetHTMLLayerCount(){return this._rootLayers.at(-1).GetHTMLIndex()+1}async _ReindexAndUpdateAllLayers(){this._ReindexLayers(),this._ReindexHTMLLayers(),this._pendingSetHTMLLayerCount=this.GetHTMLLayerCount()}_GetPendingSetHTMLLayerCount(){return this._pendingSetHTMLLayerCount}_ResetPendingHTMLLayerCount(){this._pendingSetHTMLLayerCount=-1}GetRootLayersForHTMLLayer(e){const t=[];for(const s of this._rootLayers){const n=s.GetHTMLIndex();if(n===e)t.push(s);else if(n>e)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;n<a;++n){const a=t[n],i=this._runtime.GetObjectClassByIndex(a[1]);i.IsGlobal()?i.IsInContainer()&&i.GetContainer().HasAnyWorldType()||e.push(this._runtime.CreateInstanceFromData(a,null,!0)):(t[s]=a,++s)}C3.truncateArray(t,s),this._runtime.FlushPendingInstances(),this._CreateAndLinkContainerInstances(e)}RecreateInitialObjects(e,t,s,n,a,i,r){if(s)return s.RecreateInitialObjects(e,t,a,i,n,r);{const s=[];for(const o of this._allLayersFlat)s.push(o.RecreateInitialObjects(e,t,a,i,n,r));return s.flat()}}async _StopRunning(){const e=this._layoutManager;this._runtime.IsLoadingState()||(await this.DispatchRuntimeUserScriptEventAsyncWait(new C3.Event("beforeanylayoutend")),await this.DispatchUserScriptEventAsyncWait(new C3.Event("beforelayoutend")),await this._runtime.TriggerAsync(C3.Plugins.System.Cnds.OnLayoutEnd,null,null),await this.DispatchUserScriptEventAsyncWait(new C3.Event("afterlayoutend")),await this.DispatchRuntimeUserScriptEventAsyncWait(new C3.Event("afteranylayoutend"))),e.SetIsEndingLayout(!0),this._runtime.GetEventSheetManager().ClearAllScheduledWaits(),this._isFirstVisit||this._SavePersistData();for(const e of this._allLayersFlat)e._End();for(const e of this._runtime.GetAllObjectClasses())if(!(e.IsGlobal()||e.IsWorldType()||e.GetPlugin().IsSingleGlobal()||e.IsFamily())){for(const t of e.GetInstances())this._runtime.DestroyInstance(t);this._runtime.FlushPendingInstances()}e.SetIsEndingLayout(!1),e.GetMainRunningLayout()===this&&e._SetMainRunningLayout(null)}_SaveInstanceToPersist(e,t){const s=e.GetObjectClass().GetSID().toString();this._persistData.hasOwnProperty(s)||(this._persistData[s]=[]);const n=this._persistData[s],a={"index":t,"instJson":e.SaveToJson(),"sceneGraphJson":{"children":[]}};n.push(a),this._persistedIntances.set(e,a)}_SaveSceneGraphInfoToPersist(e){const t=this._persistedIntances.get(e);for(const s of e.GetChildren()){const e=this._persistedIntances.get(s);e&&t["sceneGraphJson"]["children"].push({"index":e["index"],"flags":C3.SceneGraphInfo._GetFlagsNumber(s.GetWorldInfo())})}}_SavePersistData(){this._persistedIntances.clear();let e=0;for(const t of this._allLayersFlat){t._UpdateZIndices();for(const s of t._GetInstances()){const t=s.GetObjectClass();!t.IsGlobal()&&t.HasPersistBehavior()&&(this._SaveInstanceToPersist(s,e),e++)}}for(const e of this._allLayersFlat)for(const t of e._GetInstances()){const e=t.GetObjectClass();!e.IsGlobal()&&e.HasPersistBehavior()&&this._SaveSceneGraphInfoToPersist(t)}this._persistedIntances.clear()}ResetPersistData(){this._persistData={},this._isFirstVisit=!0}GetRenderTarget(){return this._curRenderTarget}UsesOwnTexture(){const e=this._runtime,t=e.GetRenderer().IsWebGL();return"low"===e.GetCanvasManager().GetCurrentFullscreenScalingQuality()||t&&e.UsesAnyBackgroundBlending()||this._effectList.HasAnyActiveEffect()||t&&e.Uses3DFeatures()}_MaybeStartDrawToOwnTexture(e){const t=this._runtime.GetCanvasManager();if(this.UsesOwnTexture()){e.SetRenderTarget(null),e.ClearRgba(0,0,0,0);const s={isSampled:e.IsWebGPU()||this._runtime.UsesAnyBackgroundBlending()||this._effectList.HasAnyActiveEffect(),canReadPixels:!!e.IsWebGPU()&&this._runtime.UsesAnyBackgroundBlending()};"low"===t.GetCurrentFullscreenScalingQuality()&&(s.width=t.GetDrawWidth(),s.height=t.GetDrawHeight()),this._curRenderTarget=this._runtime.GetAdditionalRenderTarget(s),this._curRenderTarget.SetDefaultSampling(this.GetActiveSampling())}else this._curRenderTarget=null}_MaybeCopyOwnTextureToBackbuffer(e){this._runtime._NeedsHTMLLayerCompositing(e)&&(e.SetDepthEnabled(!1),e.SetRenderTarget(null),e.SetTextureFillMode(),e.CopyRenderTarget(this._curRenderTarget))}_MaybeEndDrawToOwnTexture(e){this.UsesOwnTexture()&&(e.SetDepthEnabled(!1),this._DrawLayoutOwnTextureToRenderTarget(e,this._curRenderTarget))}DrawMain(e){e.SetRenderTarget(this._curRenderTarget),e.Clear(this.GetLayoutBackgroundColor()),this._runtime.Uses3DFeatures()&&e.ClearDepth();const t=this.GetRootLayersForHTMLLayer(0);this._DrawLayerList(e,this._curRenderTarget,t,!0),e.IsWebGPU()&&e.StartMeasuringRenderPassTime(0,1),this._MaybeEndDrawToOwnTexture(e),this._curRenderTarget=null}DrawForHTMLLayerIndex(e,t){let s=null;this._runtime._NeedsHTMLLayerCompositing(e)&&(s=this._curRenderTarget),e.SetRenderTarget(s),e.ClearRgba(0,0,0,0),this._runtime.Uses3DFeatures()&&e.ClearDepth();const n=this.GetRootLayersForHTMLLayer(t);this._DrawLayerList(e,s,n,!0),this._MaybeCopyOwnTextureToBackbuffer(e),e.EndBatch(),this._runtime.GetCanvasManager().BlitMainCanvasToHTMLLayerCanvas(t)}_DrawLayerList(e,t,s,n){const a=s.filter(e=>e.ShouldDraw());for(let s=0,i=a.length;s<i;){const r=a[s];if(r.SelfAndAllSubLayersHave3DCamera()&&!r.SelfOrAnySubLayerUsesOwnTexture()){tempRender3dList.push(r);for(let e=s+1;e<i;++e){const t=a[e];if(!t.SelfAndAllSubLayersHave3DCamera()||t.SelfOrAnySubLayerUsesOwnTexture())break;tempRender3dList.push(a[e])}if(tempRender3dList.length>=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;e<t;e++){const t=this._markedForRemovalTimelines[e];i||(i=new Set),t.Removed(),this._MaybeExecuteTimelineFinishTriggers(t),i.add(t)}if(i){C3.arrayRemoveAllInSet(this._markedForRemovalTimelines,i),this._renderChange=0;for(let e=0,i=this._playingTimelines.length;e<i;e++)if(0!==this._playingTimelines[e].GetRenderChange()){this._renderChange=1;break}}this._MaybeDisableRuntimeListeners(),e.IsDebug()&&globalThis.C3Debugger.AddTweensAndTimelinesTime(performance.now()-t)}_MaybeExecuteTimelineFinishTriggers(e){e.IsReleased()||e.HasValidTracks()&&e.IsComplete()&&e.InitialStateSet()&&e.FinishTriggers()}_MaybeEnableRuntimeListeners(){this._hasRuntimeListeners||(this._hasRuntimeListeners=!0)}_MaybeDisableRuntimeListeners(){this._markedForRemovalTimelines.length||this._playingTimelines.length||this._scheduledTimelines.length||this._isTickingTimelines||(this._hasRuntimeListeners=!1)}_OnBeforeChangeLayout(){for(this._changingLayout=!0;this._scheduledTimelines.length;)this.DeScheduleTimeline(this._scheduledTimelines.pop());const e=new Set;for(const i of this._playingTimelines){i._OnBeforeChangeLayout()&&(i.Removed(),e.add(i))}C3.arrayRemoveAllInSet(this._playingTimelines,e),e.clear();for(const i of this._markedForRemovalTimelines){i._OnBeforeChangeLayout()&&(i.Removed(),e.add(i))}C3.arrayRemoveAllInSet(this._markedForRemovalTimelines,e),this._MaybeDisableRuntimeListeners();for(const e of this._timelines)e.CleanCaches()}_OnAfterChangeLayout(){this._changingLayout=!1}_OnInstanceDestroy(e){const i=e.GetObjectClass(),t=this.GetTimelinesForObjectClass(i);if(t)if(this._runtime.IsLoadingState())this._destroyedWhileLoadingState.push(e);else for(const e of t)e.IsTemplate()||(e.IsReleased()?this.Remove(e):e.HasValidTracks()||(this._MaybeExecuteTimelineFinishTriggers(e),this.Remove(e)))}_OnBeforeLoad(){for(const e of this._scheduledTimelines.map(e=>e))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);t<i;++t){const i=h[t],e=(i.GetNext(),i.GetPrevious()),s=n[t],_=(s.GetNext(),s.GetPrevious());e&&"cubic-bezier"===e.GetPathMode()&&_&&"cubic-bezier"===_.GetPathMode()?this._segments.push(C3.New(C3.TimelineCubicBezierSegmentInfo,e,_,i,s,this._segments.length)):(e&&"line"===e.GetPathMode()&&_&&_.GetPathMode(),this._segments.push(C3.New(C3.TimelineLineSegmentInfo,i,s,this._segments.length)))}this._initialized=!0}Release(){for(const t of this._segments)t.Release();C3.clearArray(this._segments),this._segments=null,this._timeline=null,this._xTrack=null,this._yTrack=null}WasInitialized(){return this._initialized}segments(){return this._segments}SetOrigin(t){const i="relative"===this._xTrack.GetResultMode()?t.GetX():0,e="relative"===this._yTrack.GetResultMode()?t.GetY():0;for(const t of this._segments)t.SetOrigin(i,e)}Project(t,i,e){let s=NaN,_=this._segments.length;for(let e=0;e<_;e++){const _=this._segments[e];if("cubic-bezier"===_.GetType()){const e=_.Project(t,i);(isNaN(s)||e[3]<s)&&(s=e[3],SHORT_PROJECTION_RESULT[0]=e[2],SHORT_PROJECTION_RESULT[1]=_.GetIndex())}}return SHORT_PROJECTION_RESULT}ProjectWithOptions(t,i,e){const s=e.tRange;C3.IsFiniteNumber(s[0])||(s[0]=0),C3.IsFiniteNumber(s[1])||(s[1]=1);let _=NaN,h=this._segments.length;for(let e=0;e<h;e++){const h=this._segments[e];if("cubic-bezier"===h.GetType()){const e=h.ProjectWithRange(t,i,s);(isNaN(_)||e[3]<_)&&(_=e[3],SHORT_PROJECTION_RESULT[0]=e[2],SHORT_PROJECTION_RESULT[1]=h.GetIndex())}}return SHORT_PROJECTION_RESULT}Tangent(t,i){return this._segments[i].Tangent(t)}TangentAngle(t,i){return this._segments[i].TangentAngle(t)}},C3.TimelineCubicBezierSegmentInfo=class{constructor(t,i,e,s,_){this._index=_;const h=t.GetAddOn("cubic-bezier"),n=e.GetAddOn("cubic-bezier"),r=i.GetAddOn("cubic-bezier"),a=s.GetAddOn("cubic-bezier");this._aX=t.GetValueWithResultMode(),this._aY=i.GetValueWithResultMode(),this._bX=t.GetValueWithResultMode()+h.GetStartAnchor(),this._bY=i.GetValueWithResultMode()+r.GetStartAnchor(),this._cX=e.GetValueWithResultMode()+n.GetEndAnchor(),this._cY=s.GetValueWithResultMode()+a.GetEndAnchor(),this._dX=e.GetValueWithResultMode(),this._dY=s.GetValueWithResultMode(),this._aXO=0,this._aYO=0,this._bXO=0,this._bYO=0,this._cXO=0,this._cYO=0,this._dXO=0,this._dYO=0,this._d0x=0,this._d0y=0,this._d1x=0,this._d1y=0,this._d2x=0,this._d2y=0,this._x1Factor=0,this._x2Factor=0,this._x3Factor=0,this._y1Factor=0,this._y2Factor=0,this._y3Factor=0,this._lutIndex=NaN,this._initialized=!1,this._len=100,this._arcLengths=new Array(this._len+1),this._arcLengths[0]=0,this._length=0,this._lut=[],this._lutObjects=[];for(let t=0;t<100;t++)this._lutObjects.push({x:0,y:0,t:0,distance:0});this._CalculateLength()}Release(){C3.clearArray(this._arcLengths),this._arcLengths=null,C3.clearArray(this._lut),this._lut=null,C3.clearArray(this._lutObjects),this._lutObjects=null}GetType(){return"cubic-bezier"}GetIndex(){return this._index}GetStepCount(){return Math.floor(this._length/25)}GetStepIncrement(){return 1/this.GetStepCount()}SetOrigin(t,i){this._originX=t,this._originY=i,this._arcLengths=new Array(this._len+1),this._arcLengths[0]=0,this._CalculateLength(),this._aXO=this._aX+this._originX,this._aYO=this._aY+this._originY,this._bXO=this._bX+this._originX,this._bYO=this._bY+this._originY,this._cXO=this._cX+this._originX,this._cYO=this._cY+this._originY,this._dXO=this._dX+this._originX,this._dYO=this._dY+this._originY,this._d0x=3*(this._bXO-this._aXO),this._d0y=3*(this._bYO-this._aYO),this._d1x=3*(this._cXO-this._bXO),this._d1y=3*(this._cYO-this._bYO),this._d2x=3*(this._dXO-this._cXO),this._d2y=3*(this._dYO-this._cYO),this._x1Factor=3*(this._bXO-this._aXO),this._x2Factor=3*(this._aXO+this._cXO-2*this._bXO),this._x3Factor=this._dXO-this._aXO+3*(this._bXO-this._cXO),this._y1Factor=3*(this._bYO-this._aYO),this._y2Factor=3*(this._aYO+this._cYO-2*this._bYO),this._y3Factor=this._dYO-this._aYO+3*(this._bYO-this._cYO)}Map(t){if(!this._initialized)return NaN;const i=this._Map(t);return MAP_RESULT[0]=this._X(i),MAP_RESULT[1]=this._Y(i),MAP_RESULT}Project(t,i){const e=this._GenerateLUT(100),s=this._FindClosestFromLUT(t,i,e),_=this._RefineProjection(t,i,e,s);return PROJECTION_RESULT[0]=_.x,PROJECTION_RESULT[1]=_.y,PROJECTION_RESULT[2]=_.t,PROJECTION_RESULT[3]=_.distance,PROJECTION_RESULT}ProjectWithRange(t,i,e){const s=this._GenerateLUT(100),_=this._FindClosestFromLUTWithRange(t,i,s,e),h=this._RefineProjection(t,i,s,_);return PROJECTION_RESULT[0]=h.x,PROJECTION_RESULT[1]=h.y,PROJECTION_RESULT[2]=h.t,PROJECTION_RESULT[3]=h.distance,PROJECTION_RESULT}Tangent(t){const i=1-t,e=i*i,s=2*i*t,_=t*t,h=e*this._d0x+s*this._d1x+_*this._d2x,n=e*this._d0y+s*this._d1y+_*this._d2y,r=C3.hypot2DFast(h,n);return TANGENT_RESULT[0]=h/r,TANGENT_RESULT[1]=n/r,TANGENT_RESULT}TangentAngle(t){const i=1-t,e=i*i,s=2*i*t,_=t*t,h=e*this._d0x+s*this._d1x+_*this._d2x,n=e*this._d0y+s*this._d1y+_*this._d2y;return Math.atan2(n,h)}_Map(t){if(!this._initialized)return;let i=t*this._arcLengths[this._len],e=0,s=this._len,_=0;for(;e<s;)_=e+((s-e)/2|0),this._arcLengths[_]<i?e=_+1:s=_;this._arcLengths[_]>i&&_--;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<t-1;i++){const e=i/(t-1),s=e**2,_=e**3,h=this._x1Factor*e,n=this._x2Factor*s,r=this._x3Factor*_,a=this._y1Factor*e,c=this._y2Factor*s,l=this._y3Factor*_,o=this._aXO+h+n+r,d=this._aYO+a+c+l;this._lutObjects[i].x=o,this._lutObjects[i].y=d,this._lutObjects[i].t=e,this._lutObjects[i].distance=0,this._lut[i]=this._lutObjects[i]}return this._lut}_FindClosestFromLUT(t,i,e,s=null,_=Number.MAX_SAFE_INTEGER){let h=0;if(isNaN(this._lutIndex))for(let s=0;s<100;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)}else{for(let s=this._lutIndex;s<this._lutIndex+5&&!(s>=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<this._lutIndex+5&&!(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(S<n){n=S,s=e,REFINE_RESULT.x=R,REFINE_RESULT.y=g,REFINE_RESULT.t=h,REFINE_RESULT.distance=S,_=REFINE_RESULT;break t}const x=REFINE_LUT_OBJECTS[e-1];x.x=R,x.y=g,x.t=h,x.distance=S,REFINE_LUT[e]=x}REFINE_LUT[3]=e[a],e=REFINE_LUT}while(h++<20);return _}_CalculateLength(){this._initialized=!0;let t=this._X(0),i=this._Y(0),e=0;for(let s=1;s<=this._len;s++){const _=this._X(.01*s),h=this._Y(.01*s),n=t-_,r=i-h;e+=C3.hypot2DFast(n,r),this._arcLengths[s]=e,t=_,i=h}this._length=e}},C3.TimelineLineSegmentInfo=class{constructor(t,i,e){this._index=e,this._targetX=t.GetValueWithResultMode(),this._targetY=i.GetValueWithResultMode(),this._originX=0,this._originY=0}Release(){}GetType(){return"line"}GetIndex(){return this._index}SetOrigin(t,i){this._originX=t,this._originY=i}GetX(){return this._targetX+this._originX}GetY(){return this._targetY+this._originY}};
}

// timelines/state/timelineState.js
{
const C3=self.C3,PING_PONG_BEGIN=0,PING_PONG_END=1;C3.TimelineState=class extends C3.DefendedBase{constructor(t,e,i){super(),this._runtime=i.GetRuntime(),this._timelineManager=i,this._timelineDataItem=e,this._name=t,this._tracks=[],this._tracksLength=0,this._beforeAndAfterTracks=null,this._beforeAndAfterTracksLength=0,this.CreateTrackStates(),this._playPromise=null,this._playResolve=null,this._playheadTime=0,this._overshoot=0,this._playbackRate=1,this._pingPongState=0,this._resumePingPongState=-1,this._currentRepeatCount=1,this._isPlaying=!1,this._isScheduled=!1,this._initialStateSet=!1,this._complete=!0,this._released=!1,this._markedForRemoval=!1,this._completedTick=-1,this._implicitPause=!1,this._isTemplate=!1,this._finishedTriggers=!1,this._firstTick=!1,this._lastDelta=NaN,this._tags=[""],this._stringTags="",this._tagsChanged=!1,this._renderChange=0,this._hasNestedContent=0,this._stoppedKeyframeDataItem=null,this._iTimelineState=null}static CreateInitial(t,e){const i=e.GetTimelineDataManager(),s=i.GetNameId(),a=i.Get(t[s]),n=C3.New(C3.TimelineState,t[s],a,e);return n.SetIsTemplate(!0),n}static CreateFromTemplate(t,e,i){return C3.New(C3.TimelineState,t,e,i)}Release(){if(this.IsReleased())return;const t=this._runtime.Dispatcher();this._timelineManager.DeScheduleTimeline(this),this._timelineManager.CompleteTimelineAndResolve(this);for(const t of this._tracks)t.Release();C3.clearArray(this._tracks),this._tracks=null,this._runtime=null,this._timelineManager=null,this._timelineDataItem=null,this._released=!0,this._playPromise=null,this._playResolve=null,this.FireReleaseEvent(t)}FireReleaseEvent(t){const e=C3.New(C3.Event,"timelinestatereleased");e.timelineState=this,t.dispatchEvent(e)}GetType(){return 0}CreateTrackStates(){for(const t of this._timelineDataItem.GetTrackData().trackDataItems())this._tracksLength=this._tracks.push(C3.TrackState.Create(this,t))}GetTimelineManager(){return this._timelineManager}GetRuntime(){return this._runtime}GetTracks(){return this._tracks}GetSimilarPropertyTracks(t,e,i,s){if(!this._hasNestedContent)return;let a;for(let n=0;n<this._tracks.length;n++){let r=this._tracks[n];if(t!==r.GetInstance())continue;const h=r.GetPropertyTrack(i);h&&(e.constructor===h.GetSourceAdapter().constructor&&h.GetResultMode()===s.GetResultMode()&&(a||(a=[]),a.push(h)))}return a}HasTracks(){return!!this._tracks.length}GetTrackById(t){for(const e of this._tracks)if(C3.equalsNoCase(e.GetId(),t))return e;return null}GetTrackByName(t){for(const e of this._tracks)if(!e.IsInstanceTrack()&&C3.equalsNoCase(e.GetName(),t))return e;return null}SetName(t){this._name=t}GetName(){return this._name}GetTimelineDataItem(){return this._timelineDataItem}GetTemplateName(){return this._timelineDataItem.GetName()}GetTotalTime(){return this._timelineDataItem.GetTotalTime()}SetTotalTime(t){this._timelineDataItem.SetTotalTime(t)}GetStep(){return this._timelineDataItem.GetStep()}SetStep(t){this._timelineDataItem.SetStep(t)}GetInterpolationMode(){return this._timelineDataItem.GetInterpolationMode()}SetInterpolationMode(t){this._timelineDataItem.SetInterpolationMode(t)}GetResultMode(){return this._timelineDataItem.GetResultMode()}SetResultMode(t){this._timelineDataItem.GetResultMode(t)}SetEase(t){for(const e of this.GetTracks())e.SetEase(t)}GetLoop(){return this._timelineDataItem.GetLoop()}SetLoop(t){return this._timelineDataItem.SetLoop(t)}GetPingPong(){return this._timelineDataItem.GetPingPong()}SetPingPong(t){return this._timelineDataItem.SetPingPong(t)}GetRepeatCount(){return this._timelineDataItem.GetRepeatCount()}GetCurrentRepeatCount(){return this._currentRepeatCount}SetRepeatCount(t){return this._timelineDataItem.SetRepeatCount(t)}SetPlaybackRate(t){if(t=Number(t),C3.IsFiniteNumber(t))return this._playbackRate=t}GetPlaybackRate(){return this._playbackRate}GetStartOnLayout(){return this._timelineDataItem.GetStartOnLayout()}GetTransformWithSceneGraph(){return this._timelineDataItem.GetTransformWithSceneGraph()}GetUseSystemTimescale(){return this._timelineDataItem.GetUseSystemTimescale()}GetPingPongState(){return this._pingPongState}IsForwardPlayBack(){return!this.IsPlaying()||this._playbackRate>0}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._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._pingPongState=0):r=!0:0===this._pingPongState&&(this._pingPongState=1)):this._playheadTime<=0&&(this._SetTime(0),this.SetPlaybackRate(-1*this.GetPlaybackRate()),h=!0,1===this._pingPongState?this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._pingPongState=0):r=!0:0===this._pingPongState&&(this._pingPongState=1)):l&&o&&(this._playbackRate>0?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._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._SetTimeAndReset(0)):(this._SetTime(n),r=!0)):this._playheadTime<=0&&(this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._SetTimeAndReset(n)):(this._SetTime(0),r=!0));const _=this._tracksLength;if(r){for(m=0;m<_;m++)this._tracks[m].SetEndState();return this.Stop(!0),void this.OnCompleted()}const c=this._beforeAndAfterTracksLength;for(m=0;m<c;m++){const t=this._beforeAndAfterTracks[m],e=t.GetStartOffset();this._playheadTime-e<0&&s-e>0?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;m<c;m++){const t=this._beforeAndAfterTracks[m],e=t.GetStartOffset();this._playheadTime-e<0&&s-e>0?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;e<this._propertyTracks.length;e++){const a=this._propertyTracks[e];if(a.GetPropertyName()===t)return a}}MaybeGetInstance(){this._instance||this.GetInstance()}IsInstanceValid(){return!!this._instance&&!this._instance.IsDestroyed()}CanInstanceBeValid(){if(!this.IsInstanceTrack())return!1;if(this._cleared)return!1;const t=this.GetInstanceUID(),e=this.GetRuntime().GetInstanceByUID(t);return!!e&&!e.IsDestroyed()}GetObjectClass(){if(!this.IsInstanceTrack())return;const t=this.GetObjectClassIndex();return-1!==t?this.GetRuntime().GetObjectClassByIndex(t):void 0}GetTrackIndexInTimeline(){return this._timeline.GetTracks().indexOf(this)}ClearInstance(){this._instance=null,this._instanceUid=NaN,this._worldInfo=null,this._objectClassIndex=NaN,this._cleared=!0}HasInstance(){return!!this._instance}GetInstance(){if(this._cleared)return;if(this._instance&&this.IsInstanceValid())return this._instance;const t=this.GetInstanceUID();return this._instance=this.GetRuntime().GetInstanceByUID(t),this._instance}SetInstance(t){if(this._cleared=!1,this._instance!==t){this.CleanCaches(),this._instance=t,this._objectClassIndex=t.GetObjectClass().GetIndex(),this._instanceUid=t.GetUID(),this._worldInfo=t.GetWorldInfo();for(const e of this.propertyTrackItems()){const a=e.propertyTrack,s=e.sourceAdapter;switch(a.GetSourceAdapterId()){case"instance-variable":{s.GetEditorIndex();const a=t.GetObjectClass(),r=a.GetInstanceVariableIndexByName(e.name),i=a.GetInstanceVariableName(r),n=a.GetInstanceVariableType(r);i===e.name&&n===e.type&&s.UpdateInstanceVariableIndex(r);break}case"behavior":{const a=e.behaviorType,r=this.GetObjectClass(),i=t.GetObjectClass(),n=s.GetBehaviorType(i);if(a&&n){const t=a.GetName();r.GetBehaviorIndexByName(t),i.GetBehaviorIndexByName(t),s.GetEditorIndex();s.UpdateBehaviorTypeSid(n.GetSID())}break}}}}}*propertyTrackItems(){for(const t of this._propertyTracks){const e=t.GetSourceAdapter(),a=this.GetObjectClass(),s={propertyTrack:t,sourceAdapter:e};switch(t.GetSourceAdapterId()){case"world-instance":s.property=t.GetPropertyName();break;case"instance-variable":{const t=e.GetEditorIndex();s.name=a.GetInstanceVariableName(t),s.type=a.GetInstanceVariableType(t);break}case"effect":{const t=a.GetEffectList(),r=e.GetEffectType(t);s.effectType=r;break}case"behavior":{const t=e.GetBehaviorType(a);s.behaviorType=t;break}case"plugin":s.plugin=a.GetPlugin()}yield s}}GetWorldInfo(){if(this._worldInfo&&this.IsInstanceValid())return this._worldInfo;const t=this.GetInstance();return t&&(this._worldInfo=t.GetWorldInfo()),this._worldInfo}GetTrackDataItem(){return this._trackDataItem}GetInstanceUID(){return isNaN(this._instanceUid)?this._trackDataItem.GetInstanceUID():this._instanceUid}SetInstanceUID(t){this._trackDataItem.SetInstanceUID(t)}GetInterpolationMode(){return this._trackDataItem.GetInterpolationMode()}SetInterpolationMode(t){this._trackDataItem.SetInterpolationMode(t)}GetResultMode(){return this._trackDataItem.GetResultMode()}GetId(){return this._trackDataItem.GetId()}GetStartOffset(){return this._trackDataItem.GetStartOffset()}GetLocalTotalTime(){return this._trackDataItem.GetLocalTotalTime()}SetLocalTotalTime(t){this._trackDataItem.SetLocalTotalTime(t)}SetResultMode(t){this._trackDataItem.SetResultMode(t)}SetEase(t){for(const e of this.GetKeyframeDataItems())e.SetEase(t);for(const e of this.GetPropertyTracks())e.SetEase(t)}GetEnable(){return this._trackDataItem.GetEnable()}SetEnable(t){this._trackDataItem.SetEnable(t)}GetObjectClassIndex(){return isNaN(this._objectClassIndex)?this._trackDataItem.GetObjectClassIndex():this._objectClassIndex}SetObjectClassIndex(t){this._trackDataItem.SetObjectClassIndex(t)}GetOriginalSize(){const t=this.GetInstance();return t&&t.IsOriginalSizeKnown()?t.GetOriginalSize():this._trackDataItem.GetOriginalSize()}SetOriginalWidth(t){this._trackDataItem.SetOriginalWidth(t)}SetOriginalHeight(t){this._trackDataItem.SetOriginalHeight(t)}GetType(){return this._trackDataItem.GetType()}GetName(){return this._trackDataItem.GetName()}IsInstanceTrack(){return 0===this.GetType()}IsValueTrack(){return 1===this.GetType()}IsAudioTrack(){return 2===this.GetType()}GetWorldInfoChange(){return this._worldInfoChange}GetRenderChange(){return this._renderChange}GetNeedsBeforeAndAfter(){return this._needsBeforeAndAfter}IsNested(){return this._isNested}SetResetState(){for(const t of this._propertyTracks)t.SetResetState();const t=this.GetTimeline(),e=t.GetTime();t.IsForwardPlayBack()?this._lastKeyframeDataItem=this._GetLastKeyFrameBeforeTime(e):this._lastKeyframeDataItem=this._GetFirstKeyFrameAfterTime(e),this._lastTime=NaN}SetInitialState(){if(this.MaybeGetInstance(),!this.IsInstanceValid()&&this.IsInstanceTrack())return;const t=this.GetTimeline().IsForwardPlayBack(),e=t?0:this.GetLocalTotalTime();for(const t of this._propertyTracks)t.SetInitialState(e),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),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()||"<no tags>"},s={GetTime:()=>e?e.GetTime()+this.GetStartOffset():this.GetLocalTotalTime(),GetTags:()=>e?.GetTagsString()||"<no tags>"}):(a={GetTime:()=>e?e.GetTime()+this.GetStartOffset():this.GetLocalTotalTime(),GetTags:()=>e?.GetTagsString()||"<no tags>"},s={GetTime:()=>t.GetTime()+this.GetStartOffset(),GetTags:()=>t.GetTagsString()||"<no tags>"}),[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;t<e;t++){const e=this._propertyTracks[t];e._SetUpdateState(),0===this._worldInfoChange&&1===e.GetWorldInfoChange()&&(this._worldInfoChange=1),0===this._renderChange&&1===e.GetRenderChange()&&(this._renderChange=1)}}BeforeInterpolate(t,e=!1){const a=this._propertyTracks.length;for(let s=0;s<a;s++)this._propertyTracks[s].BeforeInterpolate(t,e)}Interpolate(t,e=!1,a=!1,s=!1,r=!1,i=!1,n=!1){this._instance||this.GetInstance();const h=this._instance&&!this._instance.IsDestroyed(),o=0===this._trackDataItem._type;if((h||!o)&&!(i&&o&&this.GetObjectClass().IsGlobal())&&!((t-=this.GetStartOffset())<0)&&(this._lastTime!==t||!e||a||s||r||n)){this.MaybeSetInitialStateOfNestedTrack(t,e),this.MaybeTriggerKeyframeReachedConditions(t,e,r),!this.GetTimeline().IsPlaying()&&this.GetTimeline().GetStoppedOnKeyframe()&&(t=this.GetTimeline().GetStoppedOnKeyframe().GetTime());for(let e=0,r=this._propertyTracks.length;e<r;e++)this._propertyTracks[e].Interpolate(t,a,s,n);this.MaybeSetEndStateOfNestedTrack(t,e),0!==this._worldInfoChange&&(this._worldInfo||(this._worldInfo=this._instance.GetWorldInfo()),this._worldInfo&&this._worldInfo.SetBboxChanged()),this._lastTime=t}}AfterInterpolate(t,e=!1){const a=this._propertyTracks.length;for(let s=0;s<a;s++)this._propertyTracks[s].AfterInterpolate(t,e)}MaybeSetInitialStateOfNestedTrack(t,e){if(!e)return;if(!this._isNested)return;if(this._initialStateOfNestedSet)return;if(this.GetTimeline().IsForwardPlayBack()){if(t<0)return}else if(t>this.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<this._startOffsetTime)return void(this._audioPlaybackStarted=!1);const e=this._expressions.PlaybackRate.call(this._sdkInstance,this._audioTag),s=this._timeline.GetPlaybackRate();if(s!==e&&this._actions.SetPlaybackRate.call(this._sdkInstance,this._audioTag,s),this._audioPlaybackStarted)return;if(!this._propertyTrack.GetTimeline().IsPlaying())return;if(this._audioPlaybackStarted=!0,isNaN(this._pauseTime)){const e=self["performance"].now(),s=t-this._startOffsetTime;if("suspended"===this._sdkInstance.GetAudioContextState())return void(this._audioPlaybackStarted=!1);const i=s+(self["performance"].now()-e)/1e3;if(this._actions){let t=this.GetVolume();isNaN(t)?(this.SetVolume(0),t=0):this.SetVolume(t),this._actions.PlayFromTimeline.call(this._sdkInstance,this._fileArgs,t,this._audioTag,i)}}else{const t=this._pauseTime;this._pauseTime=NaN;const e=this._GetPauseVolume();this._pauseVolume=NaN;if("suspended"===this._sdkInstance.GetAudioContextState())return void(this._audioPlaybackStarted=!1);this._actions&&(this.SetVolume(e),this._actions.PlayFromTimeline.call(this._sdkInstance,this._fileArgs,e,this._audioTag,t))}break}case"volume":this._MaybeSetAudioSource(),super.Interpolate(t,e,s,i,a,o,r)}}GetInterpolatedValue(t,e,s){if(this._sdkInstance)switch(this._propertyTrack.GetPropertyName()){case"audioSource":return;case"volume":return this._MaybeSetAudioSource(),super.GetInterpolatedValue(t,e,s)}}Getter(t,e){return this._audioSource?this._audioSource.GetVolume():0}Setter(t,e,s,i){this._audioSource&&this._audioSource.SetVolume(this.Getter()+e),this._actions&&this._audioSource&&this._actions.SetVolume.call(this._sdkInstance,this._audioSource.GetAudioTag(),this._audioSource.GetVolume())}AbsoluteSetter(t,e,s){this._audioSource&&this._audioSource.SetVolume(e),this._actions&&this._audioSource&&this._actions.SetVolume.call(this._sdkInstance,this._audioSource.GetAudioTag(),this._audioSource.GetVolume())}DoesRounding(){return!0}_SaveToJson(){return{"audioPlaybackStarted":this._audioPlaybackStarted,"audioTag":this._audioTag,"pauseTime":this._pauseTime,"pauseVolume":this._pauseVolume,"volume":this._volume}}_LoadFromJson(t){t&&(this._audioPlaybackStarted=t["audioPlaybackStarted"],this._audioTag=t["audioTag"],this._pauseTime=t["pauseTime"],this._pauseVolume=t["pauseVolume"],this._volume=t["volume"],this._Initialize())}}C3.PropertyTrackState.AudioSourceAdapter=AudioSourceAdapter;
}

// timelines/state/propertyInterpolationAdapters/propertyInterpolationAdapter.js
{
const C3=self.C3;C3.PropertyTrackState.PropertyInterpolationAdapter=class{constructor(t){this._sourceAdapter=t,this._propertyTrack=t.GetPropertyTrack(),this._worldInfo=this._propertyTrack.GetTrack().GetWorldInfo(),this._property=this._propertyTrack.GetPropertyName(),this._firstAbsoluteUpdate=!1,this._saveState=null,this._target=null}Release(){this._sourceAdapter=null,this._propertyTrack=null,this._worldInfo=null,this._saveState=null,this._target=null}MayNeedBeforeAndAfterInterpolate(){return!1}TimelineRemoved(){}CleanCaches(){this._worldInfo=null,this._saveState=null,this._target=null}GetSourceAdapter(){return this._sourceAdapter}GetPropertyTrack(){return this._propertyTrack}GetWorldInfo(){return this._worldInfo||(this._worldInfo=this._propertyTrack.GetTrack().GetWorldInfo()),this._worldInfo}SetFirstAbsoluteUpdate(t){this._firstAbsoluteUpdate=!!t}GetFirstAbsoluteUpdate(){return this._firstAbsoluteUpdate}SetResetState(){}SetInitialState(){}SetResumeState(){}SetSaveState(){this._saveState=this.GetCurrentState()}ClearSaveState(){this._saveState=null}GetCurrentState(){}CompareInitialStateWithCurrent(){}CompareSaveStateWithCurrent(){}CanChange(t){return typeof this._Getter()===typeof t}BeforeChangeProperty(t,e){}ChangeProperty(t,e,r,a,s,o,i,n){}AfterChangeProperty(t,e){}_FirstKeyframeGetter(){return this._PickTimelinePlaybackMode(()=>{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<r.length;t++)i+=get_last_property_keyframe_value(r[t],a,"offsetOpacity");t._opacityFactor=0===i?1:i}},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;e<t;e++)this._propertyTracks[e].SetAbsoluteValueObject(this)}GetPropertyTracks(){return this._propertyTracks}SetUsed(){this._used=!0}GetUsed(){return this._used}SetValue(e){this._value=e}GetValue(){return this._value}SetPropertyKeyframeReached(e){this._propertyKeyframeReached=e}GetPropertyKeyframeReached(){return this._propertyKeyframeReached}SetEndState(e){this._endState=e}GetEndState(){return this._endState}Reset(){this._used=!1,this._value=0,this._propertyKeyframeReached=!1,this._endState=!1}}class NumericInterpolationAdapterForTimeline{constructor(e){this._numericInterpolationAdapter=e}Release(){this._numericInterpolationAdapter=null}GetType(){return 0}SetInitialState(){const e=this._numericInterpolationAdapter;this._numericInterpolationAdapter.GetPropertyTrack();return e._PickResultMode(()=>e._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;a<i;a++){const i=e[a];if(i.GetTime()===t)return i}}GetFirstKeyFrameDataItemHigherThan(t,a){const e=a.GetKeyframeData().GetKeyframeDataItemArray(),i=e.length;for(let a=0;a<i;a++){const i=e[a];if(i.GetTime()>t)return i}}GetFirstKeyFrameDataItemHigherOrEqualThan(t,a){const e=a.GetKeyframeData().GetKeyframeDataItemArray(),i=e.length;for(let a=0;a<i;a++){const i=e[a];if(i.GetTime()>=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;e<a;e++){const a=r[e];if(a.GetTime()===t)return a}}GetFirstPropertyKeyFrameDataItemHigherThan(t,e){const r=e.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray(),a=r.length;for(let e=0;e<a;e++){const a=r[e];if(a.GetTime()>t)return a}}GetFirstPropertyKeyFrameDataItemHigherOrEqualThan(t,e){const r=e.GetPropertyKeyframeData().GetPropertyKeyframeDataItemArray(),a=r.length;for(let e=0;e<a;e++){const a=r[e];if(a.GetTime()>=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;e<this._keyframeDataItems.length;e++){const t=this._keyframeDataItems[e];t.SetNext(this._keyframeDataItems[e+1]),t.SetLast(this._keyframeDataItems[e-1])}}GetTrackDataItem(){return this._trackDataItem}GetKeyframeDataItemCount(){return this._keyframeDataItems.length}GetKeyframeDataItemArray(){return this._keyframeDataItems}AddEmptyKeyframeDataItem(){const e=new KeyframeDataItem(null,this);return this._keyframeDataItems.push(e),this._LinkKeyframeDataItems(),e}DeleteKeyframeDataItems(e){for(const t of this._keyframeDataItems){if(!e(t))continue;const a=this._keyframeDataItems.indexOf(t);-1!==a&&(t.Release(),this._keyframeDataItems.splice(a,1))}this.SortKeyframeDataItems(),this._LinkKeyframeDataItems()}SortKeyframeDataItems(){this._keyframeDataItems.sort((e,t)=>e.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;r<a;r++){const a=t[r];if(a.GetId()===e)return this._addonInstance=a,this._addonInstance}return this._addonInstance=null,this._addonInstance}_SaveToJson(){const e=this._addonData;return{"addonDataJson":e?e._SaveToJson():e,"value":this._value,"aValue":this._aValue,"type":this._type,"time":this._time,"ease":this._ease,"enable":this._enable}}_LoadFromJson(e){e&&(e["addonDataJson"]&&this._addonData._SetFromJson(e["addonDataJson"]),this._value=e["value"],this._aValue=e["aValue"],this._type=e["type"],this._time=e["time"],this._ease=e["ease"],this._enable=e["enable"])}}C3.PropertyKeyframeData=class{constructor(e,t){this._propertyTrackDataItem=t,this._propertyKeyframeDataItems=[],this._propertyKeyframeDataItemsIncludingDisabled=[],C3.TimelineDataManager._CreateDataItems(this._propertyKeyframeDataItems,e,PropertyKeyframeDataItem,this),C3.TimelineDataManager._CreateDataItemsIncludingDisabled(this._propertyKeyframeDataItemsIncludingDisabled,e,PropertyKeyframeDataItem,this),this._LinkPropertyKeyframeDataItems()}Release(){this._propertyTrackDataItem=null;for(const e of this._propertyKeyframeDataItems)e.Release();C3.clearArray(this._propertyKeyframeDataItems),this._propertyKeyframeDataItems=null;for(const e of this._propertyKeyframeDataItemsIncludingDisabled)e.Release();C3.clearArray(this._propertyKeyframeDataItemsIncludingDisabled),this._propertyKeyframeDataItemsIncludingDisabled=null}_LinkPropertyKeyframeDataItems(){let e=this._propertyKeyframeDataItems;e.sort((e,t)=>e.GetTime()-t.GetTime());for(let t=0;t<e.length;t++){const a=e[t];t+1<e.length&&a.SetNext(e[t+1]),t-1>=0&&a.SetPrevious(e[t-1])}e=this._propertyKeyframeDataItemsIncludingDisabled,e.sort((e,t)=>e.GetTime()-t.GetTime());for(let t=0;t<e.length;t++){const a=e[t];t+1<e.length&&a.SetNext(e[t+1]),t-1>=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._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,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=0:this._resumePingPongState=0):(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong),r=!0):0===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong),this.IsPlaying()?this._pingPongState=1:this._resumePingPongState=1)):this._playheadTime<=0&&(this._SetTime(0),this.SetPlaybackRate(-1*this.GetPlaybackRate()),o=!0,1===this._pingPongState?this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,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=0:this._resumePingPongState=0):(r=!0,this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong)):0===this._pingPongState&&(this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenPingPong),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensPingPong),this.IsPlaying()?this._pingPongState=1:this._resumePingPongState=1)):h&&l&&(this._playbackRate>0?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._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._SetTimeAndReset(0),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),o=!0):(this._SetTime(a),r=!0)):this._playheadTime<=0&&(this._currentRepeatCount<this.GetRepeatCount()?(this._currentRepeatCount++,this._SetTimeAndReset(a),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnAnyTweenLoop),this._TweenTrigger(C3.Behaviors.Tween.Cnds.OnTweensLoop),o=!0):(this._SetTime(0),r=!0)),!this.IsReleased()&&this.IsPlaying()){if(r)return this._track.SetEndState(),this.Stop(!0),void this.OnCompleted();this._track.Interpolate(this._playheadTime,!0,!1,o,this._firstTick,!1),this._firstTick&&(this._firstTick=!1)}}_TweenTrigger(e){const t=this.GetInstance();this._behInst.PushTriggerTween(this),this._runtime.Trigger(e,t,this._behInst.GetBehaviorType()),this._behInst.PopTriggerTween()}_SaveToJson(){const e=super._SaveToJson(),t=this.GetTimelineDataItem();return Object.assign(e,{"tweenDataItemJson":t._SaveToJson(),"id":this._id,"destroyInstanceOnComplete":this._destroyInstanceOnComplete,"initialValueMode":this._initialValueMode})}_LoadFromJson(e){if(!e)return;this.GetTimelineDataItem()._LoadFromJson(e["tweenDataItemJson"]),super._LoadFromJson(e),this._id=e["id"],this._destroyInstanceOnComplete=e["destroyInstanceOnComplete"],this._initialValueMode=e["initialValueMode"],this._CacheTrack()}static IsPlaying(e){return e.IsPlaying()}static IsPaused(e){return e.IsPaused()}static IsPing(e){return!!e.GetPingPong()&&0===e.GetPingPongState()}static IsPong(e){return!!e.GetPingPong()&&1===e.GetPingPongState()}static Build(e){const t=e.runtime.GetTimelineManager(),s=new C3.TimelineDataItem;if(e.json){s._LoadFromJson(e.json["tweenDataItemJson"]);const n=new C3.TweenState(s,t);return n._LoadFromJson(e.json),n}{const n=new C3.TweenState(s,t);C3.IsArray(e.propertyTracksConfig)||(e.propertyTracksConfig=[e.propertyTracksConfig]),n.SetId(e.id),n.SetTags(e.tags),n.SetInitialValueMode(e.initialValueMode),n.SetDestroyInstanceOnComplete(e.releaseOnComplete),n.SetLoop(e.loop),n.SetPingPong(e.pingPong),n.SetTotalTime(e.time),n.SetStep(0),n.SetInterpolationMode("default"),n.SetResultMode(e.propertyTracksConfig[0].resultMode),n.SetRepeatCount(e.repeatCount);const i=n.AddTrack();i.SetInstanceUID(e.instance.GetUID()),i.SetInterpolationMode("default"),i.SetResultMode(e.propertyTracksConfig[0].resultMode),i.SetEnable(!0),i.SetObjectClassIndex(e.instance.GetObjectClass().GetIndex());const a=e.instance;let r,o;if(a.IsOriginalSizeKnown())[r,o]=a.GetOriginalSize();else{const t=e.instance.GetWorldInfo();r=t.GetWidth(),o=t.GetHeight()}i.SetOriginalWidth(r),i.SetOriginalHeight(o);const h=i.AddKeyframe();h.SetTime(0),h.SetEase("noease"),h.SetEnable(!0),h.SetTags("");const l=i.AddKeyframe();l.SetTime(e.time),l.SetEase("noease"),l.SetEnable(!0),l.SetTags("");for(const t of e.propertyTracksConfig){const s=i.AddPropertyTrack();s.SetSourceAdapterId(t.sourceId),s.SetSourceAdapterArgs(t.sourceArgs),s.SetPropertyName(t.property),s.SetPropertyType(t.type),s.SetMin(NaN),s.SetMax(NaN),s.SetInterpolationMode("default"),s.SetResultMode(t.resultMode),s.SetEnable(!0);const n=s.AddPropertyKeyframe();n.SetType(t.valueType),n.SetTime(0),n.SetEase(t.ease),n.SetEnable(!0),n.SetValue(t.startValue),n.SetAbsoluteValue(t.startValue);const a=s.AddPropertyKeyframe();a.SetType(t.valueType),a.SetTime(e.time),a.SetEase(t.ease),a.SetEnable(!0),a.SetValue(t.endValue),a.SetAbsoluteValue(t.endValue),s.GetSourceAdapter()}return n}}static SetInstanceUID(e,t){if(!isNaN(t))for(const s of e.GetTracks())s.SetInstanceUID(t)}static SetBehaviorInstance(e,t){e.SetBehaviorInstance(t)}GetITweenState(e,t){return this._iTweenState||(this._iTweenState=C3.New(self.ITweenState,this,e,t)),this._iTweenState}};
}

// timelines/tweens/tweenTrackState.js
{
const C3=self.C3;C3.TweenTrackState=class extends C3.TrackState{constructor(t,r){super(t,r),this._firstPropertyTrack=null,this._secondPropertyTrack=null,this._thirdPropertyTrack=null}static Create(t,r){return C3.New(C3.TweenTrackState,t,r)}_CachePropertyTracks(){1===this._propertyTracks.length?this._firstPropertyTrack=this._propertyTracks[0]:2===this._propertyTracks.length?(this._firstPropertyTrack=this._propertyTracks[0],this._secondPropertyTrack=this._propertyTracks[1]):(this._firstPropertyTrack=this._propertyTracks[0],this._secondPropertyTrack=this._propertyTracks[1],this._thirdPropertyTrack=this._propertyTracks[2])}CreatePropertyTrackStates(){for(const t of this._trackDataItem.GetPropertyTrackData().propertyTrackDataItems())this._propertyTracks.push(C3.TweenPropertyTrackState.Create(this,t));this._CachePropertyTracks()}AddPropertyTrack(){const t=this._trackDataItem.GetPropertyTrackData().AddEmptyPropertyTrackDataItem(),r=C3.TweenPropertyTrackState.Create(this,t);return this._propertyTracks.push(r),this._CachePropertyTracks(),r}SetInitialState(){if(this.MaybeGetInstance(),!this.IsInstanceValid()&&this.IsInstanceTrack())return;const t=this.GetTimeline().IsForwardPlayBack()?0:this.GetLocalTotalTime();for(const r of this._propertyTracks)r.SetInitialState(t),0===this._worldInfoChange&&1===r.GetWorldInfoChange()&&(this._worldInfoChange=1),0===this._renderChange&&1===r.GetRenderChange()&&(this._renderChange=1);this._needsBeforeAndAfter=0;this._propertyTracks.some(t=>t.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;e<this._transitionKeyframes.length;e++){const t=this._transitionKeyframes[e],a=this._transitionKeyframes[e+1],s=this._transitionKeyframes[e-1];t.SetNext(a),t.SetPrevious(s)}this._precalculatedSamples=new Map,this._transitionKeyframeCache=new Map,this._PreCalcSamples(),t&&Ease.AddCustomEase(this._name,(e,t,a,s)=>this.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(s<e)return t;if(s===e){for(;t;){const e=t.GetPrevious();if(!e)break;if(e.GetValueX()!==t.GetValueX())break;t=e}return t}}}}Interpolate(e,t,a,s){let n=e/s;if(this._linear){const n=this.GetTransitionKeyFrameAt(0),r=this.GetTransitionKeyFrameAt(1),i=t+(t+a)*n.GetValueY(),l=(t+a)*r.GetValueY()-i;return 0===s?i+l:Ease.NoEase(e,i,l,s)}0===s&&(n=1);let r=this.GetFirstTransitionKeyFrameLowerOrEqualThan(n),i=r.GetNext();if(!i){const e=r.GetPrevious(),t=r;r=e,i=t}const l=i.GetValueX()-r.GetValueX(),o=C3.mapToRange(n,r.GetValueX(),i.GetValueX(),0,l);if(r.IsSegmentLinear()||0===l){const e=t+(t+a)*r.GetValueY(),s=(t+a)*i.GetValueY()-e;return 0===l?1===o?e+s:e:Ease.NoEase(o,e,s,l)}const h=r.GetValueX(),u=r.GetValueY(),c=r.GetValueX()+r.GetStartAnchorX(),f=r.GetValueY()+r.GetStartAnchorY(),G=i.GetValueX()+i.GetEndAnchorX(),m=i.GetValueY()+i.GetEndAnchorY(),_=i.GetValueX(),y=i.GetValueY();let K=Ease.GetRuntimeEase("spline")(o,h,u,c,f,G,m,_,y,this._precalculatedSamples.get(r));return K+=r.GetValueY(),(1-K)*t+K*(t+a)}_PreCalcSamples(){this._precalculatedSamples.clear();for(let e=0;e<this._transitionKeyframes.length-1;e++){const t=this._transitionKeyframes[e];if(!t.GetStartEnable())continue;const a=t,s=this._transitionKeyframes[e+1];if(!s.GetEndEnable())continue;const n=a.GetValueX(),r=a.GetValueX()+a.GetStartAnchorX(),i=s.GetValueX()+s.GetEndAnchorX(),l=s.GetValueX();this._precalculatedSamples.set(a,Ease.GetBezierSamples(n,r,i,l))}}};
}

// timelines/transitions/transitionKeyframe.js
{
const C3=self.C3,VALUE_X=0,VALUE_Y=1,START_ANCHOR_X=2,START_ANCHOR_Y=3,END_ANCHOR_X=4,END_ANCHOR_Y=5,START_ENABLE=6,END_ENABLE=7,SEGMENT_MODE=8;C3.TransitionKeyframe=class extends C3.DefendedBase{constructor(t,e){super(),this._transition=t,this._valueX=e[0],this._valueY=e[1],this._startAnchorX=e[2],this._startAnchorY=e[3],this._endAnchorX=e[4],this._endAnchorY=e[5],this._startEnable=e[6],this._endEnable=e[7],this._segmentMode=e[8],this._next=null,this._prev=null}Release(){this._transition=null}static Create(t,e){return C3.New(C3.TransitionKeyframe,t,e)}SetNext(t){this._next=t}GetNext(){return this._next}SetPrevious(t){this._prev=t}GetPrevious(){return this._prev}GetValueX(){return this._valueX}GetValueY(){return this._valueY}GetStartAnchorX(){return this._startAnchorX}GetStartAnchorY(){return this._startAnchorY}GetEndAnchorX(){return this._endAnchorX}GetEndAnchorY(){return this._endAnchorY}GetStartEnable(){return this._startEnable}GetEndEnable(){return this._endEnable}IsSegmentLinear(){return"linear"===this._segmentMode}IsSegmentCubic(){return"cubic"===this._segmentMode}};
}

// timelines/transitions/transitionManager.js
{
const C3=self.C3;C3.TransitionManager=class extends C3.DefendedBase{constructor(s){super(),this._runtime=s,this._transitions=[]}Release(){for(const s of this._transitions)s.Release();C3.clearArray(this._transitions),this._transitions=null}Create(s){this._transitions.push(C3.Transition.Create(s))}};
}

// templates/templateManager.js
{
const C3=self.C3;C3.TemplateManager=class extends C3.DefendedBase{constructor(e){super(),this._runtime=e,this._templateDataMap=null,this._instanceToTemplateNameMap=null,this._instanceDestroy=e=>this._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;r<e.length;r++)if(e[r].GetName()===t)return!0;return!1}return!1}MarkForRelease(){this._markForRelease=!0}IsInTriggerState(){return this._triggerCount>0}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.size<t.size?e:t)].filter(t=>e.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<n;++e)s[e].RemoveInstances(t)}};
}

// events/stacks/sol.js
{
const C3=self.C3;C3.Sol=class extends C3.DefendedBase{constructor(s){super(),this._stack=s,this._objectClass=this._stack.GetObjectClass(),this._eventStack=this._objectClass.GetRuntime().GetEventStack(),this._selectAll=!0,this._instances=[],this._elseInstances=[]}Release(){this.ClearArrays(),this._stack=null,this._objectClass=null,this._eventStack=null}ClearArrays(){C3.clearArray(this._instances),C3.clearArray(this._elseInstances)}GetObjectClass(){return this._objectClass}IsSelectAll(){return this._selectAll}HasAnyInstances(){return this._selectAll?!!this._objectClass.GetInstanceCount():!!this._instances.length}GetInstances(){return this._selectAll?this._objectClass.GetInstances():this._instances}HasAnyElseInstances(){return!!this._elseInstances.length}GetElseInstances(){return this._elseInstances}GetExpressionInstances(){const s=this.GetInstances();return s.length?s:this._elseInstances}Reset(){this._selectAll=!0,C3.clearArray(this._elseInstances)}Clear(){this._selectAll=!0}Copy(s){s.IsSelectAll()?this.Reset():(this._selectAll=!1,C3.shallowAssignArray(this._instances,s._instances),C3.clearArray(this._elseInstances))}_PushInstance(s){this._instances.push(s)}_PushElseInstance(s){this._elseInstances.push(s)}_SetSelectAll(s){this._selectAll=!!s}_GetOwnInstances(){return this._instances}_GetOwnElseInstances(){return this._elseInstances}SetSinglePicked(s){this._selectAll=!1,C3.clearArray(this._instances),this._instances.push(s)}SetArrayPicked(s){this._selectAll=!1,C3.shallowAssignArray(this._instances,s)}SetSetPicked(s){this._selectAll=!1,C3.clearArray(this._instances);for(const e of s)this._instances.push(e)}AddElseInstances(s,e){for(const t of e)s.has(t)||this._elseInstances.push(t)}TransferElseInstancesToOwn(s){for(const e of s)this._instances.push(e);C3.arrayRemoveAllInSet(this._elseInstances,s)}ClearElseInstances(){C3.clearArray(this._elseInstances)}PickOne(s){if(s)if(this._eventStack.GetCurrentStackFrame().GetCurrentEvent().IsOrBlock()){this.IsSelectAll()&&(C3.clearArray(this._instances),C3.shallowAssignArray(this._elseInstances,s.GetObjectClass().GetInstances()),this._selectAll=!1);const e=this._elseInstances.indexOf(s);-1!==e&&(this._instances.push(this._elseInstances[e]),this._elseInstances.splice(e,1))}else this.SetSinglePicked(s)}RemoveInstances(s){C3.arrayRemoveAllInSet(this._instances,s),C3.arrayRemoveAllInSet(this._elseInstances,s)}};
}

// events/stacks/eventStack.js
{
const C3=self.C3;C3.EventStack=class extends C3.DefendedBase{constructor(t){super(),this._eventSheetManager=t,this._runtime=this._eventSheetManager.GetRuntime(),this._stack=[],this._stack.push(C3.New(C3.EventStackFrame,this,null)),this._index=0,this._expFuncStack=[]}Release(){for(const t of this._stack)t.Release();C3.clearArray(this._stack),C3.clearArray(this._expFuncStack),this._eventSheetManager=null,this._runtime=null}GetEventSheetManager(){return this._eventSheetManager}GetRuntime(){return this._runtime}GetCurrentStackFrame(){return this._stack[this._index]}GetAllStackFrames(){return this._stack}GetCurrentStackFrameIndex(){return this._index}Push(t){const e=this._stack,n=++this._index;if(n===e.length){const n=C3.New(C3.EventStackFrame,this,t);return e.push(n),n}{const s=e[n];return s.Reset(t),s}}Pop(){--this._index}PushExpFunc(t){this._expFuncStack.push(t)}PopExpFunc(){this._expFuncStack.pop()}GetCurrentExpFuncStackFrame(){const t=this._expFuncStack;return 0===t.length?null:t.at(-1)}};
}

// events/stacks/eventStackFrame.js
{
const C3=self.C3;C3.EventStackFrame=class extends C3.DefendedBase{constructor(t,e){super(),this._stack=t,this._runtime=this._stack.GetRuntime(),this._currentEvent=e,this._cndIndex=0,this._actIndex=0,this._lastEventTrue=!1,this._elseBranchRan=!1,this._expressionObjectClass=null,this._functionReturnType=0,this._functionReturnValue=0,this._dynamicSolModifiers=null}Release(){this.Reset(null),this._stack=null,this._runtime=null}Reset(t){this._currentEvent=t,this._cndIndex=0,this._actIndex=0,this._lastEventTrue=!1,this._elseBranchRan=!1,this._dynamicSolModifiers=null}_Restore(t,e){this._currentEvent=t,this._cndIndex=0,this._actIndex=e}ResetQuick(){this._cndIndex=0,this._actIndex=0}GetCurrentEvent(){return this._currentEvent}SetCurrentEvent(t){this._currentEvent=t}GetConditionIndex(){return this._cndIndex}SetConditionIndex(t){this._cndIndex=t}GetActionIndex(){return this._actIndex}SetActionIndex(t){this._actIndex=t}SetLastEventTrue(t){this._lastEventTrue=!!t}GetLastEventTrue(){return this._lastEventTrue}SetElseBranchRan(t){this._elseBranchRan=!!t}GetElseBranchRan(){return this._elseBranchRan}SetExpressionObjectClass(t){this._expressionObjectClass=t}GetExpressionObjectClass(){return this._expressionObjectClass}InitCallFunctionExpression(t,e){this._functionReturnType=t,this._functionReturnValue=e}GetFunctionReturnType(){return this._functionReturnType}SetFunctionReturnValue(t){this._functionReturnValue=t}GetFunctionReturnValue(){return this._functionReturnValue}IsSolModifierAfterCnds(){const t=this._currentEvent;return!!t.IsSolWriterAfterCnds()||this._cndIndex<t.GetConditionCount()-1&&!!t.GetSolModifiers().length}SetDynamicSolModifiers(t){this._dynamicSolModifiers=t}GetDynamicSolModifiers(){return this._dynamicSolModifiers}};
}

// events/stacks/localVarStack.js
{
const C3=self.C3;C3.LocalVarStack=class extends C3.DefendedBase{constructor(t){super(),this._eventSheetManager=t,this._runtime=this._eventSheetManager.GetRuntime(),this._stack=[],this._index=-1,this._current=null,this._initialValues=[]}Release(){C3.clearArray(this._stack),this._eventSheetManager=null,this._runtime=null}_SetInitialValues(t){this._initialValues=t;const e=this._initialValues.slice(0);this._stack.push(e),this._index=0,this._current=e}GetEventSheetManager(){return this._eventSheetManager}GetRuntime(){return this._runtime}GetCurrent(){return this._current}Push(){const t=++this._index,e=this._stack;t===e.length?e.push(this._initialValues.slice(0)):C3.shallowAssignArray(e[t],this._initialValues),this._current=e[t]}Pop(){this._current=this._stack[--this._index]}};
}

// events/stacks/loopStack.js
{
const C3=self.C3;C3.LoopStack=class extends C3.DefendedBase{constructor(t){super(),this._eventSheetManager=t,this._runtime=this._eventSheetManager.GetRuntime(),this._stack=[],this._index=-1}Release(){C3.clearArray(this._stack),this._eventSheetManager=null,this._runtime=null}GetEventSheetManager(){return this._eventSheetManager}GetRuntime(){return this._runtime}IsInLoop(){return this._index>=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;s<n;++s)if(t[s]!==e[s])return!1;return!0}C3.EventSheetManager=class extends C3.DefendedBase{constructor(t){super(),this._runtime=t,this._allSheets=[],this._sheetsByName=new Map,this._allGroups=[],this._groupsByName=new Map,this._blocksBySid=new Map,this._cndsBySid=new Map,this._actsBySid=new Map,this._allUniqueSolModifiers=new Map,this._eventVarsBySid=new Map,this._nextLocalVarIndex=0,this._allGlobalVars=[],this._allLocalVars=[],this._localVarInitialValues=[],this._functionBlocksByName=new Map,this._customActionBlocksMap=new Map,this._eventStack=C3.New(C3.EventStack,this),this._localVarStack=C3.New(C3.LocalVarStack,this),this._loopStack=C3.New(C3.LoopStack,this),this._triggersToPostInit=[],this._queuedTriggers=[],this._queuedDebugTriggers=[],this._runningEventsDepth=0,this._executingTriggerDepth=0,this._blockFlushingDepth=0,this._scheduledWaits=[],this._asyncActionPromises=[],this._signalTags=[],this._signalPromises=new Map,this._instSignals=new Map,self["c3_callFunction"]=(t,e)=>this._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;s<n;++s){const n=e[s];if(IsSolArrayIdentical(t,n))return n}return e.push(t),t}_GetNextLocalVarIndex(t){return this._localVarInitialValues.push(t.GetInitialValue()),this._nextLocalVarIndex++}GetEventStack(){return this._eventStack}GetCurrentEventStackFrame(){return this.GetEventStack().GetCurrentStackFrame()}GetCurrentEvent(){return this.GetCurrentEventStackFrame().GetCurrentEvent()}GetCurrentCondition(){const t=this.GetCurrentEventStackFrame();return t.GetCurrentEvent().GetConditionAt(t.GetConditionIndex())}GetCurrentAction(){const t=this.GetCurrentEventStackFrame();return t.GetCurrentEvent().GetActionAt(t.GetActionIndex())}GetLocalVarStack(){return this._localVarStack}GetLoopStack(){return this._loopStack}GetAllLocalVariablesInScope(t){const e=[];for(t=t.GetScopeParent();t;)C3.appendArray(e,t._GetAllLocalVariablesInScope()),t=t.GetScopeParent();return e}_GetLocalVariablesScriptInterface(t){const e={};for(const s of this.GetAllLocalVariablesInScope(t))e[s.GetJsPropName()]=s._GetScriptInterfaceDescriptor();return Object.create(Object.prototype,e)}GetEventVariableBySID(t){return this._eventVarsBySid.get(t)||null}GetEventBlockBySID(t){return this._blocksBySid.get(t)||null}GetConditionBySID(t){return this._cndsBySid.get(t)||null}GetActionBySID(t){return this._actsBySid.get(t)||null}GetFunctionBlockByName(t){return this._functionBlocksByName.get(t.toLowerCase())||null}GetCustomActionBlockByName(t,e){let s=this._customActionBlocksMap.get((t.GetName()+"."+e).toLowerCase());if(s)return s;if(!t.IsFamily())for(const n of t.GetFamilies())if(s=this._customActionBlocksMap.get((n.GetName()+"."+e).toLowerCase()),s)return s;return null}GetAllGlobalVariables(){return this._allGlobalVars}GetAllLocalVariables(){return this._allLocalVars}ResetAllGlobalsToInitialValue(t){for(const t of this._allGlobalVars)t.ResetToInitialValue();if(t)for(const t of this._allLocalVars)t.IsStatic()&&t.ResetToInitialValue()}GetEventGroupByName(t){return this._groupsByName.get(t.toLowerCase())||null}GetEventGroupBySID(t){const e=this._blocksBySid.get(t);return e&&e.IsGroup()?e:null}GetAllGroups(){return this._allGroups}ResetAllGroupsInitialActivation(){for(const t of this._allGroups)t.ResetInitialActivation()}_ResetAllHasRunFlags(){for(const t of this._allSheets)t._ResetHasRunFlag()}RunEvents(t){this._ResetAllHasRunFlags(),this._runningEventsDepth++;for(const e of t.runningLayouts()){const t=e.GetEventSheet();t&&(this._runtime.PushCurrentLayout(e),t.Run(),this._runtime.PopCurrentLayout())}this._runningEventsDepth--}async DebugRunEvents(t){this._ResetAllHasRunFlags(),this._runningEventsDepth++;for(const e of this._DebugRunEventsGen(t))await this._runtime.DebugBreak(e);this._runningEventsDepth--}*_DebugRunEventsGen(t){for(const e of t.runningLayouts()){const t=e.GetEventSheet();t&&(this._runtime.PushCurrentLayout(e),yield*t.DebugRun(),this._runtime.PopCurrentLayout())}}_Trigger(t,e,s,n){let i=!1;if(!t.GetMainRunningLayout())return this.QueueTrigger(e,s,n);this._executingTriggerDepth++;for(const r of t.runningLayouts()){const t=r.GetEventSheet();if(!t)continue;this._runtime.PushCurrentLayout(r);for(const r of t.deepIncludes()){const t=r._Trigger(e,s,n);i=i||t}const o=t._Trigger(e,s,n);i=i||o,this._runtime.PopCurrentLayout()}return this._executingTriggerDepth--,i}*_DebugTrigger(t,e,s,n){let i=!1;if(!t.GetMainRunningLayout())return this.QueueTrigger(e,s,n);this._executingTriggerDepth++;for(const r of t.runningLayouts()){const t=r.GetEventSheet();if(!t)continue;this._runtime.PushCurrentLayout(r);for(const r of t.deepIncludes()){const t=yield*r._DebugTrigger(e,s,n);i=i||t}const o=yield*t._DebugTrigger(e,s,n);i=i||o,this._runtime.PopCurrentLayout()}return this._executingTriggerDepth--,i}QueueTrigger(t,e,s){return this._queuedTriggers.push([t,e,s]),!1}QueueDebugTrigger(t,e,s){let n=null;const i=new Promise(t=>n=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;t<r;++t){const r=a[t]._FastTrigger(e,s,n);i=i||r}const l=o._FastTrigger(e,s,n);return i=i||l,this._runtime.PopCurrentLayout(),this._executingTriggerDepth--,i}*_DebugFastTrigger(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;t<r;++t){const r=yield*a[t]._DebugFastTrigger(e,s,n);i=i||r}const l=yield*o._DebugFastTrigger(e,s,n);return i=i||l,this._runtime.PopCurrentLayout(),this._executingTriggerDepth--,i}GetTriggerDepth(){return this._executingTriggerDepth}_SetTriggerDepth(t){this._executingTriggerDepth=t}IsInTrigger(){return this.GetTriggerDepth()>0}_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;e<s;++e)t[e].GetSolStack().Clear()}PushCleanSol(t){for(let e=0,s=t.length;e<s;++e)t[e].GetSolStack().PushClean()}PushCopySol(t){for(let e=0,s=t.length;e<s;++e)t[e].GetSolStack().PushCopy()}PopSol(t){for(let e=0,s=t.length;e<s;++e)t[e].GetSolStack().Pop()}GetDynamicSolModifiersSet(){const t=new Set,e=this._eventStack.GetAllStackFrames(),s=this._eventStack.GetCurrentStackFrameIndex();for(let n=0;n<=s;++n){const s=e[n].GetDynamicSolModifiers();if(s)for(const e of s)t.add(e)}return t}PushCleanSolDynamic(t){const e=this.GetDynamicSolModifiersSet();if(0===e.size)return null;const s=e.difference(C3.ensureSet(t));if(0===s.size)return null;for(const t of s)t.GetSolStack().PushClean();return[...s]}AddScheduledWait(){const t=C3.New(C3.ScheduledWait,this);return this._scheduledWaits.push(t),t}scheduledWaits(){return this._scheduledWaits}RunScheduledWaits(){if(!this._scheduledWaits.length)return;const t=this.GetCurrentEventStackFrame();let e=!1;this._runningEventsDepth++;const s=this._executingTriggerDepth;for(let s=0,n=this._scheduledWaits.length;s<n;++s){const n=this._scheduledWaits[s];n._ShouldRun()&&n._Run(t),n.ShouldRelease()&&(e=!0)}this._executingTriggerDepth=s,e&&(this._FilterScheduledWaitsToRelease(),t.Reset(null)),this._runningEventsDepth--}async DebugRunScheduledWaits(){if(!this._scheduledWaits.length)return;const t=this.GetCurrentEventStackFrame();let e=!1;this._runningEventsDepth++;const s=this._executingTriggerDepth;for(let s=0,n=this._scheduledWaits.length;s<n;++s){const n=this._scheduledWaits[s];n._ShouldRun()&&await n._DebugRun(t),n.ShouldRelease()&&(e=!0)}this._executingTriggerDepth=s,e&&(this._FilterScheduledWaitsToRelease(),t.Reset(null)),this._runningEventsDepth--}_FilterScheduledWaitsToRelease(){const t=C3.arrayFilterOut(this._scheduledWaits,t=>t.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.triggerDepth<t),e}Signal(t){const e=t.toLowerCase();this._signalTags.push(e),this._runtime.Trigger(C3.Plugins.System.Cnds.OnSignal,null),this._signalTags.pop();for(const t of this._runtime.GetEventSheetManager().scheduledWaits())t.IsSignal()&&t.GetSignalTag()===e&&t.SetSignalled();const s=this._signalPromises.get(e);s&&(s.resolve(),this._signalPromises.delete(e))}WaitForSignal(t){const e=t.toLowerCase(),s=this._signalPromises.get(e);if(s)return s.promise;{let t=null;const s=new Promise(e=>t=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.length<n.length){e=e.slice(0);do{e.push(n[e.length].GetInitialValue())}while(e.length<n.length)}const i=s.GetEventBlock();return i.RunAsExpressionOrJSFunctionCall(i.GetSolModifiersIncludingParents(),!1,s.GetReturnType(),s.GetDefaultReturnValue(),null,...e)}};
}

// events/eventSheet.js
{
const C3=self.C3;C3.EventSheet=class extends C3.DefendedBase{constructor(e,t){super(),this._eventSheetManager=e,this._runtime=e.GetRuntime(),this._name=t[0],this._events=[],this._triggers=new Map,this._fastTriggers=new Map,this._eventsByDisplayNumber=new Map,this._hasRun=!1,this._shallowIncludes=[],this._deepIncludes=[],this._alreadyIncludedSheets=new Set;for(const e of t[1])this._CreateEvent(e,null,this._events);this._perfRecord=this._runtime.IsDebug()?{type:"sheet",name:this._name,totalTimeCounter:0,children:[]}:null}Release(){this._eventSheetManager=null,this._runtime=null}_CreateEvent(e,t,s){switch(e[0]){case 0:case 3:this._CreateEventBlock(e,t,s);break;case 1:this._CreateEventVariable(e,t,s);break;case 2:this._CreateInclude(e,t,s);break;case 4:this._CreateFunctionBlock(e,t);break;case 5:this._CreateScriptBlock(e,t,s);break;case 6:this._CreateCustomACEBlock(e,t);break;default:throw new Error("invalid event type")}}_CreateEventBlock(e,t,s){const n=C3.EventBlock.Create(this,t,e);if(n.IsOrBlock()){s.push(n);const e=n.GetConditions();for(let t=0,s=e.length;t<s;++t)e[t].IsTrigger()&&this._InitTrigger(n,t)}else n.IsTrigger()?this._InitTrigger(n,0):s.push(n)}_CreateFunctionBlock(e,t){const s=C3.FunctionBlock.CreateFunctionBlock(this,t,e);this._eventSheetManager._RegisterFunctionBlock(s)}_CreateCustomACEBlock(e,t){const s=C3.FunctionBlock.CreateCustomACEBlock(this,t,e);this._eventSheetManager._RegisterFunctionBlock(s)}_CreateEventVariable(e,t,s){const n=C3.EventVariable.Create(this,t,e);s.push(n)}_CreateInclude(e,t,s){const n=C3.EventInclude.Create(this,t,e);s.push(n)}_CreateScriptBlock(e,t,s){const n=C3.EventScript.Create(this,t,e);s.push(n)}_InitTrigger(e,t){e.IsOrBlock()||this._eventSheetManager._AddTriggerToPostInit(e);const s=e.GetConditionAt(t),n=s._GetFunc(),r=s.GetObjectClass();if(s.IsFastTrigger()){let i=this._fastTriggers.get(r);i||(i=new Map,this._fastTriggers.set(r,i));const l=s.GetFastTriggerValue().toLowerCase();let o=i.get(n);o||(o=new Map,i.set(n,o));let a=o.get(l);a||(a=[],o.set(l,a)),a.push([e,t])}else{let i=this._triggers.get(r);i||(i={methodMap:new Map,behaviors:new Map},this._triggers.set(r,i));const l=s.GetBehaviorType();let o;l?(o=i.behaviors.get(l),o||(o=new Map,i.behaviors.set(l,o))):o=i.methodMap;let a=o.get(n);a||(a=[],o.set(n,a)),a.push([e,t])}}_PostInit(){const e=this._events;for(let t=0,s=e.length;t<s;++t){const n=t<s-1&&e[t+1]instanceof C3.EventBlock&&e[t+1].IsElseBlock();e[t]._PostInit(n)}}_AddShallowInclude(e){this._shallowIncludes.push(e)}_UpdateDeepIncludes(){C3.clearArray(this._deepIncludes),this._AddDeepIncludes(this),this._alreadyIncludedSheets.clear()}_AddDeepIncludes(e){const t=e._deepIncludes,s=e._alreadyIncludedSheets;for(const n of this._shallowIncludes){const r=n.GetIncludeSheet();n.IsActive()&&e!==r&&!s.has(r)&&(s.add(r),r._AddDeepIncludes(e),t.push(r))}}deepIncludes(){return this._deepIncludes}GetEventSheetManager(){return this._eventSheetManager}GetRuntime(){return this._runtime}GetName(){return this._name}_RegisterEventByDisplayNumber(e,t){this._eventsByDisplayNumber.set(t,e)}_GetEventByDisplayNumber(e){return this._eventsByDisplayNumber.get(e)||null}_ResetHasRunFlag(){this._hasRun=!1}Run(){if(this._hasRun)return;const e=this._runtime,t=e.IsCPUProfiling(),s=t?performance.now():0;this._hasRun=!0;const n=this.GetEventSheetManager(),r=n.GetCurrentEventStackFrame();for(const t of this._events)t.Run(r),n.ClearSol(t.GetSolModifiers()),n.ClearAsyncActionPromises(),e.FlushPendingInstances();r.Reset(null),t&&(this._perfRecord.totalTimeCounter+=performance.now()-s)}*DebugRun(){if(this._hasRun)return;this._hasRun=!0;const e=this._runtime,t=this.GetEventSheetManager(),s=t.GetCurrentEventStackFrame();for(const n of this._events)yield*n.DebugRun(s),t.ClearSol(n.GetSolModifiers()),t.ClearAsyncActionPromises(),e.FlushPendingInstances();s.Reset(null)}_Trigger(e,t,s){if(!t)return this._TriggerForClass(e,t,null,null);{const n=t.GetObjectClass();let r=!1,i=this._TriggerForClass(e,t,n,s);r=r||i;for(const l of n.GetFamilies())i=this._TriggerForClass(e,t,l,s),r=r||i}}_TriggerForClass(e,t,s,n){const r=this._triggers.get(s);if(!r)return!1;const i=n?r.behaviors.get(n):r.methodMap;if(!i)return!1;const l=i.get(e);if(!l)return!1;let o=!1;for(const[e,s]of l){const n=this._ExecuteTrigger(t,e,s);o=o||n}return o}*_DebugTrigger(e,t,s){if(!t)return yield*this._DebugTriggerForClass(e,t,null,null);{const n=t.GetObjectClass();let r=!1,i=yield*this._DebugTriggerForClass(e,t,n,s);r=r||i;for(const l of n.GetFamilies())i=yield*this._DebugTriggerForClass(e,t,l,s),r=r||i}}*_DebugTriggerForClass(e,t,s,n){const r=this._triggers.get(s);if(!r)return!1;const i=n?r.behaviors.get(n):r.methodMap;if(!i)return!1;const l=i.get(e);if(!l)return!1;let o=!1;for(const[e,s]of l){let n;n=e.DebugCanRunFast()?this._ExecuteTrigger(t,e,s):yield*this._DebugExecuteTrigger(t,e,s),o=o||n}return o}_FastTrigger(e,t,s){const n=t.GetObjectClass(),r=this._fastTriggers.get(n);if(!r)return!1;const i=r.get(e);if(!i)return!1;const l=i.get(s);if(!l)return!1;let o=!1;for(let e=0,t=l.length;e<t;++e){const t=l[e],s=this._ExecuteTrigger(null,t[0],t[1]);o=o||s}return o}*_DebugFastTrigger(e,t,s){const n=t.GetObjectClass(),r=this._fastTriggers.get(n);if(!r)return!1;const i=r.get(e);if(!i)return!1;const l=i.get(s);if(!l)return!1;let o=!1;for(let e=0,t=l.length;e<t;++e){const t=l[e],s=t[0],n=t[1];let r;r=s.DebugCanRunFast()?this._ExecuteTrigger(null,s,n):yield*this._DebugExecuteTrigger(null,s,n),o=o||r}return o}_ExecuteTrigger(e,t,s){const n=this._runtime,r=this._eventSheetManager,i=r.GetCurrentEvent(),l=r.GetEventStack(),o=r.GetTriggerDepth();let a=!1,c=null,u=null;if(i){const e=new Set(t.GetSolModifiersIncludingParents());for(const t of i.GetSolModifiersIncludingParents())e.add(t);c=[...e],u=r.PushCleanSolDynamic(e)}else c=t.GetSolModifiersIncludingParents();r.PushCleanSol(c);const g=o>1;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;t<s;++t)if(!e[t].RunPreTrigger(h)){_=!1;break}}return _&&(t.IsOrBlock()?t.RunOrBlockTrigger(h,s):t.Run(h),a=h.GetLastEventTrue()),l.Pop(),g&&r.GetLocalVarStack().Pop(),r.PopSol(c),u&&r.PopSol(u),i||1!==o||(r.ClearAsyncActionPromises(),r.IsFlushingBlocked()||n.FlushPendingInstances()),a}*_DebugExecuteTrigger(e,t,s){const n=this._runtime,r=this._eventSheetManager,i=r.GetCurrentEvent(),l=r.GetEventStack(),o=r.GetTriggerDepth();let a=!1;i&&r.PushCleanSol(i.GetSolModifiersIncludingParents()),r.PushCleanSol(t.GetSolModifiersIncludingParents());const c=o>1;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;t<s;++t)if(!(yield*e[t].DebugRunPreTrigger(u))){g=!1;break}}return g&&(t.IsOrBlock()?yield*t.DebugRunOrBlockTrigger(u,s):yield*t.DebugRun(u),a=u.GetLastEventTrue()),l.Pop(),c&&r.GetLocalVarStack().Pop(),r.PopSol(t.GetSolModifiersIncludingParents()),i&&r.PopSol(i.GetSolModifiersIncludingParents()),i||1!==o||(r.ClearAsyncActionPromises(),r.IsFlushingBlocked()||n.FlushPendingInstances()),a}_GetPerfRecord(){return this._perfRecord}};
}

// events/eventBlock.js
{
const C3=self.C3,EMPTY_ARRAY=[];function NoActions(t,e){return!0}function*DebugNoActions(t,e){return!0}C3.EventBlock=class extends C3.DefendedBase{constructor(t,e,n){super(),this._eventSheet=t,this._runtime=t.GetRuntime(),this._parent=e,this._scopeParent=null,this._eventStack=this._runtime.GetEventSheetManager().GetEventStack(),this._solModifiers=[],this._solModifiersIncludingParents=[],this._hasGotSolModifiersIncludingParents=!1,this._isSolWriterAfterCnds=!1,this._isTopLevelGroup=!1,this._hasElseBlock=!1,this._isOrBlock=!!n[2],this._isElseBlock=!1,this._triggerParents=null,this._conditions=[],this._actions=[],this._subEvents=[],this._RunActions=NoActions,this._DebugRunActions=DebugNoActions,this._isGroup=!1,this._isInitiallyActive=!1,this._groupName="",this._isGroupActive=!1,this._containedIncludes=null,this._perfRecord=null,this._sid=n[4],this._displayNumber=n[5],this._eventSheet._RegisterEventByDisplayNumber(this,this._displayNumber),this._debugData=this._runtime.IsDebug()?{isBreakpoint:n[3][0],isBreakable:n[3][1],canRunAllConditionsFast:!1,canRunAllActionsFast:!1,canRunAllSubEventsFast:!1,canRunSelfFast:!1}:null,this.GetEventSheetManager()._RegisterEventBlock(this),3===n[0]&&this._InitGroup(n[1]);let s=0;for(const t of n[6]){const e=C3.Condition.Create(this,t,s++);this._conditions.push(e),this._AddSolModifier(e.GetObjectClass())}s=0;for(const t of n[7]){const e=C3.Action.Create(this,t,s++);this._actions.push(e)}if(9===n.length){const t=n[8];for(const e of t)this._eventSheet._CreateEvent(e,this,this._subEvents)}this._conditions.length&&(this._isElseBlock=null===this._conditions[0].GetObjectClass()&&this._conditions[0]._GetFunc()===C3.Plugins.System.Cnds.Else),0===this._conditions.length&&(this._conditions=EMPTY_ARRAY),0===this._actions.length&&(this._actions=EMPTY_ARRAY),0===this._subEvents.length&&(this._subEvents=EMPTY_ARRAY)}static Create(t,e,n){return C3.New(C3.EventBlock,t,e,n)}_InitGroup(t){this._isGroup=!0,this._isInitiallyActive=!!t[0],this._isGroupActive=this._isInitiallyActive,this._groupName=t[1].toLowerCase(),this._containedIncludes=[],this.GetEventSheetManager()._RegisterGroup(this),this._runtime.IsDebug()&&(this._perfRecord={type:"group",name:t[1],totalTimeCounter:0,children:[]})}_AddContainedInclude(t){this._containedIncludes.push(t)}_AddContainerSolModifierToList(t,e){for(const n of t.GetContainer().objectTypes())e.includes(n)||e.push(n)}_AddSolModifierToList(t,e){if(t)if(e.includes(t)||e.push(t),t.IsFamily())for(const n of t.GetFamilyMembers())n.IsInContainer()&&this._AddContainerSolModifierToList(n,e);else t.IsInContainer()&&this._AddContainerSolModifierToList(t,e)}_AddSolModifier(t){this._AddSolModifierToList(t,this._solModifiers)}_AddParentSolModifier(t){this._AddSolModifierToList(t,this._solModifiersIncludingParents)}SetAllSolModifiers(){this._solModifiers=this._runtime.GetAllObjectClasses()}_PostInit(t){this._hasElseBlock=!!t,this._IdentifyTopLevelGroup(),this._IdentifyTriggerParents();for(const t of this._conditions)t._PostInit();if(this._actions.length>0){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;t<n;++t){const s=t<n-1&&e[t+1]instanceof C3.EventBlock&&e[t+1].IsElseBlock();e[t]._PostInit(s)}this._debugData&&this._UpdateCanRunFast(),this._perfRecord&&this._GetPerfRecordParent()._GetPerfRecord().children.push(this._perfRecord)}_GetPerfRecord(){return this._perfRecord}_GetPerfRecordParent(){let t=this.GetParent();for(;t;){if(t.IsGroup())return t;t=t.GetParent()}return this._eventSheet}_UpdateCanRunFast(){const t=this._debugData;t.canRunAllConditionsFast=this._conditions.every(t=>t.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&&t<this._actions.length}GetSubEvents(){return this._subEvents}_GetAllLocalVariablesInScope(){return this._subEvents.filter(t=>t instanceof C3.EventVariable)}RunPreTrigger(t){t.SetCurrentEvent(this);const e=this._conditions;let n=0===e.length;for(let s=0,i=e.length;s<i;++s){const i=e[s];if(t.SetConditionIndex(s),i.IsLooping())throw new Error("trigger cannot be used as sub-event to a loop");if(i.Run())n=!0;else if(!this._isOrBlock)return!1}return!this._isOrBlock||n}RunOrBlockTrigger(t,e){t.SetCurrentEvent(this),t.SetConditionIndex(e),this._conditions[e].Run()&&(this._RunActions(t,0)&&this._RunSubEvents(t),t.SetLastEventTrue(!0))}*DebugRunPreTrigger(t){t.SetCurrentEvent(this);const e=this._conditions;let n=0===e.length;for(let s=0,i=e.length;s<i;++s){const i=e[s];if(t.SetConditionIndex(s),i.IsLooping())throw new Error("trigger cannot be used as sub-event to a loop");let o;if(o=i.DebugCanRunFast()?i.Run():yield*i.DebugRun(),o)n=!0;else if(!this._isOrBlock)return!1}return!this._isOrBlock||n}*DebugRunOrBlockTrigger(t,e){t.SetCurrentEvent(this),t.SetConditionIndex(e);const n=this._conditions[e];let s;if(s=n.DebugCanRunFast()?n.Run():yield*n.DebugRun(),s){let e;e=this.DebugCanRunActionsFast()?this._RunActions(t,0):yield*this._DebugRunActions(t,0),e&&(this.DebugCanRunSubEventsFast()?this._RunSubEvents():yield*this._DebugRunSubEvents()),t.SetLastEventTrue(!0)}}Run(t){t.SetCurrentEvent(this),this._isElseBlock||t.SetElseBranchRan(!1),this._isOrBlock?this._RunOrBlock(t):this._RunAndBlock(t)}*DebugRun(t){(this.IsDebugBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),t.SetCurrentEvent(this),this._isElseBlock||t.SetElseBranchRan(!1),this._isOrBlock?yield*this._DebugRunOrBlock(t):yield*this._DebugRunAndBlock(t)}_RunOrBlock(t){const e=this._conditions;let n=0===e.length;for(let s=0,i=e.length;s<i;++s){const i=e[s];if(i.IsTrigger())continue;t.SetConditionIndex(s);const o=i.Run();n=n||o}t.SetLastEventTrue(n),n&&(this._RunActions(t,0)&&this._RunSubEvents(t),this._hasElseBlock&&t.SetElseBranchRan(!0))}*_DebugRunOrBlock(t){const e=this._conditions;let n=0===e.length;for(let s=0,i=e.length;s<i;++s){const i=e[s];if(i.IsTrigger())continue;let o;t.SetConditionIndex(s),o=i.DebugCanRunFast()?i.Run():yield*i.DebugRun(),n=n||o}if(t.SetLastEventTrue(n),n){let e;e=this.DebugCanRunActionsFast()?this._RunActions(t,0):yield*this._DebugRunActions(t,0),e&&(this.DebugCanRunSubEventsFast()?this._RunSubEvents():yield*this._DebugRunSubEvents()),this._hasElseBlock&&t.SetElseBranchRan(!0)}}_RunAndBlock(t){const e=this._conditions;for(let n=0,s=e.length;n<s;++n){const s=e[n];t.SetConditionIndex(n);if(!s.Run())return void t.SetLastEventTrue(!1)}t.SetLastEventTrue(!0),this._RunActions(t,0)&&this._RunSubEvents(t),t.GetLastEventTrue()&&this._hasElseBlock&&t.SetElseBranchRan(!0)}*_DebugRunAndBlock(t){const e=this._conditions;for(let n=0,s=e.length;n<s;++n){const s=e[n];let i;if(t.SetConditionIndex(n),i=s.DebugCanRunFast()?s.Run():yield*s.DebugRun(),!i)return void t.SetLastEventTrue(!1)}let n;t.SetLastEventTrue(!0),n=this.DebugCanRunActionsFast()?this._RunActions(t,0):yield*this._DebugRunActions(t,0),n&&(this.DebugCanRunSubEventsFast()?this._RunSubEvents():yield*this._DebugRunSubEvents()),t.GetLastEventTrue()&&this._hasElseBlock&&t.SetElseBranchRan(!0)}_RunActions_Fast(t,e){const n=this._actions;for(let s=e,i=n.length;s<i;++s){const e=n[s];t.SetActionIndex(s),e.Run()}return!0}*_DebugRunActions_Fast(t,e){const n=this._actions;for(let s=e,i=n.length;s<i;++s){const e=n[s];t.SetActionIndex(s),e.DebugCanRunFast()?e.Run():yield*e.DebugRun()}return!0}_RunActions_ReturnValue(t,e){const n=this.GetEventSheetManager(),s=this._actions;for(let i=e,o=s.length;i<o;++i){const e=s[i];t.SetActionIndex(i);const o=e.Run();if(e.CanBailOut()&&!0===o)return!1;e.IsAsync()&&o instanceof Promise&&n.AddAsyncActionPromise(o)}return!0}*_DebugRunActions_ReturnValue(t,e){const n=this.GetEventSheetManager(),s=this._actions;for(let i=e,o=s.length;i<o;++i){const e=s[i];let o;if(t.SetActionIndex(i),o=e.DebugCanRunFast()?e.Run():yield*e.DebugRun(),e.CanBailOut()&&!0===o)return!1;e.IsAsync()&&o instanceof Promise&&n.AddAsyncActionPromise(o)}return!0}_ResumeActionsAndSubEvents(t){this._RunActions(t,t.GetActionIndex())&&this._RunSubEvents()}*_DebugResumeActionsAndSubEvents(t){(yield*this._DebugRunActions(t,t.GetActionIndex()))&&(yield*this._DebugRunSubEvents())}_RunSubEvents(){if(!this._subEvents.length)return;const t=this.IsGroup()&&this._runtime.IsCPUProfiling(),e=t?performance.now():0,n=this._eventStack,s=n.Push(this);this._isSolWriterAfterCnds?this._RunSubEvents_SolWriterAfterCnds(s):this._RunSubEvents_Fast(s),n.Pop(),t&&(this._perfRecord.totalTimeCounter+=performance.now()-e)}_RunSubEvents_SolWriterAfterCnds(t){const e=this._isGroup,n=this._isTopLevelGroup,s=this.GetEventSheetManager(),i=this._subEvents;for(let o=0,r=i.length,u=r-1;o<r;++o){const r=i[o],l=r.GetSolModifiers(),a=!n||!e&&o<u;a&&s.PushCopySol(l),r.Run(t),a?s.PopSol(l):s.ClearSol(l)}}_RunSubEvents_Fast(t){const e=this._subEvents;for(let n=0,s=e.length;n<s;++n)e[n].Run(t)}*_DebugRunSubEvents(){if(!this._subEvents.length)return;const t=this._eventStack,e=t.Push(this);this._isSolWriterAfterCnds?yield*this._DebugRunSubEvents_SolWriterAfterCnds(e):yield*this._DebugRunSubEvents_Fast(e),t.Pop()}*_DebugRunSubEvents_SolWriterAfterCnds(t){const e=this._isGroup,n=this._isTopLevelGroup,s=this.GetEventSheetManager(),i=this._subEvents;for(let o=0,r=i.length,u=r-1;o<r;++o){const r=i[o],l=r.GetSolModifiers(),a=!n||!e&&o<u;a&&s.PushCopySol(l),yield*r.DebugRun(t),a?s.PopSol(l):s.ClearSol(l)}}*_DebugRunSubEvents_Fast(t){const e=this._subEvents;for(let n=0,s=e.length;n<s;++n)yield*e[n].DebugRun(t)}Retrigger(t,e){e.ResetQuick();const n=this._conditions;if(!this.IsOrBlock())for(let s=t.GetConditionIndex()+1,i=n.length;s<i;++s){const t=n[s];e.SetConditionIndex(s);if(!t.Run())return!1}return this._RunActions(e,0)&&this._RunSubEvents(e),!0}*DebugRetrigger(t,e){e.ResetQuick();const n=this._conditions;if(!this.IsOrBlock())for(let s=t.GetConditionIndex()+1,i=n.length;s<i;++s){const t=n[s];let i;if(e.SetConditionIndex(s),i=t.DebugCanRunFast()?t.Run():yield*t.DebugRun(),!i)return!1}let s;return s=this.DebugCanRunActionsFast()?this._RunActions(e,0):yield*this._DebugRunActions(e,0),s&&(this.DebugCanRunSubEventsFast()?this._RunSubEvents():yield*this._DebugRunSubEvents()),!0}DebugCanRunFast(){return!this.IsDebugBreakpoint()&&!this._runtime.DebugBreakNext()&&this._debugData.canRunSelfFast}DebugCanRunActionsFast(){return!this._runtime.DebugBreakNext()&&this._debugData.canRunAllActionsFast}DebugCanRunSubEventsFast(){return!this._runtime.DebugBreakNext()&&this._debugData.canRunAllSubEventsFast}_CheckParentsOKToRun(t){if(this.GetParent()){const e=this.GetTriggerParents();for(let n=0,s=e.length;n<s;++n)if(!e[n].RunPreTrigger(t))return!1}return!0}*_DebugCheckParentsOKToRun(t){if(this.GetParent()){const e=this.GetTriggerParents();for(let n=0,s=e.length;n<s;++n)if(!(yield*e[n].DebugRunPreTrigger(t)))return!1}return!0}_EvaluateFunctionCallParameters(t,e,n){if(e.length>0)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;s<n;++s)e[s].SetValue(t[s].Get(0))}SetFunctionParameters(t){const e=this._functionParameters;for(let s=0,n=e.length;s<n;++s)e[s].SetValue(t[s])}CaptureFunctionParameters(){return this._functionParameters.map(t=>t.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<e;++t)this._numberedNodes.push(C3.ExpNode.CreateNode(this,n[t]));this._numberedNodes.length?this.Get=this.GetExpression:(this.Get=GetExpressionFunc(this._expressionNumber),this._isConstant=!0)}_GetNode(t){if(t<0||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;t<e;++t){const e=C3.Parameter.Create(this._owner,r[t],0);this._subParams.push(e),this._variadicRet.push(0),e.IsConstant()||(this._isConstant=!1)}this.Get=this.GetVariadic}_PostInit(){for(const t of this._subParams)t._PostInit()}GetVariadic(){const t=this._subParams,e=this._variadicRet;for(let s=0,r=t.length;s<r;++s)e[s]=t[s].Get(0);return e}}class EaseParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._easeIndex=r[1],this.Get=this.GetEase,this._isConstant=!0}GetEase(){return this._easeIndex}}class TilemapBrushParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._brushIndex=r[1],this.Get=this.GetTilemapBrush,this._isConstant=!0}GetTilemapBrush(){return this._brushIndex}}class TemplateExpressionParameter extends ExpressionParameter{constructor(t,e,s,r){super(t,e,s,r),this.Get=this.GetTemplateName,this._isConstant=!1}GetTemplateName(){return this._expressionFunc()}}class FlowchartParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._flowchartDataItem=this.GetRuntime().GetFlowchartManager().GetFlowchartDataItemByName(r[1]),this.Get=this.GetFlowchartName,this._isConstant=!0}GetFlowchartName(){return this._flowchartDataItem.GetName()}}class Model3dParameter extends C3.Parameter{constructor(t,e,s,r){super(t,e,s),this._model3dDataItem=this.GetRuntime().GetModel3dManager().GetModel3dDataItemByName(r[1]),this.Get=this.GetModel3dName,this._isConstant=!0}GetModel3dName(){return this._model3dDataItem.GetName()}}
}

// events/condition.js
{
const C3=self.C3,assert=self.assert;function EvalParams(t,e){for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(0)}const EMPTY_PARAMS_ARRAY=[],noop=function(){};C3.Condition=class extends C3.DefendedBase{constructor(t,e,s){if(super(),this._eventBlock=t,this._runtime=t.GetRuntime(),this._index=s,this._func=this._runtime.GetObjectReference(e[1]),this._isTrigger=e[3]>0,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<n;++s){const n=t[s];n.VariesPerInstance()||(e[s]=n.Get(0))}return s.IsSelectAll()?this._RunObject_FirstFilter(s):this._RunObject_NextFilter(s)}*_DebugRunObject(){return(this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._RunObject()}_EvaluateVaryingParameters(t){const e=this._parameters,s=this._results;for(let n=0,i=e.length;n<i;++n){const i=e[n];i.VariesPerInstance()&&(s[n]=i.Get(t))}}_RunObject_FirstFilter(t){const e=this._objectClass,s=e.IsFamily(),n=e.GetFamilyIndex(),i=this._behaviorIndex,r=i>=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<c;++e){const c=a[e];let g;if(h&&this._EvaluateVaryingParameters(e),r){const t=s?c.GetObjectClass().GetFamilyBehaviorOffset(n):0;g=l.apply(c.GetBehaviorInstances()[i+t].GetSdkInstance(),o)}else g=l.apply(c.GetSdkInstance(),o);C3.xor(g,u)?t._PushInstance(c):_&&t._PushElseInstance(c)}return e.FinishCondition(!0),t._SetSelectAll(!1),e.ApplySolToContainer(),t.HasAnyInstances()}_RunObject_NextFilter(t){const e=this._objectClass,s=e.IsFamily(),n=e.GetFamilyIndex(),i=e.IsInContainer(),r=this._behaviorIndex,a=r>=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<e;++t){const e=I[t];let m;if(h&&this._EvaluateVaryingParameters(t),a){const t=s?e.GetObjectClass().GetFamilyBehaviorOffset(n):0;m=l.apply(e.GetBehaviorInstances()[r+t].GetSdkInstance(),o)}else m=l.apply(e.GetSdkInstance(),o);C3.xor(m,u)?(b=!0,d?(c.push(e),i&&e._PushSiblingsToSolInstances()):(I[G]=e,i&&e._SetSiblingsToSolInstancesIndex(G),++G)):d?(I[G]=e,i&&e._SetSiblingsToSolElseInstancesIndex(G),++G):_&&(g.push(e),i&&e._PushSiblingsToSolElseInstances())}C3.truncateArray(I,G),i&&e._TruncateContainerSols(d,G);const m=b;return d&&!b&&(b=this._OrBlockCheckInstances(c)),e.FinishCondition(m||_),_?b:t.HasAnyInstances()}_OrBlockCheckInstances(t){const e=this._objectClass,s=e.IsFamily(),n=e.GetFamilyIndex(),i=this._anyParamVariesPerInstance,r=this._behaviorIndex,a=r>=0,h=this._results,o=this._func,l=this._isInverted;for(let e=0,u=t.length;e<u;++e){const u=t[e];let _;if(i&&this._EvaluateVaryingParameters(e),a){const t=s?u.GetObjectClass().GetFamilyBehaviorOffset(n):0;_=o.apply(u.GetBehaviorInstances()[r+t].GetSdkInstance(),h)}else _=o.apply(u.GetSdkInstance(),h);if(C3.xor(_,l))return!0}return!1}ReevaluateParameter(t,e){return this._parameters[t].Get(e)}GetFastTriggerValue(){const t=this._parameters;if(!t.length)throw new Error("no parameters");return t[0]._GetFastTriggerValue()}_SaveToJson(){if(!this._savedData||!this._savedData.size)return null;const t={};for(const[e,s]of this._savedData.entries()){let n=s;"collmemory"===e&&(n=[...s.entries()].map(t=>[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<n;++s)e[s]=t[s].Get(0)}const EMPTY_PARAMS_ARRAY=[],noop=function(){},noopGenerator=function*(){},FLAG_CANPICKANYOBJECTCLASS=1,FLAG_COPYPICKED=2,FLAG_CUSTOM_ACE=4,FLAG_IS_ASYNC=8,FLAG_CAN_BAIL_OUT=16;C3.Action=class extends C3.DefendedBase{constructor(t,e,s){super(),this._eventBlock=t;const n=t.GetRuntime();this._runtime=n,this._index=s,this._sid=e.length>=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<n;++s)this._func.apply(e[s].GetSdkInstance(),t)}*_DebugRunObject_ParamsConst(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results,e=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=e.length;s<n;++s)yield*this._func.apply(e[s].GetSdkInstance(),t)}else this._RunObject_ParamsConst()}_RunObject_ParamsDontVary(){const t=this._results;EvalParams(this._parameters,t);const e=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=e.length;s<n;++s)this._func.apply(e[s].GetSdkInstance(),t)}*_DebugRunObject_ParamsDontVary(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._results;EvalParams(this._parameters,t);const e=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=e.length;s<n;++s)yield*this._func.apply(e[s].GetSdkInstance(),t)}else this._RunObject_ParamsDontVary()}_RunObject_AllParamsVary(){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances();for(let i=0,a=n.length;i<a;++i){const a=n[i];for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(i);s.apply(a.GetSdkInstance(),e)}}*_DebugRunObject_AllParamsVary(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances();for(let i=0,a=n.length;i<a;++i){const a=n[i];for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(i);yield*s.apply(a.GetSdkInstance(),e)}}else this._RunObject_AllParamsVary()}_RunObject_SomeParamsVary(){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=t.length;s<n;++s){const n=t[s];n.VariesPerInstance()||(e[s]=n.Get(0))}for(let i=0,a=n.length;i<a;++i){const a=n[i];for(let s=0,n=t.length;s<n;++s){const n=t[s];n.VariesPerInstance()&&(e[s]=n.Get(i))}s.apply(a.GetSdkInstance(),e)}}*_DebugRunObject_SomeParamsVary(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances();for(let s=0,n=t.length;s<n;++s){const n=t[s];n.VariesPerInstance()||(e[s]=n.Get(0))}for(let i=0,a=n.length;i<a;++i){const a=n[i];for(let s=0,n=t.length;s<n;++s){const n=t[s];n.VariesPerInstance()&&(e[s]=n.Get(i))}yield*s.apply(a.GetSdkInstance(),e)}}else this._RunObject_SomeParamsVary()}_RunObject_BeforeAfterHooks(){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass,i=n.GetSdkType(),a=n.GetCurrentSol().GetInstances();i.BeforeRunAction(s);for(let n=0,i=a.length;n<i;++n){const i=a[n];for(let s=0,i=t.length;s<i;++s)e[s]=t[s].Get(n);s.apply(i.GetSdkInstance(),e)}i.AfterRunAction(s)}*_DebugRunObject_BeforeAfterHooks(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass,i=n.GetSdkType(),a=n.GetCurrentSol().GetInstances();i.BeforeRunAction(s);for(let n=0,i=a.length;n<i;++n){const i=a[n];for(let s=0,i=t.length;s<i;++s)e[s]=t[s].Get(n);yield*s.apply(i.GetSdkInstance(),e)}i.AfterRunAction(s)}else this._RunObject_BeforeAfterHooks()}_GetStaticActionThis(){return this._behaviorType?this._behaviorType.GetBehavior().GetSdkVersion()>=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;t<e;++t){const e=n[t];e.VariesPerInstance()||(a[t]=e.Get(0))}for(let t=0,h=l.length;t<h;++t){const h=l[t];if(i)for(let e=0,s=n.length;e<s;++e){const s=n[e];s.VariesPerInstance()&&(a[e]=s.Get(t))}const u=e?h.GetObjectClass().GetFamilyBehaviorOffset(s):0;r.apply(h.GetBehaviorInstances()[o+u].GetSdkInstance(),a)}}*_DebugRunBehavior(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){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;t<e;++t){const e=n[t];e.VariesPerInstance()||(a[t]=e.Get(0))}for(let t=0,h=l.length;t<h;++t){const h=l[t];if(i)for(let e=0,s=n.length;e<s;++e){const s=n[e];s.VariesPerInstance()&&(a[e]=s.Get(t))}const u=e?h.GetObjectClass().GetFamilyBehaviorOffset(s):0;yield*r.apply(h.GetBehaviorInstances()[o+u].GetSdkInstance(),a)}}else this._RunBehavior()}_RunObject_Async(){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances(),i=[];for(let a=0,r=n.length;a<r;++a){const r=n[a];for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(a);i.push(s.apply(r.GetSdkInstance(),e))}return Promise.all(i)}*_DebugRunObject_Async(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._parameters,e=this._results,s=this._func,n=this._objectClass.GetCurrentSol().GetInstances(),i=[];for(let a=0,r=n.length;a<r;++a){const r=n[a];for(let s=0,n=t.length;s<n;++s)e[s]=t[s].Get(a);i.push(yield*s.apply(r.GetSdkInstance(),e))}return Promise.all(i)}return this._RunObject_Async()}_RunBehavior_Async(){const t=this._objectClass,e=t.IsFamily(),s=t.GetFamilyIndex(),n=this._parameters,i=this._results,a=this._func,r=this._behaviorIndex,o=t.GetCurrentSol().GetInstances(),l=[];for(let t=0,h=o.length;t<h;++t){const h=o[t];for(let e=0,s=n.length;e<s;++e)i[e]=n[e].Get(t);const u=e?h.GetObjectClass().GetFamilyBehaviorOffset(s):0;l.push(a.apply(h.GetBehaviorInstances()[r+u].GetSdkInstance(),i))}return Promise.all(l)}*_DebugRunBehavior_Async(){if((this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this._DebugReturnsGenerator()){const t=this._objectClass,e=t.IsFamily(),s=t.GetFamilyIndex(),n=this._parameters,i=this._results,a=this._func,r=this._behaviorIndex,o=t.GetCurrentSol().GetInstances(),l=[];for(let t=0,h=o.length;t<h;++t){const h=o[t];for(let e=0,s=n.length;e<s;++e)i[e]=n[e].Get(t);const u=e?h.GetObjectClass().GetFamilyBehaviorOffset(s):0;l.push(yield*a.apply(h.GetBehaviorInstances()[r+u].GetSdkInstance(),i))}return Promise.all(l)}return this._RunBehavior_Async()}async RunUserScript(){try{await this._func()}catch(t){console.error(`Unhandled exception running script %c${this._eventBlock.GetEventSheet().GetName()}, event ${this._eventBlock.GetDisplayNumber()}, action ${this.GetDebugIndex()+1}:`,"font-size: 1.2em; font-weight: bold;",t),self.C3Debugger&&self.C3Debugger._SetLastErrorScript(this),C3.EventScript.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"),C3.EventScript.SetHadUserScriptException())}}*DebugRunUserScript(){return(this.IsBreakpoint()||this._runtime.DebugBreakNext())&&(yield this),this.RunUserScript()}_SaveToJson(){return this._savedData&&this._savedData.size?{"ex":C3.ToSuperJSON(this._savedData)}:null}_LoadFromJson(t){if(this._savedData&&(this._savedData.clear(),this._savedData=null),!t)return;const e=t["ex"];e&&(this._savedData=C3.FromSuperJSON(e))}};
}

// events/commonACEs.js
{
const C3=self.C3,tempColor=new C3.Color,AnySDK={},SDKv1={},SDKv2={};let runtime=null;C3.CommonACES_SetRuntime=function(t){runtime=t};const IInstance=self.IInstance,IObjectClass=self.IObjectClass,ILayer=self.ILayer;function GetInst(t){return t instanceof IInstance?runtime._UnwrapScriptInterface(t):t.GetInstance()}function GetWorldInfo(t){return GetInst(t).GetWorldInfo()}function GetInst_SDKv2(t){return runtime._UnwrapScriptInterface(t)}function GetWorldInfo_SDKv2(t){return GetInst_SDKv2(t).GetWorldInfo()}function GetObjectClass(t){return t instanceof IObjectClass?runtime._UnwrapScriptInterface(t):t}function GetLayer(t){return t instanceof ILayer?runtime._UnwrapScriptInterface(t):t}SDKv1.CompareX=function(t,e){return C3.compare(this.GetWorldInfo().GetX(),t,e)},SDKv2.CompareX=function(t,e){return C3.compare(this.x,t,e)},SDKv1.CompareY=function(t,e){return C3.compare(this.GetWorldInfo().GetY(),t,e)},SDKv2.CompareY=function(t,e){return C3.compare(this.y,t,e)},SDKv1.CompareZ=function(t,e,n){const o=this.GetWorldInfo(),s=0===t?o.GetZ():o.GetTotalZ();return C3.compare(s,e,n)},SDKv2.CompareZ=function(t,e,n){const o=0===t?this.z:this.totalZ;return C3.compare(o,e,n)},SDKv1.IsOnScreen=function(){return this.GetWorldInfo().IsInViewport2()},SDKv2.IsOnScreen=function(){return this.isOnScreen()},AnySDK.IsOutsideLayout=function(){const t=GetWorldInfo(this),e=t.GetLayout(),n=t.GetBoundingBox();return n.getRight()<0||n.getBottom()<0||n.getLeft()>e.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;s<l;++s){const l=i[s],c=l.GetWorldInfo(),u=C3.distanceSquared(c.GetX(),c.GetY(),e,n);0===r.length||0===t&&u<a||1===t&&u>a?(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;e<s;++e){const s=n[e],i=s.GetWorldInfo(),r=o.GetWorldInfo(),a=i.GetLayer().GetIndex(),l=r.GetLayer().GetIndex();0===t?(a>l||a===l&&i.GetZIndex()>r.GetZIndex())&&(o=s):(a<l||a===l&&i.GetZIndex()<r.GetZIndex())&&(o=s)}return e.PickOne(o),!0},SDKv1.MoveToTop=function(){this.GetWorldInfo().ZOrderMoveToTop()},SDKv2.MoveToTop=function(){this.moveToTop()},SDKv1.MoveToBottom=function(){this.GetWorldInfo().ZOrderMoveToBottom()},SDKv2.MoveToBottom=function(){this.moveToBottom()},AnySDK.MoveToLayer=function(t){(t=GetLayer(t))&&GetWorldInfo(this).ZOrderMoveToLayer(t)},AnySDK.ZMoveToObject=function(t,e){const n=0===t;if(!(e=GetObjectClass(e)))return;const o=GetInst(this),s=e.GetFirstPicked(o);s&&o.GetWorldInfo().ZOrderMoveAdjacentToInstance(s,n)},AnySDK.LayerNumber=function(){return GetWorldInfo(this).GetLayer().GetIndex()},AnySDK.LayerName=function(){return GetWorldInfo(this).GetLayer().GetName()},SDKv1.ZIndex=function(){return this.GetWorldInfo().GetZIndex()},SDKv2.ZIndex=function(){return this.zIndex},AnySDK.IsEffectEnabled=function(t){const e=GetInst(this),n=e.GetObjectClass().GetEffectList().GetEffectTypeByName(t);if(!n)return;const o=n.GetIndex();return e.GetWorldInfo().GetInstanceEffectList().IsEffectIndexActive(o)},AnySDK.SetEffectEnabled=function(t,e){const n=GetInst(this),o=n.GetObjectClass().GetEffectList().GetEffectTypeByName(e);if(!o)return;const s=o.GetIndex(),i=1===t,r=n.GetWorldInfo().GetInstanceEffectList();r.IsEffectIndexActive(s)!==i&&(r.SetEffectIndexActive(s,i),r.UpdateActiveEffects(),runtime.UpdateRender())},AnySDK.SetEffectParam=function(t,e,n){const o=GetInst(this),s=o.GetObjectClass().GetEffectList().GetEffectTypeByName(t);if(!s)return;e=Math.floor(e);const i=s.GetShaderProgram().GetParameterType(e);if(!i)return;"color"===i?(tempColor.setFromRgbValue(n),n=tempColor):"percent"===i&&(n/=100);const r=s.GetIndex(),a=o.GetWorldInfo().GetInstanceEffectList();a.SetEffectParameter(r,e,n)&&a.IsEffectIndexActive(r)&&runtime.UpdateRender()};const tempRect=C3.New(C3.Rect),tempCandidates1=[],tempCandidates2=[];let needsCollisionFinish=!1,rPickType=null,rPickFromElseInstances=!1;const rToPick=new Set;function CollMemory_Add(t,e,n,o){e.GetUID()<n.GetUID()?t.Set(e,n,o):t.Set(n,e,o)}function CollMemory_Remove(t,e,n){e.GetUID()<n.GetUID()?t.Delete(e,n):t.Delete(n,e)}function CollMemory_RemoveInstance(t,e){t.DeleteEither(e)}function CollMemory_Get(t,e,n){return e.GetUID()<n.GetUID()?t.Get(e,n):t.Get(n,e)}function DoOverlapCondition(t,e,n,o){if(!e)return!1;const s=0!==n||0!==o,i=t.GetWorldInfo(),r=runtime.GetCollisionEngine(),a=runtime.GetCurrentCondition(),l=a.GetEventBlock().IsOrBlock(),c=a.GetObjectClass(),u=a.IsInverted(),S=e.GetCurrentSol(),f=c!==e;let G;rPickType=e,needsCollisionFinish=f&&!u,rPickFromElseInstances=!1;let d=0,h=0,I=!1;S.IsSelectAll()?(tempRect.setFromAABB3D(i.GetBoundingBox()),tempRect.offset(n,o),r.GetCollisionCandidates(i.GetLayer(),e,tempRect,tempCandidates2),G=tempCandidates2):l?runtime.IsCurrentConditionFirst()&&!S._GetOwnElseInstances().length&&S._GetOwnInstances().length?G=S._GetOwnInstances():(G=S._GetOwnElseInstances(),rPickFromElseInstances=!0):G=S._GetOwnInstances(),s&&(d=i.GetX(),h=i.GetY(),i.OffsetXY(n,o),i.SetBboxChanged());for(const e of G)if(r.TestOverlap(t,e)){if(I=!0,u)break;f&&rToPick.add(e)}return s&&(i.SetXY(d,h),i.SetBboxChanged()),C3.clearArray(tempCandidates2),I}function FinishCollisionConditionPicking(t){const e=runtime.GetCurrentEvent().IsOrBlock(),n=rPickType.GetCurrentSol(),o=n._GetOwnInstances(),s=n._GetOwnElseInstances();n.IsSelectAll()?(n.SetSetPicked(rToPick),e&&(C3.clearArray(s),n.AddElseInstances(rToPick,rPickType.GetInstances()))):e?rPickFromElseInstances?n.TransferElseInstancesToOwn(rToPick):(n.AddElseInstances(rToPick,o),n.SetSetPicked(rToPick)):n.SetSetPicked(rToPick),rPickType.ApplySolToContainer()}function FinishCollisionCondition(t,e){needsCollisionFinish&&(e&&FinishCollisionConditionPicking(t),rToPick.clear(),rPickType=null,needsCollisionFinish=!1)}function*DebugOnCollision(t){if(!t)return!1;const e=this.GetRuntime(),n=e.GetCollisionEngine(),o=e.GetEventSheetManager(),s=o.GetEventStack(),i=o.GetCurrentCondition(),r=i.GetObjectClass(),a=i.GetSavedDataMap(),l=i.GetUnsavedDataMap(),c=s.GetCurrentStackFrame(),u=e.GetTickCount(),S=u-1,f=c.GetCurrentEvent(),G=s.Push(f);let d=a.get("collmemory");d||(d=C3.New(C3.PairMap),a.set("collmemory",d)),l.get("collisionCreatedDestroyCallback")||(l.set("collisionCreatedDestroyCallback",!0),e.Dispatcher().addEventListener("instancedestroy",t=>CollMemory_RemoveInstance(d,t.instance)));const h=r.GetCurrentSol(),I=t.GetCurrentSol(),C=h.GetInstances();let m=null;for(let e=0;e<C.length;++e){const s=C[e];I.IsSelectAll()?(n.GetCollisionCandidates(s.GetWorldInfo().GetLayer(),t,s.GetWorldInfo().GetBoundingBox(),tempCandidates1),m=tempCandidates1,n.AddRegisteredCollisionCandidates(s,t,m)):m=I.GetInstances();for(let e=0;e<m.length;++e){const i=m[e];if(n.TestOverlap(s,i)||n.CheckRegisteredCollision(s,i)){const e=CollMemory_Get(d,s,i);let n=!1,a=-2;"number"==typeof e&&(n=!0,a=e);const l=!n||a<S;if(CollMemory_Add(d,s,i,u),l){const e=f.GetSolModifiers();o.PushCopySol(e);const n=r.GetCurrentSol(),a=t.GetCurrentSol();if(n._SetSelectAll(!1),a._SetSelectAll(!1),r===t){const t=n._GetOwnInstances();C3.clearArray(t),t.push(s),t.push(i),r.ApplySolToContainer()}else{const e=n._GetOwnInstances(),o=a._GetOwnInstances();C3.clearArray(e),C3.clearArray(o),e.push(s),o.push(i),r.ApplySolToContainer(),t.ApplySolToContainer()}yield*f.DebugRetrigger(c,G),o.PopSol(e)}}else CollMemory_Remove(d,s,i)}C3.clearArray(tempCandidates1)}return s.Pop(),!1}function PickByUID_Normal(t,e){const n=runtime.GetInstanceByUID(e);if(!n)return!1;const o=t.GetCurrentSol();if(!o.IsSelectAll()&&!o._GetOwnInstances().includes(n))return!1;if(t.IsFamily()){if(n.GetObjectClass().BelongsToFamily(t))return o.PickOne(n),t.ApplySolToContainer(),!0}else if(n.GetObjectClass()===t)return o.PickOne(n),t.ApplySolToContainer(),!0;return!1}function PickByUID_Inverted(t,e){const n=t.GetCurrentSol();if(n.IsSelectAll()){n._SetSelectAll(!1),n.ClearArrays();const o=t.GetInstances();for(let t=0,s=o.length;t<s;++t){const s=o[t];s.GetUID()===e?n._PushElseInstance(s):n._PushInstance(s)}return t.ApplySolToContainer(),!!n._GetOwnInstances().length}{const o=n._GetOwnInstances();let s=0;for(let t=0,i=o.length;t<i;++t){const i=o[t];o[s]=i,i.GetUID()===e?n._PushElseInstance(i):++s}return C3.truncateArray(o,s),t.ApplySolToContainer(),!!o.length}}AnySDK.OnCollision=function(t){const e=GetObjectClass(this);t=GetObjectClass(t);const n=e.GetRuntime();if(n.IsDebugging())return DebugOnCollision.call(e,t);if(!t)return!1;const o=n.GetCollisionEngine(),s=n.GetEventSheetManager(),i=s.GetEventStack(),r=s.GetCurrentCondition(),a=r.GetObjectClass(),l=r.GetSavedDataMap(),c=r.GetUnsavedDataMap(),u=i.GetCurrentStackFrame(),S=n.GetTickCount(),f=S-1,G=u.GetCurrentEvent(),d=i.Push(G);let h=l.get("collmemory");h||(h=C3.New(C3.PairMap),l.set("collmemory",h)),c.get("collisionCreatedDestroyCallback")||(c.set("collisionCreatedDestroyCallback",!0),n.Dispatcher().addEventListener("instancedestroy",t=>CollMemory_RemoveInstance(h,t.instance)));const I=a.GetCurrentSol(),C=t.GetCurrentSol(),m=I.GetInstances();let g=null;for(let e=0;e<m.length;++e){const n=m[e];C.IsSelectAll()?(o.GetCollisionCandidates(n.GetWorldInfo().GetLayer(),t,n.GetWorldInfo().GetBoundingBox(),tempCandidates1),g=tempCandidates1,o.AddRegisteredCollisionCandidates(n,t,g)):g=C.GetInstances();for(let e=0;e<g.length;++e){const i=g[e];if(o.TestOverlap(n,i)||o.CheckRegisteredCollision(n,i)){const e=CollMemory_Get(h,n,i);let o=!1,r=-2;"number"==typeof e&&(o=!0,r=e);const l=!o||r<f;if(CollMemory_Add(h,n,i,S),l){const e=G.GetSolModifiers();s.PushCopySol(e);const o=a.GetCurrentSol(),r=t.GetCurrentSol();if(o._SetSelectAll(!1),r._SetSelectAll(!1),a===t){const t=o._GetOwnInstances();C3.clearArray(t),t.push(n),t.push(i),a.ApplySolToContainer()}else{const e=o._GetOwnInstances(),s=r._GetOwnInstances();C3.clearArray(e),C3.clearArray(s),e.push(n),s.push(i),a.ApplySolToContainer(),t.ApplySolToContainer()}G.Retrigger(u,d),s.PopSol(e)}}else CollMemory_Remove(h,n,i)}C3.clearArray(tempCandidates1)}return i.Pop(),!1},AnySDK.IsOverlapping=function(t){return t=GetObjectClass(t),DoOverlapCondition(GetInst(this),t,0,0)},AnySDK.IsOverlappingOffset=function(t,e,n){return t=GetObjectClass(t),DoOverlapCondition(GetInst(this),t,e,n)},AnySDK.OnHierarchyReady=function(){return!0},AnySDK.HasParent=function(){return GetWorldInfo(this).HasParent()},AnySDK.HasChildren=function(){return GetWorldInfo(this).HasChildren()},AnySDK.PickParent=function(t,e){const n=GetObjectClass(this);t=GetObjectClass(t);const o=n.GetRuntime(),s=n.GetCurrentSol().GetInstances();if(0===s.length)return!1;const i=t.GetCurrentSol();let r=i.GetInstances();if(i.IsSelectAll()){const e=[...o.instancesPendingCreateForObjectClass(t)];e.length>0&&(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;n<o;++n){const o=s[n];if(1===e)for(const e of o.parents())e.BelongsToObjectClass(t)&&(null===a||a.has(e))&&l.add(e);else{let n;if(0===e){if(n=o.GetParent(),null===n)continue}else n=o.GetTopParent();n.BelongsToObjectClass(t)&&(null===a||a.has(n))&&l.add(n)}}return 0!==l.size&&(i.SetSetPicked(l),t.ApplySolToContainer(),!0)},AnySDK.PickChildren=function(t,e){const n=GetObjectClass(this);t=GetObjectClass(t);const o=n.GetRuntime(),s=n.GetCurrentSol().GetInstances();if(0===s.length)return!1;const i=t.GetCurrentSol();let r=i.GetInstances();if(i.IsSelectAll()){const e=[...o.instancesPendingCreateForObjectClass(t)];e.length>0&&(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;n<o;++n){const o=s[n];2!==e||o.HasChildren()||!o.BelongsToObjectClass(t)||null!==a&&!a.has(o)||l.add(o);for(const n of 0===e?o.children():o.allChildren())2===e&&n.HasChildren()||n.BelongsToObjectClass(t)&&(null===a||a.has(n))&&l.add(n)}return 0!==l.size&&(i.SetSetPicked(l),t.ApplySolToContainer(),!0)},AnySDK.PickNthChild=function(t,e,n){const o=GetObjectClass(this);t=GetObjectClass(t);const s=o.GetRuntime(),i=o.GetCurrentSol().GetInstances();if(0===i.length)return!1;const r=t.GetCurrentSol();let a=r.GetInstances();if(r.IsSelectAll()){const e=[...s.instancesPendingCreateForObjectClass(t)];e.length>0&&(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;o<s;++o){const s=i[o];if(0===e){const e=s.GetChildAt(n);null!==e&&e.BelongsToObjectClass(t)&&(null===l||l.has(e))&&c.push(e)}else if(1===e)for(const e of s.children())if(e.BelongsToObjectClass(t)){if(0===n){(null===l||l.has(e))&&c.push(e);break}--n}}return 0!==c.length&&(r.SetArrayPicked(c),t.ApplySolToContainer(),!0)},AnySDK.CompareChildCount=function(t,e,n){const o=GetInst(this);switch(t){case 0:default:return C3.compare(o.GetChildCount(),e,n);case 1:return C3.compare(o.GetAllChildCount(),e,n)}},AnySDK.AddChild=function(t,e,n,o,s,i,r,a,l,c){t=GetObjectClass(t);const u=GetInst(this),S=runtime.GetCurrentAction().GetObjectClass();for(const f of t.allCorrespondingInstances(u,S)){if(!f.GetPlugin().SupportsSceneGraph())return;u.AddChild(f,{transformX:e,transformY:n,transformZ:o,transformWidth:s,transformHeight:i,transformAngle:r,transformOpacity:a,transformVisibility:l,destroyWithParent:c})}},AnySDK.RemoveChild=function(t){t=GetObjectClass(t);const e=GetInst(this),n=runtime.GetCurrentAction().GetObjectClass();for(const o of t.allCorrespondingInstances(e,n))e.RemoveChild(o)},AnySDK.RemoveFromParent=function(){const t=GetInst(this);if(!t.HasParent())return;t.GetParent().RemoveChild(t)},AnySDK.ParentUID=function(){const t=GetInst(this).GetParent();return t?t.GetUID():-1},AnySDK.ChildCount=function(){return GetInst(this).GetChildCount()},AnySDK.AllChildCount=function(){return GetInst(this).GetAllChildCount()},AnySDK.SetMeshSize=function(t,e,n){t=Math.floor(t),e=Math.floor(e);const o=GetWorldInfo(this);t<2||e<2||!isFinite(t)||!isFinite(e)?(o.ReleaseMesh(),o.SetBboxChanged()):o.CreateMesh(t,e,n)},AnySDK.SetMeshPoint=function(t,e,n,o,s,i,r,a){const l=GetWorldInfo(this);l.SetMeshPoint(t,e,{mode:0===n?"absolute":"relative",x:o,y:s,z:i,u:r,v:a})&&l.SetBboxChanged()},AnySDK.MeshColumns=function(){const t=GetWorldInfo(this);return t.HasMesh()?t.GetSourceMesh().GetHSize():0},AnySDK.MeshRows=function(){const t=GetWorldInfo(this);return t.HasMesh()?t.GetSourceMesh().GetVSize():0},AnySDK.SetElementVisible=function(t){const e=GetWorldInfo(this);t=2===t?!e.IsVisible():0!==t,e.IsVisible()!==t&&e.SetVisible(t)},AnySDK.SetElementCSSStyle=function(t,e){this instanceof self.IInstance?this.setElementCSSStyle(t,e):this.SetElementCSSStyle(t,e)},AnySDK.SetElementAttribute=function(t,e){this instanceof self.IInstance?this.setElementAttribute(t,""+e):this.SetElementAttribute(t,""+e)},AnySDK.RemoveElementAttribute=function(t){this instanceof self.IInstance?this.removeElementAttribute(t):this.RemoveElementAttribute(t)},AnySDK.SetElementFocus=function(){this instanceof self.IInstance?this.focusElement():this.FocusElement()},AnySDK.SetElementBlur=function(){this instanceof self.IInstance?this.blurElement():this.BlurElement()},AnySDK.IsElementFocused=function(){return this instanceof self.IInstance?this.isElementFocused():this.IsElementFocused()},AnySDK.SetElementEnabled=function(t){this instanceof self.IInstance?this._setEnabled(0!==t):this._SetEnabled(0!==t)},AnySDK.IsElementEnabled=function(){return this instanceof self.IInstance?this._isEnabled():this._IsEnabled()},SDKv1.CompareInstanceVar=function(t,e,n){return C3.compare(this.GetInstance().GetInstanceVariableValue(t),e,n)},SDKv2.CompareInstanceVar=function(t,e,n){return C3.compare(GetInst_SDKv2(this).GetInstanceVariableValue(t),e,n)},SDKv1.IsBoolInstanceVarSet=function(t){return!!this.GetInstance().GetInstanceVariableValue(t)},SDKv2.IsBoolInstanceVarSet=function(t){return!!GetInst_SDKv2(this).GetInstanceVariableValue(t)},AnySDK.PickInstVarHiLow=function(t,e,n){const o=GetObjectClass(this),s=o.GetCurrentSol(),i=s.GetInstances();if(0===i.length)return!1;const r=o.IsFamily(),a=[];let l=0;for(let s=0,c=i.length;s<c;++s){const c=i[s],u=r?c.GetObjectClass().GetFamilyInstanceVariableOffset(o.GetFamilyIndex()):0,S=c.GetInstanceVariableValue(u+e);0===a.length||0===t&&S<l||1===t&&S>l?(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<r;++t)if(C3.equalsNoCase(this._frames[t].GetTag(),e))return t;return-1}FrameTagOrIndexToIndex(e){if("string"==typeof e){const t=this.GetFrameIndexByTag(e);if(-1===t)throw new Error(`cannot find animation frame with tag ${e}`);return t}return e}GetSpeed(){return this._speed}IsLooping(){return this._isLooping}GetRepeatCount(){return this._repeatCount}GetRepeatTo(){return this._repeatTo}IsPingPong(){return this._isPingPong}GetIAnimation(){return this._iAnimation}};
}

// objects/animationFrameInfo.js
{
const C3=self.C3,EMPTY_IMAGE_BLOB=(()=>{const t=atob("iVBORw0KGgoAAAANSUhEUgAAAGQAAABkAQMAAABKLAcXAAAAAXNSR0IArs4c6QAAAANQTFRFAAAAp3o92gAAAAF0Uk5TAEDm2GYAAAATSURBVBgZYxgFo2AUjIJRQFcAAAV4AAHcRQIbAAAAAElFTkSuQmCC"),i=new Uint8Array(t.length);for(let e=0,n=t.length;e<n;++e)i[e]=t.charCodeAt(e);return new Blob([i],{type:"image/png"})})();C3.AnimationFrameInfo=class extends C3.DefendedBase{constructor(t){super(),this._imageInfo=C3.New(C3.ImageInfo),this._imageInfo.LoadData(t),this._duration=t[7],this._origin=C3.New(C3.Vector2,t[8],t[9]),this._imagePoints=t[10].map(t=>C3.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;e<s;++e){const s=this._runtime.GetObjectClassByIndex(t[e]);this._familyMembers.push(s),this._familyMembersSet.add(s),s._families.push(this),s._familiesSet.add(this)}}_SetContainer(t){this._isInContainer=!0,this._container=t}IsInContainer(){return this._isInContainer}GetContainer(){return this._container}_OnAfterCreate(){let t=0;if(!this._isFamily)for(const e of this._families)for(const s of e.GetBehaviorTypes()){const e=s.GetName().toLowerCase();this._behaviorsByName.set(e,s),this._behaviorNameToIndex.set(e,t),this._behaviorTypesIncludingInherited.push(s),++t}for(const e of this.GetBehaviorTypes()){const s=e.GetName().toLowerCase();this._behaviorsByName.set(s,e),this._behaviorNameToIndex.set(s,t),this._behaviorTypesIncludingInherited.push(e),++t}for(const t of this._behaviorTypesIncludingInherited)this._usedBehaviorCtors.add(t.GetBehavior().constructor);if(!this._isFamily&&this._families.length){const t=this._runtime.GetFamilyCount();C3.extendArray(this._familyInstVarMap,t,0),C3.extendArray(this._familyBehaviorMap,t,0),C3.extendArray(this._familyEffectMap,t,0);const e=[];let s=0,i=0,n=0;for(const t of this._families){const a=t.GetFamilyIndex();this._familyInstVarMap[a]=s,s+=t.GetInstanceVariablesCount(),this._familyBehaviorMap[a]=i,i+=t.GetBehaviorTypesCount(),this._familyEffectMap[a]=n,n+=t.GetEffectTypesCount();const r=t.GetEffectList();if(r&&this._effectList)for(const t of r.GetAllEffectTypes())e.push(t.Clone(this._effectList))}this._effectList&&this._effectList.PrependEffectTypes(e)}}_CreateSingleGlobalInstance(t){const e=C3.IsFiniteNumber(t[17])?t[17]:this._runtime._GetNewUID(),s=C3.New(C3.Instance,{runtime:this._runtime,objectType:this,uid:e});s._CreateSdkInstance(t[16],[]),this._runtime._MapInstanceByUID(e,s),this._instances.push(s)}GetSdkType(){return this._sdkType}IsOnLoaderLayout(){return this._isOnLoaderLayout}Dispatcher(){return this._dispatcher}OnCreate(){this._isFamily||(this._sdkType?this._sdkType.OnCreate():this._iObjectClass._onCreate())}HasLoadedTextures(){return this._textureRefCount>0}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;e<s;++e)t[e]._SetIID(e);const s=this._runtime._GetInstancesPendingCreate();for(const t of s)t.GetObjectClass()===this&&t._SetIID(e++);this._iidsStale=!1}GetInstanceByIID(t){const e=this._instances;if(t<e.length)return e[t];t-=e.length;const s=this._runtime._GetInstancesPendingCreate();for(const e of s)if(e.GetObjectClass()===this){if(0===t)return e;--t}return null}GetFirstPicked(t){if(t&&t.IsInContainer()&&t.GetObjectClass()!==this)for(const e of t.siblings())if(e.GetObjectClass()===this)return e;const e=this.GetCurrentSol().GetInstances();return e.length?e[0]:null}GetPairedInstance(t){const e=this.GetCurrentSol().GetInstances();return e.length>0?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||o<l?(_=o*h,c=h):(_=l*h+(o-l)*(h-1),c=h-1);for(let t=_,e=_+c;t<e;++t)yield s[t]}FinishCondition(t){this._sdkType?.FinishCondition(t)}ApplySolToContainer(){if(!this._isInContainer||this._isFamily)return;this._UpdateIIDs();const t=this.GetCurrentSol(),e=t._GetOwnInstances(),s=t.IsSelectAll(),i=this._runtime.GetCurrentEventStackFrame(),n=i&&i.GetCurrentEvent()&&i.GetCurrentEvent().IsOrBlock();for(const i of this._container.objectTypes()){if(i===this)continue;i._UpdateIIDs();const a=i.GetCurrentSol();if(a._SetSelectAll(s),!s){const s=a._GetOwnInstances();C3.clearArray(s);for(const t of e)s.push(i.GetInstanceByIID(t.GetIID()));if(n){const e=t._GetOwnElseInstances(),s=a._GetOwnElseInstances();C3.clearArray(s);for(const t of e)s.push(i.GetInstanceByIID(t.GetIID()))}}}}_TruncateContainerSols(t,e){for(const s of this.GetContainer().objectTypes()){const i=s.GetCurrentSol();t?C3.truncateArray(i._GetOwnElseInstances(),e):C3.truncateArray(i._GetOwnInstances(),e)}}_GetCollisionCellGrid(){return this._collisionGrid}_SetAnyCollisionCellChanged(t){this._anyCollisionCellChanged=!!t}_UpdateAllCollisionCells(){if(this._anyCollisionCellChanged&&this._isWorldType){for(const t of this._instances)t.GetWorldInfo()._UpdateCollisionCell();for(const t of this._runtime._GetInstancesPendingCreate())t.GetObjectClass()===this&&t.GetWorldInfo()._UpdateCollisionCell();this._anyCollisionCellChanged=!1}}_OnWorldInstanceLayerChanged(t,e,s){if(e){const s=this._worldInfosByLayer.get(e);s&&(s.delete(t),0===s.size&&this._worldInfosByLayer.delete(e))}if(s){let e=this._worldInfosByLayer.get(s);e||(e=new Set,this._worldInfosByLayer.set(s,e)),e.add(t)}}*layersHasInstancesOn(){if(this.IsFamily()){const t=new Set;for(const e of this._familyMembers)for(const s of e.layersHasInstancesOn())t.add(s);yield*t.values()}else for(const t of this._worldInfosByLayer.keys())t.WasReleased()||(yield t)}GetSavedDataMap(){return this._savedData||(this._savedData=new Map),this._savedData}HasSolidBehavior(){return this.UsesBehaviorByCtor(C3.Behaviors.solid)}HasJumpthruBehavior(){return this.UsesBehaviorByCtor(C3.Behaviors.jumpthru)}HasNoSaveBehavior(){return this.UsesBehaviorByCtor(C3.Behaviors.NoSave)}HasPersistBehavior(){return this.UsesBehaviorByCtor(C3.Behaviors.Persist)}_SaveToJson(){const t={"instances":this._instances.map(t=>t.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);t<e;++t)i[t].LoadFromJson(n[t]);for(let t=n.length,e=i.length;t<e;++t)this._runtime.DestroyInstance(i[t]);for(let t=i.length,s=n.length;t<s;++t){const s=n[t];let i=null;if(this.IsWorldType()&&(i=this._runtime.GetMainRunningLayout().GetLayerBySID(s["w"]["l"]),!i))continue;const a=this._runtime.CreateInstanceFromData(this._defaultInstanceData||this,i,!1,0,0,!0);a.LoadFromJson(s),e&&e.add(a)}this._loadInstancesJson=n,this._SetIIDsStale()}_GetLoadInstancesJson(){return this._loadInstancesJson}_ClearLoadInstancesJson(){this._loadInstancesJson=null}_SetupSceneGraphConnectionsOnChangeOfLayout(){for(let t=0,e=this._instances;t<e;++t)this._instances[t]._SetupSceneGraphConnectionsOnChangeOfLayout()}GetIObjectClass(){return this._iObjectClass}UserScriptDispatcher(){return this._userScriptDispatcher}_GetUserScriptInstanceClass(){return this._instanceUserScriptClass}_SetUserScriptInstanceClass(t){this._instanceUserScriptClass=t}DispatchUserScriptEvent(t){const e=this._runtime,s=e.IsDebug()&&!e.GetEventSheetManager().IsInEventEngine();s&&C3Debugger.StartMeasuringScriptTime(),this._userScriptDispatcher.dispatchEvent(t),s&&C3Debugger.AddScriptTime()}};
}

// objects/container.js
{
const C3=self.C3;C3.Container=class extends C3.DefendedBase{constructor(e,t){super(),this._runtime=e,this._objectTypes=t;for(const e of this._objectTypes)e._SetContainer(this)}Release(){this._runtime=null}GetRuntime(){return this._runtime}GetObjectTypes(){return this._objectTypes}objectTypes(){return this._objectTypes}HasAnyWorldType(){return this._objectTypes.some(e=>e.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<t;++s)this._instVarValues.push(e[this._objectType.GetInstanceVariableType(s)])}_CreateSdkInstance(t,e){if(this._sdkInst)throw new Error("already got sdk instance");for(let t=0,s=this._behaviorInstances.length;t<s;++t){this._behaviorInstances[t]._CreateSdkInstance(e?e[t]:null)}if(this.GetPlugin().GetSdkVersion()<2){if(this._sdkInst=C3.New(this._objectType.GetInstanceSdkCtor(),this,t),!(this._sdkInst instanceof C3.SDKInstanceBase))throw new Error("sdk type must derive from SDKInstanceBase");!this.GetPlugin().IsWorldType()&&this._objectType._GetUserScriptInstanceClass()&&this.GetInterfaceClass()}else{const e=this.GetPlugin().GetScriptInterfaceClass();this._InitUserScriptInterface(e.Instance,t)}}GetSdkInstance(){return this._sdkInst??this._iScriptInterface}GetWorldInfo(){return this._worldInfo}GetRuntime(){return this._runtime}GetTimeScale(){return this._timeScale}GetActiveTimeScale(){const t=this._timeScale;return-1===t?this.GetRuntime().GetTimeScale():t}SetTimeScale(t){((t=+t)<0||!isFinite(t))&&(t=0),this._timeScale=t,this.GetObjectClass().UsesEffects()&&this._runtime._SetTrackingInstanceTime(this,!0)}RestoreTimeScale(){this._timeScale=-1,this.GetObjectClass().UsesEffects()&&this._runtime._SetTrackingInstanceTime(this,!1)}GetInstanceGameTime(){return this._runtime._GetInstanceGameTime(this)}Dispatcher(){return this._dispatcher||(this._dispatcher=C3.New(C3.Event.Dispatcher)),this._dispatcher}Draw(t){this._sdkInst?this._sdkInst.Draw(t):this._iScriptInterface._draw(this._runtime.GetCanvasManager().GetIRenderer())}OnCreate(t){this._sdkInst.OnCreate(t)}_SetHasTilemap(){this._flags|=2}HasTilemap(){return!!(2&this._flags)}_MarkDestroyed(){this._flags|=1}IsDestroyed(){return!!(1&this._flags)}MustPreDraw(){return!!(4&this._flags)||(this._sdkInst?this._sdkInst.MustPreDraw():this._iScriptInterface._mustPreDraw())}SetMustMitigateZFighting(){this._flags|=32}MustMitigateZFighting(){return!!(32&this._flags)}_IsSolidEnabled(){return!!(8&this._flags)}_SetSolidEnabled(t){t?this._flags|=8:this._flags&=-9}_IsSolidUsingInstanceTags(){return!!(16&this._flags)}_SetSolidUsingInstanceTags(t){t?this._flags|=16:this._flags&=-17}_IsJumpthruEnabled(){return!!(32&this._flags)}_SetJumpthruEnabled(t){t?this._flags|=32:this._flags&=-33}_IsDrawingWithEffects(){return!!(64&this._flags)}_SetIsDrawingWithEffects(t){t?this._flags|=64:this._flags&=-65}SetFlag(t,e){t<<=16,e?this._flags|=t:this._flags&=~t}GetFlag(t){return!!(this._flags&t<<16)}IsOriginalSizeKnown(){return this._sdkInst?this._sdkInst.IsOriginalSizeKnown():this._iScriptInterface._isOriginalSizeKnown()}GetOriginalSize(){if(!this.IsOriginalSizeKnown())throw new Error("original size not known");return this._sdkInst?this._sdkInst.GetOriginalSize():this._iScriptInterface._getOriginalSize()}GetCurrentImageInfo(){return this._sdkInst?this._sdkInst.GetCurrentImageInfo():null}GetCurrentSurfaceSize(){return this._sdkInst?this._sdkInst.GetCurrentSurfaceSize():null}GetCurrentTexRect(){return this._sdkInst?this._sdkInst.GetCurrentTexRect():null}GetCurrentTexQuad(){return this._sdkInst?this._sdkInst.GetCurrentTexQuad():null}IsCurrentTexRotated(){return!!this._sdkInst&&this._sdkInst.IsCurrentTexRotated()}GetImagePoint(t){return this._sdkInst?this._sdkInst.GetImagePoint(t):[this._iScriptInterface.x,this._iScriptInterface.y,this._iScriptInterface.totalZ]}GetObjectClass(){return this._objectType}RendersToOwnZPlane(){return this._sdkInst?this._sdkInst.RendersToOwnZPlane():this._iScriptInterface._rendersToOwnZPlane()}BelongsToObjectClass(t){return t.IsFamily()?t.FamilyHasMember(this.GetObjectClass()):this.GetObjectClass()===t}CollectInstancesToPick(t,e,s){const n=(e,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<n;++s)if(e[s].GetBehaviorType().GetSID()===t)return s;return-1}GetAllInstanceVariableValues(){return this._instVarValues}_GetAllInstanceVariableNames(){return this._objectType._GetAllInstanceVariableNames()}GetInstanceVariableCount(){return this._instVarValues.length}GetInstanceVariableValue(t){t|=0;const e=this._instVarValues;if(t<0||t>=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<n;++s)t[e[s].toString()]=this._instVarValues[s];s["ivs"]=t}if(this._behaviorInstances.length){const e={};for(const s of this._behaviorInstances){const n=s.SaveToJson(t);n&&(e[s.GetBehaviorType().GetSID().toString()]=n)}s["behs"]=e}}this._worldInfo&&(s["w"]=this._worldInfo._SaveToJson(t,e));const i=this._sdkInst?this._sdkInst.SaveToJson():this._iScriptInterface._saveToJson();return i&&(s["data"]=i),s}_OnBeforeLoad(t="full",e=null){this._worldInfo&&this._worldInfo._OnBeforeLoad(t)}_OnAfterLoad(t,e="full",s=null){this._worldInfo&&this._worldInfo._OnAfterLoad(t,e,s)}_OnAfterLoad2(t,e="full",s=null){this._worldInfo&&this._worldInfo._OnAfterLoad2(t,e,s)}_SetupSceneGraphConnectionsOnChangeOfLayout(){this.GetPlugin().IsWorldType()&&this._worldInfo._SetupSceneGraphConnectionsOnChangeOfLayout()}LoadFromJson(t,e="full",s=null){if("full"===e)this._uid=t["uid"];else if(!t["c3"])return;if(this.SetTagsSet(new Set(t["tags"]??[])),"visual-state"!==e){let e=savedDataMaps.get(this);e&&(e.clear(),savedDataMaps.delete(this));const s=t["ex"];s&&(e=C3.FromSuperJSON(s),savedDataMaps.set(this,e)),this._timeScale=t.hasOwnProperty("mts")?t["mts"]:-1;const n=t["ivs"];if(n)for(const[t,e]of Object.entries(n)){const s=parseInt(t,10),n=this._objectType.GetInstanceVariableIndexBySID(s);if(n<0||n>=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<n;++t)e[s[t]]={configurable:!1,enumerable:!0,get:C3.Instance.prototype._GetInstanceVariableTypedValue.bind(this,t),set:C3.Instance.prototype.SetInstanceVariableValue.bind(this,t)};const n=Object.create(Object.prototype,e);t.instVars={value:n,writable:!1}}_GetBehaviorsScriptDescriptor(t){const e=this._behaviorInstances;if(0===e.length)return;const s={};for(const t of e)s[t.GetBehaviorType().GetJsPropName()]={value:t.GetScriptInterface(),writable:!1};const n=Object.create(Object.prototype,s);t.behaviors={value:n,writable:!1}}DispatchUserScriptEvent(t){if(!this.HasScriptInterface())return;const e=this.GetInterfaceClass();t.instance=e;const s=this._runtime,n=s.IsDebug()&&!s.GetEventSheetManager().IsInEventEngine();n&&C3Debugger.StartMeasuringScriptTime(),e.dispatchEvent(t),n&&C3Debugger.AddScriptTime()}};
}

// objects/sceneGraphInfo.js
{
const C3=self.C3,updatedInstances=new Map;C3.SceneGraphInfo=class extends C3.DefendedBase{constructor(t){super(),this._owner=t,this._parent=null,this._children=[],this._startWidth=t.GetWidth(),this._startHeight=t.GetHeight(),this._startScaleX=1,this._startScaleY=1,this._parentStartAngle=0,this._ownOpacity=1,this._startOpacity=t.GetOpacity(),this._tmpSceneGraphChildren=null,this._tmpSceneGraphChildrenIndexes=null,this._indexInParent=NaN,this._originalSizeKnown=!1,this._originalWidth=NaN,this._originalHeight=NaN,this._on_instance_create=e=>{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;++t){const e=i[t];for(let i=0,n=e.length;i<n;++i){const n=e[i],r=s.GetMeshPointAt(i,t);r.SetX(n[0]),r.SetY(n[1]),r.SetZ(n[2]),r.SetU(n[3]),r.SetV(n[4])}}}if(t[17]){const e=t[17][0],s=t[17][1],i=!!s,n=!i,r=this._runtime.GetTemplateManager();i&&r&&r.MapInstanceToTemplateName(this.GetInstance(),s),n&&r&&r.MapInstanceToTemplateName(this.GetInstance(),e)}this.GetLayout().IsCreatingInitialInstances()||this._UpdateActiveSamplingMode(),enableUpdateRendererStateGroup=!0,this._UpdateRendererStateGroup()}InitNoData(){this._x=0,this._y=0,this._z=0,this._w=0,this._h=0,this._depth=0,this._a=0,this._sinA=0,this._cosA=1,this.#t=0,this.#e=0,this.#s=0,this.GetLayout().IsCreatingInitialInstances()||this._UpdateActiveSamplingMode(),this._UpdateRendererStateGroup()}GetRuntime(){return this._runtime}GetObjectClass(){return this._objectClass}GetInstance(){return this._inst}_GetParentOffsetAngle(){return this.GetTransformWithParentAngle()?this._MaybeReflectAngleForMirrorFlip(this.GetParent()._GetAngleNoReflect()-this._sceneGraphInfo.GetParentStartAngle()):0}SetX(t){if(t=+t,this.GetTransformWithParentX()){const e=this._sceneGraphInfo,s=t-this.GetX(),i=-this._GetParentOffsetAngle();0===i?this._x+=s/e.GetParentScaleX():(this._x+=Math.cos(i)*s/e.GetParentScaleX(),this.GetTransformWithParentY()&&(this._y+=Math.sin(i)*s/e.GetParentScaleY()))}else this._x=t}OffsetX(t,e=!1){t=+t,e?this._x+=t:this.GetTransformWithParentX()?this.SetX(this.GetX()+t):this._x+=t}GetX(){if(this.GetTransformWithParentX()){let t=this._x;const e=this._sceneGraphInfo,s=this.GetParent(),i=this._GetParentOffsetAngle();return 0===i?t*=e.GetParentScaleX():(t=t*e.GetParentScaleX()*Math.cos(i),this.GetTransformWithParentY()&&(t-=this._y*e.GetParentScaleY()*Math.sin(i))),s.GetX()+t}return this._x}SetY(t){if(t=+t,this.GetTransformWithParentY()){const e=this._sceneGraphInfo,s=t-this.GetY(),i=-this._GetParentOffsetAngle();0===i?this._y+=s/e.GetParentScaleY():(this.GetTransformWithParentX()&&(this._x-=Math.sin(i)*s/e.GetParentScaleX()),this._y+=Math.cos(i)*s/e.GetParentScaleY())}else this._y=t}OffsetY(t,e=!1){t=+t,e?this._y+=t:this.GetTransformWithParentY()?this.SetY(this.GetY()+t):this._y+=t}GetY(){if(this.GetTransformWithParentY()){let t=this._y;const e=this._sceneGraphInfo,s=this.GetParent(),i=this._GetParentOffsetAngle();return 0===i?t*=e.GetParentScaleY():(t=t*e.GetParentScaleY()*Math.cos(i),this.GetTransformWithParentX()&&(t+=this._x*e.GetParentScaleX()*Math.sin(i))),s.GetY()+t}return this._y}SetXY(t,e){if(t=+t,e=+e,this.GetTransformWithParentXOrY()){const s=this.GetTransformWithParentX(),i=this.GetTransformWithParentY(),n=this._sceneGraphInfo,r=t-this.GetX(),h=e-this.GetY(),a=-this._GetParentOffsetAngle();if(0===a)s?this._x+=r/n.GetParentScaleX():this._x=t,i?this._y+=h/n.GetParentScaleY():this._y=e;else{const o=Math.sin(a),l=Math.cos(a);s?this._x+=i?(l*r-o*h)/n.GetParentScaleX():l*r/n.GetParentScaleX():this._x=t,i?this._y+=s?(o*r+l*h)/n.GetParentScaleY():l*h/n.GetParentScaleY():this._y=e}}else this._x=t,this._y=e}SetXYZ(t,e,s){this.SetXY(t,e),this.SetZ(s)}GetXY(){return[this.GetX(),this.GetY()]}GetXYZ(){return[this.GetX(),this.GetY(),this.GetZ()]}OffsetXY(t,e){t=+t,e=+e,this.GetTransformWithParentXOrY()?this.SetXY(this.GetX()+t,this.GetY()+e):(this._x+=t,this._y+=e)}OffsetXYZ(t,e,s){this.OffsetXY(t,e),this.OffsetZ(s)}EqualsXY(t,e){return this.GetX()===t&&this.GetY()===e}EqualsXYZ(t,e,s){return this.EqualsXY(t,e)&&this.GetZ()===s}SetZ(t){if(t=+t,this.GetTransformWithParentZ()&&(t-=this.GetParent().GetZ()),this._z===t)return;this._z=t,this._UpdateZElevation();const e=this.GetLayer();0!==this._z&&e._SetAnyInstanceZElevated(),e.SetZIndicesChanged(this)}_UpdateZElevation(){if(this._UpdateRendererStateGroup(),this.HasChildren()){const t=this.GetChildren();for(let e=0,s=t.length;e<s;e++){const s=t[e];s.GetTransformWithParentZ()&&s._UpdateZElevation()}}}OffsetZ(t){this.SetZ(this.GetZ()+t)}GetZ(){return this.GetTransformWithParentZ()?this.GetParent().GetZ()+this._z:this._z}GetTotalZ(){return this.GetLayer().GetZElevation()+this.GetZ()}IsOriginalSizeKnown(){return this.GetInstance().IsOriginalSizeKnown()}SetWidth(t){if(t=+t,this.GetTransformWithParentWidth()){const e=this.GetWidth();0===e?this._w=Number.EPSILON:this._w*=t/e}else this._w=t;this._MarkSinCosAngleChanged()}OffsetWidth(t,e){t=+t,e?this._w+=t:this.GetTransformWithParentWidth()?this.SetWidth(this.GetWidth()+t):this._w+=t,this._MarkSinCosAngleChanged()}GetWidth(){if(this.GetTransformWithParentWidth()){const t=this.GetParent(),e=t.GetWidth();return t._GetSceneGraphInfo()._GetStartWidth()===Number.EPSILON?(this._GetSceneGraphInfo()._GetStartWidth()+e)*this._w:e*this._w}return this._w}SetHeight(t){if(t=+t,this.GetTransformWithParentHeight()){const e=this.GetHeight();0===e?this._h=Number.EPSILON:this._h*=t/e}else this._h=t;this._MarkSinCosAngleChanged()}OffsetHeight(t,e){t=+t,e?this._h+=t:this.GetTransformWithParentHeight()?this.SetHeight(this.GetHeight()+t):this._h+=t,this._MarkSinCosAngleChanged()}GetHeight(){if(this.GetTransformWithParentHeight()){const t=this.GetParent(),e=t.GetHeight();return t._GetSceneGraphInfo()._GetStartHeight()===Number.EPSILON?(this._GetSceneGraphInfo()._GetStartHeight()+e)*this._h:e*this._h}return this._h}SetSize(t,e){if(t=+t,e=+e,this.GetTransformWithParentWidth()){const e=this.GetWidth();0===e?this._w=Number.EPSILON:this._w*=t/e}else this._w=t;if(this.GetTransformWithParentHeight()){const t=this.GetHeight();0===t?this._h=Number.EPSILON:this._h*=e/t}else this._h=e;this._MarkSinCosAngleChanged()}GetSize(){return[this.GetWidth(),this.GetHeight()]}GetDepth(){return this._depth}SetDepth(t){this._depth=t}GetSceneGraphScale(){if(this.HasParent()){const t=this._sceneGraphInfo;return Math.min(t.GetParentScaleX(),t.GetParentScaleY())}return 1}IsRotatable(){return!!(128&this._flags)}SetAngle(t){t=+t,this.IsRotatable()&&(this.GetTransformWithParentAngle()&&(t-=this.GetParent().GetAngle()),t=C3.clampAngle(t),this._a!==t&&(this._a=t,this._MarkSinCosAngleChanged()))}OffsetAngle(t){0!==(t=+t)&&this.IsRotatable()&&(this._a=C3.clampAngle(this._a+t),this._MarkSinCosAngleChanged())}_MarkSinCosAngleChanged(){if(this._flags|=262144,this.HasChildren()){const t=this.GetChildren();for(let e=0,s=t.length;e<s;e++)t[e]._MarkSinCosAngleChanged()}}GetAngle(){return this.GetTransformWithParentAngle()&&this.IsRotatable()?this._MaybeReflectAngleForMirrorFlip(C3.clampAngle(this.GetParent()._GetAngleNoReflect()+this._a)):this._a}_GetAngleNoReflect(){return this.GetTransformWithParentAngle()&&this.IsRotatable()?C3.clampAngle(this.GetParent()._GetAngleNoReflect()+this._a):this._a}_MaybeReflectAngleForMirrorFlip(t){return this.GetTransformWithParentWidth()&&this.GetTopParent().GetWidth()<0&&(t=C3.clampAngle(C3.angleReflect(t,this.GetTopParent().GetAngle()+Math.PI))),this.GetTransformWithParentHeight()&&this.GetTopParent().GetHeight()<0&&(t=C3.angleReflect(t,this.GetTopParent().GetAngle())),t}_NeedsReflectAngleForMirrorOrFlip(){const t=this.GetParent();return!!(this.GetTransformWithParentWidth()&&t.GetWidth()<0)||!!(this.GetTransformWithParentHeight()&&t.GetHeight()<0)}_NeedsReflectAngleForMirrorAndFlip(){const t=this.GetParent();return!!(this.GetTransformWithParentWidth()&&t.GetWidth()<0&&this.GetTransformWithParentHeight()&&t.GetHeight()<0)}_MaybeUpdateSinCosAngle(){const t=this._flags;if(!(262144&t))return;const e=this.GetAngle();this._sinA=Math.sin(e),this._cosA=Math.cos(e),this._flags=-262145&t}GetSinAngle(){return this._MaybeUpdateSinCosAngle(),this._sinA}GetCosAngle(){return this._MaybeUpdateSinCosAngle(),this._cosA}SetOriginX(t){this.#t=+t}OffsetOriginX(t){this.#t+=+t}GetOriginX(){return this.#t}SetOriginY(t){this.#e=+t}OffsetOriginY(t){this.#e+=+t}GetOriginY(){return this.#e}SetOriginZ(t){this.#s=+t}OffsetOriginZ(t){this.#s+=+t}GetOriginZ(){return this.#s}_SetColor(t){this._color.equals(t)||(this._color===DEFAULT_COLOR?(this._color=C3.New(C3.Color,t),this._colorPremultiplied=C3.New(C3.Color,t),this._colorPremultiplied.premultiply()):t.equalsRgba(1,1,1,1)?(this._color=DEFAULT_COLOR,this._colorPremultiplied=DEFAULT_COLOR):(this._color.set(t),this._colorPremultiplied.set(t),this._colorPremultiplied.premultiply()),this._UpdateRendererStateGroup())}SetOpacity(t){if(t=C3.clamp(+t,0,1),this.GetTransformWithParentOpacity()){if(this._GetSceneGraphInfo().GetOwnOpacity()===t)return;this._GetSceneGraphInfo().SetOwnOpacity(t),t=this.GetOpacity()}else if(this._color.a===t)return;this._SetColorWithOpacity(t)}_SetOpacityOfChildren(){if(!this.HasChildren())return;const t=this.GetChildren();for(let e=0,s=t.length;e<s;e++){const s=t[e];s._SetColorWithOpacity(s.GetOpacity())}}_SetColorWithOpacity(t){tempColor.copyRgb(this._color),tempColor.a=t,this._SetColor(tempColor),this._SetOpacityOfChildren()}OffsetOpacity(t){this.GetTransformWithParentOpacity()?this.SetOpacity(this._GetSceneGraphInfo().GetOwnOpacity()+t):this.SetOpacity(this.GetOpacity()+t)}GetOpacity(){return this.GetTransformWithParentOpacity()?this.GetParent().GetOpacity()*this._GetSceneGraphInfo().GetOwnOpacity():this._color.a}SetUnpremultipliedColor(t){this._color.equalsIgnoringAlpha(t)||(tempColor.copyRgb(t),tempColor.a=this.GetOpacity(),this._SetColor(tempColor))}SetUnpremultipliedColorRGB(t,e,s){tempColor.setRgb(t,e,s),this.SetUnpremultipliedColor(tempColor)}OffsetUnpremultipliedColorRGB(t,e,s){0===t&&0===e&&0===s||(tempColor.copyRgb(this._color),tempColor.r+=t,tempColor.g+=e,tempColor.b+=s,this.SetUnpremultipliedColor(tempColor))}GetUnpremultipliedColor(){return this._color}GetPremultipliedColor(){return this._colorPremultiplied}SetSamplingMode(t){if(!this.GetInstance().GetPlugin().SupportsChangingSampling())throw new Error("object does not support changing sampling");const e=C3.Gfx.RendererBase.SamplingModeToNumber(t);this.#i!==e&&(this.#i=e,this._runtime.UpdateRender(),this._UpdateActiveSamplingMode())}GetSamplingMode(){return C3.Gfx.RendererBase.SamplingNumberToMode(this.#i)}_UpdateActiveSamplingMode(){let t;t=this.HasParent()?C3.Gfx.RendererBase.SamplingNumberToMode(this.GetParent().GetActiveSampling()):this.GetLayer().GetActiveSampling();const e=this.GetSamplingMode();"auto"!==e&&(t=e),this.#n=C3.Gfx.RendererBase.SamplingModeToNumber(t);for(const t of this.children())t._UpdateActiveSamplingMode()}GetActiveSampling(){return this.#n}GetDestroyWithParent(){return!!(512&this._flags)}SetDestroyWithParent(t){this._SetFlag(512,t)}GetTransformWithParentX(){return!!(1024&this._flags)}SetTransformWithParentX(t){this._SetFlag(1024,t)}GetTransformWithParentY(){return!!(2048&this._flags)}GetTransformWithParentXOrY(){return!!(3072&this._flags)}SetTransformWithParentY(t){this._SetFlag(2048,t)}GetTransformWithParentWidth(){return!!(4096&this._flags)}SetTransformWithParentWidth(t){this._SetFlag(4096,t)}GetTransformWithParentHeight(){return!!(8192&this._flags)}SetTransformWithParentHeight(t){this._SetFlag(8192,t)}GetTransformWithParentAngle(){return!!(16384&this._flags)}SetTransformWithParentAngle(t){this._SetFlag(16384,t)}GetTransformWithParentZ(){return!!(32768&this._flags)}SetTransformWithParentZ(t){this._SetFlag(32768,t)}GetTransformWithParentOpacity(){return!!(4194304&this._flags)}SetTransformWithParentOpacity(t){this._SetFlag(4194304,t)}GetTransformWithParentVisibility(){return!!(8388608&this._flags)}SetTransformWithParentVisibility(t){this._SetFlag(8388608,t)}_ClearAllSceneGraphFlags(){this._flags&=-12647937}AddChild(t,e){if(t===this)return!1;if(t.HasParent())return!1;if(this._HasChildRecursive(t))return!1;if(this._HasAnyParent(t))return!1;const s=t.GetX(),i=t.GetY(),n=t.GetZ(),r=t.GetWidth(),h=t.GetHeight(),a=t.GetAngle(),o=t.GetOpacity();t._SetParent(this),t.SetTransformWithParentX(e.transformX),t.SetTransformWithParentY(e.transformY),t.SetTransformWithParentZ(e.transformZ),t.SetTransformWithParentWidth(e.transformWidth),t.SetTransformWithParentHeight(e.transformHeight),t.SetTransformWithParentAngle(e.transformAngle),t.SetTransformWithParentOpacity(e.transformOpacity),t.SetTransformWithParentVisibility(e.transformVisibility),t.SetDestroyWithParent(e.destroyWithParent);const l=s-this.GetX(),_=i-this.GetY(),c=-this.GetAngle(),G=Math.cos(c),d=Math.sin(c);if(e.transformX&&(e.transformAngle?t._x=l*G-_*d:t._x=l,e.transformWidth)){const e=this.GetWidth()/this._sceneGraphInfo._GetStartWidth();0!==e&&(t._x/=e)}if(e.transformY&&(e.transformAngle?t._y=l*d+_*G:t._y=_,e.transformHeight)){const e=this.GetHeight()/this._sceneGraphInfo._GetStartHeight();0!==e&&(t._y/=e)}if(e.transformZ&&(t._z=n-this.GetZ()),e.transformWidth){const e=this.GetWidth();0===e||e===Number.EPSILON?(t._w=1,t._sceneGraphInfo.SetStartScaleX(1)):(t._w=r/this.GetWidth(),t._sceneGraphInfo.SetStartScaleX(t._w))}if(e.transformHeight){const e=this.GetHeight();0===e||e===Number.EPSILON?(t._h=1,t._sceneGraphInfo.SetStartScaleY(1)):(t._h=h/this.GetHeight(),t._sceneGraphInfo.SetStartScaleY(t._h))}return e.transformAngle&&(t._a=a-this.GetAngle()),e.transformOpacity&&t._sceneGraphInfo.SetOwnOpacity(o),e.transformVisibility&&t.SetVisible(this.IsVisible()),this._AddChildToSceneGraphInfo(t),this.SetBboxChanged(),this._SetOpacityOfChildren(),!0}RemoveChild(t){if(t.GetParent()!==this)return;const e=t.GetX(),s=t.GetY(),i=t.GetZ(),n=t.GetWidth(),r=t.GetHeight(),h=t.GetAngle(),a=t.GetOpacity();t._SetParent(null),t._ClearAllSceneGraphFlags(),t.SetXYZ(e,s,i),t.SetSize(n,r),t.SetAngle(h),t.SetOpacity(a),this._RemoveChildFromSceneGraphInfo(t),this.SetBboxChanged()}GetTmpHierarchyPosition(){return this._tmpHierarchyPosition}_ResetAllSceneGraphState(){this._BuildTmpSceneGraphData();const t=[...this.children()];for(const e of t)this.RemoveChild(e);const e=this.GetParent();e&&e.RemoveChild(this),this._ClearAllSceneGraphFlags()}_BuildTmpSceneGraphData(){if(this._SetTmpHierarchyPosition(),!this._tmpSceneGraphChildren){const t=[...this.children()];t.length&&(this._tmpSceneGraphChildren=[],this._tmpSceneGraphChildrenIndexes=new WeakMap);let e=0;for(const s of t){const t=s.GetInstance();this._tmpSceneGraphChildren.push(t),this._tmpSceneGraphChildrenIndexes.set(t,e),e++}}const t=this.GetParent();t&&t._BuildTmpSceneGraphData()}_SetTmpHierarchyPosition(){if(-1!==this._tmpHierarchyPosition)return;const t=[...this.parents()];this._tmpHierarchyPosition=t.length;for(const e of t)e._SetTmpHierarchyPosition();const e=[...this.children()];for(const t of e)t._SetTmpHierarchyPosition()}_ReleaseTmpSceneGraphInfo(){this._tmpSceneGraphChildren&&(this._tmpSceneGraphChildren.length=0),this._tmpSceneGraphChildren=null,this._tmpSceneGraphChildrenIndexes=null;const t=this.GetParent();t&&t._ReleaseTmpSceneGraphInfo(),this._tmpHierarchyPosition=-1}HasParent(){return null!==this.GetParent()}GetParent(){const t=this._sceneGraphInfo;return null!==t?t.GetParent():null}GetTopParent(){let t=this;for(;t.HasParent();)t=t.GetParent();return t}*parents(){let t=this.GetParent();for(;t;)yield t,t=t.GetParent()}HasChild(t){return this.GetChildren().includes(t)}HasChildren(){const t=this._sceneGraphInfo;return null!==t&&t.HasChildren()}GetChildren(){const t=this._sceneGraphInfo;return null!==t?t.GetChildren():EMPTY_ARRAY}children(){return this.GetChildren()}*allChildren(){for(const t of this.children())yield t,yield*t.allChildren()}GetChildCount(){return this.GetChildren().length}GetAllChildCount(){return[...this.allChildren()].length}GetChildAt(t){const e=this.GetChildren();return(t=Math.floor(+t))<0||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<e.length;s++)if(t===e[s])return s;return NaN}_CreateSceneGraphInfo(t){this._sceneGraphInfo||(this._sceneGraphInfo=C3.New(C3.SceneGraphInfo,this)),t&&this._sceneGraphInfo.SetParent(t)}_GetSceneGraphInfo(){return this._sceneGraphInfo}_ReleaseSceneGraphInfo(){this._sceneGraphInfo&&(this._sceneGraphInfo.Release(),this._sceneGraphInfo=null)}_SetParent(t){t?(t._CreateSceneGraphInfo(null),this._CreateSceneGraphInfo(t)):(this._sceneGraphInfo&&this._sceneGraphInfo.SetParent(null),this.HasChildren()||this._ReleaseSceneGraphInfo());const e=this.GetLayout();e&&!e.IsCreatingInitialInstances()&&this._UpdateActiveSamplingMode()}_HasAnyParent(t){if(!this.HasParent())return!1;const e=this.GetParent();return e===t||e._HasAnyParent(t)}_HasChildRecursive(t){if(this.HasChild(t))return!0;for(const e of this.GetChildren())if(e._HasChildRecursive(t))return!0;return!1}_AddChildToSceneGraphInfo(t){this._sceneGraphInfo.GetChildren().push(t)}_RemoveChildFromSceneGraphInfo(t){const e=this._sceneGraphInfo.GetChildren(),s=e.indexOf(t);-1!==s&&e.splice(s,1),0!==e.length||this.HasParent()||this._ReleaseSceneGraphInfo(),t.HasChildren()||t._ReleaseSceneGraphInfo()}GetSceneGraphChildrenExportData(){const t=sceneGraphExportDataMap.get(this);return t?t.childrenData:null}GetSceneGraphZIndexExportData(){const t=sceneGraphExportDataMap.get(this);return t?t.zIndexData:NaN}GetSceneGraphZIndex(){const t=sceneGraphZIndexMap.get(this);return C3.IsFiniteNumber(t)?t:NaN}SetSceneGraphZIndex(t){sceneGraphZIndexMap.set(this,t)}SetUsePointsShaderProgram(){this._SetFlag(524288,!0),this._UpdateRendererStateGroup()}_UpdateRendererStateGroup(){if(!enableUpdateRendererStateGroup)return;const t=this._runtime.GetRenderer();let e;this._stateGroup&&t.ReleaseStateGroup(this._stateGroup),e=524288&this._flags?t.GetPointsRenderingProgram()||"<point>":t.GetTextureFillShaderProgram()||"<default>",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;++e)t[e].SetBboxChanged()}}CalculateBbox(t,e,s){const i=this.GetX(),n=this.GetY(),r=this.GetWidth(),h=this.GetHeight(),a=this.GetAngle();if(tempRect.setWH(i-this.#t*r,n-this.#e*h,r,h),s&&this.HasMesh()&&this.#r(tempRect),0===a?(e.setFromRect(tempRect),tempRect.normalize()):(tempRect.offset(-i,-n),e.setFromRotatedRectPrecalc(tempRect,this.GetSinAngle(),this.GetCosAngle()),e.offset(i,n),e.getBoundingBox(tempRect)),t){const e=this.GetDepth(),i=this.#s*e,n=this.GetTotalZ(),r=n-i,h=n+e-i;t.setFromRect(tempRect,Math.min(r,h),Math.max(r,h)),s&&this.HasMesh()&&this.#h(t)}}_UpdateBbox(){const t=this._flags;2&t&&(this.CalculateBbox(this._boundingBox,this._boundingQuad,!0),this._flags=-3&t)}GetBoundingBox(){return this._UpdateBbox(),this._boundingBox}GetBoundingQuad(){return this._UpdateBbox(),this._boundingQuad}PixelRoundQuad(t){const e=this.GetX(),s=this.GetY(),i=Math.round(e)-e,n=Math.round(s)-s;return 0===i&&0===n?t:(tempQuad.copy(t),tempQuad.offset(i,n),tempQuad)}OverwriteBoundingBox(t){this._boundingBox.copyAABB3D(t),this._boundingQuad.setFromAABB3DIgnoringZ(this._boundingBox),this._flags&=-3,this._UpdateCollisionCell(),this._UpdateRenderCell()}SetBboxChangeEventEnabled(t){this._SetFlag(4,t)}IsBboxChangeEventEnabled(){return!!(4&this._flags)}IsInViewport(t,e,s){const i=this.GetBoundingBox(),n=i.getBack();return e&&0!==n?this.GetLayer()._GetViewFrustum().ContainsAABB(i):0===n||s?t.intersectsAABB3D(i):this.#a(i,n)}#a(t,e){const s=this.GetLayer();return!(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;e<t;++e)this._allEffectTypes[e]._SetIndex(e)}}_LoadSingleEffectParameters(e,t){e.SetActive(t[0]);const s=t.slice(1);for(let e=0,t=s.length;e<t;++e){const t=s[e];if(Array.isArray(t)){const f=C3.New(C3.Color);f.setFromJSON(t),s[e]=f}}return s}GetOwner(){return this._owner}GetRuntime(){return this._owner.GetRuntime()}UpdateActiveEffects(){C3.clearArray(this._activeEffectTypes);let e=!0;for(const t of this._allEffectTypes)t.IsActive()&&(this._activeEffectTypes.push(t),t.GetShaderProgram().PreservesOpaqueness()||(e=!1));this._preservesOpaqueness=e}GetAllEffectTypes(){return this._allEffectTypes}HasAnyEffectType(){return this._allEffectTypes.length>0}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._effectParamBuffers.length?this._effectParamBuffers[e]:this._effectParams[e]}GetEffectParameter(e,t){if(e<0||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<this._effectParamBuffers.length&&this._effectParamBuffers[e].SetParameterValue(t,s),!0}_UpdateAllEffectParamBuffers(){const e=this._effectParams,t=this._effectParamBuffers;for(let s=0,f=Math.min(e.length,t.length);s<f;++s){const f=t[s],r=e[s];for(let e=0,t=r.length;e<t;++e)f.SetParameterValue(e,r[e])}}static SaveFxParamToJson(e){return e&&e instanceof C3.Color?{"t":"color","v":e.toJSON()}:e}static LoadFxParamFromJson(e){if(null===e)return NaN;if("object"==typeof e){if("color"===e["t"]){const t=C3.New(C3.Color);return t.setFromJSON(e["v"]),t}throw new Error("invalid effect parameter type")}return e}static SaveFxParamsToJson(e){return e.map(C3.EffectList.SaveFxParamToJson)}static LoadFxParamsFromJson(e){return e.map(C3.EffectList.LoadFxParamFromJson)}SaveToJson(){return this._allEffectTypes.map(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<r;++t){const r=this._shaderProgram.GetParameterType(t);if("float"===r||"percent"===r)e.push(0);else{if("color"!==r)throw new TypeError("unknown effect parameter type");e.push(C3.New(C3.Color,1,1,1,1))}}return e}};
}

// objects/instanceEffectList.js
{
const C3=self.C3;C3.InstanceEffectList=class extends C3.DefendedBase{constructor(e,t){super(),this._inst=e,this._wi=t,this._effectList=e.GetObjectClass().GetEffectList(),this._needsRebuildSteps=!0,this._wasDefaultColor=!0,this._was3D=!1,this._wasRotatedOrNegativeSize=!1,this._wasTexRotated=!1,this._wasMustPreDraw=!1,this._effectChain=C3.New(C3.Gfx.EffectChain,e.GetRuntime().GetCanvasManager().GetEffectChainManager(),{drawContent:(e,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<t;++e)this._activeEffectFlags.push(!0);this.UpdateActiveEffects(),this._effectList._AddInstanceEffectList(this)}Release(){this._effectList._RemoveInstanceEffectList(this);for(const e of this._effectParamBuffers)e&&e.Release();C3.clearArray(this._effectParamBuffers),this._effectChain.Release(),this._effectChain=null,C3.clearArray(this._activeEffectFlags),C3.clearArray(this._activeEffectTypes),C3.clearArray(this._effectParams),this._inst=null,this._effectList=null}_InitRenderer(e){e.IsWebGPU()&&(this._effectParamBuffers=this._effectList.GetAllEffectTypes().map(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;e<t;++e){const t=s[e];if(Array.isArray(t)){const f=C3.New(C3.Color);f.setFromJSON(t),s[e]=f}}return s}LoadDefaultEffectParameters(){for(const e of this._effectList.GetAllEffectTypes())this._effectParams.push(e.GetDefaultParameterValues());this._UpdateAllEffectParamBuffers()}GetOwner(){return this._owner}GetEffectList(){return this._effectList}GetEffectChain(){return this._MaybeRebuildEffectChainSteps(),this._effectChain}GetRuntime(){return this._inst.GetRuntime()}UpdateActiveEffects(){C3.clearArray(this._activeEffectTypes);const e=this._wi,t=this._effectList.GetAllEffectTypes(),s=this._activeEffectTypes,f=this._activeEffectFlags;let a=!0;for(let e=0,r=t.length;e<r;++e)if(f[e]){const f=t[e];s.push(f),f.GetShaderProgram().PreservesOpaqueness()||(a=!1)}this._preservesOpaqueness=a,e._SetHasAnyActiveEffect(!!s.length),this._needsRebuildSteps=!0}_MaybeRebuildEffectChainSteps(){const e=this._inst,t=this._wi,s=t.HasDefaultColor(),f=e.GetPlugin().Is3D(),a=0!==t.GetAngle()||0!==t.GetLayer().GetAngle()||t.GetWidth()<0||t.GetHeight()<0,r=e.IsCurrentTexRotated(),i=e.MustPreDraw();(this._needsRebuildSteps||s!==this._wasDefaultColor||f!==this._was3D||a!==this._wasRotatedOrNegativeSize||r!==this._wasTexRotated||i!==this._wasMustPreDraw||this._effectChain.NeedsRebuild())&&(this._effectChain.BuildSteps(this._activeEffectTypes.map(e=>e.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._effectParamBuffers.length?this._effectParamBuffers[e]:this._effectParams[e]}GetEffectParameter(e,t){if(e<0||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 e<this._effectParamBuffers.length&&this._effectParamBuffers[e].SetParameterValue(t,s),!0}_UpdateAllEffectParamBuffers(){const e=this._effectParams,t=this._effectParamBuffers;for(let s=0,f=t.length;s<f;++s){const f=t[s],a=e[s];for(let e=0,t=a.length;e<t;++e)f.SetParameterValue(e,a[e])}}PreservesOpaqueness(){return this._preservesOpaqueness}HasAnyActiveBackgroundBlendingEffect(){return this._activeEffectTypes.some(e=>e.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<n;t+=2){const n=t+1,o=l[t],i=l[n],[r,a]=s.LayerToCanvasCss(o+e.GetX(),i+e.GetY());l[t]=r,l[n]=a}const o=tempPolyB.pointsArr();for(let e=0,s=o.length;e<s;e+=2){const s=e+1,l=o[e],i=o[s],[r,a]=n.LayerToCanvasCss(l+t.GetX(),i+t.GetY());o[e]=r,o[s]=a}return tempPolyA.setBboxChanged(),tempPolyB.setBboxChanged(),this._polyCheckCount++,tempPolyA.intersectsPoly(tempPolyB,0,0)}}TestTilemapOverlapDifferentLayers(e,t){const s=e.GetLayer(),n=t.GetLayer();tempPolyC||(tempPolyC=C3.New(C3.CollisionPoly)),tempRect3||(tempRect3=C3.New(C3.Rect)),tempQuadB||(tempQuadB=C3.New(C3.Quad2D));const l=t.GetX(),o=t.GetY(),[i,r]=n.LayerToCanvasCss(l,o),[a,c]=s.CanvasCssToLayer(i,r),C=a-l,d=c-o;if(tempRect3.setFromAABB3D(t.GetBoundingBox()),tempRect3.offset(C,d),!e.GetBoundingBox().intersectsRect(tempRect3))return!1;if(tempQuadB.copy(t.GetBoundingQuad()),tempQuadB.offset(C,d),this._polyCheckCount++,!e.GetBoundingQuad().intersectsQuad(tempQuadB))return!1;tempPolyC.copy(t.GetTransformedCollisionPoly());const u=tempPolyC.pointsArr();for(let e=0,t=u.length;e<t;e+=2){const t=e+1;u[e]+=C,u[t]+=d}return tempPolyC.setBboxChanged(),this.TestTilemapOverlap(e,t,a,c,tempPolyC,tempRect3,tempQuadB)}TestTilemapOverlap(e,t,s,n,l,o,i){const r=void 0!==o?o:t.GetBoundingBox().toRect(),a=e.GetX(),c=e.GetY(),C=e.GetInstance().GetSdkInstance(),d=void 0!==s?s:t.GetX(),u=void 0!==n?n:t.GetY(),h=t.HasOwnCollisionPoly(),p=void 0!==i?i:t.GetBoundingQuad(),f=tileCollRectCandidates;C.GetCollisionRectCandidates(r,f);for(let e=0,s=f.length;e<s;++e){const s=f[e],n=s.GetRect();if(this._collisionCheckCount++,r.intersectsRectOffset(n,a,c)&&(tempQuad.setFromRect(n),tempQuad.offset(a,c),tempQuad.intersectsQuad(p)))if(h){const e=void 0!==l?l:t.GetTransformedCollisionPoly();let o=d,i=u;void 0!==l&&(o=t.GetX(),i=t.GetY());const r=s.GetPoly();if(r){if(this._polyCheckCount++,r.intersectsPoly(e,o-(a+n.getLeft()),i-(c+n.getTop())))return C3.clearArray(f),!0}else if(tempPolyA.setFromQuad(tempQuad,0,0),tempPolyA.intersectsPoly(e,o,i))return C3.clearArray(f),!0}else{const e=s.GetPoly();if(!e)return C3.clearArray(f),!0;if(tempPolyA.setFromQuad(p,0,0),e.intersectsPoly(tempPolyA,-(a+n.getLeft()),-(c+n.getTop())))return C3.clearArray(f),!0}}return C3.clearArray(f),!1}TestAndSelectCanvasPointOverlap(e,t,s){const n=e.GetCurrentSol(),l=this._runtime.GetCurrentEvent();if(!l)throw new Error("cannot call outside event");const o=l.IsOrBlock(),i=new C3.LayerStateCache;if(n.IsSelectAll()){s||(n._SetSelectAll(!1),C3.clearArray(n._GetOwnInstances())),o&&C3.clearArray(n._GetOwnElseInstances());for(const l of e.GetInstances()){const e=l.GetWorldInfo(),r=e.GetLayer();let a=!1;if(i.IsInteractive(r)&&e.IsInViewport2()&&(a=t.some(([t,s])=>{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<c;++l){const c=e[l],C=c.GetWorldInfo(),d=C.GetLayer();let u=!1;if(i.IsInteractive(d)&&C.IsInViewport2()&&(u=t.some(([e,t])=>{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;a<n;++a)if(o.SetXY(i+t*a,r+s*a),o.SetBboxChanged(),!this.TestOverlap(e,l))return!0;return o.SetXY(i,r),o.SetBboxChanged(),!1}PushOutSolid(e,t,s,n,l,o){n=n||50;const i=e.GetWorldInfo(),r=i.GetX(),a=i.GetY();let c=null,C=null;for(let d=0;d<n;++d)if(i.SetXY(r+t*d,a+s*d),i.SetBboxChanged(),!this.TestOverlap(e,c))if(c=this.TestOverlapSolid(e),c)C=c;else if(l&&(c=o?this.TestOverlap(e,o)?o:null:this.TestOverlapJumpthru(e),c&&(C=c)),!c)return C&&this.PushInFractional(e,t,s,C,16,!0),!0;return i.SetXY(r,a),i.SetBboxChanged(),!1}PushOutSolidAxis(e,t,s,n){n=n||50;const l=e.GetWorldInfo(),o=l.GetX(),i=l.GetY();let r=null,a=null;for(let c=0;c<n;++c)for(let n=0;n<2;++n){const C=2*n-1;if(l.SetXY(o+t*c*C,i+s*c*C),l.SetBboxChanged(),!this.TestOverlap(e,r)){if(r=this.TestOverlapSolid(e),!r)return a&&this.PushInFractional(e,t*C,s*C,a,16,!0),!0;a=r}}return l.SetXY(o,i),l.SetBboxChanged(),!1}PushInFractional(e,t,s,n,l,o){let i=2,r=!1,a=!1;const c=e.GetWorldInfo();let C=c.GetX(),d=c.GetY();for(;i<=l;){const l=1/i;i*=2,c.OffsetXY(t*l*(r?1:-1),s*l*(r?1:-1)),c.SetBboxChanged(),this.TestOverlap(e,n)||o&&this.TestOverlapSolid(e)?(r=!0,a=!0):(r=!1,a=!1,C=c.GetX(),d=c.GetY())}a&&(c.SetXY(C,d),c.SetBboxChanged())}PushOutSolidNearest(e,t=100){let s=0;const n=e.GetWorldInfo(),l=n.GetX(),o=n.GetY();let i=0,r=this.TestOverlapSolid(e);if(!r)return!0;for(;s<=t;){let t=0,a=0;switch(i){case 0:t=0,a=-1,s++;break;case 1:t=1,a=-1;break;case 2:t=1,a=0;break;case 3:t=1,a=1;break;case 4:t=0,a=1;break;case 5:t=-1,a=1;break;case 6:t=-1,a=0;break;case 7:t=-1,a=-1}if(i=(i+1)%8,n.SetXY(Math.floor(l+t*s),Math.floor(o+a*s)),n.SetBboxChanged(),!this.TestOverlap(e,r)&&(r=this.TestOverlapSolid(e),!r))return!0}return n.SetXY(l,o),n.SetBboxChanged(),!1}CalculateBounceAngle(e,t,s,n){const l=e.GetWorldInfo(),o=l.GetX(),i=l.GetY(),r=Math.max(10,C3.distanceTo(t,s,o,i)),a=C3.angleTo(t,s,o,i),c=n||this.TestOverlapSolid(e);if(!c)return C3.clampAngle(a+Math.PI);let C=c,d=0,u=0;const h=C3.toRadians(5);let p;for(p=1;p<36;++p){const o=a-p*h;if(l.SetXY(t+Math.cos(o)*r,s+Math.sin(o)*r),l.SetBboxChanged(),!this.TestOverlap(e,C)&&(C=n?null:this.TestOverlapSolid(e),!C)){d=o;break}}for(36===p&&(d=C3.clampAngle(a+Math.PI)),C=c,p=1;p<36;++p){const o=a+p*h;if(l.SetXY(t+Math.cos(o)*r,s+Math.sin(o)*r),l.SetBboxChanged(),!this.TestOverlap(e,C)&&(C=n?null:this.TestOverlapSolid(e),!C)){u=o;break}}if(36===p&&(u=C3.clampAngle(a+Math.PI)),l.SetXY(o,i),l.SetBboxChanged(),u===d)return u;const f=C3.angleDiff(u,d)/2;let G;G=C3.angleClockwise(u,d)?C3.clampAngle(d+f+Math.PI):C3.clampAngle(u+f);const m=Math.cos(a),y=Math.sin(a),g=Math.cos(G),T=Math.sin(G),_=m*g+y*T,I=m-2*_*g,S=y-2*_*T;return C3.angleTo(0,0,I,S)}TestSegmentOverlap(e,t,s,n,l){if(!l)return!1;const o=l.GetWorldInfo();if(!o.IsCollisionEnabled())return!1;if(this._collisionCheckCount++,tempRect.set(Math.min(e,s),Math.min(t,n),Math.max(e,s),Math.max(t,n)),!o.GetBoundingBox().intersectsRect(tempRect))return!1;if(l.HasTilemap())return this._TestSegmentOverlapTilemap(e,t,s,n,l,o);if(this._polyCheckCount++,!o.GetBoundingQuad().intersectsSegment(e,t,s,n))return!1;if(!o.HasOwnCollisionPoly())return!0;return o.GetTransformedCollisionPoly().intersectsSegment(o.GetX(),o.GetY(),e,t,s,n)}_TestSegmentOverlapTilemap(e,t,s,n,l,o){const i=o.GetX(),r=o.GetY(),a=l.GetSdkInstance(),c=tileCollRectCandidates;tempRect2.set(e,t,s,n),tempRect2.normalize(),a.GetCollisionRectCandidates(tempRect2,c);for(let l=0,o=c.length;l<o;++l){const o=c[l],a=o.GetRect();if(this._collisionCheckCount++,tempRect.intersectsRectOffset(a,i,r)&&(tempQuad.setFromRect(a),tempQuad.offset(i,r),tempQuad.intersectsSegment(e,t,s,n))){const l=o.GetPoly();if(!l)return C3.clearArray(c),!0;if(this._polyCheckCount++,l.intersectsSegment(i+a.getLeft(),r+a.getTop(),e,t,s,n))return C3.clearArray(c),!0}}return C3.clearArray(c),!1}TestRectOverlap(e,t){if(!t)return!1;const s=t.GetWorldInfo();if(!s.IsCollisionEnabled())return!1;if(this._collisionCheckCount++,!s.GetBoundingBox().intersectsRect(e))return!1;if(t.HasTilemap())return this._TestRectOverlapTilemap(e,t,s);if(this._polyCheckCount++,tempQuad.setFromRect(e),!s.GetBoundingQuad().intersectsQuad(tempQuad))return!1;if(!s.HasOwnCollisionPoly())return!0;const n=tempPolyA;n.setFromRect(e,s.GetX(),s.GetY());const l=s.GetTransformedCollisionPoly();return n.intersectsPoly(l,0,0)}_TestRectOverlapTilemap(e,t,s){const n=s.GetX(),l=s.GetY(),o=t.GetSdkInstance(),i=tileCollRectCandidates;o.GetCollisionRectCandidates(e,i);for(let t=0,s=i.length;t<s;++t){const s=i[t],o=s.GetRect();if(this._collisionCheckCount++,e.intersectsRectOffset(o,n,l)){const t=s.GetPoly();if(!t)return C3.clearArray(i),!0;if(this._polyCheckCount++,tempPolyA.setFromRect(e,0,0),t.intersectsPoly(tempPolyA,-(n+o.getLeft()),-(l+o.getTop())))return C3.clearArray(i),!0}}return C3.clearArray(i),!1}TestRayIntersectsInstance(e,t){if(!e)return;const s=e.GetWorldInfo();s.IsCollisionEnabled()&&(this._collisionCheckCount++,s.GetBoundingBox().intersectsRect(t.rect)&&(e.HasTilemap()?this._TestRayIntersectsTilemap(e,s,t):(this._polyCheckCount++,s.HasOwnCollisionPoly()?t.TestInstancePoly(e,s.GetX(),s.GetY(),s.GetTransformedCollisionPoly()):t.TestInstanceQuad(e,s.GetBoundingQuad()))))}_TestRayIntersectsTilemap(e,t,s){const n=t.GetX(),l=t.GetY(),o=tileCollRectCandidates;e.GetSdkInstance().GetCollisionRectCandidates(s.rect,o);for(let i=0,r=o.length;i<r;i++){const r=o[i],a=r.GetRect();if(this._collisionCheckCount++,s.rect.intersectsRectOffset(a,n,l)){const o=r.GetPoly();this._polyCheckCount++,o?s.TestInstancePoly(e,n+a.getLeft(),l+a.getTop(),o):s.TestInstanceRect(e,t.GetX(),t.GetY(),a)}}C3.clearArray(o)}SetCollisionCellSize(e,t){if(e===this._collisionCellWidth&&t===this._collisionCellHeight)return;this._collisionCellWidth=e,this._collisionCellHeight=t;const s=this._runtime.GetAllObjectClasses();for(const n of s)if(n.IsWorldType()){for(const e of n.instancesIncludingPendingCreate())e.GetWorldInfo()._RemoveFromCollisionCells();n._GetCollisionCellGrid().SetCellSize(e,t),n._SetAnyCollisionCellChanged();for(const e of n.instancesIncludingPendingCreate()){const t=e.GetWorldInfo();t._SetCollisionCellChanged(),t._UpdateCollisionCell()}}}GetCollisionCellSize(){return[this._collisionCellWidth,this._collisionCellHeight]}_InitCollisionCellSize(e,t){this._collisionCellWidth=e,this._collisionCellHeight=t}};
}

// collisions/sparseGrid.js
{
const C3=self.C3;C3.SparseGrid=class extends C3.DefendedBase{constructor(t,e){super(),this._cellWidth=t,this._cellHeight=e,this._cells=C3.New(C3.PairMap)}Release(){this._cells.Release(),this._cells=null}SetCellSize(t,e){if(!this._cells.IsEmpty())throw new Error("grid not empty");this._cellWidth=t,this._cellHeight=e}GetCell(t,e,l){let i=this._cells.Get(t,e);return i||(l?(i=C3.New(C3.GridCell,this,t,e),this._cells.Set(t,e,i),i):null)}XToCell(t){const e=Math.floor(t/this._cellWidth);return isFinite(e)?e:0}YToCell(t){const e=Math.floor(t/this._cellHeight);return isFinite(e)?e:0}Update(t,e,l){if(e)for(let i=e.getLeft(),s=e.getRight();i<=s;++i)for(let s=e.getTop(),o=e.getBottom();s<=o;++s){if(l&&l.containsPoint(i,s))continue;const e=this.GetCell(i,s,!1);e&&(e.Remove(t),e.IsEmpty()&&this._cells.Delete(i,s))}if(l)for(let i=l.getLeft(),s=l.getRight();i<=s;++i)for(let s=l.getTop(),o=l.getBottom();s<=o;++s)e&&e.containsPoint(i,s)||this.GetCell(i,s,!0).Insert(t)}QueryRange(t,e){let l=this.XToCell(t.getLeft());const i=this.YToCell(t.getTop()),s=this.XToCell(t.getRight()),o=this.YToCell(t.getBottom());if(isFinite(s)&&isFinite(o))for(;l<=s;++l)for(let t=i;t<=o;++t){const i=this.GetCell(l,t,!1);i&&i.Dump(e)}}};
}

// collisions/gridCell.js
{
const C3=self.C3;C3.GridCell=class extends C3.DefendedBase{constructor(s,e,t){super(),this._grid=s,this._x=e,this._y=t,this._instances=C3.New(C3.ArraySet)}Release(){this._instances.Release(),this._instances=null,this._grid=null}IsEmpty(){return this._instances.IsEmpty()}Insert(s){this._instances.Add(s)}Remove(s){this._instances.Delete(s)}Dump(s){C3.appendArray(s,this._instances.GetArray())}};
}

// collisions/ray.js
{
const C3=self.C3,PADDING=1e-6,NO_HIT=2;C3.Ray=class{constructor(){this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.dx=0,this.dy=0,this.rect=new C3.Rect,this.hitFraction=2,this.hitUid=null,this.hitNormal=0,this.hitNormalDx=0,this.hitNormalDy=0,this.hitX=0,this.hitY=0,this.distance=0,this.normalX=1,this.normalY=0,this.reflectionX=1,this.reflectionY=0}DidCollide(){return this.hitFraction<1.000001}Reset(){this.hitFraction=2}Set(t,i,s,h){return this.x1=t,this.y1=i,this.x2=s,this.y2=h,this.dx=s-t,this.dy=h-i,this.rect.set(t,i,s,h),this.rect.normalize(),this.hitFraction=2,this.hitUid=null,this.hitNormal=0,this.hitNormalDx=0,this.hitNormalDy=0,this.hitX=0,this.hitY=0,this.distance=0,this.normalX=1,this.normalY=0,this.reflectionX=1,this.reflectionY=0,this}Complete(){if(!1===this.DidCollide())return;const t=this.dx*this.hitFraction,i=this.dy*this.hitFraction,s=C3.hypot2DFast(t,i),h=t/s,e=i/s;this.distance=s-PADDING,this.hitX=this.x1+h*this.distance,this.hitY=this.y1+e*this.distance,this.hitNormal=Math.atan2(this.hitNormalDy,this.hitNormalDx)+Math.PI/2,this.normalX=Math.cos(this.hitNormal),this.normalY=Math.sin(this.hitNormal);const n=h*this.normalX+e*this.normalY;if(this.reflectionX=h-2*this.normalX*n,this.reflectionY=e-2*this.normalY*n,n>0){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.hitFraction&&(this.hitFraction=n,this.hitUid=t.GetUID(),this.hitNormalDx=i-h,this.hitNormalDy=s-e)}TestInstanceRect(t,i,s,h){const e=i+h.getLeft(),n=i+h.getRight(),a=s+h.getTop(),o=s+h.getBottom();this.TestInstanceSegment(t,e,a,n,a),this.TestInstanceSegment(t,n,a,n,o),this.TestInstanceSegment(t,n,o,e,o),this.TestInstanceSegment(t,e,o,e,a)}TestInstanceQuad(t,i){const s=i.getTlx(),h=i.getTly(),e=i.getTrx(),n=i.getTry(),a=i.getBrx(),o=i.getBry(),r=i.getBlx(),l=i.getBly();this.TestInstanceSegment(t,s,h,e,n),this.TestInstanceSegment(t,e,n,a,o),this.TestInstanceSegment(t,a,o,r,l),this.TestInstanceSegment(t,r,l,s,h)}TestInstancePoly(t,i,s,h){const e=h.pointsArr();for(let h=0,n=e.length;h<n;h+=2){const a=(h+2)%n,o=e[h]+i,r=e[h+1]+s,l=e[a]+i,c=e[a+1]+s;this.TestInstanceSegment(t,o,r,l,c)}}};
}

// collisions/layerStateCache.js
{
const C3=self.C3;C3.LayerStateCache=class{constructor(){this._layerCache=new Map}Release(){for(const e of this._layerCache.values())e.layerPts.Clear();this._layerCache.clear()}_GetLayerCache(e){let a=this._layerCache.get(e);return void 0===a&&(a={isInteractive:null,layerPts:new C3.PairMap},this._layerCache.set(e,a)),a}IsInteractive(e){const a=this._GetLayerCache(e);return null===a.isInteractive&&(a.isInteractive=e.IsSelfAndParentsInteractive()),a.isInteractive}CanvasCssToLayer(e,a,t,s){if(0!==s)return e.CanvasCssToLayer(a,t,s);const r=this._GetLayerCache(e);let n=r.layerPts.Get(a,t);return void 0===n&&(n=e.CanvasCssToLayer(a,t,s),r.layerPts.Set(a,t,n)),n}};
}

// canvasManager.js
{
const C3=self.C3,VALID_FULLSCREEN_MODES=new Set(["off","crop","scale-inner","integer-scale-inner","scale-outer","integer-scale-outer","letterbox-scale","letterbox-integer-scale"]),VALID_FULLSCREEN_SCALING_QUALITIES=new Set(["high","low"]),glMatrix=self.glMatrix,mat4=glMatrix.mat4,vec3=glMatrix.vec3,tempProjection=mat4.create(),PERCENTTEXT_WIDTH=300,PERCENTTEXT_HEIGHT=200,PROGRESSBAR_WIDTH=120,PROGRESSBAR_HEIGHT=8,tempQuad=C3.New(C3.Quad2D),tempRect=C3.New(C3.Rect),SPLASH_MIN_DISPLAY_TIME=3e3,SPLASH_AFTER_FADEOUT_WAIT_TIME=200,SPLASH_FADE_DURATION=300,RENDERER_THROTTLE_FRAME_INTERVAL=8;C3.CanvasManager=class extends C3.DefendedBase{#e=!1;#t=null;constructor(e){super(),this._runtime=e,this._canvasLayers=[],this._isWebGPUEnabled=!1,this._webglRenderer=null,this._webgpuRenderer=null,this._iRenderer=null,this._gpuPreference="high-performance",this._multitexturingMode="auto",this._windowInnerWidth=0,this._windowInnerHeight=0,this._cssDisplayMode="",this._canvasCssWidth=0,this._canvasCssHeight=0,this._canvasDeviceWidth=0,this._canvasDeviceHeight=0,this._canvasCssOffsetX=0,this._canvasCssOffsetY=0,this._zAxisScale="normalized",this._initFieldOfView=0,this._zNear=1,this._zFar=1e4,this._enableMipmaps=!0,this._textureAnisotropy=1,this._drawWidth=0,this._drawHeight=0,this._fullscreenMode="letterbox-scale",this._documentFullscreenMode="letterbox-scale",this._deviceTransformOffX=0,this._deviceTransformOffY=0,this._defaultProjectionMatrix=mat4.create(),this._wantFullscreenScalingQuality="high",this._fullscreenScalingQuality=this._wantFullscreenScalingQuality,this._isDocumentFullscreen=!1,this._availableAdditionalRenderTargets=[],this._usedAdditionalRenderTargets=new Set,this._shaderData=self["C3_Shaders"],this._effectChainManager=C3.New(C3.Gfx.EffectChainManager,{getDrawSize:()=>[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._canvasDeviceWidth<t||this._canvasDeviceHeight<i)this._drawWidth=this._canvasDeviceWidth,this._drawHeight=this._canvasDeviceHeight,this._fullscreenScalingQuality="high";else{const s=this.GetDisplayScale(),r=this._runtime.GetDevicePixelRatio();if(this._drawWidth=t,this._drawHeight=i,this._fullscreenScalingQuality="low","scale-inner"===e){const e=t/i,s=this._windowInnerWidth/this._windowInnerHeight;s<e?this._drawWidth=this._drawHeight*s:s>e&&(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:s<e&&(this._drawHeight=this._drawWidth/s)}else"integer-scale-inner"!==e&&"integer-scale-outer"!==e||(this._drawWidth=this._windowInnerWidth/s,this._drawHeight=this._windowInnerHeight/s);"scale-inner"!==e&&"scale-outer"!==e&&"integer-scale-inner"!==e&&"integer-scale-outer"!==e||(this._drawWidth!==Math.ceil(this._drawWidth)&&(this._drawWidth=Math.ceil(this._drawWidth),this._canvasDeviceWidth=Math.round(this._drawWidth*s*r),this._canvasCssWidth=this._canvasDeviceWidth/r),this._drawHeight!==Math.ceil(this._drawHeight)&&(this._drawHeight=Math.ceil(this._drawHeight),this._canvasDeviceHeight=Math.round(this._drawHeight*s*r),this._canvasCssHeight=this._canvasDeviceHeight/r),this._runtime.SetViewportSize(this._drawWidth,this._drawHeight))}}}GetRuntime(){return this._runtime}GetMainCanvas(){return this._canvasLayers[0].canvas}GetEffectChainManager(){return this._effectChainManager}IsDocumentFullscreen(){return this._isDocumentFullscreen}GetCssDisplayMode(){return this._cssDisplayMode}SetFullscreenMode(e){if(!VALID_FULLSCREEN_MODES.has(e))throw new Error("invalid fullscreen mode");this._fullscreenMode=e;const t=this._runtime.GetLayoutManager();t.SetAllLayerProjectionChanged(),t.SetAllLayerMVChanged()}GetFullscreenMode(){return this._fullscreenMode}SetDocumentFullscreenMode(e){if(!VALID_FULLSCREEN_MODES.has(e))throw new Error("invalid fullscreen mode");this._documentFullscreenMode=e;const t=this._runtime.GetLayoutManager();t.SetAllLayerProjectionChanged(),t.SetAllLayerMVChanged()}GetDocumentFullscreenMode(){return this._documentFullscreenMode}GetCurrentFullscreenMode(){return this.IsDocumentFullscreen()?this.GetDocumentFullscreenMode():this.GetFullscreenMode()}SetFullscreenScalingQuality(e){if(!VALID_FULLSCREEN_SCALING_QUALITIES.has(e))throw new Error("invalid fullscreen scaling quality");this._wantFullscreenScalingQuality=e,this._runtime.GetLayoutManager().SetAllLayerProjectionChanged()}GetSetFullscreenScalingQuality(){return this._wantFullscreenScalingQuality}GetCurrentFullscreenScalingQuality(){return this._fullscreenScalingQuality}static _FullscreenModeNumberToString(e){switch(e){case 0:return"off";case 1:return"crop";case 2:return"scale-inner";case 3:return"integer-scale-inner";case 4:return"scale-outer";case 5:return"integer-scale-outer";case 6:return"letterbox-scale";case 7:return"letterbox-integer-scale";default:throw new Error("invalid fullscreen mode")}}GetLastWidth(){return this._windowInnerWidth}GetLastHeight(){return this._windowInnerHeight}GetDrawWidth(){return this._drawWidth}GetDrawHeight(){return this._drawHeight}SetMipmapsEnabled(e){this._enableMipmaps=!!e}GetMipmapsEnabled(){return this._enableMipmaps}_SetTextureAnisotropy(e){this._textureAnisotropy=e}GetTextureAnisotropy(){return this._textureAnisotropy}SetAnisotropicFiltering(e){this._textureAnisotropy!==e&&(this._textureAnisotropy=e,this.GetRenderer().SetTexturesAnisotropy(this._textureAnisotropy),this._runtime.UpdateRender())}IsRendererContextLost(){return this.GetRenderer().IsContextLost()}_OnWebGLContextLost(e){console.log("[Construct] WebGL context lost"),e.preventDefault(),this._availableAdditionalRenderTargets=[],this._usedAdditionalRenderTargets.clear(),this._effectChainManager.OnContextLost(),this._webglRenderer.OnContextLost(),this._runtime._OnRendererContextLost()}_OnWebGPUDeviceLost(){console.log("[Construct] WebGPU device lost"),this._availableAdditionalRenderTargets=[],this._usedAdditionalRenderTargets.clear(),this._effectChainManager.OnContextLost(),this._runtime._OnRendererContextLost()}async _OnWebGLContextRestored(e){await this._webglRenderer.OnContextRestored(),await this._InitRenderer(),await this._runtime._OnRendererContextRestored(),console.log("[Construct] WebGL context restored")}async _OnWebGPUDeviceRestored(){await this._InitRenderer(),await this._runtime._OnRendererContextRestored(),console.log("[Construct] WebGPU device restored")}GetWebGLRenderer(){return this._webglRenderer}GetWebGPURenderer(){return this._webgpuRenderer}GetRenderer(){return this._webgpuRenderer||this._webglRenderer}GetIRenderer(){return this._iRenderer}GetRendererString(){let e="";return this._runtime.GetWebGPURenderer()?(e="webgpu",this._runtime.GetWebGPURenderer().IsCompatibilityMode()&&(e+="-compatibility")):e="webgl"+this._runtime.GetWebGLRenderer().GetWebGLVersionNumber(),this._runtime.GetRenderer().HasMajorPerformanceCaveat()&&(e+="-software"),e}GetRendererDetailString(){return this._runtime.GetWebGPURenderer()?this._runtime.GetWebGPURenderer().GetAdapterInfoString():this._runtime.GetWebGLRenderer().GetUnmaskedRenderer()}GetRenderScale(){return"low"===this._fullscreenScalingQuality?1/this._runtime.GetDevicePixelRatio():this.GetDisplayScale()}GetDisplayScale(){const e=this.GetCurrentFullscreenMode();if("off"===e||"crop"===e)return 1;const t=this._runtime.GetOriginalViewportWidth(),i=this._runtime.GetOriginalViewportHeight(),s=t/i,r=this._canvasDeviceWidth/this._canvasDeviceHeight;let a;return a="scale-inner"!==e&&"integer-scale-inner"!==e&&r>s||("scale-inner"===e||"integer-scale-inner"===e)&&r<s?this._canvasCssHeight/i:this._canvasCssWidth/t,"integer-scale-outer"===e?Math.floor(a):"integer-scale-inner"===e?Math.ceil(a):a}GetEffectLayerScaleParam(){return"low"===this.GetCurrentFullscreenScalingQuality()?1:this.GetDisplayScale()}GetEffectDevicePixelRatioParam(){return"low"===this.GetCurrentFullscreenScalingQuality()?1:this._runtime.GetDevicePixelRatio()}SetDeviceTransformOffset(e,t){this._deviceTransformOffX=e,this._deviceTransformOffY=t}SetDeviceTransform(e,t,i,s=!0){t=t||this._drawWidth,i=i||this._drawHeight;const r=t/2+this._deviceTransformOffX,a=i/2+this._deviceTransformOffY;if(s){let s=this.GetDefaultProjectionMatrix();t===this._drawWidth&&i===this._drawHeight||(e.CalculatePerspectiveMatrix(tempProjection,t/i),s=tempProjection),e.SetProjectionMatrix(s)}const n=e.CalculateLookAtModelView2(r,a,e.GetDefaultCameraZ(i),r,a,0,i);e.SetModelViewMatrix(n)}SetCssTransform(e,t=!0){const i=this.GetCssWidth(),s=this.GetCssHeight(),r=i/2,a=s/2;t&&e.SetProjectionMatrix(this.GetDefaultProjectionMatrix());const n=e.CalculateLookAtModelView2(r,a,e.GetDefaultCameraZ(s),r,a,0,s);e.SetModelViewMatrix(n)}GetDeviceWidth(){return this._canvasDeviceWidth}GetDeviceHeight(){return this._canvasDeviceHeight}GetCssWidth(){return this._canvasCssWidth}GetCssHeight(){return this._canvasCssHeight}GetCanvasClientX(){return this._canvasCssOffsetX}GetCanvasClientY(){return this._canvasCssOffsetY}GetHTMLLayerCount(){return this._canvasLayers.length}#i(){return"undefined"!=typeof OffscreenCanvas&&this.GetMainCanvas()instanceof OffscreenCanvas}async SetHTMLLayerCount(e,t=!1){if(e<1)throw new Error("invalid HTML layer count");if(this._canvasLayers.length===e)return;const i={"count":e,"layersDomState":this._runtime.GetLayoutManager().GetMainRunningLayout()._GetRootLayers().filter(e=>e.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)this._canvasLayers.length=e;else for(const e of s["addedCanvases"]){e.width=this._canvasDeviceWidth,e.height=this._canvasDeviceHeight;const t=this.#i()?"bitmaprenderer":"2d",i=e.getContext(t);if(!i)throw new Error(`failed to acquire '${t}' canvas context`);this._canvasLayers.push({canvas:e,ctx:i})}this._runtime.UpdateRender()}BlitMainCanvasToHTMLLayerCanvas(e){if(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;t<this._gpuTimeEndFrame;++t)e.push(this._webgpuTimingPromises.get(t)),this._webgpuTimingPromises.delete(t);this._gpuTimeStartFrame=this._gpuTimeEndFrame,this._gpuTimeEndFrame=0,this.#s(e)}async#s(e){let t;try{t=await Promise.all(e)}catch(e){return void console.error("[WebGPU] Error reading frame timing results: ",e)}const i=this._runtime.GetMainRunningLayout(),s=C3.MakeFilledArray(i.GetLayerCount()+1,0);let r=0;for(const e of t){if(!e)continue;let t=BigInt(0),i=BigInt(0);const a=BigInt(0);for(let r=0,n=Math.min(s.length,e.length/2);r<n;++r){const n=e[2*r],h=e[2*r+1];n!==a&&(t===a||n<t)&&(t=n),h>i&&(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);i<r;++i){const r=s[i+1];t.set(e[i],r)}const r=[],a=new Map;for(const[e,i]of t){const s=[...e.selfAndAllSubLayers()].reduce((e,i)=>e+(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.#T<s?this.#T=s+t:i=this.#T-s,this.#v=globalThis.setTimeout(()=>e.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;i<s;++i)t.DrawForHTMLLayerIndex(e,i),e.IsWebGPU()&&e.Restart();this._NeedsHTMLLayerCompositing(e)||t._MaybeStartDrawToOwnTexture(e),t.DrawMain(e),this.Dispatcher().dispatchEvent(this.#s["afterrender"])}Trigger(e,t,s){if(!this._hasStarted)return!1;const i=!this._isInTick&&!this.#r.IsInTrigger();let n=0;i&&(n=performance.now());const a=this.IsDebug();a&&this.SetDebuggingEnabled(!1);const r=this.#r._Trigger(this.#a,e,t,s);if(i){const e=performance.now()-n;this._mainThreadTimeCounter+=e,a&&C3Debugger.AddTriggersTime(e)}return a&&this.SetDebuggingEnabled(!0),r}DebugTrigger(e,t,s){if(!this.IsDebugging())return this.Trigger(e,t,s);if(this.HitBreakpoint())throw new Error("called DebugTrigger() while stopped on breakpoint");if(!this._isInTick&&!this.#r.IsInTrigger())throw new Error("called DebugTrigger() outside of event code - use TriggerAsync() instead");return this.#r._DebugTrigger(this.#a,e,t,s)}async TriggerAsync(e,t,s){if(!this.IsDebugging())return this.Trigger(e,t,s);if(!this._hasStarted)return!1;if(this.HitBreakpoint())return this.#r.QueueDebugTrigger(e,t,s);if(!this.GetMainRunningLayout())return this.#r.QueueTrigger(e,t,s);const i=performance.now(),n=this.#r._DebugTrigger(this.#a,e,t,s);let a=n.next();for(;!a.done;)await this.DebugBreak(a.value),a=n.next();return this.IsSuspended()||this.#r.IsInTrigger()||(await this.#r.RunQueuedDebugTriggersAsync(),this._hasStartedTicking&&!this._isInTick&&this._RequestAnimationFrame()),this._mainThreadTimeCounter+=performance.now()-i,a.value}FastTrigger(e,t,s){const i=this.IsDebug();i&&this.SetDebuggingEnabled(!1);const n=this.#r._FastTrigger(this.#a,e,t,s);return i&&this.SetDebuggingEnabled(!0),n}DebugFastTrigger(e,t,s){return this.#r._DebugFastTrigger(this.#a,e,t,s)}ScheduleTriggers(e){return this._scheduleTriggersThrottle.Add(e)}PushCurrentLayout(e){this._currentLayoutStack.push(e)}PopCurrentLayout(){if(!this._currentLayoutStack.length)throw new Error("layout stack empty");this._currentLayoutStack.pop()}GetCurrentLayout(){return this._currentLayoutStack.length?this._currentLayoutStack.at(-1):this.GetMainRunningLayout()}GetDt(e){return e&&-1!==e.GetTimeScale()?this._dt1*e.GetTimeScale():this._dt}_GetDtFast(){return this._dt}GetDt1(){return this._dt1}GetDtRaw(){return this._dtRaw}GetTimeScale(){return this._timeScale}SetTimeScale(e){(isNaN(e)||e<0)&&(e=0),this._timeScale=e}SetMinDt(e){this._minDt=Math.max(e,0)}GetMinDt(){return this._minDt}SetMaxDt(e){this._maxDt=Math.max(e,0)}GetMaxDt(){return this._maxDt}GetFramesPerSecond(){return this._fps}GetTicksPerSecond(){return this._tps}GetMainThreadTime(){return this._mainThreadTime}GetStartTime(){return this._startTime}GetGameTime(){return this._gameTime.Get()}GetGameTimeRaw(){return this._gameTimeRaw.Get()}GetWallTime(){return this._wallTime.Get()}GetTickCount(){return this._tickCount}GetTickCountNoSave(){return this._tickCountNoSave}GetObjectCount(){return this._objectCount}GetProjectName(){return this._projectName}GetProjectVersion(){return this._projectVersion}GetProjectUniqueId(){return this._projectUniqueId}GetAppId(){return this._appId}GetExportTimestamp(){return this._exportTimestamp}GetInstanceByUID(e){if(this.#M)throw new Error("cannot call while loading state - wait until afterload event");return this._instancesByUid.get(e)||null}_RemoveInstanceFromUIDMap(e){if(this.#M)throw new Error("cannot call while loading state - wait until afterload event");this._instancesByUid.delete(e)}_RefreshUidMap(){this._instancesByUid.clear();for(const e of this._allObjectClasses)if(!e.IsFamily())for(const t of e.GetInstances())this._instancesByUid.set(t.GetUID(),t)}IsPreview(){return"preview"===this._exportType}IsDebug(){return this._isDebug}GetExportType(){return this._exportType}IsCordova(){return"cordova"===this._exportType}IsAndroidWebView(){return"Android"===C3.Platform.OS&&("cordova"===this._exportType||"playable-ad-single-file"===this._exportType||"playable-ad-zip"===this._exportType||"instant-games"===this._exportType)}IsiOSCordova(){return this._isiOSCordova}IsiOSWebView(){return this._isiOSWebView}IsWindowsWebView2(){return this._isWindowsWebView2}IsAnyWebView2Wrapper(){return this._isAnyWebView2Wrapper}GetCollisionEngine(){return this.#h}GetSolidBehavior(){return this.#o.GetSolidBehavior()}GetJumpthruBehavior(){return this.#o.GetJumpthruBehavior()}Uses3DFeatures(){return this._uses3dFeatures}GetZScaleFactor(){return this.GetRenderer().GetZAxisScaleFactor(this.GetViewportHeight())}GetDefaultCameraZ(e){return this.GetRenderer().GetDefaultCameraZ(e||this.GetViewportHeight())}IsLayoutFirstTick(){return this._isLayoutFirstTick}SetPixelRoundingEnabled(e){e=!!e,this._isPixelRoundingEnabled!==e&&(this._isPixelRoundingEnabled=e,this.GetLayoutManager().SetAllLayerMVChanged(),this.UpdateRender())}IsPixelRoundingEnabled(){return this._isPixelRoundingEnabled}GetTextIconSet(e){if(!this._iconChangeHandlers.has(e)){const t=()=>this.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<this._maxNumWorkers?this._MaybeCreateExtraWorker():this._inputPort.postMessage({"type":"_no_more_workers"}))}_GetWorkerCountNeededForPendingJobs(){let r=0;const e=[...this._jobPromises.values()].sort((r,e)=>(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"]["setcolor"] = {
	glsl: "varying mediump vec2 vTex;\nuniform lowp sampler2D samplerFront;\nuniform lowp vec3 setColor;\nvoid main(void)\n{\nlowp float a = texture2D(samplerFront, vTex).a;\ngl_FragColor = vec4(setColor.r * a, setColor.g * a, setColor.b * a, a);\n}",
	glslWebGL2: "",
	wgsl: "%%SAMPLERFRONT_BINDING%% var samplerFront : sampler;\n%%TEXTUREFRONT_BINDING%% var textureFront : texture_2d<f32>;\nstruct ShaderParams {\nsetColor : vec3<f32>\n};\n%%SHADERPARAMS_BINDING%% var<uniform> shaderParams : ShaderParams;\n%%FRAGMENTINPUT_STRUCT%%\n%%FRAGMENTOUTPUT_STRUCT%%\n@fragment\nfn main(input : FragmentInput) -> FragmentOutput\n{\nvar a : f32 = textureSample(textureFront, samplerFront, input.fragUV).a;\nvar output : FragmentOutput;\noutput.color = vec4<f32>(shaderParams.setColor * a, a);\nreturn output;\n}",
	blendsBackground: false,
	usesDepth: false,
	extendBoxHorizontal: 0,
	extendBoxVertical: 0,
	crossSampling: false,
	mustPreDraw: false,
	preservesOpaqueness: true,
	supports3dDirectRendering: false,
	animated: false,
	parameters: [["setColor",0,"color"]]
};

}

// 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 e<t?-1:e>t?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<e&&!l.IsStopped();++n)t.PushCopySol(i),l.SetIndex(n),a.Retrigger(r,o),t.PopSol(i);else for(let t=0;t<e&&!l.IsStopped();++t)l.SetIndex(t),a.Retrigger(r,o);return n.Pop(),u.Pop(),!1}*_DebugRepeat(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<e&&!l.IsStopped();++n)t.PushCopySol(i),l.SetIndex(n),yield*a.DebugRetrigger(r,o),t.PopSol(i);else for(let t=0;t<e&&!l.IsStopped();++t)l.SetIndex(t),yield*a.DebugRetrigger(r,o);return n.Pop(),u.Pop(),!1}_While(){const e=this._runtime.GetEventSheetManager(),t=e.GetEventStack(),n=t.GetCurrentStackFrame(),r=n.GetCurrentEvent(),a=r.GetSolModifiers(),i=n.IsSolModifierAfterCnds(),s=t.Push(r),o=e.GetLoopStack(),u=o.Push();if(i)for(let t=0;!u.IsStopped();++t)e.PushCopySol(a),u.SetIndex(t),r.Retrigger(n,s)||u.Stop(),e.PopSol(a);else for(let e=0;!u.IsStopped();++e)u.SetIndex(e),r.Retrigger(n,s)||u.Stop();return t.Pop(),o.Pop(),!1}*_DebugWhile(){const e=this._runtime.GetEventSheetManager(),t=e.GetEventStack(),n=t.GetCurrentStackFrame(),r=n.GetCurrentEvent(),a=r.GetSolModifiers(),i=n.IsSolModifierAfterCnds(),s=t.Push(r),o=e.GetLoopStack(),u=o.Push();if(i)for(let t=0;!u.IsStopped();++t){e.PushCopySol(a),u.SetIndex(t);(yield*r.DebugRetrigger(n,s))||u.Stop(),e.PopSol(a)}else for(let e=0;!u.IsStopped();++e){u.SetIndex(e);(yield*r.DebugRetrigger(n,s))||u.Stop()}return t.Pop(),o.Pop(),!1}_For(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<t)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);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<t)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);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<n&&!d.IsStopped();++e){a.PushCopySol(l);const n=p[e];t.GetCurrentSol().SetSinglePicked(n),S&&n.SetSiblingsSinglePicked(),d.SetIndex(e),o.Retrigger(s,h),a.PopSol(l)}else{n._SetSelectAll(!1);const t=n._GetOwnInstances();e.clearArray(t),t.push(null);for(let e=0,n=p.length;e<n&&!d.IsStopped();++e){const n=p[e];t[0]=n,S&&n.SetSiblingsSinglePicked(),d.SetIndex(e),o.Retrigger(s,h)}}return i.Pop(),g.Pop(),e.clearArray(p),u.Pop(),!1}*_DebugForEach(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<n&&!d.IsStopped();++e){a.PushCopySol(l);const n=p[e];t.GetCurrentSol().SetSinglePicked(n),S&&n.SetSiblingsSinglePicked(),d.SetIndex(e),yield*o.DebugRetrigger(s,h),a.PopSol(l)}else{n._SetSelectAll(!1);const t=n._GetOwnInstances();e.clearArray(t),t.push(null);for(let e=0,n=p.length;e<n&&!d.IsStopped();++e){const n=p[e];t[0]=n,S&&n.SetSiblingsSinglePicked(),d.SetIndex(e),yield*o.DebugRetrigger(s,h)}}return i.Pop(),g.Pop(),e.clearArray(p),u.Pop(),!1}_ForEachOrdered(t,n){const r=t.GetCurrentSol(),a=r.GetInstances();if(0===a.length)return!1;const i=this._runtime.GetEventSheetManager(),s=i.GetEventStack(),o=i.GetCurrentCondition(),l=s.GetCurrentStackFrame(),c=l.GetCurrentEvent(),h=c.GetSolModifiers(),g=l.IsSolModifierAfterCnds(),d=s.Push(c),S=i.GetLoopStack(),p=S.Push(),m=t.IsInContainer(),G=u.Push();e.clearArray(G),p.SetEnd(a.length);for(let e=0,t=a.length;e<t;++e)G.push([a[e],o.ReevaluateParameter(1,e)]);if(G.sort(ForEachOrdered_SortInstances),1===n&&G.reverse(),g)for(let e=0,n=G.length;e<n&&!p.IsStopped();++e){i.PushCopySol(h);const n=G[e][0];t.GetCurrentSol().SetSinglePicked(n),m&&n.SetSiblingsSinglePicked(),p.SetIndex(e),c.Retrigger(l,d),i.PopSol(h)}else{r._SetSelectAll(!1);const t=r._GetOwnInstances();e.clearArray(t),t.push(null);for(let e=0,n=G.length;e<n&&!p.IsStopped();++e){const n=G[e][0];t[0]=n,m&&n.SetSiblingsSinglePicked(),p.SetIndex(e),c.Retrigger(l,d)}}return s.Pop(),S.Pop(),e.clearArray(G),u.Pop(),!1}*_DebugForEachOrdered(t,n){const r=t.GetCurrentSol(),a=r.GetInstances();if(0===a.length)return!1;const i=this._runtime.GetEventSheetManager(),s=i.GetEventStack(),o=i.GetCurrentCondition(),l=s.GetCurrentStackFrame(),c=l.GetCurrentEvent(),h=c.GetSolModifiers(),g=l.IsSolModifierAfterCnds(),d=s.Push(c),S=i.GetLoopStack(),p=S.Push(),m=t.IsInContainer(),G=u.Push();e.clearArray(G),p.SetEnd(a.length);for(let e=0,t=a.length;e<t;++e)G.push([a[e],o.ReevaluateParameter(1,e)]);if(G.sort(ForEachOrdered_SortInstances),1===n&&G.reverse(),g)for(let e=0,n=G.length;e<n&&!p.IsStopped();++e){i.PushCopySol(h);const n=G[e][0];t.GetCurrentSol().SetSinglePicked(n),m&&n.SetSiblingsSinglePicked(),p.SetIndex(e),yield*c.DebugRetrigger(l,d),i.PopSol(h)}else{r._SetSelectAll(!1);const t=r._GetOwnInstances();e.clearArray(t),t.push(null);for(let e=0,n=G.length;e<n&&!p.IsStopped();++e){const n=G[e][0];t[0]=n,m&&n.SetSiblingsSinglePicked(),p.SetIndex(e),yield*c.DebugRetrigger(l,d)}}return s.Pop(),S.Pop(),e.clearArray(G),u.Pop(),!1}_GetFunctionMap(e,t){let n=this._functionMaps.get(e);return n||(t?(n={defaultFunc:null,strMap:new Map},this._functionMaps.set(e,n),n):null)}_DoCallMappedFunction(e,t,n,r,a){t.GetEventBlock().RunAsMappedFunctionCall(n,t.IsCopyPicked()),r&&e.PopSol(a)}*_DebugDoCallMappedFunction(e,t,n,r,a){yield*t.GetEventBlock().DebugRunAsMappedFunctionCall(n,t.IsCopyPicked()),r&&e.PopSol(a)}}}{const l=self.C3;l.Plugins.System.Type=class extends l.DefendedBase{constructor(e){super(),this._objectClass=e,this._runtime=e.GetRuntime(),this._plugin=e.GetPlugin()}OnCreate(){}Release(){this._objectClass=null,this._runtime=null,this._plugin=null}}}{const c=self.C3;c.Plugins.System.Instance=class extends c.DefendedBase{constructor(e,t){super(),this._inst=e,this._objectClass=this._inst.GetObjectClass(),this._sdkType=this._objectClass.GetSdkType(),this._runtime=this._inst.GetRuntime()}Release(){this._inst=null,this._objectClass=null,this._sdkType=null,this._runtime=null}}}{const h=self.C3,g=[];h.Plugins.System.Cnds={EveryTick:()=>!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):(r<n-.1&&t.set("Every_lastTime",r),!1)},IsGroupActive(e){const t=this._runtime.GetEventSheetManager().GetEventGroupByName(e);return t&&t.IsGroupActive()},IsPreview(){return this._runtime.IsPreview()},IsMobile:()=>h.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;e<a;++e){const a=i[e];i[u]=a,t=o.ReevaluateParameter(1,e),r=o.ReevaluateParameter(3,e),h.compare(t,n,r)?++u:s._PushElseInstance(a)}h.truncateArray(i,u),s.SetArrayPicked(i);const l=!!i.length;return h.clearArray(i),a.Pop(),e.ApplySolToContainer(),l},PickByEvaluate(e,t){if(!e)return!1;const n=this._GetForEachStack(),r=n.Push(),a=e.GetCurrentSol();h.shallowAssignArray(r,a.GetInstances()),a.IsSelectAll()&&h.clearArray(a._GetOwnElseInstances());const i=this._runtime.GetCurrentCondition();let s=0;for(let e=0,t=r.length;e<t;++e){const t=r[e];r[s]=t,i.ReevaluateParameter(1,e)?++s:a._PushElseInstance(t)}h.truncateArray(r,s),a.SetArrayPicked(r);const o=!!r.length;return h.clearArray(r),n.Pop(),e.ApplySolToContainer(),o},PickByHighestLowestValue(e,t,n,r){if(!e)return!1;const a=e.GetCurrentSol(),i=a.GetInstances();if(0===i.length)return!1;const s=this._runtime.GetCurrentCondition(),o=[];let u=0;for(let e=0,a=i.length;e<a;++e){const a=i[e];n=s.ReevaluateParameter(2,e),0===o.length||0===t&&n<u||1===t&&n>u?(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<a;++e){const a=g[e];h.xor(a.GetWorldInfo().ContainsPoint(t,n),s)?r._PushInstance(a):r._PushElseInstance(a)}return e.ApplySolToContainer(),h.xor(!!r._GetOwnInstances().length,s)},PickLastCreated(e){if(!e)return!1;const t=e.IsFamily();let n=null;const r=this._runtime._GetInstancesPendingCreate();for(let a=r.length-1;a>=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;e<i;++e){const i=n[e],u=i.GetWorldInfo();if(!u||u.IsDestroyed())continue;let l;l=s?i.GetInstanceVariableValue(t+i.GetObjectClass().GetFamilyInstanceVariableOffset(o)):i.GetInstanceVariableValue(t),r.push([u.GetLayer().GetIndex(),u.GetZIndex()]),a.push([i,l])}if(!r.length)return;r.sort(SortZOrderList),a.sort(SortInstancesByValue);let u=!1;for(let e=0,t=r.length;e<t;++e){const t=a[e][0],n=i.GetLayerByIndex(r[e][0]),s=r[e][1],o=n._GetInstances();o[s]!==t&&(o[s]=t,t.GetWorldInfo()._SetLayer(n,!0),n.SetZIndicesChanged(t),u=!0)}u&&this._runtime.UpdateRender(),d.clearArray(S),d.clearArray(p)},SetCollisionCellSize(e,t){e=Math.floor(e),t=Math.floor(t),e<=0||t<=0||!Number.isFinite(e)||!Number.isFinite(t)||this._runtime.GetCollisionEngine().SetCollisionCellSize(e,t)},GoToLayout(e){if(this._runtime.IsLoading())return;const t=this._runtime.GetLayoutManager();t.IsPendingChangeMainLayout()||t.ChangeMainLayout(e)},GoToLayoutByName(e){if(this._runtime.IsLoading())return;const t=this._runtime.GetLayoutManager();if(t.IsPendingChangeMainLayout())return;const n=t.GetLayoutByName(e);n&&t.ChangeMainLayout(n)},NextPrevLayout(e){if(this._runtime.IsLoading())return;const t=this._runtime.GetLayoutManager();if(t.IsPendingChangeMainLayout())return;const n=t.GetAllLayouts(),r=n.indexOf(t.GetMainRunningLayout());if(e&&0===r)return;if(!e&&r===n.length-1)return;const a=n[r+(e?-1:1)];t.ChangeMainLayout(a)},RestartLayout(){if(this._runtime.IsLoading())return;const e=this._runtime.GetLayoutManager();e.IsPendingChangeMainLayout()||(e.ChangeMainLayout(e.GetMainRunningLayout()),this._runtime.GetEventSheetManager().ResetAllGroupsInitialActivation())},SetLayoutScale(e){this._runtime.GetCurrentLayout().SetScale(+e)},SetLayoutAngle(e){this._runtime.GetCurrentLayout().SetAngle(d.toRadians(+e))},SetLayoutEffectEnabled(e,t){const n=this._runtime.GetCurrentLayout(),r=n.GetEffectList().GetEffectTypeByName(t);if(!r)return;const a=1===e;r.IsActive()!==a&&(r.SetActive(a),n.UpdateActiveEffects(),this._runtime.UpdateRender())},SetLayoutEffectParam(e,t,n){const r=this._runtime.GetCurrentLayout().GetEffectList(),a=r.GetEffectTypeByName(e);if(!a)return;t=Math.floor(t);const i=a.GetShaderProgram().GetParameterType(t);if(!i)return;"color"===i?(G.setFromRgbValue(n),n=G):"percent"===i&&(n/=100);r.SetEffectParameter(a.GetIndex(),t,n)&&a.IsActive()&&this._runtime.UpdateRender()},SetLayoutVanishingPoint(e,t){this._runtime.GetCurrentLayout().SetVanishingPointXY(e/100,t/100)},SetLayoutProjection(e){const t=this._runtime.GetCurrentLayout();0===e?t.SetPerspectiveProjection():t.SetOrthographicProjection()},SetLayoutSampling(e){this._runtime.GetCurrentLayout().SetSamplingMode(d.Gfx.RendererBase.SamplingNumberToMode(e))},ScrollX(e){this._runtime.GetCurrentLayout().SetScrollX(e)},ScrollY(e){this._runtime.GetCurrentLayout().SetScrollY(e)},Scroll(e,t){const n=this._runtime.GetCurrentLayout();n.SetScrollX(e),n.SetScrollY(t)},ScrollToObject(e){if(!e)return;const t=e.GetFirstPicked();if(!t)return;const n=t.GetWorldInfo();if(!n)return;const r=this._runtime.GetCurrentLayout();r.SetScrollX(n.GetX()),r.SetScrollY(n.GetY())},SetLayerVisible(e,t){e&&e.SetVisible(t)},SetLayerInteractive(e,t){e&&e.SetInteractive(t)},SetLayerHTML(e,t){e&&e.SetIsHTMLElementsLayer(t)},SetLayerOpacity(e,t){e&&e.SetOpacity(t/100)},SetLayerScale(e,t){e&&e.SetOwnScale(t)},SetLayerScaleRate(e,t){e&&e.SetScaleRate(t)},SetLayerAngle(e,t){e&&e.SetAngle(d.toRadians(+t))},SetLayerScroll(e,t,n){e&&(e.SetOwnScrollPositionEnabled(!0),e.SetScrollX(t),e.SetScrollY(n))},RestoreLayerScroll(e){e&&e.SetOwnScrollPositionEnabled(!1)},SetLayerParallax(e,t,n){e&&e.SetParallax(t/100,n/100)},SetLayerZElevation(e,t){e&&e.SetZElevation(+t)},SetLayerRenderingMode(e,t){e&&e.SetRenderAs3D(1===t)},SetLayerSampling(e,t){e&&e.SetSamplingMode(d.Gfx.RendererBase.SamplingNumberToMode(t))},SetLayerBackground(e,t){if(!e)return;G.setFromRgbValue(t),G.clamp();const n=e.GetBackgroundColor();n.equalsIgnoringAlpha(G)||(n.copyRgb(G),this.UpdateRender())},SetLayerTransparent(e,t){e&&e.SetTransparent(t)},SetLayerBlendMode(e,t){e&&e.SetBlendMode(t)},SetLayerEffectEnabled(e,t,n){if(!e)return;const r=e.GetEffectList().GetEffectTypeByName(n);if(!r)return;const a=1===t;r.IsActive()!==a&&(r.SetActive(a),e.UpdateActiveEffects(),this._runtime.UpdateRender())},SetLayerEffectParam(e,t,n,r){if(!e)return;const a=e.GetEffectList(),i=a.GetEffectTypeByName(t);if(!i)return;n=Math.floor(n);const s=i.GetShaderProgram().GetParameterType(n);if(!s)return;"color"===s?(G.setFromRgbValue(r),r=G):"percent"===s&&(r/=100);a.SetEffectParameter(i.GetIndex(),n,r)&&i.IsActive()&&this._runtime.UpdateRender()},SetLayerForceOwnTexture(e,t){e&&e.SetForceOwnTexture(t)},AddLayer(e,t,n){const r=this._runtime.GetCurrentLayout();try{r.AddLayer(e,t,n)}catch(e){console.warn("[Construct] Cannot add layer: ",e)}},MoveLayer(e,t,n){if(!e)return;const r=this._runtime.GetCurrentLayout();try{r.MoveLayer(e,t,n)}catch(e){console.warn("[Construct] Cannot move layer: ",e)}},RemoveLayer(e){if(!e)return;this._runtime.GetCurrentLayout().RemoveLayer(e)},RemoveAllDynamicLayers(){this._runtime.GetCurrentLayout().RemoveAllDynamicLayers()},async LoadObjectTextures(e){const t=this._runtime.GetMainRunningLayout();if(!t||!e||this._runtime.IsLoading())return;const n=e.IsFamily()?e.GetFamilyMembers():[e];await this._LoadTexturesForObjectClasses(t,n)},async LoadObjectTexturesByName(e){await d.Plugins.System.Acts.LoadObjectTextures.call(this,this._runtime.GetObjectClassByName(e))},UnloadObjectTextures(e){const t=this._runtime.GetMainRunningLayout();if(!t||!e)return;const n=e.IsFamily()?e.GetFamilyMembers():[e];this._UnloadTexturesForObjectClasses(t,n)},UnloadObjectTexturesByName(e){d.Plugins.System.Acts.UnloadObjectTextures.call(this,this._runtime.GetObjectClassByName(e))},UnloadUnusedTextures(){const e=this._runtime.GetMainRunningLayout();if(!e)return;this._runtime.FlushPendingInstances();const t=e._GetTextureLoadedObjectTypes();this._UnloadTexturesForObjectClasses(e,t),this._UnloadUnusedTextures(e,t)},async LoadLayoutTextures(e){const t=this._runtime.GetMainRunningLayout();e&&t&&!this._runtime.IsLoading()&&await this._LoadTexturesForObjectClasses(t,e._GetInitialObjectClasses())},async LoadLayoutTexturesByName(e){const t=this._runtime.GetMainRunningLayout(),n=this._runtime.GetLayoutManager().GetLayoutByName(e);n&&t&&!this._runtime.IsLoading()&&await this._LoadTexturesForObjectClasses(t,n._GetInitialObjectClasses())},SetFunctionReturnValue(e){const t=this._eventStack.GetCurrentExpFuncStackFrame();if(t)switch(t.GetFunctionReturnType()){case 1:"number"==typeof e&&t.SetFunctionReturnValue(e);break;case 2:"string"==typeof e&&t.SetFunctionReturnValue(e);break;case 3:t.SetFunctionReturnValue(e)}},MapFunction(e,t,n){const r=this._GetFunctionMap(e.toLowerCase(),!0),a=r.strMap,i=t.toLowerCase();a.has(i)&&console.warn(`[Construct] Function map '${e}' string '${t}' already in map; overwriting entry`);const s=d.first(a.values())||r.defaultFunc;if(s){if(0!==s.GetReturnType()!==(0!==n.GetReturnType()))return void console.error(`[Construct] Function map '${e}' string '${t}' function return type not compatible with other functions in the map; entry ignored`)}a.set(i,n)},MapFunctionDefault(e,t){const n=this._GetFunctionMap(e.toLowerCase(),!0);n.defaultFunc&&console.warn(`[Construct] Function map '${e}' already has a default; overwriting entry`);const r=d.first(n.strMap.values())||n.defaultFunc;if(r){if(0!==r.GetReturnType()!==(0!==t.GetReturnType()))return void console.error(`[Construct] Function map '${e}' default: function return type not compatible with other functions in the map; entry ignored`)}n.defaultFunc=t},CallMappedFunction(e,t,n){const r=this._runtime,a=r.IsDebugging()?y:null;n=Math.floor(n);const i=this._GetFunctionMap(e.toLowerCase(),!1);if(!i)return console.warn(`[Construct] Call mapped function: map name '${e}' not found; call ignored`),a;let s=i.strMap.get(t.toLowerCase());if(!s){if(!i.defaultFunc)return console.warn(`[Construct] Call mapped function: no function associated with map '${e}' string '${t}'; call ignored (consider setting a default)`),a;s=i.defaultFunc,n=0}if(!s.IsEnabled())return a;if(0!==s.GetReturnType())return console.warn(`[Construct] Call mapped function: map '${e}' string '${t}' has a return type so cannot be called`),a;const o=r.GetEventSheetManager(),u=o.GetCurrentEvent(),l=u.GetSolModifiersIncludingParents(),c=l.length>0;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;t<r;++t)h.push(e[t].GetValue())}const d=s.GetFunctionParameters();for(let e=h.length,t=d.length;e<t;++e)h.push(d[e].GetInitialValue());return r.IsDebugging()?this._DebugDoCallMappedFunction(o,s,h,c,l):this._DoCallMappedFunction(o,s,h,c,l)}}}{const f=self.C3,C=f.New(f.Color);f.Plugins.System.Exps={int:function(e){return"string"==typeof e&&(e=parseInt(e,10),isNaN(e)&&(e=0)),Math.floor(e)},float:function(e){return"string"==typeof e&&(e=parseFloat(e),isNaN(e)&&(e=0)),e},str:e=>e.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;n<r;++n){let r=e[n];"number"==typeof r&&(t<r&&(t=r))}return t},min(...e){let t=e[0];"number"!=typeof t&&(t=0);for(let n=1,r=e.length;n<r;++n){let r=e[n];"number"==typeof r&&(t>r&&(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)<<t,togglebit:(e,t)=>(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<r;++e)n=n.replaceAll(`{${e}}`,t[e].toString());return n},regexsearch(e,t,n){const r=this.GetRegex(t,n);return e?e.search(r):-1},regexreplace(e,t,n,r){const a=this.GetRegex(t,n);return e?e.replace(a,r):""},regexmatchcount(e,t,n){const r=this.GetRegexMatches(e.toString(),t,n);return r?r.length:0},regexmatchat(e,t,n,r){r=Math.floor(r);const a=this.GetRegexMatches(e.toString(),t,n);return!a||r<0||r>=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;e<t;++e)n.push(c[e].GetInitialValue());const h=a.GetEventBlock(),g=h.RunAsExpressionOrJSFunctionCall(h.GetSolModifiersIncludingParents(),a.IsCopyPicked(),i,s,null,...n);return l&&o.PopSol(u),g},loadingprogress(){return this._runtime.GetAssetManager().GetLoadProgress()},imageloadingprogress(){return this.GetImageLoadingProgress()},renderer(){return this._runtime.GetWebGPURenderer()?"webgpu":"webgl"},rendererdetail(){return this._runtime.GetWebGPURenderer()?this._runtime.GetWebGPURenderer().GetAdapterInfoString():this._runtime.GetWebGLRenderer().GetUnmaskedRenderer()},imagememoryusage(){let e=this._runtime.GetRenderer().GetEstimatedTextureMemoryUsage();return Math.round(100*e/1048576)/100},rgb:(e,t,n)=>f.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/Arr/c3runtime/runtime.js
{
{const t=self.C3;t.Plugins.Arr=class extends t.SDKPluginBase{constructor(t){super(t)}Release(){super.Release()}}}{const e=self.C3;e.Plugins.Arr.Type=class extends e.SDKTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}}}{const r=self.C3,s=self.C3X,i=self.IInstance;function ResizeArray(t,e,s){if(e<t.length)r.truncateArray(t,e);else if(e>t.length)if("function"==typeof s)for(let r=t.length;r<e;++r)t.push(s());else for(let r=t.length;r<e;++r)t.push(s)}r.Plugins.Arr.Instance=class extends r.SDKInstanceBase{constructor(t,e){super(t),this._cx=10,this._cy=1,this._cz=1,this._arr=null,this._forX=[],this._forY=[],this._forZ=[],this._forDepth=-1,e&&(this._cx=e[0],this._cy=e[1],this._cz=e[2]),this._arr=r.MakeFilledArray(this._cx,()=>r.MakeFilledArray(this._cy,()=>r.MakeFilledArray(this._cz,0)))}Release(){this._arr=null,super.Release()}At(t,e,r){return t=Math.floor(t),e=Math.floor(e),r=Math.floor(r),t>=0&&t<this._cx&&e>=0&&e<this._cy&&r>=0&&r<this._cz?this._arr[t][e][r]:0}Set(t,e,r,s){t=Math.floor(t),e=Math.floor(e),r=Math.floor(r),t>=0&&t<this._cx&&e>=0&&e<this._cy&&r>=0&&r<this._cz&&(this._arr[t][e][r]=s)}SetSize(t,e,s){if(t=Math.floor(t),e=Math.floor(e),s=Math.floor(s),t<0&&(t=0),e<0&&(e=0),s<0&&(s=0),this._cx===t&&this._cy===e&&this._cz===s)return;this._cx=t,this._cy=e,this._cz=s;const i=this._arr;ResizeArray(i,t,()=>r.MakeFilledArray(e,()=>r.MakeFilledArray(s,0)));for(let h=0;h<t;++h){ResizeArray(i[h],e,()=>r.MakeFilledArray(s,0));for(let t=0;t<e;++t)ResizeArray(i[h][t],s,0)}}GetWidth(){return this._cx}GetHeight(){return this._cy}GetDepth(){return this._cz}_ShuffleHelper(t,e,r,s,i){for(;e>0;){const h=Math.floor(this._runtime.Random()*e);if(--e,0===t){const t=this.At(e,s,i),r=this.At(h,s,i);this.Set(e,s,i,r),this.Set(h,s,i,t)}else if(1===t){const t=this.At(r,e,i),s=this.At(r,h,i);this.Set(r,e,i,s),this.Set(r,h,i,t)}else if(2===t){const t=this.At(r,s,e),i=this.At(r,s,h);this.Set(r,s,e,i),this.Set(r,s,h,t)}}}GetDebuggerProperties(){const t="plugins.arr.debugger",e="plugins.arr.properties",r=[{title:t+".array-properties.title",properties:[{name:e+".width.name",value:this._cx,onedit:t=>this.SetSize(t,this._cy,this._cz)},{name:e+".height.name",value:this._cy,onedit:t=>this.SetSize(this._cx,t,this._cz)},{name:e+".depth.name",value:this._cz,onedit:t=>this.SetSize(this._cx,this._cy,t)},{name:e+".elements.name",value:this._cx*this._cy*this._cz}]}],s=[];if(1===this._cy&&1===this._cz)for(let t=0;t<this._cx;++t)s.push({name:"$"+t,value:this._arr[t][0][0],onedit:e=>this._arr[t][0][0]=e});else for(let t=0;t<this._cx;++t)s.push({name:"$"+t,value:this._arr[t].toString()});return s.length&&r.push({title:t+".array-data.title",properties:s}),r}GetAsJsonString(){return JSON.stringify({"c2array":!0,"size":[this._cx,this._cy,this._cz],"data":this._arr})}SaveToJson(){return{"size":[this._cx,this._cy,this._cz],"data":this._arr}}LoadFromJson(t){const e=t["size"];this._cx=e[0],this._cy=e[1],this._cz=e[2],this._arr=t["data"]}_GetForX(){return this._forDepth>=0&&this._forDepth<this._forX.length?this._forX[this._forDepth]:0}_GetForY(){return this._forDepth>=0&&this._forDepth<this._forY.length?this._forY[this._forDepth]:0}_GetForZ(){return this._forDepth>=0&&this._forDepth<this._forZ.length?this._forZ[this._forDepth]:0}GetScriptInterfaceClass(){return self.IArrayInstance}};const h=new WeakMap;self.IArrayInstance=class extends i{constructor(){super(),h.set(this,i._GetInitInst().GetSdkInstance())}get width(){return h.get(this).GetWidth()}get height(){return h.get(this).GetHeight()}get depth(){return h.get(this).GetDepth()}setSize(t,e=1,r=1){s.RequireFiniteNumber(t),s.RequireFiniteNumber(e),s.RequireFiniteNumber(r),h.get(this).SetSize(t,e,r)}getAt(t,e=0,r=0){return s.RequireFiniteNumber(t),s.RequireFiniteNumber(e),s.RequireFiniteNumber(r),h.get(this).At(t,e,r)}setAt(t,e,r=0,i=0){if(s.RequireFiniteNumber(e),s.RequireFiniteNumber(r),s.RequireFiniteNumber(i),"number"!=typeof t&&"string"!=typeof t)throw new TypeError("invalid type");h.get(this).Set(e,r,i,t)}}}{const o=self.C3;function DoForEachTrigger(t,e,r,s,i,h){t.PushCopySol(r);h.GetObjectClass().GetCurrentSol().PickOne(h.GetInstance()),e.Retrigger(s,i),t.PopSol(r)}o.Plugins.Arr.Cnds={CompareX(t,e,r){return o.compare(this.At(t,0,0),e,r)},CompareXY(t,e,r,s){return o.compare(this.At(t,e,0),r,s)},CompareXYZ(t,e,r,s,i){return o.compare(this.At(t,e,r),s,i)},ArrForEach(t){const e=this._runtime,r=e.GetEventSheetManager(),s=e.GetCurrentEvent(),i=s.GetSolModifiers(),h=e.GetEventStack(),o=h.GetCurrentStackFrame(),n=h.Push(s),l=++this._forDepth,c=this._forX,a=this._forY,f=this._forZ,_=this._cx,u=this._cy,p=this._cz;if(l===this._forX.length?(c.push(0),a.push(0),f.push(0)):(c[l]=0,a[l]=0,f[l]=0),e.SetDebuggingEnabled(!1),0===t)for(let t=0;t<_;++t)for(let e=0;e<u;++e)for(let h=0;h<p;++h)c[l]=t,a[l]=e,f[l]=h,DoForEachTrigger(r,s,i,o,n,this);else if(1===t)for(let t=0;t<_;++t)for(let e=0;e<u;++e)c[l]=t,a[l]=e,DoForEachTrigger(r,s,i,o,n,this);else for(let t=0;t<_;++t)c[l]=t,DoForEachTrigger(r,s,i,o,n,this);return e.SetDebuggingEnabled(!0),this._forDepth--,h.Pop(),!1},CompareCurrent(t,e){return o.compare(this.At(this._GetForX(),this._GetForY(),this._GetForZ()),t,e)},Contains(t){const e=this._cx,r=this._cy,s=this._cz,i=this._arr;for(let h=0;h<e;++h)for(let e=0;e<r;++e)for(let r=0;r<s;++r)if(i[h][e][r]===t)return!0;return!1},IsEmpty(){return 0===this._cx||0===this._cy||0===this._cz},CompareSize(t,e,r){let s=0;switch(t){case 0:s=this._cx;break;case 1:s=this._cy;break;case 2:s=this._cz}return o.compare(s,e,r)}}}{const n=self.C3;function CompareValues(t,e){if("number"==typeof t&&"number"==typeof e)return t-e;{const r=t.toString(),s=e.toString();return r<s?-1:r>s?1:0}}n.Plugins.Arr.Acts={Clear(t){const e=this._cx,r=this._cy,s=this._cz,i=this._arr;for(let h=0;h<e;++h)for(let e=0;e<r;++e)for(let r=0;r<s;++r)i[h][e][r]=t},SetSize(t,e,r){this.SetSize(t,e,r)},SetX(t,e){this.Set(t,0,0,e)},SetXY(t,e,r){this.Set(t,e,0,r)},SetXYZ(t,e,r,s){this.Set(t,e,r,s)},Push(t,e,r){const s=this._cx,i=this._cy,h=this._cz,o=this._arr;if(0===r){const r=n.MakeFilledArray(i,()=>n.MakeFilledArray(h,e));0===t?o.push(r):o.unshift(r),this._cx++}else if(1===r){for(let r=0;r<s;++r){const s=n.MakeFilledArray(h,e);0===t?o[r].push(s):o[r].unshift(s)}this._cy++}else{for(let r=0;r<s;++r)for(let s=0;s<i;++s)0===t?o[r][s].push(e):o[r][s].unshift(e);this._cz++}},Pop(t,e){const r=this._cx,s=this._cy,i=this._cz,h=this._arr;if(0===e){if(0===r)return;0===t?h.pop():h.shift(),this._cx--}else if(1===e){if(0===s)return;for(let e=0;e<r;++e)0===t?h[e].pop():h[e].shift();this._cy--}else{if(0===i)return;for(let e=0;e<r;++e)for(let r=0;r<s;++r)0===t?h[e][r].pop():h[e][r].shift();this._cz--}},Reverse(t){const e=this._cx,r=this._cy,s=this._cz,i=this._arr;if(0!==e&&0!==r&&0!==s)if(0===t)i.reverse();else if(1===t)for(let t=0;t<e;++t)i[t].reverse();else for(let t=0;t<e;++t)for(let e=0;e<r;++e)i[t][e].reverse()},Sort(t){const e=this._cx,r=this._cy,s=this._cz,i=this._arr;if(0!==e&&0!==r&&0!==s)if(0===t)i.sort((t,e)=>CompareValues(t[0][0],e[0][0]));else if(1===t)for(let t=0;t<e;++t)i[t].sort((t,e)=>CompareValues(t[0],e[0]));else for(let t=0;t<e;++t)for(let e=0;e<r;++e)i[t][e].sort(CompareValues)},Sort2(t){const e=this._cx,r=this._cy,s=this._cz,i=this._arr;if(0!==e&&0!==r&&0!==s)if(0===t)i.sort((t,e)=>{for(let s=0;s<r;++s){const r=CompareValues(t[s][0],e[s][0]);if(0!==r)return r}return 0});else if(1===t)for(let t=0;t<r;++t){const r=[];for(let s=0;s<e;++s)r.push(i[s][t]);r.sort((t,e)=>CompareValues(t[0],e[0]));for(let s=0;s<e;++s)i[s][t]=r[s]}else if(2===t){const t=[];for(let e=0;e<r;++e)t.push(e);t.sort((t,r)=>{for(let s=0;s<e;++s){const e=CompareValues(i[s][t],i[s][r]);if(0!==e)return e}return 0});for(let r=0;r<e;++r){let e=[];for(const s of t)e.push(i[r][s]);i[r]=e}}else if(3===t)for(let t=0;t<e;++t)i[t].sort((t,e)=>CompareValues(t[0],e[0]));else for(let t=0;t<e;++t)for(let e=0;e<r;++e)i[t][e].sort(CompareValues)},Shuffle(t){const e=this._cx,r=this._cy,s=this._cz;if(0!==e&&0!==r&&0!==s)if(0===t)for(let i=0;i<r;++i)for(let r=0;r<s;++r)this._ShuffleHelper(t,e,0,i,r);else if(1===t)for(let i=0;i<e;++i)for(let e=0;e<s;++e)this._ShuffleHelper(t,r,i,0,e);else for(let i=0;i<e;++i)for(let e=0;e<r;++e)this._ShuffleHelper(t,s,i,e,0)},Delete(t,e){if((t=Math.floor(t))<0)return;const r=this._cx,s=this._cy,i=this._cz,h=this._arr;if(0===e){if(t>=r)return;h.splice(t,1),this._cx--}else if(1===e){if(t>=s)return;for(let e=0;e<r;++e)h[e].splice(t,1);this._cy--}else{if(t>=i)return;for(let e=0;e<r;++e)for(let r=0;r<s;++r)h[e][r].splice(t,1);this._cz--}},Insert(t,e,r){if((e=Math.floor(e))<0)return;const s=this._cx,i=this._cy,h=this._cz,o=this._arr;if(0===r){if(e>s)return;o.splice(e,0,n.MakeFilledArray(i,()=>n.MakeFilledArray(h,t))),this._cx++}else if(1===r){if(e>i)return;for(let r=0;r<s;++r)o[r].splice(e,0,n.MakeFilledArray(h,t));this._cy++}else{if(e>h)return;for(let r=0;r<s;++r)for(let s=0;s<i;++s)o[r][s].splice(e,0,t);this._cz++}},SplitString(t,e,r){const s=t.split(e);this.SetSize(s.length,1,1);for(let t=0,e=s.length;t<e;++t){let e=s[t];0===r?String(Number(e))===e&&(e=Number(e)):2===r&&(e=Number(e)),this.Set(t,0,0,e)}},JSONLoad(t){let e=null;try{e=JSON.parse(t)}catch(t){return void console.error("[Construct] Failed to parse JSON: ",t)}if(!e["c2array"])return void console.warn("[Array] Attempted to load JSON that does not appear to be Construct array data - no data loaded");const r=e["size"];this._cx=r[0],this._cy=r[1],this._cz=r[2],this._arr=e["data"]},JSONDownload(t){const e=URL.createObjectURL(new Blob([this.GetAsJsonString()],{type:"application/json"}));this._runtime.InvokeDownload(e,t)}}}self.C3.Plugins.Arr.Exps={At(t,e,r){return this.At(t,e||0,r||0)},Width(){return this._cx},Height(){return this._cy},Depth(){return this._cz},CurX(){return this._GetForX()},CurY(){return this._GetForY()},CurZ(){return this._GetForZ()},CurValue(){return this.At(this._GetForX(),this._GetForY(),this._GetForZ())},Front(){return this.At(0,0,0)},Back(){return this.At(this._cx-1,0,0)},IndexOf(t){const e=this._arr;for(let r=0,s=this._cx;r<s;++r)if(e[r][0][0]===t)return r;return-1},LastIndexOf(t){const e=this._arr;for(let r=this._cx-1;r>=0;--r)if(e[r][0][0]===t)return r;return-1},JoinString(t){let e=[];for(let t=0;t<this._cx;++t)e.push(this.At(t,0,0));return e.join(t)},AsJSON(){return this.GetAsJsonString()}};
}

// scripts/plugins/Dictionary/c3runtime/runtime.js
{
{const t=self.C3;t.Plugins.Dictionary=class extends t.SDKPluginBase{constructor(t){super(t)}Release(){super.Release()}}}{const t=self.C3;t.Plugins.Dictionary.Type=class extends t.SDKTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}}}{const t=self.C3,e=(self.C3X,self.IInstance);t.Plugins.Dictionary.Instance=class extends t.SDKInstanceBase{constructor(t,e){super(t),this._data=new Map,this._curKey=""}Release(){this._data.clear(),super.Release()}GetAsJsonString(){return JSON.stringify({"c2dictionary":!0,"data":t.MapToObject(this._data)})}GetDataMap(){return this._data}SaveToJson(){return t.MapToObject(this._data)}LoadFromJson(e){t.ObjectToMap(e,this._data)}GetDebuggerProperties(){const t="plugins.dictionary";return[{title:t+".name",properties:[{name:t+".debugger.key-count",value:this._data.size},...[...this._data].map(t=>({name:"$"+t[0],value:t[1],onedit:e=>this._data.set(t[0],e)}))]}]}GetScriptInterfaceClass(){return self.IDictionaryInstance}};const a=new WeakMap;self.IDictionaryInstance=class extends e{constructor(){super(),a.set(this,e._GetInitInst().GetSdkInstance())}getDataMap(){return a.get(this).GetDataMap()}}}{const t=self.C3;t.Plugins.Dictionary.Cnds={CompareValue(e,a,s){const n=this._data.get(e);return void 0!==n&&t.compare(n,a,s)},ForEachKey(){const t=this._runtime,e=t.GetEventSheetManager(),a=t.GetCurrentEvent(),s=a.GetSolModifiers(),n=t.GetEventStack(),r=n.GetCurrentStackFrame(),i=n.Push(a);t.SetDebuggingEnabled(!1);for(const t of this._data.keys()){this._curKey=t,e.PushCopySol(s);this.GetObjectClass().GetCurrentSol().PickOne(this.GetInstance()),a.Retrigger(r,i),e.PopSol(s)}return t.SetDebuggingEnabled(!0),this._curKey="",n.Pop(),!1},CompareCurrentValue(e,a){const s=this._data.get(this._curKey);return void 0!==s&&t.compare(s,e,a)},HasKey(t){return this._data.has(t)},IsEmpty(){return 0===this._data.size}}}{const t=self.C3;t.Plugins.Dictionary.Acts={AddKey(t,e){this._data.set(t,e)},SetKey(t,e){this._data.has(t)&&this._data.set(t,e)},DeleteKey(t){this._data.delete(t)},Clear(){this._data.clear()},JSONLoad(e){let a=null;try{a=JSON.parse(e)}catch(t){return void console.error("[Construct] Error parsing JSON: ",t)}a["c2dictionary"]?t.ObjectToMap(a["data"],this._data):console.warn("[Dictionary] Attempted to load JSON that does not appear to be Construct dictionary data - no data loaded")},JSONDownload(t){const e=URL.createObjectURL(new Blob([this.GetAsJsonString()],{type:"application/json"}));this._runtime.InvokeDownload(e,t)}}}self.C3.Plugins.Dictionary.Exps={Get(t){const e=this._data.get(t);return void 0===e?0:e},GetDefault(t,e){const a=this._data.get(t);return void 0===a?e:a},KeyCount(){return this._data.size},CurrentKey(){return this._curKey},CurrentValue(){return this._data.get(this._curKey)??0},AsJSON(){return this.GetAsJsonString()}};
}

// scripts/plugins/AJAX/c3runtime/runtime.js
{
{const e=self.C3;e.Plugins.AJAX=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Plugins.AJAX.Type=class extends e.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3;e.Plugins.AJAX.Instance=class extends e.SDKInstanceBase{constructor(e,t){super(e),this._lastData="",this._lastStatusCode=0,this._curTag="",this._progress=0,this._timeout=-1,this._nextRequestHeaders=new Map,this._nextReponseBinaryData=null,this._nextRequestOverrideMimeType="",this._nextRequestWithCredentials=!1,this._isUploadProgressEnabled=!0}Release(){super.Release()}async _TriggerError(t,s,r){console.error(`[Construct] AJAX request to '${s}' (tag '${t}') failed: `,r),this._curTag=t,await this.TriggerAsync(e.Plugins.AJAX.Cnds.OnAnyError),this._curTag=t,await this.TriggerAsync(e.Plugins.AJAX.Cnds.OnError)}async _TriggerComplete(t){this._curTag=t,await this.TriggerAsync(e.Plugins.AJAX.Cnds.OnAnyComplete),this._curTag=t,await this.TriggerAsync(e.Plugins.AJAX.Cnds.OnComplete)}async _OnProgress(t,s){s["lengthComputable"]&&(this._progress=s["loaded"]/s["total"],this._curTag=t,await this.TriggerAsync(e.Plugins.AJAX.Cnds.OnProgress))}async _OnUploadProgress(t,s){s["lengthComputable"]&&(this._progress=s["loaded"]/s["total"],this._curTag=t,await this.TriggerAsync(e.Plugins.AJAX.Cnds.OnUploadProgress))}_OnError(e,t,s){this._TriggerError(e,t,s)}_DoRequest(e,t,s,r){return new Promise(a=>{const n=s=>{this._OnError(e,t,s),a()},i=this._nextReponseBinaryData;this._nextReponseBinaryData=null;try{const o=new XMLHttpRequest;o.onreadystatechange=()=>{if(4===o.readyState){if(this._lastData=i?"":(o.responseText||"").replace(/\r\n/g,"\n"),this._lastStatusCode=o.status,o.status>=400)this._TriggerError(e,t,o.status+o.statusText);else{const t=this._lastData.length||i&&o.response instanceof ArrayBuffer;(0!==o.status||t)&&(i&&i.SetArrayBufferTransfer(o.response),this._TriggerComplete(e))}a()}},o.onerror=n,o.ontimeout=n,o.onabort=n,o["onprogress"]=t=>this._OnProgress(e,t),this._isUploadProgressEnabled&&(o["upload"]["onprogress"]=t=>this._OnUploadProgress(e,t)),o.open(s,t),this._timeout>=0&&void 0!==o["timeout"]&&(o["timeout"]=this._timeout),o.responseType=i?"arraybuffer":"text",r&&!this._nextRequestHeaders.has("Content-Type")&&("string"!=typeof r?o["setRequestHeader"]("Content-Type","application/octet-stream"):o["setRequestHeader"]("Content-Type","application/x-www-form-urlencoded"));for(const[e,t]of this._nextRequestHeaders)try{o["setRequestHeader"](e,t)}catch(s){console.error(`[Construct] AJAX: Failed to set header '${e}: ${t}': `,s)}if(this._nextRequestHeaders.clear(),this._nextRequestOverrideMimeType){try{o["overrideMimeType"](this._nextRequestOverrideMimeType)}catch(e){console.error("[Construct] AJAX: failed to override MIME type: ",e)}this._nextRequestOverrideMimeType=""}this._nextRequestWithCredentials&&(o.withCredentials=!0,this._nextRequestWithCredentials=!1),r?o.send(r):o.send()}catch(e){n(e)}})}GetDebuggerProperties(){const e="plugins.ajax.debugger";return[{title:e+".title",properties:[{name:e+".last-status-code",value:this._lastStatusCode},{name:e+".last-data",value:this._lastData}]}]}SaveToJson(){return{"lastData":this._lastData,"lastStatusCode":this._lastStatusCode}}LoadFromJson(e){this._lastData=e["lastData"],this._lastStatusCode=e.hasOwnProperty("lastStatusCode")?e["lastStatusCode"]:0,this._curTag="",this._progress=0}}}{const e=self.C3;e.Plugins.AJAX.Cnds={OnComplete(t){return e.equalsNoCase(this._curTag,t)},OnAnyComplete:()=>!0,OnError(t){return e.equalsNoCase(this._curTag,t)},OnAnyError:()=>!0,OnProgress(t){return e.equalsNoCase(this._curTag,t)},OnUploadProgress(t){return e.equalsNoCase(this._curTag,t)}}}self.C3.Plugins.AJAX.Acts={async Request(e,t){await this._DoRequest(e,t,"GET",null)},async RequestFile(e,t){await this._DoRequest(e,t,"GET",null)},async Post(e,t,s,r){await this._DoRequest(e,t,r,s)},async PostBinary(e,t,s,r){if(!s)return;const a=s.GetFirstPicked(this._inst);if(!a)return;const n=a.GetSdkInstance().GetArrayBufferReadOnly();await this._DoRequest(e,t,r,n)},SetTimeout(e){this._timeout=1e3*e},SetHeader(e,t){this._nextRequestHeaders.set(e,t)},SetResponseBinary(e){if(!e)return;const t=e.GetFirstPicked(this._inst);t&&(this._nextReponseBinaryData=t.GetSdkInstance())},OverrideMIMEType(e){this._nextRequestOverrideMimeType=e},SetWithCredentials(e){this._nextRequestWithCredentials=!!e},SetUploadProgressEnabled(e){this._isUploadProgressEnabled=!!e}};self.C3.Plugins.AJAX.Exps={LastData(){return this._lastData},LastStatusCode(){return this._lastStatusCode},Progress(){return this._progress},Tag(){return this._curTag}};
}

// 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<this._runtime.GetCanvasCssWidth()&&e<this._runtime.GetCanvasCssHeight()}GetDebuggerProperties(){return[{title:"plugins.touch.debugger.touches",properties:[...this._touches.values()].map(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/Mouse/c3runtime/runtime.js
{
{const e=self.C3;e.Plugins.Mouse=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const t=self.C3,s=self.C3X;t.Plugins.Mouse.Type=class extends t.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}GetScriptInterfaceClass(){return self.IMouseObjectType}};let n=null;function GetMouseSdkInstance(){return n.GetSingleGlobalInstance().GetSdkInstance()}self.IMouseObjectType=class extends self.IObjectType{constructor(e){super(e),n=e,e.GetRuntime()._GetCommonScriptInterfaces().mouse=this}getMouseX(e){return GetMouseSdkInstance().GetMousePositionForLayer(e)[0]}getMouseY(e){return GetMouseSdkInstance().GetMousePositionForLayer(e)[1]}getMousePosition(e){return GetMouseSdkInstance().GetMousePositionForLayer(e)}isMouseButtonDown(e){return GetMouseSdkInstance().IsMouseButtonDown(e)}setCursorStyle(e){s.RequireString(e),GetMouseSdkInstance().SetCursorStyle(e)}setCursorObjectClass(e){const t=GetMouseSdkInstance(),s=t.GetRuntime()._UnwrapIObjectClass(e);t.SetCursorObjectClass(s)}get hasPointerLock(){return GetMouseSdkInstance()._HasPointerLock()}requestPointerLock(e){GetMouseSdkInstance()._RequestPointerLock(e?.unadjustedMovement)}releasePointerLock(){GetMouseSdkInstance()._ReleasePointerLock()}}}{const o=self.C3,i="mouse";let r=null;o.Plugins.Mouse.Instance=class extends o.SDKInstanceBase{#e=!1;#t=!1;#s=!1;#n=0;#o=0;constructor(e,t){super(e,i),this._buttonMap=[!1,!1,!1,!1,!1],this._mouseXcanvas=0,this._mouseYcanvas=0,this._triggerButton=0,this._triggerType=0,this._triggerDir=0,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this.#s=this._runtime.IsWindowsWebView2()||"macos-wkwebview"===this._runtime.GetExportType()||"linux-cef"===this._runtime.GetExportType(),this.AddDOMMessageHandlers([["pointer-lock-change",e=>this._OnPointerLockChange(e)],["pointer-lock-error",e=>this._OnPointerLockError(e)],["wrapper-pointer-lock-movement",e=>this.#i(e)]]);const s=this.GetRuntime().Dispatcher();this._disposables=new o.CompositeDisposable(o.Disposable.From(s,"pointermove",e=>this._OnPointerMove(e.data)),o.Disposable.From(s,"pointerdown",e=>this._OnPointerDown(e.data)),o.Disposable.From(s,"pointerup",e=>this._OnPointerUp(e.data)),o.Disposable.From(s,"dblclick",e=>this._OnDoubleClick(e.data)),o.Disposable.From(s,"wheel",e=>this._OnMouseWheel(e.data)),o.Disposable.From(s,"window-blur",()=>this._OnWindowBlur())),this._runtime.AddLoadPromise(this.PostToDOMAsync("init",{"isPointerLockWrapperPolyfill":this.#s}))}Release(){super.Release()}_OnPointerDown(e){"mouse"===e["pointerType"]&&(this._mouseXcanvas=e["pageX"]-this._runtime.GetCanvasClientX(),this._mouseYcanvas=e["pageY"]-this._runtime.GetCanvasClientY(),this._CheckButtonChanges(e["lastButtons"],e["buttons"]))}#r(e,t){this.GetSdkType().DispatchScriptEvent("movement",!1,{movementX:e,movementY:t}),this.#n=e,this.#o=t,this.Trigger(o.Plugins.Mouse.Cnds.OnMovement),this.#n=0,this.#o=0}_OnPointerMove(e){this.#s&&(this.#e||this.#t)||this.#r(e["movementX"],e["movementY"]),"mouse"===e["pointerType"]&&(this._mouseXcanvas=e["pageX"]-this._runtime.GetCanvasClientX(),this._mouseYcanvas=e["pageY"]-this._runtime.GetCanvasClientY(),this._CheckButtonChanges(e["lastButtons"],e["buttons"]))}_OnPointerUp(e){"mouse"===e["pointerType"]&&this._CheckButtonChanges(e["lastButtons"],e["buttons"])}_CheckButtonChanges(e,t){this._CheckButtonChange(e,t,1,0),this._CheckButtonChange(e,t,4,1),this._CheckButtonChange(e,t,2,2),this._CheckButtonChange(e,t,8,3),this._CheckButtonChange(e,t,16,4)}_CheckButtonChange(e,t,s,n){!(e&s)&&t&s?this._OnMouseDown(n):e&s&&!(t&s)&&this._OnMouseUp(n)}_OnMouseDown(e){this._buttonMap[e]=!0,this.Trigger(o.Plugins.Mouse.Cnds.OnAnyClick),this._triggerButton=e,this._triggerType=0,this.Trigger(o.Plugins.Mouse.Cnds.OnClick),this.Trigger(o.Plugins.Mouse.Cnds.OnObjectClicked)}_OnMouseUp(e){this._buttonMap[e]&&(this._buttonMap[e]=!1,this._triggerButton=e,this.Trigger(o.Plugins.Mouse.Cnds.OnRelease))}_OnDoubleClick(e){this._triggerButton=e["button"],this._triggerType=1,this.Trigger(o.Plugins.Mouse.Cnds.OnClick),this.Trigger(o.Plugins.Mouse.Cnds.OnObjectClicked)}_OnMouseWheel(e){this._triggerDir=e["deltaY"]<0?1:0,this._wheelDeltaX=e["deltaX"],this._wheelDeltaY=e["deltaY"],this._wheelDeltaZ=e["deltaZ"],this.Trigger(o.Plugins.Mouse.Cnds.OnWheel)}_OnWindowBlur(){for(let e=0,t=this._buttonMap.length;e<t;++e){if(!this._buttonMap[e])return;this._buttonMap[e]=!1,this._triggerButton=e,this.Trigger(o.Plugins.Mouse.Cnds.OnRelease)}}GetMousePositionForLayer(e){const t=this._runtime.GetMainRunningLayout(),s=this._mouseXcanvas,n=this._mouseYcanvas;if(void 0===e){return t.GetLayerByIndex(0).CanvasCssToLayer_DefaultTransform(s,n)}{const o=t.GetLayer(e);return o?o.CanvasCssToLayer(s,n):[0,0]}}IsMouseButtonDown(e){return e=Math.floor(e),!!this._buttonMap[e]}_IsMouseOverCanvas(){return this._mouseXcanvas>=0&&this._mouseYcanvas>=0&&this._mouseXcanvas<this._runtime.GetCanvasCssWidth()&&this._mouseYcanvas<this._runtime.GetCanvasCssHeight()}SetCursorStyle(e){r!==e&&(r=e,this.PostToDOM("cursor",e))}async SetCursorObjectClass(e){if(o.Platform.IsMobile||!e)return;const t=e.GetFirstPicked();if(!t)return;const s=t.GetWorldInfo(),n=t.GetCurrentImageInfo();if(!s||!n)return;if(r===n)return;r=n;const i=`url(${await n.ExtractImageToBlobURL()}) ${Math.round(s.GetOriginX()*n.GetWidth())} ${Math.round(s.GetOriginY()*n.GetHeight())}, auto`;this.PostToDOM("cursor",i)}_RequestPointerLock(e){this.#e||this.#t||(this.#t=!0,this._PostToDOMMaybeSync("request-pointer-lock",{"unadjustedMovement":e}))}_ReleasePointerLock(){this.#e&&(this.#t=!1,this.PostToDOM("release-pointer-lock"))}_GetMovementX(){return this.#n}_GetMovementY(){return this.#o}_OnPointerLockChange(e){this._UpdatePointerLockState(e["hasPointerLock"])}_OnPointerLockError(e){this._UpdatePointerLockState(e["hasPointerLock"]),this.GetSdkType().DispatchScriptEvent("pointerlockerror"),this.Trigger(o.Plugins.Mouse.Cnds.OnPointerLockError)}_UpdatePointerLockState(e){this.#t=!1,this.#e!==e&&(this.#e=e,this.GetSdkType().DispatchScriptEvent("pointerlockchange",!1,{hasPointerLock:e}),this.#e?this.Trigger(o.Plugins.Mouse.Cnds.OnPointerLocked):this.Trigger(o.Plugins.Mouse.Cnds.OnPointerUnlocked))}_HasPointerLock(){return this.#e}#i(e){this.#r(e["movementX"],e["movementY"])}GetDebuggerProperties(){const e="plugins.mouse";return[{title:e+".name",properties:[{name:e+".debugger.absolute-position",value:this._mouseXcanvas+","+this._mouseYcanvas},{name:e+".debugger.left-button",value:this._buttonMap[0]},{name:e+".debugger.middle-button",value:this._buttonMap[1]},{name:e+".debugger.right-button",value:this._buttonMap[2]},{name:e+".debugger.button-4",value:this._buttonMap[3]},{name:e+".debugger.button-5",value:this._buttonMap[4]}]},{title:e+".debugger.position-on-each-layer",properties:this._runtime.GetMainRunningLayout().GetLayers().map(e=>({name:"$"+e.GetName(),value:e.CanvasCssToLayer(this._mouseXcanvas,this._mouseYcanvas).join(", ")}))}]}}}{const a=self.C3;a.Plugins.Mouse.Cnds={OnClick(e,t){return this._triggerButton===e&&this._triggerType===t},OnAnyClick:()=>!0,IsButtonDown(e){return this._buttonMap[e]},OnRelease(e){return this._triggerButton===e},IsOverObject(e){const t=this._runtime.GetCurrentCondition().IsInverted(),s=[];return this._IsMouseOverCanvas()&&s.push([this._mouseXcanvas,this._mouseYcanvas]),a.xor(this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(e,s,t),t)},OnObjectClicked(e,t,s){if(e!==this._triggerButton||t!==this._triggerType)return!1;if(!this._IsMouseOverCanvas())return!1;const n=this._mouseXcanvas,o=this._mouseYcanvas;return this._runtime.GetCollisionEngine().TestAndSelectCanvasPointOverlap(s,[[n,o]],!1)},OnWheel(e){return 2===e||this._triggerDir===e},OnPointerLocked:()=>!0,OnPointerUnlocked:()=>!0,OnPointerLockError:()=>!0,HasPointerLock(){return this._HasPointerLock()},OnMovement:()=>!0}}{const u=self.C3,h=["auto","pointer","text","crosshair","move","help","wait","none"],l=["auto","all-scroll","none","help","pointer","progress","wait","cell","crosshair","text","vertical-text","alias","copy","move","not-allowed","grab","grabbing","col-resize","row-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out"];u.Plugins.Mouse.Acts={SetCursor(e){this.SetCursorStyle(h[e])},SetCursor2(e){this.SetCursorStyle(l[e])},SetCursorSprite(e){this.SetCursorObjectClass(e)},RequestPointerLock(e){this._RequestPointerLock(e)},ReleasePointerLock(){this._ReleasePointerLock()}}}self.C3.Plugins.Mouse.Exps={X(e){return this.GetMousePositionForLayer(e)[0]},Y(e){return this.GetMousePositionForLayer(e)[1]},AbsoluteX(){return this._mouseXcanvas},AbsoluteY(){return this._mouseYcanvas},MovementX(){return this._GetMovementX()},MovementY(){return this._GetMovementY()},WheelDeltaX(){return this._wheelDeltaX},WheelDeltaY(){return this._wheelDeltaY},WheelDeltaZ(){return this._wheelDeltaZ}};
}

// 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/Button/c3runtime/runtime.js
{
{const e=self.C3,t="button";e.Plugins.Button=class extends e.SDKDOMPluginBase{constructor(e){super(e,t),this.AddElementMessageHandler("click",(e,t)=>e._OnClick(t))}Release(){super.Release()}}}{const e=self.C3;e.Plugins.Button.Type=class extends e.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t=self.C3X,s=0,i=1,n=2,h=3,a=4,l=5,c=6,r=7,_=8,o="button";e.Plugins.Button.Instance=class extends e.SDKDOMInstanceBase{constructor(e,t){super(e,o),this._text="OK",this._isCheckbox=!1,this._isChecked=!1,this._title="",this._id="",this._className="",this._isEnabled=!0,this._autoFontSize=!0,t&&(this._isCheckbox=1===t[s],this._text=t[i],this._title=t[n],this.GetWorldInfo().SetVisible(t[h]),this._isEnabled=t[a],this._autoFontSize=t[l],this._isChecked=t[c],this._id=t[r],this._className=t[_]),this.CreateElement({"id":this._id,"className":this._className,"usesAutoFontSize":this._autoFontSize})}Release(){super.Release()}GetElementState(){return{"text":this._text,"isCheckbox":this._isCheckbox,"isChecked":this._isChecked,"title":this._title,"isVisible":this.GetWorldInfo().IsVisible(),"isEnabled":this._isEnabled}}async _OnClick(t){this._isChecked=t["isChecked"],this.DispatchScriptEvent("click",!0),await this.TriggerAsync(e.Plugins.Button.Cnds.OnClicked)}_SetText(e){this._text!==e&&(this._text=e,this.UpdateElementState())}_GetText(){return this._text}_SetTooltip(e){this._title!==e&&(this._title=e,this.UpdateElementState())}_GetTooltip(){return this._title}_SetEnabled(e){e=!!e,this._isEnabled!==e&&(this._isEnabled=e,this.UpdateElementState())}_IsEnabled(){return this._isEnabled}_SetChecked(e){this._isCheckbox&&(e=!!e,this._isChecked!==e&&(this._isChecked=e,this.UpdateElementState()))}_IsChecked(){return this._isChecked}Draw(e){}SaveToJson(){return{"text":this._text,"checked":this._isChecked,"title":this._title,"enabled":this._isEnabled}}LoadFromJson(e){this._text=e["text"],this._isChecked=e["checked"],this._title=e["title"],this._isEnabled=e["enabled"],this.UpdateElementState()}GetPropertyValueByIndex(e){switch(e){case i:return this._GetText();case n:return this._GetTooltip();case a:return this._IsEnabled();case l:return this._autoFontSize;case c:return this._IsChecked()}}SetPropertyValueByIndex(e,t){switch(e){case i:this._SetText(t);break;case n:this._SetTooltip(t);break;case a:this._SetEnabled(!!t);break;case l:this._autoFontSize=!!t;break;case c:this._SetChecked(!!t)}}GetDebuggerProperties(){const e="plugins.button";return[{title:e+".name",properties:[{name:e+".properties.text.name",value:this._GetText(),onedit:e=>this._SetText(e)},{name:e+".properties.enabled.name",value:this._IsEnabled(),onedit:e=>this._SetEnabled(e)},{name:e+".properties.checked.name",value:this._IsChecked(),onedit:e=>this._SetChecked(e)}]}]}GetScriptInterfaceClass(){return self.IButtonInstance}};const d=new WeakMap;self.IButtonInstance=class extends self.IDOMInstance{constructor(){super(),d.set(this,self.IInstance._GetInitInst().GetSdkInstance())}set text(e){t.RequireString(e),d.get(this)._SetText(e)}get text(){return d.get(this)._GetText()}set tooltip(e){t.RequireString(e),d.get(this)._SetTooltip(e)}get tooltip(){return d.get(this)._GetTooltip()}set isEnabled(e){d.get(this)._SetEnabled(e)}get isEnabled(){return d.get(this)._IsEnabled()}set isChecked(e){d.get(this)._SetChecked(e)}get isChecked(){return d.get(this)._IsChecked()}}}{const e=self.C3;e.Plugins.Button.Cnds={OnClicked:()=>!0,IsChecked(){return this._isChecked},CompareText(t,s){return s?this._text===t:e.equalsNoCase(this._text,t)}}}self.C3.Plugins.Button.Acts={SetText(e){this._SetText(e)},SetTooltip(e){this._SetTooltip(e)},SetChecked(e){this._SetChecked(0!==e)},ToggleChecked(){this._isCheckbox&&(this._isChecked=!this._isChecked,this.UpdateElementState())}};self.C3.Plugins.Button.Exps={Text(){return this._text}};
}

// 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<this._frameStartTime+a)return;const s=this._currentAnimation,o=this._currentAnimationRepeatTo,m=s.GetFrameCount(),h=s.GetRepeatCount(),u=s.IsLooping(),c=s.IsPingPong();this.IsPlayingForwards()?this._currentFrameIndex++:this._currentFrameIndex--,this._frameStartTime+=a,this._currentFrameIndex>=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;t<i;++t)c[t].OnSpriteFrameChanged(e,n);this.DispatchScriptEvent("framechange",!1,{animationName:this._currentAnimation.GetName(),animationFrame:this._currentFrameIndex}),this.Trigger(t.Plugins.Sprite.Cnds.OnFrameChanged),this._runtime.UpdateRender()}_StartAnim(t){this.SetAnimationPlaying(!0),this._frameStartTime=this.GetAnimationTime(),1===t&&0!==this._currentFrameIndex&&(this._changeAnimFrameIndex=0,this.IsInAnimationTrigger()||this._DoChangeAnimFrame()),this._StartTicking()}_SetAnim(t,e,n){this._changeAnimationName=t,this._changeAnimationFrom=e,this._StartTicking(),!n&&this.IsInAnimationTrigger()||this._DoChangeAnimation()}_GetCurrentAnimation(){return this._currentAnimation}_GetCurrentAnimationName(){return this._changeAnimationName?this._changeAnimationName:this._currentAnimation.GetName()}_OnAnimationRemoved(e){t.equalsNoCase(e,this._GetCurrentAnimationName())&&this._SetAnim(this._objectClass.GetFirstAnimation().GetName(),1,!0)}_SetAnimFrame(t){if("string"==typeof t)if(String(Number(t))===t)t=Number(t);else{const e=this._objectClass.GetAnimationByName(this._GetCurrentAnimationName());if(!e)return;if(-1===(t=e.GetFrameIndexByTag(t)))return}isFinite(t)&&(this._changeAnimFrameIndex=t,this.IsInAnimationTrigger()||this._DoChangeAnimFrame())}_OnAnimationFramesChanged(){if(this._changeAnimationName||-1!==this._changeAnimFrameIndex)return;const e=this._currentAnimationFrame,n=this._currentAnimation.GetFrameAt(t.clamp(this._currentFrameIndex,0,this._currentAnimation.GetFrameCount()-1));e!==n&&this._OnFrameChanged(e,n),this._currentAnimation.GetFrameCount()>1&&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/TiledBg/c3runtime/runtime.js
{
{const e=self.C3;e.Plugins.TiledBg=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const t=self.C3;function WrapModeToStr(e){switch(e){case 0:return"clamp-to-edge";case 1:return"repeat";case 2:return"mirror-repeat"}return"repeat"}t.Plugins.TiledBg.Type=class extends t.SDKTypeBase{constructor(e,t){super(e),this._wrapX="repeat",this._wrapY="repeat",t&&(this._wrapX=WrapModeToStr(t[0]),this._wrapY=WrapModeToStr(t[1]))}Release(){super.Release()}OnCreate(){this.GetImageInfo().LoadAsset(this._runtime)}LoadTextures(e){return this.GetImageInfo().LoadStaticTexture(e,{wrapX:this._wrapX,wrapY:this._wrapY})}ReleaseTextures(){this.GetImageInfo().ReleaseTexture()}GetWrapModeX(){return this._wrapX}GetWrapModeY(){return this._wrapY}}}{const i=globalThis.C3,a=globalThis.C3X,n=0,s=4,r=5,l=6,g=7,m=8,d=9,h=10,o=11,_=12,u=13,R=14,S=i.New(i.Quad2D),f=i.New(i.Rect),I=i.New(i.Quad2D);i.Plugins.TiledBg.Instance=class extends i.SDKWorldInstanceBase{constructor(e,t){super(e),this._imageOffsetX=0,this._imageOffsetY=0,this._imageScaleX=1,this._imageScaleY=1,this._imageAngle=0,this._enableTileRandomization=!1,this._tileXRandom=0,this._tileYRandom=0,this._tileAngleRandom=0,this._tileBlendMarginX=0,this._tileBlendMarginY=0,this._ownImageInfo=null,t&&(this.GetWorldInfo().SetVisible(!!t[n]),this._imageOffsetX=t[s],this._imageOffsetY=t[r],this._imageScaleX=t[l],this._imageScaleY=t[g],this._imageAngle=i.toRadians(t[m]),this._enableTileRandomization=!!t[d],this._tileXRandom=t[h],this._tileYRandom=t[o],this._tileAngleRandom=t[_],this._tileBlendMarginX=t[u],this._tileBlendMarginY=t[R])}Release(){this._ReleaseOwnImage(),super.Release()}_ReleaseOwnImage(){this._ownImageInfo&&(this._ownImageInfo.Release(),this._ownImageInfo=null)}CalculateTextureCoordsFor3DFace(e,t,i){const a=this.GetCurrentImageInfo(),n=a.GetWidth(),s=a.GetHeight(),r=this._imageOffsetX/n,l=this._imageOffsetY/s,g=this._imageAngle;f.set(0,0,e/(n*this._imageScaleX),t/(s*this._imageScaleY)),f.offset(-r,-l),0===g?i.setFromRect(f):i.setFromRotatedRect(f,-g)}SetTilingShaderProgram(e,t=!0){if(this._enableTileRandomization){const t=this.GetCurrentImageInfo();e.SetTileRandomizationMode(),e.SetTileRandomizationInfo(t.GetWidth()*this._imageScaleX,t.GetHeight()*this._imageScaleY,this._tileXRandom,this._tileYRandom,this._tileAngleRandom,this._tileBlendMarginX,this._tileBlendMarginY)}else t&&e.SetTextureFillMode()}Draw(e){const t=this.GetCurrentImageInfo(),i=t.GetTexture();if(null===i)return;this.SetTilingShaderProgram(e);const a=this.GetWorldInfo();e.SetTexture(i,a.GetActiveSampling());const n=t.GetWidth(),s=t.GetHeight();let r=this._imageOffsetX/n,l=this._imageOffsetY/s;0!==this._imageAngle||this._enableTileRandomization||("repeat"===this.GetSdkType().GetWrapModeX()&&(r%=1),"repeat"===this.GetSdkType().GetWrapModeY()&&(l%=1)),f.set(0,0,a.GetWidth()/(n*this._imageScaleX),a.GetHeight()/(s*this._imageScaleY)),f.offset(-r,-l),a.HasMesh()?this._DrawMesh(a,e):this._DrawStandard(a,e)}_DrawStandard(e,t){let i=e.GetBoundingQuad();this._runtime.IsPixelRoundingEnabled()&&(i=e.PixelRoundQuad(i)),0===this._imageAngle?t.Quad3(i,f):(I.setFromRotatedRect(f,-this._imageAngle),t.Quad4(i,I))}_DrawMesh(e,t){const i=e.GetTransformedMesh();if(e.IsMeshChanged()){e.CalculateBbox(null,S,!1);let t=S;this._runtime.IsPixelRoundingEnabled()&&(t=e.PixelRoundQuad(t));let a=f;0!==this._imageAngle&&(I.setFromRotatedRect(f,-this._imageAngle),a=I),i.CalculateTransformedMesh(e.GetSourceMesh(),t,a),e.SetMeshChanged(!1)}i.Draw(t,e.GetTotalZ())}GetCurrentImageInfo(){return this._ownImageInfo||this._objectClass.GetImageInfo()}IsOriginalSizeKnown(){return!0}GetTexture(){return this.GetCurrentImageInfo().GetTexture()}_SetMeshChanged(){this.GetWorldInfo().SetMeshChanged(!0)}_SetImageOffsetX(e){this._imageOffsetX!==e&&(this._imageOffsetX=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageOffsetX(){return this._imageOffsetX}_SetImageOffsetY(e){this._imageOffsetY!==e&&(this._imageOffsetY=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageOffsetY(){return this._imageOffsetY}_SetImageScaleX(e){this._imageScaleX!==e&&(this._imageScaleX=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageScaleX(){return this._imageScaleX}_SetImageScaleY(e){this._imageScaleY!==e&&(this._imageScaleY=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageScaleY(){return this._imageScaleY}_SetImageAngle(e){this._imageAngle!==e&&(this._imageAngle=e,this._runtime.UpdateRender(),this._SetMeshChanged())}_GetImageAngle(){return this._imageAngle}_SetTileRandomizationEnabled(e){e=!!e,this._enableTileRandomization!==e&&(this._enableTileRandomization=e,this._runtime.UpdateRender())}_IsTileRandomizationEnabled(){return this._enableTileRandomization}_SetTileXRandom(e){this._tileXRandom!==e&&(this._tileXRandom=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileXRandom(){return this._tileXRandom}_SetTileYRandom(e){this._tileYRandom!==e&&(this._tileYRandom=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileYRandom(){return this._tileYRandom}_SetTileAngleRandom(e){this._tileAngleRandom!==e&&(this._tileAngleRandom=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileAngleRandom(){return this._tileAngleRandom}_SetTileBlendMarginX(e){this._tileBlendMarginX!==e&&(this._tileBlendMarginX=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileBlendMarginX(){return this._tileBlendMarginX}_SetTileBlendMarginY(e){this._tileBlendMarginY!==e&&(this._tileBlendMarginY=e,this._IsTileRandomizationEnabled()&&this._runtime.UpdateRender())}_GetTileBlendMarginY(){return this._tileBlendMarginY}SaveToJson(){const e={};return 0!==this._imageOffsetX&&(e["iox"]=this._imageOffsetX),0!==this._imageOffsetY&&(e["ioy"]=this._imageOffsetY),1!==this._imageScaleX&&(e["isx"]=this._imageScaleX),1!==this._imageScaleY&&(e["isy"]=this._imageScaleY),0!==this._imageAngle&&(e["ia"]=this._imageAngle),this._enableTileRandomization&&(e["tr"]=!0),1!==this._tileXRandom&&(e["trx"]=this._tileXRandom),1!==this._tileYRandom&&(e["try"]=this._tileYRandom),1!==this._tileAngleRandom&&(e["tra"]=this._tileAngleRandom),.1!==this._tileBlendMarginX&&(e["trbmx"]=this._tileBlendMarginX),.1!==this._tileBlendMarginY&&(e["trbmy"]=this._tileBlendMarginY),e}LoadFromJson(e){this._imageOffsetX=e["iox"]||0,this._imageOffsetY=e["ioy"]||0,this._imageScaleX=e.hasOwnProperty("isx")?e["isx"]:1,this._imageScaleY=e.hasOwnProperty("isy")?e["isy"]:1,this._imageAngle=e["ia"]||0,this._enableTileRandomization=!!e["tr"],this._tileXRandom=e.hasOwnProperty("trx")?e["trx"]:1,this._tileYRandom=e.hasOwnProperty("try")?e["try"]:1,this._tileAngleRandom=e.hasOwnProperty("tra")?e["tra"]:1,this._tileBlendMarginX=e.hasOwnProperty("trbmx")?e["trbmx"]:.1,this._tileBlendMarginY=e.hasOwnProperty("trbmy")?e["trbmy"]:.1}GetDebuggerProperties(){const e="plugins.tiledbg.properties";return[{title:e+".image-transform.name",properties:[{name:e+".image-offset-x.name",value:this._GetImageOffsetX(),onedit:e=>this._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/plugins/Tilemap/c3runtime/runtime.js
{
{const t=self.C3;t.Plugins.Tilemap=class extends t.SDKPluginBase{constructor(t){super(t)}Release(){super.Release()}},t.Plugins.Tilemap.TILE_FLIPPED_HORIZONTAL=-2147483648,t.Plugins.Tilemap.TILE_FLIPPED_VERTICAL=1073741824,t.Plugins.Tilemap.TILE_FLIPPED_DIAGONAL=536870912,t.Plugins.Tilemap.TILE_FLAGS_MASK=3758096384,t.Plugins.Tilemap.TILE_ID_MASK=536870911}{const e=self.C3,i=e.Plugins.Tilemap.TILE_FLIPPED_HORIZONTAL,s=e.Plugins.Tilemap.TILE_FLIPPED_VERTICAL,h=e.Plugins.Tilemap.TILE_FLIPPED_DIAGONAL,l=e.Plugins.Tilemap.TILE_ID_MASK;e.Plugins.Tilemap.Type=class extends e.SDKTypeBase{constructor(t){super(t),this._tilePolys=[],this._areTilePolysCached=!1,this._maxTileIndex=0,this._brushesData=[],this._nameToIndexMap=null}Release(){this._nameToIndexMap.clear(),this._nameToIndexMap=null,super.Release()}OnCreate(){this.GetImageInfo().LoadAsset(this._runtime)}LoadTextures(t){return this.GetImageInfo().LoadStaticTexture(t)}ReleaseTextures(){this.GetImageInfo().ReleaseTexture()}OnDynamicTextureLoadComplete(){for(const t of this.GetObjectClass().instancesIncludingPendingCreate())t.GetSdkInstance()._OnDynamicTextureLoadComplete()}LoadTilemapData(t,e,i){this._maxTileIndex=e;for(const e of t)if(e){const t=e[0],i=!!e[1];this._tilePolys.push({poly:t,use:i,flipmap:[[[null,null],[null,null]],[[null,null],[null,null]]]})}else this._tilePolys.push(null);for(const t of i){const e=t[0],i=t[1],s=t[2];this._brushesData.push({name:e,type:i,tileData:s})}}_ForceCacheOfTileCollisionPolys(t,e){this._areTilePolysCached=!1,this._MaybeCacheTileCollisionPolys(t,e)}_MaybeCacheTileCollisionPolys(t,e){if(!this._areTilePolysCached){this._areTilePolysCached=!0;for(let i=0,s=this._tilePolys.length;i<s;++i)this._tilePolys[i]&&(this._CacheTilePoly(i,t,e,!1,!1,!1),this._CacheTilePoly(i,t,e,!1,!1,!0),this._CacheTilePoly(i,t,e,!1,!0,!1),this._CacheTilePoly(i,t,e,!1,!0,!0),this._CacheTilePoly(i,t,e,!0,!1,!1),this._CacheTilePoly(i,t,e,!0,!1,!0),this._CacheTilePoly(i,t,e,!0,!0,!1),this._CacheTilePoly(i,t,e,!0,!0,!0))}}_CacheTilePoly(t,i,s,h,l,a){if(t<0||t>=this._tilePolys.length)return;const n=this._tilePolys[t];if(!n)return;const r=e.New(e.CollisionPoly,n.poly,n.use);r.transform(i,s,0),a&&r.diag(),h&&r.mirror(i/2),l&&r.flip(s/2),n.flipmap[h?1:0][l?1:0][a?1:0]=null,n.flipmap[h?1:0][l?1:0][a?1:0]=r}GetTilePoly(t){if(-1===t)return null;const e=t&l;if(e<0||e>=this._tilePolys.length)return null;const a=this._tilePolys[e];if(!a)return null;const n=t&i?1:0,r=t&s?1:0,o=t&h?1:0;return a.flipmap[n][r][o]}IsTilePolyEnabled(t){return!t||t.IsEnabled()}GetMaxTileIndex(){return this._maxTileIndex}GetBrushData(t){this._nameToIndexMap||(this._nameToIndexMap=new Map);const e=this._nameToIndexMap.get(t);if("number"==typeof e&&e>=0)return this._brushesData[e];for(let e=0;e<this._brushesData.length;e++)if(this._brushesData[e].name===t)return this._nameToIndexMap.set(t,e),this._brushesData[e]}}}{const a=self.C3,n=self.C3X,r=0,o=1,_=2,u=3,d=4,g=5,p=6,c=a.Plugins.Tilemap.TILE_FLIPPED_HORIZONTAL,T=a.Plugins.Tilemap.TILE_FLIPPED_VERTICAL,f=a.Plugins.Tilemap.TILE_FLIPPED_DIAGONAL,m=a.Plugins.Tilemap.TILE_FLAGS_MASK,M=a.Plugins.Tilemap.TILE_ID_MASK,G=new a.Rect,I=new a.Rect,y=new a.Rect,W=new a.AABB3D;function RunLengthDecode(t){const e=[],i=t.split(",");for(let t=0,s=i.length;t<s;++t){const s=i[t],h=s.indexOf("x");if(h>-1){let t=parseInt(s.substring(0,h),10);const i=s.substring(h+1);let l=parseInt(i,10);for(i.includes("h")&&(l|=c),i.includes("v")&&(l|=T),i.includes("d")&&(l|=f);t>0;--t)e.push(l)}else{let t=parseInt(s,10);s.includes("h")&&(t|=c),s.includes("v")&&(t|=T),s.includes("d")&&(t|=f),e.push(t)}}return e}a.Plugins.Tilemap.Instance=class extends a.SDKWorldInstanceBase{constructor(t,e){super(t);const i=this.GetWorldInfo();this._tileWidth=32,this._tileHeight=32,this._tileXoffset=0,this._tileYoffset=0,this._tileXspacing=0,this._tileYspacing=0,this._mapWidth=0,this._mapHeight=0,this._lastWidth=i.GetWidth(),this._lastHeight=i.GetHeight(),this._cellWidth=0,this._cellHeight=0,this._tileCells=[],this._tileTexQuads=new Map,this._isAnyQuadMapChanged=!0,this._ownImageInfo=null,e&&(i.SetVisible(e[r]),this._tileWidth=Math.max(e[o],1),this._tileHeight=Math.max(e[_],1),this._tileXoffset=e[u],this._tileYoffset=e[d],this._tileXspacing=e[g],this._tileYspacing=e[p]),this._cellWidth=Math.ceil(this._runtime.GetOriginalViewportWidth()/this._tileWidth),this._cellHeight=Math.ceil(this._runtime.GetOriginalViewportHeight()/this._tileHeight),this._sdkType._MaybeCacheTileCollisionPolys(this._tileWidth,this._tileHeight),this._brushManager=null}Release(){this._ReleaseOwnImage(),a.clearArray(this._tileCells),this._tileCells=null,this._tileTexQuads.clear(),this._tileTexQuads=null,super.Release()}_ReleaseOwnImage(){this._ownImageInfo&&(this._ownImageInfo.Release(),this._ownImageInfo=null)}LoadTilemapData(t,e,i){this._mapWidth=e,this._mapHeight=i,this._MaybeResizeTilemap(!0),this.SetTilesFromRLECSV(t),this._MaybeBuildAllQuadMap()}_MaybeResizeTilemap(t){const[e,i]=this.GetMapDisplaySize();if(e<=this._mapWidth&&i<=this._mapHeight&&!t)return;let s=0,h=0;t?(s=Math.ceil(this._mapHeight/this._cellHeight),h=Math.ceil(this._mapWidth/this._cellWidth)):(s=this._tileCells.length,h=Math.ceil(this._mapWidth/this._cellWidth),i>this._mapHeight&&(this._mapHeight=i,s=Math.ceil(this._mapHeight/this._cellHeight)),e>this._mapWidth&&(this._mapWidth=e,h=Math.ceil(this._mapWidth/this._cellWidth)),this._SetAllQuadMapChanged(),this._SetPhysicsChanged(),this._runtime.UpdateRender());const l=this._tileCells;if(l.length<s)for(let t=l.length;t<s;++t)l.push([]);for(let t=0;t<s;++t){const e=l[t];for(let i=e.length;i<h;++i)e.push(a.New(a.Plugins.Tilemap.TileCell,this,i,t))}}SetTilesFromRLECSV(t){const e=RunLengthDecode(t);let i=0;const s=this._mapWidth,h=this._cellWidth,l=this._cellHeight;for(let t=0,a=this._mapHeight;t<a;++t)for(let a=0;a<s;++a){const s=e[i++],n=this.GetCellAt(a,t);n&&n.SetTileAt(a%h,t%l,s)}}GetTilesAsRLECSV(){let t="";if(this._mapWidth<=0||this._mapHeight<=0)return t;let e=1,i=this.GetTileAt(0,0);const[s,h]=this.GetMapDisplaySize();let l=-1,a=!1,n=!1,r=!1;for(let o=0;o<h;++o)for(let h=0===o?1:0;h<s;++h){const s=this.GetTileAt(h,o);s===i?++e:(-1===i?(l=-1,a=!1,n=!1,r=!1):(l=i&M,a=0!==(i&c),n=0!==(i&T),r=0!==(i&f)),t+=1===e?""+l:e+"x"+l,a&&(t+="h"),n&&(t+="v"),r&&(t+="d"),t+=",",e=1,i=s)}return-1===i?(l=-1,a=!1,n=!1,r=!1):(l=i&M,a=0!==(i&c),n=0!==(i&T),r=0!==(i&f)),t+=1===e?""+l:e+"x"+l,a&&(t+="h"),n&&(t+="v"),r&&(t+="d"),t}_SetAllQuadMapChanged(){const t=this._tileCells;for(let e=0,i=t.length;e<i;++e){const i=t[e];for(let t=0,e=i.length;t<e;++t)i[t]._SetQuadMapChanged()}this._isAnyQuadMapChanged=!0}_MaybeBuildAllQuadMap(){if(!this._isAnyQuadMapChanged)return;this._isAnyQuadMapChanged=!1;const t=this._tileCells;for(let e=0,i=t.length;e<i;++e){const i=t[e];for(let t=0,e=i.length;t<e;++t)i[t].MaybeBuildQuadMap()}}SetTileChanged(){this._isAnyQuadMapChanged=!0,this._SetPhysicsChanged(),this._runtime.UpdateRender()}_SetPhysicsChanged(){this.GetWorldInfo().SetPhysicsBodyChanged(!0)}GetCellAt(t,e){if(t<0||e<0)return null;const i=Math.floor(e/this._cellHeight);if(i>=this._tileCells.length)return null;const s=this._tileCells[i],h=Math.floor(t/this._cellWidth);return h>=s.length?null:s[h]}GetCellAtIndex(t,e){if(t<0||e<0||e>=this._tileCells.length)return null;const i=this._tileCells[e];return t>=i.length?null:i[t]}GetTileAt(t,e){if(t=Math.floor(t),e=Math.floor(e),t<0||e<0||t>=this._mapWidth||e>=this._mapHeight)return-1;const i=this.GetCellAt(t,e);return i?i.GetTilesArr()[e%this._cellHeight][t%this._cellWidth]:-1}SetTileAt(t,e,i){if(t=Math.floor(t),e=Math.floor(e),t<0||e<0||t>=this._mapWidth||e>=this._mapHeight)return;if(-1!==i&&(i&M)>this.GetMaxTileIndex())return;const s=this.GetCellAt(t,e);s&&s.SetTileAt(t%this._cellWidth,e%this._cellHeight,i)}GetMaxTileIndex(){return this._sdkType.GetMaxTileIndex()}WorldToCellX(t){return Math.floor((t-this.GetWorldInfo().GetX())/(this._cellWidth*this._tileWidth))}WorldToCellY(t){return Math.floor((t-this.GetWorldInfo().GetY())/(this._cellHeight*this._tileHeight))}WorldToTileX(t){return Math.floor((t-this.GetWorldInfo().GetX())/this._tileWidth)}WorldToTileY(t){return Math.floor((t-this.GetWorldInfo().GetY())/this._tileHeight)}GetMapWidth(){return this._mapWidth}GetMapHeight(){return this._mapHeight}GetMapDisplayWidth(){return Math.floor(this.GetWorldInfo().GetWidth()/this.GetTileWidth())}GetMapDisplayHeight(){return Math.floor(this.GetWorldInfo().GetHeight()/this.GetTileHeight())}GetMapDisplaySize(){const t=this.GetWorldInfo();return[Math.floor(t.GetWidth()/this.GetTileWidth()),Math.floor(t.GetHeight()/this.GetTileHeight())]}GetTileWidth(){return this._tileWidth}GetTileHeight(){return this._tileHeight}GetCellWidth(){return this._cellWidth}GetCellHeight(){return this._cellHeight}GetCollisionRectCandidates(t,e){const i=this.WorldToCellX(t.getLeft()),s=this.WorldToCellY(t.getTop()),h=this.WorldToCellX(t.getRight()),l=this.WorldToCellY(t.getBottom());for(let t=i;t<=h;++t)for(let i=s;i<=l;++i){const s=this.GetCellAtIndex(t,i);s&&(s.MaybeBuildQuadMap(),a.appendArray(e,s.GetCollisionRects()))}}TestPointOverlapTile(t,e){const i=this.WorldToTileX(t),s=this.WorldToTileY(e),h=this.GetTileAt(i,s);if(-1===h)return!1;const l=this._sdkType.GetTilePoly(h);if(!l)return!0;if(!this._sdkType.IsTilePolyEnabled(l))return!1;const a=this.GetWorldInfo();return t-=Math.floor((t-a.GetX())/this._tileWidth)*this._tileWidth+a.GetX(),e-=Math.floor((e-a.GetY())/this._tileHeight)*this._tileHeight+a.GetY(),l.containsPoint(t,e)}GetAllCollisionRects(t){const e=this._tileCells;for(let i=0,s=e.length;i<s;++i){const s=e[i];for(let e=0,i=s.length;e<i;++e){const i=s[e];i.MaybeBuildQuadMap(),a.appendArray(t,i.GetCollisionRects())}}}GetCurrentImageInfo(){return this._ownImageInfo||this._objectClass.GetImageInfo()}GetTileUvQuad(t){const e=this._tileTexQuads,i=e.get(t);if(i)return i;const s=t&M,h=0!==(t&c),l=0!==(t&T),n=0!==(t&f),r=this.GetCurrentImageInfo(),o=r.GetWidth(),_=this._tileWidth,u=this._tileXoffset,d=this._tileXspacing,g=Math.floor((o-u)/(_+d)*_)+d,p=Math.floor(g/_),m=s%p,I=Math.floor(s/p),y=r.GetOffsetX()+this._tileXoffset+(this._tileWidth+this._tileXspacing)*m,W=r.GetOffsetY()+this._tileYoffset+(this._tileHeight+this._tileYspacing)*I;G.setWH(y,W,this._tileWidth,this._tileHeight),G.divide(r.GetSheetWidth(),r.GetSheetHeight());const C=a.New(a.Quad2D);return C.setFromRect(G),n&&C.diag(),h&&C.mirror(),l&&C.flip(),C.offset(m,I),e.set(t,C),C}_OnDynamicTextureLoadComplete(){this._tileTexQuads.clear(),this._SetAllQuadMapChanged()}Draw(t){const e=this.GetCurrentImageInfo(),i=e.GetTexture();if(!i)return;G.copy(e.GetTexRect()),G.offsetLeft(this._tileXoffset/i.GetWidth()),G.offsetTop(this._tileYoffset/i.GetHeight());const s=this.GetWorldInfo();t.SetTilemapFillMode(),t.SetTilemapInfo(G,i.GetWidth(),i.GetHeight(),this._tileWidth,this._tileHeight,this._tileXspacing,this._tileYspacing),t.SetTexture(i,s.GetActiveSampling());const h=s.GetLayer();s.GetWidth()===this._lastWidth&&s.GetHeight()===this._lastHeight||(this._SetPhysicsChanged(),this._SetAllQuadMapChanged(),this._lastWidth=s.GetWidth(),this._lastHeight=s.GetHeight());let l=s.GetX(),a=s.GetY();this._runtime.IsPixelRoundingEnabled()&&(l=Math.round(l),a=Math.round(a));const n=this._cellWidth*this._tileWidth,r=this._cellHeight*this._tileHeight,o=s.GetTotalZ(),_=I;if(h.Has3DCamera()){_.set(-1/0,-1/0,1/0,1/0);const e=y,i=h._GetViewFrustum();for(const s of this._tileCells)for(const h of s)h.GetLayoutRect(e),W.setFromRect(e,o,o),i.ContainsAABB(W)&&(h.MaybeBuildQuadMap(),h.Draw(t,_,l,a))}else{h.GetViewportForZ(o,_);const e=Math.floor((_.getLeft()-l)/n),i=Math.floor((_.getRight()-l)/n),s=Math.floor((_.getTop()-a)/r),u=Math.floor((_.getBottom()-a)/r);for(let h=e;h<=i;++h)for(let e=s;e<=u;++e){const i=this.GetCellAtIndex(h,e);i&&(i.MaybeBuildQuadMap(),i.Draw(t,_,l,a))}}}SaveToJson(){this._MaybeResizeTilemap();const[t,e]=this.GetMapDisplaySize();return{"tw":this._tileWidth,"th":this._tileHeight,"tox":this._tileXoffset,"toy":this._tileYoffset,"tsx":this._tileXspacing,"tsy":this._tileYspacing,"w":t,"h":e,"d":this.GetTilesAsRLECSV()}}LoadFromJson(t){this._tileWidth=t["tw"],this._tileHeight=t["th"],this._tileXoffset=t["tox"],this._tileYoffset=t["toy"],this._tileXspacing=t["tsx"],this._tileYspacing=t["tsy"],this._mapWidth=t["w"],this._mapHeight=t["h"],this._MaybeResizeTilemap(!0),this.SetTilesFromRLECSV(t["d"]),this._SetPhysicsChanged(),this._SetAllQuadMapChanged()}GetAsJsonString(){this._MaybeResizeTilemap();const[t,e]=this.GetMapDisplaySize();return JSON.stringify({"c2tilemap":!0,"width":t,"height":e,"data":this.GetTilesAsRLECSV()})}StateComboToFlags(t){switch(t){case 0:default:return 0;case 1:return c;case 2:return T;case 3:return c|f;case 4:return c|T;case 5:return T|f;case 6:return c|T|f;case 7:return f}}GetPropertyValueByIndex(t){switch(t){case o:return this._tileWidth;case _:return this._tileHeight;case u:return this._tileXoffset;case d:return this._tileYoffset;case g:return this._tileXspacing;case p:return this._tileYspacing}}SetPropertyValueByIndex(t,e){switch(t){case o:if(this._tileWidth===e)return;this._tileWidth=Math.max(e,1),this._cellWidth=Math.ceil(this._runtime.GetOriginalViewportWidth()/this._tileWidth),this._sdkType._ForceCacheOfTileCollisionPolys(),this._UpdateQuadMaps();break;case _:if(this._tileHeight===e)return;this._tileHeight=Math.max(e,1),this._cellHeight=Math.ceil(this._runtime.GetOriginalViewportHeight()/this._tileHeight),this._sdkType._ForceCacheOfTileCollisionPolys(),this._UpdateQuadMaps();break;case u:if(this._tileXoffset===e)return;this._tileXoffset=e,this._UpdateQuadMaps();break;case d:if(this._tileYoffset===e)return;this._tileYoffset=e,this._UpdateQuadMaps();break;case g:if(this._tileXspacing===e)return;this._tileXspacing=e,this._UpdateQuadMaps();break;case p:if(this._tileYspacing===e)return;this._tileYspacing=e,this._UpdateQuadMaps()}}_UpdateQuadMaps(){this._tileTexQuads.clear(),this._SetAllQuadMapChanged(),this._MaybeBuildAllQuadMap()}GetScriptInterfaceClass(){return P}};const C=new WeakMap,P=self.ITilemapInstance=class extends self.IWorldInstance{constructor(){super(),C.set(this,self.IInstance._GetInitInst().GetSdkInstance())}get mapWidth(){return C.get(this).GetMapWidth()}get mapHeight(){return C.get(this).GetMapHeight()}getMapSize(){const t=C.get(this);return[t.GetMapWidth(),t.GetMapHeight()]}get mapDisplayWidth(){return C.get(this).GetMapDisplayWidth()}get mapDisplayHeight(){return C.get(this).GetMapDisplayHeight()}getMapDisplaySize(){const t=C.get(this);return[t.GetMapDisplayWidth(),t.GetMapDisplayHeight()]}get tileWidth(){return C.get(this).GetTileWidth()}get tileHeight(){return C.get(this).GetTileHeight()}getTileSize(){const t=C.get(this);return[t.GetTileWidth(),t.GetTileHeight()]}getTileAt(t,e){return n.RequireFiniteNumber(t),n.RequireFiniteNumber(e),C.get(this).GetTileAt(t,e)}setTileAt(t,e,i){n.RequireFiniteNumber(t),n.RequireFiniteNumber(e),n.RequireFiniteNumber(i);const s=C.get(this);s._MaybeResizeTilemap(),s.SetTileAt(t,e,i)}async replaceImage(t){n.RequireInstanceOf(t,Blob);const e=C.get(this),i=e.GetRuntime(),s=a.New(a.ImageInfo);s.LoadDynamicBlobAsset(i,t),await s.LoadStaticTexture(i.GetRenderer()),e.WasReleased()?s.Release():(e._ReleaseOwnImage(),e._ownImageInfo=s,e._tileTexQuads.clear(),e._SetAllQuadMapChanged(),i.UpdateRender())}};P.TILE_FLIPPED_HORIZONTAL=c,P.TILE_FLIPPED_VERTICAL=T,P.TILE_FLIPPED_DIAGONAL=f,P.TILE_FLAGS_MASK=m,P.TILE_ID_MASK=M}{const S=self.C3,A=S.Plugins.Tilemap.TILE_FLAGS_MASK,b=S.Plugins.Tilemap.TILE_ID_MASK;S.Plugins.Tilemap.Cnds={CompareTileAt(t,e,i,s){let h=this.GetTileAt(t,e);return-1!==h&&(h&=b),S.compare(h,i,s)},CompareTileStateAt(t,e,i){const s=this.GetTileAt(t,e);let h=0;return-1!==s&&(h=s&A),h===this.StateComboToFlags(i)},OnURLLoaded:()=>!0,OnURLFailed:()=>!0,BrushExists(t){return this._brushManager||(this._brushManager=new S.Plugins.Tilemap.BrushManager(this,this._sdkType)),this._brushManager.BrushExists(t)}}}{const H=self.C3,L=H.Plugins.Tilemap.TILE_ID_MASK;H.Plugins.Tilemap.Acts={EraseTile(t,e){this._MaybeResizeTilemap(),this.SetTileAt(t,e,-1)},SetTile(t,e,i,s){this._MaybeResizeTilemap(),this.SetTileAt(t,e,i&L|this.StateComboToFlags(s))},SetTileState(t,e,i){const s=this.GetTileAt(t,e);-1!==s&&(this._MaybeResizeTilemap(),this.SetTileAt(t,e,s&L|this.StateComboToFlags(i)))},EraseTileRange(t,e,i,s){const h=Math.floor(Math.max(t,0)),l=Math.floor(Math.max(e,0)),a=Math.floor(Math.min(t+i,this._mapWidth)),n=Math.floor(Math.min(e+s,this._mapHeight));for(let t=l;t<n;++t)for(let e=h;e<a;++e)this.SetTileAt(e,t,-1)},SetTileRange(t,e,i,s,h,l){this._MaybeResizeTilemap();const a=Math.floor(Math.max(t,0)),n=Math.floor(Math.max(e,0)),r=Math.floor(Math.min(t+i,this._mapWidth)),o=Math.floor(Math.min(e+s,this._mapHeight)),_=h&L|this.StateComboToFlags(l);for(let t=n;t<o;++t)for(let e=a;e<r;++e)this.SetTileAt(e,t,_)},SetTileStateRange(t,e,i,s,h){this._MaybeResizeTilemap();const l=Math.floor(Math.max(t,0)),a=Math.floor(Math.max(e,0)),n=Math.floor(Math.min(t+i,this._mapWidth)),r=Math.floor(Math.min(e+s,this._mapHeight)),o=this.StateComboToFlags(h);for(let t=a;t<r;++t)for(let e=l;e<n;++e){const i=this.GetTileAt(e,t);-1!==i&&this.SetTileAt(e,t,i&L|o)}},LoadFromJSON(t){let e=null;try{e=JSON.parse(t)}catch(t){return void console.error("[Construct] Failed to parse tilemap JSON: ",t)}e["c2tilemap"]?(this._mapWidth=e["width"],this._mapHeight=e["height"],this._MaybeResizeTilemap(!0),this.SetTilesFromRLECSV(e["data"]),this._SetAllQuadMapChanged(),this._SetPhysicsChanged()):console.error("[Construct] Unrecognized JSON data format")},JSONDownload(t){const e=URL.createObjectURL(new Blob([this.GetAsJsonString()],{type:"application/json"}));this._runtime.InvokeDownload(e,t)},async LoadURL(t,e){if(this._ownImageInfo&&this._ownImageInfo.GetURL()===t)return;const i=this._runtime,s=H.New(H.ImageInfo);try{if(await s.LoadDynamicAsset(i,t),!s.IsLoaded())throw new Error("image failed to load");if(this.WasReleased())return s.Release(),null;if(!await s.LoadStaticTexture(i.GetRenderer()))return}catch(t){return console.error("Load image from URL failed: ",t),void(this.WasReleased()||this.Trigger(H.Plugins.Tilemap.Cnds.OnURLFailed))}this.WasReleased()?s.Release():(this._ReleaseOwnImage(),this._ownImageInfo=s,i.UpdateRender(),this._tileTexQuads.clear(),this._SetAllQuadMapChanged(),await this.TriggerAsync(H.Plugins.Tilemap.Cnds.OnURLLoaded))},SetEffect(t){t>=2&&t++,this.GetWorldInfo().SetBlendMode(t),this._runtime.UpdateRender()},SetTileWithBrush(t,e,i){if(this._MaybeResizeTilemap(),this._brushManager||(this._brushManager=new H.Plugins.Tilemap.BrushManager(this,this._sdkType)),this._brushManager.BrushExists(i))switch(this._brushManager.GetBrushType(i)){case 0:case 1:this._brushManager.SetAutoTile(t,e,i);break;case 2:this._brushManager.SetPatchTile(t,e,i)}},SetTileWithPatchBrush(t,e,i,s,h,l,a){if(this._MaybeResizeTilemap(),this._brushManager||(this._brushManager=new H.Plugins.Tilemap.BrushManager(this,this._sdkType)),this._brushManager.BrushExists(i)&&2===this._brushManager.GetBrushType(i))this._brushManager.SetPatchTile(t,e,i,s,h,l,a)},EraseTileWithBrush(t,e,i){if(this._MaybeResizeTilemap(),this._brushManager||(this._brushManager=new H.Plugins.Tilemap.BrushManager(this,this._sdkType)),this._brushManager.BrushExists(i))switch(this._brushManager.GetBrushType(i)){case 0:case 1:this._brushManager.EraseAutoTile(t,e,i);break;case 2:this._brushManager.ErasePatchTile(t,e,i)}},EraseTileWithPatchBrush(t,e,i,s,h,l){if(this._MaybeResizeTilemap(),this._brushManager||(this._brushManager=new H.Plugins.Tilemap.BrushManager(this,this._sdkType)),this._brushManager.BrushExists(i)&&2===this._brushManager.GetBrushType(i))this._brushManager.ErasePatchTile(t,e,i,s,h,l)},SetTileWithPatchBrushByName(t,e,i,s,h,l,a){H.Plugins.Tilemap.Acts.SetTileWithPatchBrush.call(this,t,e,i,s,h,l,a)},EraseTileWithPatchBrushByName(t,e,i,s,h,l){H.Plugins.Tilemap.Acts.EraseTileWithPatchBrush.call(this,t,e,i,s,h,l)},SetTileWithBrushByName(t,e,i){H.Plugins.Tilemap.Acts.SetTileWithBrush.call(this,t,e,i)},EraseTileWithBrushByName(t,e,i){H.Plugins.Tilemap.Acts.EraseTileWithBrush.call(this,t,e,i)}}}{const R=self.C3,x=R.Plugins.Tilemap.TILE_ID_MASK;R.Plugins.Tilemap.Exps={TileAt(t,e){const i=this.GetTileAt(t,e);return-1===i?-1:i&x},PositionToTileX(t){return this.WorldToTileX(t)},PositionToTileY(t){return this.WorldToTileY(t)},TileToPositionX(t){return t*this._tileWidth+this.GetWorldInfo().GetX()+this._tileWidth/2},TileToPositionY(t){return t*this._tileHeight+this.GetWorldInfo().GetY()+this._tileHeight/2},SnapX(t){const e=this.GetWorldInfo().GetX();return Math.floor((t-e)/this._tileWidth)*this._tileWidth+e+this._tileWidth/2},SnapY(t){const e=this.GetWorldInfo().GetY();return Math.floor((t-e)/this._tileHeight)*this._tileHeight+e+this._tileHeight/2},TilesJSON(){return this.GetAsJsonString()},TileWidth(){return this.GetTileWidth()},TileHeight(){return this.GetTileHeight()},MapDisplayWidth(){return this.GetMapDisplayWidth()},MapDisplayHeight(){return this.GetMapDisplayHeight()},BrushWidth(t){return this._brushManager||(this._brushManager=new R.Plugins.Tilemap.BrushManager(this,this._sdkType)),this._brushManager.BrushExists(t)&&2===this._brushManager.GetBrushType(t)?this._brushManager.GetBrushWidth(t):0},BrushHeight(t){return this._brushManager||(this._brushManager=new R.Plugins.Tilemap.BrushManager(this,this._sdkType)),this._brushManager.BrushExists(t)&&2===this._brushManager.GetBrushType(t)?this._brushManager.GetBrushHeight(t):0}}}
}

// scripts/plugins/Tilemap/c3runtime/tileQuad.js
{
const C3=self.C3,TILE_FLIPPED_HORIZONTAL=C3.Plugins.Tilemap.TILE_FLIPPED_HORIZONTAL,TILE_FLIPPED_VERTICAL=C3.Plugins.Tilemap.TILE_FLIPPED_VERTICAL,TILE_FLIPPED_DIAGONAL=C3.Plugins.Tilemap.TILE_FLIPPED_DIAGONAL,TILE_ID_MASK=C3.Plugins.Tilemap.TILE_ID_MASK,tempRect=C3.New(C3.Rect),tempQuad=C3.New(C3.Quad2D);C3.Plugins.Tilemap.TileQuad=class extends C3.DefendedBase{constructor(){super(),this._id=-1,this._tileId=-1,this._isHorizFlip=!1,this._isVertFlip=!1,this._isDiagFlip=!1,this._rc=C3.New(C3.Rect),this._uv=null}Update(i,t,e,s,_,I,L,T){this._id=i,this._tileId=i&TILE_ID_MASK,this._isHorizFlip=0!==(i&TILE_FLIPPED_HORIZONTAL),this._isVertFlip=0!==(i&TILE_FLIPPED_VERTICAL),this._isDiagFlip=0!==(i&TILE_FLIPPED_DIAGONAL),this._rc.setWH(s*t+I,_*e+L,t,e),this._uv=T.GetTileUvQuad(this._id)}Draw(i,t,e,s,_){tempRect.copy(this._rc),tempRect.offset(e,s),tempRect.intersectsRect(t)&&(tempQuad.setFromRect(tempRect),i.Quad4(tempQuad,this._uv))}};
}

// scripts/plugins/Tilemap/c3runtime/tileCollisionRect.js
{
const C3=self.C3;C3.Plugins.Tilemap.TileCollisionRect=class extends C3.DefendedBase{constructor(){super(),this._id=-1,this._poly=null,this._rc=C3.New(C3.Rect)}Update(t,e,s,i,l,r,h,c){this._id=t,this._poly=e,this._rc.setWH(l*s+h,r*i+c,s,i)}ExtendRight(t){this._rc.setRight(this._rc.getRight()+t)}GetTileId(){return this._id}HasPoly(){return!!this._poly}GetPoly(){return this._poly}GetRect(){return this._rc}};
}

// scripts/plugins/Tilemap/c3runtime/tileCell.js
{
const C3=self.C3,TILE_ID_MASK=C3.Plugins.Tilemap.TILE_ID_MASK;C3.Plugins.Tilemap.TileCell=class extends C3.DefendedBase{constructor(t,e,i){super();const l=t.GetCellWidth(),s=t.GetCellHeight();this._sdkInst=t,this._x=e,this._y=i,this._left=this._x*l*t.GetTileWidth(),this._top=this._y*s*t.GetTileHeight(),this._tiles=[],this._quads=[],this._collisionRects=[],this._isQuadMapValid=!1;for(let t=0;t<s;++t){const t=new Int32Array(l);t.fill(-1),this._tiles.push(t)}}Clear(){const t=this._sdkInst.GetCellWidth(),e=this._sdkInst.GetCellHeight(),i=this._tiles;if(i.length<e)for(let l=i.length;l<e;++l)i.push(new Int32Array(t));else i.length>e&&C3.truncateArray(i,e);for(let e=0,l=i.length;e<l;++e){let l=i[e];l.length!==t&&(l=new Int32Array(t),i[e]=l),l.fill(-1)}}GetLayoutRect(t){const e=this._sdkInst,i=e.GetWorldInfo(),l=e.GetCellWidth()*e.GetTileWidth(),s=e.GetCellHeight()*e.GetTileHeight(),h=i.GetX()+this._left,n=i.GetY()+this._top;t.set(h,n,h+l,n+s)}_SetQuadMapChanged(){this._isQuadMapValid=!1}MaybeBuildQuadMap(){if(this._isQuadMapValid)return;const t=this._sdkInst,e=t.GetSdkType(),i=t.GetWorldInfo(),l=t.GetTileWidth(),s=t.GetTileHeight(),h=t.GetCellWidth(),n=t.GetCellHeight(),o=this._left,a=this._top;if(l<=0||s<=0)return;let d=Math.min(t.GetMapWidth(),Math.floor(i.GetWidth()/l)),r=Math.min(t.GetMapHeight(),Math.floor(i.GetHeight()/s));d-=o/l,r-=a/s,d>h&&(d=h),r>n&&(r=n);const g=this._tiles,_=this._quads;let u=0;for(let e=0;e<r;++e){const i=g[e];for(let h=0;h<d;++h){const n=i[h];if(-1===n)continue;let d=null;u<_.length?d=_[u]:(d=C3.New(C3.Plugins.Tilemap.TileQuad),_.push(d)),d.Update(n,l,s,h,e,o,a,t),++u}}u<_.length&&C3.truncateArray(_,u);let c=null,f=!1;const p=this._collisionRects;C3.clearArray(p);for(let t=0;t<r;++t){const i=g[t];for(let h=0;h<d;++h){const n=i[h],d=e.GetTilePoly(n),r=e.IsTilePolyEnabled(d);-1!==n&&r?!c||d||f?(c&&p.push(c),c=C3.New(C3.Plugins.Tilemap.TileCollisionRect),c.Update(n,d,l,s,h,t,o,a),f=!!d):c.ExtendRight(l):c&&(p.push(c),c=null,f=!1)}c&&(p.push(c),c=null,f=!1)}let G=p.length;for(let t=0;t<G;++t){const e=p[t];if(e.HasPoly())continue;const i=e.GetRect();for(let e=t+1;e<G;++e){const t=p[e],l=t.GetRect();l.getTop()<i.getBottom()||(l.getTop()>i.getBottom()||l.getRight()>i.getRight()||l.getLeft()>i.getLeft()||t.HasPoly()||l.getLeft()===i.getLeft()&&l.getRight()===i.getRight()&&(p.splice(e,1),--G,i.setBottom(i.getBottom()+s),--e))}}this._isQuadMapValid=!0}SetTileAt(t,e,i){this._tiles[e][t]!==i&&(this._tiles[e][t]=i,this._isQuadMapValid=!1,this._sdkInst.SetTileChanged())}GetTilesArr(){return this._tiles}GetCollisionRects(){return this._collisionRects}Draw(t,e,i,l){const s=this._sdkInst,h=this._quads;for(let n=0,o=h.length;n<o;++n)h[n].Draw(t,e,i,l,s)}};
}

// scripts/plugins/Tilemap/c3runtime/brushManager.js
{
const C3=self.C3,IGNORE_INDEX=-999,FORCE_INDEX=-998,EMPTY_INDEX=-1,PAINT_MODE=0,ERASE_MODE=1,AUTO_TILING_PATCH=Object.freeze([[0,0,0],[0,0,0],[0,0,0]]);C3.Plugins.Tilemap.BrushManager=class{constructor(t,e){this._sdkInst=t,this._sdkType=e,this._brushAdapterInstances=[null,null,null],this._brushAdapterConstructors=[C3.Plugins.Tilemap.AutoTiling16,C3.Plugins.Tilemap.AutoTiling47,C3.Plugins.Tilemap.Patch],this._probabilityTable=new C3.ProbabilityTable}get AUTO_TILING_PATCH(){return AUTO_TILING_PATCH}get IGNORE_INDEX(){return-999}get FORCE_INDEX(){return-998}get EMPTY_INDEX(){return-1}get PAINT_MODE(){return 0}get ERASE_MODE(){return 1}GetSdkInstance(){return this._sdkInst}GetSdkType(){return this._sdkType}GetProbabilityTable(){return this._probabilityTable}GetBrushWidth(t){return this.BrushExists(t)?this._GetBrushWidth(t):0}GetBrushHeight(t){return this.BrushExists(t)?this._GetBrushHeight(t):0}SetAutoTile(t,e,s){this.BrushExists(s)&&(this._SetMode(s,0),this._SetAutoTilePatch(t,e,this._GetPatch(t,e,s)))}EraseAutoTile(t,e,s){this.BrushExists(s)&&(this._SetMode(s,1),this._EraseTile(t,e),this._SetAutoTilePatch(t,e,this._GetPatch(t,e,s)))}SetPatchTile(t,e,s,h,i,r,a){this.BrushExists(s)&&(this._SetMode(s,0),this._SetTilePatch(t,e,s,this._GetPatch(t,e,s),h,i,r,a,0))}ErasePatchTile(t,e,s,h,i,r){this.BrushExists(s)&&(this._SetMode(s,1),this._SetTilePatch(t,e,s,this._GetPatch(t,e,s),h,i,r,0,1))}GetBrushType(t){return this._GetBrushType(t)}BrushExists(t){return!!this.GetSdkType().GetBrushData(t)}GetTile(t,e){return this.GetSdkInstance().GetTileAt(t,e)}_SetTile(t,e,s){this.GetSdkInstance().SetTileAt(t,e,s)}_EraseTile(t,e){this.GetSdkInstance().SetTileAt(t,e,-1)}_SetAutoTilePatch(t,e,s){s&&(this._SetTile(t-1,e-1,s[0][0]),this._SetTile(t,e-1,s[1][0]),this._SetTile(t+1,e-1,s[2][0]),this._SetTile(t-1,e,s[0][1]),this._SetTile(t,e,s[1][1]),this._SetTile(t+1,e,s[2][1]),this._SetTile(t-1,e+1,s[0][2]),this._SetTile(t,e+1,s[1][2]),this._SetTile(t+1,e+1,s[2][2]))}_SetTilePatch(t,e,s,h,i=!1,r=!1,a=0,u=0,_=0){if(!h)return;const n=(h=this._TransformPatch(h,s,i,r,a,u,_))[0].length,T=h.length;for(let s=0;s<T;s++)for(let i=0;i<n;i++)if(h[s][i]!==this.IGNORE_INDEX)switch(u){case 0:h[s][i]===this.EMPTY_INDEX?this._EraseTile(t+i,e+s):this._SetTile(t+i,e+s,h[s][i]);break;case 1:-1!==h[s][i]&&this._SetTile(t+i,e+s,h[s][i])}}_GetBrushType(t){return this.GetSdkType().GetBrushData(t).type}_MaybeCreateBrushAdapter(t){const e=this._GetBrushType(t);this._brushAdapterInstances[e]||(this._brushAdapterInstances[e]=new this._brushAdapterConstructors[e](this))}_SetMode(t,e){this._MaybeCreateBrushAdapter(t);const s=this._GetBrushType(t);this._brushAdapterInstances[s]&&this._brushAdapterInstances[s].SetMode(e)}_GetMode(t){this._MaybeCreateBrushAdapter(t);const e=this._GetBrushType(t);if(this._brushAdapterInstances[e])return this._brushAdapterInstances[e].GetMode()}_GetPatch(t,e,s){this._MaybeCreateBrushAdapter(s);const h=this.GetSdkType().GetBrushData(s);if(this._brushAdapterInstances[h.type])return this._brushAdapterInstances[h.type].BuildPatch(t,e,h)}_TransformPatch(t,e,s=!1,h=!1,i=0,r=0,a=0){this._MaybeCreateBrushAdapter(e);const u=this.GetSdkType().GetBrushData(e);if(this._brushAdapterInstances[u.type])return this._brushAdapterInstances[u.type].TransformPatch(t,s,h,i,r,a)}_GetBrushWidth(t){this._MaybeCreateBrushAdapter(t);const e=this.GetSdkType().GetBrushData(t);if(this._brushAdapterInstances[e.type])return this._brushAdapterInstances[e.type].GetBrushWidth(e)}_GetBrushHeight(t){this._MaybeCreateBrushAdapter(t);const e=this.GetSdkType().GetBrushData(t);if(this._brushAdapterInstances[e.type])return this._brushAdapterInstances[e.type].GetBrushHeight(e)}};
}

// scripts/plugins/Tilemap/c3runtime/autoTilingHelper.js
{
const C3=self.C3;C3.Plugins.Tilemap.AutoTilingHelper=class{constructor(e){this._manager=e}DoesTileExist(e,t,i){const n=this._manager.GetTile(e,t);return!!this.IsTileValid(n,!0,n,i)}IsTileValid(e,t,i,n){return e===this._manager.EMPTY_INDEX?0:t&&e===this._manager.FORCE_INDEX?1:t&&n&&!this._IsTileIndexInBrush(i,n)?0:1}GetTileIndex(e,t,i,n){const r=n.tileData[e];if(!r.length)return this._manager.EMPTY_INDEX;if(1===r.length)return r[0][0];const s=this._manager.GetTile(t,i);if(this.IsTileValid(s)){if(r.some(e=>s===e[0]))return s}const a=this._manager.GetProbabilityTable();a.Clear();for(let[e,t]of r)e>this._manager.GetSdkInstance().GetMaxTileIndex()||("number"!=typeof t&&(t=1),a.AddItem(t,e));return a.Sample()}_IsTileIndexInBrush(e,t){for(const i of t.tileData)for(const[t]of i)if(t===e)return!0;return!1}};
}

// scripts/plugins/Tilemap/c3runtime/autoTiling16.js
{
const C3=self.C3;C3.Plugins.Tilemap.AutoTiling16=class{constructor(t){this._manager=t,this._helper=new C3.Plugins.Tilemap.AutoTilingHelper(t),this._mode=t.PAINT_MODE}SetMode(t){this._mode=t}GetMode(){return this._mode}GetBrushWidth(t){return 0}GetBrushHeight(t){return 0}TransformPatch(t,e=!1,i=!1,_=0,s=0,h=0){return t}BuildPatch(t,e,i){return this._Build4BitAutoTilePatch(t,e,i)}_Build4BitAutoTilePatch(t,e,i){const _=this._mode===this._manager.PAINT_MODE?this._4BitAutoTiling(t,e,void 0,i):this._manager.EMPTY_INDEX,s=this._Get4BitAutoTile(t,e-1,"s",i),h=this._Get4BitAutoTile(t-1,e,"e",i),a=this._Get4BitAutoTile(t+1,e,"w",i),r=this._Get4BitAutoTile(t,e+1,"n",i),n=this._manager.AUTO_TILING_PATCH;return n[0][0]=this._manager.IGNORE_INDEX,n[1][0]=this._Get4BitTileIndex(s,t,e-1,i),n[2][0]=this._manager.IGNORE_INDEX,n[0][1]=this._Get4BitTileIndex(h,t-1,e,i),n[1][1]=this._Get4BitTileIndex(_,t,e,i),n[2][1]=this._Get4BitTileIndex(a,t+1,e,i),n[0][2]=this._manager.IGNORE_INDEX,n[1][2]=this._Get4BitTileIndex(r,t,e+1,i),n[2][2]=this._manager.IGNORE_INDEX,n}_Get4BitAutoTile(t,e,i,_){return this._helper.DoesTileExist(t,e,_)?this._4BitAutoTiling(t,e,i,_):this._manager.IGNORE_INDEX}_4BitAutoTiling(t,e,i,_){this._mode===this._manager.ERASE_MODE&&(i=void 0);const s=this._manager.GetTile(t,e-1),h=this._manager.GetTile(t-1,e),a=this._manager.GetTile(t+1,e),r=this._manager.GetTile(t,e+1),n="n"===i?this._manager.FORCE_INDEX:s,l="w"===i?this._manager.FORCE_INDEX:h,T="e"===i?this._manager.FORCE_INDEX:a,I="s"===i?this._manager.FORCE_INDEX:r;return 1*this._helper.IsTileValid(n,!0,s,_)+2*this._helper.IsTileValid(l,!0,h,_)+4*this._helper.IsTileValid(T,!0,a,_)+8*this._helper.IsTileValid(I,!0,r,_)}_Get4BitTileIndex(t,e,i,_){return t===this._manager.IGNORE_INDEX||t===this._manager.EMPTY_INDEX?t:this._helper.GetTileIndex(t,e,i,_)}};
}

// scripts/plugins/Tilemap/c3runtime/autoTiling47.js
{
const C3=self.C3,TILE_INDEX_MAP=new Map([[2,1],[8,2],[10,3],[11,4],[16,5],[18,6],[22,7],[24,8],[26,9],[27,10],[30,11],[31,12],[64,13],[66,14],[72,15],[74,16],[75,17],[80,18],[82,19],[86,20],[88,21],[90,22],[91,23],[94,24],[95,25],[104,26],[106,27],[107,28],[120,29],[122,30],[123,31],[126,32],[127,33],[208,34],[210,35],[214,36],[216,37],[218,38],[219,39],[222,40],[223,41],[248,42],[250,43],[251,44],[254,45],[255,46],[0,47]]);C3.Plugins.Tilemap.AutoTiling47=class{constructor(e){this._manager=e,this._helper=new C3.Plugins.Tilemap.AutoTilingHelper(e),this._mode=e.PAINT_MODE}SetMode(e){this._mode=e}GetMode(){return this._mode}GetBrushWidth(e){return 0}GetBrushHeight(e){return 0}TransformPatch(e,t=!1,i=!1,s=0,_=0,h=0){return e}BuildPatch(e,t,i){return this._Build8BitAutoTilePatch(e,t,i)}_Build8BitAutoTilePatch(e,t,i){const s=this._mode===this._manager.PAINT_MODE?this._8BitAutoTiling(e,t,void 0,i):this._manager.EMPTY_INDEX,_=this._Get8BitAutoTile(e-1,t-1,"se",i),h=this._Get8BitAutoTile(e,t-1,"s",i),l=this._Get8BitAutoTile(e+1,t-1,"sw",i),a=this._Get8BitAutoTile(e-1,t,"e",i),n=this._Get8BitAutoTile(e+1,t,"w",i),r=this._Get8BitAutoTile(e-1,t+1,"ne",i),T=this._Get8BitAutoTile(e,t+1,"n",i),I=this._Get8BitAutoTile(e+1,t+1,"nw",i),E=this._manager.AUTO_TILING_PATCH;return E[0][0]=this._Get8BitTileIndex(_,e-1,t-1,i),E[1][0]=this._Get8BitTileIndex(h,e,t-1,i),E[2][0]=this._Get8BitTileIndex(l,e+1,t-1,i),E[0][1]=this._Get8BitTileIndex(a,e-1,t,i),E[1][1]=this._Get8BitTileIndex(s,e,t,i),E[2][1]=this._Get8BitTileIndex(n,e+1,t,i),E[0][2]=this._Get8BitTileIndex(r,e-1,t+1,i),E[1][2]=this._Get8BitTileIndex(T,e,t+1,i),E[2][2]=this._Get8BitTileIndex(I,e+1,t+1,i),E}_Get8BitAutoTile(e,t,i,s){return this._helper.DoesTileExist(e,t,s)?this._8BitAutoTiling(e,t,i,s):this._manager.IGNORE_INDEX}_8BitAutoTiling(e,t,i,s){this._mode===this._manager.ERASE_MODE&&(i=void 0);const _=this._manager.GetTile(e,t-1),h=this._manager.GetTile(e-1,t),l=this._manager.GetTile(e+1,t),a=this._manager.GetTile(e,t+1),n=this._manager.GetTile(e-1,t-1),r=this._manager.GetTile(e+1,t-1),T=this._manager.GetTile(e-1,t+1),I=this._manager.GetTile(e+1,t+1),E="n"===i?this._manager.FORCE_INDEX:_,G="w"===i?this._manager.FORCE_INDEX:h,g="e"===i?this._manager.FORCE_INDEX:l,u="s"===i?this._manager.FORCE_INDEX:a,d="nw"===i?this._manager.FORCE_INDEX:n,m="ne"===i?this._manager.FORCE_INDEX:r,o="sw"===i?this._manager.FORCE_INDEX:T,B="se"===i?this._manager.FORCE_INDEX:I,A=this._helper.IsTileValid(E,!0,_,s),N=this._helper.IsTileValid(G,!0,h,s),D=this._helper.IsTileValid(g,!0,l,s),p=this._helper.IsTileValid(u,!0,a,s);return 1*(A&&N?this._helper.IsTileValid(d,!0,n,s):0)+2*A+4*(A&&D?this._helper.IsTileValid(m,!0,r,s):0)+8*N+16*D+32*(p&&N?this._helper.IsTileValid(o,!0,T,s):0)+64*p+128*(p&&D?this._helper.IsTileValid(B,!0,I,s):0)}_Get8BitTileIndex(e,t,i,s){return e===this._manager.IGNORE_INDEX||e===this._manager.EMPTY_INDEX?e:this._helper.GetTileIndex(TILE_INDEX_MAP.get(e),t,i,s)}};
}

// scripts/plugins/Tilemap/c3runtime/patch.js
{
const C3=self.C3;C3.Plugins.Tilemap.Patch=class{constructor(r){this._manager=r,this._mode=r.PAINT_MODE,this._mirror=0,this._flip=0,this._diagonal=0,this._indexTransformMirror=0,this._indexTransformFlip=0,this._indexTransformDiagonal=0}SetMode(r){this._mode=r}GetMode(){return this._mode}GetBrushWidth(r){return r.tileData[0].length}GetBrushHeight(r){return r.tileData.length}TransformPatch(r,t=!1,i=!1,e=0,s=0,a=0){switch(r=this._SetTransformState(0,0,e,r),this._indexTransformMirror=this._mirror,this._indexTransformFlip=this._flip,this._indexTransformDiagonal=this._diagonal,this._diagonal&&(r=this._TransposePatch(r)),this._mirror&&(r=this._MirrorPatch(r,a===this._manager.PAINT_MODE)),this._flip&&(r=this._FlipPatch(r,a===this._manager.PAINT_MODE)),r=this._SetTransformState(t?1:0,i?1:0,0,r),e){case 0:this._indexTransformMirror=this._mirror,this._indexTransformFlip=this._flip;break;case 1:this._indexTransformMirror=1^this._mirror,this._indexTransformFlip=this._flip;break;case 2:this._indexTransformMirror=1^this._mirror,this._indexTransformFlip=1^this._flip;break;case 3:this._indexTransformMirror=this._mirror,this._indexTransformFlip=1^this._flip}return this._mirror&&(r=this._MirrorPatch(r,a===this._manager.PAINT_MODE)),this._flip&&(r=this._FlipPatch(r,a===this._manager.PAINT_MODE)),r}BuildPatch(r,t,i){const e=i.tileData[0].length,s=i.tileData.length,a=Array.from({length:s},()=>new Array(e).fill(this._manager.EMPTY_INDEX)),n=this._manager.GetProbabilityTable();n.Clear();for(let r=0;r<s;r++)for(let t=0;t<e;t++){const e=i.tileData[r][t];switch(this._mode){case this._manager.PAINT_MODE:if(1===e.length){const i=e[0][0];if(i>this._manager.GetSdkInstance().GetMaxTileIndex())continue;a[r][t]=i}else{for(let[r,t]of e)r>this._manager.GetSdkInstance().GetMaxTileIndex()||("number"!=typeof t&&(t=1),n.AddItem(t,r));a[r][t]=n.Sample()}break;case this._manager.ERASE_MODE:i.tileData[r][t][0][0]===this._manager.EMPTY_INDEX?a[r][t]=this._manager.IGNORE_INDEX:a[r][t]=this._manager.EMPTY_INDEX}}return a}_SetTransformState(r,t,i,e){switch(i){case 0:this._mirror=r,this._flip=t,this._diagonal=0;break;case 1:this._mirror=1^t,this._flip=r,this._diagonal=1;break;case 2:this._mirror=1^r,this._flip=1^t,this._diagonal=0;break;case 3:this._mirror=t,this._flip=1^r,this._diagonal=1}return e}_GetTileIndexTransformation(r){if(r===this._manager.IGNORE_INDEX||r===this._manager.EMPTY_INDEX)return r;const t=globalThis.ITilemapInstance;let i=r&t.TILE_ID_MASK;return this._indexTransformDiagonal&&(i|=t.TILE_FLIPPED_DIAGONAL),this._indexTransformMirror&&(i|=t.TILE_FLIPPED_HORIZONTAL),this._indexTransformFlip&&(i|=t.TILE_FLIPPED_VERTICAL),i}_MirrorPatch(r,t){for(let t=0;t<r.length;t++)r[t].reverse();if(t){let t=r[0].length,i=r.length;for(let e=0;e<i;e++)for(let i=0;i<t;i++){const t=this._GetTileIndexTransformation(r[e][i]);r[e][i]=t}}return r}_FlipPatch(r,t){if(r.reverse(),t){let t=r[0].length,i=r.length;for(let e=0;e<i;e++)for(let i=0;i<t;i++){const t=this._GetTileIndexTransformation(r[e][i]);r[e][i]=t}}return r}_TransposePatch(r){let t=[],i=r.length,e=r[0].length;for(let s=0;s<e;s++){let e=[];for(let t=0;t<i;t++)e.push(r[t][s]);t.push(e)}return t}};
}

// scripts/plugins/Text/c3runtime/runtime.js
{
{const e=self.C3;e.Plugins.Text=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Plugins.Text.Type=class extends e.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}LoadTextures(e){}ReleaseTextures(){}}}{const e=self.C3,t=self.C3X,i=[0,0,0],r=0,s=1,n=2,a=3,o=4,h=5,_=6,l=7,d=8,c=9,g=10,u=11,T=12,S=13,p=15,x=["left","center","right"],G=["top","center","bottom"],f=["ltr","rtl"],m=["word","cjk","character"],w=new e.Rect,I=new e.Quad2D,b=new e.Color,y=e.New(e.Vector2),R=new Map([["b","strong"],["i","em"],["s","s"],["u","u"],["iconoffsety",null]]);e.Plugins.Text.Instance=class extends e.SDKWorldInstanceBase{constructor(t,i){if(super(t),this._text="",this._enableBBcode=!0,this._faceName="Arial",this._ptSize=12,this._lineHeightOffset=0,this._isBold=!1,this._isItalic=!1,this._color=e.New(e.Color),this._horizontalAlign=0,this._verticalAlign=0,this._wrapMode="word",this._textDirection=0,this._resolutionMode="auto",this._fixedScaleFactor=1,this._iconObjectClass=null,this._htmlString="",this._isHtmlStringUpToDate=!1,this._readAloud=!1,this._screenReaderText=null,this._typewriterStartTime=-1,this._typewriterEndTime=-1,this._typewriterLength=0,this._rendererText=e.New(e.Gfx.RendererText,this._runtime.GetRenderer(),{timeout:5,textureAnisotropy:this._runtime.GetCanvasManager().GetTextureAnisotropy()}),this._rendererText.ontextureupdate=()=>this._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"),`</${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='<span class="c3-text"';const s=[];s.push(`font-family: '${this._GetFontFace()}';`),this._IsBold()&&s.push("font-weight: bold;"),this._IsItalic()&&s.push("font-style: italic;"),"character"===this._GetWrapMode()&&s.push("word-break: break-all;"),r+=` style="${s.join(" ")}">`;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","<br>")),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+=`<img class="c3-text-icon" data-icon="${s.GetIconParameter()}" width="${e.GetWidth()}" height="${e.GetHeight()}" style="${i.join(";")}" src="${n}">`}}}}const o=[...a.keys()];o.reverse();for(const e of o)r+=this._GetHTMLCloseTag(e);return r+="</span>",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/NinePatch/c3runtime/runtime.js
{
{const t=self.C3;t.Plugins.NinePatch=class extends t.SDKPluginBase{constructor(t){super(t)}Release(){super.Release()}}}{const t=self.C3;t.Plugins.NinePatch.Type=class extends t.SDKTypeBase{constructor(t){super(t),this._textureSet=null,this._leftMargin=16,this._rightMargin=16,this._topMargin=16,this._bottomMargin=16,this._drawable=null}Release(){this.ReleaseTextures(),super.Release()}OnCreate(){this.GetImageInfo().LoadAsset(this._runtime)}async LoadTextures(t){const e=this.GetImageInfo();this._drawable=await e.ExtractImageToCanvas()}ShouldCreatePatch(){return!(this._textureSet||!this._drawable)}CreatePatch(){this.ShouldCreatePatch()&&(this._textureSet=new self.NinePatchTextureSet(this._runtime),this._textureSet.CreateTextures(this._drawable,this._leftMargin,this._rightMargin,this._topMargin,this._bottomMargin))}ReleaseTextures(){this._textureSet&&(this._textureSet.Release(),this._textureSet=null)}_OnTextureSetChanged(){this.ReleaseTextures()}GetTextureSet(){return this._textureSet}_SetLeftMargin(t){t=Math.max(+t,0),this._leftMargin!==t&&(this._leftMargin=t,this._OnTextureSetChanged(),this._runtime.UpdateRender())}_GetLeftMargin(){return this._leftMargin}_SetRightMargin(t){t=Math.max(+t,0),this._rightMargin!==t&&(this._rightMargin=t,this._OnTextureSetChanged(),this._runtime.UpdateRender())}_GetRightMargin(){return this._rightMargin}_SetTopMargin(t){t=Math.max(+t,0),this._topMargin!==t&&(this._topMargin=t,this._OnTextureSetChanged(),this._runtime.UpdateRender())}_GetTopMargin(){return this._topMargin}_SetBottomMargin(t){t=Math.max(+t,0),this._bottomMargin!==t&&(this._bottomMargin=t,this._OnTextureSetChanged(),this._runtime.UpdateRender())}_GetBottomMargin(){return this._bottomMargin}}}{const t=globalThis.C3,e=globalThis.C3X,i=0,a=1,s=2,n=3,r=4,h=5,g=6,_=7,o=8,l=10,m=0,c=1,u=2,S=4,M=8,d=t.New(t.Rect),f=t.New(t.Rect),p=t.New(t.Quad2D);t.Plugins.NinePatch.Instance=class extends t.SDKWorldInstanceBase{constructor(t,e){super(t),this._leftMargin=16,this._rightMargin=16,this._topMargin=16,this._bottomMargin=16,this._edges=1,this._fill=1,this._imageScaleX=1,this._imageScaleY=1,this._seams=1,this._ownImageInfo=null,this._ownDrawable=null,this._ownTextureSet=null,this._callback3d=null,e&&(this._leftMargin=e[i],this._rightMargin=e[a],this._topMargin=e[s],this._bottomMargin=e[n],this._edges=e[r],this._fill=e[h],this._imageScaleX=e[g],this._imageScaleY=e[_],this._seams=e[l],this.GetWorldInfo().SetVisible(!!e[o]));const m=this._sdkType;m.ShouldCreatePatch()&&(m._SetLeftMargin(this._leftMargin),m._SetRightMargin(this._rightMargin),m._SetTopMargin(this._topMargin),m._SetBottomMargin(this._bottomMargin),m.CreatePatch())}Release(){this._ReleaseOwnImage(),super.Release()}_ReleaseOwnImage(){this._ownTextureSet&&(this._ownTextureSet.Release(),this._ownTextureSet=null),this._ownDrawable=null,this._ownImageInfo&&(this._ownImageInfo.GetImageAsset().DecRefCount(),this._ownImageInfo.Release(),this._ownImageInfo=null)}_Set3DCallback(t){this._callback3d=t}Draw(t){const e=this.GetWorldInfo();this._Draw(t,e.GetWidth(),e.GetHeight())}_Draw(e,i,a){let s=null;if(this._ownImageInfo)this._ownTextureSet||(this._ownTextureSet=new globalThis.NinePatchTextureSet(this._runtime),this._ownTextureSet.CreateTextures(this._ownDrawable,this._leftMargin,this._rightMargin,this._topMargin,this._bottomMargin)),s=this._ownTextureSet;else{const t=this._sdkType;if(s=t.GetTextureSet(),!s&&(t._SetLeftMargin(this._leftMargin),t._SetRightMargin(this._rightMargin),t._SetTopMargin(this._topMargin),t._SetBottomMargin(this._bottomMargin),t.CreatePatch(),s=t.GetTextureSet(),!s))return}const n=Math.abs(i),r=Math.abs(a),h=s.GetImageWidth(),g=s.GetImageHeight(),_=Math.min(this._GetLeftMargin(),h),o=Math.min(this._GetRightMargin(),h),l=Math.min(this._GetTopMargin(),g),d=Math.min(this._GetBottomMargin(),g),f=h-o,p=g-d,I=Math.min(this._GetLeftMargin()*this._imageScaleX,h),G=Math.min(this._GetRightMargin()*this._imageScaleX,h),T=Math.min(this._GetTopMargin()*this._imageScaleY,g),w=Math.min(this._GetBottomMargin()*this._imageScaleY,g),x=this._seams,R=t.clamp(n-I,0,x),b=t.clamp(n-G,0,x),P=t.clamp(r-T,0,x),C=t.clamp(r-w,0,x),v=R/this._imageScaleX,L=b/this._imageScaleX,y=P/this._imageScaleY,B=C/this._imageScaleY,X=this._edges,D=this._fill,Y=2===D?0:R,k=2===D?0:b,O=2===D?0:P,N=2===D?0:C;_>0&&l>0&&this._DrawPatch(e,i,a,s.GetTexture(),c|u,0,0,_+v,l+y,0,0,I+R,T+P),0===X&&_>0&&p>l?this._TilePatch(e,i,a,s.GetLeftTexture(),c,0,T,I+Y,r-T-w,0,0):1===X&&_>0&&p>l&&this._DrawPatch(e,i,a,s.GetTexture(),c,0,l,_,p-l,0,T,I,r-T-w),0===X&&l>0&&f>_?this._TilePatch(e,i,a,s.GetTopTexture(),u,I,0,n-I-G,T+O,0,0):1===X&&l>0&&f>_&&this._DrawPatch(e,i,a,s.GetTexture(),u,_,0,f-_,l,I,0,n-I-G,T),p>l&&f>_&&(0===D?this._TilePatch(e,i,a,s.GetFillTexture(),m,I,T,n-I-G,r-T-w,0,0):1===D&&this._DrawPatch(e,i,a,s.GetTexture(),m,_,l,f-_,p-l,I,T,n-I-G,r-T-w)),_>0&&d>0&&this._DrawPatch(e,i,a,s.GetTexture(),c|M,0,p-B,_+v,d+B,0,r-w-C,I+R,w+C),o>0&&l>0&&this._DrawPatch(e,i,a,s.GetTexture(),S|u,f-L,0,o+L,l+y,n-G-b,0,G+b,T+P),0===X&&d>0&&f>_?this._TilePatch(e,i,a,s.GetBottomTexture(),M,I,r-w-N,n-I-G,w+N,0,N):1===X&&d>0&&f>_&&this._DrawPatch(e,i,a,s.GetTexture(),M,_,p,f-_,d,I,r-w,n-I-G,w),0===X&&o>0&&p>l?this._TilePatch(e,i,a,s.GetRightTexture(),S,n-G-k,T,G+k,r-T-w,k,0):1===X&&o>0&&p>l&&this._DrawPatch(e,i,a,s.GetTexture(),S,f,l,o,p-l,n-G,T,G,r-T-w),o>0&&d>0&&this._DrawPatch(e,i,a,s.GetTexture(),S|M,f-L,p-B,o+L,d+B,n-G-b,r-w-C,G+b,w+C)}_DrawPatch(t,e,i,a,s,n,r,h,g,_,o,l,m){if(({sx:n,sy:r,sw:h,sh:g,dx:_,dy:o,dw:l,dh:m}=this._ClipEdges(e,i,s,n,r,h,g,_,o,l,m)),l<=0||m<=0||!a)return;e<0&&(_*=-1,l*=-1),i<0&&(o*=-1,m*=-1);const c=this.GetWorldInfo(),u=a.GetWidth(),S=a.GetHeight();if(t.SetTexture(a,c.GetActiveSampling()),d.set(_,o,_+l,o+m),f.set(n/u,r/S,(n+h)/u,(r+g)/S),null===this._callback3d){const e=c.GetBoundingQuad();p.setFromRotatedRect(d,c.GetAngle()),p.offset(e.getTlx(),e.getTly()),t.Quad3(p,f)}else this._callback3d(d,f)}_TilePatch(t,e,i,a,s,n,r,h,g,_,o){let l=0,m=0,c=0,u=0;if(({sx:l,sy:m,sw:c,sh:u,dx:n,dy:r,dw:h,dh:g}=this._ClipEdges(e,i,s,l,m,c,u,n,r,h,g)),_-=l*this._imageScaleX,o-=m*this._imageScaleY,h<=0||g<=0||!a)return;e<0&&(n*=-1,h*=-1),i<0&&(r*=-1,g*=-1);const S=this.GetWorldInfo(),M=a.GetWidth(),I=a.GetHeight();if(t.SetTexture(a,S.GetActiveSampling()),d.set(n,r,n+h,r+g),f.set(-_/(M*this._imageScaleX),-o/(I*this._imageScaleY),(Math.abs(h)-_)/(M*this._imageScaleX),(Math.abs(g)-o)/(I*this._imageScaleY)),null===this._callback3d){const e=S.GetBoundingQuad();p.setFromRotatedRect(d,S.GetAngle()),p.offset(e.getTlx(),e.getTly()),t.Quad3(p,f)}else this._callback3d(d,f)}_ClipEdges(t,e,i,a,s,n,r,h,g,_,o){t=Math.abs(t),e=Math.abs(e);const l=this._imageScaleX,m=this._imageScaleY,d=this.GetTextureSet(),f=d.GetImageWidth(),p=d.GetImageHeight(),I=Math.min(this._GetLeftMargin()*l,f),G=Math.min(this._GetRightMargin()*l,f),T=Math.min(this._GetTopMargin()*m,p),w=Math.min(this._GetBottomMargin()*m,p);if(i&c){const e=t-G-I;e<-I?_=0:e<0&&(n+=e/l,_+=e)}if(i&u){const t=e-w-T;t<-T?o=0:t<0&&(r+=t/m,o+=t)}if(i&S){const e=t-G;e<-G?_=0:e<0&&(n+=e/l,_+=e,a-=e/l,h-=e)}if(i&M){const t=e-w;t<-w?o=0:t<0&&(r+=t/m,o+=t,s-=t/m,g-=t)}return{sx:a,sy:s,sw:n,sh:r,dx:h,dy:g,dw:_,dh:o}}GetTextureSet(){return this._ownTextureSet||this._sdkType.GetTextureSet()}_OnTextureSetChanged(){this._ownImageInfo&&(this._ownTextureSet&&(this._ownTextureSet.Release(),this._ownTextureSet=null),this._runtime.UpdateRender())}GetCurrentImageInfo(){return this._ownImageInfo||this._objectClass.GetImageInfo()}_SetLeftMargin(t){this._ownImageInfo||this._sdkType._SetLeftMargin(t),t=Math.max(+t,0),this._leftMargin!==t&&(this._leftMargin=t,this._OnTextureSetChanged())}_GetLeftMargin(){return this._ownImageInfo?this._leftMargin:this._sdkType._GetLeftMargin()}_SetRightMargin(t){this._ownImageInfo||this._sdkType._SetRightMargin(t),t=Math.max(+t,0),this._rightMargin!==t&&(this._rightMargin=t,this._OnTextureSetChanged())}_GetRightMargin(){return this._ownImageInfo?this._rightMargin:this._sdkType._GetRightMargin()}_SetTopMargin(t){this._ownImageInfo||this._sdkType._SetTopMargin(t),t=Math.max(+t,0),this._topMargin!==t&&(this._topMargin=t,this._OnTextureSetChanged())}_GetTopMargin(){return this._ownImageInfo?this._topMargin:this._sdkType._GetTopMargin()}_SetBottomMargin(t){this._ownImageInfo||this._sdkType._SetBottomMargin(t),t=Math.max(+t,0),this._bottomMargin!==t&&(this._bottomMargin=t,this._OnTextureSetChanged())}_GetBottomMargin(){return this._ownImageInfo?this._bottomMargin:this._sdkType._GetBottomMargin()}_SetEdges(t){this._edges!==t&&(this._edges=t,this._runtime.UpdateRender())}_GetEdges(){return this._edges}_SetFill(t){this._fill!==t&&(this._fill=t,this._runtime.UpdateRender())}_GetFill(){return this._fill}_SetImageScaleX(t){this._imageScaleX!==t&&(this._imageScaleX=t,this._runtime.UpdateRender())}_GetImageScaleX(){return this._imageScaleX}_SetImageScaleY(t){this._imageScaleY!==t&&(this._imageScaleY=t,this._runtime.UpdateRender())}_GetImageScaleY(){return this._imageScaleY}_SetSeams(t){this._seams!==t&&(this._seams=t,this._runtime.UpdateRender())}_GetSeams(){return this._seams}GetPropertyValueByIndex(t){switch(t){case i:return this._GetLeftMargin();case a:return this._GetRightMargin();case s:return this._GetTopMargin();case n:return this._GetBottomMargin();case g:return this._GetImageScaleX();case _:return this._GetImageScaleY()}}SetPropertyValueByIndex(t,e){switch(t){case i:this._SetLeftMargin(e);break;case a:this._SetRightMargin(e);break;case s:this._SetTopMargin(e);break;case n:this._SetBottomMargin(e);break;case g:this._SetImageScaleX(e);break;case _:this._SetImageScaleY(e)}}GetDebuggerProperties(){const t="plugins.ninepatch.properties";return[{title:"plugins.ninepatch.name",properties:[{name:t+".left-margin.name",value:this._GetLeftMargin(),onedit:t=>this._SetLeftMargin(t)},{name:t+".right-margin.name",value:this._GetRightMargin(),onedit:t=>this._SetRightMargin(t)},{name:t+".top-margin.name",value:this._GetTopMargin(),onedit:t=>this._SetTopMargin(t)},{name:t+".bottom-margin.name",value:this._GetBottomMargin(),onedit:t=>this._SetBottomMargin(t)},{name:t+".image-scale-x.name",value:100*this._GetImageScaleX(),onedit:t=>this._SetImageScaleX(t/100)},{name:t+".image-scale-y.name",value:100*this._GetImageScaleY(),onedit:t=>this._SetImageScaleY(t/100)}]}]}GetScriptInterfaceClass(){return globalThis.I9PatchInstance}};const I=["tile","stretch"],G=["tile","stretch","transparent"],T=["exact","overlap"];globalThis.I9PatchInstance=class extends self.IWorldInstance{#t;constructor(){super(),this.#t=globalThis.IInstance._GetInitInst().GetSdkInstance()}set leftMargin(t){e.RequireFiniteNumber(t),this.#t._SetLeftMargin(t)}get leftMargin(){return this.#t._GetLeftMargin()}set rightMargin(t){e.RequireFiniteNumber(t),this.#t._SetRightMargin(t)}get rightMargin(){return this.#t._GetRightMargin()}set topMargin(t){e.RequireFiniteNumber(t),this.#t._SetTopMargin(t)}get topMargin(){return this.#t._GetTopMargin()}set bottomMargin(t){e.RequireFiniteNumber(t),this.#t._SetBottomMargin(t)}get bottomMargin(){return this.#t._GetBottomMargin()}set edges(t){const e=I.indexOf(t);if(-1===e)throw new Error("invalid edge");this.#t._SetEdges(e)}get edges(){return I[this.#t._GetEdges()]}set fill(t){const e=G.indexOf(t);if(-1===e)throw new Error("invalid fill");this.#t._SetFill(e)}get fill(){return G[this.#t._GetFill()]}set imageScaleX(t){e.RequireFiniteNumber(t),this.#t._SetImageScaleX(t)}get imageScaleX(){return this.#t._GetImageScaleX()}set imageScaleY(t){e.RequireFiniteNumber(t),this.#t._SetImageScaleY(t)}get imageScaleY(){return this.#t._GetImageScaleY()}set seams(t){const e=T.indexOf(t);if(-1===e)throw new Error("invalid seams");this.#t._SetSeams(e)}get seams(){return T[this.#t._GetSeams()]}async replaceImage(i){e.RequireInstanceOf(i,Blob);const a=this.#t,s=a.GetRuntime(),n=t.New(t.ImageInfo);await n.LoadDynamicBlobAsset(s,i),n.GetImageAsset().IncRefCount();const r=await n.ExtractImageToCanvas();a.WasReleased()?n.Release():(a._ReleaseOwnImage(),a._ownImageInfo=n,a._ownDrawable=r,s.UpdateRender())}}}self.C3.Plugins.NinePatch.Cnds={OnURLLoaded:()=>!0,OnURLFailed:()=>!0};{const t=self.C3;t.Plugins.NinePatch.Acts={SetEffect(t){this.GetWorldInfo().SetBlendMode(t),this._runtime.UpdateRender()},SetMargins(t,e,i,a){this._SetLeftMargin(t),this._SetRightMargin(e),this._SetTopMargin(i),this._SetBottomMargin(a)},SetEdges(t){this._SetEdges(t)},SetFill(t){this._SetFill(t)},SetImageScaleX(t){this._SetImageScaleX(t/100)},SetImageScaleY(t){this._SetImageScaleY(t/100)},SetSeams(t){this._SetSeams(t)},async LoadURL(e){if(this._ownImageInfo&&this._ownImageInfo.GetURL()===e)return;const i=this._runtime,a=t.New(t.ImageInfo);let s=null;try{if(await a.LoadDynamicAsset(i,e),!a.IsLoaded())throw new Error("image failed to load");if(this.WasReleased())return a.Release(),null;a.GetImageAsset().IncRefCount(),s=await a.ExtractImageToCanvas()}catch(e){return console.error("Load image from URL failed: ",e),void(this.WasReleased()||this.Trigger(t.Plugins.NinePatch.Cnds.OnURLFailed))}this.WasReleased()?a.Release():(this._ReleaseOwnImage(),this._ownImageInfo=a,this._ownDrawable=s,i.UpdateRender(),await this.TriggerAsync(t.Plugins.NinePatch.Cnds.OnURLLoaded))}}}self.C3.Plugins.NinePatch.Exps={LeftMargin(){return this._GetLeftMargin()},RightMargin(){return this._GetRightMargin()},TopMargin(){return this._GetTopMargin()},BottomMargin(){return this._GetBottomMargin()},ImageScaleX(){return 100*this._GetImageScaleX()},ImageScaleY(){return 100*this._GetImageScaleY()}};
}

// scripts/plugins/NinePatch/c3runtime/textureSet.js
{
const C3=self.C3;function CloneDrawable(e){const t=C3.CreateCanvas(e.width,e.height);return t.getContext("2d").drawImage(e,0,0),t}self.NinePatchTextureSet=class{constructor(e){this._runtime=e,this._texture=null,this._fillTexture=null,this._leftTexture=null,this._rightTexture=null,this._topTexture=null,this._bottomTexture=null,this._imageWidth=0,this._imageHeight=0,this._renderer=e.GetRenderer(),this._isLoading=!1,this._wasReleased=!1}Release(){this._renderer.IsContextLost()||(this._renderer.DeleteTexture(this._texture),this._renderer.DeleteTexture(this._fillTexture),this._renderer.DeleteTexture(this._leftTexture),this._renderer.DeleteTexture(this._rightTexture),this._renderer.DeleteTexture(this._topTexture),this._renderer.DeleteTexture(this._bottomTexture)),this._texture=null,this._fillTexture=null,this._leftTexture=null,this._rightTexture=null,this._topTexture=null,this._bottomTexture=null,this._renderer=null,this._wasReleased=!0}WasReleased(){return this._wasReleased}CreateTextures(e,t,r,i,s){this._SliceImage(e,t,r,i,s)}HasCreatedTextures(){return!!this._texture}_SliceImage(e,t,r,i,s){if(this._wasReleased)return;const a=e.width,h=e.height;this._imageWidth=a,this._imageHeight=h,t=Math.min(Math.floor(t),a),r=Math.min(Math.floor(r),a),i=Math.min(Math.floor(i),h);const u=a-r,l=h-(s=Math.min(Math.floor(s),h)),n=this._runtime.GetCanvasManager().GetTextureAnisotropy();this._texture=this._renderer.CreateStaticTexture(CloneDrawable(e),{anisotropy:n}),u>t&&l>i&&(this._fillTexture=this._renderer.CreateStaticTexture(this._SliceSubImage(CloneDrawable(e),t,i,u,l),{wrapX:"repeat",wrapY:"repeat",anisotropy:n})),t>0&&l>i&&(this._leftTexture=this._renderer.CreateStaticTexture(this._SliceSubImage(CloneDrawable(e),0,i,t,l),{wrapY:"repeat",anisotropy:n})),r>0&&l>i&&(this._rightTexture=this._renderer.CreateStaticTexture(this._SliceSubImage(CloneDrawable(e),u,i,a,l),{wrapY:"repeat",anisotropy:n})),i>0&&u>t&&(this._topTexture=this._renderer.CreateStaticTexture(this._SliceSubImage(CloneDrawable(e),t,0,u,i),{wrapX:"repeat",anisotropy:n})),s>0&&u>t&&(this._bottomTexture=this._renderer.CreateStaticTexture(this._SliceSubImage(CloneDrawable(e),t,l,u,h),{wrapX:"repeat",anisotropy:n}))}_SliceSubImage(e,t,r,i,s){const a=i-t,h=s-r,u=C3.CreateCanvas(a,h);return u.getContext("2d").drawImage(e,t,r,a,h,0,0,a,h),u}GetImageWidth(){return this._imageWidth}GetImageHeight(){return this._imageHeight}GetTexture(){return this._texture}GetFillTexture(){return this._fillTexture}GetLeftTexture(){return this._leftTexture}GetRightTexture(){return this._rightTexture}GetTopTexture(){return this._topTexture}GetBottomTexture(){return this._bottomTexture}};
}

// 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;e<t;++e)a[e].setFromJSON(n[e]);"state"===t&&this._spawnObjectClass&&(i.UpdateAllParticlesUserData(),i.ApplyParticleDataToUserData(this))}_OnAfterLoad(){const e=this._particleEngine;e.UpdateAllParticlesUserData(),e.ApplyParticleDataToUserData(this);const t=e.GetParticles();for(let e=0,i=t.length;e<i;++e){const i=t[e],n=i.GetUserData();if(!n)continue;const a=n.GetWorldInfo();if(!a)continue;const r=a.GetInstance();if(!r)continue;const s=i.GetUserDataUID(),o=r.GetUID();if(("number"!=typeof s||"number"!=typeof o||s!==o)&&"number"==typeof s){const e=this.GetRuntime(),t=e.GetInstanceByUID(s);t&&e.DestroyInstance(t)}}}Tick(){const e=this._runtime.GetDt(this._inst);this._UpdateEngineParameters(),this._isFirstTick&&"one-shot"===this._particleEngine.GetSprayType()&&this._particleEngine.ReInitAllParticles(),this._particleEngine.Tick(e),this._particleEngine.IsSpraying()&&this._runtime.UpdateRender(),this.GetWorldInfo().SetBboxChanged(),this._isFirstTick=!1}_FastForward(e){const t=1/60;for(this._isFirstTick&&"one-shot"===this._particleEngine.GetSprayType()&&this._particleEngine.ReInitAllParticles();e>0;)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;e<i;++e)t[e].Destroy();C3.appendArray(inactiveParticles,t),C3.clearArray(t),inactiveParticles.length>1e3&&C3.truncateArray(inactiveParticles,1e3),this._isSpraying=!1}CreateOneShotSpray(){for(let t=0,e=this._rate;t<e;++t)this._CreateParticle();this._particles.length&&(this._isSpraying=!0)}_CreateParticle(t=!0){let e=null;return inactiveParticles.length?(e=inactiveParticles.pop(),e.SetEngine(this)):e=C3.New(self.Particle,this),this._particles.push(e),t?e.Init(this.onparticlecreate):e.Init(),e}ReInitAllParticles(){const t=this._particles,e=this.onparticlecreate;for(let i=0,n=t.length;i<n;++i)t[i].Init(e)}UpdateAllParticlesUserData(){const t=this._particles,e=this.onparticlecreate;for(let i=0,n=t.length;i<n;++i)t[i].UpdateUserData(e)}ApplyParticleDataToUserData(t){const e=this._particles;for(let i=0,n=e.length;i<n;++i){const n=e[i],s=n.GetUserData();if(s){const e=s.GetWorldInfo();e.SetX(n.GetX()),e.SetY(n.GetY()),e.SetSize(n.GetSize(),n.GetSize()),e.SetOpacity(n.GetOpacity()),e.SetAngle(n.GetAngle()),e.SetUnpremultipliedColor(t.GetWorldInfo().GetUnpremultipliedColor()),e.SetBboxChanged()}}}SetParticleCount(t,e=!0){const i=this._particles;if(t<i.length){const e=i.length-t;for(let t=0;t<e;++t){const t=i.pop();t.Destroy(),inactiveParticles.push(t)}inactiveParticles.length>1e3&&C3.truncateArray(inactiveParticles,1e3)}else if(t>i.length){const n=t-i.length;for(let t=0;t<n;++t)this._CreateParticle(e)}}GetParticles(){return this._particles}GetParticleCount(){return this._particles.length}Tick(t){this._SpawnContinuous(t),this._TickParticles(t),this._MaybeFinishOneShot()}_SpawnContinuous(t){if("continuous-spray"===this._sprayType&&this._isSpraying){this._createCounter+=t*this._rate;const e=Math.floor(this._createCounter);this._createCounter-=e;for(let t=0;t<e;++t)this._CreateParticle()}}_SetCreateCounter(t){this._createCounter=t}_GetCreateCounter(){return this._createCounter}_TickParticles(t){const e=this._boundingBox;e.set(this._spawnX,this._spawnY,this._spawnX,this._spawnY);const i=this._particles;let n=0;for(let s=0,r=i.length;s<r;++s){const r=i[s];i[n]=r,r.Tick(t),r.IsActive()?(++n,e.expandToContain(r.GetBoundingBox())):(r.Destroy(),inactiveParticles.push(r))}C3.truncateArray(i,n),inactiveParticles.length>1e3&&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<a;++r){const a=s[r];i.intersectsRect(a.GetBoundingBox())&&a.Draw(t,e,n)}t.FinishRenderingPoints()}GetColor(){return this._color}SetRate(t){this._rate=+t}GetRate(){return this._rate}SetSprayCone(t){this._sprayCone=+t}GetSprayCone(){return this._sprayCone}SetSprayType(t){if(!VALID_SPRAY_TYPES.has(t))throw new Error("invalid spray type");this._sprayType=t}GetSprayType(){return this._sprayType}SetSpraying(t){this._isSpraying=!!t}IsSpraying(){return this._isSpraying}SetMasterOpacity(t){this._masterOpacity=+t}GetMasterOpacity(){return this._masterOpacity}SetPixelRounding(t){this._isPixelRounding=!!t}IsPixelRounding(){return this._isPixelRounding}SetSpawnX(t){this._spawnX=+t}GetSpawnX(){return this._spawnX}SetSpawnY(t){this._spawnY=+t}GetSpawnY(){return this._spawnY}SetSpawnAngle(t){this._spawnAngle=+t}GetInitAngle(){return this._spawnAngle}SetInitSpeed(t){this._initSpeed=+t}GetInitSpeed(){return this._initSpeed}SetInitSize(t){this._initSize=+t}GetInitSize(){return this._initSize}SetInitSizeScale(t){this._initSizeScale=+t}GetInitSizeScale(){return this._initSizeScale}SetInitOpacity(t){this._initOpacity=+t}GetInitOpacity(){return this._initOpacity}SetGrowRate(t){this._growRate=+t}GetGrowRate(){return this._growRate}SetInitXRandom(t){this._xRandom=+t}GetInitXRandom(){return this._xRandom}SetInitYRandom(t){this._yRandom=+t}GetInitYRandom(){return this._yRandom}SetInitSpeedRandom(t){this._initSpeedRandom=+t}GetInitSpeedRandom(){return this._initSpeedRandom}SetInitSizeRandom(t){this._initSizeRandom=+t}GetInitSizeRandom(){return this._initSizeRandom}SetGrowRandom(t){this._growRandom=+t}GetGrowRandom(){return this._growRandom}SetAcceleration(t){this._acceleration=+t}GetAcceleration(){return this._acceleration}SetGravity(t){this._gravity=+t}GetGravity(){return this._gravity}SetLifeAngleRandom(t){this._lifeAngleRandom=+t}GetLifeAngleRandom(){return this._lifeAngleRandom}SetLifeSpeedRandom(t){this._lifeSpeedRandom=+t}GetLifeSpeedRandom(){return this._lifeSpeedRandom}SetLifeOpacityRandom(t){this._lifeOpacityRandom=+t}GetLifeOpacityRandom(){return this._lifeOpacityRandom}SetDestroyMode(t){let e=DESTROY_MODES.indexOf(t);if(-1===e)throw new Error("invalid destroy mode");this._destroyMode=e}SetDestroyModeIndex(t){this.SetDestroyMode(DESTROY_MODES[t])}GetDestroyMode(){return DESTROY_MODES[this._destroyMode]}GetDestroyModeIndex(){return this._destroyMode}SetTimeout(t){this._timeout=+t}GetTimeout(){return this._timeout}SetParticleScale(t){this._particleScale=+t}GetParticleScale(){return this._particleScale}GetBoundingBox(){return this._boundingBox}GetDevicePixelRatio(){return this._devicePixelRatio}};
}

// scripts/plugins/Particles/particle.js
{
const C3=self.C3,ParticleEngine=self.ParticleEngine;function randomOffset(t){return Math.random()*t-t/2}const tmpQuad=new C3.Quad2D,tmpColor=new C3.Color;let didChangeColor=!1;self.Particle=class{constructor(t){this._engine=t,this._isActive=!1,this._x=0,this._y=0,this._speed=0,this._angle=0,this._opacity=1,this._lastOpacity=0,this._grow=0,this._size=0,this._halfSize=0,this._gs=0,this._age=0,this._bbox=new C3.Rect,this._userData=null,this._userDataUid=NaN,this._updateCallback=null,this._destroyCallback=null}SetEngine(t){this._engine=t}Init(t){const e=this._engine;this._isActive=!0,this._x=e.GetSpawnX()+randomOffset(e.GetInitXRandom()),this._y=e.GetSpawnY()+randomOffset(e.GetInitYRandom()),this._speed=e.GetInitSpeed()+randomOffset(e.GetInitSpeedRandom()),this._angle=e.GetInitAngle()+randomOffset(e.GetSprayCone()),this._opacity=e.GetInitOpacity(),this._lastOpacity=this._opacity,this._size=(e.GetInitSize()+randomOffset(e.GetInitSizeRandom()))*e.GetInitSizeScale(),this._halfSize=this._size/2,this._grow=e.GetGrowRate()+randomOffset(e.GetGrowRandom()),this._gs=0,this._age=0,this._UpdateBoundingBox(),t?this._userData||(this._userData=t(this)):(this._userData=null,this._updateCallback=null,this._destroyCallback=null)}UpdateUserData(t){t?this._userData&&!this._userData.IsDestroyed()||(this._userData=t(this,this._userDataUid)):(this._userData=null,this._updateCallback=null,this._destroyCallback=null)}SetUpdateCallback(t){this._updateCallback=t}SetDestroyCallback(t){this._destroyCallback=t}Destroy(){const t=this._destroyCallback;t&&t(this._userData),this._userData=null,this._updateCallback=null,this._destroyCallback=null}toJSON(){let t;return this._userData&&this._userData.GetWorldInfo()&&(t=this._userData.GetWorldInfo().GetInstance().GetUID()),[this._x,this._y,this._speed,this._angle,this._opacity,this._grow,this._size,this._gs,this._age,t]}setFromJSON(t){this._x=t[0],this._y=t[1],this._speed=t[2],this._angle=t[3],this._opacity=t[4],this._lastOpacity=this._opacity,this._grow=t[5],this._size=t[6],this._gs=t[7],this._age=t[8],this._userDataUid=t[9],this._halfSize=this._size/2,this._UpdateBoundingBox()}Tick(t){const e=this._engine,i=this._speed*t,s=this._angle,a=Math.cos(s)*i,h=Math.sin(s)*i+this._gs*t;this._x+=a,this._y+=h;const n=this._grow*t;this._size+=n,this._halfSize=this._size/2,this._speed+=e.GetAcceleration()*t,this._gs+=e.GetGravity()*t,this._age+=t,this._UpdateBoundingBox();const _=e.GetLifeAngleRandom(),o=e.GetLifeSpeedRandom(),l=e.GetLifeOpacityRandom();let r=0;0!==_&&(r=randomOffset(_*t),this._angle+=r),0!==o&&(this._speed+=randomOffset(o*t)),0!==l&&(this._opacity=C3.clamp(this._opacity+randomOffset(l*t),0,1));const d=this._size>=1&&(2===e.GetDestroyModeIndex()?this._speed>0:this._age<e.GetTimeout()),c=this._updateCallback;if(c&&d){let t=e.GetMasterOpacity()*this._opacity;0===e.GetDestroyModeIndex()&&(t*=1-this._age/e.GetTimeout());const i=t-this._lastOpacity;this._lastOpacity=t,c(this._userData,a,h,n,r,i)}this._isActive=d}IsActive(){return this._isActive}GetBoundingBox(){return this._bbox}_UpdateBoundingBox(){const t=this._x,e=this._y,i=this._halfSize;this._bbox.set(t-i,e-i,t+i,e+i)}Draw(t,e,i){if(this._userData)return;const s=this._engine;let a=s.GetMasterOpacity()*this._opacity;if(0===s.GetDestroyModeIndex()&&(a*=1-this._age/s.GetTimeout()),a<=0)return;const h=this._size,n=h*s.GetParticleScale()*s.GetDevicePixelRatio();if(n<1)return;let _=this._x,o=this._y;s.IsPixelRounding()&&(_=_+.5|0,o=o+.5|0),t.IsWebGPU()?t.Point(_,o,h,a):i||n>t.GetMaxPointSize()||n<t.GetMinPointSize()?(tmpColor.copy(s.GetColor()),tmpColor.multiplyAlpha(a),t.SetColor(tmpColor),didChangeColor=!0,tmpQuad.setFromRect(this._bbox),t.Quad4(tmpQuad,e)):(didChangeColor&&(t.SetColor(s.GetColor()),didChangeColor=!1),t.Point(_,o,n,a))}GetUserData(){return this._userData}GetUserDataUID(){return this._userDataUid}GetX(){return this._x}GetY(){return this._y}GetSize(){return this._size}GetAngle(){return this._angle}GetOpacity(){return this._opacity}};
}

// scripts/plugins/Browser/c3runtime/runtime.js
{
{const e=self.C3;e.Plugins.Browser=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Plugins.Browser.Type=class extends e.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t="browser";e.Plugins.Browser.Instance=class extends e.SDKInstanceBase{constructor(s,n){super(s,t),this._initLocationStr="",this._isOnline=!1,this._referrer="",this._docTitle="",this._isCookieEnabled=!1,this._screenWidth=0,this._screenHeight=0,this._windowOuterWidth=0,this._windowOuterHeight=0,this._windowHasFocus=!1,this._isConstructArcade=!1,this._cssStyleMap=new Map,this._isInstallAvailable=!1,this._installResult="",this._isWarnOnCloseEnabled=!1,this.AddDOMMessageHandlers([["online-state",e=>this._OnOnlineStateChanged(e)],["backbutton",()=>this._OnBackButton()],["sw-message",e=>this._OnSWMessage(e)],["hashchange",e=>this._OnHashChange(e)],["install-available",()=>this._OnInstallAvailable()],["app-installed",e=>this._OnAppInstalled(e)],["fullscreenerror",()=>this._OnFullscreenError()]]);const i=this.GetRuntime().Dispatcher();this._disposables=new e.CompositeDisposable(e.Disposable.From(i,"afterfirstlayoutstart",()=>this._OnAfterFirstLayoutStart()),e.Disposable.From(i,"window-resize",()=>this._OnWindowResize()),e.Disposable.From(i,"window-focus",()=>this._OnWindowFocus()),e.Disposable.From(i,"window-blur",()=>this._OnWindowBlur()),e.Disposable.From(i,"suspend",()=>this._OnSuspend()),e.Disposable.From(i,"resume",()=>this._OnResume()),e.Disposable.From(i,"windowmaximize",()=>this._OnWindowMaximized()),e.Disposable.From(i,"windowminimize",()=>this._OnWindowMinimized())),this._runtime.AddLoadPromise(this.PostToDOMAsync("get-initial-state",{"exportType":this._runtime.GetExportType()}).then(e=>{this._initLocationStr=e["location"],this._isOnline=e["isOnline"],this._referrer=e["referrer"],this._docTitle=e["title"],this._isCookieEnabled=e["isCookieEnabled"],this._screenWidth=e["screenWidth"],this._screenHeight=e["screenHeight"],this._windowOuterWidth=e["windowOuterWidth"],this._windowOuterHeight=e["windowOuterHeight"],this._windowHasFocus=e["windowHasFocus"],this._isConstructArcade=e["isConstructArcade"]}))}Release(){super.Release()}_OnAfterFirstLayoutStart(){this.PostToDOM("ready-for-sw-messages")}async _OnOnlineStateChanged(t){const s=!!t["isOnline"];this._isOnline!==s&&(this._isOnline=s,this._isOnline?await this.TriggerAsync(e.Plugins.Browser.Cnds.OnOnline):await this.TriggerAsync(e.Plugins.Browser.Cnds.OnOffline))}async _OnWindowResize(){await this.TriggerAsync(e.Plugins.Browser.Cnds.OnResize)}async _OnFullscreenError(){await this.TriggerAsync(e.Plugins.Browser.Cnds.OnFullscreenError)}async _OnWindowFocus(){this._windowHasFocus=!0,await this.TriggerAsync(e.Plugins.Browser.Cnds.OnWindowFocus)}async _OnWindowBlur(){this._windowHasFocus=!1,await this.TriggerAsync(e.Plugins.Browser.Cnds.OnWindowBlur)}async _OnWindowMaximized(){await this.TriggerAsync(e.Plugins.Browser.Cnds.OnWindowMaximized)}async _OnWindowMinimized(){await this.TriggerAsync(e.Plugins.Browser.Cnds.OnWindowMinimized)}_OnSuspend(){this.Trigger(e.Plugins.Browser.Cnds.OnPageHidden)}_OnResume(){this.Trigger(e.Plugins.Browser.Cnds.OnPageVisible)}async _OnBackButton(){await this.TriggerAsync(e.Plugins.Browser.Cnds.OnBackButton)}_OnSWMessage(t){const s=t["type"];"downloading-update"===s?this.Trigger(e.Plugins.Browser.Cnds.OnUpdateFound):"update-ready"===s||"update-pending"===s?this.Trigger(e.Plugins.Browser.Cnds.OnUpdateReady):"offline-ready"===s&&this.Trigger(e.Plugins.Browser.Cnds.OnOfflineReady)}_OnHashChange(t){this._initLocationStr=t["location"],this.Trigger(e.Plugins.Browser.Cnds.OnHashChange)}_OnInstallAvailable(){this._isInstallAvailable=!0,this.Trigger(e.Plugins.Browser.Cnds.OnInstallAvailable)}_OnAppInstalled(t){this._isInstallAvailable=!1,this.Trigger(e.Plugins.Browser.Cnds.OnAppInstalled)}_IsWarnOnCloseEnabled(){return this._isWarnOnCloseEnabled}_SetWarnOnCloseEnabled(e){e=!!e,this._isWarnOnCloseEnabled!==e&&(this._isWarnOnCloseEnabled=e,this.PostToDOM("set-warn-on-close",{"enabled":e}))}GetDebuggerProperties(){const e="plugins.browser.debugger";return[{title:"plugins.browser.name",properties:[{name:e+".user-agent",value:navigator.userAgent},{name:e+".is-online",value:this._isOnline},{name:e+".is-fullscreen",value:this._runtime.GetCanvasManager().IsDocumentFullscreen()}]}]}}}{const e=self.C3;e.Plugins.Browser.Cnds={IsOnline(){return this._isOnline},OnOnline:()=>!0,OnOffline:()=>!0,OnResize:()=>!0,OnFullscreenError:()=>!0,OnWindowFocus:()=>!0,OnWindowBlur:()=>!0,WindowHasFocus(){return this._windowHasFocus},CookiesEnabled(){return this._isCookieEnabled},IsFullscreen(){return this._runtime.GetCanvasManager().IsDocumentFullscreen()},OnBackButton:()=>!0,IsPortraitLandscape(e){return(this._runtime.GetCanvasManager().GetLastWidth()<=this._runtime.GetCanvasManager().GetLastHeight()?0:1)===e},OnUpdateFound:()=>!0,OnUpdateReady:()=>!0,OnOfflineReady:()=>!0,OnHashChange:()=>!0,OnInstallAvailable:()=>!0,IsInstallAvailable(){return this._isInstallAvailable},OnInstallResult(e){switch(e){case 0:return"accepted"===this._installResult;case 1:return"dismissed"===this._installResult;case 2:return"error"===this._installResult;case 3:return!0;default:return!1}},OnAppInstalled:()=>!0,CompareDisplayMode(e){const t=this._runtime.GetCanvasManager().GetCssDisplayMode();switch(e){case 0:return"browser"===t;case 1:return"minimal-ui"===t;case 2:return"standalone"===t;case 3:return"fullscreen"===t;default:return!1}},IsWarnOnCloseEnabled(){return this._IsWarnOnCloseEnabled()},OnWindowMaximized:()=>!0,OnWindowMinimized:()=>!0,PageVisible(){return!this._runtime.IsSuspended()},OnPageHidden:()=>!0,OnPageVisible:()=>!0,HasJava:()=>!1,IsDownloadingUpdate:()=>!1,OnMenuButton:()=>!1,OnSearchButton:()=>!1,IsMetered:()=>!1,IsCharging:()=>!0,SupportsFullscreen:()=>!0}}{const C3=self.C3,ORIENTATIONS=["portrait","landscape","portrait-primary","portrait-secondary","landscape-primary","landscape-secondary"];C3.Plugins.Browser.Acts={Alert(e){this.PostToDOM("alert",{"message":e.toString()})},Close(){this._isConstructArcade||(this._runtime.IsDebug()?self.C3Debugger.CloseWindow():this.PostToDOM("close"))},Focus(){this.PostToDOM("set-focus",{"isFocus":!0})},Blur(){this.PostToDOM("set-focus",{"isFocus":!1})},GoBack(){this._isConstructArcade||this.PostToDOM("navigate",{"type":"back"})},GoForward(){this._isConstructArcade||this.PostToDOM("navigate",{"type":"forward"})},GoHome(){},Reload(){this._isConstructArcade||(this._runtime.IsDebug()?this._runtime.PostToDebugger({"type":"reload"}):this.PostToDOM("navigate",{"type":"reload"}))},GoToURL(e,t){this._PostToDOMMaybeSync("navigate",{"type":"url","url":e,"target":t,"exportType":this._runtime.GetExportType()})},GoToURLWindow(e,t){this._PostToDOMMaybeSync("navigate",{"type":"new-window","url":e,"tag":t,"exportType":this._runtime.GetExportType()})},RequestFullScreen(e,t){const s=C3.CanvasManager._FullscreenModeNumberToString(e);this._runtime.GetCanvasManager().SetDocumentFullscreenMode(s),this._PostToDOMMaybeSync("request-fullscreen",{"navUI":t})},CancelFullScreen(){this._PostToDOMMaybeSync("exit-fullscreen")},Vibrate(e){const t=e.split(",");for(let e=0,s=t.length;e<s;++e)t[e]=parseInt(t[e],10);this._PostToDOMMaybeSync("vibrate",{"pattern":t})},InvokeDownload(e,t){if(!e||!t)return;const s=this._runtime.GetAssetManager().GetProjectFileUrl(e);this._runtime.InvokeDownload(s,t)},InvokeDownloadString(e,t,s){if(!s)return;const n=`data:${t},${encodeURIComponent(e)}`;this._runtime.InvokeDownload(n,s)},ConsoleLog(e,t){t=t.toString(),0===e?console.log(t):1===e?console.warn(t):2===e&&console.error(t)},ConsoleGroup(e){console.group(e)},ConsoleGroupEnd(){console.groupEnd()},ExecJs(jsStr){try{eval(jsStr)}catch(e){console.error("Error executing JavaScript: ",e)}},LockOrientation(e){if((e=Math.floor(e))<0||e>=ORIENTATIONS.length)return;const t=ORIENTATIONS[e];this._PostToDOMMaybeSync("lock-orientation",{"orientation":t})},UnlockOrientation(){this._PostToDOMMaybeSync("unlock-orientation")},LoadStyleSheet(e){this._runtime.GetAssetManager().LoadStyleSheet(e)},async SetDocumentCSSStyle(e,t,s,n){await this.PostToDOMAsync("set-document-css-style",{"prop":C3.CSSToCamelCase(e),"value":t,"selector":s,"is-all":0!==n})},async GetDocumentCSSStyle(e,t,s){const n=await this.PostToDOMAsync("get-document-css-style",{"prop":e,"selector":t});n["isOk"]&&this._cssStyleMap.set(s.toLowerCase(),n["result"].trim())},SetHash(e){this.PostToDOM("set-hash",{"hash":e})},SetWindowSize(e,t){this.PostToDOM("set-window-size",{"windowWidth":e,"windowHeight":t})},SetWindowPosition(e,t){this.PostToDOM("set-window-position",{"windowX":e,"windowY":t})},async RequestInstall(){const e=await this.PostToDOMAsync("request-install");this._installResult=e["result"],this.Trigger(C3.Plugins.Browser.Cnds.OnInstallResult)},SetWarnOnClose(e){this._SetWarnOnCloseEnabled(e)},MaximizeWindow(){this._runtime.SendRawWrapperExtensionMessage({"type":"maximize-window"})},MinimizeWindow(){this._runtime.SendRawWrapperExtensionMessage({"type":"minimize-window"})},RestoreWindow(){this._runtime.SendRawWrapperExtensionMessage({"type":"restore-window"})}}}{const C3=self.C3;C3.Plugins.Browser.Exps={URL(){return this._runtime.IsInWorker()?this._initLocationStr:location.toString()},Protocol(){return this._runtime.IsInWorker()?new URL(this._initLocationStr).protocol:location.protocol},Domain(){return this._runtime.IsInWorker()?new URL(this._initLocationStr).hostname:location.hostname},Port(){return this._runtime.IsInWorker()?new URL(this._initLocationStr).port:location.port},PathName(){return this._runtime.IsInWorker()?new URL(this._initLocationStr).pathname:location.pathname},Hash(){return this._runtime.IsInWorker()?new URL(this._initLocationStr).hash:location.hash},QueryString(){return this._runtime.IsInWorker()?new URL(this._initLocationStr).search:location.search},QueryParam(e){const t=this._runtime.IsInWorker()?new URL(this._initLocationStr).search:location.search,s=RegExp("[?&]"+e+"=([^&]*)").exec(t);return s?decodeURIComponent(s[1].replace(/\+/g," ")):""},Referrer(){return this._referrer},Title(){return this._docTitle},Language:()=>navigator.language,Platform:()=>navigator.platform,UserAgent:()=>navigator.userAgent,ExecJS(jsStr){let result=0;try{result=eval(jsStr)}catch(e){console.error("Error executing JavaScript: ",e)}return"number"==typeof result||"string"==typeof result?result:"boolean"==typeof result&&result?1:0},CSSStyleValue(e){return this._cssStyleMap.get(e)||""},Name:()=>navigator.appName,Version:()=>navigator.appVersion,Product:()=>navigator.product,Vendor:()=>navigator.vendor,BatteryLevel:()=>1,BatteryTimeLeft:()=>1/0,Bandwidth(){const e=navigator["connection"];return e&&(e["downlink"]||e["downlinkMax"]||e["bandwidth"])||1/0},ConnectionType(){const e=navigator["connection"];return e&&e["type"]||"unknown"},DevicePixelRatio:()=>self.devicePixelRatio,ScreenWidth(){return this._screenWidth},ScreenHeight(){return this._screenHeight},WindowInnerWidth(){return this._runtime.GetCanvasManager().GetLastWidth()},WindowInnerHeight(){return this._runtime.GetCanvasManager().GetLastHeight()},WindowOuterWidth(){return this._windowOuterWidth},WindowOuterHeight(){return this._windowOuterWidth},DisplayMode(){return this._runtime.GetCanvasManager().GetCssDisplayMode()},InstallResult(){return this._installResult}}}
}

// scripts/plugins/PlatformInfo/c3runtime/runtime.js
{
{const e=self.C3;e.Plugins.PlatformInfo=class extends e.SDKPluginBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Plugins.PlatformInfo.Type=class extends e.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t="platform-info";e.Plugins.PlatformInfo.Instance=class extends e.SDKInstanceBase{constructor(e,n){super(e,t),this._screenWidth=0,this._screenHeight=0,this._windowOuterWidth=0,this._windowOuterHeight=0,this._safeAreaInset=[0,0,0,0],this._supportsWakeLock=!1,this._isWakeLockActive=!1,this.AddDOMMessageHandlers([["window-resize",e=>this._OnWindowResize(e)],["wake-lock-acquired",e=>this._OnWakeLockAcquired(e)],["wake-lock-error",e=>this._OnWakeLockError(e)],["wake-lock-released",e=>this._OnWakeLockReleased(e)]]),navigator.connection&&navigator.connection.addEventListener("change",()=>this._OnNetworkChange()),this._runtime.AddLoadPromise(this.PostToDOMAsync("get-initial-state").then(e=>{this._screenWidth=e["screenWidth"],this._screenHeight=e["screenHeight"],this._windowOuterWidth=e["windowOuterWidth"],this._windowOuterHeight=e["windowOuterHeight"],this._safeAreaInset=e["safeAreaInset"],this._supportsWakeLock=e["supportsWakeLock"]}))}Release(){super.Release()}_OnWindowResize(e){this._windowOuterWidth=e["windowOuterWidth"],this._windowOuterHeight=e["windowOuterHeight"],this._safeAreaInset=e["safeAreaInset"]}async _OnNetworkChange(){await this.TriggerAsync(e.Plugins.PlatformInfo.Cnds.OnNetworkChange)}async _OnWakeLockAcquired(){this._isWakeLockActive=!0,await this.TriggerAsync(e.Plugins.PlatformInfo.Cnds.OnWakeLockAcquired)}async _OnWakeLockError(){this._isWakeLockActive=!1,await this.TriggerAsync(e.Plugins.PlatformInfo.Cnds.OnWakeLockError)}async _OnWakeLockReleased(){this._isWakeLockActive=!1,await this.TriggerAsync(e.Plugins.PlatformInfo.Cnds.OnWakeLockReleased)}}}{const e=self.C3;e.Plugins.PlatformInfo.Cnds={IsOnMobile:()=>e.Platform.IsMobile,IsOnWindows:()=>"Windows"===e.Platform.OS,IsOnMacOS:()=>"macOS"===e.Platform.OS,IsOnLinux:()=>"Linux"===e.Platform.OS,IsOnChromeOS:()=>"Chrome OS"===e.Platform.OS,IsOnAndroid:()=>"Android"===e.Platform.OS,IsOniOS:()=>"iOS"===e.Platform.OS,IsWebExport(){const e=this._runtime.GetExportType();return"html5"===e||"scirra-arcade"===e||"preview"===e||"instant-games"===e},IsCordovaExport(){return this._runtime.IsCordova()},IsNWjsExport:()=>!1,IsWindowsUWPExport(){return"windows-uwp"===this._runtime.GetExportType()},IsWindowsWebView2Export(){return this._runtime.IsWindowsWebView2()},IsMacOSWKWebView2Export(){return"macos-wkwebview"===this._runtime.GetExportType()},IsLinuxCEFExport(){return"linux-cef"===this._runtime.GetExportType()},OnNetworkChange:()=>!0,OnWakeLockAcquired:()=>!0,OnWakeLockError:()=>!0,OnWakeLockReleased:()=>!0,IsWakeLockActive(){return this._isWakeLockActive},IsWakeLockSupported(){return this._supportsWakeLock}}}self.C3.Plugins.PlatformInfo.Acts={RequestWakeLock(){this._supportsWakeLock&&this._PostToDOMMaybeSync("request-wake-lock")},ReleaseWakeLock(){this._supportsWakeLock&&(this._isWakeLockActive=!1,this.PostToDOM("release-wake-lock"))}};self.C3.Plugins.PlatformInfo.Exps={Renderer(){return this._runtime.GetCanvasManager().GetRendererString()},RendererDetail(){return this._runtime.GetCanvasManager().GetRendererDetailString()},DevicePixelRatio(){return this._runtime.GetDevicePixelRatio()},ScreenWidth(){return this._screenWidth},ScreenHeight(){return this._screenHeight},WindowInnerWidth(){return this._runtime.GetCanvasManager().GetLastWidth()},WindowInnerHeight(){return this._runtime.GetCanvasManager().GetLastHeight()},WindowOuterWidth(){return this._windowOuterWidth},WindowOuterHeight(){return this._windowOuterHeight},CanvasCssWidth(){return this._runtime.GetCanvasManager().GetCssWidth()},CanvasCssHeight(){return this._runtime.GetCanvasManager().GetCssHeight()},CanvasDeviceWidth(){return this._runtime.GetCanvasManager().GetDeviceWidth()},CanvasDeviceHeight(){return this._runtime.GetCanvasManager().GetDeviceHeight()},Downlink:()=>navigator.connection&&navigator.connection["downlink"]||0,DownlinkMax:()=>navigator.connection&&navigator.connection["downlinkMax"]||0,ConnectionType:()=>navigator.connection&&navigator.connection["type"]||"unknown",ConnectionEffectiveType:()=>navigator.connection&&navigator.connection["effectiveType"]||"unknown",ConnectionRTT:()=>navigator.connection&&navigator.connection["rtt"]||0,HardwareConcurrency:()=>navigator.hardwareConcurrency||0,DeviceMemory:()=>navigator.deviceMemory||0,SafeAreaInsetTop(){return this._safeAreaInset[0]},SafeAreaInsetRight(){return this._safeAreaInset[1]},SafeAreaInsetBottom(){return this._safeAreaInset[2]},SafeAreaInsetLeft(){return this._safeAreaInset[3]},FramesPerSecond(){return this._runtime.GetFramesPerSecond()},TicksPerSecond(){return this._runtime.GetTicksPerSecond()}};
}

// scripts/plugins/sliderbar/c3runtime/runtime.js
{
{const e=self.C3,t="sliderbar";e.Plugins.sliderbar=class extends e.SDKDOMPluginBase{constructor(e){super(e,t),this.AddElementMessageHandler("click",(e,t)=>e._OnClick(t)),this.AddElementMessageHandler("change",(e,t)=>e._OnChange(t)),this.AddElementMessageHandler("input",(e,t)=>e._OnInput(t))}Release(){super.Release()}}}{const e=self.C3;e.Plugins.sliderbar.Type=class extends e.SDKTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t=self.C3X,i=0,s=1,a=2,n=3,r=4,l=5,h=6,u=7,m=8,_="sliderbar";e.Plugins.sliderbar.Instance=class extends e.SDKDOMInstanceBase{constructor(e,t){super(e,_),this._value=0,this._min=0,this._max=100,this._step=1,this._title="",this._isEnabled=!0,this._id="",this._className="",t&&(this._value=t[i],this._min=t[s],this._max=t[a],this._step=t[n],this._title=t[r],this.GetWorldInfo().SetVisible(t[l]),this._isEnabled=t[h],this._id=t[u],this._className=t[m]),this.CreateElement({"id":this._id,"className":this._className})}Release(){super.Release()}GetElementState(){return{"value":this._value,"min":this._min,"max":this._max,"step":this._step,"title":this._title,"isEnabled":this._isEnabled}}async _OnClick(t){this.DispatchScriptEvent("click",!0),await this.TriggerAsync(e.Plugins.sliderbar.Cnds.OnClicked)}async _OnChange(t){this._value=t["value"],this.DispatchScriptEvent("change",!0),await this.TriggerAsync(e.Plugins.sliderbar.Cnds.OnChanged)}async _OnInput(t){this._value=t["value"],this.DispatchScriptEvent("input",!0),await this.TriggerAsync(e.Plugins.sliderbar.Cnds.OnChanging)}Draw(e){}_SetValue(e){this._value!==e&&(this._value=e,this.UpdateElementState())}_GetValue(){return this._value}_SetMaximum(e){this._max!==e&&(this._max=e,this.UpdateElementState())}_GetMaximum(){return this._max}_SetMinimum(e){this._min!==e&&(this._min=e,this.UpdateElementState())}_GetMinimum(){return this._min}_SetTooltip(e){this._title!==e&&(this._title=e,this.UpdateElementState())}_GetTooltip(){return this._title}_SetStep(e){this._step!==e&&(this._step=e,this.UpdateElementState())}_GetStep(){return this._step}_SetEnabled(e){e=!!e,this._isEnabled!==e&&(this._isEnabled=e,this.UpdateElementState())}_IsEnabled(){return this._isEnabled}SaveToJson(){return{"v":this._value,"min":this._min,"max":this._max,"s":this._step,"t":this._title,"e":this._isEnabled,"id":this._id}}LoadFromJson(e){this._value=e["v"],this._min=e["min"],this._max=e["max"],this._step=e["s"],this._title=e["t"],this._isEnabled=e["e"],this._id=e["id"],this.UpdateElementState()}GetPropertyValueByIndex(e){switch(e){case i:return this._GetValue();case s:return this._GetMinimum();case a:return this._GetMaximum();case n:return this._GetStep();case r:return this._GetTooltip();case h:return this._IsEnbled()}}SetPropertyValueByIndex(e,t){switch(e){case i:this._SetValue(t);break;case s:this._SetMinimum(t);break;case a:this._SetMaximum(t);break;case n:this._SetStep(t);break;case r:this._SetTooltip(t);break;case h:this._SetEnabled(t)}}GetDebuggerProperties(){e.Plugins.sliderbar.Acts;const t="plugins.sliderbar";return[{title:t+".name",properties:[{name:t+".properties.value.name",value:this._GetValue(),onedit:e=>this._SetValue(e)},{name:t+".properties.minimum.name",value:this._GetMinimum(),onedit:e=>this._SetMinimum(e)},{name:t+".properties.maximum.name",value:this._GetMaximum(),onedit:e=>this._SetMaximum(e)},{name:t+".properties.step.name",value:this._GetStep(),onedit:e=>this._SetStep(e)},{name:t+".properties.enabled.name",value:this._IsEnabled(),onedit:e=>this._SetEnabled(e)}]}]}GetScriptInterfaceClass(){return self.ISliderBarInstance}};const d=new WeakMap;self.ISliderBarInstance=class extends self.IDOMInstance{constructor(){super(),d.set(this,self.IInstance._GetInitInst().GetSdkInstance())}set value(e){t.RequireFiniteNumber(e),d.get(this)._SetValue(e)}get value(){return d.get(this)._GetValue()}set maximum(e){t.RequireFiniteNumber(e),d.get(this)._SetMaximum(e)}get maximum(){return d.get(this)._GetMaximum()}set minimum(e){t.RequireFiniteNumber(e),d.get(this)._SetMinimum(e)}get minimum(){return d.get(this)._GetMinimum()}set step(e){t.RequireFiniteNumber(e),d.get(this)._SetStep(e)}get step(){return d.get(this)._GetStep()}set tooltip(e){t.RequireString(e),d.get(this)._SetTooltip(e)}get tooltip(){return d.get(this)._GetTooltip()}set isEnabled(e){d.get(this)._SetEnabled(e)}get isEnabled(){return d.get(this)._IsEnabled()}}}{const e=self.C3;e.Plugins.sliderbar.Cnds={OnClicked:()=>!0,OnChanged:()=>!0,OnChanging:()=>!0,CompareValue(t,i){return e.compare(this._GetValue(),t,i)}}}self.C3.Plugins.sliderbar.Acts={SetTooltip(e){this._SetTooltip(e)},SetValue(e){this._SetValue(e)},SetMaximum(e){this._SetMaximum(e)},SetMinimum(e){this._SetMinimum(e)},SetStep(e){this._SetStep(e)}};self.C3.Plugins.sliderbar.Exps={Value(){return this._GetValue()},Maximum(){return this._GetMaximum()},Minimum(){return this._GetMinimum()},Step(){return this._GetStep()}};
}

// scripts/behaviors/Fade/c3runtime/runtime.js
{
{const t=self.C3;t.Behaviors.Fade=class extends t.SDKBehaviorBase{constructor(t){super(t)}Release(){super.Release()}}}{const t=self.C3;t.Behaviors.Fade.Type=class extends t.SDKBehaviorTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}}}{const t=self.C3,e=self.C3X,i=self.IBehaviorInstance,s=0,a=1,h=2,r=3,n=4;t.Behaviors.Fade.Instance=class extends t.SDKBehaviorInstanceBase{constructor(e,i){super(e),this._fadeInTime=0,this._waitTime=0,this._fadeOutTime=0,this._destroy=!0,this._activeAtStart=!0,this._setMaxOpacity=!1,this._stage=0,this._stageTime=t.New(t.KahanSum),this._maxOpacity=this._inst.GetWorldInfo().GetOpacity()||1,i&&(this._fadeInTime=i[s],this._waitTime=i[a],this._fadeOutTime=i[h],this._destroy=!!i[r],this._activeAtStart=!!i[n],this._stage=this._activeAtStart?0:3),this._activeAtStart&&(0===this._fadeInTime?(this._stage=1,0===this._waitTime&&(this._stage=2)):(this._inst.GetWorldInfo().SetOpacity(0),this._runtime.UpdateRender())),this._StartTicking()}Release(){super.Release()}SaveToJson(){return{"fit":this._fadeInTime,"wt":this._waitTime,"fot":this._fadeOutTime,"d":this._destroy,"s":this._stage,"st":this._stageTime.Get(),"mo":this._maxOpacity}}LoadFromJson(t){this._fadeInTime=t["fit"],this._waitTime=t["wt"],this._fadeOutTime=t["fot"],this._destroy=t["d"],this._stage=t["s"],this._stageTime.Set(t["st"]),this._maxOpacity=t["mo"],3===this._stage?this._StopTicking():this._StartTicking()}Tick(){const e=this._runtime.GetDt(this._inst);this._stageTime.Add(e);const i=this._inst.GetWorldInfo();0===this._stage&&(i.SetOpacity(this._stageTime.Get()/this._fadeInTime*this._maxOpacity),this._runtime.UpdateRender(),i.GetOpacity()>=this._maxOpacity&&(i.SetOpacity(this._maxOpacity),this._stage=1,this._stageTime.Reset(),this.DispatchScriptEvent("fadeinend"),this.Trigger(t.Behaviors.Fade.Cnds.OnFadeInEnd))),1===this._stage&&this._stageTime.Get()>=this._waitTime&&(this._stage=2,this._stageTime.Reset(),this.DispatchScriptEvent("waitend"),this.Trigger(t.Behaviors.Fade.Cnds.OnWaitEnd)),2===this._stage&&(0!==this._fadeOutTime?(i.SetOpacity(this._maxOpacity-this._stageTime.Get()/this._fadeOutTime*this._maxOpacity),this._runtime.UpdateRender(),i.GetOpacity()<=0&&(this._stage=3,this._stageTime.Reset(),this.DispatchScriptEvent("fadeoutend"),this.Trigger(t.Behaviors.Fade.Cnds.OnFadeOutEnd),this._destroy&&this._runtime.DestroyInstance(this._inst))):(this._stage=3,this._stageTime.Reset())),3===this._stage&&this._StopTicking()}_StartFade(){this._activeAtStart||this._setMaxOpacity||(this._maxOpacity=this._inst.GetWorldInfo().GetOpacity()||1,this._setMaxOpacity=!0),3===this._stage&&this.Start()}_RestartFade(){this.Start()}Start(){this._stage=0,this._stageTime.Reset(),0===this._fadeInTime?(this._stage=1,0===this._waitTime&&(this._stage=2)):(this._inst.GetWorldInfo().SetOpacity(0),this._runtime.UpdateRender()),this._StartTicking()}_SetFadeInTime(t){this._fadeInTime=Math.max(t,0)}_GetFadeInTime(){return this._fadeInTime}_SetWaitTime(t){this._waitTime=Math.max(t,0)}_GetWaitTime(){return this._waitTime}_SetFadeOutTime(t){this._fadeOutTime=Math.max(t,0)}_GetFadeOutTime(){return this._fadeOutTime}GetPropertyValueByIndex(t){switch(t){case s:return this._GetFadeInTime();case a:return this._GetWaitTime();case h:return this._GetFadeOutTime();case r:return this._destroy}}SetPropertyValueByIndex(t,e){switch(t){case s:this._SetFadeInTime(e);break;case a:this._SetWaitTime(e);break;case h:this._SetFadeOutTime(e);break;case r:this._destroy=!!e}}GetDebuggerProperties(){const t="behaviors.fade";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:t+".properties.fade-in-time.name",value:this._GetFadeInTime(),onedit:t=>this._SetFadeInTime(t)},{name:t+".properties.wait-time.name",value:this._GetWaitTime(),onedit:t=>this._SetWaitTime(t)},{name:t+".properties.fade-out-time.name",value:this._GetFadeOutTime(),onedit:t=>this._SetFadeOutTime(t)},{name:t+".debugger.stage",value:[t+".debugger."+["fade-in","wait","fade-out","done"][this._stage]]}]}]}GetScriptInterfaceClass(){return self.IFadeBehaviorInstance}};const _=new WeakMap;self.IFadeBehaviorInstance=class extends i{constructor(){super(),_.set(this,i._GetInitInst().GetSdkInstance())}startFade(){_.get(this)._StartFade()}restartFade(){_.get(this)._RestartFade()}set fadeInTime(t){e.RequireFiniteNumber(t),_.get(this)._SetFadeInTime(t)}get fadeInTime(){return _.get(this)._GetFadeInTime()}set waitTime(t){e.RequireFiniteNumber(t),_.get(this)._SetWaitTime(t)}get waitTime(){return _.get(this)._GetWaitTime()}set fadeOutTime(t){e.RequireFiniteNumber(t),_.get(this)._SetFadeOutTime(t)}get fadeOutTime(){return _.get(this)._GetFadeOutTime()}}}self.C3.Behaviors.Fade.Cnds={OnFadeOutEnd:()=>!0,OnFadeInEnd:()=>!0,OnWaitEnd:()=>!0};self.C3.Behaviors.Fade.Acts={StartFade(){this._StartFade()},RestartFade(){this._RestartFade()},SetFadeInTime(t){this._SetFadeInTime(t)},SetWaitTime(t){this._SetWaitTime(t)},SetFadeOutTime(t){this._SetFadeOutTime(t)}};self.C3.Behaviors.Fade.Exps={FadeInTime(){return this._GetFadeInTime()},WaitTime(){return this._GetWaitTime()},FadeOutTime(){return this._GetFadeOutTime()}};
}

// scripts/behaviors/Bullet/c3runtime/runtime.js
{
{const t=self.C3;t.Behaviors.Bullet=class extends t.SDKBehaviorBase{constructor(t){super(t)}Release(){super.Release()}}}{const t=self.C3;t.Behaviors.Bullet.Type=class extends t.SDKBehaviorTypeBase{constructor(t){super(t)}Release(){super.Release()}OnCreate(){}}}{const t=self.C3,e=self.C3X,i=self.IBehaviorInstance,s=0,n=1,h=2,r=3,a=4,_=5,o=6;t.Behaviors.Bullet.Instance=class extends t.SDKBehaviorInstanceBase{constructor(t,e){super(t);const i=this.GetWorldInfo();this._speed=0,this._acc=0,this._g=0,this._gx=0,this._gy=1,this._gz=0,this._bounceOffSolid=!1,this._setAngle=!1,this._isStepping=!1,this._isEnabled=!0,this._dx=0,this._dy=0,this._dz=0,this._lastX=i.GetX(),this._lastY=i.GetY(),this._lastKnownAngle=i.GetAngle(),this._travelled=0,this._stepSize=Math.min(Math.abs(i.GetWidth()),Math.abs(i.GetHeight())/2),this._stopStepping=!1,e&&(this._speed=e[s],this._acc=e[n],this._g=e[h],this._bounceOffSolid=!!e[r],this._setAngle=!!e[a],this._isStepping=!!e[_],this._isEnabled=!!e[o]);const d=i.GetAngle();this._dx=Math.cos(d)*this._speed,this._dy=Math.sin(d)*this._speed,this._isEnabled&&(this._StartTicking(),this._bounceOffSolid&&this._StartPostTicking())}Release(){super.Release()}SaveToJson(){const t={"dx":this._dx,"dy":this._dy,"dz":this._dz,"lx":this._lastX,"ly":this._lastY,"lka":this._lastKnownAngle,"t":this._travelled};return 0!==this._acc&&(t["acc"]=this._acc),0!==this._g&&(t["g"]=this._g),this._isStepping&&(t["st"]=this._isStepping),this._isEnabled||(t["e"]=this._isEnabled),this._bounceOffSolid&&(t["bos"]=this._bounceOffSolid),this._setAngle&&(t["sa"]=this._setAngle),t}LoadFromJson(t){this._dx=t["dx"],this._dy=t["dy"],t.hasOwnProperty("dz")&&(this._dz=t["dz"]),this._lastX=t["lx"],this._lastY=t["ly"],this._lastKnownAngle=t["lka"],this._travelled=t["t"],this._acc=t.hasOwnProperty("acc")?t["acc"]:0,this._g=t.hasOwnProperty("g")?t["g"]:0,this._isStepping=!!t.hasOwnProperty("st")&&t["st"],this._bounceOffSolid=!!t.hasOwnProperty("bos")&&t["bos"],this._setAngle=!!t.hasOwnProperty("sa")&&t["sa"],this._SetEnabled(!t.hasOwnProperty("e")||t["e"])}Tick(){if(!this._isEnabled)return;const e=this._runtime.GetDt(this._inst),i=this._inst.GetWorldInfo();if(i.GetAngle()!==this._lastKnownAngle){const e=i.GetAngle();if(this._setAngle){const i=t.distanceTo(0,0,this._dx,this._dy);this._dx=Math.cos(e)*i,this._dy=Math.sin(e)*i}this._lastKnownAngle=e}let s=0,n=0,h=0;if(0!==this._acc){const r=t.distanceTo3d(0,0,0,this._dx,this._dy,this._dz);let a=this._dx/r,_=this._dy/r,o=this._dz/r;if(0===this._dx&&0===this._dy&&0===this._dz){const t=i.GetAngle();a=Math.cos(t),_=Math.sin(t),o=0}s=a*this._acc,n=_*this._acc,h=o*this._acc;const d=Math.sign(this._dx),l=Math.sign(this._dy),c=Math.sign(this._dz);this._dx+=s*e,this._dy+=n*e,this._dz+=h*e,d!==Math.sign(this._dx)&&(this._dx=0,s=0),l!==Math.sign(this._dy)&&(this._dy=0,n=0),c!==Math.sign(this._dz)&&(this._dz=0,h=0)}if(0!==this._g&&(this._dx+=this._gx*this._g*e,this._dy+=this._gy*this._g*e,this._dz+=this._gz*this._g*e,s+=this._gx*this._g,n+=this._gy*this._g,h+=this._gz*this._g),this._lastX=i.GetX(),this._lastY=i.GetY(),0!==this._dx||0!==this._dy||0!==this._dz){const r=this._dx*e+.5*s*e*e,a=this._dy*e+.5*n*e*e,_=this._dz*e+.5*h*e*e,o=t.distanceTo3d(0,0,0,r,a,_);if(this.#t(r,a,_,o),this._travelled+=o,this._setAngle&&(0!==r||0!==a)){const e=t.angleTo(0,0,r,a);i.SetAngle(e),this._lastKnownAngle=i.GetAngle()}i.SetBboxChanged()}}#t(e,i,s,n){const h=this.GetWorldInfo();if(!this._isStepping||n<=this._stepSize)return h.OffsetXYZ(e,i,s),h.SetBboxChanged(),void(this._isStepping&&this.Trigger(t.Behaviors.Bullet.Cnds.OnStep));this._stopStepping=!1;const r=h.GetX(),a=h.GetY(),_=h.GetZ(),o=r+e,d=a+i,l=_+s,c=this._stepSize/n,g=e*c,u=i*c,S=s*c,p=Math.floor(n/this._stepSize);for(let e=1;e<=p;++e)if(h.SetXYZ(r+g*e,a+u*e,_*S*e),h.SetBboxChanged(),this.Trigger(t.Behaviors.Bullet.Cnds.OnStep),this._inst.IsDestroyed()||this._stopStepping)return;h.SetXYZ(o,d,l),h.SetBboxChanged(),this.Trigger(t.Behaviors.Bullet.Cnds.OnStep)}PostTick(){if(!this._isEnabled||!this._bounceOffSolid||0===this._dx&&0===this._dy)return;const e=this._runtime.GetDt(this._inst),i=this._inst.GetWorldInfo(),s=this._runtime.GetCollisionEngine(),n=s.TestOverlapSolid(this._inst);if(n){s.RegisterCollision(this._inst,n);const h=t.distanceTo(0,0,this._dx,this._dy),r=s.CalculateBounceAngle(this._inst,this._lastX,this._lastY);this._dx=Math.cos(r)*h,this._dy=Math.sin(r)*h,i.OffsetXY(this._dx*e,this._dy*e),i.SetBboxChanged(),this._setAngle&&(i.SetAngle(r),this._lastKnownAngle=i.GetAngle(),i.SetBboxChanged()),s.PushOutSolid(this._inst,this._dx/h,this._dy/h,Math.max(2.5*h*e,30))||s.PushOutSolidNearest(this._inst,100)}}GetPropertyValueByIndex(t){switch(t){case s:return this._GetSpeed();case n:return this._GetAcceleration();case h:return this._GetGravity();case a:return this._setAngle;case _:return this._isStepping;case o:return this._IsEnabled()}}SetPropertyValueByIndex(t,e){switch(t){case s:this._SetSpeed(e);break;case n:this._acc=e;break;case h:this._g=e;break;case a:this._setAngle=!!e;break;case _:this._isStepping=!!e;break;case o:this._SetEnabled(!!e)}}_SetSpeed(e){const i=t.distanceTo3d(0,0,0,this._dx,this._dy,this._dz);if(0===i)this._dx=e,this._dy=0,this._dz=0;else{const t=e/i;this._dx*=t,this._dy*=t,this._dz*=t}}_GetSpeedExact(){return t.distanceTo3d(0,0,0,this._dx,this._dy,this._dz)}_GetSpeed(){return t.roundToDp(this._GetSpeedExact(),6)}_SetVector(t,e,i){this._dx=t,this._dy=e,this._dz=i}_GetVector(){return[this._dx,this._dy,this._dz]}_SetAcceleration(t){this._acc=t}_GetAcceleration(){return this._acc}_SetGravity(t){this._g=t}_GetGravity(){return this._g}_SetGravityVector(e,i,s){const n=t.distanceTo3d(0,0,0,e,i,s);0===n?(this._gx=0,this._gy=0,this._gz=0):(this._gx=e/n,this._gy=i/n,this._gz=s/n)}_GetGravityVector(){return[this._gx,this._gy,this._gz]}_SetAngleOfMotion(e){const i=t.distanceTo(0,0,this._dx,this._dy);this._dx=Math.cos(e)*i,this._dy=Math.sin(e)*i}_GetAngleOfMotion(){return t.angleTo(0,0,this._dx,this._dy)}_SetBounceOffSolids(t){t=!!t,this._bounceOffSolid!==t&&(this._bounceOffSolid=t,this._isEnabled&&(this._bounceOffSolid?this._StartPostTicking():this._StopPostTicking()))}_IsBounceOffSolids(){return this._bounceOffSolid}_SetDistanceTravelled(t){this._travelled=t}_GetDistanceTravelled(){return this._travelled}_SetEnabled(t){this._isEnabled=!!t,this._isEnabled?(this._StartTicking(),this._bounceOffSolid&&this._StartPostTicking()):(this._StopTicking(),this._StopPostTicking())}_IsEnabled(){return this._isEnabled}GetDebuggerProperties(){const e="behaviors.bullet";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:e+".debugger.vector-x",value:this._dx,onedit:t=>this._dx=t},{name:e+".debugger.vector-y",value:this._dy,onedit:t=>this._dy=t},{name:e+".debugger.vector-z",value:this._dz,onedit:t=>this._dz=t},{name:e+".properties.speed.name",value:this._GetSpeed(),onedit:t=>this._SetSpeed(t)},{name:e+".debugger.angle-of-motion",value:t.toDegrees(this._GetAngleOfMotion())},{name:e+".properties.gravity.name",value:this._GetGravity(),onedit:t=>this._SetGravity(t)},{name:e+".debugger.gravity-vector-x",value:this._gx},{name:e+".debugger.gravity-vector-y",value:this._gy},{name:e+".debugger.gravity-vector-z",value:this._gz},{name:e+".properties.acceleration.name",value:this._GetAcceleration(),onedit:t=>this._SetAcceleration(t)},{name:e+".debugger.distance-travelled",value:this._GetDistanceTravelled()},{name:e+".properties.enabled.name",value:this._IsEnabled(),onedit:t=>this._SetEnabled(t)}]}]}GetScriptInterfaceClass(){return self.IBulletBehaviorInstance}},self.IBulletBehaviorInstance=class extends i{#e;constructor(){super(),this.#e=i._GetInitInst().GetSdkInstance()}get speed(){return this.#e._GetSpeed()}set speed(t){e.RequireFiniteNumber(t),this.#e._SetSpeed(t)}get acceleration(){return this.#e._GetAcceleration()}set acceleration(t){e.RequireFiniteNumber(t),this.#e._SetAcceleration(t)}get gravity(){return this.#e._GetGravity()}set gravity(t){e.RequireFiniteNumber(t),this.#e._SetGravity(t)}setGravityVector(t,i,s){e.RequireFiniteNumber(t),e.RequireFiniteNumber(i),e.RequireFiniteNumber(s),this.#e._SetGravityVector(t,i,s)}getGravityVector(){return this.#e._GetGravityVector()}get angleOfMotion(){return this.#e._GetAngleOfMotion()}set angleOfMotion(t){e.RequireFiniteNumber(t),this.#e._SetAngleOfMotion(t)}get bounceOffSolids(){return this.#e._IsBounceOffSolids()}set bounceOffSolids(t){this.#e._SetBounceOffSolids(!!t)}get distanceTravelled(){return this.#e._GetDistanceTravelled()}set distanceTravelled(t){e.RequireFiniteNumber(t),this.#e._SetDistanceTravelled(t)}get isEnabled(){return this.#e._IsEnabled()}set isEnabled(t){this.#e._SetEnabled(t)}setVector(t,i,s=0){e.RequireFiniteNumber(t),e.RequireFiniteNumber(i),e.RequireFiniteNumber(s),this.#e._SetVector(t,i,s)}getVector(){return this.#e._GetVector()}}}{const t=self.C3;t.Behaviors.Bullet.Cnds={CompareSpeed(e,i){return t.compare(this._GetSpeedExact(),e,i)},CompareTravelled(e,i){return t.compare(this._GetDistanceTravelled(),e,i)},OnStep:()=>!0,IsEnabled(){return this._IsEnabled()}}}{const t=self.C3;t.Behaviors.Bullet.Acts={SetSpeed(t){this._SetSpeed(t)},SetAcceleration(t){this._SetAcceleration(t)},SetGravity(t){this._SetGravity(t)},SetAngleOfMotion(e){this._SetAngleOfMotion(t.toRadians(e))},Bounce(e){if(!e)return;const i=e.GetFirstPicked(this._inst);if(!i)return;const s=this._inst.GetWorldInfo(),n=this._runtime.GetCollisionEngine(),h=this._runtime.GetDt(this._inst),r=t.distanceTo(0,0,this._dx,this._dy),a=n.CalculateBounceAngle(this._inst,this._lastX,this._lastY,i);this._dx=Math.cos(a)*r,this._dy=Math.sin(a)*r,s.OffsetXY(this._dx*h,this._dy*h),s.SetBboxChanged(),this._setAngle&&(s.SetAngle(a),this._lastKnownAngle=s.GetAngle(),s.SetBboxChanged()),0!==r&&(this._bounceOffSolid?n.PushOutSolid(this._inst,this._dx/r,this._dy/r,Math.max(2.5*r*h,30))||n.PushOutSolidNearest(this._inst,100):n.PushOut(this._inst,this._dx/r,this._dy/r,Math.max(2.5*r*h,30),i))},SetBounceOffSolids(t){this._SetBounceOffSolids(t)},SetDistanceTravelled(t){this._SetDistanceTravelled(t)},SetEnabled(t){this._SetEnabled(t)},StopStepping(){this._stopStepping=!0},SetVector3D(t,e,i){this._SetVector(t,e,i)},SetGravityVector3D(t,e,i){this._SetGravityVector(t,e,i)}}}{const t=self.C3;t.Behaviors.Bullet.Exps={Speed(){return this._GetSpeed()},Acceleration(){return this._GetAcceleration()},AngleOfMotion(){return t.toDegrees(this._GetAngleOfMotion())},DistanceTravelled(){return this._GetDistanceTravelled()},Gravity(){return this._GetGravity()},GravityVectorX(){return this._GetGravityVector()[0]},GravityVectorY(){return this._GetGravityVector()[1]},GravityVectorZ(){return this._GetGravityVector()[2]},VectorX(){return this._GetVector()[0]},VectorY(){return this._GetVector()[1]},VectorZ(){return this._GetVector()[2]}}}
}

// scripts/behaviors/Rotate/c3runtime/runtime.js
{
{const e=self.C3;e.Behaviors.Rotate=class extends e.SDKBehaviorBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.Rotate.Type=class extends e.SDKBehaviorTypeBase{constructor(e){super(e)}Release(){super.Release()}OnCreate(){}}}{const e=self.C3,t=self.C3X,s=self.IBehaviorInstance,a=0,i=1,n=2;e.Behaviors.Rotate.Instance=class extends e.SDKBehaviorInstanceBase{constructor(t,s){super(t),this._speed=0,this._acceleration=0,this._isEnabled=!0,s&&(this._speed=e.toRadians(s[a]),this._acceleration=e.toRadians(s[i]),this._isEnabled=s[n]),this._isEnabled&&this._StartTicking()}Release(){super.Release()}_SetSpeed(e){this._speed=e}_GetSpeed(){return this._speed}_SetAcceleration(e){this._acceleration=e}_GetAcceleration(){return this._acceleration}SaveToJson(){return{"s":this._speed,"a":this._acceleration,"e":this._isEnabled}}LoadFromJson(e){this._speed=e["s"],this._acceleration=e["a"],this._SetEnabled(e["e"])}Tick(){if(!this._isEnabled)return;const e=this._runtime.GetDt(this._inst);if(0!==e&&(0!==this._acceleration&&(this._speed+=this._acceleration*e),0!==this._speed)){const t=this._inst.GetWorldInfo();t.SetAngle(t.GetAngle()+this._speed*e),t.SetBboxChanged()}}GetPropertyValueByIndex(t){switch(t){case a:return e.toDegrees(this._GetSpeed());case i:return e.toDegrees(this._GetAcceleration());case n:return this._IsEnabled()}}SetPropertyValueByIndex(t,s){switch(t){case a:this._SetSpeed(e.toRadians(s));break;case i:this._SetAcceleration(e.toRadians(s));break;case n:this._SetEnabled(s)}}_SetEnabled(e){this._isEnabled=!!e,this._isEnabled?this._StartTicking():this._StopTicking()}_IsEnabled(){return this._isEnabled}GetDebuggerProperties(){const t="behaviors.rotate";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:t+".properties.speed.name",value:e.toDegrees(this._GetSpeed()),onedit:t=>this._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/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 e<Math.PI?-1:1}return 0}Tick(){const e=this._runtime.GetDt(this._inst);this._isEnabled&&0!==e&&(0===this._period?this._i=0:this._i=(this._i+e/this._period*k)%k,this._UpdateFromPhase())}_UpdateFromPhase(){const t=this._inst.GetWorldInfo();switch(this._movement){case d:t.GetX()!==this._lastKnownValue&&(this._initialValue+=t.GetX()-this._lastKnownValue),t.SetX(this._initialValue+this.WaveFunc(this._i)*this._mag),this._lastKnownValue=t.GetX();break;case m:t.GetY()!==this._lastKnownValue&&(this._initialValue+=t.GetY()-this._lastKnownValue),t.SetY(this._initialValue+this.WaveFunc(this._i)*this._mag),this._lastKnownValue=t.GetY();break;case g:t.SetWidth(this._initialValue+this.WaveFunc(this._i)*this._mag),t.SetHeight(t.GetWidth()*this._ratio);break;case v:t.SetWidth(this._initialValue+this.WaveFunc(this._i)*this._mag);break;case c:t.SetHeight(this._initialValue+this.WaveFunc(this._i)*this._mag);break;case p:t.GetAngle()!==this._lastKnownValue&&(this._initialValue=e.clampAngle(this._initialValue+(t.GetAngle()-this._lastKnownValue))),t.SetAngle(this._initialValue+this.WaveFunc(this._i)*this._mag),this._lastKnownValue=t.GetAngle();break;case G:t.SetOpacity(this._initialValue+this.WaveFunc(this._i)*this._mag/100);break;case S:t.GetX()!==this._lastKnownValue&&(this._initialValue+=t.GetX()-this._lastKnownValue),t.GetY()!==this._lastKnownValue2&&(this._initialValue2+=t.GetY()-this._lastKnownValue2),t.SetX(this._initialValue+Math.cos(t.GetAngle())*this.WaveFunc(this._i)*this._mag),t.SetY(this._initialValue2+Math.sin(t.GetAngle())*this.WaveFunc(this._i)*this._mag),this._lastKnownValue=t.GetX(),this._lastKnownValue2=t.GetY();break;case V:t.SetZ(this._initialValue+this.WaveFunc(this._i)*this._mag)}t.SetBboxChanged()}_OnSpriteFrameChanged(e,t){}_SetPeriod(e){this._period=e}_GetPeriod(){return this._period}_SetMagnitude(e){this._mag=e}_SetMagnitude_ConvertAngle(t){5===this._movement&&(t=e.toRadians(t)),this._SetMagnitude(t)}_GetMagnitude(){return this._mag}_GetMagnitude_ConvertAngle(){let t=this._GetMagnitude();return 5===this._movement&&(t=e.toDegrees(t)),t}_SetMovement(t){5===this._movement&&5!==t&&(this._mag=e.toDegrees(this._mag)),this._movement=t,this.Init()}_GetMovement(){return this._movement}_SetWave(e){this._wave=e}_GetWave(){return this._wave}_SetPhase(t){this._i=e.clamp(t,0,2*Math.PI),this._UpdateFromPhase()}_GetPhase(){return this._i}_SetEnabled(e){this._isEnabled=!!e,this._isEnabled?this._StartTicking():this._StopTicking()}_IsEnabled(){return this._isEnabled}GetPropertyValueByIndex(e){switch(e){case s:return this._movement;case a:return this._wave;case n:return this._basePeriod;case o:return this._baseMag;case u:return this._isEnabled}}SetPropertyValueByIndex(t,i){switch(t){case s:this._movement=E[i],this.Init();break;case a:this._wave=i;break;case n:this._basePeriod=i,this._period=this._basePeriod+this._periodRandom,this._isEnabled||(0!==this._period?(this._i=this._basePeriodOffset/this._period*k,this._i+=this._periodOffsetRandom/this._period*k):this._i=0);break;case o:this._baseMag=i,this._mag=this._baseMag+this._magnitudeRandom,this._movement===p&&(this._mag=e.toRadians(this._mag));break;case u:this._isEnabled=!!i}}GetDebuggerProperties(){const e="behaviors.sin";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:e+".properties.enabled.name",value:this._IsEnabled(),onedit:e=>this._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/behaviors/MoveTo/c3runtime/runtime.js
{
{const e=self.C3;e.Behaviors.MoveTo=class extends e.SDKBehaviorBase{constructor(e){super(e)}Release(){super.Release()}}}{const e=self.C3;e.Behaviors.MoveTo.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,n=1,a=2,o=3,r=4,h=5,_=6;e.Behaviors.MoveTo.Instance=class extends e.SDKBehaviorInstanceBase{constructor(t,i){super(t),this._maxSpeed=200,this._acc=600,this._dec=600,this._rotateSpeed=0,this._setAngle=!0,this._stopOnSolids=!1,this._isEnabled=!0,this._speed=0,this._movingAngle=this.GetWorldInfo().GetAngle(),this._waypoints=[],i&&(this._maxSpeed=i[s],this._acc=i[n],this._dec=i[a],this._rotateSpeed=e.toRadians(i[o]),this._setAngle=i[r],this._stopOnSolids=i[h],this._isEnabled=i[_]),this._timelineInfo=null,this._lastTargetX=NaN,this._lastTargetY=NaN,this._lastTargetAngle=NaN,this._tRange=[0,0],this._timelineInfoProjectionRange={tRange:this._tRange}}Release(){this._timelineInfo&&(this._timelineInfo.Release(),this._timelineInfo=null),this._lastTargetX=NaN,this._lastTargetY=NaN,this._lastTargetAngle=NaN,this._tRange=null,this._timelineInfoProjectionRange=null,super.Release()}SaveToJson(){return{"ms":this._maxSpeed,"acc":this._acc,"dec":this._dec,"rs":this._rotateSpeed,"sa":this._setAngle,"sos":this._stopOnSolids,"s":this._speed,"ma":this._movingAngle,"wp":this._waypoints.map(e=>({"x":e.x,"y":e.y})),"e":this._isEnabled}}LoadFromJson(e){this._maxSpeed=e["ms"],this._acc=e["acc"],this._dec=e["dec"],this._rotateSpeed=e["rs"],this._setAngle=e["sa"],this._stopOnSolids=e["sos"],this._speed=e["s"],this._movingAngle=e["ma"],this._waypoints=e["wp"].map(e=>({x:e["x"],y:e["y"]})),this._SetEnabled(e["e"]),this._isEnabled&&this._waypoints.length>0&&this._StartTicking()}_AddWaypoint(t,i,s,n){s&&e.clearArray(this._waypoints),this._waypoints.push({x:t,y:i,opts:n}),this._isEnabled&&this._StartTicking()}_GetWaypointCount(){return this._waypoints.length}_GetWaypointXAt(e){return(e=Math.floor(e))<0||e>=this._waypoints.length?0:this._waypoints[e].x}_GetWaypointYAt(e){return(e=Math.floor(e))<0||e>=this._waypoints.length?0:this._waypoints[e].y}_IsMoving(){return this._waypoints.length>0}_Stop(){e.clearArray(this._waypoints),this._speed=0,this._StopTicking()}_GetTargetX(){return this._waypoints.length>0?this._waypoints[0].x:0}_GetTargetY(){return this._waypoints.length>0?this._waypoints[0].y:0}_GetTargetIsBezier(){if(this._waypoints.length>0){const e=this._waypoints[0];if(e.opts)return e.opts.isBezier}return!1}_GetTargetIsBezierFirst(){if(this._waypoints.length>0){const e=this._waypoints[0];if(e.opts)return e.opts.isBezier&&e.opts.isFirst}return!1}_GetTargetBezierAngle(){if(this._waypoints.length>0){const e=this._waypoints[0];if(e.opts)return e.opts.bezierAngle}return NaN}_SetSpeed(e){this._IsMoving()&&(this._speed=Math.min(e,this._maxSpeed))}_GetSpeed(){return this._speed}_SetMaxSpeed(e){this._maxSpeed=Math.max(e,0),this._SetSpeed(this._speed)}_GetMaxSpeed(){return this._maxSpeed}_IsRotationEnabled(){return 0!==this._rotateSpeed}Tick(){if(!this._isEnabled||!this._IsMoving())return;const t=this._runtime.GetDt(this._inst),i=this._inst.GetWorldInfo(),s=i.GetX(),n=i.GetY(),a=i.GetAngle();let o=this._speed,r=this._maxSpeed;const h=this._acc,_=this._dec,l=this._GetTargetX(),g=this._GetTargetY(),d=e.angleTo(s,n,l,g);let p=!1;if(_>0&&1===this._waypoints.length){const t=.5*o*o/_*1.0001;if(p=e.distanceSquared(s,n,l,g)<=t*t,p){const t=e.distanceTo(s,n,l,g);o=Math.sqrt(2*_*t),r=o,this._speed=o}}if(this._IsRotationEnabled()){const t=e.angleDiff(this._movingAngle,d);if(t>Number.EPSILON){const s=t/this._rotateSpeed,n=e.distanceTo(i.GetX(),i.GetY(),l,g)/(2*Math.sin(t))*t;r=Math.min(r,e.clamp(n/s,0,this._maxSpeed))}}let c=p?-_:h;const S=Math.min(o*t+.5*c*t*t,r*t);if(p){if(_>0&&(this._speed=Math.max(this._speed-_*t,0),0===this._speed))return void this._OnArrived(i,l,g)}else this._speed=0===h?r:Math.min(this._speed+h*t,r);if(e.distanceSquared(i.GetX(),i.GetY(),l,g)<=S*S)this._OnArrived(i,l,g);else{if(this._IsRotationEnabled()?this._movingAngle=e.angleRotate(this._movingAngle,d,this._rotateSpeed*t):this._movingAngle=d,i.OffsetXY(Math.cos(this._movingAngle)*S,Math.sin(this._movingAngle)*S),this._setAngle){const t=this._GetTargetIsBezier(),s=this._GetTargetIsBezierFirst();if(t&&!s){const t=e.distanceTo(this._lastTargetX,this._lastTargetY,i.GetX(),i.GetY())/e.distanceTo(this._lastTargetX,this._lastTargetY,l,g);i.SetAngle(e.angleLerp(this._lastTargetAngle,this._GetTargetBezierAngle(),t))}else i.SetAngle(this._movingAngle),this._lastTargetX=NaN,this._lastTargetY=NaN,this._lastTargetAngle=NaN}i.SetBboxChanged(),this._CheckSolidCollision(s,n,a)}}_OnArrived(t,i,s){t.SetXY(i,s);const n=this._waypoints[0];n.opts&&n.opts.isBezier?(this._lastTargetX=n.x,this._lastTargetY=n.y,this._lastTargetAngle=n.opts.bezierAngle,this._setAngle&&t.SetAngle(this._lastTargetAngle)):(this._lastTargetX=NaN,this._lastTargetY=NaN,this._lastTargetAngle=NaN),t.SetBboxChanged(),this._waypoints.shift(),0===this._waypoints.length&&(this._timelineInfo&&(this._timelineInfo.Release(),this._timelineInfo=null,this._lastTargetX=NaN,this._lastTargetY=NaN,this._lastTargetAngle=NaN),this._speed=0,this._StopTicking()),this.DispatchScriptEvent("arrived"),this.Trigger(e.Behaviors.MoveTo.Cnds.OnArrived)}_CheckSolidCollision(t,i,s){const n=this._runtime.GetCollisionEngine();if(this._stopOnSolids&&n.TestOverlapSolid(this._inst)){this._Stop();const a=this._inst.GetWorldInfo(),o=a.GetX(),r=a.GetY(),h=e.angleTo(o,r,t,i),_=e.distanceTo(o,r,t,i);n.PushOutSolid(this._inst,Math.cos(h),Math.sin(h),Math.max(_,1))||(a.SetXY(t,i),a.SetAngle(s),a.SetBboxChanged()),this.DispatchScriptEvent("hitsolid"),this.Trigger(e.Behaviors.MoveTo.Cnds.OnHitSolid)}}_IsSetAngle(){return this._setAngle}_SetSetAngle(e){this._setAngle=!!e}_SetAngleOfMotion(e){if(this._movingAngle=e,this._isEnabled&&this._setAngle&&!this._IsMoving()){const e=this.GetWorldInfo();e.SetAngle(this._movingAngle),e.SetBboxChanged()}}_GetAngleOfMotion(){return this._movingAngle}_SetAcceleration(e){this._acc=Math.max(e,0)}_GetAcceleration(){return this._acc}_SetDeceleration(e){this._dec=Math.max(e,0)}_GetDeceleration(){return this._dec}_SetRotateSpeed(e){this._rotateSpeed=Math.max(e,0)}_GetRotateSpeed(){return this._rotateSpeed}_SetStopOnSolids(e){this._stopOnSolids=!!e}_IsStopOnSolids(){return this._stopOnSolids}_SetEnabled(e){e=!!e,this._isEnabled!==e&&(this._isEnabled=e,this._isEnabled&&this._IsMoving()?this._StartTicking():this._StopTicking())}_IsEnabled(){return this._isEnabled}GetPropertyValueByIndex(t){switch(t){case s:return this._GetMaxSpeed();case n:return this._GetAcceleration();case a:return this._GetDeceleration();case o:return e.toDegrees(this._GetRotateSpeed());case r:return this._IsSetAngle();case h:return this._IsStopOnSolids();case _:return this._IsEnabled()}}SetPropertyValueByIndex(t,i){switch(t){case s:this._SetMaxSpeed(i);break;case n:this._SetAcceleration(i);break;case a:this._SetDeceleration(i);break;case o:this._SetRotateSpeed(e.toRadians(i));break;case r:this._SetSetAngle(i);break;case h:this._SetStopOnSolids(i);break;case _:this._SetEnabled(i)}}GetDebuggerProperties(){const t="behaviors.moveto";return[{title:"$"+this.GetBehaviorType().GetName(),properties:[{name:t+".debugger.speed",value:this._GetSpeed(),onedit:e=>this._SetSpeed(e)},{name:t+".debugger.angle-of-motion",value:e.toDegrees(this._GetAngleOfMotion()),onedit:t=>this._movingAngle=e.toRadians(t)},{name:t+".debugger.target-x",value:this._GetTargetX()},{name:t+".debugger.target-y",value:this._GetTargetY()},{name:t+".debugger.waypoint-count",value:this._GetWaypointCount()},{name:t+".properties.max-speed.name",value:this._GetMaxSpeed(),onedit:e=>this._SetMaxSpeed(e)},{name:t+".properties.acceleration.name",value:this._GetAcceleration(),onedit:e=>this._SetAcceleration(e)},{name:t+".properties.deceleration.name",value:this._GetDeceleration(),onedit:e=>this._SetDeceleration(e)},{name:t+".properties.rotate-speed.name",value:e.toDegrees(this._GetRotateSpeed()),onedit:t=>this._SetRotateSpeed(e.toRadians(t))},{name:t+".properties.enabled.name",value:this._IsEnabled(),onedit:e=>this._SetEnabled(e)}]}]}GetScriptInterfaceClass(){return self.IMoveToBehaviorInstance}};const l=new WeakMap;self.IMoveToBehaviorInstance=class extends i{constructor(){super(),l.set(this,i._GetInitInst().GetSdkInstance())}moveToPosition(e,i,s=!0){t.RequireFiniteNumber(e),t.RequireFiniteNumber(i),l.get(this)._AddWaypoint(e,i,!!s)}getTargetX(){return l.get(this)._GetTargetX()}getTargetY(){return l.get(this)._GetTargetY()}getTargetPosition(){const e=l.get(this);return[e._GetTargetX(),e._GetTargetY()]}getWaypointCount(){return l.get(this)._GetWaypointCount()}getWaypointX(e){return t.RequireFiniteNumber(e),l.get(this)._GetWaypointXAt(e)}getWaypointY(e){return t.RequireFiniteNumber(e),l.get(this)._GetWaypointYAt(e)}getWaypoint(e){t.RequireFiniteNumber(e);const i=l.get(this);return[i._GetWaypointXAt(e),i._GetWaypointYAt(e)]}stop(){l.get(this)._Stop()}get isMoving(){return l.get(this)._IsMoving()}get speed(){return l.get(this)._GetSpeed()}set speed(e){t.RequireFiniteNumber(e),l.get(this)._SetSpeed(e)}get maxSpeed(){return l.get(this)._GetMaxSpeed()}set maxSpeed(e){t.RequireFiniteNumber(e),l.get(this)._SetMaxSpeed(e)}get acceleration(){return l.get(this)._GetAcceleration()}set acceleration(e){t.RequireFiniteNumber(e),l.get(this)._SetAcceleration(e)}get deceleration(){return l.get(this)._GetDeceleration()}set deceleration(e){t.RequireFiniteNumber(e),l.get(this)._SetDeceleration(e)}get angleOfMotion(){return l.get(this)._GetAngleOfMotion()}set angleOfMotion(e){t.RequireFiniteNumber(e),l.get(this)._SetAngleOfMotion(e)}get rotateSpeed(){return l.get(this)._GetRotateSpeed()}set rotateSpeed(e){t.RequireFiniteNumber(e),l.get(this)._SetRotateSpeed(e)}get isStopOnSolids(){return l.get(this)._IsStopOnSolids()}set isStopOnSolids(e){l.get(this)._SetStopOnSolids(e)}get isEnabled(){return l.get(this)._IsEnabled()}set isEnabled(e){l.get(this)._SetEnabled(e)}}}{const e=self.C3;e.Behaviors.MoveTo.Cnds={IsMoving(){return this._IsMoving()},CompareSpeed(t,i){return e.compare(this._GetSpeed(),t,i)},IsEnabled(){return this._IsEnabled()},OnArrived:()=>!0,OnHitSolid:()=>!0}}{const e=self.C3,t=25;e.Behaviors.MoveTo.Acts={MoveToPosition(e,t,i){this._AddWaypoint(e,t,0===i)},MoveToObject(e,t,i){if(!e)return;const s=e.GetPairedInstance(this._inst);if(!s||!s.GetWorldInfo())return;const[n,a]=s.GetImagePoint(t);this._AddWaypoint(n,a,0===i)},MoveAlongPathfindingPath(t){const i=this._inst.GetBehaviorSdkInstanceFromCtor(e.Behaviors.Pathfinding);if(!i)return;const s=i._GetPath();if(0!==s.length)for(let e=0,i=s.length;e<i;++e){const i=s[e];this._AddWaypoint(i.x,i.y,0===e&&0===t)}},MoveAlongTimeline(i,s,n){const a=e.New(e.TimelineInfo,i,s);if(!a.WasInitialized())return void a.Release();a.SetOrigin(this._inst.GetWorldInfo());let o=!0;for(const i of a.segments())switch(i.GetType()){case"line":{const e=i.GetX(),t=i.GetY();this._AddWaypoint(e,t,o&&0===n),o=!1;break}case"cubic-bezier":for(let s=0;s<=i.GetStepCount();s++){const a=s*i.GetStepIncrement(),r=i.Map(a),h=r[0],_=r[1],l=this._GetWaypointXAt(this._GetWaypointCount()-1),g=this._GetWaypointYAt(this._GetWaypointCount()-1);!o&&e.IsFiniteNumber(l)&&e.IsFiniteNumber(g)&&e.distanceSquared(l,g,h,_)<t||(this._AddWaypoint(h,_,o&&0===n,{isBezier:!0,isFirst:o,bezierAngle:Math.atan2(_-g,h-l)}),o=!1)}}this._timelineInfo=a},MoveAlongTimelineByName(t,i,s){const n=this._runtime.GetTimelineManager().GetTimelineByName(t);n&&e.Behaviors.MoveTo.Acts.MoveAlongTimeline.call(this,n,i,s)},Stop(){this._Stop()},SetMovingAngle(t){this._SetAngleOfMotion(e.toRadians(t))},SetSpeed(e){this._SetSpeed(e)},SetMaxSpeed(e){this._SetMaxSpeed(e)},SetAcceleration(e){this._SetAcceleration(e)},SetDeceleration(e){this._SetDeceleration(e)},SetRotateSpeed(t){this._SetRotateSpeed(e.toRadians(t))},SetStopOnSolids(e){this._SetStopOnSolids(e)},SetEnabled(e){this._SetEnabled(e)}}}{const e=self.C3;e.Behaviors.MoveTo.Exps={Speed(){return this._GetSpeed()},MaxSpeed(){return this._GetMaxSpeed()},Acceleration(){return this._GetAcceleration()},Deceleration(){return this._GetDeceleration()},MovingAngle(){return e.toDegrees(this._GetAngleOfMotion())},RotateSpeed(){return e.toDegrees(this._GetRotateSpeed())},TargetX(){return this._GetTargetX()},TargetY(){return this._GetTargetY()},WaypointCount(){return this._GetWaypointCount()},WaypointXAt(e){return this._GetWaypointXAt(e)},WaypointYAt(e){return this._GetWaypointYAt(e)}}}
}

// 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 = [
		() => "BattleField",
		() => 0.8,
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0();
		},
		() => "b1",
		() => "0,0;1,0;2,0/0,0;1,0",
		() => "b2",
		() => "3,0;3,6;4,0;4,6/2,0;3,0;3,6",
		() => "b3",
		() => "6,6;7,0;7,6;8,0;8,6;9,0;9,6;10,0;10,6;11,0/6,0;7,0;7,6;8,0;8,6;9,0;10,0",
		() => "b4",
		() => "12,0;12,6;13,0;13,6;13,12;14,0;14,6;14,12;15,0;15,6;16,0;16,6/11,0;12,0;13,0;13,6;14,0;14,6;15,0",
		() => "b5",
		() => "0,6;0,12;1,6;1,12;2,6;2,12;3,6/0,6;0,12;1,6;1,12;2,6;3,6",
		() => "b6",
		() => "4,0;4,6;5,0;5,6;6,0;6,6;7,0;7,6/3,0;4,0;4,6;5,0;5,6;6,0;6,6;7,0",
		() => "b7",
		() => "10,0;10,6;10,12;11,0;11,6;11,12;12,0;12,6;13,0;13,6/9,0;9,6;10,0;10,6;11,0;11,6;12,0;12,6;13,0",
		() => "b8",
		() => "3,12;4,12;5,12;5,18;6,12;7,12;8,12/3,12;4,6;4,12;5,6;5,12;6,6;6,12;7,12",
		() => "b9",
		() => "6,12;7,12;8,6;8,12;8,18;9,6;9,12;9,18;10,12;10,18;11,12/6,6;7,6;7,12;8,6;8,12;9,6;9,12;10,6;10,12",
		() => "b10",
		() => "0,12;0,18;0,24;1,12;1,18;1,24;2,12;2,18;3,12;3,18;4,12;4,18/0,12;0,18;1,6;1,12;1,18;2,6;2,12;2,18;3,12;4,12",
		() => "b11",
		() => "12,12;12,18;13,12;13,18;14,6;14,12;14,18;15,6;15,12;15,18;15,19;15,19;16,6;16,12;16,18/11,12;12,6;12,12;13,6;13,12;13,18;14,6;14,12;14,18;15,6;15,12",
		() => "b12",
		() => "5,18;6,18;6,24;7,18;7,24;8,18;8,24/5,12;5,18;6,12;6,18;7,12;7,18;8,12;8,18",
		() => "b13",
		() => "9,18;10,18;11,18;12,12;12,18;13,18/9,12;9,18;10,12;10,18;11,12;11,18;12,12",
		() => "b14",
		() => "3,18;3,24;3,30;4,24;4,30;5,18;5,24;5,30;6,18;6,24;6,30;7,24/2,24;3,18;3,24;4,18;4,24;5,18;5,24;6,18;6,24",
		() => "b15",
		() => "8,30;9,24;9,30;10,24;10,30;11,24;11,30;12,24;12,30/8,24;9,18;9,24;10,18;10,24;11,18;11,24;12,18;12,24",
		() => "b16",
		() => "13,24;14,18;14,24;15,18;15,24;16,18;16,24/13,18;14,18;15,18",
		() => "b17",
		() => "0,18;0,24;0,30;1,18;1,24;1,30;2,18;2,24;2,30;3,24;3,30;4,24;4,30/0,18;0,24;1,18;1,24;2,18;2,24;3,24;4,24",
		() => "b18",
		() => "5,30;6,24;6,30;7,24;7,30;8,24;8,30;9,24;9,30;10,24;10,30;11,30/5,24;6,18;6,24;7,18;7,24;8,18;8,24;9,24;10,24",
		() => "b19",
		() => "12,24;12,30;13,24;13,30;14,30/11,24;12,24;13,24",
		() => "b20",
		() => "15,30;16,30/14,24;15,24",
		() => "cardBack1",
		() => 0,
		() => "cardBack2",
		() => "cardBack3",
		() => "cardBack4",
		() => "cardBack5",
		() => "cardBack6",
		() => "Buff_0",
		() => "Разведка. Враг знает наши позиции.",
		() => "Buff_1",
		() => "К нам подоспели колдуны",
		() => "Buff_2",
		() => "Враг подослал конницу",
		() => "Buff_3",
		() => "Враг насторожился и отправил колдунов",
		() => "Buff_4",
		() => "Загнанный в угол враг начал использовать осадную магию",
		() => "Buff_5",
		() => "У врага нехватка войск в регионе, отряды подходят дольше",
		() => "Buff_6",
		() => "У врага появились дизертиры",
		() => "Buff_7",
		() => "Враг расслабился и отправил только 3 вида войск",
		() => "card_about_1",
		() => "Пехотинцы, с мечем и щитом. Эффективна против лучников и копейщиков.",
		() => "card_about_2",
		() => "Лучники. Эффективны против копейщиков и способны противостоять коннице.",
		() => "card_about_3",
		() => "Копейщики. Эффективны против конницы.",
		() => "card_about_4",
		() => "Конница. Эффективна против пехотинцев.",
		() => "card_about_5",
		() => "Колдуны. До них сложно добраться.",
		() => "card_about_6",
		() => "Осадная магия. Требовательная, но мощная.",
		() => "bluecard_about_1",
		() => "Пехотник, с мечем и щитом. Эффективна против лукарей и копьеносцев.",
		() => "bluecard_about_2",
		() => "Лукари. Эффективны против копьеносцев и способны противостоять лошаднице.",
		() => "bluecard_about_3",
		() => "Копьеносцы. Эффективны против лошадницы.",
		() => "bluecard_about_4",
		() => "Лошадница. Эффективна против пехотников.",
		() => "bluecard_about_5",
		() => "Колдователь. До них сложно добраться.",
		() => "bluecard_about_6",
		() => "Осаждающая магия. Требовательная, но мощная.",
		() => 7,
		() => 2,
		() => 1,
		() => 18,
		() => 9,
		() => 14,
		() => 3,
		() => 12,
		() => 4,
		() => 17,
		() => 5,
		() => 6,
		() => 10,
		() => "Arr_back",
		() => "Arr_battle",
		() => "Dict_var",
		() => "Loading",
		() => "Start",
		() => "L_loca",
		() => "L_Choosen",
		() => "GameOver",
		() => "UI",
		() => 150,
		() => "SetColor",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const f1 = p._GetNode(1).GetBoundMethod();
			const n2 = p._GetNode(2);
			const f3 = p._GetNode(3).GetBoundMethod();
			const n4 = p._GetNode(4);
			return () => f0(f1(250, n2.ExpObject()), f3(250, (250 - n4.ExpObject())), 0);
		},
		() => "Mobile1",
		() => "PC1",
		p => {
			const n0 = p._GetNode(0);
			return () => n0.ExpObject();
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			const f3 = p._GetNode(3).GetBoundMethod();
			return () => f0(n1.ExpObject(and("b", n2.ExpObject(f3(), 0))), 0, "/");
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			const f3 = p._GetNode(3).GetBoundMethod();
			return () => f0(n1.ExpObject(and("b", n2.ExpObject(f3()))), 1, "/");
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			return () => n0.ExpObject(f1(), 1);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => (f0() / 2);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			return () => n0.ExpObject(f1(), 0);
		},
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() * 0.5);
		},
		() => "Field",
		() => "Battle",
		p => {
			const n0 = p._GetNode(0);
			return () => n0.ExpInstVar();
		},
		() => 0.5,
		() => -10,
		() => "",
		() => "Back",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => (f0() / 10);
		},
		p => {
			const n0 = p._GetNode(0);
			return () => ((n0.ExpObject() * 0.1) + 0.5);
		},
		() => "Blue",
		() => "hand",
		() => "take",
		() => 850,
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			return () => n0.ExpObject(and("bluecard_about_", n1.ExpInstVar()));
		},
		() => "choose",
		() => 950,
		() => "CardBattle",
		() => 720,
		() => 600,
		() => "battle",
		() => "RedChoose",
		() => 1200,
		() => 485,
		() => 960,
		() => 530,
		p => {
			const v0 = p._GetNode(0).GetVar();
			return () => and("card", v0.GetValue());
		},
		() => -15,
		() => 0.2,
		() => "Card",
		() => 595,
		p => {
			const n0 = p._GetNode(0);
			const v1 = p._GetNode(1).GetVar();
			const v2 = p._GetNode(2).GetVar();
			return () => and("-", n0.ExpObject(v1.GetValue(), v2.GetValue()));
		},
		() => 455,
		() => 225,
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const f1 = p._GetNode(1).GetBoundMethod();
			const n2 = p._GetNode(2);
			const n3 = p._GetNode(3);
			const v4 = p._GetNode(4).GetVar();
			const v5 = p._GetNode(5).GetVar();
			return () => f0(f1(10, subtract(n2.ExpObject(), n3.ExpObject(v4.GetValue(), v5.GetValue()))));
		},
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			return () => ((n0.ExpObject() - n1.ExpObject()) + 10);
		},
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			return () => ((n0.ExpObject() + n1.ExpObject()) - 10);
		},
		() => 0.3,
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			return () => ((((n0.ExpObject()) === ("Blue") ? 1 : 0)) ? (((180 * n1.ExpInstVar()) - 60)) : ((1980 - (180 * n2.ExpInstVar()))));
		},
		p => {
			const n0 = p._GetNode(0);
			return () => ((((n0.ExpObject()) === ("Blue") ? 1 : 0)) ? (1230) : ((-140)));
		},
		p => {
			const n0 = p._GetNode(0);
			return () => ((((n0.ExpObject()) === ("Blue") ? 1 : 0)) ? ("back") : ("red"));
		},
		() => 20,
		() => "BattleEnd",
		p => {
			const n0 = p._GetNode(0);
			return () => and("cardBack", n0.ExpInstVar());
		},
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			return () => n0.ExpObject(n1.ExpInstVar(), (7 + ((n2.ExpObject()) > (150) ? 1 : 0)));
		},
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			return () => n0.ExpObject(and("Buff_", n1.ExpInstVar()));
		},
		p => {
			const v0 = p._GetNode(0).GetVar();
			return () => v0.GetValue();
		},
		() => 50,
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() - 30);
		},
		() => -20,
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			const n3 = p._GetNode(3);
			const n4 = p._GetNode(4);
			return () => f0((C3.distanceTo(n1.ExpObject(1), n2.ExpObject(1), n3.ExpObject(), n4.ExpObject()) / 40));
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const f1 = p._GetNode(1).GetBoundMethod();
			return () => (f0() * f1());
		},
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() + 40);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			const n3 = p._GetNode(3);
			const n4 = p._GetNode(4);
			const f5 = p._GetNode(5).GetBoundMethod();
			return () => (f0((C3.distanceTo(n1.ExpObject(1), n2.ExpObject(1), n3.ExpObject(), n4.ExpObject()) / 40)) * f5());
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			return () => ((n0.ExpObject() - f1()) / 24);
		},
		() => 0.05,
		() => "battle1",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => and("card", f0(1, 1, 2, 2, 2, 3, 3, 4, 4, 4));
		},
		() => -25,
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => and("card", f0(2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6));
		},
		() => "battle2",
		() => "count",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const v1 = p._GetNode(1).GetVar();
			return () => (f0(v1.GetValue(), ";") - 1);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const v1 = p._GetNode(1).GetVar();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => f0(v1.GetValue(), f2("count"), ";");
		},
		() => "tiles",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const f2 = p._GetNode(2).GetBoundMethod();
			const f3 = p._GetNode(3).GetBoundMethod();
			const v4 = p._GetNode(4).GetVar();
			const f5 = p._GetNode(5).GetBoundMethod();
			const f6 = p._GetNode(6).GetBoundMethod();
			const v7 = p._GetNode(7).GetVar();
			const f8 = p._GetNode(8).GetBoundMethod();
			return () => f0(n1.ExpObject(f2(f3(v4.GetValue(), 0, ",")), (f5(f6(v7.GetValue(), 1, ",")) + f8("tiles"))));
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const f1 = p._GetNode(1).GetBoundMethod();
			const v2 = p._GetNode(2).GetVar();
			return () => f0(f1(v2.GetValue(), 0, ","));
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const f1 = p._GetNode(1).GetBoundMethod();
			const v2 = p._GetNode(2).GetVar();
			const f3 = p._GetNode(3).GetBoundMethod();
			return () => (f0(f1(v2.GetValue(), 1, ",")) + f3("tiles"));
		},
		p => {
			const v0 = p._GetNode(0).GetVar();
			const v1 = p._GetNode(1).GetVar();
			const v2 = p._GetNode(2).GetVar();
			return () => ((v0.GetValue() - (v1.GetValue() % 4)) + (3 * v2.GetValue()));
		},
		() => "x",
		() => 16,
		() => "y",
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(0, f1("x"), (f2("y") * 6)) % 4);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(0, (f1("x") - 1), (f2("y") * 6)) % 4);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(0, (f1("x") + 1), (f2("y") * 6)) % 4);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(1, f1("x"), (f2("y") * 6)) % 4);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(1, (f1("x") - 1), (f2("y") * 6)) % 4);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(1, f1("x"), ((f2("y") - 1) * 6)) % 4);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(1, (f1("x") - 1), ((f2("y") - 1) * 6)) % 4);
		},
		() => "ty",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => (f0("y") * 6);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => ((f0("y") * 6) + 3);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0("x");
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0("ty");
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			const n3 = p._GetNode(3);
			const f4 = p._GetNode(4).GetBoundMethod();
			const f5 = p._GetNode(5).GetBoundMethod();
			return () => ((n0.ExpObject(f1("x"), f2("ty")) - (n3.ExpObject(f4("x"), f5("ty")) % 4)) + 1);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			const n3 = p._GetNode(3);
			const f4 = p._GetNode(4).GetBoundMethod();
			const f5 = p._GetNode(5).GetBoundMethod();
			return () => (n0.ExpObject(f1("x"), f2("ty")) - (n3.ExpObject(f4("x"), f5("ty")) % 4));
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			const n3 = p._GetNode(3);
			const f4 = p._GetNode(4).GetBoundMethod();
			const f5 = p._GetNode(5).GetBoundMethod();
			return () => ((n0.ExpObject(f1("x"), f2("ty")) - (n3.ExpObject(f4("x"), f5("ty")) % 4)) + 2);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			const n3 = p._GetNode(3);
			const f4 = p._GetNode(4).GetBoundMethod();
			const f5 = p._GetNode(5).GetBoundMethod();
			return () => ((n0.ExpObject(f1("x"), f2("ty")) - (n3.ExpObject(f4("x"), f5("ty")) % 4)) + 3);
		},
		() => 15,
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(1, (f1("x") + 1), (f2("y") * 6)) % 4);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(0, f1("x"), ((f2("y") + 1) * 6)) % 4);
		},
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => (n0.ExpObject_InstExpr(0, (f1("x") + 1), ((f2("y") + 1) * 6)) % 4);
		},
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			const n3 = p._GetNode(3);
			const n4 = p._GetNode(4);
			return () => (n0.ExpObject(n1.ExpObject(n2.ExpObject()), n3.ExpObject(n4.ExpObject())) % 4);
		},
		() => "Danger",
		p => {
			const n0 = p._GetNode(0);
			return () => ((n0.ExpObject() / 17) * 150);
		},
		() => 1740,
		() => 945,
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			return () => add(n0.ExpObject("Danger"), (((1680 - C3.distanceTo(n1.ExpObject(), n2.ExpObject(), 1740, 945)) / 1260) * 96));
		},
		p => {
			const n0 = p._GetNode(0);
			return () => n0.ExpObject("Danger");
		},
		() => 24,
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const v1 = p._GetNode(1).GetVar();
			return () => (f0("BattleField") + v1.GetValue());
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const v1 = p._GetNode(1).GetVar();
			return () => (f0() + v1.GetValue());
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => (25 * f0());
		},
		() => 540,
		p => {
			const v0 = p._GetNode(0).GetVar();
			return () => and("end", v0.GetValue());
		},
		() => -5,
		() => "top",
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() - 14);
		},
		() => "bot",
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() + 14);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => Math.round(((960 - f0()) / 24));
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => Math.round(((540 - f0()) / 24));
		},
		() => -0.05,
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const v2 = p._GetNode(2).GetVar();
			return () => f0(n1.ExpObject(and("b", v2.GetValue())), 0, "/");
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const v2 = p._GetNode(2).GetVar();
			return () => f0(n1.ExpObject(and("b", v2.GetValue())), 1, "/");
		},
		p => {
			const n0 = p._GetNode(0);
			return () => (n0.ExpObject() - 1);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0(0, 0, 1);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			return () => f0(n1.ExpObject(and("b", n2.ExpInstVar())), 0, "/");
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			return () => f0(n1.ExpObject(and("b", n2.ExpInstVar())), 1, "/");
		},
		p => {
			const n0 = p._GetNode(0);
			return () => divide(n0.ExpObject("ArmyRed"), 2);
		},
		p => {
			const n0 = p._GetNode(0);
			return () => divide(n0.ExpObject("ArmyBlue"), 2);
		},
		() => 99,
		() => "BlueHa",
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			const n2 = p._GetNode(2);
			const n3 = p._GetNode(3);
			return () => ((((n0.ExpObject()) < (100) ? 1 : 0)) ? (3) : (((((n1.ExpObject()) < (150) ? 1 : 0)) ? (4) : (((((n2.ExpObject()) < (150) ? 1 : 0)) ? (4) : (((((n3.ExpObject()) < (185) ? 1 : 0)) ? (5) : (6))))))));
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => (120 + (180 * f0()));
		},
		() => 1230,
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => (f0() + 1);
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => and("cardBack", (f0() + 1));
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => and("Blue", (f0() + 1));
		},
		() => "BlueSlow",
		p => {
			const n0 = p._GetNode(0);
			return () => ((((n0.ExpObject()) > (12) ? 1 : 0)) ? (5) : (4));
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => (1800 - (180 * f0()));
		},
		() => -145,
		() => "Red",
		() => "red",
		() => "RedMag",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => f0(1, 2, 0, 0, 0, 0);
		},
		p => {
			const v0 = p._GetNode(0).GetVar();
			return () => and("cardBack", v0.GetValue());
		},
		() => "BlueMinus",
		() => "RedSearch",
		() => "back",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => and("cardBack", f0());
		},
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const n1 = p._GetNode(1);
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => f0(subtract(n1.ExpObject(and("cardBack", f2())), 1), 0);
		},
		() => 1120,
		() => "cardback",
		() => "Выбери карту за врага, а затем отправь в атаку",
		() => 135,
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const f2 = p._GetNode(2).GetBoundMethod();
			return () => ((((n0.ExpObject()) === (4) ? 1 : 0)) ? (f1(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4)) : (f2(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5)));
		},
		() => 235,
		p => {
			const n0 = p._GetNode(0);
			const n1 = p._GetNode(1);
			return () => n0.ExpObject(and("card_about_", n1.ExpInstVar()));
		},
		() => "Войска врага на подходе. А пока атакуем без сопротивления.",
		p => {
			const n0 = p._GetNode(0);
			return () => and("card", n0.ExpInstVar());
		},
		p => {
			const n0 = p._GetNode(0);
			return () => (1980 - (180 * n0.ExpInstVar()));
		},
		() => -140,
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			const f1 = p._GetNode(1).GetBoundMethod();
			const n2 = p._GetNode(2);
			const n3 = p._GetNode(3);
			const n4 = p._GetNode(4);
			return () => f0(f1(10, subtract(n2.ExpObject(), n3.ExpObject(0, n4.ExpInstVar()))));
		},
		() => "ach1",
		() => "About",
		() => "Autors",
		p => {
			const n0 = p._GetNode(0);
			return () => n0.ExpObject("Volume");
		},
		() => "Sound",
		() => "music",
		() => "Mobile",
		() => "PC",
		p => {
			const n0 = p._GetNode(0);
			const f1 = p._GetNode(1).GetBoundMethod();
			const n2 = p._GetNode(2);
			const f3 = p._GetNode(3).GetBoundMethod();
			return () => and(n0.ExpObject(and((and("a", (f1() + 1)) + "-"), n2.ExpObject(and("ach", (f3() + 1))))), "\n");
		},
		() => "NewWindow",
		p => {
			const f0 = p._GetNode(0).GetBoundMethod();
			return () => (f0() + 9);
		},
		() => "Volume"
];


}

