@designcombo/video 0.1.15 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{SharedSystems-C-xrqDs6.js → SharedSystems-c89R2YB4.js} +1 -1
- package/dist/{WebGLRenderer-DA5apB9s.js → WebGLRenderer-yczU8Q7o.js} +2 -2
- package/dist/{WebGPURenderer-uG2zGI9E.js → WebGPURenderer-Dm2y598C.js} +2 -2
- package/dist/{browserAll-DBeYf_Ix.js → browserAll-hKruQd3x.js} +2 -2
- package/dist/{index-BsY0yXsw.js → index-CmsRjoEr.js} +231 -200
- package/dist/index.es.js +1 -1
- package/dist/index.umd.js +46 -46
- package/dist/studio.d.ts +1 -0
- package/dist/{webworkerAll-BNQ2PT3I.js → webworkerAll-BQqf01s5.js} +1 -1
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
(function(se,bi){typeof exports=="object"&&typeof module<"u"?bi(exports):typeof define=="function"&&define.amd?define(["exports"],bi):(se=typeof globalThis<"u"?globalThis:se||self,bi(se.core={}))})(this,(function(se){"use strict";var bi=i=>{throw TypeError(i)},yn=(i,e,t)=>e.has(i)||bi("Cannot "+t),xy=(i,e,t)=>(yn(i,e,"read from private field"),t?t.call(i):e.get(i)),ff=(i,e,t)=>e.has(i)?bi("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),yy=(i,e,t,s)=>(yn(i,e,"write to private field"),e.set(i,t),t),pf=(i,e,t)=>(yn(i,e,"access private method"),t),vy=Object.defineProperty,mf=(i,e)=>{for(var t in e)vy(i,t,{get:e[t],enumerable:!0})},vn=Math.pow(2,32),Ae=Math.pow(2,32)-1,by=1,Ty=2,wy=4,js=1,Zs=2,Js=8,Qs=16,er=32,gf=131072,ts=1,tr=4,is=256,ss=512,rs=1024,ns=2048,_f=-1,Wt=0,We=1,xt=class $x extends ArrayBuffer{constructor(e){super(e),this.fileStart=0,this.usedBytes=0}static fromArrayBuffer(e,t){const s=new $x(e.byteLength);return new Uint8Array(s).set(new Uint8Array(e)),s.fileStart=t,s}},xf=(i=>(i[i.BIG_ENDIAN=1]="BIG_ENDIAN",i[i.LITTLE_ENDIAN=2]="LITTLE_ENDIAN",i))(xf||{}),ir,bn,Z,Pe=(Z=class{constructor(i,e,t){ff(this,ir),this._byteLength=0,this.failurePosition=0,this._dynamicSize=1,this._byteOffset=e||0,i instanceof ArrayBuffer?this.buffer=xt.fromArrayBuffer(i,0):i instanceof DataView?(this.dataView=i,e&&(this._byteOffset+=e)):this.buffer=new xt(i||0),this.position=0,this.endianness=t||1}getPosition(){return this.position}_realloc(i){if(!this._dynamicSize)return;const e=this._byteOffset+this.position+i;let t=this._buffer.byteLength;if(e<=t){e>this._byteLength&&(this._byteLength=e);return}for(t<1&&(t=1);e>t;)t*=2;const s=new xt(t),r=new Uint8Array(this._buffer);new Uint8Array(s,0,r.length).set(r),this.buffer=s,this._byteLength=e}_trimAlloc(){if(this._byteLength===this._buffer.byteLength)return;const i=new xt(this._byteLength),e=new Uint8Array(i),t=new Uint8Array(this._buffer,0,e.length);e.set(t),this.buffer=i}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(i){this._buffer=i,this._dataView=new DataView(i,this._byteOffset),this._byteLength=i.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(i){this._byteOffset=i,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(i){this._byteOffset=i.byteOffset,this._buffer=xt.fromArrayBuffer(i.buffer,0),this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+i.byteLength}seek(i){const e=Math.max(0,Math.min(this.byteLength,i));this.position=isNaN(e)||!isFinite(e)?0:e}isEof(){return this.position>=this._byteLength}mapUint8Array(i){this._realloc(i*1);const e=new Uint8Array(this._buffer,this.byteOffset+this.position,i);return this.position+=i*1,e}readInt32Array(i,e){i=i===void 0?this.byteLength-this.position/4:i;const t=new Int32Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readInt16Array(i,e){i=i===void 0?this.byteLength-this.position/2:i;const t=new Int16Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readInt8Array(i){i=i===void 0?this.byteLength-this.position:i;const e=new Int8Array(i);return Z.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,i*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e}readUint32Array(i,e){i=i===void 0?this.byteLength-this.position/4:i;const t=new Uint32Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readUint16Array(i,e){i=i===void 0?this.byteLength-this.position/2:i;const t=new Uint16Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readUint8Array(i){i=i===void 0?this.byteLength-this.position:i;const e=new Uint8Array(i);return Z.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,i*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e}readFloat64Array(i,e){i=i===void 0?this.byteLength-this.position/8:i;const t=new Float64Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readFloat32Array(i,e){i=i===void 0?this.byteLength-this.position/4:i;const t=new Float32Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readInt32(i){const e=this._dataView.getInt32(this.position,(i??this.endianness)===2);return this.position+=4,e}readInt16(i){const e=this._dataView.getInt16(this.position,(i??this.endianness)===2);return this.position+=2,e}readInt8(){const i=this._dataView.getInt8(this.position);return this.position+=1,i}readUint32(i){const e=this._dataView.getUint32(this.position,(i??this.endianness)===2);return this.position+=4,e}readUint16(i){const e=this._dataView.getUint16(this.position,(i??this.endianness)===2);return this.position+=2,e}readUint8(){const i=this._dataView.getUint8(this.position);return this.position+=1,i}readFloat32(i){const e=this._dataView.getFloat32(this.position,(i??this.endianness)===2);return this.position+=4,e}readFloat64(i){const e=this._dataView.getFloat64(this.position,(i??this.endianness)===2);return this.position+=8,e}static memcpy(i,e,t,s,r){const n=new Uint8Array(i,e,r),o=new Uint8Array(t,s,r);n.set(o)}static arrayToNative(i,e){return e===Z.ENDIANNESS?i:this.flipArrayEndianness(i)}static nativeToEndian(i,e){return e&&Z.ENDIANNESS===2?i:this.flipArrayEndianness(i)}static flipArrayEndianness(i){const e=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);for(let t=0;t<i.byteLength;t+=i.BYTES_PER_ELEMENT)for(let s=t+i.BYTES_PER_ELEMENT-1,r=t;s>r;s--,r++){const n=e[r];e[r]=e[s],e[s]=n}return i}readString(i,e){return e===void 0||e==="ASCII"?yf(this.mapUint8Array(i===void 0?this.byteLength-this.position:i)):new TextDecoder(e).decode(this.mapUint8Array(i))}readCString(i){let e=0;const t=this.byteLength-this.position,s=new Uint8Array(this._buffer,this._byteOffset+this.position),r=i!==void 0?Math.min(i,t):t;for(;e<r&&s[e]!==0;e++);const n=yf(this.mapUint8Array(e));return i!==void 0?this.position+=r-e:e!==t&&(this.position+=1),n}readInt64(){return this.readInt32()*vn+this.readUint32()}readUint64(){return this.readUint32()*vn+this.readUint32()}readUint24(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()}save(i){const e=new Blob([this.buffer]);if(typeof window<"u"&&typeof document<"u")if(window.URL&&URL.createObjectURL){const t=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.setAttribute("href",t),s.setAttribute("download",i),s.setAttribute("target","_self"),s.click(),window.URL.revokeObjectURL(t),document.body.removeChild(s)}else throw new Error("DataStream.save: Can't create object URL.");return e}get dynamicSize(){return this._dynamicSize}set dynamicSize(i){i||this._trimAlloc(),this._dynamicSize=i}shift(i){const e=new xt(this._byteLength-i),t=new Uint8Array(e),s=new Uint8Array(this._buffer,i,t.length);t.set(s),this.buffer=e,this.position-=i}writeInt32Array(i,e){if(this._realloc(i.length*4),i instanceof Int32Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapInt32Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeInt32(i[t],e)}writeInt16Array(i,e){if(this._realloc(i.length*2),i instanceof Int16Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapInt16Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeInt16(i[t],e)}writeInt8Array(i){if(this._realloc(i.length*1),i instanceof Int8Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapInt8Array(i.length);else for(let e=0;e<i.length;e++)this.writeInt8(i[e])}writeUint32Array(i,e){if(this._realloc(i.length*4),i instanceof Uint32Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapUint32Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeUint32(i[t],e)}writeUint16Array(i,e){if(this._realloc(i.length*2),i instanceof Uint16Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapUint16Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeUint16(i[t],e)}writeUint8Array(i){if(this._realloc(i.length*1),i instanceof Uint8Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapUint8Array(i.length);else for(let e=0;e<i.length;e++)this.writeUint8(i[e])}writeFloat64Array(i,e){if(this._realloc(i.length*8),i instanceof Float64Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapFloat64Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeFloat64(i[t],e)}writeFloat32Array(i,e){if(this._realloc(i.length*4),i instanceof Float32Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapFloat32Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeFloat32(i[t],e)}writeInt64(i,e){this._realloc(8),this._dataView.setBigInt64(this.position,BigInt(i),(e??this.endianness)===2),this.position+=8}writeInt32(i,e){this._realloc(4),this._dataView.setInt32(this.position,i,(e??this.endianness)===2),this.position+=4}writeInt16(i,e){this._realloc(2),this._dataView.setInt16(this.position,i,(e??this.endianness)===2),this.position+=2}writeInt8(i){this._realloc(1),this._dataView.setInt8(this.position,i),this.position+=1}writeUint32(i,e){this._realloc(4),this._dataView.setUint32(this.position,i,(e??this.endianness)===2),this.position+=4}writeUint16(i,e){this._realloc(2),this._dataView.setUint16(this.position,i,(e??this.endianness)===2),this.position+=2}writeUint8(i){this._realloc(1),this._dataView.setUint8(this.position,i),this.position+=1}writeFloat32(i,e){this._realloc(4),this._dataView.setFloat32(this.position,i,(e??this.endianness)===2),this.position+=4}writeFloat64(i,e){this._realloc(8),this._dataView.setFloat64(this.position,i,(e??this.endianness)===2),this.position+=8}writeUCS2String(i,e,t){t===void 0&&(t=i.length);let s;for(s=0;s<i.length&&s<t;s++)this.writeUint16(i.charCodeAt(s),e);for(;s<t;s++)this.writeUint16(0)}writeString(i,e,t){let s=0;if(e===void 0||e==="ASCII")if(t!==void 0){const r=Math.min(i.length,t);for(s=0;s<r;s++)this.writeUint8(i.charCodeAt(s));for(;s<t;s++)this.writeUint8(0)}else for(s=0;s<i.length;s++)this.writeUint8(i.charCodeAt(s));else this.writeUint8Array(new TextEncoder(e).encode(i.substring(0,t)))}writeCString(i,e){let t=0;if(e!==void 0){const s=Math.min(i.length,e);for(t=0;t<s;t++)this.writeUint8(i.charCodeAt(t));for(;t<e;t++)this.writeUint8(0)}else{for(t=0;t<i.length;t++)this.writeUint8(i.charCodeAt(t));this.writeUint8(0)}}writeStruct(i,e){for(let t=0;t<i.length;t++){const[s,r]=i[t],n=e[s];this.writeType(r,n,e)}}writeType(i,e,t){if(typeof i=="function")return i(this,e);if(typeof i=="object"&&!(i instanceof Array))return i.set(this,e,t);let s,r="ASCII";const n=this.position;let o=i;if(typeof i=="string"&&/:/.test(i)){const a=i.split(":");o=a[0],s=parseInt(a[1])}if(typeof o=="string"&&/,/.test(o)){const a=o.split(",");o=a[0],r=a[1]}switch(o){case"uint8":this.writeUint8(e);break;case"int8":this.writeInt8(e);break;case"uint16":this.writeUint16(e,this.endianness);break;case"int16":this.writeInt16(e,this.endianness);break;case"uint32":this.writeUint32(e,this.endianness);break;case"int32":this.writeInt32(e,this.endianness);break;case"float32":this.writeFloat32(e,this.endianness);break;case"float64":this.writeFloat64(e,this.endianness);break;case"uint16be":this.writeUint16(e,1);break;case"int16be":this.writeInt16(e,1);break;case"uint32be":this.writeUint32(e,1);break;case"int32be":this.writeInt32(e,1);break;case"float32be":this.writeFloat32(e,1);break;case"float64be":this.writeFloat64(e,1);break;case"uint16le":this.writeUint16(e,2);break;case"int16le":this.writeInt16(e,2);break;case"uint32le":this.writeUint32(e,2);break;case"int32le":this.writeInt32(e,2);break;case"float32le":this.writeFloat32(e,2);break;case"float64le":this.writeFloat64(e,2);break;case"cstring":this.writeCString(e,s);break;case"string":this.writeString(e,r,s);break;case"u16string":this.writeUCS2String(e,this.endianness,s);break;case"u16stringle":this.writeUCS2String(e,2,s);break;case"u16stringbe":this.writeUCS2String(e,1,s);break;default:if(pf(this,ir,bn).call(this,o)){const[,a]=o;for(let l=0;l<e.length;l++)this.writeType(a,e[l]);break}else{this.writeStruct(o,e);break}}s&&(this.position=n,this._realloc(s),this.position=n+s)}writeUint64(i){const e=Math.floor(i/vn);this.writeUint32(e),this.writeUint32(i&4294967295)}writeUint24(i){this.writeUint8((i&16711680)>>16),this.writeUint8((i&65280)>>8),this.writeUint8(i&255)}adjustUint32(i,e){const t=this.position;this.seek(i),this.writeUint32(e),this.seek(t)}readStruct(i){const e={},t=this.position;for(let s=0;s<i.length;s+=1){const r=i[s][1],n=this.readType(r,e);if(!n){this.failurePosition===0&&(this.failurePosition=this.position),this.position=t;return}e[i[s][0]]=n}return e}readUCS2String(i,e){return String.fromCharCode.apply(void 0,this.readUint16Array(i,e))}readType(i,e){if(typeof i=="function")return i(this,e);if(typeof i=="object"&&!(i instanceof Array))return i.get(this,e);if(i instanceof Array&&i.length!==3)return this.readStruct(i);let t,s,r="ASCII";const n=this.position;let o=i;if(typeof o=="string"&&/:/.test(o)){const a=o.split(":");o=a[0],s=parseInt(a[1])}if(typeof o=="string"&&/,/.test(o)){const a=o.split(",");o=a[0],r=a[1]}switch(o){case"uint8":t=this.readUint8();break;case"int8":t=this.readInt8();break;case"uint16":t=this.readUint16(this.endianness);break;case"int16":t=this.readInt16(this.endianness);break;case"uint32":t=this.readUint32(this.endianness);break;case"int32":t=this.readInt32(this.endianness);break;case"float32":t=this.readFloat32(this.endianness);break;case"float64":t=this.readFloat64(this.endianness);break;case"uint16be":t=this.readUint16(1);break;case"int16be":t=this.readInt16(1);break;case"uint32be":t=this.readUint32(1);break;case"int32be":t=this.readInt32(1);break;case"float32be":t=this.readFloat32(1);break;case"float64be":t=this.readFloat64(1);break;case"uint16le":t=this.readUint16(2);break;case"int16le":t=this.readInt16(2);break;case"uint32le":t=this.readUint32(2);break;case"int32le":t=this.readInt32(2);break;case"float32le":t=this.readFloat32(2);break;case"float64le":t=this.readFloat64(2);break;case"cstring":t=this.readCString(s);break;case"string":t=this.readString(s,r);break;case"u16string":t=this.readUCS2String(s,this.endianness);break;case"u16stringle":t=this.readUCS2String(s,2);break;case"u16stringbe":t=this.readUCS2String(s,1);break;default:if(pf(this,ir,bn).call(this,o)){const[,a,l]=o,c=typeof l=="function"?l(e,this,o):typeof l=="string"&&e[l]!==void 0?parseInt(e[l]):typeof l=="number"?l:l==="*"?void 0:parseInt(l);if(typeof a=="string"){const h=a.replace(/(le|be)$/,"");let u;switch(/le$/.test(a)?u=2:/be$/.test(a)&&(u=1),h){case"uint8":t=this.readUint8Array(c);break;case"uint16":t=this.readUint16Array(c,u);break;case"uint32":t=this.readUint32Array(c,u);break;case"int8":t=this.readInt8Array(c);break;case"int16":t=this.readInt16Array(c,u);break;case"int32":t=this.readInt32Array(c,u);break;case"float32":t=this.readFloat32Array(c,u);break;case"float64":t=this.readFloat64Array(c,u);break;case"cstring":case"utf16string":case"string":if(c){t=new Array(c);for(let d=0;d<c;d++)t[d]=this.readType(a,e)}else for(t=[];!this.isEof();){const d=this.readType(a,e);if(!d)break;t.push(d)}break}}else if(c){t=new Array(c);for(let h=0;h<c;h++){const u=this.readType(a,e);if(!u)return;t[h]=u}}else for(t=[];;){const h=this.position;try{const u=this.readType(a,e);if(!u){this.position=h;break}t.push(u)}catch{this.position=h;break}}break}}return s&&(this.position=n+s),t}mapInt32Array(i,e){this._realloc(i*4);const t=new Int32Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*4,t}mapInt16Array(i,e){this._realloc(i*2);const t=new Int16Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*2,t}mapInt8Array(i,e){this._realloc(i*1);const t=new Int8Array(this._buffer,this.byteOffset+this.position,i);return this.position+=i*1,t}mapUint32Array(i,e){this._realloc(i*4);const t=new Uint32Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*4,t}mapUint16Array(i,e){this._realloc(i*2);const t=new Uint16Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*2,t}mapFloat64Array(i,e){this._realloc(i*8);const t=new Float64Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*8,t}mapFloat32Array(i,e){this._realloc(i*4);const t=new Float32Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*4,t}},ir=new WeakSet,bn=function(i){return Array.isArray(i)&&i.length===3&&i[0]==="[]"},Z.ENDIANNESS=new Int8Array(new Int16Array([1]).buffer)[0]>0?2:1,Z);function yf(i){const e=[];for(let t=0;t<i.length;t++)e[t]=i[t];return String.fromCharCode.apply(void 0,e)}var sr=new Date,Tn=4,vf=3,bf=2,Tf=1,Vt=Tn,I={setLogLevel(i){i===this.debug?Vt=Tf:i===this.info?Vt=bf:i===this.warn?Vt=vf:(this.error,Vt=Tn)},debug(i,e){console.debug===void 0&&(console.debug=console.log),Tf>=Vt&&console.debug("["+I.getDurationString(new Date().getTime()-sr.getTime(),1e3)+"]","["+i+"]",e)},log(i,e){this.debug(i.msg)},info(i,e){bf>=Vt&&console.info("["+I.getDurationString(new Date().getTime()-sr.getTime(),1e3)+"]","["+i+"]",e)},warn(i,e){vf>=Vt&&console.warn("["+I.getDurationString(new Date().getTime()-sr.getTime(),1e3)+"]","["+i+"]",e)},error(i,e,t){t?.onError?t.onError(i,e):Tn>=Vt&&console.error("["+I.getDurationString(new Date().getTime()-sr.getTime(),1e3)+"]","["+i+"]",e)},getDurationString(i,e){let t;function s(l,c){const h=(""+l).split(".");for(;h[0].length<c;)h[0]="0"+h[0];return h.join(".")}i<0?(t=!0,i=-i):t=!1;let r=i/(e||1);const n=Math.floor(r/3600);r-=n*3600;const o=Math.floor(r/60);r-=o*60;let a=r*1e3;return r=Math.floor(r),a-=r*1e3,a=Math.floor(a),(t?"-":"")+n+":"+s(o,2)+":"+s(r,2)+"."+s(a,3)},printRanges(i){const e=i.length;if(e>0){let t="";for(let s=0;s<e;s++)s>0&&(t+=","),t+="["+I.getDurationString(i.start(s))+","+I.getDurationString(i.end(s))+"]";return t}else return"(empty)"}};function Sy(i,e){I.debug("ArrayBuffer","Trying to create a new buffer of size: "+(i.byteLength+e.byteLength));const t=new Uint8Array(i.byteLength+e.byteLength);return t.set(new Uint8Array(i),0),t.set(new Uint8Array(e),i.byteLength),t.buffer}var Ti=class extends Pe{constructor(i){super(new ArrayBuffer,0),this.buffers=[],this.bufferIndex=-1,i&&(this.insertBuffer(i),this.bufferIndex=0)}initialized(){if(this.bufferIndex>-1)return!0;if(this.buffers.length>0){const i=this.buffers[0];return i.fileStart===0?(this.buffer=i,this.bufferIndex=0,I.debug("MultiBufferStream","Stream ready for parsing"),!0):(I.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)}else return I.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1}reduceBuffer(i,e,t){const s=new Uint8Array(t);return s.set(new Uint8Array(i,e,t)),s.buffer.fileStart=i.fileStart+e,s.buffer.usedBytes=0,s.buffer}insertBuffer(i){let e=!0,t=0;for(;t<this.buffers.length;t++){const s=this.buffers[t];if(i.fileStart<=s.fileStart){if(i.fileStart===s.fileStart)if(i.byteLength>s.byteLength){this.buffers.splice(t,1),t--;continue}else I.warn("MultiBufferStream","Buffer (fileStart: "+i.fileStart+" - Length: "+i.byteLength+") already appended, ignoring");else i.fileStart+i.byteLength<=s.fileStart||(i=this.reduceBuffer(i,0,s.fileStart-i.fileStart)),I.debug("MultiBufferStream","Appending new buffer (fileStart: "+i.fileStart+" - Length: "+i.byteLength+")"),this.buffers.splice(t,0,i),t===0&&(this.buffer=i);e=!1;break}else if(i.fileStart<s.fileStart+s.byteLength){const r=s.fileStart+s.byteLength-i.fileStart,n=i.byteLength-r;if(n>0)i=this.reduceBuffer(i,r,n);else{e=!1;break}}}e&&(I.debug("MultiBufferStream","Appending new buffer (fileStart: "+i.fileStart+" - Length: "+i.byteLength+")"),this.buffers.push(i),t===0&&(this.buffer=i))}logBufferLevel(i){const e=[];let t="",s,r=0,n=0;for(let a=0;a<this.buffers.length;a++){const l=this.buffers[a];a===0?(s={start:l.fileStart,end:l.fileStart+l.byteLength},e.push(s),t+="["+s.start+"-"):s.end===l.fileStart?s.end=l.fileStart+l.byteLength:(s={start:l.fileStart,end:l.fileStart+l.byteLength},t+=e[e.length-1].end-1+"], ["+s.start+"-",e.push(s)),r+=l.usedBytes,n+=l.byteLength}e.length>0&&(t+=s.end-1+"]");const o=i?I.info:I.debug;this.buffers.length===0?o("MultiBufferStream","No more buffer in memory"):o("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+r+"/"+n+" bytes), continuous ranges: "+t)}cleanBuffers(){for(let i=0;i<this.buffers.length;i++){const e=this.buffers[i];e.usedBytes===e.byteLength&&(I.debug("MultiBufferStream","Removing buffer #"+i),this.buffers.splice(i,1),i--)}}mergeNextBuffer(){if(this.bufferIndex+1<this.buffers.length){const i=this.buffers[this.bufferIndex+1];if(i.fileStart===this.buffer.fileStart+this.buffer.byteLength){const e=this.buffer.byteLength,t=this.buffer.usedBytes,s=this.buffer.fileStart;return this.buffers[this.bufferIndex]=Sy(this.buffer,i),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=t,this.buffer.fileStart=s,I.debug("ISOFile","Concatenating buffer for box parsing (length: "+e+"->"+this.buffer.byteLength+")"),!0}else return!1}else return!1}findPosition(i,e,t){let s=-1,r=i===!0?0:this.bufferIndex;for(;r<this.buffers.length;){const o=this.buffers[r];if(o&&o.fileStart<=e)s=r,t&&(o.fileStart+o.byteLength<=e?o.usedBytes=o.byteLength:o.usedBytes=e-o.fileStart,this.logBufferLevel());else break;r++}if(s===-1)return-1;const n=this.buffers[s];return n.fileStart+n.byteLength>=e?(I.debug("MultiBufferStream","Found position in existing buffer #"+s),s):-1}findEndContiguousBuf(i){const e=i!==void 0?i:this.bufferIndex;let t=this.buffers[e];if(this.buffers.length>e+1)for(let s=e+1;s<this.buffers.length;s++){const r=this.buffers[s];if(r.fileStart===t.fileStart+t.byteLength)t=r;else break}return t.fileStart+t.byteLength}getEndFilePositionAfter(i){const e=this.findPosition(!0,i,!1);return e!==-1?this.findEndContiguousBuf(e):i}addUsedBytes(i){this.buffer.usedBytes+=i,this.logBufferLevel()}setAllUsedBytes(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()}seek(i,e,t){const s=this.findPosition(e,i,t);return s!==-1?(this.buffer=this.buffers[s],this.bufferIndex=s,this.position=i-this.buffer.fileStart,I.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(I.debug("MultiBufferStream","Position "+i+" not found in buffered data"),!1)}getPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.position}getLength(){return this.byteLength}getEndPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.byteLength}getAbsoluteEndPosition(){if(this.buffers.length===0)return 0;const i=this.buffers[this.buffers.length-1];return i.fileStart+i.byteLength}},rr,wn,B=(wn=class{constructor(i=0){ff(this,rr),this.size=i}get type(){return this.constructor.fourcc??xy(this,rr)}set type(i){yy(this,rr,i)}addBox(i){return this.boxes||(this.boxes=[]),this.boxes.push(i),this[i.type+"s"]?this[i.type+"s"].push(i):this[i.type]=i,i}set(i,e){return this[i]=e,this}addEntry(i,e){const t=e||"entries";return this[t]||(this[t]=[]),this[t].push(i),this}writeHeader(i,e){if(this.size+=8,(this.size>Ae||this.original_size===1)&&(this.size+=8),this.type==="uuid"&&(this.size+=16),I.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+i.getPosition()+(e||"")),this.original_size===0?i.writeUint32(0):this.size>Ae||this.original_size===1?i.writeUint32(1):(this.sizePosition=i.getPosition(),i.writeUint32(this.size)),i.writeString(this.type,void 0,4),this.type==="uuid"){const t=new Uint8Array(16);for(let s=0;s<16;s++)t[s]=parseInt(this.uuid.substring(s*2,s*2+2),16);i.writeUint8Array(t)}(this.size>Ae||this.original_size===1)&&(this.sizePosition=i.getPosition(),i.writeUint64(this.size))}write(i){if(this.type==="mdat"){const e=this;if(e.stream){this.size=e.stream.getAbsoluteEndPosition(),this.writeHeader(i);for(const t of e.stream.buffers){const s=new Uint8Array(t);i.writeUint8Array(s)}}else e.data&&(this.size=e.data.length,this.writeHeader(i),i.writeUint8Array(e.data))}else this.size=this.data?this.data.length:0,this.writeHeader(i),this.data&&i.writeUint8Array(this.data)}printHeader(i){this.size+=8,this.size>Ae&&(this.size+=8),this.type==="uuid"&&(this.size+=16),i.log(i.indent+"size:"+this.size),i.log(i.indent+"type:"+this.type)}print(i){this.printHeader(i)}parse(i){this.type!=="mdat"?this.data=i.readUint8Array(this.size-this.hdr_size):this.size===0?i.seek(i.getEndPosition()):i.seek(this.start+this.size)}parseDataAndRewind(i){this.data=i.readUint8Array(this.size-this.hdr_size),i.seek(this.start+this.hdr_size)}parseLanguage(i){this.language=i.readUint16();const e=[];e[0]=this.language>>10&31,e[1]=this.language>>5&31,e[2]=this.language&31,this.languageString=String.fromCharCode(e[0]+96,e[1]+96,e[2]+96)}computeSize(i){const e=i||new Ti;this.write(e)}isEndOfBox(i){const e=i.getPosition(),t=this.start+this.size;return e===t}},rr=new WeakMap,wn.registryId=Symbol.for("BoxIdentifier"),wn),R=class extends B{constructor(){super(...arguments),this.flags=0,this.version=0}writeHeader(e){this.size+=4,super.writeHeader(e," v="+this.version+" f="+this.flags),e.writeUint8(this.version),e.writeUint24(this.flags)}printHeader(e){this.size+=4,super.printHeader(e),e.log(e.indent+"version:"+this.version),e.log(e.indent+"flags:"+this.flags)}parseDataAndRewind(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,e.seek(this.start+this.hdr_size)}parseFullHeader(e){this.version=e.readUint8(),this.flags=e.readUint24(),this.hdr_size+=4}parse(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)}},Sn,ye=(Sn=class{constructor(i){this.grouping_type=i}write(i){i.writeUint8Array(this.data)}parse(i){I.warn("BoxParser",`Unknown sample group type: '${this.grouping_type}'`),this.data=i.readUint8Array(this.description_length)}},Sn.registryId=Symbol.for("SampleGroupEntryIdentifier"),Sn),wf=class extends R{parse(i){this.parseFullHeader(i),this.track_group_id=i.readUint32()}},Sf=class extends B{constructor(i,e,t,s,r){super(e),this.box_name=t,this.hdr_size=s,this.start=r,this.type=i}parse(i){this.from_item_ID=i.readUint16();const e=i.readUint16();this.references=[];for(let t=0;t<e;t++)this.references[t]={to_item_ID:i.readUint16()}}},Cf=class extends B{constructor(i,e,t,s,r){super(e),this.box_name=t,this.hdr_size=s,this.start=r,this.type=i}parse(i){this.from_item_ID=i.readUint32();const e=i.readUint16();this.references=[];for(let t=0;t<e;t++)this.references[t]={to_item_ID:i.readUint32()}}},Af=class extends B{constructor(i,e,t,s){super(e),this.hdr_size=t,this.start=s,this.type=i}parse(i){this.track_ids=i.readUint32Array((this.size-this.hdr_size)/4)}write(i){this.size=this.track_ids.length*4,this.writeHeader(i),i.writeUint32Array(this.track_ids)}},nr=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],Ef=["compatible_brands","matrix","opcolor","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"];function If(i,e){if(i&&!e)return!1;let t;for(t in i)if(!nr.find(s=>s===t)){if(i[t]instanceof B||e[t]instanceof B||typeof i[t]>"u"||typeof e[t]>"u"||typeof i[t]=="function"||typeof e[t]=="function"||"subBoxNames"in i&&i.subBoxNames.indexOf(t.slice(0,4))>-1||"subBoxNames"in e&&e.subBoxNames.indexOf(t.slice(0,4))>-1||t==="data"||t==="start"||t==="size"||t==="creation_time"||t==="modification_time"||Ef.find(s=>s===t))continue;if(i[t]!==e[t])return!1}return!0}function Cn(i,e){if(!If(i,e))return!1;for(let t=0;t<nr.length;t++){const s=nr[t];if(i[s]&&e[s]&&!Cn(i[s],e[s]))return!1}return!0}function An(i){let e=i;for(;e;){if("registryId"in e)return e.registryId;e=Object.getPrototypeOf(e)}}var Cy=i=>{const e=Symbol.for("SampleGroupEntryIdentifier");return An(i)===e},Ay=i=>{const e=Symbol.for("SampleEntryIdentifier");return An(i)===e},Ey=i=>{const e=Symbol.for("BoxIdentifier");return An(i)===e},Ve={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};function Iy(i){const e={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};for(const[t,s]of Object.entries(i)){if(Cy(s)){const r="grouping_type"in s?s.grouping_type:void 0;if(!r)throw new Error(`SampleGroupEntry class ${t} does not have a valid static grouping_type. Please ensure it is defined correctly.`);if(r in e.sampleGroupEntry)throw new Error(`SampleGroupEntry class ${t} has a grouping_type that is already registered. Please ensure it is unique.`);e.sampleGroupEntry[r]=s;continue}if(Ay(s)){const r="fourcc"in s?s.fourcc:void 0;if(!r)throw new Error(`SampleEntry class ${t} does not have a valid static fourcc. Please ensure it is defined correctly.`);if(r in e.sampleEntry)throw new Error(`SampleEntry class ${t} has a fourcc that is already registered. Please ensure it is unique.`);e.sampleEntry[r]=s;continue}if(Ey(s)){const r="fourcc"in s?s.fourcc:void 0,n="uuid"in s?s.uuid:void 0;if(r==="uuid"){if(!n)throw new Error(`Box class ${t} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.`);if(n in e.uuid)throw new Error(`Box class ${t} has a uuid that is already registered. Please ensure it is unique.`);e.uuid[n]=s;continue}e.box[r]=s;continue}throw new Error(`Box class ${t} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.`)}return Ve.uuid={...e.uuid},Ve.sampleEntry={...e.sampleEntry},Ve.sampleGroupEntry={...e.sampleGroupEntry},Ve.box={...e.box},Ve}var or={};function Py(i){return Object.entries(i).forEach(([e,t])=>or[e]=t),or}function Ry(i){return ri(i)}function ri(i){let e="";for(let t=0;t<16;t++){const s=i.readUint8().toString(16);e+=s.length===1?"0"+s:s}return e}function ht(i,e,t){let s,r;const n=i.getPosition();let o=0,a;if(i.getEndPosition()-n<8)return I.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:Wt};if(t&&t<8)return I.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:Wt};let l=i.readUint32();const c=i.readString(4);if(c.length!==4||!/^[\x20-\x7E]{4}$/.test(c))return I.error("BoxParser",`Invalid box type: '${c}'`),{code:_f,start:n,type:c};let h=c;if(I.debug("BoxParser","Found box of type '"+c+"' and size "+l+" at position "+n),o=8,c==="uuid"){if(i.getEndPosition()-i.getPosition()<16||t-o<16)return i.seek(n),I.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:Wt};a=Ry(i),o+=16,h=a}if(l===1){if(i.getEndPosition()-i.getPosition()<8||t&&t-o<8)return i.seek(n),I.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+c+'" box'),{code:Wt};r=l,l=i.readUint64(),o+=8}else if(l===0){if(t)l=t;else if(c!=="mdat")return I.error("BoxParser","Unlimited box size not supported for type: '"+c+"'"),s=new B(l),s.type=c,{code:We,box:s,size:s.size}}if(l!==0&&l<o)return I.error("BoxParser","Box of type "+c+" has an invalid size "+l+" (too small to be a box)"),{code:Wt,type:c,size:l,hdr_size:o,start:n};if(l!==0&&t&&l>t)return I.error("BoxParser","Box of type '"+c+"' has a size "+l+" greater than its container size "+t),{code:Wt,type:c,size:l,hdr_size:o,start:n};if(l!==0&&n+l>i.getEndPosition())return i.seek(n),I.info("BoxParser","Not enough data in stream to parse the entire '"+c+"' box"),{code:Wt,type:c,size:l,hdr_size:o,start:n,original_size:r};if(e)return{code:We,type:c,size:l,hdr_size:o,start:n};c in Ve.box?s=new Ve.box[c](l):c!=="uuid"?(I.warn("BoxParser",`Unknown box type: '${c}'`),s=new B(l),s.type=c,s.has_unparsed_data=!0):a in Ve.uuid?s=new Ve.uuid[a](l):(I.warn("BoxParser",`Unknown UUID box type: '${a}'`),s=new B(l),s.type=c,s.uuid=a,s.has_unparsed_data=!0),s.original_size=r,s.hdr_size=o,s.start=n,s.write===B.prototype.write&&s.type!=="mdat"&&(I.info("BoxParser","'"+h+"' box writing not yet implemented, keeping unparsed data in memory for later write"),s.parseDataAndRewind(i)),s.parse(i);const u=i.getPosition()-(s.start+s.size);return u<0?(I.warn("BoxParser","Parsing of box '"+h+"' did not read the entire indicated box data size (missing "+-u+" bytes), seeking forward"),i.seek(s.start+s.size)):u>0&&s.size!==0&&(I.error("BoxParser","Parsing of box '"+h+"' read "+u+" more bytes than the indicated box data size, seeking backwards"),i.seek(s.start+s.size)),{code:We,box:s,size:s.size}}var ee=class extends B{write(e){if(this.size=0,this.writeHeader(e),this.boxes)for(let t=0;t<this.boxes.length;t++)this.boxes[t]&&(this.boxes[t].write(e),this.size+=this.boxes[t].size);I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)}print(e){this.printHeader(e);for(let t=0;t<this.boxes.length;t++)if(this.boxes[t]){const s=e.indent;e.indent+=" ",this.boxes[t].print(e),e.indent=s}}parse(e){let t;for(;e.getPosition()<this.start+this.size;)if(t=ht(e,!1,this.size-(e.getPosition()-this.start)),t.code===We){const s=t.box;if(this.boxes||(this.boxes=[]),this.boxes.push(s),this.subBoxNames&&this.subBoxNames.indexOf(s.type)!==-1){const r=this.subBoxNames[this.subBoxNames.indexOf(s.type)]+"s";this[r]||(this[r]=[]),this[r].push(s)}else{const r=s.type!=="uuid"?s.type:s.uuid;this[r]?I.warn("ContainerBox",`Box of type ${r} already exists in container box ${this.type}.`):this[r]=s}}else return}},En,yt=(En=class extends ee{constructor(i,e,t){super(i),this.hdr_size=e,this.start=t}isVideo(){return!1}isAudio(){return!1}isSubtitle(){return!1}isMetadata(){return!1}isHint(){return!1}getCodec(){return this.type.replace(".","")}getWidth(){return""}getHeight(){return""}getChannelCount(){return""}getSampleRate(){return""}getSampleSize(){return""}parseHeader(i){i.readUint8Array(6),this.data_reference_index=i.readUint16(),this.hdr_size+=8}parse(i){this.parseHeader(i),this.data=i.readUint8Array(this.size-this.hdr_size)}parseDataAndRewind(i){this.parseHeader(i),this.data=i.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,i.seek(this.start+this.hdr_size)}parseFooter(i){super.parse(i)}writeHeader(i){this.size=8,super.writeHeader(i),i.writeUint8(0),i.writeUint8(0),i.writeUint8(0),i.writeUint8(0),i.writeUint8(0),i.writeUint8(0),i.writeUint16(this.data_reference_index)}writeFooter(i){if(this.boxes)for(let e=0;e<this.boxes.length;e++)this.boxes[e].write(i),this.size+=this.boxes[e].size;I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),i.adjustUint32(this.sizePosition,this.size)}write(i){this.writeHeader(i),i.writeUint8Array(this.data),this.size+=this.data.length,I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),i.adjustUint32(this.sizePosition,this.size)}},En.registryId=Symbol.for("SampleEntryIdentifier"),En),In=class extends yt{},ni=class extends yt{isMetadata(){return!0}},$t=class extends yt{isSubtitle(){return!0}},Pf=class extends yt{},fe=class extends yt{parse(e){this.parseHeader(e),e.readUint16(),e.readUint16(),e.readUint32Array(3),this.width=e.readUint16(),this.height=e.readUint16(),this.horizresolution=e.readUint32(),this.vertresolution=e.readUint32(),e.readUint32(),this.frame_count=e.readUint16();const t=Math.min(31,e.readUint8());this.compressorname=e.readString(t),t<31&&e.readString(31-t),this.depth=e.readUint16(),e.readUint16(),this.parseFooter(e)}isVideo(){return!0}getWidth(){return this.width}getHeight(){return this.height}write(e){this.writeHeader(e),this.size+=70,e.writeUint16(0),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.width),e.writeUint16(this.height),e.writeUint32(this.horizresolution),e.writeUint32(this.vertresolution),e.writeUint32(0),e.writeUint16(this.frame_count),e.writeUint8(Math.min(31,this.compressorname.length)),e.writeString(this.compressorname,void 0,31),e.writeUint16(this.depth),e.writeInt16(-1),this.writeFooter(e)}},ze=class extends yt{parse(e){this.parseHeader(e),this.version=e.readUint16(),e.readUint16(),e.readUint32(),this.channel_count=e.readUint16(),this.samplesize=e.readUint16(),e.readUint16(),e.readUint16(),this.samplerate=e.readUint32()/65536,e.isofile?.ftyp?.major_brand.includes("qt")&&(this.version===1?this.extensions=e.readUint8Array(16):this.version===2&&(this.extensions=e.readUint8Array(36))),this.parseFooter(e)}isAudio(){return!0}getChannelCount(){return this.channel_count}getSampleRate(){return this.samplerate}getSampleSize(){return this.samplesize}write(e){this.writeHeader(e),this.size+=20,e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.channel_count),e.writeUint16(this.samplesize),e.writeUint16(0),e.writeUint16(0),e.writeUint32(this.samplerate<<16),this.writeFooter(e)}},ar=class extends yt{parse(i){this.parseHeader(i),this.parseFooter(i)}write(i){this.writeHeader(i),this.writeFooter(i)}},Rf=class extends Array{toString(){let i="<table class='inner-table'>";i+="<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",i+="<tbody>";for(let e=0;e<this.length;e++){const t=this[e];i+="<tr>",i+="<td>"+t.length+"</td>",i+="<td>",i+=t.data.reduce(function(s,r){return s+r.toString(16).padStart(2,"0")},"0x"),i+="</td></tr>"}return i+="</tbody></table>",i}},Pn,Mf=(Pn=class extends B{constructor(){super(...arguments),this.box_name="AVCConfigurationBox"}parse(i){this.configurationVersion=i.readUint8(),this.AVCProfileIndication=i.readUint8(),this.profile_compatibility=i.readUint8(),this.AVCLevelIndication=i.readUint8(),this.lengthSizeMinusOne=i.readUint8()&3,this.nb_SPS_nalus=i.readUint8()&31;let e=this.size-this.hdr_size-6;this.SPS=new Rf;for(let t=0;t<this.nb_SPS_nalus;t++){const s=i.readUint16();this.SPS.push({length:s,data:i.readUint8Array(s)}),e-=2+s}this.nb_PPS_nalus=i.readUint8(),e--,this.PPS=new Rf;for(let t=0;t<this.nb_PPS_nalus;t++){const s=i.readUint16();this.PPS.push({length:s,data:i.readUint8Array(s)}),e-=2+s}e>0&&(this.ext=i.readUint8Array(e))}write(i){this.size=7;for(let e=0;e<this.SPS.length;e++)this.size+=2+this.SPS[e].length;for(let e=0;e<this.PPS.length;e++)this.size+=2+this.PPS[e].length;this.ext&&(this.size+=this.ext.length),this.writeHeader(i),i.writeUint8(this.configurationVersion),i.writeUint8(this.AVCProfileIndication),i.writeUint8(this.profile_compatibility),i.writeUint8(this.AVCLevelIndication),i.writeUint8(this.lengthSizeMinusOne+252),i.writeUint8(this.SPS.length+224);for(let e=0;e<this.SPS.length;e++)i.writeUint16(this.SPS[e].length),i.writeUint8Array(this.SPS[e].data);i.writeUint8(this.PPS.length);for(let e=0;e<this.PPS.length;e++)i.writeUint16(this.PPS[e].length),i.writeUint8Array(this.PPS[e].data);this.ext&&i.writeUint8Array(this.ext)}},Pn.fourcc="avcC",Pn),Rn,lr=(Rn=class extends B{constructor(){super(...arguments),this.box_name="MediaDataBox"}},Rn.fourcc="mdat",Rn),Mn,My=(Mn=class extends B{constructor(){super(...arguments),this.box_name="ItemDataBox"}},Mn.fourcc="idat",Mn),kn,ky=(kn=class extends B{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}},kn.fourcc="free",kn),Fn,Fy=(Fn=class extends B{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}},Fn.fourcc="skip",Fn),Bn,kf=(Bn=class extends R{constructor(){super(...arguments),this.box_name="HintMediaHeaderBox"}},Bn.fourcc="hmhd",Bn),Un,cr=(Un=class extends R{constructor(){super(...arguments),this.box_name="NullMediaHeaderBox"}},Un.fourcc="nmhd",Un),On,By=(On=class extends R{constructor(){super(...arguments),this.box_name="ObjectDescriptorBox"}},On.fourcc="iods",On),Dn,Uy=(Dn=class extends R{constructor(){super(...arguments),this.box_name="XMLBox"}},Dn.fourcc="xml ",Dn),Gn,Oy=(Gn=class extends R{constructor(){super(...arguments),this.box_name="BinaryXMLBox"}},Gn.fourcc="bxml",Gn),zn,Dy=(zn=class extends R{constructor(){super(...arguments),this.box_name="ItemProtectionBox",this.sinfs=[]}get protections(){return this.sinfs}},zn.fourcc="ipro",zn),Nn,Ln=(Nn=class extends ee{constructor(){super(...arguments),this.box_name="MovieBox",this.traks=[],this.psshs=[],this.subBoxNames=["trak","pssh"]}},Nn.fourcc="moov",Nn),Hn,Ff=(Hn=class extends ee{constructor(){super(...arguments),this.box_name="TrackBox",this.samples=[]}},Hn.fourcc="trak",Hn),Wn,Gy=(Wn=class extends ee{constructor(){super(...arguments),this.box_name="EditBox"}},Wn.fourcc="edts",Wn),Vn,Bf=(Vn=class extends ee{constructor(){super(...arguments),this.box_name="MediaBox"}},Vn.fourcc="mdia",Vn),$n,Uf=($n=class extends ee{constructor(){super(...arguments),this.box_name="MediaInformationBox"}},$n.fourcc="minf",$n),Xn,Of=(Xn=class extends ee{constructor(){super(...arguments),this.box_name="DataInformationBox"}},Xn.fourcc="dinf",Xn),Yn,Df=(Yn=class extends ee{constructor(){super(...arguments),this.box_name="SampleTableBox",this.sgpds=[],this.sbgps=[],this.subBoxNames=["sgpd","sbgp"]}},Yn.fourcc="stbl",Yn),qn,Kn=(qn=class extends ee{constructor(){super(...arguments),this.box_name="MovieExtendsBox",this.trexs=[],this.subBoxNames=["trex"]}},qn.fourcc="mvex",qn),jn,Gf=(jn=class extends ee{constructor(){super(...arguments),this.box_name="MovieFragmentBox",this.trafs=[],this.subBoxNames=["traf"]}},jn.fourcc="moof",jn),Zn,zf=(Zn=class extends ee{constructor(){super(...arguments),this.box_name="TrackFragmentBox",this.truns=[],this.sgpds=[],this.sbgps=[],this.subBoxNames=["trun","sgpd","sbgp"]}},Zn.fourcc="traf",Zn),Jn,zy=(Jn=class extends ee{constructor(){super(...arguments),this.box_name="VTTCueBox"}},Jn.fourcc="vttc",Jn),Qn,Ny=(Qn=class extends ee{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessBox",this.tfras=[],this.subBoxNames=["tfra"]}},Qn.fourcc="mfra",Qn),eo,Ly=(eo=class extends ee{constructor(){super(...arguments),this.box_name="AdditionalMetadataContainerBox"}},eo.fourcc="meco",eo),to,Hy=(to=class extends ee{constructor(){super(...arguments),this.box_name="trackhintinformation",this.subBoxNames=["sdp ","rtp "]}},to.fourcc="hnti",to),io,Wy=(io=class extends ee{constructor(){super(...arguments),this.box_name="hintstatisticsbox",this.maxrs=[],this.subBoxNames=["maxr"]}},io.fourcc="hinf",io),so,Vy=(so=class extends ee{constructor(){super(...arguments),this.box_name="SubTrackBox"}},so.fourcc="strk",so),ro,$y=(ro=class extends ee{constructor(){super(...arguments),this.box_name="SubTrackDefinitionBox"}},ro.fourcc="strd",ro),no,Xy=(no=class extends ee{constructor(){super(...arguments),this.box_name="ProtectionSchemeInfoBox"}},no.fourcc="sinf",no),oo,Yy=(oo=class extends ee{constructor(){super(...arguments),this.box_name="RestrictedSchemeInfoBox"}},oo.fourcc="rinf",oo),ao,qy=(ao=class extends ee{constructor(){super(...arguments),this.box_name="SchemeInformationBox"}},ao.fourcc="schi",ao),lo,Ky=(lo=class extends ee{constructor(){super(...arguments),this.box_name="TrackGroupBox"}},lo.fourcc="trgr",lo),co,jy=(co=class extends ee{constructor(){super(...arguments),this.box_name="UserDataBox",this.kinds=[],this.strks=[],this.subBoxNames=["kind","strk"]}},co.fourcc="udta",co),ho,Zy=(ho=class extends ee{constructor(){super(...arguments),this.box_name="ItemPropertiesBox",this.ipmas=[],this.subBoxNames=["ipma"]}},ho.fourcc="iprp",ho),uo,Jy=(uo=class extends ee{constructor(){super(...arguments),this.box_name="ItemPropertyContainerBox",this.hvcCs=[],this.ispes=[],this.claps=[],this.irots=[],this.subBoxNames=["hvcC","ispe","clap","irot"]}},uo.fourcc="ipco",uo),fo,Qy=(fo=class extends ee{constructor(){super(...arguments),this.box_name="GroupsListBox"}},fo.fourcc="grpl",fo),po,ev=(po=class extends ee{constructor(){super(...arguments),this.box_name="J2KHeaderInfoBox"}},po.fourcc="j2kH",po),mo,tv=(mo=class extends ee{constructor(){super(...arguments),this.box_name="ExtendedTypeBox",this.tycos=[],this.subBoxNames=["tyco"]}},mo.fourcc="etyp",mo),go,iv=(go=class extends ee{constructor(){super(...arguments),this.box_name="ProjectedOmniVideoBox",this.subBoxNames=["prfr"]}},go.fourcc="povd",go),_o,Nf=(_o=class extends R{constructor(){super(...arguments),this.box_name="DataReferenceBox"}parse(i){this.parseFullHeader(i),this.entries=[];const e=i.readUint32();for(let t=0;t<e;t++){const s=ht(i,!1,this.size-(i.getPosition()-this.start));if(s.code===We){const r=s.box;this.entries.push(r)}else return}}write(i){this.version=0,this.flags=0,this.size=4,this.writeHeader(i),i.writeUint32(this.entries.length);for(let e=0;e<this.entries.length;e++)this.entries[e].write(i),this.size+=this.entries[e].size;I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),i.adjustUint32(this.sizePosition,this.size)}},_o.fourcc="dref",_o),xo,Lf=(xo=class extends R{constructor(){super(...arguments),this.box_name="ExtendedLanguageBox"}parse(i){this.parseFullHeader(i),this.extended_language=i.readString(this.size-this.hdr_size)}write(i){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(i),i.writeString(this.extended_language)}},xo.fourcc="elng",xo),yo,Hf=(yo=class extends B{constructor(){super(...arguments),this.box_name="FileTypeBox"}parse(i){let e=this.size-this.hdr_size;this.major_brand=i.readString(4),this.minor_version=i.readUint32(),e-=8,this.compatible_brands=[];let t=0;for(;e>=4;)this.compatible_brands[t]=i.readString(4),e-=4,t++}write(i){this.size=8+4*this.compatible_brands.length,this.writeHeader(i),i.writeString(this.major_brand,void 0,4),i.writeUint32(this.minor_version);for(let e=0;e<this.compatible_brands.length;e++)i.writeString(this.compatible_brands[e],void 0,4)}},yo.fourcc="ftyp",yo),vo,Wf=(vo=class extends R{constructor(){super(...arguments),this.box_name="HandlerBox"}parse(i){if(this.parseFullHeader(i),this.version===0&&(i.readUint32(),this.handler=i.readString(4),i.readUint32Array(3),!this.isEndOfBox(i))){const e=this.start+this.size-i.getPosition();this.name=i.readCString();const t=this.start+this.size-1;i.seek(t),i.readUint8()!==0&&e>1&&(I.info("BoxParser","Warning: hdlr name is not null-terminated, possibly length-prefixed string. Trimming first byte."),this.name=this.name.slice(1))}}write(i){this.size=20+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(i),i.writeUint32(0),i.writeString(this.handler,void 0,4),i.writeUint32Array([0,0,0]),i.writeCString(this.name)}},vo.fourcc="hdlr",vo),bo,Vf=(bo=class extends B{constructor(){super(...arguments),this.box_name="HEVCConfigurationBox"}parse(i){this.configurationVersion=i.readUint8();let e=i.readUint8();this.general_profile_space=e>>6,this.general_tier_flag=(e&32)>>5,this.general_profile_idc=e&31,this.general_profile_compatibility=i.readUint32(),this.general_constraint_indicator=i.readUint8Array(6),this.general_level_idc=i.readUint8(),this.min_spatial_segmentation_idc=i.readUint16()&4095,this.parallelismType=i.readUint8()&3,this.chroma_format_idc=i.readUint8()&3,this.bit_depth_luma_minus8=i.readUint8()&7,this.bit_depth_chroma_minus8=i.readUint8()&7,this.avgFrameRate=i.readUint16(),e=i.readUint8(),this.constantFrameRate=e>>6,this.numTemporalLayers=(e&13)>>3,this.temporalIdNested=(e&4)>>2,this.lengthSizeMinusOne=e&3,this.nalu_arrays=[];const t=i.readUint8();for(let s=0;s<t;s++){const r=[];this.nalu_arrays.push(r),e=i.readUint8(),r.completeness=(e&128)>>7,r.nalu_type=e&63;const n=i.readUint16();for(let o=0;o<n;o++){const a=i.readUint16();r.push({data:i.readUint8Array(a)})}}}write(i){this.size=23;for(let e=0;e<this.nalu_arrays.length;e++){this.size+=3;for(let t=0;t<this.nalu_arrays[e].length;t++)this.size+=2+this.nalu_arrays[e][t].data.length}this.writeHeader(i),i.writeUint8(this.configurationVersion),i.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),i.writeUint32(this.general_profile_compatibility),i.writeUint8Array(this.general_constraint_indicator),i.writeUint8(this.general_level_idc),i.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),i.writeUint8(this.parallelismType+252),i.writeUint8(this.chroma_format_idc+252),i.writeUint8(this.bit_depth_luma_minus8+248),i.writeUint8(this.bit_depth_chroma_minus8+248),i.writeUint16(this.avgFrameRate),i.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),i.writeUint8(this.nalu_arrays.length);for(let e=0;e<this.nalu_arrays.length;e++){i.writeUint8((this.nalu_arrays[e].completeness<<7)+this.nalu_arrays[e].nalu_type),i.writeUint16(this.nalu_arrays[e].length);for(let t=0;t<this.nalu_arrays[e].length;t++)i.writeUint16(this.nalu_arrays[e][t].data.length),i.writeUint8Array(this.nalu_arrays[e][t].data)}}},bo.fourcc="hvcC",bo),To,$f=(To=class extends R{constructor(){super(...arguments),this.box_name="MediaHeaderBox"}parse(i){this.parseFullHeader(i),this.version===1?(this.creation_time=i.readUint64(),this.modification_time=i.readUint64(),this.timescale=i.readUint32(),this.duration=i.readUint64()):(this.creation_time=i.readUint32(),this.modification_time=i.readUint32(),this.timescale=i.readUint32(),this.duration=i.readUint32()),this.parseLanguage(i),i.readUint16()}write(i){const e=this.modification_time>Ae||this.creation_time>Ae||this.duration>Ae||this.version===1;this.version=e?1:0,this.size=20,this.size+=e?12:0,this.flags=0,this.writeHeader(i),e?(i.writeUint64(this.creation_time),i.writeUint64(this.modification_time),i.writeUint32(this.timescale),i.writeUint64(this.duration)):(i.writeUint32(this.creation_time),i.writeUint32(this.modification_time),i.writeUint32(this.timescale),i.writeUint32(this.duration)),i.writeUint16(this.language),i.writeUint16(0)}},To.fourcc="mdhd",To),wo,Xf=(wo=class extends R{constructor(){super(...arguments),this.box_name="MovieExtendsHeaderBox"}parse(i){this.parseFullHeader(i),this.flags&1&&(I.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version===1?this.fragment_duration=i.readUint64():this.fragment_duration=i.readUint32()}write(i){const e=this.fragment_duration>Ae||this.version===1;this.version=e?1:0,this.size=4,this.size+=e?4:0,this.flags=0,this.writeHeader(i),e?i.writeUint64(this.fragment_duration):i.writeUint32(this.fragment_duration)}},wo.fourcc="mehd",wo),So,sv=(So=class extends R{constructor(){super(...arguments),this.box_name="ItemInfoEntry"}parse(i){if(this.parseFullHeader(i),(this.version===0||this.version===1)&&(this.item_ID=i.readUint16(),this.item_protection_index=i.readUint16(),this.item_name=i.readCString(),this.content_type=i.readCString(),this.isEndOfBox(i)||(this.content_encoding=i.readCString())),this.version===1){this.extension_type=i.readString(4),I.warn("BoxParser","Cannot parse extension type"),i.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=i.readUint16():this.version===3&&(this.item_ID=i.readUint32()),this.item_protection_index=i.readUint16(),this.item_type=i.readString(4),this.item_name=i.readCString(),this.item_type==="mime"?(this.content_type=i.readCString(),this.content_encoding=i.readCString()):this.item_type==="uri "&&(this.item_uri_type=i.readCString()))}},So.fourcc="infe",So),Co,rv=(Co=class extends R{constructor(){super(...arguments),this.box_name="ItemInfoBox"}parse(i){this.parseFullHeader(i),this.version===0?this.entry_count=i.readUint16():this.entry_count=i.readUint32(),this.item_infos=[];for(let e=0;e<this.entry_count;e++){const t=ht(i,!1,this.size-(i.getPosition()-this.start));if(t.code===We){const s=t.box;s.type==="infe"?this.item_infos[e]=s:I.error("BoxParser","Expected 'infe' box, got "+t.box.type,i.isofile)}else return}}},Co.fourcc="iinf",Co),Ao,nv=(Ao=class extends R{constructor(){super(...arguments),this.box_name="ItemLocationBox"}parse(i){this.parseFullHeader(i);let e;e=i.readUint8(),this.offset_size=e>>4&15,this.length_size=e&15,e=i.readUint8(),this.base_offset_size=e>>4&15,this.version===1||this.version===2?this.index_size=e&15:this.index_size=0,this.items=[];let t=0;if(this.version<2)t=i.readUint16();else if(this.version===2)t=i.readUint32();else throw new Error("version of iloc box not supported");for(let s=0;s<t;s++){let r=0,n=0,o=0;if(this.version<2)r=i.readUint16();else if(this.version===2)r=i.readUint32();else throw new Error("version of iloc box not supported");this.version===1||this.version===2?n=i.readUint16()&15:n=0;const a=i.readUint16();switch(this.base_offset_size){case 0:o=0;break;case 4:o=i.readUint32();break;case 8:o=i.readUint64();break;default:throw new Error("Error reading base offset size")}const l=[],c=i.readUint16();for(let h=0;h<c;h++){let u=0,d=0,f=0;if(this.version===1||this.version===2)switch(this.index_size){case 0:u=0;break;case 4:u=i.readUint32();break;case 8:u=i.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.offset_size){case 0:d=0;break;case 4:d=i.readUint32();break;case 8:d=i.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.length_size){case 0:f=0;break;case 4:f=i.readUint32();break;case 8:f=i.readUint64();break;default:throw new Error("Error reading extent index")}l.push({extent_index:u,extent_length:f,extent_offset:d})}this.items.push({base_offset:o,construction_method:n,item_ID:r,data_reference_index:a,extents:l})}}},Ao.fourcc="iloc",Ao),ov={auxl:"Auxiliary image item",base:"Pre-derived image item base",cdsc:"Item describes referenced item",dimg:"Derived image item",dpnd:"Item coding dependency",eroi:"Region",evir:"EVC slice",exbl:"Scalable image item","fdl ":"File delivery",font:"Font item",iloc:"Item data location",mask:"Region mask",mint:"Data integrity",pred:"Predictively coded item",prem:"Pre-multiplied item",tbas:"HEVC tile track base item",text:"Text item",thmb:"Thumbnail image item"},os,av=(os=class extends R{constructor(){super(...arguments),this.box_name="ItemReferenceBox",this.references=[]}parse(i){for(this.parseFullHeader(i),this.references=[];i.getPosition()<this.start+this.size;){const e=ht(i,!0,this.size-(i.getPosition()-this.start));if(e.code===We){let t="Unknown item reference";os.allowed_types.includes(e.type)?t=ov[e.type]:I.warn("BoxParser",`Unknown item reference type: '${e.type}'`);const s=this.version===0?new Sf(e.type,e.size,t,e.hdr_size,e.start):new Cf(e.type,e.size,t,e.hdr_size,e.start);s.write===B.prototype.write&&s.type!=="mdat"&&(I.warn("BoxParser",s.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),s.parseDataAndRewind(i)),s.parse(i),this.references.push(s)}else return}}},os.fourcc="iref",os.allowed_types=["auxl","base","cdsc","dimg","dpnd","eroi","evir","exbl","fdl ","font","iloc","mask","mint","pred","prem","tbas","text","thmb"],os),Eo,lv=(Eo=class extends R{constructor(){super(...arguments),this.box_name="PrimaryItemBox"}parse(i){this.parseFullHeader(i),this.version===0?this.item_id=i.readUint16():this.item_id=i.readUint32()}},Eo.fourcc="pitm",Eo),Io,cv=(Io=class extends R{constructor(){super(...arguments),this.box_name="MetaBox",this.isQT=!1}parse(i){const e=i.getPosition();if(this.size>8){switch(i.readUint32(),i.readString(4)){case"hdlr":case"mhdr":case"keys":case"ilst":case"ctry":case"lang":this.isQT=!0;break}i.seek(e)}this.isQT||this.parseFullHeader(i),ee.prototype.parse.call(this,i)}},Io.fourcc="meta",Io),Po,Yf=(Po=class extends R{constructor(){super(...arguments),this.box_name="MovieFragmentHeaderBox"}parse(i){this.parseFullHeader(i),this.sequence_number=i.readUint32()}write(i){this.version=0,this.flags=0,this.size=4,this.writeHeader(i),i.writeUint32(this.sequence_number)}},Po.fourcc="mfhd",Po),Ro,qf=(Ro=class extends R{constructor(){super(...arguments),this.box_name="MovieHeaderBox"}parse(i){this.parseFullHeader(i),this.version===1?(this.creation_time=i.readUint64(),this.modification_time=i.readUint64(),this.timescale=i.readUint32(),this.duration=i.readUint64()):(this.creation_time=i.readUint32(),this.modification_time=i.readUint32(),this.timescale=i.readUint32(),this.duration=i.readUint32()),this.rate=i.readUint32(),this.volume=i.readUint16()>>8,i.readUint16(),i.readUint32Array(2),this.matrix=i.readInt32Array(9),i.readUint32Array(6),this.next_track_id=i.readUint32()}write(i){const e=this.modification_time>Ae||this.creation_time>Ae||this.duration>Ae||this.version===1;this.version=e?1:0,this.size=96,this.size+=e?12:0,this.flags=0,this.writeHeader(i),e?(i.writeUint64(this.creation_time),i.writeUint64(this.modification_time),i.writeUint32(this.timescale),i.writeUint64(this.duration)):(i.writeUint32(this.creation_time),i.writeUint32(this.modification_time),i.writeUint32(this.timescale),i.writeUint32(this.duration)),i.writeUint32(this.rate),i.writeUint16(this.volume<<8),i.writeUint16(0),i.writeUint32(0),i.writeUint32(0),i.writeInt32Array(this.matrix),i.writeUint32(0),i.writeUint32(0),i.writeUint32(0),i.writeUint32(0),i.writeUint32(0),i.writeUint32(0),i.writeUint32(this.next_track_id)}print(i){super.printHeader(i),i.log(i.indent+"creation_time: "+this.creation_time),i.log(i.indent+"modification_time: "+this.modification_time),i.log(i.indent+"timescale: "+this.timescale),i.log(i.indent+"duration: "+this.duration),i.log(i.indent+"rate: "+this.rate),i.log(i.indent+"volume: "+(this.volume>>8)),i.log(i.indent+"matrix: "+this.matrix.join(", ")),i.log(i.indent+"next_track_id: "+this.next_track_id)}},Ro.fourcc="mvhd",Ro),Mo,hv=(Mo=class extends ni{parse(i){this.parseHeader(i),this.content_encoding=i.readCString(),this.mime_format=i.readCString(),this.parseFooter(i)}},Mo.fourcc="mett",Mo),ko,uv=(ko=class extends ni{parse(i){this.parseHeader(i),this.content_encoding=i.readCString(),this.namespace=i.readCString(),this.schema_location=i.readCString(),this.parseFooter(i)}},ko.fourcc="metx",ko),Fo,dv=(Fo=class extends B{constructor(){super(...arguments),this.box_name="AV1CodecConfigurationBox"}parse(i){let e=i.readUint8();if((e>>7&1)!==1){I.error("BoxParser","av1C marker problem",i.isofile);return}if(this.version=e&127,this.version!==1){I.error("BoxParser","av1C version "+this.version+" not supported",i.isofile);return}if(e=i.readUint8(),this.seq_profile=e>>5&7,this.seq_level_idx_0=e&31,e=i.readUint8(),this.seq_tier_0=e>>7&1,this.high_bitdepth=e>>6&1,this.twelve_bit=e>>5&1,this.monochrome=e>>4&1,this.chroma_subsampling_x=e>>3&1,this.chroma_subsampling_y=e>>2&1,this.chroma_sample_position=e&3,e=i.readUint8(),this.reserved_1=e>>5&7,this.reserved_1!==0){I.error("BoxParser","av1C reserved_1 parsing problem",i.isofile);return}if(this.initial_presentation_delay_present=e>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=e&15;else if(this.reserved_2=e&15,this.reserved_2!==0){I.error("BoxParser","av1C reserved_2 parsing problem",i.isofile);return}const t=this.size-this.hdr_size-4;this.configOBUs=i.readUint8Array(t)}},Fo.fourcc="av1C",Fo),Bo,fv=(Bo=class extends R{constructor(){super(...arguments),this.box_name="ElementaryStreamDescriptorBox"}parse(i){this.parseFullHeader(i);const e=i.readUint8Array(this.size-this.hdr_size);if("MPEG4DescriptorParser"in or){const t=new or.MPEG4DescriptorParser;this.esd=t.parseOneDescriptor(new Pe(e.buffer,0))}}},Bo.fourcc="esds",Bo),Uo,pv=(Uo=class extends R{constructor(){super(...arguments),this.box_name="VPCodecConfigurationRecord"}parse(i){if(this.parseFullHeader(i),this.version===1){this.profile=i.readUint8(),this.level=i.readUint8();const e=i.readUint8();this.bitDepth=e>>4,this.chromaSubsampling=e>>1&7,this.videoFullRangeFlag=e&1,this.colourPrimaries=i.readUint8(),this.transferCharacteristics=i.readUint8(),this.matrixCoefficients=i.readUint8(),this.codecIntializationDataSize=i.readUint16(),this.codecIntializationData=i.readUint8Array(this.codecIntializationDataSize)}else{this.profile=i.readUint8(),this.level=i.readUint8();let e=i.readUint8();this.bitDepth=e>>4&15,this.colorSpace=e&15,e=i.readUint8(),this.chromaSubsampling=e>>4&15,this.transferFunction=e>>1&7,this.videoFullRangeFlag=e&1,this.codecIntializationDataSize=i.readUint16(),this.codecIntializationData=i.readUint8Array(this.codecIntializationDataSize)}}},Uo.fourcc="vpcC",Uo),Oo,mv=(Oo=class extends R{constructor(){super(...arguments),this.box_name="VvcConfigurationBox"}parse(i){this.parseFullHeader(i);const e={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(n){this.held_bits=n.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(n){this.held_bits=n.readUint16(),this.num_held_bits=16},extract_bits:function(n){const o=this.held_bits>>this.num_held_bits-n&(1<<n)-1;return this.num_held_bits-=n,o}};if(e.stream_read_1_bytes(i),e.extract_bits(5),this.lengthSizeMinusOne=e.extract_bits(2),this.ptl_present_flag=e.extract_bits(1),this.ptl_present_flag){e.stream_read_2_bytes(i),this.ols_idx=e.extract_bits(9),this.num_sublayers=e.extract_bits(3),this.constant_frame_rate=e.extract_bits(2),this.chroma_format_idc=e.extract_bits(2),e.stream_read_1_bytes(i),this.bit_depth_minus8=e.extract_bits(3),e.extract_bits(5);{if(e.stream_read_2_bytes(i),e.extract_bits(2),this.num_bytes_constraint_info=e.extract_bits(6),this.general_profile_idc=e.extract_bits(7),this.general_tier_flag=e.extract_bits(1),this.general_level_idc=i.readUint8(),e.stream_read_1_bytes(i),this.ptl_frame_only_constraint_flag=e.extract_bits(1),this.ptl_multilayer_enabled_flag=e.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(let n=0;n<this.num_bytes_constraint_info-1;n++){const o=e.extract_bits(6);e.stream_read_1_bytes(i);const a=e.extract_bits(2);this.general_constraint_info[n]=o<<2|a}this.general_constraint_info[this.num_bytes_constraint_info-1]=e.extract_bits(6)}else e.extract_bits(6);if(this.num_sublayers>1){e.stream_read_1_bytes(i),this.ptl_sublayer_present_mask=0;for(let n=this.num_sublayers-2;n>=0;--n){const o=e.extract_bits(1);this.ptl_sublayer_present_mask|=o<<n}for(let n=this.num_sublayers;n<=8&&this.num_sublayers>1;++n)e.extract_bits(1);this.sublayer_level_idc=[];for(let n=this.num_sublayers-2;n>=0;--n)this.ptl_sublayer_present_mask&1<<n&&(this.sublayer_level_idc[n]=i.readUint8())}if(this.ptl_num_sub_profiles=i.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(let n=0;n<this.ptl_num_sub_profiles;n++)this.general_sub_profile_idc.push(i.readUint32())}this.max_picture_width=i.readUint16(),this.max_picture_height=i.readUint16(),this.avg_frame_rate=i.readUint16()}const t=12,s=13;this.nalu_arrays=[];const r=i.readUint8();for(let n=0;n<r;n++){const o=[];this.nalu_arrays.push(o),e.stream_read_1_bytes(i),o.completeness=e.extract_bits(1),e.extract_bits(2),o.nalu_type=e.extract_bits(5);let a=1;o.nalu_type!==s&&o.nalu_type!==t&&(a=i.readUint16());for(let l=0;l<a;l++){const c=i.readUint16();o.push({data:i.readUint8Array(c),length:c})}}}},Oo.fourcc="vvcC",Oo),Do,gv=(Do=class extends B{constructor(){super(...arguments),this.box_name="ColourInformationBox"}parse(i){if(this.colour_type=i.readString(4),this.colour_type==="nclx"){this.colour_primaries=i.readUint16(),this.transfer_characteristics=i.readUint16(),this.matrix_coefficients=i.readUint16();const e=i.readUint8();this.full_range_flag=e>>7}else this.colour_type==="rICC"?this.ICC_profile=i.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=i.readUint8Array(this.size-4))}},Do.fourcc="colr",Do);function wi(i,e){let t=Number(i).toString(16);for(e=typeof e>"u"?2:e;t.length<e;)t="0"+t;return t}var hr=class extends fe{getCodec(){const i=super.getCodec();return this.avcC?`${i}.${wi(this.avcC.AVCProfileIndication)}${wi(this.avcC.profile_compatibility)}${wi(this.avcC.AVCLevelIndication)}`:i}},Go,_v=(Go=class extends hr{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}},Go.fourcc="avc1",Go),zo,xv=(zo=class extends hr{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}},zo.fourcc="avc2",zo),No,yv=(No=class extends hr{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}},No.fourcc="avc3",No),Lo,vv=(Lo=class extends hr{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}},Lo.fourcc="avc4",Lo),Ho,bv=(Ho=class extends fe{constructor(){super(...arguments),this.box_name="AV1SampleEntry"}getCodec(){const i=super.getCodec(),e=this.av1C.seq_level_idx_0,t=e<10?"0"+e:e;let s;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?s=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(s=this.av1C.high_bitdepth===1?"10":"08"),i+"."+this.av1C.seq_profile+"."+t+(this.av1C.seq_tier_0?"H":"M")+"."+s}},Ho.fourcc="av01",Ho),Wo,Tv=(Wo=class extends fe{},Wo.fourcc="dav1",Wo),ur=class extends fe{getCodec(){let i=super.getCodec();if(this.hvcC){switch(i+=".",this.hvcC.general_profile_space){case 0:i+="";break;case 1:i+="A";break;case 2:i+="B";break;case 3:i+="C";break}i+=this.hvcC.general_profile_idc,i+=".";let e=this.hvcC.general_profile_compatibility,t=0;for(let n=0;n<32&&(t|=e&1,n!==31);n++)t<<=1,e>>=1;i+=wi(t,0),i+=".",this.hvcC.general_tier_flag===0?i+="L":i+="H",i+=this.hvcC.general_level_idc;let s=!1,r="";for(let n=5;n>=0;n--)(this.hvcC.general_constraint_indicator[n]||s)&&(r="."+wi(this.hvcC.general_constraint_indicator[n],0)+r,s=!0);i+=r}return i}},Vo,wv=(Vo=class extends ur{constructor(){super(...arguments),this.box_name="HEVCSampleEntry"}},Vo.fourcc="hvc1",Vo),$o,Sv=($o=class extends ur{},$o.fourcc="hvc2",$o),Xo,Cv=(Xo=class extends ur{constructor(){super(...arguments),this.box_name="HEVCSampleEntry",this.colrs=[],this.subBoxNames=["colr"]}},Xo.fourcc="hev1",Xo),Yo,Av=(Yo=class extends ur{},Yo.fourcc="hev2",Yo),qo,Ev=(qo=class extends fe{constructor(){super(...arguments),this.box_name="HEVCTileSampleSampleEntry"}},qo.fourcc="hvt1",qo),Ko,Iv=(Ko=class extends fe{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},Ko.fourcc="lhe1",Ko),jo,Pv=(jo=class extends fe{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},jo.fourcc="lhv1",jo),Zo,Rv=(Zo=class extends fe{},Zo.fourcc="dvh1",Zo),Jo,Mv=(Jo=class extends fe{},Jo.fourcc="dvhe",Jo),Kf=class extends fe{getCodec(){let i=super.getCodec();if(this.vvcC){i+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?i+=".H":i+=".L",i+=this.vvcC.general_level_idc;let e="";if(this.vvcC.general_constraint_info){const t=[];let s=0;s|=this.vvcC.ptl_frame_only_constraint_flag<<7,s|=this.vvcC.ptl_multilayer_enabled_flag<<6;let r;for(let n=0;n<this.vvcC.general_constraint_info.length;++n)s|=this.vvcC.general_constraint_info[n]>>2&63,t.push(s),s&&(r=n),s=this.vvcC.general_constraint_info[n]>>2&3;if(r===void 0)e=".CA";else{e=".C";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";let o=0,a=0;for(let l=0;l<=r;++l)for(o=o<<8|t[l],a+=8;a>=5;){const c=o>>a-5&31;e+=n[c],a-=5,o&=(1<<a)-1}a&&(o<<=5-a,e+=n[o&31])}}i+=e}return i}},Qo,kv=(Qo=class extends Kf{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},Qo.fourcc="vvc1",Qo),ea,Fv=(ea=class extends Kf{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},ea.fourcc="vvi1",ea),ta,Bv=(ta=class extends fe{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},ta.fourcc="vvs1",ta),ia,Uv=(ia=class extends fe{constructor(){super(...arguments),this.box_name="VvcNonVCLSampleEntry"}},ia.fourcc="vvcN",ia),jf=class extends fe{getCodec(){const i=super.getCodec();let e=this.vpcC.level;e===0&&(e="00");let t=this.vpcC.bitDepth;return t===8&&(t="08"),`${i}.0${this.vpcC.profile}.${e}.${t}`}},sa,Ov=(sa=class extends jf{},sa.fourcc="vp08",sa),ra,Dv=(ra=class extends jf{},ra.fourcc="vp09",ra),na,Gv=(na=class extends fe{},na.fourcc="avs3",na),oa,zv=(oa=class extends fe{constructor(){super(...arguments),this.box_name="J2KSampleEntry"}},oa.fourcc="j2ki",oa),aa,Nv=(aa=class extends fe{},aa.fourcc="mjp2",aa),la,Lv=(la=class extends fe{},la.fourcc="mjpg",la),ca,Hv=(ca=class extends fe{constructor(){super(...arguments),this.box_name="UncompressedVideoSampleEntry"}},ca.fourcc="uncv",ca),ha,Wv=(ha=class extends fe{constructor(){super(...arguments),this.box_name="MP4VisualSampleEntry"}},ha.fourcc="mp4v",ha),ua,Vv=(ua=class extends ze{constructor(){super(...arguments),this.box_name="MP4AudioSampleEntry"}getCodec(){const i=super.getCodec();if(this.esds&&this.esds.esd){const e=this.esds.esd.getOTI(),t=this.esds.esd.getAudioConfig();return i+"."+wi(e)+(t?"."+t:"")}else return i}},ua.fourcc="mp4a",ua),da,$v=(da=class extends ze{},da.fourcc="m4ae",da),fa,Xv=(fa=class extends ze{},fa.fourcc="ac-3",fa),pa,Yv=(pa=class extends ze{},pa.fourcc="ac-4",pa),ma,qv=(ma=class extends ze{},ma.fourcc="ec-3",ma),ga,Kv=(ga=class extends ze{},ga.fourcc="Opus",ga),_a,jv=(_a=class extends ze{},_a.fourcc="mha1",_a),xa,Zv=(xa=class extends ze{},xa.fourcc="mha2",xa),ya,Jv=(ya=class extends ze{},ya.fourcc="mhm1",ya),va,Qv=(va=class extends ze{},va.fourcc="mhm2",va),ba,eb=(ba=class extends ze{},ba.fourcc="fLaC",ba),Ta,tb=(Ta=class extends fe{},Ta.fourcc="encv",Ta),wa,ib=(wa=class extends ze{},wa.fourcc="enca",wa),Sa,sb=(Sa=class extends $t{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Sa.fourcc="encu",Sa),Ca,rb=(Ca=class extends ar{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Ca.fourcc="encs",Ca),Aa,nb=(Aa=class extends ar{},Aa.fourcc="mp4s",Aa),Ea,ob=(Ea=class extends Pf{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Ea.fourcc="enct",Ea),Ia,ab=(Ia=class extends ni{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Ia.fourcc="encm",Ia),Pa,lb=(Pa=class extends fe{constructor(){super(...arguments),this.box_name="RestrictedVideoSampleEntry"}},Pa.fourcc="resv",Pa),Ra,cb=(Ra=class extends $t{parse(i){this.parseHeader(i),this.content_encoding=i.readCString(),this.mime_format=i.readCString(),this.parseFooter(i)}},Ra.fourcc="sbtt",Ra),Ma,Zf=(Ma=class extends $t{parse(i){this.parseHeader(i),this.namespace=i.readCString(),this.schema_location=i.readCString(),this.auxiliary_mime_types=i.readCString(),this.parseFooter(i)}write(i){this.writeHeader(i),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,i.writeCString(this.namespace),i.writeCString(this.schema_location),i.writeCString(this.auxiliary_mime_types),this.writeFooter(i)}},Ma.fourcc="stpp",Ma),ka,hb=(ka=class extends $t{parse(i){this.parseHeader(i),this.content_encoding=i.readCString(),this.mime_format=i.readCString(),this.parseFooter(i)}getCodec(){const i=super.getCodec();return this.mime_format?i+"."+this.mime_format:i}},ka.fourcc="stxt",ka),Fa,ub=(Fa=class extends $t{parse(i){this.parseHeader(i),this.displayFlags=i.readUint32(),this.horizontal_justification=i.readInt8(),this.vertical_justification=i.readInt8(),this.bg_color_rgba=i.readUint8Array(4),this.box_record=i.readInt16Array(4),this.style_record=i.readUint8Array(12),this.parseFooter(i)}},Fa.fourcc="tx3g",Fa),Ba,db=(Ba=class extends ni{parse(i){this.parseHeader(i),this.parseFooter(i)}},Ba.fourcc="wvtt",Ba),Ua,fb=(Ua=class extends R{constructor(){super(...arguments),this.box_name="SampleToGroupBox"}parse(i){this.parseFullHeader(i),this.grouping_type=i.readString(4),this.version===1?this.grouping_type_parameter=i.readUint32():this.grouping_type_parameter=0,this.entries=[];const e=i.readUint32();for(let t=0;t<e;t++)this.entries.push({sample_count:i.readInt32(),group_description_index:i.readInt32()})}write(i){this.grouping_type_parameter?this.version=1:this.version=0,this.flags=0,this.size=8+8*this.entries.length+(this.version===1?4:0),this.writeHeader(i),i.writeString(this.grouping_type,void 0,4),this.version===1&&i.writeUint32(this.grouping_type_parameter),i.writeUint32(this.entries.length);for(let e=0;e<this.entries.length;e++){const t=this.entries[e];i.writeInt32(t.sample_count),i.writeInt32(t.group_description_index)}}},Ua.fourcc="sbgp",Ua),Oa,pb=(Oa=class extends R{constructor(){super(...arguments),this.box_name="SampleDependencyTypeBox"}parse(i){this.parseFullHeader(i);const e=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(let t=0;t<e;t++){const s=i.readUint8();this.is_leading[t]=s>>6,this.sample_depends_on[t]=s>>4&3,this.sample_is_depended_on[t]=s>>2&3,this.sample_has_redundancy[t]=s&3}}},Oa.fourcc="sdtp",Oa),Da,mb=(Da=class extends R{constructor(){super(...arguments),this.box_name="SampleGroupDescriptionBox"}parse(i){this.parseFullHeader(i),this.grouping_type=i.readString(4),I.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=i.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=i.readUint32()),this.entries=[];const e=i.readUint32();for(let t=0;t<e;t++){let s;this.grouping_type in Ve.sampleGroupEntry?s=new Ve.sampleGroupEntry[this.grouping_type](this.grouping_type):s=new ye(this.grouping_type),this.entries.push(s),this.version===1?this.default_length===0?s.description_length=i.readUint32():s.description_length=this.default_length:s.description_length=this.default_length,s.write===ye.prototype.write&&(I.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),s.data=i.readUint8Array(s.description_length),i.seek(i.getPosition()-s.description_length)),s.parse(i)}}write(i){this.flags=0,this.size=12;for(let e=0;e<this.entries.length;e++){const t=this.entries[e];this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=t.data.length)}this.writeHeader(i),i.writeString(this.grouping_type,void 0,4),this.version===1&&i.writeUint32(this.default_length),this.version>=2&&i.writeUint32(this.default_sample_description_index),i.writeUint32(this.entries.length);for(let e=0;e<this.entries.length;e++){const t=this.entries[e];this.version===1&&this.default_length===0&&i.writeUint32(t.description_length),t.write(i)}}},Da.fourcc="sgpd",Da),Ga,gb=(Ga=class extends R{constructor(){super(...arguments),this.box_name="CompressedSegmentIndexBox"}parse(i){this.parseFullHeader(i),this.reference_ID=i.readUint32(),this.timescale=i.readUint32(),this.version===0?(this.earliest_presentation_time=i.readUint32(),this.first_offset=i.readUint32()):(this.earliest_presentation_time=i.readUint64(),this.first_offset=i.readUint64()),i.readUint16(),this.references=[];const e=i.readUint16();for(let t=0;t<e;t++){const s=i.readUint32(),r=i.readUint32(),n=i.readUint32();this.references.push({reference_type:s>>31&1,referenced_size:s&2147483647,subsegment_duration:r,starts_with_SAP:n>>31&1,SAP_type:n>>28&7,SAP_delta_time:n&268435455})}}write(i){const e=this.earliest_presentation_time>Ae||this.first_offset>Ae||this.version===1;this.version=e?1:0,this.size=12+12*this.references.length,this.size+=e?16:8,this.flags=0,this.writeHeader(i),i.writeUint32(this.reference_ID),i.writeUint32(this.timescale),e?(i.writeUint64(this.earliest_presentation_time),i.writeUint64(this.first_offset)):(i.writeUint32(this.earliest_presentation_time),i.writeUint32(this.first_offset)),i.writeUint16(0),i.writeUint16(this.references.length);for(let t=0;t<this.references.length;t++){const s=this.references[t];i.writeUint32(s.reference_type<<31|s.referenced_size),i.writeUint32(s.subsegment_duration),i.writeUint32(s.starts_with_SAP<<31|s.SAP_type<<28|s.SAP_delta_time)}}},Ga.fourcc="sidx",Ga),za,Jf=(za=class extends R{constructor(){super(...arguments),this.box_name="SoundMediaHeaderBox"}parse(i){this.parseFullHeader(i),this.balance=i.readUint16(),i.readUint16()}write(i){this.version=0,this.size=4,this.writeHeader(i),i.writeUint16(this.balance),i.writeUint16(0)}},za.fourcc="smhd",za),Na,Qf=(Na=class extends R{constructor(){super(...arguments),this.box_name="ChunkOffsetBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.chunk_offsets=[],this.version===0)for(let t=0;t<e;t++)this.chunk_offsets.push(i.readUint32())}write(i){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(i),i.writeUint32(this.chunk_offsets.length),i.writeUint32Array(this.chunk_offsets)}unpack(i){for(let e=0;e<this.chunk_offsets.length;e++)i[e].offset=this.chunk_offsets[e]}},Na.fourcc="stco",Na),La,ep=(La=class extends R{constructor(){super(...arguments),this.box_name="SubtitleMediaHeaderBox"}},La.fourcc="sthd",La),Ha,tp=(Ha=class extends R{constructor(){super(...arguments),this.box_name="SampleToChunkBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(let t=0;t<e;t++)this.first_chunk.push(i.readUint32()),this.samples_per_chunk.push(i.readUint32()),this.sample_description_index.push(i.readUint32())}write(i){this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(i),i.writeUint32(this.first_chunk.length);for(let e=0;e<this.first_chunk.length;e++)i.writeUint32(this.first_chunk[e]),i.writeUint32(this.samples_per_chunk[e]),i.writeUint32(this.sample_description_index[e])}unpack(i){let e=0,t=0;for(let s=0;s<this.first_chunk.length;s++)for(let r=0;r<(s+1<this.first_chunk.length?this.first_chunk[s+1]:1/0);r++){t++;for(let n=0;n<this.samples_per_chunk[s];n++){if(i[e])i[e].description_index=this.sample_description_index[s],i[e].chunk_index=t;else return;e++}}}},Ha.fourcc="stsc",Ha),Wa,ip=(Wa=class extends R{constructor(){super(...arguments),this.box_name="SampleDescriptionBox"}parse(i){this.parseFullHeader(i),this.entries=[];const e=i.readUint32();for(let t=1;t<=e;t++){const s=ht(i,!0,this.size-(i.getPosition()-this.start));if(s.code===We){let r;s.type in Ve.sampleEntry?(r=new Ve.sampleEntry[s.type](s.size),r.hdr_size=s.hdr_size,r.start=s.start):(I.warn("BoxParser",`Unknown sample entry type: '${s.type}'`),r=new yt(s.size,s.hdr_size,s.start),r.type=s.type),r.write===yt.prototype.write&&(I.info("BoxParser","SampleEntry "+r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(i)),r.parse(i),this.entries.push(r)}else return}}write(i){this.version=0,this.flags=0,this.size=0,this.writeHeader(i),i.writeUint32(this.entries.length),this.size+=4;for(let e=0;e<this.entries.length;e++)this.entries[e].write(i),this.size+=this.entries[e].size;I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),i.adjustUint32(this.sizePosition,this.size)}},Wa.fourcc="stsd",Wa),Va,sp=(Va=class extends R{constructor(){super(...arguments),this.box_name="SampleSizeBox"}parse(i){if(this.parseFullHeader(i),this.sample_sizes=[],this.version===0){this.sample_size=i.readUint32(),this.sample_count=i.readUint32();for(let e=0;e<this.sample_count;e++)this.sample_size===0?this.sample_sizes.push(i.readUint32()):this.sample_sizes[e]=this.sample_size}}write(i){let e=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0){let t=0;for(;t+1<this.sample_sizes.length;)if(this.sample_sizes[t+1]!==this.sample_sizes[0]){e=!1;break}else t++}else e=!1;this.size=8,e||(this.size+=4*this.sample_sizes.length),this.writeHeader(i),e?i.writeUint32(this.sample_sizes[0]):i.writeUint32(0),i.writeUint32(this.sample_sizes.length),e||i.writeUint32Array(this.sample_sizes)}unpack(i){for(let e=0;e<this.sample_sizes.length;e++)i[e].size=this.sample_sizes[e]}},Va.fourcc="stsz",Va),$a,rp=($a=class extends R{constructor(){super(...arguments),this.box_name="TimeToSampleBox",this.sample_counts=[],this.sample_deltas=[]}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.sample_counts.length=0,this.sample_deltas.length=0,this.version===0)for(let t=0;t<e;t++){this.sample_counts.push(i.readUint32());let s=i.readInt32();s<0&&(I.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),s=1),this.sample_deltas.push(s)}}write(i){this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(i),i.writeUint32(this.sample_counts.length);for(let e=0;e<this.sample_counts.length;e++)i.writeUint32(this.sample_counts[e]),i.writeUint32(this.sample_deltas[e])}unpack(i){let e=0;for(let t=0;t<this.sample_counts.length;t++)for(let s=0;s<this.sample_counts[t];s++)e===0?i[e].dts=0:i[e].dts=i[e-1].dts+this.sample_deltas[t],e++}},$a.fourcc="stts",$a),Xa,np=(Xa=class extends R{constructor(){super(...arguments),this.box_name="TrackFragmentBaseMediaDecodeTimeBox"}parse(i){this.parseFullHeader(i),this.version===1?this.baseMediaDecodeTime=i.readUint64():this.baseMediaDecodeTime=i.readUint32()}write(i){const e=this.baseMediaDecodeTime>Ae||this.version===1;this.version=e?1:0,this.size=4,this.size+=e?4:0,this.flags=0,this.writeHeader(i),e?i.writeUint64(this.baseMediaDecodeTime):i.writeUint32(this.baseMediaDecodeTime)}},Xa.fourcc="tfdt",Xa),Ya,op=(Ya=class extends R{constructor(){super(...arguments),this.box_name="TrackFragmentHeaderBox"}parse(i){this.parseFullHeader(i);let e=0;this.track_id=i.readUint32(),this.size-this.hdr_size>e&&this.flags&js?(this.base_data_offset=i.readUint64(),e+=8):this.base_data_offset=0,this.size-this.hdr_size>e&&this.flags&Zs?(this.default_sample_description_index=i.readUint32(),e+=4):this.default_sample_description_index=0,this.size-this.hdr_size>e&&this.flags&Js?(this.default_sample_duration=i.readUint32(),e+=4):this.default_sample_duration=0,this.size-this.hdr_size>e&&this.flags&Qs?(this.default_sample_size=i.readUint32(),e+=4):this.default_sample_size=0,this.size-this.hdr_size>e&&this.flags&er?(this.default_sample_flags=i.readUint32(),e+=4):this.default_sample_flags=0}write(i){this.version=0,this.size=4,this.flags&js&&(this.size+=8),this.flags&Zs&&(this.size+=4),this.flags&Js&&(this.size+=4),this.flags&Qs&&(this.size+=4),this.flags&er&&(this.size+=4),this.writeHeader(i),i.writeUint32(this.track_id),this.flags&js&&i.writeUint64(this.base_data_offset),this.flags&Zs&&i.writeUint32(this.default_sample_description_index),this.flags&Js&&i.writeUint32(this.default_sample_duration),this.flags&Qs&&i.writeUint32(this.default_sample_size),this.flags&er&&i.writeUint32(this.default_sample_flags)}},Ya.fourcc="tfhd",Ya),qa,ap=(qa=class extends R{constructor(){super(...arguments),this.box_name="TrackHeaderBox",this.layer=0,this.alternate_group=0}parse(i){this.parseFullHeader(i),this.version===1?(this.creation_time=i.readUint64(),this.modification_time=i.readUint64(),this.track_id=i.readUint32(),i.readUint32(),this.duration=i.readUint64()):(this.creation_time=i.readUint32(),this.modification_time=i.readUint32(),this.track_id=i.readUint32(),i.readUint32(),this.duration=i.readUint32()),i.readUint32Array(2),this.layer=i.readInt16(),this.alternate_group=i.readInt16(),this.volume=i.readInt16()>>8,i.readUint16(),this.matrix=i.readInt32Array(9),this.width=i.readUint32(),this.height=i.readUint32()}write(i){const e=this.modification_time>Ae||this.creation_time>Ae||this.duration>Ae||this.version===1;this.version=e?1:0,this.size=80,this.size+=e?12:0,this.flags=this.flags??3,this.writeHeader(i),e?(i.writeUint64(this.creation_time),i.writeUint64(this.modification_time),i.writeUint32(this.track_id),i.writeUint32(0),i.writeUint64(this.duration)):(i.writeUint32(this.creation_time),i.writeUint32(this.modification_time),i.writeUint32(this.track_id),i.writeUint32(0),i.writeUint32(this.duration)),i.writeUint32Array([0,0]),i.writeInt16(this.layer),i.writeInt16(this.alternate_group),i.writeInt16(this.volume<<8),i.writeInt16(0),i.writeInt32Array(this.matrix),i.writeUint32(this.width),i.writeUint32(this.height)}print(i){super.printHeader(i),i.log(i.indent+"creation_time: "+this.creation_time),i.log(i.indent+"modification_time: "+this.modification_time),i.log(i.indent+"track_id: "+this.track_id),i.log(i.indent+"duration: "+this.duration),i.log(i.indent+"volume: "+(this.volume>>8)),i.log(i.indent+"matrix: "+this.matrix.join(", ")),i.log(i.indent+"layer: "+this.layer),i.log(i.indent+"alternate_group: "+this.alternate_group),i.log(i.indent+"width: "+this.width),i.log(i.indent+"height: "+this.height)}},qa.fourcc="tkhd",qa),Ka,ja=(Ka=class extends R{constructor(){super(...arguments),this.box_name="TrackExtendsBox"}parse(i){this.parseFullHeader(i),this.track_id=i.readUint32(),this.default_sample_description_index=i.readUint32(),this.default_sample_duration=i.readUint32(),this.default_sample_size=i.readUint32(),this.default_sample_flags=i.readUint32()}write(i){this.version=0,this.flags=0,this.size=20,this.writeHeader(i),i.writeUint32(this.track_id),i.writeUint32(this.default_sample_description_index),i.writeUint32(this.default_sample_duration),i.writeUint32(this.default_sample_size),i.writeUint32(this.default_sample_flags)}},Ka.fourcc="trex",Ka),Za,lp=(Za=class extends R{constructor(){super(...arguments),this.box_name="TrackRunBox",this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[]}parse(i){this.parseFullHeader(i);let e=0;if(this.sample_count=i.readUint32(),e+=4,this.size-this.hdr_size>e&&this.flags&ts?(this.data_offset=i.readInt32(),e+=4):this.data_offset=0,this.size-this.hdr_size>e&&this.flags&tr?(this.first_sample_flags=i.readUint32(),e+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>e)for(let t=0;t<this.sample_count;t++)this.flags&is&&(this.sample_duration[t]=i.readUint32()),this.flags&ss&&(this.sample_size[t]=i.readUint32()),this.flags&rs&&(this.sample_flags[t]=i.readUint32()),this.flags&ns&&(this.version===0?this.sample_composition_time_offset[t]=i.readUint32():this.sample_composition_time_offset[t]=i.readInt32())}write(i){this.size=4,this.flags&ts&&(this.size+=4),this.flags&tr&&(this.size+=4),this.flags&is&&(this.size+=4*this.sample_duration.length),this.flags&ss&&(this.size+=4*this.sample_size.length),this.flags&rs&&(this.size+=4*this.sample_flags.length),this.flags&ns&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(i),i.writeUint32(this.sample_count),this.flags&ts&&(this.data_offset_position=i.getPosition(),i.writeInt32(this.data_offset)),this.flags&tr&&i.writeUint32(this.first_sample_flags);for(let e=0;e<this.sample_count;e++)this.flags&is&&i.writeUint32(this.sample_duration[e]),this.flags&ss&&i.writeUint32(this.sample_size[e]),this.flags&rs&&i.writeUint32(this.sample_flags[e]),this.flags&ns&&(this.version===0?i.writeUint32(this.sample_composition_time_offset[e]):i.writeInt32(this.sample_composition_time_offset[e]))}},Za.fourcc="trun",Za),Ja,cp=(Ja=class extends R{constructor(){super(...arguments),this.box_name="DataEntryUrlBox"}parse(i){this.parseFullHeader(i),this.flags!==1&&(this.location=i.readCString())}write(i){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(i),this.location&&i.writeCString(this.location)}},Ja.fourcc="url ",Ja),Qa,hp=(Qa=class extends R{constructor(){super(...arguments),this.box_name="VideoMediaHeaderBox"}parse(i){this.parseFullHeader(i),this.graphicsmode=i.readUint16(),this.opcolor=i.readUint16Array(3)}write(i){this.version=0,this.size=8,this.writeHeader(i),i.writeUint16(this.graphicsmode),i.writeUint16Array(this.opcolor)}},Qa.fourcc="vmhd",Qa),dr=class{constructor(i,e,t){this.grouping_type=i,this.grouping_type_parameter=e,this.sbgp=t,this.last_sample_in_run=-1,this.entry_index=-1}},up=class ii{constructor(e,t=!0){this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.moovStartSent=!1,this.readySent=!1,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.sidxSent=!1,this.items=[],this.entity_groups=[],this.itemsDataSize=0,this.lastMoofIndex=0,this.samplesDataSize=0,this.lastBoxStartPosition=0,this.nextParsePosition=0,this.discardMdatData=!0,this.discardMdatData=t,e?(this.stream=e,this.parse()):this.stream=new Ti,this.stream.isofile=this}setSegmentOptions(e,t,s){const{sizePerSegment:r=Number.MAX_SAFE_INTEGER,rapAlignement:n=!0}=s;let o=s.nbSamples??s.nbSamplesPerFragment??1e3;const a=s.nbSamplesPerFragment??o;if(o<=0||a<=0||r<=0){I.error("ISOFile",`Invalid segment options: nbSamples=${o}, nbSamplesPerFragment=${a}, sizePerSegment=${r}`);return}if(o<a&&(I.warn("ISOFile",`nbSamples (${o}) is less than nbSamplesPerFragment (${a}), setting nbSamples to nbSamplesPerFragment`),o=a),this.fragmentedTracks.some(c=>c.nb_samples!==o)){I.error("ISOFile",`Cannot set segment options for track ${e}: nbSamples (${o}) does not match existing tracks`);return}const l=this.getTrackById(e);if(l){const c={id:e,user:t,trak:l,segmentStream:void 0,nb_samples:o,nb_samples_per_fragment:a,size_per_segment:r,rapAlignement:n,state:{lastFragmentSampleNumber:0,lastSegmentSampleNumber:0,accumulatedSize:0}};this.fragmentedTracks.push(c),l.nextSample=0}this.discardMdatData&&I.warn("ISOFile","Segmentation options set but discardMdatData is true, samples will not be segmented")}unsetSegmentOptions(e){let t=-1;for(let s=0;s<this.fragmentedTracks.length;s++)this.fragmentedTracks[s].id===e&&(t=s);t>-1&&this.fragmentedTracks.splice(t,1)}setExtractionOptions(e,t,{nbSamples:s=1e3}={}){const r=this.getTrackById(e);r&&(this.extractedTracks.push({id:e,user:t,trak:r,nb_samples:s,samples:[]}),r.nextSample=0),this.discardMdatData&&I.warn("ISOFile","Extraction options set but discardMdatData is true, samples will not be extracted")}unsetExtractionOptions(e){let t=-1;for(let s=0;s<this.extractedTracks.length;s++)this.extractedTracks[s].id===e&&(t=s);t>-1&&this.extractedTracks.splice(t,1)}parse(){if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else{this.saveParsePosition&&this.saveParsePosition();const e=ht(this.stream,!1);if(e.code===Wt)if(this.processIncompleteBox){if(this.processIncompleteBox(e))continue;return}else return;else if(e.code===We){const t=e.box;if(this.boxes.push(t),t.type==="uuid")this[t.uuid]!==void 0&&I.warn("ISOFile","Duplicate Box of uuid: "+t.uuid+", overriding previous occurrence"),this[t.uuid]=t;else switch(t.type){case"mdat":this.mdats.push(t),this.transferMdatData(t);break;case"moof":this.moofs.push(t);break;case"free":case"skip":break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[t.type]!==void 0?Array.isArray(this[t.type+"s"])?(I.info("ISOFile",`Found multiple boxes of type ${t.type} in ISOFile, adding to array`),this[t.type+"s"].push(t)):(I.warn("ISOFile",`Found multiple boxes of type ${t.type} but no array exists. Creating array dynamically.`),this[t.type+"s"]=[this[t.type],t]):(this[t.type]=t,Array.isArray(this[t.type+"s"])&&this[t.type+"s"].push(t));break}this.updateUsedBytes&&this.updateUsedBytes(t,e)}else if(e.code===_f){I.error("ISOFile",`Invalid data found while parsing box of type '${e.type}' at position ${e.start}. Aborting parsing.`,this);break}}}checkBuffer(e){if(!e)throw new Error("Buffer must be defined and non empty");return e.byteLength===0?(I.warn("ISOFile","Ignoring empty buffer (fileStart: "+e.fileStart+")"),this.stream.logBufferLevel(),!1):(I.info("ISOFile","Processing buffer (fileStart: "+e.fileStart+")"),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(I.warn("ISOFile","Not ready to start parsing"),!1))}appendBuffer(e,t){let s;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(t),this.nextSeekPosition?(s=this.nextSeekPosition,this.nextSeekPosition=void 0):s=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(s=this.stream.getEndFilePositionAfter(s))):this.nextParsePosition?s=this.nextParsePosition:s=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(I.info("ISOFile","Done processing buffer (fileStart: "+e.fileStart+") - next buffer to fetch should have a fileStart position of "+s),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),I.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),s}getFragmentDuration(){const e=this.getBox("mvex");if(!e)return;if(e.mehd)return{num:e.mehd.fragment_duration,den:this.moov.mvhd.timescale};const t=this.getBoxes("trak",!1);let s={num:0,den:1};for(const r of t){const n=r.samples_duration,o=r.mdia.mdhd.timescale;n&&o&&n/o>s.num/s.den&&(s={num:n,den:o})}return s}getInfo(){if(!this.moov)return{hasMoov:!1,mime:""};const e=new Date("1904-01-01T00:00:00Z").getTime(),t=this.getBox("mvex")!==void 0,s={hasMoov:!0,duration:this.moov.mvhd.duration,timescale:this.moov.mvhd.timescale,isFragmented:t,fragment_duration:this.getFragmentDuration(),isProgressive:this.isProgressive,hasIOD:this.moov.iods!==void 0,brands:[this.ftyp.major_brand].concat(this.ftyp.compatible_brands),created:new Date(e+this.moov.mvhd.creation_time*1e3),modified:new Date(e+this.moov.mvhd.modification_time*1e3),tracks:[],audioTracks:[],videoTracks:[],subtitleTracks:[],metadataTracks:[],hintTracks:[],otherTracks:[],mime:""};for(let r=0;r<this.moov.traks.length;r++){const n=this.moov.traks[r],o=n.mdia.minf.stbl.stsd.entries[0],a=n.samples_size,l=n.mdia.mdhd.timescale,c=n.samples_duration,h=a*8*l/c,u={samples_duration:c,bitrate:h,size:a,timescale:l,alternate_group:n.tkhd.alternate_group,codec:o.getCodec(),created:new Date(e+n.tkhd.creation_time*1e3),cts_shift:n.mdia.minf.stbl.cslg,duration:n.mdia.mdhd.duration,id:n.tkhd.track_id,kind:n.udta&&n.udta.kinds.length?n.udta.kinds[0]:{schemeURI:"",value:""},language:n.mdia.elng?n.mdia.elng.extended_language:n.mdia.mdhd.languageString,layer:n.tkhd.layer,matrix:n.tkhd.matrix,modified:new Date(e+n.tkhd.modification_time*1e3),movie_duration:n.tkhd.duration,movie_timescale:s.timescale,name:n.mdia.hdlr.name,nb_samples:n.samples.length,references:[],track_height:n.tkhd.height/65536,track_width:n.tkhd.width/65536,volume:n.tkhd.volume};if(s.tracks.push(u),n.tref)for(let d=0;d<n.tref.references.length;d++)u.references.push({type:n.tref.references[d].type,track_ids:n.tref.references[d].track_ids});n.edts!==void 0&&n.edts.elst!==void 0&&(u.edits=n.edts.elst.entries),o instanceof ze?(u.type="audio",s.audioTracks.push(u),u.audio={sample_rate:o.getSampleRate(),channel_count:o.getChannelCount(),sample_size:o.getSampleSize()}):o instanceof fe?(u.type="video",s.videoTracks.push(u),u.video={width:o.getWidth(),height:o.getHeight()}):o instanceof $t?(u.type="subtitles",s.subtitleTracks.push(u)):o instanceof In?(u.type="metadata",s.hintTracks.push(u)):o instanceof ni?(u.type="metadata",s.metadataTracks.push(u)):(u.type="metadata",s.otherTracks.push(u))}s.videoTracks&&s.videoTracks.length>0?s.mime+='video/mp4; codecs="':s.audioTracks&&s.audioTracks.length>0?s.mime+='audio/mp4; codecs="':s.mime+='application/mp4; codecs="';for(let r=0;r<s.tracks.length;r++)r!==0&&(s.mime+=","),s.mime+=s.tracks[r].codec;return s.mime+='"; profiles="',s.mime+=this.ftyp.compatible_brands.join(),s.mime+='"',s}setNextSeekPositionFromSample(e){e&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(e.offset+e.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=e.offset+e.alreadyRead)}processSamples(e){if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==void 0){const t=new Set;for(;t.size<this.fragmentedTracks.length&&this.fragmentedTracks.some(s=>s.trak.nextSample<s.trak.samples.length)&&this.sampleProcessingStarted;)for(const s of this.fragmentedTracks){const r=s.trak;if(!t.has(s.id)){const n=r.nextSample<r.samples.length?this.getSample(r,r.nextSample):void 0;if(!n){this.setNextSeekPositionFromSample(r.samples[r.nextSample]),t.add(s.id);continue}s.state.accumulatedSize+=n.size;const o=r.nextSample+1,a=o-s.state.lastFragmentSampleNumber>s.nb_samples_per_fragment,l=o-s.state.lastSegmentSampleNumber>s.nb_samples;let c=a||o%s.nb_samples_per_fragment===0,h=l||o%s.nb_samples===0,u=s.state.accumulatedSize>=s.size_per_segment;const d=!s.rapAlignement||n.is_sync,f=e||r.nextSample+1>=r.samples.length;if(f&&!d&&I.warn("ISOFile","Flushing track #"+s.id+" at sample #"+r.nextSample+" which is not a RAP, this may lead to playback issues"),c=c&&d,h=h&&d,u=u&&d,c||u||f){a?I.warn("ISOFile","Fragment on track #"+s.id+" is overdue, creating it with samples ["+s.state.lastFragmentSampleNumber+", "+r.nextSample+"]"):I.debug("ISOFile","Creating media fragment on track #"+s.id+" for samples ["+s.state.lastFragmentSampleNumber+", "+r.nextSample+"]");const p=this.createFragment(s.id,s.state.lastFragmentSampleNumber,r.nextSample,s.segmentStream);if(p)s.segmentStream=p,s.state.lastFragmentSampleNumber=r.nextSample+1;else{t.add(s.id);continue}}(h||u||f)&&(l?I.warn("ISOFile","Segment on track #"+s.id+" is overdue, sending it with samples ["+Math.max(0,r.nextSample-s.nb_samples)+", "+(r.nextSample-1)+"]"):I.info("ISOFile","Sending fragmented data on track #"+s.id+" for samples ["+Math.max(0,r.nextSample-s.nb_samples)+", "+(r.nextSample-1)+"]"),I.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(s.id,s.user,s.segmentStream.buffer,r.nextSample+1,e||r.nextSample+1>=r.samples.length),s.segmentStream=void 0,s.state.accumulatedSize=0,s.state.lastSegmentSampleNumber=r.nextSample+1),r.nextSample++}}}if(this.onSamples!==void 0)for(let t=0;t<this.extractedTracks.length;t++){const s=this.extractedTracks[t],r=s.trak;for(;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){I.debug("ISOFile","Exporting on track #"+s.id+" sample #"+r.nextSample);const n=this.getSample(r,r.nextSample);if(n)r.nextSample++,s.samples.push(n);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%s.nb_samples===0||r.nextSample>=r.samples.length)&&(I.debug("ISOFile","Sending samples on track #"+s.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(s.id,s.user,s.samples),s.samples=[],s!==this.extractedTracks[t]))break}}}}getBox(e){const t=this.getBoxes(e,!0);return t.length?t[0]:void 0}getBoxes(e,t){const s=[],r=n=>{n instanceof B&&n.type&&n.type===e&&s.push(n);const o=[];n.boxes&&o.push(...n.boxes),n.entries&&o.push(...n.entries),n.item_infos&&o.push(...n.item_infos),n.references&&o.push(...n.references);for(const a of o){if(s.length&&t)return;r(a)}};return r(this),s}getTrackSamplesInfo(e){const t=this.getTrackById(e);if(t)return t.samples}getTrackSample(e,t){const s=this.getTrackById(e);return this.getSample(s,t)}releaseUsedSamples(e,t){let s=0;const r=this.getTrackById(e);r.lastValidSample||(r.lastValidSample=0);for(let n=r.lastValidSample;n<t;n++)s+=this.releaseSample(r,n);I.info("ISOFile","Track #"+e+" released samples up to "+t+" (released size: "+s+", remaining: "+this.samplesDataSize+")"),r.lastValidSample=t}start(){this.sampleProcessingStarted=!0,this.processSamples(!1)}stop(){this.sampleProcessingStarted=!1}flush(){I.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)}seekTrack(e,t,s){let r=0,n=0,o;if(s.samples.length===0)return I.info("ISOFile","No sample in track, cannot seek! Using time "+I.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(let l=0;l<s.samples.length;l++){const c=s.samples[l];if(l===0)n=0,o=c.timescale;else if(c.cts>e*c.timescale){n=l-1;break}t&&c.is_sync&&(r=l)}for(t&&(n=r),e=s.samples[n].cts,s.nextSample=n;s.samples[n].alreadyRead===s.samples[n].size&&s.samples[n+1];)n++;const a=s.samples[n].offset+s.samples[n].alreadyRead;return I.info("ISOFile","Seeking to "+(t?"RAP":"")+" sample #"+s.nextSample+" on track "+s.tkhd.track_id+", time "+I.getDurationString(e,o)+" and offset: "+a),{offset:a,time:e/o}}getTrackDuration(e){if(!e.samples)return 1/0;const t=e.samples[e.samples.length-1];return(t.cts+t.duration)/t.timescale}seek(e,t){const s=this.moov;let r={offset:1/0,time:1/0};if(this.moov){for(let n=0;n<s.traks.length;n++){const o=s.traks[n];if(e>this.getTrackDuration(o))continue;const a=this.seekTrack(e,t,o);a.offset<r.offset&&(r.offset=a.offset),a.time<r.time&&(r.time=a.time)}return I.info("ISOFile","Seeking at time "+I.getDurationString(r.time,1)+" needs a buffer with a fileStart position of "+r.offset),r.offset===1/0?r={offset:this.nextParsePosition,time:0}:r.offset=this.stream.getEndFilePositionAfter(r.offset),I.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+r.offset),r}else throw new Error("Cannot seek: moov not received!")}equal(e){let t=0;for(;t<this.boxes.length&&t<e.boxes.length;){const s=this.boxes[t],r=e.boxes[t];if(!Cn(s,r))return!1;t++}return!0}write(e){for(let t=0;t<this.boxes.length;t++)this.boxes[t].write(e)}createFragment(e,t,s,r){const n=[];for(let h=t;h<=s;h++){const u=this.getTrackById(e),d=this.getSample(u,h);if(!d){this.setNextSeekPositionFromSample(u.samples[h]);return}n.push(d)}const o=r||new Pe,a=this.createMoof(n);a.write(o),a.trafs[0].truns[0].data_offset=a.size+8,I.debug("MP4Box","Adjusting data_offset with new value "+a.trafs[0].truns[0].data_offset),o.adjustUint32(a.trafs[0].truns[0].data_offset_position,a.trafs[0].truns[0].data_offset);const l=new lr;l.stream=new Ti;let c=0;for(const h of n)if(h.data){const u=xt.fromArrayBuffer(h.data.buffer,c);l.stream.insertBuffer(u),c+=h.data.byteLength}return l.write(o),o}static writeInitializationSegment(e,t,s){I.debug("ISOFile","Generating initialization segment");const r=new Pe;e.write(r);const n=t.addBox(new Kn);if(s){const o=n.addBox(new Xf);o.fragment_duration=s}for(let o=0;o<t.traks.length;o++){const a=n.addBox(new ja);a.track_id=t.traks[o].tkhd.track_id,a.default_sample_description_index=1,a.default_sample_duration=t.traks[o].samples[0]?.duration??0,a.default_sample_size=0,a.default_sample_flags=65536}return t.write(r),r.buffer}save(e){const t=new Pe;return t.isofile=this,this.write(t),t.save(e)}getBuffer(){const e=new Pe;return e.isofile=this,this.write(e),e}initializeSegmentation(){this.onSegment||I.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.resetTables());const e=new Ln;e.addBox(this.moov.mvhd);for(let t=0;t<this.fragmentedTracks.length;t++){const s=this.getTrackById(this.fragmentedTracks[t].id);if(!s){I.warn("ISOFile",`Track with id ${this.fragmentedTracks[t].id} not found, skipping fragmentation initialization`);continue}e.addBox(s)}return{tracks:e.traks.map((t,s)=>({id:t.tkhd.track_id,user:this.fragmentedTracks[s].user})),buffer:ii.writeInitializationSegment(this.ftyp,e,this.moov?.mvex?.mehd.fragment_duration)}}resetTables(){this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0;for(let e=0;e<this.moov.traks.length;e++){const t=this.moov.traks[e];t.tkhd.duration=0,t.mdia.mdhd.duration=0;const s=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64;s.chunk_offsets=[];const r=t.mdia.minf.stbl.stsc;r.first_chunk=[],r.samples_per_chunk=[],r.sample_description_index=[];const n=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2;n.sample_sizes=[];const o=t.mdia.minf.stbl.stts;o.sample_counts=[],o.sample_deltas=[];const a=t.mdia.minf.stbl.ctts;a&&(a.sample_counts=[],a.sample_offsets=[]);const l=t.mdia.minf.stbl.stss,c=t.mdia.minf.stbl.boxes.indexOf(l);c!==-1&&(t.mdia.minf.stbl.boxes[c]=void 0)}}static initSampleGroups(e,t,s,r,n){t&&(t.sample_groups_info=[]),e.sample_groups_info||(e.sample_groups_info=[]);for(let o=0;o<s.length;o++){const a=s[o].grouping_type+"/"+s[o].grouping_type_parameter,l=new dr(s[o].grouping_type,s[o].grouping_type_parameter,s[o]);t&&(t.sample_groups_info[a]=l),e.sample_groups_info[a]||(e.sample_groups_info[a]=l);for(let c=0;c<r.length;c++)r[c].grouping_type===s[o].grouping_type&&(l.description=r[c],l.description.used=!0);if(n)for(let c=0;c<n.length;c++)n[c].grouping_type===s[o].grouping_type&&(l.fragment_description=n[c],l.fragment_description.used=!0,l.is_fragment=!0)}if(t){if(n){for(let o=0;o<n.length;o++)if(!n[o].used&&n[o].version>=2){const a=n[o].grouping_type+"/0",l=new dr(n[o].grouping_type,0);l.is_fragment=!0,t.sample_groups_info[a]||(t.sample_groups_info[a]=l)}}}else for(let o=0;o<r.length;o++)if(!r[o].used&&r[o].version>=2){const a=r[o].grouping_type+"/0",l=new dr(r[o].grouping_type,0);e.sample_groups_info[a]||(e.sample_groups_info[a]=l)}}static setSampleGroupProperties(e,t,s,r){t.sample_groups=[];for(const n in r)if(t.sample_groups[n]={grouping_type:r[n].grouping_type,grouping_type_parameter:r[n].grouping_type_parameter},s>=r[n].last_sample_in_run&&(r[n].last_sample_in_run<0&&(r[n].last_sample_in_run=0),r[n].entry_index++,r[n].entry_index<=r[n].sbgp.entries.length-1&&(r[n].last_sample_in_run+=r[n].sbgp.entries[r[n].entry_index].sample_count)),r[n].entry_index<=r[n].sbgp.entries.length-1?t.sample_groups[n].group_description_index=r[n].sbgp.entries[r[n].entry_index].group_description_index:t.sample_groups[n].group_description_index=-1,t.sample_groups[n].group_description_index!==0){let o;if(r[n].fragment_description?o=r[n].fragment_description:o=r[n].description,t.sample_groups[n].group_description_index>0){let a;t.sample_groups[n].group_description_index>65535?a=(t.sample_groups[n].group_description_index>>16)-1:a=t.sample_groups[n].group_description_index-1,o&&a>=0&&(t.sample_groups[n].description=o.entries[a])}else o&&o.version>=2&&o.default_group_description_index>0&&(t.sample_groups[n].description=o.entries[o.default_group_description_index-1])}}static process_sdtp(e,t,s){t&&(e?(t.is_leading=e.is_leading[s],t.depends_on=e.sample_depends_on[s],t.is_depended_on=e.sample_is_depended_on[s],t.has_redundancy=e.sample_has_redundancy[s]):(t.is_leading=0,t.depends_on=0,t.is_depended_on=0,t.has_redundancy=0))}buildSampleLists(){for(let e=0;e<this.moov.traks.length;e++)this.buildTrakSampleLists(this.moov.traks[e])}buildTrakSampleLists(e){let t,s,r,n,o,a;e.samples=[],e.samples_duration=0,e.samples_size=0;const l=e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64,c=e.mdia.minf.stbl.stsc,h=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,u=e.mdia.minf.stbl.stts,d=e.mdia.minf.stbl.ctts,f=e.mdia.minf.stbl.stss,p=e.mdia.minf.stbl.stsd,g=e.mdia.minf.stbl.subs,m=e.mdia.minf.stbl.stdp,_=e.mdia.minf.stbl.sbgps,x=e.mdia.minf.stbl.sgpds;let y=-1,v=-1,T=-1,S=-1,w=0,E=0,P=0;if(ii.initSampleGroups(e,void 0,_,x),!(typeof h>"u")){for(t=0;t<h.sample_sizes.length;t++){const C={number:t,track_id:e.tkhd.track_id,timescale:e.mdia.mdhd.timescale,alreadyRead:0,size:h.sample_sizes[t]};e.samples[t]=C,e.samples_size+=C.size,t===0?(r=1,s=0,C.chunk_index=r,C.chunk_run_index=s,a=c.samples_per_chunk[s],o=0,s+1<c.first_chunk.length?n=c.first_chunk[s+1]-1:n=1/0):t<a?(C.chunk_index=r,C.chunk_run_index=s):(r++,C.chunk_index=r,o=0,r<=n||(s++,s+1<c.first_chunk.length?n=c.first_chunk[s+1]-1:n=1/0),C.chunk_run_index=s,a+=c.samples_per_chunk[s]),C.description_index=c.sample_description_index[C.chunk_run_index]-1,C.description=p.entries[C.description_index],C.offset=l.chunk_offsets[C.chunk_index-1]+o,o+=C.size,t>y&&(v++,y<0&&(y=0),y+=u.sample_counts[v]),t>0?(e.samples[t-1].duration=u.sample_deltas[v],e.samples_duration+=e.samples[t-1].duration,C.dts=e.samples[t-1].dts+e.samples[t-1].duration):C.dts=0,d?(t>=T&&(S++,T<0&&(T=0),T+=d.sample_counts[S]),C.cts=e.samples[t].dts+d.sample_offsets[S]):C.cts=C.dts,f?(t===f.sample_numbers[w]-1?(C.is_sync=!0,w++):(C.is_sync=!1,C.degradation_priority=0),g&&g.entries[E].sample_delta+P===t+1&&(C.subsamples=g.entries[E].subsamples,P+=g.entries[E].sample_delta,E++)):C.is_sync=!0,ii.process_sdtp(e.mdia.minf.stbl.sdtp,C,C.number),m?C.degradation_priority=m.priority[t]:C.degradation_priority=0,g&&g.entries[E].sample_delta+P===t&&(C.subsamples=g.entries[E].subsamples,P+=g.entries[E].sample_delta),(_.length>0||x.length>0)&&ii.setSampleGroupProperties(e,C,t,e.sample_groups_info)}t>0&&(e.samples[t-1].duration=Math.max(e.mdia.mdhd.duration-e.samples[t-1].dts,0),e.samples_duration+=e.samples[t-1].duration)}}updateSampleLists(){let e,t,s,r,n;if(this.moov!==void 0)for(;this.lastMoofIndex<this.moofs.length;){const o=this.moofs[this.lastMoofIndex];if(this.lastMoofIndex++,o.type==="moof"){const a=o;for(let l=0;l<a.trafs.length;l++){const c=a.trafs[l],h=this.getTrackById(c.tfhd.track_id),u=this.getTrexById(c.tfhd.track_id);c.tfhd.flags&Zs?e=c.tfhd.default_sample_description_index:e=u?u.default_sample_description_index:1,c.tfhd.flags&Js?t=c.tfhd.default_sample_duration:t=u?u.default_sample_duration:0,c.tfhd.flags&Qs?s=c.tfhd.default_sample_size:s=u?u.default_sample_size:0,c.tfhd.flags&er?r=c.tfhd.default_sample_flags:r=u?u.default_sample_flags:0,c.sample_number=0,c.sbgps.length>0&&ii.initSampleGroups(h,c,c.sbgps,h.mdia.minf.stbl.sgpds,c.sgpds);for(let d=0;d<c.truns.length;d++){const f=c.truns[d];for(let p=0;p<f.sample_count;p++){const g=e-1;let m=r;f.flags&rs?m=f.sample_flags[p]:p===0&&f.flags&tr&&(m=f.first_sample_flags);let _=s;f.flags&ss&&(_=f.sample_size[p]),h.samples_size+=_;let x=t;f.flags&is&&(x=f.sample_duration[p]),h.samples_duration+=x;let y;h.first_traf_merged||p>0?y=h.samples[h.samples.length-1].dts+h.samples[h.samples.length-1].duration:(c.tfdt?y=c.tfdt.baseMediaDecodeTime:y=0,h.first_traf_merged=!0);let v=y;f.flags&ns&&(v=y+f.sample_composition_time_offset[p]);const T=!!(c.tfhd.flags&js),S=!!(c.tfhd.flags&gf),w=!!(f.flags&ts);let E=0;T?E=c.tfhd.base_data_offset:S||d===0?E=a.start:E=n;let P;d===0&&p===0?w?P=E+f.data_offset:P=E:P=n,n=P+_;const C=c.sample_number;c.sample_number++;const A={cts:v,description_index:g,description:h.mdia.minf.stbl.stsd.entries[g],dts:y,duration:x,moof_number:this.lastMoofIndex,number_in_traf:C,number:h.samples.length,offset:P,size:_,timescale:h.mdia.mdhd.timescale,track_id:h.tkhd.track_id,is_sync:!(m>>16&1),is_leading:m>>26&3,depends_on:m>>24&3,is_depended_on:m>>22&3,has_redundancy:m>>20&3,degradation_priority:m&65535};c.first_sample_index=h.samples.length,h.samples.push(A),(c.sbgps.length>0||c.sgpds.length>0||h.mdia.minf.stbl.sbgps.length>0||h.mdia.minf.stbl.sgpds.length>0)&&ii.setSampleGroupProperties(h,A,A.number_in_traf,c.sample_groups_info)}}if(c.subs){h.has_fragment_subsamples=!0;let d=c.first_sample_index;for(let f=0;f<c.subs.entries.length;f++){d+=c.subs.entries[f].sample_delta;const p=h.samples[d-1];p.subsamples=c.subs.entries[f].subsamples}}}}}}getSample(e,t){const s=e.samples[t];if(this.moov){if(!s.data)s.data=new Uint8Array(s.size),s.alreadyRead=0,this.samplesDataSize+=s.size,I.debug("ISOFile","Allocating sample #"+t+" on track #"+e.tkhd.track_id+" of size "+s.size+" (total: "+this.samplesDataSize+")");else if(s.alreadyRead===s.size)return s;for(;;){let r=this.stream,n=r.findPosition(!0,s.offset+s.alreadyRead,!1),o,a;if(n>-1)o=r.buffers[n],a=o.fileStart;else for(const l of this.mdats){if(!l.stream){I.debug("ISOFile","mdat stream not yet fully read for #"+this.mdats.indexOf(l)+" mdat");continue}if(n=l.stream.findPosition(!0,s.offset+s.alreadyRead-l.start-l.hdr_size,!1),n>-1){r=l.stream,o=l.stream.buffers[n],a=l.start+l.hdr_size+o.fileStart;break}}if(o){const l=o.byteLength-(s.offset+s.alreadyRead-a);if(s.size-s.alreadyRead<=l)return I.debug("ISOFile","Getting sample #"+t+" data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-a)+" read size: "+(s.size-s.alreadyRead)+" full size: "+s.size+")"),Pe.memcpy(s.data.buffer,s.alreadyRead,o,s.offset+s.alreadyRead-a,s.size-s.alreadyRead),o.usedBytes+=s.size-s.alreadyRead,r.logBufferLevel(),s.alreadyRead=s.size,s;if(l===0)return;I.debug("ISOFile","Getting sample #"+t+" partial data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-a)+" read size: "+l+" full size: "+s.size+")"),Pe.memcpy(s.data.buffer,s.alreadyRead,o,s.offset+s.alreadyRead-a,l),s.alreadyRead+=l,o.usedBytes+=l,r.logBufferLevel()}else return}}}releaseSample(e,t){const s=e.samples[t];return s.data?(this.samplesDataSize-=s.size,s.data=void 0,s.alreadyRead=0,s.size):0}getAllocatedSampleDataSize(){return this.samplesDataSize}getCodecs(){let e="";for(let t=0;t<this.moov.traks.length;t++){const s=this.moov.traks[t];t>0&&(e+=","),e+=s.mdia.minf.stbl.stsd.entries[0].getCodec()}return e}getTrexById(e){if(!(!this.moov||!this.moov.mvex))for(let t=0;t<this.moov.mvex.trexs.length;t++){const s=this.moov.mvex.trexs[t];if(s.track_id===e)return s}}getTrackById(e){if(this.moov)for(let t=0;t<this.moov.traks.length;t++){const s=this.moov.traks[t];if(s.tkhd.track_id===e)return s}}flattenItemInfo(){const e=this.items,t=this.entity_groups,s=this.meta;if(!(!s||!s.hdlr||!s.iinf)){for(let r=0;r<s.iinf.item_infos.length;r++){const n=s.iinf.item_infos[r].item_ID;e[n]={id:n,name:s.iinf.item_infos[r].item_name,ref_to:[],content_type:s.iinf.item_infos[r].content_type,content_encoding:s.iinf.item_infos[r].content_encoding,item_uri_type:s.iinf.item_infos[r].item_uri_type,type:s.iinf.item_infos[r].item_type?s.iinf.item_infos[r].item_type:"mime",protection:s.iinf.item_infos[r].item_protection_index>0?s.ipro.protections[s.iinf.item_infos[r].item_protection_index-1]:void 0}}if(s.grpl)for(let r=0;r<s.grpl.boxes.length;r++){const n=s.grpl.boxes[r];t[n.group_id]={id:n.group_id,entity_ids:n.entity_ids,type:n.type}}if(s.iloc)for(let r=0;r<s.iloc.items.length;r++){const n=s.iloc.items[r],o=e[n.item_ID];n.data_reference_index!==0&&(I.warn("Item storage with reference to other files: not supported"),o.source=s.dinf.boxes[n.data_reference_index-1]),o.extents=[],o.size=0;for(let a=0;a<n.extents.length;a++)o.extents[a]={offset:n.extents[a].extent_offset+n.base_offset,length:n.extents[a].extent_length,alreadyRead:0},n.construction_method===1&&(o.extents[a].offset+=s.idat.start+s.idat.hdr_size),o.size+=o.extents[a].length}if(s.pitm&&(e[s.pitm.item_id].primary=!0),s.iref)for(let r=0;r<s.iref.references.length;r++){const n=s.iref.references[r];for(let o=0;o<n.references.length;o++)e[n.from_item_ID].ref_to.push({type:n.type,id:n.references[o]})}if(s.iprp)for(let r=0;r<s.iprp.ipmas.length;r++){const n=s.iprp.ipmas[r];for(let o=0;o<n.associations.length;o++){const a=n.associations[o],l=e[a.id]??t[a.id];if(l){l.properties===void 0&&(l.properties={boxes:[]});for(let c=0;c<a.props.length;c++){const h=a.props[c];if(h.property_index>0&&h.property_index-1<s.iprp.ipco.boxes.length){const u=s.iprp.ipco.boxes[h.property_index-1];l.properties[u.type]=u,l.properties.boxes.push(u)}}}}}}}getItem(e){if(!this.meta)return;const t=this.items[e];if(!t.data&&t.size)t.data=new Uint8Array(t.size),t.alreadyRead=0,this.itemsDataSize+=t.size,I.debug("ISOFile","Allocating item #"+e+" of size "+t.size+" (total: "+this.itemsDataSize+")");else if(t.alreadyRead===t.size)return t;for(let s=0;s<t.extents.length;s++){const r=t.extents[s];if(r.alreadyRead!==r.length){const n=this.stream.findPosition(!0,r.offset+r.alreadyRead,!1);if(n>-1){const o=this.stream.buffers[n],a=o.byteLength-(r.offset+r.alreadyRead-o.fileStart);if(r.length-r.alreadyRead<=a)I.debug("ISOFile","Getting item #"+e+" extent #"+s+" data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-o.fileStart)+" read size: "+(r.length-r.alreadyRead)+" full extent size: "+r.length+" full item size: "+t.size+")"),Pe.memcpy(t.data.buffer,t.alreadyRead,o,r.offset+r.alreadyRead-o.fileStart,r.length-r.alreadyRead),(!this.parsingMdat||this.discardMdatData)&&(o.usedBytes+=r.length-r.alreadyRead),this.stream.logBufferLevel(),t.alreadyRead+=r.length-r.alreadyRead,r.alreadyRead=r.length;else{I.debug("ISOFile","Getting item #"+e+" extent #"+s+" partial data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-o.fileStart)+" read size: "+a+" full extent size: "+r.length+" full item size: "+t.size+")"),Pe.memcpy(t.data.buffer,t.alreadyRead,o,r.offset+r.alreadyRead-o.fileStart,a),r.alreadyRead+=a,t.alreadyRead+=a,(!this.parsingMdat||this.discardMdatData)&&(o.usedBytes+=a),this.stream.logBufferLevel();return}}else return}}if(t.alreadyRead===t.size)return t}releaseItem(e){const t=this.items[e];if(t.data){this.itemsDataSize-=t.size,t.data=void 0,t.alreadyRead=0;for(let s=0;s<t.extents.length;s++){const r=t.extents[s];r.alreadyRead=0}return t.size}else return 0}processItems(e){for(const t in this.items){const s=this.items[t];this.getItem(s.id),e&&!s.sent&&(e(s),s.sent=!0,s.data=void 0)}}hasItem(e){for(const t in this.items){const s=this.items[t];if(s.name===e)return s.id}return-1}getMetaHandler(){if(this.meta)return this.meta.hdlr.handler}getPrimaryItem(){if(this.meta&&this.meta.pitm)return this.getItem(this.meta.pitm.item_id)}itemToFragmentedTrackFile({itemId:e}={}){let t;if(e?t=this.getItem(e):t=this.getPrimaryItem(),!t)return;const s=new ii;s.discardMdatData=!1;const r={type:t.type,description_boxes:t.properties.boxes};t.properties.ispe&&(r.width=t.properties.ispe.image_width,r.height=t.properties.ispe.image_height);const n=s.addTrack(r);if(n)return s.addSample(n,t.data),s}processIncompleteBox(e){if(e.type==="mdat"){const t=new lr(e.size);return this.parsingMdat=t,this.boxes.push(t),this.mdats.push(t),t.start=e.start,t.hdr_size=e.hdr_size,t.original_size=e.original_size,this.stream.addUsedBytes(t.hdr_size),this.lastBoxStartPosition=t.start+t.size,this.stream.seek(t.start+t.size,!1,this.discardMdatData)?(this.transferMdatData(),this.parsingMdat=void 0,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=t.start+t.size,!1)}else return e.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),this.stream.mergeNextBuffer&&this.stream.mergeNextBuffer()?(this.nextParsePosition=this.stream.getEndPosition(),!0):(e.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+e.size:this.nextParsePosition=this.stream.getEndPosition(),!1)}hasIncompleteMdat(){return this.parsingMdat!==void 0}transferMdatData(e){const t=e??this.parsingMdat;if(this.discardMdatData){I.debug("ISOFile","Discarding 'mdat' data, not transferring it to the mdat box stream");return}if(!t){I.warn("ISOFile","Cannot transfer 'mdat' data, no mdat box is being parsed");return}const s=this.stream.findPosition(!0,t.start+t.hdr_size,!1),r=this.stream.findPosition(!0,t.start+t.size,!1);if(s===-1||r===-1){I.warn("ISOFile","Cannot transfer 'mdat' data, start or end buffer not found");return}t.stream=new Ti;for(let n=s;n<=r;n++){const o=this.stream.buffers[n],a=n===s?t.start+t.hdr_size-o.fileStart:0,l=n===r?t.start+t.size-o.fileStart:o.byteLength;if(l>a){I.debug("ISOFile","Transferring 'mdat' data from buffer #"+n+" ("+a+" to "+l+")");const c=l-a,h=new xt(c),u=t.stream.getAbsoluteEndPosition();Pe.memcpy(h,0,o,a,c),h.fileStart=u,t.stream.insertBuffer(h),o.usedBytes+=c}}}processIncompleteMdat(){const e=this.parsingMdat;return this.stream.seek(e.start+e.size,!1,this.discardMdatData)?(I.debug("ISOFile","Found 'mdat' end in buffered data"),this.transferMdatData(),this.parsingMdat=void 0,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)}restoreParsePosition(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)}saveParsePosition(){this.lastBoxStartPosition=this.stream.getPosition()}updateUsedBytes(e,t){this.stream.addUsedBytes&&(e.type==="mdat"?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))}addBox(e){return B.prototype.addBox.call(this,e)}init(e={}){const t=this.addBox(new Hf);t.major_brand=e.brands&&e.brands[0]||"iso4",t.minor_version=0,t.compatible_brands=e.brands||["iso4"];const s=this.addBox(new Ln);s.addBox(new Kn);const r=s.addBox(new qf);return r.timescale=e.timescale||600,r.rate=e.rate||65536,r.creation_time=0,r.modification_time=0,r.duration=e.duration||0,r.volume=e.width?0:256,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.next_track_id=1,this}addTrack(e={}){this.moov||this.init(e);const t=e||{};t.width=t.width||320,t.height=t.height||320,t.id=t.id||this.moov.mvhd.next_track_id,t.type=t.type||"avc1";const s=this.moov.addBox(new Ff);this.moov.mvhd.next_track_id=t.id+1;const r=s.addBox(new ap);r.flags=by|Ty|wy,r.creation_time=0,r.modification_time=0,r.track_id=t.id,r.duration=t.duration||0,r.layer=t.layer||0,r.alternate_group=0,r.volume=1,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.width=t.width<<16,r.height=t.height<<16;const n=s.addBox(new Bf),o=n.addBox(new $f);o.creation_time=0,o.modification_time=0,o.timescale=t.timescale||1,o.duration=t.media_duration||0,o.language=t.language||"und";const a=n.addBox(new Wf);a.handler=t.hdlr||"vide",a.name=t.name||"Track created with MP4Box.js";const l=n.addBox(new Lf);l.extended_language=t.language||"fr-FR";const c=n.addBox(new Uf),h=Ve.sampleEntry[t.type];if(!h)return;const u=new h;if(u.data_reference_index=1,u instanceof fe){const v=u,T=c.addBox(new hp);T.graphicsmode=0,T.opcolor=[0,0,0],v.width=t.width,v.height=t.height,v.horizresolution=72<<16,v.vertresolution=72<<16,v.frame_count=1,v.compressorname=t.type+" Compressor",v.depth=24,t.avcDecoderConfigRecord?v.addBox(new Mf(t.avcDecoderConfigRecord.byteLength)).parse(new Pe(t.avcDecoderConfigRecord)):t.hevcDecoderConfigRecord&&v.addBox(new Vf(t.hevcDecoderConfigRecord.byteLength)).parse(new Pe(t.hevcDecoderConfigRecord))}else if(u instanceof ze){const v=u,T=c.addBox(new Jf);T.balance=t.balance||0,v.channel_count=t.channel_count||2,v.samplesize=t.samplesize||16,v.samplerate=t.samplerate||65536}else u instanceof In?c.addBox(new kf):u instanceof $t?(c.addBox(new ep),u instanceof Zf&&(u.namespace=t.namespace||"nonamespace",u.schema_location=t.schema_location||"",u.auxiliary_mime_types=t.auxiliary_mime_types||"")):u instanceof ni?c.addBox(new cr):u instanceof ar?c.addBox(new cr):c.addBox(new cr);t.description&&u.addBox.call(u,t.description),t.description_boxes&&t.description_boxes.forEach(function(v){u.addBox.call(u,v)});const d=c.addBox(new Of).addBox(new Nf),f=new cp;f.flags=1,d.addEntry(f);const p=c.addBox(new Df);p.addBox(new ip).addEntry(u);const g=p.addBox(new rp);g.sample_counts=[],g.sample_deltas=[];const m=p.addBox(new tp);m.first_chunk=[],m.samples_per_chunk=[],m.sample_description_index=[];const _=p.addBox(new Qf);_.chunk_offsets=[];const x=p.addBox(new sp);x.sample_sizes=[];const y=this.moov.mvex.addBox(new ja);return y.track_id=t.id,y.default_sample_description_index=t.default_sample_description_index||1,y.default_sample_duration=t.default_sample_duration||0,y.default_sample_size=t.default_sample_size||0,y.default_sample_flags=t.default_sample_flags||0,this.buildTrakSampleLists(s),t.id}addSample(e,t,{sample_description_index:s,duration:r=1,cts:n=0,dts:o=0,is_sync:a=!1,is_leading:l=0,depends_on:c=0,is_depended_on:h=0,has_redundancy:u=0,degradation_priority:d=0,subsamples:f,offset:p=0}={}){const g=this.getTrackById(e);if(g===void 0)return;const m=s?s-1:0,_={number:g.samples.length,track_id:g.tkhd.track_id,timescale:g.mdia.mdhd.timescale,description_index:m,description:g.mdia.minf.stbl.stsd.entries[m],data:t,size:t.byteLength,alreadyRead:t.byteLength,duration:r,cts:n,dts:o,is_sync:a,is_leading:l,depends_on:c,is_depended_on:h,has_redundancy:u,degradation_priority:d,offset:p,subsamples:f};g.samples.push(_),g.samples_size+=_.size,g.samples_duration+=_.duration,g.first_dts===void 0&&(g.first_dts=o),this.processSamples();const x=this.addBox(this.createMoof([_]));x.computeSize(),x.trafs[0].truns[0].data_offset=x.size+8;const y=this.addBox(new lr);return y.data=new Uint8Array(t),_}createMoof(e){if(e.length===0)return;if(e.some(h=>h.track_id!==e[0].track_id))throw new Error("Cannot create moof for samples from different tracks: "+e.map(h=>h.track_id).join(", "));const t=e[0].track_id,s=this.getTrackById(t);if(!s)throw new Error("Cannot create moof for non-existing track: "+t);const r=new Gf,n=r.addBox(new Yf);n.sequence_number=++this.nextMoofNumber;const o=r.addBox(new zf),a=o.addBox(new op);a.track_id=t,a.flags=gf;const l=o.addBox(new np);l.baseMediaDecodeTime=e[0].dts-(s.first_dts||0);const c=o.addBox(new lp);c.flags=ts|is|ss|rs|ns,c.data_offset=0,c.first_sample_flags=0,c.sample_count=e.length;for(const h of e){let u=0;h.is_sync?u=1<<25:u=65536,c.sample_duration.push(h.duration),c.sample_size.push(h.size),c.sample_flags.push(u),c.sample_composition_time_offset.push(h.cts-h.dts)}return r}print(e){e.indent="";for(let t=0;t<this.boxes.length;t++)this.boxes[t]&&this.boxes[t].print(e)}};function dp(i=!1,e){return new up(e,!i)}var fp={};mf(fp,{Descriptor:()=>Xt,ES_Descriptor:()=>tl,MPEG4DescriptorParser:()=>gp});var pp=3,fr=4,el=5,mp=6,Xt=class Xx{constructor(e,t){this.tag=e,this.size=t,this.descs=[]}parse(e){this.data=e.readUint8Array(this.size)}findDescriptor(e){for(let t=0;t<this.descs.length;t++)if(this.descs[t].tag===e)return this.descs[t]}parseOneDescriptor(e){let t=0;const s=e.readUint8();let r=e.readUint8();for(;r&128;)t=(t<<7)+(r&127),r=e.readUint8();t=(t<<7)+(r&127),I.debug("Descriptor","Found "+(pr[s]||"Descriptor "+s)+", size "+t+" at position "+e.getPosition());const n=pr[s]?new vb[pr[s]](t):new Xx(t);return n.parse(e),n}parseRemainingDescriptors(e){const t=e.getPosition();for(;e.getPosition()<t+this.size;){const s=this.parseOneDescriptor?.(e);this.descs.push(s)}}},tl=class extends Xt{constructor(i){super(pp,i)}parse(i){if(this.ES_ID=i.readUint16(),this.flags=i.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=i.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){const e=i.readUint8();this.URL=i.readString(e),this.size-=e+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=i.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(i)}getOTI(){const i=this.findDescriptor(fr);return i?i.oti:0}getAudioConfig(){const i=this.findDescriptor(fr);if(!i)return;const e=i.findDescriptor(el);if(e&&e.data){let t=(e.data[0]&248)>>3;return t===31&&e.data.length>=2&&(t=32+((e.data[0]&7)<<3)+((e.data[1]&224)>>5)),t}}},_b=class extends Xt{constructor(i){super(fr,i)}parse(i){this.oti=i.readUint8(),this.streamType=i.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=i.readUint24(),this.maxBitrate=i.readUint32(),this.avgBitrate=i.readUint32(),this.size-=13,this.parseRemainingDescriptors(i)}},xb=class extends Xt{constructor(i){super(el,i)}},yb=class extends Xt{constructor(i){super(mp,i)}},vb={Descriptor:Xt,ES_Descriptor:tl,DecoderConfigDescriptor:_b,DecoderSpecificInfo:xb,SLConfigDescriptor:yb},pr={[pp]:"ES_Descriptor",[fr]:"DecoderConfigDescriptor",[el]:"DecoderSpecificInfo",[mp]:"SLConfigDescriptor"},gp=class{constructor(){this.parseOneDescriptor=Xt.prototype.parseOneDescriptor}getDescriptorName(i){return pr[i]}},bb=class{parseSample(i){const e=[],t=new Ti(xt.fromArrayBuffer(i.buffer,0));for(;!t.isEof();){const s=ht(t,!1);s.code===We&&s.box?.type==="vttc"&&e.push(s.box)}return e}getText(i,e,t){function s(a,l){const c=a.toString();return c.length>=l?c:new Array(l-c.length+1).join("0")+c}function r(a){const l=Math.floor(a/3600),c=Math.floor((a-l*3600)/60),h=Math.floor(a-l*3600-c*60),u=Math.floor((a-l*3600-c*60-h)*1e3);return""+s(l,2)+":"+s(c,2)+":"+s(h,2)+"."+s(u,3)}const n=this.parseSample(t);let o="";for(let a=0;a<n.length;a++){const l=n[a];o+=r(i)+" --> "+r(e)+`\r
|
|
2
|
-
`,o+=l.payl.text}return o}},Tb=class{parseSample(i){const e={resources:[],documentString:"",document:void 0},t=new Pe(i.data.buffer);if(!i.subsamples||i.subsamples.length===0)e.documentString=t.readString(i.data.length);else if(e.documentString=t.readString(i.subsamples[0].size),i.subsamples.length>1)for(let s=1;s<i.subsamples.length;s++)e.resources[s]=t.readUint8Array(i.subsamples[s].size);return typeof DOMParser<"u"&&(e.document=new DOMParser().parseFromString(e.documentString,"application/xml")),e}},wb=class{parseSample(i){return new Pe(i.data.buffer).readString(i.data.length)}parseConfig(i){const e=new Pe(i.buffer);return e.readUint32(),e.readCString()}},Sb=class{parseSample(i){const e=new Pe(i.data.buffer),t=e.readUint16();if(t!==0)return e.readString(t)}},_p={};mf(_p,{CoLLBox:()=>Db,ItemContentIDPropertyBox:()=>dw,OpusSampleEntry:()=>Kv,SmDmBox:()=>cT,a1lxBox:()=>Cb,a1opBox:()=>Ab,ac_3SampleEntry:()=>Xv,ac_4SampleEntry:()=>Yv,aebrBox:()=>t2,afbrBox:()=>i2,albcBox:()=>s2,alstSampleGroupEntry:()=>LT,altrBox:()=>r2,auxCBox:()=>Eb,av01SampleEntry:()=>bv,av1CBox:()=>dv,avc1SampleEntry:()=>_v,avc2SampleEntry:()=>xv,avc3SampleEntry:()=>yv,avc4SampleEntry:()=>vv,avcCBox:()=>Mf,avllSampleGroupEntry:()=>HT,avs3SampleEntry:()=>Gv,avssSampleGroupEntry:()=>WT,brstBox:()=>n2,btrtBox:()=>Ib,bxmlBox:()=>Oy,ccstBox:()=>Pb,cdefBox:()=>Rb,clapBox:()=>Mb,clefBox:()=>Y2,clliBox:()=>kb,cmexBox:()=>Fb,cminBox:()=>Bb,cmpdBox:()=>Ub,co64Box:()=>Ob,colrBox:()=>gv,coviBox:()=>Nb,cprtBox:()=>Lb,cschBox:()=>Hb,cslgBox:()=>Wb,cttsBox:()=>Vb,dOpsBox:()=>Zb,dac3Box:()=>$b,dataBox:()=>ls,dav1SampleEntry:()=>Tv,dec3Box:()=>Xb,dfLaBox:()=>Yb,dimmBox:()=>qb,dinfBox:()=>Of,dmax:()=>Kb,dmedBox:()=>jb,dobrBox:()=>o2,drefBox:()=>Nf,drepBox:()=>Jb,dtrtSampleGroupEntry:()=>VT,dvh1SampleEntry:()=>Rv,dvheSampleEntry:()=>Mv,ec_3SampleEntry:()=>qv,edtsBox:()=>Gy,elngBox:()=>Lf,elstBox:()=>Qb,emsgBox:()=>e2,encaSampleEntry:()=>ib,encmSampleEntry:()=>ab,encsSampleEntry:()=>rb,enctSampleEntry:()=>ob,encuSampleEntry:()=>sb,encvSampleEntry:()=>tb,enofBox:()=>K2,eqivBox:()=>a2,esdsBox:()=>fv,etypBox:()=>tv,fLaCSampleEntry:()=>eb,favcBox:()=>l2,fielBox:()=>x2,fobrBox:()=>c2,freeBox:()=>ky,frmaBox:()=>y2,ftypBox:()=>Hf,grplBox:()=>Qy,hdlrBox:()=>Wf,hev1SampleEntry:()=>Cv,hev2SampleEntry:()=>Av,hinfBox:()=>Wy,hmhdBox:()=>kf,hntiBox:()=>Hy,hvc1SampleEntry:()=>wv,hvc2SampleEntry:()=>Sv,hvcCBox:()=>Vf,hvt1SampleEntry:()=>Ev,iaugBox:()=>h2,idatBox:()=>My,iinfBox:()=>rv,ilocBox:()=>nv,ilstBox:()=>j2,imirBox:()=>v2,infeBox:()=>sv,iodsBox:()=>By,ipcoBox:()=>Jy,ipmaBox:()=>b2,iproBox:()=>Dy,iprpBox:()=>Zy,irefBox:()=>av,irotBox:()=>T2,ispeBox:()=>w2,itaiBox:()=>S2,j2kHBox:()=>ev,j2kiSampleEntry:()=>zv,keysBox:()=>Z2,kindBox:()=>C2,levaBox:()=>A2,lhe1SampleEntry:()=>Iv,lhv1SampleEntry:()=>Pv,lhvCBox:()=>E2,lselBox:()=>I2,m4aeSampleEntry:()=>$v,maxrBox:()=>P2,mdatBox:()=>lr,mdcvBox:()=>R2,mdhdBox:()=>$f,mdiaBox:()=>Bf,mecoBox:()=>Ly,mehdBox:()=>Xf,metaBox:()=>cv,mettSampleEntry:()=>hv,metxSampleEntry:()=>uv,mfhdBox:()=>Yf,mfraBox:()=>Ny,mfroBox:()=>M2,mha1SampleEntry:()=>jv,mha2SampleEntry:()=>Zv,mhm1SampleEntry:()=>Jv,mhm2SampleEntry:()=>Qv,minfBox:()=>Uf,mjp2SampleEntry:()=>Nv,mjpgSampleEntry:()=>Lv,moofBox:()=>Gf,moovBox:()=>Ln,mp4aSampleEntry:()=>Vv,mp4sSampleEntry:()=>nb,mp4vSampleEntry:()=>Wv,mskCBox:()=>k2,msrcTrackGroupTypeBox:()=>PT,mvexBox:()=>Kn,mvhdBox:()=>qf,mvifSampleGroupEntry:()=>$T,nmhdBox:()=>cr,npckBox:()=>F2,numpBox:()=>B2,padbBox:()=>O2,panoBox:()=>u2,paspBox:()=>D2,paylBox:()=>G2,paytBox:()=>z2,pdinBox:()=>N2,piffLsmBox:()=>ow,piffPsshBox:()=>aw,piffSencBox:()=>lw,piffTencBox:()=>cw,piffTfrfBox:()=>hw,piffTfxdBox:()=>uw,pitmBox:()=>lv,pixiBox:()=>L2,pmaxBox:()=>H2,povdBox:()=>iv,prdiBox:()=>W2,prfrBox:()=>V2,prftBox:()=>$2,prgrBox:()=>g2,profBox:()=>J2,prolSampleGroupEntry:()=>XT,psshBox:()=>X2,pymdBox:()=>_2,rapSampleGroupEntry:()=>YT,rashSampleGroupEntry:()=>qT,resvSampleEntry:()=>lb,rinfBox:()=>Yy,rollSampleGroupEntry:()=>KT,rtp_Box:()=>tT,saioBox:()=>iT,saizBox:()=>sT,sbgpBox:()=>fb,sbpmBox:()=>nT,sbttSampleEntry:()=>cb,schiBox:()=>qy,schmBox:()=>oT,scifSampleGroupEntry:()=>jT,scnmSampleGroupEntry:()=>ZT,sdp_Box:()=>aT,sdtpBox:()=>pb,seigSampleGroupEntry:()=>JT,sencBox:()=>lT,sgpdBox:()=>mb,sidxBox:()=>gb,sinfBox:()=>Xy,skipBox:()=>Fy,slidBox:()=>d2,smhdBox:()=>Jf,sratBox:()=>hT,ssixBox:()=>uT,stblBox:()=>Df,stcoBox:()=>Qf,stdpBox:()=>dT,sterBox:()=>f2,sthdBox:()=>ep,stppSampleEntry:()=>Zf,strdBox:()=>$y,striBox:()=>fT,strkBox:()=>Vy,stsaSampleGroupEntry:()=>QT,stscBox:()=>tp,stsdBox:()=>ip,stsgBox:()=>pT,stshBox:()=>mT,stssBox:()=>gT,stszBox:()=>sp,sttsBox:()=>rp,stviBox:()=>_T,stxtSampleEntry:()=>hb,stypBox:()=>xT,stz2Box:()=>yT,subsBox:()=>vT,syncSampleGroupEntry:()=>ew,taicBox:()=>bT,taptBox:()=>Q2,teleSampleGroupEntry:()=>tw,tencBox:()=>TT,tfdtBox:()=>np,tfhdBox:()=>op,tfraBox:()=>wT,tkhdBox:()=>ap,tmaxBox:()=>ST,tminBox:()=>CT,totlBox:()=>AT,tpayBox:()=>ET,tpylBox:()=>IT,trafBox:()=>zf,trakBox:()=>Ff,trefBox:()=>RT,trepBox:()=>MT,trexBox:()=>ja,trgrBox:()=>Ky,trpyBox:()=>kT,trunBox:()=>lp,tsasSampleGroupEntry:()=>iw,tsclSampleGroupEntry:()=>sw,tselBox:()=>FT,tsynBox:()=>p2,tx3gSampleEntry:()=>ub,txtcBox:()=>BT,tycoBox:()=>UT,udesBox:()=>OT,udtaBox:()=>jy,uncCBox:()=>DT,uncvSampleEntry:()=>Hv,urlBox:()=>cp,urnBox:()=>GT,viprSampleGroupEntry:()=>rw,vmhdBox:()=>hp,vp08SampleEntry:()=>Ov,vp09SampleEntry:()=>Dv,vpcCBox:()=>pv,vttCBox:()=>zT,vttcBox:()=>zy,vvc1SampleEntry:()=>kv,vvcCBox:()=>mv,vvcNSampleEntry:()=>Uv,vvi1SampleEntry:()=>Fv,vvnCBox:()=>NT,vvs1SampleEntry:()=>Bv,waveBox:()=>eT,wbbrBox:()=>m2,wvttSampleEntry:()=>db,xmlBox:()=>Uy});var il,Cb=(il=class extends B{constructor(){super(...arguments),this.box_name="AV1LayeredImageIndexingProperty"}parse(i){const e=((i.readUint8()&1&1)+1)*16;this.layer_size=[];for(let t=0;t<3;t++)e===16?this.layer_size[t]=i.readUint16():this.layer_size[t]=i.readUint32()}},il.fourcc="a1lx",il),sl,Ab=(sl=class extends B{constructor(){super(...arguments),this.box_name="OperatingPointSelectorProperty"}parse(i){this.op_index=i.readUint8()}},sl.fourcc="a1op",sl),rl,Eb=(rl=class extends R{constructor(){super(...arguments),this.box_name="AuxiliaryTypeProperty"}parse(i){this.parseFullHeader(i),this.aux_type=i.readCString();const e=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=i.readUint8Array(e)}},rl.fourcc="auxC",rl),nl,Ib=(nl=class extends B{constructor(){super(...arguments),this.box_name="BitRateBox"}parse(i){this.bufferSizeDB=i.readUint32(),this.maxBitrate=i.readUint32(),this.avgBitrate=i.readUint32()}},nl.fourcc="btrt",nl),ol,Pb=(ol=class extends R{constructor(){super(...arguments),this.box_name="CodingConstraintsBox"}parse(i){this.parseFullHeader(i);const e=i.readUint8();this.all_ref_pics_intra=(e&128)===128,this.intra_pred_used=(e&64)===64,this.max_ref_per_pic=(e&63)>>2,i.readUint24()}},ol.fourcc="ccst",ol),al,Rb=(al=class extends B{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}parse(i){this.channel_count=i.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[];for(let e=0;e<this.channel_count;e++)this.channel_indexes.push(i.readUint16()),this.channel_types.push(i.readUint16()),this.channel_associations.push(i.readUint16())}},al.fourcc="cdef",al),ll,Mb=(ll=class extends B{constructor(){super(...arguments),this.box_name="CleanApertureBox"}parse(i){this.cleanApertureWidthN=i.readUint32(),this.cleanApertureWidthD=i.readUint32(),this.cleanApertureHeightN=i.readUint32(),this.cleanApertureHeightD=i.readUint32(),this.horizOffN=i.readUint32(),this.horizOffD=i.readUint32(),this.vertOffN=i.readUint32(),this.vertOffD=i.readUint32()}},ll.fourcc="clap",ll),cl,kb=(cl=class extends B{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}parse(i){this.max_content_light_level=i.readUint16(),this.max_pic_average_light_level=i.readUint16()}},cl.fourcc="clli",cl),hl,Fb=(hl=class extends B{constructor(){super(...arguments),this.box_name="CameraExtrinsicMatrixProperty"}parse(i){this.flags&1&&(this.pos_x=i.readInt32()),this.flags&2&&(this.pos_y=i.readInt32()),this.flags&4&&(this.pos_z=i.readInt32()),this.flags&8&&(this.version===0?this.flags&16?(this.quat_x=i.readInt32(),this.quat_y=i.readInt32(),this.quat_z=i.readInt32()):(this.quat_x=i.readInt16(),this.quat_y=i.readInt16(),this.quat_z=i.readInt16()):this.version),this.flags&32&&(this.id=i.readUint32())}},hl.fourcc="cmex",hl),ul,Bb=(ul=class extends B{constructor(){super(...arguments),this.box_name="CameraIntrinsicMatrixProperty"}parse(i){this.focal_length_x=i.readInt32(),this.principal_point_x=i.readInt32(),this.principal_point_y=i.readInt32(),this.flags&1&&(this.focal_length_y=i.readInt32(),this.skew_factor=i.readInt32())}},ul.fourcc="cmin",ul),dl,Ub=(dl=class extends B{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}parse(i){this.component_count=i.readUint32(),this.component_types=[],this.component_type_urls=[];for(let e=0;e<this.component_count;e++){const t=i.readUint16();this.component_types.push(t),t>=32768&&this.component_type_urls.push(i.readCString())}}},dl.fourcc="cmpd",dl),fl,Ob=(fl=class extends R{constructor(){super(...arguments),this.box_name="ChunkLargeOffsetBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.chunk_offsets=[],this.version===0)for(let t=0;t<e;t++)this.chunk_offsets.push(i.readUint64())}write(i){this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(i),i.writeUint32(this.chunk_offsets.length);for(let e=0;e<this.chunk_offsets.length;e++)i.writeUint64(this.chunk_offsets[e])}},fl.fourcc="co64",fl),pl,Db=(pl=class extends R{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}parse(i){this.parseFullHeader(i),this.maxCLL=i.readUint16(),this.maxFALL=i.readUint16()}},pl.fourcc="CoLL",pl),Gb=class{toString(){let i="centre_azimuth: ";return i+=this.centre_azimuth,i+=" (",i+=this.centre_azimuth*2**-16,i+="°), centre_elevation: ",i+=this.centre_elevation,i+=" (",i+=this.centre_elevation*2**-16,i+="°), centre_tilt: ",i+=this.centre_tilt,i+=" (",i+=this.centre_tilt*2**-16,i+="°)",this.range_included_flag&&(i+=", azimuth_range: ",i+=this.azimuth_range,i+=" (",i+=this.azimuth_range*2**-16,i+="°), elevation_range: ",i+=this.elevation_range,i+=" (",i+=this.elevation_range*2**-16,i+="°)"),this.interpolate_included_flag&&(i+=", interpolate: ",i+=this.interpolate),i}},zb=class{toString(){let i="";return this.view_idc&&(i+="view_idc: ",i+=this.view_idc,i+=", "),i+="sphere_region: {",i+=this.sphere_region,i+="}",i}},ml,Nb=(ml=class extends R{constructor(){super(...arguments),this.box_name="CoverageInformationBox"}parse(i){this.parseFullHeader(i),this.coverage_shape_type=i.readUint8();const e=i.readUint8(),t=i.readInt8(),s=t&128;s&&(this.default_view_idc=(t&96)>>5),this.coverage_regions=new Array;for(let r=0;r<e;r++){const n=new zb;s&&(n.view_idc=i.readUint8()>>6),n.sphere_region=this.parseSphereRegion(i,!0,!0),this.coverage_regions.push(n)}}parseSphereRegion(i,e,t){const s=new Gb;return s.centre_azimuth=i.readInt32(),s.centre_elevation=i.readInt32(),s.centre_tilt=i.readInt32(),s.range_included_flag=e,e&&(s.azimuth_range=i.readUint32(),s.elevation_range=i.readUint32()),s.interpolate_included_flag=t,t&&(s.interpolate=(i.readUint8()&128)===128),s}},ml.fourcc="covi",ml),gl,Lb=(gl=class extends R{constructor(){super(...arguments),this.box_name="CopyrightBox"}parse(i){this.parseFullHeader(i),this.parseLanguage(i),this.notice=i.readCString()}},gl.fourcc="cprt",gl),_l,Hb=(_l=class extends R{constructor(){super(...arguments),this.box_name="CompatibleSchemeTypeBox"}parse(i){this.parseFullHeader(i),this.scheme_type=i.readString(4),this.scheme_version=i.readUint32(),this.flags&1&&(this.scheme_uri=i.readCString())}},_l.fourcc="csch",_l),as=2147483647,xl,Wb=(xl=class extends R{constructor(){super(...arguments),this.box_name="CompositionToDecodeBox"}parse(i){this.parseFullHeader(i),this.version===0?(this.compositionToDTSShift=i.readInt32(),this.leastDecodeToDisplayDelta=i.readInt32(),this.greatestDecodeToDisplayDelta=i.readInt32(),this.compositionStartTime=i.readInt32(),this.compositionEndTime=i.readInt32()):this.version===1&&(this.compositionToDTSShift=i.readInt64(),this.leastDecodeToDisplayDelta=i.readInt64(),this.greatestDecodeToDisplayDelta=i.readInt64(),this.compositionStartTime=i.readInt64(),this.compositionEndTime=i.readInt64())}write(i){this.version=0,(this.compositionToDTSShift>as||this.leastDecodeToDisplayDelta>as||this.greatestDecodeToDisplayDelta>as||this.compositionStartTime>as||this.compositionEndTime>as)&&(this.version=1),this.flags=0,this.version===0?(this.size=20,this.writeHeader(i),i.writeInt32(this.compositionToDTSShift),i.writeInt32(this.leastDecodeToDisplayDelta),i.writeInt32(this.greatestDecodeToDisplayDelta),i.writeInt32(this.compositionStartTime),i.writeInt32(this.compositionEndTime)):this.version===1&&(this.size=40,this.writeHeader(i),i.writeInt64(this.compositionToDTSShift),i.writeInt64(this.leastDecodeToDisplayDelta),i.writeInt64(this.greatestDecodeToDisplayDelta),i.writeInt64(this.compositionStartTime),i.writeInt64(this.compositionEndTime))}},xl.fourcc="cslg",xl),yl,Vb=(yl=class extends R{constructor(){super(...arguments),this.box_name="CompositionOffsetBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.sample_counts=[],this.sample_offsets=[],this.version===0)for(let t=0;t<e;t++){this.sample_counts.push(i.readUint32());const s=i.readInt32();s<0&&I.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(s)}else if(this.version===1)for(let t=0;t<e;t++)this.sample_counts.push(i.readUint32()),this.sample_offsets.push(i.readInt32())}write(i){this.version=this.sample_offsets.some(e=>e<0)?1:0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(i),i.writeUint32(this.sample_counts.length);for(let e=0;e<this.sample_counts.length;e++)i.writeUint32(this.sample_counts[e]),this.version===1?i.writeInt32(this.sample_offsets[e]):i.writeUint32(this.sample_offsets[e])}unpack(i){let e=0;for(let t=0;t<this.sample_counts.length;t++)for(let s=0;s<this.sample_counts[t];s++)i[e].pts=i[e].dts+this.sample_offsets[t],e++}},yl.fourcc="ctts",yl),vl,$b=(vl=class extends B{constructor(){super(...arguments),this.box_name="AC3SpecificBox"}parse(i){const e=i.readUint8(),t=i.readUint8(),s=i.readUint8();this.fscod=e>>6,this.bsid=e>>1&31,this.bsmod=(e&1)<<2|t>>6&3,this.acmod=t>>3&7,this.lfeon=t>>2&1,this.bit_rate_code=t&3|s>>5&7}},vl.fourcc="dac3",vl),bl,Xb=(bl=class extends B{constructor(){super(...arguments),this.box_name="EC3SpecificBox"}parse(i){const e=i.readUint16();this.data_rate=e>>3,this.num_ind_sub=e&7,this.ind_subs=[];for(let t=0;t<this.num_ind_sub+1;t++){const s=i.readUint8(),r=i.readUint8(),n=i.readUint8(),o={fscod:s>>6,bsid:s>>1&31,bsmod:(s&1)<<4|r>>4&15,acmod:r>>1&7,lfeon:r&1,num_dep_sub:n>>1&15};this.ind_subs.push(o),o.num_dep_sub>0&&(o.chan_loc=(n&1)<<8|i.readUint8())}}},bl.fourcc="dec3",bl),Tl,Yb=(Tl=class extends R{constructor(){super(...arguments),this.box_name="FLACSpecificBox"}parse(i){this.parseFullHeader(i);const e=127,t=128,s=[],r=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];let n;do{n=i.readUint8();const o=Math.min(n&e,r.length-1);o?i.readUint8Array(i.readUint24()):(i.readUint8Array(13),this.samplerate=i.readUint32()>>12,i.readUint8Array(20)),s.push(r[o])}while(n&t);this.numMetadataBlocks=s.length+" ("+s.join(", ")+")"}},Tl.fourcc="dfLa",Tl),wl,qb=(wl=class extends B{constructor(){super(...arguments),this.box_name="hintimmediateBytesSent"}parse(i){this.bytessent=i.readUint64()}},wl.fourcc="dimm",wl),Sl,Kb=(Sl=class extends B{constructor(){super(...arguments),this.box_name="hintlongestpacket"}parse(i){this.time=i.readUint32()}},Sl.fourcc="dmax",Sl),Cl,jb=(Cl=class extends B{constructor(){super(...arguments),this.box_name="hintmediaBytesSent"}parse(i){this.bytessent=i.readUint64()}},Cl.fourcc="dmed",Cl),Al,Zb=(Al=class extends B{constructor(){super(...arguments),this.box_name="OpusSpecificBox"}parse(i){if(this.Version=i.readUint8(),this.OutputChannelCount=i.readUint8(),this.PreSkip=i.readUint16(),this.InputSampleRate=i.readUint32(),this.OutputGain=i.readInt16(),this.ChannelMappingFamily=i.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=i.readUint8(),this.CoupledCount=i.readUint8(),this.ChannelMapping=[];for(let e=0;e<this.OutputChannelCount;e++)this.ChannelMapping[e]=i.readUint8()}}write(i){if(this.size=11,this.ChannelMappingFamily!==0&&(this.size+=2+this.OutputChannelCount),this.writeHeader(i),i.writeUint8(this.Version),i.writeUint8(this.OutputChannelCount),i.writeUint16(this.PreSkip),i.writeUint32(this.InputSampleRate),i.writeInt16(this.OutputGain),i.writeUint8(this.ChannelMappingFamily),this.ChannelMappingFamily!==0){i.writeUint8(this.StreamCount),i.writeUint8(this.CoupledCount);for(let e=0;e<this.OutputChannelCount;e++)i.writeUint8(this.ChannelMapping[e])}}},Al.fourcc="dOps",Al),El,Jb=(El=class extends B{constructor(){super(...arguments),this.box_name="hintrepeatedBytesSent"}parse(i){this.bytessent=i.readUint64()}},El.fourcc="drep",El),Il,Qb=(Il=class extends R{constructor(){super(...arguments),this.box_name="EditListBox"}parse(i){this.parseFullHeader(i),this.entries=[];const e=i.readUint32();for(let t=0;t<e;t++){const s={segment_duration:this.version===1?i.readUint64():i.readUint32(),media_time:this.version===1?i.readInt64():i.readInt32(),media_rate_integer:i.readInt16(),media_rate_fraction:i.readInt16()};this.entries.push(s)}}write(i){const e=this.entries.some(t=>t.segment_duration>Ae||t.media_time>Ae)||this.version===1;this.version=e?1:0,this.size=4+12*this.entries.length,this.size+=e?8*this.entries.length:0,this.writeHeader(i),i.writeUint32(this.entries.length);for(let t=0;t<this.entries.length;t++){const s=this.entries[t];e?(i.writeUint64(s.segment_duration),i.writeInt64(s.media_time)):(i.writeUint32(s.segment_duration),i.writeInt32(s.media_time)),i.writeInt16(s.media_rate_integer),i.writeInt16(s.media_rate_fraction)}}},Il.fourcc="elst",Il),Pl,e2=(Pl=class extends R{constructor(){super(...arguments),this.box_name="EventMessageBox"}parse(i){this.parseFullHeader(i),this.version===1?(this.timescale=i.readUint32(),this.presentation_time=i.readUint64(),this.event_duration=i.readUint32(),this.id=i.readUint32(),this.scheme_id_uri=i.readCString(),this.value=i.readCString()):(this.scheme_id_uri=i.readCString(),this.value=i.readCString(),this.timescale=i.readUint32(),this.presentation_time_delta=i.readUint32(),this.event_duration=i.readUint32(),this.id=i.readUint32());let e=this.size-this.hdr_size-(16+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version===1&&(e-=4),this.message_data=i.readUint8Array(e)}write(i){this.version=0,this.flags=0,this.size=16+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(i),i.writeCString(this.scheme_id_uri),i.writeCString(this.value),i.writeUint32(this.timescale),i.writeUint32(this.presentation_time_delta),i.writeUint32(this.event_duration),i.writeUint32(this.id),i.writeUint8Array(this.message_data)}},Pl.fourcc="emsg",Pl),ke=class extends R{parse(e){this.parseFullHeader(e),this.group_id=e.readUint32(),this.num_entities_in_group=e.readUint32(),this.entity_ids=[];for(let t=0;t<this.num_entities_in_group;t++){const s=e.readUint32();this.entity_ids.push(s)}}},Rl,t2=(Rl=class extends ke{constructor(){super(...arguments),this.box_name="Auto exposure bracketing"}},Rl.fourcc="aebr",Rl),Ml,i2=(Ml=class extends ke{constructor(){super(...arguments),this.box_name="Flash exposure information"}},Ml.fourcc="afbr",Ml),kl,s2=(kl=class extends ke{constructor(){super(...arguments),this.box_name="Album collection"}},kl.fourcc="albc",kl),Fl,r2=(Fl=class extends ke{constructor(){super(...arguments),this.box_name="Alternative entity"}},Fl.fourcc="altr",Fl),Bl,n2=(Bl=class extends ke{constructor(){super(...arguments),this.box_name="Burst image"}},Bl.fourcc="brst",Bl),Ul,o2=(Ul=class extends ke{constructor(){super(...arguments),this.box_name="Depth of field bracketing"}},Ul.fourcc="dobr",Ul),Ol,a2=(Ol=class extends ke{constructor(){super(...arguments),this.box_name="Equivalent entity"}},Ol.fourcc="eqiv",Ol),Dl,l2=(Dl=class extends ke{constructor(){super(...arguments),this.box_name="Favorites collection"}},Dl.fourcc="favc",Dl),Gl,c2=(Gl=class extends ke{constructor(){super(...arguments),this.box_name="Focus bracketing"}},Gl.fourcc="fobr",Gl),zl,h2=(zl=class extends ke{constructor(){super(...arguments),this.box_name="Image item with an audio track"}},zl.fourcc="iaug",zl),Nl,u2=(Nl=class extends ke{constructor(){super(...arguments),this.box_name="Panorama"}},Nl.fourcc="pano",Nl),Ll,d2=(Ll=class extends ke{constructor(){super(...arguments),this.box_name="Slideshow"}},Ll.fourcc="slid",Ll),Hl,f2=(Hl=class extends ke{constructor(){super(...arguments),this.box_name="Stereo"}},Hl.fourcc="ster",Hl),Wl,p2=(Wl=class extends ke{constructor(){super(...arguments),this.box_name="Time-synchronized capture"}},Wl.fourcc="tsyn",Wl),Vl,m2=(Vl=class extends ke{constructor(){super(...arguments),this.box_name="White balance bracketing"}},Vl.fourcc="wbbr",Vl),$l,g2=($l=class extends ke{constructor(){super(...arguments),this.box_name="Progressive rendering"}},$l.fourcc="prgr",$l),Xl,_2=(Xl=class extends ke{constructor(){super(...arguments),this.box_name="Image pyramid"}parse(i){this.parseFullHeader(i),this.group_id=i.readUint32(),this.num_entities_in_group=i.readUint32(),this.entity_ids=[];for(let e=0;e<this.num_entities_in_group;e++){const t=i.readUint32();this.entity_ids.push(t)}this.tile_size_x=i.readUint16(),this.tile_size_y=i.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[];for(let e=0;e<this.num_entities_in_group;e++)this.layer_binning[e]=i.readUint16(),this.tiles_in_layer_row_minus1[e]=i.readUint16(),this.tiles_in_layer_column_minus1[e]=i.readUint16()}},Xl.fourcc="pymd",Xl),Yl,x2=(Yl=class extends B{constructor(){super(...arguments),this.box_name="FieldHandlingBox"}parse(i){this.fieldCount=i.readUint8(),this.fieldOrdering=i.readUint8()}},Yl.fourcc="fiel",Yl),ql,y2=(ql=class extends B{constructor(){super(...arguments),this.box_name="OriginalFormatBox"}parse(i){this.data_format=i.readString(4)}},ql.fourcc="frma",ql),Kl,v2=(Kl=class extends B{constructor(){super(...arguments),this.box_name="ImageMirror"}parse(i){const e=i.readUint8();this.reserved=e>>7,this.axis=e&1}},Kl.fourcc="imir",Kl),jl,b2=(jl=class extends R{constructor(){super(...arguments),this.box_name="ItemPropertyAssociationBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();this.associations=[];for(let t=0;t<e;t++){const s=this.version<1?i.readUint16():i.readUint32(),r=[],n=i.readUint8();for(let o=0;o<n;o++){const a=i.readUint8();r.push({essential:(a&128)>>7===1,property_index:this.flags&1?(a&127)<<8|i.readUint8():a&127})}this.associations.push({id:s,props:r})}}},jl.fourcc="ipma",jl),Zl,T2=(Zl=class extends B{constructor(){super(...arguments),this.box_name="ImageRotation"}parse(i){this.angle=i.readUint8()&3}},Zl.fourcc="irot",Zl),Jl,w2=(Jl=class extends R{constructor(){super(...arguments),this.box_name="ImageSpatialExtentsProperty"}parse(i){this.parseFullHeader(i),this.image_width=i.readUint32(),this.image_height=i.readUint32()}},Jl.fourcc="ispe",Jl),Ql,S2=(Ql=class extends R{constructor(){super(...arguments),this.box_name="TAITimestampBox"}parse(i){this.TAI_timestamp=i.readUint64();const e=i.readUint8();this.sychronization_state=e>>7&1,this.timestamp_generation_failure=e>>6&1,this.timestamp_is_modified=e>>5&1}},Ql.fourcc="itai",Ql),ec,C2=(ec=class extends R{constructor(){super(...arguments),this.box_name="KindBox"}parse(i){this.parseFullHeader(i),this.schemeURI=i.readCString(),this.isEndOfBox(i)||(this.value=i.readCString())}write(i){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value?this.value.length+1:0),this.writeHeader(i),i.writeCString(this.schemeURI),this.value&&i.writeCString(this.value)}},ec.fourcc="kind",ec),tc,A2=(tc=class extends R{constructor(){super(...arguments),this.box_name="LevelAssignmentBox"}parse(i){this.parseFullHeader(i);const e=i.readUint8();this.levels=[];for(let t=0;t<e;t++){const s={};this.levels[t]=s,s.track_ID=i.readUint32();const r=i.readUint8();switch(s.padding_flag=r>>7,s.assignment_type=r&127,s.assignment_type){case 0:s.grouping_type=i.readString(4);break;case 1:s.grouping_type=i.readString(4),s.grouping_type_parameter=i.readUint32();break;case 2:break;case 3:break;case 4:s.sub_track_id=i.readUint32();break;default:I.warn("BoxParser",`Unknown level assignment type: ${s.assignment_type}`)}}}},tc.fourcc="leva",tc),ic,E2=(ic=class extends B{constructor(){super(...arguments),this.box_name="LHEVCConfigurationBox"}parse(i){this.configurationVersion=i.readUint8(),this.min_spatial_segmentation_idc=i.readUint16()&4095,this.parallelismType=i.readUint8()&3;let e=i.readUint8();this.numTemporalLayers=(e&13)>>3,this.temporalIdNested=(e&4)>>2,this.lengthSizeMinusOne=e&3,this.nalu_arrays=[];const t=i.readUint8();for(let s=0;s<t;s++){const r=[];this.nalu_arrays.push(r),e=i.readUint8(),r.completeness=(e&128)>>7,r.nalu_type=e&63;const n=i.readUint16();for(let o=0;o<n;o++){const a=i.readUint16();r.push({data:i.readUint8Array(a)})}}}},ic.fourcc="lhvC",ic),sc,I2=(sc=class extends B{constructor(){super(...arguments),this.box_name="LayerSelectorProperty"}parse(i){this.layer_id=i.readUint16()}},sc.fourcc="lsel",sc),rc,P2=(rc=class extends B{constructor(){super(...arguments),this.box_name="hintmaxrate"}parse(i){this.period=i.readUint32(),this.bytes=i.readUint32()}},rc.fourcc="maxr",rc),mr=class{constructor(i,e){this.x=i,this.y=e}toString(){return"("+this.x+","+this.y+")"}},nc,R2=(nc=class extends B{constructor(){super(...arguments),this.box_name="MasteringDisplayColourVolumeBox"}parse(i){this.display_primaries=[],this.display_primaries[0]=new mr(i.readUint16(),i.readUint16()),this.display_primaries[1]=new mr(i.readUint16(),i.readUint16()),this.display_primaries[2]=new mr(i.readUint16(),i.readUint16()),this.white_point=new mr(i.readUint16(),i.readUint16()),this.max_display_mastering_luminance=i.readUint32(),this.min_display_mastering_luminance=i.readUint32()}},nc.fourcc="mdcv",nc),oc,M2=(oc=class extends R{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessOffsetBox"}parse(i){this.parseFullHeader(i),this._size=i.readUint32()}},oc.fourcc="mfro",oc),ac,k2=(ac=class extends R{constructor(){super(...arguments),this.box_name="MaskConfigurationProperty"}parse(i){this.parseFullHeader(i),this.bits_per_pixel=i.readUint8()}},ac.fourcc="mskC",ac),lc,F2=(lc=class extends B{constructor(){super(...arguments),this.box_name="hintPacketsSent"}parse(i){this.packetssent=i.readUint32()}},lc.fourcc="npck",lc),cc,B2=(cc=class extends B{constructor(){super(...arguments),this.box_name="hintPacketsSent"}parse(i){this.packetssent=i.readUint64()}},cc.fourcc="nump",cc),U2=class{constructor(i,e){this.pad1=i,this.pad2=e}},hc,O2=(hc=class extends R{constructor(){super(...arguments),this.box_name="PaddingBitsBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();this.padbits=[];for(let t=0;t<Math.floor((e+1)/2);t++){const s=i.readUint8(),r=(s&112)>>4,n=s&7;this.padbits.push(new U2(r,n))}}},hc.fourcc="padb",hc),uc,D2=(uc=class extends B{constructor(){super(...arguments),this.box_name="PixelAspectRatioBox"}parse(i){this.hSpacing=i.readUint32(),this.vSpacing=i.readUint32()}},uc.fourcc="pasp",uc),dc,G2=(dc=class extends B{constructor(){super(...arguments),this.box_name="CuePayloadBox"}parse(i){this.text=i.readString(this.size-this.hdr_size)}},dc.fourcc="payl",dc),fc,z2=(fc=class extends B{constructor(){super(...arguments),this.box_name="hintpayloadID"}parse(i){this.payloadID=i.readUint32();const e=i.readUint8();this.rtpmap_string=i.readString(e)}},fc.fourcc="payt",fc),pc,N2=(pc=class extends R{constructor(){super(...arguments),this.box_name="ProgressiveDownloadInfoBox",this.rate=[],this.initial_delay=[]}parse(i){this.parseFullHeader(i);const e=(this.size-this.hdr_size)/8;for(let t=0;t<e;t++)this.rate[t]=i.readUint32(),this.initial_delay[t]=i.readUint32()}},pc.fourcc="pdin",pc),mc,L2=(mc=class extends R{constructor(){super(...arguments),this.box_name="PixelInformationProperty"}parse(i){this.parseFullHeader(i),this.num_channels=i.readUint8(),this.bits_per_channels=[];for(let e=0;e<this.num_channels;e++)this.bits_per_channels[e]=i.readUint8()}},mc.fourcc="pixi",mc),gc,H2=(gc=class extends B{constructor(){super(...arguments),this.box_name="hintlargestpacket"}parse(i){this.bytes=i.readUint32()}},gc.fourcc="pmax",gc),_c,W2=(_c=class extends R{constructor(){super(...arguments),this.box_name="ProgressiveDerivedImageItemInformationProperty"}parse(i){if(this.parseFullHeader(i),this.step_count=i.readUint16(),this.item_count=[],this.flags&2)for(let e=0;e<this.step_count;e++)this.item_count[e]=i.readUint16()}},_c.fourcc="prdi",_c),xc,V2=(xc=class extends R{constructor(){super(...arguments),this.box_name="ProjectionFormatBox"}parse(i){this.parseFullHeader(i),this.projection_type=i.readUint8()&31}},xc.fourcc="prfr",xc),yc,$2=(yc=class extends R{constructor(){super(...arguments),this.box_name="ProducerReferenceTimeBox"}parse(i){this.parseFullHeader(i),this.ref_track_id=i.readUint32(),this.ntp_timestamp=i.readUint64(),this.version===0?this.media_time=i.readUint32():this.media_time=i.readUint64()}},yc.fourcc="prft",yc),vc,X2=(vc=class extends R{constructor(){super(...arguments),this.box_name="ProtectionSystemSpecificHeaderBox"}parse(i){if(this.parseFullHeader(i),this.system_id=ri(i),this.kid=[],this.version>0){const t=i.readUint32();for(let s=0;s<t;s++)this.kid[s]=ri(i)}const e=i.readUint32();e>0&&(this.protection_data=i.readUint8Array(e))}},vc.fourcc="pssh",vc),bc,Y2=(bc=class extends R{constructor(){super(...arguments),this.box_name="TrackCleanApertureDimensionsBox"}parse(i){this.parseFullHeader(i),this.width=i.readUint32(),this.height=i.readUint32()}},bc.fourcc="clef",bc);function q2(i,e){if(i===ls.Types.UTF8)return new TextDecoder("utf-8").decode(e);const t=new DataView(e.buffer);if(i===ls.Types.BE_UNSIGNED_INT){if(e.length===1)return t.getUint8(0);if(e.length===2)return t.getUint16(0,!1);if(e.length===4)return t.getUint32(0,!1);if(e.length===8)return t.getBigUint64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_UNSIGNED_INT length "+e.length)}else if(i===ls.Types.BE_SIGNED_INT){if(e.length===1)return t.getInt8(0);if(e.length===2)return t.getInt16(0,!1);if(e.length===4)return t.getInt32(0,!1);if(e.length===8)return t.getBigInt64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_SIGNED_INT length "+e.length)}else if(i===ls.Types.BE_FLOAT32)return t.getFloat32(0,!1);I.warn("DataBox","Unsupported or unimplemented itif data type: "+i)}var gr,ls=(gr=class extends B{constructor(){super(...arguments),this.box_name="DataBox"}parse(i){this.valueType=i.readUint32(),this.country=i.readUint16(),this.country>255&&(i.seek(i.getPosition()-2),this.countryString=i.readString(2)),this.language=i.readUint16(),this.language>255&&(i.seek(i.getPosition()-2),this.parseLanguage(i)),this.raw=i.readUint8Array(this.size-this.hdr_size-8),this.value=q2(this.valueType,this.raw)}},gr.fourcc="data",gr.Types={RESERVED:0,UTF8:1,UTF16:2,SJIS:3,UTF8_SORT:4,UTF16_SORT:5,JPEG:13,PNG:14,BE_SIGNED_INT:21,BE_UNSIGNED_INT:22,BE_FLOAT32:23,BE_FLOAT64:24,BMP:27,QT_ATOM:28,BE_SIGNED_INT8:65,BE_SIGNED_INT16:66,BE_SIGNED_INT32:67,BE_FLOAT32_POINT:70,BE_FLOAT32_DIMENSIONS:71,BE_FLOAT32_RECT:72,BE_SIGNED_INT64:74,BE_UNSIGNED_INT8:75,BE_UNSIGNED_INT16:76,BE_UNSIGNED_INT32:77,BE_UNSIGNED_INT64:78,BE_FLOAT64_AFFINE_TRANSFORM:79},gr),Tc,K2=(Tc=class extends R{constructor(){super(...arguments),this.box_name="TrackEncodedPixelsDimensionsBox"}parse(i){this.parseFullHeader(i),this.width=i.readUint32(),this.height=i.readUint32()}},Tc.fourcc="enof",Tc),wc,j2=(wc=class extends B{constructor(){super(...arguments),this.box_name="IlstBox"}parse(i){this.list={};let e=this.size-this.hdr_size;for(;e>0;){const t=i.readUint32(),s=i.readUint32(),r=ht(i,!1,t-8);r.code===We&&(this.list[s]=r.box),e-=t}}},wc.fourcc="ilst",wc),Sc,Z2=(Sc=class extends R{constructor(){super(...arguments),this.box_name="KeysBox"}parse(i){this.parseFullHeader(i),this.count=i.readUint32(),this.keys={};for(let e=0;e<this.count;e++){const t=i.readUint32();this.keys[e+1]=i.readString(t-4)}}},Sc.fourcc="keys",Sc),Cc,J2=(Cc=class extends R{constructor(){super(...arguments),this.box_name="TrackProductionApertureDimensionsBox"}parse(i){this.parseFullHeader(i),this.width=i.readUint32(),this.height=i.readUint32()}},Cc.fourcc="prof",Cc),Ac,Q2=(Ac=class extends ee{constructor(){super(...arguments),this.box_name="TrackApertureModeDimensionsBox",this.clefs=[],this.profs=[],this.enofs=[],this.subBoxNames=["clef","prof","enof"]}},Ac.fourcc="tapt",Ac),Ec,eT=(Ec=class extends ee{constructor(){super(...arguments),this.box_name="siDecompressionParamBox"}},Ec.fourcc="wave",Ec),Ic,tT=(Ic=class extends B{constructor(){super(...arguments),this.box_name="rtpmoviehintinformation"}parse(i){this.descriptionformat=i.readString(4),this.sdptext=i.readString(this.size-this.hdr_size-4)}},Ic.fourcc="rtp ",Ic),Pc,iT=(Pc=class extends R{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationOffsetsBox"}parse(i){this.parseFullHeader(i),this.flags&1&&(this.aux_info_type=i.readString(4),this.aux_info_type_parameter=i.readUint32());const e=i.readUint32();this.offset=[];for(let t=0;t<e;t++)this.version===0?this.offset[t]=i.readUint32():this.offset[t]=i.readUint64()}},Pc.fourcc="saio",Pc),Rc,sT=(Rc=class extends R{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationSizesBox"}parse(i){if(this.parseFullHeader(i),this.flags&1&&(this.aux_info_type=i.readString(4),this.aux_info_type_parameter=i.readUint32()),this.default_sample_info_size=i.readUint8(),this.sample_count=i.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(let e=0;e<this.sample_count;e++)this.sample_info_size[e]=i.readUint8()}},Rc.fourcc="saiz",Rc),rT=class{constructor(i,e){this.bad_pixel_row=i,this.bad_pixel_column=e}toString(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"}},Mc,nT=(Mc=class extends R{constructor(){super(...arguments),this.box_name="SensorBadPixelsMapBox"}parse(i){this.parseFullHeader(i),this.component_count=i.readUint16(),this.component_index=[];for(let t=0;t<this.component_count;t++)this.component_index.push(i.readUint16());const e=i.readUint8();this.correction_applied=(e&128)===128,this.num_bad_rows=i.readUint32(),this.num_bad_cols=i.readUint32(),this.num_bad_pixels=i.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[];for(let t=0;t<this.num_bad_rows;t++)this.bad_rows.push(i.readUint32());for(let t=0;t<this.num_bad_cols;t++)this.bad_columns.push(i.readUint32());for(let t=0;t<this.num_bad_pixels;t++){const s=i.readUint32(),r=i.readUint32();this.bad_pixels.push(new rT(s,r))}}},Mc.fourcc="sbpm",Mc),kc,oT=(kc=class extends R{constructor(){super(...arguments),this.box_name="SchemeTypeBox"}parse(i){this.parseFullHeader(i),this.scheme_type=i.readString(4),this.scheme_version=i.readUint32(),this.flags&1&&(this.scheme_uri=i.readString(this.size-this.hdr_size-8))}},kc.fourcc="schm",kc),Fc,aT=(Fc=class extends B{constructor(){super(...arguments),this.box_name="rtptracksdphintinformation"}parse(i){this.sdptext=i.readString(this.size-this.hdr_size)}},Fc.fourcc="sdp ",Fc),Bc,lT=(Bc=class extends R{constructor(){super(...arguments),this.box_name="SampleEncryptionBox"}},Bc.fourcc="senc",Bc),Uc,cT=(Uc=class extends R{constructor(){super(...arguments),this.box_name="SMPTE2086MasteringDisplayMetadataBox"}parse(i){this.parseFullHeader(i),this.primaryRChromaticity_x=i.readUint16(),this.primaryRChromaticity_y=i.readUint16(),this.primaryGChromaticity_x=i.readUint16(),this.primaryGChromaticity_y=i.readUint16(),this.primaryBChromaticity_x=i.readUint16(),this.primaryBChromaticity_y=i.readUint16(),this.whitePointChromaticity_x=i.readUint16(),this.whitePointChromaticity_y=i.readUint16(),this.luminanceMax=i.readUint32(),this.luminanceMin=i.readUint32()}},Uc.fourcc="SmDm",Uc),Oc,hT=(Oc=class extends R{constructor(){super(...arguments),this.box_name="SamplingRateBox"}parse(i){this.parseFullHeader(i),this.sampling_rate=i.readUint32()}},Oc.fourcc="srat",Oc),Dc,uT=(Dc=class extends R{constructor(){super(...arguments),this.box_name="CompressedSubsegmentIndexBox"}parse(i){this.parseFullHeader(i),this.subsegments=[];const e=i.readUint32();for(let t=0;t<e;t++){const s={};this.subsegments.push(s),s.ranges=[];const r=i.readUint32();for(let n=0;n<r;n++){const o={};s.ranges.push(o),o.level=i.readUint8(),o.range_size=i.readUint24()}}}},Dc.fourcc="ssix",Dc),Gc,dT=(Gc=class extends R{constructor(){super(...arguments),this.box_name="DegradationPriorityBox"}parse(i){this.parseFullHeader(i);const e=(this.size-this.hdr_size)/2;this.priority=[];for(let t=0;t<e;t++)this.priority[t]=i.readUint16()}},Gc.fourcc="stpd",Gc),zc,fT=(zc=class extends R{constructor(){super(...arguments),this.box_name="SubTrackInformationBox"}parse(i){this.parseFullHeader(i),this.switch_group=i.readUint16(),this.alternate_group=i.readUint16(),this.sub_track_id=i.readUint32();const e=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(let t=0;t<e;t++)this.attribute_list[t]=i.readUint32()}},zc.fourcc="stri",zc),Nc,pT=(Nc=class extends R{constructor(){super(...arguments),this.box_name="SubTrackSampleGroupBox"}parse(i){this.parseFullHeader(i),this.grouping_type=i.readUint32();const e=i.readUint16();this.group_description_index=[];for(let t=0;t<e;t++)this.group_description_index[t]=i.readUint32()}},Nc.fourcc="stsg",Nc),Lc,mT=(Lc=class extends R{constructor(){super(...arguments),this.box_name="ShadowSyncSampleBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(let t=0;t<e;t++)this.shadowed_sample_numbers.push(i.readUint32()),this.sync_sample_numbers.push(i.readUint32())}write(i){this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(i),i.writeUint32(this.shadowed_sample_numbers.length);for(let e=0;e<this.shadowed_sample_numbers.length;e++)i.writeUint32(this.shadowed_sample_numbers[e]),i.writeUint32(this.sync_sample_numbers[e])}},Lc.fourcc="stsh",Lc),Hc,gT=(Hc=class extends R{constructor(){super(...arguments),this.box_name="SyncSampleBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.version===0){this.sample_numbers=[];for(let t=0;t<e;t++)this.sample_numbers.push(i.readUint32())}}write(i){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(i),i.writeUint32(this.sample_numbers.length),i.writeUint32Array(this.sample_numbers)}},Hc.fourcc="stss",Hc),Wc,_T=(Wc=class extends R{constructor(){super(...arguments),this.box_name="StereoVideoBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();this.single_view_allowed=e&3,this.stereo_scheme=i.readUint32();const t=i.readUint32();for(this.stereo_indication_type=i.readString(t),this.boxes=[];i.getPosition()<this.start+this.size;){const s=ht(i,!1,this.size-(i.getPosition()-this.start));if(s.code===We){const r=s.box;this.boxes.push(r),this[r.type]=r}else return}}},Wc.fourcc="stvi",Wc),Vc,xT=(Vc=class extends B{constructor(){super(...arguments),this.box_name="SegmentTypeBox"}parse(i){let e=this.size-this.hdr_size;this.major_brand=i.readString(4),this.minor_version=i.readUint32(),e-=8,this.compatible_brands=[];let t=0;for(;e>=4;)this.compatible_brands[t]=i.readString(4),e-=4,t++}write(i){this.size=8+4*this.compatible_brands.length,this.writeHeader(i),i.writeString(this.major_brand,void 0,4),i.writeUint32(this.minor_version);for(let e=0;e<this.compatible_brands.length;e++)i.writeString(this.compatible_brands[e],void 0,4)}},Vc.fourcc="styp",Vc),$c,yT=($c=class extends R{constructor(){super(...arguments),this.box_name="CompactSampleSizeBox"}parse(i){if(this.parseFullHeader(i),this.sample_sizes=[],this.version===0){this.reserved=i.readUint24(),this.field_size=i.readUint8();const e=i.readUint32();if(this.field_size===4)for(let t=0;t<e;t+=2){const s=i.readUint8();this.sample_sizes[t]=s>>4&15,this.sample_sizes[t+1]=s&15}else if(this.field_size===8)for(let t=0;t<e;t++)this.sample_sizes[t]=i.readUint8();else if(this.field_size===16)for(let t=0;t<e;t++)this.sample_sizes[t]=i.readUint16();else I.error("BoxParser","Error in length field in stz2 box",i.isofile)}}},$c.fourcc="stz2",$c),Xc,vT=(Xc=class extends R{constructor(){super(...arguments),this.box_name="SubSampleInformationBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();this.entries=[];let t;for(let s=0;s<e;s++){const r={};if(this.entries[s]=r,r.sample_delta=i.readUint32(),r.subsamples=[],t=i.readUint16(),t>0)for(let n=0;n<t;n++){const o={};r.subsamples.push(o),this.version===1?o.size=i.readUint32():o.size=i.readUint16(),o.priority=i.readUint8(),o.discardable=i.readUint8(),o.codec_specific_parameters=i.readUint32()}}}},Xc.fourcc="subs",Xc),Yc,bT=(Yc=class extends R{constructor(){super(...arguments),this.box_name="TAIClockInfoBox"}parse(i){this.time_uncertainty=i.readUint64(),this.clock_resolution=i.readUint32(),this.clock_drift_rate=i.readInt32();const e=i.readUint8();this.clock_type=(e&192)>>6}},Yc.fourcc="taic",Yc),qc,TT=(qc=class extends R{constructor(){super(...arguments),this.box_name="TrackEncryptionBox"}parse(i){if(this.parseFullHeader(i),i.readUint8(),this.version===0)i.readUint8();else{const e=i.readUint8();this.default_crypt_byte_block=e>>4&15,this.default_skip_byte_block=e&15}this.default_isProtected=i.readUint8(),this.default_Per_Sample_IV_Size=i.readUint8(),this.default_KID=ri(i),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=i.readUint8(),this.default_constant_IV=i.readUint8Array(this.default_constant_IV_size))}},qc.fourcc="tenc",qc),Kc,wT=(Kc=class extends R{constructor(){super(...arguments),this.box_name="TrackFragmentRandomAccessBox"}parse(i){this.parseFullHeader(i),this.track_ID=i.readUint32(),i.readUint24();const e=i.readUint8();this.length_size_of_traf_num=e>>4&3,this.length_size_of_trun_num=e>>2&3,this.length_size_of_sample_num=e&3,this.entries=[];const t=i.readUint32();for(let s=0;s<t;s++)this.version===1?(this.time=i.readUint64(),this.moof_offset=i.readUint64()):(this.time=i.readUint32(),this.moof_offset=i.readUint32()),this.traf_number=i["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=i["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=i["readUint"+8*(this.length_size_of_sample_num+1)]()}},Kc.fourcc="tfra",Kc),jc,ST=(jc=class extends B{constructor(){super(...arguments),this.box_name="hintmaxrelativetime"}parse(i){this.time=i.readUint32()}},jc.fourcc="tmax",jc),Zc,CT=(Zc=class extends B{constructor(){super(...arguments),this.box_name="hintminrelativetime"}parse(i){this.time=i.readUint32()}},Zc.fourcc="tmin",Zc),Jc,AT=(Jc=class extends B{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(i){this.bytessent=i.readUint32()}},Jc.fourcc="totl",Jc),Qc,ET=(Qc=class extends B{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(i){this.bytessent=i.readUint32()}},Qc.fourcc="tpay",Qc),eh,IT=(eh=class extends B{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(i){this.bytessent=i.readUint64()}},eh.fourcc="tpyl",eh),th,PT=(th=class extends wf{},th.fourcc="msrc",th),cs,RT=(cs=class extends B{constructor(){super(...arguments),this.box_name="TrackReferenceBox",this.references=[]}parse(i){for(;i.getPosition()<this.start+this.size;){const e=ht(i,!0,this.size-(i.getPosition()-this.start));if(e.code===We){cs.allowed_types.includes(e.type)||I.warn("BoxParser",`Unknown track reference type: '${e.type}'`);const t=new Af(e.type,e.size,e.hdr_size,e.start);t.write===B.prototype.write&&t.type!=="mdat"&&(I.info("BoxParser","TrackReference "+t.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),t.parseDataAndRewind(i)),t.parse(i),this.references.push(t)}else return}}},cs.fourcc="tref",cs.allowed_types=["hint","cdsc","font","hind","vdep","vplx","subt","thmb","auxl","cdtg","shsc","aest"],cs),ih,MT=(ih=class extends R{constructor(){super(...arguments),this.box_name="TrackExtensionPropertiesBox"}parse(i){for(this.parseFullHeader(i),this.track_ID=i.readUint32(),this.boxes=[];i.getPosition()<this.start+this.size;){const e=ht(i,!1,this.size-(i.getPosition()-this.start));if(e.code===We){const t=e.box;this.boxes.push(t)}else return}}},ih.fourcc="trep",ih),sh,kT=(sh=class extends B{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(i){this.bytessent=i.readUint64()}},sh.fourcc="trpy",sh),rh,FT=(rh=class extends R{constructor(){super(...arguments),this.box_name="TrackSelectionBox"}parse(i){this.parseFullHeader(i),this.switch_group=i.readUint32();const e=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(let t=0;t<e;t++)this.attribute_list[t]=i.readUint32()}},rh.fourcc="tsel",rh),nh,BT=(nh=class extends R{constructor(){super(...arguments),this.box_name="TextConfigBox"}parse(i){this.parseFullHeader(i),this.config=i.readCString()}},nh.fourcc="txtc",nh),oh,UT=(oh=class extends B{constructor(){super(...arguments),this.box_name="TypeCombinationBox"}parse(i){const e=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(let t=0;t<e;t++)this.compatible_brands[t]=i.readString(4)}},oh.fourcc="tyco",oh),ah,OT=(ah=class extends R{constructor(){super(...arguments),this.box_name="UserDescriptionProperty"}parse(i){this.parseFullHeader(i),this.lang=i.readCString(),this.name=i.readCString(),this.description=i.readCString(),this.tags=i.readCString()}},ah.fourcc="udes",ah),lh,DT=(lh=class extends R{constructor(){super(...arguments),this.box_name="UncompressedFrameConfigBox"}parse(i){if(this.parseFullHeader(i),this.profile=i.readString(4),this.version!==1&&this.version===0){this.component_count=i.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[];for(let t=0;t<this.component_count;t++)this.component_index.push(i.readUint16()),this.component_bit_depth_minus_one.push(i.readUint8()),this.component_format.push(i.readUint8()),this.component_align_size.push(i.readUint8());this.sampling_type=i.readUint8(),this.interleave_type=i.readUint8(),this.block_size=i.readUint8();const e=i.readUint8();this.component_little_endian=e>>7&1,this.block_pad_lsb=e>>6&1,this.block_little_endian=e>>5&1,this.block_reversed=e>>4&1,this.pad_unknown=e>>3&1,this.pixel_size=i.readUint32(),this.row_align_size=i.readUint32(),this.tile_align_size=i.readUint32(),this.num_tile_cols_minus_one=i.readUint32(),this.num_tile_rows_minus_one=i.readUint32()}}},lh.fourcc="uncC",lh),ch,GT=(ch=class extends R{constructor(){super(...arguments),this.box_name="DataEntryUrnBox"}parse(i){this.parseFullHeader(i),this.name=i.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=i.readCString())}write(i){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(i),i.writeCString(this.name),this.location&&i.writeCString(this.location)}},ch.fourcc="urn ",ch),hh,zT=(hh=class extends B{constructor(){super(...arguments),this.box_name="WebVTTConfigurationBox"}parse(i){this.text=i.readString(this.size-this.hdr_size)}},hh.fourcc="vttC",hh),uh,NT=(uh=class extends R{constructor(){super(...arguments),this.box_name="VvcNALUConfigBox"}parse(i){this.parseFullHeader(i);const e=i.readUint8();this.lengthSizeMinusOne=e&3}},uh.fourcc="vvnC",uh),dh,LT=(dh=class extends ye{parse(i){const e=i.readUint16();this.first_output_sample=i.readUint16(),this.sample_offset=[];for(let s=0;s<e;s++)this.sample_offset[s]=i.readUint32();const t=this.description_length-4-4*e;this.num_output_samples=[],this.num_total_samples=[];for(let s=0;s<t/4;s++)this.num_output_samples[s]=i.readUint16(),this.num_total_samples[s]=i.readUint16()}},dh.grouping_type="alst",dh),fh,HT=(fh=class extends ye{parse(i){this.layerNumber=i.readUint8(),this.accurateStatisticsFlag=i.readUint8(),this.avgBitRate=i.readUint16(),this.avgFrameRate=i.readUint16()}},fh.grouping_type="avll",fh),ph,WT=(ph=class extends ye{parse(i){this.subSequenceIdentifier=i.readUint16(),this.layerNumber=i.readUint8();const e=i.readUint8();this.durationFlag=e>>7,this.avgRateFlag=e>>6&1,this.durationFlag&&(this.duration=i.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=i.readUint8(),this.avgBitRate=i.readUint16(),this.avgFrameRate=i.readUint16()),this.dependency=[];const t=i.readUint8();for(let s=0;s<t;s++)this.dependency.push({subSeqDirectionFlag:i.readUint8(),layerNumber:i.readUint8(),subSequenceIdentifier:i.readUint16()})}},ph.grouping_type="avss",ph),mh,VT=(mh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},mh.grouping_type="dtrt",mh),gh,$T=(gh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},gh.grouping_type="mvif",gh),_h,XT=(_h=class extends ye{parse(i){this.roll_distance=i.readInt16()}},_h.grouping_type="prol",_h),xh,YT=(xh=class extends ye{parse(i){const e=i.readUint8();this.num_leading_samples_known=e>>7,this.num_leading_samples=e&127}},xh.grouping_type="rap ",xh),yh,qT=(yh=class extends ye{parse(i){if(this.operation_point_count=i.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)I.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=i.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=i.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(let e=0;e<this.operation_point_count;e++)this.available_bitrate[e]=i.readUint32(),this.target_rate_share[e]=i.readUint16()}this.maximum_bitrate=i.readUint32(),this.minimum_bitrate=i.readUint32(),this.discard_priority=i.readUint8()}}},yh.grouping_type="rash",yh),vh,KT=(vh=class extends ye{parse(i){this.roll_distance=i.readInt16()}},vh.grouping_type="roll",vh),bh,jT=(bh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},bh.grouping_type="scif",bh),Th,ZT=(Th=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Th.grouping_type="scnm",Th),wh,JT=(wh=class extends ye{parse(i){this.reserved=i.readUint8();const e=i.readUint8();this.crypt_byte_block=e>>4,this.skip_byte_block=e&15,this.isProtected=i.readUint8(),this.Per_Sample_IV_Size=i.readUint8(),this.KID=ri(i),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=i.readUint8(),this.constant_IV=i.readUint8Array(this.constant_IV_size))}},wh.grouping_type="seig",wh),Sh,QT=(Sh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Sh.grouping_type="stsa",Sh),Ch,ew=(Ch=class extends ye{parse(i){const e=i.readUint8();this.NAL_unit_type=e&63}},Ch.grouping_type="sync",Ch),Ah,tw=(Ah=class extends ye{parse(i){const e=i.readUint8();this.level_independently_decodable=e>>7}},Ah.grouping_type="tele",Ah),Eh,iw=(Eh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Eh.grouping_type="tsas",Eh),Ih,sw=(Ih=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Ih.grouping_type="tscl",Ih),Ph,rw=(Ph=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Ph.grouping_type="vipr",Ph),Rh,nw=(Rh=class extends B{},Rh.fourcc="uuid",Rh),Mh,Si=(Mh=class extends R{},Mh.fourcc="uuid",Mh),kh,ow=(kh=class extends Si{constructor(){super(...arguments),this.box_name="LiveServerManifestBox"}parse(i){this.parseFullHeader(i),this.LiveServerManifest=i.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}},kh.uuid="a5d40b30e81411ddba2f0800200c9a66",kh),Fh,aw=(Fh=class extends Si{constructor(){super(...arguments),this.box_name="PiffProtectionSystemSpecificHeaderBox"}parse(i){this.parseFullHeader(i),this.system_id=ri(i);const e=i.readUint32();e>0&&(this.data=i.readUint8Array(e))}},Fh.uuid="d08a4f1810f34a82b6c832d8aba183d3",Fh),Bh,lw=(Bh=class extends Si{constructor(){super(...arguments),this.box_name="PiffSampleEncryptionBox"}},Bh.uuid="a2394f525a9b4f14a2446c427c648df4",Bh),Uh,cw=(Uh=class extends Si{constructor(){super(...arguments),this.box_name="PiffTrackEncryptionBox"}parse(i){this.parseFullHeader(i),this.default_AlgorithmID=i.readUint24(),this.default_IV_size=i.readUint8(),this.default_KID=ri(i)}},Uh.uuid="8974dbce7be74c5184f97148f9882554",Uh),Oh,hw=(Oh=class extends Si{constructor(){super(...arguments),this.box_name="TfrfBox"}parse(i){this.parseFullHeader(i),this.fragment_count=i.readUint8(),this.entries=[];for(let e=0;e<this.fragment_count;e++){let t=0,s=0;this.version===1?(t=i.readUint64(),s=i.readUint64()):(t=i.readUint32(),s=i.readUint32()),this.entries.push({absolute_time:t,absolute_duration:s})}}},Oh.uuid="d4807ef2ca3946958e5426cb9e46a79f",Oh),Dh,uw=(Dh=class extends Si{constructor(){super(...arguments),this.box_name="TfxdBox"}parse(i){this.parseFullHeader(i),this.version===1?(this.absolute_time=i.readUint64(),this.duration=i.readUint64()):(this.absolute_time=i.readUint32(),this.duration=i.readUint32())}},Dh.uuid="6d1d9b0542d544e680e2141daff757b2",Dh),Gh,dw=(Gh=class extends nw{constructor(){super(...arguments),this.box_name="ItemContentIDProperty"}parse(i){this.content_id=i.readCString()}},Gh.uuid="261ef3741d975bbaacbd9d2c8ea73522",Gh),xp=Iy(_p);Py(fp);const oi=Object.freeze(Object.defineProperty({__proto__:null,AudioSampleEntry:ze,Box:B,BoxParser:xp,DIFF_BOXES_PROP_NAMES:nr,DIFF_PRIMITIVE_ARRAY_PROP_NAMES:Ef,DataStream:Pe,Descriptor:Xt,ES_Descriptor:tl,Endianness:xf,FullBox:R,HintSampleEntry:In,ISOFile:up,Log:I,MP4BoxBuffer:xt,MPEG4DescriptorParser:gp,MetadataSampleEntry:ni,MultiBufferStream:Ti,SampleEntry:yt,SampleGroupEntry:ye,SampleGroupInfo:dr,SingleItemTypeReferenceBox:Sf,SingleItemTypeReferenceBoxLarge:Cf,SubtitleSampleEntry:$t,SystemSampleEntry:ar,TX3GParser:Sb,TextSampleEntry:Pf,Textin4Parser:wb,TrackGroupTypeBox:wf,TrackReferenceTypeBox:Af,VTTin4Parser:bb,VisualSampleEntry:fe,XMLSubtitlein4Parser:Tb,boxEqual:Cn,boxEqualFields:If,createFile:dp},Symbol.toStringTag,{value:"Module"})),fw=xp?.box?.esds,pw=dp;class mw{all=new Map;on(e,t){const s=this.all.get(e);return s?s.push(t):this.all.set(e,[t]),()=>this.off(e,t)}once(e,t){const s=this.on(e,r=>{s(),t(r)});return s}off(e,t){const s=this.all.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let s=this.all.get(e);s&&s.slice().forEach(r=>{r(t)}),s=this.all.get("*"),s&&s.slice().forEach(r=>{r(e,t)})}}const gw={0:"debug",1:"info",2:"warn",3:"error"};function _w(i){if(i instanceof Error)return String(i);if(typeof i=="object"&&i!==null)try{return JSON.stringify(i,(e,t)=>t instanceof Error?String(t):t)}catch{return String(i)}return String(i)}function xw(){const i=new Date,e=s=>s.toString().padStart(2,"0"),t=i.getMilliseconds().toString().padStart(3,"0");return`${e(i.getHours())}:${e(i.getMinutes())}:${e(i.getSeconds())}.${t}`}class yw{threshold=1;history=[];debug=(...e)=>this.log(0,console.debug,e);info=(...e)=>this.log(1,console.info,e);warn=(...e)=>this.log(2,console.warn,e);error=(...e)=>this.log(3,console.error,e);log(e,t,s){e>=this.threshold&&(t(...s),this.history.push({level:gw[e],time:xw(),args:s}))}setThreshold(e){this.threshold=e}getThreshold(){return this.threshold}createTagged(e){return{debug:(...t)=>this.debug(e,...t),info:(...t)=>this.info(e,...t),warn:(...t)=>this.warn(e,...t),error:(...t)=>this.error(e,...t)}}dump(){return this.history.map(({level:e,time:t,args:s})=>`[${e.toUpperCase()}][${t}] ${s.map(_w).join(" ")}`).join(`
|
|
3
|
-
`)}}const vt=new yw,Fe={debug:vt.debug,info:vt.info,warn:vt.warn,error:vt.error,setLogLevel:i=>{const e=i;e===Fe.debug?vt.setThreshold(0):e===Fe.info?vt.setThreshold(1):e===Fe.warn?vt.setThreshold(2):e===Fe.error&&vt.setThreshold(3)},create:i=>vt.createTagged(i),dump:async()=>vt.dump()};(async function(){if(!(typeof navigator>"u"||typeof document>"u")&&(Fe.info(`User Agent: ${navigator.userAgent}`),document.addEventListener("visibilitychange",()=>{Fe.info(`visibilitychange: ${document.visibilityState}`)}),"PressureObserver"in globalThis))try{let i="";new globalThis.PressureObserver(e=>{const t=JSON.stringify(e.map(s=>s.state));t!==i&&(Fe.info(`cpu state change: ${t}`),i=t)}).observe("cpu")}catch(i){Fe.debug("Failed to initialize PressureObserver",i)}})();let Pt=class{buffer;view;offset=0;constructor(e){this.buffer=new Uint8Array(e),this.view=new DataView(this.buffer.buffer)}writeUint32(e){return this.view.setUint32(this.offset,e),this.offset+=4,this}writeUint16(e){return this.view.setUint16(this.offset,e),this.offset+=2,this}writeUint8(e){return this.view.setUint8(this.offset,e),this.offset+=1,this}writeType(e){for(let t=0;t<4;t++){const s=t<e.length?e.charCodeAt(t):0;this.buffer[this.offset+t]=s}return this.offset+=4,this}writeBytes(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);return this.buffer.set(t,this.offset),this.offset+=t.byteLength,this}skip(e){return this.offset+=e,this}};const vw=()=>{const i=new TextEncoder().encode("mp4 handler"),e=32+i.byteLength+1;return new Pt(e).writeUint32(e).writeType("hdlr").writeUint32(0).skip(4).writeType("mdta").skip(12).writeBytes(i).skip(1).buffer},bw=i=>{const e=new TextEncoder,t=i.map(n=>{const o=e.encode(n),a=8+o.byteLength;return new Pt(a).writeUint32(a).writeType("mdta").writeBytes(o).buffer}),s=16+t.reduce((n,o)=>n+o.byteLength,0),r=new Pt(s).writeUint32(s).writeType("keys").writeUint32(0).writeUint32(i.length);return t.forEach(n=>r.writeBytes(n)),r.buffer},Tw=i=>{const e=new TextEncoder,t=Object.entries(i).map(([n,o],a)=>{const l=a+1,c=e.encode(o),h=16+c.byteLength,u=8+h;return new Pt(u).writeUint32(u).writeUint32(l).writeUint32(h).writeType("data").writeUint32(1).skip(4).writeBytes(c).buffer}),s=8+t.reduce((n,o)=>n+o.byteLength,0),r=new Pt(s).writeUint32(s).writeType("ilst");return t.forEach(n=>r.writeBytes(n)),r.buffer},ww=i=>{const e=vw(),t=bw(Object.keys(i)),s=Tw(i),r=e.length+t.length+s.length;return new Pt(r).writeBytes(e).writeBytes(t).writeBytes(s).buffer};function yp(i){const e=new ArrayBuffer(i.byteLength);i.copyTo(e);const t=i.timestamp;return{duration:i.duration??0,dts:t,cts:t,is_sync:i.type==="key",data:e}}function Sw(i){const e=i.byteLength,t=i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),s=26+e+3;return new Pt(s).writeUint8(3).writeUint8(23+e).writeUint16(1).writeUint8(0).writeUint8(4).writeUint8(15+e).writeUint8(64).writeUint8(21).writeBytes([0,0,0]).writeUint32(0).writeUint32(0).writeUint8(5).writeUint8(e).writeBytes(t).writeUint8(6).writeUint8(1).writeUint8(2).buffer}function Cw(i){const e=new DataView(i instanceof ArrayBuffer?i:i.buffer,i.byteOffset||0),t=e.getUint8(9),s=e.getUint16(10,!0),r=e.getUint32(12,!0),n=e.getInt16(16,!0),o=e.getUint8(18);return new Pt(11).writeUint8(0).writeUint8(t).writeUint16(s).writeUint32(r).writeUint16(n).writeUint8(o).buffer}function Aw(i){const e=(i.codec||"vp09.00.40.08").split("."),t=parseInt(e[1]||"0",10),s=parseInt(e[2]||"40",10),r=parseInt(e[3]||"08",10),n={bt709:1,bt601:5,bt2020:9},o={bt709:1,srgb:13,pq:16,hlg:18},a={bt709:1,bt601:5,bt2020:9},l=n[i.colorSpace?.primaries||"bt709"]||1,c=o[i.colorSpace?.transfer||"bt709"]||1,h=a[i.colorSpace?.matrix||"bt709"]||1,u=i.colorSpace?.fullRange?1:0;return new Pt(12).writeUint32(1<<24).writeUint8(t).writeUint8(s).writeUint8(r<<4|2|u).writeUint8(l).writeUint8(c).writeUint8(h).writeUint16(0).buffer.buffer}function Ew(i){if(i.byteLength<7)return!1;const e=new DataView(i);let t=0;try{t+=6;const s=e.getUint8(5)&31;for(let n=0;n<s;n++){if(t+2>i.byteLength)return!1;const o=e.getUint16(t);t+=2+o}if(t+1>i.byteLength)return!1;const r=e.getUint8(t++);for(let n=0;n<r;n++){if(t+2>i.byteLength)return!1;const o=e.getUint16(t);t+=2+o}return t<=i.byteLength}catch{return!1}}function Iw(i){if(!i||i.byteLength<3)return;const e=new Uint8Array(i);e[2]?.toString(2).slice(-2).includes("1")&&(e[2]=0)}class Pw{constructor(e,t,s){this.opts=e,this.mp4File=t,this.avSyncTool=s,this.encoder=this.initEncoder(),this.avSyncTool.once("VideoReady",()=>{this.videoReady=!0,this.flushCache()})}encoder;trackId=-1;cache=[];videoReady=!1;initEncoder(){const e={codec:this.opts.codec==="aac"?"mp4a.40.2":"opus",sampleRate:this.opts.sampleRate,numberOfChannels:this.opts.channelCount,bitrate:128e3},t=new AudioEncoder({error:s=>{const r=`AudioEncoder error: ${s.message}, config: ${JSON.stringify(e)}`;throw Fe.error(r),Error(r)},output:(s,r)=>this.onOutput(s,r)});return t.configure(e),t}onOutput(e,t){this.trackId===-1&&this.setupTrack(t);const s=yp(e);this.videoReady?this.mp4File.addSample(this.trackId,new Uint8Array(s.data),s):this.cache.push(s)}setupTrack(e){const t=e?.decoderConfig?.description,s=this.opts.codec==="aac",r={timescale:1e6,samplerate:this.opts.sampleRate,channel_count:this.opts.channelCount,hdlr:"soun",type:s?"mp4a":"Opus",name:"Track created with designcombo",description:t==null?void 0:s?this.createESDS(t):this.createDOps(t)};this.trackId=this.mp4File.addTrack(r),this.avSyncTool.emit("AudioReady",void 0),Fe.info("AudioEncoder, audio track ready, trackId:",this.trackId)}createESDS(e){const t=new fw;return t.version=0,t.flags=0,t.data=Sw(e),t}createDOps(e){const t=Cw(e);return{type:"dOps",size:t.byteLength+8,hdr_size:8,start:0,data:t,write:function(s){s.writeUint32(this.size),s.writeString("dOps"),s.writeUint8Array(this.data)},parse:function(){}}}flushCache(){this.cache.forEach(e=>{this.mp4File.addSample(this.trackId,new Uint8Array(e.data),e)}),this.cache=[]}encode(e){this.encoder.encode(e)}async flush(){this.encoder.state==="configured"&&await this.encoder.flush()}close(){this.encoder.state==="configured"&&this.encoder.close()}get encodeQueueSize(){return this.encoder.encodeQueueSize}get state(){return this.encoder.state}}const Rw=()=>{let i,e=16.6;self.onmessage=t=>{t.data.event==="start"&&(self.clearInterval(i),i=self.setInterval(()=>{self.postMessage({})},e)),t.data.event==="stop"&&self.clearInterval(i)}},Mw=()=>{const i=new Blob([`(${Rw.toString()})()`]),e=URL.createObjectURL(i);return new Worker(e)},Ci=new Map;let zh=1,_r=null;globalThis.Worker!=null&&(_r=Mw(),_r.onmessage=()=>{zh+=1;for(const[i,e]of Ci)if(zh%i===0)for(const t of e)t()});const kw=(i,e)=>{const t=Math.round(e/16.6),s=Ci.get(t)??new Set;return s.add(i),Ci.set(t,s),Ci.size===1&&s.size===1&&_r?.postMessage({event:"start"}),()=>{s.delete(i),s.size===0&&Ci.delete(t),Ci.size===0&&(zh=0,_r?.postMessage({event:"stop"}))}};class Fw{constructor(e,t,s){this.opts=e,this.mp4File=t,this.avSyncTool=s,this.frameDeltaTime=Math.floor(1e3/e.expectFPS*1e3),this.encoder0=this.initEncoder("encoder0"),this.encoder1=this.initEncoder("encoder1"),this.avSyncTool.once("AudioReady",()=>{this.audioReady=!0}),this.stopTimer=kw(()=>this.checkCache(),15)}encoder0;encoder1;trackId=-1;samplesCache={encoder0:[],encoder1:[]};currentEncoderId="encoder1";lastAddedSampleTime=0;audioReady=!1;gopId=0;stopTimer;frameDeltaTime;initEncoder(e){const t={codec:this.opts.codec,framerate:this.opts.expectFPS,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__,bitrate:this.opts.bitrate,width:this.opts.width,height:this.opts.height,alpha:"discard",avc:{format:"avc"}},s=new VideoEncoder({error:r=>{throw Fe.error(`VideoEncoder error: ${r.message}`,t),Error(`VideoEncoder error: ${r.message}`)},output:(r,n)=>this.onOutput(e,r,n)});return s.configure(t),s}onOutput(e,t,s){this.trackId===-1&&s!=null&&this.setupTrack(s),this.samplesCache[e].push(yp(t))}setupTrack(e){if(!e.decoderConfig)return;let t=e.decoderConfig.description,s="avc1";if(this.opts.codec.startsWith("avc1")){if(Iw(t),!Ew(t)){Fe.warn("Invalid AVCC descriptor, waiting for next metadata");return}}else this.opts.codec.startsWith("vp09")&&(s="vp09",t=Aw(e.decoderConfig));const r=this.getDecoderConfKey();if(!r||!t||t.byteLength<7){Fe.warn("VideoEncoder metadata missing valid configuration");return}const n={timescale:1e6,width:this.opts.width,height:this.opts.height,brands:["isom","iso2","avc1","mp42","mp41"],type:s,name:"Track created with designcombo"};n[r]=t;try{this.trackId=this.mp4File.addTrack(n),this.avSyncTool.emit("VideoReady",void 0),Fe.info("VideoEncoder, video track ready, trackId:",this.trackId)}catch(o){Fe.warn("mp4File.addTrack warning",o)}}getDecoderConfKey(){return this.opts.codec.startsWith("avc1")?"avcDecoderConfigRecord":this.opts.codec.startsWith("hvc1")?"hevcDecoderConfigRecord":this.opts.codec.startsWith("vp09")?"vpcDecoderConfigRecord":null}checkCache(){if(!this.audioReady||this.trackId===-1)return;const e=this.currentEncoderId==="encoder1"?"encoder0":"encoder1",t=this.samplesCache[this.currentEncoderId],s=this.samplesCache[e];if(t.length===0&&s.length===0)return;const r=t[0];if(r!=null&&(!r.is_sync||r.cts-this.lastAddedSampleTime<this.frameDeltaTime)){const o=this.addSampleToFile(t);o>this.lastAddedSampleTime&&(this.lastAddedSampleTime=o)}const n=s[0];if(n?.is_sync&&n.cts-this.lastAddedSampleTime<this.frameDeltaTime){this.currentEncoderId=e,this.checkCache();return}if(r?.is_sync&&n?.is_sync)if(r.cts<=n.cts){const o=this.addSampleToFile(t);o>this.lastAddedSampleTime&&(this.lastAddedSampleTime=o)}else this.currentEncoderId=e,this.checkCache()}addSampleToFile(e){let t=-1,s=0;for(;s<e.length;s++){const r=e[s];if(s>0&&r.is_sync)break;this.mp4File.addSample(this.trackId,new Uint8Array(r.data),r),t=r.cts+r.duration}return e.splice(0,s),t}encode(e,t){t.keyFrame&&this.gopId++,(this.gopId%2===0?this.encoder0:this.encoder1).encode(e,t)}async flush(){await Promise.all([this.encoder0.state==="configured"?this.encoder0.flush():null,this.encoder1.state==="configured"?this.encoder1.flush():null]),this.stopTimer(),this.checkCache()}close(){this.encoder0.state==="configured"&&this.encoder0.close(),this.encoder1.state==="configured"&&this.encoder1.close()}get encodeQueueSize(){return this.encoder0.encodeQueueSize+this.encoder1.encodeQueueSize}}function Bw(i){Fe.info("recodemux opts:",i);const e=pw(),t=new mw,s=(l,c)=>{const h=l.add("udta").add("meta");h.data=ww(c),h.size=h.data.byteLength};let r=!1;const n=()=>{e.moov==null||r||(r=!0,i.metaDataTags&&s(e.moov,i.metaDataTags),i.duration!=null&&(e.moov.mvhd.duration=i.duration))};t.once("VideoReady",n),t.once("AudioReady",n);const o=i.video?new Fw(i.video,e,t):null,a=i.audio?new Pw(i.audio,e,t):null;return i.video||t.emit("VideoReady",void 0),i.audio||t.emit("AudioReady",void 0),{encodeVideo:(l,c)=>{o?.encode(l,c),l.close()},encodeAudio:l=>{if(a)try{a.encode(l),l.close()}catch(c){throw Fe.error("encode audio chunk error",c),c}},getEncodeQueueSize:()=>o?.encodeQueueSize??a?.encodeQueueSize??0,flush:async()=>{await Promise.all([o?.flush(),a?.flush()])},close:()=>{t.all.clear(),o?.close(),a?.close()},mp4file:e}}var vp=i=>{throw TypeError(i)},bp=(i,e,t)=>e.has(i)||vp("Cannot "+t),J=(i,e,t)=>(bp(i,e,"read from private field"),t?t.call(i):e.get(i)),st=(i,e,t)=>e.has(i)?vp("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Ne=(i,e,t,s)=>(bp(i,e,"write to private field"),e.set(i,t),t);const Tp="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2Z1bmN0aW9uIHUobil7aWYobj09PSIvIilyZXR1cm57cGFyZW50Om51bGwsbmFtZToiIn07Y29uc3QgZT1uLnNwbGl0KCIvIikuZmlsdGVyKGk9PmkubGVuZ3RoPjApO2lmKGUubGVuZ3RoPT09MCl0aHJvdyBFcnJvcigiSW52YWxpZCBwYXRoIik7Y29uc3QgYT1lW2UubGVuZ3RoLTFdLHI9Ii8iK2Uuc2xpY2UoMCwtMSkuam9pbigiLyIpO3JldHVybntuYW1lOmEscGFyZW50OnJ9fWFzeW5jIGZ1bmN0aW9uIHcobixlKXtjb25zdHtwYXJlbnQ6YSxuYW1lOnJ9PXUobik7aWYoYT09bnVsbClyZXR1cm4gYXdhaXQgbmF2aWdhdG9yLnN0b3JhZ2UuZ2V0RGlyZWN0b3J5KCk7Y29uc3QgaT1hLnNwbGl0KCIvIikuZmlsdGVyKHQ9PnQubGVuZ3RoPjApO3RyeXtsZXQgdD1hd2FpdCBuYXZpZ2F0b3Iuc3RvcmFnZS5nZXREaXJlY3RvcnkoKTtmb3IoY29uc3QgcyBvZiBpKXQ9YXdhaXQgdC5nZXREaXJlY3RvcnlIYW5kbGUocyx7Y3JlYXRlOmUuY3JlYXRlfSk7aWYoZS5pc0ZpbGUpcmV0dXJuIGF3YWl0IHQuZ2V0RmlsZUhhbmRsZShyLHtjcmVhdGU6ZS5jcmVhdGV9KX1jYXRjaCh0KXtpZih0Lm5hbWU9PT0iTm90Rm91bmRFcnJvciIpcmV0dXJuIG51bGw7dGhyb3cgdH19Y29uc3QgZj17fTtzZWxmLm9ubWVzc2FnZT1hc3luYyBuPT57dmFyIGk7Y29uc3R7ZXZ0VHlwZTplLGFyZ3M6YX09bi5kYXRhO2xldCByPWZbYS5maWxlSWRdO3RyeXtsZXQgdDtjb25zdCBzPVtdO2lmKGU9PT0icmVnaXN0ZXIiKXtjb25zdCBsPWF3YWl0IHcoYS5maWxlUGF0aCx7Y3JlYXRlOiEwLGlzRmlsZTohMH0pO2lmKGw9PW51bGwpdGhyb3cgRXJyb3IoYG5vdCBmb3VuZCBmaWxlOiAke2EuZmlsZUlkfWApO3I9YXdhaXQgbC5jcmVhdGVTeW5jQWNjZXNzSGFuZGxlKHttb2RlOmEubW9kZX0pLGZbYS5maWxlSWRdPXJ9ZWxzZSBpZihlPT09ImNsb3NlIilhd2FpdCByLmNsb3NlKCksZGVsZXRlIGZbYS5maWxlSWRdO2Vsc2UgaWYoZT09PSJ0cnVuY2F0ZSIpYXdhaXQgci50cnVuY2F0ZShhLm5ld1NpemUpO2Vsc2UgaWYoZT09PSJ3cml0ZSIpe2NvbnN0e2RhdGE6bCxvcHRzOm99PW4uZGF0YS5hcmdzO3Q9YXdhaXQgci53cml0ZShsLG8pfWVsc2UgaWYoZT09PSJyZWFkIil7Y29uc3R7b2Zmc2V0Omwsc2l6ZTpvfT1uLmRhdGEuYXJncyxnPW5ldyBVaW50OEFycmF5KG8pLGQ9YXdhaXQgci5yZWFkKGcse2F0Omx9KSxjPWcuYnVmZmVyO3Q9ZD09PW8/YzooKGk9Yy50cmFuc2Zlcik9PW51bGw/dm9pZCAwOmkuY2FsbChjLGQpKT8/Yy5zbGljZSgwLGQpLHMucHVzaCh0KX1lbHNlIGU9PT0iZ2V0U2l6ZSI/dD1hd2FpdCByLmdldFNpemUoKTplPT09ImZsdXNoIiYmYXdhaXQgci5mbHVzaCgpO3NlbGYucG9zdE1lc3NhZ2Uoe2V2dFR5cGU6ImNhbGxiYWNrIixjYklkOm4uZGF0YS5jYklkLHJldHVyblZhbDp0fSxzKX1jYXRjaCh0KXtjb25zdCBzPXQ7c2VsZi5wb3N0TWVzc2FnZSh7ZXZ0VHlwZToidGhyb3dFcnJvciIsY2JJZDpuLmRhdGEuY2JJZCxlcnJNc2c6cy5uYW1lKyI6ICIrcy5tZXNzYWdlK2AKYCtKU09OLnN0cmluZ2lmeShuLmRhdGEpfSl9fX0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPW9wZnMtd29ya2VyLUY0UldscWNfLmpzLm1hcAo=",Uw=i=>Uint8Array.from(atob(i),e=>e.charCodeAt(0)),wp=typeof self<"u"&&self.Blob&&new Blob([Uw(Tp)],{type:"text/javascript;charset=utf-8"});function Ow(i){let e;try{if(e=wp&&(self.URL||self.webkitURL).createObjectURL(wp),!e)throw"";const t=new Worker(e,{name:i?.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;base64,"+Tp,{name:i?.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}async function Dw(i,e,t){const s=Gw();return await s("register",{fileId:i,filePath:e,mode:t}),{read:async(r,n)=>await s("read",{fileId:i,offset:r,size:n}),write:async(r,n)=>await s("write",{fileId:i,data:r,opts:n},[ArrayBuffer.isView(r)?r.buffer:r]),close:async()=>await s("close",{fileId:i}),truncate:async r=>await s("truncate",{fileId:i,newSize:r}),getSize:async()=>await s("getSize",{fileId:i}),flush:async()=>await s("flush",{fileId:i})}}const xr=[];let Nh=0;function Gw(){if(xr.length<3){const e=i();return xr.push(e),e}else{const e=xr[Nh];return Nh=(Nh+1)%xr.length,e}function i(){const e=new Ow;let t=0,s={};return e.onmessage=({data:r})=>{var n,o;r.evtType==="callback"?(n=s[r.cbId])==null||n.resolve(r.returnVal):r.evtType==="throwError"&&((o=s[r.cbId])==null||o.reject(Error(r.errMsg))),delete s[r.cbId]},async function(r,n,o=[]){t+=1;const a=new Promise((l,c)=>{s[t]={resolve:l,reject:c}});return e.postMessage({cbId:t,evtType:r,args:n},o),a}}}function yr(i){if(i==="/")return{parent:null,name:""};const e=i.split("/").filter(r=>r.length>0);if(e.length===0)throw Error("Invalid path");const t=e[e.length-1],s="/"+e.slice(0,-1).join("/");return{name:t,parent:s}}async function Yt(i,e){const{parent:t,name:s}=yr(i);if(t==null)return await navigator.storage.getDirectory();const r=t.split("/").filter(n=>n.length>0);try{let n=await navigator.storage.getDirectory();for(const o of r)n=await n.getDirectoryHandle(o,{create:e.create});return e.isFile?await n.getFileHandle(s,{create:e.create}):await n.getDirectoryHandle(s,{create:e.create})}catch(n){if(n.name==="NotFoundError")return null;throw n}}async function Lh(i){const{parent:e,name:t}=yr(i);if(e==null){const r=await navigator.storage.getDirectory();for await(const n of r.keys())await r.removeEntry(n,{recursive:!0});return}const s=await Yt(e,{create:!1,isFile:!1});if(s!=null)try{await s.removeEntry(t,{recursive:!0})}catch(r){if(r.name==="NotFoundError")return;throw r}}function Hh(i,e){return`${i}/${e}`.replace("//","/")}function Ai(i){return new Sp(i)}var bt,vr,hs;const zw=class Yx{constructor(e){st(this,bt),st(this,vr),st(this,hs),Ne(this,bt,e);const{parent:t,name:s}=yr(e);Ne(this,vr,s),Ne(this,hs,t)}get kind(){return"dir"}get name(){return J(this,vr)}get path(){return J(this,bt)}get parent(){return J(this,hs)==null?null:Ai(J(this,hs))}async create(){return await Yt(J(this,bt),{create:!0,isFile:!1}),Ai(J(this,bt))}async exists(){return await Yt(J(this,bt),{create:!1,isFile:!1})instanceof FileSystemDirectoryHandle}async remove(e={}){for(const t of await this.children())try{await t.remove(e)}catch(s){console.warn(s)}try{await Lh(J(this,bt))}catch(t){console.warn(t)}}async children(){const e=await Yt(J(this,bt),{create:!1,isFile:!1});if(e==null)return[];const t=[];for await(const s of e.values())t.push((s.kind==="file"?ai:Ai)(Hh(J(this,bt),s.name)));return t}async copyTo(e){if(!await this.exists())throw Error(`dir ${this.path} not exists`);if(e instanceof Yx){const t=await e.exists()?Ai(Hh(e.path,this.name)):e;return await t.create(),await Promise.all((await this.children()).map(s=>s.copyTo(t))),t}else if(e instanceof FileSystemDirectoryHandle)return await Promise.all((await this.children()).map(async t=>{t.kind==="file"?await t.copyTo(await e.getFileHandle(t.name,{create:!0})):await t.copyTo(await e.getDirectoryHandle(t.name,{create:!0}))})),null;throw Error("Illegal target type")}async moveTo(e){const t=await this.copyTo(e);return await this.remove(),t}};bt=new WeakMap,vr=new WeakMap,hs=new WeakMap;let Sp=zw;const Wh=new Map;function ai(i,e="rw"){if(e==="rw"){const t=Wh.get(i)??new Cr(i,e);return Wh.set(i,t),t}return new Cr(i,e)}async function Ei(i,e,t={overwrite:!0}){if(e instanceof Cr){await Ei(i,await e.stream(),t);return}const s=await(i instanceof Cr?i:ai(i,"rw")).createWriter();try{if(t.overwrite&&await s.truncate(0),e instanceof ReadableStream){const r=e.getReader();for(;;){const{done:n,value:o}=await r.read();if(n)break;await s.write(o)}}else await s.write(e)}catch(r){throw r}finally{await s.close()}}let Nw=0;const Lw=()=>++Nw;var rt,us,br,ds,Tr,Rt,wr,Sr,Ii;const Hw=class qx{constructor(e,t){st(this,rt),st(this,us),st(this,br),st(this,ds),st(this,Tr),st(this,Rt,0),st(this,wr,async()=>{}),st(this,Sr,(()=>{let n=null;return()=>(Ne(this,Rt,J(this,Rt)+1),n!=null||(n=new Promise(async(o,a)=>{try{const l=await Dw(J(this,Tr),J(this,rt),J(this,ds));Ne(this,wr,async()=>{n!=null&&(n=null,Ne(this,Rt,0),await l.close().catch(console.error))}),o([l,async()=>{Ne(this,Rt,J(this,Rt)-1),!(J(this,Rt)>0)&&(n=null,await l.close())}])}catch(l){a(l)}})),n)})()),st(this,Ii,!1),Ne(this,Tr,Lw()),Ne(this,rt,e),Ne(this,ds,{r:"read-only",rw:"readwrite","rw-unsafe":"readwrite-unsafe"}[t]);const{parent:s,name:r}=yr(e);if(s==null)throw Error("Invalid path");Ne(this,br,r),Ne(this,us,s)}get kind(){return"file"}get path(){return J(this,rt)}get name(){return J(this,br)}get parent(){return J(this,us)==null?null:Ai(J(this,us))}async createWriter(){if(J(this,ds)==="read-only")throw Error("file is read-only");if(J(this,Ii))throw Error("Other writer have not been closed");Ne(this,Ii,!0);try{const e=new TextEncoder,[t,s]=await J(this,Sr).call(this);let r=await t.getSize(),n=!1;return{write:async(o,a={})=>{if(n)throw Error("Writer is closed");const l=typeof o=="string"?e.encode(o):o,c=a.at??r,h=l.byteLength;return r=c+h,await t.write(l,{at:c})},truncate:async o=>{if(n)throw Error("Writer is closed");await t.truncate(o),r>o&&(r=o)},flush:async()=>{if(n)throw Error("Writer is closed");await t.flush()},close:async()=>{if(n)throw Error("Writer is closed");n=!0,Ne(this,Ii,!1),await s()}}}catch(e){throw Ne(this,Ii,!1),e}}async createReader(){const[e,t]=await J(this,Sr).call(this);let s=!1,r=0;return{read:async(n,o={})=>{if(s)throw Error("Reader is closed");const a=o.at??r,l=await e.read(a,n);return r=a+l.byteLength,l},getSize:async()=>{if(s)throw Error("Reader is closed");return await e.getSize()},close:async()=>{s||(s=!0,await t())}}}async text(){return new TextDecoder().decode(await this.arrayBuffer())}async arrayBuffer(){const e=await Yt(J(this,rt),{create:!1,isFile:!0});return e==null?new ArrayBuffer(0):(await e.getFile()).arrayBuffer()}async stream(){const e=await this.getOriginFile();return e==null?new ReadableStream({pull:t=>{t.close()}}):e.stream()}async getOriginFile(){var e;return(e=await Yt(J(this,rt),{create:!1,isFile:!0}))==null?void 0:e.getFile()}async getSize(){const e=await Yt(J(this,rt),{create:!1,isFile:!0});return e==null?0:(await e.getFile()).size}async exists(){return await Yt(J(this,rt),{create:!1,isFile:!0})instanceof FileSystemFileHandle}async remove(e={}){if(e.force===!0){await J(this,wr).call(this),await Lh(J(this,rt)),Wh.delete(J(this,rt));return}if(J(this,Rt)>0)throw Error("exists unclosed reader/writer");await Lh(J(this,rt))}async copyTo(e){if(e instanceof qx)return e.path===this.path?this:(await Ei(e,this),e);if(e instanceof Sp){if(!await this.exists())throw Error(`file ${this.path} not exists`);return await this.copyTo(ai(Hh(e.path,this.name)))}else if(e instanceof FileSystemFileHandle)return await(await this.stream()).pipeTo(await e.createWritable()),null;throw Error("Illegal target type")}async moveTo(e){const t=await this.copyTo(e);return await this.remove(),t}};rt=new WeakMap,us=new WeakMap,br=new WeakMap,ds=new WeakMap,Tr=new WeakMap,Rt=new WeakMap,wr=new WeakMap,Sr=new WeakMap,Ii=new WeakMap;let Cr=Hw;const Vh="/.opfs-tools-temp-dir";async function Cp(i){try{if(i.kind==="file"){if(!await i.exists())return!0;const e=await i.createWriter();await e.truncate(0),await e.close(),await i.remove()}else await i.remove();return!0}catch(e){return console.warn(e),!1}}function Ww(){setInterval(async()=>{for(const i of await Ai(Vh).children()){const e=/^\d+-(\d+)$/.exec(i.name);(e==null||Date.now()-Number(e[1])>2592e5)&&await Cp(i)}},60*1e3)}const $h=[];let Ap=!1;async function Vw(){if(globalThis.localStorage==null)return;const i="OPFS_TOOLS_EXPIRES_TMP_FILES";Ap||(Ap=!0,globalThis.addEventListener("unload",()=>{$h.length!==0&&localStorage.setItem(i,`${localStorage.getItem(i)??""},${$h.join(",")}`)}));let e=localStorage.getItem(i)??"";for(const t of e.split(","))t.length!==0&&await Cp(ai(`${Vh}/${t}`))&&(e=e.replace(t,""));localStorage.setItem(i,e.replace(/,{2,}/g,","))}(async function(){var i;globalThis.__opfs_tools_tmpfile_init__!==!0&&(globalThis.__opfs_tools_tmpfile_init__=!0,!(globalThis.FileSystemDirectoryHandle==null||globalThis.FileSystemFileHandle==null||((i=globalThis.navigator)==null?void 0:i.storage.getDirectory)==null)&&(Ww(),await Vw()))})();function Xh(){const i=`${Math.random().toString().slice(2)}-${Date.now()}`;return $h.push(i),ai(`${Vh}/${i}`)}const $w={0:"debug",1:"info",2:"warn",3:"error"};function Xw(i){if(i instanceof Error)return String(i);if(typeof i=="object"&&i!==null)try{return JSON.stringify(i,(e,t)=>t instanceof Error?String(t):t)}catch{return String(i)}return String(i)}function Yw(){const i=new Date,e=s=>s.toString().padStart(2,"0"),t=i.getMilliseconds().toString().padStart(3,"0");return`${e(i.getHours())}:${e(i.getMinutes())}:${e(i.getSeconds())}.${t}`}class qw{threshold=1;history=[];debug=(...e)=>this.log(0,console.debug,e);info=(...e)=>this.log(1,console.info,e);warn=(...e)=>this.log(2,console.warn,e);error=(...e)=>this.log(3,console.error,e);log(e,t,s){e>=this.threshold&&(t(...s),this.history.push({level:$w[e],time:Yw(),args:s}))}setThreshold(e){this.threshold=e}getThreshold(){return this.threshold}createTagged(e){return{debug:(...t)=>this.debug(e,...t),info:(...t)=>this.info(e,...t),warn:(...t)=>this.warn(e,...t),error:(...t)=>this.error(e,...t)}}dump(){return this.history.map(({level:e,time:t,args:s})=>`[${e.toUpperCase()}][${t}] ${s.map(Xw).join(" ")}`).join(`
|
|
4
|
-
`)}}const Tt=new qw,
|
|
1
|
+
(function(se,bi){typeof exports=="object"&&typeof module<"u"?bi(exports):typeof define=="function"&&define.amd?define(["exports"],bi):(se=typeof globalThis<"u"?globalThis:se||self,bi(se.core={}))})(this,(function(se){"use strict";var bi=i=>{throw TypeError(i)},yn=(i,e,t)=>e.has(i)||bi("Cannot "+t),_y=(i,e,t)=>(yn(i,e,"read from private field"),t?t.call(i):e.get(i)),ff=(i,e,t)=>e.has(i)?bi("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),yy=(i,e,t,s)=>(yn(i,e,"write to private field"),e.set(i,t),t),pf=(i,e,t)=>(yn(i,e,"access private method"),t),vy=Object.defineProperty,mf=(i,e)=>{for(var t in e)vy(i,t,{get:e[t],enumerable:!0})},vn=Math.pow(2,32),Ae=Math.pow(2,32)-1,by=1,Ty=2,wy=4,js=1,Zs=2,Js=8,Qs=16,er=32,gf=131072,ts=1,tr=4,is=256,ss=512,rs=1024,ns=2048,xf=-1,Wt=0,We=1,_t=class $_ extends ArrayBuffer{constructor(e){super(e),this.fileStart=0,this.usedBytes=0}static fromArrayBuffer(e,t){const s=new $_(e.byteLength);return new Uint8Array(s).set(new Uint8Array(e)),s.fileStart=t,s}},_f=(i=>(i[i.BIG_ENDIAN=1]="BIG_ENDIAN",i[i.LITTLE_ENDIAN=2]="LITTLE_ENDIAN",i))(_f||{}),ir,bn,Z,Pe=(Z=class{constructor(i,e,t){ff(this,ir),this._byteLength=0,this.failurePosition=0,this._dynamicSize=1,this._byteOffset=e||0,i instanceof ArrayBuffer?this.buffer=_t.fromArrayBuffer(i,0):i instanceof DataView?(this.dataView=i,e&&(this._byteOffset+=e)):this.buffer=new _t(i||0),this.position=0,this.endianness=t||1}getPosition(){return this.position}_realloc(i){if(!this._dynamicSize)return;const e=this._byteOffset+this.position+i;let t=this._buffer.byteLength;if(e<=t){e>this._byteLength&&(this._byteLength=e);return}for(t<1&&(t=1);e>t;)t*=2;const s=new _t(t),r=new Uint8Array(this._buffer);new Uint8Array(s,0,r.length).set(r),this.buffer=s,this._byteLength=e}_trimAlloc(){if(this._byteLength===this._buffer.byteLength)return;const i=new _t(this._byteLength),e=new Uint8Array(i),t=new Uint8Array(this._buffer,0,e.length);e.set(t),this.buffer=i}get byteLength(){return this._byteLength-this._byteOffset}get buffer(){return this._trimAlloc(),this._buffer}set buffer(i){this._buffer=i,this._dataView=new DataView(i,this._byteOffset),this._byteLength=i.byteLength}get byteOffset(){return this._byteOffset}set byteOffset(i){this._byteOffset=i,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}get dataView(){return this._dataView}set dataView(i){this._byteOffset=i.byteOffset,this._buffer=_t.fromArrayBuffer(i.buffer,0),this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+i.byteLength}seek(i){const e=Math.max(0,Math.min(this.byteLength,i));this.position=isNaN(e)||!isFinite(e)?0:e}isEof(){return this.position>=this._byteLength}mapUint8Array(i){this._realloc(i*1);const e=new Uint8Array(this._buffer,this.byteOffset+this.position,i);return this.position+=i*1,e}readInt32Array(i,e){i=i===void 0?this.byteLength-this.position/4:i;const t=new Int32Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readInt16Array(i,e){i=i===void 0?this.byteLength-this.position/2:i;const t=new Int16Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readInt8Array(i){i=i===void 0?this.byteLength-this.position:i;const e=new Int8Array(i);return Z.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,i*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e}readUint32Array(i,e){i=i===void 0?this.byteLength-this.position/4:i;const t=new Uint32Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readUint16Array(i,e){i=i===void 0?this.byteLength-this.position/2:i;const t=new Uint16Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readUint8Array(i){i=i===void 0?this.byteLength-this.position:i;const e=new Uint8Array(i);return Z.memcpy(e.buffer,0,this.buffer,this.byteOffset+this.position,i*e.BYTES_PER_ELEMENT),this.position+=e.byteLength,e}readFloat64Array(i,e){i=i===void 0?this.byteLength-this.position/8:i;const t=new Float64Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readFloat32Array(i,e){i=i===void 0?this.byteLength-this.position/4:i;const t=new Float32Array(i);return Z.memcpy(t.buffer,0,this.buffer,this.byteOffset+this.position,i*t.BYTES_PER_ELEMENT),Z.arrayToNative(t,e??this.endianness),this.position+=t.byteLength,t}readInt32(i){const e=this._dataView.getInt32(this.position,(i??this.endianness)===2);return this.position+=4,e}readInt16(i){const e=this._dataView.getInt16(this.position,(i??this.endianness)===2);return this.position+=2,e}readInt8(){const i=this._dataView.getInt8(this.position);return this.position+=1,i}readUint32(i){const e=this._dataView.getUint32(this.position,(i??this.endianness)===2);return this.position+=4,e}readUint16(i){const e=this._dataView.getUint16(this.position,(i??this.endianness)===2);return this.position+=2,e}readUint8(){const i=this._dataView.getUint8(this.position);return this.position+=1,i}readFloat32(i){const e=this._dataView.getFloat32(this.position,(i??this.endianness)===2);return this.position+=4,e}readFloat64(i){const e=this._dataView.getFloat64(this.position,(i??this.endianness)===2);return this.position+=8,e}static memcpy(i,e,t,s,r){const n=new Uint8Array(i,e,r),o=new Uint8Array(t,s,r);n.set(o)}static arrayToNative(i,e){return e===Z.ENDIANNESS?i:this.flipArrayEndianness(i)}static nativeToEndian(i,e){return e&&Z.ENDIANNESS===2?i:this.flipArrayEndianness(i)}static flipArrayEndianness(i){const e=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);for(let t=0;t<i.byteLength;t+=i.BYTES_PER_ELEMENT)for(let s=t+i.BYTES_PER_ELEMENT-1,r=t;s>r;s--,r++){const n=e[r];e[r]=e[s],e[s]=n}return i}readString(i,e){return e===void 0||e==="ASCII"?yf(this.mapUint8Array(i===void 0?this.byteLength-this.position:i)):new TextDecoder(e).decode(this.mapUint8Array(i))}readCString(i){let e=0;const t=this.byteLength-this.position,s=new Uint8Array(this._buffer,this._byteOffset+this.position),r=i!==void 0?Math.min(i,t):t;for(;e<r&&s[e]!==0;e++);const n=yf(this.mapUint8Array(e));return i!==void 0?this.position+=r-e:e!==t&&(this.position+=1),n}readInt64(){return this.readInt32()*vn+this.readUint32()}readUint64(){return this.readUint32()*vn+this.readUint32()}readUint24(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()}save(i){const e=new Blob([this.buffer]);if(typeof window<"u"&&typeof document<"u")if(window.URL&&URL.createObjectURL){const t=window.URL.createObjectURL(e),s=document.createElement("a");document.body.appendChild(s),s.setAttribute("href",t),s.setAttribute("download",i),s.setAttribute("target","_self"),s.click(),window.URL.revokeObjectURL(t),document.body.removeChild(s)}else throw new Error("DataStream.save: Can't create object URL.");return e}get dynamicSize(){return this._dynamicSize}set dynamicSize(i){i||this._trimAlloc(),this._dynamicSize=i}shift(i){const e=new _t(this._byteLength-i),t=new Uint8Array(e),s=new Uint8Array(this._buffer,i,t.length);t.set(s),this.buffer=e,this.position-=i}writeInt32Array(i,e){if(this._realloc(i.length*4),i instanceof Int32Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapInt32Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeInt32(i[t],e)}writeInt16Array(i,e){if(this._realloc(i.length*2),i instanceof Int16Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapInt16Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeInt16(i[t],e)}writeInt8Array(i){if(this._realloc(i.length*1),i instanceof Int8Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapInt8Array(i.length);else for(let e=0;e<i.length;e++)this.writeInt8(i[e])}writeUint32Array(i,e){if(this._realloc(i.length*4),i instanceof Uint32Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapUint32Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeUint32(i[t],e)}writeUint16Array(i,e){if(this._realloc(i.length*2),i instanceof Uint16Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapUint16Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeUint16(i[t],e)}writeUint8Array(i){if(this._realloc(i.length*1),i instanceof Uint8Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapUint8Array(i.length);else for(let e=0;e<i.length;e++)this.writeUint8(i[e])}writeFloat64Array(i,e){if(this._realloc(i.length*8),i instanceof Float64Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapFloat64Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeFloat64(i[t],e)}writeFloat32Array(i,e){if(this._realloc(i.length*4),i instanceof Float32Array&&this.byteOffset+this.position%i.BYTES_PER_ELEMENT===0)Z.memcpy(this._buffer,this.byteOffset+this.position,i.buffer,0,i.byteLength),this.mapFloat32Array(i.length,e);else for(let t=0;t<i.length;t++)this.writeFloat32(i[t],e)}writeInt64(i,e){this._realloc(8),this._dataView.setBigInt64(this.position,BigInt(i),(e??this.endianness)===2),this.position+=8}writeInt32(i,e){this._realloc(4),this._dataView.setInt32(this.position,i,(e??this.endianness)===2),this.position+=4}writeInt16(i,e){this._realloc(2),this._dataView.setInt16(this.position,i,(e??this.endianness)===2),this.position+=2}writeInt8(i){this._realloc(1),this._dataView.setInt8(this.position,i),this.position+=1}writeUint32(i,e){this._realloc(4),this._dataView.setUint32(this.position,i,(e??this.endianness)===2),this.position+=4}writeUint16(i,e){this._realloc(2),this._dataView.setUint16(this.position,i,(e??this.endianness)===2),this.position+=2}writeUint8(i){this._realloc(1),this._dataView.setUint8(this.position,i),this.position+=1}writeFloat32(i,e){this._realloc(4),this._dataView.setFloat32(this.position,i,(e??this.endianness)===2),this.position+=4}writeFloat64(i,e){this._realloc(8),this._dataView.setFloat64(this.position,i,(e??this.endianness)===2),this.position+=8}writeUCS2String(i,e,t){t===void 0&&(t=i.length);let s;for(s=0;s<i.length&&s<t;s++)this.writeUint16(i.charCodeAt(s),e);for(;s<t;s++)this.writeUint16(0)}writeString(i,e,t){let s=0;if(e===void 0||e==="ASCII")if(t!==void 0){const r=Math.min(i.length,t);for(s=0;s<r;s++)this.writeUint8(i.charCodeAt(s));for(;s<t;s++)this.writeUint8(0)}else for(s=0;s<i.length;s++)this.writeUint8(i.charCodeAt(s));else this.writeUint8Array(new TextEncoder(e).encode(i.substring(0,t)))}writeCString(i,e){let t=0;if(e!==void 0){const s=Math.min(i.length,e);for(t=0;t<s;t++)this.writeUint8(i.charCodeAt(t));for(;t<e;t++)this.writeUint8(0)}else{for(t=0;t<i.length;t++)this.writeUint8(i.charCodeAt(t));this.writeUint8(0)}}writeStruct(i,e){for(let t=0;t<i.length;t++){const[s,r]=i[t],n=e[s];this.writeType(r,n,e)}}writeType(i,e,t){if(typeof i=="function")return i(this,e);if(typeof i=="object"&&!(i instanceof Array))return i.set(this,e,t);let s,r="ASCII";const n=this.position;let o=i;if(typeof i=="string"&&/:/.test(i)){const a=i.split(":");o=a[0],s=parseInt(a[1])}if(typeof o=="string"&&/,/.test(o)){const a=o.split(",");o=a[0],r=a[1]}switch(o){case"uint8":this.writeUint8(e);break;case"int8":this.writeInt8(e);break;case"uint16":this.writeUint16(e,this.endianness);break;case"int16":this.writeInt16(e,this.endianness);break;case"uint32":this.writeUint32(e,this.endianness);break;case"int32":this.writeInt32(e,this.endianness);break;case"float32":this.writeFloat32(e,this.endianness);break;case"float64":this.writeFloat64(e,this.endianness);break;case"uint16be":this.writeUint16(e,1);break;case"int16be":this.writeInt16(e,1);break;case"uint32be":this.writeUint32(e,1);break;case"int32be":this.writeInt32(e,1);break;case"float32be":this.writeFloat32(e,1);break;case"float64be":this.writeFloat64(e,1);break;case"uint16le":this.writeUint16(e,2);break;case"int16le":this.writeInt16(e,2);break;case"uint32le":this.writeUint32(e,2);break;case"int32le":this.writeInt32(e,2);break;case"float32le":this.writeFloat32(e,2);break;case"float64le":this.writeFloat64(e,2);break;case"cstring":this.writeCString(e,s);break;case"string":this.writeString(e,r,s);break;case"u16string":this.writeUCS2String(e,this.endianness,s);break;case"u16stringle":this.writeUCS2String(e,2,s);break;case"u16stringbe":this.writeUCS2String(e,1,s);break;default:if(pf(this,ir,bn).call(this,o)){const[,a]=o;for(let l=0;l<e.length;l++)this.writeType(a,e[l]);break}else{this.writeStruct(o,e);break}}s&&(this.position=n,this._realloc(s),this.position=n+s)}writeUint64(i){const e=Math.floor(i/vn);this.writeUint32(e),this.writeUint32(i&4294967295)}writeUint24(i){this.writeUint8((i&16711680)>>16),this.writeUint8((i&65280)>>8),this.writeUint8(i&255)}adjustUint32(i,e){const t=this.position;this.seek(i),this.writeUint32(e),this.seek(t)}readStruct(i){const e={},t=this.position;for(let s=0;s<i.length;s+=1){const r=i[s][1],n=this.readType(r,e);if(!n){this.failurePosition===0&&(this.failurePosition=this.position),this.position=t;return}e[i[s][0]]=n}return e}readUCS2String(i,e){return String.fromCharCode.apply(void 0,this.readUint16Array(i,e))}readType(i,e){if(typeof i=="function")return i(this,e);if(typeof i=="object"&&!(i instanceof Array))return i.get(this,e);if(i instanceof Array&&i.length!==3)return this.readStruct(i);let t,s,r="ASCII";const n=this.position;let o=i;if(typeof o=="string"&&/:/.test(o)){const a=o.split(":");o=a[0],s=parseInt(a[1])}if(typeof o=="string"&&/,/.test(o)){const a=o.split(",");o=a[0],r=a[1]}switch(o){case"uint8":t=this.readUint8();break;case"int8":t=this.readInt8();break;case"uint16":t=this.readUint16(this.endianness);break;case"int16":t=this.readInt16(this.endianness);break;case"uint32":t=this.readUint32(this.endianness);break;case"int32":t=this.readInt32(this.endianness);break;case"float32":t=this.readFloat32(this.endianness);break;case"float64":t=this.readFloat64(this.endianness);break;case"uint16be":t=this.readUint16(1);break;case"int16be":t=this.readInt16(1);break;case"uint32be":t=this.readUint32(1);break;case"int32be":t=this.readInt32(1);break;case"float32be":t=this.readFloat32(1);break;case"float64be":t=this.readFloat64(1);break;case"uint16le":t=this.readUint16(2);break;case"int16le":t=this.readInt16(2);break;case"uint32le":t=this.readUint32(2);break;case"int32le":t=this.readInt32(2);break;case"float32le":t=this.readFloat32(2);break;case"float64le":t=this.readFloat64(2);break;case"cstring":t=this.readCString(s);break;case"string":t=this.readString(s,r);break;case"u16string":t=this.readUCS2String(s,this.endianness);break;case"u16stringle":t=this.readUCS2String(s,2);break;case"u16stringbe":t=this.readUCS2String(s,1);break;default:if(pf(this,ir,bn).call(this,o)){const[,a,l]=o,c=typeof l=="function"?l(e,this,o):typeof l=="string"&&e[l]!==void 0?parseInt(e[l]):typeof l=="number"?l:l==="*"?void 0:parseInt(l);if(typeof a=="string"){const h=a.replace(/(le|be)$/,"");let u;switch(/le$/.test(a)?u=2:/be$/.test(a)&&(u=1),h){case"uint8":t=this.readUint8Array(c);break;case"uint16":t=this.readUint16Array(c,u);break;case"uint32":t=this.readUint32Array(c,u);break;case"int8":t=this.readInt8Array(c);break;case"int16":t=this.readInt16Array(c,u);break;case"int32":t=this.readInt32Array(c,u);break;case"float32":t=this.readFloat32Array(c,u);break;case"float64":t=this.readFloat64Array(c,u);break;case"cstring":case"utf16string":case"string":if(c){t=new Array(c);for(let d=0;d<c;d++)t[d]=this.readType(a,e)}else for(t=[];!this.isEof();){const d=this.readType(a,e);if(!d)break;t.push(d)}break}}else if(c){t=new Array(c);for(let h=0;h<c;h++){const u=this.readType(a,e);if(!u)return;t[h]=u}}else for(t=[];;){const h=this.position;try{const u=this.readType(a,e);if(!u){this.position=h;break}t.push(u)}catch{this.position=h;break}}break}}return s&&(this.position=n+s),t}mapInt32Array(i,e){this._realloc(i*4);const t=new Int32Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*4,t}mapInt16Array(i,e){this._realloc(i*2);const t=new Int16Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*2,t}mapInt8Array(i,e){this._realloc(i*1);const t=new Int8Array(this._buffer,this.byteOffset+this.position,i);return this.position+=i*1,t}mapUint32Array(i,e){this._realloc(i*4);const t=new Uint32Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*4,t}mapUint16Array(i,e){this._realloc(i*2);const t=new Uint16Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*2,t}mapFloat64Array(i,e){this._realloc(i*8);const t=new Float64Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*8,t}mapFloat32Array(i,e){this._realloc(i*4);const t=new Float32Array(this._buffer,this.byteOffset+this.position,i);return Z.arrayToNative(t,e??this.endianness),this.position+=i*4,t}},ir=new WeakSet,bn=function(i){return Array.isArray(i)&&i.length===3&&i[0]==="[]"},Z.ENDIANNESS=new Int8Array(new Int16Array([1]).buffer)[0]>0?2:1,Z);function yf(i){const e=[];for(let t=0;t<i.length;t++)e[t]=i[t];return String.fromCharCode.apply(void 0,e)}var sr=new Date,Tn=4,vf=3,bf=2,Tf=1,Vt=Tn,I={setLogLevel(i){i===this.debug?Vt=Tf:i===this.info?Vt=bf:i===this.warn?Vt=vf:(this.error,Vt=Tn)},debug(i,e){console.debug===void 0&&(console.debug=console.log),Tf>=Vt&&console.debug("["+I.getDurationString(new Date().getTime()-sr.getTime(),1e3)+"]","["+i+"]",e)},log(i,e){this.debug(i.msg)},info(i,e){bf>=Vt&&console.info("["+I.getDurationString(new Date().getTime()-sr.getTime(),1e3)+"]","["+i+"]",e)},warn(i,e){vf>=Vt&&console.warn("["+I.getDurationString(new Date().getTime()-sr.getTime(),1e3)+"]","["+i+"]",e)},error(i,e,t){t?.onError?t.onError(i,e):Tn>=Vt&&console.error("["+I.getDurationString(new Date().getTime()-sr.getTime(),1e3)+"]","["+i+"]",e)},getDurationString(i,e){let t;function s(l,c){const h=(""+l).split(".");for(;h[0].length<c;)h[0]="0"+h[0];return h.join(".")}i<0?(t=!0,i=-i):t=!1;let r=i/(e||1);const n=Math.floor(r/3600);r-=n*3600;const o=Math.floor(r/60);r-=o*60;let a=r*1e3;return r=Math.floor(r),a-=r*1e3,a=Math.floor(a),(t?"-":"")+n+":"+s(o,2)+":"+s(r,2)+"."+s(a,3)},printRanges(i){const e=i.length;if(e>0){let t="";for(let s=0;s<e;s++)s>0&&(t+=","),t+="["+I.getDurationString(i.start(s))+","+I.getDurationString(i.end(s))+"]";return t}else return"(empty)"}};function Sy(i,e){I.debug("ArrayBuffer","Trying to create a new buffer of size: "+(i.byteLength+e.byteLength));const t=new Uint8Array(i.byteLength+e.byteLength);return t.set(new Uint8Array(i),0),t.set(new Uint8Array(e),i.byteLength),t.buffer}var Ti=class extends Pe{constructor(i){super(new ArrayBuffer,0),this.buffers=[],this.bufferIndex=-1,i&&(this.insertBuffer(i),this.bufferIndex=0)}initialized(){if(this.bufferIndex>-1)return!0;if(this.buffers.length>0){const i=this.buffers[0];return i.fileStart===0?(this.buffer=i,this.bufferIndex=0,I.debug("MultiBufferStream","Stream ready for parsing"),!0):(I.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)}else return I.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1}reduceBuffer(i,e,t){const s=new Uint8Array(t);return s.set(new Uint8Array(i,e,t)),s.buffer.fileStart=i.fileStart+e,s.buffer.usedBytes=0,s.buffer}insertBuffer(i){let e=!0,t=0;for(;t<this.buffers.length;t++){const s=this.buffers[t];if(i.fileStart<=s.fileStart){if(i.fileStart===s.fileStart)if(i.byteLength>s.byteLength){this.buffers.splice(t,1),t--;continue}else I.warn("MultiBufferStream","Buffer (fileStart: "+i.fileStart+" - Length: "+i.byteLength+") already appended, ignoring");else i.fileStart+i.byteLength<=s.fileStart||(i=this.reduceBuffer(i,0,s.fileStart-i.fileStart)),I.debug("MultiBufferStream","Appending new buffer (fileStart: "+i.fileStart+" - Length: "+i.byteLength+")"),this.buffers.splice(t,0,i),t===0&&(this.buffer=i);e=!1;break}else if(i.fileStart<s.fileStart+s.byteLength){const r=s.fileStart+s.byteLength-i.fileStart,n=i.byteLength-r;if(n>0)i=this.reduceBuffer(i,r,n);else{e=!1;break}}}e&&(I.debug("MultiBufferStream","Appending new buffer (fileStart: "+i.fileStart+" - Length: "+i.byteLength+")"),this.buffers.push(i),t===0&&(this.buffer=i))}logBufferLevel(i){const e=[];let t="",s,r=0,n=0;for(let a=0;a<this.buffers.length;a++){const l=this.buffers[a];a===0?(s={start:l.fileStart,end:l.fileStart+l.byteLength},e.push(s),t+="["+s.start+"-"):s.end===l.fileStart?s.end=l.fileStart+l.byteLength:(s={start:l.fileStart,end:l.fileStart+l.byteLength},t+=e[e.length-1].end-1+"], ["+s.start+"-",e.push(s)),r+=l.usedBytes,n+=l.byteLength}e.length>0&&(t+=s.end-1+"]");const o=i?I.info:I.debug;this.buffers.length===0?o("MultiBufferStream","No more buffer in memory"):o("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+r+"/"+n+" bytes), continuous ranges: "+t)}cleanBuffers(){for(let i=0;i<this.buffers.length;i++){const e=this.buffers[i];e.usedBytes===e.byteLength&&(I.debug("MultiBufferStream","Removing buffer #"+i),this.buffers.splice(i,1),i--)}}mergeNextBuffer(){if(this.bufferIndex+1<this.buffers.length){const i=this.buffers[this.bufferIndex+1];if(i.fileStart===this.buffer.fileStart+this.buffer.byteLength){const e=this.buffer.byteLength,t=this.buffer.usedBytes,s=this.buffer.fileStart;return this.buffers[this.bufferIndex]=Sy(this.buffer,i),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=t,this.buffer.fileStart=s,I.debug("ISOFile","Concatenating buffer for box parsing (length: "+e+"->"+this.buffer.byteLength+")"),!0}else return!1}else return!1}findPosition(i,e,t){let s=-1,r=i===!0?0:this.bufferIndex;for(;r<this.buffers.length;){const o=this.buffers[r];if(o&&o.fileStart<=e)s=r,t&&(o.fileStart+o.byteLength<=e?o.usedBytes=o.byteLength:o.usedBytes=e-o.fileStart,this.logBufferLevel());else break;r++}if(s===-1)return-1;const n=this.buffers[s];return n.fileStart+n.byteLength>=e?(I.debug("MultiBufferStream","Found position in existing buffer #"+s),s):-1}findEndContiguousBuf(i){const e=i!==void 0?i:this.bufferIndex;let t=this.buffers[e];if(this.buffers.length>e+1)for(let s=e+1;s<this.buffers.length;s++){const r=this.buffers[s];if(r.fileStart===t.fileStart+t.byteLength)t=r;else break}return t.fileStart+t.byteLength}getEndFilePositionAfter(i){const e=this.findPosition(!0,i,!1);return e!==-1?this.findEndContiguousBuf(e):i}addUsedBytes(i){this.buffer.usedBytes+=i,this.logBufferLevel()}setAllUsedBytes(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()}seek(i,e,t){const s=this.findPosition(e,i,t);return s!==-1?(this.buffer=this.buffers[s],this.bufferIndex=s,this.position=i-this.buffer.fileStart,I.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(I.debug("MultiBufferStream","Position "+i+" not found in buffered data"),!1)}getPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.position}getLength(){return this.byteLength}getEndPosition(){return this.bufferIndex===-1||this.buffers[this.bufferIndex]===void 0?0:this.buffers[this.bufferIndex].fileStart+this.byteLength}getAbsoluteEndPosition(){if(this.buffers.length===0)return 0;const i=this.buffers[this.buffers.length-1];return i.fileStart+i.byteLength}},rr,wn,B=(wn=class{constructor(i=0){ff(this,rr),this.size=i}get type(){return this.constructor.fourcc??_y(this,rr)}set type(i){yy(this,rr,i)}addBox(i){return this.boxes||(this.boxes=[]),this.boxes.push(i),this[i.type+"s"]?this[i.type+"s"].push(i):this[i.type]=i,i}set(i,e){return this[i]=e,this}addEntry(i,e){const t=e||"entries";return this[t]||(this[t]=[]),this[t].push(i),this}writeHeader(i,e){if(this.size+=8,(this.size>Ae||this.original_size===1)&&(this.size+=8),this.type==="uuid"&&(this.size+=16),I.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+i.getPosition()+(e||"")),this.original_size===0?i.writeUint32(0):this.size>Ae||this.original_size===1?i.writeUint32(1):(this.sizePosition=i.getPosition(),i.writeUint32(this.size)),i.writeString(this.type,void 0,4),this.type==="uuid"){const t=new Uint8Array(16);for(let s=0;s<16;s++)t[s]=parseInt(this.uuid.substring(s*2,s*2+2),16);i.writeUint8Array(t)}(this.size>Ae||this.original_size===1)&&(this.sizePosition=i.getPosition(),i.writeUint64(this.size))}write(i){if(this.type==="mdat"){const e=this;if(e.stream){this.size=e.stream.getAbsoluteEndPosition(),this.writeHeader(i);for(const t of e.stream.buffers){const s=new Uint8Array(t);i.writeUint8Array(s)}}else e.data&&(this.size=e.data.length,this.writeHeader(i),i.writeUint8Array(e.data))}else this.size=this.data?this.data.length:0,this.writeHeader(i),this.data&&i.writeUint8Array(this.data)}printHeader(i){this.size+=8,this.size>Ae&&(this.size+=8),this.type==="uuid"&&(this.size+=16),i.log(i.indent+"size:"+this.size),i.log(i.indent+"type:"+this.type)}print(i){this.printHeader(i)}parse(i){this.type!=="mdat"?this.data=i.readUint8Array(this.size-this.hdr_size):this.size===0?i.seek(i.getEndPosition()):i.seek(this.start+this.size)}parseDataAndRewind(i){this.data=i.readUint8Array(this.size-this.hdr_size),i.seek(this.start+this.hdr_size)}parseLanguage(i){this.language=i.readUint16();const e=[];e[0]=this.language>>10&31,e[1]=this.language>>5&31,e[2]=this.language&31,this.languageString=String.fromCharCode(e[0]+96,e[1]+96,e[2]+96)}computeSize(i){const e=i||new Ti;this.write(e)}isEndOfBox(i){const e=i.getPosition(),t=this.start+this.size;return e===t}},rr=new WeakMap,wn.registryId=Symbol.for("BoxIdentifier"),wn),R=class extends B{constructor(){super(...arguments),this.flags=0,this.version=0}writeHeader(e){this.size+=4,super.writeHeader(e," v="+this.version+" f="+this.flags),e.writeUint8(this.version),e.writeUint24(this.flags)}printHeader(e){this.size+=4,super.printHeader(e),e.log(e.indent+"version:"+this.version),e.log(e.indent+"flags:"+this.flags)}parseDataAndRewind(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,e.seek(this.start+this.hdr_size)}parseFullHeader(e){this.version=e.readUint8(),this.flags=e.readUint24(),this.hdr_size+=4}parse(e){this.parseFullHeader(e),this.data=e.readUint8Array(this.size-this.hdr_size)}},Sn,ye=(Sn=class{constructor(i){this.grouping_type=i}write(i){i.writeUint8Array(this.data)}parse(i){I.warn("BoxParser",`Unknown sample group type: '${this.grouping_type}'`),this.data=i.readUint8Array(this.description_length)}},Sn.registryId=Symbol.for("SampleGroupEntryIdentifier"),Sn),wf=class extends R{parse(i){this.parseFullHeader(i),this.track_group_id=i.readUint32()}},Sf=class extends B{constructor(i,e,t,s,r){super(e),this.box_name=t,this.hdr_size=s,this.start=r,this.type=i}parse(i){this.from_item_ID=i.readUint16();const e=i.readUint16();this.references=[];for(let t=0;t<e;t++)this.references[t]={to_item_ID:i.readUint16()}}},Cf=class extends B{constructor(i,e,t,s,r){super(e),this.box_name=t,this.hdr_size=s,this.start=r,this.type=i}parse(i){this.from_item_ID=i.readUint32();const e=i.readUint16();this.references=[];for(let t=0;t<e;t++)this.references[t]={to_item_ID:i.readUint32()}}},Af=class extends B{constructor(i,e,t,s){super(e),this.hdr_size=t,this.start=s,this.type=i}parse(i){this.track_ids=i.readUint32Array((this.size-this.hdr_size)/4)}write(i){this.size=this.track_ids.length*4,this.writeHeader(i),i.writeUint32Array(this.track_ids)}},nr=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],Ef=["compatible_brands","matrix","opcolor","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"];function If(i,e){if(i&&!e)return!1;let t;for(t in i)if(!nr.find(s=>s===t)){if(i[t]instanceof B||e[t]instanceof B||typeof i[t]>"u"||typeof e[t]>"u"||typeof i[t]=="function"||typeof e[t]=="function"||"subBoxNames"in i&&i.subBoxNames.indexOf(t.slice(0,4))>-1||"subBoxNames"in e&&e.subBoxNames.indexOf(t.slice(0,4))>-1||t==="data"||t==="start"||t==="size"||t==="creation_time"||t==="modification_time"||Ef.find(s=>s===t))continue;if(i[t]!==e[t])return!1}return!0}function Cn(i,e){if(!If(i,e))return!1;for(let t=0;t<nr.length;t++){const s=nr[t];if(i[s]&&e[s]&&!Cn(i[s],e[s]))return!1}return!0}function An(i){let e=i;for(;e;){if("registryId"in e)return e.registryId;e=Object.getPrototypeOf(e)}}var Cy=i=>{const e=Symbol.for("SampleGroupEntryIdentifier");return An(i)===e},Ay=i=>{const e=Symbol.for("SampleEntryIdentifier");return An(i)===e},Ey=i=>{const e=Symbol.for("BoxIdentifier");return An(i)===e},Ve={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};function Iy(i){const e={uuid:{},sampleEntry:{},sampleGroupEntry:{},box:{}};for(const[t,s]of Object.entries(i)){if(Cy(s)){const r="grouping_type"in s?s.grouping_type:void 0;if(!r)throw new Error(`SampleGroupEntry class ${t} does not have a valid static grouping_type. Please ensure it is defined correctly.`);if(r in e.sampleGroupEntry)throw new Error(`SampleGroupEntry class ${t} has a grouping_type that is already registered. Please ensure it is unique.`);e.sampleGroupEntry[r]=s;continue}if(Ay(s)){const r="fourcc"in s?s.fourcc:void 0;if(!r)throw new Error(`SampleEntry class ${t} does not have a valid static fourcc. Please ensure it is defined correctly.`);if(r in e.sampleEntry)throw new Error(`SampleEntry class ${t} has a fourcc that is already registered. Please ensure it is unique.`);e.sampleEntry[r]=s;continue}if(Ey(s)){const r="fourcc"in s?s.fourcc:void 0,n="uuid"in s?s.uuid:void 0;if(r==="uuid"){if(!n)throw new Error(`Box class ${t} has a fourcc of 'uuid' but does not have a valid uuid. Please ensure it is defined correctly.`);if(n in e.uuid)throw new Error(`Box class ${t} has a uuid that is already registered. Please ensure it is unique.`);e.uuid[n]=s;continue}e.box[r]=s;continue}throw new Error(`Box class ${t} does not have a valid static fourcc, uuid, or grouping_type. Please ensure it is defined correctly.`)}return Ve.uuid={...e.uuid},Ve.sampleEntry={...e.sampleEntry},Ve.sampleGroupEntry={...e.sampleGroupEntry},Ve.box={...e.box},Ve}var or={};function Py(i){return Object.entries(i).forEach(([e,t])=>or[e]=t),or}function Ry(i){return ri(i)}function ri(i){let e="";for(let t=0;t<16;t++){const s=i.readUint8().toString(16);e+=s.length===1?"0"+s:s}return e}function ht(i,e,t){let s,r;const n=i.getPosition();let o=0,a;if(i.getEndPosition()-n<8)return I.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:Wt};if(t&&t<8)return I.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:Wt};let l=i.readUint32();const c=i.readString(4);if(c.length!==4||!/^[\x20-\x7E]{4}$/.test(c))return I.error("BoxParser",`Invalid box type: '${c}'`),{code:xf,start:n,type:c};let h=c;if(I.debug("BoxParser","Found box of type '"+c+"' and size "+l+" at position "+n),o=8,c==="uuid"){if(i.getEndPosition()-i.getPosition()<16||t-o<16)return i.seek(n),I.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:Wt};a=Ry(i),o+=16,h=a}if(l===1){if(i.getEndPosition()-i.getPosition()<8||t&&t-o<8)return i.seek(n),I.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+c+'" box'),{code:Wt};r=l,l=i.readUint64(),o+=8}else if(l===0){if(t)l=t;else if(c!=="mdat")return I.error("BoxParser","Unlimited box size not supported for type: '"+c+"'"),s=new B(l),s.type=c,{code:We,box:s,size:s.size}}if(l!==0&&l<o)return I.error("BoxParser","Box of type "+c+" has an invalid size "+l+" (too small to be a box)"),{code:Wt,type:c,size:l,hdr_size:o,start:n};if(l!==0&&t&&l>t)return I.error("BoxParser","Box of type '"+c+"' has a size "+l+" greater than its container size "+t),{code:Wt,type:c,size:l,hdr_size:o,start:n};if(l!==0&&n+l>i.getEndPosition())return i.seek(n),I.info("BoxParser","Not enough data in stream to parse the entire '"+c+"' box"),{code:Wt,type:c,size:l,hdr_size:o,start:n,original_size:r};if(e)return{code:We,type:c,size:l,hdr_size:o,start:n};c in Ve.box?s=new Ve.box[c](l):c!=="uuid"?(I.warn("BoxParser",`Unknown box type: '${c}'`),s=new B(l),s.type=c,s.has_unparsed_data=!0):a in Ve.uuid?s=new Ve.uuid[a](l):(I.warn("BoxParser",`Unknown UUID box type: '${a}'`),s=new B(l),s.type=c,s.uuid=a,s.has_unparsed_data=!0),s.original_size=r,s.hdr_size=o,s.start=n,s.write===B.prototype.write&&s.type!=="mdat"&&(I.info("BoxParser","'"+h+"' box writing not yet implemented, keeping unparsed data in memory for later write"),s.parseDataAndRewind(i)),s.parse(i);const u=i.getPosition()-(s.start+s.size);return u<0?(I.warn("BoxParser","Parsing of box '"+h+"' did not read the entire indicated box data size (missing "+-u+" bytes), seeking forward"),i.seek(s.start+s.size)):u>0&&s.size!==0&&(I.error("BoxParser","Parsing of box '"+h+"' read "+u+" more bytes than the indicated box data size, seeking backwards"),i.seek(s.start+s.size)),{code:We,box:s,size:s.size}}var ee=class extends B{write(e){if(this.size=0,this.writeHeader(e),this.boxes)for(let t=0;t<this.boxes.length;t++)this.boxes[t]&&(this.boxes[t].write(e),this.size+=this.boxes[t].size);I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),e.adjustUint32(this.sizePosition,this.size)}print(e){this.printHeader(e);for(let t=0;t<this.boxes.length;t++)if(this.boxes[t]){const s=e.indent;e.indent+=" ",this.boxes[t].print(e),e.indent=s}}parse(e){let t;for(;e.getPosition()<this.start+this.size;)if(t=ht(e,!1,this.size-(e.getPosition()-this.start)),t.code===We){const s=t.box;if(this.boxes||(this.boxes=[]),this.boxes.push(s),this.subBoxNames&&this.subBoxNames.indexOf(s.type)!==-1){const r=this.subBoxNames[this.subBoxNames.indexOf(s.type)]+"s";this[r]||(this[r]=[]),this[r].push(s)}else{const r=s.type!=="uuid"?s.type:s.uuid;this[r]?I.warn("ContainerBox",`Box of type ${r} already exists in container box ${this.type}.`):this[r]=s}}else return}},En,yt=(En=class extends ee{constructor(i,e,t){super(i),this.hdr_size=e,this.start=t}isVideo(){return!1}isAudio(){return!1}isSubtitle(){return!1}isMetadata(){return!1}isHint(){return!1}getCodec(){return this.type.replace(".","")}getWidth(){return""}getHeight(){return""}getChannelCount(){return""}getSampleRate(){return""}getSampleSize(){return""}parseHeader(i){i.readUint8Array(6),this.data_reference_index=i.readUint16(),this.hdr_size+=8}parse(i){this.parseHeader(i),this.data=i.readUint8Array(this.size-this.hdr_size)}parseDataAndRewind(i){this.parseHeader(i),this.data=i.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,i.seek(this.start+this.hdr_size)}parseFooter(i){super.parse(i)}writeHeader(i){this.size=8,super.writeHeader(i),i.writeUint8(0),i.writeUint8(0),i.writeUint8(0),i.writeUint8(0),i.writeUint8(0),i.writeUint8(0),i.writeUint16(this.data_reference_index)}writeFooter(i){if(this.boxes)for(let e=0;e<this.boxes.length;e++)this.boxes[e].write(i),this.size+=this.boxes[e].size;I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),i.adjustUint32(this.sizePosition,this.size)}write(i){this.writeHeader(i),i.writeUint8Array(this.data),this.size+=this.data.length,I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),i.adjustUint32(this.sizePosition,this.size)}},En.registryId=Symbol.for("SampleEntryIdentifier"),En),In=class extends yt{},ni=class extends yt{isMetadata(){return!0}},$t=class extends yt{isSubtitle(){return!0}},Pf=class extends yt{},fe=class extends yt{parse(e){this.parseHeader(e),e.readUint16(),e.readUint16(),e.readUint32Array(3),this.width=e.readUint16(),this.height=e.readUint16(),this.horizresolution=e.readUint32(),this.vertresolution=e.readUint32(),e.readUint32(),this.frame_count=e.readUint16();const t=Math.min(31,e.readUint8());this.compressorname=e.readString(t),t<31&&e.readString(31-t),this.depth=e.readUint16(),e.readUint16(),this.parseFooter(e)}isVideo(){return!0}getWidth(){return this.width}getHeight(){return this.height}write(e){this.writeHeader(e),this.size+=70,e.writeUint16(0),e.writeUint16(0),e.writeUint32(0),e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.width),e.writeUint16(this.height),e.writeUint32(this.horizresolution),e.writeUint32(this.vertresolution),e.writeUint32(0),e.writeUint16(this.frame_count),e.writeUint8(Math.min(31,this.compressorname.length)),e.writeString(this.compressorname,void 0,31),e.writeUint16(this.depth),e.writeInt16(-1),this.writeFooter(e)}},ze=class extends yt{parse(e){this.parseHeader(e),this.version=e.readUint16(),e.readUint16(),e.readUint32(),this.channel_count=e.readUint16(),this.samplesize=e.readUint16(),e.readUint16(),e.readUint16(),this.samplerate=e.readUint32()/65536,e.isofile?.ftyp?.major_brand.includes("qt")&&(this.version===1?this.extensions=e.readUint8Array(16):this.version===2&&(this.extensions=e.readUint8Array(36))),this.parseFooter(e)}isAudio(){return!0}getChannelCount(){return this.channel_count}getSampleRate(){return this.samplerate}getSampleSize(){return this.samplesize}write(e){this.writeHeader(e),this.size+=20,e.writeUint32(0),e.writeUint32(0),e.writeUint16(this.channel_count),e.writeUint16(this.samplesize),e.writeUint16(0),e.writeUint16(0),e.writeUint32(this.samplerate<<16),this.writeFooter(e)}},ar=class extends yt{parse(i){this.parseHeader(i),this.parseFooter(i)}write(i){this.writeHeader(i),this.writeFooter(i)}},Rf=class extends Array{toString(){let i="<table class='inner-table'>";i+="<thead><tr><th>length</th><th>nalu_data</th></tr></thead>",i+="<tbody>";for(let e=0;e<this.length;e++){const t=this[e];i+="<tr>",i+="<td>"+t.length+"</td>",i+="<td>",i+=t.data.reduce(function(s,r){return s+r.toString(16).padStart(2,"0")},"0x"),i+="</td></tr>"}return i+="</tbody></table>",i}},Pn,Mf=(Pn=class extends B{constructor(){super(...arguments),this.box_name="AVCConfigurationBox"}parse(i){this.configurationVersion=i.readUint8(),this.AVCProfileIndication=i.readUint8(),this.profile_compatibility=i.readUint8(),this.AVCLevelIndication=i.readUint8(),this.lengthSizeMinusOne=i.readUint8()&3,this.nb_SPS_nalus=i.readUint8()&31;let e=this.size-this.hdr_size-6;this.SPS=new Rf;for(let t=0;t<this.nb_SPS_nalus;t++){const s=i.readUint16();this.SPS.push({length:s,data:i.readUint8Array(s)}),e-=2+s}this.nb_PPS_nalus=i.readUint8(),e--,this.PPS=new Rf;for(let t=0;t<this.nb_PPS_nalus;t++){const s=i.readUint16();this.PPS.push({length:s,data:i.readUint8Array(s)}),e-=2+s}e>0&&(this.ext=i.readUint8Array(e))}write(i){this.size=7;for(let e=0;e<this.SPS.length;e++)this.size+=2+this.SPS[e].length;for(let e=0;e<this.PPS.length;e++)this.size+=2+this.PPS[e].length;this.ext&&(this.size+=this.ext.length),this.writeHeader(i),i.writeUint8(this.configurationVersion),i.writeUint8(this.AVCProfileIndication),i.writeUint8(this.profile_compatibility),i.writeUint8(this.AVCLevelIndication),i.writeUint8(this.lengthSizeMinusOne+252),i.writeUint8(this.SPS.length+224);for(let e=0;e<this.SPS.length;e++)i.writeUint16(this.SPS[e].length),i.writeUint8Array(this.SPS[e].data);i.writeUint8(this.PPS.length);for(let e=0;e<this.PPS.length;e++)i.writeUint16(this.PPS[e].length),i.writeUint8Array(this.PPS[e].data);this.ext&&i.writeUint8Array(this.ext)}},Pn.fourcc="avcC",Pn),Rn,lr=(Rn=class extends B{constructor(){super(...arguments),this.box_name="MediaDataBox"}},Rn.fourcc="mdat",Rn),Mn,My=(Mn=class extends B{constructor(){super(...arguments),this.box_name="ItemDataBox"}},Mn.fourcc="idat",Mn),kn,ky=(kn=class extends B{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}},kn.fourcc="free",kn),Fn,Fy=(Fn=class extends B{constructor(){super(...arguments),this.box_name="FreeSpaceBox"}},Fn.fourcc="skip",Fn),Bn,kf=(Bn=class extends R{constructor(){super(...arguments),this.box_name="HintMediaHeaderBox"}},Bn.fourcc="hmhd",Bn),Un,cr=(Un=class extends R{constructor(){super(...arguments),this.box_name="NullMediaHeaderBox"}},Un.fourcc="nmhd",Un),On,By=(On=class extends R{constructor(){super(...arguments),this.box_name="ObjectDescriptorBox"}},On.fourcc="iods",On),Dn,Uy=(Dn=class extends R{constructor(){super(...arguments),this.box_name="XMLBox"}},Dn.fourcc="xml ",Dn),Gn,Oy=(Gn=class extends R{constructor(){super(...arguments),this.box_name="BinaryXMLBox"}},Gn.fourcc="bxml",Gn),zn,Dy=(zn=class extends R{constructor(){super(...arguments),this.box_name="ItemProtectionBox",this.sinfs=[]}get protections(){return this.sinfs}},zn.fourcc="ipro",zn),Nn,Ln=(Nn=class extends ee{constructor(){super(...arguments),this.box_name="MovieBox",this.traks=[],this.psshs=[],this.subBoxNames=["trak","pssh"]}},Nn.fourcc="moov",Nn),Hn,Ff=(Hn=class extends ee{constructor(){super(...arguments),this.box_name="TrackBox",this.samples=[]}},Hn.fourcc="trak",Hn),Wn,Gy=(Wn=class extends ee{constructor(){super(...arguments),this.box_name="EditBox"}},Wn.fourcc="edts",Wn),Vn,Bf=(Vn=class extends ee{constructor(){super(...arguments),this.box_name="MediaBox"}},Vn.fourcc="mdia",Vn),$n,Uf=($n=class extends ee{constructor(){super(...arguments),this.box_name="MediaInformationBox"}},$n.fourcc="minf",$n),Xn,Of=(Xn=class extends ee{constructor(){super(...arguments),this.box_name="DataInformationBox"}},Xn.fourcc="dinf",Xn),Yn,Df=(Yn=class extends ee{constructor(){super(...arguments),this.box_name="SampleTableBox",this.sgpds=[],this.sbgps=[],this.subBoxNames=["sgpd","sbgp"]}},Yn.fourcc="stbl",Yn),qn,Kn=(qn=class extends ee{constructor(){super(...arguments),this.box_name="MovieExtendsBox",this.trexs=[],this.subBoxNames=["trex"]}},qn.fourcc="mvex",qn),jn,Gf=(jn=class extends ee{constructor(){super(...arguments),this.box_name="MovieFragmentBox",this.trafs=[],this.subBoxNames=["traf"]}},jn.fourcc="moof",jn),Zn,zf=(Zn=class extends ee{constructor(){super(...arguments),this.box_name="TrackFragmentBox",this.truns=[],this.sgpds=[],this.sbgps=[],this.subBoxNames=["trun","sgpd","sbgp"]}},Zn.fourcc="traf",Zn),Jn,zy=(Jn=class extends ee{constructor(){super(...arguments),this.box_name="VTTCueBox"}},Jn.fourcc="vttc",Jn),Qn,Ny=(Qn=class extends ee{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessBox",this.tfras=[],this.subBoxNames=["tfra"]}},Qn.fourcc="mfra",Qn),eo,Ly=(eo=class extends ee{constructor(){super(...arguments),this.box_name="AdditionalMetadataContainerBox"}},eo.fourcc="meco",eo),to,Hy=(to=class extends ee{constructor(){super(...arguments),this.box_name="trackhintinformation",this.subBoxNames=["sdp ","rtp "]}},to.fourcc="hnti",to),io,Wy=(io=class extends ee{constructor(){super(...arguments),this.box_name="hintstatisticsbox",this.maxrs=[],this.subBoxNames=["maxr"]}},io.fourcc="hinf",io),so,Vy=(so=class extends ee{constructor(){super(...arguments),this.box_name="SubTrackBox"}},so.fourcc="strk",so),ro,$y=(ro=class extends ee{constructor(){super(...arguments),this.box_name="SubTrackDefinitionBox"}},ro.fourcc="strd",ro),no,Xy=(no=class extends ee{constructor(){super(...arguments),this.box_name="ProtectionSchemeInfoBox"}},no.fourcc="sinf",no),oo,Yy=(oo=class extends ee{constructor(){super(...arguments),this.box_name="RestrictedSchemeInfoBox"}},oo.fourcc="rinf",oo),ao,qy=(ao=class extends ee{constructor(){super(...arguments),this.box_name="SchemeInformationBox"}},ao.fourcc="schi",ao),lo,Ky=(lo=class extends ee{constructor(){super(...arguments),this.box_name="TrackGroupBox"}},lo.fourcc="trgr",lo),co,jy=(co=class extends ee{constructor(){super(...arguments),this.box_name="UserDataBox",this.kinds=[],this.strks=[],this.subBoxNames=["kind","strk"]}},co.fourcc="udta",co),ho,Zy=(ho=class extends ee{constructor(){super(...arguments),this.box_name="ItemPropertiesBox",this.ipmas=[],this.subBoxNames=["ipma"]}},ho.fourcc="iprp",ho),uo,Jy=(uo=class extends ee{constructor(){super(...arguments),this.box_name="ItemPropertyContainerBox",this.hvcCs=[],this.ispes=[],this.claps=[],this.irots=[],this.subBoxNames=["hvcC","ispe","clap","irot"]}},uo.fourcc="ipco",uo),fo,Qy=(fo=class extends ee{constructor(){super(...arguments),this.box_name="GroupsListBox"}},fo.fourcc="grpl",fo),po,ev=(po=class extends ee{constructor(){super(...arguments),this.box_name="J2KHeaderInfoBox"}},po.fourcc="j2kH",po),mo,tv=(mo=class extends ee{constructor(){super(...arguments),this.box_name="ExtendedTypeBox",this.tycos=[],this.subBoxNames=["tyco"]}},mo.fourcc="etyp",mo),go,iv=(go=class extends ee{constructor(){super(...arguments),this.box_name="ProjectedOmniVideoBox",this.subBoxNames=["prfr"]}},go.fourcc="povd",go),xo,Nf=(xo=class extends R{constructor(){super(...arguments),this.box_name="DataReferenceBox"}parse(i){this.parseFullHeader(i),this.entries=[];const e=i.readUint32();for(let t=0;t<e;t++){const s=ht(i,!1,this.size-(i.getPosition()-this.start));if(s.code===We){const r=s.box;this.entries.push(r)}else return}}write(i){this.version=0,this.flags=0,this.size=4,this.writeHeader(i),i.writeUint32(this.entries.length);for(let e=0;e<this.entries.length;e++)this.entries[e].write(i),this.size+=this.entries[e].size;I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),i.adjustUint32(this.sizePosition,this.size)}},xo.fourcc="dref",xo),_o,Lf=(_o=class extends R{constructor(){super(...arguments),this.box_name="ExtendedLanguageBox"}parse(i){this.parseFullHeader(i),this.extended_language=i.readString(this.size-this.hdr_size)}write(i){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(i),i.writeString(this.extended_language)}},_o.fourcc="elng",_o),yo,Hf=(yo=class extends B{constructor(){super(...arguments),this.box_name="FileTypeBox"}parse(i){let e=this.size-this.hdr_size;this.major_brand=i.readString(4),this.minor_version=i.readUint32(),e-=8,this.compatible_brands=[];let t=0;for(;e>=4;)this.compatible_brands[t]=i.readString(4),e-=4,t++}write(i){this.size=8+4*this.compatible_brands.length,this.writeHeader(i),i.writeString(this.major_brand,void 0,4),i.writeUint32(this.minor_version);for(let e=0;e<this.compatible_brands.length;e++)i.writeString(this.compatible_brands[e],void 0,4)}},yo.fourcc="ftyp",yo),vo,Wf=(vo=class extends R{constructor(){super(...arguments),this.box_name="HandlerBox"}parse(i){if(this.parseFullHeader(i),this.version===0&&(i.readUint32(),this.handler=i.readString(4),i.readUint32Array(3),!this.isEndOfBox(i))){const e=this.start+this.size-i.getPosition();this.name=i.readCString();const t=this.start+this.size-1;i.seek(t),i.readUint8()!==0&&e>1&&(I.info("BoxParser","Warning: hdlr name is not null-terminated, possibly length-prefixed string. Trimming first byte."),this.name=this.name.slice(1))}}write(i){this.size=20+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(i),i.writeUint32(0),i.writeString(this.handler,void 0,4),i.writeUint32Array([0,0,0]),i.writeCString(this.name)}},vo.fourcc="hdlr",vo),bo,Vf=(bo=class extends B{constructor(){super(...arguments),this.box_name="HEVCConfigurationBox"}parse(i){this.configurationVersion=i.readUint8();let e=i.readUint8();this.general_profile_space=e>>6,this.general_tier_flag=(e&32)>>5,this.general_profile_idc=e&31,this.general_profile_compatibility=i.readUint32(),this.general_constraint_indicator=i.readUint8Array(6),this.general_level_idc=i.readUint8(),this.min_spatial_segmentation_idc=i.readUint16()&4095,this.parallelismType=i.readUint8()&3,this.chroma_format_idc=i.readUint8()&3,this.bit_depth_luma_minus8=i.readUint8()&7,this.bit_depth_chroma_minus8=i.readUint8()&7,this.avgFrameRate=i.readUint16(),e=i.readUint8(),this.constantFrameRate=e>>6,this.numTemporalLayers=(e&13)>>3,this.temporalIdNested=(e&4)>>2,this.lengthSizeMinusOne=e&3,this.nalu_arrays=[];const t=i.readUint8();for(let s=0;s<t;s++){const r=[];this.nalu_arrays.push(r),e=i.readUint8(),r.completeness=(e&128)>>7,r.nalu_type=e&63;const n=i.readUint16();for(let o=0;o<n;o++){const a=i.readUint16();r.push({data:i.readUint8Array(a)})}}}write(i){this.size=23;for(let e=0;e<this.nalu_arrays.length;e++){this.size+=3;for(let t=0;t<this.nalu_arrays[e].length;t++)this.size+=2+this.nalu_arrays[e][t].data.length}this.writeHeader(i),i.writeUint8(this.configurationVersion),i.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),i.writeUint32(this.general_profile_compatibility),i.writeUint8Array(this.general_constraint_indicator),i.writeUint8(this.general_level_idc),i.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),i.writeUint8(this.parallelismType+252),i.writeUint8(this.chroma_format_idc+252),i.writeUint8(this.bit_depth_luma_minus8+248),i.writeUint8(this.bit_depth_chroma_minus8+248),i.writeUint16(this.avgFrameRate),i.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),i.writeUint8(this.nalu_arrays.length);for(let e=0;e<this.nalu_arrays.length;e++){i.writeUint8((this.nalu_arrays[e].completeness<<7)+this.nalu_arrays[e].nalu_type),i.writeUint16(this.nalu_arrays[e].length);for(let t=0;t<this.nalu_arrays[e].length;t++)i.writeUint16(this.nalu_arrays[e][t].data.length),i.writeUint8Array(this.nalu_arrays[e][t].data)}}},bo.fourcc="hvcC",bo),To,$f=(To=class extends R{constructor(){super(...arguments),this.box_name="MediaHeaderBox"}parse(i){this.parseFullHeader(i),this.version===1?(this.creation_time=i.readUint64(),this.modification_time=i.readUint64(),this.timescale=i.readUint32(),this.duration=i.readUint64()):(this.creation_time=i.readUint32(),this.modification_time=i.readUint32(),this.timescale=i.readUint32(),this.duration=i.readUint32()),this.parseLanguage(i),i.readUint16()}write(i){const e=this.modification_time>Ae||this.creation_time>Ae||this.duration>Ae||this.version===1;this.version=e?1:0,this.size=20,this.size+=e?12:0,this.flags=0,this.writeHeader(i),e?(i.writeUint64(this.creation_time),i.writeUint64(this.modification_time),i.writeUint32(this.timescale),i.writeUint64(this.duration)):(i.writeUint32(this.creation_time),i.writeUint32(this.modification_time),i.writeUint32(this.timescale),i.writeUint32(this.duration)),i.writeUint16(this.language),i.writeUint16(0)}},To.fourcc="mdhd",To),wo,Xf=(wo=class extends R{constructor(){super(...arguments),this.box_name="MovieExtendsHeaderBox"}parse(i){this.parseFullHeader(i),this.flags&1&&(I.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version===1?this.fragment_duration=i.readUint64():this.fragment_duration=i.readUint32()}write(i){const e=this.fragment_duration>Ae||this.version===1;this.version=e?1:0,this.size=4,this.size+=e?4:0,this.flags=0,this.writeHeader(i),e?i.writeUint64(this.fragment_duration):i.writeUint32(this.fragment_duration)}},wo.fourcc="mehd",wo),So,sv=(So=class extends R{constructor(){super(...arguments),this.box_name="ItemInfoEntry"}parse(i){if(this.parseFullHeader(i),(this.version===0||this.version===1)&&(this.item_ID=i.readUint16(),this.item_protection_index=i.readUint16(),this.item_name=i.readCString(),this.content_type=i.readCString(),this.isEndOfBox(i)||(this.content_encoding=i.readCString())),this.version===1){this.extension_type=i.readString(4),I.warn("BoxParser","Cannot parse extension type"),i.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=i.readUint16():this.version===3&&(this.item_ID=i.readUint32()),this.item_protection_index=i.readUint16(),this.item_type=i.readString(4),this.item_name=i.readCString(),this.item_type==="mime"?(this.content_type=i.readCString(),this.content_encoding=i.readCString()):this.item_type==="uri "&&(this.item_uri_type=i.readCString()))}},So.fourcc="infe",So),Co,rv=(Co=class extends R{constructor(){super(...arguments),this.box_name="ItemInfoBox"}parse(i){this.parseFullHeader(i),this.version===0?this.entry_count=i.readUint16():this.entry_count=i.readUint32(),this.item_infos=[];for(let e=0;e<this.entry_count;e++){const t=ht(i,!1,this.size-(i.getPosition()-this.start));if(t.code===We){const s=t.box;s.type==="infe"?this.item_infos[e]=s:I.error("BoxParser","Expected 'infe' box, got "+t.box.type,i.isofile)}else return}}},Co.fourcc="iinf",Co),Ao,nv=(Ao=class extends R{constructor(){super(...arguments),this.box_name="ItemLocationBox"}parse(i){this.parseFullHeader(i);let e;e=i.readUint8(),this.offset_size=e>>4&15,this.length_size=e&15,e=i.readUint8(),this.base_offset_size=e>>4&15,this.version===1||this.version===2?this.index_size=e&15:this.index_size=0,this.items=[];let t=0;if(this.version<2)t=i.readUint16();else if(this.version===2)t=i.readUint32();else throw new Error("version of iloc box not supported");for(let s=0;s<t;s++){let r=0,n=0,o=0;if(this.version<2)r=i.readUint16();else if(this.version===2)r=i.readUint32();else throw new Error("version of iloc box not supported");this.version===1||this.version===2?n=i.readUint16()&15:n=0;const a=i.readUint16();switch(this.base_offset_size){case 0:o=0;break;case 4:o=i.readUint32();break;case 8:o=i.readUint64();break;default:throw new Error("Error reading base offset size")}const l=[],c=i.readUint16();for(let h=0;h<c;h++){let u=0,d=0,f=0;if(this.version===1||this.version===2)switch(this.index_size){case 0:u=0;break;case 4:u=i.readUint32();break;case 8:u=i.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.offset_size){case 0:d=0;break;case 4:d=i.readUint32();break;case 8:d=i.readUint64();break;default:throw new Error("Error reading extent index")}switch(this.length_size){case 0:f=0;break;case 4:f=i.readUint32();break;case 8:f=i.readUint64();break;default:throw new Error("Error reading extent index")}l.push({extent_index:u,extent_length:f,extent_offset:d})}this.items.push({base_offset:o,construction_method:n,item_ID:r,data_reference_index:a,extents:l})}}},Ao.fourcc="iloc",Ao),ov={auxl:"Auxiliary image item",base:"Pre-derived image item base",cdsc:"Item describes referenced item",dimg:"Derived image item",dpnd:"Item coding dependency",eroi:"Region",evir:"EVC slice",exbl:"Scalable image item","fdl ":"File delivery",font:"Font item",iloc:"Item data location",mask:"Region mask",mint:"Data integrity",pred:"Predictively coded item",prem:"Pre-multiplied item",tbas:"HEVC tile track base item",text:"Text item",thmb:"Thumbnail image item"},os,av=(os=class extends R{constructor(){super(...arguments),this.box_name="ItemReferenceBox",this.references=[]}parse(i){for(this.parseFullHeader(i),this.references=[];i.getPosition()<this.start+this.size;){const e=ht(i,!0,this.size-(i.getPosition()-this.start));if(e.code===We){let t="Unknown item reference";os.allowed_types.includes(e.type)?t=ov[e.type]:I.warn("BoxParser",`Unknown item reference type: '${e.type}'`);const s=this.version===0?new Sf(e.type,e.size,t,e.hdr_size,e.start):new Cf(e.type,e.size,t,e.hdr_size,e.start);s.write===B.prototype.write&&s.type!=="mdat"&&(I.warn("BoxParser",s.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),s.parseDataAndRewind(i)),s.parse(i),this.references.push(s)}else return}}},os.fourcc="iref",os.allowed_types=["auxl","base","cdsc","dimg","dpnd","eroi","evir","exbl","fdl ","font","iloc","mask","mint","pred","prem","tbas","text","thmb"],os),Eo,lv=(Eo=class extends R{constructor(){super(...arguments),this.box_name="PrimaryItemBox"}parse(i){this.parseFullHeader(i),this.version===0?this.item_id=i.readUint16():this.item_id=i.readUint32()}},Eo.fourcc="pitm",Eo),Io,cv=(Io=class extends R{constructor(){super(...arguments),this.box_name="MetaBox",this.isQT=!1}parse(i){const e=i.getPosition();if(this.size>8){switch(i.readUint32(),i.readString(4)){case"hdlr":case"mhdr":case"keys":case"ilst":case"ctry":case"lang":this.isQT=!0;break}i.seek(e)}this.isQT||this.parseFullHeader(i),ee.prototype.parse.call(this,i)}},Io.fourcc="meta",Io),Po,Yf=(Po=class extends R{constructor(){super(...arguments),this.box_name="MovieFragmentHeaderBox"}parse(i){this.parseFullHeader(i),this.sequence_number=i.readUint32()}write(i){this.version=0,this.flags=0,this.size=4,this.writeHeader(i),i.writeUint32(this.sequence_number)}},Po.fourcc="mfhd",Po),Ro,qf=(Ro=class extends R{constructor(){super(...arguments),this.box_name="MovieHeaderBox"}parse(i){this.parseFullHeader(i),this.version===1?(this.creation_time=i.readUint64(),this.modification_time=i.readUint64(),this.timescale=i.readUint32(),this.duration=i.readUint64()):(this.creation_time=i.readUint32(),this.modification_time=i.readUint32(),this.timescale=i.readUint32(),this.duration=i.readUint32()),this.rate=i.readUint32(),this.volume=i.readUint16()>>8,i.readUint16(),i.readUint32Array(2),this.matrix=i.readInt32Array(9),i.readUint32Array(6),this.next_track_id=i.readUint32()}write(i){const e=this.modification_time>Ae||this.creation_time>Ae||this.duration>Ae||this.version===1;this.version=e?1:0,this.size=96,this.size+=e?12:0,this.flags=0,this.writeHeader(i),e?(i.writeUint64(this.creation_time),i.writeUint64(this.modification_time),i.writeUint32(this.timescale),i.writeUint64(this.duration)):(i.writeUint32(this.creation_time),i.writeUint32(this.modification_time),i.writeUint32(this.timescale),i.writeUint32(this.duration)),i.writeUint32(this.rate),i.writeUint16(this.volume<<8),i.writeUint16(0),i.writeUint32(0),i.writeUint32(0),i.writeInt32Array(this.matrix),i.writeUint32(0),i.writeUint32(0),i.writeUint32(0),i.writeUint32(0),i.writeUint32(0),i.writeUint32(0),i.writeUint32(this.next_track_id)}print(i){super.printHeader(i),i.log(i.indent+"creation_time: "+this.creation_time),i.log(i.indent+"modification_time: "+this.modification_time),i.log(i.indent+"timescale: "+this.timescale),i.log(i.indent+"duration: "+this.duration),i.log(i.indent+"rate: "+this.rate),i.log(i.indent+"volume: "+(this.volume>>8)),i.log(i.indent+"matrix: "+this.matrix.join(", ")),i.log(i.indent+"next_track_id: "+this.next_track_id)}},Ro.fourcc="mvhd",Ro),Mo,hv=(Mo=class extends ni{parse(i){this.parseHeader(i),this.content_encoding=i.readCString(),this.mime_format=i.readCString(),this.parseFooter(i)}},Mo.fourcc="mett",Mo),ko,uv=(ko=class extends ni{parse(i){this.parseHeader(i),this.content_encoding=i.readCString(),this.namespace=i.readCString(),this.schema_location=i.readCString(),this.parseFooter(i)}},ko.fourcc="metx",ko),Fo,dv=(Fo=class extends B{constructor(){super(...arguments),this.box_name="AV1CodecConfigurationBox"}parse(i){let e=i.readUint8();if((e>>7&1)!==1){I.error("BoxParser","av1C marker problem",i.isofile);return}if(this.version=e&127,this.version!==1){I.error("BoxParser","av1C version "+this.version+" not supported",i.isofile);return}if(e=i.readUint8(),this.seq_profile=e>>5&7,this.seq_level_idx_0=e&31,e=i.readUint8(),this.seq_tier_0=e>>7&1,this.high_bitdepth=e>>6&1,this.twelve_bit=e>>5&1,this.monochrome=e>>4&1,this.chroma_subsampling_x=e>>3&1,this.chroma_subsampling_y=e>>2&1,this.chroma_sample_position=e&3,e=i.readUint8(),this.reserved_1=e>>5&7,this.reserved_1!==0){I.error("BoxParser","av1C reserved_1 parsing problem",i.isofile);return}if(this.initial_presentation_delay_present=e>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=e&15;else if(this.reserved_2=e&15,this.reserved_2!==0){I.error("BoxParser","av1C reserved_2 parsing problem",i.isofile);return}const t=this.size-this.hdr_size-4;this.configOBUs=i.readUint8Array(t)}},Fo.fourcc="av1C",Fo),Bo,fv=(Bo=class extends R{constructor(){super(...arguments),this.box_name="ElementaryStreamDescriptorBox"}parse(i){this.parseFullHeader(i);const e=i.readUint8Array(this.size-this.hdr_size);if("MPEG4DescriptorParser"in or){const t=new or.MPEG4DescriptorParser;this.esd=t.parseOneDescriptor(new Pe(e.buffer,0))}}},Bo.fourcc="esds",Bo),Uo,pv=(Uo=class extends R{constructor(){super(...arguments),this.box_name="VPCodecConfigurationRecord"}parse(i){if(this.parseFullHeader(i),this.version===1){this.profile=i.readUint8(),this.level=i.readUint8();const e=i.readUint8();this.bitDepth=e>>4,this.chromaSubsampling=e>>1&7,this.videoFullRangeFlag=e&1,this.colourPrimaries=i.readUint8(),this.transferCharacteristics=i.readUint8(),this.matrixCoefficients=i.readUint8(),this.codecIntializationDataSize=i.readUint16(),this.codecIntializationData=i.readUint8Array(this.codecIntializationDataSize)}else{this.profile=i.readUint8(),this.level=i.readUint8();let e=i.readUint8();this.bitDepth=e>>4&15,this.colorSpace=e&15,e=i.readUint8(),this.chromaSubsampling=e>>4&15,this.transferFunction=e>>1&7,this.videoFullRangeFlag=e&1,this.codecIntializationDataSize=i.readUint16(),this.codecIntializationData=i.readUint8Array(this.codecIntializationDataSize)}}},Uo.fourcc="vpcC",Uo),Oo,mv=(Oo=class extends R{constructor(){super(...arguments),this.box_name="VvcConfigurationBox"}parse(i){this.parseFullHeader(i);const e={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(n){this.held_bits=n.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(n){this.held_bits=n.readUint16(),this.num_held_bits=16},extract_bits:function(n){const o=this.held_bits>>this.num_held_bits-n&(1<<n)-1;return this.num_held_bits-=n,o}};if(e.stream_read_1_bytes(i),e.extract_bits(5),this.lengthSizeMinusOne=e.extract_bits(2),this.ptl_present_flag=e.extract_bits(1),this.ptl_present_flag){e.stream_read_2_bytes(i),this.ols_idx=e.extract_bits(9),this.num_sublayers=e.extract_bits(3),this.constant_frame_rate=e.extract_bits(2),this.chroma_format_idc=e.extract_bits(2),e.stream_read_1_bytes(i),this.bit_depth_minus8=e.extract_bits(3),e.extract_bits(5);{if(e.stream_read_2_bytes(i),e.extract_bits(2),this.num_bytes_constraint_info=e.extract_bits(6),this.general_profile_idc=e.extract_bits(7),this.general_tier_flag=e.extract_bits(1),this.general_level_idc=i.readUint8(),e.stream_read_1_bytes(i),this.ptl_frame_only_constraint_flag=e.extract_bits(1),this.ptl_multilayer_enabled_flag=e.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(let n=0;n<this.num_bytes_constraint_info-1;n++){const o=e.extract_bits(6);e.stream_read_1_bytes(i);const a=e.extract_bits(2);this.general_constraint_info[n]=o<<2|a}this.general_constraint_info[this.num_bytes_constraint_info-1]=e.extract_bits(6)}else e.extract_bits(6);if(this.num_sublayers>1){e.stream_read_1_bytes(i),this.ptl_sublayer_present_mask=0;for(let n=this.num_sublayers-2;n>=0;--n){const o=e.extract_bits(1);this.ptl_sublayer_present_mask|=o<<n}for(let n=this.num_sublayers;n<=8&&this.num_sublayers>1;++n)e.extract_bits(1);this.sublayer_level_idc=[];for(let n=this.num_sublayers-2;n>=0;--n)this.ptl_sublayer_present_mask&1<<n&&(this.sublayer_level_idc[n]=i.readUint8())}if(this.ptl_num_sub_profiles=i.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(let n=0;n<this.ptl_num_sub_profiles;n++)this.general_sub_profile_idc.push(i.readUint32())}this.max_picture_width=i.readUint16(),this.max_picture_height=i.readUint16(),this.avg_frame_rate=i.readUint16()}const t=12,s=13;this.nalu_arrays=[];const r=i.readUint8();for(let n=0;n<r;n++){const o=[];this.nalu_arrays.push(o),e.stream_read_1_bytes(i),o.completeness=e.extract_bits(1),e.extract_bits(2),o.nalu_type=e.extract_bits(5);let a=1;o.nalu_type!==s&&o.nalu_type!==t&&(a=i.readUint16());for(let l=0;l<a;l++){const c=i.readUint16();o.push({data:i.readUint8Array(c),length:c})}}}},Oo.fourcc="vvcC",Oo),Do,gv=(Do=class extends B{constructor(){super(...arguments),this.box_name="ColourInformationBox"}parse(i){if(this.colour_type=i.readString(4),this.colour_type==="nclx"){this.colour_primaries=i.readUint16(),this.transfer_characteristics=i.readUint16(),this.matrix_coefficients=i.readUint16();const e=i.readUint8();this.full_range_flag=e>>7}else this.colour_type==="rICC"?this.ICC_profile=i.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=i.readUint8Array(this.size-4))}},Do.fourcc="colr",Do);function wi(i,e){let t=Number(i).toString(16);for(e=typeof e>"u"?2:e;t.length<e;)t="0"+t;return t}var hr=class extends fe{getCodec(){const i=super.getCodec();return this.avcC?`${i}.${wi(this.avcC.AVCProfileIndication)}${wi(this.avcC.profile_compatibility)}${wi(this.avcC.AVCLevelIndication)}`:i}},Go,xv=(Go=class extends hr{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}},Go.fourcc="avc1",Go),zo,_v=(zo=class extends hr{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}},zo.fourcc="avc2",zo),No,yv=(No=class extends hr{constructor(){super(...arguments),this.box_name="AVCSampleEntry"}},No.fourcc="avc3",No),Lo,vv=(Lo=class extends hr{constructor(){super(...arguments),this.box_name="AVC2SampleEntry"}},Lo.fourcc="avc4",Lo),Ho,bv=(Ho=class extends fe{constructor(){super(...arguments),this.box_name="AV1SampleEntry"}getCodec(){const i=super.getCodec(),e=this.av1C.seq_level_idx_0,t=e<10?"0"+e:e;let s;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?s=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(s=this.av1C.high_bitdepth===1?"10":"08"),i+"."+this.av1C.seq_profile+"."+t+(this.av1C.seq_tier_0?"H":"M")+"."+s}},Ho.fourcc="av01",Ho),Wo,Tv=(Wo=class extends fe{},Wo.fourcc="dav1",Wo),ur=class extends fe{getCodec(){let i=super.getCodec();if(this.hvcC){switch(i+=".",this.hvcC.general_profile_space){case 0:i+="";break;case 1:i+="A";break;case 2:i+="B";break;case 3:i+="C";break}i+=this.hvcC.general_profile_idc,i+=".";let e=this.hvcC.general_profile_compatibility,t=0;for(let n=0;n<32&&(t|=e&1,n!==31);n++)t<<=1,e>>=1;i+=wi(t,0),i+=".",this.hvcC.general_tier_flag===0?i+="L":i+="H",i+=this.hvcC.general_level_idc;let s=!1,r="";for(let n=5;n>=0;n--)(this.hvcC.general_constraint_indicator[n]||s)&&(r="."+wi(this.hvcC.general_constraint_indicator[n],0)+r,s=!0);i+=r}return i}},Vo,wv=(Vo=class extends ur{constructor(){super(...arguments),this.box_name="HEVCSampleEntry"}},Vo.fourcc="hvc1",Vo),$o,Sv=($o=class extends ur{},$o.fourcc="hvc2",$o),Xo,Cv=(Xo=class extends ur{constructor(){super(...arguments),this.box_name="HEVCSampleEntry",this.colrs=[],this.subBoxNames=["colr"]}},Xo.fourcc="hev1",Xo),Yo,Av=(Yo=class extends ur{},Yo.fourcc="hev2",Yo),qo,Ev=(qo=class extends fe{constructor(){super(...arguments),this.box_name="HEVCTileSampleSampleEntry"}},qo.fourcc="hvt1",qo),Ko,Iv=(Ko=class extends fe{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},Ko.fourcc="lhe1",Ko),jo,Pv=(jo=class extends fe{constructor(){super(...arguments),this.box_name="LHEVCSampleEntry"}},jo.fourcc="lhv1",jo),Zo,Rv=(Zo=class extends fe{},Zo.fourcc="dvh1",Zo),Jo,Mv=(Jo=class extends fe{},Jo.fourcc="dvhe",Jo),Kf=class extends fe{getCodec(){let i=super.getCodec();if(this.vvcC){i+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?i+=".H":i+=".L",i+=this.vvcC.general_level_idc;let e="";if(this.vvcC.general_constraint_info){const t=[];let s=0;s|=this.vvcC.ptl_frame_only_constraint_flag<<7,s|=this.vvcC.ptl_multilayer_enabled_flag<<6;let r;for(let n=0;n<this.vvcC.general_constraint_info.length;++n)s|=this.vvcC.general_constraint_info[n]>>2&63,t.push(s),s&&(r=n),s=this.vvcC.general_constraint_info[n]>>2&3;if(r===void 0)e=".CA";else{e=".C";const n="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";let o=0,a=0;for(let l=0;l<=r;++l)for(o=o<<8|t[l],a+=8;a>=5;){const c=o>>a-5&31;e+=n[c],a-=5,o&=(1<<a)-1}a&&(o<<=5-a,e+=n[o&31])}}i+=e}return i}},Qo,kv=(Qo=class extends Kf{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},Qo.fourcc="vvc1",Qo),ea,Fv=(ea=class extends Kf{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},ea.fourcc="vvi1",ea),ta,Bv=(ta=class extends fe{constructor(){super(...arguments),this.box_name="VvcSampleEntry"}},ta.fourcc="vvs1",ta),ia,Uv=(ia=class extends fe{constructor(){super(...arguments),this.box_name="VvcNonVCLSampleEntry"}},ia.fourcc="vvcN",ia),jf=class extends fe{getCodec(){const i=super.getCodec();let e=this.vpcC.level;e===0&&(e="00");let t=this.vpcC.bitDepth;return t===8&&(t="08"),`${i}.0${this.vpcC.profile}.${e}.${t}`}},sa,Ov=(sa=class extends jf{},sa.fourcc="vp08",sa),ra,Dv=(ra=class extends jf{},ra.fourcc="vp09",ra),na,Gv=(na=class extends fe{},na.fourcc="avs3",na),oa,zv=(oa=class extends fe{constructor(){super(...arguments),this.box_name="J2KSampleEntry"}},oa.fourcc="j2ki",oa),aa,Nv=(aa=class extends fe{},aa.fourcc="mjp2",aa),la,Lv=(la=class extends fe{},la.fourcc="mjpg",la),ca,Hv=(ca=class extends fe{constructor(){super(...arguments),this.box_name="UncompressedVideoSampleEntry"}},ca.fourcc="uncv",ca),ha,Wv=(ha=class extends fe{constructor(){super(...arguments),this.box_name="MP4VisualSampleEntry"}},ha.fourcc="mp4v",ha),ua,Vv=(ua=class extends ze{constructor(){super(...arguments),this.box_name="MP4AudioSampleEntry"}getCodec(){const i=super.getCodec();if(this.esds&&this.esds.esd){const e=this.esds.esd.getOTI(),t=this.esds.esd.getAudioConfig();return i+"."+wi(e)+(t?"."+t:"")}else return i}},ua.fourcc="mp4a",ua),da,$v=(da=class extends ze{},da.fourcc="m4ae",da),fa,Xv=(fa=class extends ze{},fa.fourcc="ac-3",fa),pa,Yv=(pa=class extends ze{},pa.fourcc="ac-4",pa),ma,qv=(ma=class extends ze{},ma.fourcc="ec-3",ma),ga,Kv=(ga=class extends ze{},ga.fourcc="Opus",ga),xa,jv=(xa=class extends ze{},xa.fourcc="mha1",xa),_a,Zv=(_a=class extends ze{},_a.fourcc="mha2",_a),ya,Jv=(ya=class extends ze{},ya.fourcc="mhm1",ya),va,Qv=(va=class extends ze{},va.fourcc="mhm2",va),ba,eb=(ba=class extends ze{},ba.fourcc="fLaC",ba),Ta,tb=(Ta=class extends fe{},Ta.fourcc="encv",Ta),wa,ib=(wa=class extends ze{},wa.fourcc="enca",wa),Sa,sb=(Sa=class extends $t{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Sa.fourcc="encu",Sa),Ca,rb=(Ca=class extends ar{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Ca.fourcc="encs",Ca),Aa,nb=(Aa=class extends ar{},Aa.fourcc="mp4s",Aa),Ea,ob=(Ea=class extends Pf{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Ea.fourcc="enct",Ea),Ia,ab=(Ia=class extends ni{constructor(){super(...arguments),this.subBoxNames=["sinf"],this.sinfs=[]}},Ia.fourcc="encm",Ia),Pa,lb=(Pa=class extends fe{constructor(){super(...arguments),this.box_name="RestrictedVideoSampleEntry"}},Pa.fourcc="resv",Pa),Ra,cb=(Ra=class extends $t{parse(i){this.parseHeader(i),this.content_encoding=i.readCString(),this.mime_format=i.readCString(),this.parseFooter(i)}},Ra.fourcc="sbtt",Ra),Ma,Zf=(Ma=class extends $t{parse(i){this.parseHeader(i),this.namespace=i.readCString(),this.schema_location=i.readCString(),this.auxiliary_mime_types=i.readCString(),this.parseFooter(i)}write(i){this.writeHeader(i),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,i.writeCString(this.namespace),i.writeCString(this.schema_location),i.writeCString(this.auxiliary_mime_types),this.writeFooter(i)}},Ma.fourcc="stpp",Ma),ka,hb=(ka=class extends $t{parse(i){this.parseHeader(i),this.content_encoding=i.readCString(),this.mime_format=i.readCString(),this.parseFooter(i)}getCodec(){const i=super.getCodec();return this.mime_format?i+"."+this.mime_format:i}},ka.fourcc="stxt",ka),Fa,ub=(Fa=class extends $t{parse(i){this.parseHeader(i),this.displayFlags=i.readUint32(),this.horizontal_justification=i.readInt8(),this.vertical_justification=i.readInt8(),this.bg_color_rgba=i.readUint8Array(4),this.box_record=i.readInt16Array(4),this.style_record=i.readUint8Array(12),this.parseFooter(i)}},Fa.fourcc="tx3g",Fa),Ba,db=(Ba=class extends ni{parse(i){this.parseHeader(i),this.parseFooter(i)}},Ba.fourcc="wvtt",Ba),Ua,fb=(Ua=class extends R{constructor(){super(...arguments),this.box_name="SampleToGroupBox"}parse(i){this.parseFullHeader(i),this.grouping_type=i.readString(4),this.version===1?this.grouping_type_parameter=i.readUint32():this.grouping_type_parameter=0,this.entries=[];const e=i.readUint32();for(let t=0;t<e;t++)this.entries.push({sample_count:i.readInt32(),group_description_index:i.readInt32()})}write(i){this.grouping_type_parameter?this.version=1:this.version=0,this.flags=0,this.size=8+8*this.entries.length+(this.version===1?4:0),this.writeHeader(i),i.writeString(this.grouping_type,void 0,4),this.version===1&&i.writeUint32(this.grouping_type_parameter),i.writeUint32(this.entries.length);for(let e=0;e<this.entries.length;e++){const t=this.entries[e];i.writeInt32(t.sample_count),i.writeInt32(t.group_description_index)}}},Ua.fourcc="sbgp",Ua),Oa,pb=(Oa=class extends R{constructor(){super(...arguments),this.box_name="SampleDependencyTypeBox"}parse(i){this.parseFullHeader(i);const e=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(let t=0;t<e;t++){const s=i.readUint8();this.is_leading[t]=s>>6,this.sample_depends_on[t]=s>>4&3,this.sample_is_depended_on[t]=s>>2&3,this.sample_has_redundancy[t]=s&3}}},Oa.fourcc="sdtp",Oa),Da,mb=(Da=class extends R{constructor(){super(...arguments),this.box_name="SampleGroupDescriptionBox"}parse(i){this.parseFullHeader(i),this.grouping_type=i.readString(4),I.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=i.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=i.readUint32()),this.entries=[];const e=i.readUint32();for(let t=0;t<e;t++){let s;this.grouping_type in Ve.sampleGroupEntry?s=new Ve.sampleGroupEntry[this.grouping_type](this.grouping_type):s=new ye(this.grouping_type),this.entries.push(s),this.version===1?this.default_length===0?s.description_length=i.readUint32():s.description_length=this.default_length:s.description_length=this.default_length,s.write===ye.prototype.write&&(I.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),s.data=i.readUint8Array(s.description_length),i.seek(i.getPosition()-s.description_length)),s.parse(i)}}write(i){this.flags=0,this.size=12;for(let e=0;e<this.entries.length;e++){const t=this.entries[e];this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=t.data.length)}this.writeHeader(i),i.writeString(this.grouping_type,void 0,4),this.version===1&&i.writeUint32(this.default_length),this.version>=2&&i.writeUint32(this.default_sample_description_index),i.writeUint32(this.entries.length);for(let e=0;e<this.entries.length;e++){const t=this.entries[e];this.version===1&&this.default_length===0&&i.writeUint32(t.description_length),t.write(i)}}},Da.fourcc="sgpd",Da),Ga,gb=(Ga=class extends R{constructor(){super(...arguments),this.box_name="CompressedSegmentIndexBox"}parse(i){this.parseFullHeader(i),this.reference_ID=i.readUint32(),this.timescale=i.readUint32(),this.version===0?(this.earliest_presentation_time=i.readUint32(),this.first_offset=i.readUint32()):(this.earliest_presentation_time=i.readUint64(),this.first_offset=i.readUint64()),i.readUint16(),this.references=[];const e=i.readUint16();for(let t=0;t<e;t++){const s=i.readUint32(),r=i.readUint32(),n=i.readUint32();this.references.push({reference_type:s>>31&1,referenced_size:s&2147483647,subsegment_duration:r,starts_with_SAP:n>>31&1,SAP_type:n>>28&7,SAP_delta_time:n&268435455})}}write(i){const e=this.earliest_presentation_time>Ae||this.first_offset>Ae||this.version===1;this.version=e?1:0,this.size=12+12*this.references.length,this.size+=e?16:8,this.flags=0,this.writeHeader(i),i.writeUint32(this.reference_ID),i.writeUint32(this.timescale),e?(i.writeUint64(this.earliest_presentation_time),i.writeUint64(this.first_offset)):(i.writeUint32(this.earliest_presentation_time),i.writeUint32(this.first_offset)),i.writeUint16(0),i.writeUint16(this.references.length);for(let t=0;t<this.references.length;t++){const s=this.references[t];i.writeUint32(s.reference_type<<31|s.referenced_size),i.writeUint32(s.subsegment_duration),i.writeUint32(s.starts_with_SAP<<31|s.SAP_type<<28|s.SAP_delta_time)}}},Ga.fourcc="sidx",Ga),za,Jf=(za=class extends R{constructor(){super(...arguments),this.box_name="SoundMediaHeaderBox"}parse(i){this.parseFullHeader(i),this.balance=i.readUint16(),i.readUint16()}write(i){this.version=0,this.size=4,this.writeHeader(i),i.writeUint16(this.balance),i.writeUint16(0)}},za.fourcc="smhd",za),Na,Qf=(Na=class extends R{constructor(){super(...arguments),this.box_name="ChunkOffsetBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.chunk_offsets=[],this.version===0)for(let t=0;t<e;t++)this.chunk_offsets.push(i.readUint32())}write(i){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(i),i.writeUint32(this.chunk_offsets.length),i.writeUint32Array(this.chunk_offsets)}unpack(i){for(let e=0;e<this.chunk_offsets.length;e++)i[e].offset=this.chunk_offsets[e]}},Na.fourcc="stco",Na),La,ep=(La=class extends R{constructor(){super(...arguments),this.box_name="SubtitleMediaHeaderBox"}},La.fourcc="sthd",La),Ha,tp=(Ha=class extends R{constructor(){super(...arguments),this.box_name="SampleToChunkBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(let t=0;t<e;t++)this.first_chunk.push(i.readUint32()),this.samples_per_chunk.push(i.readUint32()),this.sample_description_index.push(i.readUint32())}write(i){this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(i),i.writeUint32(this.first_chunk.length);for(let e=0;e<this.first_chunk.length;e++)i.writeUint32(this.first_chunk[e]),i.writeUint32(this.samples_per_chunk[e]),i.writeUint32(this.sample_description_index[e])}unpack(i){let e=0,t=0;for(let s=0;s<this.first_chunk.length;s++)for(let r=0;r<(s+1<this.first_chunk.length?this.first_chunk[s+1]:1/0);r++){t++;for(let n=0;n<this.samples_per_chunk[s];n++){if(i[e])i[e].description_index=this.sample_description_index[s],i[e].chunk_index=t;else return;e++}}}},Ha.fourcc="stsc",Ha),Wa,ip=(Wa=class extends R{constructor(){super(...arguments),this.box_name="SampleDescriptionBox"}parse(i){this.parseFullHeader(i),this.entries=[];const e=i.readUint32();for(let t=1;t<=e;t++){const s=ht(i,!0,this.size-(i.getPosition()-this.start));if(s.code===We){let r;s.type in Ve.sampleEntry?(r=new Ve.sampleEntry[s.type](s.size),r.hdr_size=s.hdr_size,r.start=s.start):(I.warn("BoxParser",`Unknown sample entry type: '${s.type}'`),r=new yt(s.size,s.hdr_size,s.start),r.type=s.type),r.write===yt.prototype.write&&(I.info("BoxParser","SampleEntry "+r.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),r.parseDataAndRewind(i)),r.parse(i),this.entries.push(r)}else return}}write(i){this.version=0,this.flags=0,this.size=0,this.writeHeader(i),i.writeUint32(this.entries.length),this.size+=4;for(let e=0;e<this.entries.length;e++)this.entries[e].write(i),this.size+=this.entries[e].size;I.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),i.adjustUint32(this.sizePosition,this.size)}},Wa.fourcc="stsd",Wa),Va,sp=(Va=class extends R{constructor(){super(...arguments),this.box_name="SampleSizeBox"}parse(i){if(this.parseFullHeader(i),this.sample_sizes=[],this.version===0){this.sample_size=i.readUint32(),this.sample_count=i.readUint32();for(let e=0;e<this.sample_count;e++)this.sample_size===0?this.sample_sizes.push(i.readUint32()):this.sample_sizes[e]=this.sample_size}}write(i){let e=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0){let t=0;for(;t+1<this.sample_sizes.length;)if(this.sample_sizes[t+1]!==this.sample_sizes[0]){e=!1;break}else t++}else e=!1;this.size=8,e||(this.size+=4*this.sample_sizes.length),this.writeHeader(i),e?i.writeUint32(this.sample_sizes[0]):i.writeUint32(0),i.writeUint32(this.sample_sizes.length),e||i.writeUint32Array(this.sample_sizes)}unpack(i){for(let e=0;e<this.sample_sizes.length;e++)i[e].size=this.sample_sizes[e]}},Va.fourcc="stsz",Va),$a,rp=($a=class extends R{constructor(){super(...arguments),this.box_name="TimeToSampleBox",this.sample_counts=[],this.sample_deltas=[]}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.sample_counts.length=0,this.sample_deltas.length=0,this.version===0)for(let t=0;t<e;t++){this.sample_counts.push(i.readUint32());let s=i.readInt32();s<0&&(I.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),s=1),this.sample_deltas.push(s)}}write(i){this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(i),i.writeUint32(this.sample_counts.length);for(let e=0;e<this.sample_counts.length;e++)i.writeUint32(this.sample_counts[e]),i.writeUint32(this.sample_deltas[e])}unpack(i){let e=0;for(let t=0;t<this.sample_counts.length;t++)for(let s=0;s<this.sample_counts[t];s++)e===0?i[e].dts=0:i[e].dts=i[e-1].dts+this.sample_deltas[t],e++}},$a.fourcc="stts",$a),Xa,np=(Xa=class extends R{constructor(){super(...arguments),this.box_name="TrackFragmentBaseMediaDecodeTimeBox"}parse(i){this.parseFullHeader(i),this.version===1?this.baseMediaDecodeTime=i.readUint64():this.baseMediaDecodeTime=i.readUint32()}write(i){const e=this.baseMediaDecodeTime>Ae||this.version===1;this.version=e?1:0,this.size=4,this.size+=e?4:0,this.flags=0,this.writeHeader(i),e?i.writeUint64(this.baseMediaDecodeTime):i.writeUint32(this.baseMediaDecodeTime)}},Xa.fourcc="tfdt",Xa),Ya,op=(Ya=class extends R{constructor(){super(...arguments),this.box_name="TrackFragmentHeaderBox"}parse(i){this.parseFullHeader(i);let e=0;this.track_id=i.readUint32(),this.size-this.hdr_size>e&&this.flags&js?(this.base_data_offset=i.readUint64(),e+=8):this.base_data_offset=0,this.size-this.hdr_size>e&&this.flags&Zs?(this.default_sample_description_index=i.readUint32(),e+=4):this.default_sample_description_index=0,this.size-this.hdr_size>e&&this.flags&Js?(this.default_sample_duration=i.readUint32(),e+=4):this.default_sample_duration=0,this.size-this.hdr_size>e&&this.flags&Qs?(this.default_sample_size=i.readUint32(),e+=4):this.default_sample_size=0,this.size-this.hdr_size>e&&this.flags&er?(this.default_sample_flags=i.readUint32(),e+=4):this.default_sample_flags=0}write(i){this.version=0,this.size=4,this.flags&js&&(this.size+=8),this.flags&Zs&&(this.size+=4),this.flags&Js&&(this.size+=4),this.flags&Qs&&(this.size+=4),this.flags&er&&(this.size+=4),this.writeHeader(i),i.writeUint32(this.track_id),this.flags&js&&i.writeUint64(this.base_data_offset),this.flags&Zs&&i.writeUint32(this.default_sample_description_index),this.flags&Js&&i.writeUint32(this.default_sample_duration),this.flags&Qs&&i.writeUint32(this.default_sample_size),this.flags&er&&i.writeUint32(this.default_sample_flags)}},Ya.fourcc="tfhd",Ya),qa,ap=(qa=class extends R{constructor(){super(...arguments),this.box_name="TrackHeaderBox",this.layer=0,this.alternate_group=0}parse(i){this.parseFullHeader(i),this.version===1?(this.creation_time=i.readUint64(),this.modification_time=i.readUint64(),this.track_id=i.readUint32(),i.readUint32(),this.duration=i.readUint64()):(this.creation_time=i.readUint32(),this.modification_time=i.readUint32(),this.track_id=i.readUint32(),i.readUint32(),this.duration=i.readUint32()),i.readUint32Array(2),this.layer=i.readInt16(),this.alternate_group=i.readInt16(),this.volume=i.readInt16()>>8,i.readUint16(),this.matrix=i.readInt32Array(9),this.width=i.readUint32(),this.height=i.readUint32()}write(i){const e=this.modification_time>Ae||this.creation_time>Ae||this.duration>Ae||this.version===1;this.version=e?1:0,this.size=80,this.size+=e?12:0,this.flags=this.flags??3,this.writeHeader(i),e?(i.writeUint64(this.creation_time),i.writeUint64(this.modification_time),i.writeUint32(this.track_id),i.writeUint32(0),i.writeUint64(this.duration)):(i.writeUint32(this.creation_time),i.writeUint32(this.modification_time),i.writeUint32(this.track_id),i.writeUint32(0),i.writeUint32(this.duration)),i.writeUint32Array([0,0]),i.writeInt16(this.layer),i.writeInt16(this.alternate_group),i.writeInt16(this.volume<<8),i.writeInt16(0),i.writeInt32Array(this.matrix),i.writeUint32(this.width),i.writeUint32(this.height)}print(i){super.printHeader(i),i.log(i.indent+"creation_time: "+this.creation_time),i.log(i.indent+"modification_time: "+this.modification_time),i.log(i.indent+"track_id: "+this.track_id),i.log(i.indent+"duration: "+this.duration),i.log(i.indent+"volume: "+(this.volume>>8)),i.log(i.indent+"matrix: "+this.matrix.join(", ")),i.log(i.indent+"layer: "+this.layer),i.log(i.indent+"alternate_group: "+this.alternate_group),i.log(i.indent+"width: "+this.width),i.log(i.indent+"height: "+this.height)}},qa.fourcc="tkhd",qa),Ka,ja=(Ka=class extends R{constructor(){super(...arguments),this.box_name="TrackExtendsBox"}parse(i){this.parseFullHeader(i),this.track_id=i.readUint32(),this.default_sample_description_index=i.readUint32(),this.default_sample_duration=i.readUint32(),this.default_sample_size=i.readUint32(),this.default_sample_flags=i.readUint32()}write(i){this.version=0,this.flags=0,this.size=20,this.writeHeader(i),i.writeUint32(this.track_id),i.writeUint32(this.default_sample_description_index),i.writeUint32(this.default_sample_duration),i.writeUint32(this.default_sample_size),i.writeUint32(this.default_sample_flags)}},Ka.fourcc="trex",Ka),Za,lp=(Za=class extends R{constructor(){super(...arguments),this.box_name="TrackRunBox",this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[]}parse(i){this.parseFullHeader(i);let e=0;if(this.sample_count=i.readUint32(),e+=4,this.size-this.hdr_size>e&&this.flags&ts?(this.data_offset=i.readInt32(),e+=4):this.data_offset=0,this.size-this.hdr_size>e&&this.flags&tr?(this.first_sample_flags=i.readUint32(),e+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>e)for(let t=0;t<this.sample_count;t++)this.flags&is&&(this.sample_duration[t]=i.readUint32()),this.flags&ss&&(this.sample_size[t]=i.readUint32()),this.flags&rs&&(this.sample_flags[t]=i.readUint32()),this.flags&ns&&(this.version===0?this.sample_composition_time_offset[t]=i.readUint32():this.sample_composition_time_offset[t]=i.readInt32())}write(i){this.size=4,this.flags&ts&&(this.size+=4),this.flags&tr&&(this.size+=4),this.flags&is&&(this.size+=4*this.sample_duration.length),this.flags&ss&&(this.size+=4*this.sample_size.length),this.flags&rs&&(this.size+=4*this.sample_flags.length),this.flags&ns&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(i),i.writeUint32(this.sample_count),this.flags&ts&&(this.data_offset_position=i.getPosition(),i.writeInt32(this.data_offset)),this.flags&tr&&i.writeUint32(this.first_sample_flags);for(let e=0;e<this.sample_count;e++)this.flags&is&&i.writeUint32(this.sample_duration[e]),this.flags&ss&&i.writeUint32(this.sample_size[e]),this.flags&rs&&i.writeUint32(this.sample_flags[e]),this.flags&ns&&(this.version===0?i.writeUint32(this.sample_composition_time_offset[e]):i.writeInt32(this.sample_composition_time_offset[e]))}},Za.fourcc="trun",Za),Ja,cp=(Ja=class extends R{constructor(){super(...arguments),this.box_name="DataEntryUrlBox"}parse(i){this.parseFullHeader(i),this.flags!==1&&(this.location=i.readCString())}write(i){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(i),this.location&&i.writeCString(this.location)}},Ja.fourcc="url ",Ja),Qa,hp=(Qa=class extends R{constructor(){super(...arguments),this.box_name="VideoMediaHeaderBox"}parse(i){this.parseFullHeader(i),this.graphicsmode=i.readUint16(),this.opcolor=i.readUint16Array(3)}write(i){this.version=0,this.size=8,this.writeHeader(i),i.writeUint16(this.graphicsmode),i.writeUint16Array(this.opcolor)}},Qa.fourcc="vmhd",Qa),dr=class{constructor(i,e,t){this.grouping_type=i,this.grouping_type_parameter=e,this.sbgp=t,this.last_sample_in_run=-1,this.entry_index=-1}},up=class ii{constructor(e,t=!0){this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.moovStartSent=!1,this.readySent=!1,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.sidxSent=!1,this.items=[],this.entity_groups=[],this.itemsDataSize=0,this.lastMoofIndex=0,this.samplesDataSize=0,this.lastBoxStartPosition=0,this.nextParsePosition=0,this.discardMdatData=!0,this.discardMdatData=t,e?(this.stream=e,this.parse()):this.stream=new Ti,this.stream.isofile=this}setSegmentOptions(e,t,s){const{sizePerSegment:r=Number.MAX_SAFE_INTEGER,rapAlignement:n=!0}=s;let o=s.nbSamples??s.nbSamplesPerFragment??1e3;const a=s.nbSamplesPerFragment??o;if(o<=0||a<=0||r<=0){I.error("ISOFile",`Invalid segment options: nbSamples=${o}, nbSamplesPerFragment=${a}, sizePerSegment=${r}`);return}if(o<a&&(I.warn("ISOFile",`nbSamples (${o}) is less than nbSamplesPerFragment (${a}), setting nbSamples to nbSamplesPerFragment`),o=a),this.fragmentedTracks.some(c=>c.nb_samples!==o)){I.error("ISOFile",`Cannot set segment options for track ${e}: nbSamples (${o}) does not match existing tracks`);return}const l=this.getTrackById(e);if(l){const c={id:e,user:t,trak:l,segmentStream:void 0,nb_samples:o,nb_samples_per_fragment:a,size_per_segment:r,rapAlignement:n,state:{lastFragmentSampleNumber:0,lastSegmentSampleNumber:0,accumulatedSize:0}};this.fragmentedTracks.push(c),l.nextSample=0}this.discardMdatData&&I.warn("ISOFile","Segmentation options set but discardMdatData is true, samples will not be segmented")}unsetSegmentOptions(e){let t=-1;for(let s=0;s<this.fragmentedTracks.length;s++)this.fragmentedTracks[s].id===e&&(t=s);t>-1&&this.fragmentedTracks.splice(t,1)}setExtractionOptions(e,t,{nbSamples:s=1e3}={}){const r=this.getTrackById(e);r&&(this.extractedTracks.push({id:e,user:t,trak:r,nb_samples:s,samples:[]}),r.nextSample=0),this.discardMdatData&&I.warn("ISOFile","Extraction options set but discardMdatData is true, samples will not be extracted")}unsetExtractionOptions(e){let t=-1;for(let s=0;s<this.extractedTracks.length;s++)this.extractedTracks[s].id===e&&(t=s);t>-1&&this.extractedTracks.splice(t,1)}parse(){if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else{this.saveParsePosition&&this.saveParsePosition();const e=ht(this.stream,!1);if(e.code===Wt)if(this.processIncompleteBox){if(this.processIncompleteBox(e))continue;return}else return;else if(e.code===We){const t=e.box;if(this.boxes.push(t),t.type==="uuid")this[t.uuid]!==void 0&&I.warn("ISOFile","Duplicate Box of uuid: "+t.uuid+", overriding previous occurrence"),this[t.uuid]=t;else switch(t.type){case"mdat":this.mdats.push(t),this.transferMdatData(t);break;case"moof":this.moofs.push(t);break;case"free":case"skip":break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[t.type]!==void 0?Array.isArray(this[t.type+"s"])?(I.info("ISOFile",`Found multiple boxes of type ${t.type} in ISOFile, adding to array`),this[t.type+"s"].push(t)):(I.warn("ISOFile",`Found multiple boxes of type ${t.type} but no array exists. Creating array dynamically.`),this[t.type+"s"]=[this[t.type],t]):(this[t.type]=t,Array.isArray(this[t.type+"s"])&&this[t.type+"s"].push(t));break}this.updateUsedBytes&&this.updateUsedBytes(t,e)}else if(e.code===xf){I.error("ISOFile",`Invalid data found while parsing box of type '${e.type}' at position ${e.start}. Aborting parsing.`,this);break}}}checkBuffer(e){if(!e)throw new Error("Buffer must be defined and non empty");return e.byteLength===0?(I.warn("ISOFile","Ignoring empty buffer (fileStart: "+e.fileStart+")"),this.stream.logBufferLevel(),!1):(I.info("ISOFile","Processing buffer (fileStart: "+e.fileStart+")"),e.usedBytes=0,this.stream.insertBuffer(e),this.stream.logBufferLevel(),this.stream.initialized()?!0:(I.warn("ISOFile","Not ready to start parsing"),!1))}appendBuffer(e,t){let s;if(this.checkBuffer(e))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(t),this.nextSeekPosition?(s=this.nextSeekPosition,this.nextSeekPosition=void 0):s=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(s=this.stream.getEndFilePositionAfter(s))):this.nextParsePosition?s=this.nextParsePosition:s=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(I.info("ISOFile","Done processing buffer (fileStart: "+e.fileStart+") - next buffer to fetch should have a fileStart position of "+s),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),I.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),s}getFragmentDuration(){const e=this.getBox("mvex");if(!e)return;if(e.mehd)return{num:e.mehd.fragment_duration,den:this.moov.mvhd.timescale};const t=this.getBoxes("trak",!1);let s={num:0,den:1};for(const r of t){const n=r.samples_duration,o=r.mdia.mdhd.timescale;n&&o&&n/o>s.num/s.den&&(s={num:n,den:o})}return s}getInfo(){if(!this.moov)return{hasMoov:!1,mime:""};const e=new Date("1904-01-01T00:00:00Z").getTime(),t=this.getBox("mvex")!==void 0,s={hasMoov:!0,duration:this.moov.mvhd.duration,timescale:this.moov.mvhd.timescale,isFragmented:t,fragment_duration:this.getFragmentDuration(),isProgressive:this.isProgressive,hasIOD:this.moov.iods!==void 0,brands:[this.ftyp.major_brand].concat(this.ftyp.compatible_brands),created:new Date(e+this.moov.mvhd.creation_time*1e3),modified:new Date(e+this.moov.mvhd.modification_time*1e3),tracks:[],audioTracks:[],videoTracks:[],subtitleTracks:[],metadataTracks:[],hintTracks:[],otherTracks:[],mime:""};for(let r=0;r<this.moov.traks.length;r++){const n=this.moov.traks[r],o=n.mdia.minf.stbl.stsd.entries[0],a=n.samples_size,l=n.mdia.mdhd.timescale,c=n.samples_duration,h=a*8*l/c,u={samples_duration:c,bitrate:h,size:a,timescale:l,alternate_group:n.tkhd.alternate_group,codec:o.getCodec(),created:new Date(e+n.tkhd.creation_time*1e3),cts_shift:n.mdia.minf.stbl.cslg,duration:n.mdia.mdhd.duration,id:n.tkhd.track_id,kind:n.udta&&n.udta.kinds.length?n.udta.kinds[0]:{schemeURI:"",value:""},language:n.mdia.elng?n.mdia.elng.extended_language:n.mdia.mdhd.languageString,layer:n.tkhd.layer,matrix:n.tkhd.matrix,modified:new Date(e+n.tkhd.modification_time*1e3),movie_duration:n.tkhd.duration,movie_timescale:s.timescale,name:n.mdia.hdlr.name,nb_samples:n.samples.length,references:[],track_height:n.tkhd.height/65536,track_width:n.tkhd.width/65536,volume:n.tkhd.volume};if(s.tracks.push(u),n.tref)for(let d=0;d<n.tref.references.length;d++)u.references.push({type:n.tref.references[d].type,track_ids:n.tref.references[d].track_ids});n.edts!==void 0&&n.edts.elst!==void 0&&(u.edits=n.edts.elst.entries),o instanceof ze?(u.type="audio",s.audioTracks.push(u),u.audio={sample_rate:o.getSampleRate(),channel_count:o.getChannelCount(),sample_size:o.getSampleSize()}):o instanceof fe?(u.type="video",s.videoTracks.push(u),u.video={width:o.getWidth(),height:o.getHeight()}):o instanceof $t?(u.type="subtitles",s.subtitleTracks.push(u)):o instanceof In?(u.type="metadata",s.hintTracks.push(u)):o instanceof ni?(u.type="metadata",s.metadataTracks.push(u)):(u.type="metadata",s.otherTracks.push(u))}s.videoTracks&&s.videoTracks.length>0?s.mime+='video/mp4; codecs="':s.audioTracks&&s.audioTracks.length>0?s.mime+='audio/mp4; codecs="':s.mime+='application/mp4; codecs="';for(let r=0;r<s.tracks.length;r++)r!==0&&(s.mime+=","),s.mime+=s.tracks[r].codec;return s.mime+='"; profiles="',s.mime+=this.ftyp.compatible_brands.join(),s.mime+='"',s}setNextSeekPositionFromSample(e){e&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(e.offset+e.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=e.offset+e.alreadyRead)}processSamples(e){if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==void 0){const t=new Set;for(;t.size<this.fragmentedTracks.length&&this.fragmentedTracks.some(s=>s.trak.nextSample<s.trak.samples.length)&&this.sampleProcessingStarted;)for(const s of this.fragmentedTracks){const r=s.trak;if(!t.has(s.id)){const n=r.nextSample<r.samples.length?this.getSample(r,r.nextSample):void 0;if(!n){this.setNextSeekPositionFromSample(r.samples[r.nextSample]),t.add(s.id);continue}s.state.accumulatedSize+=n.size;const o=r.nextSample+1,a=o-s.state.lastFragmentSampleNumber>s.nb_samples_per_fragment,l=o-s.state.lastSegmentSampleNumber>s.nb_samples;let c=a||o%s.nb_samples_per_fragment===0,h=l||o%s.nb_samples===0,u=s.state.accumulatedSize>=s.size_per_segment;const d=!s.rapAlignement||n.is_sync,f=e||r.nextSample+1>=r.samples.length;if(f&&!d&&I.warn("ISOFile","Flushing track #"+s.id+" at sample #"+r.nextSample+" which is not a RAP, this may lead to playback issues"),c=c&&d,h=h&&d,u=u&&d,c||u||f){a?I.warn("ISOFile","Fragment on track #"+s.id+" is overdue, creating it with samples ["+s.state.lastFragmentSampleNumber+", "+r.nextSample+"]"):I.debug("ISOFile","Creating media fragment on track #"+s.id+" for samples ["+s.state.lastFragmentSampleNumber+", "+r.nextSample+"]");const p=this.createFragment(s.id,s.state.lastFragmentSampleNumber,r.nextSample,s.segmentStream);if(p)s.segmentStream=p,s.state.lastFragmentSampleNumber=r.nextSample+1;else{t.add(s.id);continue}}(h||u||f)&&(l?I.warn("ISOFile","Segment on track #"+s.id+" is overdue, sending it with samples ["+Math.max(0,r.nextSample-s.nb_samples)+", "+(r.nextSample-1)+"]"):I.info("ISOFile","Sending fragmented data on track #"+s.id+" for samples ["+Math.max(0,r.nextSample-s.nb_samples)+", "+(r.nextSample-1)+"]"),I.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(s.id,s.user,s.segmentStream.buffer,r.nextSample+1,e||r.nextSample+1>=r.samples.length),s.segmentStream=void 0,s.state.accumulatedSize=0,s.state.lastSegmentSampleNumber=r.nextSample+1),r.nextSample++}}}if(this.onSamples!==void 0)for(let t=0;t<this.extractedTracks.length;t++){const s=this.extractedTracks[t],r=s.trak;for(;r.nextSample<r.samples.length&&this.sampleProcessingStarted;){I.debug("ISOFile","Exporting on track #"+s.id+" sample #"+r.nextSample);const n=this.getSample(r,r.nextSample);if(n)r.nextSample++,s.samples.push(n);else{this.setNextSeekPositionFromSample(r.samples[r.nextSample]);break}if((r.nextSample%s.nb_samples===0||r.nextSample>=r.samples.length)&&(I.debug("ISOFile","Sending samples on track #"+s.id+" for sample "+r.nextSample),this.onSamples&&this.onSamples(s.id,s.user,s.samples),s.samples=[],s!==this.extractedTracks[t]))break}}}}getBox(e){const t=this.getBoxes(e,!0);return t.length?t[0]:void 0}getBoxes(e,t){const s=[],r=n=>{n instanceof B&&n.type&&n.type===e&&s.push(n);const o=[];n.boxes&&o.push(...n.boxes),n.entries&&o.push(...n.entries),n.item_infos&&o.push(...n.item_infos),n.references&&o.push(...n.references);for(const a of o){if(s.length&&t)return;r(a)}};return r(this),s}getTrackSamplesInfo(e){const t=this.getTrackById(e);if(t)return t.samples}getTrackSample(e,t){const s=this.getTrackById(e);return this.getSample(s,t)}releaseUsedSamples(e,t){let s=0;const r=this.getTrackById(e);r.lastValidSample||(r.lastValidSample=0);for(let n=r.lastValidSample;n<t;n++)s+=this.releaseSample(r,n);I.info("ISOFile","Track #"+e+" released samples up to "+t+" (released size: "+s+", remaining: "+this.samplesDataSize+")"),r.lastValidSample=t}start(){this.sampleProcessingStarted=!0,this.processSamples(!1)}stop(){this.sampleProcessingStarted=!1}flush(){I.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)}seekTrack(e,t,s){let r=0,n=0,o;if(s.samples.length===0)return I.info("ISOFile","No sample in track, cannot seek! Using time "+I.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(let l=0;l<s.samples.length;l++){const c=s.samples[l];if(l===0)n=0,o=c.timescale;else if(c.cts>e*c.timescale){n=l-1;break}t&&c.is_sync&&(r=l)}for(t&&(n=r),e=s.samples[n].cts,s.nextSample=n;s.samples[n].alreadyRead===s.samples[n].size&&s.samples[n+1];)n++;const a=s.samples[n].offset+s.samples[n].alreadyRead;return I.info("ISOFile","Seeking to "+(t?"RAP":"")+" sample #"+s.nextSample+" on track "+s.tkhd.track_id+", time "+I.getDurationString(e,o)+" and offset: "+a),{offset:a,time:e/o}}getTrackDuration(e){if(!e.samples)return 1/0;const t=e.samples[e.samples.length-1];return(t.cts+t.duration)/t.timescale}seek(e,t){const s=this.moov;let r={offset:1/0,time:1/0};if(this.moov){for(let n=0;n<s.traks.length;n++){const o=s.traks[n];if(e>this.getTrackDuration(o))continue;const a=this.seekTrack(e,t,o);a.offset<r.offset&&(r.offset=a.offset),a.time<r.time&&(r.time=a.time)}return I.info("ISOFile","Seeking at time "+I.getDurationString(r.time,1)+" needs a buffer with a fileStart position of "+r.offset),r.offset===1/0?r={offset:this.nextParsePosition,time:0}:r.offset=this.stream.getEndFilePositionAfter(r.offset),I.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+r.offset),r}else throw new Error("Cannot seek: moov not received!")}equal(e){let t=0;for(;t<this.boxes.length&&t<e.boxes.length;){const s=this.boxes[t],r=e.boxes[t];if(!Cn(s,r))return!1;t++}return!0}write(e){for(let t=0;t<this.boxes.length;t++)this.boxes[t].write(e)}createFragment(e,t,s,r){const n=[];for(let h=t;h<=s;h++){const u=this.getTrackById(e),d=this.getSample(u,h);if(!d){this.setNextSeekPositionFromSample(u.samples[h]);return}n.push(d)}const o=r||new Pe,a=this.createMoof(n);a.write(o),a.trafs[0].truns[0].data_offset=a.size+8,I.debug("MP4Box","Adjusting data_offset with new value "+a.trafs[0].truns[0].data_offset),o.adjustUint32(a.trafs[0].truns[0].data_offset_position,a.trafs[0].truns[0].data_offset);const l=new lr;l.stream=new Ti;let c=0;for(const h of n)if(h.data){const u=_t.fromArrayBuffer(h.data.buffer,c);l.stream.insertBuffer(u),c+=h.data.byteLength}return l.write(o),o}static writeInitializationSegment(e,t,s){I.debug("ISOFile","Generating initialization segment");const r=new Pe;e.write(r);const n=t.addBox(new Kn);if(s){const o=n.addBox(new Xf);o.fragment_duration=s}for(let o=0;o<t.traks.length;o++){const a=n.addBox(new ja);a.track_id=t.traks[o].tkhd.track_id,a.default_sample_description_index=1,a.default_sample_duration=t.traks[o].samples[0]?.duration??0,a.default_sample_size=0,a.default_sample_flags=65536}return t.write(r),r.buffer}save(e){const t=new Pe;return t.isofile=this,this.write(t),t.save(e)}getBuffer(){const e=new Pe;return e.isofile=this,this.write(e),e}initializeSegmentation(){this.onSegment||I.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.resetTables());const e=new Ln;e.addBox(this.moov.mvhd);for(let t=0;t<this.fragmentedTracks.length;t++){const s=this.getTrackById(this.fragmentedTracks[t].id);if(!s){I.warn("ISOFile",`Track with id ${this.fragmentedTracks[t].id} not found, skipping fragmentation initialization`);continue}e.addBox(s)}return{tracks:e.traks.map((t,s)=>({id:t.tkhd.track_id,user:this.fragmentedTracks[s].user})),buffer:ii.writeInitializationSegment(this.ftyp,e,this.moov?.mvex?.mehd.fragment_duration)}}resetTables(){this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0;for(let e=0;e<this.moov.traks.length;e++){const t=this.moov.traks[e];t.tkhd.duration=0,t.mdia.mdhd.duration=0;const s=t.mdia.minf.stbl.stco||t.mdia.minf.stbl.co64;s.chunk_offsets=[];const r=t.mdia.minf.stbl.stsc;r.first_chunk=[],r.samples_per_chunk=[],r.sample_description_index=[];const n=t.mdia.minf.stbl.stsz||t.mdia.minf.stbl.stz2;n.sample_sizes=[];const o=t.mdia.minf.stbl.stts;o.sample_counts=[],o.sample_deltas=[];const a=t.mdia.minf.stbl.ctts;a&&(a.sample_counts=[],a.sample_offsets=[]);const l=t.mdia.minf.stbl.stss,c=t.mdia.minf.stbl.boxes.indexOf(l);c!==-1&&(t.mdia.minf.stbl.boxes[c]=void 0)}}static initSampleGroups(e,t,s,r,n){t&&(t.sample_groups_info=[]),e.sample_groups_info||(e.sample_groups_info=[]);for(let o=0;o<s.length;o++){const a=s[o].grouping_type+"/"+s[o].grouping_type_parameter,l=new dr(s[o].grouping_type,s[o].grouping_type_parameter,s[o]);t&&(t.sample_groups_info[a]=l),e.sample_groups_info[a]||(e.sample_groups_info[a]=l);for(let c=0;c<r.length;c++)r[c].grouping_type===s[o].grouping_type&&(l.description=r[c],l.description.used=!0);if(n)for(let c=0;c<n.length;c++)n[c].grouping_type===s[o].grouping_type&&(l.fragment_description=n[c],l.fragment_description.used=!0,l.is_fragment=!0)}if(t){if(n){for(let o=0;o<n.length;o++)if(!n[o].used&&n[o].version>=2){const a=n[o].grouping_type+"/0",l=new dr(n[o].grouping_type,0);l.is_fragment=!0,t.sample_groups_info[a]||(t.sample_groups_info[a]=l)}}}else for(let o=0;o<r.length;o++)if(!r[o].used&&r[o].version>=2){const a=r[o].grouping_type+"/0",l=new dr(r[o].grouping_type,0);e.sample_groups_info[a]||(e.sample_groups_info[a]=l)}}static setSampleGroupProperties(e,t,s,r){t.sample_groups=[];for(const n in r)if(t.sample_groups[n]={grouping_type:r[n].grouping_type,grouping_type_parameter:r[n].grouping_type_parameter},s>=r[n].last_sample_in_run&&(r[n].last_sample_in_run<0&&(r[n].last_sample_in_run=0),r[n].entry_index++,r[n].entry_index<=r[n].sbgp.entries.length-1&&(r[n].last_sample_in_run+=r[n].sbgp.entries[r[n].entry_index].sample_count)),r[n].entry_index<=r[n].sbgp.entries.length-1?t.sample_groups[n].group_description_index=r[n].sbgp.entries[r[n].entry_index].group_description_index:t.sample_groups[n].group_description_index=-1,t.sample_groups[n].group_description_index!==0){let o;if(r[n].fragment_description?o=r[n].fragment_description:o=r[n].description,t.sample_groups[n].group_description_index>0){let a;t.sample_groups[n].group_description_index>65535?a=(t.sample_groups[n].group_description_index>>16)-1:a=t.sample_groups[n].group_description_index-1,o&&a>=0&&(t.sample_groups[n].description=o.entries[a])}else o&&o.version>=2&&o.default_group_description_index>0&&(t.sample_groups[n].description=o.entries[o.default_group_description_index-1])}}static process_sdtp(e,t,s){t&&(e?(t.is_leading=e.is_leading[s],t.depends_on=e.sample_depends_on[s],t.is_depended_on=e.sample_is_depended_on[s],t.has_redundancy=e.sample_has_redundancy[s]):(t.is_leading=0,t.depends_on=0,t.is_depended_on=0,t.has_redundancy=0))}buildSampleLists(){for(let e=0;e<this.moov.traks.length;e++)this.buildTrakSampleLists(this.moov.traks[e])}buildTrakSampleLists(e){let t,s,r,n,o,a;e.samples=[],e.samples_duration=0,e.samples_size=0;const l=e.mdia.minf.stbl.stco||e.mdia.minf.stbl.co64,c=e.mdia.minf.stbl.stsc,h=e.mdia.minf.stbl.stsz||e.mdia.minf.stbl.stz2,u=e.mdia.minf.stbl.stts,d=e.mdia.minf.stbl.ctts,f=e.mdia.minf.stbl.stss,p=e.mdia.minf.stbl.stsd,g=e.mdia.minf.stbl.subs,m=e.mdia.minf.stbl.stdp,x=e.mdia.minf.stbl.sbgps,_=e.mdia.minf.stbl.sgpds;let y=-1,v=-1,T=-1,S=-1,w=0,E=0,P=0;if(ii.initSampleGroups(e,void 0,x,_),!(typeof h>"u")){for(t=0;t<h.sample_sizes.length;t++){const C={number:t,track_id:e.tkhd.track_id,timescale:e.mdia.mdhd.timescale,alreadyRead:0,size:h.sample_sizes[t]};e.samples[t]=C,e.samples_size+=C.size,t===0?(r=1,s=0,C.chunk_index=r,C.chunk_run_index=s,a=c.samples_per_chunk[s],o=0,s+1<c.first_chunk.length?n=c.first_chunk[s+1]-1:n=1/0):t<a?(C.chunk_index=r,C.chunk_run_index=s):(r++,C.chunk_index=r,o=0,r<=n||(s++,s+1<c.first_chunk.length?n=c.first_chunk[s+1]-1:n=1/0),C.chunk_run_index=s,a+=c.samples_per_chunk[s]),C.description_index=c.sample_description_index[C.chunk_run_index]-1,C.description=p.entries[C.description_index],C.offset=l.chunk_offsets[C.chunk_index-1]+o,o+=C.size,t>y&&(v++,y<0&&(y=0),y+=u.sample_counts[v]),t>0?(e.samples[t-1].duration=u.sample_deltas[v],e.samples_duration+=e.samples[t-1].duration,C.dts=e.samples[t-1].dts+e.samples[t-1].duration):C.dts=0,d?(t>=T&&(S++,T<0&&(T=0),T+=d.sample_counts[S]),C.cts=e.samples[t].dts+d.sample_offsets[S]):C.cts=C.dts,f?(t===f.sample_numbers[w]-1?(C.is_sync=!0,w++):(C.is_sync=!1,C.degradation_priority=0),g&&g.entries[E].sample_delta+P===t+1&&(C.subsamples=g.entries[E].subsamples,P+=g.entries[E].sample_delta,E++)):C.is_sync=!0,ii.process_sdtp(e.mdia.minf.stbl.sdtp,C,C.number),m?C.degradation_priority=m.priority[t]:C.degradation_priority=0,g&&g.entries[E].sample_delta+P===t&&(C.subsamples=g.entries[E].subsamples,P+=g.entries[E].sample_delta),(x.length>0||_.length>0)&&ii.setSampleGroupProperties(e,C,t,e.sample_groups_info)}t>0&&(e.samples[t-1].duration=Math.max(e.mdia.mdhd.duration-e.samples[t-1].dts,0),e.samples_duration+=e.samples[t-1].duration)}}updateSampleLists(){let e,t,s,r,n;if(this.moov!==void 0)for(;this.lastMoofIndex<this.moofs.length;){const o=this.moofs[this.lastMoofIndex];if(this.lastMoofIndex++,o.type==="moof"){const a=o;for(let l=0;l<a.trafs.length;l++){const c=a.trafs[l],h=this.getTrackById(c.tfhd.track_id),u=this.getTrexById(c.tfhd.track_id);c.tfhd.flags&Zs?e=c.tfhd.default_sample_description_index:e=u?u.default_sample_description_index:1,c.tfhd.flags&Js?t=c.tfhd.default_sample_duration:t=u?u.default_sample_duration:0,c.tfhd.flags&Qs?s=c.tfhd.default_sample_size:s=u?u.default_sample_size:0,c.tfhd.flags&er?r=c.tfhd.default_sample_flags:r=u?u.default_sample_flags:0,c.sample_number=0,c.sbgps.length>0&&ii.initSampleGroups(h,c,c.sbgps,h.mdia.minf.stbl.sgpds,c.sgpds);for(let d=0;d<c.truns.length;d++){const f=c.truns[d];for(let p=0;p<f.sample_count;p++){const g=e-1;let m=r;f.flags&rs?m=f.sample_flags[p]:p===0&&f.flags&tr&&(m=f.first_sample_flags);let x=s;f.flags&ss&&(x=f.sample_size[p]),h.samples_size+=x;let _=t;f.flags&is&&(_=f.sample_duration[p]),h.samples_duration+=_;let y;h.first_traf_merged||p>0?y=h.samples[h.samples.length-1].dts+h.samples[h.samples.length-1].duration:(c.tfdt?y=c.tfdt.baseMediaDecodeTime:y=0,h.first_traf_merged=!0);let v=y;f.flags&ns&&(v=y+f.sample_composition_time_offset[p]);const T=!!(c.tfhd.flags&js),S=!!(c.tfhd.flags&gf),w=!!(f.flags&ts);let E=0;T?E=c.tfhd.base_data_offset:S||d===0?E=a.start:E=n;let P;d===0&&p===0?w?P=E+f.data_offset:P=E:P=n,n=P+x;const C=c.sample_number;c.sample_number++;const A={cts:v,description_index:g,description:h.mdia.minf.stbl.stsd.entries[g],dts:y,duration:_,moof_number:this.lastMoofIndex,number_in_traf:C,number:h.samples.length,offset:P,size:x,timescale:h.mdia.mdhd.timescale,track_id:h.tkhd.track_id,is_sync:!(m>>16&1),is_leading:m>>26&3,depends_on:m>>24&3,is_depended_on:m>>22&3,has_redundancy:m>>20&3,degradation_priority:m&65535};c.first_sample_index=h.samples.length,h.samples.push(A),(c.sbgps.length>0||c.sgpds.length>0||h.mdia.minf.stbl.sbgps.length>0||h.mdia.minf.stbl.sgpds.length>0)&&ii.setSampleGroupProperties(h,A,A.number_in_traf,c.sample_groups_info)}}if(c.subs){h.has_fragment_subsamples=!0;let d=c.first_sample_index;for(let f=0;f<c.subs.entries.length;f++){d+=c.subs.entries[f].sample_delta;const p=h.samples[d-1];p.subsamples=c.subs.entries[f].subsamples}}}}}}getSample(e,t){const s=e.samples[t];if(this.moov){if(!s.data)s.data=new Uint8Array(s.size),s.alreadyRead=0,this.samplesDataSize+=s.size,I.debug("ISOFile","Allocating sample #"+t+" on track #"+e.tkhd.track_id+" of size "+s.size+" (total: "+this.samplesDataSize+")");else if(s.alreadyRead===s.size)return s;for(;;){let r=this.stream,n=r.findPosition(!0,s.offset+s.alreadyRead,!1),o,a;if(n>-1)o=r.buffers[n],a=o.fileStart;else for(const l of this.mdats){if(!l.stream){I.debug("ISOFile","mdat stream not yet fully read for #"+this.mdats.indexOf(l)+" mdat");continue}if(n=l.stream.findPosition(!0,s.offset+s.alreadyRead-l.start-l.hdr_size,!1),n>-1){r=l.stream,o=l.stream.buffers[n],a=l.start+l.hdr_size+o.fileStart;break}}if(o){const l=o.byteLength-(s.offset+s.alreadyRead-a);if(s.size-s.alreadyRead<=l)return I.debug("ISOFile","Getting sample #"+t+" data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-a)+" read size: "+(s.size-s.alreadyRead)+" full size: "+s.size+")"),Pe.memcpy(s.data.buffer,s.alreadyRead,o,s.offset+s.alreadyRead-a,s.size-s.alreadyRead),o.usedBytes+=s.size-s.alreadyRead,r.logBufferLevel(),s.alreadyRead=s.size,s;if(l===0)return;I.debug("ISOFile","Getting sample #"+t+" partial data (alreadyRead: "+s.alreadyRead+" offset: "+(s.offset+s.alreadyRead-a)+" read size: "+l+" full size: "+s.size+")"),Pe.memcpy(s.data.buffer,s.alreadyRead,o,s.offset+s.alreadyRead-a,l),s.alreadyRead+=l,o.usedBytes+=l,r.logBufferLevel()}else return}}}releaseSample(e,t){const s=e.samples[t];return s.data?(this.samplesDataSize-=s.size,s.data=void 0,s.alreadyRead=0,s.size):0}getAllocatedSampleDataSize(){return this.samplesDataSize}getCodecs(){let e="";for(let t=0;t<this.moov.traks.length;t++){const s=this.moov.traks[t];t>0&&(e+=","),e+=s.mdia.minf.stbl.stsd.entries[0].getCodec()}return e}getTrexById(e){if(!(!this.moov||!this.moov.mvex))for(let t=0;t<this.moov.mvex.trexs.length;t++){const s=this.moov.mvex.trexs[t];if(s.track_id===e)return s}}getTrackById(e){if(this.moov)for(let t=0;t<this.moov.traks.length;t++){const s=this.moov.traks[t];if(s.tkhd.track_id===e)return s}}flattenItemInfo(){const e=this.items,t=this.entity_groups,s=this.meta;if(!(!s||!s.hdlr||!s.iinf)){for(let r=0;r<s.iinf.item_infos.length;r++){const n=s.iinf.item_infos[r].item_ID;e[n]={id:n,name:s.iinf.item_infos[r].item_name,ref_to:[],content_type:s.iinf.item_infos[r].content_type,content_encoding:s.iinf.item_infos[r].content_encoding,item_uri_type:s.iinf.item_infos[r].item_uri_type,type:s.iinf.item_infos[r].item_type?s.iinf.item_infos[r].item_type:"mime",protection:s.iinf.item_infos[r].item_protection_index>0?s.ipro.protections[s.iinf.item_infos[r].item_protection_index-1]:void 0}}if(s.grpl)for(let r=0;r<s.grpl.boxes.length;r++){const n=s.grpl.boxes[r];t[n.group_id]={id:n.group_id,entity_ids:n.entity_ids,type:n.type}}if(s.iloc)for(let r=0;r<s.iloc.items.length;r++){const n=s.iloc.items[r],o=e[n.item_ID];n.data_reference_index!==0&&(I.warn("Item storage with reference to other files: not supported"),o.source=s.dinf.boxes[n.data_reference_index-1]),o.extents=[],o.size=0;for(let a=0;a<n.extents.length;a++)o.extents[a]={offset:n.extents[a].extent_offset+n.base_offset,length:n.extents[a].extent_length,alreadyRead:0},n.construction_method===1&&(o.extents[a].offset+=s.idat.start+s.idat.hdr_size),o.size+=o.extents[a].length}if(s.pitm&&(e[s.pitm.item_id].primary=!0),s.iref)for(let r=0;r<s.iref.references.length;r++){const n=s.iref.references[r];for(let o=0;o<n.references.length;o++)e[n.from_item_ID].ref_to.push({type:n.type,id:n.references[o]})}if(s.iprp)for(let r=0;r<s.iprp.ipmas.length;r++){const n=s.iprp.ipmas[r];for(let o=0;o<n.associations.length;o++){const a=n.associations[o],l=e[a.id]??t[a.id];if(l){l.properties===void 0&&(l.properties={boxes:[]});for(let c=0;c<a.props.length;c++){const h=a.props[c];if(h.property_index>0&&h.property_index-1<s.iprp.ipco.boxes.length){const u=s.iprp.ipco.boxes[h.property_index-1];l.properties[u.type]=u,l.properties.boxes.push(u)}}}}}}}getItem(e){if(!this.meta)return;const t=this.items[e];if(!t.data&&t.size)t.data=new Uint8Array(t.size),t.alreadyRead=0,this.itemsDataSize+=t.size,I.debug("ISOFile","Allocating item #"+e+" of size "+t.size+" (total: "+this.itemsDataSize+")");else if(t.alreadyRead===t.size)return t;for(let s=0;s<t.extents.length;s++){const r=t.extents[s];if(r.alreadyRead!==r.length){const n=this.stream.findPosition(!0,r.offset+r.alreadyRead,!1);if(n>-1){const o=this.stream.buffers[n],a=o.byteLength-(r.offset+r.alreadyRead-o.fileStart);if(r.length-r.alreadyRead<=a)I.debug("ISOFile","Getting item #"+e+" extent #"+s+" data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-o.fileStart)+" read size: "+(r.length-r.alreadyRead)+" full extent size: "+r.length+" full item size: "+t.size+")"),Pe.memcpy(t.data.buffer,t.alreadyRead,o,r.offset+r.alreadyRead-o.fileStart,r.length-r.alreadyRead),(!this.parsingMdat||this.discardMdatData)&&(o.usedBytes+=r.length-r.alreadyRead),this.stream.logBufferLevel(),t.alreadyRead+=r.length-r.alreadyRead,r.alreadyRead=r.length;else{I.debug("ISOFile","Getting item #"+e+" extent #"+s+" partial data (alreadyRead: "+r.alreadyRead+" offset: "+(r.offset+r.alreadyRead-o.fileStart)+" read size: "+a+" full extent size: "+r.length+" full item size: "+t.size+")"),Pe.memcpy(t.data.buffer,t.alreadyRead,o,r.offset+r.alreadyRead-o.fileStart,a),r.alreadyRead+=a,t.alreadyRead+=a,(!this.parsingMdat||this.discardMdatData)&&(o.usedBytes+=a),this.stream.logBufferLevel();return}}else return}}if(t.alreadyRead===t.size)return t}releaseItem(e){const t=this.items[e];if(t.data){this.itemsDataSize-=t.size,t.data=void 0,t.alreadyRead=0;for(let s=0;s<t.extents.length;s++){const r=t.extents[s];r.alreadyRead=0}return t.size}else return 0}processItems(e){for(const t in this.items){const s=this.items[t];this.getItem(s.id),e&&!s.sent&&(e(s),s.sent=!0,s.data=void 0)}}hasItem(e){for(const t in this.items){const s=this.items[t];if(s.name===e)return s.id}return-1}getMetaHandler(){if(this.meta)return this.meta.hdlr.handler}getPrimaryItem(){if(this.meta&&this.meta.pitm)return this.getItem(this.meta.pitm.item_id)}itemToFragmentedTrackFile({itemId:e}={}){let t;if(e?t=this.getItem(e):t=this.getPrimaryItem(),!t)return;const s=new ii;s.discardMdatData=!1;const r={type:t.type,description_boxes:t.properties.boxes};t.properties.ispe&&(r.width=t.properties.ispe.image_width,r.height=t.properties.ispe.image_height);const n=s.addTrack(r);if(n)return s.addSample(n,t.data),s}processIncompleteBox(e){if(e.type==="mdat"){const t=new lr(e.size);return this.parsingMdat=t,this.boxes.push(t),this.mdats.push(t),t.start=e.start,t.hdr_size=e.hdr_size,t.original_size=e.original_size,this.stream.addUsedBytes(t.hdr_size),this.lastBoxStartPosition=t.start+t.size,this.stream.seek(t.start+t.size,!1,this.discardMdatData)?(this.transferMdatData(),this.parsingMdat=void 0,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=t.start+t.size,!1)}else return e.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),this.stream.mergeNextBuffer&&this.stream.mergeNextBuffer()?(this.nextParsePosition=this.stream.getEndPosition(),!0):(e.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+e.size:this.nextParsePosition=this.stream.getEndPosition(),!1)}hasIncompleteMdat(){return this.parsingMdat!==void 0}transferMdatData(e){const t=e??this.parsingMdat;if(this.discardMdatData){I.debug("ISOFile","Discarding 'mdat' data, not transferring it to the mdat box stream");return}if(!t){I.warn("ISOFile","Cannot transfer 'mdat' data, no mdat box is being parsed");return}const s=this.stream.findPosition(!0,t.start+t.hdr_size,!1),r=this.stream.findPosition(!0,t.start+t.size,!1);if(s===-1||r===-1){I.warn("ISOFile","Cannot transfer 'mdat' data, start or end buffer not found");return}t.stream=new Ti;for(let n=s;n<=r;n++){const o=this.stream.buffers[n],a=n===s?t.start+t.hdr_size-o.fileStart:0,l=n===r?t.start+t.size-o.fileStart:o.byteLength;if(l>a){I.debug("ISOFile","Transferring 'mdat' data from buffer #"+n+" ("+a+" to "+l+")");const c=l-a,h=new _t(c),u=t.stream.getAbsoluteEndPosition();Pe.memcpy(h,0,o,a,c),h.fileStart=u,t.stream.insertBuffer(h),o.usedBytes+=c}}}processIncompleteMdat(){const e=this.parsingMdat;return this.stream.seek(e.start+e.size,!1,this.discardMdatData)?(I.debug("ISOFile","Found 'mdat' end in buffered data"),this.transferMdatData(),this.parsingMdat=void 0,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)}restoreParsePosition(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)}saveParsePosition(){this.lastBoxStartPosition=this.stream.getPosition()}updateUsedBytes(e,t){this.stream.addUsedBytes&&(e.type==="mdat"?(this.stream.addUsedBytes(e.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(e.size-e.hdr_size)):this.stream.addUsedBytes(e.size))}addBox(e){return B.prototype.addBox.call(this,e)}init(e={}){const t=this.addBox(new Hf);t.major_brand=e.brands&&e.brands[0]||"iso4",t.minor_version=0,t.compatible_brands=e.brands||["iso4"];const s=this.addBox(new Ln);s.addBox(new Kn);const r=s.addBox(new qf);return r.timescale=e.timescale||600,r.rate=e.rate||65536,r.creation_time=0,r.modification_time=0,r.duration=e.duration||0,r.volume=e.width?0:256,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.next_track_id=1,this}addTrack(e={}){this.moov||this.init(e);const t=e||{};t.width=t.width||320,t.height=t.height||320,t.id=t.id||this.moov.mvhd.next_track_id,t.type=t.type||"avc1";const s=this.moov.addBox(new Ff);this.moov.mvhd.next_track_id=t.id+1;const r=s.addBox(new ap);r.flags=by|Ty|wy,r.creation_time=0,r.modification_time=0,r.track_id=t.id,r.duration=t.duration||0,r.layer=t.layer||0,r.alternate_group=0,r.volume=1,r.matrix=[65536,0,0,0,65536,0,0,0,1073741824],r.width=t.width<<16,r.height=t.height<<16;const n=s.addBox(new Bf),o=n.addBox(new $f);o.creation_time=0,o.modification_time=0,o.timescale=t.timescale||1,o.duration=t.media_duration||0,o.language=t.language||"und";const a=n.addBox(new Wf);a.handler=t.hdlr||"vide",a.name=t.name||"Track created with MP4Box.js";const l=n.addBox(new Lf);l.extended_language=t.language||"fr-FR";const c=n.addBox(new Uf),h=Ve.sampleEntry[t.type];if(!h)return;const u=new h;if(u.data_reference_index=1,u instanceof fe){const v=u,T=c.addBox(new hp);T.graphicsmode=0,T.opcolor=[0,0,0],v.width=t.width,v.height=t.height,v.horizresolution=72<<16,v.vertresolution=72<<16,v.frame_count=1,v.compressorname=t.type+" Compressor",v.depth=24,t.avcDecoderConfigRecord?v.addBox(new Mf(t.avcDecoderConfigRecord.byteLength)).parse(new Pe(t.avcDecoderConfigRecord)):t.hevcDecoderConfigRecord&&v.addBox(new Vf(t.hevcDecoderConfigRecord.byteLength)).parse(new Pe(t.hevcDecoderConfigRecord))}else if(u instanceof ze){const v=u,T=c.addBox(new Jf);T.balance=t.balance||0,v.channel_count=t.channel_count||2,v.samplesize=t.samplesize||16,v.samplerate=t.samplerate||65536}else u instanceof In?c.addBox(new kf):u instanceof $t?(c.addBox(new ep),u instanceof Zf&&(u.namespace=t.namespace||"nonamespace",u.schema_location=t.schema_location||"",u.auxiliary_mime_types=t.auxiliary_mime_types||"")):u instanceof ni?c.addBox(new cr):u instanceof ar?c.addBox(new cr):c.addBox(new cr);t.description&&u.addBox.call(u,t.description),t.description_boxes&&t.description_boxes.forEach(function(v){u.addBox.call(u,v)});const d=c.addBox(new Of).addBox(new Nf),f=new cp;f.flags=1,d.addEntry(f);const p=c.addBox(new Df);p.addBox(new ip).addEntry(u);const g=p.addBox(new rp);g.sample_counts=[],g.sample_deltas=[];const m=p.addBox(new tp);m.first_chunk=[],m.samples_per_chunk=[],m.sample_description_index=[];const x=p.addBox(new Qf);x.chunk_offsets=[];const _=p.addBox(new sp);_.sample_sizes=[];const y=this.moov.mvex.addBox(new ja);return y.track_id=t.id,y.default_sample_description_index=t.default_sample_description_index||1,y.default_sample_duration=t.default_sample_duration||0,y.default_sample_size=t.default_sample_size||0,y.default_sample_flags=t.default_sample_flags||0,this.buildTrakSampleLists(s),t.id}addSample(e,t,{sample_description_index:s,duration:r=1,cts:n=0,dts:o=0,is_sync:a=!1,is_leading:l=0,depends_on:c=0,is_depended_on:h=0,has_redundancy:u=0,degradation_priority:d=0,subsamples:f,offset:p=0}={}){const g=this.getTrackById(e);if(g===void 0)return;const m=s?s-1:0,x={number:g.samples.length,track_id:g.tkhd.track_id,timescale:g.mdia.mdhd.timescale,description_index:m,description:g.mdia.minf.stbl.stsd.entries[m],data:t,size:t.byteLength,alreadyRead:t.byteLength,duration:r,cts:n,dts:o,is_sync:a,is_leading:l,depends_on:c,is_depended_on:h,has_redundancy:u,degradation_priority:d,offset:p,subsamples:f};g.samples.push(x),g.samples_size+=x.size,g.samples_duration+=x.duration,g.first_dts===void 0&&(g.first_dts=o),this.processSamples();const _=this.addBox(this.createMoof([x]));_.computeSize(),_.trafs[0].truns[0].data_offset=_.size+8;const y=this.addBox(new lr);return y.data=new Uint8Array(t),x}createMoof(e){if(e.length===0)return;if(e.some(h=>h.track_id!==e[0].track_id))throw new Error("Cannot create moof for samples from different tracks: "+e.map(h=>h.track_id).join(", "));const t=e[0].track_id,s=this.getTrackById(t);if(!s)throw new Error("Cannot create moof for non-existing track: "+t);const r=new Gf,n=r.addBox(new Yf);n.sequence_number=++this.nextMoofNumber;const o=r.addBox(new zf),a=o.addBox(new op);a.track_id=t,a.flags=gf;const l=o.addBox(new np);l.baseMediaDecodeTime=e[0].dts-(s.first_dts||0);const c=o.addBox(new lp);c.flags=ts|is|ss|rs|ns,c.data_offset=0,c.first_sample_flags=0,c.sample_count=e.length;for(const h of e){let u=0;h.is_sync?u=1<<25:u=65536,c.sample_duration.push(h.duration),c.sample_size.push(h.size),c.sample_flags.push(u),c.sample_composition_time_offset.push(h.cts-h.dts)}return r}print(e){e.indent="";for(let t=0;t<this.boxes.length;t++)this.boxes[t]&&this.boxes[t].print(e)}};function dp(i=!1,e){return new up(e,!i)}var fp={};mf(fp,{Descriptor:()=>Xt,ES_Descriptor:()=>tl,MPEG4DescriptorParser:()=>gp});var pp=3,fr=4,el=5,mp=6,Xt=class X_{constructor(e,t){this.tag=e,this.size=t,this.descs=[]}parse(e){this.data=e.readUint8Array(this.size)}findDescriptor(e){for(let t=0;t<this.descs.length;t++)if(this.descs[t].tag===e)return this.descs[t]}parseOneDescriptor(e){let t=0;const s=e.readUint8();let r=e.readUint8();for(;r&128;)t=(t<<7)+(r&127),r=e.readUint8();t=(t<<7)+(r&127),I.debug("Descriptor","Found "+(pr[s]||"Descriptor "+s)+", size "+t+" at position "+e.getPosition());const n=pr[s]?new vb[pr[s]](t):new X_(t);return n.parse(e),n}parseRemainingDescriptors(e){const t=e.getPosition();for(;e.getPosition()<t+this.size;){const s=this.parseOneDescriptor?.(e);this.descs.push(s)}}},tl=class extends Xt{constructor(i){super(pp,i)}parse(i){if(this.ES_ID=i.readUint16(),this.flags=i.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=i.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){const e=i.readUint8();this.URL=i.readString(e),this.size-=e+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=i.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(i)}getOTI(){const i=this.findDescriptor(fr);return i?i.oti:0}getAudioConfig(){const i=this.findDescriptor(fr);if(!i)return;const e=i.findDescriptor(el);if(e&&e.data){let t=(e.data[0]&248)>>3;return t===31&&e.data.length>=2&&(t=32+((e.data[0]&7)<<3)+((e.data[1]&224)>>5)),t}}},xb=class extends Xt{constructor(i){super(fr,i)}parse(i){this.oti=i.readUint8(),this.streamType=i.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=i.readUint24(),this.maxBitrate=i.readUint32(),this.avgBitrate=i.readUint32(),this.size-=13,this.parseRemainingDescriptors(i)}},_b=class extends Xt{constructor(i){super(el,i)}},yb=class extends Xt{constructor(i){super(mp,i)}},vb={Descriptor:Xt,ES_Descriptor:tl,DecoderConfigDescriptor:xb,DecoderSpecificInfo:_b,SLConfigDescriptor:yb},pr={[pp]:"ES_Descriptor",[fr]:"DecoderConfigDescriptor",[el]:"DecoderSpecificInfo",[mp]:"SLConfigDescriptor"},gp=class{constructor(){this.parseOneDescriptor=Xt.prototype.parseOneDescriptor}getDescriptorName(i){return pr[i]}},bb=class{parseSample(i){const e=[],t=new Ti(_t.fromArrayBuffer(i.buffer,0));for(;!t.isEof();){const s=ht(t,!1);s.code===We&&s.box?.type==="vttc"&&e.push(s.box)}return e}getText(i,e,t){function s(a,l){const c=a.toString();return c.length>=l?c:new Array(l-c.length+1).join("0")+c}function r(a){const l=Math.floor(a/3600),c=Math.floor((a-l*3600)/60),h=Math.floor(a-l*3600-c*60),u=Math.floor((a-l*3600-c*60-h)*1e3);return""+s(l,2)+":"+s(c,2)+":"+s(h,2)+"."+s(u,3)}const n=this.parseSample(t);let o="";for(let a=0;a<n.length;a++){const l=n[a];o+=r(i)+" --> "+r(e)+`\r
|
|
2
|
+
`,o+=l.payl.text}return o}},Tb=class{parseSample(i){const e={resources:[],documentString:"",document:void 0},t=new Pe(i.data.buffer);if(!i.subsamples||i.subsamples.length===0)e.documentString=t.readString(i.data.length);else if(e.documentString=t.readString(i.subsamples[0].size),i.subsamples.length>1)for(let s=1;s<i.subsamples.length;s++)e.resources[s]=t.readUint8Array(i.subsamples[s].size);return typeof DOMParser<"u"&&(e.document=new DOMParser().parseFromString(e.documentString,"application/xml")),e}},wb=class{parseSample(i){return new Pe(i.data.buffer).readString(i.data.length)}parseConfig(i){const e=new Pe(i.buffer);return e.readUint32(),e.readCString()}},Sb=class{parseSample(i){const e=new Pe(i.data.buffer),t=e.readUint16();if(t!==0)return e.readString(t)}},xp={};mf(xp,{CoLLBox:()=>Db,ItemContentIDPropertyBox:()=>dw,OpusSampleEntry:()=>Kv,SmDmBox:()=>cT,a1lxBox:()=>Cb,a1opBox:()=>Ab,ac_3SampleEntry:()=>Xv,ac_4SampleEntry:()=>Yv,aebrBox:()=>t2,afbrBox:()=>i2,albcBox:()=>s2,alstSampleGroupEntry:()=>LT,altrBox:()=>r2,auxCBox:()=>Eb,av01SampleEntry:()=>bv,av1CBox:()=>dv,avc1SampleEntry:()=>xv,avc2SampleEntry:()=>_v,avc3SampleEntry:()=>yv,avc4SampleEntry:()=>vv,avcCBox:()=>Mf,avllSampleGroupEntry:()=>HT,avs3SampleEntry:()=>Gv,avssSampleGroupEntry:()=>WT,brstBox:()=>n2,btrtBox:()=>Ib,bxmlBox:()=>Oy,ccstBox:()=>Pb,cdefBox:()=>Rb,clapBox:()=>Mb,clefBox:()=>Y2,clliBox:()=>kb,cmexBox:()=>Fb,cminBox:()=>Bb,cmpdBox:()=>Ub,co64Box:()=>Ob,colrBox:()=>gv,coviBox:()=>Nb,cprtBox:()=>Lb,cschBox:()=>Hb,cslgBox:()=>Wb,cttsBox:()=>Vb,dOpsBox:()=>Zb,dac3Box:()=>$b,dataBox:()=>ls,dav1SampleEntry:()=>Tv,dec3Box:()=>Xb,dfLaBox:()=>Yb,dimmBox:()=>qb,dinfBox:()=>Of,dmax:()=>Kb,dmedBox:()=>jb,dobrBox:()=>o2,drefBox:()=>Nf,drepBox:()=>Jb,dtrtSampleGroupEntry:()=>VT,dvh1SampleEntry:()=>Rv,dvheSampleEntry:()=>Mv,ec_3SampleEntry:()=>qv,edtsBox:()=>Gy,elngBox:()=>Lf,elstBox:()=>Qb,emsgBox:()=>e2,encaSampleEntry:()=>ib,encmSampleEntry:()=>ab,encsSampleEntry:()=>rb,enctSampleEntry:()=>ob,encuSampleEntry:()=>sb,encvSampleEntry:()=>tb,enofBox:()=>K2,eqivBox:()=>a2,esdsBox:()=>fv,etypBox:()=>tv,fLaCSampleEntry:()=>eb,favcBox:()=>l2,fielBox:()=>_2,fobrBox:()=>c2,freeBox:()=>ky,frmaBox:()=>y2,ftypBox:()=>Hf,grplBox:()=>Qy,hdlrBox:()=>Wf,hev1SampleEntry:()=>Cv,hev2SampleEntry:()=>Av,hinfBox:()=>Wy,hmhdBox:()=>kf,hntiBox:()=>Hy,hvc1SampleEntry:()=>wv,hvc2SampleEntry:()=>Sv,hvcCBox:()=>Vf,hvt1SampleEntry:()=>Ev,iaugBox:()=>h2,idatBox:()=>My,iinfBox:()=>rv,ilocBox:()=>nv,ilstBox:()=>j2,imirBox:()=>v2,infeBox:()=>sv,iodsBox:()=>By,ipcoBox:()=>Jy,ipmaBox:()=>b2,iproBox:()=>Dy,iprpBox:()=>Zy,irefBox:()=>av,irotBox:()=>T2,ispeBox:()=>w2,itaiBox:()=>S2,j2kHBox:()=>ev,j2kiSampleEntry:()=>zv,keysBox:()=>Z2,kindBox:()=>C2,levaBox:()=>A2,lhe1SampleEntry:()=>Iv,lhv1SampleEntry:()=>Pv,lhvCBox:()=>E2,lselBox:()=>I2,m4aeSampleEntry:()=>$v,maxrBox:()=>P2,mdatBox:()=>lr,mdcvBox:()=>R2,mdhdBox:()=>$f,mdiaBox:()=>Bf,mecoBox:()=>Ly,mehdBox:()=>Xf,metaBox:()=>cv,mettSampleEntry:()=>hv,metxSampleEntry:()=>uv,mfhdBox:()=>Yf,mfraBox:()=>Ny,mfroBox:()=>M2,mha1SampleEntry:()=>jv,mha2SampleEntry:()=>Zv,mhm1SampleEntry:()=>Jv,mhm2SampleEntry:()=>Qv,minfBox:()=>Uf,mjp2SampleEntry:()=>Nv,mjpgSampleEntry:()=>Lv,moofBox:()=>Gf,moovBox:()=>Ln,mp4aSampleEntry:()=>Vv,mp4sSampleEntry:()=>nb,mp4vSampleEntry:()=>Wv,mskCBox:()=>k2,msrcTrackGroupTypeBox:()=>PT,mvexBox:()=>Kn,mvhdBox:()=>qf,mvifSampleGroupEntry:()=>$T,nmhdBox:()=>cr,npckBox:()=>F2,numpBox:()=>B2,padbBox:()=>O2,panoBox:()=>u2,paspBox:()=>D2,paylBox:()=>G2,paytBox:()=>z2,pdinBox:()=>N2,piffLsmBox:()=>ow,piffPsshBox:()=>aw,piffSencBox:()=>lw,piffTencBox:()=>cw,piffTfrfBox:()=>hw,piffTfxdBox:()=>uw,pitmBox:()=>lv,pixiBox:()=>L2,pmaxBox:()=>H2,povdBox:()=>iv,prdiBox:()=>W2,prfrBox:()=>V2,prftBox:()=>$2,prgrBox:()=>g2,profBox:()=>J2,prolSampleGroupEntry:()=>XT,psshBox:()=>X2,pymdBox:()=>x2,rapSampleGroupEntry:()=>YT,rashSampleGroupEntry:()=>qT,resvSampleEntry:()=>lb,rinfBox:()=>Yy,rollSampleGroupEntry:()=>KT,rtp_Box:()=>tT,saioBox:()=>iT,saizBox:()=>sT,sbgpBox:()=>fb,sbpmBox:()=>nT,sbttSampleEntry:()=>cb,schiBox:()=>qy,schmBox:()=>oT,scifSampleGroupEntry:()=>jT,scnmSampleGroupEntry:()=>ZT,sdp_Box:()=>aT,sdtpBox:()=>pb,seigSampleGroupEntry:()=>JT,sencBox:()=>lT,sgpdBox:()=>mb,sidxBox:()=>gb,sinfBox:()=>Xy,skipBox:()=>Fy,slidBox:()=>d2,smhdBox:()=>Jf,sratBox:()=>hT,ssixBox:()=>uT,stblBox:()=>Df,stcoBox:()=>Qf,stdpBox:()=>dT,sterBox:()=>f2,sthdBox:()=>ep,stppSampleEntry:()=>Zf,strdBox:()=>$y,striBox:()=>fT,strkBox:()=>Vy,stsaSampleGroupEntry:()=>QT,stscBox:()=>tp,stsdBox:()=>ip,stsgBox:()=>pT,stshBox:()=>mT,stssBox:()=>gT,stszBox:()=>sp,sttsBox:()=>rp,stviBox:()=>xT,stxtSampleEntry:()=>hb,stypBox:()=>_T,stz2Box:()=>yT,subsBox:()=>vT,syncSampleGroupEntry:()=>ew,taicBox:()=>bT,taptBox:()=>Q2,teleSampleGroupEntry:()=>tw,tencBox:()=>TT,tfdtBox:()=>np,tfhdBox:()=>op,tfraBox:()=>wT,tkhdBox:()=>ap,tmaxBox:()=>ST,tminBox:()=>CT,totlBox:()=>AT,tpayBox:()=>ET,tpylBox:()=>IT,trafBox:()=>zf,trakBox:()=>Ff,trefBox:()=>RT,trepBox:()=>MT,trexBox:()=>ja,trgrBox:()=>Ky,trpyBox:()=>kT,trunBox:()=>lp,tsasSampleGroupEntry:()=>iw,tsclSampleGroupEntry:()=>sw,tselBox:()=>FT,tsynBox:()=>p2,tx3gSampleEntry:()=>ub,txtcBox:()=>BT,tycoBox:()=>UT,udesBox:()=>OT,udtaBox:()=>jy,uncCBox:()=>DT,uncvSampleEntry:()=>Hv,urlBox:()=>cp,urnBox:()=>GT,viprSampleGroupEntry:()=>rw,vmhdBox:()=>hp,vp08SampleEntry:()=>Ov,vp09SampleEntry:()=>Dv,vpcCBox:()=>pv,vttCBox:()=>zT,vttcBox:()=>zy,vvc1SampleEntry:()=>kv,vvcCBox:()=>mv,vvcNSampleEntry:()=>Uv,vvi1SampleEntry:()=>Fv,vvnCBox:()=>NT,vvs1SampleEntry:()=>Bv,waveBox:()=>eT,wbbrBox:()=>m2,wvttSampleEntry:()=>db,xmlBox:()=>Uy});var il,Cb=(il=class extends B{constructor(){super(...arguments),this.box_name="AV1LayeredImageIndexingProperty"}parse(i){const e=((i.readUint8()&1&1)+1)*16;this.layer_size=[];for(let t=0;t<3;t++)e===16?this.layer_size[t]=i.readUint16():this.layer_size[t]=i.readUint32()}},il.fourcc="a1lx",il),sl,Ab=(sl=class extends B{constructor(){super(...arguments),this.box_name="OperatingPointSelectorProperty"}parse(i){this.op_index=i.readUint8()}},sl.fourcc="a1op",sl),rl,Eb=(rl=class extends R{constructor(){super(...arguments),this.box_name="AuxiliaryTypeProperty"}parse(i){this.parseFullHeader(i),this.aux_type=i.readCString();const e=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=i.readUint8Array(e)}},rl.fourcc="auxC",rl),nl,Ib=(nl=class extends B{constructor(){super(...arguments),this.box_name="BitRateBox"}parse(i){this.bufferSizeDB=i.readUint32(),this.maxBitrate=i.readUint32(),this.avgBitrate=i.readUint32()}},nl.fourcc="btrt",nl),ol,Pb=(ol=class extends R{constructor(){super(...arguments),this.box_name="CodingConstraintsBox"}parse(i){this.parseFullHeader(i);const e=i.readUint8();this.all_ref_pics_intra=(e&128)===128,this.intra_pred_used=(e&64)===64,this.max_ref_per_pic=(e&63)>>2,i.readUint24()}},ol.fourcc="ccst",ol),al,Rb=(al=class extends B{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}parse(i){this.channel_count=i.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[];for(let e=0;e<this.channel_count;e++)this.channel_indexes.push(i.readUint16()),this.channel_types.push(i.readUint16()),this.channel_associations.push(i.readUint16())}},al.fourcc="cdef",al),ll,Mb=(ll=class extends B{constructor(){super(...arguments),this.box_name="CleanApertureBox"}parse(i){this.cleanApertureWidthN=i.readUint32(),this.cleanApertureWidthD=i.readUint32(),this.cleanApertureHeightN=i.readUint32(),this.cleanApertureHeightD=i.readUint32(),this.horizOffN=i.readUint32(),this.horizOffD=i.readUint32(),this.vertOffN=i.readUint32(),this.vertOffD=i.readUint32()}},ll.fourcc="clap",ll),cl,kb=(cl=class extends B{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}parse(i){this.max_content_light_level=i.readUint16(),this.max_pic_average_light_level=i.readUint16()}},cl.fourcc="clli",cl),hl,Fb=(hl=class extends B{constructor(){super(...arguments),this.box_name="CameraExtrinsicMatrixProperty"}parse(i){this.flags&1&&(this.pos_x=i.readInt32()),this.flags&2&&(this.pos_y=i.readInt32()),this.flags&4&&(this.pos_z=i.readInt32()),this.flags&8&&(this.version===0?this.flags&16?(this.quat_x=i.readInt32(),this.quat_y=i.readInt32(),this.quat_z=i.readInt32()):(this.quat_x=i.readInt16(),this.quat_y=i.readInt16(),this.quat_z=i.readInt16()):this.version),this.flags&32&&(this.id=i.readUint32())}},hl.fourcc="cmex",hl),ul,Bb=(ul=class extends B{constructor(){super(...arguments),this.box_name="CameraIntrinsicMatrixProperty"}parse(i){this.focal_length_x=i.readInt32(),this.principal_point_x=i.readInt32(),this.principal_point_y=i.readInt32(),this.flags&1&&(this.focal_length_y=i.readInt32(),this.skew_factor=i.readInt32())}},ul.fourcc="cmin",ul),dl,Ub=(dl=class extends B{constructor(){super(...arguments),this.box_name="ComponentDefinitionBox"}parse(i){this.component_count=i.readUint32(),this.component_types=[],this.component_type_urls=[];for(let e=0;e<this.component_count;e++){const t=i.readUint16();this.component_types.push(t),t>=32768&&this.component_type_urls.push(i.readCString())}}},dl.fourcc="cmpd",dl),fl,Ob=(fl=class extends R{constructor(){super(...arguments),this.box_name="ChunkLargeOffsetBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.chunk_offsets=[],this.version===0)for(let t=0;t<e;t++)this.chunk_offsets.push(i.readUint64())}write(i){this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(i),i.writeUint32(this.chunk_offsets.length);for(let e=0;e<this.chunk_offsets.length;e++)i.writeUint64(this.chunk_offsets[e])}},fl.fourcc="co64",fl),pl,Db=(pl=class extends R{constructor(){super(...arguments),this.box_name="ContentLightLevelBox"}parse(i){this.parseFullHeader(i),this.maxCLL=i.readUint16(),this.maxFALL=i.readUint16()}},pl.fourcc="CoLL",pl),Gb=class{toString(){let i="centre_azimuth: ";return i+=this.centre_azimuth,i+=" (",i+=this.centre_azimuth*2**-16,i+="°), centre_elevation: ",i+=this.centre_elevation,i+=" (",i+=this.centre_elevation*2**-16,i+="°), centre_tilt: ",i+=this.centre_tilt,i+=" (",i+=this.centre_tilt*2**-16,i+="°)",this.range_included_flag&&(i+=", azimuth_range: ",i+=this.azimuth_range,i+=" (",i+=this.azimuth_range*2**-16,i+="°), elevation_range: ",i+=this.elevation_range,i+=" (",i+=this.elevation_range*2**-16,i+="°)"),this.interpolate_included_flag&&(i+=", interpolate: ",i+=this.interpolate),i}},zb=class{toString(){let i="";return this.view_idc&&(i+="view_idc: ",i+=this.view_idc,i+=", "),i+="sphere_region: {",i+=this.sphere_region,i+="}",i}},ml,Nb=(ml=class extends R{constructor(){super(...arguments),this.box_name="CoverageInformationBox"}parse(i){this.parseFullHeader(i),this.coverage_shape_type=i.readUint8();const e=i.readUint8(),t=i.readInt8(),s=t&128;s&&(this.default_view_idc=(t&96)>>5),this.coverage_regions=new Array;for(let r=0;r<e;r++){const n=new zb;s&&(n.view_idc=i.readUint8()>>6),n.sphere_region=this.parseSphereRegion(i,!0,!0),this.coverage_regions.push(n)}}parseSphereRegion(i,e,t){const s=new Gb;return s.centre_azimuth=i.readInt32(),s.centre_elevation=i.readInt32(),s.centre_tilt=i.readInt32(),s.range_included_flag=e,e&&(s.azimuth_range=i.readUint32(),s.elevation_range=i.readUint32()),s.interpolate_included_flag=t,t&&(s.interpolate=(i.readUint8()&128)===128),s}},ml.fourcc="covi",ml),gl,Lb=(gl=class extends R{constructor(){super(...arguments),this.box_name="CopyrightBox"}parse(i){this.parseFullHeader(i),this.parseLanguage(i),this.notice=i.readCString()}},gl.fourcc="cprt",gl),xl,Hb=(xl=class extends R{constructor(){super(...arguments),this.box_name="CompatibleSchemeTypeBox"}parse(i){this.parseFullHeader(i),this.scheme_type=i.readString(4),this.scheme_version=i.readUint32(),this.flags&1&&(this.scheme_uri=i.readCString())}},xl.fourcc="csch",xl),as=2147483647,_l,Wb=(_l=class extends R{constructor(){super(...arguments),this.box_name="CompositionToDecodeBox"}parse(i){this.parseFullHeader(i),this.version===0?(this.compositionToDTSShift=i.readInt32(),this.leastDecodeToDisplayDelta=i.readInt32(),this.greatestDecodeToDisplayDelta=i.readInt32(),this.compositionStartTime=i.readInt32(),this.compositionEndTime=i.readInt32()):this.version===1&&(this.compositionToDTSShift=i.readInt64(),this.leastDecodeToDisplayDelta=i.readInt64(),this.greatestDecodeToDisplayDelta=i.readInt64(),this.compositionStartTime=i.readInt64(),this.compositionEndTime=i.readInt64())}write(i){this.version=0,(this.compositionToDTSShift>as||this.leastDecodeToDisplayDelta>as||this.greatestDecodeToDisplayDelta>as||this.compositionStartTime>as||this.compositionEndTime>as)&&(this.version=1),this.flags=0,this.version===0?(this.size=20,this.writeHeader(i),i.writeInt32(this.compositionToDTSShift),i.writeInt32(this.leastDecodeToDisplayDelta),i.writeInt32(this.greatestDecodeToDisplayDelta),i.writeInt32(this.compositionStartTime),i.writeInt32(this.compositionEndTime)):this.version===1&&(this.size=40,this.writeHeader(i),i.writeInt64(this.compositionToDTSShift),i.writeInt64(this.leastDecodeToDisplayDelta),i.writeInt64(this.greatestDecodeToDisplayDelta),i.writeInt64(this.compositionStartTime),i.writeInt64(this.compositionEndTime))}},_l.fourcc="cslg",_l),yl,Vb=(yl=class extends R{constructor(){super(...arguments),this.box_name="CompositionOffsetBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.sample_counts=[],this.sample_offsets=[],this.version===0)for(let t=0;t<e;t++){this.sample_counts.push(i.readUint32());const s=i.readInt32();s<0&&I.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(s)}else if(this.version===1)for(let t=0;t<e;t++)this.sample_counts.push(i.readUint32()),this.sample_offsets.push(i.readInt32())}write(i){this.version=this.sample_offsets.some(e=>e<0)?1:0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(i),i.writeUint32(this.sample_counts.length);for(let e=0;e<this.sample_counts.length;e++)i.writeUint32(this.sample_counts[e]),this.version===1?i.writeInt32(this.sample_offsets[e]):i.writeUint32(this.sample_offsets[e])}unpack(i){let e=0;for(let t=0;t<this.sample_counts.length;t++)for(let s=0;s<this.sample_counts[t];s++)i[e].pts=i[e].dts+this.sample_offsets[t],e++}},yl.fourcc="ctts",yl),vl,$b=(vl=class extends B{constructor(){super(...arguments),this.box_name="AC3SpecificBox"}parse(i){const e=i.readUint8(),t=i.readUint8(),s=i.readUint8();this.fscod=e>>6,this.bsid=e>>1&31,this.bsmod=(e&1)<<2|t>>6&3,this.acmod=t>>3&7,this.lfeon=t>>2&1,this.bit_rate_code=t&3|s>>5&7}},vl.fourcc="dac3",vl),bl,Xb=(bl=class extends B{constructor(){super(...arguments),this.box_name="EC3SpecificBox"}parse(i){const e=i.readUint16();this.data_rate=e>>3,this.num_ind_sub=e&7,this.ind_subs=[];for(let t=0;t<this.num_ind_sub+1;t++){const s=i.readUint8(),r=i.readUint8(),n=i.readUint8(),o={fscod:s>>6,bsid:s>>1&31,bsmod:(s&1)<<4|r>>4&15,acmod:r>>1&7,lfeon:r&1,num_dep_sub:n>>1&15};this.ind_subs.push(o),o.num_dep_sub>0&&(o.chan_loc=(n&1)<<8|i.readUint8())}}},bl.fourcc="dec3",bl),Tl,Yb=(Tl=class extends R{constructor(){super(...arguments),this.box_name="FLACSpecificBox"}parse(i){this.parseFullHeader(i);const e=127,t=128,s=[],r=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];let n;do{n=i.readUint8();const o=Math.min(n&e,r.length-1);o?i.readUint8Array(i.readUint24()):(i.readUint8Array(13),this.samplerate=i.readUint32()>>12,i.readUint8Array(20)),s.push(r[o])}while(n&t);this.numMetadataBlocks=s.length+" ("+s.join(", ")+")"}},Tl.fourcc="dfLa",Tl),wl,qb=(wl=class extends B{constructor(){super(...arguments),this.box_name="hintimmediateBytesSent"}parse(i){this.bytessent=i.readUint64()}},wl.fourcc="dimm",wl),Sl,Kb=(Sl=class extends B{constructor(){super(...arguments),this.box_name="hintlongestpacket"}parse(i){this.time=i.readUint32()}},Sl.fourcc="dmax",Sl),Cl,jb=(Cl=class extends B{constructor(){super(...arguments),this.box_name="hintmediaBytesSent"}parse(i){this.bytessent=i.readUint64()}},Cl.fourcc="dmed",Cl),Al,Zb=(Al=class extends B{constructor(){super(...arguments),this.box_name="OpusSpecificBox"}parse(i){if(this.Version=i.readUint8(),this.OutputChannelCount=i.readUint8(),this.PreSkip=i.readUint16(),this.InputSampleRate=i.readUint32(),this.OutputGain=i.readInt16(),this.ChannelMappingFamily=i.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=i.readUint8(),this.CoupledCount=i.readUint8(),this.ChannelMapping=[];for(let e=0;e<this.OutputChannelCount;e++)this.ChannelMapping[e]=i.readUint8()}}write(i){if(this.size=11,this.ChannelMappingFamily!==0&&(this.size+=2+this.OutputChannelCount),this.writeHeader(i),i.writeUint8(this.Version),i.writeUint8(this.OutputChannelCount),i.writeUint16(this.PreSkip),i.writeUint32(this.InputSampleRate),i.writeInt16(this.OutputGain),i.writeUint8(this.ChannelMappingFamily),this.ChannelMappingFamily!==0){i.writeUint8(this.StreamCount),i.writeUint8(this.CoupledCount);for(let e=0;e<this.OutputChannelCount;e++)i.writeUint8(this.ChannelMapping[e])}}},Al.fourcc="dOps",Al),El,Jb=(El=class extends B{constructor(){super(...arguments),this.box_name="hintrepeatedBytesSent"}parse(i){this.bytessent=i.readUint64()}},El.fourcc="drep",El),Il,Qb=(Il=class extends R{constructor(){super(...arguments),this.box_name="EditListBox"}parse(i){this.parseFullHeader(i),this.entries=[];const e=i.readUint32();for(let t=0;t<e;t++){const s={segment_duration:this.version===1?i.readUint64():i.readUint32(),media_time:this.version===1?i.readInt64():i.readInt32(),media_rate_integer:i.readInt16(),media_rate_fraction:i.readInt16()};this.entries.push(s)}}write(i){const e=this.entries.some(t=>t.segment_duration>Ae||t.media_time>Ae)||this.version===1;this.version=e?1:0,this.size=4+12*this.entries.length,this.size+=e?8*this.entries.length:0,this.writeHeader(i),i.writeUint32(this.entries.length);for(let t=0;t<this.entries.length;t++){const s=this.entries[t];e?(i.writeUint64(s.segment_duration),i.writeInt64(s.media_time)):(i.writeUint32(s.segment_duration),i.writeInt32(s.media_time)),i.writeInt16(s.media_rate_integer),i.writeInt16(s.media_rate_fraction)}}},Il.fourcc="elst",Il),Pl,e2=(Pl=class extends R{constructor(){super(...arguments),this.box_name="EventMessageBox"}parse(i){this.parseFullHeader(i),this.version===1?(this.timescale=i.readUint32(),this.presentation_time=i.readUint64(),this.event_duration=i.readUint32(),this.id=i.readUint32(),this.scheme_id_uri=i.readCString(),this.value=i.readCString()):(this.scheme_id_uri=i.readCString(),this.value=i.readCString(),this.timescale=i.readUint32(),this.presentation_time_delta=i.readUint32(),this.event_duration=i.readUint32(),this.id=i.readUint32());let e=this.size-this.hdr_size-(16+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version===1&&(e-=4),this.message_data=i.readUint8Array(e)}write(i){this.version=0,this.flags=0,this.size=16+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(i),i.writeCString(this.scheme_id_uri),i.writeCString(this.value),i.writeUint32(this.timescale),i.writeUint32(this.presentation_time_delta),i.writeUint32(this.event_duration),i.writeUint32(this.id),i.writeUint8Array(this.message_data)}},Pl.fourcc="emsg",Pl),ke=class extends R{parse(e){this.parseFullHeader(e),this.group_id=e.readUint32(),this.num_entities_in_group=e.readUint32(),this.entity_ids=[];for(let t=0;t<this.num_entities_in_group;t++){const s=e.readUint32();this.entity_ids.push(s)}}},Rl,t2=(Rl=class extends ke{constructor(){super(...arguments),this.box_name="Auto exposure bracketing"}},Rl.fourcc="aebr",Rl),Ml,i2=(Ml=class extends ke{constructor(){super(...arguments),this.box_name="Flash exposure information"}},Ml.fourcc="afbr",Ml),kl,s2=(kl=class extends ke{constructor(){super(...arguments),this.box_name="Album collection"}},kl.fourcc="albc",kl),Fl,r2=(Fl=class extends ke{constructor(){super(...arguments),this.box_name="Alternative entity"}},Fl.fourcc="altr",Fl),Bl,n2=(Bl=class extends ke{constructor(){super(...arguments),this.box_name="Burst image"}},Bl.fourcc="brst",Bl),Ul,o2=(Ul=class extends ke{constructor(){super(...arguments),this.box_name="Depth of field bracketing"}},Ul.fourcc="dobr",Ul),Ol,a2=(Ol=class extends ke{constructor(){super(...arguments),this.box_name="Equivalent entity"}},Ol.fourcc="eqiv",Ol),Dl,l2=(Dl=class extends ke{constructor(){super(...arguments),this.box_name="Favorites collection"}},Dl.fourcc="favc",Dl),Gl,c2=(Gl=class extends ke{constructor(){super(...arguments),this.box_name="Focus bracketing"}},Gl.fourcc="fobr",Gl),zl,h2=(zl=class extends ke{constructor(){super(...arguments),this.box_name="Image item with an audio track"}},zl.fourcc="iaug",zl),Nl,u2=(Nl=class extends ke{constructor(){super(...arguments),this.box_name="Panorama"}},Nl.fourcc="pano",Nl),Ll,d2=(Ll=class extends ke{constructor(){super(...arguments),this.box_name="Slideshow"}},Ll.fourcc="slid",Ll),Hl,f2=(Hl=class extends ke{constructor(){super(...arguments),this.box_name="Stereo"}},Hl.fourcc="ster",Hl),Wl,p2=(Wl=class extends ke{constructor(){super(...arguments),this.box_name="Time-synchronized capture"}},Wl.fourcc="tsyn",Wl),Vl,m2=(Vl=class extends ke{constructor(){super(...arguments),this.box_name="White balance bracketing"}},Vl.fourcc="wbbr",Vl),$l,g2=($l=class extends ke{constructor(){super(...arguments),this.box_name="Progressive rendering"}},$l.fourcc="prgr",$l),Xl,x2=(Xl=class extends ke{constructor(){super(...arguments),this.box_name="Image pyramid"}parse(i){this.parseFullHeader(i),this.group_id=i.readUint32(),this.num_entities_in_group=i.readUint32(),this.entity_ids=[];for(let e=0;e<this.num_entities_in_group;e++){const t=i.readUint32();this.entity_ids.push(t)}this.tile_size_x=i.readUint16(),this.tile_size_y=i.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[];for(let e=0;e<this.num_entities_in_group;e++)this.layer_binning[e]=i.readUint16(),this.tiles_in_layer_row_minus1[e]=i.readUint16(),this.tiles_in_layer_column_minus1[e]=i.readUint16()}},Xl.fourcc="pymd",Xl),Yl,_2=(Yl=class extends B{constructor(){super(...arguments),this.box_name="FieldHandlingBox"}parse(i){this.fieldCount=i.readUint8(),this.fieldOrdering=i.readUint8()}},Yl.fourcc="fiel",Yl),ql,y2=(ql=class extends B{constructor(){super(...arguments),this.box_name="OriginalFormatBox"}parse(i){this.data_format=i.readString(4)}},ql.fourcc="frma",ql),Kl,v2=(Kl=class extends B{constructor(){super(...arguments),this.box_name="ImageMirror"}parse(i){const e=i.readUint8();this.reserved=e>>7,this.axis=e&1}},Kl.fourcc="imir",Kl),jl,b2=(jl=class extends R{constructor(){super(...arguments),this.box_name="ItemPropertyAssociationBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();this.associations=[];for(let t=0;t<e;t++){const s=this.version<1?i.readUint16():i.readUint32(),r=[],n=i.readUint8();for(let o=0;o<n;o++){const a=i.readUint8();r.push({essential:(a&128)>>7===1,property_index:this.flags&1?(a&127)<<8|i.readUint8():a&127})}this.associations.push({id:s,props:r})}}},jl.fourcc="ipma",jl),Zl,T2=(Zl=class extends B{constructor(){super(...arguments),this.box_name="ImageRotation"}parse(i){this.angle=i.readUint8()&3}},Zl.fourcc="irot",Zl),Jl,w2=(Jl=class extends R{constructor(){super(...arguments),this.box_name="ImageSpatialExtentsProperty"}parse(i){this.parseFullHeader(i),this.image_width=i.readUint32(),this.image_height=i.readUint32()}},Jl.fourcc="ispe",Jl),Ql,S2=(Ql=class extends R{constructor(){super(...arguments),this.box_name="TAITimestampBox"}parse(i){this.TAI_timestamp=i.readUint64();const e=i.readUint8();this.sychronization_state=e>>7&1,this.timestamp_generation_failure=e>>6&1,this.timestamp_is_modified=e>>5&1}},Ql.fourcc="itai",Ql),ec,C2=(ec=class extends R{constructor(){super(...arguments),this.box_name="KindBox"}parse(i){this.parseFullHeader(i),this.schemeURI=i.readCString(),this.isEndOfBox(i)||(this.value=i.readCString())}write(i){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value?this.value.length+1:0),this.writeHeader(i),i.writeCString(this.schemeURI),this.value&&i.writeCString(this.value)}},ec.fourcc="kind",ec),tc,A2=(tc=class extends R{constructor(){super(...arguments),this.box_name="LevelAssignmentBox"}parse(i){this.parseFullHeader(i);const e=i.readUint8();this.levels=[];for(let t=0;t<e;t++){const s={};this.levels[t]=s,s.track_ID=i.readUint32();const r=i.readUint8();switch(s.padding_flag=r>>7,s.assignment_type=r&127,s.assignment_type){case 0:s.grouping_type=i.readString(4);break;case 1:s.grouping_type=i.readString(4),s.grouping_type_parameter=i.readUint32();break;case 2:break;case 3:break;case 4:s.sub_track_id=i.readUint32();break;default:I.warn("BoxParser",`Unknown level assignment type: ${s.assignment_type}`)}}}},tc.fourcc="leva",tc),ic,E2=(ic=class extends B{constructor(){super(...arguments),this.box_name="LHEVCConfigurationBox"}parse(i){this.configurationVersion=i.readUint8(),this.min_spatial_segmentation_idc=i.readUint16()&4095,this.parallelismType=i.readUint8()&3;let e=i.readUint8();this.numTemporalLayers=(e&13)>>3,this.temporalIdNested=(e&4)>>2,this.lengthSizeMinusOne=e&3,this.nalu_arrays=[];const t=i.readUint8();for(let s=0;s<t;s++){const r=[];this.nalu_arrays.push(r),e=i.readUint8(),r.completeness=(e&128)>>7,r.nalu_type=e&63;const n=i.readUint16();for(let o=0;o<n;o++){const a=i.readUint16();r.push({data:i.readUint8Array(a)})}}}},ic.fourcc="lhvC",ic),sc,I2=(sc=class extends B{constructor(){super(...arguments),this.box_name="LayerSelectorProperty"}parse(i){this.layer_id=i.readUint16()}},sc.fourcc="lsel",sc),rc,P2=(rc=class extends B{constructor(){super(...arguments),this.box_name="hintmaxrate"}parse(i){this.period=i.readUint32(),this.bytes=i.readUint32()}},rc.fourcc="maxr",rc),mr=class{constructor(i,e){this.x=i,this.y=e}toString(){return"("+this.x+","+this.y+")"}},nc,R2=(nc=class extends B{constructor(){super(...arguments),this.box_name="MasteringDisplayColourVolumeBox"}parse(i){this.display_primaries=[],this.display_primaries[0]=new mr(i.readUint16(),i.readUint16()),this.display_primaries[1]=new mr(i.readUint16(),i.readUint16()),this.display_primaries[2]=new mr(i.readUint16(),i.readUint16()),this.white_point=new mr(i.readUint16(),i.readUint16()),this.max_display_mastering_luminance=i.readUint32(),this.min_display_mastering_luminance=i.readUint32()}},nc.fourcc="mdcv",nc),oc,M2=(oc=class extends R{constructor(){super(...arguments),this.box_name="MovieFragmentRandomAccessOffsetBox"}parse(i){this.parseFullHeader(i),this._size=i.readUint32()}},oc.fourcc="mfro",oc),ac,k2=(ac=class extends R{constructor(){super(...arguments),this.box_name="MaskConfigurationProperty"}parse(i){this.parseFullHeader(i),this.bits_per_pixel=i.readUint8()}},ac.fourcc="mskC",ac),lc,F2=(lc=class extends B{constructor(){super(...arguments),this.box_name="hintPacketsSent"}parse(i){this.packetssent=i.readUint32()}},lc.fourcc="npck",lc),cc,B2=(cc=class extends B{constructor(){super(...arguments),this.box_name="hintPacketsSent"}parse(i){this.packetssent=i.readUint64()}},cc.fourcc="nump",cc),U2=class{constructor(i,e){this.pad1=i,this.pad2=e}},hc,O2=(hc=class extends R{constructor(){super(...arguments),this.box_name="PaddingBitsBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();this.padbits=[];for(let t=0;t<Math.floor((e+1)/2);t++){const s=i.readUint8(),r=(s&112)>>4,n=s&7;this.padbits.push(new U2(r,n))}}},hc.fourcc="padb",hc),uc,D2=(uc=class extends B{constructor(){super(...arguments),this.box_name="PixelAspectRatioBox"}parse(i){this.hSpacing=i.readUint32(),this.vSpacing=i.readUint32()}},uc.fourcc="pasp",uc),dc,G2=(dc=class extends B{constructor(){super(...arguments),this.box_name="CuePayloadBox"}parse(i){this.text=i.readString(this.size-this.hdr_size)}},dc.fourcc="payl",dc),fc,z2=(fc=class extends B{constructor(){super(...arguments),this.box_name="hintpayloadID"}parse(i){this.payloadID=i.readUint32();const e=i.readUint8();this.rtpmap_string=i.readString(e)}},fc.fourcc="payt",fc),pc,N2=(pc=class extends R{constructor(){super(...arguments),this.box_name="ProgressiveDownloadInfoBox",this.rate=[],this.initial_delay=[]}parse(i){this.parseFullHeader(i);const e=(this.size-this.hdr_size)/8;for(let t=0;t<e;t++)this.rate[t]=i.readUint32(),this.initial_delay[t]=i.readUint32()}},pc.fourcc="pdin",pc),mc,L2=(mc=class extends R{constructor(){super(...arguments),this.box_name="PixelInformationProperty"}parse(i){this.parseFullHeader(i),this.num_channels=i.readUint8(),this.bits_per_channels=[];for(let e=0;e<this.num_channels;e++)this.bits_per_channels[e]=i.readUint8()}},mc.fourcc="pixi",mc),gc,H2=(gc=class extends B{constructor(){super(...arguments),this.box_name="hintlargestpacket"}parse(i){this.bytes=i.readUint32()}},gc.fourcc="pmax",gc),xc,W2=(xc=class extends R{constructor(){super(...arguments),this.box_name="ProgressiveDerivedImageItemInformationProperty"}parse(i){if(this.parseFullHeader(i),this.step_count=i.readUint16(),this.item_count=[],this.flags&2)for(let e=0;e<this.step_count;e++)this.item_count[e]=i.readUint16()}},xc.fourcc="prdi",xc),_c,V2=(_c=class extends R{constructor(){super(...arguments),this.box_name="ProjectionFormatBox"}parse(i){this.parseFullHeader(i),this.projection_type=i.readUint8()&31}},_c.fourcc="prfr",_c),yc,$2=(yc=class extends R{constructor(){super(...arguments),this.box_name="ProducerReferenceTimeBox"}parse(i){this.parseFullHeader(i),this.ref_track_id=i.readUint32(),this.ntp_timestamp=i.readUint64(),this.version===0?this.media_time=i.readUint32():this.media_time=i.readUint64()}},yc.fourcc="prft",yc),vc,X2=(vc=class extends R{constructor(){super(...arguments),this.box_name="ProtectionSystemSpecificHeaderBox"}parse(i){if(this.parseFullHeader(i),this.system_id=ri(i),this.kid=[],this.version>0){const t=i.readUint32();for(let s=0;s<t;s++)this.kid[s]=ri(i)}const e=i.readUint32();e>0&&(this.protection_data=i.readUint8Array(e))}},vc.fourcc="pssh",vc),bc,Y2=(bc=class extends R{constructor(){super(...arguments),this.box_name="TrackCleanApertureDimensionsBox"}parse(i){this.parseFullHeader(i),this.width=i.readUint32(),this.height=i.readUint32()}},bc.fourcc="clef",bc);function q2(i,e){if(i===ls.Types.UTF8)return new TextDecoder("utf-8").decode(e);const t=new DataView(e.buffer);if(i===ls.Types.BE_UNSIGNED_INT){if(e.length===1)return t.getUint8(0);if(e.length===2)return t.getUint16(0,!1);if(e.length===4)return t.getUint32(0,!1);if(e.length===8)return t.getBigUint64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_UNSIGNED_INT length "+e.length)}else if(i===ls.Types.BE_SIGNED_INT){if(e.length===1)return t.getInt8(0);if(e.length===2)return t.getInt16(0,!1);if(e.length===4)return t.getInt32(0,!1);if(e.length===8)return t.getBigInt64(0,!1);throw new Error("Unsupported ITIF_TYPE_BE_SIGNED_INT length "+e.length)}else if(i===ls.Types.BE_FLOAT32)return t.getFloat32(0,!1);I.warn("DataBox","Unsupported or unimplemented itif data type: "+i)}var gr,ls=(gr=class extends B{constructor(){super(...arguments),this.box_name="DataBox"}parse(i){this.valueType=i.readUint32(),this.country=i.readUint16(),this.country>255&&(i.seek(i.getPosition()-2),this.countryString=i.readString(2)),this.language=i.readUint16(),this.language>255&&(i.seek(i.getPosition()-2),this.parseLanguage(i)),this.raw=i.readUint8Array(this.size-this.hdr_size-8),this.value=q2(this.valueType,this.raw)}},gr.fourcc="data",gr.Types={RESERVED:0,UTF8:1,UTF16:2,SJIS:3,UTF8_SORT:4,UTF16_SORT:5,JPEG:13,PNG:14,BE_SIGNED_INT:21,BE_UNSIGNED_INT:22,BE_FLOAT32:23,BE_FLOAT64:24,BMP:27,QT_ATOM:28,BE_SIGNED_INT8:65,BE_SIGNED_INT16:66,BE_SIGNED_INT32:67,BE_FLOAT32_POINT:70,BE_FLOAT32_DIMENSIONS:71,BE_FLOAT32_RECT:72,BE_SIGNED_INT64:74,BE_UNSIGNED_INT8:75,BE_UNSIGNED_INT16:76,BE_UNSIGNED_INT32:77,BE_UNSIGNED_INT64:78,BE_FLOAT64_AFFINE_TRANSFORM:79},gr),Tc,K2=(Tc=class extends R{constructor(){super(...arguments),this.box_name="TrackEncodedPixelsDimensionsBox"}parse(i){this.parseFullHeader(i),this.width=i.readUint32(),this.height=i.readUint32()}},Tc.fourcc="enof",Tc),wc,j2=(wc=class extends B{constructor(){super(...arguments),this.box_name="IlstBox"}parse(i){this.list={};let e=this.size-this.hdr_size;for(;e>0;){const t=i.readUint32(),s=i.readUint32(),r=ht(i,!1,t-8);r.code===We&&(this.list[s]=r.box),e-=t}}},wc.fourcc="ilst",wc),Sc,Z2=(Sc=class extends R{constructor(){super(...arguments),this.box_name="KeysBox"}parse(i){this.parseFullHeader(i),this.count=i.readUint32(),this.keys={};for(let e=0;e<this.count;e++){const t=i.readUint32();this.keys[e+1]=i.readString(t-4)}}},Sc.fourcc="keys",Sc),Cc,J2=(Cc=class extends R{constructor(){super(...arguments),this.box_name="TrackProductionApertureDimensionsBox"}parse(i){this.parseFullHeader(i),this.width=i.readUint32(),this.height=i.readUint32()}},Cc.fourcc="prof",Cc),Ac,Q2=(Ac=class extends ee{constructor(){super(...arguments),this.box_name="TrackApertureModeDimensionsBox",this.clefs=[],this.profs=[],this.enofs=[],this.subBoxNames=["clef","prof","enof"]}},Ac.fourcc="tapt",Ac),Ec,eT=(Ec=class extends ee{constructor(){super(...arguments),this.box_name="siDecompressionParamBox"}},Ec.fourcc="wave",Ec),Ic,tT=(Ic=class extends B{constructor(){super(...arguments),this.box_name="rtpmoviehintinformation"}parse(i){this.descriptionformat=i.readString(4),this.sdptext=i.readString(this.size-this.hdr_size-4)}},Ic.fourcc="rtp ",Ic),Pc,iT=(Pc=class extends R{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationOffsetsBox"}parse(i){this.parseFullHeader(i),this.flags&1&&(this.aux_info_type=i.readString(4),this.aux_info_type_parameter=i.readUint32());const e=i.readUint32();this.offset=[];for(let t=0;t<e;t++)this.version===0?this.offset[t]=i.readUint32():this.offset[t]=i.readUint64()}},Pc.fourcc="saio",Pc),Rc,sT=(Rc=class extends R{constructor(){super(...arguments),this.box_name="SampleAuxiliaryInformationSizesBox"}parse(i){if(this.parseFullHeader(i),this.flags&1&&(this.aux_info_type=i.readString(4),this.aux_info_type_parameter=i.readUint32()),this.default_sample_info_size=i.readUint8(),this.sample_count=i.readUint32(),this.sample_info_size=[],this.default_sample_info_size===0)for(let e=0;e<this.sample_count;e++)this.sample_info_size[e]=i.readUint8()}},Rc.fourcc="saiz",Rc),rT=class{constructor(i,e){this.bad_pixel_row=i,this.bad_pixel_column=e}toString(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"}},Mc,nT=(Mc=class extends R{constructor(){super(...arguments),this.box_name="SensorBadPixelsMapBox"}parse(i){this.parseFullHeader(i),this.component_count=i.readUint16(),this.component_index=[];for(let t=0;t<this.component_count;t++)this.component_index.push(i.readUint16());const e=i.readUint8();this.correction_applied=(e&128)===128,this.num_bad_rows=i.readUint32(),this.num_bad_cols=i.readUint32(),this.num_bad_pixels=i.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[];for(let t=0;t<this.num_bad_rows;t++)this.bad_rows.push(i.readUint32());for(let t=0;t<this.num_bad_cols;t++)this.bad_columns.push(i.readUint32());for(let t=0;t<this.num_bad_pixels;t++){const s=i.readUint32(),r=i.readUint32();this.bad_pixels.push(new rT(s,r))}}},Mc.fourcc="sbpm",Mc),kc,oT=(kc=class extends R{constructor(){super(...arguments),this.box_name="SchemeTypeBox"}parse(i){this.parseFullHeader(i),this.scheme_type=i.readString(4),this.scheme_version=i.readUint32(),this.flags&1&&(this.scheme_uri=i.readString(this.size-this.hdr_size-8))}},kc.fourcc="schm",kc),Fc,aT=(Fc=class extends B{constructor(){super(...arguments),this.box_name="rtptracksdphintinformation"}parse(i){this.sdptext=i.readString(this.size-this.hdr_size)}},Fc.fourcc="sdp ",Fc),Bc,lT=(Bc=class extends R{constructor(){super(...arguments),this.box_name="SampleEncryptionBox"}},Bc.fourcc="senc",Bc),Uc,cT=(Uc=class extends R{constructor(){super(...arguments),this.box_name="SMPTE2086MasteringDisplayMetadataBox"}parse(i){this.parseFullHeader(i),this.primaryRChromaticity_x=i.readUint16(),this.primaryRChromaticity_y=i.readUint16(),this.primaryGChromaticity_x=i.readUint16(),this.primaryGChromaticity_y=i.readUint16(),this.primaryBChromaticity_x=i.readUint16(),this.primaryBChromaticity_y=i.readUint16(),this.whitePointChromaticity_x=i.readUint16(),this.whitePointChromaticity_y=i.readUint16(),this.luminanceMax=i.readUint32(),this.luminanceMin=i.readUint32()}},Uc.fourcc="SmDm",Uc),Oc,hT=(Oc=class extends R{constructor(){super(...arguments),this.box_name="SamplingRateBox"}parse(i){this.parseFullHeader(i),this.sampling_rate=i.readUint32()}},Oc.fourcc="srat",Oc),Dc,uT=(Dc=class extends R{constructor(){super(...arguments),this.box_name="CompressedSubsegmentIndexBox"}parse(i){this.parseFullHeader(i),this.subsegments=[];const e=i.readUint32();for(let t=0;t<e;t++){const s={};this.subsegments.push(s),s.ranges=[];const r=i.readUint32();for(let n=0;n<r;n++){const o={};s.ranges.push(o),o.level=i.readUint8(),o.range_size=i.readUint24()}}}},Dc.fourcc="ssix",Dc),Gc,dT=(Gc=class extends R{constructor(){super(...arguments),this.box_name="DegradationPriorityBox"}parse(i){this.parseFullHeader(i);const e=(this.size-this.hdr_size)/2;this.priority=[];for(let t=0;t<e;t++)this.priority[t]=i.readUint16()}},Gc.fourcc="stpd",Gc),zc,fT=(zc=class extends R{constructor(){super(...arguments),this.box_name="SubTrackInformationBox"}parse(i){this.parseFullHeader(i),this.switch_group=i.readUint16(),this.alternate_group=i.readUint16(),this.sub_track_id=i.readUint32();const e=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(let t=0;t<e;t++)this.attribute_list[t]=i.readUint32()}},zc.fourcc="stri",zc),Nc,pT=(Nc=class extends R{constructor(){super(...arguments),this.box_name="SubTrackSampleGroupBox"}parse(i){this.parseFullHeader(i),this.grouping_type=i.readUint32();const e=i.readUint16();this.group_description_index=[];for(let t=0;t<e;t++)this.group_description_index[t]=i.readUint32()}},Nc.fourcc="stsg",Nc),Lc,mT=(Lc=class extends R{constructor(){super(...arguments),this.box_name="ShadowSyncSampleBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(let t=0;t<e;t++)this.shadowed_sample_numbers.push(i.readUint32()),this.sync_sample_numbers.push(i.readUint32())}write(i){this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(i),i.writeUint32(this.shadowed_sample_numbers.length);for(let e=0;e<this.shadowed_sample_numbers.length;e++)i.writeUint32(this.shadowed_sample_numbers[e]),i.writeUint32(this.sync_sample_numbers[e])}},Lc.fourcc="stsh",Lc),Hc,gT=(Hc=class extends R{constructor(){super(...arguments),this.box_name="SyncSampleBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();if(this.version===0){this.sample_numbers=[];for(let t=0;t<e;t++)this.sample_numbers.push(i.readUint32())}}write(i){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(i),i.writeUint32(this.sample_numbers.length),i.writeUint32Array(this.sample_numbers)}},Hc.fourcc="stss",Hc),Wc,xT=(Wc=class extends R{constructor(){super(...arguments),this.box_name="StereoVideoBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();this.single_view_allowed=e&3,this.stereo_scheme=i.readUint32();const t=i.readUint32();for(this.stereo_indication_type=i.readString(t),this.boxes=[];i.getPosition()<this.start+this.size;){const s=ht(i,!1,this.size-(i.getPosition()-this.start));if(s.code===We){const r=s.box;this.boxes.push(r),this[r.type]=r}else return}}},Wc.fourcc="stvi",Wc),Vc,_T=(Vc=class extends B{constructor(){super(...arguments),this.box_name="SegmentTypeBox"}parse(i){let e=this.size-this.hdr_size;this.major_brand=i.readString(4),this.minor_version=i.readUint32(),e-=8,this.compatible_brands=[];let t=0;for(;e>=4;)this.compatible_brands[t]=i.readString(4),e-=4,t++}write(i){this.size=8+4*this.compatible_brands.length,this.writeHeader(i),i.writeString(this.major_brand,void 0,4),i.writeUint32(this.minor_version);for(let e=0;e<this.compatible_brands.length;e++)i.writeString(this.compatible_brands[e],void 0,4)}},Vc.fourcc="styp",Vc),$c,yT=($c=class extends R{constructor(){super(...arguments),this.box_name="CompactSampleSizeBox"}parse(i){if(this.parseFullHeader(i),this.sample_sizes=[],this.version===0){this.reserved=i.readUint24(),this.field_size=i.readUint8();const e=i.readUint32();if(this.field_size===4)for(let t=0;t<e;t+=2){const s=i.readUint8();this.sample_sizes[t]=s>>4&15,this.sample_sizes[t+1]=s&15}else if(this.field_size===8)for(let t=0;t<e;t++)this.sample_sizes[t]=i.readUint8();else if(this.field_size===16)for(let t=0;t<e;t++)this.sample_sizes[t]=i.readUint16();else I.error("BoxParser","Error in length field in stz2 box",i.isofile)}}},$c.fourcc="stz2",$c),Xc,vT=(Xc=class extends R{constructor(){super(...arguments),this.box_name="SubSampleInformationBox"}parse(i){this.parseFullHeader(i);const e=i.readUint32();this.entries=[];let t;for(let s=0;s<e;s++){const r={};if(this.entries[s]=r,r.sample_delta=i.readUint32(),r.subsamples=[],t=i.readUint16(),t>0)for(let n=0;n<t;n++){const o={};r.subsamples.push(o),this.version===1?o.size=i.readUint32():o.size=i.readUint16(),o.priority=i.readUint8(),o.discardable=i.readUint8(),o.codec_specific_parameters=i.readUint32()}}}},Xc.fourcc="subs",Xc),Yc,bT=(Yc=class extends R{constructor(){super(...arguments),this.box_name="TAIClockInfoBox"}parse(i){this.time_uncertainty=i.readUint64(),this.clock_resolution=i.readUint32(),this.clock_drift_rate=i.readInt32();const e=i.readUint8();this.clock_type=(e&192)>>6}},Yc.fourcc="taic",Yc),qc,TT=(qc=class extends R{constructor(){super(...arguments),this.box_name="TrackEncryptionBox"}parse(i){if(this.parseFullHeader(i),i.readUint8(),this.version===0)i.readUint8();else{const e=i.readUint8();this.default_crypt_byte_block=e>>4&15,this.default_skip_byte_block=e&15}this.default_isProtected=i.readUint8(),this.default_Per_Sample_IV_Size=i.readUint8(),this.default_KID=ri(i),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=i.readUint8(),this.default_constant_IV=i.readUint8Array(this.default_constant_IV_size))}},qc.fourcc="tenc",qc),Kc,wT=(Kc=class extends R{constructor(){super(...arguments),this.box_name="TrackFragmentRandomAccessBox"}parse(i){this.parseFullHeader(i),this.track_ID=i.readUint32(),i.readUint24();const e=i.readUint8();this.length_size_of_traf_num=e>>4&3,this.length_size_of_trun_num=e>>2&3,this.length_size_of_sample_num=e&3,this.entries=[];const t=i.readUint32();for(let s=0;s<t;s++)this.version===1?(this.time=i.readUint64(),this.moof_offset=i.readUint64()):(this.time=i.readUint32(),this.moof_offset=i.readUint32()),this.traf_number=i["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=i["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=i["readUint"+8*(this.length_size_of_sample_num+1)]()}},Kc.fourcc="tfra",Kc),jc,ST=(jc=class extends B{constructor(){super(...arguments),this.box_name="hintmaxrelativetime"}parse(i){this.time=i.readUint32()}},jc.fourcc="tmax",jc),Zc,CT=(Zc=class extends B{constructor(){super(...arguments),this.box_name="hintminrelativetime"}parse(i){this.time=i.readUint32()}},Zc.fourcc="tmin",Zc),Jc,AT=(Jc=class extends B{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(i){this.bytessent=i.readUint32()}},Jc.fourcc="totl",Jc),Qc,ET=(Qc=class extends B{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(i){this.bytessent=i.readUint32()}},Qc.fourcc="tpay",Qc),eh,IT=(eh=class extends B{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(i){this.bytessent=i.readUint64()}},eh.fourcc="tpyl",eh),th,PT=(th=class extends wf{},th.fourcc="msrc",th),cs,RT=(cs=class extends B{constructor(){super(...arguments),this.box_name="TrackReferenceBox",this.references=[]}parse(i){for(;i.getPosition()<this.start+this.size;){const e=ht(i,!0,this.size-(i.getPosition()-this.start));if(e.code===We){cs.allowed_types.includes(e.type)||I.warn("BoxParser",`Unknown track reference type: '${e.type}'`);const t=new Af(e.type,e.size,e.hdr_size,e.start);t.write===B.prototype.write&&t.type!=="mdat"&&(I.info("BoxParser","TrackReference "+t.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),t.parseDataAndRewind(i)),t.parse(i),this.references.push(t)}else return}}},cs.fourcc="tref",cs.allowed_types=["hint","cdsc","font","hind","vdep","vplx","subt","thmb","auxl","cdtg","shsc","aest"],cs),ih,MT=(ih=class extends R{constructor(){super(...arguments),this.box_name="TrackExtensionPropertiesBox"}parse(i){for(this.parseFullHeader(i),this.track_ID=i.readUint32(),this.boxes=[];i.getPosition()<this.start+this.size;){const e=ht(i,!1,this.size-(i.getPosition()-this.start));if(e.code===We){const t=e.box;this.boxes.push(t)}else return}}},ih.fourcc="trep",ih),sh,kT=(sh=class extends B{constructor(){super(...arguments),this.box_name="hintBytesSent"}parse(i){this.bytessent=i.readUint64()}},sh.fourcc="trpy",sh),rh,FT=(rh=class extends R{constructor(){super(...arguments),this.box_name="TrackSelectionBox"}parse(i){this.parseFullHeader(i),this.switch_group=i.readUint32();const e=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(let t=0;t<e;t++)this.attribute_list[t]=i.readUint32()}},rh.fourcc="tsel",rh),nh,BT=(nh=class extends R{constructor(){super(...arguments),this.box_name="TextConfigBox"}parse(i){this.parseFullHeader(i),this.config=i.readCString()}},nh.fourcc="txtc",nh),oh,UT=(oh=class extends B{constructor(){super(...arguments),this.box_name="TypeCombinationBox"}parse(i){const e=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(let t=0;t<e;t++)this.compatible_brands[t]=i.readString(4)}},oh.fourcc="tyco",oh),ah,OT=(ah=class extends R{constructor(){super(...arguments),this.box_name="UserDescriptionProperty"}parse(i){this.parseFullHeader(i),this.lang=i.readCString(),this.name=i.readCString(),this.description=i.readCString(),this.tags=i.readCString()}},ah.fourcc="udes",ah),lh,DT=(lh=class extends R{constructor(){super(...arguments),this.box_name="UncompressedFrameConfigBox"}parse(i){if(this.parseFullHeader(i),this.profile=i.readString(4),this.version!==1&&this.version===0){this.component_count=i.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[];for(let t=0;t<this.component_count;t++)this.component_index.push(i.readUint16()),this.component_bit_depth_minus_one.push(i.readUint8()),this.component_format.push(i.readUint8()),this.component_align_size.push(i.readUint8());this.sampling_type=i.readUint8(),this.interleave_type=i.readUint8(),this.block_size=i.readUint8();const e=i.readUint8();this.component_little_endian=e>>7&1,this.block_pad_lsb=e>>6&1,this.block_little_endian=e>>5&1,this.block_reversed=e>>4&1,this.pad_unknown=e>>3&1,this.pixel_size=i.readUint32(),this.row_align_size=i.readUint32(),this.tile_align_size=i.readUint32(),this.num_tile_cols_minus_one=i.readUint32(),this.num_tile_rows_minus_one=i.readUint32()}}},lh.fourcc="uncC",lh),ch,GT=(ch=class extends R{constructor(){super(...arguments),this.box_name="DataEntryUrnBox"}parse(i){this.parseFullHeader(i),this.name=i.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=i.readCString())}write(i){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(i),i.writeCString(this.name),this.location&&i.writeCString(this.location)}},ch.fourcc="urn ",ch),hh,zT=(hh=class extends B{constructor(){super(...arguments),this.box_name="WebVTTConfigurationBox"}parse(i){this.text=i.readString(this.size-this.hdr_size)}},hh.fourcc="vttC",hh),uh,NT=(uh=class extends R{constructor(){super(...arguments),this.box_name="VvcNALUConfigBox"}parse(i){this.parseFullHeader(i);const e=i.readUint8();this.lengthSizeMinusOne=e&3}},uh.fourcc="vvnC",uh),dh,LT=(dh=class extends ye{parse(i){const e=i.readUint16();this.first_output_sample=i.readUint16(),this.sample_offset=[];for(let s=0;s<e;s++)this.sample_offset[s]=i.readUint32();const t=this.description_length-4-4*e;this.num_output_samples=[],this.num_total_samples=[];for(let s=0;s<t/4;s++)this.num_output_samples[s]=i.readUint16(),this.num_total_samples[s]=i.readUint16()}},dh.grouping_type="alst",dh),fh,HT=(fh=class extends ye{parse(i){this.layerNumber=i.readUint8(),this.accurateStatisticsFlag=i.readUint8(),this.avgBitRate=i.readUint16(),this.avgFrameRate=i.readUint16()}},fh.grouping_type="avll",fh),ph,WT=(ph=class extends ye{parse(i){this.subSequenceIdentifier=i.readUint16(),this.layerNumber=i.readUint8();const e=i.readUint8();this.durationFlag=e>>7,this.avgRateFlag=e>>6&1,this.durationFlag&&(this.duration=i.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=i.readUint8(),this.avgBitRate=i.readUint16(),this.avgFrameRate=i.readUint16()),this.dependency=[];const t=i.readUint8();for(let s=0;s<t;s++)this.dependency.push({subSeqDirectionFlag:i.readUint8(),layerNumber:i.readUint8(),subSequenceIdentifier:i.readUint16()})}},ph.grouping_type="avss",ph),mh,VT=(mh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},mh.grouping_type="dtrt",mh),gh,$T=(gh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},gh.grouping_type="mvif",gh),xh,XT=(xh=class extends ye{parse(i){this.roll_distance=i.readInt16()}},xh.grouping_type="prol",xh),_h,YT=(_h=class extends ye{parse(i){const e=i.readUint8();this.num_leading_samples_known=e>>7,this.num_leading_samples=e&127}},_h.grouping_type="rap ",_h),yh,qT=(yh=class extends ye{parse(i){if(this.operation_point_count=i.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)I.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=i.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=i.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(let e=0;e<this.operation_point_count;e++)this.available_bitrate[e]=i.readUint32(),this.target_rate_share[e]=i.readUint16()}this.maximum_bitrate=i.readUint32(),this.minimum_bitrate=i.readUint32(),this.discard_priority=i.readUint8()}}},yh.grouping_type="rash",yh),vh,KT=(vh=class extends ye{parse(i){this.roll_distance=i.readInt16()}},vh.grouping_type="roll",vh),bh,jT=(bh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},bh.grouping_type="scif",bh),Th,ZT=(Th=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Th.grouping_type="scnm",Th),wh,JT=(wh=class extends ye{parse(i){this.reserved=i.readUint8();const e=i.readUint8();this.crypt_byte_block=e>>4,this.skip_byte_block=e&15,this.isProtected=i.readUint8(),this.Per_Sample_IV_Size=i.readUint8(),this.KID=ri(i),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=i.readUint8(),this.constant_IV=i.readUint8Array(this.constant_IV_size))}},wh.grouping_type="seig",wh),Sh,QT=(Sh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Sh.grouping_type="stsa",Sh),Ch,ew=(Ch=class extends ye{parse(i){const e=i.readUint8();this.NAL_unit_type=e&63}},Ch.grouping_type="sync",Ch),Ah,tw=(Ah=class extends ye{parse(i){const e=i.readUint8();this.level_independently_decodable=e>>7}},Ah.grouping_type="tele",Ah),Eh,iw=(Eh=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Eh.grouping_type="tsas",Eh),Ih,sw=(Ih=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Ih.grouping_type="tscl",Ih),Ph,rw=(Ph=class extends ye{parse(i){I.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}},Ph.grouping_type="vipr",Ph),Rh,nw=(Rh=class extends B{},Rh.fourcc="uuid",Rh),Mh,Si=(Mh=class extends R{},Mh.fourcc="uuid",Mh),kh,ow=(kh=class extends Si{constructor(){super(...arguments),this.box_name="LiveServerManifestBox"}parse(i){this.parseFullHeader(i),this.LiveServerManifest=i.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}},kh.uuid="a5d40b30e81411ddba2f0800200c9a66",kh),Fh,aw=(Fh=class extends Si{constructor(){super(...arguments),this.box_name="PiffProtectionSystemSpecificHeaderBox"}parse(i){this.parseFullHeader(i),this.system_id=ri(i);const e=i.readUint32();e>0&&(this.data=i.readUint8Array(e))}},Fh.uuid="d08a4f1810f34a82b6c832d8aba183d3",Fh),Bh,lw=(Bh=class extends Si{constructor(){super(...arguments),this.box_name="PiffSampleEncryptionBox"}},Bh.uuid="a2394f525a9b4f14a2446c427c648df4",Bh),Uh,cw=(Uh=class extends Si{constructor(){super(...arguments),this.box_name="PiffTrackEncryptionBox"}parse(i){this.parseFullHeader(i),this.default_AlgorithmID=i.readUint24(),this.default_IV_size=i.readUint8(),this.default_KID=ri(i)}},Uh.uuid="8974dbce7be74c5184f97148f9882554",Uh),Oh,hw=(Oh=class extends Si{constructor(){super(...arguments),this.box_name="TfrfBox"}parse(i){this.parseFullHeader(i),this.fragment_count=i.readUint8(),this.entries=[];for(let e=0;e<this.fragment_count;e++){let t=0,s=0;this.version===1?(t=i.readUint64(),s=i.readUint64()):(t=i.readUint32(),s=i.readUint32()),this.entries.push({absolute_time:t,absolute_duration:s})}}},Oh.uuid="d4807ef2ca3946958e5426cb9e46a79f",Oh),Dh,uw=(Dh=class extends Si{constructor(){super(...arguments),this.box_name="TfxdBox"}parse(i){this.parseFullHeader(i),this.version===1?(this.absolute_time=i.readUint64(),this.duration=i.readUint64()):(this.absolute_time=i.readUint32(),this.duration=i.readUint32())}},Dh.uuid="6d1d9b0542d544e680e2141daff757b2",Dh),Gh,dw=(Gh=class extends nw{constructor(){super(...arguments),this.box_name="ItemContentIDProperty"}parse(i){this.content_id=i.readCString()}},Gh.uuid="261ef3741d975bbaacbd9d2c8ea73522",Gh),_p=Iy(xp);Py(fp);const oi=Object.freeze(Object.defineProperty({__proto__:null,AudioSampleEntry:ze,Box:B,BoxParser:_p,DIFF_BOXES_PROP_NAMES:nr,DIFF_PRIMITIVE_ARRAY_PROP_NAMES:Ef,DataStream:Pe,Descriptor:Xt,ES_Descriptor:tl,Endianness:_f,FullBox:R,HintSampleEntry:In,ISOFile:up,Log:I,MP4BoxBuffer:_t,MPEG4DescriptorParser:gp,MetadataSampleEntry:ni,MultiBufferStream:Ti,SampleEntry:yt,SampleGroupEntry:ye,SampleGroupInfo:dr,SingleItemTypeReferenceBox:Sf,SingleItemTypeReferenceBoxLarge:Cf,SubtitleSampleEntry:$t,SystemSampleEntry:ar,TX3GParser:Sb,TextSampleEntry:Pf,Textin4Parser:wb,TrackGroupTypeBox:wf,TrackReferenceTypeBox:Af,VTTin4Parser:bb,VisualSampleEntry:fe,XMLSubtitlein4Parser:Tb,boxEqual:Cn,boxEqualFields:If,createFile:dp},Symbol.toStringTag,{value:"Module"})),fw=_p?.box?.esds,pw=dp;class mw{all=new Map;on(e,t){const s=this.all.get(e);return s?s.push(t):this.all.set(e,[t]),()=>this.off(e,t)}once(e,t){const s=this.on(e,r=>{s(),t(r)});return s}off(e,t){const s=this.all.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let s=this.all.get(e);s&&s.slice().forEach(r=>{r(t)}),s=this.all.get("*"),s&&s.slice().forEach(r=>{r(e,t)})}}const gw={0:"debug",1:"info",2:"warn",3:"error"};function xw(i){if(i instanceof Error)return String(i);if(typeof i=="object"&&i!==null)try{return JSON.stringify(i,(e,t)=>t instanceof Error?String(t):t)}catch{return String(i)}return String(i)}function _w(){const i=new Date,e=s=>s.toString().padStart(2,"0"),t=i.getMilliseconds().toString().padStart(3,"0");return`${e(i.getHours())}:${e(i.getMinutes())}:${e(i.getSeconds())}.${t}`}class yw{threshold=1;history=[];debug=(...e)=>this.log(0,console.debug,e);info=(...e)=>this.log(1,console.info,e);warn=(...e)=>this.log(2,console.warn,e);error=(...e)=>this.log(3,console.error,e);log(e,t,s){e>=this.threshold&&(t(...s),this.history.push({level:gw[e],time:_w(),args:s}))}setThreshold(e){this.threshold=e}getThreshold(){return this.threshold}createTagged(e){return{debug:(...t)=>this.debug(e,...t),info:(...t)=>this.info(e,...t),warn:(...t)=>this.warn(e,...t),error:(...t)=>this.error(e,...t)}}dump(){return this.history.map(({level:e,time:t,args:s})=>`[${e.toUpperCase()}][${t}] ${s.map(xw).join(" ")}`).join(`
|
|
3
|
+
`)}}const vt=new yw,Fe={debug:vt.debug,info:vt.info,warn:vt.warn,error:vt.error,setLogLevel:i=>{const e=i;e===Fe.debug?vt.setThreshold(0):e===Fe.info?vt.setThreshold(1):e===Fe.warn?vt.setThreshold(2):e===Fe.error&&vt.setThreshold(3)},create:i=>vt.createTagged(i),dump:async()=>vt.dump()};(async function(){if(!(typeof navigator>"u"||typeof document>"u")&&(Fe.info(`User Agent: ${navigator.userAgent}`),document.addEventListener("visibilitychange",()=>{Fe.info(`visibilitychange: ${document.visibilityState}`)}),"PressureObserver"in globalThis))try{let i="";new globalThis.PressureObserver(e=>{const t=JSON.stringify(e.map(s=>s.state));t!==i&&(Fe.info(`cpu state change: ${t}`),i=t)}).observe("cpu")}catch(i){Fe.debug("Failed to initialize PressureObserver",i)}})();let Pt=class{buffer;view;offset=0;constructor(e){this.buffer=new Uint8Array(e),this.view=new DataView(this.buffer.buffer)}writeUint32(e){return this.view.setUint32(this.offset,e),this.offset+=4,this}writeUint16(e){return this.view.setUint16(this.offset,e),this.offset+=2,this}writeUint8(e){return this.view.setUint8(this.offset,e),this.offset+=1,this}writeType(e){for(let t=0;t<4;t++){const s=t<e.length?e.charCodeAt(t):0;this.buffer[this.offset+t]=s}return this.offset+=4,this}writeBytes(e){const t=e instanceof Uint8Array?e:new Uint8Array(e);return this.buffer.set(t,this.offset),this.offset+=t.byteLength,this}skip(e){return this.offset+=e,this}};const vw=()=>{const i=new TextEncoder().encode("mp4 handler"),e=32+i.byteLength+1;return new Pt(e).writeUint32(e).writeType("hdlr").writeUint32(0).skip(4).writeType("mdta").skip(12).writeBytes(i).skip(1).buffer},bw=i=>{const e=new TextEncoder,t=i.map(n=>{const o=e.encode(n),a=8+o.byteLength;return new Pt(a).writeUint32(a).writeType("mdta").writeBytes(o).buffer}),s=16+t.reduce((n,o)=>n+o.byteLength,0),r=new Pt(s).writeUint32(s).writeType("keys").writeUint32(0).writeUint32(i.length);return t.forEach(n=>r.writeBytes(n)),r.buffer},Tw=i=>{const e=new TextEncoder,t=Object.entries(i).map(([n,o],a)=>{const l=a+1,c=e.encode(o),h=16+c.byteLength,u=8+h;return new Pt(u).writeUint32(u).writeUint32(l).writeUint32(h).writeType("data").writeUint32(1).skip(4).writeBytes(c).buffer}),s=8+t.reduce((n,o)=>n+o.byteLength,0),r=new Pt(s).writeUint32(s).writeType("ilst");return t.forEach(n=>r.writeBytes(n)),r.buffer},ww=i=>{const e=vw(),t=bw(Object.keys(i)),s=Tw(i),r=e.length+t.length+s.length;return new Pt(r).writeBytes(e).writeBytes(t).writeBytes(s).buffer};function yp(i){const e=new ArrayBuffer(i.byteLength);i.copyTo(e);const t=i.timestamp;return{duration:i.duration??0,dts:t,cts:t,is_sync:i.type==="key",data:e}}function Sw(i){const e=i.byteLength,t=i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength),s=26+e+3;return new Pt(s).writeUint8(3).writeUint8(23+e).writeUint16(1).writeUint8(0).writeUint8(4).writeUint8(15+e).writeUint8(64).writeUint8(21).writeBytes([0,0,0]).writeUint32(0).writeUint32(0).writeUint8(5).writeUint8(e).writeBytes(t).writeUint8(6).writeUint8(1).writeUint8(2).buffer}function Cw(i){const e=new DataView(i instanceof ArrayBuffer?i:i.buffer,i.byteOffset||0),t=e.getUint8(9),s=e.getUint16(10,!0),r=e.getUint32(12,!0),n=e.getInt16(16,!0),o=e.getUint8(18);return new Pt(11).writeUint8(0).writeUint8(t).writeUint16(s).writeUint32(r).writeUint16(n).writeUint8(o).buffer}function Aw(i){const e=(i.codec||"vp09.00.40.08").split("."),t=parseInt(e[1]||"0",10),s=parseInt(e[2]||"40",10),r=parseInt(e[3]||"08",10),n={bt709:1,bt601:5,bt2020:9},o={bt709:1,srgb:13,pq:16,hlg:18},a={bt709:1,bt601:5,bt2020:9},l=n[i.colorSpace?.primaries||"bt709"]||1,c=o[i.colorSpace?.transfer||"bt709"]||1,h=a[i.colorSpace?.matrix||"bt709"]||1,u=i.colorSpace?.fullRange?1:0;return new Pt(12).writeUint32(1<<24).writeUint8(t).writeUint8(s).writeUint8(r<<4|2|u).writeUint8(l).writeUint8(c).writeUint8(h).writeUint16(0).buffer.buffer}function Ew(i){if(i.byteLength<7)return!1;const e=new DataView(i);let t=0;try{t+=6;const s=e.getUint8(5)&31;for(let n=0;n<s;n++){if(t+2>i.byteLength)return!1;const o=e.getUint16(t);t+=2+o}if(t+1>i.byteLength)return!1;const r=e.getUint8(t++);for(let n=0;n<r;n++){if(t+2>i.byteLength)return!1;const o=e.getUint16(t);t+=2+o}return t<=i.byteLength}catch{return!1}}function Iw(i){if(!i||i.byteLength<3)return;const e=new Uint8Array(i);e[2]?.toString(2).slice(-2).includes("1")&&(e[2]=0)}class Pw{constructor(e,t,s){this.opts=e,this.mp4File=t,this.avSyncTool=s,this.encoder=this.initEncoder(),this.avSyncTool.once("VideoReady",()=>{this.videoReady=!0,this.flushCache()})}encoder;trackId=-1;cache=[];videoReady=!1;initEncoder(){const e={codec:this.opts.codec==="aac"?"mp4a.40.2":"opus",sampleRate:this.opts.sampleRate,numberOfChannels:this.opts.channelCount,bitrate:128e3},t=new AudioEncoder({error:s=>{const r=`AudioEncoder error: ${s.message}, config: ${JSON.stringify(e)}`;throw Fe.error(r),Error(r)},output:(s,r)=>this.onOutput(s,r)});return t.configure(e),t}onOutput(e,t){this.trackId===-1&&this.setupTrack(t);const s=yp(e);this.videoReady?this.mp4File.addSample(this.trackId,new Uint8Array(s.data),s):this.cache.push(s)}setupTrack(e){const t=e?.decoderConfig?.description,s=this.opts.codec==="aac",r={timescale:1e6,samplerate:this.opts.sampleRate,channel_count:this.opts.channelCount,hdlr:"soun",type:s?"mp4a":"Opus",name:"Track created with designcombo",description:t==null?void 0:s?this.createESDS(t):this.createDOps(t)};this.trackId=this.mp4File.addTrack(r),this.avSyncTool.emit("AudioReady",void 0),Fe.info("AudioEncoder, audio track ready, trackId:",this.trackId)}createESDS(e){const t=new fw;return t.version=0,t.flags=0,t.data=Sw(e),t}createDOps(e){const t=Cw(e);return{type:"dOps",size:t.byteLength+8,hdr_size:8,start:0,data:t,write:function(s){s.writeUint32(this.size),s.writeString("dOps"),s.writeUint8Array(this.data)},parse:function(){}}}flushCache(){this.cache.forEach(e=>{this.mp4File.addSample(this.trackId,new Uint8Array(e.data),e)}),this.cache=[]}encode(e){this.encoder.encode(e)}async flush(){this.encoder.state==="configured"&&await this.encoder.flush()}close(){this.encoder.state==="configured"&&this.encoder.close()}get encodeQueueSize(){return this.encoder.encodeQueueSize}get state(){return this.encoder.state}}const Rw=()=>{let i,e=16.6;self.onmessage=t=>{t.data.event==="start"&&(self.clearInterval(i),i=self.setInterval(()=>{self.postMessage({})},e)),t.data.event==="stop"&&self.clearInterval(i)}},Mw=()=>{const i=new Blob([`(${Rw.toString()})()`]),e=URL.createObjectURL(i);return new Worker(e)},Ci=new Map;let zh=1,xr=null;globalThis.Worker!=null&&(xr=Mw(),xr.onmessage=()=>{zh+=1;for(const[i,e]of Ci)if(zh%i===0)for(const t of e)t()});const kw=(i,e)=>{const t=Math.round(e/16.6),s=Ci.get(t)??new Set;return s.add(i),Ci.set(t,s),Ci.size===1&&s.size===1&&xr?.postMessage({event:"start"}),()=>{s.delete(i),s.size===0&&Ci.delete(t),Ci.size===0&&(zh=0,xr?.postMessage({event:"stop"}))}};class Fw{constructor(e,t,s){this.opts=e,this.mp4File=t,this.avSyncTool=s,this.frameDeltaTime=Math.floor(1e3/e.expectFPS*1e3),this.encoder0=this.initEncoder("encoder0"),this.encoder1=this.initEncoder("encoder1"),this.avSyncTool.once("AudioReady",()=>{this.audioReady=!0}),this.stopTimer=kw(()=>this.checkCache(),15)}encoder0;encoder1;trackId=-1;samplesCache={encoder0:[],encoder1:[]};currentEncoderId="encoder1";lastAddedSampleTime=0;audioReady=!1;gopId=0;stopTimer;frameDeltaTime;initEncoder(e){const t={codec:this.opts.codec,framerate:this.opts.expectFPS,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__,bitrate:this.opts.bitrate,width:this.opts.width,height:this.opts.height,alpha:"discard",avc:{format:"avc"}},s=new VideoEncoder({error:r=>{throw Fe.error(`VideoEncoder error: ${r.message}`,t),Error(`VideoEncoder error: ${r.message}`)},output:(r,n)=>this.onOutput(e,r,n)});return s.configure(t),s}onOutput(e,t,s){this.trackId===-1&&s!=null&&this.setupTrack(s),this.samplesCache[e].push(yp(t))}setupTrack(e){if(!e.decoderConfig)return;let t=e.decoderConfig.description,s="avc1";if(this.opts.codec.startsWith("avc1")){if(Iw(t),!Ew(t)){Fe.warn("Invalid AVCC descriptor, waiting for next metadata");return}}else this.opts.codec.startsWith("vp09")&&(s="vp09",t=Aw(e.decoderConfig));const r=this.getDecoderConfKey();if(!r||!t||t.byteLength<7){Fe.warn("VideoEncoder metadata missing valid configuration");return}const n={timescale:1e6,width:this.opts.width,height:this.opts.height,brands:["isom","iso2","avc1","mp42","mp41"],type:s,name:"Track created with designcombo"};n[r]=t;try{this.trackId=this.mp4File.addTrack(n),this.avSyncTool.emit("VideoReady",void 0),Fe.info("VideoEncoder, video track ready, trackId:",this.trackId)}catch(o){Fe.warn("mp4File.addTrack warning",o)}}getDecoderConfKey(){return this.opts.codec.startsWith("avc1")?"avcDecoderConfigRecord":this.opts.codec.startsWith("hvc1")?"hevcDecoderConfigRecord":this.opts.codec.startsWith("vp09")?"vpcDecoderConfigRecord":null}checkCache(){if(!this.audioReady||this.trackId===-1)return;const e=this.currentEncoderId==="encoder1"?"encoder0":"encoder1",t=this.samplesCache[this.currentEncoderId],s=this.samplesCache[e];if(t.length===0&&s.length===0)return;const r=t[0];if(r!=null&&(!r.is_sync||r.cts-this.lastAddedSampleTime<this.frameDeltaTime)){const o=this.addSampleToFile(t);o>this.lastAddedSampleTime&&(this.lastAddedSampleTime=o)}const n=s[0];if(n?.is_sync&&n.cts-this.lastAddedSampleTime<this.frameDeltaTime){this.currentEncoderId=e,this.checkCache();return}if(r?.is_sync&&n?.is_sync)if(r.cts<=n.cts){const o=this.addSampleToFile(t);o>this.lastAddedSampleTime&&(this.lastAddedSampleTime=o)}else this.currentEncoderId=e,this.checkCache()}addSampleToFile(e){let t=-1,s=0;for(;s<e.length;s++){const r=e[s];if(s>0&&r.is_sync)break;this.mp4File.addSample(this.trackId,new Uint8Array(r.data),r),t=r.cts+r.duration}return e.splice(0,s),t}encode(e,t){t.keyFrame&&this.gopId++,(this.gopId%2===0?this.encoder0:this.encoder1).encode(e,t)}async flush(){await Promise.all([this.encoder0.state==="configured"?this.encoder0.flush():null,this.encoder1.state==="configured"?this.encoder1.flush():null]),this.stopTimer(),this.checkCache()}close(){this.encoder0.state==="configured"&&this.encoder0.close(),this.encoder1.state==="configured"&&this.encoder1.close()}get encodeQueueSize(){return this.encoder0.encodeQueueSize+this.encoder1.encodeQueueSize}}function Bw(i){Fe.info("recodemux opts:",i);const e=pw(),t=new mw,s=(l,c)=>{const h=l.add("udta").add("meta");h.data=ww(c),h.size=h.data.byteLength};let r=!1;const n=()=>{e.moov==null||r||(r=!0,i.metaDataTags&&s(e.moov,i.metaDataTags),i.duration!=null&&(e.moov.mvhd.duration=i.duration))};t.once("VideoReady",n),t.once("AudioReady",n);const o=i.video?new Fw(i.video,e,t):null,a=i.audio?new Pw(i.audio,e,t):null;return i.video||t.emit("VideoReady",void 0),i.audio||t.emit("AudioReady",void 0),{encodeVideo:(l,c)=>{o?.encode(l,c),l.close()},encodeAudio:l=>{if(a)try{a.encode(l),l.close()}catch(c){throw Fe.error("encode audio chunk error",c),c}},getEncodeQueueSize:()=>o?.encodeQueueSize??a?.encodeQueueSize??0,flush:async()=>{await Promise.all([o?.flush(),a?.flush()])},close:()=>{t.all.clear(),o?.close(),a?.close()},mp4file:e}}var vp=i=>{throw TypeError(i)},bp=(i,e,t)=>e.has(i)||vp("Cannot "+t),J=(i,e,t)=>(bp(i,e,"read from private field"),t?t.call(i):e.get(i)),st=(i,e,t)=>e.has(i)?vp("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(i):e.set(i,t),Ne=(i,e,t,s)=>(bp(i,e,"write to private field"),e.set(i,t),t);const Tp="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2Z1bmN0aW9uIHUobil7aWYobj09PSIvIilyZXR1cm57cGFyZW50Om51bGwsbmFtZToiIn07Y29uc3QgZT1uLnNwbGl0KCIvIikuZmlsdGVyKGk9PmkubGVuZ3RoPjApO2lmKGUubGVuZ3RoPT09MCl0aHJvdyBFcnJvcigiSW52YWxpZCBwYXRoIik7Y29uc3QgYT1lW2UubGVuZ3RoLTFdLHI9Ii8iK2Uuc2xpY2UoMCwtMSkuam9pbigiLyIpO3JldHVybntuYW1lOmEscGFyZW50OnJ9fWFzeW5jIGZ1bmN0aW9uIHcobixlKXtjb25zdHtwYXJlbnQ6YSxuYW1lOnJ9PXUobik7aWYoYT09bnVsbClyZXR1cm4gYXdhaXQgbmF2aWdhdG9yLnN0b3JhZ2UuZ2V0RGlyZWN0b3J5KCk7Y29uc3QgaT1hLnNwbGl0KCIvIikuZmlsdGVyKHQ9PnQubGVuZ3RoPjApO3RyeXtsZXQgdD1hd2FpdCBuYXZpZ2F0b3Iuc3RvcmFnZS5nZXREaXJlY3RvcnkoKTtmb3IoY29uc3QgcyBvZiBpKXQ9YXdhaXQgdC5nZXREaXJlY3RvcnlIYW5kbGUocyx7Y3JlYXRlOmUuY3JlYXRlfSk7aWYoZS5pc0ZpbGUpcmV0dXJuIGF3YWl0IHQuZ2V0RmlsZUhhbmRsZShyLHtjcmVhdGU6ZS5jcmVhdGV9KX1jYXRjaCh0KXtpZih0Lm5hbWU9PT0iTm90Rm91bmRFcnJvciIpcmV0dXJuIG51bGw7dGhyb3cgdH19Y29uc3QgZj17fTtzZWxmLm9ubWVzc2FnZT1hc3luYyBuPT57dmFyIGk7Y29uc3R7ZXZ0VHlwZTplLGFyZ3M6YX09bi5kYXRhO2xldCByPWZbYS5maWxlSWRdO3RyeXtsZXQgdDtjb25zdCBzPVtdO2lmKGU9PT0icmVnaXN0ZXIiKXtjb25zdCBsPWF3YWl0IHcoYS5maWxlUGF0aCx7Y3JlYXRlOiEwLGlzRmlsZTohMH0pO2lmKGw9PW51bGwpdGhyb3cgRXJyb3IoYG5vdCBmb3VuZCBmaWxlOiAke2EuZmlsZUlkfWApO3I9YXdhaXQgbC5jcmVhdGVTeW5jQWNjZXNzSGFuZGxlKHttb2RlOmEubW9kZX0pLGZbYS5maWxlSWRdPXJ9ZWxzZSBpZihlPT09ImNsb3NlIilhd2FpdCByLmNsb3NlKCksZGVsZXRlIGZbYS5maWxlSWRdO2Vsc2UgaWYoZT09PSJ0cnVuY2F0ZSIpYXdhaXQgci50cnVuY2F0ZShhLm5ld1NpemUpO2Vsc2UgaWYoZT09PSJ3cml0ZSIpe2NvbnN0e2RhdGE6bCxvcHRzOm99PW4uZGF0YS5hcmdzO3Q9YXdhaXQgci53cml0ZShsLG8pfWVsc2UgaWYoZT09PSJyZWFkIil7Y29uc3R7b2Zmc2V0Omwsc2l6ZTpvfT1uLmRhdGEuYXJncyxnPW5ldyBVaW50OEFycmF5KG8pLGQ9YXdhaXQgci5yZWFkKGcse2F0Omx9KSxjPWcuYnVmZmVyO3Q9ZD09PW8/YzooKGk9Yy50cmFuc2Zlcik9PW51bGw/dm9pZCAwOmkuY2FsbChjLGQpKT8/Yy5zbGljZSgwLGQpLHMucHVzaCh0KX1lbHNlIGU9PT0iZ2V0U2l6ZSI/dD1hd2FpdCByLmdldFNpemUoKTplPT09ImZsdXNoIiYmYXdhaXQgci5mbHVzaCgpO3NlbGYucG9zdE1lc3NhZ2Uoe2V2dFR5cGU6ImNhbGxiYWNrIixjYklkOm4uZGF0YS5jYklkLHJldHVyblZhbDp0fSxzKX1jYXRjaCh0KXtjb25zdCBzPXQ7c2VsZi5wb3N0TWVzc2FnZSh7ZXZ0VHlwZToidGhyb3dFcnJvciIsY2JJZDpuLmRhdGEuY2JJZCxlcnJNc2c6cy5uYW1lKyI6ICIrcy5tZXNzYWdlK2AKYCtKU09OLnN0cmluZ2lmeShuLmRhdGEpfSl9fX0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPW9wZnMtd29ya2VyLUY0UldscWNfLmpzLm1hcAo=",Uw=i=>Uint8Array.from(atob(i),e=>e.charCodeAt(0)),wp=typeof self<"u"&&self.Blob&&new Blob([Uw(Tp)],{type:"text/javascript;charset=utf-8"});function Ow(i){let e;try{if(e=wp&&(self.URL||self.webkitURL).createObjectURL(wp),!e)throw"";const t=new Worker(e,{name:i?.name});return t.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(e)}),t}catch{return new Worker("data:text/javascript;base64,"+Tp,{name:i?.name})}finally{e&&(self.URL||self.webkitURL).revokeObjectURL(e)}}async function Dw(i,e,t){const s=Gw();return await s("register",{fileId:i,filePath:e,mode:t}),{read:async(r,n)=>await s("read",{fileId:i,offset:r,size:n}),write:async(r,n)=>await s("write",{fileId:i,data:r,opts:n},[ArrayBuffer.isView(r)?r.buffer:r]),close:async()=>await s("close",{fileId:i}),truncate:async r=>await s("truncate",{fileId:i,newSize:r}),getSize:async()=>await s("getSize",{fileId:i}),flush:async()=>await s("flush",{fileId:i})}}const _r=[];let Nh=0;function Gw(){if(_r.length<3){const e=i();return _r.push(e),e}else{const e=_r[Nh];return Nh=(Nh+1)%_r.length,e}function i(){const e=new Ow;let t=0,s={};return e.onmessage=({data:r})=>{var n,o;r.evtType==="callback"?(n=s[r.cbId])==null||n.resolve(r.returnVal):r.evtType==="throwError"&&((o=s[r.cbId])==null||o.reject(Error(r.errMsg))),delete s[r.cbId]},async function(r,n,o=[]){t+=1;const a=new Promise((l,c)=>{s[t]={resolve:l,reject:c}});return e.postMessage({cbId:t,evtType:r,args:n},o),a}}}function yr(i){if(i==="/")return{parent:null,name:""};const e=i.split("/").filter(r=>r.length>0);if(e.length===0)throw Error("Invalid path");const t=e[e.length-1],s="/"+e.slice(0,-1).join("/");return{name:t,parent:s}}async function Yt(i,e){const{parent:t,name:s}=yr(i);if(t==null)return await navigator.storage.getDirectory();const r=t.split("/").filter(n=>n.length>0);try{let n=await navigator.storage.getDirectory();for(const o of r)n=await n.getDirectoryHandle(o,{create:e.create});return e.isFile?await n.getFileHandle(s,{create:e.create}):await n.getDirectoryHandle(s,{create:e.create})}catch(n){if(n.name==="NotFoundError")return null;throw n}}async function Lh(i){const{parent:e,name:t}=yr(i);if(e==null){const r=await navigator.storage.getDirectory();for await(const n of r.keys())await r.removeEntry(n,{recursive:!0});return}const s=await Yt(e,{create:!1,isFile:!1});if(s!=null)try{await s.removeEntry(t,{recursive:!0})}catch(r){if(r.name==="NotFoundError")return;throw r}}function Hh(i,e){return`${i}/${e}`.replace("//","/")}function Ai(i){return new Sp(i)}var bt,vr,hs;const zw=class Y_{constructor(e){st(this,bt),st(this,vr),st(this,hs),Ne(this,bt,e);const{parent:t,name:s}=yr(e);Ne(this,vr,s),Ne(this,hs,t)}get kind(){return"dir"}get name(){return J(this,vr)}get path(){return J(this,bt)}get parent(){return J(this,hs)==null?null:Ai(J(this,hs))}async create(){return await Yt(J(this,bt),{create:!0,isFile:!1}),Ai(J(this,bt))}async exists(){return await Yt(J(this,bt),{create:!1,isFile:!1})instanceof FileSystemDirectoryHandle}async remove(e={}){for(const t of await this.children())try{await t.remove(e)}catch(s){console.warn(s)}try{await Lh(J(this,bt))}catch(t){console.warn(t)}}async children(){const e=await Yt(J(this,bt),{create:!1,isFile:!1});if(e==null)return[];const t=[];for await(const s of e.values())t.push((s.kind==="file"?ai:Ai)(Hh(J(this,bt),s.name)));return t}async copyTo(e){if(!await this.exists())throw Error(`dir ${this.path} not exists`);if(e instanceof Y_){const t=await e.exists()?Ai(Hh(e.path,this.name)):e;return await t.create(),await Promise.all((await this.children()).map(s=>s.copyTo(t))),t}else if(e instanceof FileSystemDirectoryHandle)return await Promise.all((await this.children()).map(async t=>{t.kind==="file"?await t.copyTo(await e.getFileHandle(t.name,{create:!0})):await t.copyTo(await e.getDirectoryHandle(t.name,{create:!0}))})),null;throw Error("Illegal target type")}async moveTo(e){const t=await this.copyTo(e);return await this.remove(),t}};bt=new WeakMap,vr=new WeakMap,hs=new WeakMap;let Sp=zw;const Wh=new Map;function ai(i,e="rw"){if(e==="rw"){const t=Wh.get(i)??new Cr(i,e);return Wh.set(i,t),t}return new Cr(i,e)}async function Ei(i,e,t={overwrite:!0}){if(e instanceof Cr){await Ei(i,await e.stream(),t);return}const s=await(i instanceof Cr?i:ai(i,"rw")).createWriter();try{if(t.overwrite&&await s.truncate(0),e instanceof ReadableStream){const r=e.getReader();for(;;){const{done:n,value:o}=await r.read();if(n)break;await s.write(o)}}else await s.write(e)}catch(r){throw r}finally{await s.close()}}let Nw=0;const Lw=()=>++Nw;var rt,us,br,ds,Tr,Rt,wr,Sr,Ii;const Hw=class q_{constructor(e,t){st(this,rt),st(this,us),st(this,br),st(this,ds),st(this,Tr),st(this,Rt,0),st(this,wr,async()=>{}),st(this,Sr,(()=>{let n=null;return()=>(Ne(this,Rt,J(this,Rt)+1),n!=null||(n=new Promise(async(o,a)=>{try{const l=await Dw(J(this,Tr),J(this,rt),J(this,ds));Ne(this,wr,async()=>{n!=null&&(n=null,Ne(this,Rt,0),await l.close().catch(console.error))}),o([l,async()=>{Ne(this,Rt,J(this,Rt)-1),!(J(this,Rt)>0)&&(n=null,await l.close())}])}catch(l){a(l)}})),n)})()),st(this,Ii,!1),Ne(this,Tr,Lw()),Ne(this,rt,e),Ne(this,ds,{r:"read-only",rw:"readwrite","rw-unsafe":"readwrite-unsafe"}[t]);const{parent:s,name:r}=yr(e);if(s==null)throw Error("Invalid path");Ne(this,br,r),Ne(this,us,s)}get kind(){return"file"}get path(){return J(this,rt)}get name(){return J(this,br)}get parent(){return J(this,us)==null?null:Ai(J(this,us))}async createWriter(){if(J(this,ds)==="read-only")throw Error("file is read-only");if(J(this,Ii))throw Error("Other writer have not been closed");Ne(this,Ii,!0);try{const e=new TextEncoder,[t,s]=await J(this,Sr).call(this);let r=await t.getSize(),n=!1;return{write:async(o,a={})=>{if(n)throw Error("Writer is closed");const l=typeof o=="string"?e.encode(o):o,c=a.at??r,h=l.byteLength;return r=c+h,await t.write(l,{at:c})},truncate:async o=>{if(n)throw Error("Writer is closed");await t.truncate(o),r>o&&(r=o)},flush:async()=>{if(n)throw Error("Writer is closed");await t.flush()},close:async()=>{if(n)throw Error("Writer is closed");n=!0,Ne(this,Ii,!1),await s()}}}catch(e){throw Ne(this,Ii,!1),e}}async createReader(){const[e,t]=await J(this,Sr).call(this);let s=!1,r=0;return{read:async(n,o={})=>{if(s)throw Error("Reader is closed");const a=o.at??r,l=await e.read(a,n);return r=a+l.byteLength,l},getSize:async()=>{if(s)throw Error("Reader is closed");return await e.getSize()},close:async()=>{s||(s=!0,await t())}}}async text(){return new TextDecoder().decode(await this.arrayBuffer())}async arrayBuffer(){const e=await Yt(J(this,rt),{create:!1,isFile:!0});return e==null?new ArrayBuffer(0):(await e.getFile()).arrayBuffer()}async stream(){const e=await this.getOriginFile();return e==null?new ReadableStream({pull:t=>{t.close()}}):e.stream()}async getOriginFile(){var e;return(e=await Yt(J(this,rt),{create:!1,isFile:!0}))==null?void 0:e.getFile()}async getSize(){const e=await Yt(J(this,rt),{create:!1,isFile:!0});return e==null?0:(await e.getFile()).size}async exists(){return await Yt(J(this,rt),{create:!1,isFile:!0})instanceof FileSystemFileHandle}async remove(e={}){if(e.force===!0){await J(this,wr).call(this),await Lh(J(this,rt)),Wh.delete(J(this,rt));return}if(J(this,Rt)>0)throw Error("exists unclosed reader/writer");await Lh(J(this,rt))}async copyTo(e){if(e instanceof q_)return e.path===this.path?this:(await Ei(e,this),e);if(e instanceof Sp){if(!await this.exists())throw Error(`file ${this.path} not exists`);return await this.copyTo(ai(Hh(e.path,this.name)))}else if(e instanceof FileSystemFileHandle)return await(await this.stream()).pipeTo(await e.createWritable()),null;throw Error("Illegal target type")}async moveTo(e){const t=await this.copyTo(e);return await this.remove(),t}};rt=new WeakMap,us=new WeakMap,br=new WeakMap,ds=new WeakMap,Tr=new WeakMap,Rt=new WeakMap,wr=new WeakMap,Sr=new WeakMap,Ii=new WeakMap;let Cr=Hw;const Vh="/.opfs-tools-temp-dir";async function Cp(i){try{if(i.kind==="file"){if(!await i.exists())return!0;const e=await i.createWriter();await e.truncate(0),await e.close(),await i.remove()}else await i.remove();return!0}catch(e){return console.warn(e),!1}}function Ww(){setInterval(async()=>{for(const i of await Ai(Vh).children()){const e=/^\d+-(\d+)$/.exec(i.name);(e==null||Date.now()-Number(e[1])>2592e5)&&await Cp(i)}},60*1e3)}const $h=[];let Ap=!1;async function Vw(){if(globalThis.localStorage==null)return;const i="OPFS_TOOLS_EXPIRES_TMP_FILES";Ap||(Ap=!0,globalThis.addEventListener("unload",()=>{$h.length!==0&&localStorage.setItem(i,`${localStorage.getItem(i)??""},${$h.join(",")}`)}));let e=localStorage.getItem(i)??"";for(const t of e.split(","))t.length!==0&&await Cp(ai(`${Vh}/${t}`))&&(e=e.replace(t,""));localStorage.setItem(i,e.replace(/,{2,}/g,","))}(async function(){var i;globalThis.__opfs_tools_tmpfile_init__!==!0&&(globalThis.__opfs_tools_tmpfile_init__=!0,!(globalThis.FileSystemDirectoryHandle==null||globalThis.FileSystemFileHandle==null||((i=globalThis.navigator)==null?void 0:i.storage.getDirectory)==null)&&(Ww(),await Vw()))})();function Xh(){const i=`${Math.random().toString().slice(2)}-${Date.now()}`;return $h.push(i),ai(`${Vh}/${i}`)}const $w={0:"debug",1:"info",2:"warn",3:"error"};function Xw(i){if(i instanceof Error)return String(i);if(typeof i=="object"&&i!==null)try{return JSON.stringify(i,(e,t)=>t instanceof Error?String(t):t)}catch{return String(i)}return String(i)}function Yw(){const i=new Date,e=s=>s.toString().padStart(2,"0"),t=i.getMilliseconds().toString().padStart(3,"0");return`${e(i.getHours())}:${e(i.getMinutes())}:${e(i.getSeconds())}.${t}`}class qw{threshold=1;history=[];debug=(...e)=>this.log(0,console.debug,e);info=(...e)=>this.log(1,console.info,e);warn=(...e)=>this.log(2,console.warn,e);error=(...e)=>this.log(3,console.error,e);log(e,t,s){e>=this.threshold&&(t(...s),this.history.push({level:$w[e],time:Yw(),args:s}))}setThreshold(e){this.threshold=e}getThreshold(){return this.threshold}createTagged(e){return{debug:(...t)=>this.debug(e,...t),info:(...t)=>this.info(e,...t),warn:(...t)=>this.warn(e,...t),error:(...t)=>this.error(e,...t)}}dump(){return this.history.map(({level:e,time:t,args:s})=>`[${e.toUpperCase()}][${t}] ${s.map(Xw).join(" ")}`).join(`
|
|
4
|
+
`)}}const Tt=new qw,q={debug:Tt.debug,info:Tt.info,warn:Tt.warn,error:Tt.error,setLogLevel:i=>{const e=i;e===q.debug?Tt.setThreshold(0):e===q.info?Tt.setThreshold(1):e===q.warn?Tt.setThreshold(2):e===q.error&&Tt.setThreshold(3)},create:i=>Tt.createTagged(i),dump:async()=>Tt.dump()};class Kw{constructor(e,t,s){this.length_=e,this.scaleFactor_=(e-1)/t,this.interpolate=this.cubic,s.method==="point"?this.interpolate=this.point:s.method==="linear"?this.interpolate=this.linear:s.method==="sinc"&&(this.interpolate=this.sinc),this.tangentFactor_=1-Math.max(0,Math.min(1,s.tension||0)),this.sincFilterSize_=s.sincFilterSize||1,this.kernel_=Zw(s.sincWindow||jw)}point(e,t){return this.getClippedInput_(Math.round(this.scaleFactor_*e),t)}linear(e,t){e=this.scaleFactor_*e;let s=Math.floor(e);return e-=s,(1-e)*this.getClippedInput_(s,t)+e*this.getClippedInput_(s+1,t)}cubic(e,t){e=this.scaleFactor_*e;let s=Math.floor(e),r=[this.getTangent_(s,t),this.getTangent_(s+1,t)],n=[this.getClippedInput_(s,t),this.getClippedInput_(s+1,t)];e-=s;let o=e*e,a=e*o;return(2*a-3*o+1)*n[0]+(a-2*o+e)*r[0]+(-2*a+3*o)*n[1]+(a-o)*r[1]}sinc(e,t){e=this.scaleFactor_*e;let s=Math.floor(e),r=s-this.sincFilterSize_+1,n=s+this.sincFilterSize_,o=0;for(let a=r;a<=n;a++)o+=this.kernel_(e-a)*this.getClippedInput_(a,t);return o}getTangent_(e,t){return this.tangentFactor_*(this.getClippedInput_(e+1,t)-this.getClippedInput_(e-1,t))/2}getClippedInput_(e,t){return 0<=e&&e<this.length_?t[e]:0}}function jw(i){return Math.exp(-i/2*i/2)}function Zw(i){return function(e){return Jw(e)*i(e)}}function Jw(i){return i===0?1:Math.sin(Math.PI*i)/(Math.PI*i)}class Qw{constructor(e,t,s){let r=2*Math.PI*s/t,n=0;this.filters=[];for(let o=0;o<=e;o++)o-e/2===0?this.filters[o]=r:(this.filters[o]=Math.sin(r*(o-e/2))/(o-e/2),this.filters[o]*=.54-.46*Math.cos(2*Math.PI*o/e)),n=n+this.filters[o];for(let o=0;o<=e;o++)this.filters[o]/=n;this.z=this.initZ_()}filter(e){this.z.buf[this.z.pointer]=e;let t=0;for(let s=0,r=this.z.buf.length;s<r;s++)t+=this.filters[s]*this.z.buf[(this.z.pointer+s)%this.z.buf.length];return this.z.pointer=(this.z.pointer+1)%this.z.buf.length,t}reset(){this.z=this.initZ_()}initZ_(){let e=[];for(let t=0;t<this.filters.length-1;t++)e.push(0);return{buf:e,pointer:0}}}class e1{constructor(e,t,s){let r=[];for(let n=0;n<e;n++)r.push(this.getCoeffs_({Fs:t,Fc:s,Q:.5/Math.sin(Math.PI/(e*2)*(n+.5))}));this.stages=[];for(let n=0;n<r.length;n++)this.stages[n]={b0:r[n].b[0],b1:r[n].b[1],b2:r[n].b[2],a1:r[n].a[0],a2:r[n].a[1],k:r[n].k,z:[0,0]}}filter(e){let t=e;for(let s=0,r=this.stages.length;s<r;s++)t=this.runStage_(s,t);return t}getCoeffs_(e){let t={};t.z=[0,0],t.a=[],t.b=[];let s=this.preCalc_(e,t);return t.k=1,t.b.push((1-s.cw)/(2*s.a0)),t.b.push(2*t.b[0]),t.b.push(t.b[0]),t}preCalc_(e,t){let s={},r=2*Math.PI*e.Fc/e.Fs;return s.alpha=Math.sin(r)/(2*e.Q),s.cw=Math.cos(r),s.a0=1+s.alpha,t.a0=s.a0,t.a.push(-2*s.cw/s.a0),t.k=1,t.a.push((1-s.alpha)/s.a0),s}runStage_(e,t){let s=t*this.stages[e].k-this.stages[e].a1*this.stages[e].z[0]-this.stages[e].a2*this.stages[e].z[1],r=this.stages[e].b0*s+this.stages[e].b1*this.stages[e].z[0]+this.stages[e].b2*this.stages[e].z[1];return this.stages[e].z[1]=this.stages[e].z[0],this.stages[e].z[0]=s,r}reset(){for(let e=0;e<this.stages.length;e++)this.stages[e].z=[0,0]}}const t1={point:!1,linear:!1,cubic:!0,sinc:!0},Ep={IIR:16,FIR:71},i1={IIR:e1,FIR:Qw};function s1(i,e,t,s={}){let r=(t-e)/e+1,n=new Float64Array(i.length*r);s.method=s.method||"cubic";let o=new Kw(i.length,n.length,{method:s.method,tension:s.tension||0,sincFilterSize:s.sincFilterSize||6,sincWindow:s.sincWindow||void 0});if(s.LPF===void 0&&(s.LPF=t1[s.method]),s.LPF){s.LPFType=s.LPFType||"IIR";const a=i1[s.LPFType];if(t>e){let l=new a(s.LPFOrder||Ep[s.LPFType],t,e/2);r1(i,n,o,l)}else{let l=new a(s.LPFOrder||Ep[s.LPFType],e,t/2);n1(i,n,o,l)}}else Ip(i,n,o);return n}function Ip(i,e,t){for(let s=0,r=e.length;s<r;s++)e[s]=t.interpolate(s,i)}function r1(i,e,t,s){for(let r=0,n=e.length;r<n;r++)e[r]=s.filter(t.interpolate(r,i));s.reset();for(let r=e.length-1;r>=0;r--)e[r]=s.filter(e[r])}function n1(i,e,t,s){for(let r=0,n=i.length;r<n;r++)i[r]=s.filter(i[r]);s.reset();for(let r=i.length-1;r>=0;r--)i[r]=s.filter(i[r]);Ip(i,e,t)}function o1(i){const e=new Float32Array(i.map(s=>s.length).reduce((s,r)=>s+r));let t=0;for(const s of i)e.set(s,t),t+=s.length;return e}function Pp(i){const e=[];for(let t=0;t<i.length;t+=1)for(let s=0;s<i[t].length;s+=1)e[s]==null&&(e[s]=[]),e[s].push(i[t][s]);return e.map(o1)}function Rp(i){if(i.format==="f32-planar"){const e=[];for(let t=0;t<i.numberOfChannels;t+=1){const s=i.allocationSize({planeIndex:t}),r=new ArrayBuffer(s);i.copyTo(r,{planeIndex:t}),e.push(new Float32Array(r))}return e}else if(i.format==="f32"){const e=new ArrayBuffer(i.allocationSize({planeIndex:0}));return i.copyTo(e,{planeIndex:0}),l1(new Float32Array(e),i.numberOfChannels)}else if(i.format==="s16"){const e=new ArrayBuffer(i.allocationSize({planeIndex:0}));return i.copyTo(e,{planeIndex:0}),a1(new Int16Array(e),i.numberOfChannels)}throw Error("Unsupported audio data format")}function a1(i,e){const t=i.length/e,s=Array.from({length:e},()=>new Float32Array(t));for(let r=0;r<t;r++)for(let n=0;n<e;n++){const o=i[r*e+n];s[n][r]=o/32768}return s}function l1(i,e){const t=i.length/e,s=Array.from({length:e},()=>new Float32Array(t));for(let r=0;r<t;r++)for(let n=0;n<e;n++)s[n][r]=i[r*e+n];return s}function Yh(i){return Array(i.numberOfChannels).fill(0).map((e,t)=>i.getChannelData(t))}function Mp(i){const e=Math.max(...i.map(s=>s[0]?.length??0)),t=new Float32Array(e*2);for(let s=0;s<e;s++){let r=0,n=0;for(let o=0;o<i.length;o++){const a=i[o][0]?.[s]??0,l=i[o][1]?.[s]??a;r+=a,n+=l}t[s]=r,t[s+e]=n}return t}async function c1(i,e,t){const s=i.length,r=Array(t.chanCount).fill(0).map(()=>new Float32Array(0));if(s===0)return r;const n=Math.max(...i.map(c=>c.length));if(n===0)return r;if(globalThis.OfflineAudioContext==null)return i.map(c=>new Float32Array(s1(c,e,t.rate,{method:"sinc",LPF:!1})));const o=new globalThis.OfflineAudioContext(t.chanCount,n*t.rate/e,t.rate),a=o.createBufferSource(),l=o.createBuffer(s,n,e);return i.forEach((c,h)=>l.copyToChannel(new Float32Array(c),h)),a.buffer=l,a.connect(o.destination),a.start(),Yh(await o.startRendering())}function qh(i,e,t){const s=t-e,r=new Float32Array(s);let n=0;for(;n<s;)r[n]=i[(e+n)%i.length],n+=1;return r}function kp(i,e){const t=Math.floor(i.length/e),s=new Float32Array(t);for(let r=0;r<t;r++){const n=r*e,o=Math.floor(n),a=n-o;o+1<i.length?s[r]=i[o]*(1-a)+i[o+1]*a:s[r]=i[o]}return s}const h1=[{codec:"mp4a.40.2",codecType:"aac",sampleRate:48e3,channelCount:2},{codec:"opus",codecType:"opus",sampleRate:48e3,channelCount:2}];let Pi=null;function u1(){if(typeof navigator>"u")return"unknown";const i=navigator.userAgent.toLowerCase();return i.includes("linux")?"linux":i.includes("mac")?"macos":i.includes("win")?"windows":"unknown"}async function d1(i){if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported({codec:i.codec,sampleRate:i.sampleRate,numberOfChannels:i.channelCount})).supported??!1}catch{return!1}}async function f1(){if(Pi!==null)return Pi;const i=u1();for(const t of h1)if(await d1(t))return Pi={...t},console.log(`[AudioCodec] Selected ${t.codec} for ${i}`),Pi;const e={codec:"opus",codecType:"opus",sampleRate:48e3,channelCount:2};return console.warn("[AudioCodec] No supported codec found, falling back to Opus"),Pi=e,e}function Ar(){return Pi}const p1=`#version 300 es
|
|
5
5
|
layout (location = 0) in vec4 a_position;
|
|
6
6
|
layout (location = 1) in vec2 a_texCoord;
|
|
7
7
|
out vec2 v_texCoord;
|
|
@@ -49,7 +49,7 @@ void main() {
|
|
|
49
49
|
rgba.rgb = mix(vec3(desat, desat, desat), rgba.rgb, spillVal);
|
|
50
50
|
FragColor = rgba;
|
|
51
51
|
}
|
|
52
|
-
`,g1=[-1,1,-1,-1,1,-1,1,-1,1,1,-1,1],
|
|
52
|
+
`,g1=[-1,1,-1,-1,1,-1,1,-1,1,1,-1,1],x1=[0,1,0,0,1,0,1,0,1,1,0,1];function _1(i,e,t){const s=Fp(i,i.VERTEX_SHADER,e),r=Fp(i,i.FRAGMENT_SHADER,t),n=i.createProgram();if(i.attachShader(n,s),i.attachShader(n,r),i.linkProgram(n),!i.getProgramParameter(n,i.LINK_STATUS))throw Error(i.getProgramInfoLog(n)??"Unable to initialize the shader program");return n}function Fp(i,e,t){const s=i.createShader(e);if(i.shaderSource(s,t),i.compileShader(s),!i.getShaderParameter(s,i.COMPILE_STATUS)){const r=i.getShaderInfoLog(s);throw i.deleteShader(s),Error(r??"An error occurred compiling the shaders")}return s}function y1(i,e,t){i.bindTexture(i.TEXTURE_2D,t),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,e),i.drawArrays(i.TRIANGLES,0,6)}function v1(i){const e=i.createTexture();if(e==null)throw Error("Create WebGL texture error");i.bindTexture(i.TEXTURE_2D,e);const t=0,s=i.RGBA,r=1,n=1,o=0,a=i.RGBA,l=i.UNSIGNED_BYTE,c=new Uint8Array([0,0,255,255]);return i.texImage2D(i.TEXTURE_2D,t,s,r,n,o,a,l,c),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.LINEAR),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),e}function b1(i){const e="document"in globalThis?globalThis.document.createElement("canvas"):new OffscreenCanvas(i.width,i.height);e.width=i.width,e.height=i.height;const t=e.getContext("webgl2",{premultipliedAlpha:!1,alpha:!0});if(t==null)throw Error("Cant create gl context");const s=_1(t,p1,m1);t.useProgram(s),t.uniform3fv(t.getUniformLocation(s,"keyColor"),i.keyColor.map(l=>l/255)),t.uniform1f(t.getUniformLocation(s,"similarity"),i.similarity),t.uniform1f(t.getUniformLocation(s,"smoothness"),i.smoothness),t.uniform1f(t.getUniformLocation(s,"spill"),i.spill);const r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.bufferData(t.ARRAY_BUFFER,new Float32Array(g1),t.STATIC_DRAW);const n=t.getAttribLocation(s,"a_position");t.vertexAttribPointer(n,2,t.FLOAT,!1,Float32Array.BYTES_PER_ELEMENT*2,0),t.enableVertexAttribArray(n);const o=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,o),t.bufferData(t.ARRAY_BUFFER,new Float32Array(x1),t.STATIC_DRAW);const a=t.getAttribLocation(s,"a_texCoord");return t.vertexAttribPointer(a,2,t.FLOAT,!1,Float32Array.BYTES_PER_ELEMENT*2,0),t.enableVertexAttribArray(a),t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,1),{canvas:e,gl:t}}function T1(i){return i instanceof VideoFrame?{width:i.codedWidth,height:i.codedHeight}:{width:i.width,height:i.height}}function w1(i){const t=new OffscreenCanvas(1,1).getContext("2d");t.drawImage(i,0,0);const{data:[s,r,n]}=t.getImageData(0,0,1,1);return[s,r,n]}const S1=i=>{let e=null,t=null,s=i.keyColor,r=null;return async n=>{if((e==null||t==null||r==null)&&(s==null&&(s=w1(n)),{canvas:e,gl:t}=b1({...T1(n),keyColor:s,...i}),r=v1(t)),y1(t,n,r),globalThis.VideoFrame!=null&&n instanceof globalThis.VideoFrame){const o=new VideoFrame(e,{alpha:"keep",timestamp:n.timestamp,duration:n.duration??void 0});return n.close(),o}return createImageBitmap(e,{imageOrientation:n instanceof ImageBitmap?"flipY":"none"})}},C1=()=>{let i,e=16.6;self.onmessage=t=>{t.data.event==="start"&&(self.clearInterval(i),i=self.setInterval(()=>{self.postMessage({})},e)),t.data.event==="stop"&&self.clearInterval(i)}},A1=()=>{const i=new Blob([`(${C1.toString()})()`]),e=URL.createObjectURL(i);return new Worker(e)},Ri=new Map;let Kh=1,Er=null;globalThis.Worker!=null&&(Er=A1(),Er.onmessage=()=>{Kh+=1;for(const[i,e]of Ri)if(Kh%i===0)for(const t of e)t()});const E1=(i,e)=>{const t=Math.round(e/16.6),s=Ri.get(t)??new Set;return s.add(i),Ri.set(t,s),Ri.size===1&&s.size===1&&Er?.postMessage({event:"start"}),()=>{s.delete(i),s.size===0&&Ri.delete(t),Ri.size===0&&(Kh=0,Er?.postMessage({event:"stop"}))}};function jh(i){return new Promise(e=>{const t=E1(()=>{t(),e()},i)})}function I1(i){return document.createElement(i)}function P1(i){var e="",t=new Uint8Array(i),s=t.byteLength;for(let r=0;r<s;r++)e+=String.fromCharCode(t[r]);return window.btoa(e)}async function R1(i,e,t={}){const s=I1("pre");s.style.cssText=`margin: 0; ${e}; position: fixed;`,s.textContent=i,document.body.appendChild(s),t.onCreated?.(s);const{width:r,height:n}=s.getBoundingClientRect();s.remove();const o=new Image;o.width=r,o.height=n;const a=t.font==null?"":`
|
|
53
53
|
@font-face {
|
|
54
54
|
font-family: '${t.font.name}';
|
|
55
55
|
src: url('data:font/woff2;base64,${P1(await(await fetch(t.font.url)).arrayBuffer())}') format('woff2');
|
|
@@ -63,10 +63,10 @@ void main() {
|
|
|
63
63
|
<div xmlns="http://www.w3.org/1999/xhtml">${s.outerHTML}</div>
|
|
64
64
|
</foreignObject>
|
|
65
65
|
</svg>
|
|
66
|
-
`.replace(/\t/g,"").replace(/#/g,"%23");return o.src=`data:image/svg+xml;charset=utf-8,${l}`,await new Promise(c=>{o.onload=c}),o}async function M1(i,e,t={}){const s=await R1(i,e,t),r=new OffscreenCanvas(s.width,s.height);return r.getContext("2d")?.drawImage(s,0,0,s.width,s.height),await createImageBitmap(r)}async function k1(i,e){const t={type:e,data:i},s=new ImageDecoder(t);await Promise.all([s.completed,s.tracks.ready]);const r=s.tracks.selectedTrack?.frameCount??1,n=[];for(let o=0;o<r;o+=1)n.push((await s.decode({frameIndex:o})).image);return n}let Zh=class{all=new Map;on(e,t){const s=this.all.get(e);return s?s.push(t):this.all.set(e,[t]),()=>this.off(e,t)}once(e,t){const s=this.on(e,r=>{s(),t(r)});return s}off(e,t){const s=this.all.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let s=this.all.get(e);s&&s.slice().forEach(r=>{r(t)}),s=this.all.get("*"),s&&s.slice().forEach(r=>{r(e,t)})}};class F1 extends Zh{id="";display={from:0,to:0};duration=0;playbackRate=1;trim={from:0,to:0};constructor(){super()}_left=0;get left(){return this._left}set left(e){const t=this._left!==e;this._left=e,t&&this.emit("propsChange",{left:e})}_top=0;get top(){return this._top}set top(e){const t=this._top!==e;this._top=e,t&&this.emit("propsChange",{top:e})}_width=0;get width(){return this._width}set width(e){const t=this._width!==e;this._width=e,t&&this.emit("propsChange",{width:e})}_height=0;get height(){return this._height}set height(e){const t=this._height!==e;this._height=e,t&&this.emit("propsChange",{height:e})}_angle=0;get angle(){return this._angle}set angle(e){const t=this._angle!==e;this._angle=e,t&&this.emit("propsChange",{angle:e})}get center(){return{x:this.left+this.width/2,y:this.top+this.height/2}}_zIndex=0;get zIndex(){return this._zIndex}set zIndex(e){const t=this._zIndex!==e;this._zIndex=e,t&&this.emit("propsChange",{zIndex:e})}_opacity=1;get opacity(){return this._opacity}set opacity(e){const t=this._opacity!==e;this._opacity=e,t&&this.emit("propsChange",{opacity:e})}_volume=1;get volume(){return this._volume}set volume(e){const t=this._volume!==e;this._volume=e,t&&this.emit("propsChange",{volume:e})}flip=null;effects=[];_style={};get style(){return this._style}set style(e){this._style=e}animatKeyFrame=null;animatOpts=null;ready=Promise.resolve();_render(e){const{center:t}=this;e.setTransform(this.flip==="horizontal"?-1:1,0,0,this.flip==="vertical"?-1:1,t.x,t.y);const s=this.angle*Math.PI/180;e.rotate((this.flip==null?1:-1)*s),e.globalAlpha=this.opacity}setAnimation(e,t){this.animatKeyFrame=Object.entries(e).map(([s,r])=>{const n={from:0,to:100}[s]??Number(s.slice(0,-1));if(isNaN(n)||n>100||n<0)throw Error("keyFrame must between 0~100");return[n/100,r]}),this.animatOpts=Object.assign({},this.animatOpts,{duration:t.duration,delay:t.delay??0,iterCount:t.iterCount??1/0})}animate(e){if(this.animatKeyFrame==null||this.animatOpts==null||e<this.animatOpts.delay)return;const t=B1(e,this.animatKeyFrame,this.animatOpts);for(const s in t)switch(s){case"opacity":this.opacity=t[s];break;case"x":this.left=t[s];break;case"y":this.top=t[s];break;case"w":this.width=t[s];break;case"h":this.height=t[s];break;case"angle":this.angle=t[s];break}}copyStateTo(e){e.animatKeyFrame=this.animatKeyFrame,e.animatOpts=this.animatOpts,e.zIndex=this.zIndex,e.opacity=this.opacity,e.volume=this.volume,e.flip=this.flip,e.left=this.left,e.top=this.top,e.width=this.width,e.height=this.height,e.angle=this.angle,e.display={...this.display},e.duration=this.duration,e.playbackRate=this.playbackRate,e.trim={...this.trim},e.style=JSON.parse(JSON.stringify(this.style||{})),"src"in this&&"src"in e&&(e.src=this.src)}update(e){Object.assign(this,e),this.emit("propsChange",e)}destroy(){this.all.clear()}}function B1(i,e,t){const s=i-t.delay,r=s%t.duration,n=s/t.duration>=t.iterCount||s===t.duration?1:r/t.duration,o=e.findIndex(f=>f[0]>=n);if(o===-1)return{};const a=e[o-1],l=e[o],c=l[1];if(a==null)return c;const h=a[1],u={},d=(n-a[0])/(l[0]-a[0]);for(const f in c){if(!Object.hasOwn(c,f)||typeof f!="string")continue;const p=f;h[p]!=null&&(u[p]=(c[p]-h[p])*d+h[p])}return u}class qt extends F1{lastVf=null;destroyed=!1;src="";transition;constructor(){super()}async getFrame(e){const t=e*this.playbackRate,{video:s,audio:r,state:n}=await this.tick(t);let o=r??[];r!=null&&this.playbackRate!==1&&(o=r.map(l=>kp(l,this.playbackRate)));let a=null;return s!=null?(this.lastVf?.close(),s instanceof VideoFrame?(a=await createImageBitmap(s),s.close()):a=s,this.lastVf=a):this.lastVf!=null&&(a=this.lastVf),{video:a,audio:o,done:n==="done"}}async offscreenRender(e,t){const s=t*this.playbackRate;this.animate(s),super._render(e);const{width:r,height:n}=this,{video:o,audio:a,state:l}=await this.tick(s);let c=a??[];if(a!=null&&this.playbackRate!==1&&(c=a.map(u=>kp(u,this.playbackRate))),l==="done")return{audio:c,done:!0};const h=o??this.lastVf;if(h!=null){const u=this.style.borderRadius||0,d=this.style.dropShadow;if(e.save(),d&&(d.blur>0||d.distance>0)){const p=d.distance??0,g=d.angle??0;e.shadowColor=d.color||"#000000",e.shadowBlur=d.blur||0,e.shadowOffsetX=Math.cos(g)*p,e.shadowOffsetY=Math.sin(g)*p}if(u>0){const p=Math.min(u,r/2,n/2);e.beginPath(),e.roundRect(-r/2,-n/2,r,n,p),e.clip()}e.drawImage(h,-r/2,-n/2,r,n),e.restore();const f=this.style.stroke;if(f&&f.width>0){if(e.save(),e.strokeStyle=f.color,e.lineWidth=f.width,u>0){const p=Math.min(u,r/2,n/2);e.beginPath(),e.roundRect(-r/2,-n/2,r,n,p),e.stroke()}else e.strokeRect(-r/2,-n/2,r,n);e.restore()}}return o!=null&&(this.lastVf?.close(),o instanceof ImageBitmap&&(this.lastVf=o)),{audio:c,done:!1}}set(e,t=30){if(e.display&&(e.display.from!==void 0&&(this.display.from=e.display.from<1e6?e.display.from/t*1e6:e.display.from),e.display.to!==void 0&&(this.display.to=e.display.to<1e6?e.display.to/t*1e6:e.display.to)),e.x!==void 0&&(this.left=e.x),e.y!==void 0&&(this.top=e.y),e.width!==void 0&&(this.width=e.width),e.height!==void 0&&(this.height=e.height),e.duration!==void 0){const s=e.duration<1e6?e.duration/t*1e6:e.duration;this.duration=s,this.display.from!==void 0&&(this.display.to=this.display.from+s)}return this}toJSON(e=!1){const t=this.animatKeyFrame&&this.animatOpts?{keyFrames:this.animatKeyFrame.reduce((s,[r,n])=>{const o=r===0?"from":r===1?"to":`${Math.round(r*100)}%`;return s[o]=n,s},{}),opts:this.animatOpts}:void 0;return{type:this.constructor.name,src:this.src,display:{from:this.display.from,to:this.display.to},playbackRate:this.playbackRate,duration:this.duration,left:this.left,top:this.top,width:this.width,height:this.height,angle:this.angle,zIndex:this.zIndex,opacity:this.opacity,flip:this.flip,style:this.style,trim:{from:this.trim.from,to:this.trim.to},...t&&{animation:t},...e&&{main:!0}}}getVisibleHandles(){return["tl","tr","bl","br","ml","mr","mt","mb","rot"]}async scaleToFit(e,t){await this.ready;const{width:s,height:r}=this.meta;if(s===0||r===0)return;const n=Math.min(e/s,t/r);this.width=s*n,this.height=r*n}async scaleToFill(e,t){await this.ready;const{width:s,height:r}=this.meta;if(s===0||r===0)return;const n=Math.max(e/s,t/r);this.width=s*n,this.height=r*n}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}destroy(){this.destroyed||(this.destroyed=!0,K.info("BaseClip destroy"),super.destroy(),this.lastVf?.close(),this.lastVf=null)}}let Jh=null;async function Bp(){return Jh===null&&(Jh=f1()),await Jh}const le={get codec(){return Ar()?.codec??"mp4a.40.2"},get codecType(){return Ar()?.codecType??"aac"},get sampleRate(){return Ar()?.sampleRate??48e3},get channelCount(){return Ar()?.channelCount??2}};class Ke extends qt{type="Audio";static ctx=null;ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta,sampleRate:le.sampleRate,chanCount:2}}chan0Buf=new Float32Array;chan1Buf=new Float32Array;getPCMData(){return[this.chan0Buf,this.chan1Buf]}opts;loop=!1;static async fromUrl(e,t={}){const s=await fetch(e);if(!s.ok)throw new Error(`Failed to fetch audio from ${e}: ${s.status} ${s.statusText}`);const r=new Ke(s.body,t,e);return await r.ready,r}static async fromObject(e){if(e.type!=="Audio")throw new Error(`Expected Audio, got ${e.type}`);if(!e.src||e.src.trim()==="")throw new Error("Audio requires a valid source URL");const t={};e.loop!==void 0&&(t.loop=e.loop),e.volume!==void 0&&(t.volume=e.volume);const s=await Ke.fromUrl(e.src,t);return s.left=e.left,s.top=e.top,s.width=e.width,s.height=e.height,s.angle=e.angle,s.display.from=e.display.from,s.display.to=e.display.to,s.duration=e.duration,s.playbackRate=e.playbackRate,s.zIndex=e.zIndex,s.opacity=e.opacity,s.flip=e.flip,e.animation&&s.setAnimation(e.animation.keyFrames,e.animation.opts),s}constructor(e,t={},s){super(),this.src=s!==void 0?s:"",this.opts={loop:!1,volume:1,...t},this.loop=this.opts.loop??!1,this.volume=this.opts.volume??1,this.ready=this.init(e).then(r=>{const n={width:0,height:0,duration:t.loop?1/0:this._meta.duration};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration=this.duration===0?n.duration:this.duration,this.display.to=this.display.from+this.duration,n})}async init(e){Ke.ctx==null&&(Ke.ctx=new AudioContext({sampleRate:le.sampleRate}));const t=performance.now(),s=e instanceof ReadableStream?await O1(e,Ke.ctx):e;K.info("Audio clip decoded complete:",performance.now()-t),this._meta.duration=s[0].length/le.sampleRate*1e6,this.chan0Buf=s[0],this.chan1Buf=s[1]??this.chan0Buf,K.info("Audio clip convert to AudioData, time:",performance.now()-t)}tickInterceptor=async(e,t)=>t;timestamp=0;frameOffset=0;async tick(e){if(!this.opts.loop&&e>=this._meta.duration)return await this.tickInterceptor(e,{audio:[],state:"done"});const t=e-this.timestamp;if(e<this.timestamp||t>3e6)return this.timestamp=e,this.frameOffset=Math.ceil(this.timestamp/1e6*le.sampleRate),await this.tickInterceptor(e,{audio:[new Float32Array(0),new Float32Array(0)],state:"success"});this.timestamp=e;const s=Math.ceil(t/1e6*le.sampleRate),r=this.frameOffset+s,n=this.opts.loop?[qh(this.chan0Buf,this.frameOffset,r),qh(this.chan1Buf,this.frameOffset,r)]:[this.chan0Buf.slice(this.frameOffset,r),this.chan1Buf.slice(this.frameOffset,r)];if(this.volume!==1)for(const o of n)for(let a=0;a<o.length;a++)o[a]*=this.volume;return this.frameOffset=r,await this.tickInterceptor(e,{audio:n,state:"success"})}async split(e){await this.ready;const t=Math.ceil(e/1e6*le.sampleRate),s=new Ke(this.getPCMData().map(n=>n.slice(0,t)),this.opts,this.src),r=new Ke(this.getPCMData().map(n=>n.slice(t)),this.opts,this.src);return[s,r]}async clone(){await this.ready;const e=new Ke(this.getPCMData(),this.opts,this.src);return await e.ready,this.copyStateTo(e),e}destroy(){this.chan0Buf=new Float32Array(0),this.chan1Buf=new Float32Array(0),K.info("---- audioclip destroy ----"),super.destroy()}toJSON(e=!1){return{...super.toJSON(e),type:"Audio",loop:this.loop,id:this.id,volume:this.volume}}static concatAudio=U1;async createPlaybackElement(){if(await this.ready,!this.src||this.src.trim()==="")throw new Error("Audio requires a source URL for playback");const e=this.src.startsWith("blob:")?this.src:void 0,t=document.createElement("audio");return t.crossOrigin="anonymous",t.autoplay=!1,t.preload="auto",t.loop=this.opts.loop||!1,t.src=this.src,await new Promise((s,r)=>{const n=()=>{t.removeEventListener("loadeddata",n),t.removeEventListener("error",o),t.pause(),t.currentTime=0,s()},o=()=>{t.removeEventListener("loadeddata",n),t.removeEventListener("error",o),r(new Error("Failed to load audio"))};t.addEventListener("loadeddata",n,{once:!0}),t.addEventListener("error",o,{once:!0}),t.load()}),{element:t,objectUrl:e}}async play(e,t){const s=e;if(Math.abs(s.currentTime-t)>.1&&(s.currentTime=t),s.paused)try{await s.play()}catch{try{await s.play()}catch(n){console.warn("Failed to play audio:",n)}}}pause(e){e.pause()}async seek(e,t){const s=e;return s.pause(),s.currentTime=t,new Promise(r=>{if(Math.abs(s.currentTime-t)<.01){r();return}const n=()=>{s.removeEventListener("seeked",n),r()};s.addEventListener("seeked",n,{once:!0}),setTimeout(()=>{s.removeEventListener("seeked",n),r()},500)})}syncPlayback(e,t,s){const r=e,n=this.meta.duration/1e6,o=s>=0&&s<n;r.volume=this.volume,t&&o?r.paused&&this.play(r,s).catch(console.warn):(r.paused||r.pause(),o&&Math.abs(r.currentTime-s)>.1&&(r.currentTime=s))}cleanupPlayback(e,t){const s=e;s.pause(),s.removeAttribute("src"),s.load(),t&&t.startsWith("blob:")&&URL.revokeObjectURL(t)}}async function U1(i,e){const t=[];for(const s of i)await s.ready,t.push(s.getPCMData());return new Ke(Pp(t),e)}async function O1(i,e){const t=await new Response(i).arrayBuffer();return Yh(await e.decodeAudioData(t))}var b=(i=>(i.Application="application",i.WebGLPipes="webgl-pipes",i.WebGLPipesAdaptor="webgl-pipes-adaptor",i.WebGLSystem="webgl-system",i.WebGPUPipes="webgpu-pipes",i.WebGPUPipesAdaptor="webgpu-pipes-adaptor",i.WebGPUSystem="webgpu-system",i.CanvasSystem="canvas-system",i.CanvasPipesAdaptor="canvas-pipes-adaptor",i.CanvasPipes="canvas-pipes",i.Asset="asset",i.LoadParser="load-parser",i.ResolveParser="resolve-parser",i.CacheParser="cache-parser",i.DetectionParser="detection-parser",i.MaskEffect="mask-effect",i.BlendMode="blend-mode",i.TextureSource="texture-source",i.Environment="environment",i.ShapeBuilder="shape-builder",i.Batcher="batcher",i))(b||{});const Qh=i=>{if(typeof i=="function"||typeof i=="object"&&i.extension){if(!i.extension)throw new Error("Extension class must have an extension object");i={...typeof i.extension!="object"?{type:i.extension}:i.extension,ref:i}}if(typeof i=="object")i={...i};else throw new Error("Invalid extension type");return typeof i.type=="string"&&(i.type=[i.type]),i},Ir=(i,e)=>Qh(i).priority??e,V={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...i){return i.map(Qh).forEach(e=>{e.type.forEach(t=>this._removeHandlers[t]?.(e))}),this},add(...i){return i.map(Qh).forEach(e=>{e.type.forEach(t=>{const s=this._addHandlers,r=this._queue;s[t]?s[t]?.(e):(r[t]=r[t]||[],r[t]?.push(e))})}),this},handle(i,e,t){const s=this._addHandlers,r=this._removeHandlers;if(s[i]||r[i])throw new Error(`Extension type ${i} already has a handler`);s[i]=e,r[i]=t;const n=this._queue;return n[i]&&(n[i]?.forEach(o=>e(o)),delete n[i]),this},handleByMap(i,e){return this.handle(i,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(i,e,t=-1){return this.handle(i,s=>{e.findIndex(n=>n.name===s.name)>=0||(e.push({name:s.name,value:s.ref}),e.sort((n,o)=>Ir(o.value,t)-Ir(n.value,t)))},s=>{const r=e.findIndex(n=>n.name===s.name);r!==-1&&e.splice(r,1)})},handleByList(i,e,t=-1){return this.handle(i,s=>{e.includes(s.ref)||(e.push(s.ref),e.sort((r,n)=>Ir(n,t)-Ir(r,t)))},s=>{const r=e.indexOf(s.ref);r!==-1&&e.splice(r,1)})},mixin(i,...e){for(const t of e)Object.defineProperties(i.prototype,Object.getOwnPropertyDescriptors(t))}},D1={extension:{type:b.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>gk)}},G1={extension:{type:b.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>_k)}};class Be{constructor(e,t,s){this._x=t||0,this._y=s||0,this._observer=e}clone(e){return new Be(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}function eu(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var tu={exports:{}},Up;function z1(){return Up||(Up=1,(function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function n(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new r(h,u||l,d),p=t?t+c:c;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c]}function a(){this._events=new s,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},a.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,p=new Array(f);d<f;d++)p[d]=u[d].fn;return p},a.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},a.prototype.emit=function(c,h,u,d,f,p){var g=t?t+c:c;if(!this._events[g])return!1;var m=this._events[g],_=arguments.length,x,y;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),_){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,h),!0;case 3:return m.fn.call(m.context,h,u),!0;case 4:return m.fn.call(m.context,h,u,d),!0;case 5:return m.fn.call(m.context,h,u,d,f),!0;case 6:return m.fn.call(m.context,h,u,d,f,p),!0}for(y=1,x=new Array(_-1);y<_;y++)x[y-1]=arguments[y];m.fn.apply(m.context,x)}else{var v=m.length,T;for(y=0;y<v;y++)switch(m[y].once&&this.removeListener(c,m[y].fn,void 0,!0),_){case 1:m[y].fn.call(m[y].context);break;case 2:m[y].fn.call(m[y].context,h);break;case 3:m[y].fn.call(m[y].context,h,u);break;case 4:m[y].fn.call(m[y].context,h,u,d);break;default:if(!x)for(T=1,x=new Array(_-1);T<_;T++)x[T-1]=arguments[T];m[y].fn.apply(m[y].context,x)}}return!0},a.prototype.on=function(c,h,u){return n(this,c,h,u,!1)},a.prototype.once=function(c,h,u){return n(this,c,h,u,!0)},a.prototype.removeListener=function(c,h,u,d){var f=t?t+c:c;if(!this._events[f])return this;if(!h)return o(this,f),this;var p=this._events[f];if(p.fn)p.fn===h&&(!d||p.once)&&(!u||p.context===u)&&o(this,f);else{for(var g=0,m=[],_=p.length;g<_;g++)(p[g].fn!==h||d&&!p[g].once||u&&p[g].context!==u)&&m.push(p[g]);m.length?this._events[f]=m.length===1?m[0]:m:o(this,f)}return this},a.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&o(this,h)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,i.exports=a})(tu)),tu.exports}var N1=z1();const je=eu(N1),L1=Math.PI*2,H1=180/Math.PI,W1=Math.PI/180;class X{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new X(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return iu.x=0,iu.y=0,iu}}const iu=new X;class O{constructor(e=1,t=0,s=0,r=1,n=0,o=0){this.array=null,this.a=e,this.b=t,this.c=s,this.d=r,this.tx=n,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,s,r,n,o){return this.a=e,this.b=t,this.c=s,this.d=r,this.tx=n,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const s=t||this.array;return e?(s[0]=this.a,s[1]=this.b,s[2]=0,s[3]=this.c,s[4]=this.d,s[5]=0,s[6]=this.tx,s[7]=this.ty,s[8]=1):(s[0]=this.a,s[1]=this.c,s[2]=this.tx,s[3]=this.b,s[4]=this.d,s[5]=this.ty,s[6]=0,s[7]=0,s[8]=1),s}apply(e,t){t=t||new X;const s=e.x,r=e.y;return t.x=this.a*s+this.c*r+this.tx,t.y=this.b*s+this.d*r+this.ty,t}applyInverse(e,t){t=t||new X;const s=this.a,r=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,c=1/(s*o+n*-r),h=e.x,u=e.y;return t.x=o*c*h+-n*c*u+(l*n-a*o)*c,t.y=s*c*u+-r*c*h+(-l*s+a*r)*c,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),s=Math.sin(e),r=this.a,n=this.c,o=this.tx;return this.a=r*t-this.b*s,this.b=r*s+this.b*t,this.c=n*t-this.d*s,this.d=n*s+this.d*t,this.tx=o*t-this.ty*s,this.ty=o*s+this.ty*t,this}append(e){const t=this.a,s=this.b,r=this.c,n=this.d;return this.a=e.a*t+e.b*r,this.b=e.a*s+e.b*n,this.c=e.c*t+e.d*r,this.d=e.c*s+e.d*n,this.tx=e.tx*t+e.ty*r+this.tx,this.ty=e.tx*s+e.ty*n+this.ty,this}appendFrom(e,t){const s=e.a,r=e.b,n=e.c,o=e.d,a=e.tx,l=e.ty,c=t.a,h=t.b,u=t.c,d=t.d;return this.a=s*c+r*u,this.b=s*h+r*d,this.c=n*c+o*u,this.d=n*h+o*d,this.tx=a*c+l*u+t.tx,this.ty=a*h+l*d+t.ty,this}setTransform(e,t,s,r,n,o,a,l,c){return this.a=Math.cos(a+c)*n,this.b=Math.sin(a+c)*n,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=e-(s*this.a+r*this.c),this.ty=t-(s*this.b+r*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const s=this.a,r=this.c;this.a=s*e.a+this.b*e.c,this.b=s*e.b+this.b*e.d,this.c=r*e.a+this.d*e.c,this.d=r*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,s=this.b,r=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-r,n),l=Math.atan2(s,t),c=Math.abs(a+l);return c<1e-5||Math.abs(L1-c)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=Math.sqrt(t*t+s*s),e.scale.y=Math.sqrt(r*r+n*n),e.position.x=this.tx+(o.x*t+o.y*r),e.position.y=this.ty+(o.x*s+o.y*n),e}invert(){const e=this.a,t=this.b,s=this.c,r=this.d,n=this.tx,o=e*r-t*s;return this.a=r/o,this.b=-t/o,this.c=-s/o,this.d=e/o,this.tx=(s*this.ty-r*n)/o,this.ty=-(e*this.ty-t*n)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const e=new O;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return $1.identity()}static get shared(){return V1.identity()}}const V1=new O,$1=new O,li=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],ci=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],hi=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],ui=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],su=[],Op=[],Pr=Math.sign;function X1(){for(let i=0;i<16;i++){const e=[];su.push(e);for(let t=0;t<16;t++){const s=Pr(li[i]*li[t]+hi[i]*ci[t]),r=Pr(ci[i]*li[t]+ui[i]*ci[t]),n=Pr(li[i]*hi[t]+hi[i]*ui[t]),o=Pr(ci[i]*hi[t]+ui[i]*ui[t]);for(let a=0;a<16;a++)if(li[a]===s&&ci[a]===r&&hi[a]===n&&ui[a]===o){e.push(a);break}}}for(let i=0;i<16;i++){const e=new O;e.set(li[i],ci[i],hi[i],ui[i],0,0),Op.push(e)}}X1();const oe={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:i=>li[i],uY:i=>ci[i],vX:i=>hi[i],vY:i=>ui[i],inv:i=>i&8?i&15:-i&7,add:(i,e)=>su[i][e],sub:(i,e)=>su[i][oe.inv(e)],rotate180:i=>i^4,isVertical:i=>(i&3)===2,byDirection:(i,e)=>Math.abs(i)*2<=Math.abs(e)?e>=0?oe.S:oe.N:Math.abs(e)*2<=Math.abs(i)?i>0?oe.E:oe.W:e>0?i>0?oe.SE:oe.SW:i>0?oe.NE:oe.NW,matrixAppendRotationInv:(i,e,t=0,s=0)=>{const r=Op[oe.inv(e)];r.tx=t,r.ty=s,i.append(r)},transformRectCoords:(i,e,t,s)=>{const{x:r,y:n,width:o,height:a}=i,{x:l,y:c,width:h,height:u}=e;return t===oe.E?(s.set(r+l,n+c,o,a),s):t===oe.S?s.set(h-n-a+l,r+c,a,o):t===oe.W?s.set(h-r-o+l,u-n-a+c,o,a):t===oe.N?s.set(n+l,u-r-o+c,a,o):s.set(r+l,n+c,o,a)}},Rr=[new X,new X,new X,new X];class H{constructor(e=0,t=0,s=0,r=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(s),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new H(0,0,0,0)}clone(){return new H(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,s,r=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,c=s*(1-r),h=s-c,u=a-c,d=a+n+c,f=l-c,p=l+o+c,g=a+h,m=a+n-h,_=l+h,x=l+o-h;return e>=u&&e<=d&&t>=f&&t<=p&&!(e>g&&e<m&&t>_&&t<x)}intersects(e,t){if(!t){const E=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=E)return!1;const C=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>C}const s=this.left,r=this.right,n=this.top,o=this.bottom;if(r<=s||o<=n)return!1;const a=Rr[0].set(e.left,e.top),l=Rr[1].set(e.left,e.bottom),c=Rr[2].set(e.right,e.top),h=Rr[3].set(e.right,e.bottom);if(c.x<=a.x||l.y<=a.y)return!1;const u=Math.sign(t.a*t.d-t.b*t.c);if(u===0||(t.apply(a,a),t.apply(l,l),t.apply(c,c),t.apply(h,h),Math.max(a.x,l.x,c.x,h.x)<=s||Math.min(a.x,l.x,c.x,h.x)>=r||Math.max(a.y,l.y,c.y,h.y)<=n||Math.min(a.y,l.y,c.y,h.y)>=o))return!1;const d=u*(l.y-a.y),f=u*(a.x-l.x),p=d*s+f*n,g=d*r+f*n,m=d*s+f*o,_=d*r+f*o;if(Math.max(p,g,m,_)<=d*a.x+f*a.y||Math.min(p,g,m,_)>=d*h.x+f*h.y)return!1;const x=u*(a.y-c.y),y=u*(c.x-a.x),v=x*s+y*n,T=x*r+y*n,S=x*s+y*o,w=x*r+y*o;return!(Math.max(v,T,S,w)<=x*a.x+y*a.y||Math.min(v,T,S,w)>=x*h.x+y*h.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),s=Math.min(this.x+this.width,e.x+e.width),r=Math.max(this.y,e.y),n=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(s-t,0),this.y=r,this.height=Math.max(n-r,0),this}ceil(e=1,t=.001){const s=Math.ceil((this.x+this.width-t)*e)/e,r=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=s-this.x,this.height=r-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),s=Math.max(this.x+this.width,e.x+e.width),r=Math.min(this.y,e.y),n=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=s-t,this.y=r,this.height=n-r,this}getBounds(e){return e||(e=new H),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,s=e.y,r=e.x+e.width,n=e.y+e.height;return t>=this.x&&t<this.x+this.width&&s>=this.y&&s<this.y+this.height&&r>=this.x&&r<this.x+this.width&&n>=this.y&&n<this.y+this.height}set(e,t,s,r){return this.x=e,this.y=t,this.width=s,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const ru={default:-1};function he(i="default"){return ru[i]===void 0&&(ru[i]=-1),++ru[i]}const Dp=new Set,Q="8.0.0",Y1="8.3.4",Mi={quiet:!1,noColor:!1},W=(i,e,t=3)=>{if(Mi.quiet||Dp.has(e))return;let s=new Error().stack;const r=`${e}
|
|
66
|
+
`.replace(/\t/g,"").replace(/#/g,"%23");return o.src=`data:image/svg+xml;charset=utf-8,${l}`,await new Promise(c=>{o.onload=c}),o}async function M1(i,e,t={}){const s=await R1(i,e,t),r=new OffscreenCanvas(s.width,s.height);return r.getContext("2d")?.drawImage(s,0,0,s.width,s.height),await createImageBitmap(r)}async function k1(i,e){const t={type:e,data:i},s=new ImageDecoder(t);await Promise.all([s.completed,s.tracks.ready]);const r=s.tracks.selectedTrack?.frameCount??1,n=[];for(let o=0;o<r;o+=1)n.push((await s.decode({frameIndex:o})).image);return n}let Zh=class{all=new Map;on(e,t){const s=this.all.get(e);return s?s.push(t):this.all.set(e,[t]),()=>this.off(e,t)}once(e,t){const s=this.on(e,r=>{s(),t(r)});return s}off(e,t){const s=this.all.get(e);s&&(t?s.splice(s.indexOf(t)>>>0,1):this.all.set(e,[]))}emit(e,t){let s=this.all.get(e);s&&s.slice().forEach(r=>{r(t)}),s=this.all.get("*"),s&&s.slice().forEach(r=>{r(e,t)})}};class F1 extends Zh{id="";display={from:0,to:0};duration=0;playbackRate=1;trim={from:0,to:0};constructor(){super()}_left=0;get left(){return this._left}set left(e){const t=this._left!==e;this._left=e,t&&this.emit("propsChange",{left:e})}_top=0;get top(){return this._top}set top(e){const t=this._top!==e;this._top=e,t&&this.emit("propsChange",{top:e})}_width=0;get width(){return this._width}set width(e){const t=this._width!==e;this._width=e,t&&this.emit("propsChange",{width:e})}_height=0;get height(){return this._height}set height(e){const t=this._height!==e;this._height=e,t&&this.emit("propsChange",{height:e})}_angle=0;get angle(){return this._angle}set angle(e){const t=this._angle!==e;this._angle=e,t&&this.emit("propsChange",{angle:e})}get center(){return{x:this.left+this.width/2,y:this.top+this.height/2}}_zIndex=0;get zIndex(){return this._zIndex}set zIndex(e){const t=this._zIndex!==e;this._zIndex=e,t&&this.emit("propsChange",{zIndex:e})}_opacity=1;get opacity(){return this._opacity}set opacity(e){const t=this._opacity!==e;this._opacity=e,t&&this.emit("propsChange",{opacity:e})}_volume=1;get volume(){return this._volume}set volume(e){const t=this._volume!==e;this._volume=e,t&&this.emit("propsChange",{volume:e})}flip=null;effects=[];_style={};get style(){return this._style}set style(e){this._style=e}animatKeyFrame=null;animatOpts=null;ready=Promise.resolve();_render(e){const{center:t}=this;e.setTransform(this.flip==="horizontal"?-1:1,0,0,this.flip==="vertical"?-1:1,t.x,t.y);const s=this.angle*Math.PI/180;e.rotate((this.flip==null?1:-1)*s),e.globalAlpha=this.opacity}setAnimation(e,t){this.animatKeyFrame=Object.entries(e).map(([s,r])=>{const n={from:0,to:100}[s]??Number(s.slice(0,-1));if(isNaN(n)||n>100||n<0)throw Error("keyFrame must between 0~100");return[n/100,r]}),this.animatOpts=Object.assign({},this.animatOpts,{duration:t.duration,delay:t.delay??0,iterCount:t.iterCount??1/0})}animate(e){if(this.animatKeyFrame==null||this.animatOpts==null||e<this.animatOpts.delay)return;const t=B1(e,this.animatKeyFrame,this.animatOpts);for(const s in t)switch(s){case"opacity":this.opacity=t[s];break;case"x":this.left=t[s];break;case"y":this.top=t[s];break;case"w":this.width=t[s];break;case"h":this.height=t[s];break;case"angle":this.angle=t[s];break}}copyStateTo(e){e.animatKeyFrame=this.animatKeyFrame,e.animatOpts=this.animatOpts,e.zIndex=this.zIndex,e.opacity=this.opacity,e.volume=this.volume,e.flip=this.flip,e.left=this.left,e.top=this.top,e.width=this.width,e.height=this.height,e.angle=this.angle,e.display={...this.display},e.duration=this.duration,e.playbackRate=this.playbackRate,e.trim={...this.trim},e.style=JSON.parse(JSON.stringify(this.style||{})),"src"in this&&"src"in e&&(e.src=this.src)}update(e){Object.assign(this,e),this.emit("propsChange",e)}destroy(){this.all.clear()}}function B1(i,e,t){const s=i-t.delay,r=s%t.duration,n=s/t.duration>=t.iterCount||s===t.duration?1:r/t.duration,o=e.findIndex(f=>f[0]>=n);if(o===-1)return{};const a=e[o-1],l=e[o],c=l[1];if(a==null)return c;const h=a[1],u={},d=(n-a[0])/(l[0]-a[0]);for(const f in c){if(!Object.hasOwn(c,f)||typeof f!="string")continue;const p=f;h[p]!=null&&(u[p]=(c[p]-h[p])*d+h[p])}return u}class qt extends F1{lastVf=null;destroyed=!1;src="";transition;constructor(){super()}async getFrame(e){const t=e*this.playbackRate,{video:s,audio:r,state:n}=await this.tick(t);let o=r??[];r!=null&&this.playbackRate!==1&&(o=r.map(l=>kp(l,this.playbackRate)));let a=null;return s!=null?(this.lastVf?.close(),s instanceof VideoFrame?(a=await createImageBitmap(s),s.close()):a=s,this.lastVf=a):this.lastVf!=null&&(a=this.lastVf),{video:a,audio:o,done:n==="done"}}async offscreenRender(e,t){const s=t*this.playbackRate;this.animate(s),super._render(e);const{width:r,height:n}=this,{video:o,audio:a,state:l}=await this.tick(s);let c=a??[];if(a!=null&&this.playbackRate!==1&&(c=a.map(u=>kp(u,this.playbackRate))),l==="done")return{audio:c,done:!0};const h=o??this.lastVf;if(h!=null){const u=this.style.borderRadius||0,d=this.style.dropShadow;if(e.save(),d&&(d.blur>0||d.distance>0)){const p=d.distance??0,g=d.angle??0;e.shadowColor=d.color||"#000000",e.shadowBlur=d.blur||0,e.shadowOffsetX=Math.cos(g)*p,e.shadowOffsetY=Math.sin(g)*p}if(u>0){const p=Math.min(u,r/2,n/2);e.beginPath(),e.roundRect(-r/2,-n/2,r,n,p),e.clip()}e.drawImage(h,-r/2,-n/2,r,n),e.restore();const f=this.style.stroke;if(f&&f.width>0){if(e.save(),e.strokeStyle=f.color,e.lineWidth=f.width,u>0){const p=Math.min(u,r/2,n/2);e.beginPath(),e.roundRect(-r/2,-n/2,r,n,p),e.stroke()}else e.strokeRect(-r/2,-n/2,r,n);e.restore()}}return o!=null&&(this.lastVf?.close(),o instanceof ImageBitmap&&(this.lastVf=o)),{audio:c,done:!1}}set(e,t=30){if(e.display&&(e.display.from!==void 0&&(this.display.from=e.display.from<1e6?e.display.from/t*1e6:e.display.from),e.display.to!==void 0&&(this.display.to=e.display.to<1e6?e.display.to/t*1e6:e.display.to)),e.x!==void 0&&(this.left=e.x),e.y!==void 0&&(this.top=e.y),e.width!==void 0&&(this.width=e.width),e.height!==void 0&&(this.height=e.height),e.duration!==void 0){const s=e.duration<1e6?e.duration/t*1e6:e.duration;this.duration=s,this.display.from!==void 0&&(this.display.to=this.display.from+s)}return this}toJSON(e=!1){const t=this.animatKeyFrame&&this.animatOpts?{keyFrames:this.animatKeyFrame.reduce((s,[r,n])=>{const o=r===0?"from":r===1?"to":`${Math.round(r*100)}%`;return s[o]=n,s},{}),opts:this.animatOpts}:void 0;return{type:this.constructor.name,src:this.src,display:{from:this.display.from,to:this.display.to},playbackRate:this.playbackRate,duration:this.duration,left:this.left,top:this.top,width:this.width,height:this.height,angle:this.angle,zIndex:this.zIndex,opacity:this.opacity,flip:this.flip,style:this.style,trim:{from:this.trim.from,to:this.trim.to},...t&&{animation:t},...e&&{main:!0}}}getVisibleHandles(){return["tl","tr","bl","br","ml","mr","mt","mb","rot"]}async scaleToFit(e,t){await this.ready;const{width:s,height:r}=this.meta;if(s===0||r===0)return;const n=Math.min(e/s,t/r);this.width=s*n,this.height=r*n}async scaleToFill(e,t){await this.ready;const{width:s,height:r}=this.meta;if(s===0||r===0)return;const n=Math.max(e/s,t/r);this.width=s*n,this.height=r*n}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}destroy(){this.destroyed||(this.destroyed=!0,q.info("BaseClip destroy"),super.destroy(),this.lastVf?.close(),this.lastVf=null)}}let Jh=null;async function Bp(){return Jh===null&&(Jh=f1()),await Jh}const le={get codec(){return Ar()?.codec??"mp4a.40.2"},get codecType(){return Ar()?.codecType??"aac"},get sampleRate(){return Ar()?.sampleRate??48e3},get channelCount(){return Ar()?.channelCount??2}};class Ke extends qt{type="Audio";static ctx=null;ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta,sampleRate:le.sampleRate,chanCount:2}}chan0Buf=new Float32Array;chan1Buf=new Float32Array;getPCMData(){return[this.chan0Buf,this.chan1Buf]}opts;loop=!1;static async fromUrl(e,t={}){const s=await fetch(e);if(!s.ok)throw new Error(`Failed to fetch audio from ${e}: ${s.status} ${s.statusText}`);const r=new Ke(s.body,t,e);return await r.ready,r}static async fromObject(e){if(e.type!=="Audio")throw new Error(`Expected Audio, got ${e.type}`);if(!e.src||e.src.trim()==="")throw new Error("Audio requires a valid source URL");const t={};e.loop!==void 0&&(t.loop=e.loop),e.volume!==void 0&&(t.volume=e.volume);const s=await Ke.fromUrl(e.src,t);return s.left=e.left,s.top=e.top,s.width=e.width,s.height=e.height,s.angle=e.angle,s.display.from=e.display.from,s.display.to=e.display.to,s.duration=e.duration,s.playbackRate=e.playbackRate,s.zIndex=e.zIndex,s.opacity=e.opacity,s.flip=e.flip,e.animation&&s.setAnimation(e.animation.keyFrames,e.animation.opts),s}constructor(e,t={},s){super(),this.src=s!==void 0?s:"",this.opts={loop:!1,volume:1,...t},this.loop=this.opts.loop??!1,this.volume=this.opts.volume??1,this.ready=this.init(e).then(r=>{const n={width:0,height:0,duration:t.loop?1/0:this._meta.duration};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration=this.duration===0?n.duration:this.duration,this.display.to=this.display.from+this.duration,n})}async init(e){Ke.ctx==null&&(Ke.ctx=new AudioContext({sampleRate:le.sampleRate}));const t=performance.now(),s=e instanceof ReadableStream?await O1(e,Ke.ctx):e;q.info("Audio clip decoded complete:",performance.now()-t),this._meta.duration=s[0].length/le.sampleRate*1e6,this.chan0Buf=s[0],this.chan1Buf=s[1]??this.chan0Buf,q.info("Audio clip convert to AudioData, time:",performance.now()-t)}tickInterceptor=async(e,t)=>t;timestamp=0;frameOffset=0;async tick(e){if(!this.opts.loop&&e>=this._meta.duration)return await this.tickInterceptor(e,{audio:[],state:"done"});const t=e-this.timestamp;if(e<this.timestamp||t>3e6)return this.timestamp=e,this.frameOffset=Math.ceil(this.timestamp/1e6*le.sampleRate),await this.tickInterceptor(e,{audio:[new Float32Array(0),new Float32Array(0)],state:"success"});this.timestamp=e;const s=Math.ceil(t/1e6*le.sampleRate),r=this.frameOffset+s,n=this.opts.loop?[qh(this.chan0Buf,this.frameOffset,r),qh(this.chan1Buf,this.frameOffset,r)]:[this.chan0Buf.slice(this.frameOffset,r),this.chan1Buf.slice(this.frameOffset,r)];if(this.volume!==1)for(const o of n)for(let a=0;a<o.length;a++)o[a]*=this.volume;return this.frameOffset=r,await this.tickInterceptor(e,{audio:n,state:"success"})}async split(e){await this.ready;const t=Math.ceil(e/1e6*le.sampleRate),s=new Ke(this.getPCMData().map(n=>n.slice(0,t)),this.opts,this.src),r=new Ke(this.getPCMData().map(n=>n.slice(t)),this.opts,this.src);return[s,r]}async clone(){await this.ready;const e=new Ke(this.getPCMData(),this.opts,this.src);return await e.ready,this.copyStateTo(e),e}destroy(){this.chan0Buf=new Float32Array(0),this.chan1Buf=new Float32Array(0),q.info("---- audioclip destroy ----"),super.destroy()}toJSON(e=!1){return{...super.toJSON(e),type:"Audio",loop:this.loop,id:this.id,volume:this.volume}}static concatAudio=U1;async createPlaybackElement(){if(await this.ready,!this.src||this.src.trim()==="")throw new Error("Audio requires a source URL for playback");const e=this.src.startsWith("blob:")?this.src:void 0,t=document.createElement("audio");return t.crossOrigin="anonymous",t.autoplay=!1,t.preload="auto",t.loop=this.opts.loop||!1,t.src=this.src,await new Promise((s,r)=>{const n=()=>{t.removeEventListener("loadeddata",n),t.removeEventListener("error",o),t.pause(),t.currentTime=0,s()},o=()=>{t.removeEventListener("loadeddata",n),t.removeEventListener("error",o),r(new Error("Failed to load audio"))};t.addEventListener("loadeddata",n,{once:!0}),t.addEventListener("error",o,{once:!0}),t.load()}),{element:t,objectUrl:e}}async play(e,t){const s=e;if(Math.abs(s.currentTime-t)>.1&&(s.currentTime=t),s.paused)try{await s.play()}catch{try{await s.play()}catch(n){console.warn("Failed to play audio:",n)}}}pause(e){e.pause()}async seek(e,t){const s=e;return s.pause(),s.currentTime=t,new Promise(r=>{if(Math.abs(s.currentTime-t)<.01){r();return}const n=()=>{s.removeEventListener("seeked",n),r()};s.addEventListener("seeked",n,{once:!0}),setTimeout(()=>{s.removeEventListener("seeked",n),r()},500)})}syncPlayback(e,t,s){const r=e,n=this.meta.duration/1e6,o=s>=0&&s<n;r.volume=this.volume,t&&o?r.paused&&this.play(r,s).catch(console.warn):(r.paused||r.pause(),o&&Math.abs(r.currentTime-s)>.1&&(r.currentTime=s))}cleanupPlayback(e,t){const s=e;s.pause(),s.removeAttribute("src"),s.load(),t&&t.startsWith("blob:")&&URL.revokeObjectURL(t)}}async function U1(i,e){const t=[];for(const s of i)await s.ready,t.push(s.getPCMData());return new Ke(Pp(t),e)}async function O1(i,e){const t=await new Response(i).arrayBuffer();return Yh(await e.decodeAudioData(t))}var b=(i=>(i.Application="application",i.WebGLPipes="webgl-pipes",i.WebGLPipesAdaptor="webgl-pipes-adaptor",i.WebGLSystem="webgl-system",i.WebGPUPipes="webgpu-pipes",i.WebGPUPipesAdaptor="webgpu-pipes-adaptor",i.WebGPUSystem="webgpu-system",i.CanvasSystem="canvas-system",i.CanvasPipesAdaptor="canvas-pipes-adaptor",i.CanvasPipes="canvas-pipes",i.Asset="asset",i.LoadParser="load-parser",i.ResolveParser="resolve-parser",i.CacheParser="cache-parser",i.DetectionParser="detection-parser",i.MaskEffect="mask-effect",i.BlendMode="blend-mode",i.TextureSource="texture-source",i.Environment="environment",i.ShapeBuilder="shape-builder",i.Batcher="batcher",i))(b||{});const Qh=i=>{if(typeof i=="function"||typeof i=="object"&&i.extension){if(!i.extension)throw new Error("Extension class must have an extension object");i={...typeof i.extension!="object"?{type:i.extension}:i.extension,ref:i}}if(typeof i=="object")i={...i};else throw new Error("Invalid extension type");return typeof i.type=="string"&&(i.type=[i.type]),i},Ir=(i,e)=>Qh(i).priority??e,V={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...i){return i.map(Qh).forEach(e=>{e.type.forEach(t=>this._removeHandlers[t]?.(e))}),this},add(...i){return i.map(Qh).forEach(e=>{e.type.forEach(t=>{const s=this._addHandlers,r=this._queue;s[t]?s[t]?.(e):(r[t]=r[t]||[],r[t]?.push(e))})}),this},handle(i,e,t){const s=this._addHandlers,r=this._removeHandlers;if(s[i]||r[i])throw new Error(`Extension type ${i} already has a handler`);s[i]=e,r[i]=t;const n=this._queue;return n[i]&&(n[i]?.forEach(o=>e(o)),delete n[i]),this},handleByMap(i,e){return this.handle(i,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(i,e,t=-1){return this.handle(i,s=>{e.findIndex(n=>n.name===s.name)>=0||(e.push({name:s.name,value:s.ref}),e.sort((n,o)=>Ir(o.value,t)-Ir(n.value,t)))},s=>{const r=e.findIndex(n=>n.name===s.name);r!==-1&&e.splice(r,1)})},handleByList(i,e,t=-1){return this.handle(i,s=>{e.includes(s.ref)||(e.push(s.ref),e.sort((r,n)=>Ir(n,t)-Ir(r,t)))},s=>{const r=e.indexOf(s.ref);r!==-1&&e.splice(r,1)})},mixin(i,...e){for(const t of e)Object.defineProperties(i.prototype,Object.getOwnPropertyDescriptors(t))}},D1={extension:{type:b.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>gk)}},G1={extension:{type:b.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>xk)}};class Be{constructor(e,t,s){this._x=t||0,this._y=s||0,this._observer=e}clone(e){return new Be(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}function eu(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var tu={exports:{}},Up;function z1(){return Up||(Up=1,(function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function r(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function n(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new r(h,u||l,d),p=t?t+c:c;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],f]:l._events[p].push(f):(l._events[p]=f,l._eventsCount++),l}function o(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c]}function a(){this._events=new s,this._eventsCount=0}a.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},a.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,p=new Array(f);d<f;d++)p[d]=u[d].fn;return p},a.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},a.prototype.emit=function(c,h,u,d,f,p){var g=t?t+c:c;if(!this._events[g])return!1;var m=this._events[g],x=arguments.length,_,y;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),x){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,h),!0;case 3:return m.fn.call(m.context,h,u),!0;case 4:return m.fn.call(m.context,h,u,d),!0;case 5:return m.fn.call(m.context,h,u,d,f),!0;case 6:return m.fn.call(m.context,h,u,d,f,p),!0}for(y=1,_=new Array(x-1);y<x;y++)_[y-1]=arguments[y];m.fn.apply(m.context,_)}else{var v=m.length,T;for(y=0;y<v;y++)switch(m[y].once&&this.removeListener(c,m[y].fn,void 0,!0),x){case 1:m[y].fn.call(m[y].context);break;case 2:m[y].fn.call(m[y].context,h);break;case 3:m[y].fn.call(m[y].context,h,u);break;case 4:m[y].fn.call(m[y].context,h,u,d);break;default:if(!_)for(T=1,_=new Array(x-1);T<x;T++)_[T-1]=arguments[T];m[y].fn.apply(m[y].context,_)}}return!0},a.prototype.on=function(c,h,u){return n(this,c,h,u,!1)},a.prototype.once=function(c,h,u){return n(this,c,h,u,!0)},a.prototype.removeListener=function(c,h,u,d){var f=t?t+c:c;if(!this._events[f])return this;if(!h)return o(this,f),this;var p=this._events[f];if(p.fn)p.fn===h&&(!d||p.once)&&(!u||p.context===u)&&o(this,f);else{for(var g=0,m=[],x=p.length;g<x;g++)(p[g].fn!==h||d&&!p[g].once||u&&p[g].context!==u)&&m.push(p[g]);m.length?this._events[f]=m.length===1?m[0]:m:o(this,f)}return this},a.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&o(this,h)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,i.exports=a})(tu)),tu.exports}var N1=z1();const je=eu(N1),L1=Math.PI*2,H1=180/Math.PI,W1=Math.PI/180;class X{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new X(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return iu.x=0,iu.y=0,iu}}const iu=new X;class O{constructor(e=1,t=0,s=0,r=1,n=0,o=0){this.array=null,this.a=e,this.b=t,this.c=s,this.d=r,this.tx=n,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,s,r,n,o){return this.a=e,this.b=t,this.c=s,this.d=r,this.tx=n,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const s=t||this.array;return e?(s[0]=this.a,s[1]=this.b,s[2]=0,s[3]=this.c,s[4]=this.d,s[5]=0,s[6]=this.tx,s[7]=this.ty,s[8]=1):(s[0]=this.a,s[1]=this.c,s[2]=this.tx,s[3]=this.b,s[4]=this.d,s[5]=this.ty,s[6]=0,s[7]=0,s[8]=1),s}apply(e,t){t=t||new X;const s=e.x,r=e.y;return t.x=this.a*s+this.c*r+this.tx,t.y=this.b*s+this.d*r+this.ty,t}applyInverse(e,t){t=t||new X;const s=this.a,r=this.b,n=this.c,o=this.d,a=this.tx,l=this.ty,c=1/(s*o+n*-r),h=e.x,u=e.y;return t.x=o*c*h+-n*c*u+(l*n-a*o)*c,t.y=s*c*u+-r*c*h+(-l*s+a*r)*c,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),s=Math.sin(e),r=this.a,n=this.c,o=this.tx;return this.a=r*t-this.b*s,this.b=r*s+this.b*t,this.c=n*t-this.d*s,this.d=n*s+this.d*t,this.tx=o*t-this.ty*s,this.ty=o*s+this.ty*t,this}append(e){const t=this.a,s=this.b,r=this.c,n=this.d;return this.a=e.a*t+e.b*r,this.b=e.a*s+e.b*n,this.c=e.c*t+e.d*r,this.d=e.c*s+e.d*n,this.tx=e.tx*t+e.ty*r+this.tx,this.ty=e.tx*s+e.ty*n+this.ty,this}appendFrom(e,t){const s=e.a,r=e.b,n=e.c,o=e.d,a=e.tx,l=e.ty,c=t.a,h=t.b,u=t.c,d=t.d;return this.a=s*c+r*u,this.b=s*h+r*d,this.c=n*c+o*u,this.d=n*h+o*d,this.tx=a*c+l*u+t.tx,this.ty=a*h+l*d+t.ty,this}setTransform(e,t,s,r,n,o,a,l,c){return this.a=Math.cos(a+c)*n,this.b=Math.sin(a+c)*n,this.c=-Math.sin(a-l)*o,this.d=Math.cos(a-l)*o,this.tx=e-(s*this.a+r*this.c),this.ty=t-(s*this.b+r*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const s=this.a,r=this.c;this.a=s*e.a+this.b*e.c,this.b=s*e.b+this.b*e.d,this.c=r*e.a+this.d*e.c,this.d=r*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,s=this.b,r=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-r,n),l=Math.atan2(s,t),c=Math.abs(a+l);return c<1e-5||Math.abs(L1-c)<1e-5?(e.rotation=l,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=l),e.scale.x=Math.sqrt(t*t+s*s),e.scale.y=Math.sqrt(r*r+n*n),e.position.x=this.tx+(o.x*t+o.y*r),e.position.y=this.ty+(o.x*s+o.y*n),e}invert(){const e=this.a,t=this.b,s=this.c,r=this.d,n=this.tx,o=e*r-t*s;return this.a=r/o,this.b=-t/o,this.c=-s/o,this.d=e/o,this.tx=(s*this.ty-r*n)/o,this.ty=-(e*this.ty-t*n)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const e=new O;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return $1.identity()}static get shared(){return V1.identity()}}const V1=new O,$1=new O,li=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],ci=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],hi=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],ui=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],su=[],Op=[],Pr=Math.sign;function X1(){for(let i=0;i<16;i++){const e=[];su.push(e);for(let t=0;t<16;t++){const s=Pr(li[i]*li[t]+hi[i]*ci[t]),r=Pr(ci[i]*li[t]+ui[i]*ci[t]),n=Pr(li[i]*hi[t]+hi[i]*ui[t]),o=Pr(ci[i]*hi[t]+ui[i]*ui[t]);for(let a=0;a<16;a++)if(li[a]===s&&ci[a]===r&&hi[a]===n&&ui[a]===o){e.push(a);break}}}for(let i=0;i<16;i++){const e=new O;e.set(li[i],ci[i],hi[i],ui[i],0,0),Op.push(e)}}X1();const oe={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:i=>li[i],uY:i=>ci[i],vX:i=>hi[i],vY:i=>ui[i],inv:i=>i&8?i&15:-i&7,add:(i,e)=>su[i][e],sub:(i,e)=>su[i][oe.inv(e)],rotate180:i=>i^4,isVertical:i=>(i&3)===2,byDirection:(i,e)=>Math.abs(i)*2<=Math.abs(e)?e>=0?oe.S:oe.N:Math.abs(e)*2<=Math.abs(i)?i>0?oe.E:oe.W:e>0?i>0?oe.SE:oe.SW:i>0?oe.NE:oe.NW,matrixAppendRotationInv:(i,e,t=0,s=0)=>{const r=Op[oe.inv(e)];r.tx=t,r.ty=s,i.append(r)},transformRectCoords:(i,e,t,s)=>{const{x:r,y:n,width:o,height:a}=i,{x:l,y:c,width:h,height:u}=e;return t===oe.E?(s.set(r+l,n+c,o,a),s):t===oe.S?s.set(h-n-a+l,r+c,a,o):t===oe.W?s.set(h-r-o+l,u-n-a+c,o,a):t===oe.N?s.set(n+l,u-r-o+c,a,o):s.set(r+l,n+c,o,a)}},Rr=[new X,new X,new X,new X];class H{constructor(e=0,t=0,s=0,r=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(s),this.height=Number(r)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new H(0,0,0,0)}clone(){return new H(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,s,r=.5){const{width:n,height:o}=this;if(n<=0||o<=0)return!1;const a=this.x,l=this.y,c=s*(1-r),h=s-c,u=a-c,d=a+n+c,f=l-c,p=l+o+c,g=a+h,m=a+n-h,x=l+h,_=l+o-h;return e>=u&&e<=d&&t>=f&&t<=p&&!(e>g&&e<m&&t>x&&t<_)}intersects(e,t){if(!t){const E=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=E)return!1;const C=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>C}const s=this.left,r=this.right,n=this.top,o=this.bottom;if(r<=s||o<=n)return!1;const a=Rr[0].set(e.left,e.top),l=Rr[1].set(e.left,e.bottom),c=Rr[2].set(e.right,e.top),h=Rr[3].set(e.right,e.bottom);if(c.x<=a.x||l.y<=a.y)return!1;const u=Math.sign(t.a*t.d-t.b*t.c);if(u===0||(t.apply(a,a),t.apply(l,l),t.apply(c,c),t.apply(h,h),Math.max(a.x,l.x,c.x,h.x)<=s||Math.min(a.x,l.x,c.x,h.x)>=r||Math.max(a.y,l.y,c.y,h.y)<=n||Math.min(a.y,l.y,c.y,h.y)>=o))return!1;const d=u*(l.y-a.y),f=u*(a.x-l.x),p=d*s+f*n,g=d*r+f*n,m=d*s+f*o,x=d*r+f*o;if(Math.max(p,g,m,x)<=d*a.x+f*a.y||Math.min(p,g,m,x)>=d*h.x+f*h.y)return!1;const _=u*(a.y-c.y),y=u*(c.x-a.x),v=_*s+y*n,T=_*r+y*n,S=_*s+y*o,w=_*r+y*o;return!(Math.max(v,T,S,w)<=_*a.x+y*a.y||Math.min(v,T,S,w)>=_*h.x+y*h.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),s=Math.min(this.x+this.width,e.x+e.width),r=Math.max(this.y,e.y),n=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(s-t,0),this.y=r,this.height=Math.max(n-r,0),this}ceil(e=1,t=.001){const s=Math.ceil((this.x+this.width-t)*e)/e,r=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=s-this.x,this.height=r-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),s=Math.max(this.x+this.width,e.x+e.width),r=Math.min(this.y,e.y),n=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=s-t,this.y=r,this.height=n-r,this}getBounds(e){return e||(e=new H),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,s=e.y,r=e.x+e.width,n=e.y+e.height;return t>=this.x&&t<this.x+this.width&&s>=this.y&&s<this.y+this.height&&r>=this.x&&r<this.x+this.width&&n>=this.y&&n<this.y+this.height}set(e,t,s,r){return this.x=e,this.y=t,this.width=s,this.height=r,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const ru={default:-1};function he(i="default"){return ru[i]===void 0&&(ru[i]=-1),++ru[i]}const Dp=new Set,Q="8.0.0",Y1="8.3.4",Mi={quiet:!1,noColor:!1},W=(i,e,t=3)=>{if(Mi.quiet||Dp.has(e))return;let s=new Error().stack;const r=`${e}
|
|
67
67
|
Deprecated since v${i}`,n=typeof console.groupCollapsed=="function"&&!Mi.noColor;typeof s>"u"?console.warn("PixiJS Deprecation Warning: ",r):(s=s.split(`
|
|
68
68
|
`).splice(t).join(`
|
|
69
|
-
`),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",r),console.warn(s),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",r),console.warn(s))),Dp.add(e)};Object.defineProperties(W,{quiet:{get:()=>Mi.quiet,set:i=>{Mi.quiet=i},enumerable:!0,configurable:!1},noColor:{get:()=>Mi.noColor,set:i=>{Mi.noColor=i},enumerable:!0,configurable:!1}});const Gp=()=>{};function ki(i){return i+=i===0?1:0,--i,i|=i>>>1,i|=i>>>2,i|=i>>>4,i|=i>>>8,i|=i>>>16,i+1}function zp(i){return!(i&i-1)&&!!i}function Np(i){const e={};for(const t in i)i[t]!==void 0&&(e[t]=i[t]);return e}const Lp=Object.create(null);function q1(i){const e=Lp[i];return e===void 0&&(Lp[i]=he("resource")),e}const Hp=class Kx extends je{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...Kx.defaultOptions,...e},this.addressMode=e.addressMode,this.addressModeU=e.addressModeU??this.addressModeU,this.addressModeV=e.addressModeV??this.addressModeV,this.addressModeW=e.addressModeW??this.addressModeW,this.scaleMode=e.scaleMode,this.magFilter=e.magFilter??this.magFilter,this.minFilter=e.minFilter??this.minFilter,this.mipmapFilter=e.mipmapFilter??this.mipmapFilter,this.lodMinClamp=e.lodMinClamp,this.lodMaxClamp=e.lodMaxClamp,this.compare=e.compare,this.maxAnisotropy=e.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){W(Q,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this.emit("change",this),this._sharedResourceId=null}_generateResourceId(){const e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=q1(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};Hp.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let wt=Hp;const Wp=class jx extends je{constructor(e={}){super(),this.options=e,this.uid=he("textureSource"),this._resourceType="textureSource",this._resourceId=he("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,e={...jx.defaultOptions,...e},this.label=e.label??"",this.resource=e.resource,this.autoGarbageCollect=e.autoGarbageCollect,this._resolution=e.resolution,e.width?this.pixelWidth=e.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,e.height?this.pixelHeight=e.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=e.format,this.dimension=e.dimensions,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=e.antialias,this.alphaMode=e.alphaMode,this.style=new wt(Np(e)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(e){this.style!==e&&(this._style?.off("change",this._onStyleChange,this),this._style=e,this._style?.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){this._resourceId=he("resource"),this.emit("change",this),this.emit("unload",this)}get resourceWidth(){const{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){const{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,s){s||(s=this._resolution),e||(e=this.width),t||(t=this.height);const r=Math.round(e*s),n=Math.round(t*s);return this.width=r/s,this.height=n/s,this._resolution=s,this.pixelWidth===r&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=n,this.emit("resize",this),this._resourceId=he("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=zp(this.pixelWidth)&&zp(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};Wp.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let Ee=Wp;class nu extends Ee{constructor(e){const t=e.resource||new Float32Array(e.width*e.height*4);let s=e.format;s||(t instanceof Float32Array?s="rgba32float":t instanceof Int32Array||t instanceof Uint32Array?s="rgba32uint":t instanceof Int16Array||t instanceof Uint16Array?s="rgba16uint":(t instanceof Int8Array,s="bgra8unorm")),super({...e,resource:t,format:s}),this.uploadMethodId="buffer"}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}}nu.extension=b.TextureSource;const Vp=new O;class $p{constructor(e,t){this.mapCoord=new O,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof t>"u"?this.clampMargin=e.width<10?0:.5:this.clampMargin=t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){this.texture!==e&&(this._texture?.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(e,t){t===void 0&&(t=e);const s=this.mapCoord;for(let r=0;r<e.length;r+=2){const n=e[r],o=e[r+1];t[r]=n*s.a+o*s.c+s.tx,t[r+1]=n*s.b+o*s.d+s.ty}return t}update(){const e=this._texture;this._updateID++;const t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);const s=e.orig,r=e.trim;r&&(Vp.set(s.width/r.width,0,0,s.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(Vp));const n=e.source,o=this.uClampFrame,a=this.clampMargin/n._resolution,l=this.clampOffset/n._resolution;return o[0]=(e.frame.x+a+l)/n.width,o[1]=(e.frame.y+a+l)/n.height,o[2]=(e.frame.x+e.frame.width-a+l)/n.width,o[3]=(e.frame.y+e.frame.height-a+l)/n.height,this.uClampOffset[0]=this.clampOffset/n.pixelWidth,this.uClampOffset[1]=this.clampOffset/n.pixelHeight,this.isSimple=e.frame.width===n.width&&e.frame.height===n.height&&e.rotate===0,!0}}class M extends je{constructor({source:e,label:t,frame:s,orig:r,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:c}={}){if(super(),this.uid=he("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new H,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=e?.source??new Ee,this.noFrame=!s,s)this.frame.copyFrom(s);else{const{width:h,height:u}=this._source;this.frame.width=h,this.frame.height=u}this.orig=r||this.frame,this.trim=n,this.rotate=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=c||!1,this.updateUvs()}set source(e){this._source&&this._source.off("resize",this.update,this),this._source=e,e.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new $p(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:s,height:r}=this._source,n=t.x/s,o=t.y/r,a=t.width/s,l=t.height/r;let c=this.rotate;if(c){const h=a/2,u=l/2,d=n+h,f=o+u;c=oe.add(c,oe.NW),e.x0=d+h*oe.uX(c),e.y0=f+u*oe.uY(c),c=oe.add(c,2),e.x1=d+h*oe.uX(c),e.y1=f+u*oe.uY(c),c=oe.add(c,2),e.x2=d+h*oe.uX(c),e.y2=f+u*oe.uY(c),c=oe.add(c,2),e.x3=d+h*oe.uX(c),e.y3=f+u*oe.uY(c)}else e.x0=n,e.y0=o,e.x1=n+a,e.y1=o,e.x2=n+a,e.y2=o+l,e.x3=n,e.y3=o+l}destroy(e=!1){this._source&&(this._source.off("resize",this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return W(Q,"Texture.baseTexture is now Texture.source"),this._source}}M.EMPTY=new M({label:"EMPTY",source:new Ee({label:"EMPTY"})}),M.EMPTY.destroy=Gp,M.WHITE=new M({source:new nu({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),M.WHITE.destroy=Gp;function Xp(i,e,t){const{width:s,height:r}=t.orig,n=t.trim;if(n){const o=n.width,a=n.height;i.minX=n.x-e._x*s,i.maxX=i.minX+o,i.minY=n.y-e._y*r,i.maxY=i.minY+a}else i.minX=-e._x*s,i.maxX=i.minX+s,i.minY=-e._y*r,i.maxY=i.minY+r}const Yp=new O;class De{constructor(e=1/0,t=1/0,s=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=Yp,this.minX=e,this.minY=t,this.maxX=s,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new H);const e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=Yp,this}set(e,t,s,r){this.minX=e,this.minY=t,this.maxX=s,this.maxY=r}addFrame(e,t,s,r,n){n||(n=this.matrix);const o=n.a,a=n.b,l=n.c,c=n.d,h=n.tx,u=n.ty;let d=this.minX,f=this.minY,p=this.maxX,g=this.maxY,m=o*e+l*t+h,_=a*e+c*t+u;m<d&&(d=m),_<f&&(f=_),m>p&&(p=m),_>g&&(g=_),m=o*s+l*t+h,_=a*s+c*t+u,m<d&&(d=m),_<f&&(f=_),m>p&&(p=m),_>g&&(g=_),m=o*e+l*r+h,_=a*e+c*r+u,m<d&&(d=m),_<f&&(f=_),m>p&&(p=m),_>g&&(g=_),m=o*s+l*r+h,_=a*s+c*r+u,m<d&&(d=m),_<f&&(f=_),m>p&&(p=m),_>g&&(g=_),this.minX=d,this.minY=f,this.maxX=p,this.maxY=g}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){const t=this.minX,s=this.minY,r=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:c,tx:h,ty:u}=e;let d=o*t+l*s+h,f=a*t+c*s+u;this.minX=d,this.minY=f,this.maxX=d,this.maxY=f,d=o*r+l*s+h,f=a*r+c*s+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=o*t+l*n+h,f=a*t+c*n+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=o*r+l*n+h,f=a*r+c*n+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY}fit(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,s,r){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<s&&(this.minY=s),this.maxY>r&&(this.maxY=r),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new De(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){const t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){const t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,s,r){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;r||(r=this.matrix);const c=r.a,h=r.b,u=r.c,d=r.d,f=r.tx,p=r.ty;for(let g=t;g<s;g+=2){const m=e[g],_=e[g+1],x=c*m+u*_+f,y=h*m+d*_+p;n=x<n?x:n,o=y<o?y:o,a=x>a?x:a,l=y>l?y:l}this.minX=n,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}var K1={grad:.9,turn:360,rad:360/(2*Math.PI)},Mt=function(i){return typeof i=="string"?i.length>0:typeof i=="number"},Re=function(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*i)/t+0},nt=function(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),i>t?t:i>e?i:e},qp=function(i){return(i=isFinite(i)?i%360:0)>0?i:i+360},Kp=function(i){return{r:nt(i.r,0,255),g:nt(i.g,0,255),b:nt(i.b,0,255),a:nt(i.a)}},ou=function(i){return{r:Re(i.r),g:Re(i.g),b:Re(i.b),a:Re(i.a,3)}},j1=/^#([0-9a-f]{3,8})$/i,Mr=function(i){var e=i.toString(16);return e.length<2?"0"+e:e},jp=function(i){var e=i.r,t=i.g,s=i.b,r=i.a,n=Math.max(e,t,s),o=n-Math.min(e,t,s),a=o?n===e?(t-s)/o:n===t?2+(s-e)/o:4+(e-t)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},Zp=function(i){var e=i.h,t=i.s,s=i.v,r=i.a;e=e/360*6,t/=100,s/=100;var n=Math.floor(e),o=s*(1-t),a=s*(1-(e-n)*t),l=s*(1-(1-e+n)*t),c=n%6;return{r:255*[s,a,o,o,l,s][c],g:255*[l,s,s,a,o,o][c],b:255*[o,o,l,s,s,a][c],a:r}},Jp=function(i){return{h:qp(i.h),s:nt(i.s,0,100),l:nt(i.l,0,100),a:nt(i.a)}},Qp=function(i){return{h:Re(i.h),s:Re(i.s),l:Re(i.l),a:Re(i.a,3)}},em=function(i){return Zp((t=(e=i).s,{h:e.h,s:(t*=((s=e.l)<50?s:100-s)/100)>0?2*t/(s+t)*100:0,v:s+t,a:e.a}));var e,t,s},fs=function(i){return{h:(e=jp(i)).h,s:(r=(200-(t=e.s))*(s=e.v)/100)>0&&r<200?t*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,t,s,r},Z1=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,J1=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Q1=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,eS=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,au={string:[[function(i){var e=j1.exec(i);return e?(i=e[1]).length<=4?{r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16),a:i.length===4?Re(parseInt(i[3]+i[3],16)/255,2):1}:i.length===6||i.length===8?{r:parseInt(i.substr(0,2),16),g:parseInt(i.substr(2,2),16),b:parseInt(i.substr(4,2),16),a:i.length===8?Re(parseInt(i.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(i){var e=Q1.exec(i)||eS.exec(i);return e?e[2]!==e[4]||e[4]!==e[6]?null:Kp({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(i){var e=Z1.exec(i)||J1.exec(i);if(!e)return null;var t,s,r=Jp({h:(t=e[1],s=e[2],s===void 0&&(s="deg"),Number(t)*(K1[s]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return em(r)},"hsl"]],object:[[function(i){var e=i.r,t=i.g,s=i.b,r=i.a,n=r===void 0?1:r;return Mt(e)&&Mt(t)&&Mt(s)?Kp({r:Number(e),g:Number(t),b:Number(s),a:Number(n)}):null},"rgb"],[function(i){var e=i.h,t=i.s,s=i.l,r=i.a,n=r===void 0?1:r;if(!Mt(e)||!Mt(t)||!Mt(s))return null;var o=Jp({h:Number(e),s:Number(t),l:Number(s),a:Number(n)});return em(o)},"hsl"],[function(i){var e=i.h,t=i.s,s=i.v,r=i.a,n=r===void 0?1:r;if(!Mt(e)||!Mt(t)||!Mt(s))return null;var o=(function(a){return{h:qp(a.h),s:nt(a.s,0,100),v:nt(a.v,0,100),a:nt(a.a)}})({h:Number(e),s:Number(t),v:Number(s),a:Number(n)});return Zp(o)},"hsv"]]},tm=function(i,e){for(var t=0;t<e.length;t++){var s=e[t][0](i);if(s)return[s,e[t][1]]}return[null,void 0]},tS=function(i){return typeof i=="string"?tm(i.trim(),au.string):typeof i=="object"&&i!==null?tm(i,au.object):[null,void 0]},lu=function(i,e){var t=fs(i);return{h:t.h,s:nt(t.s+100*e,0,100),l:t.l,a:t.a}},cu=function(i){return(299*i.r+587*i.g+114*i.b)/1e3/255},im=function(i,e){var t=fs(i);return{h:t.h,s:t.s,l:nt(t.l+100*e,0,100),a:t.a}},hu=(function(){function i(e){this.parsed=tS(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return i.prototype.isValid=function(){return this.parsed!==null},i.prototype.brightness=function(){return Re(cu(this.rgba),2)},i.prototype.isDark=function(){return cu(this.rgba)<.5},i.prototype.isLight=function(){return cu(this.rgba)>=.5},i.prototype.toHex=function(){return e=ou(this.rgba),t=e.r,s=e.g,r=e.b,o=(n=e.a)<1?Mr(Re(255*n)):"","#"+Mr(t)+Mr(s)+Mr(r)+o;var e,t,s,r,n,o},i.prototype.toRgb=function(){return ou(this.rgba)},i.prototype.toRgbString=function(){return e=ou(this.rgba),t=e.r,s=e.g,r=e.b,(n=e.a)<1?"rgba("+t+", "+s+", "+r+", "+n+")":"rgb("+t+", "+s+", "+r+")";var e,t,s,r,n},i.prototype.toHsl=function(){return Qp(fs(this.rgba))},i.prototype.toHslString=function(){return e=Qp(fs(this.rgba)),t=e.h,s=e.s,r=e.l,(n=e.a)<1?"hsla("+t+", "+s+"%, "+r+"%, "+n+")":"hsl("+t+", "+s+"%, "+r+"%)";var e,t,s,r,n},i.prototype.toHsv=function(){return e=jp(this.rgba),{h:Re(e.h),s:Re(e.s),v:Re(e.v),a:Re(e.a,3)};var e},i.prototype.invert=function(){return St({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},i.prototype.saturate=function(e){return e===void 0&&(e=.1),St(lu(this.rgba,e))},i.prototype.desaturate=function(e){return e===void 0&&(e=.1),St(lu(this.rgba,-e))},i.prototype.grayscale=function(){return St(lu(this.rgba,-1))},i.prototype.lighten=function(e){return e===void 0&&(e=.1),St(im(this.rgba,e))},i.prototype.darken=function(e){return e===void 0&&(e=.1),St(im(this.rgba,-e))},i.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},i.prototype.alpha=function(e){return typeof e=="number"?St({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Re(this.rgba.a,3);var t},i.prototype.hue=function(e){var t=fs(this.rgba);return typeof e=="number"?St({h:e,s:t.s,l:t.l,a:t.a}):Re(t.h)},i.prototype.isEqual=function(e){return this.toHex()===St(e).toHex()},i})(),St=function(i){return i instanceof hu?i:new hu(i)},sm=[],iS=function(i){i.forEach(function(e){sm.indexOf(e)<0&&(e(hu,au),sm.push(e))})};function sS(i,e){var t={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},s={};for(var r in t)s[t[r]]=r;var n={};i.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,c=s[this.toHex()];if(c)return c;if(o?.closest){var h=this.toRgb(),u=1/0,d="black";if(!n.length)for(var f in t)n[f]=new i(t[f]).toRgb();for(var p in t){var g=(a=h,l=n[p],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));g<u&&(u=g,d=p)}return d}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new i(l).toRgb():null},"name"])}iS([sS]);const Fi=class qs{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(e){if(e instanceof qs)this._value=this._cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(e===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,e))&&(this._value=this._cloneSource(e),this._normalize(this._value))}}get value(){return this._value}_cloneSource(e){return typeof e=="string"||typeof e=="number"||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e=="object"&&e!==null?{...e}:e}_isSourceEqual(e,t){const s=typeof e;if(s!==typeof t)return!1;if(s==="number"||s==="string"||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length!==t.length?!1:e.every((n,o)=>n===t[o]);if(e!==null&&t!==null){const n=Object.keys(e),o=Object.keys(t);return n.length!==o.length?!1:n.every(a=>e[a]===t[a])}return e===t}toRgba(){const[e,t,s,r]=this._components;return{r:e,g:t,b:s,a:r}}toRgb(){const[e,t,s]=this._components;return{r:e,g:t,b:s}}toRgbaString(){const[e,t,s]=this.toUint8RgbArray();return`rgba(${e},${t},${s},${this.alpha})`}toUint8RgbArray(e){const[t,s,r]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(s*255),e[2]=Math.round(r*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,s,r,n]=this._components;return e[0]=t,e[1]=s,e[2]=r,e[3]=n,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,s,r]=this._components;return e[0]=t,e[1]=s,e[2]=r,e}toNumber(){return this._int}toBgrNumber(){const[e,t,s]=this.toUint8RgbArray();return(s<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,s,r,n]=qs._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let s=this._int>>16&255,r=this._int>>8&255,n=this._int&255;return t&&(s=s*e+.5|0,r=r*e+.5|0,n=n*e+.5|0),(e*255<<24)+(s<<16)+(r<<8)+n}toHex(){const e=this._int.toString(16);return`#${"000000".substring(0,6-e.length)+e}`}toHexa(){const t=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(e){return this._components[3]=this._clamp(e),this}_normalize(e){let t,s,r,n;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,s=(o>>8&255)/255,r=(o&255)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,s,r,n=255]=e,t/=255,s/=255,r/=255,n/=255;else if(typeof e=="string"||typeof e=="object"){if(typeof e=="string"){const a=qs.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=St(e);o.isValid()&&({r:t,g:s,b:r,a:n}=o.rgba,t/=255,s/=255,r/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=s,this._components[2]=r,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,s]=this._components;this._int=(e*255<<16)+(t*255<<8)+(s*255|0)}_clamp(e,t=0,s=1){return typeof e=="number"?Math.min(Math.max(e,t),s):(e.forEach((r,n)=>{e[n]=Math.min(Math.max(r,t),s)}),e)}static isColorLike(e){return typeof e=="number"||typeof e=="string"||e instanceof Number||e instanceof qs||Array.isArray(e)||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Float32Array||e.r!==void 0&&e.g!==void 0&&e.b!==void 0||e.r!==void 0&&e.g!==void 0&&e.b!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0&&e.a!==void 0}};Fi.shared=new Fi,Fi._temp=new Fi,Fi.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let ue=Fi;const rS={cullArea:null,cullable:!1,cullableChildren:!0};let uu=0;const rm=500;function L(...i){uu!==rm&&(uu++,uu===rm?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...i))}const Bi={_registeredResources:new Set,register(i){this._registeredResources.add(i)},unregister(i){this._registeredResources.delete(i)},release(){this._registeredResources.forEach(i=>i.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(i){return this._registeredResources.has(i)},reset(){this._registeredResources.clear()}};class nS{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),t.init?.(e),t}return(e){e.reset?.(),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}class oS{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new nS(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const s=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[s]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Se=new oS;Bi.register(Se);const aS={get isCachedAsTexture(){return!!this.renderGroup?.isCachedAsTexture},cacheAsTexture(i){typeof i=="boolean"&&i===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(i===!0?{}:i))},updateCacheTexture(){this.renderGroup?.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(i){W("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(i)}};function nm(i,e,t){const s=i.length;let r;if(e>=s||t===0)return;t=e+t>s?s-e:t;const n=s-t;for(r=e;r<n;++r)i[r]=i[r+t];i.length=n}const lS={allowChildren:!0,removeChildren(i=0,e){const t=e??this.children.length,s=t-i,r=[];if(s>0&&s<=t){for(let o=t-1;o>=i;o--){const a=this.children[o];a&&(r.push(a),a.parent=null)}nm(this.children,i,t);const n=this.renderGroup||this.parentRenderGroup;n&&n.removeChildren(r);for(let o=0;o<r.length;++o){const a=r[o];a.parentRenderLayer?.detach(a),this.emit("childRemoved",a,this,o),r[o].emit("removed",this)}return r.length>0&&this._didViewChangeTick++,r}else if(s===0&&this.children.length===0)return r;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(i){const e=this.getChildAt(i);return this.removeChild(e)},getChildAt(i){if(i<0||i>=this.children.length)throw new Error(`getChildAt: Index (${i}) does not exist.`);return this.children[i]},setChildIndex(i,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(i),this.addChildAt(i,e)},getChildIndex(i){const e=this.children.indexOf(i);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(i,e){this.allowChildren||W(Q,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:t}=this;if(e<0||e>t.length)throw new Error(`${i}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);if(i.parent){const r=i.parent.children.indexOf(i);if(i.parent===this&&r===e)return i;r!==-1&&i.parent.children.splice(r,1)}e===t.length?t.push(i):t.splice(e,0,i),i.parent=this,i.didChange=!0,i._updateFlags=15;const s=this.renderGroup||this.parentRenderGroup;return s&&s.addChild(i),this.sortableChildren&&(this.sortDirty=!0),this.emit("childAdded",i,this,e),i.emit("added",this),i},swapChildren(i,e){if(i===e)return;const t=this.getChildIndex(i),s=this.getChildIndex(e);this.children[t]=e,this.children[s]=i;const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){this.parent?.removeChild(this)},reparentChild(...i){return i.length===1?this.reparentChildAt(i[0],this.children.length):(i.forEach(e=>this.reparentChildAt(e,this.children.length)),i[0])},reparentChildAt(i,e){if(i.parent===this)return this.setChildIndex(i,e),i;const t=i.worldTransform.clone();i.removeFromParent(),this.addChildAt(i,e);const s=this.worldTransform.clone();return s.invert(),t.prepend(s),i.setFromMatrix(t),i},replaceChild(i,e){i.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(i)),e.setFromMatrix(i.localTransform),e.updateLocalTransform(),this.removeChild(i)}},cS={collectRenderables(i,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(i,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,i):this.collectRenderablesWithEffects(i,e,t))},collectRenderablesSimple(i,e,t){const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(i,e,t)},collectRenderablesWithEffects(i,e,t){const{renderPipes:s}=e;for(let r=0;r<this.effects.length;r++){const n=this.effects[r];s[n.pipe].push(n,this,i)}this.collectRenderablesSimple(i,e,t);for(let r=this.effects.length-1;r>=0;r--){const n=this.effects[r];s[n.pipe].pop(n,this,i)}}};class kr{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}class hS{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){const s=this._tests[t];if(s.test(e))return Se.get(s.maskClass,e)}return e}returnMaskEffect(e){Se.return(e)}}const du=new hS;V.handleByList(b.MaskEffect,du._effectClasses);const uS={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const i=this.renderGroup||this.parentRenderGroup;i&&(i.structureDidChange=!0)},addEffect(i){this.effects.indexOf(i)===-1&&(this.effects.push(i),this.effects.sort((t,s)=>t.priority-s.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(i){const e=this.effects.indexOf(i);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(i){const e=this._maskEffect;e?.mask!==i&&(e&&(this.removeEffect(e),du.returnMaskEffect(e),this._maskEffect=null),i!=null&&(this._maskEffect=du.getMaskEffect(i),this.addEffect(this._maskEffect)))},get mask(){return this._maskEffect?.mask},setMask(i){this._maskOptions={...this._maskOptions,...i},i.mask&&(this.mask=i.mask),this._markStructureAsChanged()},set filters(i){!Array.isArray(i)&&i&&(i=[i]);const e=this._filterEffect||(this._filterEffect=new kr);i=i;const t=i?.length>0,s=e.filters?.length>0,r=t!==s;i=Array.isArray(i)?i.slice(0):i,e.filters=Object.freeze(i),r&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=i??null))},get filters(){return this._filterEffect?.filters},set filterArea(i){this._filterEffect||(this._filterEffect=new kr),this._filterEffect.filterArea=i},get filterArea(){return this._filterEffect?.filterArea}},dS={label:null,get name(){return W(Q,"Container.name property has been removed, use Container.label instead"),this.label},set name(i){W(Q,"Container.name property has been removed, use Container.label instead"),this.label=i},getChildByName(i,e=!1){return this.getChildByLabel(i,e)},getChildByLabel(i,e=!1){const t=this.children;for(let s=0;s<t.length;s++){const r=t[s];if(r.label===i||i instanceof RegExp&&i.test(r.label))return r}if(e)for(let s=0;s<t.length;s++){const n=t[s].getChildByLabel(i,!0);if(n)return n}return null},getChildrenByLabel(i,e=!1,t=[]){const s=this.children;for(let r=0;r<s.length;r++){const n=s[r];(n.label===i||i instanceof RegExp&&i.test(n.label))&&t.push(n)}if(e)for(let r=0;r<s.length;r++)s[r].getChildrenByLabel(i,!0,t);return t}},Le=Se.getPool(O),kt=Se.getPool(De),fS=new O,pS={getFastGlobalBounds(i,e){e||(e=new De),e.clear(),this._getGlobalBoundsRecursive(!!i,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(i,e,t){let s=e;if(i&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const r=!!this.effects.length;if((this.renderGroup||r)&&(s=kt.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;s.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const n=this.children;for(let o=0;o<n.length;o++)n[o]._getGlobalBoundsRecursive(i,s,t)}if(r){let n=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(n||(n=!0,s.applyMatrix(o.worldTransform)),this.effects[a].addBounds(s,!0));n&&s.applyMatrix(o.worldTransform.copyTo(fS).invert()),e.addBounds(s),kt.return(s)}else this.renderGroup&&(e.addBounds(s,this.relativeGroupTransform),kt.return(s))}};function fu(i,e,t){t.clear();let s,r;return i.parent?e?s=i.parent.worldTransform:(r=Le.get().identity(),s=pu(i,r)):s=O.IDENTITY,om(i,t,s,e),r&&Le.return(r),t.isValid||t.set(0,0,0,0),t}function om(i,e,t,s){if(!i.visible||!i.measurable)return;let r;s?r=i.worldTransform:(i.updateLocalTransform(),r=Le.get(),r.appendFrom(i.localTransform,t));const n=e,o=!!i.effects.length;if(o&&(e=kt.get().clear()),i.boundsArea)e.addRect(i.boundsArea,r);else{const a=i.bounds;a&&!a.isEmpty()&&(e.matrix=r,e.addBounds(a));for(let l=0;l<i.children.length;l++)om(i.children[l],e,r,s)}if(o){for(let a=0;a<i.effects.length;a++)i.effects[a].addBounds?.(e);n.addBounds(e,O.IDENTITY),kt.return(e)}s||Le.return(r)}function pu(i,e){const t=i.parent;return t&&(pu(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function am(i,e){if(i===16777215||!e)return e;if(e===16777215||!i)return i;const t=i>>16&255,s=i>>8&255,r=i&255,n=e>>16&255,o=e>>8&255,a=e&255,l=t*n/255|0,c=s*o/255|0,h=r*a/255|0;return(l<<16)+(c<<8)+h}const lm=16777215;function Fr(i,e){return i===lm?e:e===lm?i:am(i,e)}function Br(i){return((i&255)<<16)+(i&65280)+(i>>16&255)}const mS={getGlobalAlpha(i){if(i)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let e=this.alpha,t=this.parent;for(;t;)e*=t.alpha,t=t.parent;return e},getGlobalTransform(i=new O,e){if(e)return i.copyFrom(this.worldTransform);this.updateLocalTransform();const t=pu(this,Le.get().identity());return i.appendFrom(this.localTransform,t),Le.return(t),i},getGlobalTint(i){if(i)return this.renderGroup?Br(this.renderGroup.worldColor):this.parentRenderGroup?Br(Fr(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=Fr(e,t.localColor),t=t.parent;return Br(e)}};function mu(i,e,t){return e.clear(),t||(t=O.IDENTITY),cm(i,e,t,i,!0),e.isValid||e.set(0,0,0,0),e}function cm(i,e,t,s,r){let n;if(r)n=Le.get(),n=t.copyTo(n);else{if(!i.visible||!i.measurable)return;i.updateLocalTransform();const l=i.localTransform;n=Le.get(),n.appendFrom(l,t)}const o=e,a=!!i.effects.length;if(a&&(e=kt.get().clear()),i.boundsArea)e.addRect(i.boundsArea,n);else{i.renderPipeId&&(e.matrix=n,e.addBounds(i.bounds));const l=i.children;for(let c=0;c<l.length;c++)cm(l[c],e,n,s,!1)}if(a){for(let l=0;l<i.effects.length;l++)i.effects[l].addLocalBounds?.(e,s);o.addBounds(e,O.IDENTITY),kt.return(e)}Le.return(n)}function hm(i,e){const t=i.children;for(let s=0;s<t.length;s++){const r=t[s],n=r.uid,o=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,a=e.index;(e.data[a]!==n||e.data[a+1]!==o)&&(e.data[e.index]=n,e.data[e.index+1]=o,e.didChange=!0),e.index=a+2,r.children.length&&hm(r,e)}return e.didChange}const gS=new O,_S={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(i,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=i/e*t:this.scale.x=t},_setHeight(i,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=i/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new De});const i=this._localBoundsCacheData;return i.index=1,i.didChange=!1,i.data[0]!==this._didViewChangeTick&&(i.didChange=!0,i.data[0]=this._didViewChangeTick),hm(this,i),i.didChange&&mu(this,i.localBounds,gS),i.localBounds},getBounds(i,e){return fu(this,i,e||new De)}},xS={_onRender:null,set onRender(i){const e=this.renderGroup||this.parentRenderGroup;if(!i){this._onRender&&e?.removeOnRender(this),this._onRender=null;return}this._onRender||e?.addOnRender(this),this._onRender=i},get onRender(){return this._onRender}},yS={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(i){this._zIndex!==i&&(this._zIndex=i,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(vS))}};function vS(i,e){return i._zIndex-e._zIndex}const bS={getGlobalPosition(i=new X,e=!1){return this.parent?this.parent.toGlobal(this._position,i,e):(i.x=this._position.x,i.y=this._position.y),i},toGlobal(i,e,t=!1){const s=this.getGlobalTransform(Le.get(),t);return e=s.apply(i,e),Le.return(s),e},toLocal(i,e,t,s){e&&(i=e.toGlobal(i,t,s));const r=this.getGlobalTransform(Le.get(),s);return t=r.applyInverse(i,t),Le.return(r),t}};class um{constructor(){this.uid=he("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let TS=0;class wS{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new wt(this.textureOptions)}createTexture(e,t,s){const r=new Ee({...this.textureOptions,width:e,height:t,resolution:1,antialias:s,autoGarbageCollect:!1});return new M({source:r,label:`texturePool_${TS++}`})}getOptimalTexture(e,t,s=1,r){let n=Math.ceil(e*s-1e-6),o=Math.ceil(t*s-1e-6);n=ki(n),o=ki(o);const a=(n<<17)+(o<<1)+(r?1:0);this._texturePool[a]||(this._texturePool[a]=[]);let l=this._texturePool[a].pop();return l||(l=this.createTexture(n,o,r)),l.source._resolution=s,l.source.width=n/s,l.source.height=o/s,l.source.pixelWidth=n,l.source.pixelHeight=o,l.frame.x=0,l.frame.y=0,l.frame.width=e,l.frame.height=t,l.updateUvs(),this._poolKeyHash[l.uid]=a,l}getSameSizeTexture(e,t=!1){const s=e.source;return this.getOptimalTexture(e.width,e.height,s._resolution,t)}returnTexture(e,t=!1){const s=this._poolKeyHash[e.uid];t&&(e.source.style=this.textureStyle),this._texturePool[s].push(e)}clear(e){if(e=e!==!1,e)for(const t in this._texturePool){const s=this._texturePool[t];if(s)for(let r=0;r<s.length;r++)s[r].destroy(!0)}this._texturePool={}}}const ve=new wS;Bi.register(ve);class gu{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new O,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new um,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;const t=e.children;for(let s=0;s<t.length;s++){const r=t[s];r._updateFlags=15,this.addChild(r)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(ve.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const e in this.childrenToUpdate){const t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){const t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.parent===this.root?e.relativeRenderGroupDepth=1:e.relativeRenderGroupDepth=e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);const t=e.children;for(let s=0;s<t.length;s++)this.addChild(t[s])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}const t=e.children;for(let s=0;s<t.length;s++)this.removeChild(t[s])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||(t=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]}),t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.push(e)}removeOnRender(e){this._onRenderContainers.splice(this._onRenderContainers.indexOf(e),1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let s=0;s<t.length;s++)this._getChildren(t[s],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const s=e.children;for(let r=0;r<s.length;r++)this._getChildren(s[r],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new O),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new O),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new O),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function SS(i,e,t={}){for(const s in e)!t[s]&&e[s]!==void 0&&(i[s]=e[s])}const _u=new Be(null),Ur=new Be(null),xu=new Be(null,1,1),Or=new Be(null),Dr=1,yu=2,ps=4;class re extends je{constructor(e={}){super(),this.uid=he("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new O,this.relativeGroupTransform=new O,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new Be(this,0,0),this._scale=xu,this._pivot=Ur,this._origin=Or,this._skew=_u,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],SS(this,e,{children:!0,parent:!0,effects:!0}),e.children?.forEach(t=>this.addChild(t)),e.parent?.addChild(this)}static mixin(e){W("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),V.mixin(re,e)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||W(Q,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let r=0;r<e.length;r++)this.addChild(e[r]);return e[0]}const t=e[0],s=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),s&&(s.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,s&&s.addChild(t),this.emit("childAdded",t,this,this.children.length-1),t.emit("added",this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let r=0;r<e.length;r++)this.removeChild(e[r]);return e[0]}const t=e[0],s=this.children.indexOf(t);return s>-1&&(this._didViewChangeTick++,this.children.splice(s,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit("childRemoved",t,this,s),t.emit("removed",this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const e=this.parentRenderGroup;e?.removeChild(this),this.renderGroup=Se.get(gu,this),this.groupTransform=O.IDENTITY,e?.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e?.removeChild(this),Se.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e?.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new O),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*H1}set angle(e){this.rotation=e*W1}get pivot(){return this._pivot===Ur&&(this._pivot=new Be(this,0,0)),this._pivot}set pivot(e){this._pivot===Ur&&(this._pivot=new Be(this,0,0),this._origin!==Or&&L("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===_u&&(this._skew=new Be(this,0,0)),this._skew}set skew(e){this._skew===_u&&(this._skew=new Be(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===xu&&(this._scale=new Be(this,1,1)),this._scale}set scale(e){this._scale===xu&&(this._scale=new Be(this,0,0)),typeof e=="string"&&(e=parseFloat(e)),typeof e=="number"?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===Or&&(this._origin=new Be(this,0,0)),this._origin}set origin(e){this._origin===Or&&(this._origin=new Be(this,0,0),this._pivot!==Ur&&L("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){const t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){const t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||(e={});const t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){const s=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,s.width),t!==void 0&&this._setHeight(t,s.height)}_updateSkew(){const e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x=="number"?e.x:this.position.x,typeof e.y=="number"?e.y:this.position.y),this.scale.set(typeof e.scaleX=="number"?e.scaleX||1:this.scale.x,typeof e.scaleY=="number"?e.scaleY||1:this.scale.y),this.rotation=typeof e.rotation=="number"?e.rotation:this.rotation,this.skew.set(typeof e.skewX=="number"?e.skewX:this.skew.x,typeof e.skewY=="number"?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX=="number"?e.pivotX:this.pivot.x,typeof e.pivotY=="number"?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX=="number"?e.originX:this.origin.x,typeof e.originY=="number"?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){const e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;const t=this.localTransform,s=this._scale,r=this._pivot,n=this._origin,o=this._position,a=s._x,l=s._y,c=r._x,h=r._y,u=-n._x,d=-n._y;t.a=this._cx*a,t.b=this._sx*a,t.c=this._cy*l,t.d=this._sy*l,t.tx=o._x-(c*t.a+h*t.c)+(u*t.a+d*t.c)-u,t.ty=o._y-(c*t.b+h*t.d)+(u*t.b+d*t.d)-d}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=Dr,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const s=ue.shared.setValue(e??16777215).toBgrNumber();s!==this.localColor&&(this.localColor=s,this._updateFlags|=Dr,this._onUpdate())}get tint(){return Br(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=yu,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){const t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ps,this.localDisplayStatus^=2,this._onUpdate())}get culled(){return!(this.localDisplayStatus&4)}set culled(e){const t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ps,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){const t=e?1:0;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=ps,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof e=="boolean"?e:e?.children)&&t)for(let r=0;r<t.length;++r)t[r].destroy(e);this.renderGroup?.destroy(),this.renderGroup=null}}V.mixin(re,lS,pS,bS,xS,_S,uS,dS,yS,rS,aS,mS,cS);class vu extends re{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this._bounds=new De(0,1,0,0),this._boundsDirty=!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=e?1:0}containsPoint(e){const t=this.bounds,{x:s,y:r}=e;return s>=t.minX&&s<=t.maxX&&r>=t.minY&&r<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}destroy(e){super.destroy(e),this._bounds=null;for(const t in this._gpuData)this._gpuData[t].destroy?.();this._gpuData=null}collectRenderablesSimple(e,t,s){const{renderPipes:r}=t;r.blendMode.pushBlendMode(this,this.groupBlendMode,e),r[this.renderPipeId].addRenderable(this,e),this.didViewUpdate=!1;const o=this.children,a=o.length;for(let l=0;l<a;l++)o[l].collectRenderables(e,t,s);r.blendMode.popBlendMode(e)}}class Ue extends vu{constructor(e=M.EMPTY){e instanceof M&&(e={texture:e});const{texture:t=M.EMPTY,anchor:s,roundPixels:r,width:n,height:o,...a}=e;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new Be({_onUpdate:()=>{this.onViewUpdate()}}),s?this.anchor=s:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=r??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof M?new Ue(e):new Ue(M.from(e,t))}set texture(e){e||(e=M.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return Xp(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return W("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,s=this._bounds,{width:r,height:n}=t.orig;s.minX=-e._x*r,s.maxX=s.minX+r,s.minY=-e._y*n,s.maxY=s.minY+n}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._texture.destroy(s)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null,this._gpuData=null}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}const CS=new De;function dm(i,e,t){const s=CS;i.measurable=!0,fu(i,t,s),e.addBoundsMask(s),i.measurable=!1}function fm(i,e,t){const s=kt.get();i.measurable=!0;const r=Le.get().identity(),n=pm(i,t,r);mu(i,s,n),i.measurable=!1,e.addBoundsMask(s),Le.return(r),kt.return(s)}function pm(i,e,t){return i?(i!==e&&(pm(i.parent,e,t),i.updateLocalTransform(),t.append(i.localTransform)),t):(L("Mask bounds, renderable is not inside the root container"),t)}class mm{constructor(e){this.priority=0,this.inverse=!1,this.pipe="alphaMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof Ue),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||dm(this.mask,e,t)}addLocalBounds(e,t){fm(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof Ue}}mm.extension=b.MaskEffect;class gm{constructor(e){this.priority=0,this.pipe="colorMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}gm.extension=b.MaskEffect;class _m{constructor(e){this.priority=0,this.pipe="stencilMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){dm(this.mask,e,t)}addLocalBounds(e,t){fm(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof re}}_m.extension=b.MaskEffect;let xm={createCanvas:(i,e)=>{const t=document.createElement("canvas");return t.width=i,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(i,e)=>fetch(i,e),parseXML:i=>new DOMParser().parseFromString(i,"text/xml")};const Y={get(){return xm},set(i){xm=i}};class Ft extends Ee{constructor(e){e.resource||(e.resource=Y.get().createCanvas()),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId="image",this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,s=this._resolution){const r=super.resize(e,t,s);return r&&this.resizeCanvas(),r}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}Ft.extension=b.TextureSource;class Ct extends Ee{constructor(e){super(e),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}}Ct.extension=b.TextureSource;var Ui=(i=>(i[i.INTERACTION=50]="INTERACTION",i[i.HIGH=25]="HIGH",i[i.NORMAL=0]="NORMAL",i[i.LOW=-25]="LOW",i[i.UTILITY=-50]="UTILITY",i))(Ui||{});class bu{constructor(e,t=null,s=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=s,this._once=r}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));const t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const t=this.next;return this.next=e?null:t,this.previous=null,t}}const ym=class it{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new bu(null,null,1/0),this.deltaMS=1/it.targetFPMS,this.elapsedMS=1/it.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,s=Ui.NORMAL){return this._addListener(new bu(e,t,s))}addOnce(e,t,s=Ui.NORMAL){return this._addListener(new bu(e,t,s,!0))}_addListener(e){let t=this._head.next,s=this._head;if(!t)e.connect(s);else{for(;t;){if(e.priority>t.priority){e.connect(s);break}s=t,t=t.next}e.previous||e.connect(s)}return this._startIfPossible(),this}remove(e,t){let s=this._head.next;for(;s;)s.match(e,t)?s=s.destroy():s=s.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let t;if(e>this.lastTime){if(t=this.elapsedMS=e-this.lastTime,t>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){const n=e-this._lastFrame|0;if(n<this._minElapsedMS)return;this._lastFrame=e-n%this._minElapsedMS}this.deltaMS=t,this.deltaTime=this.deltaMS*it.targetFPMS;const s=this._head;let r=s.next;for(;r;)r=r.emit(this);s.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const t=Math.min(this.maxFPS,e),s=Math.min(Math.max(0,t)/1e3,it.targetFPMS);this._maxElapsedMS=1/s}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){if(e===0)this._minElapsedMS=0;else{const t=Math.max(this.minFPS,e);this._minElapsedMS=1/(t/1e3)}}static get shared(){if(!it._shared){const e=it._shared=new it;e.autoStart=!0,e._protected=!0}return it._shared}static get system(){if(!it._system){const e=it._system=new it;e.autoStart=!0,e._protected=!0}return it._system}};ym.targetFPMS=.06;let Ze=ym,Tu;async function vm(){return Tu??(Tu=(async()=>{const e=Y.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(o=>{const a=document.createElement("video");a.onloadeddata=()=>o(a),a.onerror=()=>o(null),a.autoplay=!1,a.crossOrigin="anonymous",a.preload="auto",a.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",a.load()});if(!t)return"premultiply-alpha-on-upload";const s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);const n=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,n),e.deleteFramebuffer(r),e.deleteTexture(s),e.getExtension("WEBGL_lose_context")?.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),Tu}const Gr=class Zx extends Ee{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...Zx.defaultOptions,...e},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=e.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=e.autoPlay!==!1,this.alphaMode=e.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=Ze.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener("play",this._onPlayStart),e.addEventListener("pause",this._onPlayStop),e.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener("canplay",this._onCanPlay),e.addEventListener("canplaythrough",this._onCanPlayThrough),e.addEventListener("error",this._onError,!0)),this.alphaMode=await vm(),this._load=new Promise((s,r)=>{this.isValid?s(this):(this._resolve=s,this._reject=r,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){const e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const e=this.resource;e&&(e.removeEventListener("play",this._onPlayStart),e.removeEventListener("pause",this._onPlayStop),e.removeEventListener("seeked",this._onSeeked),e.removeEventListener("canplay",this._onCanPlay),e.removeEventListener("canplaythrough",this._onCanPlayThrough),e.removeEventListener("error",this._onError,!0),e.pause(),e.src="",e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(Ze.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(Ze.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(Ze.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};Gr.extension=b.TextureSource,Gr.defaultOptions={...Ee.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},Gr.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let ms=Gr;const ut=(i,e,t=!1)=>(Array.isArray(i)||(i=[i]),e?i.map(s=>typeof s=="string"||t?e(s):s):i);class AS{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){const t=this._cache.get(e);return t||L(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const s=ut(e);let r;for(let l=0;l<this.parsers.length;l++){const c=this.parsers[l];if(c.test(t)){r=c.getCacheableAssets(s,t);break}}const n=new Map(Object.entries(r||{}));r||s.forEach(l=>{n.set(l,t)});const o=[...n.keys()],a={cacheKeys:o,keys:s};s.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const c=r?r[l]:t;this._cache.has(l)&&this._cache.get(l)!==c&&L("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(e){if(!this._cacheMap.has(e)){L(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(r=>{this._cache.delete(r)}),t.keys.forEach(r=>{this._cacheMap.delete(r)})}get parsers(){return this._parsers}}const ae=new AS,wu=[];V.handleByList(b.TextureSource,wu);function bm(i={}){const e=i&&i.resource,t=e?i.resource:i,s=e?i:{resource:i};for(let r=0;r<wu.length;r++){const n=wu[r];if(n.test(t))return new n(s)}throw new Error(`Could not find a source type for resource: ${s.resource}`)}function ES(i={},e=!1){const t=i&&i.resource,s=t?i.resource:i,r=t?i:{resource:i};if(!e&&ae.has(s))return ae.get(s);const n=new M({source:bm(r)});return n.on("destroy",()=>{ae.has(s)&&ae.remove(s)}),e||ae.set(s,n),n}function IS(i,e=!1){return typeof i=="string"?ae.get(i):i instanceof Ee?new M({source:i}):ES(i,e)}M.from=IS,Ee.from=bm,V.add(mm,gm,_m,ms,Ct,Ft,nu);var Kt=(i=>(i[i.Low=0]="Low",i[i.Normal=1]="Normal",i[i.High=2]="High",i))(Kt||{});function dt(i){if(typeof i!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(i)}`)}function gs(i){return i.split("?")[0].split("#")[0]}function PS(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function RS(i,e,t){return i.replace(new RegExp(PS(e),"g"),t)}function MS(i,e){let t="",s=0,r=-1,n=0,o=-1;for(let a=0;a<=i.length;++a){if(a<i.length)o=i.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||n===1))if(r!==a-1&&n===2){if(t.length<2||s!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){const l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",s=0):(t=t.slice(0,l),s=t.length-1-t.lastIndexOf("/")),r=a,n=0;continue}}else if(t.length===2||t.length===1){t="",s=0,r=a,n=0;continue}}}else t.length>0?t+=`/${i.slice(r+1,a)}`:t=i.slice(r+1,a),s=a-r-1;r=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}const Je={toPosix(i){return RS(i,"\\","/")},isUrl(i){return/^https?:/.test(this.toPosix(i))},isDataUrl(i){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(i)},isBlobUrl(i){return i.startsWith("blob:")},hasProtocol(i){return/^[^/:]+:/.test(this.toPosix(i))},getProtocol(i){dt(i),i=this.toPosix(i);const e=/^file:\/\/\//.exec(i);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(i);return t?t[0]:""},toAbsolute(i,e,t){if(dt(i),this.isDataUrl(i)||this.isBlobUrl(i))return i;const s=gs(this.toPosix(e??Y.get().getBaseUrl())),r=gs(this.toPosix(t??this.rootname(s)));return i=this.toPosix(i),i.startsWith("/")?Je.join(r,i.slice(1)):this.isAbsolute(i)?i:this.join(s,i)},normalize(i){if(dt(i),i.length===0)return".";if(this.isDataUrl(i)||this.isBlobUrl(i))return i;i=this.toPosix(i);let e="";const t=i.startsWith("/");this.hasProtocol(i)&&(e=this.rootname(i),i=i.slice(e.length));const s=i.endsWith("/");return i=MS(i),i.length>0&&s&&(i+="/"),t?`/${i}`:e+i},isAbsolute(i){return dt(i),i=this.toPosix(i),this.hasProtocol(i)?!0:i.startsWith("/")},join(...i){if(i.length===0)return".";let e;for(let t=0;t<i.length;++t){const s=i[t];if(dt(s),s.length>0)if(e===void 0)e=s;else{const r=i[t-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${s}`:e+=`/${s}`}}return e===void 0?".":this.normalize(e)},dirname(i){if(dt(i),i.length===0)return".";i=this.toPosix(i);let e=i.charCodeAt(0);const t=e===47;let s=-1,r=!0;const n=this.getProtocol(i),o=i;i=i.slice(n.length);for(let a=i.length-1;a>=1;--a)if(e=i.charCodeAt(a),e===47){if(!r){s=a;break}}else r=!1;return s===-1?t?"/":this.isUrl(o)?n+i:n:t&&s===1?"//":n+i.slice(0,s)},rootname(i){dt(i),i=this.toPosix(i);let e="";if(i.startsWith("/")?e="/":e=this.getProtocol(i),this.isUrl(i)){const t=i.indexOf("/",e.length);t!==-1?e=i.slice(0,t):e=i,e.endsWith("/")||(e+="/")}return e},basename(i,e){dt(i),e&&dt(e),i=gs(this.toPosix(i));let t=0,s=-1,r=!0,n;if(e!==void 0&&e.length>0&&e.length<=i.length){if(e.length===i.length&&e===i)return"";let o=e.length-1,a=-1;for(n=i.length-1;n>=0;--n){const l=i.charCodeAt(n);if(l===47){if(!r){t=n+1;break}}else a===-1&&(r=!1,a=n+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(s=n):(o=-1,s=a))}return t===s?s=a:s===-1&&(s=i.length),i.slice(t,s)}for(n=i.length-1;n>=0;--n)if(i.charCodeAt(n)===47){if(!r){t=n+1;break}}else s===-1&&(r=!1,s=n+1);return s===-1?"":i.slice(t,s)},extname(i){dt(i),i=gs(this.toPosix(i));let e=-1,t=0,s=-1,r=!0,n=0;for(let o=i.length-1;o>=0;--o){const a=i.charCodeAt(o);if(a===47){if(!r){t=o+1;break}continue}s===-1&&(r=!1,s=o+1),a===46?e===-1?e=o:n!==1&&(n=1):e!==-1&&(n=-1)}return e===-1||s===-1||n===0||n===1&&e===s-1&&e===t+1?"":i.slice(e,s)},parse(i){dt(i);const e={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return e;i=gs(this.toPosix(i));let t=i.charCodeAt(0);const s=this.isAbsolute(i);let r;e.root=this.rootname(i),s||this.hasProtocol(i)?r=1:r=0;let n=-1,o=0,a=-1,l=!0,c=i.length-1,h=0;for(;c>=r;--c){if(t=i.charCodeAt(c),t===47){if(!l){o=c+1;break}continue}a===-1&&(l=!1,a=c+1),t===46?n===-1?n=c:h!==1&&(h=1):n!==-1&&(h=-1)}return n===-1||a===-1||h===0||h===1&&n===a-1&&n===o+1?a!==-1&&(o===0&&s?e.base=e.name=i.slice(1,a):e.base=e.name=i.slice(o,a)):(o===0&&s?(e.name=i.slice(1,n),e.base=i.slice(1,a)):(e.name=i.slice(o,n),e.base=i.slice(o,a)),e.ext=i.slice(n,a)),e.dir=this.dirname(i),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function Tm(i,e,t,s,r){const n=e[t];for(let o=0;o<n.length;o++){const a=n[o];t<e.length-1?Tm(i.replace(s[t],a),e,t+1,s,r):r.push(i.replace(s[t],a))}}function kS(i){const e=/\{(.*?)\}/g,t=i.match(e),s=[];if(t){const r=[];t.forEach(n=>{const o=n.substring(1,n.length-1).split(",");r.push(o)}),Tm(i,r,0,t,s)}else s.push(i);return s}const zr=i=>!Array.isArray(i);class Oi{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...e){e.forEach(t=>{this._preferredOrder.push(t),t.priority||(t.priority=Object.keys(t.params))}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e=="string")this._defaultSearchParams=e;else{const t=e;this._defaultSearchParams=Object.keys(t).map(s=>`${encodeURIComponent(s)}=${encodeURIComponent(t[s])}`).join("&")}}getAlias(e){const{alias:t,src:s}=e;return ut(t||s,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>o?.src??o):n?.src?n.src:n,!0)}addManifest(e){this._manifest&&L("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=e,e.bundles.forEach(t=>{this.addBundle(t.name,t.assets)})}addBundle(e,t){const s=[];let r=t;Array.isArray(t)||(r=Object.entries(t).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),r.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const c=this._createBundleAssetId(e,a);s.push(c),l=[a,c]}else{const c=a.map(h=>this._createBundleAssetId(e,h));s.push(...c),l=[...a,...c]}this.add({...n,alias:l,src:o})}),this._bundles[e]=s}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let s;s=n=>{this.hasKey(n)&&L(`[Resolver] already has key: ${n} overwriting`)},ut(t).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:c,parser:h}=n;const u=ut(o).map(g=>typeof g=="string"?kS(g):Array.isArray(g)?g:[g]),d=this.getAlias(n);Array.isArray(d)?d.forEach(s):s(d);const f=[],p=g=>({...this._parsers.find(_=>_.test(g))?.parse(g),src:g});u.forEach(g=>{g.forEach(m=>{let _={};if(typeof m!="object"?_=p(m):(a=m.data??a,l=m.format??l,(m.loadParser||m.parser)&&(c=m.loadParser??c,h=m.parser??h),_={...p(m.src),...m}),!d)throw new Error(`[Resolver] alias is undefined for this asset: ${_.src}`);_=this._buildResolvedAsset(_,{aliases:d,data:a,format:l,loadParser:c,parser:h,progressSize:n.progressSize}),f.push(_)})}),d.forEach(g=>{this._assetMap[g]=f})})}resolveBundle(e){const t=zr(e);e=ut(e);const s={};return e.forEach(r=>{const n=this._bundles[r];if(n){const o=this.resolve(n),a={};for(const l in o){const c=o[l];a[this._extractAssetIdFromBundle(r,l)]=c}s[r]=a}}),t?s[e[0]]:s}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const s={};for(const r in t)s[r]=t[r].src;return s}return t.src}resolve(e){const t=zr(e);e=ut(e);const s={};return e.forEach(r=>{if(!this._resolverHash[r])if(this._assetMap[r]){let n=this._assetMap[r];const o=this._getPreferredOrder(n);o?.priority.forEach(a=>{o.params[a].forEach(l=>{const c=n.filter(h=>h[a]?h[a]===l:!1);c.length&&(n=c)})}),this._resolverHash[r]=n[0]}else this._resolverHash[r]=this._buildResolvedAsset({alias:[r],src:r},{});s[r]=this._resolverHash[r]}),t?s[e[0]]:s}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const s=e[t],r=this._preferredOrder.find(n=>n.params.format.includes(s.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(e){if(!this._defaultSearchParams)return e;const t=/\?/.test(e)?"&":"?";return`${e}${t}${this._defaultSearchParams}`}_buildResolvedAsset(e,t){const{aliases:s,data:r,loadParser:n,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=Je.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=s??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...r||{},...e.data},e.loadParser=n??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??FS(e.src),l!==void 0&&(e.progressSize=l),e}}Oi.RETINA_PREFIX=/@([0-9\.]+)x/;function FS(i){return i.split(".").pop().split("?").shift().split("#").shift()}const Su=(i,e)=>{const t=e.split("?")[1];return t&&(i+=`?${t}`),i},wm=class Ks{constructor(e,t){this.linkedSheets=[];let s=e;e?.source instanceof Ee&&(s={texture:e,data:t});const{texture:r,data:n,cachePrefix:o=""}=s;this.cachePrefix=o,this._texture=r instanceof M?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(e=>{this._callback=e,this._batchIndex=0,this._frameKeys.length<=Ks.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}_processFrames(e){let t=e;const s=Ks.BATCH_SIZE;for(;t-e<s&&t<this._frameKeys.length;){const r=this._frameKeys[t],n=this._frames[r],o=n.frame;if(o){let a=null,l=null;const c=n.trimmed!==!1&&n.sourceSize?n.sourceSize:n.frame,h=new H(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);n.rotated?a=new H(Math.floor(o.x)/this.resolution,Math.floor(o.y)/this.resolution,Math.floor(o.h)/this.resolution,Math.floor(o.w)/this.resolution):a=new H(Math.floor(o.x)/this.resolution,Math.floor(o.y)/this.resolution,Math.floor(o.w)/this.resolution,Math.floor(o.h)/this.resolution),n.trimmed!==!1&&n.spriteSourceSize&&(l=new H(Math.floor(n.spriteSourceSize.x)/this.resolution,Math.floor(n.spriteSourceSize.y)/this.resolution,Math.floor(o.w)/this.resolution,Math.floor(o.h)/this.resolution)),this.textures[r]=new M({source:this.textureSource,frame:a,orig:h,trim:l,rotate:n.rotated?2:0,defaultAnchor:n.anchor,defaultBorders:n.borders,label:r.toString()})}t++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let s=0;s<e[t].length;s++){const r=e[t][s];this.animations[t].push(this.textures[r])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*Ks.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*Ks.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){for(const t in this.textures)this.textures[t].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&(this._texture?.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};wm.BATCH_SIZE=1e3;let Sm=wm;const BS=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Cm(i,e,t){const s={};if(i.forEach(r=>{s[r]=e}),Object.keys(e.textures).forEach(r=>{s[`${e.cachePrefix}${r}`]=e.textures[r]}),!t){const r=Je.dirname(i[0]);e.linkedSheets.forEach((n,o)=>{const a=Cm([`${r}/${e.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(s,a)})}return s}const US={extension:b.Asset,cache:{test:i=>i instanceof Sm,getCacheableAssets:(i,e)=>Cm(i,e,!1)},resolver:{extension:{type:b.ResolveParser,name:"resolveSpritesheet"},test:i=>{const t=i.split("?")[0].split("."),s=t.pop(),r=t.pop();return s==="json"&&BS.includes(r)},parse:i=>{const e=i.split(".");return{resolution:parseFloat(Oi.RETINA_PREFIX.exec(i)?.[1]??"1"),format:e[e.length-2],src:i}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:b.LoadParser,priority:Kt.Normal,name:"spritesheetLoader"},async testParse(i,e){return Je.extname(e.src).toLowerCase()===".json"&&!!i.frames},async parse(i,e,t){const{texture:s,imageFilename:r,textureOptions:n,cachePrefix:o}=e?.data??{};let a=Je.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(s instanceof M)l=s;else{const u=Su(a+(r??i.meta.image),e.src);l=(await t.load([{src:u,data:n}]))[u]}const c=new Sm({texture:l.source,data:i,cachePrefix:o});await c.parse();const h=i?.meta?.related_multi_packs;if(Array.isArray(h)){const u=[];for(const f of h){if(typeof f!="string")continue;let p=a+f;e.data?.ignoreMultiPack||(p=Su(p,e.src),u.push(t.load({src:p,data:{textureOptions:n,ignoreMultiPack:!0}})))}const d=await Promise.all(u);c.linkedSheets=d,d.forEach(f=>{f.linkedSheets=[c].concat(c.linkedSheets.filter(p=>p!==f))})}return c},async unload(i,e,t){await t.unload(i.textureSource._sourceOrigin),i.destroy(!1)}}};V.add(US);class Am{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),s=this._canvas.width,r=this._canvas.height,n=t.width/s*this._renderer.resolution,o=t.height/r*this._renderer.resolution,a=t.left,l=t.top,c=`translate(${a}px, ${l}px) scale(${n}, ${o})`;c!==this._lastTransform&&(this._domElement.style.transform=c,this._lastTransform=c)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(e=>{for(const t of e){if(t.target!==this._canvas)continue;const s=this.canvas.width,r=this.canvas.height,n=t.contentRect.width/s*this._renderer.resolution,o=t.contentRect.height/r*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||Ze.shared.add(this.updateTranslation,this,Ui.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&Ze.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class _s{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=_s.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new X,this.page=new X,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,s){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,s,r,n){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var Cu=/iPhone/i,Em=/iPod/i,Im=/iPad/i,Pm=/\biOS-universal(?:.+)Mac\b/i,Au=/\bAndroid(?:.+)Mobile\b/i,Rm=/Android/i,Di=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Nr=/Silk/i,Bt=/Windows Phone/i,Mm=/\bWindows(?:.+)ARM\b/i,km=/BlackBerry/i,Fm=/BB10/i,Bm=/Opera Mini/i,Um=/\b(CriOS|Chrome)(?:.+)Mobile/i,Om=/Mobile(?:.+)Firefox\b/i,Dm=function(i){return typeof i<"u"&&i.platform==="MacIntel"&&typeof i.maxTouchPoints=="number"&&i.maxTouchPoints>1&&typeof MSStream>"u"};function OS(i){return function(e){return e.test(i)}}function Gm(i){var e={userAgent:"",platform:"",maxTouchPoints:0};!i&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof i=="string"?e.userAgent=i:i&&i.userAgent&&(e={userAgent:i.userAgent,platform:i.platform,maxTouchPoints:i.maxTouchPoints||0});var t=e.userAgent,s=t.split("[FBAN");typeof s[1]<"u"&&(t=s[0]),s=t.split("Twitter"),typeof s[1]<"u"&&(t=s[0]);var r=OS(t),n={apple:{phone:r(Cu)&&!r(Bt),ipod:r(Em),tablet:!r(Cu)&&(r(Im)||Dm(e))&&!r(Bt),universal:r(Pm),device:(r(Cu)||r(Em)||r(Im)||r(Pm)||Dm(e))&&!r(Bt)},amazon:{phone:r(Di),tablet:!r(Di)&&r(Nr),device:r(Di)||r(Nr)},android:{phone:!r(Bt)&&r(Di)||!r(Bt)&&r(Au),tablet:!r(Bt)&&!r(Di)&&!r(Au)&&(r(Nr)||r(Rm)),device:!r(Bt)&&(r(Di)||r(Nr)||r(Au)||r(Rm))||r(/\bokhttp\b/i)},windows:{phone:r(Bt),tablet:r(Mm),device:r(Bt)||r(Mm)},other:{blackberry:r(km),blackberry10:r(Fm),opera:r(Bm),firefox:r(Om),chrome:r(Um),device:r(km)||r(Fm)||r(Bm)||r(Om)||r(Um)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const DS=(Gm.default??Gm)(globalThis.navigator),GS=9,zm=100,zS=0,NS=0,Nm=2,Lm=1,LS=-1e3,HS=-1e3,WS=2,Eu=class Jx{constructor(e,t=DS){this._mobileInfo=t,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(t.tablet||t.phone)&&this._createTouchHook(),this._renderer=e}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const e=document.createElement("button");e.style.width=`${Lm}px`,e.style.height=`${Lm}px`,e.style.position="absolute",e.style.top=`${LS}px`,e.style.left=`${HS}px`,e.style.zIndex=WS.toString(),e.style.backgroundColor="#FF0000",e.title="select to enable accessibility for this content",e.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(e),this._hookDiv=e}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${zS}px`,this._div.style.left=`${NS}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=Nm.toString(),this._canvasObserver=new Am({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const e=this._renderer.view.canvas;if(e.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const t=new MutationObserver(()=>{e.parentNode&&(t.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});t.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const e of this._children)e._accessibleDiv?.parentNode&&(e._accessibleDiv.parentNode.removeChild(e._accessibleDiv),e._accessibleDiv=null),e._accessibleActive=!1;for(const e in this._pools)this._pools[e].forEach(s=>{s.parentNode&&s.parentNode.removeChild(s)}),delete this._pools[e];this._div?.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(e){if(!e.visible||!e.accessibleChildren)return;e.accessible&&(e._accessibleActive||this._addChild(e),e._renderId=this._renderId);const t=e.children;if(t)for(let s=0;s<t.length;s++)this._updateAccessibleObjects(t[s])}init(e){const s={accessibilityOptions:{...Jx.defaultOptions,...e?.accessibilityOptions||{}}};this.debug=s.accessibilityOptions.debug,this._activateOnTab=s.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=s.accessibilityOptions.deactivateOnMouseMove,s.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const e=performance.now();if(this._mobileInfo.android.device&&e<this._androidUpdateCount||(this._androidUpdateCount=e+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const t=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const s of this._children)s._renderId===this._renderId&&t.add(this._children.indexOf(s))}for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];t.has(s)||(r._accessibleDiv&&r._accessibleDiv.parentNode&&(r._accessibleDiv.parentNode.removeChild(r._accessibleDiv),this._getPool(r.accessibleType).push(r._accessibleDiv),r._accessibleDiv=null),r._accessibleActive=!1,nm(this._children,s,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let s=0;s<this._children.length;s++){const r=this._children[s];if(!r._accessibleActive||!r._accessibleDiv)continue;const n=r._accessibleDiv,o=r.hitArea||r.getBounds().rectangle;if(r.hitArea){const a=r.worldTransform;n.style.left=`${a.tx+o.x*a.a}px`,n.style.top=`${a.ty+o.y*a.d}px`,n.style.width=`${o.width*a.a}px`,n.style.height=`${o.height*a.d}px`}else this._capHitArea(o),n.style.left=`${o.x}px`,n.style.top=`${o.y}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`}this._renderId++}_updateDebugHTML(e){e.innerHTML=`type: ${e.type}</br> title : ${e.title}</br> tabIndex: ${e.tabIndex}`}_capHitArea(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);const{width:t,height:s}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>s&&(e.height=s-e.y)}_addChild(e){let s=this._getPool(e.accessibleType).pop();s?(s.innerHTML="",s.removeAttribute("title"),s.removeAttribute("aria-label"),s.tabIndex=0):(e.accessibleType==="button"?s=document.createElement("button"):(s=document.createElement(e.accessibleType),s.style.cssText=`
|
|
69
|
+
`),n?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",r),console.warn(s),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",r),console.warn(s))),Dp.add(e)};Object.defineProperties(W,{quiet:{get:()=>Mi.quiet,set:i=>{Mi.quiet=i},enumerable:!0,configurable:!1},noColor:{get:()=>Mi.noColor,set:i=>{Mi.noColor=i},enumerable:!0,configurable:!1}});const Gp=()=>{};function ki(i){return i+=i===0?1:0,--i,i|=i>>>1,i|=i>>>2,i|=i>>>4,i|=i>>>8,i|=i>>>16,i+1}function zp(i){return!(i&i-1)&&!!i}function Np(i){const e={};for(const t in i)i[t]!==void 0&&(e[t]=i[t]);return e}const Lp=Object.create(null);function q1(i){const e=Lp[i];return e===void 0&&(Lp[i]=he("resource")),e}const Hp=class K_ extends je{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...K_.defaultOptions,...e},this.addressMode=e.addressMode,this.addressModeU=e.addressModeU??this.addressModeU,this.addressModeV=e.addressModeV??this.addressModeV,this.addressModeW=e.addressModeW??this.addressModeW,this.scaleMode=e.scaleMode,this.magFilter=e.magFilter??this.magFilter,this.minFilter=e.minFilter??this.minFilter,this.mipmapFilter=e.mipmapFilter??this.mipmapFilter,this.lodMinClamp=e.lodMinClamp,this.lodMaxClamp=e.lodMaxClamp,this.compare=e.compare,this.maxAnisotropy=e.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){W(Q,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this.emit("change",this),this._sharedResourceId=null}_generateResourceId(){const e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=q1(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};Hp.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let wt=Hp;const Wp=class j_ extends je{constructor(e={}){super(),this.options=e,this.uid=he("textureSource"),this._resourceType="textureSource",this._resourceId=he("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,e={...j_.defaultOptions,...e},this.label=e.label??"",this.resource=e.resource,this.autoGarbageCollect=e.autoGarbageCollect,this._resolution=e.resolution,e.width?this.pixelWidth=e.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,e.height?this.pixelHeight=e.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=e.format,this.dimension=e.dimensions,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=e.antialias,this.alphaMode=e.alphaMode,this.style=new wt(Np(e)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(e){this.style!==e&&(this._style?.off("change",this._onStyleChange,this),this._style=e,this._style?.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){this._resourceId=he("resource"),this.emit("change",this),this.emit("unload",this)}get resourceWidth(){const{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){const{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,s){s||(s=this._resolution),e||(e=this.width),t||(t=this.height);const r=Math.round(e*s),n=Math.round(t*s);return this.width=r/s,this.height=n/s,this._resolution=s,this.pixelWidth===r&&this.pixelHeight===n?!1:(this._refreshPOT(),this.pixelWidth=r,this.pixelHeight=n,this.emit("resize",this),this._resourceId=he("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=zp(this.pixelWidth)&&zp(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};Wp.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let Ee=Wp;class nu extends Ee{constructor(e){const t=e.resource||new Float32Array(e.width*e.height*4);let s=e.format;s||(t instanceof Float32Array?s="rgba32float":t instanceof Int32Array||t instanceof Uint32Array?s="rgba32uint":t instanceof Int16Array||t instanceof Uint16Array?s="rgba16uint":(t instanceof Int8Array,s="bgra8unorm")),super({...e,resource:t,format:s}),this.uploadMethodId="buffer"}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}}nu.extension=b.TextureSource;const Vp=new O;class $p{constructor(e,t){this.mapCoord=new O,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof t>"u"?this.clampMargin=e.width<10?0:.5:this.clampMargin=t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){this.texture!==e&&(this._texture?.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(e,t){t===void 0&&(t=e);const s=this.mapCoord;for(let r=0;r<e.length;r+=2){const n=e[r],o=e[r+1];t[r]=n*s.a+o*s.c+s.tx,t[r+1]=n*s.b+o*s.d+s.ty}return t}update(){const e=this._texture;this._updateID++;const t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);const s=e.orig,r=e.trim;r&&(Vp.set(s.width/r.width,0,0,s.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(Vp));const n=e.source,o=this.uClampFrame,a=this.clampMargin/n._resolution,l=this.clampOffset/n._resolution;return o[0]=(e.frame.x+a+l)/n.width,o[1]=(e.frame.y+a+l)/n.height,o[2]=(e.frame.x+e.frame.width-a+l)/n.width,o[3]=(e.frame.y+e.frame.height-a+l)/n.height,this.uClampOffset[0]=this.clampOffset/n.pixelWidth,this.uClampOffset[1]=this.clampOffset/n.pixelHeight,this.isSimple=e.frame.width===n.width&&e.frame.height===n.height&&e.rotate===0,!0}}class M extends je{constructor({source:e,label:t,frame:s,orig:r,trim:n,defaultAnchor:o,defaultBorders:a,rotate:l,dynamic:c}={}){if(super(),this.uid=he("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new H,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=e?.source??new Ee,this.noFrame=!s,s)this.frame.copyFrom(s);else{const{width:h,height:u}=this._source;this.frame.width=h,this.frame.height=u}this.orig=r||this.frame,this.trim=n,this.rotate=l??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=c||!1,this.updateUvs()}set source(e){this._source&&this._source.off("resize",this.update,this),this._source=e,e.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new $p(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:s,height:r}=this._source,n=t.x/s,o=t.y/r,a=t.width/s,l=t.height/r;let c=this.rotate;if(c){const h=a/2,u=l/2,d=n+h,f=o+u;c=oe.add(c,oe.NW),e.x0=d+h*oe.uX(c),e.y0=f+u*oe.uY(c),c=oe.add(c,2),e.x1=d+h*oe.uX(c),e.y1=f+u*oe.uY(c),c=oe.add(c,2),e.x2=d+h*oe.uX(c),e.y2=f+u*oe.uY(c),c=oe.add(c,2),e.x3=d+h*oe.uX(c),e.y3=f+u*oe.uY(c)}else e.x0=n,e.y0=o,e.x1=n+a,e.y1=o,e.x2=n+a,e.y2=o+l,e.x3=n,e.y3=o+l}destroy(e=!1){this._source&&(this._source.off("resize",this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return W(Q,"Texture.baseTexture is now Texture.source"),this._source}}M.EMPTY=new M({label:"EMPTY",source:new Ee({label:"EMPTY"})}),M.EMPTY.destroy=Gp,M.WHITE=new M({source:new nu({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),M.WHITE.destroy=Gp;function Xp(i,e,t){const{width:s,height:r}=t.orig,n=t.trim;if(n){const o=n.width,a=n.height;i.minX=n.x-e._x*s,i.maxX=i.minX+o,i.minY=n.y-e._y*r,i.maxY=i.minY+a}else i.minX=-e._x*s,i.maxX=i.minX+s,i.minY=-e._y*r,i.maxY=i.minY+r}const Yp=new O;class De{constructor(e=1/0,t=1/0,s=-1/0,r=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=Yp,this.minX=e,this.minY=t,this.maxX=s,this.maxY=r}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new H);const e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=Yp,this}set(e,t,s,r){this.minX=e,this.minY=t,this.maxX=s,this.maxY=r}addFrame(e,t,s,r,n){n||(n=this.matrix);const o=n.a,a=n.b,l=n.c,c=n.d,h=n.tx,u=n.ty;let d=this.minX,f=this.minY,p=this.maxX,g=this.maxY,m=o*e+l*t+h,x=a*e+c*t+u;m<d&&(d=m),x<f&&(f=x),m>p&&(p=m),x>g&&(g=x),m=o*s+l*t+h,x=a*s+c*t+u,m<d&&(d=m),x<f&&(f=x),m>p&&(p=m),x>g&&(g=x),m=o*e+l*r+h,x=a*e+c*r+u,m<d&&(d=m),x<f&&(f=x),m>p&&(p=m),x>g&&(g=x),m=o*s+l*r+h,x=a*s+c*r+u,m<d&&(d=m),x<f&&(f=x),m>p&&(p=m),x>g&&(g=x),this.minX=d,this.minY=f,this.maxX=p,this.maxY=g}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){const t=this.minX,s=this.minY,r=this.maxX,n=this.maxY,{a:o,b:a,c:l,d:c,tx:h,ty:u}=e;let d=o*t+l*s+h,f=a*t+c*s+u;this.minX=d,this.minY=f,this.maxX=d,this.maxY=f,d=o*r+l*s+h,f=a*r+c*s+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=o*t+l*n+h,f=a*t+c*n+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY,d=o*r+l*n+h,f=a*r+c*n+u,this.minX=d<this.minX?d:this.minX,this.minY=f<this.minY?f:this.minY,this.maxX=d>this.maxX?d:this.maxX,this.maxY=f>this.maxY?f:this.maxY}fit(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,s,r){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<s&&(this.minY=s),this.maxY>r&&(this.maxY=r),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new De(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){const t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){const t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,s,r){let n=this.minX,o=this.minY,a=this.maxX,l=this.maxY;r||(r=this.matrix);const c=r.a,h=r.b,u=r.c,d=r.d,f=r.tx,p=r.ty;for(let g=t;g<s;g+=2){const m=e[g],x=e[g+1],_=c*m+u*x+f,y=h*m+d*x+p;n=_<n?_:n,o=y<o?y:o,a=_>a?_:a,l=y>l?y:l}this.minX=n,this.minY=o,this.maxX=a,this.maxY=l}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}var K1={grad:.9,turn:360,rad:360/(2*Math.PI)},Mt=function(i){return typeof i=="string"?i.length>0:typeof i=="number"},Re=function(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*i)/t+0},nt=function(i,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),i>t?t:i>e?i:e},qp=function(i){return(i=isFinite(i)?i%360:0)>0?i:i+360},Kp=function(i){return{r:nt(i.r,0,255),g:nt(i.g,0,255),b:nt(i.b,0,255),a:nt(i.a)}},ou=function(i){return{r:Re(i.r),g:Re(i.g),b:Re(i.b),a:Re(i.a,3)}},j1=/^#([0-9a-f]{3,8})$/i,Mr=function(i){var e=i.toString(16);return e.length<2?"0"+e:e},jp=function(i){var e=i.r,t=i.g,s=i.b,r=i.a,n=Math.max(e,t,s),o=n-Math.min(e,t,s),a=o?n===e?(t-s)/o:n===t?2+(s-e)/o:4+(e-t)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},Zp=function(i){var e=i.h,t=i.s,s=i.v,r=i.a;e=e/360*6,t/=100,s/=100;var n=Math.floor(e),o=s*(1-t),a=s*(1-(e-n)*t),l=s*(1-(1-e+n)*t),c=n%6;return{r:255*[s,a,o,o,l,s][c],g:255*[l,s,s,a,o,o][c],b:255*[o,o,l,s,s,a][c],a:r}},Jp=function(i){return{h:qp(i.h),s:nt(i.s,0,100),l:nt(i.l,0,100),a:nt(i.a)}},Qp=function(i){return{h:Re(i.h),s:Re(i.s),l:Re(i.l),a:Re(i.a,3)}},em=function(i){return Zp((t=(e=i).s,{h:e.h,s:(t*=((s=e.l)<50?s:100-s)/100)>0?2*t/(s+t)*100:0,v:s+t,a:e.a}));var e,t,s},fs=function(i){return{h:(e=jp(i)).h,s:(r=(200-(t=e.s))*(s=e.v)/100)>0&&r<200?t*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,t,s,r},Z1=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,J1=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Q1=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,eS=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,au={string:[[function(i){var e=j1.exec(i);return e?(i=e[1]).length<=4?{r:parseInt(i[0]+i[0],16),g:parseInt(i[1]+i[1],16),b:parseInt(i[2]+i[2],16),a:i.length===4?Re(parseInt(i[3]+i[3],16)/255,2):1}:i.length===6||i.length===8?{r:parseInt(i.substr(0,2),16),g:parseInt(i.substr(2,2),16),b:parseInt(i.substr(4,2),16),a:i.length===8?Re(parseInt(i.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(i){var e=Q1.exec(i)||eS.exec(i);return e?e[2]!==e[4]||e[4]!==e[6]?null:Kp({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(i){var e=Z1.exec(i)||J1.exec(i);if(!e)return null;var t,s,r=Jp({h:(t=e[1],s=e[2],s===void 0&&(s="deg"),Number(t)*(K1[s]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return em(r)},"hsl"]],object:[[function(i){var e=i.r,t=i.g,s=i.b,r=i.a,n=r===void 0?1:r;return Mt(e)&&Mt(t)&&Mt(s)?Kp({r:Number(e),g:Number(t),b:Number(s),a:Number(n)}):null},"rgb"],[function(i){var e=i.h,t=i.s,s=i.l,r=i.a,n=r===void 0?1:r;if(!Mt(e)||!Mt(t)||!Mt(s))return null;var o=Jp({h:Number(e),s:Number(t),l:Number(s),a:Number(n)});return em(o)},"hsl"],[function(i){var e=i.h,t=i.s,s=i.v,r=i.a,n=r===void 0?1:r;if(!Mt(e)||!Mt(t)||!Mt(s))return null;var o=(function(a){return{h:qp(a.h),s:nt(a.s,0,100),v:nt(a.v,0,100),a:nt(a.a)}})({h:Number(e),s:Number(t),v:Number(s),a:Number(n)});return Zp(o)},"hsv"]]},tm=function(i,e){for(var t=0;t<e.length;t++){var s=e[t][0](i);if(s)return[s,e[t][1]]}return[null,void 0]},tS=function(i){return typeof i=="string"?tm(i.trim(),au.string):typeof i=="object"&&i!==null?tm(i,au.object):[null,void 0]},lu=function(i,e){var t=fs(i);return{h:t.h,s:nt(t.s+100*e,0,100),l:t.l,a:t.a}},cu=function(i){return(299*i.r+587*i.g+114*i.b)/1e3/255},im=function(i,e){var t=fs(i);return{h:t.h,s:t.s,l:nt(t.l+100*e,0,100),a:t.a}},hu=(function(){function i(e){this.parsed=tS(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return i.prototype.isValid=function(){return this.parsed!==null},i.prototype.brightness=function(){return Re(cu(this.rgba),2)},i.prototype.isDark=function(){return cu(this.rgba)<.5},i.prototype.isLight=function(){return cu(this.rgba)>=.5},i.prototype.toHex=function(){return e=ou(this.rgba),t=e.r,s=e.g,r=e.b,o=(n=e.a)<1?Mr(Re(255*n)):"","#"+Mr(t)+Mr(s)+Mr(r)+o;var e,t,s,r,n,o},i.prototype.toRgb=function(){return ou(this.rgba)},i.prototype.toRgbString=function(){return e=ou(this.rgba),t=e.r,s=e.g,r=e.b,(n=e.a)<1?"rgba("+t+", "+s+", "+r+", "+n+")":"rgb("+t+", "+s+", "+r+")";var e,t,s,r,n},i.prototype.toHsl=function(){return Qp(fs(this.rgba))},i.prototype.toHslString=function(){return e=Qp(fs(this.rgba)),t=e.h,s=e.s,r=e.l,(n=e.a)<1?"hsla("+t+", "+s+"%, "+r+"%, "+n+")":"hsl("+t+", "+s+"%, "+r+"%)";var e,t,s,r,n},i.prototype.toHsv=function(){return e=jp(this.rgba),{h:Re(e.h),s:Re(e.s),v:Re(e.v),a:Re(e.a,3)};var e},i.prototype.invert=function(){return St({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},i.prototype.saturate=function(e){return e===void 0&&(e=.1),St(lu(this.rgba,e))},i.prototype.desaturate=function(e){return e===void 0&&(e=.1),St(lu(this.rgba,-e))},i.prototype.grayscale=function(){return St(lu(this.rgba,-1))},i.prototype.lighten=function(e){return e===void 0&&(e=.1),St(im(this.rgba,e))},i.prototype.darken=function(e){return e===void 0&&(e=.1),St(im(this.rgba,-e))},i.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},i.prototype.alpha=function(e){return typeof e=="number"?St({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Re(this.rgba.a,3);var t},i.prototype.hue=function(e){var t=fs(this.rgba);return typeof e=="number"?St({h:e,s:t.s,l:t.l,a:t.a}):Re(t.h)},i.prototype.isEqual=function(e){return this.toHex()===St(e).toHex()},i})(),St=function(i){return i instanceof hu?i:new hu(i)},sm=[],iS=function(i){i.forEach(function(e){sm.indexOf(e)<0&&(e(hu,au),sm.push(e))})};function sS(i,e){var t={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},s={};for(var r in t)s[t[r]]=r;var n={};i.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,l,c=s[this.toHex()];if(c)return c;if(o?.closest){var h=this.toRgb(),u=1/0,d="black";if(!n.length)for(var f in t)n[f]=new i(t[f]).toRgb();for(var p in t){var g=(a=h,l=n[p],Math.pow(a.r-l.r,2)+Math.pow(a.g-l.g,2)+Math.pow(a.b-l.b,2));g<u&&(u=g,d=p)}return d}},e.string.push([function(o){var a=o.toLowerCase(),l=a==="transparent"?"#0000":t[a];return l?new i(l).toRgb():null},"name"])}iS([sS]);const Fi=class qs{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(e){if(e instanceof qs)this._value=this._cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(e===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,e))&&(this._value=this._cloneSource(e),this._normalize(this._value))}}get value(){return this._value}_cloneSource(e){return typeof e=="string"||typeof e=="number"||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e=="object"&&e!==null?{...e}:e}_isSourceEqual(e,t){const s=typeof e;if(s!==typeof t)return!1;if(s==="number"||s==="string"||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length!==t.length?!1:e.every((n,o)=>n===t[o]);if(e!==null&&t!==null){const n=Object.keys(e),o=Object.keys(t);return n.length!==o.length?!1:n.every(a=>e[a]===t[a])}return e===t}toRgba(){const[e,t,s,r]=this._components;return{r:e,g:t,b:s,a:r}}toRgb(){const[e,t,s]=this._components;return{r:e,g:t,b:s}}toRgbaString(){const[e,t,s]=this.toUint8RgbArray();return`rgba(${e},${t},${s},${this.alpha})`}toUint8RgbArray(e){const[t,s,r]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(s*255),e[2]=Math.round(r*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,s,r,n]=this._components;return e[0]=t,e[1]=s,e[2]=r,e[3]=n,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,s,r]=this._components;return e[0]=t,e[1]=s,e[2]=r,e}toNumber(){return this._int}toBgrNumber(){const[e,t,s]=this.toUint8RgbArray();return(s<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,s,r,n]=qs._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let s=this._int>>16&255,r=this._int>>8&255,n=this._int&255;return t&&(s=s*e+.5|0,r=r*e+.5|0,n=n*e+.5|0),(e*255<<24)+(s<<16)+(r<<8)+n}toHex(){const e=this._int.toString(16);return`#${"000000".substring(0,6-e.length)+e}`}toHexa(){const t=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(e){return this._components[3]=this._clamp(e),this}_normalize(e){let t,s,r,n;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,s=(o>>8&255)/255,r=(o&255)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,s,r,n=255]=e,t/=255,s/=255,r/=255,n/=255;else if(typeof e=="string"||typeof e=="object"){if(typeof e=="string"){const a=qs.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=St(e);o.isValid()&&({r:t,g:s,b:r,a:n}=o.rgba,t/=255,s/=255,r/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=s,this._components[2]=r,this._components[3]=n,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,s]=this._components;this._int=(e*255<<16)+(t*255<<8)+(s*255|0)}_clamp(e,t=0,s=1){return typeof e=="number"?Math.min(Math.max(e,t),s):(e.forEach((r,n)=>{e[n]=Math.min(Math.max(r,t),s)}),e)}static isColorLike(e){return typeof e=="number"||typeof e=="string"||e instanceof Number||e instanceof qs||Array.isArray(e)||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Float32Array||e.r!==void 0&&e.g!==void 0&&e.b!==void 0||e.r!==void 0&&e.g!==void 0&&e.b!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0&&e.a!==void 0}};Fi.shared=new Fi,Fi._temp=new Fi,Fi.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let ue=Fi;const rS={cullArea:null,cullable:!1,cullableChildren:!0};let uu=0;const rm=500;function L(...i){uu!==rm&&(uu++,uu===rm?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...i))}const Bi={_registeredResources:new Set,register(i){this._registeredResources.add(i)},unregister(i){this._registeredResources.delete(i)},release(){this._registeredResources.forEach(i=>i.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(i){return this._registeredResources.has(i)},reset(){this._registeredResources.clear()}};class nS{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),t.init?.(e),t}return(e){e.reset?.(),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}class oS{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new nS(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const s=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[s]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Se=new oS;Bi.register(Se);const aS={get isCachedAsTexture(){return!!this.renderGroup?.isCachedAsTexture},cacheAsTexture(i){typeof i=="boolean"&&i===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(i===!0?{}:i))},updateCacheTexture(){this.renderGroup?.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(i){W("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(i)}};function nm(i,e,t){const s=i.length;let r;if(e>=s||t===0)return;t=e+t>s?s-e:t;const n=s-t;for(r=e;r<n;++r)i[r]=i[r+t];i.length=n}const lS={allowChildren:!0,removeChildren(i=0,e){const t=e??this.children.length,s=t-i,r=[];if(s>0&&s<=t){for(let o=t-1;o>=i;o--){const a=this.children[o];a&&(r.push(a),a.parent=null)}nm(this.children,i,t);const n=this.renderGroup||this.parentRenderGroup;n&&n.removeChildren(r);for(let o=0;o<r.length;++o){const a=r[o];a.parentRenderLayer?.detach(a),this.emit("childRemoved",a,this,o),r[o].emit("removed",this)}return r.length>0&&this._didViewChangeTick++,r}else if(s===0&&this.children.length===0)return r;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(i){const e=this.getChildAt(i);return this.removeChild(e)},getChildAt(i){if(i<0||i>=this.children.length)throw new Error(`getChildAt: Index (${i}) does not exist.`);return this.children[i]},setChildIndex(i,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(i),this.addChildAt(i,e)},getChildIndex(i){const e=this.children.indexOf(i);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(i,e){this.allowChildren||W(Q,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:t}=this;if(e<0||e>t.length)throw new Error(`${i}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);if(i.parent){const r=i.parent.children.indexOf(i);if(i.parent===this&&r===e)return i;r!==-1&&i.parent.children.splice(r,1)}e===t.length?t.push(i):t.splice(e,0,i),i.parent=this,i.didChange=!0,i._updateFlags=15;const s=this.renderGroup||this.parentRenderGroup;return s&&s.addChild(i),this.sortableChildren&&(this.sortDirty=!0),this.emit("childAdded",i,this,e),i.emit("added",this),i},swapChildren(i,e){if(i===e)return;const t=this.getChildIndex(i),s=this.getChildIndex(e);this.children[t]=e,this.children[s]=i;const r=this.renderGroup||this.parentRenderGroup;r&&(r.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){this.parent?.removeChild(this)},reparentChild(...i){return i.length===1?this.reparentChildAt(i[0],this.children.length):(i.forEach(e=>this.reparentChildAt(e,this.children.length)),i[0])},reparentChildAt(i,e){if(i.parent===this)return this.setChildIndex(i,e),i;const t=i.worldTransform.clone();i.removeFromParent(),this.addChildAt(i,e);const s=this.worldTransform.clone();return s.invert(),t.prepend(s),i.setFromMatrix(t),i},replaceChild(i,e){i.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(i)),e.setFromMatrix(i.localTransform),e.updateLocalTransform(),this.removeChild(i)}},cS={collectRenderables(i,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(i,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,i):this.collectRenderablesWithEffects(i,e,t))},collectRenderablesSimple(i,e,t){const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(i,e,t)},collectRenderablesWithEffects(i,e,t){const{renderPipes:s}=e;for(let r=0;r<this.effects.length;r++){const n=this.effects[r];s[n.pipe].push(n,this,i)}this.collectRenderablesSimple(i,e,t);for(let r=this.effects.length-1;r>=0;r--){const n=this.effects[r];s[n.pipe].pop(n,this,i)}}};class kr{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}class hS{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){const s=this._tests[t];if(s.test(e))return Se.get(s.maskClass,e)}return e}returnMaskEffect(e){Se.return(e)}}const du=new hS;V.handleByList(b.MaskEffect,du._effectClasses);const uS={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const i=this.renderGroup||this.parentRenderGroup;i&&(i.structureDidChange=!0)},addEffect(i){this.effects.indexOf(i)===-1&&(this.effects.push(i),this.effects.sort((t,s)=>t.priority-s.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(i){const e=this.effects.indexOf(i);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(i){const e=this._maskEffect;e?.mask!==i&&(e&&(this.removeEffect(e),du.returnMaskEffect(e),this._maskEffect=null),i!=null&&(this._maskEffect=du.getMaskEffect(i),this.addEffect(this._maskEffect)))},get mask(){return this._maskEffect?.mask},setMask(i){this._maskOptions={...this._maskOptions,...i},i.mask&&(this.mask=i.mask),this._markStructureAsChanged()},set filters(i){!Array.isArray(i)&&i&&(i=[i]);const e=this._filterEffect||(this._filterEffect=new kr);i=i;const t=i?.length>0,s=e.filters?.length>0,r=t!==s;i=Array.isArray(i)?i.slice(0):i,e.filters=Object.freeze(i),r&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=i??null))},get filters(){return this._filterEffect?.filters},set filterArea(i){this._filterEffect||(this._filterEffect=new kr),this._filterEffect.filterArea=i},get filterArea(){return this._filterEffect?.filterArea}},dS={label:null,get name(){return W(Q,"Container.name property has been removed, use Container.label instead"),this.label},set name(i){W(Q,"Container.name property has been removed, use Container.label instead"),this.label=i},getChildByName(i,e=!1){return this.getChildByLabel(i,e)},getChildByLabel(i,e=!1){const t=this.children;for(let s=0;s<t.length;s++){const r=t[s];if(r.label===i||i instanceof RegExp&&i.test(r.label))return r}if(e)for(let s=0;s<t.length;s++){const n=t[s].getChildByLabel(i,!0);if(n)return n}return null},getChildrenByLabel(i,e=!1,t=[]){const s=this.children;for(let r=0;r<s.length;r++){const n=s[r];(n.label===i||i instanceof RegExp&&i.test(n.label))&&t.push(n)}if(e)for(let r=0;r<s.length;r++)s[r].getChildrenByLabel(i,!0,t);return t}},Le=Se.getPool(O),kt=Se.getPool(De),fS=new O,pS={getFastGlobalBounds(i,e){e||(e=new De),e.clear(),this._getGlobalBoundsRecursive(!!i,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(i,e,t){let s=e;if(i&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const r=!!this.effects.length;if((this.renderGroup||r)&&(s=kt.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;s.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const n=this.children;for(let o=0;o<n.length;o++)n[o]._getGlobalBoundsRecursive(i,s,t)}if(r){let n=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(n||(n=!0,s.applyMatrix(o.worldTransform)),this.effects[a].addBounds(s,!0));n&&s.applyMatrix(o.worldTransform.copyTo(fS).invert()),e.addBounds(s),kt.return(s)}else this.renderGroup&&(e.addBounds(s,this.relativeGroupTransform),kt.return(s))}};function fu(i,e,t){t.clear();let s,r;return i.parent?e?s=i.parent.worldTransform:(r=Le.get().identity(),s=pu(i,r)):s=O.IDENTITY,om(i,t,s,e),r&&Le.return(r),t.isValid||t.set(0,0,0,0),t}function om(i,e,t,s){if(!i.visible||!i.measurable)return;let r;s?r=i.worldTransform:(i.updateLocalTransform(),r=Le.get(),r.appendFrom(i.localTransform,t));const n=e,o=!!i.effects.length;if(o&&(e=kt.get().clear()),i.boundsArea)e.addRect(i.boundsArea,r);else{const a=i.bounds;a&&!a.isEmpty()&&(e.matrix=r,e.addBounds(a));for(let l=0;l<i.children.length;l++)om(i.children[l],e,r,s)}if(o){for(let a=0;a<i.effects.length;a++)i.effects[a].addBounds?.(e);n.addBounds(e,O.IDENTITY),kt.return(e)}s||Le.return(r)}function pu(i,e){const t=i.parent;return t&&(pu(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function am(i,e){if(i===16777215||!e)return e;if(e===16777215||!i)return i;const t=i>>16&255,s=i>>8&255,r=i&255,n=e>>16&255,o=e>>8&255,a=e&255,l=t*n/255|0,c=s*o/255|0,h=r*a/255|0;return(l<<16)+(c<<8)+h}const lm=16777215;function Fr(i,e){return i===lm?e:e===lm?i:am(i,e)}function Br(i){return((i&255)<<16)+(i&65280)+(i>>16&255)}const mS={getGlobalAlpha(i){if(i)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let e=this.alpha,t=this.parent;for(;t;)e*=t.alpha,t=t.parent;return e},getGlobalTransform(i=new O,e){if(e)return i.copyFrom(this.worldTransform);this.updateLocalTransform();const t=pu(this,Le.get().identity());return i.appendFrom(this.localTransform,t),Le.return(t),i},getGlobalTint(i){if(i)return this.renderGroup?Br(this.renderGroup.worldColor):this.parentRenderGroup?Br(Fr(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=Fr(e,t.localColor),t=t.parent;return Br(e)}};function mu(i,e,t){return e.clear(),t||(t=O.IDENTITY),cm(i,e,t,i,!0),e.isValid||e.set(0,0,0,0),e}function cm(i,e,t,s,r){let n;if(r)n=Le.get(),n=t.copyTo(n);else{if(!i.visible||!i.measurable)return;i.updateLocalTransform();const l=i.localTransform;n=Le.get(),n.appendFrom(l,t)}const o=e,a=!!i.effects.length;if(a&&(e=kt.get().clear()),i.boundsArea)e.addRect(i.boundsArea,n);else{i.renderPipeId&&(e.matrix=n,e.addBounds(i.bounds));const l=i.children;for(let c=0;c<l.length;c++)cm(l[c],e,n,s,!1)}if(a){for(let l=0;l<i.effects.length;l++)i.effects[l].addLocalBounds?.(e,s);o.addBounds(e,O.IDENTITY),kt.return(e)}Le.return(n)}function hm(i,e){const t=i.children;for(let s=0;s<t.length;s++){const r=t[s],n=r.uid,o=(r._didViewChangeTick&65535)<<16|r._didContainerChangeTick&65535,a=e.index;(e.data[a]!==n||e.data[a+1]!==o)&&(e.data[e.index]=n,e.data[e.index+1]=o,e.didChange=!0),e.index=a+2,r.children.length&&hm(r,e)}return e.didChange}const gS=new O,xS={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(i,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=i/e*t:this.scale.x=t},_setHeight(i,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=i/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new De});const i=this._localBoundsCacheData;return i.index=1,i.didChange=!1,i.data[0]!==this._didViewChangeTick&&(i.didChange=!0,i.data[0]=this._didViewChangeTick),hm(this,i),i.didChange&&mu(this,i.localBounds,gS),i.localBounds},getBounds(i,e){return fu(this,i,e||new De)}},_S={_onRender:null,set onRender(i){const e=this.renderGroup||this.parentRenderGroup;if(!i){this._onRender&&e?.removeOnRender(this),this._onRender=null;return}this._onRender||e?.addOnRender(this),this._onRender=i},get onRender(){return this._onRender}},yS={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(i){this._zIndex!==i&&(this._zIndex=i,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(vS))}};function vS(i,e){return i._zIndex-e._zIndex}const bS={getGlobalPosition(i=new X,e=!1){return this.parent?this.parent.toGlobal(this._position,i,e):(i.x=this._position.x,i.y=this._position.y),i},toGlobal(i,e,t=!1){const s=this.getGlobalTransform(Le.get(),t);return e=s.apply(i,e),Le.return(s),e},toLocal(i,e,t,s){e&&(i=e.toGlobal(i,t,s));const r=this.getGlobalTransform(Le.get(),s);return t=r.applyInverse(i,t),Le.return(r),t}};class um{constructor(){this.uid=he("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let TS=0;class wS{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new wt(this.textureOptions)}createTexture(e,t,s){const r=new Ee({...this.textureOptions,width:e,height:t,resolution:1,antialias:s,autoGarbageCollect:!1});return new M({source:r,label:`texturePool_${TS++}`})}getOptimalTexture(e,t,s=1,r){let n=Math.ceil(e*s-1e-6),o=Math.ceil(t*s-1e-6);n=ki(n),o=ki(o);const a=(n<<17)+(o<<1)+(r?1:0);this._texturePool[a]||(this._texturePool[a]=[]);let l=this._texturePool[a].pop();return l||(l=this.createTexture(n,o,r)),l.source._resolution=s,l.source.width=n/s,l.source.height=o/s,l.source.pixelWidth=n,l.source.pixelHeight=o,l.frame.x=0,l.frame.y=0,l.frame.width=e,l.frame.height=t,l.updateUvs(),this._poolKeyHash[l.uid]=a,l}getSameSizeTexture(e,t=!1){const s=e.source;return this.getOptimalTexture(e.width,e.height,s._resolution,t)}returnTexture(e,t=!1){const s=this._poolKeyHash[e.uid];t&&(e.source.style=this.textureStyle),this._texturePool[s].push(e)}clear(e){if(e=e!==!1,e)for(const t in this._texturePool){const s=this._texturePool[t];if(s)for(let r=0;r<s.length;r++)s[r].destroy(!0)}this._texturePool={}}}const ve=new wS;Bi.register(ve);class gu{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new O,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new um,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;const t=e.children;for(let s=0;s<t.length;s++){const r=t[s];r._updateFlags=15,this.addChild(r)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(ve.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const e in this.childrenToUpdate){const t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){const t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.parent===this.root?e.relativeRenderGroupDepth=1:e.relativeRenderGroupDepth=e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);const t=e.children;for(let s=0;s<t.length;s++)this.addChild(t[s])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}const t=e.children;for(let s=0;s<t.length;s++)this.removeChild(t[s])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||(t=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]}),t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.push(e)}removeOnRender(e){this._onRenderContainers.splice(this._onRenderContainers.indexOf(e),1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let s=0;s<t.length;s++)this._getChildren(t[s],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const s=e.children;for(let r=0;r<s.length;r++)this._getChildren(s[r],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new O),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new O),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new O),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function SS(i,e,t={}){for(const s in e)!t[s]&&e[s]!==void 0&&(i[s]=e[s])}const xu=new Be(null),Ur=new Be(null),_u=new Be(null,1,1),Or=new Be(null),Dr=1,yu=2,ps=4;class re extends je{constructor(e={}){super(),this.uid=he("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new O,this.relativeGroupTransform=new O,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new Be(this,0,0),this._scale=_u,this._pivot=Ur,this._origin=Or,this._skew=xu,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],SS(this,e,{children:!0,parent:!0,effects:!0}),e.children?.forEach(t=>this.addChild(t)),e.parent?.addChild(this)}static mixin(e){W("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),V.mixin(re,e)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||W(Q,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let r=0;r<e.length;r++)this.addChild(e[r]);return e[0]}const t=e[0],s=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),s&&(s.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,s&&s.addChild(t),this.emit("childAdded",t,this,this.children.length-1),t.emit("added",this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let r=0;r<e.length;r++)this.removeChild(e[r]);return e[0]}const t=e[0],s=this.children.indexOf(t);return s>-1&&(this._didViewChangeTick++,this.children.splice(s,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit("childRemoved",t,this,s),t.emit("removed",this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const e=this.parentRenderGroup;e?.removeChild(this),this.renderGroup=Se.get(gu,this),this.groupTransform=O.IDENTITY,e?.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e?.removeChild(this),Se.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e?.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new O),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*H1}set angle(e){this.rotation=e*W1}get pivot(){return this._pivot===Ur&&(this._pivot=new Be(this,0,0)),this._pivot}set pivot(e){this._pivot===Ur&&(this._pivot=new Be(this,0,0),this._origin!==Or&&L("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===xu&&(this._skew=new Be(this,0,0)),this._skew}set skew(e){this._skew===xu&&(this._skew=new Be(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===_u&&(this._scale=new Be(this,1,1)),this._scale}set scale(e){this._scale===_u&&(this._scale=new Be(this,0,0)),typeof e=="string"&&(e=parseFloat(e)),typeof e=="number"?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===Or&&(this._origin=new Be(this,0,0)),this._origin}set origin(e){this._origin===Or&&(this._origin=new Be(this,0,0),this._pivot!==Ur&&L("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){const t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){const t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||(e={});const t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){const s=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,s.width),t!==void 0&&this._setHeight(t,s.height)}_updateSkew(){const e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x=="number"?e.x:this.position.x,typeof e.y=="number"?e.y:this.position.y),this.scale.set(typeof e.scaleX=="number"?e.scaleX||1:this.scale.x,typeof e.scaleY=="number"?e.scaleY||1:this.scale.y),this.rotation=typeof e.rotation=="number"?e.rotation:this.rotation,this.skew.set(typeof e.skewX=="number"?e.skewX:this.skew.x,typeof e.skewY=="number"?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX=="number"?e.pivotX:this.pivot.x,typeof e.pivotY=="number"?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX=="number"?e.originX:this.origin.x,typeof e.originY=="number"?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){const e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;const t=this.localTransform,s=this._scale,r=this._pivot,n=this._origin,o=this._position,a=s._x,l=s._y,c=r._x,h=r._y,u=-n._x,d=-n._y;t.a=this._cx*a,t.b=this._sx*a,t.c=this._cy*l,t.d=this._sy*l,t.tx=o._x-(c*t.a+h*t.c)+(u*t.a+d*t.c)-u,t.ty=o._y-(c*t.b+h*t.d)+(u*t.b+d*t.d)-d}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=Dr,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const s=ue.shared.setValue(e??16777215).toBgrNumber();s!==this.localColor&&(this.localColor=s,this._updateFlags|=Dr,this._onUpdate())}get tint(){return Br(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=yu,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){const t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ps,this.localDisplayStatus^=2,this._onUpdate())}get culled(){return!(this.localDisplayStatus&4)}set culled(e){const t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ps,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){const t=e?1:0;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=ps,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof e=="boolean"?e:e?.children)&&t)for(let r=0;r<t.length;++r)t[r].destroy(e);this.renderGroup?.destroy(),this.renderGroup=null}}V.mixin(re,lS,pS,bS,_S,xS,uS,dS,yS,rS,aS,mS,cS);class vu extends re{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this._bounds=new De(0,1,0,0),this._boundsDirty=!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=e?1:0}containsPoint(e){const t=this.bounds,{x:s,y:r}=e;return s>=t.minX&&s<=t.maxX&&r>=t.minY&&r<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}destroy(e){super.destroy(e),this._bounds=null;for(const t in this._gpuData)this._gpuData[t].destroy?.();this._gpuData=null}collectRenderablesSimple(e,t,s){const{renderPipes:r}=t;r.blendMode.pushBlendMode(this,this.groupBlendMode,e),r[this.renderPipeId].addRenderable(this,e),this.didViewUpdate=!1;const o=this.children,a=o.length;for(let l=0;l<a;l++)o[l].collectRenderables(e,t,s);r.blendMode.popBlendMode(e)}}class Ue extends vu{constructor(e=M.EMPTY){e instanceof M&&(e={texture:e});const{texture:t=M.EMPTY,anchor:s,roundPixels:r,width:n,height:o,...a}=e;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new Be({_onUpdate:()=>{this.onViewUpdate()}}),s?this.anchor=s:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=r??!1,n!==void 0&&(this.width=n),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof M?new Ue(e):new Ue(M.from(e,t))}set texture(e){e||(e=M.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return Xp(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return W("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,s=this._bounds,{width:r,height:n}=t.orig;s.minX=-e._x*r,s.maxX=s.minX+r,s.minY=-e._y*n,s.maxY=s.minY+n}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._texture.destroy(s)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null,this._gpuData=null}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}const CS=new De;function dm(i,e,t){const s=CS;i.measurable=!0,fu(i,t,s),e.addBoundsMask(s),i.measurable=!1}function fm(i,e,t){const s=kt.get();i.measurable=!0;const r=Le.get().identity(),n=pm(i,t,r);mu(i,s,n),i.measurable=!1,e.addBoundsMask(s),Le.return(r),kt.return(s)}function pm(i,e,t){return i?(i!==e&&(pm(i.parent,e,t),i.updateLocalTransform(),t.append(i.localTransform)),t):(L("Mask bounds, renderable is not inside the root container"),t)}class mm{constructor(e){this.priority=0,this.inverse=!1,this.pipe="alphaMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof Ue),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||dm(this.mask,e,t)}addLocalBounds(e,t){fm(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof Ue}}mm.extension=b.MaskEffect;class gm{constructor(e){this.priority=0,this.pipe="colorMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}gm.extension=b.MaskEffect;class xm{constructor(e){this.priority=0,this.pipe="stencilMask",e?.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){dm(this.mask,e,t)}addLocalBounds(e,t){fm(this.mask,e,t)}containsPoint(e,t){const s=this.mask;return t(s,e)}destroy(){this.reset()}static test(e){return e instanceof re}}xm.extension=b.MaskEffect;let _m={createCanvas:(i,e)=>{const t=document.createElement("canvas");return t.width=i,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(i,e)=>fetch(i,e),parseXML:i=>new DOMParser().parseFromString(i,"text/xml")};const Y={get(){return _m},set(i){_m=i}};class Ft extends Ee{constructor(e){e.resource||(e.resource=Y.get().createCanvas()),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId="image",this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,s=this._resolution){const r=super.resize(e,t,s);return r&&this.resizeCanvas(),r}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}Ft.extension=b.TextureSource;class Ct extends Ee{constructor(e){super(e),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}}Ct.extension=b.TextureSource;var Ui=(i=>(i[i.INTERACTION=50]="INTERACTION",i[i.HIGH=25]="HIGH",i[i.NORMAL=0]="NORMAL",i[i.LOW=-25]="LOW",i[i.UTILITY=-50]="UTILITY",i))(Ui||{});class bu{constructor(e,t=null,s=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=s,this._once=r}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));const t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const t=this.next;return this.next=e?null:t,this.previous=null,t}}const ym=class it{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new bu(null,null,1/0),this.deltaMS=1/it.targetFPMS,this.elapsedMS=1/it.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,s=Ui.NORMAL){return this._addListener(new bu(e,t,s))}addOnce(e,t,s=Ui.NORMAL){return this._addListener(new bu(e,t,s,!0))}_addListener(e){let t=this._head.next,s=this._head;if(!t)e.connect(s);else{for(;t;){if(e.priority>t.priority){e.connect(s);break}s=t,t=t.next}e.previous||e.connect(s)}return this._startIfPossible(),this}remove(e,t){let s=this._head.next;for(;s;)s.match(e,t)?s=s.destroy():s=s.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let t;if(e>this.lastTime){if(t=this.elapsedMS=e-this.lastTime,t>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){const n=e-this._lastFrame|0;if(n<this._minElapsedMS)return;this._lastFrame=e-n%this._minElapsedMS}this.deltaMS=t,this.deltaTime=this.deltaMS*it.targetFPMS;const s=this._head;let r=s.next;for(;r;)r=r.emit(this);s.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const t=Math.min(this.maxFPS,e),s=Math.min(Math.max(0,t)/1e3,it.targetFPMS);this._maxElapsedMS=1/s}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){if(e===0)this._minElapsedMS=0;else{const t=Math.max(this.minFPS,e);this._minElapsedMS=1/(t/1e3)}}static get shared(){if(!it._shared){const e=it._shared=new it;e.autoStart=!0,e._protected=!0}return it._shared}static get system(){if(!it._system){const e=it._system=new it;e.autoStart=!0,e._protected=!0}return it._system}};ym.targetFPMS=.06;let Ze=ym,Tu;async function vm(){return Tu??(Tu=(async()=>{const e=Y.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(o=>{const a=document.createElement("video");a.onloadeddata=()=>o(a),a.onerror=()=>o(null),a.autoplay=!1,a.crossOrigin="anonymous",a.preload="auto",a.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",a.load()});if(!t)return"premultiply-alpha-on-upload";const s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);const n=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,n),e.deleteFramebuffer(r),e.deleteTexture(s),e.getExtension("WEBGL_lose_context")?.loseContext(),n[0]<=n[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),Tu}const Gr=class Z_ extends Ee{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...Z_.defaultOptions,...e},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=e.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=e.autoPlay!==!1,this.alphaMode=e.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=Ze.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener("play",this._onPlayStart),e.addEventListener("pause",this._onPlayStop),e.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener("canplay",this._onCanPlay),e.addEventListener("canplaythrough",this._onCanPlayThrough),e.addEventListener("error",this._onError,!0)),this.alphaMode=await vm(),this._load=new Promise((s,r)=>{this.isValid?s(this):(this._resolve=s,this._reject=r,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){const e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const e=this.resource;e&&(e.removeEventListener("play",this._onPlayStart),e.removeEventListener("pause",this._onPlayStop),e.removeEventListener("seeked",this._onSeeked),e.removeEventListener("canplay",this._onCanPlay),e.removeEventListener("canplaythrough",this._onCanPlayThrough),e.removeEventListener("error",this._onError,!0),e.pause(),e.src="",e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(Ze.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(Ze.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(Ze.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};Gr.extension=b.TextureSource,Gr.defaultOptions={...Ee.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},Gr.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let ms=Gr;const ut=(i,e,t=!1)=>(Array.isArray(i)||(i=[i]),e?i.map(s=>typeof s=="string"||t?e(s):s):i);class AS{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){const t=this._cache.get(e);return t||L(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const s=ut(e);let r;for(let l=0;l<this.parsers.length;l++){const c=this.parsers[l];if(c.test(t)){r=c.getCacheableAssets(s,t);break}}const n=new Map(Object.entries(r||{}));r||s.forEach(l=>{n.set(l,t)});const o=[...n.keys()],a={cacheKeys:o,keys:s};s.forEach(l=>{this._cacheMap.set(l,a)}),o.forEach(l=>{const c=r?r[l]:t;this._cache.has(l)&&this._cache.get(l)!==c&&L("[Cache] already has key:",l),this._cache.set(l,n.get(l))})}remove(e){if(!this._cacheMap.has(e)){L(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(r=>{this._cache.delete(r)}),t.keys.forEach(r=>{this._cacheMap.delete(r)})}get parsers(){return this._parsers}}const ae=new AS,wu=[];V.handleByList(b.TextureSource,wu);function bm(i={}){const e=i&&i.resource,t=e?i.resource:i,s=e?i:{resource:i};for(let r=0;r<wu.length;r++){const n=wu[r];if(n.test(t))return new n(s)}throw new Error(`Could not find a source type for resource: ${s.resource}`)}function ES(i={},e=!1){const t=i&&i.resource,s=t?i.resource:i,r=t?i:{resource:i};if(!e&&ae.has(s))return ae.get(s);const n=new M({source:bm(r)});return n.on("destroy",()=>{ae.has(s)&&ae.remove(s)}),e||ae.set(s,n),n}function IS(i,e=!1){return typeof i=="string"?ae.get(i):i instanceof Ee?new M({source:i}):ES(i,e)}M.from=IS,Ee.from=bm,V.add(mm,gm,xm,ms,Ct,Ft,nu);var Kt=(i=>(i[i.Low=0]="Low",i[i.Normal=1]="Normal",i[i.High=2]="High",i))(Kt||{});function dt(i){if(typeof i!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(i)}`)}function gs(i){return i.split("?")[0].split("#")[0]}function PS(i){return i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function RS(i,e,t){return i.replace(new RegExp(PS(e),"g"),t)}function MS(i,e){let t="",s=0,r=-1,n=0,o=-1;for(let a=0;a<=i.length;++a){if(a<i.length)o=i.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(r===a-1||n===1))if(r!==a-1&&n===2){if(t.length<2||s!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){const l=t.lastIndexOf("/");if(l!==t.length-1){l===-1?(t="",s=0):(t=t.slice(0,l),s=t.length-1-t.lastIndexOf("/")),r=a,n=0;continue}}else if(t.length===2||t.length===1){t="",s=0,r=a,n=0;continue}}}else t.length>0?t+=`/${i.slice(r+1,a)}`:t=i.slice(r+1,a),s=a-r-1;r=a,n=0}else o===46&&n!==-1?++n:n=-1}return t}const Je={toPosix(i){return RS(i,"\\","/")},isUrl(i){return/^https?:/.test(this.toPosix(i))},isDataUrl(i){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(i)},isBlobUrl(i){return i.startsWith("blob:")},hasProtocol(i){return/^[^/:]+:/.test(this.toPosix(i))},getProtocol(i){dt(i),i=this.toPosix(i);const e=/^file:\/\/\//.exec(i);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(i);return t?t[0]:""},toAbsolute(i,e,t){if(dt(i),this.isDataUrl(i)||this.isBlobUrl(i))return i;const s=gs(this.toPosix(e??Y.get().getBaseUrl())),r=gs(this.toPosix(t??this.rootname(s)));return i=this.toPosix(i),i.startsWith("/")?Je.join(r,i.slice(1)):this.isAbsolute(i)?i:this.join(s,i)},normalize(i){if(dt(i),i.length===0)return".";if(this.isDataUrl(i)||this.isBlobUrl(i))return i;i=this.toPosix(i);let e="";const t=i.startsWith("/");this.hasProtocol(i)&&(e=this.rootname(i),i=i.slice(e.length));const s=i.endsWith("/");return i=MS(i),i.length>0&&s&&(i+="/"),t?`/${i}`:e+i},isAbsolute(i){return dt(i),i=this.toPosix(i),this.hasProtocol(i)?!0:i.startsWith("/")},join(...i){if(i.length===0)return".";let e;for(let t=0;t<i.length;++t){const s=i[t];if(dt(s),s.length>0)if(e===void 0)e=s;else{const r=i[t-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${s}`:e+=`/${s}`}}return e===void 0?".":this.normalize(e)},dirname(i){if(dt(i),i.length===0)return".";i=this.toPosix(i);let e=i.charCodeAt(0);const t=e===47;let s=-1,r=!0;const n=this.getProtocol(i),o=i;i=i.slice(n.length);for(let a=i.length-1;a>=1;--a)if(e=i.charCodeAt(a),e===47){if(!r){s=a;break}}else r=!1;return s===-1?t?"/":this.isUrl(o)?n+i:n:t&&s===1?"//":n+i.slice(0,s)},rootname(i){dt(i),i=this.toPosix(i);let e="";if(i.startsWith("/")?e="/":e=this.getProtocol(i),this.isUrl(i)){const t=i.indexOf("/",e.length);t!==-1?e=i.slice(0,t):e=i,e.endsWith("/")||(e+="/")}return e},basename(i,e){dt(i),e&&dt(e),i=gs(this.toPosix(i));let t=0,s=-1,r=!0,n;if(e!==void 0&&e.length>0&&e.length<=i.length){if(e.length===i.length&&e===i)return"";let o=e.length-1,a=-1;for(n=i.length-1;n>=0;--n){const l=i.charCodeAt(n);if(l===47){if(!r){t=n+1;break}}else a===-1&&(r=!1,a=n+1),o>=0&&(l===e.charCodeAt(o)?--o===-1&&(s=n):(o=-1,s=a))}return t===s?s=a:s===-1&&(s=i.length),i.slice(t,s)}for(n=i.length-1;n>=0;--n)if(i.charCodeAt(n)===47){if(!r){t=n+1;break}}else s===-1&&(r=!1,s=n+1);return s===-1?"":i.slice(t,s)},extname(i){dt(i),i=gs(this.toPosix(i));let e=-1,t=0,s=-1,r=!0,n=0;for(let o=i.length-1;o>=0;--o){const a=i.charCodeAt(o);if(a===47){if(!r){t=o+1;break}continue}s===-1&&(r=!1,s=o+1),a===46?e===-1?e=o:n!==1&&(n=1):e!==-1&&(n=-1)}return e===-1||s===-1||n===0||n===1&&e===s-1&&e===t+1?"":i.slice(e,s)},parse(i){dt(i);const e={root:"",dir:"",base:"",ext:"",name:""};if(i.length===0)return e;i=gs(this.toPosix(i));let t=i.charCodeAt(0);const s=this.isAbsolute(i);let r;e.root=this.rootname(i),s||this.hasProtocol(i)?r=1:r=0;let n=-1,o=0,a=-1,l=!0,c=i.length-1,h=0;for(;c>=r;--c){if(t=i.charCodeAt(c),t===47){if(!l){o=c+1;break}continue}a===-1&&(l=!1,a=c+1),t===46?n===-1?n=c:h!==1&&(h=1):n!==-1&&(h=-1)}return n===-1||a===-1||h===0||h===1&&n===a-1&&n===o+1?a!==-1&&(o===0&&s?e.base=e.name=i.slice(1,a):e.base=e.name=i.slice(o,a)):(o===0&&s?(e.name=i.slice(1,n),e.base=i.slice(1,a)):(e.name=i.slice(o,n),e.base=i.slice(o,a)),e.ext=i.slice(n,a)),e.dir=this.dirname(i),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function Tm(i,e,t,s,r){const n=e[t];for(let o=0;o<n.length;o++){const a=n[o];t<e.length-1?Tm(i.replace(s[t],a),e,t+1,s,r):r.push(i.replace(s[t],a))}}function kS(i){const e=/\{(.*?)\}/g,t=i.match(e),s=[];if(t){const r=[];t.forEach(n=>{const o=n.substring(1,n.length-1).split(",");r.push(o)}),Tm(i,r,0,t,s)}else s.push(i);return s}const zr=i=>!Array.isArray(i);class Oi{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...e){e.forEach(t=>{this._preferredOrder.push(t),t.priority||(t.priority=Object.keys(t.params))}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e=="string")this._defaultSearchParams=e;else{const t=e;this._defaultSearchParams=Object.keys(t).map(s=>`${encodeURIComponent(s)}=${encodeURIComponent(t[s])}`).join("&")}}getAlias(e){const{alias:t,src:s}=e;return ut(t||s,n=>typeof n=="string"?n:Array.isArray(n)?n.map(o=>o?.src??o):n?.src?n.src:n,!0)}addManifest(e){this._manifest&&L("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=e,e.bundles.forEach(t=>{this.addBundle(t.name,t.assets)})}addBundle(e,t){const s=[];let r=t;Array.isArray(t)||(r=Object.entries(t).map(([n,o])=>typeof o=="string"||Array.isArray(o)?{alias:n,src:o}:{alias:n,...o})),r.forEach(n=>{const o=n.src,a=n.alias;let l;if(typeof a=="string"){const c=this._createBundleAssetId(e,a);s.push(c),l=[a,c]}else{const c=a.map(h=>this._createBundleAssetId(e,h));s.push(...c),l=[...a,...c]}this.add({...n,alias:l,src:o})}),this._bundles[e]=s}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let s;s=n=>{this.hasKey(n)&&L(`[Resolver] already has key: ${n} overwriting`)},ut(t).forEach(n=>{const{src:o}=n;let{data:a,format:l,loadParser:c,parser:h}=n;const u=ut(o).map(g=>typeof g=="string"?kS(g):Array.isArray(g)?g:[g]),d=this.getAlias(n);Array.isArray(d)?d.forEach(s):s(d);const f=[],p=g=>({...this._parsers.find(x=>x.test(g))?.parse(g),src:g});u.forEach(g=>{g.forEach(m=>{let x={};if(typeof m!="object"?x=p(m):(a=m.data??a,l=m.format??l,(m.loadParser||m.parser)&&(c=m.loadParser??c,h=m.parser??h),x={...p(m.src),...m}),!d)throw new Error(`[Resolver] alias is undefined for this asset: ${x.src}`);x=this._buildResolvedAsset(x,{aliases:d,data:a,format:l,loadParser:c,parser:h,progressSize:n.progressSize}),f.push(x)})}),d.forEach(g=>{this._assetMap[g]=f})})}resolveBundle(e){const t=zr(e);e=ut(e);const s={};return e.forEach(r=>{const n=this._bundles[r];if(n){const o=this.resolve(n),a={};for(const l in o){const c=o[l];a[this._extractAssetIdFromBundle(r,l)]=c}s[r]=a}}),t?s[e[0]]:s}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const s={};for(const r in t)s[r]=t[r].src;return s}return t.src}resolve(e){const t=zr(e);e=ut(e);const s={};return e.forEach(r=>{if(!this._resolverHash[r])if(this._assetMap[r]){let n=this._assetMap[r];const o=this._getPreferredOrder(n);o?.priority.forEach(a=>{o.params[a].forEach(l=>{const c=n.filter(h=>h[a]?h[a]===l:!1);c.length&&(n=c)})}),this._resolverHash[r]=n[0]}else this._resolverHash[r]=this._buildResolvedAsset({alias:[r],src:r},{});s[r]=this._resolverHash[r]}),t?s[e[0]]:s}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const s=e[t],r=this._preferredOrder.find(n=>n.params.format.includes(s.format));if(r)return r}return this._preferredOrder[0]}_appendDefaultSearchParams(e){if(!this._defaultSearchParams)return e;const t=/\?/.test(e)?"&":"?";return`${e}${t}${this._defaultSearchParams}`}_buildResolvedAsset(e,t){const{aliases:s,data:r,loadParser:n,parser:o,format:a,progressSize:l}=t;return(this._basePath||this._rootPath)&&(e.src=Je.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=s??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...r||{},...e.data},e.loadParser=n??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??FS(e.src),l!==void 0&&(e.progressSize=l),e}}Oi.RETINA_PREFIX=/@([0-9\.]+)x/;function FS(i){return i.split(".").pop().split("?").shift().split("#").shift()}const Su=(i,e)=>{const t=e.split("?")[1];return t&&(i+=`?${t}`),i},wm=class Ks{constructor(e,t){this.linkedSheets=[];let s=e;e?.source instanceof Ee&&(s={texture:e,data:t});const{texture:r,data:n,cachePrefix:o=""}=s;this.cachePrefix=o,this._texture=r instanceof M?r:null,this.textureSource=r.source,this.textures={},this.animations={},this.data=n;const a=parseFloat(n.meta.scale);a?(this.resolution=a,r.source.resolution=this.resolution):this.resolution=r.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(e=>{this._callback=e,this._batchIndex=0,this._frameKeys.length<=Ks.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}_processFrames(e){let t=e;const s=Ks.BATCH_SIZE;for(;t-e<s&&t<this._frameKeys.length;){const r=this._frameKeys[t],n=this._frames[r],o=n.frame;if(o){let a=null,l=null;const c=n.trimmed!==!1&&n.sourceSize?n.sourceSize:n.frame,h=new H(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);n.rotated?a=new H(Math.floor(o.x)/this.resolution,Math.floor(o.y)/this.resolution,Math.floor(o.h)/this.resolution,Math.floor(o.w)/this.resolution):a=new H(Math.floor(o.x)/this.resolution,Math.floor(o.y)/this.resolution,Math.floor(o.w)/this.resolution,Math.floor(o.h)/this.resolution),n.trimmed!==!1&&n.spriteSourceSize&&(l=new H(Math.floor(n.spriteSourceSize.x)/this.resolution,Math.floor(n.spriteSourceSize.y)/this.resolution,Math.floor(o.w)/this.resolution,Math.floor(o.h)/this.resolution)),this.textures[r]=new M({source:this.textureSource,frame:a,orig:h,trim:l,rotate:n.rotated?2:0,defaultAnchor:n.anchor,defaultBorders:n.borders,label:r.toString()})}t++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let s=0;s<e[t].length;s++){const r=e[t][s];this.animations[t].push(this.textures[r])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*Ks.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*Ks.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){for(const t in this.textures)this.textures[t].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&(this._texture?.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};wm.BATCH_SIZE=1e3;let Sm=wm;const BS=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Cm(i,e,t){const s={};if(i.forEach(r=>{s[r]=e}),Object.keys(e.textures).forEach(r=>{s[`${e.cachePrefix}${r}`]=e.textures[r]}),!t){const r=Je.dirname(i[0]);e.linkedSheets.forEach((n,o)=>{const a=Cm([`${r}/${e.data.meta.related_multi_packs[o]}`],n,!0);Object.assign(s,a)})}return s}const US={extension:b.Asset,cache:{test:i=>i instanceof Sm,getCacheableAssets:(i,e)=>Cm(i,e,!1)},resolver:{extension:{type:b.ResolveParser,name:"resolveSpritesheet"},test:i=>{const t=i.split("?")[0].split("."),s=t.pop(),r=t.pop();return s==="json"&&BS.includes(r)},parse:i=>{const e=i.split(".");return{resolution:parseFloat(Oi.RETINA_PREFIX.exec(i)?.[1]??"1"),format:e[e.length-2],src:i}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:b.LoadParser,priority:Kt.Normal,name:"spritesheetLoader"},async testParse(i,e){return Je.extname(e.src).toLowerCase()===".json"&&!!i.frames},async parse(i,e,t){const{texture:s,imageFilename:r,textureOptions:n,cachePrefix:o}=e?.data??{};let a=Je.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let l;if(s instanceof M)l=s;else{const u=Su(a+(r??i.meta.image),e.src);l=(await t.load([{src:u,data:n}]))[u]}const c=new Sm({texture:l.source,data:i,cachePrefix:o});await c.parse();const h=i?.meta?.related_multi_packs;if(Array.isArray(h)){const u=[];for(const f of h){if(typeof f!="string")continue;let p=a+f;e.data?.ignoreMultiPack||(p=Su(p,e.src),u.push(t.load({src:p,data:{textureOptions:n,ignoreMultiPack:!0}})))}const d=await Promise.all(u);c.linkedSheets=d,d.forEach(f=>{f.linkedSheets=[c].concat(c.linkedSheets.filter(p=>p!==f))})}return c},async unload(i,e,t){await t.unload(i.textureSource._sourceOrigin),i.destroy(!1)}}};V.add(US);class Am{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),s=this._canvas.width,r=this._canvas.height,n=t.width/s*this._renderer.resolution,o=t.height/r*this._renderer.resolution,a=t.left,l=t.top,c=`translate(${a}px, ${l}px) scale(${n}, ${o})`;c!==this._lastTransform&&(this._domElement.style.transform=c,this._lastTransform=c)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(e=>{for(const t of e){if(t.target!==this._canvas)continue;const s=this.canvas.width,r=this.canvas.height,n=t.contentRect.width/s*this._renderer.resolution,o=t.contentRect.height/r*this._renderer.resolution;(this._lastScaleX!==n||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=n,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||Ze.shared.add(this.updateTranslation,this,Ui.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&Ze.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class xs{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=xs.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new X,this.page=new X,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,s){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,s,r,n){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var Cu=/iPhone/i,Em=/iPod/i,Im=/iPad/i,Pm=/\biOS-universal(?:.+)Mac\b/i,Au=/\bAndroid(?:.+)Mobile\b/i,Rm=/Android/i,Di=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,Nr=/Silk/i,Bt=/Windows Phone/i,Mm=/\bWindows(?:.+)ARM\b/i,km=/BlackBerry/i,Fm=/BB10/i,Bm=/Opera Mini/i,Um=/\b(CriOS|Chrome)(?:.+)Mobile/i,Om=/Mobile(?:.+)Firefox\b/i,Dm=function(i){return typeof i<"u"&&i.platform==="MacIntel"&&typeof i.maxTouchPoints=="number"&&i.maxTouchPoints>1&&typeof MSStream>"u"};function OS(i){return function(e){return e.test(i)}}function Gm(i){var e={userAgent:"",platform:"",maxTouchPoints:0};!i&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof i=="string"?e.userAgent=i:i&&i.userAgent&&(e={userAgent:i.userAgent,platform:i.platform,maxTouchPoints:i.maxTouchPoints||0});var t=e.userAgent,s=t.split("[FBAN");typeof s[1]<"u"&&(t=s[0]),s=t.split("Twitter"),typeof s[1]<"u"&&(t=s[0]);var r=OS(t),n={apple:{phone:r(Cu)&&!r(Bt),ipod:r(Em),tablet:!r(Cu)&&(r(Im)||Dm(e))&&!r(Bt),universal:r(Pm),device:(r(Cu)||r(Em)||r(Im)||r(Pm)||Dm(e))&&!r(Bt)},amazon:{phone:r(Di),tablet:!r(Di)&&r(Nr),device:r(Di)||r(Nr)},android:{phone:!r(Bt)&&r(Di)||!r(Bt)&&r(Au),tablet:!r(Bt)&&!r(Di)&&!r(Au)&&(r(Nr)||r(Rm)),device:!r(Bt)&&(r(Di)||r(Nr)||r(Au)||r(Rm))||r(/\bokhttp\b/i)},windows:{phone:r(Bt),tablet:r(Mm),device:r(Bt)||r(Mm)},other:{blackberry:r(km),blackberry10:r(Fm),opera:r(Bm),firefox:r(Om),chrome:r(Um),device:r(km)||r(Fm)||r(Bm)||r(Om)||r(Um)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const DS=(Gm.default??Gm)(globalThis.navigator),GS=9,zm=100,zS=0,NS=0,Nm=2,Lm=1,LS=-1e3,HS=-1e3,WS=2,Eu=class J_{constructor(e,t=DS){this._mobileInfo=t,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(t.tablet||t.phone)&&this._createTouchHook(),this._renderer=e}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const e=document.createElement("button");e.style.width=`${Lm}px`,e.style.height=`${Lm}px`,e.style.position="absolute",e.style.top=`${LS}px`,e.style.left=`${HS}px`,e.style.zIndex=WS.toString(),e.style.backgroundColor="#FF0000",e.title="select to enable accessibility for this content",e.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(e),this._hookDiv=e}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${zS}px`,this._div.style.left=`${NS}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=Nm.toString(),this._canvasObserver=new Am({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const e=this._renderer.view.canvas;if(e.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const t=new MutationObserver(()=>{e.parentNode&&(t.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});t.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const e of this._children)e._accessibleDiv?.parentNode&&(e._accessibleDiv.parentNode.removeChild(e._accessibleDiv),e._accessibleDiv=null),e._accessibleActive=!1;for(const e in this._pools)this._pools[e].forEach(s=>{s.parentNode&&s.parentNode.removeChild(s)}),delete this._pools[e];this._div?.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(e){if(!e.visible||!e.accessibleChildren)return;e.accessible&&(e._accessibleActive||this._addChild(e),e._renderId=this._renderId);const t=e.children;if(t)for(let s=0;s<t.length;s++)this._updateAccessibleObjects(t[s])}init(e){const s={accessibilityOptions:{...J_.defaultOptions,...e?.accessibilityOptions||{}}};this.debug=s.accessibilityOptions.debug,this._activateOnTab=s.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=s.accessibilityOptions.deactivateOnMouseMove,s.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const e=performance.now();if(this._mobileInfo.android.device&&e<this._androidUpdateCount||(this._androidUpdateCount=e+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const t=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const s of this._children)s._renderId===this._renderId&&t.add(this._children.indexOf(s))}for(let s=this._children.length-1;s>=0;s--){const r=this._children[s];t.has(s)||(r._accessibleDiv&&r._accessibleDiv.parentNode&&(r._accessibleDiv.parentNode.removeChild(r._accessibleDiv),this._getPool(r.accessibleType).push(r._accessibleDiv),r._accessibleDiv=null),r._accessibleActive=!1,nm(this._children,s,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let s=0;s<this._children.length;s++){const r=this._children[s];if(!r._accessibleActive||!r._accessibleDiv)continue;const n=r._accessibleDiv,o=r.hitArea||r.getBounds().rectangle;if(r.hitArea){const a=r.worldTransform;n.style.left=`${a.tx+o.x*a.a}px`,n.style.top=`${a.ty+o.y*a.d}px`,n.style.width=`${o.width*a.a}px`,n.style.height=`${o.height*a.d}px`}else this._capHitArea(o),n.style.left=`${o.x}px`,n.style.top=`${o.y}px`,n.style.width=`${o.width}px`,n.style.height=`${o.height}px`}this._renderId++}_updateDebugHTML(e){e.innerHTML=`type: ${e.type}</br> title : ${e.title}</br> tabIndex: ${e.tabIndex}`}_capHitArea(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);const{width:t,height:s}=this._renderer;e.x+e.width>t&&(e.width=t-e.x),e.y+e.height>s&&(e.height=s-e.y)}_addChild(e){let s=this._getPool(e.accessibleType).pop();s?(s.innerHTML="",s.removeAttribute("title"),s.removeAttribute("aria-label"),s.tabIndex=0):(e.accessibleType==="button"?s=document.createElement("button"):(s=document.createElement(e.accessibleType),s.style.cssText=`
|
|
70
70
|
color: transparent;
|
|
71
71
|
pointer-events: none;
|
|
72
72
|
padding: 0;
|
|
@@ -79,7 +79,7 @@ Deprecated since v${i}`,n=typeof console.groupCollapsed=="function"&&!Mi.noColor
|
|
|
79
79
|
-webkit-user-select: none;
|
|
80
80
|
-moz-user-select: none;
|
|
81
81
|
-ms-user-select: none;
|
|
82
|
-
`,e.accessibleText&&(s.innerText=e.accessibleText)),s.style.width=`${zm}px`,s.style.height=`${zm}px`,s.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",s.style.position="absolute",s.style.zIndex=Nm.toString(),s.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?s.setAttribute("aria-live","off"):s.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?s.setAttribute("aria-relevant","additions"):s.setAttribute("aria-relevant","text"),s.addEventListener("click",this._onClick.bind(this)),s.addEventListener("focus",this._onFocus.bind(this)),s.addEventListener("focusout",this._onFocusOut.bind(this))),s.style.pointerEvents=e.accessiblePointerEvents,s.type=e.accessibleType,e.accessibleTitle&&e.accessibleTitle!==null?s.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(s.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&s.setAttribute("aria-label",e.accessibleHint),e.interactive?s.tabIndex=e.tabIndex:s.tabIndex=0,this.debug&&this._updateDebugHTML(s),e._accessibleActive=!0,e._accessibleDiv=s,s.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){const{container:s}=e.target,r=this._renderer.events.rootBoundary,n=Object.assign(new
|
|
82
|
+
`,e.accessibleText&&(s.innerText=e.accessibleText)),s.style.width=`${zm}px`,s.style.height=`${zm}px`,s.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",s.style.position="absolute",s.style.zIndex=Nm.toString(),s.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?s.setAttribute("aria-live","off"):s.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?s.setAttribute("aria-relevant","additions"):s.setAttribute("aria-relevant","text"),s.addEventListener("click",this._onClick.bind(this)),s.addEventListener("focus",this._onFocus.bind(this)),s.addEventListener("focusout",this._onFocusOut.bind(this))),s.style.pointerEvents=e.accessiblePointerEvents,s.type=e.accessibleType,e.accessibleTitle&&e.accessibleTitle!==null?s.title=e.accessibleTitle:(!e.accessibleHint||e.accessibleHint===null)&&(s.title=`container ${e.tabIndex}`),e.accessibleHint&&e.accessibleHint!==null&&s.setAttribute("aria-label",e.accessibleHint),e.interactive?s.tabIndex=e.tabIndex:s.tabIndex=0,this.debug&&this._updateDebugHTML(s),e._accessibleActive=!0,e._accessibleDiv=s,s.container=e,this._children.push(e),this._div.appendChild(e._accessibleDiv)}_dispatchEvent(e,t){const{container:s}=e.target,r=this._renderer.events.rootBoundary,n=Object.assign(new xs(r),{target:s});r.rootTarget=this._renderer.lastObjectRendered,t.forEach(o=>r.dispatchEvent(n,o))}_onClick(e){this._dispatchEvent(e,["click","pointertap","tap"])}_onFocus(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","assertive"),this._dispatchEvent(e,["mouseover"])}_onFocusOut(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","polite"),this._dispatchEvent(e,["mouseout"])}_onKeyDown(e){e.keyCode!==GS||!this._activateOnTab||this._activate()}_onMouseMove(e){e.movementX===0&&e.movementY===0||this._deactivate()}destroy(){this._deactivate(),this._destroyTouchHook(),this._canvasObserver?.destroy(),this._canvasObserver=null,this._div=null,this._pools=null,this._children=null,this._renderer=null,this._hookDiv=null,globalThis.removeEventListener("keydown",this._boundOnKeyDown),this._boundOnKeyDown=null,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._boundOnMouseMove=null}setAccessibilityEnabled(e){e?this._activate():this._deactivate()}_getPool(e){return this._pools[e]||(this._pools[e]=[]),this._pools[e]}};Eu.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"accessibility"},Eu.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0};let VS=Eu;const $S={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1},Iu=Object.create(null),Hm=Object.create(null);function _s(i,e){let t=Hm[i];return t===void 0&&(Iu[e]===void 0&&(Iu[e]=1),Hm[i]=t=Iu[e]++),t}let Lr;function Wm(){return(!Lr||Lr?.isContextLost())&&(Lr=Y.get().createCanvas().getContext("webgl",{})),Lr}let Hr;function XS(){if(!Hr){Hr="mediump";const i=Wm();i&&i.getShaderPrecisionFormat&&(Hr=i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision?"highp":"mediump")}return Hr}function YS(i,e,t){return e?i:t?(i=i.replace("out vec4 finalColor;",""),`
|
|
83
83
|
|
|
84
84
|
#ifdef GL_ES // This checks if it is WebGL1
|
|
85
85
|
#define in varying
|
|
@@ -97,12 +97,12 @@ Deprecated since v${i}`,n=typeof console.groupCollapsed=="function"&&!Mi.noColor
|
|
|
97
97
|
`}function qS(i,e,t){const s=t?e.maxSupportedFragmentPrecision:e.maxSupportedVertexPrecision;if(i.substring(0,9)!=="precision"){let r=t?e.requestedFragmentPrecision:e.requestedVertexPrecision;return r==="highp"&&s!=="highp"&&(r="mediump"),`precision ${r} float;
|
|
98
98
|
${i}`}else if(s!=="highp"&&i.substring(0,15)==="precision highp")return i.replace("precision highp","precision mediump");return i}function KS(i,e){return e?`#version 300 es
|
|
99
99
|
${i}`:i}const jS={},ZS={};function JS(i,{name:e="pixi-program"},t=!0){e=e.replace(/\s+/g,"-"),e+=t?"-fragment":"-vertex";const s=t?jS:ZS;return s[e]?(s[e]++,e+=`-${s[e]}`):s[e]=1,i.indexOf("#define SHADER_NAME")!==-1?i:`${`#define SHADER_NAME ${e}`}
|
|
100
|
-
${i}`}function QS(i,e){return e?i.replace("#version 300 es",""):i}const Pu={stripVersion:QS,ensurePrecision:qS,addProgramDefines:YS,setProgramName:JS,insertVersion:KS},ys=Object.create(null),Vm=class of{constructor(e){e={...of.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,s={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:XS()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let r=e.fragment,n=e.vertex;Object.keys(Pu).forEach(o=>{const a=s[o];r=Pu[o](r,a,!0),n=Pu[o](n,a,!1)}),this.fragment=r,this.vertex=n,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=xs(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,ys[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return ys[t]||(ys[t]=new of(e),ys[t]._cacheKey=t),ys[t]}};Vm.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let At=Vm;const $m={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function jt(i){return $m[i]??$m.float32}const eC={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"};function tC({source:i,entryPoint:e}){const t={},s=i.indexOf(`fn ${e}`);if(s!==-1){const r=i.indexOf("->",s);if(r!==-1){const n=i.substring(s,r),o=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|$)/g;let a;for(;(a=o.exec(n))!==null;){const l=eC[a[3]]??"float32";t[a[2]]={location:parseInt(a[1],10),format:l,stride:jt(l).stride,offset:0,instance:!1,start:0}}}}return t}function Ru(i){const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,s=/@binding\((\d+)\)/,r=/var(<[^>]+>)? (\w+)/,n=/:\s*(\w+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,c=i.match(e)?.map(u=>({group:parseInt(u.match(t)[1],10),binding:parseInt(u.match(s)[1],10),name:u.match(r)[2],isUniform:u.match(r)[1]==="<uniform>",type:u.match(n)[1]}));if(!c)return{groups:[],structs:[]};const h=i.match(o)?.map(u=>{const d=u.match(l)[1],f=u.match(a).reduce((p,g)=>{const[m,_]=g.split(":");return p[m.trim()]=_.trim(),p},{});return f?{name:d,members:f}:null}).filter(({name:u})=>c.some(d=>d.type===u))??[];return{groups:c,structs:h}}var vs=(i=>(i[i.VERTEX=1]="VERTEX",i[i.FRAGMENT=2]="FRAGMENT",i[i.COMPUTE=4]="COMPUTE",i))(vs||{});function iC({groups:i}){const e=[];for(let t=0;t<i.length;t++){const s=i[t];e[s.group]||(e[s.group]=[]),s.isUniform?e[s.group].push({binding:s.binding,visibility:vs.VERTEX|vs.FRAGMENT,buffer:{type:"uniform"}}):s.type==="sampler"?e[s.group].push({binding:s.binding,visibility:vs.FRAGMENT,sampler:{type:"filtering"}}):s.type==="texture_2d"&&e[s.group].push({binding:s.binding,visibility:vs.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}})}return e}function sC({groups:i}){const e=[];for(let t=0;t<i.length;t++){const s=i[t];e[s.group]||(e[s.group]={}),e[s.group][s.name]=s.binding}return e}function rC(i,e){const t=new Set,s=new Set,r=[...i.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),n=[...i.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return s.has(a)?!1:(s.add(a),!0)});return{structs:r,groups:n}}const bs=Object.create(null);class Ut{constructor(e){this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:s,layout:r,gpuLayout:n,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=s,t.source===s.source){const a=Ru(t.source);this.structsAndGroups=a}else{const a=Ru(s.source),l=Ru(t.source);this.structsAndGroups=rC(a,l)}this.layout=r??sC(this.structsAndGroups),this.gpuLayout=n??iC(this.structsAndGroups),this.autoAssignGlobalUniforms=this.layout[0]?.globalUniforms!==void 0,this.autoAssignLocalUniforms=this.layout[1]?.localUniforms!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,s=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=xs(s,"program")}get attributeData(){return this._attributeData??(this._attributeData=tC(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,bs[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return bs[t]||(bs[t]=new Ut(e),bs[t]._cacheKey=t),bs[t]}}const Xm=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],nC=Xm.reduce((i,e)=>(i[e]=!0,i),{});function oC(i,e){switch(i){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Ym=class Qx{constructor(e,t){this._touched=0,this.uid=he("uniform"),this._resourceType="uniformGroup",this._resourceId=he("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...Qx.defaultOptions,...t},this.uniformStructures=e;const s={};for(const r in e){const n=e[r];if(n.name=r,n.size=n.size??1,!nC[n.type]){const o=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${n.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${Xm.join(", ")}`)}n.value??(n.value=oC(n.type,n.size)),s[r]=n.value}this.uniforms=s,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=xs(Object.keys(s).map(r=>`${r}-${e[r].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};Ym.defaultOptions={ubo:!1,isStatic:!1};let He=Ym;class Ot{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const s in e){const r=e[s];this.setResource(r,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const s in this.resources)e[t++]=this.resources[s]._resourceId;this._key=e.join("|")}setResource(e,t){const s=this.resources[t];e!==s&&(s&&e.off?.("change",this.onResourceChange,this),e.on?.("change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e){const t=this.resources;for(const s in t)t[s]._touched=e}destroy(){const e=this.resources;for(const t in e)e[t]?.off?.("change",this.onResourceChange,this);this.resources=null}onResourceChange(e){if(this._dirty=!0,e.destroyed){const t=this.resources;for(const s in t)t[s]===e&&(t[s]=null)}else this._updateKey()}}var Qe=(i=>(i[i.WEBGL=1]="WEBGL",i[i.WEBGPU=2]="WEBGPU",i[i.BOTH=3]="BOTH",i))(Qe||{});class ot extends je{constructor(e){super(),this.uid=he("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:s,groups:r,resources:n,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=s,o===void 0&&(o=0,t&&(o|=Qe.WEBGPU),s&&(o|=Qe.WEBGL)),this.compatibleRenderers=o;const l={};if(!n&&!r&&(n={}),n&&r)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&r&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&r&&a)for(const c in a)for(const h in a[c]){const u=a[c][h];l[u]={group:c,binding:h,name:u}}else if(t&&r&&!a){const c=t.structsAndGroups.groups;a={},c.forEach(h=>{a[h.group]=a[h.group]||{},a[h.group][h.binding]=h.name,l[h.name]=h})}else if(n){r={},a={},t&&t.structsAndGroups.groups.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,l[u.name]=u});let c=0;for(const h in n)l[h]||(r[99]||(r[99]=new Ot,this._ownedBindGroups.push(r[99])),l[h]={group:99,binding:c,name:h},a[99]=a[99]||{},a[99][c]=h,c++);for(const h in n){const u=h;let d=n[h];!d.source&&!d._resourceType&&(d=new He(d));const f=l[u];f&&(r[f.group]||(r[f.group]=new Ot,this._ownedBindGroups.push(r[f.group])),r[f.group].setResource(d,f.binding))}}this.groups=r,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(r,l)}addResource(e,t,s){var r,n;(r=this._uniformBindMap)[t]||(r[t]={}),(n=this._uniformBindMap[t])[s]||(n[s]=e),this.groups[t]||(this.groups[t]=new Ot,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const s={};for(const r in t){const n=t[r];Object.defineProperty(s,n.name,{get(){return e[n.group].getResource(n.binding)},set(o){e[n.group].setResource(o,n.binding)}})}return s}destroy(e=!1){this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&(this.gpuProgram?.destroy(),this.glProgram?.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(t=>{t.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:s,...r}=e;let n,o;return t&&(n=Ut.from(t)),s&&(o=At.from(s)),new ot({gpuProgram:n,glProgram:o,...r})}}const aC={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},Mu=0,ku=1,Fu=2,Bu=3,Uu=4,Ou=5,Du=class ey{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<Mu)}set blend(e){!!(this.data&1<<Mu)!==e&&(this.data^=1<<Mu)}get offsets(){return!!(this.data&1<<ku)}set offsets(e){!!(this.data&1<<ku)!==e&&(this.data^=1<<ku)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<Fu)}set culling(e){!!(this.data&1<<Fu)!==e&&(this.data^=1<<Fu)}get depthTest(){return!!(this.data&1<<Bu)}set depthTest(e){!!(this.data&1<<Bu)!==e&&(this.data^=1<<Bu)}get depthMask(){return!!(this.data&1<<Ou)}set depthMask(e){!!(this.data&1<<Ou)!==e&&(this.data^=1<<Ou)}get clockwiseFrontFace(){return!!(this.data&1<<Uu)}set clockwiseFrontFace(e){!!(this.data&1<<Uu)!==e&&(this.data^=1<<Uu)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=aC[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new ey;return e.depthTest=!1,e.blend=!0,e}};Du.default2d=Du.for2d();let ft=Du;const qm=class af extends ot{constructor(e){e={...af.defaultOptions,...e},super(e),this.enabled=!0,this._state=ft.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,s,r){e.applyFilter(this,t,s,r)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:s,...r}=e;let n,o;return t&&(n=Ut.from(t)),s&&(o=At.from(s)),new af({gpuProgram:n,glProgram:o,...r})}};qm.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Gi=qm;const Gu=[];V.handleByNamedList(b.Environment,Gu);async function lC(i){if(!i)for(let e=0;e<Gu.length;e++){const t=Gu[e];if(t.value.test()){await t.value.load();return}}}let Ts;function Km(){if(typeof Ts=="boolean")return Ts;try{Ts=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Ts=!1}return Ts}function jm(i,e,t=2){const s=e&&e.length,r=s?e[0]*t:i.length;let n=Zm(i,0,r,t,!0);const o=[];if(!n||n.next===n.prev)return o;let a,l,c;if(s&&(n=fC(i,e,n,t)),i.length>80*t){a=i[0],l=i[1];let h=a,u=l;for(let d=t;d<r;d+=t){const f=i[d],p=i[d+1];f<a&&(a=f),p<l&&(l=p),f>h&&(h=f),p>u&&(u=p)}c=Math.max(h-a,u-l),c=c!==0?32767/c:0}return ws(n,o,t,a,l,c,0),o}function Zm(i,e,t,s,r){let n;if(r===SC(i,e,t,s)>0)for(let o=e;o<t;o+=s)n=tg(o/s|0,i[o],i[o+1],n);else for(let o=t-s;o>=e;o-=s)n=tg(o/s|0,i[o],i[o+1],n);return n&&zi(n,n.next)&&(As(n),n=n.next),n}function di(i,e){if(!i)return i;e||(e=i);let t=i,s;do if(s=!1,!t.steiner&&(zi(t,t.next)||ge(t.prev,t,t.next)===0)){if(As(t),t=e=t.prev,t===t.next)break;s=!0}else t=t.next;while(s||t!==e);return e}function ws(i,e,t,s,r,n,o){if(!i)return;!o&&n&&xC(i,s,r,n);let a=i;for(;i.prev!==i.next;){const l=i.prev,c=i.next;if(n?hC(i,s,r,n):cC(i)){e.push(l.i,i.i,c.i),As(i),i=c.next,a=c.next;continue}if(i=c,i===a){o?o===1?(i=uC(di(i),e),ws(i,e,t,s,r,n,2)):o===2&&dC(i,e,t,s,r,n):ws(di(i),e,t,s,r,n,1);break}}}function cC(i){const e=i.prev,t=i,s=i.next;if(ge(e,t,s)>=0)return!1;const r=e.x,n=t.x,o=s.x,a=e.y,l=t.y,c=s.y,h=Math.min(r,n,o),u=Math.min(a,l,c),d=Math.max(r,n,o),f=Math.max(a,l,c);let p=s.next;for(;p!==e;){if(p.x>=h&&p.x<=d&&p.y>=u&&p.y<=f&&Ss(r,a,n,l,o,c,p.x,p.y)&&ge(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function hC(i,e,t,s){const r=i.prev,n=i,o=i.next;if(ge(r,n,o)>=0)return!1;const a=r.x,l=n.x,c=o.x,h=r.y,u=n.y,d=o.y,f=Math.min(a,l,c),p=Math.min(h,u,d),g=Math.max(a,l,c),m=Math.max(h,u,d),_=zu(f,p,e,t,s),x=zu(g,m,e,t,s);let y=i.prevZ,v=i.nextZ;for(;y&&y.z>=_&&v&&v.z<=x;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=m&&y!==r&&y!==o&&Ss(a,h,l,u,c,d,y.x,y.y)&&ge(y.prev,y,y.next)>=0||(y=y.prevZ,v.x>=f&&v.x<=g&&v.y>=p&&v.y<=m&&v!==r&&v!==o&&Ss(a,h,l,u,c,d,v.x,v.y)&&ge(v.prev,v,v.next)>=0))return!1;v=v.nextZ}for(;y&&y.z>=_;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=m&&y!==r&&y!==o&&Ss(a,h,l,u,c,d,y.x,y.y)&&ge(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;v&&v.z<=x;){if(v.x>=f&&v.x<=g&&v.y>=p&&v.y<=m&&v!==r&&v!==o&&Ss(a,h,l,u,c,d,v.x,v.y)&&ge(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function uC(i,e){let t=i;do{const s=t.prev,r=t.next.next;!zi(s,r)&&Qm(s,t,t.next,r)&&Cs(s,r)&&Cs(r,s)&&(e.push(s.i,t.i,r.i),As(t),As(t.next),t=i=r),t=t.next}while(t!==i);return di(t)}function dC(i,e,t,s,r,n){let o=i;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&bC(o,a)){let l=eg(o,a);o=di(o,o.next),l=di(l,l.next),ws(o,e,t,s,r,n,0),ws(l,e,t,s,r,n,0);return}a=a.next}o=o.next}while(o!==i)}function fC(i,e,t,s){const r=[];for(let n=0,o=e.length;n<o;n++){const a=e[n]*s,l=n<o-1?e[n+1]*s:i.length,c=Zm(i,a,l,s,!1);c===c.next&&(c.steiner=!0),r.push(vC(c))}r.sort(pC);for(let n=0;n<r.length;n++)t=mC(r[n],t);return t}function pC(i,e){let t=i.x-e.x;if(t===0&&(t=i.y-e.y,t===0)){const s=(i.next.y-i.y)/(i.next.x-i.x),r=(e.next.y-e.y)/(e.next.x-e.x);t=s-r}return t}function mC(i,e){const t=gC(i,e);if(!t)return e;const s=eg(t,i);return di(s,s.next),di(t,t.next)}function gC(i,e){let t=e;const s=i.x,r=i.y;let n=-1/0,o;if(zi(i,t))return t;do{if(zi(i,t.next))return t.next;if(r<=t.y&&r>=t.next.y&&t.next.y!==t.y){const u=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=s&&u>n&&(n=u,o=t.x<t.next.x?t:t.next,u===s))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,l=o.x,c=o.y;let h=1/0;t=o;do{if(s>=t.x&&t.x>=l&&s!==t.x&&Jm(r<c?s:n,r,l,c,r<c?n:s,r,t.x,t.y)){const u=Math.abs(r-t.y)/(s-t.x);Cs(t,i)&&(u<h||u===h&&(t.x>o.x||t.x===o.x&&_C(o,t)))&&(o=t,h=u)}t=t.next}while(t!==a);return o}function _C(i,e){return ge(i.prev,i,e.prev)<0&&ge(e.next,i,i.next)<0}function xC(i,e,t,s){let r=i;do r.z===0&&(r.z=zu(r.x,r.y,e,t,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==i);r.prevZ.nextZ=null,r.prevZ=null,yC(r)}function yC(i){let e,t=1;do{let s=i,r;i=null;let n=null;for(e=0;s;){e++;let o=s,a=0;for(let c=0;c<t&&(a++,o=o.nextZ,!!o);c++);let l=t;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||s.z<=o.z)?(r=s,s=s.nextZ,a--):(r=o,o=o.nextZ,l--),n?n.nextZ=r:i=r,r.prevZ=n,n=r;s=o}n.nextZ=null,t*=2}while(e>1);return i}function zu(i,e,t,s,r){return i=(i-t)*r|0,e=(e-s)*r|0,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,i|e<<1}function vC(i){let e=i,t=i;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==i);return t}function Jm(i,e,t,s,r,n,o,a){return(r-o)*(e-a)>=(i-o)*(n-a)&&(i-o)*(s-a)>=(t-o)*(e-a)&&(t-o)*(n-a)>=(r-o)*(s-a)}function Ss(i,e,t,s,r,n,o,a){return!(i===o&&e===a)&&Jm(i,e,t,s,r,n,o,a)}function bC(i,e){return i.next.i!==e.i&&i.prev.i!==e.i&&!TC(i,e)&&(Cs(i,e)&&Cs(e,i)&&wC(i,e)&&(ge(i.prev,i,e.prev)||ge(i,e.prev,e))||zi(i,e)&&ge(i.prev,i,i.next)>0&&ge(e.prev,e,e.next)>0)}function ge(i,e,t){return(e.y-i.y)*(t.x-e.x)-(e.x-i.x)*(t.y-e.y)}function zi(i,e){return i.x===e.x&&i.y===e.y}function Qm(i,e,t,s){const r=Vr(ge(i,e,t)),n=Vr(ge(i,e,s)),o=Vr(ge(t,s,i)),a=Vr(ge(t,s,e));return!!(r!==n&&o!==a||r===0&&Wr(i,t,e)||n===0&&Wr(i,s,e)||o===0&&Wr(t,i,s)||a===0&&Wr(t,e,s))}function Wr(i,e,t){return e.x<=Math.max(i.x,t.x)&&e.x>=Math.min(i.x,t.x)&&e.y<=Math.max(i.y,t.y)&&e.y>=Math.min(i.y,t.y)}function Vr(i){return i>0?1:i<0?-1:0}function TC(i,e){let t=i;do{if(t.i!==i.i&&t.next.i!==i.i&&t.i!==e.i&&t.next.i!==e.i&&Qm(t,t.next,i,e))return!0;t=t.next}while(t!==i);return!1}function Cs(i,e){return ge(i.prev,i,i.next)<0?ge(i,e,i.next)>=0&&ge(i,i.prev,e)>=0:ge(i,e,i.prev)<0||ge(i,i.next,e)<0}function wC(i,e){let t=i,s=!1;const r=(i.x+e.x)/2,n=(i.y+e.y)/2;do t.y>n!=t.next.y>n&&t.next.y!==t.y&&r<(t.next.x-t.x)*(n-t.y)/(t.next.y-t.y)+t.x&&(s=!s),t=t.next;while(t!==i);return s}function eg(i,e){const t=Nu(i.i,i.x,i.y),s=Nu(e.i,e.x,e.y),r=i.next,n=e.prev;return i.next=e,e.prev=i,t.next=r,r.prev=t,s.next=t,t.prev=s,n.next=s,s.prev=n,s}function tg(i,e,t,s){const r=Nu(i,e,t);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function As(i){i.next.prev=i.prev,i.prev.next=i.next,i.prevZ&&(i.prevZ.nextZ=i.nextZ),i.nextZ&&(i.nextZ.prevZ=i.prevZ)}function Nu(i,e,t){return{i,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function SC(i,e,t,s){let r=0;for(let n=e,o=t-s;n<t;n+=s)r+=(i[o]-i[n])*(i[n+1]+i[o+1]),o=n;return r}const CC=jm.default||jm;var et=(i=>(i[i.NONE=0]="NONE",i[i.COLOR=16384]="COLOR",i[i.STENCIL=1024]="STENCIL",i[i.DEPTH=256]="DEPTH",i[i.COLOR_DEPTH=16640]="COLOR_DEPTH",i[i.COLOR_STENCIL=17408]="COLOR_STENCIL",i[i.DEPTH_STENCIL=1280]="DEPTH_STENCIL",i[i.ALL=17664]="ALL",i))(et||{});class ig{constructor(e){this.items=[],this._name=e}emit(e,t,s,r,n,o,a,l){const{name:c,items:h}=this;for(let u=0,d=h.length;u<d;u++)h[u][c](e,t,s,r,n,o,a,l);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const AC=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],sg=class ty extends je{constructor(e){super(),this.uid=he("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...AC,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await lC(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const s in this._systemsHash)e={...this._systemsHash[s].constructor.defaultOptions,...e};e={...ty.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let s=0;s<this.runners.init.items.length;s++)await this.runners.init.items[s].init(e);this._initOptions=e}render(e,t){let s=e;if(s instanceof re&&(s={container:s},t&&(W(Q,"passing a second argument is deprecated, please use render options instead"),s.target=t.renderTexture)),s.target||(s.target=this.view.renderTarget),s.target===this.view.renderTarget&&(this._lastObjectRendered=s.container,s.clearColor??(s.clearColor=this.background.colorRgba),s.clear??(s.clear=this.background.clearBeforeRender)),s.clearColor){const r=Array.isArray(s.clearColor)&&s.clearColor.length===4;s.clearColor=r?s.clearColor:ue.shared.setValue(s.clearColor).toArray()}s.transform||(s.container.updateLocalTransform(),s.transform=s.container.localTransform),s.container.visible&&(s.container.enableRenderGroup(),this.runners.prerender.emit(s),this.runners.renderStart.emit(s),this.runners.render.emit(s),this.runners.renderEnd.emit(s),this.runners.postrender.emit(s))}resize(e,t,s){const r=this.view.resolution;this.view.resize(e,t,s),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),s!==void 0&&s!==r&&this.runners.resolutionChange.emit(s)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=et.ALL);const{clear:s,clearColor:r,target:n}=e;ue.shared.setValue(r??this.background.colorRgba),t.renderTarget.clear(n,s,ue.shared.toArray())}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new ig(t)})}_addSystems(e){let t;for(t in e){const s=e[t];this._addSystem(s.value,s.name)}}_addSystem(e,t){const s=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=s,this._systemsHash[t]=s;for(const r in this.runners)this.runners[r].add(s);return this}_addPipes(e,t){const s=t.reduce((r,n)=>(r[n.name]=n.value,r),{});e.forEach(r=>{const n=r.value,o=r.name,a=s[o];this.renderPipes[o]=new n(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&Bi.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!Km())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};sg.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let $r=sg,Xr;function EC(i){return Xr!==void 0||(Xr=(()=>{const e={stencil:!0,failIfMajorPerformanceCaveat:i??$r.defaultOptions.failIfMajorPerformanceCaveat};try{if(!Y.get().getWebGLRenderingContext())return!1;let s=Y.get().createCanvas().getContext("webgl",e);const r=!!s?.getContextAttributes()?.stencil;if(s){const n=s.getExtension("WEBGL_lose_context");n&&n.loseContext()}return s=null,r}catch{return!1}})()),Xr}let Yr;async function IC(i={}){return Yr!==void 0||(Yr=await(async()=>{const e=Y.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(i)).requestDevice(),!0}catch{return!1}})()),Yr}const rg=["webgl","webgpu","canvas"];async function PC(i){let e=[];i.preference?(e.push(i.preference),rg.forEach(n=>{n!==i.preference&&e.push(n)})):e=rg.slice();let t,s={};for(let n=0;n<e.length;n++){const o=e[n];if(o==="webgpu"&&await IC()){const{WebGPURenderer:a}=await Promise.resolve().then(()=>SP);t=a,s={...i,...i.webgpu};break}else if(o==="webgl"&&EC(i.failIfMajorPerformanceCaveat??$r.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Promise.resolve().then(()=>nP);t=a,s={...i,...i.webgl};break}else if(o==="canvas")throw s={...i},new Error("CanvasRenderer is not yet implemented")}if(delete s.webgpu,delete s.webgl,!t)throw new Error("No available renderer for the current environment");const r=new t;return await r.init(s),r}const qr="8.14.3";class ng{static init(){globalThis.__PIXI_APP_INIT__?.(this,qr)}static destroy(){}}ng.extension=b.Application;class og{constructor(e){this._renderer=e}init(){globalThis.__PIXI_RENDERER_INIT__?.(this._renderer,qr)}destroy(){this._renderer=null}}og.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"initHook",priority:-10};const ag=class lf{constructor(...e){this.stage=new re,e[0]!==void 0&&W(Q,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new re),this.renderer=await PC(e),lf._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return W(Q,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const s=lf._plugins.slice(0);s.reverse(),s.forEach(r=>{r.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};ag._plugins=[];let Lu=ag;V.handleByList(b.Application,Lu._plugins),V.add(ng);class lg{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,s;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,s=globalThis.innerHeight;else{const{clientWidth:r,clientHeight:n}=this._resizeTo;t=r,s=n}this.renderer.resize(t,s),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}lg.extension=b.Application;class cg{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,Ui.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?Ze.shared:new Ze,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}cg.extension=b.Application;class hg extends je{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily="",this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:"none",range:0},this.pages=[],this.applyFillAsTint=!0,this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return W(Q,"BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead."),this.fontFamily}get pageTextures(){return W(Q,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}get size(){return W(Q,"BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead."),this.fontMetrics.fontSize}get distanceFieldRange(){return W(Q,"BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead."),this.distanceField.range}get distanceFieldType(){return W(Q,"BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead."),this.distanceField.type}destroy(e=!1){this.emit("destroy",this),this.removeAllListeners();for(const t in this.chars)this.chars[t].texture?.destroy();this.chars=null,e&&(this.pages.forEach(t=>t.texture.destroy(!0)),this.pages=null)}}class RC{constructor(e=0,t=0,s=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=e,this.resetTtl=s,this.size=0,this.ttl=t}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(e){if(this.has(e)){const t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}return this}entries(e=this.keys()){return e.map(t=>[t,this.get(t)])}evict(e=!1){if(e||this.size>0){const t=this.first;delete this.items[t.key],--this.size===0?(this.first=null,this.last=null):(this.first=t.next,this.first.prev=null)}return this}expiresAt(e){let t;return this.has(e)&&(t=this.items[e].expiry),t}get(e){const t=this.items[e];if(t!==void 0){if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.moveToEnd(t),t.value}}has(e){return e in this.items}moveToEnd(e){this.last!==e&&(e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),e.prev=this.last,e.next=null,this.last!==null&&(this.last.next=e),this.last=e,this.first===null&&(this.first=e))}keys(){const e=[];let t=this.first;for(;t!==null;)e.push(t.key),t=t.next;return e}setWithEvicted(e,t,s=this.resetTtl){let r=null;if(this.has(e))this.set(e,t,!0,s);else{this.max>0&&this.size===this.max&&(r={...this.first},this.evict(!0));let n=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};++this.size===1?this.first=n:this.last.next=n,this.last=n}return r}set(e,t,s=!1,r=this.resetTtl){let n=this.items[e];return s||n!==void 0?(n.value=t,s===!1&&r&&(n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(n)):(this.max>0&&this.size===this.max&&this.evict(!0),n=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t},++this.size===1?this.first=n:this.last.next=n,this.last=n),this}values(e=this.keys()){return e.map(t=>this.get(t))}}function ug(i=1e3,e=0,t=!1){if(isNaN(i)||i<0)throw new TypeError("Invalid max value");if(isNaN(e)||e<0)throw new TypeError("Invalid ttl value");if(typeof t!="boolean")throw new TypeError("Invalid resetTtl value");return new RC(i,e,t)}const MC=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function Kr(i){const e=typeof i.fontSize=="number"?`${i.fontSize}px`:i.fontSize;let t=i.fontFamily;Array.isArray(i.fontFamily)||(t=i.fontFamily.split(","));for(let s=t.length-1;s>=0;s--){let r=t[s].trim();!/([\"\'])[^\'\"]+\1/.test(r)&&!MC.includes(r)&&(r=`"${r}"`),t[s]=r}return`${i.fontStyle} ${i.fontVariant} ${i.fontWeight} ${e} ${t.join(",")}`}const Hu={willReadFrequently:!0},pt=class z{static get experimentalLetterSpacingSupported(){let e=z._experimentalLetterSpacingSupported;if(e===void 0){const t=Y.get().getCanvasRenderingContext2D().prototype;e=z._experimentalLetterSpacingSupported="letterSpacing"in t||"textLetterSpacing"in t}return e}constructor(e,t,s,r,n,o,a,l,c){this.text=e,this.style=t,this.width=s,this.height=r,this.lines=n,this.lineWidths=o,this.lineHeight=a,this.maxLineWidth=l,this.fontProperties=c}static measureText(e=" ",t,s=z._canvas,r=t.wordWrap){const n=`${e}-${t.styleKey}-wordWrap-${r}`;if(z._measurementCache.has(n))return z._measurementCache.get(n);const o=Kr(t),a=z.measureFont(o);a.fontSize===0&&(a.fontSize=t.fontSize,a.ascent=t.fontSize);const l=z.__context;l.font=o;const h=(r?z._wordWrap(e,t,s):e).split(/(?:\r\n|\r|\n)/),u=new Array(h.length);let d=0;for(let x=0;x<h.length;x++){const y=z._measureText(h[x],t.letterSpacing,l);u[x]=y,d=Math.max(d,y)}const f=t._stroke?.width||0;let p=d+f;t.dropShadow&&(p+=t.dropShadow.distance);const g=t.lineHeight||a.fontSize;let m=Math.max(g,a.fontSize+f)+(h.length-1)*(g+t.leading);t.dropShadow&&(m+=t.dropShadow.distance);const _=new z(e,t,p,m,h,u,g+t.leading,d,a);return z._measurementCache.set(n,_),_}static _measureText(e,t,s){let r=!1;z.experimentalLetterSpacingSupported&&(z.experimentalLetterSpacing?(s.letterSpacing=`${t}px`,s.textLetterSpacing=`${t}px`,r=!0):(s.letterSpacing="0px",s.textLetterSpacing="0px"));const n=s.measureText(e);let o=n.width;const a=-n.actualBoundingBoxLeft;let c=n.actualBoundingBoxRight-a;if(o>0)if(r)o-=t,c-=t;else{const h=(z.graphemeSegmenter(e).length-1)*t;o+=h,c+=h}return Math.max(o,c)}static _wordWrap(e,t,s=z._canvas){const r=s.getContext("2d",Hu);let n=0,o="",a="";const l=Object.create(null),{letterSpacing:c,whiteSpace:h}=t,u=z._collapseSpaces(h),d=z._collapseNewlines(h);let f=!u;const p=t.wordWrapWidth+c,g=z._tokenize(e);for(let m=0;m<g.length;m++){let _=g[m];if(z._isNewline(_)){if(!d){a+=z._addLine(o),f=!u,o="",n=0;continue}_=" "}if(u){const y=z.isBreakingSpace(_),v=z.isBreakingSpace(o[o.length-1]);if(y&&v)continue}const x=z._getFromCache(_,c,l,r);if(x>p)if(o!==""&&(a+=z._addLine(o),o="",n=0),z.canBreakWords(_,t.breakWords)){const y=z.wordWrapSplit(_);for(let v=0;v<y.length;v++){let T=y[v],S=T,w=1;for(;y[v+w];){const P=y[v+w];if(!z.canBreakChars(S,P,_,v,t.breakWords))T+=P;else break;S=P,w++}v+=w-1;const E=z._getFromCache(T,c,l,r);E+n>p&&(a+=z._addLine(o),f=!1,o="",n=0),o+=T,n+=E}}else{o.length>0&&(a+=z._addLine(o),o="",n=0);const y=m===g.length-1;a+=z._addLine(_,!y),f=!1,o="",n=0}else x+n>p&&(f=!1,a+=z._addLine(o),o="",n=0),(o.length>0||!z.isBreakingSpace(_)||f)&&(o+=_,n+=x)}return a+=z._addLine(o,!1),a}static _addLine(e,t=!0){return e=z._trimRight(e),e=t?`${e}
|
|
100
|
+
${i}`}function QS(i,e){return e?i.replace("#version 300 es",""):i}const Pu={stripVersion:QS,ensurePrecision:qS,addProgramDefines:YS,setProgramName:JS,insertVersion:KS},ys=Object.create(null),Vm=class of{constructor(e){e={...of.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,s={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:XS()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let r=e.fragment,n=e.vertex;Object.keys(Pu).forEach(o=>{const a=s[o];r=Pu[o](r,a,!0),n=Pu[o](n,a,!1)}),this.fragment=r,this.vertex=n,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=_s(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,ys[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return ys[t]||(ys[t]=new of(e),ys[t]._cacheKey=t),ys[t]}};Vm.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let At=Vm;const $m={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function jt(i){return $m[i]??$m.float32}const eC={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"};function tC({source:i,entryPoint:e}){const t={},s=i.indexOf(`fn ${e}`);if(s!==-1){const r=i.indexOf("->",s);if(r!==-1){const n=i.substring(s,r),o=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|$)/g;let a;for(;(a=o.exec(n))!==null;){const l=eC[a[3]]??"float32";t[a[2]]={location:parseInt(a[1],10),format:l,stride:jt(l).stride,offset:0,instance:!1,start:0}}}}return t}function Ru(i){const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,s=/@binding\((\d+)\)/,r=/var(<[^>]+>)? (\w+)/,n=/:\s*(\w+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,l=/struct\s+(\w+)/,c=i.match(e)?.map(u=>({group:parseInt(u.match(t)[1],10),binding:parseInt(u.match(s)[1],10),name:u.match(r)[2],isUniform:u.match(r)[1]==="<uniform>",type:u.match(n)[1]}));if(!c)return{groups:[],structs:[]};const h=i.match(o)?.map(u=>{const d=u.match(l)[1],f=u.match(a).reduce((p,g)=>{const[m,x]=g.split(":");return p[m.trim()]=x.trim(),p},{});return f?{name:d,members:f}:null}).filter(({name:u})=>c.some(d=>d.type===u))??[];return{groups:c,structs:h}}var vs=(i=>(i[i.VERTEX=1]="VERTEX",i[i.FRAGMENT=2]="FRAGMENT",i[i.COMPUTE=4]="COMPUTE",i))(vs||{});function iC({groups:i}){const e=[];for(let t=0;t<i.length;t++){const s=i[t];e[s.group]||(e[s.group]=[]),s.isUniform?e[s.group].push({binding:s.binding,visibility:vs.VERTEX|vs.FRAGMENT,buffer:{type:"uniform"}}):s.type==="sampler"?e[s.group].push({binding:s.binding,visibility:vs.FRAGMENT,sampler:{type:"filtering"}}):s.type==="texture_2d"&&e[s.group].push({binding:s.binding,visibility:vs.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}})}return e}function sC({groups:i}){const e=[];for(let t=0;t<i.length;t++){const s=i[t];e[s.group]||(e[s.group]={}),e[s.group][s.name]=s.binding}return e}function rC(i,e){const t=new Set,s=new Set,r=[...i.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),n=[...i.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return s.has(a)?!1:(s.add(a),!0)});return{structs:r,groups:n}}const bs=Object.create(null);class Ut{constructor(e){this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:s,layout:r,gpuLayout:n,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=s,t.source===s.source){const a=Ru(t.source);this.structsAndGroups=a}else{const a=Ru(s.source),l=Ru(t.source);this.structsAndGroups=rC(a,l)}this.layout=r??sC(this.structsAndGroups),this.gpuLayout=n??iC(this.structsAndGroups),this.autoAssignGlobalUniforms=this.layout[0]?.globalUniforms!==void 0,this.autoAssignLocalUniforms=this.layout[1]?.localUniforms!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,s=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=_s(s,"program")}get attributeData(){return this._attributeData??(this._attributeData=tC(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,bs[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return bs[t]||(bs[t]=new Ut(e),bs[t]._cacheKey=t),bs[t]}}const Xm=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],nC=Xm.reduce((i,e)=>(i[e]=!0,i),{});function oC(i,e){switch(i){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const Ym=class Q_{constructor(e,t){this._touched=0,this.uid=he("uniform"),this._resourceType="uniformGroup",this._resourceId=he("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...Q_.defaultOptions,...t},this.uniformStructures=e;const s={};for(const r in e){const n=e[r];if(n.name=r,n.size=n.size??1,!nC[n.type]){const o=n.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,l]=o;throw new Error(`Uniform type ${n.type} is not supported. Use type: '${a}', size: ${l} instead.`)}throw new Error(`Uniform type ${n.type} is not supported. Supported uniform types are: ${Xm.join(", ")}`)}n.value??(n.value=oC(n.type,n.size)),s[r]=n.value}this.uniforms=s,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=_s(Object.keys(s).map(r=>`${r}-${e[r].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};Ym.defaultOptions={ubo:!1,isStatic:!1};let He=Ym;class Ot{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const s in e){const r=e[s];this.setResource(r,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const s in this.resources)e[t++]=this.resources[s]._resourceId;this._key=e.join("|")}setResource(e,t){const s=this.resources[t];e!==s&&(s&&e.off?.("change",this.onResourceChange,this),e.on?.("change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e){const t=this.resources;for(const s in t)t[s]._touched=e}destroy(){const e=this.resources;for(const t in e)e[t]?.off?.("change",this.onResourceChange,this);this.resources=null}onResourceChange(e){if(this._dirty=!0,e.destroyed){const t=this.resources;for(const s in t)t[s]===e&&(t[s]=null)}else this._updateKey()}}var Qe=(i=>(i[i.WEBGL=1]="WEBGL",i[i.WEBGPU=2]="WEBGPU",i[i.BOTH=3]="BOTH",i))(Qe||{});class ot extends je{constructor(e){super(),this.uid=he("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:s,groups:r,resources:n,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=s,o===void 0&&(o=0,t&&(o|=Qe.WEBGPU),s&&(o|=Qe.WEBGL)),this.compatibleRenderers=o;const l={};if(!n&&!r&&(n={}),n&&r)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&r&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&r&&a)for(const c in a)for(const h in a[c]){const u=a[c][h];l[u]={group:c,binding:h,name:u}}else if(t&&r&&!a){const c=t.structsAndGroups.groups;a={},c.forEach(h=>{a[h.group]=a[h.group]||{},a[h.group][h.binding]=h.name,l[h.name]=h})}else if(n){r={},a={},t&&t.structsAndGroups.groups.forEach(u=>{a[u.group]=a[u.group]||{},a[u.group][u.binding]=u.name,l[u.name]=u});let c=0;for(const h in n)l[h]||(r[99]||(r[99]=new Ot,this._ownedBindGroups.push(r[99])),l[h]={group:99,binding:c,name:h},a[99]=a[99]||{},a[99][c]=h,c++);for(const h in n){const u=h;let d=n[h];!d.source&&!d._resourceType&&(d=new He(d));const f=l[u];f&&(r[f.group]||(r[f.group]=new Ot,this._ownedBindGroups.push(r[f.group])),r[f.group].setResource(d,f.binding))}}this.groups=r,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(r,l)}addResource(e,t,s){var r,n;(r=this._uniformBindMap)[t]||(r[t]={}),(n=this._uniformBindMap[t])[s]||(n[s]=e),this.groups[t]||(this.groups[t]=new Ot,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const s={};for(const r in t){const n=t[r];Object.defineProperty(s,n.name,{get(){return e[n.group].getResource(n.binding)},set(o){e[n.group].setResource(o,n.binding)}})}return s}destroy(e=!1){this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&(this.gpuProgram?.destroy(),this.glProgram?.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(t=>{t.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:s,...r}=e;let n,o;return t&&(n=Ut.from(t)),s&&(o=At.from(s)),new ot({gpuProgram:n,glProgram:o,...r})}}const aC={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},Mu=0,ku=1,Fu=2,Bu=3,Uu=4,Ou=5,Du=class ey{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<Mu)}set blend(e){!!(this.data&1<<Mu)!==e&&(this.data^=1<<Mu)}get offsets(){return!!(this.data&1<<ku)}set offsets(e){!!(this.data&1<<ku)!==e&&(this.data^=1<<ku)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<Fu)}set culling(e){!!(this.data&1<<Fu)!==e&&(this.data^=1<<Fu)}get depthTest(){return!!(this.data&1<<Bu)}set depthTest(e){!!(this.data&1<<Bu)!==e&&(this.data^=1<<Bu)}get depthMask(){return!!(this.data&1<<Ou)}set depthMask(e){!!(this.data&1<<Ou)!==e&&(this.data^=1<<Ou)}get clockwiseFrontFace(){return!!(this.data&1<<Uu)}set clockwiseFrontFace(e){!!(this.data&1<<Uu)!==e&&(this.data^=1<<Uu)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=aC[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new ey;return e.depthTest=!1,e.blend=!0,e}};Du.default2d=Du.for2d();let ft=Du;const qm=class af extends ot{constructor(e){e={...af.defaultOptions,...e},super(e),this.enabled=!0,this._state=ft.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,s,r){e.applyFilter(this,t,s,r)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:s,...r}=e;let n,o;return t&&(n=Ut.from(t)),s&&(o=At.from(s)),new af({gpuProgram:n,glProgram:o,...r})}};qm.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Gi=qm;const Gu=[];V.handleByNamedList(b.Environment,Gu);async function lC(i){if(!i)for(let e=0;e<Gu.length;e++){const t=Gu[e];if(t.value.test()){await t.value.load();return}}}let Ts;function Km(){if(typeof Ts=="boolean")return Ts;try{Ts=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Ts=!1}return Ts}function jm(i,e,t=2){const s=e&&e.length,r=s?e[0]*t:i.length;let n=Zm(i,0,r,t,!0);const o=[];if(!n||n.next===n.prev)return o;let a,l,c;if(s&&(n=fC(i,e,n,t)),i.length>80*t){a=i[0],l=i[1];let h=a,u=l;for(let d=t;d<r;d+=t){const f=i[d],p=i[d+1];f<a&&(a=f),p<l&&(l=p),f>h&&(h=f),p>u&&(u=p)}c=Math.max(h-a,u-l),c=c!==0?32767/c:0}return ws(n,o,t,a,l,c,0),o}function Zm(i,e,t,s,r){let n;if(r===SC(i,e,t,s)>0)for(let o=e;o<t;o+=s)n=tg(o/s|0,i[o],i[o+1],n);else for(let o=t-s;o>=e;o-=s)n=tg(o/s|0,i[o],i[o+1],n);return n&&zi(n,n.next)&&(As(n),n=n.next),n}function di(i,e){if(!i)return i;e||(e=i);let t=i,s;do if(s=!1,!t.steiner&&(zi(t,t.next)||ge(t.prev,t,t.next)===0)){if(As(t),t=e=t.prev,t===t.next)break;s=!0}else t=t.next;while(s||t!==e);return e}function ws(i,e,t,s,r,n,o){if(!i)return;!o&&n&&_C(i,s,r,n);let a=i;for(;i.prev!==i.next;){const l=i.prev,c=i.next;if(n?hC(i,s,r,n):cC(i)){e.push(l.i,i.i,c.i),As(i),i=c.next,a=c.next;continue}if(i=c,i===a){o?o===1?(i=uC(di(i),e),ws(i,e,t,s,r,n,2)):o===2&&dC(i,e,t,s,r,n):ws(di(i),e,t,s,r,n,1);break}}}function cC(i){const e=i.prev,t=i,s=i.next;if(ge(e,t,s)>=0)return!1;const r=e.x,n=t.x,o=s.x,a=e.y,l=t.y,c=s.y,h=Math.min(r,n,o),u=Math.min(a,l,c),d=Math.max(r,n,o),f=Math.max(a,l,c);let p=s.next;for(;p!==e;){if(p.x>=h&&p.x<=d&&p.y>=u&&p.y<=f&&Ss(r,a,n,l,o,c,p.x,p.y)&&ge(p.prev,p,p.next)>=0)return!1;p=p.next}return!0}function hC(i,e,t,s){const r=i.prev,n=i,o=i.next;if(ge(r,n,o)>=0)return!1;const a=r.x,l=n.x,c=o.x,h=r.y,u=n.y,d=o.y,f=Math.min(a,l,c),p=Math.min(h,u,d),g=Math.max(a,l,c),m=Math.max(h,u,d),x=zu(f,p,e,t,s),_=zu(g,m,e,t,s);let y=i.prevZ,v=i.nextZ;for(;y&&y.z>=x&&v&&v.z<=_;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=m&&y!==r&&y!==o&&Ss(a,h,l,u,c,d,y.x,y.y)&&ge(y.prev,y,y.next)>=0||(y=y.prevZ,v.x>=f&&v.x<=g&&v.y>=p&&v.y<=m&&v!==r&&v!==o&&Ss(a,h,l,u,c,d,v.x,v.y)&&ge(v.prev,v,v.next)>=0))return!1;v=v.nextZ}for(;y&&y.z>=x;){if(y.x>=f&&y.x<=g&&y.y>=p&&y.y<=m&&y!==r&&y!==o&&Ss(a,h,l,u,c,d,y.x,y.y)&&ge(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;v&&v.z<=_;){if(v.x>=f&&v.x<=g&&v.y>=p&&v.y<=m&&v!==r&&v!==o&&Ss(a,h,l,u,c,d,v.x,v.y)&&ge(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function uC(i,e){let t=i;do{const s=t.prev,r=t.next.next;!zi(s,r)&&Qm(s,t,t.next,r)&&Cs(s,r)&&Cs(r,s)&&(e.push(s.i,t.i,r.i),As(t),As(t.next),t=i=r),t=t.next}while(t!==i);return di(t)}function dC(i,e,t,s,r,n){let o=i;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&bC(o,a)){let l=eg(o,a);o=di(o,o.next),l=di(l,l.next),ws(o,e,t,s,r,n,0),ws(l,e,t,s,r,n,0);return}a=a.next}o=o.next}while(o!==i)}function fC(i,e,t,s){const r=[];for(let n=0,o=e.length;n<o;n++){const a=e[n]*s,l=n<o-1?e[n+1]*s:i.length,c=Zm(i,a,l,s,!1);c===c.next&&(c.steiner=!0),r.push(vC(c))}r.sort(pC);for(let n=0;n<r.length;n++)t=mC(r[n],t);return t}function pC(i,e){let t=i.x-e.x;if(t===0&&(t=i.y-e.y,t===0)){const s=(i.next.y-i.y)/(i.next.x-i.x),r=(e.next.y-e.y)/(e.next.x-e.x);t=s-r}return t}function mC(i,e){const t=gC(i,e);if(!t)return e;const s=eg(t,i);return di(s,s.next),di(t,t.next)}function gC(i,e){let t=e;const s=i.x,r=i.y;let n=-1/0,o;if(zi(i,t))return t;do{if(zi(i,t.next))return t.next;if(r<=t.y&&r>=t.next.y&&t.next.y!==t.y){const u=t.x+(r-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(u<=s&&u>n&&(n=u,o=t.x<t.next.x?t:t.next,u===s))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,l=o.x,c=o.y;let h=1/0;t=o;do{if(s>=t.x&&t.x>=l&&s!==t.x&&Jm(r<c?s:n,r,l,c,r<c?n:s,r,t.x,t.y)){const u=Math.abs(r-t.y)/(s-t.x);Cs(t,i)&&(u<h||u===h&&(t.x>o.x||t.x===o.x&&xC(o,t)))&&(o=t,h=u)}t=t.next}while(t!==a);return o}function xC(i,e){return ge(i.prev,i,e.prev)<0&&ge(e.next,i,i.next)<0}function _C(i,e,t,s){let r=i;do r.z===0&&(r.z=zu(r.x,r.y,e,t,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next;while(r!==i);r.prevZ.nextZ=null,r.prevZ=null,yC(r)}function yC(i){let e,t=1;do{let s=i,r;i=null;let n=null;for(e=0;s;){e++;let o=s,a=0;for(let c=0;c<t&&(a++,o=o.nextZ,!!o);c++);let l=t;for(;a>0||l>0&&o;)a!==0&&(l===0||!o||s.z<=o.z)?(r=s,s=s.nextZ,a--):(r=o,o=o.nextZ,l--),n?n.nextZ=r:i=r,r.prevZ=n,n=r;s=o}n.nextZ=null,t*=2}while(e>1);return i}function zu(i,e,t,s,r){return i=(i-t)*r|0,e=(e-s)*r|0,i=(i|i<<8)&16711935,i=(i|i<<4)&252645135,i=(i|i<<2)&858993459,i=(i|i<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,i|e<<1}function vC(i){let e=i,t=i;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==i);return t}function Jm(i,e,t,s,r,n,o,a){return(r-o)*(e-a)>=(i-o)*(n-a)&&(i-o)*(s-a)>=(t-o)*(e-a)&&(t-o)*(n-a)>=(r-o)*(s-a)}function Ss(i,e,t,s,r,n,o,a){return!(i===o&&e===a)&&Jm(i,e,t,s,r,n,o,a)}function bC(i,e){return i.next.i!==e.i&&i.prev.i!==e.i&&!TC(i,e)&&(Cs(i,e)&&Cs(e,i)&&wC(i,e)&&(ge(i.prev,i,e.prev)||ge(i,e.prev,e))||zi(i,e)&&ge(i.prev,i,i.next)>0&&ge(e.prev,e,e.next)>0)}function ge(i,e,t){return(e.y-i.y)*(t.x-e.x)-(e.x-i.x)*(t.y-e.y)}function zi(i,e){return i.x===e.x&&i.y===e.y}function Qm(i,e,t,s){const r=Vr(ge(i,e,t)),n=Vr(ge(i,e,s)),o=Vr(ge(t,s,i)),a=Vr(ge(t,s,e));return!!(r!==n&&o!==a||r===0&&Wr(i,t,e)||n===0&&Wr(i,s,e)||o===0&&Wr(t,i,s)||a===0&&Wr(t,e,s))}function Wr(i,e,t){return e.x<=Math.max(i.x,t.x)&&e.x>=Math.min(i.x,t.x)&&e.y<=Math.max(i.y,t.y)&&e.y>=Math.min(i.y,t.y)}function Vr(i){return i>0?1:i<0?-1:0}function TC(i,e){let t=i;do{if(t.i!==i.i&&t.next.i!==i.i&&t.i!==e.i&&t.next.i!==e.i&&Qm(t,t.next,i,e))return!0;t=t.next}while(t!==i);return!1}function Cs(i,e){return ge(i.prev,i,i.next)<0?ge(i,e,i.next)>=0&&ge(i,i.prev,e)>=0:ge(i,e,i.prev)<0||ge(i,i.next,e)<0}function wC(i,e){let t=i,s=!1;const r=(i.x+e.x)/2,n=(i.y+e.y)/2;do t.y>n!=t.next.y>n&&t.next.y!==t.y&&r<(t.next.x-t.x)*(n-t.y)/(t.next.y-t.y)+t.x&&(s=!s),t=t.next;while(t!==i);return s}function eg(i,e){const t=Nu(i.i,i.x,i.y),s=Nu(e.i,e.x,e.y),r=i.next,n=e.prev;return i.next=e,e.prev=i,t.next=r,r.prev=t,s.next=t,t.prev=s,n.next=s,s.prev=n,s}function tg(i,e,t,s){const r=Nu(i,e,t);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function As(i){i.next.prev=i.prev,i.prev.next=i.next,i.prevZ&&(i.prevZ.nextZ=i.nextZ),i.nextZ&&(i.nextZ.prevZ=i.prevZ)}function Nu(i,e,t){return{i,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function SC(i,e,t,s){let r=0;for(let n=e,o=t-s;n<t;n+=s)r+=(i[o]-i[n])*(i[n+1]+i[o+1]),o=n;return r}const CC=jm.default||jm;var et=(i=>(i[i.NONE=0]="NONE",i[i.COLOR=16384]="COLOR",i[i.STENCIL=1024]="STENCIL",i[i.DEPTH=256]="DEPTH",i[i.COLOR_DEPTH=16640]="COLOR_DEPTH",i[i.COLOR_STENCIL=17408]="COLOR_STENCIL",i[i.DEPTH_STENCIL=1280]="DEPTH_STENCIL",i[i.ALL=17664]="ALL",i))(et||{});class ig{constructor(e){this.items=[],this._name=e}emit(e,t,s,r,n,o,a,l){const{name:c,items:h}=this;for(let u=0,d=h.length;u<d;u++)h[u][c](e,t,s,r,n,o,a,l);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const AC=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],sg=class ty extends je{constructor(e){super(),this.uid=he("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...AC,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await lC(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const s in this._systemsHash)e={...this._systemsHash[s].constructor.defaultOptions,...e};e={...ty.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let s=0;s<this.runners.init.items.length;s++)await this.runners.init.items[s].init(e);this._initOptions=e}render(e,t){let s=e;if(s instanceof re&&(s={container:s},t&&(W(Q,"passing a second argument is deprecated, please use render options instead"),s.target=t.renderTexture)),s.target||(s.target=this.view.renderTarget),s.target===this.view.renderTarget&&(this._lastObjectRendered=s.container,s.clearColor??(s.clearColor=this.background.colorRgba),s.clear??(s.clear=this.background.clearBeforeRender)),s.clearColor){const r=Array.isArray(s.clearColor)&&s.clearColor.length===4;s.clearColor=r?s.clearColor:ue.shared.setValue(s.clearColor).toArray()}s.transform||(s.container.updateLocalTransform(),s.transform=s.container.localTransform),s.container.visible&&(s.container.enableRenderGroup(),this.runners.prerender.emit(s),this.runners.renderStart.emit(s),this.runners.render.emit(s),this.runners.renderEnd.emit(s),this.runners.postrender.emit(s))}resize(e,t,s){const r=this.view.resolution;this.view.resize(e,t,s),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),s!==void 0&&s!==r&&this.runners.resolutionChange.emit(s)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=et.ALL);const{clear:s,clearColor:r,target:n}=e;ue.shared.setValue(r??this.background.colorRgba),t.renderTarget.clear(n,s,ue.shared.toArray())}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new ig(t)})}_addSystems(e){let t;for(t in e){const s=e[t];this._addSystem(s.value,s.name)}}_addSystem(e,t){const s=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=s,this._systemsHash[t]=s;for(const r in this.runners)this.runners[r].add(s);return this}_addPipes(e,t){const s=t.reduce((r,n)=>(r[n.name]=n.value,r),{});e.forEach(r=>{const n=r.value,o=r.name,a=s[o];this.renderPipes[o]=new n(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&Bi.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!Km())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};sg.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let $r=sg,Xr;function EC(i){return Xr!==void 0||(Xr=(()=>{const e={stencil:!0,failIfMajorPerformanceCaveat:i??$r.defaultOptions.failIfMajorPerformanceCaveat};try{if(!Y.get().getWebGLRenderingContext())return!1;let s=Y.get().createCanvas().getContext("webgl",e);const r=!!s?.getContextAttributes()?.stencil;if(s){const n=s.getExtension("WEBGL_lose_context");n&&n.loseContext()}return s=null,r}catch{return!1}})()),Xr}let Yr;async function IC(i={}){return Yr!==void 0||(Yr=await(async()=>{const e=Y.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(i)).requestDevice(),!0}catch{return!1}})()),Yr}const rg=["webgl","webgpu","canvas"];async function PC(i){let e=[];i.preference?(e.push(i.preference),rg.forEach(n=>{n!==i.preference&&e.push(n)})):e=rg.slice();let t,s={};for(let n=0;n<e.length;n++){const o=e[n];if(o==="webgpu"&&await IC()){const{WebGPURenderer:a}=await Promise.resolve().then(()=>SP);t=a,s={...i,...i.webgpu};break}else if(o==="webgl"&&EC(i.failIfMajorPerformanceCaveat??$r.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Promise.resolve().then(()=>nP);t=a,s={...i,...i.webgl};break}else if(o==="canvas")throw s={...i},new Error("CanvasRenderer is not yet implemented")}if(delete s.webgpu,delete s.webgl,!t)throw new Error("No available renderer for the current environment");const r=new t;return await r.init(s),r}const qr="8.14.3";class ng{static init(){globalThis.__PIXI_APP_INIT__?.(this,qr)}static destroy(){}}ng.extension=b.Application;class og{constructor(e){this._renderer=e}init(){globalThis.__PIXI_RENDERER_INIT__?.(this._renderer,qr)}destroy(){this._renderer=null}}og.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"initHook",priority:-10};const ag=class lf{constructor(...e){this.stage=new re,e[0]!==void 0&&W(Q,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new re),this.renderer=await PC(e),lf._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return W(Q,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const s=lf._plugins.slice(0);s.reverse(),s.forEach(r=>{r.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};ag._plugins=[];let Lu=ag;V.handleByList(b.Application,Lu._plugins),V.add(ng);class lg{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,s;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,s=globalThis.innerHeight;else{const{clientWidth:r,clientHeight:n}=this._resizeTo;t=r,s=n}this.renderer.resize(t,s),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}lg.extension=b.Application;class cg{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,Ui.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?Ze.shared:new Ze,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}cg.extension=b.Application;class hg extends je{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily="",this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:"none",range:0},this.pages=[],this.applyFillAsTint=!0,this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return W(Q,"BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead."),this.fontFamily}get pageTextures(){return W(Q,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}get size(){return W(Q,"BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead."),this.fontMetrics.fontSize}get distanceFieldRange(){return W(Q,"BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead."),this.distanceField.range}get distanceFieldType(){return W(Q,"BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead."),this.distanceField.type}destroy(e=!1){this.emit("destroy",this),this.removeAllListeners();for(const t in this.chars)this.chars[t].texture?.destroy();this.chars=null,e&&(this.pages.forEach(t=>t.texture.destroy(!0)),this.pages=null)}}class RC{constructor(e=0,t=0,s=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=e,this.resetTtl=s,this.size=0,this.ttl=t}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(e){if(this.has(e)){const t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}return this}entries(e=this.keys()){return e.map(t=>[t,this.get(t)])}evict(e=!1){if(e||this.size>0){const t=this.first;delete this.items[t.key],--this.size===0?(this.first=null,this.last=null):(this.first=t.next,this.first.prev=null)}return this}expiresAt(e){let t;return this.has(e)&&(t=this.items[e].expiry),t}get(e){const t=this.items[e];if(t!==void 0){if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.moveToEnd(t),t.value}}has(e){return e in this.items}moveToEnd(e){this.last!==e&&(e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),e.prev=this.last,e.next=null,this.last!==null&&(this.last.next=e),this.last=e,this.first===null&&(this.first=e))}keys(){const e=[];let t=this.first;for(;t!==null;)e.push(t.key),t=t.next;return e}setWithEvicted(e,t,s=this.resetTtl){let r=null;if(this.has(e))this.set(e,t,!0,s);else{this.max>0&&this.size===this.max&&(r={...this.first},this.evict(!0));let n=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};++this.size===1?this.first=n:this.last.next=n,this.last=n}return r}set(e,t,s=!1,r=this.resetTtl){let n=this.items[e];return s||n!==void 0?(n.value=t,s===!1&&r&&(n.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(n)):(this.max>0&&this.size===this.max&&this.evict(!0),n=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t},++this.size===1?this.first=n:this.last.next=n,this.last=n),this}values(e=this.keys()){return e.map(t=>this.get(t))}}function ug(i=1e3,e=0,t=!1){if(isNaN(i)||i<0)throw new TypeError("Invalid max value");if(isNaN(e)||e<0)throw new TypeError("Invalid ttl value");if(typeof t!="boolean")throw new TypeError("Invalid resetTtl value");return new RC(i,e,t)}const MC=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function Kr(i){const e=typeof i.fontSize=="number"?`${i.fontSize}px`:i.fontSize;let t=i.fontFamily;Array.isArray(i.fontFamily)||(t=i.fontFamily.split(","));for(let s=t.length-1;s>=0;s--){let r=t[s].trim();!/([\"\'])[^\'\"]+\1/.test(r)&&!MC.includes(r)&&(r=`"${r}"`),t[s]=r}return`${i.fontStyle} ${i.fontVariant} ${i.fontWeight} ${e} ${t.join(",")}`}const Hu={willReadFrequently:!0},pt=class z{static get experimentalLetterSpacingSupported(){let e=z._experimentalLetterSpacingSupported;if(e===void 0){const t=Y.get().getCanvasRenderingContext2D().prototype;e=z._experimentalLetterSpacingSupported="letterSpacing"in t||"textLetterSpacing"in t}return e}constructor(e,t,s,r,n,o,a,l,c){this.text=e,this.style=t,this.width=s,this.height=r,this.lines=n,this.lineWidths=o,this.lineHeight=a,this.maxLineWidth=l,this.fontProperties=c}static measureText(e=" ",t,s=z._canvas,r=t.wordWrap){const n=`${e}-${t.styleKey}-wordWrap-${r}`;if(z._measurementCache.has(n))return z._measurementCache.get(n);const o=Kr(t),a=z.measureFont(o);a.fontSize===0&&(a.fontSize=t.fontSize,a.ascent=t.fontSize);const l=z.__context;l.font=o;const h=(r?z._wordWrap(e,t,s):e).split(/(?:\r\n|\r|\n)/),u=new Array(h.length);let d=0;for(let _=0;_<h.length;_++){const y=z._measureText(h[_],t.letterSpacing,l);u[_]=y,d=Math.max(d,y)}const f=t._stroke?.width||0;let p=d+f;t.dropShadow&&(p+=t.dropShadow.distance);const g=t.lineHeight||a.fontSize;let m=Math.max(g,a.fontSize+f)+(h.length-1)*(g+t.leading);t.dropShadow&&(m+=t.dropShadow.distance);const x=new z(e,t,p,m,h,u,g+t.leading,d,a);return z._measurementCache.set(n,x),x}static _measureText(e,t,s){let r=!1;z.experimentalLetterSpacingSupported&&(z.experimentalLetterSpacing?(s.letterSpacing=`${t}px`,s.textLetterSpacing=`${t}px`,r=!0):(s.letterSpacing="0px",s.textLetterSpacing="0px"));const n=s.measureText(e);let o=n.width;const a=-n.actualBoundingBoxLeft;let c=n.actualBoundingBoxRight-a;if(o>0)if(r)o-=t,c-=t;else{const h=(z.graphemeSegmenter(e).length-1)*t;o+=h,c+=h}return Math.max(o,c)}static _wordWrap(e,t,s=z._canvas){const r=s.getContext("2d",Hu);let n=0,o="",a="";const l=Object.create(null),{letterSpacing:c,whiteSpace:h}=t,u=z._collapseSpaces(h),d=z._collapseNewlines(h);let f=!u;const p=t.wordWrapWidth+c,g=z._tokenize(e);for(let m=0;m<g.length;m++){let x=g[m];if(z._isNewline(x)){if(!d){a+=z._addLine(o),f=!u,o="",n=0;continue}x=" "}if(u){const y=z.isBreakingSpace(x),v=z.isBreakingSpace(o[o.length-1]);if(y&&v)continue}const _=z._getFromCache(x,c,l,r);if(_>p)if(o!==""&&(a+=z._addLine(o),o="",n=0),z.canBreakWords(x,t.breakWords)){const y=z.wordWrapSplit(x);for(let v=0;v<y.length;v++){let T=y[v],S=T,w=1;for(;y[v+w];){const P=y[v+w];if(!z.canBreakChars(S,P,x,v,t.breakWords))T+=P;else break;S=P,w++}v+=w-1;const E=z._getFromCache(T,c,l,r);E+n>p&&(a+=z._addLine(o),f=!1,o="",n=0),o+=T,n+=E}}else{o.length>0&&(a+=z._addLine(o),o="",n=0);const y=m===g.length-1;a+=z._addLine(x,!y),f=!1,o="",n=0}else _+n>p&&(f=!1,a+=z._addLine(o),o="",n=0),(o.length>0||!z.isBreakingSpace(x)||f)&&(o+=x,n+=_)}return a+=z._addLine(o,!1),a}static _addLine(e,t=!0){return e=z._trimRight(e),e=t?`${e}
|
|
101
101
|
`:e,e}static _getFromCache(e,t,s,r){let n=s[e];return typeof n!="number"&&(n=z._measureText(e,t,r)+t,s[e]=n),n}static _collapseSpaces(e){return e==="normal"||e==="pre-line"}static _collapseNewlines(e){return e==="normal"}static _trimRight(e){if(typeof e!="string")return"";for(let t=e.length-1;t>=0;t--){const s=e[t];if(!z.isBreakingSpace(s))break;e=e.slice(0,-1)}return e}static _isNewline(e){return typeof e!="string"?!1:z._newlines.includes(e.charCodeAt(0))}static isBreakingSpace(e,t){return typeof e!="string"?!1:z._breakingSpaces.includes(e.charCodeAt(0))}static _tokenize(e){const t=[];let s="";if(typeof e!="string")return t;for(let r=0;r<e.length;r++){const n=e[r],o=e[r+1];if(z.isBreakingSpace(n,o)||z._isNewline(n)){s!==""&&(t.push(s),s=""),n==="\r"&&o===`
|
|
102
102
|
`?(t.push(`\r
|
|
103
|
-
`),r++):t.push(n);continue}s+=n}return s!==""&&t.push(s),t}static canBreakWords(e,t){return t}static canBreakChars(e,t,s,r,n){return!0}static wordWrapSplit(e){return z.graphemeSegmenter(e)}static measureFont(e){if(z._fonts[e])return z._fonts[e];const t=z._context;t.font=e;const s=t.measureText(z.METRICS_STRING+z.BASELINE_SYMBOL),r={ascent:s.actualBoundingBoxAscent,descent:s.actualBoundingBoxDescent,fontSize:s.actualBoundingBoxAscent+s.actualBoundingBoxDescent};return z._fonts[e]=r,r}static clearMetrics(e=""){e?delete z._fonts[e]:z._fonts={}}static get _canvas(){if(!z.__canvas){let e;try{const t=new OffscreenCanvas(0,0);if(t.getContext("2d",Hu)?.measureText)return z.__canvas=t,t;e=Y.get().createCanvas()}catch{e=Y.get().createCanvas()}e.width=e.height=10,z.__canvas=e}return z.__canvas}static get _context(){return z.__context||(z.__context=z._canvas.getContext("2d",Hu)),z.__context}};pt.METRICS_STRING="|ÉqÅ",pt.BASELINE_SYMBOL="M",pt.BASELINE_MULTIPLIER=1.4,pt.HEIGHT_MULTIPLIER=2,pt.graphemeSegmenter=(()=>{if(typeof Intl?.Segmenter=="function"){const i=new Intl.Segmenter;return e=>{const t=i.segment(e),s=[];let r=0;for(const n of t)s[r++]=n.segment;return s}}return i=>[...i]})(),pt.experimentalLetterSpacing=!1,pt._fonts={},pt._newlines=[10,13],pt._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],pt._measurementCache=ug(1e3);let $e=pt;const dg=[{offset:0,color:"white"},{offset:1,color:"black"}],Wu=class cf{constructor(...e){this.uid=he("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=kC(e);t={...t.type==="radial"?cf.defaultRadialOptions:cf.defaultLinearOptions,...Np(t)},this._textureSize=t.textureSize,this._wrapMode=t.wrapMode,t.type==="radial"?(this.center=t.center,this.outerCenter=t.outerCenter??this.center,this.innerRadius=t.innerRadius,this.outerRadius=t.outerRadius,this.scale=t.scale,this.rotation=t.rotation):(this.start=t.start,this.end=t.end),this.textureSpace=t.textureSpace,this.type=t.type,t.colorStops.forEach(r=>{this.addColorStop(r.offset,r.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:ue.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:s,y:r}=this.end,n=s-e,o=r-t;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const m=e;e=s,s=m,n*=-1}if(o<0){const m=t;t=r,r=m,o*=-1}}const l=this.colorStops.length?this.colorStops:dg,c=this._textureSize,{canvas:h,context:u}=pg(c,1),d=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);fg(d,l),u.fillStyle=d,u.fillRect(0,0,c,1),this.texture=new M({source:new Ct({resource:h,addressMode:this._wrapMode})});const f=Math.sqrt(n*n+o*o),p=Math.atan2(o,n),g=new O;g.scale(f/c,1),g.rotate(p),g.translate(e,t),this.textureSpace==="local"&&g.scale(c,c),this.transform=g}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:dg,t=this._textureSize,{canvas:s,context:r}=pg(t,t),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,c=this.innerRadius,h=this.outerRadius,u=a-h,d=l-h,f=t/(h*2),p=(n-u)*f,g=(o-d)*f,m=r.createRadialGradient(p,g,c*f,(a-u)*f,(l-d)*f,h*f);fg(m,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=m,r.translate(p,g),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-p,-g),r.fillRect(0,0,t,t),this.texture=new M({source:new Ct({resource:s,addressMode:this._wrapMode})});const _=new O;_.scale(1/f,1/f),_.translate(u,d),this.textureSpace==="local"&&_.scale(t,t),this.transform=_}destroy(){this.texture?.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};Wu.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},Wu.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let at=Wu;function fg(i,e){for(let t=0;t<e.length;t++){const s=e[t];i.addColorStop(s.offset,s.color)}}function pg(i,e){const t=Y.get().createCanvas(i,e),s=t.getContext("2d");return{canvas:t,context:s}}function kC(i){let e=i[0]??{};return(typeof e=="number"||i[1])&&(W("8.5.2","use options object instead"),e={type:"linear",start:{x:i[0],y:i[1]},end:{x:i[2],y:i[3]},textureSpace:i[4],textureSize:i[5]??at.defaultLinearOptions.textureSize}),e}const mg={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class jr{constructor(e,t){this.uid=he("fillPattern"),this._tick=0,this.transform=new O,this.texture=e,this.transform.scale(1/e.frame.width,1/e.frame.height),t&&(e.source.style.addressModeU=mg[t].addressModeU,e.source.style.addressModeV=mg[t].addressModeV)}setTransform(e){const t=this.texture;this.transform.copyFrom(e),this.transform.invert(),this.transform.scale(1/t.frame.width,1/t.frame.height),this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}var Vu,gg;function FC(){if(gg)return Vu;gg=1,Vu=t;var i={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},e=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function t(n){var o=[];return n.replace(e,function(a,l,c){var h=l.toLowerCase();for(c=r(c),h=="m"&&c.length>2&&(o.push([l].concat(c.splice(0,2))),h="l",l=l=="m"?"l":"L");;){if(c.length==i[h])return c.unshift(l),o.push(c);if(c.length<i[h])throw new Error("malformed path data");o.push([l].concat(c.splice(0,i[h])))}}),o}var s=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function r(n){var o=n.match(s);return o?o.map(Number):[]}return Vu}var BC=FC();const UC=eu(BC);function OC(i,e){const t=UC(i),s=[];let r=null,n=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],c=l[0],h=l;switch(c){case"M":n=h[1],o=h[2],e.moveTo(n,o);break;case"m":n+=h[1],o+=h[2],e.moveTo(n,o);break;case"H":n=h[1],e.lineTo(n,o);break;case"h":n+=h[1],e.lineTo(n,o);break;case"V":o=h[1],e.lineTo(n,o);break;case"v":o+=h[1],e.lineTo(n,o);break;case"L":n=h[1],o=h[2],e.lineTo(n,o);break;case"l":n+=h[1],o+=h[2],e.lineTo(n,o);break;case"C":n=h[5],o=h[6],e.bezierCurveTo(h[1],h[2],h[3],h[4],n,o);break;case"c":e.bezierCurveTo(n+h[1],o+h[2],n+h[3],o+h[4],n+h[5],o+h[6]),n+=h[5],o+=h[6];break;case"S":n=h[3],o=h[4],e.bezierCurveToShort(h[1],h[2],n,o);break;case"s":e.bezierCurveToShort(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"Q":n=h[3],o=h[4],e.quadraticCurveTo(h[1],h[2],n,o);break;case"q":e.quadraticCurveTo(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"T":n=h[1],o=h[2],e.quadraticCurveToShort(n,o);break;case"t":n+=h[1],o+=h[2],e.quadraticCurveToShort(n,o);break;case"A":n=h[6],o=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"a":n+=h[6],o+=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"Z":case"z":e.closePath(),s.length>0&&(r=s.pop(),r?(n=r.startX,o=r.startY):(n=0,o=0)),r=null;break;default:L(`Unknown SVG path command: ${c}`)}c!=="Z"&&c!=="z"&&r===null&&(r={startX:n,startY:o},s.push(r))}return e}class Zr{constructor(e=0,t=0,s=0){this.type="circle",this.x=e,this.y=t,this.radius=s}clone(){return new Zr(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const s=this.radius*this.radius;let r=this.x-e,n=this.y-t;return r*=r,n*=n,r+n<=s}strokeContains(e,t,s,r=.5){if(this.radius===0)return!1;const n=this.x-e,o=this.y-t,a=this.radius,l=(1-r)*s,c=Math.sqrt(n*n+o*o);return c<=a+l&&c>a-(s-l)}getBounds(e){return e||(e=new H),e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class $u{constructor(e=0,t=0,s=0,r=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=s,this.halfHeight=r}clone(){return new $u(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let s=(e-this.x)/this.halfWidth,r=(t-this.y)/this.halfHeight;return s*=s,r*=r,s+r<=1}strokeContains(e,t,s,r=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=s*(1-r),l=s-a,c=n-l,h=o-l,u=n+a,d=o+a,f=e-this.x,p=t-this.y,g=f*f/(c*c)+p*p/(h*h),m=f*f/(u*u)+p*p/(d*d);return g>1&&m<=1}getBounds(e){return e||(e=new H),e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function DC(i,e,t,s,r,n){const o=i-t,a=e-s,l=r-t,c=n-s,h=o*l+a*c,u=l*l+c*c;let d=-1;u!==0&&(d=h/u);let f,p;d<0?(f=t,p=s):d>1?(f=r,p=n):(f=t+d*l,p=s+d*c);const g=i-f,m=e-p;return g*g+m*m}let GC,zC;class Es{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const s=[];for(let r=0,n=t.length;r<n;r++)s.push(t[r].x,t[r].y);t=s}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,s=t.length;for(let r=0;r<s;r+=2){const n=t[r],o=t[r+1],a=t[(r+2)%s],l=t[(r+3)%s];e+=(a-n)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(GC),s=e.getBounds(zC);if(!t.containsRect(s))return!1;const r=e.points;for(let n=0;n<r.length;n+=2){const o=r[n],a=r[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new Es(e);return t.closePath=this.closePath,t}contains(e,t){let s=!1;const r=this.points.length/2;for(let n=0,o=r-1;n<r;o=n++){const a=this.points[n*2],l=this.points[n*2+1],c=this.points[o*2],h=this.points[o*2+1];l>t!=h>t&&e<(c-a)*((t-l)/(h-l))+a&&(s=!s)}return s}strokeContains(e,t,s,r=.5){const n=s*s,o=n*(1-r),a=n-o,{points:l}=this,c=l.length-(this.closePath?0:2);for(let h=0;h<c;h+=2){const u=l[h],d=l[h+1],f=l[(h+2)%l.length],p=l[(h+3)%l.length],g=DC(e,t,u,d,f,p),m=Math.sign((f-u)*(t-d)-(p-d)*(e-u));if(g<=(m<0?a:o))return!0}return!1}getBounds(e){e||(e=new H);const t=this.points;let s=1/0,r=-1/0,n=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const c=t[a],h=t[a+1];s=c<s?c:s,r=c>r?c:r,n=h<n?h:n,o=h>o?h:o}return e.x=s,e.width=r-s,e.y=n,e.height=o-n,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return W("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return W("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const Jr=(i,e,t,s,r,n,o)=>{const a=i-t,l=e-s,c=Math.sqrt(a*a+l*l);return c>=r-n&&c<=r+o};class Xu{constructor(e=0,t=0,s=0,r=0,n=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=s,this.height=r,this.radius=n}getBounds(e){return e||(e=new H),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new Xu(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){const s=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+s&&t<=this.y+this.height-s||e>=this.x+s&&e<=this.x+this.width-s)return!0;let r=e-(this.x+s),n=t-(this.y+s);const o=s*s;if(r*r+n*n<=o||(r=e-(this.x+this.width-s),r*r+n*n<=o)||(n=t-(this.y+this.height-s),r*r+n*n<=o)||(r=e-(this.x+s),r*r+n*n<=o))return!0}return!1}strokeContains(e,t,s,r=.5){const{x:n,y:o,width:a,height:l,radius:c}=this,h=s*(1-r),u=s-h,d=n+c,f=o+c,p=a-c*2,g=l-c*2,m=n+a,_=o+l;return(e>=n-h&&e<=n+u||e>=m-u&&e<=m+h)&&t>=f&&t<=f+g||(t>=o-h&&t<=o+u||t>=_-u&&t<=_+h)&&e>=d&&e<=d+p?!0:e<d&&t<f&&Jr(e,t,d,f,c,u,h)||e>m-c&&t<f&&Jr(e,t,m-c,f,c,u,h)||e>m-c&&t>_-c&&Jr(e,t,m-c,_-c,c,u,h)||e<d&&t>_-c&&Jr(e,t,d,_-c,c,u,h)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const _g={};function Yu(i,e,t){let s=2166136261;for(let r=0;r<e;r++)s^=i[r].uid,s=Math.imul(s,16777619),s>>>=0;return _g[s]||NC(i,e,s,t)}function NC(i,e,t,s){const r={};let n=0;for(let a=0;a<s;a++){const l=a<e?i[a]:M.EMPTY.source;r[n++]=l.source,r[n++]=l.style}const o=new Ot(r);return _g[t]=o,o}class Ni{constructor(e){typeof e=="number"?this.rawBinaryData=new ArrayBuffer(e):e instanceof Uint8Array?this.rawBinaryData=e.buffer:this.rawBinaryData=e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${e} isn't a valid view type`)}}}function qu(i,e){const t=i.byteLength/8|0,s=new Float64Array(i,0,t);new Float64Array(e,0,t).set(s);const n=i.byteLength-t*8;if(n>0){const o=new Uint8Array(i,t*8,n);new Uint8Array(e,t*8,n).set(o)}}const LC={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var be=(i=>(i[i.DISABLED=0]="DISABLED",i[i.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",i[i.MASK_ACTIVE=2]="MASK_ACTIVE",i[i.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",i[i.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",i[i.NONE=5]="NONE",i))(be||{});function Is(i,e){return e.alphaMode==="no-premultiply-alpha"&&LC[i]||i}const HC=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
103
|
+
`),r++):t.push(n);continue}s+=n}return s!==""&&t.push(s),t}static canBreakWords(e,t){return t}static canBreakChars(e,t,s,r,n){return!0}static wordWrapSplit(e){return z.graphemeSegmenter(e)}static measureFont(e){if(z._fonts[e])return z._fonts[e];const t=z._context;t.font=e;const s=t.measureText(z.METRICS_STRING+z.BASELINE_SYMBOL),r={ascent:s.actualBoundingBoxAscent,descent:s.actualBoundingBoxDescent,fontSize:s.actualBoundingBoxAscent+s.actualBoundingBoxDescent};return z._fonts[e]=r,r}static clearMetrics(e=""){e?delete z._fonts[e]:z._fonts={}}static get _canvas(){if(!z.__canvas){let e;try{const t=new OffscreenCanvas(0,0);if(t.getContext("2d",Hu)?.measureText)return z.__canvas=t,t;e=Y.get().createCanvas()}catch{e=Y.get().createCanvas()}e.width=e.height=10,z.__canvas=e}return z.__canvas}static get _context(){return z.__context||(z.__context=z._canvas.getContext("2d",Hu)),z.__context}};pt.METRICS_STRING="|ÉqÅ",pt.BASELINE_SYMBOL="M",pt.BASELINE_MULTIPLIER=1.4,pt.HEIGHT_MULTIPLIER=2,pt.graphemeSegmenter=(()=>{if(typeof Intl?.Segmenter=="function"){const i=new Intl.Segmenter;return e=>{const t=i.segment(e),s=[];let r=0;for(const n of t)s[r++]=n.segment;return s}}return i=>[...i]})(),pt.experimentalLetterSpacing=!1,pt._fonts={},pt._newlines=[10,13],pt._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],pt._measurementCache=ug(1e3);let $e=pt;const dg=[{offset:0,color:"white"},{offset:1,color:"black"}],Wu=class cf{constructor(...e){this.uid=he("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=kC(e);t={...t.type==="radial"?cf.defaultRadialOptions:cf.defaultLinearOptions,...Np(t)},this._textureSize=t.textureSize,this._wrapMode=t.wrapMode,t.type==="radial"?(this.center=t.center,this.outerCenter=t.outerCenter??this.center,this.innerRadius=t.innerRadius,this.outerRadius=t.outerRadius,this.scale=t.scale,this.rotation=t.rotation):(this.start=t.start,this.end=t.end),this.textureSpace=t.textureSpace,this.type=t.type,t.colorStops.forEach(r=>{this.addColorStop(r.offset,r.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:ue.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:s,y:r}=this.end,n=s-e,o=r-t;const a=n<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(n<0){const m=e;e=s,s=m,n*=-1}if(o<0){const m=t;t=r,r=m,o*=-1}}const l=this.colorStops.length?this.colorStops:dg,c=this._textureSize,{canvas:h,context:u}=pg(c,1),d=a?u.createLinearGradient(this._textureSize,0,0,0):u.createLinearGradient(0,0,this._textureSize,0);fg(d,l),u.fillStyle=d,u.fillRect(0,0,c,1),this.texture=new M({source:new Ct({resource:h,addressMode:this._wrapMode})});const f=Math.sqrt(n*n+o*o),p=Math.atan2(o,n),g=new O;g.scale(f/c,1),g.rotate(p),g.translate(e,t),this.textureSpace==="local"&&g.scale(c,c),this.transform=g}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:dg,t=this._textureSize,{canvas:s,context:r}=pg(t,t),{x:n,y:o}=this.center,{x:a,y:l}=this.outerCenter,c=this.innerRadius,h=this.outerRadius,u=a-h,d=l-h,f=t/(h*2),p=(n-u)*f,g=(o-d)*f,m=r.createRadialGradient(p,g,c*f,(a-u)*f,(l-d)*f,h*f);fg(m,e),r.fillStyle=e[e.length-1].color,r.fillRect(0,0,t,t),r.fillStyle=m,r.translate(p,g),r.rotate(this.rotation),r.scale(1,this.scale),r.translate(-p,-g),r.fillRect(0,0,t,t),this.texture=new M({source:new Ct({resource:s,addressMode:this._wrapMode})});const x=new O;x.scale(1/f,1/f),x.translate(u,d),this.textureSpace==="local"&&x.scale(t,t),this.transform=x}destroy(){this.texture?.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};Wu.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},Wu.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let at=Wu;function fg(i,e){for(let t=0;t<e.length;t++){const s=e[t];i.addColorStop(s.offset,s.color)}}function pg(i,e){const t=Y.get().createCanvas(i,e),s=t.getContext("2d");return{canvas:t,context:s}}function kC(i){let e=i[0]??{};return(typeof e=="number"||i[1])&&(W("8.5.2","use options object instead"),e={type:"linear",start:{x:i[0],y:i[1]},end:{x:i[2],y:i[3]},textureSpace:i[4],textureSize:i[5]??at.defaultLinearOptions.textureSize}),e}const mg={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class jr{constructor(e,t){this.uid=he("fillPattern"),this._tick=0,this.transform=new O,this.texture=e,this.transform.scale(1/e.frame.width,1/e.frame.height),t&&(e.source.style.addressModeU=mg[t].addressModeU,e.source.style.addressModeV=mg[t].addressModeV)}setTransform(e){const t=this.texture;this.transform.copyFrom(e),this.transform.invert(),this.transform.scale(1/t.frame.width,1/t.frame.height),this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}var Vu,gg;function FC(){if(gg)return Vu;gg=1,Vu=t;var i={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},e=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function t(n){var o=[];return n.replace(e,function(a,l,c){var h=l.toLowerCase();for(c=r(c),h=="m"&&c.length>2&&(o.push([l].concat(c.splice(0,2))),h="l",l=l=="m"?"l":"L");;){if(c.length==i[h])return c.unshift(l),o.push(c);if(c.length<i[h])throw new Error("malformed path data");o.push([l].concat(c.splice(0,i[h])))}}),o}var s=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function r(n){var o=n.match(s);return o?o.map(Number):[]}return Vu}var BC=FC();const UC=eu(BC);function OC(i,e){const t=UC(i),s=[];let r=null,n=0,o=0;for(let a=0;a<t.length;a++){const l=t[a],c=l[0],h=l;switch(c){case"M":n=h[1],o=h[2],e.moveTo(n,o);break;case"m":n+=h[1],o+=h[2],e.moveTo(n,o);break;case"H":n=h[1],e.lineTo(n,o);break;case"h":n+=h[1],e.lineTo(n,o);break;case"V":o=h[1],e.lineTo(n,o);break;case"v":o+=h[1],e.lineTo(n,o);break;case"L":n=h[1],o=h[2],e.lineTo(n,o);break;case"l":n+=h[1],o+=h[2],e.lineTo(n,o);break;case"C":n=h[5],o=h[6],e.bezierCurveTo(h[1],h[2],h[3],h[4],n,o);break;case"c":e.bezierCurveTo(n+h[1],o+h[2],n+h[3],o+h[4],n+h[5],o+h[6]),n+=h[5],o+=h[6];break;case"S":n=h[3],o=h[4],e.bezierCurveToShort(h[1],h[2],n,o);break;case"s":e.bezierCurveToShort(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"Q":n=h[3],o=h[4],e.quadraticCurveTo(h[1],h[2],n,o);break;case"q":e.quadraticCurveTo(n+h[1],o+h[2],n+h[3],o+h[4]),n+=h[3],o+=h[4];break;case"T":n=h[1],o=h[2],e.quadraticCurveToShort(n,o);break;case"t":n+=h[1],o+=h[2],e.quadraticCurveToShort(n,o);break;case"A":n=h[6],o=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"a":n+=h[6],o+=h[7],e.arcToSvg(h[1],h[2],h[3],h[4],h[5],n,o);break;case"Z":case"z":e.closePath(),s.length>0&&(r=s.pop(),r?(n=r.startX,o=r.startY):(n=0,o=0)),r=null;break;default:L(`Unknown SVG path command: ${c}`)}c!=="Z"&&c!=="z"&&r===null&&(r={startX:n,startY:o},s.push(r))}return e}class Zr{constructor(e=0,t=0,s=0){this.type="circle",this.x=e,this.y=t,this.radius=s}clone(){return new Zr(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const s=this.radius*this.radius;let r=this.x-e,n=this.y-t;return r*=r,n*=n,r+n<=s}strokeContains(e,t,s,r=.5){if(this.radius===0)return!1;const n=this.x-e,o=this.y-t,a=this.radius,l=(1-r)*s,c=Math.sqrt(n*n+o*o);return c<=a+l&&c>a-(s-l)}getBounds(e){return e||(e=new H),e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class $u{constructor(e=0,t=0,s=0,r=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=s,this.halfHeight=r}clone(){return new $u(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let s=(e-this.x)/this.halfWidth,r=(t-this.y)/this.halfHeight;return s*=s,r*=r,s+r<=1}strokeContains(e,t,s,r=.5){const{halfWidth:n,halfHeight:o}=this;if(n<=0||o<=0)return!1;const a=s*(1-r),l=s-a,c=n-l,h=o-l,u=n+a,d=o+a,f=e-this.x,p=t-this.y,g=f*f/(c*c)+p*p/(h*h),m=f*f/(u*u)+p*p/(d*d);return g>1&&m<=1}getBounds(e){return e||(e=new H),e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function DC(i,e,t,s,r,n){const o=i-t,a=e-s,l=r-t,c=n-s,h=o*l+a*c,u=l*l+c*c;let d=-1;u!==0&&(d=h/u);let f,p;d<0?(f=t,p=s):d>1?(f=r,p=n):(f=t+d*l,p=s+d*c);const g=i-f,m=e-p;return g*g+m*m}let GC,zC;class Es{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const s=[];for(let r=0,n=t.length;r<n;r++)s.push(t[r].x,t[r].y);t=s}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,s=t.length;for(let r=0;r<s;r+=2){const n=t[r],o=t[r+1],a=t[(r+2)%s],l=t[(r+3)%s];e+=(a-n)*(l+o)}return e<0}containsPolygon(e){const t=this.getBounds(GC),s=e.getBounds(zC);if(!t.containsRect(s))return!1;const r=e.points;for(let n=0;n<r.length;n+=2){const o=r[n],a=r[n+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new Es(e);return t.closePath=this.closePath,t}contains(e,t){let s=!1;const r=this.points.length/2;for(let n=0,o=r-1;n<r;o=n++){const a=this.points[n*2],l=this.points[n*2+1],c=this.points[o*2],h=this.points[o*2+1];l>t!=h>t&&e<(c-a)*((t-l)/(h-l))+a&&(s=!s)}return s}strokeContains(e,t,s,r=.5){const n=s*s,o=n*(1-r),a=n-o,{points:l}=this,c=l.length-(this.closePath?0:2);for(let h=0;h<c;h+=2){const u=l[h],d=l[h+1],f=l[(h+2)%l.length],p=l[(h+3)%l.length],g=DC(e,t,u,d,f,p),m=Math.sign((f-u)*(t-d)-(p-d)*(e-u));if(g<=(m<0?a:o))return!0}return!1}getBounds(e){e||(e=new H);const t=this.points;let s=1/0,r=-1/0,n=1/0,o=-1/0;for(let a=0,l=t.length;a<l;a+=2){const c=t[a],h=t[a+1];s=c<s?c:s,r=c>r?c:r,n=h<n?h:n,o=h>o?h:o}return e.x=s,e.width=r-s,e.y=n,e.height=o-n,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return W("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return W("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const Jr=(i,e,t,s,r,n,o)=>{const a=i-t,l=e-s,c=Math.sqrt(a*a+l*l);return c>=r-n&&c<=r+o};class Xu{constructor(e=0,t=0,s=0,r=0,n=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=s,this.height=r,this.radius=n}getBounds(e){return e||(e=new H),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new Xu(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){const s=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+s&&t<=this.y+this.height-s||e>=this.x+s&&e<=this.x+this.width-s)return!0;let r=e-(this.x+s),n=t-(this.y+s);const o=s*s;if(r*r+n*n<=o||(r=e-(this.x+this.width-s),r*r+n*n<=o)||(n=t-(this.y+this.height-s),r*r+n*n<=o)||(r=e-(this.x+s),r*r+n*n<=o))return!0}return!1}strokeContains(e,t,s,r=.5){const{x:n,y:o,width:a,height:l,radius:c}=this,h=s*(1-r),u=s-h,d=n+c,f=o+c,p=a-c*2,g=l-c*2,m=n+a,x=o+l;return(e>=n-h&&e<=n+u||e>=m-u&&e<=m+h)&&t>=f&&t<=f+g||(t>=o-h&&t<=o+u||t>=x-u&&t<=x+h)&&e>=d&&e<=d+p?!0:e<d&&t<f&&Jr(e,t,d,f,c,u,h)||e>m-c&&t<f&&Jr(e,t,m-c,f,c,u,h)||e>m-c&&t>x-c&&Jr(e,t,m-c,x-c,c,u,h)||e<d&&t>x-c&&Jr(e,t,d,x-c,c,u,h)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const xg={};function Yu(i,e,t){let s=2166136261;for(let r=0;r<e;r++)s^=i[r].uid,s=Math.imul(s,16777619),s>>>=0;return xg[s]||NC(i,e,s,t)}function NC(i,e,t,s){const r={};let n=0;for(let a=0;a<s;a++){const l=a<e?i[a]:M.EMPTY.source;r[n++]=l.source,r[n++]=l.style}const o=new Ot(r);return xg[t]=o,o}class Ni{constructor(e){typeof e=="number"?this.rawBinaryData=new ArrayBuffer(e):e instanceof Uint8Array?this.rawBinaryData=e.buffer:this.rawBinaryData=e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${e} isn't a valid view type`)}}}function qu(i,e){const t=i.byteLength/8|0,s=new Float64Array(i,0,t);new Float64Array(e,0,t).set(s);const n=i.byteLength-t*8;if(n>0){const o=new Uint8Array(i,t*8,n);new Uint8Array(e,t*8,n).set(o)}}const LC={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var be=(i=>(i[i.DISABLED=0]="DISABLED",i[i.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",i[i.MASK_ACTIVE=2]="MASK_ACTIVE",i[i.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",i[i.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",i[i.NONE=5]="NONE",i))(be||{});function Is(i,e){return e.alphaMode==="no-premultiply-alpha"&&LC[i]||i}const HC=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
104
104
|
`);function WC(i){let e="";for(let t=0;t<i;++t)t>0&&(e+=`
|
|
105
|
-
else `),t<i-1&&(e+=`if(test == ${t}.0){}`);return e}function xg(i,e){if(i===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const s=HC.replace(/%forloop%/gi,WC(i));if(e.shaderSource(t,s),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))i=i/2|0;else break}}finally{e.deleteShader(t)}return i}let Li=null;function VC(){if(Li)return Li;const i=Wm();return Li=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),Li=xg(Li,i),i.getExtension("WEBGL_lose_context")?.loseContext(),Li}class $C{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){const t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}class XC{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new $C,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null}}const Ps=[];let Qr=0;Bi.register({clear:()=>{if(Ps.length>0)for(const i of Ps)i&&i.destroy();Ps.length=0,Qr=0}});function yg(){return Qr>0?Ps[--Qr]:new XC}function vg(i){Ps[Qr++]=i}let Rs=0;const bg=class iy{constructor(e){this.uid=he("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...iy.defaultOptions,...e},e.maxTextures||(W("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=VC());const{maxTextures:t,attributesInitialSize:s,indicesInitialSize:r}=e;this.attributeBuffer=new Ni(s*4),this.indexBuffer=new Uint16Array(r),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)vg(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){const s=e._batch.textures.ids[t._source.uid];return!s&&s!==0?!1:(e._textureId=s,e.texture=t,!0)}updateElement(e){this.dirty=!0;const t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){const t=this._elements;if(!t[this.elementStart])return;let s=yg(),r=s.textures;r.clear();const n=t[this.elementStart];let o=Is(n.blendMode,n.texture._source),a=n.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const l=this.attributeBuffer.float32View,c=this.attributeBuffer.uint32View,h=this.indexBuffer;let u=this._batchIndexSize,d=this._batchIndexStart,f="startBatch";const p=this.maxTextures;for(let g=this.elementStart;g<this.elementSize;++g){const m=t[g];t[g]=null;const x=m.texture._source,y=Is(m.blendMode,x),v=o!==y||a!==m.topology;if(x._batchTick===Rs&&!v){m._textureId=x._textureBindLocation,u+=m.indexSize,m.packAsQuad?(this.packQuadAttributes(m,l,c,m._attributeStart,m._textureId),this.packQuadIndex(h,m._indexStart,m._attributeStart/this.vertexSize)):(this.packAttributes(m,l,c,m._attributeStart,m._textureId),this.packIndex(m,h,m._indexStart,m._attributeStart/this.vertexSize)),m._batch=s;continue}x._batchTick=Rs,(r.count>=p||v)&&(this._finishBatch(s,d,u-d,r,o,a,e,f),f="renderBatch",d=u,o=y,a=m.topology,s=yg(),r=s.textures,r.clear(),++Rs),m._textureId=x._textureBindLocation=r.count,r.ids[x.uid]=r.count,r.textures[r.count++]=x,m._batch=s,u+=m.indexSize,m.packAsQuad?(this.packQuadAttributes(m,l,c,m._attributeStart,m._textureId),this.packQuadIndex(h,m._indexStart,m._attributeStart/this.vertexSize)):(this.packAttributes(m,l,c,m._attributeStart,m._textureId),this.packIndex(m,h,m._indexStart,m._attributeStart/this.vertexSize))}r.count>0&&(this._finishBatch(s,d,u-d,r,o,a,e,f),d=u,++Rs),this.elementStart=this.elementSize,this._batchIndexStart=d,this._batchIndexSize=u}_finishBatch(e,t,s,r,n,o,a,l){e.gpuBindGroup=null,e.bindGroup=null,e.action=l,e.batcher=this,e.textures=r,e.blendMode=n,e.topology=o,e.start=t,e.size=s,++Rs,this.batches[this.batchIndex++]=e,a.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){const t=Math.max(e,this.attributeBuffer.size*2),s=new Ni(t);qu(this.attributeBuffer.rawBinaryData,s.rawBinaryData),this.attributeBuffer=s}_resizeIndexBuffer(e){const t=this.indexBuffer;let s=Math.max(e,t.length*1.5);s+=s%2;const r=s>65535?new Uint32Array(s):new Uint16Array(s);if(r.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let n=0;n<t.length;n++)r[n]=t[n];else qu(t.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(e,t,s){e[t]=s+0,e[t+1]=s+1,e[t+2]=s+2,e[t+3]=s+0,e[t+4]=s+2,e[t+5]=s+3}packIndex(e,t,s,r){const n=e.indices,o=e.indexSize,a=e.indexOffset,l=e.attributeOffset;for(let c=0;c<o;c++)t[s++]=r+n[c+a]-l}destroy(e={}){if(this.batches!==null){for(let t=0;t<this.batches.length;t++)vg(this.batches[t]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&(this.shader?.destroy(),this.shader=null);for(let t=0;t<this._elements.length;t++)this._elements[t]&&(this._elements[t]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};bg.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let YC=bg;var j=(i=>(i[i.MAP_READ=1]="MAP_READ",i[i.MAP_WRITE=2]="MAP_WRITE",i[i.COPY_SRC=4]="COPY_SRC",i[i.COPY_DST=8]="COPY_DST",i[i.INDEX=16]="INDEX",i[i.VERTEX=32]="VERTEX",i[i.UNIFORM=64]="UNIFORM",i[i.STORAGE=128]="STORAGE",i[i.INDIRECT=256]="INDIRECT",i[i.QUERY_RESOLVE=512]="QUERY_RESOLVE",i[i.STATIC=1024]="STATIC",i))(j||{});class tt extends je{constructor(e){let{data:t,size:s}=e;const{usage:r,label:n,shrinkToFit:o}=e;super(),this.uid=he("buffer"),this._resourceType="buffer",this._resourceId=he("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,s??(s=t?.byteLength);const a=!!t;this.descriptor={size:s,usage:r,mappedAtCreation:a,label:n},this.shrinkToFit=o??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&j.STATIC)}set static(e){e?this.descriptor.usage|=j.STATIC:this.descriptor.usage&=~j.STATIC}setDataWithSize(e,t,s){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._data===e){s&&this.emit("update",this);return}const r=this._data;if(this._data=e,this._dataInt32=null,!r||r.length!==e.length){!this.shrinkToFit&&r&&e.byteLength<r.byteLength?s&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=he("resource"),this.emit("change",this));return}s&&this.emit("update",this)}update(e){this._updateSize=e??this._updateSize,this._updateID++,this.emit("update",this)}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}}function Tg(i,e){if(!(i instanceof tt)){let t=e?j.INDEX:j.VERTEX;i instanceof Array&&(e?(i=new Uint32Array(i),t=j.INDEX|j.COPY_DST):(i=new Float32Array(i),t=j.VERTEX|j.COPY_DST)),i=new tt({data:i,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return i}function qC(i,e,t){const s=i.getAttribute(e);if(!s)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const r=s.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const c=r.BYTES_PER_ELEMENT,h=(s.offset||0)/c,u=(s.stride||8)/c;for(let d=h;d<r.length;d+=u){const f=r[d],p=r[d+1];f>a&&(a=f),p>l&&(l=p),f<n&&(n=f),p<o&&(o=p)}return t.minX=n,t.minY=o,t.maxX=a,t.maxY=l,t}function KC(i){return(i instanceof tt||Array.isArray(i)||i.BYTES_PER_ELEMENT)&&(i={buffer:i}),i.buffer=Tg(i.buffer,!1),i}class Ms extends je{constructor(e={}){super(),this.uid=he("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new De,this._boundsDirty=!0;const{attributes:t,indexBuffer:s,topology:r}=e;if(this.buffers=[],this.attributes={},t)for(const n in t)this.addAttribute(n,t[n]);this.instanceCount=e.instanceCount??1,s&&this.addIndex(s),this.topology=r||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}getSize(){for(const e in this.attributes){const t=this.attributes[e];return t.buffer.data.length/(t.stride/4||t.size)}return 0}addAttribute(e,t){const s=KC(t);this.buffers.indexOf(s.buffer)===-1&&(this.buffers.push(s.buffer),s.buffer.on("update",this.onBufferUpdate,this),s.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=s}addIndex(e){this.indexBuffer=Tg(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,qC(this,"aPosition",this._bounds)):this._bounds}destroy(e=!1){this.emit("destroy",this),this.removeAllListeners(),e&&this.buffers.forEach(t=>t.destroy()),this.indexBuffer?.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const jC=new Float32Array(1),ZC=new Uint32Array(1);class JC extends Ms{constructor(){const t=new tt({data:jC,label:"attribute-batch-buffer",usage:j.VERTEX|j.COPY_DST,shrinkToFit:!1}),s=new tt({data:ZC,label:"index-batch-buffer",usage:j.INDEX|j.COPY_DST,shrinkToFit:!1}),r=24;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:r,offset:0},aUV:{buffer:t,format:"float32x2",stride:r,offset:8},aColor:{buffer:t,format:"unorm8x4",stride:r,offset:16},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:r,offset:20}},indexBuffer:s})}}function wg(i,e,t){if(i)for(const s in i){const r=s.toLocaleLowerCase(),n=e[r];if(n){let o=i[s];s==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&n.push(`//----${t}----//`),n.push(o)}else L(`${s} placement hook does not exist in shader`)}}const QC=/\{\{(.*?)\}\}/g;function Sg(i){const e={};return(i.match(QC)?.map(s=>s.replace(/[{()}]/g,""))??[]).forEach(s=>{e[s]=[]}),e}function Cg(i,e){let t;const s=/@in\s+([^;]+);/g;for(;(t=s.exec(i))!==null;)e.push(t[1])}function Ag(i,e,t=!1){const s=[];Cg(e,s),i.forEach(a=>{a.header&&Cg(a.header,s)});const r=s;t&&r.sort();const n=r.map((a,l)=>` @location(${l}) ${a},`).join(`
|
|
105
|
+
else `),t<i-1&&(e+=`if(test == ${t}.0){}`);return e}function _g(i,e){if(i===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const s=HC.replace(/%forloop%/gi,WC(i));if(e.shaderSource(t,s),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))i=i/2|0;else break}}finally{e.deleteShader(t)}return i}let Li=null;function VC(){if(Li)return Li;const i=Wm();return Li=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),Li=_g(Li,i),i.getExtension("WEBGL_lose_context")?.loseContext(),Li}class $C{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){const t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}class XC{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new $C,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null}}const Ps=[];let Qr=0;Bi.register({clear:()=>{if(Ps.length>0)for(const i of Ps)i&&i.destroy();Ps.length=0,Qr=0}});function yg(){return Qr>0?Ps[--Qr]:new XC}function vg(i){Ps[Qr++]=i}let Rs=0;const bg=class iy{constructor(e){this.uid=he("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...iy.defaultOptions,...e},e.maxTextures||(W("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=VC());const{maxTextures:t,attributesInitialSize:s,indicesInitialSize:r}=e;this.attributeBuffer=new Ni(s*4),this.indexBuffer=new Uint16Array(r),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)vg(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){const s=e._batch.textures.ids[t._source.uid];return!s&&s!==0?!1:(e._textureId=s,e.texture=t,!0)}updateElement(e){this.dirty=!0;const t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){const t=this._elements;if(!t[this.elementStart])return;let s=yg(),r=s.textures;r.clear();const n=t[this.elementStart];let o=Is(n.blendMode,n.texture._source),a=n.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const l=this.attributeBuffer.float32View,c=this.attributeBuffer.uint32View,h=this.indexBuffer;let u=this._batchIndexSize,d=this._batchIndexStart,f="startBatch";const p=this.maxTextures;for(let g=this.elementStart;g<this.elementSize;++g){const m=t[g];t[g]=null;const _=m.texture._source,y=Is(m.blendMode,_),v=o!==y||a!==m.topology;if(_._batchTick===Rs&&!v){m._textureId=_._textureBindLocation,u+=m.indexSize,m.packAsQuad?(this.packQuadAttributes(m,l,c,m._attributeStart,m._textureId),this.packQuadIndex(h,m._indexStart,m._attributeStart/this.vertexSize)):(this.packAttributes(m,l,c,m._attributeStart,m._textureId),this.packIndex(m,h,m._indexStart,m._attributeStart/this.vertexSize)),m._batch=s;continue}_._batchTick=Rs,(r.count>=p||v)&&(this._finishBatch(s,d,u-d,r,o,a,e,f),f="renderBatch",d=u,o=y,a=m.topology,s=yg(),r=s.textures,r.clear(),++Rs),m._textureId=_._textureBindLocation=r.count,r.ids[_.uid]=r.count,r.textures[r.count++]=_,m._batch=s,u+=m.indexSize,m.packAsQuad?(this.packQuadAttributes(m,l,c,m._attributeStart,m._textureId),this.packQuadIndex(h,m._indexStart,m._attributeStart/this.vertexSize)):(this.packAttributes(m,l,c,m._attributeStart,m._textureId),this.packIndex(m,h,m._indexStart,m._attributeStart/this.vertexSize))}r.count>0&&(this._finishBatch(s,d,u-d,r,o,a,e,f),d=u,++Rs),this.elementStart=this.elementSize,this._batchIndexStart=d,this._batchIndexSize=u}_finishBatch(e,t,s,r,n,o,a,l){e.gpuBindGroup=null,e.bindGroup=null,e.action=l,e.batcher=this,e.textures=r,e.blendMode=n,e.topology=o,e.start=t,e.size=s,++Rs,this.batches[this.batchIndex++]=e,a.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){const t=Math.max(e,this.attributeBuffer.size*2),s=new Ni(t);qu(this.attributeBuffer.rawBinaryData,s.rawBinaryData),this.attributeBuffer=s}_resizeIndexBuffer(e){const t=this.indexBuffer;let s=Math.max(e,t.length*1.5);s+=s%2;const r=s>65535?new Uint32Array(s):new Uint16Array(s);if(r.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let n=0;n<t.length;n++)r[n]=t[n];else qu(t.buffer,r.buffer);this.indexBuffer=r}packQuadIndex(e,t,s){e[t]=s+0,e[t+1]=s+1,e[t+2]=s+2,e[t+3]=s+0,e[t+4]=s+2,e[t+5]=s+3}packIndex(e,t,s,r){const n=e.indices,o=e.indexSize,a=e.indexOffset,l=e.attributeOffset;for(let c=0;c<o;c++)t[s++]=r+n[c+a]-l}destroy(e={}){if(this.batches!==null){for(let t=0;t<this.batches.length;t++)vg(this.batches[t]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&(this.shader?.destroy(),this.shader=null);for(let t=0;t<this._elements.length;t++)this._elements[t]&&(this._elements[t]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};bg.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let YC=bg;var j=(i=>(i[i.MAP_READ=1]="MAP_READ",i[i.MAP_WRITE=2]="MAP_WRITE",i[i.COPY_SRC=4]="COPY_SRC",i[i.COPY_DST=8]="COPY_DST",i[i.INDEX=16]="INDEX",i[i.VERTEX=32]="VERTEX",i[i.UNIFORM=64]="UNIFORM",i[i.STORAGE=128]="STORAGE",i[i.INDIRECT=256]="INDIRECT",i[i.QUERY_RESOLVE=512]="QUERY_RESOLVE",i[i.STATIC=1024]="STATIC",i))(j||{});class tt extends je{constructor(e){let{data:t,size:s}=e;const{usage:r,label:n,shrinkToFit:o}=e;super(),this.uid=he("buffer"),this._resourceType="buffer",this._resourceId=he("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,s??(s=t?.byteLength);const a=!!t;this.descriptor={size:s,usage:r,mappedAtCreation:a,label:n},this.shrinkToFit=o??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&j.STATIC)}set static(e){e?this.descriptor.usage|=j.STATIC:this.descriptor.usage&=~j.STATIC}setDataWithSize(e,t,s){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._data===e){s&&this.emit("update",this);return}const r=this._data;if(this._data=e,this._dataInt32=null,!r||r.length!==e.length){!this.shrinkToFit&&r&&e.byteLength<r.byteLength?s&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=he("resource"),this.emit("change",this));return}s&&this.emit("update",this)}update(e){this._updateSize=e??this._updateSize,this._updateID++,this.emit("update",this)}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}}function Tg(i,e){if(!(i instanceof tt)){let t=e?j.INDEX:j.VERTEX;i instanceof Array&&(e?(i=new Uint32Array(i),t=j.INDEX|j.COPY_DST):(i=new Float32Array(i),t=j.VERTEX|j.COPY_DST)),i=new tt({data:i,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return i}function qC(i,e,t){const s=i.getAttribute(e);if(!s)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const r=s.buffer.data;let n=1/0,o=1/0,a=-1/0,l=-1/0;const c=r.BYTES_PER_ELEMENT,h=(s.offset||0)/c,u=(s.stride||8)/c;for(let d=h;d<r.length;d+=u){const f=r[d],p=r[d+1];f>a&&(a=f),p>l&&(l=p),f<n&&(n=f),p<o&&(o=p)}return t.minX=n,t.minY=o,t.maxX=a,t.maxY=l,t}function KC(i){return(i instanceof tt||Array.isArray(i)||i.BYTES_PER_ELEMENT)&&(i={buffer:i}),i.buffer=Tg(i.buffer,!1),i}class Ms extends je{constructor(e={}){super(),this.uid=he("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new De,this._boundsDirty=!0;const{attributes:t,indexBuffer:s,topology:r}=e;if(this.buffers=[],this.attributes={},t)for(const n in t)this.addAttribute(n,t[n]);this.instanceCount=e.instanceCount??1,s&&this.addIndex(s),this.topology=r||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}getSize(){for(const e in this.attributes){const t=this.attributes[e];return t.buffer.data.length/(t.stride/4||t.size)}return 0}addAttribute(e,t){const s=KC(t);this.buffers.indexOf(s.buffer)===-1&&(this.buffers.push(s.buffer),s.buffer.on("update",this.onBufferUpdate,this),s.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=s}addIndex(e){this.indexBuffer=Tg(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,qC(this,"aPosition",this._bounds)):this._bounds}destroy(e=!1){this.emit("destroy",this),this.removeAllListeners(),e&&this.buffers.forEach(t=>t.destroy()),this.indexBuffer?.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const jC=new Float32Array(1),ZC=new Uint32Array(1);class JC extends Ms{constructor(){const t=new tt({data:jC,label:"attribute-batch-buffer",usage:j.VERTEX|j.COPY_DST,shrinkToFit:!1}),s=new tt({data:ZC,label:"index-batch-buffer",usage:j.INDEX|j.COPY_DST,shrinkToFit:!1}),r=24;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:r,offset:0},aUV:{buffer:t,format:"float32x2",stride:r,offset:8},aColor:{buffer:t,format:"unorm8x4",stride:r,offset:16},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:r,offset:20}},indexBuffer:s})}}function wg(i,e,t){if(i)for(const s in i){const r=s.toLocaleLowerCase(),n=e[r];if(n){let o=i[s];s==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&n.push(`//----${t}----//`),n.push(o)}else L(`${s} placement hook does not exist in shader`)}}const QC=/\{\{(.*?)\}\}/g;function Sg(i){const e={};return(i.match(QC)?.map(s=>s.replace(/[{()}]/g,""))??[]).forEach(s=>{e[s]=[]}),e}function Cg(i,e){let t;const s=/@in\s+([^;]+);/g;for(;(t=s.exec(i))!==null;)e.push(t[1])}function Ag(i,e,t=!1){const s=[];Cg(e,s),i.forEach(a=>{a.header&&Cg(a.header,s)});const r=s;t&&r.sort();const n=r.map((a,l)=>` @location(${l}) ${a},`).join(`
|
|
106
106
|
`);let o=e.replace(/@in\s+[^;]+;\s*/g,"");return o=o.replace("{{in}}",`
|
|
107
107
|
${n}
|
|
108
108
|
`),o}function Eg(i,e){let t;const s=/@out\s+([^;]+);/g;for(;(t=s.exec(i))!==null;)e.push(t[1])}function eA(i){const t=/\b(\w+)\s*:/g.exec(i);return t?t[1]:""}function tA(i){const e=/@.*?\s+/g;return i.replace(e,"")}function iA(i,e){const t=[];Eg(e,t),i.forEach(l=>{l.header&&Eg(l.header,t)});let s=0;const r=t.sort().map(l=>l.indexOf("builtin")>-1?l:`@location(${s++}) ${l}`).join(`,
|
|
@@ -316,10 +316,10 @@ ${r.join(`
|
|
|
316
316
|
{
|
|
317
317
|
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
318
318
|
}
|
|
319
|
-
`}},Mg={};function id(i){let e=Mg[i];if(e)return e;const t=new Int32Array(i);for(let s=0;s<i;s++)t[s]=s;return e=Mg[i]=new He({uTextures:{value:t,type:"i32",size:i}},{isStatic:!0}),e}class kg extends ot{constructor(e){const t=Fs({name:"batch",bits:[Zu,td(e),Us]}),s=ks({name:"batch",bits:[ju,Qu(e),Bs]});super({glProgram:t,gpuProgram:s,resources:{batchSamplers:id(e)}}),this.maxTextures=e}}let Os=null;const Fg=class sy extends YC{constructor(e){super(e),this.geometry=new JC,this.name=sy.extension.name,this.vertexSize=6,Os??(Os=new kg(e.maxTextures)),this.shader=Os}packAttributes(e,t,s,r,n){const o=n<<16|e.roundPixels&65535,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,d=a.tx,f=a.ty,{positions:p,uvs:g}=e,m=e.color,_=e.attributeOffset,x=_+e.attributeSize;for(let y=_;y<x;y++){const v=y*2,T=p[v],S=p[v+1];t[r++]=l*T+h*S+d,t[r++]=u*S+c*T+f,t[r++]=g[v],t[r++]=g[v+1],s[r++]=m,s[r++]=o}}packQuadAttributes(e,t,s,r,n){const o=e.texture,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,d=a.tx,f=a.ty,p=e.bounds,g=p.maxX,m=p.minX,_=p.maxY,x=p.minY,y=o.uvs,v=e.color,T=n<<16|e.roundPixels&65535;t[r+0]=l*m+h*x+d,t[r+1]=u*x+c*m+f,t[r+2]=y.x0,t[r+3]=y.y0,s[r+4]=v,s[r+5]=T,t[r+6]=l*g+h*x+d,t[r+7]=u*x+c*g+f,t[r+8]=y.x1,t[r+9]=y.y1,s[r+10]=v,s[r+11]=T,t[r+12]=l*g+h*_+d,t[r+13]=u*_+c*g+f,t[r+14]=y.x2,t[r+15]=y.y2,s[r+16]=v,s[r+17]=T,t[r+18]=l*m+h*_+d,t[r+19]=u*_+c*m+f,t[r+20]=y.x3,t[r+21]=y.y3,s[r+22]=v,s[r+23]=T}_updateMaxTextures(e){this.shader.maxTextures!==e&&(Os=new kg(e),this.shader=Os)}destroy(){this.shader=null,super.destroy()}};Fg.extension={type:[b.Batcher],name:"default"};let sd=Fg;function gA(i,e,t,s,r,n,o,a=null){let l=0;t*=e,r*=n;const c=a.a,h=a.b,u=a.c,d=a.d,f=a.tx,p=a.ty;for(;l<o;){const g=i[t],m=i[t+1];s[r]=c*g+u*m+f,s[r+1]=h*g+d*m+p,r+=n,t+=e,l++}}function _A(i,e,t,s){let r=0;for(e*=t;r<s;)i[e]=0,i[e+1]=0,e+=t,r++}function Bg(i,e,t,s,r){const n=e.a,o=e.b,a=e.c,l=e.d,c=e.tx,h=e.ty;t||(t=0),s||(s=2),r||(r=i.length/s-t);let u=t*s;for(let d=0;d<r;d++){const f=i[u],p=i[u+1];i[u]=n*f+a*p+c,i[u+1]=o*f+l*p+h,u+=s}}const xA=new O;class rd{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,s=this.renderable;return s?am(t,s.groupColor)+(this.alpha*s.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){return this.renderable?.groupTransform||xA}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const Ds={extension:{type:b.ShapeBuilder,name:"circle"},build(i,e){let t,s,r,n,o,a;if(i.type==="circle"){const v=i;if(o=a=v.radius,o<=0)return!1;t=v.x,s=v.y,r=n=0}else if(i.type==="ellipse"){const v=i;if(o=v.halfWidth,a=v.halfHeight,o<=0||a<=0)return!1;t=v.x,s=v.y,r=n=0}else{const v=i,T=v.width/2,S=v.height/2;t=v.x+T,s=v.y+S,o=a=Math.max(0,Math.min(v.radius,Math.min(T,S))),r=T-o,n=S-a}if(r<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),c=l*8+(r?4:0)+(n?4:0);if(c===0)return!1;if(l===0)return e[0]=e[6]=t+r,e[1]=e[3]=s+n,e[2]=e[4]=t-r,e[5]=e[7]=s-n,!0;let h=0,u=l*4+(r?2:0)+2,d=u,f=c,p=r+o,g=n,m=t+p,_=t-p,x=s+g;if(e[h++]=m,e[h++]=x,e[--u]=x,e[--u]=_,n){const v=s-g;e[d++]=_,e[d++]=v,e[--f]=v,e[--f]=m}for(let v=1;v<l;v++){const T=Math.PI/2*(v/l),S=r+Math.cos(T)*o,w=n+Math.sin(T)*a,E=t+S,P=t-S,C=s+w,A=s-w;e[h++]=E,e[h++]=C,e[--u]=C,e[--u]=P,e[d++]=P,e[d++]=A,e[--f]=A,e[--f]=E}p=r,g=n+a,m=t+p,_=t-p,x=s+g;const y=s-g;return e[h++]=m,e[h++]=x,e[--f]=y,e[--f]=m,r&&(e[h++]=_,e[h++]=x,e[--f]=y,e[--f]=_),!0},triangulate(i,e,t,s,r,n){if(i.length===0)return;let o=0,a=0;for(let h=0;h<i.length;h+=2)o+=i[h],a+=i[h+1];o/=i.length/2,a/=i.length/2;let l=s;e[l*t]=o,e[l*t+1]=a;const c=l++;for(let h=0;h<i.length;h+=2)e[l*t]=i[h],e[l*t+1]=i[h+1],h>0&&(r[n++]=l,r[n++]=c,r[n++]=l-1),l++;r[n++]=c+1,r[n++]=c,r[n++]=l-1}},yA={...Ds,extension:{...Ds.extension,name:"ellipse"}},vA={...Ds,extension:{...Ds.extension,name:"roundedRectangle"}},Ug=1e-4,Og=1e-4;function bA(i){const e=i.length;if(e<6)return 1;let t=0;for(let s=0,r=i[e-2],n=i[e-1];s<e;s+=2){const o=i[s],a=i[s+1];t+=(o-r)*(a+n),r=o,n=a}return t<0?-1:1}function Dg(i,e,t,s,r,n,o,a){const l=i-t*r,c=e-s*r,h=i+t*n,u=e+s*n;let d,f;o?(d=s,f=-t):(d=-s,f=t);const p=l+d,g=c+f,m=h+d,_=u+f;return a.push(p,g),a.push(m,_),2}function fi(i,e,t,s,r,n,o,a){const l=t-i,c=s-e;let h=Math.atan2(l,c),u=Math.atan2(r-i,n-e);a&&h<u?h+=Math.PI*2:!a&&h>u&&(u+=Math.PI*2);let d=h;const f=u-h,p=Math.abs(f),g=Math.sqrt(l*l+c*c),m=(15*p*Math.sqrt(g)/Math.PI>>0)+1,_=f/m;if(d+=_,a){o.push(i,e),o.push(t,s);for(let x=1,y=d;x<m;x++,y+=_)o.push(i,e),o.push(i+Math.sin(y)*g,e+Math.cos(y)*g);o.push(i,e),o.push(r,n)}else{o.push(t,s),o.push(i,e);for(let x=1,y=d;x<m;x++,y+=_)o.push(i+Math.sin(y)*g,e+Math.cos(y)*g),o.push(i,e);o.push(r,n),o.push(i,e)}return m*2}function TA(i,e,t,s,r,n){const o=Ug;if(i.length===0)return;const a=e;let l=a.alignment;if(e.alignment!==.5){let G=bA(i);l=(l-.5)*G+.5}const c=new X(i[0],i[1]),h=new X(i[i.length-2],i[i.length-1]),u=s,d=Math.abs(c.x-h.x)<o&&Math.abs(c.y-h.y)<o;if(u){i=i.slice(),d&&(i.pop(),i.pop(),h.set(i[i.length-2],i[i.length-1]));const G=(c.x+h.x)*.5,ie=(h.y+c.y)*.5;i.unshift(G,ie),i.push(G,ie)}const f=r,p=i.length/2;let g=i.length;const m=f.length/2,_=a.width/2,x=_*_,y=a.miterLimit*a.miterLimit;let v=i[0],T=i[1],S=i[2],w=i[3],E=0,P=0,C=-(T-w),A=v-S,U=0,D=0,$=Math.sqrt(C*C+A*A);C/=$,A/=$,C*=_,A*=_;const pe=l,k=(1-pe)*2,F=pe*2;u||(a.cap==="round"?g+=fi(v-C*(k-F)*.5,T-A*(k-F)*.5,v-C*k,T-A*k,v+C*F,T+A*F,f,!0)+2:a.cap==="square"&&(g+=Dg(v,T,C,A,k,F,!0,f))),f.push(v-C*k,T-A*k),f.push(v+C*F,T+A*F);for(let G=1;G<p-1;++G){v=i[(G-1)*2],T=i[(G-1)*2+1],S=i[G*2],w=i[G*2+1],E=i[(G+1)*2],P=i[(G+1)*2+1],C=-(T-w),A=v-S,$=Math.sqrt(C*C+A*A),C/=$,A/=$,C*=_,A*=_,U=-(w-P),D=S-E,$=Math.sqrt(U*U+D*D),U/=$,D/=$,U*=_,D*=_;const ie=S-v,we=T-w,ce=S-E,Ce=P-w,Oe=ie*ce+we*Ce,N=we*ce-Ce*ie,q=N<0;if(Math.abs(N)<.001*Math.abs(Oe)){f.push(S-C*k,w-A*k),f.push(S+C*F,w+A*F),Oe>=0&&(a.join==="round"?g+=fi(S,w,S-C*k,w-A*k,S-U*k,w-D*k,f,!1)+4:g+=2,f.push(S-U*F,w-D*F),f.push(S+U*k,w+D*k));continue}const me=(-C+v)*(-A+w)-(-C+S)*(-A+T),Ie=(-U+E)*(-D+w)-(-U+S)*(-D+P),Qi=(ie*Ie-ce*me)/N,ti=(Ce*me-we*Ie)/N,Et=(Qi-S)*(Qi-S)+(ti-w)*(ti-w),qe=S+(Qi-S)*k,_t=w+(ti-w)*k,yi=S-(Qi-S)*F,vi=w-(ti-w)*F,xk=Math.min(ie*ie+we*we,ce*ce+Ce*Ce),Vx=q?k:F,yk=xk+Vx*Vx*x;Et<=yk?a.join==="bevel"||Et/x>y?(q?(f.push(qe,_t),f.push(S+C*F,w+A*F),f.push(qe,_t),f.push(S+U*F,w+D*F)):(f.push(S-C*k,w-A*k),f.push(yi,vi),f.push(S-U*k,w-D*k),f.push(yi,vi)),g+=2):a.join==="round"?q?(f.push(qe,_t),f.push(S+C*F,w+A*F),g+=fi(S,w,S+C*F,w+A*F,S+U*F,w+D*F,f,!0)+4,f.push(qe,_t),f.push(S+U*F,w+D*F)):(f.push(S-C*k,w-A*k),f.push(yi,vi),g+=fi(S,w,S-C*k,w-A*k,S-U*k,w-D*k,f,!1)+4,f.push(S-U*k,w-D*k),f.push(yi,vi)):(f.push(qe,_t),f.push(yi,vi)):(f.push(S-C*k,w-A*k),f.push(S+C*F,w+A*F),a.join==="round"?q?g+=fi(S,w,S+C*F,w+A*F,S+U*F,w+D*F,f,!0)+2:g+=fi(S,w,S-C*k,w-A*k,S-U*k,w-D*k,f,!1)+2:a.join==="miter"&&Et/x<=y&&(q?(f.push(yi,vi),f.push(yi,vi)):(f.push(qe,_t),f.push(qe,_t)),g+=2),f.push(S-U*k,w-D*k),f.push(S+U*F,w+D*F),g+=2)}v=i[(p-2)*2],T=i[(p-2)*2+1],S=i[(p-1)*2],w=i[(p-1)*2+1],C=-(T-w),A=v-S,$=Math.sqrt(C*C+A*A),C/=$,A/=$,C*=_,A*=_,f.push(S-C*k,w-A*k),f.push(S+C*F,w+A*F),u||(a.cap==="round"?g+=fi(S-C*(k-F)*.5,w-A*(k-F)*.5,S-C*k,w-A*k,S+C*F,w+A*F,f,!1)+2:a.cap==="square"&&(g+=Dg(S,w,C,A,k,F,!1,f)));const ne=Og*Og;for(let G=m;G<g+m-2;++G)v=f[G*2],T=f[G*2+1],S=f[(G+1)*2],w=f[(G+1)*2+1],E=f[(G+2)*2],P=f[(G+2)*2+1],!(Math.abs(v*(w-P)+S*(P-T)+E*(T-w))<ne)&&n.push(G,G+1,G+2)}function wA(i,e,t,s){const r=Ug;if(i.length===0)return;const n=i[0],o=i[1],a=i[i.length-2],l=i[i.length-1],c=e||Math.abs(n-a)<r&&Math.abs(o-l)<r,h=t,u=i.length/2,d=h.length/2;for(let f=0;f<u;f++)h.push(i[f*2]),h.push(i[f*2+1]);for(let f=0;f<u-1;f++)s.push(d+f,d+f+1);c&&s.push(d+u-1,d)}function Gg(i,e,t,s,r,n,o){const a=CC(i,e,2);if(!a)return;for(let c=0;c<a.length;c+=3)n[o++]=a[c]+r,n[o++]=a[c+1]+r,n[o++]=a[c+2]+r;let l=r*s;for(let c=0;c<i.length;c+=2)t[l]=i[c],t[l+1]=i[c+1],l+=s}const SA=[],CA={extension:{type:b.ShapeBuilder,name:"polygon"},build(i,e){for(let t=0;t<i.points.length;t++)e[t]=i.points[t];return!0},triangulate(i,e,t,s,r,n){Gg(i,SA,e,t,s,r,n)}},AA={extension:{type:b.ShapeBuilder,name:"rectangle"},build(i,e){const t=i,s=t.x,r=t.y,n=t.width,o=t.height;return n>0&&o>0?(e[0]=s,e[1]=r,e[2]=s+n,e[3]=r,e[4]=s+n,e[5]=r+o,e[6]=s,e[7]=r+o,!0):!1},triangulate(i,e,t,s,r,n){let o=0;s*=t,e[s+o]=i[0],e[s+o+1]=i[1],o+=t,e[s+o]=i[2],e[s+o+1]=i[3],o+=t,e[s+o]=i[6],e[s+o+1]=i[7],o+=t,e[s+o]=i[4],e[s+o+1]=i[5],o+=t;const a=s/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2,r[n++]=a+1,r[n++]=a+3,r[n++]=a+2}},EA={extension:{type:b.ShapeBuilder,name:"triangle"},build(i,e){return e[0]=i.x,e[1]=i.y,e[2]=i.x2,e[3]=i.y2,e[4]=i.x3,e[5]=i.y3,!0},triangulate(i,e,t,s,r,n){let o=0;s*=t,e[s+o]=i[0],e[s+o+1]=i[1],o+=t,e[s+o]=i[2],e[s+o+1]=i[3],o+=t,e[s+o]=i[4],e[s+o+1]=i[5];const a=s/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2}},IA=new O,PA=new H;function RA(i,e,t,s){const r=e.matrix?i.copyFrom(e.matrix).invert():i.identity();if(e.textureSpace==="local"){const o=t.getBounds(PA);e.width&&o.pad(e.width);const{x:a,y:l}=o,c=1/o.width,h=1/o.height,u=-a*c,d=-l*h,f=r.a,p=r.b,g=r.c,m=r.d;r.a*=c,r.b*=c,r.c*=h,r.d*=h,r.tx=u*f+d*g+r.tx,r.ty=u*p+d*m+r.ty}else r.translate(e.texture.frame.x,e.texture.frame.y),r.scale(1/e.texture.source.width,1/e.texture.source.height);const n=e.texture.source.style;return!(e.fill instanceof at)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),s&&r.append(IA.copyFrom(s).invert()),r}const en={};V.handleByMap(b.ShapeBuilder,en),V.add(AA,CA,EA,Ds,yA,vA);const MA=new H,kA=new O;function FA(i,e){const{geometryData:t,batches:s}=e;s.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let r=0;r<i.instructions.length;r++){const n=i.instructions[r];if(n.action==="texture")BA(n.data,s,t);else if(n.action==="fill"||n.action==="stroke"){const o=n.action==="stroke",a=n.data.path.shapePath,l=n.data.style,c=n.data.hole;o&&c&&zg(c.shapePath,l,!0,s,t),c&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=c.shapePath.shapePrimitives),zg(a,l,o,s,t)}}}function BA(i,e,t){const s=[],r=en.rectangle,n=MA;n.x=i.dx,n.y=i.dy,n.width=i.dw,n.height=i.dh;const o=i.transform;if(!r.build(n,s))return;const{vertices:a,uvs:l,indices:c}=t,h=c.length,u=a.length/2;o&&Bg(s,o),r.triangulate(s,a,2,u,c,h);const d=i.image,f=d.uvs;l.push(f.x0,f.y0,f.x1,f.y1,f.x3,f.y3,f.x2,f.y2);const p=Se.get(rd);p.indexOffset=h,p.indexSize=c.length-h,p.attributeOffset=u,p.attributeSize=a.length/2-u,p.baseColor=i.style,p.alpha=i.alpha,p.texture=d,p.geometryData=t,e.push(p)}function zg(i,e,t,s,r){const{vertices:n,uvs:o,indices:a}=r;i.shapePrimitives.forEach(({shape:l,transform:c,holes:h})=>{const u=[],d=en[l.type];if(!d.build(l,u))return;const f=a.length,p=n.length/2;let g="triangle-list";if(c&&Bg(u,c),t){const y=l.closePath??!0,v=e;v.pixelLine?(wA(u,y,n,a),g="line-list"):TA(u,v,!1,y,n,a)}else if(h){const y=[],v=u.slice();UA(h).forEach(S=>{y.push(v.length/2),v.push(...S)}),Gg(v,y,n,2,p,a,f)}else d.triangulate(u,n,2,p,a,f);const m=o.length/2,_=e.texture;if(_!==M.WHITE){const y=RA(kA,e,l,c);gA(n,2,p,o,m,2,n.length/2-p,y)}else _A(o,m,2,n.length/2-p);const x=Se.get(rd);x.indexOffset=f,x.indexSize=a.length-f,x.attributeOffset=p,x.attributeSize=n.length/2-p,x.baseColor=e.color,x.alpha=e.alpha,x.texture=_,x.geometryData=r,x.topology=g,s.push(x)})}function UA(i){const e=[];for(let t=0;t<i.length;t++){const s=i[t].shape,r=[];en[s.type].build(s,r)&&e.push(r)}return e}class OA{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}}class DA{constructor(){this.instructions=new um}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new sd({maxTextures:t}),this.instructions.reset()}get geometry(){return W(Y1,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const nd=class hf{constructor(e){this._gpuContextHash={},this._graphicsDataContextHash=Object.create(null),this._renderer=e,e.renderableGC.addManagedHash(this,"_gpuContextHash"),e.renderableGC.addManagedHash(this,"_graphicsDataContextHash")}init(e){hf.defaultOptions.bezierSmoothness=e?.bezierSmoothness??hf.defaultOptions.bezierSmoothness}getContextRenderData(e){return this._graphicsDataContextHash[e.uid]||this._initContextRenderData(e)}updateGpuContext(e){let t=this._gpuContextHash[e.uid]||this._initContext(e);if(e.dirty){t?this._cleanGraphicsContextData(e):t=this._initContext(e),FA(e,t);const s=e.batchMode;e.customShader||s==="no-batch"?t.isBatchable=!1:s==="auto"?t.isBatchable=t.geometryData.vertices.length<400:t.isBatchable=!0,e.dirty=!1}return t}getGpuContext(e){return this._gpuContextHash[e.uid]||this._initContext(e)}_initContextRenderData(e){const t=Se.get(DA,{maxTextures:this._renderer.limits.maxBatchableTextures}),{batches:s,geometryData:r}=this._gpuContextHash[e.uid],n=r.vertices.length,o=r.indices.length;for(let h=0;h<s.length;h++)s[h].applyTransform=!1;const a=t.batcher;a.ensureAttributeBuffer(n),a.ensureIndexBuffer(o),a.begin();for(let h=0;h<s.length;h++){const u=s[h];a.add(u)}a.finish(t.instructions);const l=a.geometry;l.indexBuffer.setDataWithSize(a.indexBuffer,a.indexSize,!0),l.buffers[0].setDataWithSize(a.attributeBuffer.float32View,a.attributeSize,!0);const c=a.batches;for(let h=0;h<c.length;h++){const u=c[h];u.bindGroup=Yu(u.textures.textures,u.textures.count,this._renderer.limits.maxBatchableTextures)}return this._graphicsDataContextHash[e.uid]=t,t}_initContext(e){const t=new OA;return t.context=e,this._gpuContextHash[e.uid]=t,e.on("destroy",this.onGraphicsContextDestroy,this),this._gpuContextHash[e.uid]}onGraphicsContextDestroy(e){this._cleanGraphicsContextData(e),e.off("destroy",this.onGraphicsContextDestroy,this),this._gpuContextHash[e.uid]=null}_cleanGraphicsContextData(e){const t=this._gpuContextHash[e.uid];t.isBatchable||this._graphicsDataContextHash[e.uid]&&(Se.return(this.getContextRenderData(e)),this._graphicsDataContextHash[e.uid]=null),t.batches&&t.batches.forEach(s=>{Se.return(s)})}destroy(){for(const e in this._gpuContextHash)this._gpuContextHash[e]&&this.onGraphicsContextDestroy(this._gpuContextHash[e].context);this._gpuContextHash={},this._graphicsDataContextHash={},this._renderer=null}};nd.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"graphicsContext"},nd.defaultOptions={bezierSmoothness:.5};let od=nd;const GA=8,tn=11920929e-14,zA=1;function Ng(i,e,t,s,r,n,o,a,l,c){const u=Math.min(.99,Math.max(0,c??od.defaultOptions.bezierSmoothness));let d=(zA-u)/1;return d*=d,NA(e,t,s,r,n,o,a,l,i,d),i}function NA(i,e,t,s,r,n,o,a,l,c){ad(i,e,t,s,r,n,o,a,l,c,0),l.push(o,a)}function ad(i,e,t,s,r,n,o,a,l,c,h){if(h>GA)return;const u=(i+t)/2,d=(e+s)/2,f=(t+r)/2,p=(s+n)/2,g=(r+o)/2,m=(n+a)/2,_=(u+f)/2,x=(d+p)/2,y=(f+g)/2,v=(p+m)/2,T=(_+y)/2,S=(x+v)/2;if(h>0){let w=o-i,E=a-e;const P=Math.abs((t-o)*E-(s-a)*w),C=Math.abs((r-o)*E-(n-a)*w);if(P>tn&&C>tn){if((P+C)*(P+C)<=c*(w*w+E*E)){l.push(T,S);return}}else if(P>tn){if(P*P<=c*(w*w+E*E)){l.push(T,S);return}}else if(C>tn){if(C*C<=c*(w*w+E*E)){l.push(T,S);return}}else if(w=T-(i+o)/2,E=S-(e+a)/2,w*w+E*E<=c){l.push(T,S);return}}ad(i,e,u,d,_,x,T,S,l,c,h+1),ad(T,S,y,v,g,m,o,a,l,c,h+1)}const LA=8,HA=11920929e-14,WA=1;function VA(i,e,t,s,r,n,o,a){const c=Math.min(.99,Math.max(0,a??od.defaultOptions.bezierSmoothness));let h=(WA-c)/1;return h*=h,$A(e,t,s,r,n,o,i,h),i}function $A(i,e,t,s,r,n,o,a){ld(o,i,e,t,s,r,n,a,0),o.push(r,n)}function ld(i,e,t,s,r,n,o,a,l){if(l>LA)return;const c=(e+s)/2,h=(t+r)/2,u=(s+n)/2,d=(r+o)/2,f=(c+u)/2,p=(h+d)/2;let g=n-e,m=o-t;const _=Math.abs((s-n)*m-(r-o)*g);if(_>HA){if(_*_<=a*(g*g+m*m)){i.push(f,p);return}}else if(g=f-(e+n)/2,m=p-(t+o)/2,g*g+m*m<=a){i.push(f,p);return}ld(i,e,t,c,h,f,p,a,l+1),ld(i,f,p,u,d,n,o,a,l+1)}function Lg(i,e,t,s,r,n,o,a){let l=Math.abs(r-n);(!o&&r>n||o&&n>r)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(s,1/3)*(l/Math.PI)))),a=Math.max(a,3);let c=l/a,h=r;c*=o?-1:1;for(let u=0;u<a+1;u++){const d=Math.cos(h),f=Math.sin(h),p=e+d*s,g=t+f*s;i.push(p,g),h+=c}}function XA(i,e,t,s,r,n){const o=i[i.length-2],l=i[i.length-1]-t,c=o-e,h=r-t,u=s-e,d=Math.abs(l*u-c*h);if(d<1e-8||n===0){(i[i.length-2]!==e||i[i.length-1]!==t)&&i.push(e,t);return}const f=l*l+c*c,p=h*h+u*u,g=l*h+c*u,m=n*Math.sqrt(f)/d,_=n*Math.sqrt(p)/d,x=m*g/f,y=_*g/p,v=m*u+_*c,T=m*h+_*l,S=c*(_+x),w=l*(_+x),E=u*(m+y),P=h*(m+y),C=Math.atan2(w-T,S-v),A=Math.atan2(P-T,E-v);Lg(i,v+e,T+t,n,C,A,c*h>u*l)}const Gs=Math.PI*2,cd={centerX:0,centerY:0,ang1:0,ang2:0},hd=({x:i,y:e},t,s,r,n,o,a,l)=>{i*=t,e*=s;const c=r*i-n*e,h=n*i+r*e;return l.x=c+o,l.y=h+a,l};function YA(i,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),s=e===1.5707963267948966?.551915024494:t,r=Math.cos(i),n=Math.sin(i),o=Math.cos(i+e),a=Math.sin(i+e);return[{x:r-n*s,y:n+r*s},{x:o+a*s,y:a-o*s},{x:o,y:a}]}const Hg=(i,e,t,s)=>{const r=i*s-e*t<0?-1:1;let n=i*t+e*s;return n>1&&(n=1),n<-1&&(n=-1),r*Math.acos(n)},qA=(i,e,t,s,r,n,o,a,l,c,h,u,d)=>{const f=Math.pow(r,2),p=Math.pow(n,2),g=Math.pow(h,2),m=Math.pow(u,2);let _=f*p-f*m-p*g;_<0&&(_=0),_/=f*m+p*g,_=Math.sqrt(_)*(o===a?-1:1);const x=_*r/n*u,y=_*-n/r*h,v=c*x-l*y+(i+t)/2,T=l*x+c*y+(e+s)/2,S=(h-x)/r,w=(u-y)/n,E=(-h-x)/r,P=(-u-y)/n,C=Hg(1,0,S,w);let A=Hg(S,w,E,P);a===0&&A>0&&(A-=Gs),a===1&&A<0&&(A+=Gs),d.centerX=v,d.centerY=T,d.ang1=C,d.ang2=A};function KA(i,e,t,s,r,n,o,a=0,l=0,c=0){if(n===0||o===0)return;const h=Math.sin(a*Gs/360),u=Math.cos(a*Gs/360),d=u*(e-s)/2+h*(t-r)/2,f=-h*(e-s)/2+u*(t-r)/2;if(d===0&&f===0)return;n=Math.abs(n),o=Math.abs(o);const p=Math.pow(d,2)/Math.pow(n,2)+Math.pow(f,2)/Math.pow(o,2);p>1&&(n*=Math.sqrt(p),o*=Math.sqrt(p)),qA(e,t,s,r,n,o,l,c,h,u,d,f,cd);let{ang1:g,ang2:m}=cd;const{centerX:_,centerY:x}=cd;let y=Math.abs(m)/(Gs/4);Math.abs(1-y)<1e-7&&(y=1);const v=Math.max(Math.ceil(y),1);m/=v;let T=i[i.length-2],S=i[i.length-1];const w={x:0,y:0};for(let E=0;E<v;E++){const P=YA(g,m),{x:C,y:A}=hd(P[0],n,o,u,h,_,x,w),{x:U,y:D}=hd(P[1],n,o,u,h,_,x,w),{x:$,y:pe}=hd(P[2],n,o,u,h,_,x,w);Ng(i,T,S,C,A,U,D,$,pe),T=$,S=pe,g+=m}}function jA(i,e,t){const s=(o,a)=>{const l=a.x-o.x,c=a.y-o.y,h=Math.sqrt(l*l+c*c),u=l/h,d=c/h;return{len:h,nx:u,ny:d}},r=(o,a)=>{o===0?i.moveTo(a.x,a.y):i.lineTo(a.x,a.y)};let n=e[e.length-1];for(let o=0;o<e.length;o++){const a=e[o%e.length],l=a.radius??t;if(l<=0){r(o,a),n=a;continue}const c=e[(o+1)%e.length],h=s(a,n),u=s(a,c);if(h.len<1e-4||u.len<1e-4){r(o,a),n=a;continue}let d=Math.asin(h.nx*u.ny-h.ny*u.nx),f=1,p=!1;h.nx*u.nx-h.ny*-u.ny<0?d<0?d=Math.PI+d:(d=Math.PI-d,f=-1,p=!0):d>0&&(f=-1,p=!0);const g=d/2;let m,_=Math.abs(Math.cos(g)*l/Math.sin(g));_>Math.min(h.len/2,u.len/2)?(_=Math.min(h.len/2,u.len/2),m=Math.abs(_*Math.sin(g)/Math.cos(g))):m=l;const x=a.x+u.nx*_+-u.ny*m*f,y=a.y+u.ny*_+u.nx*m*f,v=Math.atan2(h.ny,h.nx)+Math.PI/2*f,T=Math.atan2(u.ny,u.nx)-Math.PI/2*f;o===0&&i.moveTo(x+Math.cos(v)*m,y+Math.sin(v)*m),i.arc(x,y,m,v,T,p),n=a}}function ZA(i,e,t,s){const r=(a,l)=>Math.sqrt((a.x-l.x)**2+(a.y-l.y)**2),n=(a,l,c)=>({x:a.x+(l.x-a.x)*c,y:a.y+(l.y-a.y)*c}),o=e.length;for(let a=0;a<o;a++){const l=e[(a+1)%o],c=l.radius??t;if(c<=0){a===0?i.moveTo(l.x,l.y):i.lineTo(l.x,l.y);continue}const h=e[a],u=e[(a+2)%o],d=r(h,l);let f;if(d<1e-4)f=l;else{const m=Math.min(d/2,c);f=n(l,h,m/d)}const p=r(u,l);let g;if(p<1e-4)g=l;else{const m=Math.min(p/2,c);g=n(l,u,m/p)}a===0?i.moveTo(f.x,f.y):i.lineTo(f.x,f.y),i.quadraticCurveTo(l.x,l.y,g.x,g.y,s)}}const JA=new H;class QA{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new De,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const s=this._currentPoly.points,r=s[s.length-2],n=s[s.length-1];return(r!==e||n!==t)&&s.push(e,t),this}arc(e,t,s,r,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return Lg(a,e,t,s,r,n,o),this}arcTo(e,t,s,r,n){this._ensurePoly();const o=this._currentPoly.points;return XA(o,e,t,s,r,n),this}arcToSvg(e,t,s,r,n,o,a){const l=this._currentPoly.points;return KA(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,s,r,n),this}bezierCurveTo(e,t,s,r,n,o,a){this._ensurePoly();const l=this._currentPoly;return Ng(this._currentPoly.points,l.lastX,l.lastY,e,t,s,r,n,o,a),this}quadraticCurveTo(e,t,s,r,n){this._ensurePoly();const o=this._currentPoly;return VA(this._currentPoly.points,o.lastX,o.lastY,e,t,s,r,n),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const s=this.shapePrimitives,r=s.length;for(let n=0;n<e.instructions.length;n++){const o=e.instructions[n];this[o.action](...o.data)}if(e.checkForHoles&&s.length-r>1){let n=null;for(let o=r;o<s.length;o++){const a=s[o];if(a.shape.type==="polygon"){const l=a.shape,c=n?.shape;c&&c.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),s.copyWithin(o,o+1),s.length--,o--):n=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,s,r,n){return this.drawShape(new H(e,t,s,r),n),this}circle(e,t,s,r){return this.drawShape(new Zr(e,t,s),r),this}poly(e,t,s){const r=new Es(e);return r.closePath=t,this.drawShape(r,s),this}regularPoly(e,t,s,r,n=0,o){r=Math.max(r|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/r,c=[];for(let h=0;h<r;h++){const u=a-h*l;c.push(e+s*Math.cos(u),t+s*Math.sin(u))}return this.poly(c,!0,o),this}roundPoly(e,t,s,r,n,o=0,a){if(r=Math.max(r|0,3),n<=0)return this.regularPoly(e,t,s,r,o);const l=s*Math.sin(Math.PI/r)-.001;n=Math.min(n,l);const c=-1*Math.PI/2+o,h=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let d=0;d<r;d++){const f=d*h+c,p=e+s*Math.cos(f),g=t+s*Math.sin(f),m=f+Math.PI+u,_=f-Math.PI-u,x=p+n*Math.cos(m),y=g+n*Math.sin(m),v=p+n*Math.cos(_),T=g+n*Math.sin(_);d===0?this.moveTo(x,y):this.lineTo(x,y),this.quadraticCurveTo(p,g,v,T,a)}return this.closePath()}roundShape(e,t,s=!1,r){return e.length<3?this:(s?ZA(this,e,t,r):jA(this,e,t),this.closePath())}filletRect(e,t,s,r,n){if(n===0)return this.rect(e,t,s,r);const o=Math.min(s,r)/2,a=Math.min(o,Math.max(-o,n)),l=e+s,c=t+r,h=a<0?-a:0,u=Math.abs(a);return this.moveTo(e,t+u).arcTo(e+h,t+h,e+u,t,u).lineTo(l-u,t).arcTo(l-h,t+h,l,t+u,u).lineTo(l,c-u).arcTo(l-h,c-h,e+s-u,c,u).lineTo(e+u,c).arcTo(e+h,c-h,e,c-u,u).closePath()}chamferRect(e,t,s,r,n,o){if(n<=0)return this.rect(e,t,s,r);const a=Math.min(n,Math.min(s,r)/2),l=e+s,c=t+r,h=[e+a,t,l-a,t,l,t+a,l,c-a,l-a,c,e+a,c,e,c-a,e,t+a];for(let u=h.length-1;u>=2;u-=2)h[u]===h[u-2]&&h[u-1]===h[u-3]&&h.splice(u-1,2);return this.poly(h,!0,o)}ellipse(e,t,s,r,n){return this.drawShape(new $u(e,t,s,r),n),this}roundRect(e,t,s,r,n,o){return this.drawShape(new Xu(e,t,s,r,n),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let s=this._currentPoly;return s&&this.endPoly(),s=new Es,s.points.push(e,t),this._currentPoly=s,this}endPoly(e=!1){const t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new Es,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let s=t.shape.x,r=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const n=t.transform,o=s;s=n.a*s+n.c*r+n.tx,r=n.b*o+n.d*r+n.ty}this._currentPoly.points.push(s,r)}else this._currentPoly.points.push(0,0)}}buildPath(){const e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){const s=e.instructions[t];this[s.action](...s.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let s=0;s<t.length;s++){const r=t[s],n=r.shape.getBounds(JA);r.transform?e.addRect(n,r.transform):e.addRect(n)}return e}}class Dt{constructor(e,t=!1){this.instructions=[],this.uid=he("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?OC(e,this):this.instructions=e?.slice()??[]}get shapePath(){return this._shapePath||(this._shapePath=new QA(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:"addPath",data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:"arc",data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:"arcTo",data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:"arcToSvg",data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:"bezierCurveTo",data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,s,r,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(X.shared);let l=0,c=0;if(!o||o.action!=="bezierCurveTo")l=a.x,c=a.y;else{l=o.data[2],c=o.data[3];const h=a.x,u=a.y;l=h+(h-l),c=u+(u-c)}return this.instructions.push({action:"bezierCurveTo",data:[l,c,e,t,s,r,n]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:"ellipse",data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:"lineTo",data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:"moveTo",data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:"quadraticCurveTo",data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,s){const r=this.instructions[this.instructions.length-1],n=this.getLastPoint(X.shared);let o=0,a=0;if(!r||r.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=r.data[0],a=r.data[1];const l=n.x,c=n.y;o=l+(l-o),a=c+(c-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,e,t,s]}),this._dirty=!0,this}rect(e,t,s,r,n){return this.instructions.push({action:"rect",data:[e,t,s,r,n]}),this._dirty=!0,this}circle(e,t,s,r){return this.instructions.push({action:"circle",data:[e,t,s,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:"roundRect",data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:"poly",data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:"regularPoly",data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:"roundPoly",data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:"roundShape",data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:"filletRect",data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:"chamferRect",data:e}),this._dirty=!0,this}star(e,t,s,r,n,o,a){n||(n=r/2);const l=-1*Math.PI/2+o,c=s*2,h=Math.PI*2/c,u=[];for(let d=0;d<c;d++){const f=d%2?n:r,p=d*h+l;u.push(e+f*Math.cos(p),t+f*Math.sin(p))}return this.poly(u,!0,a),this}clone(e=!1){const t=new Dt;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let s=0;s<this.instructions.length;s++){const r=this.instructions[s];t.instructions.push({action:r.action,data:r.data.slice()})}return t}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;const t=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty;let l=0,c=0,h=0,u=0,d=0,f=0,p=0,g=0;for(let m=0;m<this.instructions.length;m++){const _=this.instructions[m],x=_.data;switch(_.action){case"moveTo":case"lineTo":l=x[0],c=x[1],x[0]=t*l+r*c+o,x[1]=s*l+n*c+a;break;case"bezierCurveTo":h=x[0],u=x[1],d=x[2],f=x[3],l=x[4],c=x[5],x[0]=t*h+r*u+o,x[1]=s*h+n*u+a,x[2]=t*d+r*f+o,x[3]=s*d+n*f+a,x[4]=t*l+r*c+o,x[5]=s*l+n*c+a;break;case"quadraticCurveTo":h=x[0],u=x[1],l=x[2],c=x[3],x[0]=t*h+r*u+o,x[1]=s*h+n*u+a,x[2]=t*l+r*c+o,x[3]=s*l+n*c+a;break;case"arcToSvg":l=x[5],c=x[6],p=x[0],g=x[1],x[0]=t*p+r*g,x[1]=s*p+n*g,x[5]=t*l+r*c+o,x[6]=s*l+n*c+a;break;case"circle":x[4]=zs(x[3],e);break;case"rect":x[4]=zs(x[4],e);break;case"ellipse":x[8]=zs(x[8],e);break;case"roundRect":x[5]=zs(x[5],e);break;case"addPath":x[0].transform(e);break;case"poly":x[2]=zs(x[2],e);break;default:L("unknown transform action",_.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,s=this.instructions[t];if(!s)return e.x=0,e.y=0,e;for(;s.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;s=this.instructions[t]}switch(s.action){case"moveTo":case"lineTo":e.x=s.data[0],e.y=s.data[1];break;case"quadraticCurveTo":e.x=s.data[2],e.y=s.data[3];break;case"bezierCurveTo":e.x=s.data[4],e.y=s.data[5];break;case"arc":case"arcToSvg":e.x=s.data[5],e.y=s.data[6];break;case"addPath":s.data[0].getLastPoint(e);break}return e}}function zs(i,e){return i?i.prepend(e):e.clone()}function xe(i,e,t){const s=i.getAttribute(e);return s?Number(s):t}function eE(i,e){const t=i.querySelectorAll("defs");for(let s=0;s<t.length;s++){const r=t[s];for(let n=0;n<r.children.length;n++){const o=r.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=tE(o);break;case"radialgradient":e.defs[o.id]=iE();break}}}}function tE(i){const e=xe(i,"x1",0),t=xe(i,"y1",0),s=xe(i,"x2",1),r=xe(i,"y2",0),n=i.getAttribute("gradientUnits")||"objectBoundingBox",o=new at(e,t,s,r,n==="objectBoundingBox"?"local":"global");for(let a=0;a<i.children.length;a++){const l=i.children[a],c=xe(l,"offset",0),h=ue.shared.setValue(l.getAttribute("stop-color")).toNumber();o.addColorStop(c,h)}return o}function iE(i){return L("[SVG Parser] Radial gradients are not yet supported"),new at(0,0,1,0)}function Wg(i){const e=i.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const Vg={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function $g(i,e){const t=i.getAttribute("style"),s={},r={},n={strokeStyle:s,fillStyle:r,useFill:!1,useStroke:!1};for(const o in Vg){const a=i.getAttribute(o);a&&Xg(e,n,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[c,h]=l.split(":");Vg[c]&&Xg(e,n,c,h.trim())}}return{strokeStyle:n.useStroke?s:null,fillStyle:n.useFill?r:null,useFill:n.useFill,useStroke:n.useStroke}}function Xg(i,e,t,s){switch(t){case"stroke":if(s!=="none"){if(s.startsWith("url(")){const r=Wg(s);e.strokeStyle.fill=i.defs[r]}else e.strokeStyle.color=ue.shared.setValue(s).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(s);break;case"fill":if(s!=="none"){if(s.startsWith("url(")){const r=Wg(s);e.fillStyle.fill=i.defs[r]}else e.fillStyle.color=ue.shared.setValue(s).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(s);break;case"stroke-opacity":e.strokeStyle.alpha=Number(s);break;case"opacity":e.fillStyle.alpha=Number(s),e.strokeStyle.alpha=Number(s);break}}function sE(i){if(i.length<=2)return!0;const e=i.map(a=>a.area).sort((a,l)=>l-a),[t,s]=e,r=e[e.length-1],n=t/s,o=s/r;return!(n>3&&o<2)}function rE(i){return i.split(/(?=[Mm])/).filter(s=>s.trim().length>0)}function nE(i){const e=i.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),s=[],r=[];for(let h=0;h<t.length;h+=2)h+1<t.length&&(s.push(t[h]),r.push(t[h+1]));if(s.length===0||r.length===0)return 0;const n=Math.min(...s),o=Math.max(...s),a=Math.min(...r),l=Math.max(...r);return(o-n)*(l-a)}function Yg(i,e){const t=new Dt(i,!1);for(const s of t.instructions)e.instructions.push(s)}function oE(i,e){if(typeof i=="string"){const o=document.createElement("div");o.innerHTML=i.trim(),i=o.querySelector("svg")}const t={context:e,defs:{},path:new Dt};eE(i,t);const s=i.children,{fillStyle:r,strokeStyle:n}=$g(i,t);for(let o=0;o<s.length;o++){const a=s[o];a.nodeName.toLowerCase()!=="defs"&&qg(a,t,r,n)}return e}function qg(i,e,t,s){const r=i.children,{fillStyle:n,strokeStyle:o}=$g(i,e);n&&t?t={...t,...n}:n&&(t=n),o&&s?s={...s,...o}:o&&(s=o);const a=!t&&!s;a&&(t={color:0});let l,c,h,u,d,f,p,g,m,_,x,y,v,T,S,w,E;switch(i.nodeName.toLowerCase()){case"path":{T=i.getAttribute("d");const P=i.getAttribute("fill-rule"),C=rE(T),A=P==="evenodd",U=C.length>1;if(A&&U){const $=C.map(k=>({path:k,area:nE(k)}));if($.sort((k,F)=>F.area-k.area),C.length>3||!sE($))for(let k=0;k<$.length;k++){const F=$[k],ne=k===0;e.context.beginPath();const G=new Dt(void 0,!0);Yg(F.path,G),e.context.path(G),ne?(t&&e.context.fill(t),s&&e.context.stroke(s)):e.context.cut()}else for(let k=0;k<$.length;k++){const F=$[k],ne=k%2===1;e.context.beginPath();const G=new Dt(void 0,!0);Yg(F.path,G),e.context.path(G),ne?e.context.cut():(t&&e.context.fill(t),s&&e.context.stroke(s))}}else{const $=P?P==="evenodd":!0;S=new Dt(T,$),e.context.path(S),t&&e.context.fill(t),s&&e.context.stroke(s)}break}case"circle":p=xe(i,"cx",0),g=xe(i,"cy",0),m=xe(i,"r",0),e.context.ellipse(p,g,m,m),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"rect":l=xe(i,"x",0),c=xe(i,"y",0),w=xe(i,"width",0),E=xe(i,"height",0),_=xe(i,"rx",0),x=xe(i,"ry",0),_||x?e.context.roundRect(l,c,w,E,_||x):e.context.rect(l,c,w,E),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"ellipse":p=xe(i,"cx",0),g=xe(i,"cy",0),_=xe(i,"rx",0),x=xe(i,"ry",0),e.context.beginPath(),e.context.ellipse(p,g,_,x),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"line":h=xe(i,"x1",0),u=xe(i,"y1",0),d=xe(i,"x2",0),f=xe(i,"y2",0),e.context.beginPath(),e.context.moveTo(h,u),e.context.lineTo(d,f),s&&e.context.stroke(s);break;case"polygon":v=i.getAttribute("points"),y=v.match(/\d+/g).map(P=>parseInt(P,10)),e.context.poly(y,!0),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"polyline":v=i.getAttribute("points"),y=v.match(/\d+/g).map(P=>parseInt(P,10)),e.context.poly(y,!1),s&&e.context.stroke(s);break;case"g":case"svg":break;default:{L(`[SVG parser] <${i.nodeName}> elements unsupported`);break}}a&&(t=null);for(let P=0;P<r.length;P++)qg(r[P],e,t,s)}function aE(i){return ue.isColorLike(i)}function Kg(i){return i instanceof jr}function jg(i){return i instanceof at}function lE(i){return i instanceof M}function cE(i,e,t){const s=ue.shared.setValue(e??0);return i.color=s.toNumber(),i.alpha=s.alpha===1?t.alpha:s.alpha,i.texture=M.WHITE,{...t,...i}}function hE(i,e,t){return i.texture=e,{...t,...i}}function Zg(i,e,t){return i.fill=e,i.color=16777215,i.texture=e.texture,i.matrix=e.transform,{...t,...i}}function Jg(i,e,t){return e.buildGradient(),i.fill=e,i.color=16777215,i.texture=e.texture,i.matrix=e.transform,i.textureSpace=e.textureSpace,{...t,...i}}function uE(i,e){const t={...e,...i},s=ue.shared.setValue(t.color);return t.alpha*=s.alpha,t.color=s.toNumber(),t}function pi(i,e){if(i==null)return null;const t={},s=i;return aE(i)?cE(t,i,e):lE(i)?hE(t,i,e):Kg(i)?Zg(t,i,e):jg(i)?Jg(t,i,e):s.fill&&Kg(s.fill)?Zg(s,s.fill,e):s.fill&&jg(s.fill)?Jg(s,s.fill,e):uE(s,e)}function sn(i,e){const{width:t,alignment:s,miterLimit:r,cap:n,join:o,pixelLine:a,...l}=e,c=pi(i,l);return c?{width:t,alignment:s,miterLimit:r,cap:n,join:o,pixelLine:a,...c}:null}const dE=new X,Qg=new O,ud=class It extends je{constructor(){super(...arguments),this.uid=he("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this._activePath=new Dt,this._transform=new O,this._fillStyle={...It.defaultFillStyle},this._strokeStyle={...It.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new De,this._boundsDirty=!0}clone(){const e=new It;return e.batchMode=this.batchMode,e.instructions=this.instructions.slice(),e._activePath=this._activePath.clone(),e._transform=this._transform.clone(),e._fillStyle={...this._fillStyle},e._strokeStyle={...this._strokeStyle},e._stateStack=this._stateStack.slice(),e._bounds=this._bounds.clone(),e._boundsDirty=!0,e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=pi(e,It.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=sn(e,It.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=pi(e,It.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=pi(e,It.defaultStrokeStyle),this}texture(e,t,s,r,n,o){return this.instructions.push({action:"texture",data:{image:e,dx:s||0,dy:r||0,dw:n||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t?ue.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new Dt,this}fill(e,t){let s;const r=this.instructions[this.instructions.length-1];return this._tick===0&&r?.action==="stroke"?s=r.data.path:s=this._activePath.clone(),s?(e!=null&&(t!==void 0&&typeof e=="number"&&(W(Q,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=pi(e,It.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:s}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(X.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const s=this.instructions[this.instructions.length-1];return this._tick===0&&s?.action==="fill"?t=s.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=sn(e,It.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:t}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){const t=this.instructions[this.instructions.length-1-e],s=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(s);else{t.data.hole=s;break}}return this._initNextPathLocation(),this}arc(e,t,s,r,n,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,s,r,n,o),this}arcTo(e,t,s,r,n){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*s+o.c*r+o.tx,o.b*s+o.d*r+o.ty,n),this}arcToSvg(e,t,s,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(e,t,s,r,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(e,t,s,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.bezierCurveTo(l.a*e+l.c*t+l.tx,l.b*e+l.d*t+l.ty,l.a*s+l.c*r+l.tx,l.b*s+l.d*r+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){return this._tick++,this._activePath?.closePath(),this}ellipse(e,t,s,r){return this._tick++,this._activePath.ellipse(e,t,s,r,this._transform.clone()),this}circle(e,t,s){return this._tick++,this._activePath.circle(e,t,s,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const s=this._transform;return this._activePath.lineTo(s.a*e+s.c*t+s.tx,s.b*e+s.d*t+s.ty),this}moveTo(e,t){this._tick++;const s=this._transform,r=this._activePath.instructions,n=s.a*e+s.c*t+s.tx,o=s.b*e+s.d*t+s.ty;return r.length===1&&r[0].action==="moveTo"?(r[0].data[0]=n,r[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(e,t,s,r,n){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*s+o.c*r+o.tx,o.b*s+o.d*r+o.ty,n),this}rect(e,t,s,r){return this._tick++,this._activePath.rect(e,t,s,r,this._transform.clone()),this}roundRect(e,t,s,r,n){return this._tick++,this._activePath.roundRect(e,t,s,r,n,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,s,r,n=0,o){return this._tick++,this._activePath.regularPoly(e,t,s,r,n,o),this}roundPoly(e,t,s,r,n,o){return this._tick++,this._activePath.roundPoly(e,t,s,r,n,o),this}roundShape(e,t,s,r){return this._tick++,this._activePath.roundShape(e,t,s,r),this}filletRect(e,t,s,r,n){return this._tick++,this._activePath.filletRect(e,t,s,r,n),this}chamferRect(e,t,s,r,n,o){return this._tick++,this._activePath.chamferRect(e,t,s,r,n,o),this}star(e,t,s,r,n=0,o=0){return this._tick++,this._activePath.star(e,t,s,r,n,o,this._transform.clone()),this}svg(e){return this._tick++,oE(e,this),this}restore(){const e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,s,r,n,o){return e instanceof O?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,s,r,n,o),this)}transform(e,t,s,r,n,o){return e instanceof O?(this._transform.append(e),this):(Qg.set(e,t,s,r,n,o),this._transform.append(Qg),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,!this.dirty&&(this.emit("update",this,16),this.dirty=!0)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){const s=this.instructions[t],r=s.action;if(r==="fill"){const n=s.data;e.addBounds(n.path.bounds)}else if(r==="texture"){const n=s.data;e.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(r==="stroke"){const n=s.data,o=n.style.alignment,a=n.style.width*(1-o),l=n.path.bounds;e.addFrame(l.minX-a,l.minY-a,l.maxX+a,l.maxY+a)}}return e}containsPoint(e){if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let s=!1;for(let r=0;r<t.length;r++){const n=t[r],o=n.data,a=o.path;if(!n.action||!a)continue;const l=o.style,c=a.shapePath.shapePrimitives;for(let h=0;h<c.length;h++){const u=c[h].shape;if(!l||!u)continue;const d=c[h].transform,f=d?d.applyInverse(e,dE):e;if(n.action==="fill")s=u.contains(f.x,f.y);else{const g=l;s=u.strokeContains(f.x,f.y,g.width,g.alignment)}const p=o.hole;if(p){const g=p.shapePath?.shapePrimitives;if(g)for(let m=0;m<g.length;m++)g[m].shape.contains(f.x,f.y)&&(s=!1)}if(s)return!0}}return s}destroy(e=!1){if(this._stateStack.length=0,this._transform=null,this.emit("destroy",this),this.removeAllListeners(),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(s)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(s))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};ud.defaultFillStyle={color:16777215,alpha:1,texture:M.WHITE,matrix:null,fill:null,textureSpace:"local"},ud.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:M.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let lt=ud;const dd=class es extends je{constructor(e={}){super(),this.uid=he("textStyle"),this._tick=0,fE(e);const t={...es.defaultTextStyle,...e};for(const s in t){const r=s;this[r]=t[s]}this.update(),this._tick=0}get align(){return this._align}set align(e){this._align!==e&&(this._align=e,this.update())}get breakWords(){return this._breakWords}set breakWords(e){this._breakWords!==e&&(this._breakWords=e,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(e){this._dropShadow!==e&&(e!==null&&typeof e=="object"?this._dropShadow=this._createProxy({...es.defaultDropShadow,...e}):this._dropShadow=e?this._createProxy({...es.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.update())}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize!==e&&(typeof e=="string"?this._fontSize=parseInt(e,10):this._fontSize=e,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(e){this._fontVariant!==e&&(this._fontVariant=e,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.update())}get leading(){return this._leading}set leading(e){this._leading!==e&&(this._leading=e,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(e){this._letterSpacing!==e&&(this._letterSpacing=e,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(e){this._lineHeight!==e&&(this._lineHeight=e,this.update())}get padding(){return this._padding}set padding(e){this._padding!==e&&(this._padding=e,this.update())}get filters(){return this._filters}set filters(e){this._filters!==e&&(this._filters=Object.freeze(e),this.update())}get trim(){return this._trim}set trim(e){this._trim!==e&&(this._trim=e,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(e){this._textBaseline!==e&&(this._textBaseline=e,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(e){this._whiteSpace!==e&&(this._whiteSpace=e,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(e){this._wordWrap!==e&&(this._wordWrap=e,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(e){this._wordWrapWidth!==e&&(this._wordWrapWidth=e,this.update())}get fill(){return this._originalFill}set fill(e){e!==this._originalFill&&(this._originalFill=e,this._isFillStyle(e)&&(this._originalFill=this._createProxy({...lt.defaultFillStyle,...e},()=>{this._fill=pi({...this._originalFill},lt.defaultFillStyle)})),this._fill=pi(e===0?"black":e,lt.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...lt.defaultStrokeStyle,...e},()=>{this._stroke=sn({...this._originalStroke},lt.defaultStrokeStyle)})),this._stroke=sn(e,lt.defaultStrokeStyle),this.update())}update(){this._tick++,this.emit("update",this)}reset(){const e=es.defaultTextStyle;for(const t in e)this[t]=e[t]}get styleKey(){return`${this.uid}-${this._tick}`}clone(){return new es({align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?{...this._dropShadow}:null,fill:this._fill,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,textBaseline:this.textBaseline,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,filters:this._filters?[...this._filters]:void 0})}_getFinalPadding(){let e=0;if(this._filters)for(let t=0;t<this._filters.length;t++)e+=this._filters[t].padding;return Math.max(this._padding,e)}destroy(e=!1){if(this.removeAllListeners(),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._fill?.texture&&this._fill.texture.destroy(s),this._originalFill?.texture&&this._originalFill.texture.destroy(s),this._stroke?.texture&&this._stroke.texture.destroy(s),this._originalStroke?.texture&&this._originalStroke.texture.destroy(s)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(e,t){return new Proxy(e,{set:(s,r,n)=>(s[r]===n||(s[r]=n,t?.(r,n),this.update()),!0)})}_isFillStyle(e){return(e??null)!==null&&!(ue.isColorLike(e)||e instanceof at||e instanceof jr)}};dd.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5},dd.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let Xe=dd;function fE(i){const e=i;if(typeof e.dropShadow=="boolean"&&e.dropShadow){const t=Xe.defaultDropShadow;i.dropShadow={alpha:e.dropShadowAlpha??t.alpha,angle:e.dropShadowAngle??t.angle,blur:e.dropShadowBlur??t.blur,color:e.dropShadowColor??t.color,distance:e.dropShadowDistance??t.distance}}if(e.strokeThickness!==void 0){W(Q,"strokeThickness is now a part of stroke");const t=e.stroke;let s={};if(ue.isColorLike(t))s.color=t;else if(t instanceof at||t instanceof jr)s.fill=t;else if(Object.hasOwnProperty.call(t,"color")||Object.hasOwnProperty.call(t,"fill"))s=t;else throw new Error("Invalid stroke value.");i.stroke={...s,width:e.strokeThickness}}if(Array.isArray(e.fillGradientStops)){if(W(Q,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(e.fill)||e.fill.length===0)throw new Error("Invalid fill value. Expected an array of colors for gradient fill.");e.fill.length!==e.fillGradientStops.length&&L("The number of fill colors must match the number of fill gradient stops.");const t=new at({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),s=e.fillGradientStops.slice(),r=e.fill.map(n=>ue.shared.setValue(n).toNumber());s.forEach((n,o)=>{t.addColorStop(n,r[o])}),i.fill={fill:t}}}class pE{constructor(e){this._canvasPool=Object.create(null),this.canvasOptions=e||{},this.enableFullScreen=!1}_createCanvasAndContext(e,t){const s=Y.get().createCanvas();s.width=e,s.height=t;const r=s.getContext("2d");return{canvas:s,context:r}}getOptimalCanvasAndContext(e,t,s=1){e=Math.ceil(e*s-1e-6),t=Math.ceil(t*s-1e-6),e=ki(e),t=ki(t);const r=(e<<17)+(t<<1);this._canvasPool[r]||(this._canvasPool[r]=[]);let n=this._canvasPool[r].pop();return n||(n=this._createCanvasAndContext(e,t)),n}returnCanvasAndContext(e){const t=e.canvas,{width:s,height:r}=t,n=(s<<17)+(r<<1);e.context.resetTransform(),e.context.clearRect(0,0,s,r),this._canvasPool[n].push(e)}clear(){this._canvasPool={}}}const Gt=new pE;Bi.register(Gt);const e0=1e5;function rn(i,e,t,s=0){if(i.texture===M.WHITE&&!i.fill)return ue.shared.setValue(i.color).setAlpha(i.alpha??1).toHexa();if(i.fill){if(i.fill instanceof jr){const r=i.fill,n=e.createPattern(r.texture.source.resource,"repeat"),o=r.transform.copyTo(O.shared);return o.scale(r.texture.frame.width,r.texture.frame.height),n.setTransform(o),n}else if(i.fill instanceof at){const r=i.fill,n=r.type==="linear",o=r.textureSpace==="local";let a=1,l=1;o&&t&&(a=t.width+s,l=t.height+s);let c,h=!1;if(n){const{start:u,end:d}=r;c=e.createLinearGradient(u.x*a,u.y*l,d.x*a,d.y*l),h=Math.abs(d.x-u.x)<Math.abs((d.y-u.y)*.1)}else{const{center:u,innerRadius:d,outerCenter:f,outerRadius:p}=r;c=e.createRadialGradient(u.x*a,u.y*l,d*a,f.x*a,f.y*l,p*a)}if(h&&o&&t){const u=t.lineHeight/l;for(let d=0;d<t.lines.length;d++){const f=(d*t.lineHeight+s/2)/l;r.colorStops.forEach(p=>{const g=f+p.offset*u;c.addColorStop(Math.floor(g*e0)/e0,ue.shared.setValue(p.color).toHex())})}}else r.colorStops.forEach(u=>{c.addColorStop(u.offset,ue.shared.setValue(u.color).toHex())});return c}}else{const r=e.createPattern(i.texture.source.resource,"repeat"),n=i.matrix.copyTo(O.shared);return n.scale(i.texture.frame.width,i.texture.frame.height),r.setTransform(n),r}return L("FillStyle not recognised",i),"red"}const t0=class ry extends hg{constructor(e){super(),this.resolution=1,this.pages=[],this._padding=0,this._measureCache=Object.create(null),this._currentChars=[],this._currentX=0,this._currentY=0,this._currentMaxCharHeight=0,this._currentPageIndex=-1,this._skipKerning=!1;const t={...ry.defaultOptions,...e};this._textureSize=t.textureSize,this._mipmap=t.mipmap;const s=t.style.clone();t.overrideFill&&(s._fill.color=16777215,s._fill.alpha=1,s._fill.texture=M.WHITE,s._fill.fill=null),this.applyFillAsTint=t.overrideFill;const r=s.fontSize;s.fontSize=this.baseMeasurementFontSize;const n=Kr(s);t.overrideSize?s._stroke&&(s._stroke.width*=this.baseRenderedFontSize/r):s.fontSize=this.baseRenderedFontSize=r,this._style=s,this._skipKerning=t.skipKerning??!1,this.resolution=t.resolution??1,this._padding=t.padding??4,t.textureStyle&&(this._textureStyle=t.textureStyle instanceof wt?t.textureStyle:new wt(t.textureStyle)),this.fontMetrics=$e.measureFont(n),this.lineHeight=s.lineHeight||this.fontMetrics.fontSize||s.fontSize}ensureCharacters(e){const t=$e.graphemeSegmenter(e).filter(m=>!this._currentChars.includes(m)).filter((m,_,x)=>x.indexOf(m)===_);if(!t.length)return;this._currentChars=[...this._currentChars,...t];let s;this._currentPageIndex===-1?s=this._nextPage():s=this.pages[this._currentPageIndex];let{canvas:r,context:n}=s.canvasAndContext,o=s.texture.source;const a=this._style;let l=this._currentX,c=this._currentY,h=this._currentMaxCharHeight;const u=this.baseRenderedFontSize/this.baseMeasurementFontSize,d=this._padding*u;let f=!1;const p=r.width/this.resolution,g=r.height/this.resolution;for(let m=0;m<t.length;m++){const _=t[m],x=$e.measureText(_,a,r,!1);x.lineHeight=x.height;const y=x.width*u,v=Math.ceil((a.fontStyle==="italic"?2:1)*y),T=x.height*u,S=v+d*2,w=T+d*2;if(f=!1,_!==`
|
|
320
|
-
`&&
|
|
321
|
-
`||y){if(!a&&e.wordWrap&&m(n.width+l.width)?(g(),p(l),y||n.charPositions.push(0)):(l.start=n.width,p(l),y||n.charPositions.push(0)),
|
|
322
|
-
`)g();else if(!y){const E=v.xAdvance+(v.kerning[o]||0)+h;n.width+=E,n.spaceWidth=E,n.spacesIndex.push(n.charPositions.length),n.chars.push(x)}}else{const w=v.kerning[o]||0,E=v.xAdvance+w+h;f&&m(n.width+l.width+E)&&(p(l),g()),l.positions[l.index++]=l.width+w,l.chars.push(x),l.width+=E}o=x}return g(),e.align==="center"?mE(r):e.align==="right"?gE(r):e.align==="justify"&&_E(r),r}function mE(i){for(let e=0;e<i.lines.length;e++){const t=i.lines[e],s=i.width/2-t.width/2;for(let r=0;r<t.charPositions.length;r++)t.charPositions[r]+=s}}function gE(i){for(let e=0;e<i.lines.length;e++){const t=i.lines[e],s=i.width-t.width;for(let r=0;r<t.charPositions.length;r++)t.charPositions[r]+=s}}function _E(i){const e=i.width;for(let t=0;t<i.lines.length;t++){const s=i.lines[t];let r=0,n=s.spacesIndex[r++],o=0;const a=s.spacesIndex.length,c=(e-s.width)/a;for(let h=0;h<s.charPositions.length;h++)h===n&&(n=s.spacesIndex[r++],o+=c),s.charPositions[h]+=o}}function xE(i){if(i==="")return[];typeof i=="string"&&(i=[i]);const e=[];for(let t=0,s=i.length;t<s;t++){const r=i[t];if(Array.isArray(r)){if(r.length!==2)throw new Error(`[BitmapFont]: Invalid character range length, expecting 2 got ${r.length}.`);if(r[0].length===0||r[1].length===0)throw new Error("[BitmapFont]: Invalid character delimiter.");const n=r[0].charCodeAt(0),o=r[1].charCodeAt(0);if(o<n)throw new Error("[BitmapFont]: Invalid character range.");for(let a=n,l=o;a<=l;a++)e.push(String.fromCharCode(a))}else e.push(...Array.from(r))}if(e.length===0)throw new Error("[BitmapFont]: Empty set when resolving characters.");return e}let nn=0;class yE{constructor(){this.ALPHA=[["a","z"],["A","Z"]," "],this.NUMERIC=[["0","9"]],this.ALPHANUMERIC=[["a","z"],["A","Z"],["0","9"]," "],this.ASCII=[[" ","~"]],this.defaultOptions={chars:this.ALPHANUMERIC,resolution:1,padding:4,skipKerning:!1,textureStyle:null},this.measureCache=ug(1e3)}getFont(e,t){let s=`${t.fontFamily}-bitmap`,r=!0;if(t._fill.fill&&!t._stroke?(s+=t._fill.fill.styleKey,r=!1):(t._stroke||t.dropShadow)&&(s=`${t.styleKey}-bitmap`,r=!1),!ae.has(s)){const o=Object.create(t);o.lineHeight=0;const a=new i0({style:o,overrideFill:r,overrideSize:!0,...this.defaultOptions});nn++,nn>50&&L("BitmapText",`You have dynamically created ${nn} bitmap fonts, this can be inefficient. Try pre installing your font styles using \`BitmapFont.install({name:"style1", style})\``),a.once("destroy",()=>{nn--,ae.remove(s)}),ae.set(s,a)}const n=ae.get(s);return n.ensureCharacters?.(e),n}getLayout(e,t,s=!0){const r=this.getFont(e,t),n=`${e}-${t.styleKey}-${s}`;if(this.measureCache.has(n))return this.measureCache.get(n);const o=$e.graphemeSegmenter(e),a=fd(o,t,r,s);return this.measureCache.set(n,a),a}measureText(e,t,s=!0){return this.getLayout(e,t,s)}install(...e){let t=e[0];typeof t=="string"&&(t={name:t,style:e[1],chars:e[2]?.chars,resolution:e[2]?.resolution,padding:e[2]?.padding,skipKerning:e[2]?.skipKerning},W(Q,"BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})"));const s=t?.name;if(!s)throw new Error("[BitmapFontManager] Property `name` is required.");t={...this.defaultOptions,...t};const r=t.style,n=r instanceof Xe?r:new Xe(r),o=t.dynamicFill??this._canUseTintForStyle(n),a=new i0({style:n,overrideFill:o,skipKerning:t.skipKerning,padding:t.padding,resolution:t.resolution,overrideSize:!1,textureStyle:t.textureStyle}),l=xE(t.chars);return a.ensureCharacters(l.join("")),ae.set(`${s}-bitmap`,a),a.once("destroy",()=>ae.remove(`${s}-bitmap`)),a}uninstall(e){const t=`${e}-bitmap`,s=ae.get(t);s&&s.destroy()}_canUseTintForStyle(e){return!e._stroke&&(!e.dropShadow||e.dropShadow.color===0)&&!e._fill.fill&&e._fill.color===16777215}}const Ns=new yE;class s0 extends hg{constructor(e,t){super();const{textures:s,data:r}=e;Object.keys(r.pages).forEach(n=>{const o=r.pages[parseInt(n,10)],a=s[o.id];this.pages.push({texture:a})}),Object.keys(r.chars).forEach(n=>{const o=r.chars[n],{frame:a,source:l,rotate:c}=s[o.page],h=oe.transformRectCoords(o,a,c,new H),u=new M({frame:h,orig:new H(0,0,o.width,o.height),source:l,rotate:c});this.chars[n]={id:n.codePointAt(0),xOffset:o.xOffset,yOffset:o.yOffset,xAdvance:o.xAdvance,kerning:o.kerning??{},texture:u}}),this.baseRenderedFontSize=r.fontSize,this.baseMeasurementFontSize=r.fontSize,this.fontMetrics={ascent:0,descent:0,fontSize:r.fontSize},this.baseLineOffset=r.baseLineOffset,this.lineHeight=r.lineHeight,this.fontFamily=r.fontFamily,this.distanceField=r.distanceField??{type:"none",range:0},this.url=t}destroy(){super.destroy();for(let e=0;e<this.pages.length;e++){const{texture:t}=this.pages[e];t.destroy(!0)}this.pages=null}static install(e){Ns.install(e)}static uninstall(e){Ns.uninstall(e)}}const pd={test(i){return typeof i=="string"&&i.startsWith("info face=")},parse(i){const e=i.match(/^[a-z]+\s+.+$/gm),t={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(const u in e){const d=e[u].match(/^[a-z]+/gm)[0],f=e[u].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),p={};for(const g in f){const m=f[g].split("="),_=m[0],x=m[1].replace(/"/gm,""),y=parseFloat(x),v=isNaN(y)?x:y;p[_]=v}t[d].push(p)}const s={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},[r]=t.info,[n]=t.common,[o]=t.distanceField??[];o&&(s.distanceField={range:parseInt(o.distanceRange,10),type:o.fieldType}),s.fontSize=parseInt(r.size,10),s.fontFamily=r.face,s.lineHeight=parseInt(n.lineHeight,10);const a=t.page;for(let u=0;u<a.length;u++)s.pages.push({id:parseInt(a[u].id,10)||0,file:a[u].file});const l={};s.baseLineOffset=s.lineHeight-parseInt(n.base,10);const c=t.char;for(let u=0;u<c.length;u++){const d=c[u],f=parseInt(d.id,10);let p=d.letter??d.char??String.fromCharCode(f);p==="space"&&(p=" "),l[f]=p,s.chars[p]={id:f,page:parseInt(d.page,10)||0,x:parseInt(d.x,10),y:parseInt(d.y,10),width:parseInt(d.width,10),height:parseInt(d.height,10),xOffset:parseInt(d.xoffset,10),yOffset:parseInt(d.yoffset,10),xAdvance:parseInt(d.xadvance,10),kerning:{}}}const h=t.kerning||[];for(let u=0;u<h.length;u++){const d=parseInt(h[u].first,10),f=parseInt(h[u].second,10),p=parseInt(h[u].amount,10);s.chars[l[f]].kerning[l[d]]=p}return s}},r0={test(i){const e=i;return typeof e!="string"&&"getElementsByTagName"in e&&e.getElementsByTagName("page").length&&e.getElementsByTagName("info")[0].getAttribute("face")!==null},parse(i){const e={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},t=i.getElementsByTagName("info")[0],s=i.getElementsByTagName("common")[0],r=i.getElementsByTagName("distanceField")[0];r&&(e.distanceField={type:r.getAttribute("fieldType"),range:parseInt(r.getAttribute("distanceRange"),10)});const n=i.getElementsByTagName("page"),o=i.getElementsByTagName("char"),a=i.getElementsByTagName("kerning");e.fontSize=parseInt(t.getAttribute("size"),10),e.fontFamily=t.getAttribute("face"),e.lineHeight=parseInt(s.getAttribute("lineHeight"),10);for(let c=0;c<n.length;c++)e.pages.push({id:parseInt(n[c].getAttribute("id"),10)||0,file:n[c].getAttribute("file")});const l={};e.baseLineOffset=e.lineHeight-parseInt(s.getAttribute("base"),10);for(let c=0;c<o.length;c++){const h=o[c],u=parseInt(h.getAttribute("id"),10);let d=h.getAttribute("letter")??h.getAttribute("char")??String.fromCharCode(u);d==="space"&&(d=" "),l[u]=d,e.chars[d]={id:u,page:parseInt(h.getAttribute("page"),10)||0,x:parseInt(h.getAttribute("x"),10),y:parseInt(h.getAttribute("y"),10),width:parseInt(h.getAttribute("width"),10),height:parseInt(h.getAttribute("height"),10),xOffset:parseInt(h.getAttribute("xoffset"),10),yOffset:parseInt(h.getAttribute("yoffset"),10),xAdvance:parseInt(h.getAttribute("xadvance"),10),kerning:{}}}for(let c=0;c<a.length;c++){const h=parseInt(a[c].getAttribute("first"),10),u=parseInt(a[c].getAttribute("second"),10),d=parseInt(a[c].getAttribute("amount"),10);e.chars[l[u]].kerning[l[h]]=d}return e}},n0={test(i){return typeof i=="string"&&i.match(/<font(\s|>)/)?r0.test(Y.get().parseXML(i)):!1},parse(i){return r0.parse(Y.get().parseXML(i))}},vE=[".xml",".fnt"],bE={extension:{type:b.CacheParser,name:"cacheBitmapFont"},test:i=>i instanceof s0,getCacheableAssets(i,e){const t={};return i.forEach(s=>{t[s]=e,t[`${s}-bitmap`]=e}),t[`${e.fontFamily}-bitmap`]=e,t}},TE={extension:{type:b.LoadParser,priority:Kt.Normal},name:"loadBitmapFont",id:"bitmap-font",test(i){return vE.includes(Je.extname(i).toLowerCase())},async testParse(i){return pd.test(i)||n0.test(i)},async parse(i,e,t){const s=pd.test(i)?pd.parse(i):n0.parse(i),{src:r}=e,{pages:n}=s,o=[],a=s.distanceField?{scaleMode:"linear",alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:!1,resolution:1}:{};for(let u=0;u<n.length;++u){const d=n[u].file;let f=Je.join(Je.dirname(r),d);f=Su(f,r),o.push({src:f,data:a})}const l=await t.load(o),c=o.map(u=>l[u.src]);return new s0({data:s,textures:c},r)},async load(i,e){return await(await Y.get().fetch(i)).text()},async unload(i,e,t){await Promise.all(i.pages.map(s=>t.unload(s.texture.source._sourceOrigin))),i.destroy()}};class wE{constructor(e,t=!1){this._loader=e,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=t}add(e){e.forEach(t=>{this._assetList.push(t)}),this.verbose&&console.log("[BackgroundLoader] assets: ",this._assetList),this._isActive&&!this._isLoading&&this._next()}async _next(){if(this._assetList.length&&this._isActive){this._isLoading=!0;const e=[],t=Math.min(this._assetList.length,this._maxConcurrent);for(let s=0;s<t;s++)e.push(this._assetList.pop());await this._loader.load(e),this._isLoading=!1,this._next()}}get active(){return this._isActive}set active(e){this._isActive!==e&&(this._isActive=e,e&&!this._isLoading&&this._next())}}const SE={extension:{type:b.CacheParser,name:"cacheTextureArray"},test:i=>Array.isArray(i)&&i.every(e=>e instanceof M),getCacheableAssets:(i,e)=>{const t={};return i.forEach(s=>{e.forEach((r,n)=>{t[s+(n===0?"":n+1)]=r})}),t}};async function o0(i){if("Image"in globalThis)return new Promise(e=>{const t=new Image;t.onload=()=>{e(!0)},t.onerror=()=>{e(!1)},t.src=i});if("createImageBitmap"in globalThis&&"fetch"in globalThis){try{const e=await(await fetch(i)).blob();await createImageBitmap(e)}catch{return!1}return!0}return!1}const CE={extension:{type:b.DetectionParser,priority:1},test:async()=>o0("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async i=>[...i,"avif"],remove:async i=>i.filter(e=>e!=="avif")},a0=["png","jpg","jpeg"],AE={extension:{type:b.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async i=>[...i,...a0],remove:async i=>i.filter(e=>!a0.includes(e))},EE="WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function on(i){return EE?!1:document.createElement("video").canPlayType(i)!==""}const IE={extension:{type:b.DetectionParser,priority:0},test:async()=>on("video/mp4"),add:async i=>[...i,"mp4","m4v"],remove:async i=>i.filter(e=>e!=="mp4"&&e!=="m4v")},PE={extension:{type:b.DetectionParser,priority:0},test:async()=>on("video/ogg"),add:async i=>[...i,"ogv"],remove:async i=>i.filter(e=>e!=="ogv")},RE={extension:{type:b.DetectionParser,priority:0},test:async()=>on("video/webm"),add:async i=>[...i,"webm"],remove:async i=>i.filter(e=>e!=="webm")},ME={extension:{type:b.DetectionParser,priority:0},test:async()=>o0("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async i=>[...i,"webp"],remove:async i=>i.filter(e=>e!=="webp")},l0=class _n{constructor(){this.loadOptions={..._n.defaultOptions},this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(e,t,s)=>(this._parsersValidated=!1,e[t]=s,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(e,t){const s={promise:null,parser:null};return s.promise=(async()=>{let r=null,n=null;if((t.parser||t.loadParser)&&(n=this._parserHash[t.parser||t.loadParser],t.loadParser&&L(`[Assets] "loadParser" is deprecated, use "parser" instead for ${e}`),n||L(`[Assets] specified load parser "${t.parser||t.loadParser}" not found while loading ${e}`)),!n){for(let o=0;o<this.parsers.length;o++){const a=this.parsers[o];if(a.load&&a.test?.(e,t,this)){n=a;break}}if(!n)return L(`[Assets] ${e} could not be loaded as we don't know how to parse it, ensure the correct parser has been added`),null}r=await n.load(e,t,this),s.parser=n;for(let o=0;o<this.parsers.length;o++){const a=this.parsers[o];a.parse&&a.parse&&await a.testParse?.(r,t,this)&&(r=await a.parse(r,t,this)||r,s.parser=a)}return r})(),s}async load(e,t){this._parsersValidated||this._validateParsers();const s=typeof t=="function"?{..._n.defaultOptions,...this.loadOptions,onProgress:t}:{..._n.defaultOptions,...this.loadOptions,...t||{}},{onProgress:r,onError:n,strategy:o,retryCount:a,retryDelay:l}=s;let c=0;const h={},u=zr(e),d=ut(e,g=>({alias:[g],src:g,data:{}})),f=d.reduce((g,m)=>g+(m.progressSize||1),0),p=d.map(async g=>{const m=Je.toAbsolute(g.src);h[g.src]||(await this._loadAssetWithRetry(m,g,{onProgress:r,onError:n,strategy:o,retryCount:a,retryDelay:l},h),c+=g.progressSize||1,r&&r(c/f))});return await Promise.all(p),u?h[d[0].src]:h}async unload(e){const s=ut(e,r=>({alias:[r],src:r})).map(async r=>{const n=Je.toAbsolute(r.src),o=this.promiseCache[n];if(o){const a=await o.promise;delete this.promiseCache[n],await o.parser?.unload?.(a,r,this)}});await Promise.all(s)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(e=>e.name||e.id).reduce((e,t)=>(!t.name&&!t.id?L("[Assets] parser should have an id"):(e[t.name]||e[t.id])&&L(`[Assets] parser id conflict "${t.id}"`),e[t.name]=t,t.id&&(e[t.id]=t),e),{})}async _loadAssetWithRetry(e,t,s,r){let n=0;const{onError:o,strategy:a,retryCount:l,retryDelay:c}=s,h=u=>new Promise(d=>setTimeout(d,u));for(;;)try{this.promiseCache[e]||(this.promiseCache[e]=this._getLoadPromiseAndParser(e,t)),r[t.src]=await this.promiseCache[e].promise;return}catch(u){delete this.promiseCache[e],delete r[t.src],n++;const d=a!=="retry"||n>l;if(a==="retry"&&!d){o&&o(u,t),await h(c);continue}if(a==="skip"){o&&o(u,t);return}throw o&&o(u,t),new Error(`[Loader.load] Failed to load ${e}.
|
|
319
|
+
`}},Mg={};function id(i){let e=Mg[i];if(e)return e;const t=new Int32Array(i);for(let s=0;s<i;s++)t[s]=s;return e=Mg[i]=new He({uTextures:{value:t,type:"i32",size:i}},{isStatic:!0}),e}class kg extends ot{constructor(e){const t=Fs({name:"batch",bits:[Zu,td(e),Us]}),s=ks({name:"batch",bits:[ju,Qu(e),Bs]});super({glProgram:t,gpuProgram:s,resources:{batchSamplers:id(e)}}),this.maxTextures=e}}let Os=null;const Fg=class sy extends YC{constructor(e){super(e),this.geometry=new JC,this.name=sy.extension.name,this.vertexSize=6,Os??(Os=new kg(e.maxTextures)),this.shader=Os}packAttributes(e,t,s,r,n){const o=n<<16|e.roundPixels&65535,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,d=a.tx,f=a.ty,{positions:p,uvs:g}=e,m=e.color,x=e.attributeOffset,_=x+e.attributeSize;for(let y=x;y<_;y++){const v=y*2,T=p[v],S=p[v+1];t[r++]=l*T+h*S+d,t[r++]=u*S+c*T+f,t[r++]=g[v],t[r++]=g[v+1],s[r++]=m,s[r++]=o}}packQuadAttributes(e,t,s,r,n){const o=e.texture,a=e.transform,l=a.a,c=a.b,h=a.c,u=a.d,d=a.tx,f=a.ty,p=e.bounds,g=p.maxX,m=p.minX,x=p.maxY,_=p.minY,y=o.uvs,v=e.color,T=n<<16|e.roundPixels&65535;t[r+0]=l*m+h*_+d,t[r+1]=u*_+c*m+f,t[r+2]=y.x0,t[r+3]=y.y0,s[r+4]=v,s[r+5]=T,t[r+6]=l*g+h*_+d,t[r+7]=u*_+c*g+f,t[r+8]=y.x1,t[r+9]=y.y1,s[r+10]=v,s[r+11]=T,t[r+12]=l*g+h*x+d,t[r+13]=u*x+c*g+f,t[r+14]=y.x2,t[r+15]=y.y2,s[r+16]=v,s[r+17]=T,t[r+18]=l*m+h*x+d,t[r+19]=u*x+c*m+f,t[r+20]=y.x3,t[r+21]=y.y3,s[r+22]=v,s[r+23]=T}_updateMaxTextures(e){this.shader.maxTextures!==e&&(Os=new kg(e),this.shader=Os)}destroy(){this.shader=null,super.destroy()}};Fg.extension={type:[b.Batcher],name:"default"};let sd=Fg;function gA(i,e,t,s,r,n,o,a=null){let l=0;t*=e,r*=n;const c=a.a,h=a.b,u=a.c,d=a.d,f=a.tx,p=a.ty;for(;l<o;){const g=i[t],m=i[t+1];s[r]=c*g+u*m+f,s[r+1]=h*g+d*m+p,r+=n,t+=e,l++}}function xA(i,e,t,s){let r=0;for(e*=t;r<s;)i[e]=0,i[e+1]=0,e+=t,r++}function Bg(i,e,t,s,r){const n=e.a,o=e.b,a=e.c,l=e.d,c=e.tx,h=e.ty;t||(t=0),s||(s=2),r||(r=i.length/s-t);let u=t*s;for(let d=0;d<r;d++){const f=i[u],p=i[u+1];i[u]=n*f+a*p+c,i[u+1]=o*f+l*p+h,u+=s}}const _A=new O;class rd{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,s=this.renderable;return s?am(t,s.groupColor)+(this.alpha*s.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){return this.renderable?.groupTransform||_A}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const Ds={extension:{type:b.ShapeBuilder,name:"circle"},build(i,e){let t,s,r,n,o,a;if(i.type==="circle"){const v=i;if(o=a=v.radius,o<=0)return!1;t=v.x,s=v.y,r=n=0}else if(i.type==="ellipse"){const v=i;if(o=v.halfWidth,a=v.halfHeight,o<=0||a<=0)return!1;t=v.x,s=v.y,r=n=0}else{const v=i,T=v.width/2,S=v.height/2;t=v.x+T,s=v.y+S,o=a=Math.max(0,Math.min(v.radius,Math.min(T,S))),r=T-o,n=S-a}if(r<0||n<0)return!1;const l=Math.ceil(2.3*Math.sqrt(o+a)),c=l*8+(r?4:0)+(n?4:0);if(c===0)return!1;if(l===0)return e[0]=e[6]=t+r,e[1]=e[3]=s+n,e[2]=e[4]=t-r,e[5]=e[7]=s-n,!0;let h=0,u=l*4+(r?2:0)+2,d=u,f=c,p=r+o,g=n,m=t+p,x=t-p,_=s+g;if(e[h++]=m,e[h++]=_,e[--u]=_,e[--u]=x,n){const v=s-g;e[d++]=x,e[d++]=v,e[--f]=v,e[--f]=m}for(let v=1;v<l;v++){const T=Math.PI/2*(v/l),S=r+Math.cos(T)*o,w=n+Math.sin(T)*a,E=t+S,P=t-S,C=s+w,A=s-w;e[h++]=E,e[h++]=C,e[--u]=C,e[--u]=P,e[d++]=P,e[d++]=A,e[--f]=A,e[--f]=E}p=r,g=n+a,m=t+p,x=t-p,_=s+g;const y=s-g;return e[h++]=m,e[h++]=_,e[--f]=y,e[--f]=m,r&&(e[h++]=x,e[h++]=_,e[--f]=y,e[--f]=x),!0},triangulate(i,e,t,s,r,n){if(i.length===0)return;let o=0,a=0;for(let h=0;h<i.length;h+=2)o+=i[h],a+=i[h+1];o/=i.length/2,a/=i.length/2;let l=s;e[l*t]=o,e[l*t+1]=a;const c=l++;for(let h=0;h<i.length;h+=2)e[l*t]=i[h],e[l*t+1]=i[h+1],h>0&&(r[n++]=l,r[n++]=c,r[n++]=l-1),l++;r[n++]=c+1,r[n++]=c,r[n++]=l-1}},yA={...Ds,extension:{...Ds.extension,name:"ellipse"}},vA={...Ds,extension:{...Ds.extension,name:"roundedRectangle"}},Ug=1e-4,Og=1e-4;function bA(i){const e=i.length;if(e<6)return 1;let t=0;for(let s=0,r=i[e-2],n=i[e-1];s<e;s+=2){const o=i[s],a=i[s+1];t+=(o-r)*(a+n),r=o,n=a}return t<0?-1:1}function Dg(i,e,t,s,r,n,o,a){const l=i-t*r,c=e-s*r,h=i+t*n,u=e+s*n;let d,f;o?(d=s,f=-t):(d=-s,f=t);const p=l+d,g=c+f,m=h+d,x=u+f;return a.push(p,g),a.push(m,x),2}function fi(i,e,t,s,r,n,o,a){const l=t-i,c=s-e;let h=Math.atan2(l,c),u=Math.atan2(r-i,n-e);a&&h<u?h+=Math.PI*2:!a&&h>u&&(u+=Math.PI*2);let d=h;const f=u-h,p=Math.abs(f),g=Math.sqrt(l*l+c*c),m=(15*p*Math.sqrt(g)/Math.PI>>0)+1,x=f/m;if(d+=x,a){o.push(i,e),o.push(t,s);for(let _=1,y=d;_<m;_++,y+=x)o.push(i,e),o.push(i+Math.sin(y)*g,e+Math.cos(y)*g);o.push(i,e),o.push(r,n)}else{o.push(t,s),o.push(i,e);for(let _=1,y=d;_<m;_++,y+=x)o.push(i+Math.sin(y)*g,e+Math.cos(y)*g),o.push(i,e);o.push(r,n),o.push(i,e)}return m*2}function TA(i,e,t,s,r,n){const o=Ug;if(i.length===0)return;const a=e;let l=a.alignment;if(e.alignment!==.5){let G=bA(i);l=(l-.5)*G+.5}const c=new X(i[0],i[1]),h=new X(i[i.length-2],i[i.length-1]),u=s,d=Math.abs(c.x-h.x)<o&&Math.abs(c.y-h.y)<o;if(u){i=i.slice(),d&&(i.pop(),i.pop(),h.set(i[i.length-2],i[i.length-1]));const G=(c.x+h.x)*.5,ie=(h.y+c.y)*.5;i.unshift(G,ie),i.push(G,ie)}const f=r,p=i.length/2;let g=i.length;const m=f.length/2,x=a.width/2,_=x*x,y=a.miterLimit*a.miterLimit;let v=i[0],T=i[1],S=i[2],w=i[3],E=0,P=0,C=-(T-w),A=v-S,U=0,D=0,$=Math.sqrt(C*C+A*A);C/=$,A/=$,C*=x,A*=x;const pe=l,k=(1-pe)*2,F=pe*2;u||(a.cap==="round"?g+=fi(v-C*(k-F)*.5,T-A*(k-F)*.5,v-C*k,T-A*k,v+C*F,T+A*F,f,!0)+2:a.cap==="square"&&(g+=Dg(v,T,C,A,k,F,!0,f))),f.push(v-C*k,T-A*k),f.push(v+C*F,T+A*F);for(let G=1;G<p-1;++G){v=i[(G-1)*2],T=i[(G-1)*2+1],S=i[G*2],w=i[G*2+1],E=i[(G+1)*2],P=i[(G+1)*2+1],C=-(T-w),A=v-S,$=Math.sqrt(C*C+A*A),C/=$,A/=$,C*=x,A*=x,U=-(w-P),D=S-E,$=Math.sqrt(U*U+D*D),U/=$,D/=$,U*=x,D*=x;const ie=S-v,we=T-w,ce=S-E,Ce=P-w,Oe=ie*ce+we*Ce,N=we*ce-Ce*ie,K=N<0;if(Math.abs(N)<.001*Math.abs(Oe)){f.push(S-C*k,w-A*k),f.push(S+C*F,w+A*F),Oe>=0&&(a.join==="round"?g+=fi(S,w,S-C*k,w-A*k,S-U*k,w-D*k,f,!1)+4:g+=2,f.push(S-U*F,w-D*F),f.push(S+U*k,w+D*k));continue}const me=(-C+v)*(-A+w)-(-C+S)*(-A+T),Ie=(-U+E)*(-D+w)-(-U+S)*(-D+P),Qi=(ie*Ie-ce*me)/N,ti=(Ce*me-we*Ie)/N,Et=(Qi-S)*(Qi-S)+(ti-w)*(ti-w),qe=S+(Qi-S)*k,xt=w+(ti-w)*k,yi=S-(Qi-S)*F,vi=w-(ti-w)*F,_k=Math.min(ie*ie+we*we,ce*ce+Ce*Ce),V_=K?k:F,yk=_k+V_*V_*_;Et<=yk?a.join==="bevel"||Et/_>y?(K?(f.push(qe,xt),f.push(S+C*F,w+A*F),f.push(qe,xt),f.push(S+U*F,w+D*F)):(f.push(S-C*k,w-A*k),f.push(yi,vi),f.push(S-U*k,w-D*k),f.push(yi,vi)),g+=2):a.join==="round"?K?(f.push(qe,xt),f.push(S+C*F,w+A*F),g+=fi(S,w,S+C*F,w+A*F,S+U*F,w+D*F,f,!0)+4,f.push(qe,xt),f.push(S+U*F,w+D*F)):(f.push(S-C*k,w-A*k),f.push(yi,vi),g+=fi(S,w,S-C*k,w-A*k,S-U*k,w-D*k,f,!1)+4,f.push(S-U*k,w-D*k),f.push(yi,vi)):(f.push(qe,xt),f.push(yi,vi)):(f.push(S-C*k,w-A*k),f.push(S+C*F,w+A*F),a.join==="round"?K?g+=fi(S,w,S+C*F,w+A*F,S+U*F,w+D*F,f,!0)+2:g+=fi(S,w,S-C*k,w-A*k,S-U*k,w-D*k,f,!1)+2:a.join==="miter"&&Et/_<=y&&(K?(f.push(yi,vi),f.push(yi,vi)):(f.push(qe,xt),f.push(qe,xt)),g+=2),f.push(S-U*k,w-D*k),f.push(S+U*F,w+D*F),g+=2)}v=i[(p-2)*2],T=i[(p-2)*2+1],S=i[(p-1)*2],w=i[(p-1)*2+1],C=-(T-w),A=v-S,$=Math.sqrt(C*C+A*A),C/=$,A/=$,C*=x,A*=x,f.push(S-C*k,w-A*k),f.push(S+C*F,w+A*F),u||(a.cap==="round"?g+=fi(S-C*(k-F)*.5,w-A*(k-F)*.5,S-C*k,w-A*k,S+C*F,w+A*F,f,!1)+2:a.cap==="square"&&(g+=Dg(S,w,C,A,k,F,!1,f)));const ne=Og*Og;for(let G=m;G<g+m-2;++G)v=f[G*2],T=f[G*2+1],S=f[(G+1)*2],w=f[(G+1)*2+1],E=f[(G+2)*2],P=f[(G+2)*2+1],!(Math.abs(v*(w-P)+S*(P-T)+E*(T-w))<ne)&&n.push(G,G+1,G+2)}function wA(i,e,t,s){const r=Ug;if(i.length===0)return;const n=i[0],o=i[1],a=i[i.length-2],l=i[i.length-1],c=e||Math.abs(n-a)<r&&Math.abs(o-l)<r,h=t,u=i.length/2,d=h.length/2;for(let f=0;f<u;f++)h.push(i[f*2]),h.push(i[f*2+1]);for(let f=0;f<u-1;f++)s.push(d+f,d+f+1);c&&s.push(d+u-1,d)}function Gg(i,e,t,s,r,n,o){const a=CC(i,e,2);if(!a)return;for(let c=0;c<a.length;c+=3)n[o++]=a[c]+r,n[o++]=a[c+1]+r,n[o++]=a[c+2]+r;let l=r*s;for(let c=0;c<i.length;c+=2)t[l]=i[c],t[l+1]=i[c+1],l+=s}const SA=[],CA={extension:{type:b.ShapeBuilder,name:"polygon"},build(i,e){for(let t=0;t<i.points.length;t++)e[t]=i.points[t];return!0},triangulate(i,e,t,s,r,n){Gg(i,SA,e,t,s,r,n)}},AA={extension:{type:b.ShapeBuilder,name:"rectangle"},build(i,e){const t=i,s=t.x,r=t.y,n=t.width,o=t.height;return n>0&&o>0?(e[0]=s,e[1]=r,e[2]=s+n,e[3]=r,e[4]=s+n,e[5]=r+o,e[6]=s,e[7]=r+o,!0):!1},triangulate(i,e,t,s,r,n){let o=0;s*=t,e[s+o]=i[0],e[s+o+1]=i[1],o+=t,e[s+o]=i[2],e[s+o+1]=i[3],o+=t,e[s+o]=i[6],e[s+o+1]=i[7],o+=t,e[s+o]=i[4],e[s+o+1]=i[5],o+=t;const a=s/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2,r[n++]=a+1,r[n++]=a+3,r[n++]=a+2}},EA={extension:{type:b.ShapeBuilder,name:"triangle"},build(i,e){return e[0]=i.x,e[1]=i.y,e[2]=i.x2,e[3]=i.y2,e[4]=i.x3,e[5]=i.y3,!0},triangulate(i,e,t,s,r,n){let o=0;s*=t,e[s+o]=i[0],e[s+o+1]=i[1],o+=t,e[s+o]=i[2],e[s+o+1]=i[3],o+=t,e[s+o]=i[4],e[s+o+1]=i[5];const a=s/t;r[n++]=a,r[n++]=a+1,r[n++]=a+2}},IA=new O,PA=new H;function RA(i,e,t,s){const r=e.matrix?i.copyFrom(e.matrix).invert():i.identity();if(e.textureSpace==="local"){const o=t.getBounds(PA);e.width&&o.pad(e.width);const{x:a,y:l}=o,c=1/o.width,h=1/o.height,u=-a*c,d=-l*h,f=r.a,p=r.b,g=r.c,m=r.d;r.a*=c,r.b*=c,r.c*=h,r.d*=h,r.tx=u*f+d*g+r.tx,r.ty=u*p+d*m+r.ty}else r.translate(e.texture.frame.x,e.texture.frame.y),r.scale(1/e.texture.source.width,1/e.texture.source.height);const n=e.texture.source.style;return!(e.fill instanceof at)&&n.addressMode==="clamp-to-edge"&&(n.addressMode="repeat",n.update()),s&&r.append(IA.copyFrom(s).invert()),r}const en={};V.handleByMap(b.ShapeBuilder,en),V.add(AA,CA,EA,Ds,yA,vA);const MA=new H,kA=new O;function FA(i,e){const{geometryData:t,batches:s}=e;s.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let r=0;r<i.instructions.length;r++){const n=i.instructions[r];if(n.action==="texture")BA(n.data,s,t);else if(n.action==="fill"||n.action==="stroke"){const o=n.action==="stroke",a=n.data.path.shapePath,l=n.data.style,c=n.data.hole;o&&c&&zg(c.shapePath,l,!0,s,t),c&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=c.shapePath.shapePrimitives),zg(a,l,o,s,t)}}}function BA(i,e,t){const s=[],r=en.rectangle,n=MA;n.x=i.dx,n.y=i.dy,n.width=i.dw,n.height=i.dh;const o=i.transform;if(!r.build(n,s))return;const{vertices:a,uvs:l,indices:c}=t,h=c.length,u=a.length/2;o&&Bg(s,o),r.triangulate(s,a,2,u,c,h);const d=i.image,f=d.uvs;l.push(f.x0,f.y0,f.x1,f.y1,f.x3,f.y3,f.x2,f.y2);const p=Se.get(rd);p.indexOffset=h,p.indexSize=c.length-h,p.attributeOffset=u,p.attributeSize=a.length/2-u,p.baseColor=i.style,p.alpha=i.alpha,p.texture=d,p.geometryData=t,e.push(p)}function zg(i,e,t,s,r){const{vertices:n,uvs:o,indices:a}=r;i.shapePrimitives.forEach(({shape:l,transform:c,holes:h})=>{const u=[],d=en[l.type];if(!d.build(l,u))return;const f=a.length,p=n.length/2;let g="triangle-list";if(c&&Bg(u,c),t){const y=l.closePath??!0,v=e;v.pixelLine?(wA(u,y,n,a),g="line-list"):TA(u,v,!1,y,n,a)}else if(h){const y=[],v=u.slice();UA(h).forEach(S=>{y.push(v.length/2),v.push(...S)}),Gg(v,y,n,2,p,a,f)}else d.triangulate(u,n,2,p,a,f);const m=o.length/2,x=e.texture;if(x!==M.WHITE){const y=RA(kA,e,l,c);gA(n,2,p,o,m,2,n.length/2-p,y)}else xA(o,m,2,n.length/2-p);const _=Se.get(rd);_.indexOffset=f,_.indexSize=a.length-f,_.attributeOffset=p,_.attributeSize=n.length/2-p,_.baseColor=e.color,_.alpha=e.alpha,_.texture=x,_.geometryData=r,_.topology=g,s.push(_)})}function UA(i){const e=[];for(let t=0;t<i.length;t++){const s=i[t].shape,r=[];en[s.type].build(s,r)&&e.push(r)}return e}class OA{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}}class DA{constructor(){this.instructions=new um}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new sd({maxTextures:t}),this.instructions.reset()}get geometry(){return W(Y1,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const nd=class hf{constructor(e){this._gpuContextHash={},this._graphicsDataContextHash=Object.create(null),this._renderer=e,e.renderableGC.addManagedHash(this,"_gpuContextHash"),e.renderableGC.addManagedHash(this,"_graphicsDataContextHash")}init(e){hf.defaultOptions.bezierSmoothness=e?.bezierSmoothness??hf.defaultOptions.bezierSmoothness}getContextRenderData(e){return this._graphicsDataContextHash[e.uid]||this._initContextRenderData(e)}updateGpuContext(e){let t=this._gpuContextHash[e.uid]||this._initContext(e);if(e.dirty){t?this._cleanGraphicsContextData(e):t=this._initContext(e),FA(e,t);const s=e.batchMode;e.customShader||s==="no-batch"?t.isBatchable=!1:s==="auto"?t.isBatchable=t.geometryData.vertices.length<400:t.isBatchable=!0,e.dirty=!1}return t}getGpuContext(e){return this._gpuContextHash[e.uid]||this._initContext(e)}_initContextRenderData(e){const t=Se.get(DA,{maxTextures:this._renderer.limits.maxBatchableTextures}),{batches:s,geometryData:r}=this._gpuContextHash[e.uid],n=r.vertices.length,o=r.indices.length;for(let h=0;h<s.length;h++)s[h].applyTransform=!1;const a=t.batcher;a.ensureAttributeBuffer(n),a.ensureIndexBuffer(o),a.begin();for(let h=0;h<s.length;h++){const u=s[h];a.add(u)}a.finish(t.instructions);const l=a.geometry;l.indexBuffer.setDataWithSize(a.indexBuffer,a.indexSize,!0),l.buffers[0].setDataWithSize(a.attributeBuffer.float32View,a.attributeSize,!0);const c=a.batches;for(let h=0;h<c.length;h++){const u=c[h];u.bindGroup=Yu(u.textures.textures,u.textures.count,this._renderer.limits.maxBatchableTextures)}return this._graphicsDataContextHash[e.uid]=t,t}_initContext(e){const t=new OA;return t.context=e,this._gpuContextHash[e.uid]=t,e.on("destroy",this.onGraphicsContextDestroy,this),this._gpuContextHash[e.uid]}onGraphicsContextDestroy(e){this._cleanGraphicsContextData(e),e.off("destroy",this.onGraphicsContextDestroy,this),this._gpuContextHash[e.uid]=null}_cleanGraphicsContextData(e){const t=this._gpuContextHash[e.uid];t.isBatchable||this._graphicsDataContextHash[e.uid]&&(Se.return(this.getContextRenderData(e)),this._graphicsDataContextHash[e.uid]=null),t.batches&&t.batches.forEach(s=>{Se.return(s)})}destroy(){for(const e in this._gpuContextHash)this._gpuContextHash[e]&&this.onGraphicsContextDestroy(this._gpuContextHash[e].context);this._gpuContextHash={},this._graphicsDataContextHash={},this._renderer=null}};nd.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"graphicsContext"},nd.defaultOptions={bezierSmoothness:.5};let od=nd;const GA=8,tn=11920929e-14,zA=1;function Ng(i,e,t,s,r,n,o,a,l,c){const u=Math.min(.99,Math.max(0,c??od.defaultOptions.bezierSmoothness));let d=(zA-u)/1;return d*=d,NA(e,t,s,r,n,o,a,l,i,d),i}function NA(i,e,t,s,r,n,o,a,l,c){ad(i,e,t,s,r,n,o,a,l,c,0),l.push(o,a)}function ad(i,e,t,s,r,n,o,a,l,c,h){if(h>GA)return;const u=(i+t)/2,d=(e+s)/2,f=(t+r)/2,p=(s+n)/2,g=(r+o)/2,m=(n+a)/2,x=(u+f)/2,_=(d+p)/2,y=(f+g)/2,v=(p+m)/2,T=(x+y)/2,S=(_+v)/2;if(h>0){let w=o-i,E=a-e;const P=Math.abs((t-o)*E-(s-a)*w),C=Math.abs((r-o)*E-(n-a)*w);if(P>tn&&C>tn){if((P+C)*(P+C)<=c*(w*w+E*E)){l.push(T,S);return}}else if(P>tn){if(P*P<=c*(w*w+E*E)){l.push(T,S);return}}else if(C>tn){if(C*C<=c*(w*w+E*E)){l.push(T,S);return}}else if(w=T-(i+o)/2,E=S-(e+a)/2,w*w+E*E<=c){l.push(T,S);return}}ad(i,e,u,d,x,_,T,S,l,c,h+1),ad(T,S,y,v,g,m,o,a,l,c,h+1)}const LA=8,HA=11920929e-14,WA=1;function VA(i,e,t,s,r,n,o,a){const c=Math.min(.99,Math.max(0,a??od.defaultOptions.bezierSmoothness));let h=(WA-c)/1;return h*=h,$A(e,t,s,r,n,o,i,h),i}function $A(i,e,t,s,r,n,o,a){ld(o,i,e,t,s,r,n,a,0),o.push(r,n)}function ld(i,e,t,s,r,n,o,a,l){if(l>LA)return;const c=(e+s)/2,h=(t+r)/2,u=(s+n)/2,d=(r+o)/2,f=(c+u)/2,p=(h+d)/2;let g=n-e,m=o-t;const x=Math.abs((s-n)*m-(r-o)*g);if(x>HA){if(x*x<=a*(g*g+m*m)){i.push(f,p);return}}else if(g=f-(e+n)/2,m=p-(t+o)/2,g*g+m*m<=a){i.push(f,p);return}ld(i,e,t,c,h,f,p,a,l+1),ld(i,f,p,u,d,n,o,a,l+1)}function Lg(i,e,t,s,r,n,o,a){let l=Math.abs(r-n);(!o&&r>n||o&&n>r)&&(l=2*Math.PI-l),a||(a=Math.max(6,Math.floor(6*Math.pow(s,1/3)*(l/Math.PI)))),a=Math.max(a,3);let c=l/a,h=r;c*=o?-1:1;for(let u=0;u<a+1;u++){const d=Math.cos(h),f=Math.sin(h),p=e+d*s,g=t+f*s;i.push(p,g),h+=c}}function XA(i,e,t,s,r,n){const o=i[i.length-2],l=i[i.length-1]-t,c=o-e,h=r-t,u=s-e,d=Math.abs(l*u-c*h);if(d<1e-8||n===0){(i[i.length-2]!==e||i[i.length-1]!==t)&&i.push(e,t);return}const f=l*l+c*c,p=h*h+u*u,g=l*h+c*u,m=n*Math.sqrt(f)/d,x=n*Math.sqrt(p)/d,_=m*g/f,y=x*g/p,v=m*u+x*c,T=m*h+x*l,S=c*(x+_),w=l*(x+_),E=u*(m+y),P=h*(m+y),C=Math.atan2(w-T,S-v),A=Math.atan2(P-T,E-v);Lg(i,v+e,T+t,n,C,A,c*h>u*l)}const Gs=Math.PI*2,cd={centerX:0,centerY:0,ang1:0,ang2:0},hd=({x:i,y:e},t,s,r,n,o,a,l)=>{i*=t,e*=s;const c=r*i-n*e,h=n*i+r*e;return l.x=c+o,l.y=h+a,l};function YA(i,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),s=e===1.5707963267948966?.551915024494:t,r=Math.cos(i),n=Math.sin(i),o=Math.cos(i+e),a=Math.sin(i+e);return[{x:r-n*s,y:n+r*s},{x:o+a*s,y:a-o*s},{x:o,y:a}]}const Hg=(i,e,t,s)=>{const r=i*s-e*t<0?-1:1;let n=i*t+e*s;return n>1&&(n=1),n<-1&&(n=-1),r*Math.acos(n)},qA=(i,e,t,s,r,n,o,a,l,c,h,u,d)=>{const f=Math.pow(r,2),p=Math.pow(n,2),g=Math.pow(h,2),m=Math.pow(u,2);let x=f*p-f*m-p*g;x<0&&(x=0),x/=f*m+p*g,x=Math.sqrt(x)*(o===a?-1:1);const _=x*r/n*u,y=x*-n/r*h,v=c*_-l*y+(i+t)/2,T=l*_+c*y+(e+s)/2,S=(h-_)/r,w=(u-y)/n,E=(-h-_)/r,P=(-u-y)/n,C=Hg(1,0,S,w);let A=Hg(S,w,E,P);a===0&&A>0&&(A-=Gs),a===1&&A<0&&(A+=Gs),d.centerX=v,d.centerY=T,d.ang1=C,d.ang2=A};function KA(i,e,t,s,r,n,o,a=0,l=0,c=0){if(n===0||o===0)return;const h=Math.sin(a*Gs/360),u=Math.cos(a*Gs/360),d=u*(e-s)/2+h*(t-r)/2,f=-h*(e-s)/2+u*(t-r)/2;if(d===0&&f===0)return;n=Math.abs(n),o=Math.abs(o);const p=Math.pow(d,2)/Math.pow(n,2)+Math.pow(f,2)/Math.pow(o,2);p>1&&(n*=Math.sqrt(p),o*=Math.sqrt(p)),qA(e,t,s,r,n,o,l,c,h,u,d,f,cd);let{ang1:g,ang2:m}=cd;const{centerX:x,centerY:_}=cd;let y=Math.abs(m)/(Gs/4);Math.abs(1-y)<1e-7&&(y=1);const v=Math.max(Math.ceil(y),1);m/=v;let T=i[i.length-2],S=i[i.length-1];const w={x:0,y:0};for(let E=0;E<v;E++){const P=YA(g,m),{x:C,y:A}=hd(P[0],n,o,u,h,x,_,w),{x:U,y:D}=hd(P[1],n,o,u,h,x,_,w),{x:$,y:pe}=hd(P[2],n,o,u,h,x,_,w);Ng(i,T,S,C,A,U,D,$,pe),T=$,S=pe,g+=m}}function jA(i,e,t){const s=(o,a)=>{const l=a.x-o.x,c=a.y-o.y,h=Math.sqrt(l*l+c*c),u=l/h,d=c/h;return{len:h,nx:u,ny:d}},r=(o,a)=>{o===0?i.moveTo(a.x,a.y):i.lineTo(a.x,a.y)};let n=e[e.length-1];for(let o=0;o<e.length;o++){const a=e[o%e.length],l=a.radius??t;if(l<=0){r(o,a),n=a;continue}const c=e[(o+1)%e.length],h=s(a,n),u=s(a,c);if(h.len<1e-4||u.len<1e-4){r(o,a),n=a;continue}let d=Math.asin(h.nx*u.ny-h.ny*u.nx),f=1,p=!1;h.nx*u.nx-h.ny*-u.ny<0?d<0?d=Math.PI+d:(d=Math.PI-d,f=-1,p=!0):d>0&&(f=-1,p=!0);const g=d/2;let m,x=Math.abs(Math.cos(g)*l/Math.sin(g));x>Math.min(h.len/2,u.len/2)?(x=Math.min(h.len/2,u.len/2),m=Math.abs(x*Math.sin(g)/Math.cos(g))):m=l;const _=a.x+u.nx*x+-u.ny*m*f,y=a.y+u.ny*x+u.nx*m*f,v=Math.atan2(h.ny,h.nx)+Math.PI/2*f,T=Math.atan2(u.ny,u.nx)-Math.PI/2*f;o===0&&i.moveTo(_+Math.cos(v)*m,y+Math.sin(v)*m),i.arc(_,y,m,v,T,p),n=a}}function ZA(i,e,t,s){const r=(a,l)=>Math.sqrt((a.x-l.x)**2+(a.y-l.y)**2),n=(a,l,c)=>({x:a.x+(l.x-a.x)*c,y:a.y+(l.y-a.y)*c}),o=e.length;for(let a=0;a<o;a++){const l=e[(a+1)%o],c=l.radius??t;if(c<=0){a===0?i.moveTo(l.x,l.y):i.lineTo(l.x,l.y);continue}const h=e[a],u=e[(a+2)%o],d=r(h,l);let f;if(d<1e-4)f=l;else{const m=Math.min(d/2,c);f=n(l,h,m/d)}const p=r(u,l);let g;if(p<1e-4)g=l;else{const m=Math.min(p/2,c);g=n(l,u,m/p)}a===0?i.moveTo(f.x,f.y):i.lineTo(f.x,f.y),i.quadraticCurveTo(l.x,l.y,g.x,g.y,s)}}const JA=new H;class QA{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new De,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const s=this._currentPoly.points,r=s[s.length-2],n=s[s.length-1];return(r!==e||n!==t)&&s.push(e,t),this}arc(e,t,s,r,n,o){this._ensurePoly(!1);const a=this._currentPoly.points;return Lg(a,e,t,s,r,n,o),this}arcTo(e,t,s,r,n){this._ensurePoly();const o=this._currentPoly.points;return XA(o,e,t,s,r,n),this}arcToSvg(e,t,s,r,n,o,a){const l=this._currentPoly.points;return KA(l,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,s,r,n),this}bezierCurveTo(e,t,s,r,n,o,a){this._ensurePoly();const l=this._currentPoly;return Ng(this._currentPoly.points,l.lastX,l.lastY,e,t,s,r,n,o,a),this}quadraticCurveTo(e,t,s,r,n){this._ensurePoly();const o=this._currentPoly;return VA(this._currentPoly.points,o.lastX,o.lastY,e,t,s,r,n),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const s=this.shapePrimitives,r=s.length;for(let n=0;n<e.instructions.length;n++){const o=e.instructions[n];this[o.action](...o.data)}if(e.checkForHoles&&s.length-r>1){let n=null;for(let o=r;o<s.length;o++){const a=s[o];if(a.shape.type==="polygon"){const l=a.shape,c=n?.shape;c&&c.containsPolygon(l)?(n.holes||(n.holes=[]),n.holes.push(a),s.copyWithin(o,o+1),s.length--,o--):n=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,s,r,n){return this.drawShape(new H(e,t,s,r),n),this}circle(e,t,s,r){return this.drawShape(new Zr(e,t,s),r),this}poly(e,t,s){const r=new Es(e);return r.closePath=t,this.drawShape(r,s),this}regularPoly(e,t,s,r,n=0,o){r=Math.max(r|0,3);const a=-1*Math.PI/2+n,l=Math.PI*2/r,c=[];for(let h=0;h<r;h++){const u=a-h*l;c.push(e+s*Math.cos(u),t+s*Math.sin(u))}return this.poly(c,!0,o),this}roundPoly(e,t,s,r,n,o=0,a){if(r=Math.max(r|0,3),n<=0)return this.regularPoly(e,t,s,r,o);const l=s*Math.sin(Math.PI/r)-.001;n=Math.min(n,l);const c=-1*Math.PI/2+o,h=Math.PI*2/r,u=(r-2)*Math.PI/r/2;for(let d=0;d<r;d++){const f=d*h+c,p=e+s*Math.cos(f),g=t+s*Math.sin(f),m=f+Math.PI+u,x=f-Math.PI-u,_=p+n*Math.cos(m),y=g+n*Math.sin(m),v=p+n*Math.cos(x),T=g+n*Math.sin(x);d===0?this.moveTo(_,y):this.lineTo(_,y),this.quadraticCurveTo(p,g,v,T,a)}return this.closePath()}roundShape(e,t,s=!1,r){return e.length<3?this:(s?ZA(this,e,t,r):jA(this,e,t),this.closePath())}filletRect(e,t,s,r,n){if(n===0)return this.rect(e,t,s,r);const o=Math.min(s,r)/2,a=Math.min(o,Math.max(-o,n)),l=e+s,c=t+r,h=a<0?-a:0,u=Math.abs(a);return this.moveTo(e,t+u).arcTo(e+h,t+h,e+u,t,u).lineTo(l-u,t).arcTo(l-h,t+h,l,t+u,u).lineTo(l,c-u).arcTo(l-h,c-h,e+s-u,c,u).lineTo(e+u,c).arcTo(e+h,c-h,e,c-u,u).closePath()}chamferRect(e,t,s,r,n,o){if(n<=0)return this.rect(e,t,s,r);const a=Math.min(n,Math.min(s,r)/2),l=e+s,c=t+r,h=[e+a,t,l-a,t,l,t+a,l,c-a,l-a,c,e+a,c,e,c-a,e,t+a];for(let u=h.length-1;u>=2;u-=2)h[u]===h[u-2]&&h[u-1]===h[u-3]&&h.splice(u-1,2);return this.poly(h,!0,o)}ellipse(e,t,s,r,n){return this.drawShape(new $u(e,t,s,r),n),this}roundRect(e,t,s,r,n,o){return this.drawShape(new Xu(e,t,s,r,n),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let s=this._currentPoly;return s&&this.endPoly(),s=new Es,s.points.push(e,t),this._currentPoly=s,this}endPoly(e=!1){const t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new Es,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let s=t.shape.x,r=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const n=t.transform,o=s;s=n.a*s+n.c*r+n.tx,r=n.b*o+n.d*r+n.ty}this._currentPoly.points.push(s,r)}else this._currentPoly.points.push(0,0)}}buildPath(){const e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){const s=e.instructions[t];this[s.action](...s.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let s=0;s<t.length;s++){const r=t[s],n=r.shape.getBounds(JA);r.transform?e.addRect(n,r.transform):e.addRect(n)}return e}}class Dt{constructor(e,t=!1){this.instructions=[],this.uid=he("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?OC(e,this):this.instructions=e?.slice()??[]}get shapePath(){return this._shapePath||(this._shapePath=new QA(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:"addPath",data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:"arc",data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:"arcTo",data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:"arcToSvg",data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:"bezierCurveTo",data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,s,r,n){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(X.shared);let l=0,c=0;if(!o||o.action!=="bezierCurveTo")l=a.x,c=a.y;else{l=o.data[2],c=o.data[3];const h=a.x,u=a.y;l=h+(h-l),c=u+(u-c)}return this.instructions.push({action:"bezierCurveTo",data:[l,c,e,t,s,r,n]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:"ellipse",data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:"lineTo",data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:"moveTo",data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:"quadraticCurveTo",data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,s){const r=this.instructions[this.instructions.length-1],n=this.getLastPoint(X.shared);let o=0,a=0;if(!r||r.action!=="quadraticCurveTo")o=n.x,a=n.y;else{o=r.data[0],a=r.data[1];const l=n.x,c=n.y;o=l+(l-o),a=c+(c-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,e,t,s]}),this._dirty=!0,this}rect(e,t,s,r,n){return this.instructions.push({action:"rect",data:[e,t,s,r,n]}),this._dirty=!0,this}circle(e,t,s,r){return this.instructions.push({action:"circle",data:[e,t,s,r]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:"roundRect",data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:"poly",data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:"regularPoly",data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:"roundPoly",data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:"roundShape",data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:"filletRect",data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:"chamferRect",data:e}),this._dirty=!0,this}star(e,t,s,r,n,o,a){n||(n=r/2);const l=-1*Math.PI/2+o,c=s*2,h=Math.PI*2/c,u=[];for(let d=0;d<c;d++){const f=d%2?n:r,p=d*h+l;u.push(e+f*Math.cos(p),t+f*Math.sin(p))}return this.poly(u,!0,a),this}clone(e=!1){const t=new Dt;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let s=0;s<this.instructions.length;s++){const r=this.instructions[s];t.instructions.push({action:r.action,data:r.data.slice()})}return t}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;const t=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty;let l=0,c=0,h=0,u=0,d=0,f=0,p=0,g=0;for(let m=0;m<this.instructions.length;m++){const x=this.instructions[m],_=x.data;switch(x.action){case"moveTo":case"lineTo":l=_[0],c=_[1],_[0]=t*l+r*c+o,_[1]=s*l+n*c+a;break;case"bezierCurveTo":h=_[0],u=_[1],d=_[2],f=_[3],l=_[4],c=_[5],_[0]=t*h+r*u+o,_[1]=s*h+n*u+a,_[2]=t*d+r*f+o,_[3]=s*d+n*f+a,_[4]=t*l+r*c+o,_[5]=s*l+n*c+a;break;case"quadraticCurveTo":h=_[0],u=_[1],l=_[2],c=_[3],_[0]=t*h+r*u+o,_[1]=s*h+n*u+a,_[2]=t*l+r*c+o,_[3]=s*l+n*c+a;break;case"arcToSvg":l=_[5],c=_[6],p=_[0],g=_[1],_[0]=t*p+r*g,_[1]=s*p+n*g,_[5]=t*l+r*c+o,_[6]=s*l+n*c+a;break;case"circle":_[4]=zs(_[3],e);break;case"rect":_[4]=zs(_[4],e);break;case"ellipse":_[8]=zs(_[8],e);break;case"roundRect":_[5]=zs(_[5],e);break;case"addPath":_[0].transform(e);break;case"poly":_[2]=zs(_[2],e);break;default:L("unknown transform action",x.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,s=this.instructions[t];if(!s)return e.x=0,e.y=0,e;for(;s.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;s=this.instructions[t]}switch(s.action){case"moveTo":case"lineTo":e.x=s.data[0],e.y=s.data[1];break;case"quadraticCurveTo":e.x=s.data[2],e.y=s.data[3];break;case"bezierCurveTo":e.x=s.data[4],e.y=s.data[5];break;case"arc":case"arcToSvg":e.x=s.data[5],e.y=s.data[6];break;case"addPath":s.data[0].getLastPoint(e);break}return e}}function zs(i,e){return i?i.prepend(e):e.clone()}function _e(i,e,t){const s=i.getAttribute(e);return s?Number(s):t}function eE(i,e){const t=i.querySelectorAll("defs");for(let s=0;s<t.length;s++){const r=t[s];for(let n=0;n<r.children.length;n++){const o=r.children[n];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=tE(o);break;case"radialgradient":e.defs[o.id]=iE();break}}}}function tE(i){const e=_e(i,"x1",0),t=_e(i,"y1",0),s=_e(i,"x2",1),r=_e(i,"y2",0),n=i.getAttribute("gradientUnits")||"objectBoundingBox",o=new at(e,t,s,r,n==="objectBoundingBox"?"local":"global");for(let a=0;a<i.children.length;a++){const l=i.children[a],c=_e(l,"offset",0),h=ue.shared.setValue(l.getAttribute("stop-color")).toNumber();o.addColorStop(c,h)}return o}function iE(i){return L("[SVG Parser] Radial gradients are not yet supported"),new at(0,0,1,0)}function Wg(i){const e=i.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const Vg={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function $g(i,e){const t=i.getAttribute("style"),s={},r={},n={strokeStyle:s,fillStyle:r,useFill:!1,useStroke:!1};for(const o in Vg){const a=i.getAttribute(o);a&&Xg(e,n,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const l=o[a].trim(),[c,h]=l.split(":");Vg[c]&&Xg(e,n,c,h.trim())}}return{strokeStyle:n.useStroke?s:null,fillStyle:n.useFill?r:null,useFill:n.useFill,useStroke:n.useStroke}}function Xg(i,e,t,s){switch(t){case"stroke":if(s!=="none"){if(s.startsWith("url(")){const r=Wg(s);e.strokeStyle.fill=i.defs[r]}else e.strokeStyle.color=ue.shared.setValue(s).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(s);break;case"fill":if(s!=="none"){if(s.startsWith("url(")){const r=Wg(s);e.fillStyle.fill=i.defs[r]}else e.fillStyle.color=ue.shared.setValue(s).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(s);break;case"stroke-opacity":e.strokeStyle.alpha=Number(s);break;case"opacity":e.fillStyle.alpha=Number(s),e.strokeStyle.alpha=Number(s);break}}function sE(i){if(i.length<=2)return!0;const e=i.map(a=>a.area).sort((a,l)=>l-a),[t,s]=e,r=e[e.length-1],n=t/s,o=s/r;return!(n>3&&o<2)}function rE(i){return i.split(/(?=[Mm])/).filter(s=>s.trim().length>0)}function nE(i){const e=i.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),s=[],r=[];for(let h=0;h<t.length;h+=2)h+1<t.length&&(s.push(t[h]),r.push(t[h+1]));if(s.length===0||r.length===0)return 0;const n=Math.min(...s),o=Math.max(...s),a=Math.min(...r),l=Math.max(...r);return(o-n)*(l-a)}function Yg(i,e){const t=new Dt(i,!1);for(const s of t.instructions)e.instructions.push(s)}function oE(i,e){if(typeof i=="string"){const o=document.createElement("div");o.innerHTML=i.trim(),i=o.querySelector("svg")}const t={context:e,defs:{},path:new Dt};eE(i,t);const s=i.children,{fillStyle:r,strokeStyle:n}=$g(i,t);for(let o=0;o<s.length;o++){const a=s[o];a.nodeName.toLowerCase()!=="defs"&&qg(a,t,r,n)}return e}function qg(i,e,t,s){const r=i.children,{fillStyle:n,strokeStyle:o}=$g(i,e);n&&t?t={...t,...n}:n&&(t=n),o&&s?s={...s,...o}:o&&(s=o);const a=!t&&!s;a&&(t={color:0});let l,c,h,u,d,f,p,g,m,x,_,y,v,T,S,w,E;switch(i.nodeName.toLowerCase()){case"path":{T=i.getAttribute("d");const P=i.getAttribute("fill-rule"),C=rE(T),A=P==="evenodd",U=C.length>1;if(A&&U){const $=C.map(k=>({path:k,area:nE(k)}));if($.sort((k,F)=>F.area-k.area),C.length>3||!sE($))for(let k=0;k<$.length;k++){const F=$[k],ne=k===0;e.context.beginPath();const G=new Dt(void 0,!0);Yg(F.path,G),e.context.path(G),ne?(t&&e.context.fill(t),s&&e.context.stroke(s)):e.context.cut()}else for(let k=0;k<$.length;k++){const F=$[k],ne=k%2===1;e.context.beginPath();const G=new Dt(void 0,!0);Yg(F.path,G),e.context.path(G),ne?e.context.cut():(t&&e.context.fill(t),s&&e.context.stroke(s))}}else{const $=P?P==="evenodd":!0;S=new Dt(T,$),e.context.path(S),t&&e.context.fill(t),s&&e.context.stroke(s)}break}case"circle":p=_e(i,"cx",0),g=_e(i,"cy",0),m=_e(i,"r",0),e.context.ellipse(p,g,m,m),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"rect":l=_e(i,"x",0),c=_e(i,"y",0),w=_e(i,"width",0),E=_e(i,"height",0),x=_e(i,"rx",0),_=_e(i,"ry",0),x||_?e.context.roundRect(l,c,w,E,x||_):e.context.rect(l,c,w,E),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"ellipse":p=_e(i,"cx",0),g=_e(i,"cy",0),x=_e(i,"rx",0),_=_e(i,"ry",0),e.context.beginPath(),e.context.ellipse(p,g,x,_),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"line":h=_e(i,"x1",0),u=_e(i,"y1",0),d=_e(i,"x2",0),f=_e(i,"y2",0),e.context.beginPath(),e.context.moveTo(h,u),e.context.lineTo(d,f),s&&e.context.stroke(s);break;case"polygon":v=i.getAttribute("points"),y=v.match(/\d+/g).map(P=>parseInt(P,10)),e.context.poly(y,!0),t&&e.context.fill(t),s&&e.context.stroke(s);break;case"polyline":v=i.getAttribute("points"),y=v.match(/\d+/g).map(P=>parseInt(P,10)),e.context.poly(y,!1),s&&e.context.stroke(s);break;case"g":case"svg":break;default:{L(`[SVG parser] <${i.nodeName}> elements unsupported`);break}}a&&(t=null);for(let P=0;P<r.length;P++)qg(r[P],e,t,s)}function aE(i){return ue.isColorLike(i)}function Kg(i){return i instanceof jr}function jg(i){return i instanceof at}function lE(i){return i instanceof M}function cE(i,e,t){const s=ue.shared.setValue(e??0);return i.color=s.toNumber(),i.alpha=s.alpha===1?t.alpha:s.alpha,i.texture=M.WHITE,{...t,...i}}function hE(i,e,t){return i.texture=e,{...t,...i}}function Zg(i,e,t){return i.fill=e,i.color=16777215,i.texture=e.texture,i.matrix=e.transform,{...t,...i}}function Jg(i,e,t){return e.buildGradient(),i.fill=e,i.color=16777215,i.texture=e.texture,i.matrix=e.transform,i.textureSpace=e.textureSpace,{...t,...i}}function uE(i,e){const t={...e,...i},s=ue.shared.setValue(t.color);return t.alpha*=s.alpha,t.color=s.toNumber(),t}function pi(i,e){if(i==null)return null;const t={},s=i;return aE(i)?cE(t,i,e):lE(i)?hE(t,i,e):Kg(i)?Zg(t,i,e):jg(i)?Jg(t,i,e):s.fill&&Kg(s.fill)?Zg(s,s.fill,e):s.fill&&jg(s.fill)?Jg(s,s.fill,e):uE(s,e)}function sn(i,e){const{width:t,alignment:s,miterLimit:r,cap:n,join:o,pixelLine:a,...l}=e,c=pi(i,l);return c?{width:t,alignment:s,miterLimit:r,cap:n,join:o,pixelLine:a,...c}:null}const dE=new X,Qg=new O,ud=class It extends je{constructor(){super(...arguments),this.uid=he("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this._activePath=new Dt,this._transform=new O,this._fillStyle={...It.defaultFillStyle},this._strokeStyle={...It.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new De,this._boundsDirty=!0}clone(){const e=new It;return e.batchMode=this.batchMode,e.instructions=this.instructions.slice(),e._activePath=this._activePath.clone(),e._transform=this._transform.clone(),e._fillStyle={...this._fillStyle},e._strokeStyle={...this._strokeStyle},e._stateStack=this._stateStack.slice(),e._bounds=this._bounds.clone(),e._boundsDirty=!0,e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=pi(e,It.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=sn(e,It.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=pi(e,It.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=pi(e,It.defaultStrokeStyle),this}texture(e,t,s,r,n,o){return this.instructions.push({action:"texture",data:{image:e,dx:s||0,dy:r||0,dw:n||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t?ue.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new Dt,this}fill(e,t){let s;const r=this.instructions[this.instructions.length-1];return this._tick===0&&r?.action==="stroke"?s=r.data.path:s=this._activePath.clone(),s?(e!=null&&(t!==void 0&&typeof e=="number"&&(W(Q,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=pi(e,It.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:s}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(X.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const s=this.instructions[this.instructions.length-1];return this._tick===0&&s?.action==="fill"?t=s.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=sn(e,It.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:t}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){const t=this.instructions[this.instructions.length-1-e],s=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(s);else{t.data.hole=s;break}}return this._initNextPathLocation(),this}arc(e,t,s,r,n,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,s,r,n,o),this}arcTo(e,t,s,r,n){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*s+o.c*r+o.tx,o.b*s+o.d*r+o.ty,n),this}arcToSvg(e,t,s,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.arcToSvg(e,t,s,r,n,l.a*o+l.c*a+l.tx,l.b*o+l.d*a+l.ty),this}bezierCurveTo(e,t,s,r,n,o,a){this._tick++;const l=this._transform;return this._activePath.bezierCurveTo(l.a*e+l.c*t+l.tx,l.b*e+l.d*t+l.ty,l.a*s+l.c*r+l.tx,l.b*s+l.d*r+l.ty,l.a*n+l.c*o+l.tx,l.b*n+l.d*o+l.ty,a),this}closePath(){return this._tick++,this._activePath?.closePath(),this}ellipse(e,t,s,r){return this._tick++,this._activePath.ellipse(e,t,s,r,this._transform.clone()),this}circle(e,t,s){return this._tick++,this._activePath.circle(e,t,s,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const s=this._transform;return this._activePath.lineTo(s.a*e+s.c*t+s.tx,s.b*e+s.d*t+s.ty),this}moveTo(e,t){this._tick++;const s=this._transform,r=this._activePath.instructions,n=s.a*e+s.c*t+s.tx,o=s.b*e+s.d*t+s.ty;return r.length===1&&r[0].action==="moveTo"?(r[0].data[0]=n,r[0].data[1]=o,this):(this._activePath.moveTo(n,o),this)}quadraticCurveTo(e,t,s,r,n){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*s+o.c*r+o.tx,o.b*s+o.d*r+o.ty,n),this}rect(e,t,s,r){return this._tick++,this._activePath.rect(e,t,s,r,this._transform.clone()),this}roundRect(e,t,s,r,n){return this._tick++,this._activePath.roundRect(e,t,s,r,n,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,s,r,n=0,o){return this._tick++,this._activePath.regularPoly(e,t,s,r,n,o),this}roundPoly(e,t,s,r,n,o){return this._tick++,this._activePath.roundPoly(e,t,s,r,n,o),this}roundShape(e,t,s,r){return this._tick++,this._activePath.roundShape(e,t,s,r),this}filletRect(e,t,s,r,n){return this._tick++,this._activePath.filletRect(e,t,s,r,n),this}chamferRect(e,t,s,r,n,o){return this._tick++,this._activePath.chamferRect(e,t,s,r,n,o),this}star(e,t,s,r,n=0,o=0){return this._tick++,this._activePath.star(e,t,s,r,n,o,this._transform.clone()),this}svg(e){return this._tick++,oE(e,this),this}restore(){const e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,s,r,n,o){return e instanceof O?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,s,r,n,o),this)}transform(e,t,s,r,n,o){return e instanceof O?(this._transform.append(e),this):(Qg.set(e,t,s,r,n,o),this._transform.append(Qg),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,!this.dirty&&(this.emit("update",this,16),this.dirty=!0)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){const s=this.instructions[t],r=s.action;if(r==="fill"){const n=s.data;e.addBounds(n.path.bounds)}else if(r==="texture"){const n=s.data;e.addFrame(n.dx,n.dy,n.dx+n.dw,n.dy+n.dh,n.transform)}if(r==="stroke"){const n=s.data,o=n.style.alignment,a=n.style.width*(1-o),l=n.path.bounds;e.addFrame(l.minX-a,l.minY-a,l.maxX+a,l.maxY+a)}}return e}containsPoint(e){if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let s=!1;for(let r=0;r<t.length;r++){const n=t[r],o=n.data,a=o.path;if(!n.action||!a)continue;const l=o.style,c=a.shapePath.shapePrimitives;for(let h=0;h<c.length;h++){const u=c[h].shape;if(!l||!u)continue;const d=c[h].transform,f=d?d.applyInverse(e,dE):e;if(n.action==="fill")s=u.contains(f.x,f.y);else{const g=l;s=u.strokeContains(f.x,f.y,g.width,g.alignment)}const p=o.hole;if(p){const g=p.shapePath?.shapePrimitives;if(g)for(let m=0;m<g.length;m++)g[m].shape.contains(f.x,f.y)&&(s=!1)}if(s)return!0}}return s}destroy(e=!1){if(this._stateStack.length=0,this._transform=null,this.emit("destroy",this),this.removeAllListeners(),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(s)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(s))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};ud.defaultFillStyle={color:16777215,alpha:1,texture:M.WHITE,matrix:null,fill:null,textureSpace:"local"},ud.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:M.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let lt=ud;const dd=class es extends je{constructor(e={}){super(),this.uid=he("textStyle"),this._tick=0,fE(e);const t={...es.defaultTextStyle,...e};for(const s in t){const r=s;this[r]=t[s]}this.update(),this._tick=0}get align(){return this._align}set align(e){this._align!==e&&(this._align=e,this.update())}get breakWords(){return this._breakWords}set breakWords(e){this._breakWords!==e&&(this._breakWords=e,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(e){this._dropShadow!==e&&(e!==null&&typeof e=="object"?this._dropShadow=this._createProxy({...es.defaultDropShadow,...e}):this._dropShadow=e?this._createProxy({...es.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.update())}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize!==e&&(typeof e=="string"?this._fontSize=parseInt(e,10):this._fontSize=e,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(e){this._fontVariant!==e&&(this._fontVariant=e,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.update())}get leading(){return this._leading}set leading(e){this._leading!==e&&(this._leading=e,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(e){this._letterSpacing!==e&&(this._letterSpacing=e,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(e){this._lineHeight!==e&&(this._lineHeight=e,this.update())}get padding(){return this._padding}set padding(e){this._padding!==e&&(this._padding=e,this.update())}get filters(){return this._filters}set filters(e){this._filters!==e&&(this._filters=Object.freeze(e),this.update())}get trim(){return this._trim}set trim(e){this._trim!==e&&(this._trim=e,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(e){this._textBaseline!==e&&(this._textBaseline=e,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(e){this._whiteSpace!==e&&(this._whiteSpace=e,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(e){this._wordWrap!==e&&(this._wordWrap=e,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(e){this._wordWrapWidth!==e&&(this._wordWrapWidth=e,this.update())}get fill(){return this._originalFill}set fill(e){e!==this._originalFill&&(this._originalFill=e,this._isFillStyle(e)&&(this._originalFill=this._createProxy({...lt.defaultFillStyle,...e},()=>{this._fill=pi({...this._originalFill},lt.defaultFillStyle)})),this._fill=pi(e===0?"black":e,lt.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...lt.defaultStrokeStyle,...e},()=>{this._stroke=sn({...this._originalStroke},lt.defaultStrokeStyle)})),this._stroke=sn(e,lt.defaultStrokeStyle),this.update())}update(){this._tick++,this.emit("update",this)}reset(){const e=es.defaultTextStyle;for(const t in e)this[t]=e[t]}get styleKey(){return`${this.uid}-${this._tick}`}clone(){return new es({align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?{...this._dropShadow}:null,fill:this._fill,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,textBaseline:this.textBaseline,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,filters:this._filters?[...this._filters]:void 0})}_getFinalPadding(){let e=0;if(this._filters)for(let t=0;t<this._filters.length;t++)e+=this._filters[t].padding;return Math.max(this._padding,e)}destroy(e=!1){if(this.removeAllListeners(),typeof e=="boolean"?e:e?.texture){const s=typeof e=="boolean"?e:e?.textureSource;this._fill?.texture&&this._fill.texture.destroy(s),this._originalFill?.texture&&this._originalFill.texture.destroy(s),this._stroke?.texture&&this._stroke.texture.destroy(s),this._originalStroke?.texture&&this._originalStroke.texture.destroy(s)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(e,t){return new Proxy(e,{set:(s,r,n)=>(s[r]===n||(s[r]=n,t?.(r,n),this.update()),!0)})}_isFillStyle(e){return(e??null)!==null&&!(ue.isColorLike(e)||e instanceof at||e instanceof jr)}};dd.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5},dd.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let Xe=dd;function fE(i){const e=i;if(typeof e.dropShadow=="boolean"&&e.dropShadow){const t=Xe.defaultDropShadow;i.dropShadow={alpha:e.dropShadowAlpha??t.alpha,angle:e.dropShadowAngle??t.angle,blur:e.dropShadowBlur??t.blur,color:e.dropShadowColor??t.color,distance:e.dropShadowDistance??t.distance}}if(e.strokeThickness!==void 0){W(Q,"strokeThickness is now a part of stroke");const t=e.stroke;let s={};if(ue.isColorLike(t))s.color=t;else if(t instanceof at||t instanceof jr)s.fill=t;else if(Object.hasOwnProperty.call(t,"color")||Object.hasOwnProperty.call(t,"fill"))s=t;else throw new Error("Invalid stroke value.");i.stroke={...s,width:e.strokeThickness}}if(Array.isArray(e.fillGradientStops)){if(W(Q,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(e.fill)||e.fill.length===0)throw new Error("Invalid fill value. Expected an array of colors for gradient fill.");e.fill.length!==e.fillGradientStops.length&&L("The number of fill colors must match the number of fill gradient stops.");const t=new at({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),s=e.fillGradientStops.slice(),r=e.fill.map(n=>ue.shared.setValue(n).toNumber());s.forEach((n,o)=>{t.addColorStop(n,r[o])}),i.fill={fill:t}}}class pE{constructor(e){this._canvasPool=Object.create(null),this.canvasOptions=e||{},this.enableFullScreen=!1}_createCanvasAndContext(e,t){const s=Y.get().createCanvas();s.width=e,s.height=t;const r=s.getContext("2d");return{canvas:s,context:r}}getOptimalCanvasAndContext(e,t,s=1){e=Math.ceil(e*s-1e-6),t=Math.ceil(t*s-1e-6),e=ki(e),t=ki(t);const r=(e<<17)+(t<<1);this._canvasPool[r]||(this._canvasPool[r]=[]);let n=this._canvasPool[r].pop();return n||(n=this._createCanvasAndContext(e,t)),n}returnCanvasAndContext(e){const t=e.canvas,{width:s,height:r}=t,n=(s<<17)+(r<<1);e.context.resetTransform(),e.context.clearRect(0,0,s,r),this._canvasPool[n].push(e)}clear(){this._canvasPool={}}}const Gt=new pE;Bi.register(Gt);const e0=1e5;function rn(i,e,t,s=0){if(i.texture===M.WHITE&&!i.fill)return ue.shared.setValue(i.color).setAlpha(i.alpha??1).toHexa();if(i.fill){if(i.fill instanceof jr){const r=i.fill,n=e.createPattern(r.texture.source.resource,"repeat"),o=r.transform.copyTo(O.shared);return o.scale(r.texture.frame.width,r.texture.frame.height),n.setTransform(o),n}else if(i.fill instanceof at){const r=i.fill,n=r.type==="linear",o=r.textureSpace==="local";let a=1,l=1;o&&t&&(a=t.width+s,l=t.height+s);let c,h=!1;if(n){const{start:u,end:d}=r;c=e.createLinearGradient(u.x*a,u.y*l,d.x*a,d.y*l),h=Math.abs(d.x-u.x)<Math.abs((d.y-u.y)*.1)}else{const{center:u,innerRadius:d,outerCenter:f,outerRadius:p}=r;c=e.createRadialGradient(u.x*a,u.y*l,d*a,f.x*a,f.y*l,p*a)}if(h&&o&&t){const u=t.lineHeight/l;for(let d=0;d<t.lines.length;d++){const f=(d*t.lineHeight+s/2)/l;r.colorStops.forEach(p=>{const g=f+p.offset*u;c.addColorStop(Math.floor(g*e0)/e0,ue.shared.setValue(p.color).toHex())})}}else r.colorStops.forEach(u=>{c.addColorStop(u.offset,ue.shared.setValue(u.color).toHex())});return c}}else{const r=e.createPattern(i.texture.source.resource,"repeat"),n=i.matrix.copyTo(O.shared);return n.scale(i.texture.frame.width,i.texture.frame.height),r.setTransform(n),r}return L("FillStyle not recognised",i),"red"}const t0=class ry extends hg{constructor(e){super(),this.resolution=1,this.pages=[],this._padding=0,this._measureCache=Object.create(null),this._currentChars=[],this._currentX=0,this._currentY=0,this._currentMaxCharHeight=0,this._currentPageIndex=-1,this._skipKerning=!1;const t={...ry.defaultOptions,...e};this._textureSize=t.textureSize,this._mipmap=t.mipmap;const s=t.style.clone();t.overrideFill&&(s._fill.color=16777215,s._fill.alpha=1,s._fill.texture=M.WHITE,s._fill.fill=null),this.applyFillAsTint=t.overrideFill;const r=s.fontSize;s.fontSize=this.baseMeasurementFontSize;const n=Kr(s);t.overrideSize?s._stroke&&(s._stroke.width*=this.baseRenderedFontSize/r):s.fontSize=this.baseRenderedFontSize=r,this._style=s,this._skipKerning=t.skipKerning??!1,this.resolution=t.resolution??1,this._padding=t.padding??4,t.textureStyle&&(this._textureStyle=t.textureStyle instanceof wt?t.textureStyle:new wt(t.textureStyle)),this.fontMetrics=$e.measureFont(n),this.lineHeight=s.lineHeight||this.fontMetrics.fontSize||s.fontSize}ensureCharacters(e){const t=$e.graphemeSegmenter(e).filter(m=>!this._currentChars.includes(m)).filter((m,x,_)=>_.indexOf(m)===x);if(!t.length)return;this._currentChars=[...this._currentChars,...t];let s;this._currentPageIndex===-1?s=this._nextPage():s=this.pages[this._currentPageIndex];let{canvas:r,context:n}=s.canvasAndContext,o=s.texture.source;const a=this._style;let l=this._currentX,c=this._currentY,h=this._currentMaxCharHeight;const u=this.baseRenderedFontSize/this.baseMeasurementFontSize,d=this._padding*u;let f=!1;const p=r.width/this.resolution,g=r.height/this.resolution;for(let m=0;m<t.length;m++){const x=t[m],_=$e.measureText(x,a,r,!1);_.lineHeight=_.height;const y=_.width*u,v=Math.ceil((a.fontStyle==="italic"?2:1)*y),T=_.height*u,S=v+d*2,w=T+d*2;if(f=!1,x!==`
|
|
320
|
+
`&&x!=="\r"&&x!==" "&&x!==" "&&(f=!0,h=Math.ceil(Math.max(w,h))),l+S>p&&(c+=h,h=w,l=0,c+h>g)){o.update();const P=this._nextPage();r=P.canvasAndContext.canvas,n=P.canvasAndContext.context,o=P.texture.source,l=0,c=0,h=0}const E=y/u-(a.dropShadow?.distance??0)-(a._stroke?.width??0);if(this.chars[x]={id:x.codePointAt(0),xOffset:-this._padding,yOffset:-this._padding,xAdvance:E,kerning:{}},f){this._drawGlyph(n,_,l+d,c+d,u,a);const P=o.width*u,C=o.height*u,A=new H(l/P*o.width,c/C*o.height,S/P*o.width,w/C*o.height);this.chars[x].texture=new M({source:o,frame:A}),l+=Math.ceil(S)}}o.update(),this._currentX=l,this._currentY=c,this._currentMaxCharHeight=h,this._skipKerning&&this._applyKerning(t,n)}get pageTextures(){return W(Q,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}_applyKerning(e,t){const s=this._measureCache;for(let r=0;r<e.length;r++){const n=e[r];for(let o=0;o<this._currentChars.length;o++){const a=this._currentChars[o];let l=s[n];l||(l=s[n]=t.measureText(n).width);let c=s[a];c||(c=s[a]=t.measureText(a).width);let h=t.measureText(n+a).width,u=h-(l+c);u&&(this.chars[n].kerning[a]=u),h=t.measureText(n+a).width,u=h-(l+c),u&&(this.chars[a].kerning[n]=u)}}}_nextPage(){this._currentPageIndex++;const e=this.resolution,t=Gt.getOptimalCanvasAndContext(this._textureSize,this._textureSize,e);this._setupContext(t.context,this._style,e);const s=e*(this.baseRenderedFontSize/this.baseMeasurementFontSize),r=new M({source:new Ct({resource:t.canvas,resolution:s,alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:this._mipmap})});this._textureStyle&&(r.source.style=this._textureStyle);const n={canvasAndContext:t,texture:r};return this.pages[this._currentPageIndex]=n,n}_setupContext(e,t,s){t.fontSize=this.baseRenderedFontSize,e.scale(s,s),e.font=Kr(t),t.fontSize=this.baseMeasurementFontSize,e.textBaseline=t.textBaseline;const r=t._stroke,n=r?.width??0;if(r&&(e.lineWidth=n,e.lineJoin=r.join,e.miterLimit=r.miterLimit,e.strokeStyle=rn(r,e)),t._fill&&(e.fillStyle=rn(t._fill,e)),t.dropShadow){const o=t.dropShadow,a=ue.shared.setValue(o.color).toArray(),l=o.blur*s,c=o.distance*s;e.shadowColor=`rgba(${a[0]*255},${a[1]*255},${a[2]*255},${o.alpha})`,e.shadowBlur=l,e.shadowOffsetX=Math.cos(o.angle)*c,e.shadowOffsetY=Math.sin(o.angle)*c}else e.shadowColor="black",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0}_drawGlyph(e,t,s,r,n,o){const a=t.text,l=t.fontProperties,h=(o._stroke?.width??0)*n,u=s+h/2,d=r-h/2,f=l.descent*n,p=t.lineHeight*n;let g=!1;o.stroke&&h&&(g=!0,e.strokeText(a,u,d+p-f));const{shadowBlur:m,shadowOffsetX:x,shadowOffsetY:_}=e;o._fill&&(g&&(e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0),e.fillText(a,u,d+p-f)),g&&(e.shadowBlur=m,e.shadowOffsetX=x,e.shadowOffsetY=_)}destroy(){super.destroy();for(let e=0;e<this.pages.length;e++){const{canvasAndContext:t,texture:s}=this.pages[e];Gt.returnCanvasAndContext(t),s.destroy(!0)}this.pages=null}};t0.defaultOptions={textureSize:512,style:new Xe,mipmap:!0};let i0=t0;function fd(i,e,t,s){const r={width:0,height:0,offsetY:0,scale:e.fontSize/t.baseMeasurementFontSize,lines:[{width:0,charPositions:[],spaceWidth:0,spacesIndex:[],chars:[]}]};r.offsetY=t.baseLineOffset;let n=r.lines[0],o=null,a=!0;const l={width:0,start:0,index:0,positions:[],chars:[]},c=t.baseMeasurementFontSize/e.fontSize,h=e.letterSpacing*c,u=e.wordWrapWidth*c,d=e.lineHeight?e.lineHeight*c:t.lineHeight,f=e.wordWrap&&e.breakWords,p=x=>{const _=n.width;for(let y=0;y<l.index;y++){const v=x.positions[y];n.chars.push(x.chars[y]),n.charPositions.push(v+_)}n.width+=x.width,a=!1,l.width=0,l.index=0,l.chars.length=0},g=()=>{let x=n.chars.length-1;if(s){let _=n.chars[x];for(;_===" ";)n.width-=t.chars[_].xAdvance,_=n.chars[--x]}r.width=Math.max(r.width,n.width),n={width:0,charPositions:[],chars:[],spaceWidth:0,spacesIndex:[]},a=!0,r.lines.push(n),r.height+=d},m=x=>x-h>u;for(let x=0;x<i.length+1;x++){let _;const y=x===i.length;y||(_=i[x]);const v=t.chars[_]||t.chars[" "];if(/(?:\s)/.test(_)||_==="\r"||_===`
|
|
321
|
+
`||y){if(!a&&e.wordWrap&&m(n.width+l.width)?(g(),p(l),y||n.charPositions.push(0)):(l.start=n.width,p(l),y||n.charPositions.push(0)),_==="\r"||_===`
|
|
322
|
+
`)g();else if(!y){const E=v.xAdvance+(v.kerning[o]||0)+h;n.width+=E,n.spaceWidth=E,n.spacesIndex.push(n.charPositions.length),n.chars.push(_)}}else{const w=v.kerning[o]||0,E=v.xAdvance+w+h;f&&m(n.width+l.width+E)&&(p(l),g()),l.positions[l.index++]=l.width+w,l.chars.push(_),l.width+=E}o=_}return g(),e.align==="center"?mE(r):e.align==="right"?gE(r):e.align==="justify"&&xE(r),r}function mE(i){for(let e=0;e<i.lines.length;e++){const t=i.lines[e],s=i.width/2-t.width/2;for(let r=0;r<t.charPositions.length;r++)t.charPositions[r]+=s}}function gE(i){for(let e=0;e<i.lines.length;e++){const t=i.lines[e],s=i.width-t.width;for(let r=0;r<t.charPositions.length;r++)t.charPositions[r]+=s}}function xE(i){const e=i.width;for(let t=0;t<i.lines.length;t++){const s=i.lines[t];let r=0,n=s.spacesIndex[r++],o=0;const a=s.spacesIndex.length,c=(e-s.width)/a;for(let h=0;h<s.charPositions.length;h++)h===n&&(n=s.spacesIndex[r++],o+=c),s.charPositions[h]+=o}}function _E(i){if(i==="")return[];typeof i=="string"&&(i=[i]);const e=[];for(let t=0,s=i.length;t<s;t++){const r=i[t];if(Array.isArray(r)){if(r.length!==2)throw new Error(`[BitmapFont]: Invalid character range length, expecting 2 got ${r.length}.`);if(r[0].length===0||r[1].length===0)throw new Error("[BitmapFont]: Invalid character delimiter.");const n=r[0].charCodeAt(0),o=r[1].charCodeAt(0);if(o<n)throw new Error("[BitmapFont]: Invalid character range.");for(let a=n,l=o;a<=l;a++)e.push(String.fromCharCode(a))}else e.push(...Array.from(r))}if(e.length===0)throw new Error("[BitmapFont]: Empty set when resolving characters.");return e}let nn=0;class yE{constructor(){this.ALPHA=[["a","z"],["A","Z"]," "],this.NUMERIC=[["0","9"]],this.ALPHANUMERIC=[["a","z"],["A","Z"],["0","9"]," "],this.ASCII=[[" ","~"]],this.defaultOptions={chars:this.ALPHANUMERIC,resolution:1,padding:4,skipKerning:!1,textureStyle:null},this.measureCache=ug(1e3)}getFont(e,t){let s=`${t.fontFamily}-bitmap`,r=!0;if(t._fill.fill&&!t._stroke?(s+=t._fill.fill.styleKey,r=!1):(t._stroke||t.dropShadow)&&(s=`${t.styleKey}-bitmap`,r=!1),!ae.has(s)){const o=Object.create(t);o.lineHeight=0;const a=new i0({style:o,overrideFill:r,overrideSize:!0,...this.defaultOptions});nn++,nn>50&&L("BitmapText",`You have dynamically created ${nn} bitmap fonts, this can be inefficient. Try pre installing your font styles using \`BitmapFont.install({name:"style1", style})\``),a.once("destroy",()=>{nn--,ae.remove(s)}),ae.set(s,a)}const n=ae.get(s);return n.ensureCharacters?.(e),n}getLayout(e,t,s=!0){const r=this.getFont(e,t),n=`${e}-${t.styleKey}-${s}`;if(this.measureCache.has(n))return this.measureCache.get(n);const o=$e.graphemeSegmenter(e),a=fd(o,t,r,s);return this.measureCache.set(n,a),a}measureText(e,t,s=!0){return this.getLayout(e,t,s)}install(...e){let t=e[0];typeof t=="string"&&(t={name:t,style:e[1],chars:e[2]?.chars,resolution:e[2]?.resolution,padding:e[2]?.padding,skipKerning:e[2]?.skipKerning},W(Q,"BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})"));const s=t?.name;if(!s)throw new Error("[BitmapFontManager] Property `name` is required.");t={...this.defaultOptions,...t};const r=t.style,n=r instanceof Xe?r:new Xe(r),o=t.dynamicFill??this._canUseTintForStyle(n),a=new i0({style:n,overrideFill:o,skipKerning:t.skipKerning,padding:t.padding,resolution:t.resolution,overrideSize:!1,textureStyle:t.textureStyle}),l=_E(t.chars);return a.ensureCharacters(l.join("")),ae.set(`${s}-bitmap`,a),a.once("destroy",()=>ae.remove(`${s}-bitmap`)),a}uninstall(e){const t=`${e}-bitmap`,s=ae.get(t);s&&s.destroy()}_canUseTintForStyle(e){return!e._stroke&&(!e.dropShadow||e.dropShadow.color===0)&&!e._fill.fill&&e._fill.color===16777215}}const Ns=new yE;class s0 extends hg{constructor(e,t){super();const{textures:s,data:r}=e;Object.keys(r.pages).forEach(n=>{const o=r.pages[parseInt(n,10)],a=s[o.id];this.pages.push({texture:a})}),Object.keys(r.chars).forEach(n=>{const o=r.chars[n],{frame:a,source:l,rotate:c}=s[o.page],h=oe.transformRectCoords(o,a,c,new H),u=new M({frame:h,orig:new H(0,0,o.width,o.height),source:l,rotate:c});this.chars[n]={id:n.codePointAt(0),xOffset:o.xOffset,yOffset:o.yOffset,xAdvance:o.xAdvance,kerning:o.kerning??{},texture:u}}),this.baseRenderedFontSize=r.fontSize,this.baseMeasurementFontSize=r.fontSize,this.fontMetrics={ascent:0,descent:0,fontSize:r.fontSize},this.baseLineOffset=r.baseLineOffset,this.lineHeight=r.lineHeight,this.fontFamily=r.fontFamily,this.distanceField=r.distanceField??{type:"none",range:0},this.url=t}destroy(){super.destroy();for(let e=0;e<this.pages.length;e++){const{texture:t}=this.pages[e];t.destroy(!0)}this.pages=null}static install(e){Ns.install(e)}static uninstall(e){Ns.uninstall(e)}}const pd={test(i){return typeof i=="string"&&i.startsWith("info face=")},parse(i){const e=i.match(/^[a-z]+\s+.+$/gm),t={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(const u in e){const d=e[u].match(/^[a-z]+/gm)[0],f=e[u].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),p={};for(const g in f){const m=f[g].split("="),x=m[0],_=m[1].replace(/"/gm,""),y=parseFloat(_),v=isNaN(y)?_:y;p[x]=v}t[d].push(p)}const s={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},[r]=t.info,[n]=t.common,[o]=t.distanceField??[];o&&(s.distanceField={range:parseInt(o.distanceRange,10),type:o.fieldType}),s.fontSize=parseInt(r.size,10),s.fontFamily=r.face,s.lineHeight=parseInt(n.lineHeight,10);const a=t.page;for(let u=0;u<a.length;u++)s.pages.push({id:parseInt(a[u].id,10)||0,file:a[u].file});const l={};s.baseLineOffset=s.lineHeight-parseInt(n.base,10);const c=t.char;for(let u=0;u<c.length;u++){const d=c[u],f=parseInt(d.id,10);let p=d.letter??d.char??String.fromCharCode(f);p==="space"&&(p=" "),l[f]=p,s.chars[p]={id:f,page:parseInt(d.page,10)||0,x:parseInt(d.x,10),y:parseInt(d.y,10),width:parseInt(d.width,10),height:parseInt(d.height,10),xOffset:parseInt(d.xoffset,10),yOffset:parseInt(d.yoffset,10),xAdvance:parseInt(d.xadvance,10),kerning:{}}}const h=t.kerning||[];for(let u=0;u<h.length;u++){const d=parseInt(h[u].first,10),f=parseInt(h[u].second,10),p=parseInt(h[u].amount,10);s.chars[l[f]].kerning[l[d]]=p}return s}},r0={test(i){const e=i;return typeof e!="string"&&"getElementsByTagName"in e&&e.getElementsByTagName("page").length&&e.getElementsByTagName("info")[0].getAttribute("face")!==null},parse(i){const e={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},t=i.getElementsByTagName("info")[0],s=i.getElementsByTagName("common")[0],r=i.getElementsByTagName("distanceField")[0];r&&(e.distanceField={type:r.getAttribute("fieldType"),range:parseInt(r.getAttribute("distanceRange"),10)});const n=i.getElementsByTagName("page"),o=i.getElementsByTagName("char"),a=i.getElementsByTagName("kerning");e.fontSize=parseInt(t.getAttribute("size"),10),e.fontFamily=t.getAttribute("face"),e.lineHeight=parseInt(s.getAttribute("lineHeight"),10);for(let c=0;c<n.length;c++)e.pages.push({id:parseInt(n[c].getAttribute("id"),10)||0,file:n[c].getAttribute("file")});const l={};e.baseLineOffset=e.lineHeight-parseInt(s.getAttribute("base"),10);for(let c=0;c<o.length;c++){const h=o[c],u=parseInt(h.getAttribute("id"),10);let d=h.getAttribute("letter")??h.getAttribute("char")??String.fromCharCode(u);d==="space"&&(d=" "),l[u]=d,e.chars[d]={id:u,page:parseInt(h.getAttribute("page"),10)||0,x:parseInt(h.getAttribute("x"),10),y:parseInt(h.getAttribute("y"),10),width:parseInt(h.getAttribute("width"),10),height:parseInt(h.getAttribute("height"),10),xOffset:parseInt(h.getAttribute("xoffset"),10),yOffset:parseInt(h.getAttribute("yoffset"),10),xAdvance:parseInt(h.getAttribute("xadvance"),10),kerning:{}}}for(let c=0;c<a.length;c++){const h=parseInt(a[c].getAttribute("first"),10),u=parseInt(a[c].getAttribute("second"),10),d=parseInt(a[c].getAttribute("amount"),10);e.chars[l[u]].kerning[l[h]]=d}return e}},n0={test(i){return typeof i=="string"&&i.match(/<font(\s|>)/)?r0.test(Y.get().parseXML(i)):!1},parse(i){return r0.parse(Y.get().parseXML(i))}},vE=[".xml",".fnt"],bE={extension:{type:b.CacheParser,name:"cacheBitmapFont"},test:i=>i instanceof s0,getCacheableAssets(i,e){const t={};return i.forEach(s=>{t[s]=e,t[`${s}-bitmap`]=e}),t[`${e.fontFamily}-bitmap`]=e,t}},TE={extension:{type:b.LoadParser,priority:Kt.Normal},name:"loadBitmapFont",id:"bitmap-font",test(i){return vE.includes(Je.extname(i).toLowerCase())},async testParse(i){return pd.test(i)||n0.test(i)},async parse(i,e,t){const s=pd.test(i)?pd.parse(i):n0.parse(i),{src:r}=e,{pages:n}=s,o=[],a=s.distanceField?{scaleMode:"linear",alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:!1,resolution:1}:{};for(let u=0;u<n.length;++u){const d=n[u].file;let f=Je.join(Je.dirname(r),d);f=Su(f,r),o.push({src:f,data:a})}const l=await t.load(o),c=o.map(u=>l[u.src]);return new s0({data:s,textures:c},r)},async load(i,e){return await(await Y.get().fetch(i)).text()},async unload(i,e,t){await Promise.all(i.pages.map(s=>t.unload(s.texture.source._sourceOrigin))),i.destroy()}};class wE{constructor(e,t=!1){this._loader=e,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=t}add(e){e.forEach(t=>{this._assetList.push(t)}),this.verbose&&console.log("[BackgroundLoader] assets: ",this._assetList),this._isActive&&!this._isLoading&&this._next()}async _next(){if(this._assetList.length&&this._isActive){this._isLoading=!0;const e=[],t=Math.min(this._assetList.length,this._maxConcurrent);for(let s=0;s<t;s++)e.push(this._assetList.pop());await this._loader.load(e),this._isLoading=!1,this._next()}}get active(){return this._isActive}set active(e){this._isActive!==e&&(this._isActive=e,e&&!this._isLoading&&this._next())}}const SE={extension:{type:b.CacheParser,name:"cacheTextureArray"},test:i=>Array.isArray(i)&&i.every(e=>e instanceof M),getCacheableAssets:(i,e)=>{const t={};return i.forEach(s=>{e.forEach((r,n)=>{t[s+(n===0?"":n+1)]=r})}),t}};async function o0(i){if("Image"in globalThis)return new Promise(e=>{const t=new Image;t.onload=()=>{e(!0)},t.onerror=()=>{e(!1)},t.src=i});if("createImageBitmap"in globalThis&&"fetch"in globalThis){try{const e=await(await fetch(i)).blob();await createImageBitmap(e)}catch{return!1}return!0}return!1}const CE={extension:{type:b.DetectionParser,priority:1},test:async()=>o0("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async i=>[...i,"avif"],remove:async i=>i.filter(e=>e!=="avif")},a0=["png","jpg","jpeg"],AE={extension:{type:b.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async i=>[...i,...a0],remove:async i=>i.filter(e=>!a0.includes(e))},EE="WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function on(i){return EE?!1:document.createElement("video").canPlayType(i)!==""}const IE={extension:{type:b.DetectionParser,priority:0},test:async()=>on("video/mp4"),add:async i=>[...i,"mp4","m4v"],remove:async i=>i.filter(e=>e!=="mp4"&&e!=="m4v")},PE={extension:{type:b.DetectionParser,priority:0},test:async()=>on("video/ogg"),add:async i=>[...i,"ogv"],remove:async i=>i.filter(e=>e!=="ogv")},RE={extension:{type:b.DetectionParser,priority:0},test:async()=>on("video/webm"),add:async i=>[...i,"webm"],remove:async i=>i.filter(e=>e!=="webm")},ME={extension:{type:b.DetectionParser,priority:0},test:async()=>o0("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async i=>[...i,"webp"],remove:async i=>i.filter(e=>e!=="webp")},l0=class xn{constructor(){this.loadOptions={...xn.defaultOptions},this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(e,t,s)=>(this._parsersValidated=!1,e[t]=s,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(e,t){const s={promise:null,parser:null};return s.promise=(async()=>{let r=null,n=null;if((t.parser||t.loadParser)&&(n=this._parserHash[t.parser||t.loadParser],t.loadParser&&L(`[Assets] "loadParser" is deprecated, use "parser" instead for ${e}`),n||L(`[Assets] specified load parser "${t.parser||t.loadParser}" not found while loading ${e}`)),!n){for(let o=0;o<this.parsers.length;o++){const a=this.parsers[o];if(a.load&&a.test?.(e,t,this)){n=a;break}}if(!n)return L(`[Assets] ${e} could not be loaded as we don't know how to parse it, ensure the correct parser has been added`),null}r=await n.load(e,t,this),s.parser=n;for(let o=0;o<this.parsers.length;o++){const a=this.parsers[o];a.parse&&a.parse&&await a.testParse?.(r,t,this)&&(r=await a.parse(r,t,this)||r,s.parser=a)}return r})(),s}async load(e,t){this._parsersValidated||this._validateParsers();const s=typeof t=="function"?{...xn.defaultOptions,...this.loadOptions,onProgress:t}:{...xn.defaultOptions,...this.loadOptions,...t||{}},{onProgress:r,onError:n,strategy:o,retryCount:a,retryDelay:l}=s;let c=0;const h={},u=zr(e),d=ut(e,g=>({alias:[g],src:g,data:{}})),f=d.reduce((g,m)=>g+(m.progressSize||1),0),p=d.map(async g=>{const m=Je.toAbsolute(g.src);h[g.src]||(await this._loadAssetWithRetry(m,g,{onProgress:r,onError:n,strategy:o,retryCount:a,retryDelay:l},h),c+=g.progressSize||1,r&&r(c/f))});return await Promise.all(p),u?h[d[0].src]:h}async unload(e){const s=ut(e,r=>({alias:[r],src:r})).map(async r=>{const n=Je.toAbsolute(r.src),o=this.promiseCache[n];if(o){const a=await o.promise;delete this.promiseCache[n],await o.parser?.unload?.(a,r,this)}});await Promise.all(s)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(e=>e.name||e.id).reduce((e,t)=>(!t.name&&!t.id?L("[Assets] parser should have an id"):(e[t.name]||e[t.id])&&L(`[Assets] parser id conflict "${t.id}"`),e[t.name]=t,t.id&&(e[t.id]=t),e),{})}async _loadAssetWithRetry(e,t,s,r){let n=0;const{onError:o,strategy:a,retryCount:l,retryDelay:c}=s,h=u=>new Promise(d=>setTimeout(d,u));for(;;)try{this.promiseCache[e]||(this.promiseCache[e]=this._getLoadPromiseAndParser(e,t)),r[t.src]=await this.promiseCache[e].promise;return}catch(u){delete this.promiseCache[e],delete r[t.src],n++;const d=a!=="retry"||n>l;if(a==="retry"&&!d){o&&o(u,t),await h(c);continue}if(a==="skip"){o&&o(u,t);return}throw o&&o(u,t),new Error(`[Loader.load] Failed to load ${e}.
|
|
323
323
|
${u}`)}}};l0.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",retryCount:3,retryDelay:250};let kE=l0;function Hi(i,e){if(Array.isArray(e)){for(const t of e)if(i.startsWith(`data:${t}`))return!0;return!1}return i.startsWith(`data:${e}`)}function Wi(i,e){const t=i.split("?")[0],s=Je.extname(t).toLowerCase();return Array.isArray(e)?e.includes(s):s===e}const FE=".json",BE="application/json",UE={extension:{type:b.LoadParser,priority:Kt.Low},name:"loadJson",id:"json",test(i){return Hi(i,BE)||Wi(i,FE)},async load(i){return await(await Y.get().fetch(i)).json()}},OE=".txt",DE="text/plain",GE={name:"loadTxt",id:"text",extension:{type:b.LoadParser,priority:Kt.Low,name:"loadTxt"},test(i){return Hi(i,DE)||Wi(i,OE)},async load(i){return await(await Y.get().fetch(i)).text()}},zE=["normal","bold","100","200","300","400","500","600","700","800","900"],NE=[".ttf",".otf",".woff",".woff2"],LE=["font/ttf","font/otf","font/woff","font/woff2"],HE=/^(--|-?[A-Z_])[0-9A-Z_-]*$/i;function WE(i){const e=Je.extname(i),r=Je.basename(i,e).replace(/(-|_)/g," ").toLowerCase().split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1));let n=r.length>0;for(const a of r)if(!a.match(HE)){n=!1;break}let o=r.join(" ");return n||(o=`"${o.replace(/[\\"]/g,"\\$&")}"`),o}const VE=/^[0-9A-Za-z%:/?#\[\]@!\$&'()\*\+,;=\-._~]*$/;function $E(i){return VE.test(i)?i:encodeURI(i)}const XE={extension:{type:b.LoadParser,priority:Kt.Low},name:"loadWebFont",id:"web-font",test(i){return Hi(i,LE)||Wi(i,NE)},async load(i,e){const t=Y.get().getFontFaceSet();if(t){const s=[],r=e.data?.family??WE(i),n=e.data?.weights?.filter(a=>zE.includes(a))??["normal"],o=e.data??{};for(let a=0;a<n.length;a++){const l=n[a],c=new FontFace(r,`url(${$E(i)})`,{...o,weight:l});await c.load(),t.add(c),s.push(c)}return ae.has(`${r}-and-url`)?ae.get(`${r}-and-url`).entries.push({url:i,faces:s}):ae.set(`${r}-and-url`,{entries:[{url:i,faces:s}]}),s.length===1?s[0]:s}return L("[loadWebFont] FontFace API is not supported. Skipping loading font"),null},unload(i){const e=Array.isArray(i)?i:[i],t=e[0].family,s=ae.get(`${t}-and-url`),r=s.entries.find(n=>n.faces.some(o=>e.indexOf(o)!==-1));r.faces=r.faces.filter(n=>e.indexOf(n)===-1),r.faces.length===0&&(s.entries=s.entries.filter(n=>n!==r)),e.forEach(n=>{Y.get().getFontFaceSet().delete(n)}),s.entries.length===0&&ae.remove(`${t}-and-url`)}};function md(i,e=1){const t=Oi.RETINA_PREFIX?.exec(i);return t?parseFloat(t[1]):e}function gd(i,e,t){i.label=t,i._sourceOrigin=t;const s=new M({source:i,label:t}),r=()=>{delete e.promiseCache[t],ae.has(t)&&ae.remove(t)};return s.source.once("destroy",()=>{e.promiseCache[t]&&(L("[Assets] A TextureSource managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the TextureSource."),r())}),s.once("destroy",()=>{i.destroyed||(L("[Assets] A Texture managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the Texture."),r())}),s}const YE=".svg",qE="image/svg+xml",KE={extension:{type:b.LoadParser,priority:Kt.Low,name:"loadSVG"},name:"loadSVG",id:"svg",config:{crossOrigin:"anonymous",parseAsGraphicsContext:!1},test(i){return Hi(i,qE)||Wi(i,YE)},async load(i,e,t){return e.data?.parseAsGraphicsContext??this.config.parseAsGraphicsContext?ZE(i):jE(i,e,t,this.config.crossOrigin)},unload(i){i.destroy(!0)}};async function jE(i,e,t,s){const r=await Y.get().fetch(i),n=Y.get().createImage();n.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(await r.text())}`,n.crossOrigin=s,await n.decode();const o=e.data?.width??n.width,a=e.data?.height??n.height,l=e.data?.resolution||md(i),c=Math.ceil(o*l),h=Math.ceil(a*l),u=Y.get().createCanvas(c,h),d=u.getContext("2d");d.imageSmoothingEnabled=!0,d.imageSmoothingQuality="high",d.drawImage(n,0,0,o*l,a*l);const{parseAsGraphicsContext:f,...p}=e.data??{},g=new Ct({resource:u,alphaMode:"premultiply-alpha-on-upload",resolution:l,...p});return gd(g,t,i)}async function ZE(i){const t=await(await Y.get().fetch(i)).text(),s=new lt;return s.svg(t),s}const JE=`(function () {
|
|
324
324
|
'use strict';
|
|
325
325
|
|
|
@@ -341,7 +341,7 @@ ${u}`)}}};l0.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",r
|
|
|
341
341
|
});
|
|
342
342
|
|
|
343
343
|
})();
|
|
344
|
-
`;let Vi=null,
|
|
344
|
+
`;let Vi=null,xd=class{constructor(){Vi||(Vi=URL.createObjectURL(new Blob([JE],{type:"application/javascript"}))),this.worker=new Worker(Vi)}};xd.revokeObjectURL=function(){Vi&&(URL.revokeObjectURL(Vi),Vi=null)};const QE=`(function () {
|
|
345
345
|
'use strict';
|
|
346
346
|
|
|
347
347
|
async function loadImageBitmap(url, alphaMode) {
|
|
@@ -370,7 +370,7 @@ ${u}`)}}};l0.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",r
|
|
|
370
370
|
};
|
|
371
371
|
|
|
372
372
|
})();
|
|
373
|
-
`;let $i=null;class c0{constructor(){$i||($i=URL.createObjectURL(new Blob([QE],{type:"application/javascript"}))),this.worker=new Worker($i)}}c0.revokeObjectURL=function(){$i&&(URL.revokeObjectURL($i),$i=null)};let h0=0,xd;class eI{constructor(){this._initialized=!1,this._createdWorkers=0,this._workerPool=[],this._queue=[],this._resolveHash={}}isImageBitmapSupported(){return this._isImageBitmapSupported!==void 0?this._isImageBitmapSupported:(this._isImageBitmapSupported=new Promise(e=>{const{worker:t}=new _d;t.addEventListener("message",s=>{t.terminate(),_d.revokeObjectURL(),e(s.data)})}),this._isImageBitmapSupported)}loadImageBitmap(e,t){return this._run("loadImageBitmap",[e,t?.data?.alphaMode])}async _initWorkers(){this._initialized||(this._initialized=!0)}_getWorker(){xd===void 0&&(xd=navigator.hardwareConcurrency||4);let e=this._workerPool.pop();return!e&&this._createdWorkers<xd&&(this._createdWorkers++,e=new c0().worker,e.addEventListener("message",t=>{this._complete(t.data),this._returnWorker(t.target),this._next()})),e}_returnWorker(e){this._workerPool.push(e)}_complete(e){this._resolveHash[e.uuid]&&(e.error!==void 0?this._resolveHash[e.uuid].reject(e.error):this._resolveHash[e.uuid].resolve(e.data),delete this._resolveHash[e.uuid])}async _run(e,t){await this._initWorkers();const s=new Promise((r,n)=>{this._queue.push({id:e,arguments:t,resolve:r,reject:n})});return this._next(),s}_next(){if(!this._queue.length)return;const e=this._getWorker();if(!e)return;const t=this._queue.pop(),s=t.id;this._resolveHash[h0]={resolve:t.resolve,reject:t.reject},e.postMessage({data:t.arguments,uuid:h0++,id:s})}reset(){this._workerPool.forEach(e=>e.terminate()),this._workerPool.length=0,Object.values(this._resolveHash).forEach(({reject:e})=>{e?.(new Error("WorkerManager has been reset before completion"))}),this._resolveHash={},this._queue.length=0,this._initialized=!1,this._createdWorkers=0}}const u0=new eI,tI=[".jpeg",".jpg",".png",".webp",".avif"],iI=["image/jpeg","image/png","image/webp","image/avif"];async function sI(i,e){const t=await Y.get().fetch(i);if(!t.ok)throw new Error(`[loadImageBitmap] Failed to fetch ${i}: ${t.status} ${t.statusText}`);const s=await t.blob();return e?.data?.alphaMode==="premultiplied-alpha"?createImageBitmap(s,{premultiplyAlpha:"none"}):createImageBitmap(s)}const d0={name:"loadTextures",id:"texture",extension:{type:b.LoadParser,priority:Kt.High,name:"loadTextures"},config:{preferWorkers:!0,preferCreateImageBitmap:!0,crossOrigin:"anonymous"},test(i){return Hi(i,iI)||Wi(i,tI)},async load(i,e,t){let s=null;globalThis.createImageBitmap&&this.config.preferCreateImageBitmap?this.config.preferWorkers&&await u0.isImageBitmapSupported()?s=await u0.loadImageBitmap(i,e):s=await sI(i,e):s=await new Promise((n,o)=>{s=Y.get().createImage(),s.crossOrigin=this.config.crossOrigin,s.src=i,s.complete?n(s):(s.onload=()=>{n(s)},s.onerror=o)});const r=new Ct({resource:s,alphaMode:"premultiply-alpha-on-upload",resolution:e.data?.resolution||md(i),...e.data});return gd(r,t,i)},unload(i){i.destroy(!0)}},rI=[".mp4",".m4v",".webm",".ogg",".ogv",".h264",".avi",".mov"];let yd,vd;function nI(i,e,t){t===void 0&&!e.startsWith("data:")?i.crossOrigin=aI(e):t!==!1&&(i.crossOrigin=typeof t=="string"?t:"anonymous")}function oI(i){return new Promise((e,t)=>{i.addEventListener("canplaythrough",s),i.addEventListener("error",r),i.load();function s(){n(),e()}function r(o){n(),t(o)}function n(){i.removeEventListener("canplaythrough",s),i.removeEventListener("error",r)}})}function aI(i,e=globalThis.location){if(i.startsWith("data:"))return"";e||(e=globalThis.location);const t=new URL(i,document.baseURI);return t.hostname!==e.hostname||t.port!==e.port||t.protocol!==e.protocol?"anonymous":""}function lI(){const i=[],e=[];for(const t of rI){const s=ms.MIME_TYPES[t.substring(1)]||`video/${t.substring(1)}`;on(s)&&(i.push(t),e.includes(s)||e.push(s))}return{validVideoExtensions:i,validVideoMime:e}}const cI={name:"loadVideo",id:"video",extension:{type:b.LoadParser,name:"loadVideo"},test(i){if(!yd||!vd){const{validVideoExtensions:s,validVideoMime:r}=lI();yd=s,vd=r}const e=Hi(i,vd),t=Wi(i,yd);return e||t},async load(i,e,t){const s={...ms.defaultOptions,resolution:e.data?.resolution||md(i),alphaMode:e.data?.alphaMode||await vm(),...e.data},r=document.createElement("video"),n={preload:s.autoLoad!==!1?"auto":void 0,"webkit-playsinline":s.playsinline!==!1?"":void 0,playsinline:s.playsinline!==!1?"":void 0,muted:s.muted===!0?"":void 0,loop:s.loop===!0?"":void 0,autoplay:s.autoPlay!==!1?"":void 0};Object.keys(n).forEach(l=>{const c=n[l];c!==void 0&&r.setAttribute(l,c)}),s.muted===!0&&(r.muted=!0),nI(r,i,s.crossorigin);const o=document.createElement("source");let a;if(s.mime)a=s.mime;else if(i.startsWith("data:"))a=i.slice(5,i.indexOf(";"));else if(!i.startsWith("blob:")){const l=i.split("?")[0].slice(i.lastIndexOf(".")+1).toLowerCase();a=ms.MIME_TYPES[l]||`video/${l}`}return o.src=i,a&&(o.type=a),new Promise(l=>{const c=async()=>{const h=new ms({...s,resource:r});r.removeEventListener("canplay",c),e.data.preload&&await oI(r),l(gd(h,t,i))};s.preload&&!s.autoPlay&&r.load(),r.addEventListener("canplay",c),r.appendChild(o)})},unload(i){i.destroy(!0)}},f0={extension:{type:b.ResolveParser,name:"resolveTexture"},test:d0.test,parse:i=>({resolution:parseFloat(Oi.RETINA_PREFIX.exec(i)?.[1]??"1"),format:i.split(".").pop(),src:i})},hI={extension:{type:b.ResolveParser,priority:-2,name:"resolveJson"},test:i=>Oi.RETINA_PREFIX.test(i)&&i.endsWith(".json"),parse:f0.parse};class uI{constructor(){this._detections=[],this._initialized=!1,this.resolver=new Oi,this.loader=new kE,this.cache=ae,this._backgroundLoader=new wE(this.loader),this._backgroundLoader.active=!0,this.reset()}async init(e={}){if(this._initialized){L("[Assets]AssetManager already initialized, did you load before calling this Assets.init()?");return}if(this._initialized=!0,e.defaultSearchParams&&this.resolver.setDefaultSearchParams(e.defaultSearchParams),e.basePath&&(this.resolver.basePath=e.basePath),e.bundleIdentifier&&this.resolver.setBundleIdentifier(e.bundleIdentifier),e.manifest){let n=e.manifest;typeof n=="string"&&(n=await this.load(n)),this.resolver.addManifest(n)}const t=e.texturePreference?.resolution??1,s=typeof t=="number"?[t]:t,r=await this._detectFormats({preferredFormats:e.texturePreference?.format,skipDetections:e.skipDetections,detections:this._detections});this.resolver.prefer({params:{format:r,resolution:s}}),e.preferences&&this.setPreferences(e.preferences),e.loadOptions&&(this.loader.loadOptions={...this.loader.loadOptions,...e.loadOptions})}add(e){this.resolver.add(e)}async load(e,t){this._initialized||await this.init();const s=zr(e),r=ut(e).map(a=>{if(typeof a!="string"){const l=this.resolver.getAlias(a);return l.some(c=>!this.resolver.hasKey(c))&&this.add(a),Array.isArray(l)?l[0]:l}return this.resolver.hasKey(a)||this.add({alias:a,src:a}),a}),n=this.resolver.resolve(r),o=await this._mapLoadToResolve(n,t);return s?o[r[0]]:o}addBundle(e,t){this.resolver.addBundle(e,t)}async loadBundle(e,t){this._initialized||await this.init();let s=!1;typeof e=="string"&&(s=!0,e=[e]);const r=this.resolver.resolveBundle(e),n={},o=Object.keys(r);let a=0;const l=[],c=()=>{t?.(l.reduce((u,d)=>u+d,0)/a)},h=o.map((u,d)=>{const f=r[u],p=Object.values(f),m=[...new Set(p.flat())].reduce((_,x)=>_+(x.progressSize||1),0);return l.push(0),a+=m,this._mapLoadToResolve(f,_=>{l[d]=_*m,c()}).then(_=>{n[u]=_})});return await Promise.all(h),s?n[e[0]]:n}async backgroundLoad(e){this._initialized||await this.init(),typeof e=="string"&&(e=[e]);const t=this.resolver.resolve(e);this._backgroundLoader.add(Object.values(t))}async backgroundLoadBundle(e){this._initialized||await this.init(),typeof e=="string"&&(e=[e]);const t=this.resolver.resolveBundle(e);Object.values(t).forEach(s=>{this._backgroundLoader.add(Object.values(s))})}reset(){this.resolver.reset(),this.loader.reset(),this.cache.reset(),this._initialized=!1}get(e){if(typeof e=="string")return ae.get(e);const t={};for(let s=0;s<e.length;s++)t[s]=ae.get(e[s]);return t}async _mapLoadToResolve(e,t){const s=[...new Set(Object.values(e))];this._backgroundLoader.active=!1;const r=await this.loader.load(s,t);this._backgroundLoader.active=!0;const n={};return s.forEach(o=>{const a=r[o.src],l=[o.src];o.alias&&l.push(...o.alias),l.forEach(c=>{n[c]=a}),ae.set(l,a)}),n}async unload(e){this._initialized||await this.init();const t=ut(e).map(r=>typeof r!="string"?r.src:r),s=this.resolver.resolve(t);await this._unloadFromResolved(s)}async unloadBundle(e){this._initialized||await this.init(),e=ut(e);const t=this.resolver.resolveBundle(e),s=Object.keys(t).map(r=>this._unloadFromResolved(t[r]));await Promise.all(s)}async _unloadFromResolved(e){const t=Object.values(e);t.forEach(s=>{ae.remove(s.src)}),await this.loader.unload(t)}async _detectFormats(e){let t=[];e.preferredFormats&&(t=Array.isArray(e.preferredFormats)?e.preferredFormats:[e.preferredFormats]);for(const s of e.detections)e.skipDetections||await s.test()?t=await s.add(t):e.skipDetections||(t=await s.remove(t));return t=t.filter((s,r)=>t.indexOf(s)===r),t}get detections(){return this._detections}setPreferences(e){this.loader.parsers.forEach(t=>{t.config&&Object.keys(t.config).filter(s=>s in e).forEach(s=>{t.config[s]=e[s]})})}}const Ls=new uI;V.handleByList(b.LoadParser,Ls.loader.parsers).handleByList(b.ResolveParser,Ls.resolver.parsers).handleByList(b.CacheParser,Ls.cache.parsers).handleByList(b.DetectionParser,Ls.detections),V.add(SE,AE,CE,ME,IE,PE,RE,UE,GE,XE,KE,d0,cI,TE,bE,f0,hI);const p0={loader:b.LoadParser,resolver:b.ResolveParser,cache:b.CacheParser,detection:b.DetectionParser};V.handle(b.Asset,i=>{const e=i.ref;Object.entries(p0).filter(([t])=>!!e[t]).forEach(([t,s])=>V.add(Object.assign(e[t],{extension:e[t].extension??s})))},i=>{const e=i.ref;Object.keys(p0).filter(t=>!!e[t]).forEach(t=>V.remove(e[t]))});class m0{constructor(e){this._attachedDomElements=[],this._renderer=e,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new Am({domElement:this._domElement,renderer:this._renderer})}addRenderable(e,t){this._attachedDomElements.includes(e)||this._attachedDomElements.push(e)}updateRenderable(e){}validateRenderable(e){return!0}postrender(){const e=this._attachedDomElements;if(e.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let t=0;t<e.length;t++){const s=e[t],r=s.element;if(!s.parent||s.globalDisplayStatus<7)r?.remove(),e.splice(t,1),t--;else{this._domElement.contains(r)||(r.style.position="absolute",r.style.pointerEvents="auto",this._domElement.appendChild(r));const n=s.worldTransform,o=s._anchor,a=s.width*o.x,l=s.height*o.y;r.style.transformOrigin=`${a}px ${l}px`,r.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,r.style.opacity=s.groupAlpha.toString()}}}destroy(){this._renderer.runners.postrender.remove(this);for(let e=0;e<this._attachedDomElements.length;e++)this._attachedDomElements[e].element?.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}m0.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"dom"};class dI{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(e){this.removeTickerListener(),this.events=e,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(e){this._pauseUpdate=e}addTickerListener(){this._tickerAdded||!this.domElement||(Ze.system.add(this._tickerUpdate,this,Ui.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(Ze.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const e=this.events._rootPointerEvent;this.events.supportsTouchEvents&&e.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,pointerId:e.pointerId}):new MouseEvent("mousemove",{clientX:e.clientX,clientY:e.clientY}))}_tickerUpdate(e){this._deltaTime+=e.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const zt=new dI;class an extends _s{constructor(){super(...arguments),this.client=new X,this.movement=new X,this.offset=new X,this.global=new X,this.screen=new X}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(e,t,s){return e.worldTransform.applyInverse(s||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,s,r,n,o,a,l,c,h,u,d,f,p,g){throw new Error("Method not implemented.")}}class mt extends an{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Xi extends an{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Xi.DOM_DELTA_PIXEL=0,Xi.DOM_DELTA_LINE=1,Xi.DOM_DELTA_PAGE=2;const fI=2048,pI=new X,Hs=new X;class mI{constructor(e){this.dispatch=new je,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=e,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((s,r)=>s.priority-r.priority)}dispatchEvent(e,t){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,t),this.dispatch.emit(t||e.type,e)}mapEvent(e){if(!this.rootTarget)return;const t=this.mappingTable[e.type];if(t)for(let s=0,r=t.length;s<r;s++)t[s].fn(e);else L(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){zt.pauseUpdate=!0;const r=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[r](this.rootTarget,this.rootTarget.eventMode,pI.set(e,t),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(e,t){if(!e.target)return;const s=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let r=0,n=s.length-1;r<n;r++)if(e.currentTarget=s[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return;if(e.eventPhase=e.AT_TARGET,e.currentTarget=e.target,this.notifyTarget(e,t),!(e.propagationStopped||e.propagationImmediatelyStopped)){e.eventPhase=e.BUBBLING_PHASE;for(let r=s.length-2;r>=0;r--)if(e.currentTarget=s[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,s=this._allInteractiveElements){if(s.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const r=Array.isArray(t)?t:[t];for(let n=s.length-1;n>=0;n--)r.forEach(o=>{e.currentTarget=s[n],this.notifyTarget(e,o)})}propagationPath(e){const t=[e];for(let s=0;s<fI&&e!==this.rootTarget&&e.parent;s++){if(!e.parent)throw new Error("Cannot find propagation path to disconnected target");t.push(e.parent),e=e.parent}return t.reverse(),t}hitTestMoveRecursive(e,t,s,r,n,o=!1){let a=!1;if(this._interactivePrune(e))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(zt.pauseUpdate=!1),e.interactiveChildren&&e.children){const h=e.children;for(let u=h.length-1;u>=0;u--){const d=h[u],f=this.hitTestMoveRecursive(d,this._isInteractive(t)?t:d.eventMode,s,r,n,o||n(e,s));if(f){if(f.length>0&&!f[f.length-1].parent)continue;const p=e.isInteractive();(f.length>0||p)&&(p&&this._allInteractiveElements.push(e),f.push(e)),this._hitElements.length===0&&(this._hitElements=f),a=!0}}}const l=this._isInteractive(t),c=e.isInteractive();return c&&c&&this._allInteractiveElements.push(e),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(e,s)&&r(e,s)?c?[e]:[]:null}hitTestRecursive(e,t,s,r,n){if(this._interactivePrune(e)||n(e,s))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(zt.pauseUpdate=!1),e.interactiveChildren&&e.children){const l=e.children,c=s;for(let h=l.length-1;h>=0;h--){const u=l[h],d=this.hitTestRecursive(u,this._isInteractive(t)?t:u.eventMode,c,r,n);if(d){if(d.length>0&&!d[d.length-1].parent)continue;const f=e.isInteractive();return(d.length>0||f)&&d.push(e),d}}}const o=this._isInteractive(t),a=e.isInteractive();return o&&r(e,s)?a?[e]:[]:null}_isInteractive(e){return e==="static"||e==="dynamic"}_interactivePrune(e){return!e||!e.visible||!e.renderable||!e.measurable||e.eventMode==="none"||e.eventMode==="passive"&&!e.interactiveChildren}hitPruneFn(e,t){if(e.hitArea&&(e.worldTransform.applyInverse(t,Hs),!e.hitArea.contains(Hs.x,Hs.y)))return!0;if(e.effects&&e.effects.length)for(let s=0;s<e.effects.length;s++){const r=e.effects[s];if(r.containsPoint&&!r.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e?.containsPoint?(e.worldTransform.applyInverse(t,Hs),e.containsPoint(Hs)):!1}notifyTarget(e,t){if(!e.currentTarget.isInteractive())return;t??(t=e.type);const s=`on${t}`;e.currentTarget[s]?.(e);const r=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,r),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.createPointerEvent(e);if(this.dispatchEvent(t,"pointerdown"),t.pointerType==="touch")this.dispatchEvent(t,"touchstart");else if(t.pointerType==="mouse"||t.pointerType==="pen"){const r=t.button===2;this.dispatchEvent(t,r?"rightdown":"mousedown")}const s=this.trackingData(e.pointerId);s.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const t=this.createPointerEvent(e);this._isPointerMoveEvent=!1;const s=t.pointerType==="mouse"||t.pointerType==="pen",r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.overTargets);if(r.overTargets?.length>0&&n!==t.target){const l=e.type==="mousemove"?"mouseout":"pointerout",c=this.createPointerEvent(e,l,n);if(this.dispatchEvent(c,"pointerout"),s&&this.dispatchEvent(c,"mouseout"),!t.composedPath().includes(n)){const h=this.createPointerEvent(e,"pointerleave",n);for(h.eventPhase=h.AT_TARGET;h.target&&!t.composedPath().includes(h.target);)h.currentTarget=h.target,this.notifyTarget(h),s&&this.notifyTarget(h,"mouseleave"),h.target=h.target.parent;this.freeEvent(h)}this.freeEvent(c)}if(n!==t.target){const l=e.type==="mousemove"?"mouseover":"pointerover",c=this.clonePointerEvent(t,l);this.dispatchEvent(c,"pointerover"),s&&this.dispatchEvent(c,"mouseover");let h=n?.parent;for(;h&&h!==this.rootTarget.parent&&h!==t.target;)h=h.parent;if(!h||h===this.rootTarget.parent){const d=this.clonePointerEvent(t,"pointerenter");for(d.eventPhase=d.AT_TARGET;d.target&&d.target!==n&&d.target!==this.rootTarget.parent;)d.currentTarget=d.target,this.notifyTarget(d),s&&this.notifyTarget(d,"mouseenter"),d.target=d.target.parent;this.freeEvent(d)}this.freeEvent(c)}const o=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?o.push("pointermove"):this.dispatchEvent(t,"pointermove"),a&&o.push("globalpointermove"),t.pointerType==="touch"&&(this.moveOnAll?o.splice(1,0,"touchmove"):this.dispatchEvent(t,"touchmove"),a&&o.push("globaltouchmove")),s&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&o.push("globalmousemove"),this.cursor=t.target?.cursor),o.length>0&&this.all(t,o),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.createPointerEvent(e),r=s.pointerType==="mouse"||s.pointerType==="pen";this.dispatchEvent(s,"pointerover"),r&&this.dispatchEvent(s,"mouseover"),s.pointerType==="mouse"&&(this.cursor=s.target?.cursor);const n=this.clonePointerEvent(s,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),r&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;t.overTargets=s.composedPath(),this.freeEvent(s),this.freeEvent(n)}mapPointerOut(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const s=e.pointerType==="mouse"||e.pointerType==="pen",r=this.findMountedTarget(t.overTargets),n=this.createPointerEvent(e,"pointerout",r);this.dispatchEvent(n),s&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(e,"pointerleave",r);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),s&&this.notifyTarget(o,"mouseleave"),o.target=o.target.parent;t.overTargets=null,this.freeEvent(n),this.freeEvent(o)}this.cursor=null}mapPointerUp(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),s=this.createPointerEvent(e);if(this.dispatchEvent(s,"pointerup"),s.pointerType==="touch")this.dispatchEvent(s,"touchend");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const a=s.button===2;this.dispatchEvent(s,a?"rightup":"mouseup")}const r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.pressTargetsByButton[e.button]);let o=n;if(n&&!s.composedPath().includes(n)){let a=n;for(;a&&!s.composedPath().includes(a);){if(s.currentTarget=a,this.notifyTarget(s,"pointerupoutside"),s.pointerType==="touch")this.notifyTarget(s,"touchendoutside");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const l=s.button===2;this.notifyTarget(s,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete r.pressTargetsByButton[e.button],o=a}if(o){const a=this.clonePointerEvent(s,"click");a.target=o,a.path=null,r.clicksByButton[e.button]||(r.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const l=r.clicksByButton[e.button];if(l.target===a.target&&t-l.timeStamp<200?++l.clickCount:l.clickCount=1,l.target=a.target,l.timeStamp=t,a.detail=l.clickCount,a.pointerType==="mouse"){const c=a.button===2;this.dispatchEvent(a,c?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(s)}mapPointerUpOutside(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.findMountedTarget(t.pressTargetsByButton[e.button]),r=this.createPointerEvent(e);if(s){let n=s;for(;n;)r.currentTarget=n,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch"?this.notifyTarget(r,"touchendoutside"):(r.pointerType==="mouse"||r.pointerType==="pen")&&this.notifyTarget(r,r.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(r)}mapWheel(e){if(!(e instanceof Xi)){L("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let s=1;s<e.length&&e[s].parent===t;s++)t=e[s];return t}createPointerEvent(e,t,s){const r=this.allocateEvent(mt);return this.copyPointerData(e,r),this.copyMouseData(e,r),this.copyData(e,r),r.nativeEvent=e.nativeEvent,r.originalEvent=e,r.target=s??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof t=="string"&&(r.type=t),r}createWheelEvent(e){const t=this.allocateEvent(Xi);return this.copyWheelData(e,t),this.copyMouseData(e,t),this.copyData(e,t),t.nativeEvent=e.nativeEvent,t.originalEvent=e,t.target=this.hitTest(t.global.x,t.global.y),t}clonePointerEvent(e,t){const s=this.allocateEvent(mt);return s.nativeEvent=e.nativeEvent,s.originalEvent=e.originalEvent,this.copyPointerData(e,s),this.copyMouseData(e,s),this.copyData(e,s),s.target=e.target,s.path=e.composedPath().slice(),s.type=t??s.type,s}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof mt&&t instanceof mt&&(t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist)}copyMouseData(e,t){e instanceof an&&t instanceof an&&(t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.copyFrom(e.client),t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.copyFrom(e.movement),t.screen.copyFrom(e.screen),t.shiftKey=e.shiftKey,t.global.copyFrom(e.global))}copyData(e,t){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.detail=e.detail,t.view=e.view,t.which=e.which,t.layer.copyFrom(e.layer),t.page.copyFrom(e.page)}trackingData(e){return this.mappingState.trackingData[e]||(this.mappingState.trackingData[e]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[e]}allocateEvent(e){this.eventPool.has(e)||this.eventPool.set(e,[]);const t=this.eventPool.get(e).pop()||new e(this);return t.eventPhase=t.NONE,t.currentTarget=null,t.defaultPrevented=!1,t.path=null,t.target=null,t}freeEvent(e){if(e.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const t=e.constructor;this.eventPool.has(t)||this.eventPool.set(t,[]),this.eventPool.get(t).push(e)}_notifyListeners(e,t){const s=e.currentTarget._events[t];if(s)if("fn"in s)s.once&&e.currentTarget.removeListener(t,s.fn,void 0,!0),s.fn.call(s.context,e);else for(let r=0,n=s.length;r<n&&!e.propagationImmediatelyStopped;r++)s[r].once&&e.currentTarget.removeListener(t,s[r].fn,void 0,!0),s[r].fn.call(s[r].context,e)}}const gI=1,_I={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},bd=class uf{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new mI(null),zt.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new mt(null),this._rootWheelEvent=new Xi(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...uf.defaultEventFeatures},{set:(t,s,r)=>(s==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=r),t[s]=r,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:s}=this.renderer;this.setTargetElement(t),this.resolution=s,uf._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){zt.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(e){e||(e="default");let t=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(t=!1),this._currentCursor===e)return;this._currentCursor=e;const s=this.cursorStyles[e];if(s)switch(typeof s){case"string":t&&(this.domElement.style.cursor=s);break;case"function":s(e);break;case"object":t&&Object.assign(this.domElement.style,s);break}else t&&typeof e=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,e)&&(this.domElement.style.cursor=e)}get pointer(){return this._rootPointerEvent}_onPointerDown(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);this.autoPreventDefault&&t[0].isNormalized&&(e.cancelable||!("cancelable"in e))&&e.preventDefault();for(let s=0,r=t.length;s<r;s++){const n=t[s],o=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(e){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,zt.pointerMoved();const t=this._normalizeToPointerData(e);for(let s=0,r=t.length;s<r;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=e.target;e.composedPath&&e.composedPath().length>0&&(t=e.composedPath()[0]);const s=t!==this.domElement?"outside":"",r=this._normalizeToPointerData(e);for(let n=0,o=r.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,r[n]);a.type+=s,this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);for(let s=0,r=t.length;s<r;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(e){if(!this.features.wheel)return;const t=this.normalizeWheelEvent(e);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(t)}setTargetElement(e){this._removeEvents(),this.domElement=e,zt.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;zt.addTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="none",e.msTouchAction="none"):this.supportsPointerEvents&&(e.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;zt.removeTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="",e.msTouchAction=""):this.supportsPointerEvents&&(e.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,s){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},n=1/this.resolution;e.x=(t-r.left)*(this.domElement.width/r.width)*n,e.y=(s-r.top)*(this.domElement.height/r.height)*n}_normalizeToPointerData(e){const t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let s=0,r=e.changedTouches.length;s<r;s++){const n=e.changedTouches[s];typeof n.button>"u"&&(n.button=0),typeof n.buttons>"u"&&(n.buttons=1),typeof n.isPrimary>"u"&&(n.isPrimary=e.touches.length===1&&e.type==="touchstart"),typeof n.width>"u"&&(n.width=n.radiusX||1),typeof n.height>"u"&&(n.height=n.radiusY||1),typeof n.tiltX>"u"&&(n.tiltX=0),typeof n.tiltY>"u"&&(n.tiltY=0),typeof n.pointerType>"u"&&(n.pointerType="touch"),typeof n.pointerId>"u"&&(n.pointerId=n.identifier||0),typeof n.pressure>"u"&&(n.pressure=n.force||.5),typeof n.twist>"u"&&(n.twist=0),typeof n.tangentialPressure>"u"&&(n.tangentialPressure=0),typeof n.layerX>"u"&&(n.layerX=n.offsetX=n.clientX),typeof n.layerY>"u"&&(n.layerY=n.offsetY=n.clientY),n.isNormalized=!0,n.type=e.type,t.push(n)}else if(!globalThis.MouseEvent||e instanceof MouseEvent&&(!this.supportsPointerEvents||!(e instanceof globalThis.PointerEvent))){const s=e;typeof s.isPrimary>"u"&&(s.isPrimary=!0),typeof s.width>"u"&&(s.width=1),typeof s.height>"u"&&(s.height=1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="mouse"),typeof s.pointerId>"u"&&(s.pointerId=gI),typeof s.pressure>"u"&&(s.pressure=.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),s.isNormalized=!0,t.push(s)}else t.push(e);return t}normalizeWheelEvent(e){const t=this._rootWheelEvent;return this._transferMouseData(t,e),t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ,t.deltaMode=e.deltaMode,this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.nativeEvent=e,t.type=e.type,t}_bootstrapEvent(e,t){return e.originalEvent=null,e.nativeEvent=t,e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist,this._transferMouseData(e,t),this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.isTrusted=t.isTrusted,e.type==="pointerleave"&&(e.type="pointerout"),e.type.startsWith("mouse")&&(e.type=e.type.replace("mouse","pointer")),e.type.startsWith("touch")&&(e.type=_I[e.type]||e.type),e}_transferMouseData(e,t){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.x=t.clientX,e.client.y=t.clientY,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.relatedTarget=null,e.shiftKey=t.shiftKey}};bd.extension={name:"events",type:[b.WebGLSystem,b.CanvasSystem,b.WebGPUSystem],priority:-1},bd.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let g0=bd;const xI={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(i){this.eventMode=i?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??g0.defaultEventMode},set eventMode(i){this._internalEventMode=i},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(i,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof t=="object"?t.signal:void 0,n=typeof t=="object"?t.once===!0:!1,o=typeof e=="function"?void 0:e;i=s?`${i}capture`:i;const a=typeof e=="function"?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(i,a,o)}),n?l.once(i,a,o):l.on(i,a,o)},removeEventListener(i,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof e=="function"?void 0:e;i=s?`${i}capture`:i,e=typeof e=="function"?e:e.handleEvent,this.off(i,e,r)},dispatchEvent(i){if(!(i instanceof _s))throw new Error("Container cannot propagate events outside of the Federated Events API");return i.defaultPrevented=!1,i.path=null,i.target=this,i.manager.dispatchEvent(i),!i.defaultPrevented}};var yI=`in vec2 aPosition;
|
|
373
|
+
`;let $i=null;class c0{constructor(){$i||($i=URL.createObjectURL(new Blob([QE],{type:"application/javascript"}))),this.worker=new Worker($i)}}c0.revokeObjectURL=function(){$i&&(URL.revokeObjectURL($i),$i=null)};let h0=0,_d;class eI{constructor(){this._initialized=!1,this._createdWorkers=0,this._workerPool=[],this._queue=[],this._resolveHash={}}isImageBitmapSupported(){return this._isImageBitmapSupported!==void 0?this._isImageBitmapSupported:(this._isImageBitmapSupported=new Promise(e=>{const{worker:t}=new xd;t.addEventListener("message",s=>{t.terminate(),xd.revokeObjectURL(),e(s.data)})}),this._isImageBitmapSupported)}loadImageBitmap(e,t){return this._run("loadImageBitmap",[e,t?.data?.alphaMode])}async _initWorkers(){this._initialized||(this._initialized=!0)}_getWorker(){_d===void 0&&(_d=navigator.hardwareConcurrency||4);let e=this._workerPool.pop();return!e&&this._createdWorkers<_d&&(this._createdWorkers++,e=new c0().worker,e.addEventListener("message",t=>{this._complete(t.data),this._returnWorker(t.target),this._next()})),e}_returnWorker(e){this._workerPool.push(e)}_complete(e){this._resolveHash[e.uuid]&&(e.error!==void 0?this._resolveHash[e.uuid].reject(e.error):this._resolveHash[e.uuid].resolve(e.data),delete this._resolveHash[e.uuid])}async _run(e,t){await this._initWorkers();const s=new Promise((r,n)=>{this._queue.push({id:e,arguments:t,resolve:r,reject:n})});return this._next(),s}_next(){if(!this._queue.length)return;const e=this._getWorker();if(!e)return;const t=this._queue.pop(),s=t.id;this._resolveHash[h0]={resolve:t.resolve,reject:t.reject},e.postMessage({data:t.arguments,uuid:h0++,id:s})}reset(){this._workerPool.forEach(e=>e.terminate()),this._workerPool.length=0,Object.values(this._resolveHash).forEach(({reject:e})=>{e?.(new Error("WorkerManager has been reset before completion"))}),this._resolveHash={},this._queue.length=0,this._initialized=!1,this._createdWorkers=0}}const u0=new eI,tI=[".jpeg",".jpg",".png",".webp",".avif"],iI=["image/jpeg","image/png","image/webp","image/avif"];async function sI(i,e){const t=await Y.get().fetch(i);if(!t.ok)throw new Error(`[loadImageBitmap] Failed to fetch ${i}: ${t.status} ${t.statusText}`);const s=await t.blob();return e?.data?.alphaMode==="premultiplied-alpha"?createImageBitmap(s,{premultiplyAlpha:"none"}):createImageBitmap(s)}const d0={name:"loadTextures",id:"texture",extension:{type:b.LoadParser,priority:Kt.High,name:"loadTextures"},config:{preferWorkers:!0,preferCreateImageBitmap:!0,crossOrigin:"anonymous"},test(i){return Hi(i,iI)||Wi(i,tI)},async load(i,e,t){let s=null;globalThis.createImageBitmap&&this.config.preferCreateImageBitmap?this.config.preferWorkers&&await u0.isImageBitmapSupported()?s=await u0.loadImageBitmap(i,e):s=await sI(i,e):s=await new Promise((n,o)=>{s=Y.get().createImage(),s.crossOrigin=this.config.crossOrigin,s.src=i,s.complete?n(s):(s.onload=()=>{n(s)},s.onerror=o)});const r=new Ct({resource:s,alphaMode:"premultiply-alpha-on-upload",resolution:e.data?.resolution||md(i),...e.data});return gd(r,t,i)},unload(i){i.destroy(!0)}},rI=[".mp4",".m4v",".webm",".ogg",".ogv",".h264",".avi",".mov"];let yd,vd;function nI(i,e,t){t===void 0&&!e.startsWith("data:")?i.crossOrigin=aI(e):t!==!1&&(i.crossOrigin=typeof t=="string"?t:"anonymous")}function oI(i){return new Promise((e,t)=>{i.addEventListener("canplaythrough",s),i.addEventListener("error",r),i.load();function s(){n(),e()}function r(o){n(),t(o)}function n(){i.removeEventListener("canplaythrough",s),i.removeEventListener("error",r)}})}function aI(i,e=globalThis.location){if(i.startsWith("data:"))return"";e||(e=globalThis.location);const t=new URL(i,document.baseURI);return t.hostname!==e.hostname||t.port!==e.port||t.protocol!==e.protocol?"anonymous":""}function lI(){const i=[],e=[];for(const t of rI){const s=ms.MIME_TYPES[t.substring(1)]||`video/${t.substring(1)}`;on(s)&&(i.push(t),e.includes(s)||e.push(s))}return{validVideoExtensions:i,validVideoMime:e}}const cI={name:"loadVideo",id:"video",extension:{type:b.LoadParser,name:"loadVideo"},test(i){if(!yd||!vd){const{validVideoExtensions:s,validVideoMime:r}=lI();yd=s,vd=r}const e=Hi(i,vd),t=Wi(i,yd);return e||t},async load(i,e,t){const s={...ms.defaultOptions,resolution:e.data?.resolution||md(i),alphaMode:e.data?.alphaMode||await vm(),...e.data},r=document.createElement("video"),n={preload:s.autoLoad!==!1?"auto":void 0,"webkit-playsinline":s.playsinline!==!1?"":void 0,playsinline:s.playsinline!==!1?"":void 0,muted:s.muted===!0?"":void 0,loop:s.loop===!0?"":void 0,autoplay:s.autoPlay!==!1?"":void 0};Object.keys(n).forEach(l=>{const c=n[l];c!==void 0&&r.setAttribute(l,c)}),s.muted===!0&&(r.muted=!0),nI(r,i,s.crossorigin);const o=document.createElement("source");let a;if(s.mime)a=s.mime;else if(i.startsWith("data:"))a=i.slice(5,i.indexOf(";"));else if(!i.startsWith("blob:")){const l=i.split("?")[0].slice(i.lastIndexOf(".")+1).toLowerCase();a=ms.MIME_TYPES[l]||`video/${l}`}return o.src=i,a&&(o.type=a),new Promise(l=>{const c=async()=>{const h=new ms({...s,resource:r});r.removeEventListener("canplay",c),e.data.preload&&await oI(r),l(gd(h,t,i))};s.preload&&!s.autoPlay&&r.load(),r.addEventListener("canplay",c),r.appendChild(o)})},unload(i){i.destroy(!0)}},f0={extension:{type:b.ResolveParser,name:"resolveTexture"},test:d0.test,parse:i=>({resolution:parseFloat(Oi.RETINA_PREFIX.exec(i)?.[1]??"1"),format:i.split(".").pop(),src:i})},hI={extension:{type:b.ResolveParser,priority:-2,name:"resolveJson"},test:i=>Oi.RETINA_PREFIX.test(i)&&i.endsWith(".json"),parse:f0.parse};class uI{constructor(){this._detections=[],this._initialized=!1,this.resolver=new Oi,this.loader=new kE,this.cache=ae,this._backgroundLoader=new wE(this.loader),this._backgroundLoader.active=!0,this.reset()}async init(e={}){if(this._initialized){L("[Assets]AssetManager already initialized, did you load before calling this Assets.init()?");return}if(this._initialized=!0,e.defaultSearchParams&&this.resolver.setDefaultSearchParams(e.defaultSearchParams),e.basePath&&(this.resolver.basePath=e.basePath),e.bundleIdentifier&&this.resolver.setBundleIdentifier(e.bundleIdentifier),e.manifest){let n=e.manifest;typeof n=="string"&&(n=await this.load(n)),this.resolver.addManifest(n)}const t=e.texturePreference?.resolution??1,s=typeof t=="number"?[t]:t,r=await this._detectFormats({preferredFormats:e.texturePreference?.format,skipDetections:e.skipDetections,detections:this._detections});this.resolver.prefer({params:{format:r,resolution:s}}),e.preferences&&this.setPreferences(e.preferences),e.loadOptions&&(this.loader.loadOptions={...this.loader.loadOptions,...e.loadOptions})}add(e){this.resolver.add(e)}async load(e,t){this._initialized||await this.init();const s=zr(e),r=ut(e).map(a=>{if(typeof a!="string"){const l=this.resolver.getAlias(a);return l.some(c=>!this.resolver.hasKey(c))&&this.add(a),Array.isArray(l)?l[0]:l}return this.resolver.hasKey(a)||this.add({alias:a,src:a}),a}),n=this.resolver.resolve(r),o=await this._mapLoadToResolve(n,t);return s?o[r[0]]:o}addBundle(e,t){this.resolver.addBundle(e,t)}async loadBundle(e,t){this._initialized||await this.init();let s=!1;typeof e=="string"&&(s=!0,e=[e]);const r=this.resolver.resolveBundle(e),n={},o=Object.keys(r);let a=0;const l=[],c=()=>{t?.(l.reduce((u,d)=>u+d,0)/a)},h=o.map((u,d)=>{const f=r[u],p=Object.values(f),m=[...new Set(p.flat())].reduce((x,_)=>x+(_.progressSize||1),0);return l.push(0),a+=m,this._mapLoadToResolve(f,x=>{l[d]=x*m,c()}).then(x=>{n[u]=x})});return await Promise.all(h),s?n[e[0]]:n}async backgroundLoad(e){this._initialized||await this.init(),typeof e=="string"&&(e=[e]);const t=this.resolver.resolve(e);this._backgroundLoader.add(Object.values(t))}async backgroundLoadBundle(e){this._initialized||await this.init(),typeof e=="string"&&(e=[e]);const t=this.resolver.resolveBundle(e);Object.values(t).forEach(s=>{this._backgroundLoader.add(Object.values(s))})}reset(){this.resolver.reset(),this.loader.reset(),this.cache.reset(),this._initialized=!1}get(e){if(typeof e=="string")return ae.get(e);const t={};for(let s=0;s<e.length;s++)t[s]=ae.get(e[s]);return t}async _mapLoadToResolve(e,t){const s=[...new Set(Object.values(e))];this._backgroundLoader.active=!1;const r=await this.loader.load(s,t);this._backgroundLoader.active=!0;const n={};return s.forEach(o=>{const a=r[o.src],l=[o.src];o.alias&&l.push(...o.alias),l.forEach(c=>{n[c]=a}),ae.set(l,a)}),n}async unload(e){this._initialized||await this.init();const t=ut(e).map(r=>typeof r!="string"?r.src:r),s=this.resolver.resolve(t);await this._unloadFromResolved(s)}async unloadBundle(e){this._initialized||await this.init(),e=ut(e);const t=this.resolver.resolveBundle(e),s=Object.keys(t).map(r=>this._unloadFromResolved(t[r]));await Promise.all(s)}async _unloadFromResolved(e){const t=Object.values(e);t.forEach(s=>{ae.remove(s.src)}),await this.loader.unload(t)}async _detectFormats(e){let t=[];e.preferredFormats&&(t=Array.isArray(e.preferredFormats)?e.preferredFormats:[e.preferredFormats]);for(const s of e.detections)e.skipDetections||await s.test()?t=await s.add(t):e.skipDetections||(t=await s.remove(t));return t=t.filter((s,r)=>t.indexOf(s)===r),t}get detections(){return this._detections}setPreferences(e){this.loader.parsers.forEach(t=>{t.config&&Object.keys(t.config).filter(s=>s in e).forEach(s=>{t.config[s]=e[s]})})}}const Ls=new uI;V.handleByList(b.LoadParser,Ls.loader.parsers).handleByList(b.ResolveParser,Ls.resolver.parsers).handleByList(b.CacheParser,Ls.cache.parsers).handleByList(b.DetectionParser,Ls.detections),V.add(SE,AE,CE,ME,IE,PE,RE,UE,GE,XE,KE,d0,cI,TE,bE,f0,hI);const p0={loader:b.LoadParser,resolver:b.ResolveParser,cache:b.CacheParser,detection:b.DetectionParser};V.handle(b.Asset,i=>{const e=i.ref;Object.entries(p0).filter(([t])=>!!e[t]).forEach(([t,s])=>V.add(Object.assign(e[t],{extension:e[t].extension??s})))},i=>{const e=i.ref;Object.keys(p0).filter(t=>!!e[t]).forEach(t=>V.remove(e[t]))});class m0{constructor(e){this._attachedDomElements=[],this._renderer=e,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new Am({domElement:this._domElement,renderer:this._renderer})}addRenderable(e,t){this._attachedDomElements.includes(e)||this._attachedDomElements.push(e)}updateRenderable(e){}validateRenderable(e){return!0}postrender(){const e=this._attachedDomElements;if(e.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let t=0;t<e.length;t++){const s=e[t],r=s.element;if(!s.parent||s.globalDisplayStatus<7)r?.remove(),e.splice(t,1),t--;else{this._domElement.contains(r)||(r.style.position="absolute",r.style.pointerEvents="auto",this._domElement.appendChild(r));const n=s.worldTransform,o=s._anchor,a=s.width*o.x,l=s.height*o.y;r.style.transformOrigin=`${a}px ${l}px`,r.style.transform=`matrix(${n.a}, ${n.b}, ${n.c}, ${n.d}, ${n.tx-a}, ${n.ty-l})`,r.style.opacity=s.groupAlpha.toString()}}}destroy(){this._renderer.runners.postrender.remove(this);for(let e=0;e<this._attachedDomElements.length;e++)this._attachedDomElements[e].element?.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}m0.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"dom"};class dI{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(e){this.removeTickerListener(),this.events=e,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(e){this._pauseUpdate=e}addTickerListener(){this._tickerAdded||!this.domElement||(Ze.system.add(this._tickerUpdate,this,Ui.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(Ze.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const e=this.events._rootPointerEvent;this.events.supportsTouchEvents&&e.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,pointerId:e.pointerId}):new MouseEvent("mousemove",{clientX:e.clientX,clientY:e.clientY}))}_tickerUpdate(e){this._deltaTime+=e.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const zt=new dI;class an extends xs{constructor(){super(...arguments),this.client=new X,this.movement=new X,this.offset=new X,this.global=new X,this.screen=new X}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(e,t,s){return e.worldTransform.applyInverse(s||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,s,r,n,o,a,l,c,h,u,d,f,p,g){throw new Error("Method not implemented.")}}class mt extends an{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Xi extends an{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Xi.DOM_DELTA_PIXEL=0,Xi.DOM_DELTA_LINE=1,Xi.DOM_DELTA_PAGE=2;const fI=2048,pI=new X,Hs=new X;class mI{constructor(e){this.dispatch=new je,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=e,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(e,t){this.mappingTable[e]||(this.mappingTable[e]=[]),this.mappingTable[e].push({fn:t,priority:0}),this.mappingTable[e].sort((s,r)=>s.priority-r.priority)}dispatchEvent(e,t){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,t),this.dispatch.emit(t||e.type,e)}mapEvent(e){if(!this.rootTarget)return;const t=this.mappingTable[e.type];if(t)for(let s=0,r=t.length;s<r;s++)t[s].fn(e);else L(`[EventBoundary]: Event mapping not defined for ${e.type}`)}hitTest(e,t){zt.pauseUpdate=!0;const r=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",n=this[r](this.rootTarget,this.rootTarget.eventMode,pI.set(e,t),this.hitTestFn,this.hitPruneFn);return n&&n[0]}propagate(e,t){if(!e.target)return;const s=e.composedPath();e.eventPhase=e.CAPTURING_PHASE;for(let r=0,n=s.length-1;r<n;r++)if(e.currentTarget=s[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return;if(e.eventPhase=e.AT_TARGET,e.currentTarget=e.target,this.notifyTarget(e,t),!(e.propagationStopped||e.propagationImmediatelyStopped)){e.eventPhase=e.BUBBLING_PHASE;for(let r=s.length-2;r>=0;r--)if(e.currentTarget=s[r],this.notifyTarget(e,t),e.propagationStopped||e.propagationImmediatelyStopped)return}}all(e,t,s=this._allInteractiveElements){if(s.length===0)return;e.eventPhase=e.BUBBLING_PHASE;const r=Array.isArray(t)?t:[t];for(let n=s.length-1;n>=0;n--)r.forEach(o=>{e.currentTarget=s[n],this.notifyTarget(e,o)})}propagationPath(e){const t=[e];for(let s=0;s<fI&&e!==this.rootTarget&&e.parent;s++){if(!e.parent)throw new Error("Cannot find propagation path to disconnected target");t.push(e.parent),e=e.parent}return t.reverse(),t}hitTestMoveRecursive(e,t,s,r,n,o=!1){let a=!1;if(this._interactivePrune(e))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(zt.pauseUpdate=!1),e.interactiveChildren&&e.children){const h=e.children;for(let u=h.length-1;u>=0;u--){const d=h[u],f=this.hitTestMoveRecursive(d,this._isInteractive(t)?t:d.eventMode,s,r,n,o||n(e,s));if(f){if(f.length>0&&!f[f.length-1].parent)continue;const p=e.isInteractive();(f.length>0||p)&&(p&&this._allInteractiveElements.push(e),f.push(e)),this._hitElements.length===0&&(this._hitElements=f),a=!0}}}const l=this._isInteractive(t),c=e.isInteractive();return c&&c&&this._allInteractiveElements.push(e),o||this._hitElements.length>0?null:a?this._hitElements:l&&!n(e,s)&&r(e,s)?c?[e]:[]:null}hitTestRecursive(e,t,s,r,n){if(this._interactivePrune(e)||n(e,s))return null;if((e.eventMode==="dynamic"||t==="dynamic")&&(zt.pauseUpdate=!1),e.interactiveChildren&&e.children){const l=e.children,c=s;for(let h=l.length-1;h>=0;h--){const u=l[h],d=this.hitTestRecursive(u,this._isInteractive(t)?t:u.eventMode,c,r,n);if(d){if(d.length>0&&!d[d.length-1].parent)continue;const f=e.isInteractive();return(d.length>0||f)&&d.push(e),d}}}const o=this._isInteractive(t),a=e.isInteractive();return o&&r(e,s)?a?[e]:[]:null}_isInteractive(e){return e==="static"||e==="dynamic"}_interactivePrune(e){return!e||!e.visible||!e.renderable||!e.measurable||e.eventMode==="none"||e.eventMode==="passive"&&!e.interactiveChildren}hitPruneFn(e,t){if(e.hitArea&&(e.worldTransform.applyInverse(t,Hs),!e.hitArea.contains(Hs.x,Hs.y)))return!0;if(e.effects&&e.effects.length)for(let s=0;s<e.effects.length;s++){const r=e.effects[s];if(r.containsPoint&&!r.containsPoint(t,this.hitTestFn))return!0}return!1}hitTestFn(e,t){return e.hitArea?!0:e?.containsPoint?(e.worldTransform.applyInverse(t,Hs),e.containsPoint(Hs)):!1}notifyTarget(e,t){if(!e.currentTarget.isInteractive())return;t??(t=e.type);const s=`on${t}`;e.currentTarget[s]?.(e);const r=e.eventPhase===e.CAPTURING_PHASE||e.eventPhase===e.AT_TARGET?`${t}capture`:t;this._notifyListeners(e,r),e.eventPhase===e.AT_TARGET&&this._notifyListeners(e,t)}mapPointerDown(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.createPointerEvent(e);if(this.dispatchEvent(t,"pointerdown"),t.pointerType==="touch")this.dispatchEvent(t,"touchstart");else if(t.pointerType==="mouse"||t.pointerType==="pen"){const r=t.button===2;this.dispatchEvent(t,r?"rightdown":"mousedown")}const s=this.trackingData(e.pointerId);s.pressTargetsByButton[e.button]=t.composedPath(),this.freeEvent(t)}mapPointerMove(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const t=this.createPointerEvent(e);this._isPointerMoveEvent=!1;const s=t.pointerType==="mouse"||t.pointerType==="pen",r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.overTargets);if(r.overTargets?.length>0&&n!==t.target){const l=e.type==="mousemove"?"mouseout":"pointerout",c=this.createPointerEvent(e,l,n);if(this.dispatchEvent(c,"pointerout"),s&&this.dispatchEvent(c,"mouseout"),!t.composedPath().includes(n)){const h=this.createPointerEvent(e,"pointerleave",n);for(h.eventPhase=h.AT_TARGET;h.target&&!t.composedPath().includes(h.target);)h.currentTarget=h.target,this.notifyTarget(h),s&&this.notifyTarget(h,"mouseleave"),h.target=h.target.parent;this.freeEvent(h)}this.freeEvent(c)}if(n!==t.target){const l=e.type==="mousemove"?"mouseover":"pointerover",c=this.clonePointerEvent(t,l);this.dispatchEvent(c,"pointerover"),s&&this.dispatchEvent(c,"mouseover");let h=n?.parent;for(;h&&h!==this.rootTarget.parent&&h!==t.target;)h=h.parent;if(!h||h===this.rootTarget.parent){const d=this.clonePointerEvent(t,"pointerenter");for(d.eventPhase=d.AT_TARGET;d.target&&d.target!==n&&d.target!==this.rootTarget.parent;)d.currentTarget=d.target,this.notifyTarget(d),s&&this.notifyTarget(d,"mouseenter"),d.target=d.target.parent;this.freeEvent(d)}this.freeEvent(c)}const o=[],a=this.enableGlobalMoveEvents??!0;this.moveOnAll?o.push("pointermove"):this.dispatchEvent(t,"pointermove"),a&&o.push("globalpointermove"),t.pointerType==="touch"&&(this.moveOnAll?o.splice(1,0,"touchmove"):this.dispatchEvent(t,"touchmove"),a&&o.push("globaltouchmove")),s&&(this.moveOnAll?o.splice(1,0,"mousemove"):this.dispatchEvent(t,"mousemove"),a&&o.push("globalmousemove"),this.cursor=t.target?.cursor),o.length>0&&this.all(t,o),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=t.composedPath(),this.freeEvent(t)}mapPointerOver(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.createPointerEvent(e),r=s.pointerType==="mouse"||s.pointerType==="pen";this.dispatchEvent(s,"pointerover"),r&&this.dispatchEvent(s,"mouseover"),s.pointerType==="mouse"&&(this.cursor=s.target?.cursor);const n=this.clonePointerEvent(s,"pointerenter");for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),r&&this.notifyTarget(n,"mouseenter"),n.target=n.target.parent;t.overTargets=s.composedPath(),this.freeEvent(s),this.freeEvent(n)}mapPointerOut(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId);if(t.overTargets){const s=e.pointerType==="mouse"||e.pointerType==="pen",r=this.findMountedTarget(t.overTargets),n=this.createPointerEvent(e,"pointerout",r);this.dispatchEvent(n),s&&this.dispatchEvent(n,"mouseout");const o=this.createPointerEvent(e,"pointerleave",r);for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),s&&this.notifyTarget(o,"mouseleave"),o.target=o.target.parent;t.overTargets=null,this.freeEvent(n),this.freeEvent(o)}this.cursor=null}mapPointerUp(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=performance.now(),s=this.createPointerEvent(e);if(this.dispatchEvent(s,"pointerup"),s.pointerType==="touch")this.dispatchEvent(s,"touchend");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const a=s.button===2;this.dispatchEvent(s,a?"rightup":"mouseup")}const r=this.trackingData(e.pointerId),n=this.findMountedTarget(r.pressTargetsByButton[e.button]);let o=n;if(n&&!s.composedPath().includes(n)){let a=n;for(;a&&!s.composedPath().includes(a);){if(s.currentTarget=a,this.notifyTarget(s,"pointerupoutside"),s.pointerType==="touch")this.notifyTarget(s,"touchendoutside");else if(s.pointerType==="mouse"||s.pointerType==="pen"){const l=s.button===2;this.notifyTarget(s,l?"rightupoutside":"mouseupoutside")}a=a.parent}delete r.pressTargetsByButton[e.button],o=a}if(o){const a=this.clonePointerEvent(s,"click");a.target=o,a.path=null,r.clicksByButton[e.button]||(r.clicksByButton[e.button]={clickCount:0,target:a.target,timeStamp:t});const l=r.clicksByButton[e.button];if(l.target===a.target&&t-l.timeStamp<200?++l.clickCount:l.clickCount=1,l.target=a.target,l.timeStamp=t,a.detail=l.clickCount,a.pointerType==="mouse"){const c=a.button===2;this.dispatchEvent(a,c?"rightclick":"click")}else a.pointerType==="touch"&&this.dispatchEvent(a,"tap");this.dispatchEvent(a,"pointertap"),this.freeEvent(a)}this.freeEvent(s)}mapPointerUpOutside(e){if(!(e instanceof mt)){L("EventBoundary cannot map a non-pointer event as a pointer event");return}const t=this.trackingData(e.pointerId),s=this.findMountedTarget(t.pressTargetsByButton[e.button]),r=this.createPointerEvent(e);if(s){let n=s;for(;n;)r.currentTarget=n,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch"?this.notifyTarget(r,"touchendoutside"):(r.pointerType==="mouse"||r.pointerType==="pen")&&this.notifyTarget(r,r.button===2?"rightupoutside":"mouseupoutside"),n=n.parent;delete t.pressTargetsByButton[e.button]}this.freeEvent(r)}mapWheel(e){if(!(e instanceof Xi)){L("EventBoundary cannot map a non-wheel event as a wheel event");return}const t=this.createWheelEvent(e);this.dispatchEvent(t),this.freeEvent(t)}findMountedTarget(e){if(!e)return null;let t=e[0];for(let s=1;s<e.length&&e[s].parent===t;s++)t=e[s];return t}createPointerEvent(e,t,s){const r=this.allocateEvent(mt);return this.copyPointerData(e,r),this.copyMouseData(e,r),this.copyData(e,r),r.nativeEvent=e.nativeEvent,r.originalEvent=e,r.target=s??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],typeof t=="string"&&(r.type=t),r}createWheelEvent(e){const t=this.allocateEvent(Xi);return this.copyWheelData(e,t),this.copyMouseData(e,t),this.copyData(e,t),t.nativeEvent=e.nativeEvent,t.originalEvent=e,t.target=this.hitTest(t.global.x,t.global.y),t}clonePointerEvent(e,t){const s=this.allocateEvent(mt);return s.nativeEvent=e.nativeEvent,s.originalEvent=e.originalEvent,this.copyPointerData(e,s),this.copyMouseData(e,s),this.copyData(e,s),s.target=e.target,s.path=e.composedPath().slice(),s.type=t??s.type,s}copyWheelData(e,t){t.deltaMode=e.deltaMode,t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ}copyPointerData(e,t){e instanceof mt&&t instanceof mt&&(t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist)}copyMouseData(e,t){e instanceof an&&t instanceof an&&(t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.copyFrom(e.client),t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.copyFrom(e.movement),t.screen.copyFrom(e.screen),t.shiftKey=e.shiftKey,t.global.copyFrom(e.global))}copyData(e,t){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.detail=e.detail,t.view=e.view,t.which=e.which,t.layer.copyFrom(e.layer),t.page.copyFrom(e.page)}trackingData(e){return this.mappingState.trackingData[e]||(this.mappingState.trackingData[e]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[e]}allocateEvent(e){this.eventPool.has(e)||this.eventPool.set(e,[]);const t=this.eventPool.get(e).pop()||new e(this);return t.eventPhase=t.NONE,t.currentTarget=null,t.defaultPrevented=!1,t.path=null,t.target=null,t}freeEvent(e){if(e.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const t=e.constructor;this.eventPool.has(t)||this.eventPool.set(t,[]),this.eventPool.get(t).push(e)}_notifyListeners(e,t){const s=e.currentTarget._events[t];if(s)if("fn"in s)s.once&&e.currentTarget.removeListener(t,s.fn,void 0,!0),s.fn.call(s.context,e);else for(let r=0,n=s.length;r<n&&!e.propagationImmediatelyStopped;r++)s[r].once&&e.currentTarget.removeListener(t,s[r].fn,void 0,!0),s[r].fn.call(s[r].context,e)}}const gI=1,xI={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},bd=class uf{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new mI(null),zt.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new mt(null),this._rootWheelEvent=new Xi(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...uf.defaultEventFeatures},{set:(t,s,r)=>(s==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=r),t[s]=r,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{canvas:t,resolution:s}=this.renderer;this.setTargetElement(t),this.resolution=s,uf._defaultEventMode=e.eventMode??"passive",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(e){this.resolution=e}destroy(){zt.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(e){e||(e="default");let t=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(t=!1),this._currentCursor===e)return;this._currentCursor=e;const s=this.cursorStyles[e];if(s)switch(typeof s){case"string":t&&(this.domElement.style.cursor=s);break;case"function":s(e);break;case"object":t&&Object.assign(this.domElement.style,s);break}else t&&typeof e=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,e)&&(this.domElement.style.cursor=e)}get pointer(){return this._rootPointerEvent}_onPointerDown(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);this.autoPreventDefault&&t[0].isNormalized&&(e.cancelable||!("cancelable"in e))&&e.preventDefault();for(let s=0,r=t.length;s<r;s++){const n=t[s],o=this._bootstrapEvent(this._rootPointerEvent,n);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(e){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,zt.pointerMoved();const t=this._normalizeToPointerData(e);for(let s=0,r=t.length;s<r;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let t=e.target;e.composedPath&&e.composedPath().length>0&&(t=e.composedPath()[0]);const s=t!==this.domElement?"outside":"",r=this._normalizeToPointerData(e);for(let n=0,o=r.length;n<o;n++){const a=this._bootstrapEvent(this._rootPointerEvent,r[n]);a.type+=s,this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(e){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const t=this._normalizeToPointerData(e);for(let s=0,r=t.length;s<r;s++){const n=this._bootstrapEvent(this._rootPointerEvent,t[s]);this.rootBoundary.mapEvent(n)}this.setCursor(this.rootBoundary.cursor)}onWheel(e){if(!this.features.wheel)return;const t=this.normalizeWheelEvent(e);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(t)}setTargetElement(e){this._removeEvents(),this.domElement=e,zt.domElement=e,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;zt.addTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="none",e.msTouchAction="none"):this.supportsPointerEvents&&(e.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;zt.removeTickerListener();const e=this.domElement.style;e&&(globalThis.navigator.msPointerEnabled?(e.msContentZooming="",e.msTouchAction=""):this.supportsPointerEvents&&(e.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(e,t,s){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},n=1/this.resolution;e.x=(t-r.left)*(this.domElement.width/r.width)*n,e.y=(s-r.top)*(this.domElement.height/r.height)*n}_normalizeToPointerData(e){const t=[];if(this.supportsTouchEvents&&e instanceof TouchEvent)for(let s=0,r=e.changedTouches.length;s<r;s++){const n=e.changedTouches[s];typeof n.button>"u"&&(n.button=0),typeof n.buttons>"u"&&(n.buttons=1),typeof n.isPrimary>"u"&&(n.isPrimary=e.touches.length===1&&e.type==="touchstart"),typeof n.width>"u"&&(n.width=n.radiusX||1),typeof n.height>"u"&&(n.height=n.radiusY||1),typeof n.tiltX>"u"&&(n.tiltX=0),typeof n.tiltY>"u"&&(n.tiltY=0),typeof n.pointerType>"u"&&(n.pointerType="touch"),typeof n.pointerId>"u"&&(n.pointerId=n.identifier||0),typeof n.pressure>"u"&&(n.pressure=n.force||.5),typeof n.twist>"u"&&(n.twist=0),typeof n.tangentialPressure>"u"&&(n.tangentialPressure=0),typeof n.layerX>"u"&&(n.layerX=n.offsetX=n.clientX),typeof n.layerY>"u"&&(n.layerY=n.offsetY=n.clientY),n.isNormalized=!0,n.type=e.type,t.push(n)}else if(!globalThis.MouseEvent||e instanceof MouseEvent&&(!this.supportsPointerEvents||!(e instanceof globalThis.PointerEvent))){const s=e;typeof s.isPrimary>"u"&&(s.isPrimary=!0),typeof s.width>"u"&&(s.width=1),typeof s.height>"u"&&(s.height=1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="mouse"),typeof s.pointerId>"u"&&(s.pointerId=gI),typeof s.pressure>"u"&&(s.pressure=.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),s.isNormalized=!0,t.push(s)}else t.push(e);return t}normalizeWheelEvent(e){const t=this._rootWheelEvent;return this._transferMouseData(t,e),t.deltaX=e.deltaX,t.deltaY=e.deltaY,t.deltaZ=e.deltaZ,t.deltaMode=e.deltaMode,this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.nativeEvent=e,t.type=e.type,t}_bootstrapEvent(e,t){return e.originalEvent=null,e.nativeEvent=t,e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist,this._transferMouseData(e,t),this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.isTrusted=t.isTrusted,e.type==="pointerleave"&&(e.type="pointerout"),e.type.startsWith("mouse")&&(e.type=e.type.replace("mouse","pointer")),e.type.startsWith("touch")&&(e.type=xI[e.type]||e.type),e}_transferMouseData(e,t){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.x=t.clientX,e.client.y=t.clientY,e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.x=t.movementX,e.movement.y=t.movementY,e.page.x=t.pageX,e.page.y=t.pageY,e.relatedTarget=null,e.shiftKey=t.shiftKey}};bd.extension={name:"events",type:[b.WebGLSystem,b.CanvasSystem,b.WebGPUSystem],priority:-1},bd.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let g0=bd;const _I={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(i){this.eventMode=i?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??g0.defaultEventMode},set eventMode(i){this._internalEventMode=i},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(i,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof t=="object"?t.signal:void 0,n=typeof t=="object"?t.once===!0:!1,o=typeof e=="function"?void 0:e;i=s?`${i}capture`:i;const a=typeof e=="function"?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(i,a,o)}),n?l.once(i,a,o):l.on(i,a,o)},removeEventListener(i,e,t){const s=typeof t=="boolean"&&t||typeof t=="object"&&t.capture,r=typeof e=="function"?void 0:e;i=s?`${i}capture`:i,e=typeof e=="function"?e:e.handleEvent,this.off(i,e,r)},dispatchEvent(i){if(!(i instanceof xs))throw new Error("Container cannot propagate events outside of the Federated Events API");return i.defaultPrevented=!1,i.path=null,i.target=this,i.manager.dispatchEvent(i),!i.defaultPrevented}};var yI=`in vec2 aPosition;
|
|
374
374
|
out vec2 vTextureCoord;
|
|
375
375
|
|
|
376
376
|
uniform vec4 uInputSize;
|
|
@@ -397,8 +397,8 @@ void main(void)
|
|
|
397
397
|
gl_Position = filterVertexPosition();
|
|
398
398
|
vTextureCoord = filterTextureCoord();
|
|
399
399
|
}
|
|
400
|
-
`;const
|
|
401
|
-
`);function bI(i){const e=
|
|
400
|
+
`;const x0={5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]},vI=["in vec2 vBlurTexCoords[%size%];","uniform sampler2D uTexture;","out vec4 finalColor;","void main(void)","{"," finalColor = vec4(0.0);"," %blur%","}"].join(`
|
|
401
|
+
`);function bI(i){const e=x0[i],t=e.length;let s=vI,r="";const n="finalColor += texture(uTexture, vBlurTexCoords[%index%]) * %value%;";let o;for(let a=0;a<i;a++){let l=n.replace("%index%",a.toString());o=a,a>=t&&(o=i-a-1),l=l.replace("%value%",e[o].toString()),r+=l,r+=`
|
|
402
402
|
`}return s=s.replace("%blur%",r),s=s.replace("%size%",i.toString()),s}const TI=`
|
|
403
403
|
in vec2 aPosition;
|
|
404
404
|
|
|
@@ -513,10 +513,10 @@ fn mainFragment(
|
|
|
513
513
|
%blur-sampling%
|
|
514
514
|
|
|
515
515
|
return finalColor;
|
|
516
|
-
}`;function AI(i,e){const t=
|
|
516
|
+
}`;function AI(i,e){const t=x0[e],s=t.length,r=[],n=[],o=[];for(let u=0;u<e;u++){r[u]=`@location(${u}) offset${u}: vec2<f32>,`,i?n[u]=`filteredCord + vec2(${u-s+1} * pixelStrength, 0.0),`:n[u]=`filteredCord + vec2(0.0, ${u-s+1} * pixelStrength),`;const d=u<s?u:e-u-1,f=t[d].toString();o[u]=`finalColor += textureSample(uTexture, uSampler, offset${u}) * ${f};`}const a=r.join(`
|
|
517
517
|
`),l=n.join(`
|
|
518
518
|
`),c=o.join(`
|
|
519
|
-
`),h=CI.replace("%blur-struct%",a).replace("%blur-vertex-out%",l).replace("%blur-fragment-in%",a).replace("%blur-sampling%",c).replace("%dimension%",i?"z":"w");return Ut.from({vertex:{source:h,entryPoint:"mainVertex"},fragment:{source:h,entryPoint:"mainFragment"}})}const
|
|
519
|
+
`),h=CI.replace("%blur-struct%",a).replace("%blur-vertex-out%",l).replace("%blur-fragment-in%",a).replace("%blur-sampling%",c).replace("%dimension%",i?"z":"w");return Ut.from({vertex:{source:h,entryPoint:"mainVertex"},fragment:{source:h,entryPoint:"mainFragment"}})}const _0=class ny extends Gi{constructor(e){e={...ny.defaultOptions,...e};const t=SI(e.horizontal,e.kernelSize),s=AI(e.horizontal,e.kernelSize);super({glProgram:t,gpuProgram:s,resources:{blurUniforms:{uStrength:{value:0,type:"f32"}}},...e}),this.horizontal=e.horizontal,this._quality=0,this.quality=e.quality,this.blur=e.strength,this._uniforms=this.resources.blurUniforms.uniforms}apply(e,t,s,r){if(this._uniforms.uStrength=this.strength/this.passes,this.passes===1)e.applyFilter(this,t,s,r);else{const n=ve.getSameSizeTexture(t);let o=t,a=n;this._state.blend=!1;const l=e.renderer.type===Qe.WEBGPU;for(let c=0;c<this.passes-1;c++){e.applyFilter(this,o,a,c===0?!0:l);const h=a;a=o,o=h}this._state.blend=!0,e.applyFilter(this,o,s,r),ve.returnTexture(n)}}get blur(){return this.strength}set blur(e){this.padding=1+Math.abs(e)*2,this.strength=e}get quality(){return this._quality}set quality(e){this._quality=e,this.passes=e}};_0.defaultOptions={strength:8,quality:4,kernelSize:5};let Td=_0;class y0 extends Gi{constructor(...e){let t=e[0]??{};typeof t=="number"&&(W(Q,"BlurFilter constructor params are now options object. See params: { strength, quality, resolution, kernelSize }"),t={strength:t},e[1]!==void 0&&(t.quality=e[1]),e[2]!==void 0&&(t.resolution=e[2]||"inherit"),e[3]!==void 0&&(t.kernelSize=e[3])),t={...Td.defaultOptions,...t};const{strength:s,strengthX:r,strengthY:n,quality:o,...a}=t;super({...a,compatibleRenderers:Qe.BOTH,resources:{}}),this._repeatEdgePixels=!1,this.blurXFilter=new Td({horizontal:!0,...t}),this.blurYFilter=new Td({horizontal:!1,...t}),this.quality=o,this.strengthX=r??s,this.strengthY=n??s,this.repeatEdgePixels=!1}apply(e,t,s,r){const n=Math.abs(this.blurXFilter.strength),o=Math.abs(this.blurYFilter.strength);if(n&&o){const a=ve.getSameSizeTexture(t);this.blurXFilter.blendMode="normal",this.blurXFilter.apply(e,t,a,!0),this.blurYFilter.blendMode=this.blendMode,this.blurYFilter.apply(e,a,s,r),ve.returnTexture(a)}else o?(this.blurYFilter.blendMode=this.blendMode,this.blurYFilter.apply(e,t,s,r)):(this.blurXFilter.blendMode=this.blendMode,this.blurXFilter.apply(e,t,s,r))}updatePadding(){this._repeatEdgePixels?this.padding=0:this.padding=Math.max(Math.abs(this.blurXFilter.blur),Math.abs(this.blurYFilter.blur))*2}get strength(){if(this.strengthX!==this.strengthY)throw new Error("BlurFilter's strengthX and strengthY are different");return this.strengthX}set strength(e){this.blurXFilter.blur=this.blurYFilter.blur=e,this.updatePadding()}get quality(){return this.blurXFilter.quality}set quality(e){this.blurXFilter.quality=this.blurYFilter.quality=e}get strengthX(){return this.blurXFilter.blur}set strengthX(e){this.blurXFilter.blur=e,this.updatePadding()}get strengthY(){return this.blurYFilter.blur}set strengthY(e){this.blurYFilter.blur=e,this.updatePadding()}get blur(){return W("8.3.0","BlurFilter.blur is deprecated, please use BlurFilter.strength instead."),this.strength}set blur(e){W("8.3.0","BlurFilter.blur is deprecated, please use BlurFilter.strength instead."),this.strength=e}get blurX(){return W("8.3.0","BlurFilter.blurX is deprecated, please use BlurFilter.strengthX instead."),this.strengthX}set blurX(e){W("8.3.0","BlurFilter.blurX is deprecated, please use BlurFilter.strengthX instead."),this.strengthX=e}get blurY(){return W("8.3.0","BlurFilter.blurY is deprecated, please use BlurFilter.strengthY instead."),this.strengthY}set blurY(e){W("8.3.0","BlurFilter.blurY is deprecated, please use BlurFilter.strengthY instead."),this.strengthY=e}get repeatEdgePixels(){return this._repeatEdgePixels}set repeatEdgePixels(e){this._repeatEdgePixels=e,this.updatePadding()}}y0.defaultOptions={strength:8,quality:4,kernelSize:5};var EI=`in vec2 vTextureCoord;
|
|
520
520
|
out vec4 finalColor;
|
|
521
521
|
uniform sampler2D uTexture;
|
|
522
522
|
void main() {
|
|
@@ -571,7 +571,7 @@ fn mainFragment(
|
|
|
571
571
|
) -> @location(0) vec4<f32> {
|
|
572
572
|
return textureSample(uTexture, uSampler, uv);
|
|
573
573
|
}
|
|
574
|
-
`;class II extends Gi{constructor(){const e=Ut.from({vertex:{source:v0,entryPoint:"mainVertex"},fragment:{source:v0,entryPoint:"mainFragment"},name:"passthrough-filter"}),t=At.from({vertex:yI,fragment:EI,name:"passthrough-filter"});super({gpuProgram:e,glProgram:t})}}class b0{constructor(e){this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(e){e.action==="pushFilter"?this._renderer.filter.push(e):e.action==="popFilter"&&this._renderer.filter.pop()}destroy(){this._renderer=null}}b0.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"filter"};const T0=new O;function PI(i,e){e.clear();const t=e.matrix;for(let s=0;s<i.length;s++){const r=i[s];if(r.globalDisplayStatus<7)continue;const n=r.renderGroup??r.parentRenderGroup;n?.isCachedAsTexture?e.matrix=T0.copyFrom(n.textureOffsetInverseTransform).append(r.worldTransform):n?._parentCacheAsTextureRenderGroup?e.matrix=T0.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(r.groupTransform):e.matrix=r.worldTransform,e.addBounds(r.bounds)}return e.matrix=t,e}const RI=new Ms({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),format:"float32x2",stride:8,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])});class MI{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new De,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.globalFrame={x:0,y:0,width:0,height:0},this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class w0{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new He({uInputSize:{value:new Float32Array(4),type:"vec4<f32>"},uInputPixel:{value:new Float32Array(4),type:"vec4<f32>"},uInputClamp:{value:new Float32Array(4),type:"vec4<f32>"},uOutputFrame:{value:new Float32Array(4),type:"vec4<f32>"},uGlobalFrame:{value:new Float32Array(4),type:"vec4<f32>"},uOutputTexture:{value:new Float32Array(4),type:"vec4<f32>"}}),this._globalFilterBindGroup=new Ot({}),this.renderer=e}get activeBackTexture(){return this._activeFilterData?.backTexture}push(e){const t=this.renderer,s=e.filterEffect.filters,r=this._pushFilterData();r.skip=!1,r.filters=s,r.container=e.container,r.outputRenderSurface=t.renderTarget.renderSurface;const n=t.renderTarget.renderTarget.colorTexture.source,o=n.resolution,a=n.antialias;if(s.every(f=>!f.enabled)){r.skip=!0;return}const l=r.bounds;if(this._calculateFilterArea(e,l),this._calculateFilterBounds(r,t.renderTarget.rootViewPort,a,o,1),r.skip)return;const c=this._getPreviousFilterData(),h=this._findFilterResolution(o);let u=0,d=0;c&&(u=c.bounds.minX,d=c.bounds.minY),this._calculateGlobalFrame(r,u,d,h,n.width,n.height),this._setupFilterTextures(r,l,t,c)}generateFilteredTexture({texture:e,filters:t}){const s=this._pushFilterData();this._activeFilterData=s,s.skip=!1,s.filters=t;const r=e.source,n=r.resolution,o=r.antialias;if(t.every(f=>!f.enabled))return s.skip=!0,e;const a=s.bounds;if(a.addRect(e.frame),this._calculateFilterBounds(s,a.rectangle,o,n,0),s.skip)return e;const l=n;this._calculateGlobalFrame(s,0,0,l,r.width,r.height),s.outputRenderSurface=ve.getOptimalTexture(a.width,a.height,s.resolution,s.antialias),s.backTexture=M.EMPTY,s.inputTexture=e,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(s,!0);const d=s.outputRenderSurface;return d.source.alphaMode="premultiplied-alpha",d}pop(){const e=this.renderer,t=this._popFilterData();t.skip||(e.globalUniforms.pop(),e.renderTarget.finishRenderPass(),this._activeFilterData=t,this._applyFiltersToTexture(t,!1),t.blendRequired&&ve.returnTexture(t.backTexture),ve.returnTexture(t.inputTexture))}getBackTexture(e,t,s){const r=e.colorTexture.source._resolution,n=ve.getOptimalTexture(t.width,t.height,r,!1);let o=t.minX,a=t.minY;s&&(o-=s.minX,a-=s.minY),o=Math.floor(o*r),a=Math.floor(a*r);const l=Math.ceil(t.width*r),c=Math.ceil(t.height*r);return this.renderer.renderTarget.copyToTexture(e,n,{x:o,y:a},{width:l,height:c},{x:0,y:0}),n}applyFilter(e,t,s,r){const n=this.renderer,o=this._activeFilterData,l=o.outputRenderSurface===s,c=n.renderTarget.rootRenderTarget.colorTexture.source._resolution,h=this._findFilterResolution(c);let u=0,d=0;if(l){const p=this._findPreviousFilterOffset();u=p.x,d=p.y}this._updateFilterUniforms(t,s,o,u,d,h,l,r);const f=e.enabled?e:this._getPassthroughFilter();this._setupBindGroupsAndRender(f,t,n)}calculateSpriteMatrix(e,t){const s=this._activeFilterData,r=e.set(s.inputTexture._source.width,0,0,s.inputTexture._source.height,s.bounds.minX,s.bounds.minY),n=t.worldTransform.copyTo(O.shared),o=t.renderGroup||t.parentRenderGroup;return o&&o.cacheToLocalTransform&&n.prepend(o.cacheToLocalTransform),n.invert(),r.prepend(n),r.scale(1/t.texture.orig.width,1/t.texture.orig.height),r.translate(t.anchor.x,t.anchor.y),r}destroy(){this._passthroughFilter?.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new II),this._passthroughFilter}_setupBindGroupsAndRender(e,t,s){if(s.renderPipes.uniformBatch){const r=s.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(r,0)}else this._globalFilterBindGroup.setResource(this._filterGlobalUniforms,0);this._globalFilterBindGroup.setResource(t.source,1),this._globalFilterBindGroup.setResource(t.source.style,2),e.groups[0]=this._globalFilterBindGroup,s.encoder.draw({geometry:RI,shader:e,state:e._state,topology:"triangle-list"}),s.type===Qe.WEBGL&&s.renderTarget.finishRenderPass()}_setupFilterTextures(e,t,s,r){if(e.backTexture=M.EMPTY,e.inputTexture=ve.getOptimalTexture(t.width,t.height,e.resolution,e.antialias),e.blendRequired){s.renderTarget.finishRenderPass();const n=s.renderTarget.getRenderTarget(e.outputRenderSurface);e.backTexture=this.getBackTexture(n,t,r?.bounds)}s.renderTarget.bind(e.inputTexture,!0),s.globalUniforms.push({offset:t})}_calculateGlobalFrame(e,t,s,r,n,o){const a=e.globalFrame;a.x=t*r,a.y=s*r,a.width=n*r,a.height=o*r}_updateFilterUniforms(e,t,s,r,n,o,a,l){const c=this._filterGlobalUniforms.uniforms,h=c.uOutputFrame,u=c.uInputSize,d=c.uInputPixel,f=c.uInputClamp,p=c.uGlobalFrame,g=c.uOutputTexture;a?(h[0]=s.bounds.minX-r,h[1]=s.bounds.minY-n):(h[0]=0,h[1]=0),h[2]=e.frame.width,h[3]=e.frame.height,u[0]=e.source.width,u[1]=e.source.height,u[2]=1/u[0],u[3]=1/u[1],d[0]=e.source.pixelWidth,d[1]=e.source.pixelHeight,d[2]=1/d[0],d[3]=1/d[1],f[0]=.5*d[2],f[1]=.5*d[3],f[2]=e.frame.width*u[2]-.5*d[2],f[3]=e.frame.height*u[3]-.5*d[3];const m=this.renderer.renderTarget.rootRenderTarget.colorTexture;p[0]=r*o,p[1]=n*o,p[2]=m.source.width*o,p[3]=m.source.height*o,t instanceof M&&(t.source.resource=null);const
|
|
574
|
+
`;class II extends Gi{constructor(){const e=Ut.from({vertex:{source:v0,entryPoint:"mainVertex"},fragment:{source:v0,entryPoint:"mainFragment"},name:"passthrough-filter"}),t=At.from({vertex:yI,fragment:EI,name:"passthrough-filter"});super({gpuProgram:e,glProgram:t})}}class b0{constructor(e){this._renderer=e}push(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:t,filterEffect:e})}pop(e,t,s){this._renderer.renderPipes.batch.break(s),s.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(e){e.action==="pushFilter"?this._renderer.filter.push(e):e.action==="popFilter"&&this._renderer.filter.pop()}destroy(){this._renderer=null}}b0.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"filter"};const T0=new O;function PI(i,e){e.clear();const t=e.matrix;for(let s=0;s<i.length;s++){const r=i[s];if(r.globalDisplayStatus<7)continue;const n=r.renderGroup??r.parentRenderGroup;n?.isCachedAsTexture?e.matrix=T0.copyFrom(n.textureOffsetInverseTransform).append(r.worldTransform):n?._parentCacheAsTextureRenderGroup?e.matrix=T0.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(r.groupTransform):e.matrix=r.worldTransform,e.addBounds(r.bounds)}return e.matrix=t,e}const RI=new Ms({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),format:"float32x2",stride:8,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])});class MI{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new De,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.globalFrame={x:0,y:0,width:0,height:0},this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class w0{constructor(e){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new He({uInputSize:{value:new Float32Array(4),type:"vec4<f32>"},uInputPixel:{value:new Float32Array(4),type:"vec4<f32>"},uInputClamp:{value:new Float32Array(4),type:"vec4<f32>"},uOutputFrame:{value:new Float32Array(4),type:"vec4<f32>"},uGlobalFrame:{value:new Float32Array(4),type:"vec4<f32>"},uOutputTexture:{value:new Float32Array(4),type:"vec4<f32>"}}),this._globalFilterBindGroup=new Ot({}),this.renderer=e}get activeBackTexture(){return this._activeFilterData?.backTexture}push(e){const t=this.renderer,s=e.filterEffect.filters,r=this._pushFilterData();r.skip=!1,r.filters=s,r.container=e.container,r.outputRenderSurface=t.renderTarget.renderSurface;const n=t.renderTarget.renderTarget.colorTexture.source,o=n.resolution,a=n.antialias;if(s.every(f=>!f.enabled)){r.skip=!0;return}const l=r.bounds;if(this._calculateFilterArea(e,l),this._calculateFilterBounds(r,t.renderTarget.rootViewPort,a,o,1),r.skip)return;const c=this._getPreviousFilterData(),h=this._findFilterResolution(o);let u=0,d=0;c&&(u=c.bounds.minX,d=c.bounds.minY),this._calculateGlobalFrame(r,u,d,h,n.width,n.height),this._setupFilterTextures(r,l,t,c)}generateFilteredTexture({texture:e,filters:t}){const s=this._pushFilterData();this._activeFilterData=s,s.skip=!1,s.filters=t;const r=e.source,n=r.resolution,o=r.antialias;if(t.every(f=>!f.enabled))return s.skip=!0,e;const a=s.bounds;if(a.addRect(e.frame),this._calculateFilterBounds(s,a.rectangle,o,n,0),s.skip)return e;const l=n;this._calculateGlobalFrame(s,0,0,l,r.width,r.height),s.outputRenderSurface=ve.getOptimalTexture(a.width,a.height,s.resolution,s.antialias),s.backTexture=M.EMPTY,s.inputTexture=e,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(s,!0);const d=s.outputRenderSurface;return d.source.alphaMode="premultiplied-alpha",d}pop(){const e=this.renderer,t=this._popFilterData();t.skip||(e.globalUniforms.pop(),e.renderTarget.finishRenderPass(),this._activeFilterData=t,this._applyFiltersToTexture(t,!1),t.blendRequired&&ve.returnTexture(t.backTexture),ve.returnTexture(t.inputTexture))}getBackTexture(e,t,s){const r=e.colorTexture.source._resolution,n=ve.getOptimalTexture(t.width,t.height,r,!1);let o=t.minX,a=t.minY;s&&(o-=s.minX,a-=s.minY),o=Math.floor(o*r),a=Math.floor(a*r);const l=Math.ceil(t.width*r),c=Math.ceil(t.height*r);return this.renderer.renderTarget.copyToTexture(e,n,{x:o,y:a},{width:l,height:c},{x:0,y:0}),n}applyFilter(e,t,s,r){const n=this.renderer,o=this._activeFilterData,l=o.outputRenderSurface===s,c=n.renderTarget.rootRenderTarget.colorTexture.source._resolution,h=this._findFilterResolution(c);let u=0,d=0;if(l){const p=this._findPreviousFilterOffset();u=p.x,d=p.y}this._updateFilterUniforms(t,s,o,u,d,h,l,r);const f=e.enabled?e:this._getPassthroughFilter();this._setupBindGroupsAndRender(f,t,n)}calculateSpriteMatrix(e,t){const s=this._activeFilterData,r=e.set(s.inputTexture._source.width,0,0,s.inputTexture._source.height,s.bounds.minX,s.bounds.minY),n=t.worldTransform.copyTo(O.shared),o=t.renderGroup||t.parentRenderGroup;return o&&o.cacheToLocalTransform&&n.prepend(o.cacheToLocalTransform),n.invert(),r.prepend(n),r.scale(1/t.texture.orig.width,1/t.texture.orig.height),r.translate(t.anchor.x,t.anchor.y),r}destroy(){this._passthroughFilter?.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new II),this._passthroughFilter}_setupBindGroupsAndRender(e,t,s){if(s.renderPipes.uniformBatch){const r=s.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(r,0)}else this._globalFilterBindGroup.setResource(this._filterGlobalUniforms,0);this._globalFilterBindGroup.setResource(t.source,1),this._globalFilterBindGroup.setResource(t.source.style,2),e.groups[0]=this._globalFilterBindGroup,s.encoder.draw({geometry:RI,shader:e,state:e._state,topology:"triangle-list"}),s.type===Qe.WEBGL&&s.renderTarget.finishRenderPass()}_setupFilterTextures(e,t,s,r){if(e.backTexture=M.EMPTY,e.inputTexture=ve.getOptimalTexture(t.width,t.height,e.resolution,e.antialias),e.blendRequired){s.renderTarget.finishRenderPass();const n=s.renderTarget.getRenderTarget(e.outputRenderSurface);e.backTexture=this.getBackTexture(n,t,r?.bounds)}s.renderTarget.bind(e.inputTexture,!0),s.globalUniforms.push({offset:t})}_calculateGlobalFrame(e,t,s,r,n,o){const a=e.globalFrame;a.x=t*r,a.y=s*r,a.width=n*r,a.height=o*r}_updateFilterUniforms(e,t,s,r,n,o,a,l){const c=this._filterGlobalUniforms.uniforms,h=c.uOutputFrame,u=c.uInputSize,d=c.uInputPixel,f=c.uInputClamp,p=c.uGlobalFrame,g=c.uOutputTexture;a?(h[0]=s.bounds.minX-r,h[1]=s.bounds.minY-n):(h[0]=0,h[1]=0),h[2]=e.frame.width,h[3]=e.frame.height,u[0]=e.source.width,u[1]=e.source.height,u[2]=1/u[0],u[3]=1/u[1],d[0]=e.source.pixelWidth,d[1]=e.source.pixelHeight,d[2]=1/d[0],d[3]=1/d[1],f[0]=.5*d[2],f[1]=.5*d[3],f[2]=e.frame.width*u[2]-.5*d[2],f[3]=e.frame.height*u[3]-.5*d[3];const m=this.renderer.renderTarget.rootRenderTarget.colorTexture;p[0]=r*o,p[1]=n*o,p[2]=m.source.width*o,p[3]=m.source.height*o,t instanceof M&&(t.source.resource=null);const x=this.renderer.renderTarget.getRenderTarget(t);this.renderer.renderTarget.bind(t,!!l),t instanceof M?(g[0]=t.frame.width,g[1]=t.frame.height):(g[0]=x.width,g[1]=x.height),g[2]=x.isRoot?-1:1,this._filterGlobalUniforms.update()}_findFilterResolution(e){let t=this._filterStackIndex-1;for(;t>0&&this._filterStack[t].skip;)--t;return t>0&&this._filterStack[t].inputTexture?this._filterStack[t].inputTexture.source._resolution:e}_findPreviousFilterOffset(){let e=0,t=0,s=this._filterStackIndex;for(;s>0;){s--;const r=this._filterStack[s];if(!r.skip){e=r.bounds.minX,t=r.bounds.minY;break}}return{x:e,y:t}}_calculateFilterArea(e,t){if(e.renderables?PI(e.renderables,t):e.filterEffect.filterArea?(t.clear(),t.addRect(e.filterEffect.filterArea),t.applyMatrix(e.container.worldTransform)):e.container.getFastGlobalBounds(!0,t),e.container){const r=(e.container.renderGroup||e.container.parentRenderGroup).cacheToLocalTransform;r&&t.applyMatrix(r)}}_applyFiltersToTexture(e,t){const s=e.inputTexture,r=e.bounds,n=e.filters,o=e.firstEnabledIndex,a=e.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(s.source.style,2),this._globalFilterBindGroup.setResource(e.backTexture.source,3),o===a)n[o].apply(this,s,e.outputRenderSurface,t);else{let l=e.inputTexture;const c=ve.getOptimalTexture(r.width,r.height,l.source._resolution,!1);let h=c;for(let u=o;u<a;u++){const d=n[u];if(!d.enabled)continue;d.apply(this,l,h,!0);const f=l;l=h,h=f}n[a].apply(this,l,e.outputRenderSurface,t),ve.returnTexture(c)}}_calculateFilterBounds(e,t,s,r,n){const o=this.renderer,a=e.bounds,l=e.filters;let c=1/0,h=0,u=!0,d=!1,f=!1,p=!0,g=-1,m=-1;for(let x=0;x<l.length;x++){const _=l[x];if(!_.enabled)continue;if(g===-1&&(g=x),m=x,c=Math.min(c,_.resolution==="inherit"?r:_.resolution),h+=_.padding,_.antialias==="off"?u=!1:_.antialias==="inherit"&&u&&(u=s),_.clipToViewport||(p=!1),!!!(_.compatibleRenderers&o.type)){f=!1;break}if(_.blendRequired&&!(o.backBuffer?.useBackBuffer??!0)){L("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),f=!1;break}f=!0,d||(d=_.blendRequired)}if(!f){e.skip=!0;return}if(p&&a.fitBounds(0,t.width/r,0,t.height/r),a.scale(c).ceil().scale(1/c).pad((h|0)*n),!a.isPositive){e.skip=!0;return}e.antialias=u,e.resolution=c,e.blendRequired=d,e.firstEnabledIndex=g,e.lastEnabledIndex=m}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){let e,t=this._filterStackIndex-1;for(;t>0&&(t--,e=this._filterStack[t],!!e.skip););return e}_pushFilterData(){let e=this._filterStack[this._filterStackIndex];return e||(e=this._filterStack[this._filterStackIndex]=new MI),this._filterStackIndex++,e}}w0.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"filter"};var kI=`in vec2 vMaskCoord;
|
|
575
575
|
in vec2 vTextureCoord;
|
|
576
576
|
|
|
577
577
|
uniform sampler2D uTexture;
|
|
@@ -740,7 +740,7 @@ fn mainFragment(
|
|
|
740
740
|
|
|
741
741
|
return source * a;
|
|
742
742
|
}
|
|
743
|
-
`;class BI extends Gi{constructor(e){const{sprite:t,...s}=e,r=new $p(t.texture),n=new He({uFilterMatrix:{value:new O,type:"mat3x3<f32>"},uMaskClamp:{value:r.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"}}),o=Ut.from({vertex:{source:S0,entryPoint:"mainVertex"},fragment:{source:S0,entryPoint:"mainFragment"}}),a=At.from({vertex:FI,fragment:kI,name:"mask-filter"});super({...s,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=r}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(e,t,s,r){this._textureMatrix.texture=this.sprite.texture,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,e.applyFilter(this,t,s,r)}}class _e extends vu{constructor(e){e instanceof lt&&(e={context:e});const{context:t,roundPixels:s,...r}=e||{};super({label:"Graphics",...r}),this.renderPipeId="graphics",t?this._context=t:this._context=this._ownedContext=new lt,this._context.on("update",this.onViewUpdate,this),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=s??!1}set context(e){e!==this._context&&(this._context.off("update",this.onViewUpdate,this),this._context=e,this._context.on("update",this.onViewUpdate,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||e?.context===!0)&&this._context.destroy(e),this._ownedContext=null,this._context=null,super.destroy(e)}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod("setFillStyle",e)}setStrokeStyle(...e){return this._callContextMethod("setStrokeStyle",e)}fill(...e){return this._callContextMethod("fill",e)}stroke(...e){return this._callContextMethod("stroke",e)}texture(...e){return this._callContextMethod("texture",e)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...e){return this._callContextMethod("arc",e)}arcTo(...e){return this._callContextMethod("arcTo",e)}arcToSvg(...e){return this._callContextMethod("arcToSvg",e)}bezierCurveTo(...e){return this._callContextMethod("bezierCurveTo",e)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...e){return this._callContextMethod("ellipse",e)}circle(...e){return this._callContextMethod("circle",e)}path(...e){return this._callContextMethod("path",e)}lineTo(...e){return this._callContextMethod("lineTo",e)}moveTo(...e){return this._callContextMethod("moveTo",e)}quadraticCurveTo(...e){return this._callContextMethod("quadraticCurveTo",e)}rect(...e){return this._callContextMethod("rect",e)}roundRect(...e){return this._callContextMethod("roundRect",e)}poly(...e){return this._callContextMethod("poly",e)}regularPoly(...e){return this._callContextMethod("regularPoly",e)}roundPoly(...e){return this._callContextMethod("roundPoly",e)}roundShape(...e){return this._callContextMethod("roundShape",e)}filletRect(...e){return this._callContextMethod("filletRect",e)}chamferRect(...e){return this._callContextMethod("chamferRect",e)}star(...e){return this._callContextMethod("star",e)}svg(...e){return this._callContextMethod("svg",e)}restore(...e){return this._callContextMethod("restore",e)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...e){return this._callContextMethod("rotate",e)}scaleTransform(...e){return this._callContextMethod("scale",e)}setTransform(...e){return this._callContextMethod("setTransform",e)}transform(...e){return this._callContextMethod("transform",e)}translateTransform(...e){return this._callContextMethod("translate",e)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(e=!1){return e?new _e(this._context.clone()):(this._ownedContext=null,new _e(this._context))}lineStyle(e,t,s){W(Q,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const r={};return e&&(r.width=e),t&&(r.color=t),s&&(r.alpha=s),this.context.strokeStyle=r,this}beginFill(e,t){W(Q,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const s={};return e!==void 0&&(s.color=e),t!==void 0&&(s.alpha=t),this.context.fillStyle=s,this}endFill(){W(Q,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const e=this.context.strokeStyle;return(e.width!==lt.defaultStrokeStyle.width||e.color!==lt.defaultStrokeStyle.color||e.alpha!==lt.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return W(Q,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return W(Q,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return W(Q,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return W(Q,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return W(Q,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return W(Q,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}const C0=class oy extends Ms{constructor(...e){let t=e[0]??{};t instanceof Float32Array&&(W(Q,"use new MeshGeometry({ positions, uvs, indices }) instead"),t={positions:t,uvs:e[1],indices:e[2]}),t={...oy.defaultOptions,...t};const s=t.positions||new Float32Array([0,0,1,0,1,1,0,1]);let r=t.uvs;r||(t.positions?r=new Float32Array(s.length):r=new Float32Array([0,0,1,0,1,1,0,1]));const n=t.indices||new Uint32Array([0,1,2,0,2,3]),o=t.shrinkBuffersToFit,a=new tt({data:s,label:"attribute-mesh-positions",shrinkToFit:o,usage:j.VERTEX|j.COPY_DST}),l=new tt({data:r,label:"attribute-mesh-uvs",shrinkToFit:o,usage:j.VERTEX|j.COPY_DST}),c=new tt({data:n,label:"index-mesh-buffer",shrinkToFit:o,usage:j.INDEX|j.COPY_DST});super({attributes:{aPosition:{buffer:a,format:"float32x2",stride:8,offset:0},aUV:{buffer:l,format:"float32x2",stride:8,offset:0}},indexBuffer:c,topology:t.topology}),this.batchMode="auto"}get positions(){return this.attributes.aPosition.buffer.data}set positions(e){this.attributes.aPosition.buffer.data=e}get uvs(){return this.attributes.aUV.buffer.data}set uvs(e){this.attributes.aUV.buffer.data=e}get indices(){return this.indexBuffer.data}set indices(e){this.indexBuffer.data=e}};C0.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let wd=C0;class A0 extends vu{constructor(e,t){const{text:s,resolution:r,style:n,anchor:o,width:a,height:l,roundPixels:c,...h}=e;super({...h}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=s??"",this.style=n,this.resolution=r??null,this.allowChildren=!1,this._anchor=new Be({_onUpdate:()=>{this.onViewUpdate()}}),o&&(this.anchor=o),this.roundPixels=c??!1,a!==void 0&&(this.width=a),l!==void 0&&(this.height=l)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||(e={}),this._style?.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){const t=this.bounds.width,s=this.bounds.height,r=-t*this.anchor.x;let n=0;return e.x>=r&&e.x<=r+t&&(n=-s*this.anchor.y,e.y>=n&&e.y<=n+s)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}}function E0(i,e){let t=i[0]??{};return(typeof t=="string"||i[1])&&(W(Q,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:i[1]}),t}let mi=null,Nt=null;function UI(i,e){mi||(mi=Y.get().createCanvas(256,128),Nt=mi.getContext("2d",{willReadFrequently:!0}),Nt.globalCompositeOperation="copy",Nt.globalAlpha=1),(mi.width<i||mi.height<e)&&(mi.width=ki(i),mi.height=ki(e))}function I0(i,e,t){for(let s=0,r=4*t*e;s<e;++s,r+=4)if(i[r+3]!==0)return!1;return!0}function P0(i,e,t,s,r){const n=4*e;for(let o=s,a=s*n+4*t;o<=r;++o,a+=n)if(i[a+3]!==0)return!1;return!0}function OI(...i){let e=i[0];e.canvas||(e={canvas:i[0],resolution:i[1]});const{canvas:t}=e,s=Math.min(e.resolution??1,1),r=e.width??t.width,n=e.height??t.height;let o=e.output;if(UI(r,n),!Nt)throw new TypeError("Failed to get canvas 2D context");Nt.drawImage(t,0,0,r,n,0,0,r*s,n*s);const l=Nt.getImageData(0,0,r,n).data;let c=0,h=0,u=r-1,d=n-1;for(;h<n&&I0(l,r,h);)++h;if(h===n)return H.EMPTY;for(;I0(l,r,d);)--d;for(;P0(l,r,c,h,d);)++c;for(;P0(l,r,u,h,d);)--u;return++u,++d,Nt.globalCompositeOperation="source-over",Nt.strokeRect(c,h,u-c,d-h),Nt.globalCompositeOperation="copy",o??(o=new H),o.set(c/s,h/s,(u-c)/s,(d-h)/s),o}const R0=new H;class DI{getCanvasAndContext(e){const{text:t,style:s,resolution:r=1}=e,n=s._getFinalPadding(),o=$e.measureText(t||" ",s),a=Math.ceil(Math.ceil(Math.max(1,o.width)+n*2)*r),l=Math.ceil(Math.ceil(Math.max(1,o.height)+n*2)*r),c=Gt.getOptimalCanvasAndContext(a,l);this._renderTextToCanvas(t,s,n,r,c);const h=s.trim?OI({canvas:c.canvas,width:a,height:l,resolution:1,output:R0}):R0.set(0,0,a,l);return{canvasAndContext:c,frame:h}}returnCanvasAndContext(e){Gt.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,s,r,n){const{canvas:o,context:a}=n,l=Kr(t),c=$e.measureText(e||" ",t),h=c.lines,u=c.lineHeight,d=c.lineWidths,f=c.maxLineWidth,p=c.fontProperties,g=o.height;if(a.resetTransform(),a.scale(r,r),a.textBaseline=t.textBaseline,t._stroke?.width){const y=t._stroke;a.lineWidth=y.width,a.miterLimit=y.miterLimit,a.lineJoin=y.join,a.lineCap=y.cap}a.font=l;let m,_;const x=t.dropShadow?2:1;for(let y=0;y<x;++y){const v=t.dropShadow&&y===0,T=v?Math.ceil(Math.max(1,g)+s*2):0,S=T*r;if(v){a.fillStyle="black",a.strokeStyle="black";const P=t.dropShadow,C=P.color,A=P.alpha;a.shadowColor=ue.shared.setValue(C).setAlpha(A).toRgbaString();const U=P.blur*r,D=P.distance*r;a.shadowBlur=U,a.shadowOffsetX=Math.cos(P.angle)*D,a.shadowOffsetY=Math.sin(P.angle)*D+S}else{if(a.fillStyle=t._fill?rn(t._fill,a,c,s*2):null,t._stroke?.width){const P=t._stroke.width*.5+s*2;a.strokeStyle=rn(t._stroke,a,c,P)}a.shadowColor="black"}let w=(u-p.fontSize)/2;u-p.fontSize<0&&(w=0);const E=t._stroke?.width??0;for(let P=0;P<h.length;P++)m=E/2,_=E/2+P*u+p.ascent+w,t.align==="right"?m+=f-d[P]:t.align==="center"&&(m+=(f-d[P])/2),t._stroke?.width&&this._drawLetterSpacing(h[P],t,n,m+s,_+s-T,!0),t._fill!==void 0&&this._drawLetterSpacing(h[P],t,n,m+s,_+s-T)}}_drawLetterSpacing(e,t,s,r,n,o=!1){const{context:a}=s,l=t.letterSpacing;let c=!1;if($e.experimentalLetterSpacingSupported&&($e.experimentalLetterSpacing?(a.letterSpacing=`${l}px`,a.textLetterSpacing=`${l}px`,c=!0):(a.letterSpacing="0px",a.textLetterSpacing="0px")),l===0||c){o?a.strokeText(e,r,n):a.fillText(e,r,n);return}let h=r;const u=$e.graphemeSegmenter(e);let d=a.measureText(e).width,f=0;for(let p=0;p<u.length;++p){const g=u[p];o?a.strokeText(g,h,n):a.fillText(g,h,n);let m="";for(let _=p+1;_<u.length;++_)m+=u[_];f=a.measureText(m).width,h+=d-f+l,d=f}}}const Ws=new DI;let GI=class extends A0{constructor(...e){const t=E0(e,"Text");super(t,Xe),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof wt?t.textureStyle:new wt(t.textureStyle))}updateBounds(){const e=this._bounds,t=this._anchor;let s=0,r=0;if(this._style.trim){const{frame:n,canvasAndContext:o}=Ws.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Ws.returnCanvasAndContext(o),s=n.width,r=n.height}else{const n=$e.measureText(this._text,this._style);s=n.width,r=n.height}e.minX=-t._x*s,e.maxX=e.minX+s,e.minY=-t._y*r,e.maxY=e.minY+r}};class zI extends A0{constructor(...e){var t;const s=E0(e,"BitmapText");s.style??(s.style=s.style||{}),(t=s.style).fill??(t.fill=16777215),super(s,Xe),this.renderPipeId="bitmapText"}updateBounds(){const e=this._bounds,t=this._anchor,s=Ns.measureText(this.text,this._style),r=s.scale,n=s.offsetY*r;let o=s.width*r,a=s.height*r;const l=this._style._stroke;l&&(o+=l.width,a+=l.width),e.minX=-t._x*o,e.maxX=e.minX+o,e.minY=-t._y*(a+n),e.maxY=e.minY+a}set resolution(e){e!==null&&L("[BitmapText] dynamically updating the resolution is not supported. Resolution should be managed by the BitmapFont.")}get resolution(){return this._resolution}}const M0="http://www.w3.org/2000/svg",k0="http://www.w3.org/1999/xhtml";class F0{constructor(){this.svgRoot=document.createElementNS(M0,"svg"),this.foreignObject=document.createElementNS(M0,"foreignObject"),this.domElement=document.createElementNS(k0,"div"),this.styleElement=document.createElementNS(k0,"style");const{foreignObject:e,svgRoot:t,styleElement:s,domElement:r}=this;e.setAttribute("width","10000"),e.setAttribute("height","10000"),e.style.overflow="hidden",t.appendChild(e),e.appendChild(s),e.appendChild(r),this.image=Y.get().createImage()}destroy(){this.svgRoot.remove(),this.foreignObject.remove(),this.styleElement.remove(),this.domElement.remove(),this.image.src="",this.image.remove(),this.svgRoot=null,this.foreignObject=null,this.styleElement=null,this.domElement=null,this.image=null,this.canvasAndContext=null}}let B0;function NI(i,e,t,s){s||(s=B0||(B0=new F0));const{domElement:r,styleElement:n,svgRoot:o}=s;r.innerHTML=`<style>${e.cssStyle};</style><div style='padding:0'>${i}</div>`,r.setAttribute("style","transform-origin: top left; display: inline-block"),t&&(n.textContent=t),document.body.appendChild(o);const a=r.getBoundingClientRect();o.remove();const l=e.padding*2;return{width:a.width-l,height:a.height-l}}class U0{constructor(){this._tempState=ft.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,s){const r=e.renderer,n=this._didUploadHash[s.uid];r.shader.bind(s,n),n||(this._didUploadHash[s.uid]=!0),r.shader.updateUniformGroup(r.globalUniforms.uniformGroup),r.geometry.bind(t,s.glProgram)}execute(e,t){const s=e.renderer;this._tempState.blendMode=t.blendMode,s.state.set(this._tempState);const r=t.textures.textures;for(let n=0;n<t.textures.count;n++)s.texture.bind(r[n],n);s.geometry.draw(t.topology,t.size,t.start)}}U0.extension={type:[b.WebGLPipesAdaptor],name:"batch"};const ln=ft.for2d();class O0{start(e,t,s){const r=e.renderer,n=r.encoder,o=s.gpuProgram;this._shader=s,this._geometry=t,n.setGeometry(t,o),ln.blendMode="normal",r.pipeline.getPipeline(t,o,ln);const a=r.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(e,t){const s=this._shader.gpuProgram,r=e.renderer,n=r.encoder;if(!t.bindGroup){const l=t.textures;t.bindGroup=Yu(l.textures,l.count,r.limits.maxBatchableTextures)}ln.blendMode=t.blendMode;const o=r.bindGroup.getBindGroup(t.bindGroup,s,1),a=r.pipeline.getPipeline(this._geometry,s,ln,t.topology);t.bindGroup._touch(r.textureGC.count),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(t.size,1,t.start)}}O0.extension={type:[b.WebGPUPipesAdaptor],name:"batch"};const Sd=class ay{constructor(e,t){this.state=ft.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,this._adaptor.init?.(this)}static getBatcher(e){return new this._availableBatchers[e]}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new sd({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const s in this._activeBatches)this._activeBatches[s].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let s=this._activeBatches[e.batcherName];s||(s=this._activeBatches[e.batcherName]=ay.getBatcher(e.batcherName),s.begin()),this._activeBatch=s}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const s in t){const r=t[s],n=r.geometry;n.indexBuffer.setDataWithSize(r.indexBuffer,r.indexSize,!0),n.buffers[0].setDataWithSize(r.attributeBuffer.float32View,r.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const s in t){const r=t[s],n=r.geometry;r.dirty&&(r.dirty=!1,n.buffers[0].update(r.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,s=t.geometry,r=t.shader;this._adaptor.start(this,s,r)}this._adaptor.execute(this,e)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}};Sd.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"batch"},Sd._availableBatchers=Object.create(null);let D0=Sd;V.handleByMap(b.Batcher,D0._availableBatchers),V.add(sd);const Vs={name:"local-uniform-bit",vertex:{header:`
|
|
743
|
+
`;class BI extends Gi{constructor(e){const{sprite:t,...s}=e,r=new $p(t.texture),n=new He({uFilterMatrix:{value:new O,type:"mat3x3<f32>"},uMaskClamp:{value:r.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"}}),o=Ut.from({vertex:{source:S0,entryPoint:"mainVertex"},fragment:{source:S0,entryPoint:"mainFragment"}}),a=At.from({vertex:FI,fragment:kI,name:"mask-filter"});super({...s,gpuProgram:o,glProgram:a,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=r}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(e,t,s,r){this._textureMatrix.texture=this.sprite.texture,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,e.applyFilter(this,t,s,r)}}class xe extends vu{constructor(e){e instanceof lt&&(e={context:e});const{context:t,roundPixels:s,...r}=e||{};super({label:"Graphics",...r}),this.renderPipeId="graphics",t?this._context=t:this._context=this._ownedContext=new lt,this._context.on("update",this.onViewUpdate,this),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=s??!1}set context(e){e!==this._context&&(this._context.off("update",this.onViewUpdate,this),this._context=e,this._context.on("update",this.onViewUpdate,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||e?.context===!0)&&this._context.destroy(e),this._ownedContext=null,this._context=null,super.destroy(e)}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod("setFillStyle",e)}setStrokeStyle(...e){return this._callContextMethod("setStrokeStyle",e)}fill(...e){return this._callContextMethod("fill",e)}stroke(...e){return this._callContextMethod("stroke",e)}texture(...e){return this._callContextMethod("texture",e)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...e){return this._callContextMethod("arc",e)}arcTo(...e){return this._callContextMethod("arcTo",e)}arcToSvg(...e){return this._callContextMethod("arcToSvg",e)}bezierCurveTo(...e){return this._callContextMethod("bezierCurveTo",e)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...e){return this._callContextMethod("ellipse",e)}circle(...e){return this._callContextMethod("circle",e)}path(...e){return this._callContextMethod("path",e)}lineTo(...e){return this._callContextMethod("lineTo",e)}moveTo(...e){return this._callContextMethod("moveTo",e)}quadraticCurveTo(...e){return this._callContextMethod("quadraticCurveTo",e)}rect(...e){return this._callContextMethod("rect",e)}roundRect(...e){return this._callContextMethod("roundRect",e)}poly(...e){return this._callContextMethod("poly",e)}regularPoly(...e){return this._callContextMethod("regularPoly",e)}roundPoly(...e){return this._callContextMethod("roundPoly",e)}roundShape(...e){return this._callContextMethod("roundShape",e)}filletRect(...e){return this._callContextMethod("filletRect",e)}chamferRect(...e){return this._callContextMethod("chamferRect",e)}star(...e){return this._callContextMethod("star",e)}svg(...e){return this._callContextMethod("svg",e)}restore(...e){return this._callContextMethod("restore",e)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...e){return this._callContextMethod("rotate",e)}scaleTransform(...e){return this._callContextMethod("scale",e)}setTransform(...e){return this._callContextMethod("setTransform",e)}transform(...e){return this._callContextMethod("transform",e)}translateTransform(...e){return this._callContextMethod("translate",e)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(e=!1){return e?new xe(this._context.clone()):(this._ownedContext=null,new xe(this._context))}lineStyle(e,t,s){W(Q,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const r={};return e&&(r.width=e),t&&(r.color=t),s&&(r.alpha=s),this.context.strokeStyle=r,this}beginFill(e,t){W(Q,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const s={};return e!==void 0&&(s.color=e),t!==void 0&&(s.alpha=t),this.context.fillStyle=s,this}endFill(){W(Q,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const e=this.context.strokeStyle;return(e.width!==lt.defaultStrokeStyle.width||e.color!==lt.defaultStrokeStyle.color||e.alpha!==lt.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return W(Q,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return W(Q,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return W(Q,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return W(Q,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return W(Q,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return W(Q,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}const C0=class oy extends Ms{constructor(...e){let t=e[0]??{};t instanceof Float32Array&&(W(Q,"use new MeshGeometry({ positions, uvs, indices }) instead"),t={positions:t,uvs:e[1],indices:e[2]}),t={...oy.defaultOptions,...t};const s=t.positions||new Float32Array([0,0,1,0,1,1,0,1]);let r=t.uvs;r||(t.positions?r=new Float32Array(s.length):r=new Float32Array([0,0,1,0,1,1,0,1]));const n=t.indices||new Uint32Array([0,1,2,0,2,3]),o=t.shrinkBuffersToFit,a=new tt({data:s,label:"attribute-mesh-positions",shrinkToFit:o,usage:j.VERTEX|j.COPY_DST}),l=new tt({data:r,label:"attribute-mesh-uvs",shrinkToFit:o,usage:j.VERTEX|j.COPY_DST}),c=new tt({data:n,label:"index-mesh-buffer",shrinkToFit:o,usage:j.INDEX|j.COPY_DST});super({attributes:{aPosition:{buffer:a,format:"float32x2",stride:8,offset:0},aUV:{buffer:l,format:"float32x2",stride:8,offset:0}},indexBuffer:c,topology:t.topology}),this.batchMode="auto"}get positions(){return this.attributes.aPosition.buffer.data}set positions(e){this.attributes.aPosition.buffer.data=e}get uvs(){return this.attributes.aUV.buffer.data}set uvs(e){this.attributes.aUV.buffer.data=e}get indices(){return this.indexBuffer.data}set indices(e){this.indexBuffer.data=e}};C0.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let wd=C0;class A0 extends vu{constructor(e,t){const{text:s,resolution:r,style:n,anchor:o,width:a,height:l,roundPixels:c,...h}=e;super({...h}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=s??"",this.style=n,this.resolution=r??null,this.allowChildren=!1,this._anchor=new Be({_onUpdate:()=>{this.onViewUpdate()}}),o&&(this.anchor=o),this.roundPixels=c??!1,a!==void 0&&(this.width=a),l!==void 0&&(this.height=l)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){e||(e={}),this._style?.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){const t=this.bounds.width,s=this.bounds.height,r=-t*this.anchor.x;let n=0;return e.x>=r&&e.x<=r+t&&(n=-s*this.anchor.y,e.y>=n&&e.y<=n+s)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}}function E0(i,e){let t=i[0]??{};return(typeof t=="string"||i[1])&&(W(Q,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:i[1]}),t}let mi=null,Nt=null;function UI(i,e){mi||(mi=Y.get().createCanvas(256,128),Nt=mi.getContext("2d",{willReadFrequently:!0}),Nt.globalCompositeOperation="copy",Nt.globalAlpha=1),(mi.width<i||mi.height<e)&&(mi.width=ki(i),mi.height=ki(e))}function I0(i,e,t){for(let s=0,r=4*t*e;s<e;++s,r+=4)if(i[r+3]!==0)return!1;return!0}function P0(i,e,t,s,r){const n=4*e;for(let o=s,a=s*n+4*t;o<=r;++o,a+=n)if(i[a+3]!==0)return!1;return!0}function OI(...i){let e=i[0];e.canvas||(e={canvas:i[0],resolution:i[1]});const{canvas:t}=e,s=Math.min(e.resolution??1,1),r=e.width??t.width,n=e.height??t.height;let o=e.output;if(UI(r,n),!Nt)throw new TypeError("Failed to get canvas 2D context");Nt.drawImage(t,0,0,r,n,0,0,r*s,n*s);const l=Nt.getImageData(0,0,r,n).data;let c=0,h=0,u=r-1,d=n-1;for(;h<n&&I0(l,r,h);)++h;if(h===n)return H.EMPTY;for(;I0(l,r,d);)--d;for(;P0(l,r,c,h,d);)++c;for(;P0(l,r,u,h,d);)--u;return++u,++d,Nt.globalCompositeOperation="source-over",Nt.strokeRect(c,h,u-c,d-h),Nt.globalCompositeOperation="copy",o??(o=new H),o.set(c/s,h/s,(u-c)/s,(d-h)/s),o}const R0=new H;class DI{getCanvasAndContext(e){const{text:t,style:s,resolution:r=1}=e,n=s._getFinalPadding(),o=$e.measureText(t||" ",s),a=Math.ceil(Math.ceil(Math.max(1,o.width)+n*2)*r),l=Math.ceil(Math.ceil(Math.max(1,o.height)+n*2)*r),c=Gt.getOptimalCanvasAndContext(a,l);this._renderTextToCanvas(t,s,n,r,c);const h=s.trim?OI({canvas:c.canvas,width:a,height:l,resolution:1,output:R0}):R0.set(0,0,a,l);return{canvasAndContext:c,frame:h}}returnCanvasAndContext(e){Gt.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,s,r,n){const{canvas:o,context:a}=n,l=Kr(t),c=$e.measureText(e||" ",t),h=c.lines,u=c.lineHeight,d=c.lineWidths,f=c.maxLineWidth,p=c.fontProperties,g=o.height;if(a.resetTransform(),a.scale(r,r),a.textBaseline=t.textBaseline,t._stroke?.width){const y=t._stroke;a.lineWidth=y.width,a.miterLimit=y.miterLimit,a.lineJoin=y.join,a.lineCap=y.cap}a.font=l;let m,x;const _=t.dropShadow?2:1;for(let y=0;y<_;++y){const v=t.dropShadow&&y===0,T=v?Math.ceil(Math.max(1,g)+s*2):0,S=T*r;if(v){a.fillStyle="black",a.strokeStyle="black";const P=t.dropShadow,C=P.color,A=P.alpha;a.shadowColor=ue.shared.setValue(C).setAlpha(A).toRgbaString();const U=P.blur*r,D=P.distance*r;a.shadowBlur=U,a.shadowOffsetX=Math.cos(P.angle)*D,a.shadowOffsetY=Math.sin(P.angle)*D+S}else{if(a.fillStyle=t._fill?rn(t._fill,a,c,s*2):null,t._stroke?.width){const P=t._stroke.width*.5+s*2;a.strokeStyle=rn(t._stroke,a,c,P)}a.shadowColor="black"}let w=(u-p.fontSize)/2;u-p.fontSize<0&&(w=0);const E=t._stroke?.width??0;for(let P=0;P<h.length;P++)m=E/2,x=E/2+P*u+p.ascent+w,t.align==="right"?m+=f-d[P]:t.align==="center"&&(m+=(f-d[P])/2),t._stroke?.width&&this._drawLetterSpacing(h[P],t,n,m+s,x+s-T,!0),t._fill!==void 0&&this._drawLetterSpacing(h[P],t,n,m+s,x+s-T)}}_drawLetterSpacing(e,t,s,r,n,o=!1){const{context:a}=s,l=t.letterSpacing;let c=!1;if($e.experimentalLetterSpacingSupported&&($e.experimentalLetterSpacing?(a.letterSpacing=`${l}px`,a.textLetterSpacing=`${l}px`,c=!0):(a.letterSpacing="0px",a.textLetterSpacing="0px")),l===0||c){o?a.strokeText(e,r,n):a.fillText(e,r,n);return}let h=r;const u=$e.graphemeSegmenter(e);let d=a.measureText(e).width,f=0;for(let p=0;p<u.length;++p){const g=u[p];o?a.strokeText(g,h,n):a.fillText(g,h,n);let m="";for(let x=p+1;x<u.length;++x)m+=u[x];f=a.measureText(m).width,h+=d-f+l,d=f}}}const Ws=new DI;let GI=class extends A0{constructor(...e){const t=E0(e,"Text");super(t,Xe),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof wt?t.textureStyle:new wt(t.textureStyle))}updateBounds(){const e=this._bounds,t=this._anchor;let s=0,r=0;if(this._style.trim){const{frame:n,canvasAndContext:o}=Ws.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Ws.returnCanvasAndContext(o),s=n.width,r=n.height}else{const n=$e.measureText(this._text,this._style);s=n.width,r=n.height}e.minX=-t._x*s,e.maxX=e.minX+s,e.minY=-t._y*r,e.maxY=e.minY+r}};class zI extends A0{constructor(...e){var t;const s=E0(e,"BitmapText");s.style??(s.style=s.style||{}),(t=s.style).fill??(t.fill=16777215),super(s,Xe),this.renderPipeId="bitmapText"}updateBounds(){const e=this._bounds,t=this._anchor,s=Ns.measureText(this.text,this._style),r=s.scale,n=s.offsetY*r;let o=s.width*r,a=s.height*r;const l=this._style._stroke;l&&(o+=l.width,a+=l.width),e.minX=-t._x*o,e.maxX=e.minX+o,e.minY=-t._y*(a+n),e.maxY=e.minY+a}set resolution(e){e!==null&&L("[BitmapText] dynamically updating the resolution is not supported. Resolution should be managed by the BitmapFont.")}get resolution(){return this._resolution}}const M0="http://www.w3.org/2000/svg",k0="http://www.w3.org/1999/xhtml";class F0{constructor(){this.svgRoot=document.createElementNS(M0,"svg"),this.foreignObject=document.createElementNS(M0,"foreignObject"),this.domElement=document.createElementNS(k0,"div"),this.styleElement=document.createElementNS(k0,"style");const{foreignObject:e,svgRoot:t,styleElement:s,domElement:r}=this;e.setAttribute("width","10000"),e.setAttribute("height","10000"),e.style.overflow="hidden",t.appendChild(e),e.appendChild(s),e.appendChild(r),this.image=Y.get().createImage()}destroy(){this.svgRoot.remove(),this.foreignObject.remove(),this.styleElement.remove(),this.domElement.remove(),this.image.src="",this.image.remove(),this.svgRoot=null,this.foreignObject=null,this.styleElement=null,this.domElement=null,this.image=null,this.canvasAndContext=null}}let B0;function NI(i,e,t,s){s||(s=B0||(B0=new F0));const{domElement:r,styleElement:n,svgRoot:o}=s;r.innerHTML=`<style>${e.cssStyle};</style><div style='padding:0'>${i}</div>`,r.setAttribute("style","transform-origin: top left; display: inline-block"),t&&(n.textContent=t),document.body.appendChild(o);const a=r.getBoundingClientRect();o.remove();const l=e.padding*2;return{width:a.width-l,height:a.height-l}}class U0{constructor(){this._tempState=ft.for2d(),this._didUploadHash={}}init(e){e.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(e,t,s){const r=e.renderer,n=this._didUploadHash[s.uid];r.shader.bind(s,n),n||(this._didUploadHash[s.uid]=!0),r.shader.updateUniformGroup(r.globalUniforms.uniformGroup),r.geometry.bind(t,s.glProgram)}execute(e,t){const s=e.renderer;this._tempState.blendMode=t.blendMode,s.state.set(this._tempState);const r=t.textures.textures;for(let n=0;n<t.textures.count;n++)s.texture.bind(r[n],n);s.geometry.draw(t.topology,t.size,t.start)}}U0.extension={type:[b.WebGLPipesAdaptor],name:"batch"};const ln=ft.for2d();class O0{start(e,t,s){const r=e.renderer,n=r.encoder,o=s.gpuProgram;this._shader=s,this._geometry=t,n.setGeometry(t,o),ln.blendMode="normal",r.pipeline.getPipeline(t,o,ln);const a=r.globalUniforms.bindGroup;n.resetBindGroup(1),n.setBindGroup(0,a,o)}execute(e,t){const s=this._shader.gpuProgram,r=e.renderer,n=r.encoder;if(!t.bindGroup){const l=t.textures;t.bindGroup=Yu(l.textures,l.count,r.limits.maxBatchableTextures)}ln.blendMode=t.blendMode;const o=r.bindGroup.getBindGroup(t.bindGroup,s,1),a=r.pipeline.getPipeline(this._geometry,s,ln,t.topology);t.bindGroup._touch(r.textureGC.count),n.setPipeline(a),n.renderPassEncoder.setBindGroup(1,o),n.renderPassEncoder.drawIndexed(t.size,1,t.start)}}O0.extension={type:[b.WebGPUPipesAdaptor],name:"batch"};const Sd=class ay{constructor(e,t){this.state=ft.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,this._adaptor.init?.(this)}static getBatcher(e){return new this._availableBatchers[e]}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new sd({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const s in this._activeBatches)this._activeBatches[s].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let s=this._activeBatches[e.batcherName];s||(s=this._activeBatches[e.batcherName]=ay.getBatcher(e.batcherName),s.begin()),this._activeBatch=s}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const s in t){const r=t[s],n=r.geometry;n.indexBuffer.setDataWithSize(r.indexBuffer,r.indexSize,!0),n.buffers[0].setDataWithSize(r.attributeBuffer.float32View,r.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const s in t){const r=t[s],n=r.geometry;r.dirty&&(r.dirty=!1,n.buffers[0].update(r.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,s=t.geometry,r=t.shader;this._adaptor.start(this,s,r)}this._adaptor.execute(this,e)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const e in this._activeBatches)this._activeBatches[e].destroy();this._activeBatches=null}};Sd.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"batch"},Sd._availableBatchers=Object.create(null);let D0=Sd;V.handleByMap(b.Batcher,D0._availableBatchers),V.add(sd);const Vs={name:"local-uniform-bit",vertex:{header:`
|
|
744
744
|
|
|
745
745
|
struct LocalUniforms {
|
|
746
746
|
uTransformMatrix:mat3x3<f32>,
|
|
@@ -815,7 +815,7 @@ fn mainFragment(
|
|
|
815
815
|
|
|
816
816
|
void main() {
|
|
817
817
|
finalColor = texture(uTexture, vUv);
|
|
818
|
-
}`,name:"big-triangle"});this._bigTriangleShader=new ot({glProgram:r,resources:{uTexture:M.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const s=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=s.colorTexture,e.target=this._getBackBufferTexture(s.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:ZI,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new M({source:new Ee({width:e.width,height:e.height,resolution:e._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(e.width,e.height,e._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};Id.extension={type:[b.WebGLSystem],name:"backBuffer",priority:1},Id.defaultOptions={useBackBuffer:!1};let JI=Id;class X0{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.gl.colorMask(!!(e&8),!!(e&4),!!(e&2),!!(e&1)))}}X0.extension={type:[b.WebGLSystem],name:"colorMask"};class Y0{constructor(e){this.commandFinished=Promise.resolve(),this._renderer=e}setGeometry(e,t){this._renderer.geometry.bind(e,t.glProgram)}finishRenderPass(){}draw(e){const t=this._renderer,{geometry:s,shader:r,state:n,skipSync:o,topology:a,size:l,start:c,instanceCount:h}=e;t.shader.bind(r,o),t.geometry.bind(s,t.shader._activeProgram),n&&t.state.set(n),t.geometry.draw(a,l,c,h??s.instanceCount)}destroy(){this._renderer=null}}Y0.extension={type:[b.WebGLSystem],name:"encoder"};class q0{constructor(e){this._renderer=e}contextChange(){const e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=
|
|
818
|
+
}`,name:"big-triangle"});this._bigTriangleShader=new ot({glProgram:r,resources:{uTexture:M.WHITE.source}})}renderStart(e){const t=this._renderer.renderTarget.getRenderTarget(e.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!t.isRoot,this._useBackBufferThisRender){const s=this._renderer.renderTarget.getRenderTarget(e.target);this._targetTexture=s.colorTexture,e.target=this._getBackBufferTexture(s.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const e=this._renderer;e.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(e.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,e.encoder.draw({geometry:ZI,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(e){return this._backBufferTexture=this._backBufferTexture||new M({source:new Ee({width:e.width,height:e.height,resolution:e._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(e.width,e.height,e._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};Id.extension={type:[b.WebGLSystem],name:"backBuffer",priority:1},Id.defaultOptions={useBackBuffer:!1};let JI=Id;class X0{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.gl.colorMask(!!(e&8),!!(e&4),!!(e&2),!!(e&1)))}}X0.extension={type:[b.WebGLSystem],name:"colorMask"};class Y0{constructor(e){this.commandFinished=Promise.resolve(),this._renderer=e}setGeometry(e,t){this._renderer.geometry.bind(e,t.glProgram)}finishRenderPass(){}draw(e){const t=this._renderer,{geometry:s,shader:r,state:n,skipSync:o,topology:a,size:l,start:c,instanceCount:h}=e;t.shader.bind(r,o),t.geometry.bind(s,t.shader._activeProgram),n&&t.state.set(n),t.geometry.draw(a,l,c,h??s.instanceCount)}destroy(){this._renderer=null}}Y0.extension={type:[b.WebGLSystem],name:"encoder"};class q0{constructor(e){this._renderer=e}contextChange(){const e=this._renderer.gl;this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=_g(this.maxTextures,e);const t=this._renderer.context.webGLVersion===2;this.maxUniformBindings=t?e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}q0.extension={type:[b.WebGLSystem],name:"limits"};class QI{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this.msaaRenderBuffer=[]}}const Jt=[];Jt[be.NONE]=void 0,Jt[be.DISABLED]={stencilWriteMask:0,stencilReadMask:0},Jt[be.RENDERING_MASK_ADD]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}},Jt[be.RENDERING_MASK_REMOVE]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}},Jt[be.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}},Jt[be.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"keep"},stencilBack:{compare:"not-equal",passOp:"keep"}};class K0{constructor(e){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:be.NONE},this._renderTargetStencilState=Object.create(null),e.renderTarget.onRenderTargetChange.add(this)}contextChange(e){this._gl=e,this._comparisonFuncMapping={always:e.ALWAYS,never:e.NEVER,equal:e.EQUAL,"not-equal":e.NOTEQUAL,less:e.LESS,"less-equal":e.LEQUAL,greater:e.GREATER,"greater-equal":e.GEQUAL},this._stencilOpsMapping={keep:e.KEEP,zero:e.ZERO,replace:e.REPLACE,invert:e.INVERT,"increment-clamp":e.INCR,"decrement-clamp":e.DECR,"increment-wrap":e.INCR_WRAP,"decrement-wrap":e.DECR_WRAP},this.resetState()}onRenderTargetChange(e){if(this._activeRenderTarget===e)return;this._activeRenderTarget=e;let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:be.DISABLED,stencilReference:0}),this.setStencilMode(t.stencilMode,t.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=be.NONE,this._stencilCache.stencilReference=0}setStencilMode(e,t){const s=this._renderTargetStencilState[this._activeRenderTarget.uid],r=this._gl,n=Jt[e],o=this._stencilCache;if(s.stencilMode=e,s.stencilReference=t,e===be.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,r.disable(r.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,r.enable(r.STENCIL_TEST)),(e!==o.stencilMode||o.stencilReference!==t)&&(o.stencilMode=e,o.stencilReference=t,r.stencilFunc(this._comparisonFuncMapping[n.stencilBack.compare],t,255),r.stencilOp(r.KEEP,r.KEEP,this._stencilOpsMapping[n.stencilBack.passOp]))}}K0.extension={type:[b.WebGLSystem],name:"stencil"};class j0{constructor(e){this._syncFunctionHash=Object.create(null),this._adaptor=e,this._systemCheck()}_systemCheck(){if(!Km())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}ensureUniformGroup(e){const t=this.getUniformGroupData(e);e.buffer||(e.buffer=new tt({data:new Float32Array(t.layout.size/4),usage:j.UNIFORM|j.COPY_DST}))}getUniformGroupData(e){return this._syncFunctionHash[e._signature]||this._initUniformGroup(e)}_initUniformGroup(e){const t=e._signature;let s=this._syncFunctionHash[t];if(!s){const r=Object.keys(e.uniformStructures).map(a=>e.uniformStructures[a]),n=this._adaptor.createUboElements(r),o=this._generateUboSync(n.uboElements);s=this._syncFunctionHash[t]={layout:n,syncFunction:o}}return this._syncFunctionHash[t]}_generateUboSync(e){return this._adaptor.generateUboSync(e)}syncUniformGroup(e,t,s){const r=this.getUniformGroupData(e);e.buffer||(e.buffer=new tt({data:new Float32Array(r.layout.size/4),usage:j.UNIFORM|j.COPY_DST}));let n=null;return t||(t=e.buffer.data,n=e.buffer.dataInt32),s||(s=0),r.syncFunction(e.uniforms,t,n,s),!0}updateUniformGroup(e){if(e.isStatic&&!e._dirtyId)return!1;e._dirtyId=0;const t=this.syncUniformGroup(e);return e.buffer.update(),t}destroy(){this._syncFunctionHash=null}}const Z0={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function e3(i){const e=i.map(n=>({data:n,offset:0,size:0})),t=16;let s=0,r=0;for(let n=0;n<e.length;n++){const o=e[n];if(s=Z0[o.data.type],!s)throw new Error(`Unknown type ${o.data.type}`);o.data.size>1&&(s=Math.max(s,t)*o.data.size);const a=s===12?16:s;o.size=s;const l=r%t;l>0&&t-l<a?r+=(t-l)%16:r+=(s-l%s)%s,o.offset=r,r+=s}return r=Math.ceil(r/16)*16,{uboElements:e,size:r}}const gi=[{type:"mat3x3<f32>",test:i=>i.value.a!==void 0,ubo:`
|
|
819
819
|
var matrix = uv[name].toArray(true);
|
|
820
820
|
data[offset] = matrix[0];
|
|
821
821
|
data[offset + 1] = matrix[1];
|
|
@@ -959,7 +959,7 @@ fn mainFragment(
|
|
|
959
959
|
}
|
|
960
960
|
${r!==0?`arrayOffset += ${r};`:""}
|
|
961
961
|
}
|
|
962
|
-
`}function s3(i){return J0(i,"uboStd40",i3,Q0)}class e_ extends j0{constructor(){super({createUboElements:e3,generateUboSync:s3})}}e_.extension={type:[b.WebGLSystem],name:"ubo"};class r3{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new H}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new H}copyToTexture(e,t,s,r,n){const o=this._renderTargetSystem,a=this._renderer,l=o.getGpuRenderTarget(e),c=a.gl;return this.finishRenderPass(e),c.bindFramebuffer(c.FRAMEBUFFER,l.resolveTargetFramebuffer),a.texture.bind(t,0),c.copyTexSubImage2D(c.TEXTURE_2D,0,n.x,n.y,s.x,s.y,r.width,r.height),t}startRenderPass(e,t=!0,s,r){const n=this._renderTargetSystem,o=e.colorTexture,a=n.getGpuRenderTarget(e);let l=r.y;e.isRoot&&(l=o.pixelHeight-r.height),e.colorTextures.forEach(u=>{this._renderer.texture.unbind(u)});const c=this._renderer.gl;c.bindFramebuffer(c.FRAMEBUFFER,a.framebuffer);const h=this._viewPortCache;(h.x!==r.x||h.y!==l||h.width!==r.width||h.height!==r.height)&&(h.x=r.x,h.y=l,h.width=r.width,h.height=r.height,c.viewport(r.x,l,r.width,r.height)),!a.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(a),this.clear(e,t,s)}finishRenderPass(e){const s=this._renderTargetSystem.getGpuRenderTarget(e);if(!s.msaa)return;const r=this._renderer.gl;r.bindFramebuffer(r.FRAMEBUFFER,s.resolveTargetFramebuffer),r.bindFramebuffer(r.READ_FRAMEBUFFER,s.framebuffer),r.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r.COLOR_BUFFER_BIT,r.NEAREST),r.bindFramebuffer(r.FRAMEBUFFER,s.framebuffer)}initGpuRenderTarget(e){const s=this._renderer.gl,r=new QI;return e.colorTexture instanceof Ft?(this._renderer.context.ensureCanvasSize(e.colorTexture.resource),r.framebuffer=null,r):(this._initColor(e,r),s.bindFramebuffer(s.FRAMEBUFFER,null),r)}destroyGpuRenderTarget(e){const t=this._renderer.gl;e.framebuffer&&(t.deleteFramebuffer(e.framebuffer),e.framebuffer=null),e.resolveTargetFramebuffer&&(t.deleteFramebuffer(e.resolveTargetFramebuffer),e.resolveTargetFramebuffer=null),e.depthStencilRenderBuffer&&(t.deleteRenderbuffer(e.depthStencilRenderBuffer),e.depthStencilRenderBuffer=null),e.msaaRenderBuffer.forEach(s=>{t.deleteRenderbuffer(s)}),e.msaaRenderBuffer=null}clear(e,t,s){if(!t)return;const r=this._renderTargetSystem;typeof t=="boolean"&&(t=t?et.ALL:et.NONE);const n=this._renderer.gl;if(t&et.COLOR){s??(s=r.defaultClearColor);const o=this._clearColorCache,a=s;(o[0]!==a[0]||o[1]!==a[1]||o[2]!==a[2]||o[3]!==a[3])&&(o[0]=a[0],o[1]=a[1],o[2]=a[2],o[3]=a[3],n.clearColor(a[0],a[1],a[2],a[3]))}n.clear(t)}resizeGpuRenderTarget(e){if(e.isRoot)return;const s=this._renderTargetSystem.getGpuRenderTarget(e);this._resizeColor(e,s),(e.stencil||e.depth)&&this._resizeStencil(s)}_initColor(e,t){const s=this._renderer,r=s.gl,n=r.createFramebuffer();if(t.resolveTargetFramebuffer=n,r.bindFramebuffer(r.FRAMEBUFFER,n),t.width=e.colorTexture.source.pixelWidth,t.height=e.colorTexture.source.pixelHeight,e.colorTextures.forEach((o,a)=>{const l=o.source;l.antialias&&(s.context.supports.msaa?t.msaa=!0:L("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),s.texture.bindSource(l,0);const h=s.texture.getGlSource(l).texture;r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+a,3553,h,0)}),t.msaa){const o=r.createFramebuffer();t.framebuffer=o,r.bindFramebuffer(r.FRAMEBUFFER,o),e.colorTextures.forEach((a,l)=>{const c=r.createRenderbuffer();t.msaaRenderBuffer[l]=c})}else t.framebuffer=n;this._resizeColor(e,t)}_resizeColor(e,t){const s=e.colorTexture.source;if(t.width=s.pixelWidth,t.height=s.pixelHeight,e.colorTextures.forEach((r,n)=>{n!==0&&r.source.resize(s.width,s.height,s._resolution)}),t.msaa){const r=this._renderer,n=r.gl,o=t.framebuffer;n.bindFramebuffer(n.FRAMEBUFFER,o),e.colorTextures.forEach((a,l)=>{const c=a.source;r.texture.bindSource(c,0);const u=r.texture.getGlSource(c).internalFormat,d=t.msaaRenderBuffer[l];n.bindRenderbuffer(n.RENDERBUFFER,d),n.renderbufferStorageMultisample(n.RENDERBUFFER,4,u,c.pixelWidth,c.pixelHeight),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+l,n.RENDERBUFFER,d)})}}_initStencil(e){if(e.framebuffer===null)return;const t=this._renderer.gl,s=t.createRenderbuffer();e.depthStencilRenderBuffer=s,t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,s),this._resizeStencil(e)}_resizeStencil(e){const t=this._renderer.gl;t.bindRenderbuffer(t.RENDERBUFFER,e.depthStencilRenderBuffer),e.msaa?t.renderbufferStorageMultisample(t.RENDERBUFFER,4,t.DEPTH24_STENCIL8,e.width,e.height):t.renderbufferStorage(t.RENDERBUFFER,this._renderer.context.webGLVersion===2?t.DEPTH24_STENCIL8:t.DEPTH_STENCIL,e.width,e.height)}prerender(e){const t=e.colorTexture.resource;this._renderer.context.multiView&&Ft.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(this._renderer.context.multiView&&Ft.test(e.colorTexture.resource)){const t=this._renderer.context.canvas,s=e.colorTexture;s.context2D.drawImage(t,0,s.pixelHeight-t.height)}}}function n3(i,e,t,s,r,n){const o=n?1:-1;return i.identity(),i.a=1/s*2,i.d=o*(1/r*2),i.tx=-1-e*i.a,i.ty=-o-t*i.d,i}const qi=new Map;Bi.register(qi);function t_(i,e){if(!qi.has(i)){const t=new M({source:new Ft({resource:i,...e})}),s=()=>{qi.get(i)===t&&qi.delete(i)};t.once("destroy",s),t.source.once("destroy",s),qi.set(i,t)}return qi.get(i)}function o3(i){const e=i.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}const i_=class hy{constructor(e={}){if(this.uid=he("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,e={...hy.defaultOptions,...e},this.stencil=e.stencil,this.depth=e.depth,this.isRoot=e.isRoot,typeof e.colorTextures=="number"){this._managedColorTextures=!0;for(let t=0;t<e.colorTextures;t++)this.colorTextures.push(new Ee({width:e.width,height:e.height,resolution:e.resolution,antialias:e.antialias}))}else{this.colorTextures=[...e.colorTextures.map(s=>s.source)];const t=this.colorTexture.source;this.resize(t.width,t.height,t._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(e.depthStencilTexture||this.stencil)&&(e.depthStencilTexture instanceof M||e.depthStencilTexture instanceof Ee?this.depthStencilTexture=e.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new Ee({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(e,t,s=this.resolution,r=!1){this.dirtyId++,this.colorTextures.forEach((n,o)=>{r&&o===0||n.source.resize(e,t,s)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(e,t,s)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(e=>{e.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};i_.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let Pd=i_;class s_{constructor(e){this.rootViewPort=new H,this.viewport=new H,this.onRenderTargetChange=new ig("onRenderTargetChange"),this.projectionMatrix=new O,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=e,e.renderableGC.addManagedHash(this,"_gpuRenderTargetHash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:e,clear:t,clearColor:s,frame:r}){this._renderTargetStack.length=0,this.push(e,t,s,r),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=o3(this.rootRenderTarget),this.adaptor.prerender?.(this.rootRenderTarget)}postrender(){this.adaptor.postrender?.(this.rootRenderTarget)}bind(e,t=!0,s,r){const n=this.getRenderTarget(e),o=this.renderTarget!==n;this.renderTarget=n,this.renderSurface=e;const a=this.getGpuRenderTarget(n);(n.pixelWidth!==a.width||n.pixelHeight!==a.height)&&(this.adaptor.resizeGpuRenderTarget(n),a.width=n.pixelWidth,a.height=n.pixelHeight);const l=n.colorTexture,c=this.viewport,h=l.pixelWidth,u=l.pixelHeight;if(!r&&e instanceof M&&(r=e.frame),r){const d=l._resolution;c.x=r.x*d+.5|0,c.y=r.y*d+.5|0,c.width=r.width*d+.5|0,c.height=r.height*d+.5|0}else c.x=0,c.y=0,c.width=h,c.height=u;return n3(this.projectionMatrix,0,0,c.width/l.resolution,c.height/l.resolution,!n.isRoot),this.adaptor.startRenderPass(n,t,s,c),o&&this.onRenderTargetChange.emit(n),n}clear(e,t=et.ALL,s){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,s,this.viewport))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=et.ALL,s,r){const n=this.bind(e,t,s,r);return this._renderTargetStack.push({renderTarget:n,frame:r}),n}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(e.renderTarget,!1,null,e.frame)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,s,r,n){s.x<0&&(r.width+=s.x,n.x-=s.x,s.x=0),s.y<0&&(r.height+=s.y,n.y-=s.y,s.y=0);const{pixelWidth:o,pixelHeight:a}=e;return r.width=Math.min(r.width,o-s.x),r.height=Math.min(r.height,a-s.y),this.adaptor.copyToTexture(e,t,s,r,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t&&e.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;return Ft.test(e)&&(e=t_(e).source),e instanceof Pd?t=e:e instanceof Ee&&(t=new Pd({colorTextures:[e]}),e.source instanceof Ft&&(t.isRoot=!0),e.once("destroy",()=>{t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e);const s=this._gpuRenderTargetHash[t.uid];s&&(this._gpuRenderTargetHash[t.uid]=null,this.adaptor.destroyGpuRenderTarget(s))})),this._renderSurfaceToRenderTargetHash.set(e,t),t}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this.renderSurface=null}}class r_ extends s_{constructor(e){super(e),this.adaptor=new r3,this.adaptor.init(e,this)}}r_.extension={type:[b.WebGLSystem],name:"renderTarget"};class Rd extends je{constructor({buffer:e,offset:t,size:s}){super(),this.uid=he("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=he("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=s,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=he("resource"),this.emit("change",this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}function a3(i,e){const t=[],s=[`
|
|
962
|
+
`}function s3(i){return J0(i,"uboStd40",i3,Q0)}class ex extends j0{constructor(){super({createUboElements:e3,generateUboSync:s3})}}ex.extension={type:[b.WebGLSystem],name:"ubo"};class r3{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new H}init(e,t){this._renderer=e,this._renderTargetSystem=t,e.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new H}copyToTexture(e,t,s,r,n){const o=this._renderTargetSystem,a=this._renderer,l=o.getGpuRenderTarget(e),c=a.gl;return this.finishRenderPass(e),c.bindFramebuffer(c.FRAMEBUFFER,l.resolveTargetFramebuffer),a.texture.bind(t,0),c.copyTexSubImage2D(c.TEXTURE_2D,0,n.x,n.y,s.x,s.y,r.width,r.height),t}startRenderPass(e,t=!0,s,r){const n=this._renderTargetSystem,o=e.colorTexture,a=n.getGpuRenderTarget(e);let l=r.y;e.isRoot&&(l=o.pixelHeight-r.height),e.colorTextures.forEach(u=>{this._renderer.texture.unbind(u)});const c=this._renderer.gl;c.bindFramebuffer(c.FRAMEBUFFER,a.framebuffer);const h=this._viewPortCache;(h.x!==r.x||h.y!==l||h.width!==r.width||h.height!==r.height)&&(h.x=r.x,h.y=l,h.width=r.width,h.height=r.height,c.viewport(r.x,l,r.width,r.height)),!a.depthStencilRenderBuffer&&(e.stencil||e.depth)&&this._initStencil(a),this.clear(e,t,s)}finishRenderPass(e){const s=this._renderTargetSystem.getGpuRenderTarget(e);if(!s.msaa)return;const r=this._renderer.gl;r.bindFramebuffer(r.FRAMEBUFFER,s.resolveTargetFramebuffer),r.bindFramebuffer(r.READ_FRAMEBUFFER,s.framebuffer),r.blitFramebuffer(0,0,s.width,s.height,0,0,s.width,s.height,r.COLOR_BUFFER_BIT,r.NEAREST),r.bindFramebuffer(r.FRAMEBUFFER,s.framebuffer)}initGpuRenderTarget(e){const s=this._renderer.gl,r=new QI;return e.colorTexture instanceof Ft?(this._renderer.context.ensureCanvasSize(e.colorTexture.resource),r.framebuffer=null,r):(this._initColor(e,r),s.bindFramebuffer(s.FRAMEBUFFER,null),r)}destroyGpuRenderTarget(e){const t=this._renderer.gl;e.framebuffer&&(t.deleteFramebuffer(e.framebuffer),e.framebuffer=null),e.resolveTargetFramebuffer&&(t.deleteFramebuffer(e.resolveTargetFramebuffer),e.resolveTargetFramebuffer=null),e.depthStencilRenderBuffer&&(t.deleteRenderbuffer(e.depthStencilRenderBuffer),e.depthStencilRenderBuffer=null),e.msaaRenderBuffer.forEach(s=>{t.deleteRenderbuffer(s)}),e.msaaRenderBuffer=null}clear(e,t,s){if(!t)return;const r=this._renderTargetSystem;typeof t=="boolean"&&(t=t?et.ALL:et.NONE);const n=this._renderer.gl;if(t&et.COLOR){s??(s=r.defaultClearColor);const o=this._clearColorCache,a=s;(o[0]!==a[0]||o[1]!==a[1]||o[2]!==a[2]||o[3]!==a[3])&&(o[0]=a[0],o[1]=a[1],o[2]=a[2],o[3]=a[3],n.clearColor(a[0],a[1],a[2],a[3]))}n.clear(t)}resizeGpuRenderTarget(e){if(e.isRoot)return;const s=this._renderTargetSystem.getGpuRenderTarget(e);this._resizeColor(e,s),(e.stencil||e.depth)&&this._resizeStencil(s)}_initColor(e,t){const s=this._renderer,r=s.gl,n=r.createFramebuffer();if(t.resolveTargetFramebuffer=n,r.bindFramebuffer(r.FRAMEBUFFER,n),t.width=e.colorTexture.source.pixelWidth,t.height=e.colorTexture.source.pixelHeight,e.colorTextures.forEach((o,a)=>{const l=o.source;l.antialias&&(s.context.supports.msaa?t.msaa=!0:L("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),s.texture.bindSource(l,0);const h=s.texture.getGlSource(l).texture;r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+a,3553,h,0)}),t.msaa){const o=r.createFramebuffer();t.framebuffer=o,r.bindFramebuffer(r.FRAMEBUFFER,o),e.colorTextures.forEach((a,l)=>{const c=r.createRenderbuffer();t.msaaRenderBuffer[l]=c})}else t.framebuffer=n;this._resizeColor(e,t)}_resizeColor(e,t){const s=e.colorTexture.source;if(t.width=s.pixelWidth,t.height=s.pixelHeight,e.colorTextures.forEach((r,n)=>{n!==0&&r.source.resize(s.width,s.height,s._resolution)}),t.msaa){const r=this._renderer,n=r.gl,o=t.framebuffer;n.bindFramebuffer(n.FRAMEBUFFER,o),e.colorTextures.forEach((a,l)=>{const c=a.source;r.texture.bindSource(c,0);const u=r.texture.getGlSource(c).internalFormat,d=t.msaaRenderBuffer[l];n.bindRenderbuffer(n.RENDERBUFFER,d),n.renderbufferStorageMultisample(n.RENDERBUFFER,4,u,c.pixelWidth,c.pixelHeight),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+l,n.RENDERBUFFER,d)})}}_initStencil(e){if(e.framebuffer===null)return;const t=this._renderer.gl,s=t.createRenderbuffer();e.depthStencilRenderBuffer=s,t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,s),this._resizeStencil(e)}_resizeStencil(e){const t=this._renderer.gl;t.bindRenderbuffer(t.RENDERBUFFER,e.depthStencilRenderBuffer),e.msaa?t.renderbufferStorageMultisample(t.RENDERBUFFER,4,t.DEPTH24_STENCIL8,e.width,e.height):t.renderbufferStorage(t.RENDERBUFFER,this._renderer.context.webGLVersion===2?t.DEPTH24_STENCIL8:t.DEPTH_STENCIL,e.width,e.height)}prerender(e){const t=e.colorTexture.resource;this._renderer.context.multiView&&Ft.test(t)&&this._renderer.context.ensureCanvasSize(t)}postrender(e){if(this._renderer.context.multiView&&Ft.test(e.colorTexture.resource)){const t=this._renderer.context.canvas,s=e.colorTexture;s.context2D.drawImage(t,0,s.pixelHeight-t.height)}}}function n3(i,e,t,s,r,n){const o=n?1:-1;return i.identity(),i.a=1/s*2,i.d=o*(1/r*2),i.tx=-1-e*i.a,i.ty=-o-t*i.d,i}const qi=new Map;Bi.register(qi);function tx(i,e){if(!qi.has(i)){const t=new M({source:new Ft({resource:i,...e})}),s=()=>{qi.get(i)===t&&qi.delete(i)};t.once("destroy",s),t.source.once("destroy",s),qi.set(i,t)}return qi.get(i)}function o3(i){const e=i.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}const ix=class hy{constructor(e={}){if(this.uid=he("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,e={...hy.defaultOptions,...e},this.stencil=e.stencil,this.depth=e.depth,this.isRoot=e.isRoot,typeof e.colorTextures=="number"){this._managedColorTextures=!0;for(let t=0;t<e.colorTextures;t++)this.colorTextures.push(new Ee({width:e.width,height:e.height,resolution:e.resolution,antialias:e.antialias}))}else{this.colorTextures=[...e.colorTextures.map(s=>s.source)];const t=this.colorTexture.source;this.resize(t.width,t.height,t._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(e.depthStencilTexture||this.stencil)&&(e.depthStencilTexture instanceof M||e.depthStencilTexture instanceof Ee?this.depthStencilTexture=e.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new Ee({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(e,t,s=this.resolution,r=!1){this.dirtyId++,this.colorTextures.forEach((n,o)=>{r&&o===0||n.source.resize(e,t,s)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(e,t,s)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(e=>{e.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};ix.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let Pd=ix;class sx{constructor(e){this.rootViewPort=new H,this.viewport=new H,this.onRenderTargetChange=new ig("onRenderTargetChange"),this.projectionMatrix=new O,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=e,e.renderableGC.addManagedHash(this,"_gpuRenderTargetHash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:e,clear:t,clearColor:s,frame:r}){this._renderTargetStack.length=0,this.push(e,t,s,r),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=o3(this.rootRenderTarget),this.adaptor.prerender?.(this.rootRenderTarget)}postrender(){this.adaptor.postrender?.(this.rootRenderTarget)}bind(e,t=!0,s,r){const n=this.getRenderTarget(e),o=this.renderTarget!==n;this.renderTarget=n,this.renderSurface=e;const a=this.getGpuRenderTarget(n);(n.pixelWidth!==a.width||n.pixelHeight!==a.height)&&(this.adaptor.resizeGpuRenderTarget(n),a.width=n.pixelWidth,a.height=n.pixelHeight);const l=n.colorTexture,c=this.viewport,h=l.pixelWidth,u=l.pixelHeight;if(!r&&e instanceof M&&(r=e.frame),r){const d=l._resolution;c.x=r.x*d+.5|0,c.y=r.y*d+.5|0,c.width=r.width*d+.5|0,c.height=r.height*d+.5|0}else c.x=0,c.y=0,c.width=h,c.height=u;return n3(this.projectionMatrix,0,0,c.width/l.resolution,c.height/l.resolution,!n.isRoot),this.adaptor.startRenderPass(n,t,s,c),o&&this.onRenderTargetChange.emit(n),n}clear(e,t=et.ALL,s){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,s,this.viewport))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=et.ALL,s,r){const n=this.bind(e,t,s,r);return this._renderTargetStack.push({renderTarget:n,frame:r}),n}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(e.renderTarget,!1,null,e.frame)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,s,r,n){s.x<0&&(r.width+=s.x,n.x-=s.x,s.x=0),s.y<0&&(r.height+=s.y,n.y-=s.y,s.y=0);const{pixelWidth:o,pixelHeight:a}=e;return r.width=Math.min(r.width,o-s.x),r.height=Math.min(r.height,a-s.y),this.adaptor.copyToTexture(e,t,s,r,n)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t&&e.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;return Ft.test(e)&&(e=tx(e).source),e instanceof Pd?t=e:e instanceof Ee&&(t=new Pd({colorTextures:[e]}),e.source instanceof Ft&&(t.isRoot=!0),e.once("destroy",()=>{t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e);const s=this._gpuRenderTargetHash[t.uid];s&&(this._gpuRenderTargetHash[t.uid]=null,this.adaptor.destroyGpuRenderTarget(s))})),this._renderSurfaceToRenderTargetHash.set(e,t),t}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this.renderSurface=null}}class rx extends sx{constructor(e){super(e),this.adaptor=new r3,this.adaptor.init(e,this)}}rx.extension={type:[b.WebGLSystem],name:"renderTarget"};class Rd extends je{constructor({buffer:e,offset:t,size:s}){super(),this.uid=he("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=he("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=e,this.offset=t|0,this.size=s,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=he("resource"),this.emit("change",this)}destroy(e=!1){this.destroyed=!0,e&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}function a3(i,e){const t=[],s=[`
|
|
963
963
|
var g = s.groups;
|
|
964
964
|
var sS = r.shader;
|
|
965
965
|
var p = s.glProgram;
|
|
@@ -986,10 +986,10 @@ fn mainFragment(
|
|
|
986
986
|
`)),e._gl.uniform1i(f.location,n),t.push(`
|
|
987
987
|
tS.bind(resources[${h}], ${n});
|
|
988
988
|
`),n++)}}}const a=[...s,...t].join(`
|
|
989
|
-
`);return new Function("r","s","sD",a)}class l3{constructor(e,t){this.program=e,this.uniformData=t,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function
|
|
989
|
+
`);return new Function("r","s","sD",a)}class l3{constructor(e,t){this.program=e,this.uniformData=t,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function nx(i,e,t){const s=i.createShader(e);return i.shaderSource(s,t),i.compileShader(s),s}function Md(i){const e=new Array(i);for(let t=0;t<e.length;t++)e[t]=!1;return e}function ox(i,e){switch(i){case"float":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return Md(2*e);case"bvec3":return Md(3*e);case"bvec4":return Md(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}let hn=null;const ax={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"},c3={float:"float32",vec2:"float32x2",vec3:"float32x3",vec4:"float32x4",int:"sint32",ivec2:"sint32x2",ivec3:"sint32x3",ivec4:"sint32x4",uint:"uint32",uvec2:"uint32x2",uvec3:"uint32x3",uvec4:"uint32x4",bool:"uint32",bvec2:"uint32x2",bvec3:"uint32x3",bvec4:"uint32x4"};function lx(i,e){if(!hn){const t=Object.keys(ax);hn={};for(let s=0;s<t.length;++s){const r=t[s];hn[i[r]]=ax[r]}}return hn[e]}function h3(i,e){const t=lx(i,e);return c3[t]||"float32"}function u3(i,e,t=!1){const s={},r=e.getProgramParameter(i,e.ACTIVE_ATTRIBUTES);for(let o=0;o<r;o++){const a=e.getActiveAttrib(i,o);if(a.name.startsWith("gl_"))continue;const l=h3(e,a.type);s[a.name]={location:0,format:l,stride:jt(l).stride,offset:0,instance:!1,start:0}}const n=Object.keys(s);if(t){n.sort((o,a)=>o>a?1:-1);for(let o=0;o<n.length;o++)s[n[o]].location=o,e.bindAttribLocation(i,o,n[o]);e.linkProgram(i)}else for(let o=0;o<n.length;o++)s[n[o]].location=e.getAttribLocation(i,n[o]);return s}function d3(i,e){if(!e.ACTIVE_UNIFORM_BLOCKS)return{};const t={},s=e.getProgramParameter(i,e.ACTIVE_UNIFORM_BLOCKS);for(let r=0;r<s;r++){const n=e.getActiveUniformBlockName(i,r),o=e.getUniformBlockIndex(i,n),a=e.getActiveUniformBlockParameter(i,r,e.UNIFORM_BLOCK_DATA_SIZE);t[n]={name:n,index:o,size:a}}return t}function f3(i,e){const t={},s=e.getProgramParameter(i,e.ACTIVE_UNIFORMS);for(let r=0;r<s;r++){const n=e.getActiveUniform(i,r),o=n.name.replace(/\[.*?\]$/,""),a=!!n.name.match(/\[.*?\]$/),l=lx(e,n.type);t[o]={name:o,index:r,type:l,size:n.size,isArray:a,value:ox(l,n.size)}}return t}function cx(i,e){const t=i.getShaderSource(e).split(`
|
|
990
990
|
`).map((c,h)=>`${h}: ${c}`),s=i.getShaderInfoLog(e),r=s.split(`
|
|
991
991
|
`),n={},o=r.map(c=>parseFloat(c.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(c=>c&&!n[c]?(n[c]=!0,!0):!1),a=[""];o.forEach(c=>{t[c-1]=`%c${t[c-1]}%c`,a.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const l=t.join(`
|
|
992
|
-
`);a[0]=l,console.error(s),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}function p3(i,e,t,s){i.getProgramParameter(e,i.LINK_STATUS)||(i.getShaderParameter(t,i.COMPILE_STATUS)||
|
|
992
|
+
`);a[0]=l,console.error(s),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}function p3(i,e,t,s){i.getProgramParameter(e,i.LINK_STATUS)||(i.getShaderParameter(t,i.COMPILE_STATUS)||cx(i,t),i.getShaderParameter(s,i.COMPILE_STATUS)||cx(i,s),console.error("PixiJS Error: Could not initialize shader."),i.getProgramInfoLog(e)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",i.getProgramInfoLog(e)))}function m3(i,e){const t=nx(i,i.VERTEX_SHADER,e.vertex),s=nx(i,i.FRAGMENT_SHADER,e.fragment),r=i.createProgram();i.attachShader(r,t),i.attachShader(r,s);const n=e.transformFeedbackVaryings;n&&(typeof i.transformFeedbackVaryings!="function"?L("TransformFeedback is not supported but TransformFeedbackVaryings are given."):i.transformFeedbackVaryings(r,n.names,n.bufferMode==="separate"?i.SEPARATE_ATTRIBS:i.INTERLEAVED_ATTRIBS)),i.linkProgram(r),i.getProgramParameter(r,i.LINK_STATUS)||p3(i,r,t,s),e._attributeData=u3(r,i,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertex)),e._uniformData=f3(r,i),e._uniformBlockData=d3(r,i),i.deleteShader(t),i.deleteShader(s);const o={};for(const l in e._uniformData){const c=e._uniformData[l];o[l]={location:i.getUniformLocation(r,l),value:ox(c.type,c.size)}}return new l3(r,o)}const un={textureCount:0,blockIndex:0};class hx{constructor(e){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_programDataHash")}contextChange(e){this._gl=e,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(e,t){if(this._setProgram(e.glProgram),t)return;un.textureCount=0,un.blockIndex=0;let s=this._shaderSyncFunctions[e.glProgram._key];s||(s=this._shaderSyncFunctions[e.glProgram._key]=this._generateShaderSync(e,this)),this._renderer.buffer.nextBindBase(!!e.glProgram.transformFeedbackVaryings),s(this._renderer,e,un)}updateUniformGroup(e){this._renderer.uniformGroup.updateUniformGroup(e,this._activeProgram,un)}bindUniformBlock(e,t,s=0){const r=this._renderer.buffer,n=this._getProgramData(this._activeProgram),o=e._bufferResource;o||this._renderer.ubo.updateUniformGroup(e);const a=e.buffer,l=r.updateBuffer(a),c=r.freeLocationForBufferBase(l);if(o){const{offset:u,size:d}=e;u===0&&d===a.data.byteLength?r.bindBufferBase(l,c):r.bindBufferRange(l,c,u)}else r.getLastBindBaseLocation(l)!==c&&r.bindBufferBase(l,c);const h=this._activeProgram._uniformBlockData[t].index;n.uniformBlockBindings[s]!==c&&(n.uniformBlockBindings[s]=c,this._renderer.gl.uniformBlockBinding(n.program,h,c))}_setProgram(e){if(this._activeProgram===e)return;this._activeProgram=e;const t=this._getProgramData(e);this._gl.useProgram(t.program)}_getProgramData(e){return this._programDataHash[e._key]||this._createProgramData(e)}_createProgramData(e){const t=e._key;return this._programDataHash[t]=m3(this._gl,e),this._programDataHash[t]}destroy(){for(const e of Object.keys(this._programDataHash))this._programDataHash[e].destroy(),this._programDataHash[e]=null;this._programDataHash=null,this._shaderSyncFunctions=null,this._activeProgram=null,this._renderer=null,this._gl=null}_generateShaderSync(e,t){return a3(e,t)}resetState(){this._activeProgram=null}}hx.extension={type:[b.WebGLSystem],name:"shader"};const g3={f32:`if (cv !== v) {
|
|
993
993
|
cu.value = v;
|
|
994
994
|
gl.uniform1f(location, v);
|
|
995
995
|
}`,"vec2<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
@@ -1061,7 +1061,7 @@ fn mainFragment(
|
|
|
1061
1061
|
cv[2] = v[2];
|
|
1062
1062
|
cv[3] = v[3];
|
|
1063
1063
|
gl.uniform4i(location, v[0], v[1], v[2], v[3]);
|
|
1064
|
-
}`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},
|
|
1064
|
+
}`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},x3={f32:"gl.uniform1fv(location, v);","vec2<f32>":"gl.uniform2fv(location, v);","vec3<f32>":"gl.uniform3fv(location, v);","vec4<f32>":"gl.uniform4fv(location, v);","mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2<i32>":"gl.uniform2iv(location, v);","vec3<i32>":"gl.uniform3iv(location, v);","vec4<i32>":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2<u32>":"gl.uniform2iv(location, v);","vec3<u32>":"gl.uniform3iv(location, v);","vec4<u32>":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2<bool>":"gl.uniform2iv(location, v);","vec3<bool>":"gl.uniform3iv(location, v);","vec4<bool>":"gl.uniform4iv(location, v);"};function _3(i,e){const t=[`
|
|
1065
1065
|
var v = null;
|
|
1066
1066
|
var cv = null;
|
|
1067
1067
|
var cu = null;
|
|
@@ -1074,14 +1074,14 @@ fn mainFragment(
|
|
|
1074
1074
|
renderer.shader.updateUniformGroup(uv.${s});
|
|
1075
1075
|
`):i.uniforms[s]instanceof Rd&&t.push(`
|
|
1076
1076
|
renderer.shader.bindBufferResource(uv.${s}, "${s}");
|
|
1077
|
-
`);continue}const r=i.uniformStructures[s];let n=!1;for(let o=0;o<gi.length;o++){const a=gi[o];if(r.type===a.type&&a.test(r)){t.push(`name = "${s}";`,gi[o].uniform),n=!0;break}}if(!n){const a=(r.size===1?g3:
|
|
1077
|
+
`);continue}const r=i.uniformStructures[s];let n=!1;for(let o=0;o<gi.length;o++){const a=gi[o];if(r.type===a.type&&a.test(r)){t.push(`name = "${s}";`,gi[o].uniform),n=!0;break}}if(!n){const a=(r.size===1?g3:x3)[r.type].replace("location",`ud["${s}"].location`);t.push(`
|
|
1078
1078
|
cu = ud["${s}"];
|
|
1079
1079
|
cv = cu.value;
|
|
1080
1080
|
v = uv["${s}"];
|
|
1081
1081
|
${a};`)}}return new Function("ud","uv","renderer","syncData",t.join(`
|
|
1082
|
-
`))}class u_{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,s){const r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,s))}_getUniformSyncFunction(e,t){return this._uniformGroupSyncHash[e._signature]?.[t._key]||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const s=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,"u");return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),s[t._key]=this._cache[r],s[t._key]}_generateUniformsSync(e,t){return x3(e,t)}_getSignature(e,t,s){const r=e.uniforms,n=[`${s}-`];for(const o in r)n.push(o),t[o]&&n.push(t[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}u_.extension={type:[b.WebGLSystem],name:"uniformGroup"};function y3(i){const e={};if(e.normal=[i.ONE,i.ONE_MINUS_SRC_ALPHA],e.add=[i.ONE,i.ONE],e.multiply=[i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.screen=[i.ONE,i.ONE_MINUS_SRC_COLOR,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[i.SRC_ALPHA,i.ONE,i.ONE,i.ONE],e["screen-npm"]=[i.SRC_ALPHA,i.ONE_MINUS_SRC_COLOR,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.erase=[i.ZERO,i.ONE_MINUS_SRC_ALPHA],!(i instanceof Y.get().getWebGLRenderingContext()))e.min=[i.ONE,i.ONE,i.ONE,i.ONE,i.MIN,i.MIN],e.max=[i.ONE,i.ONE,i.ONE,i.ONE,i.MAX,i.MAX];else{const s=i.getExtension("EXT_blend_minmax");s&&(e.min=[i.ONE,i.ONE,i.ONE,i.ONE,s.MIN_EXT,s.MIN_EXT],e.max=[i.ONE,i.ONE,i.ONE,i.ONE,s.MAX_EXT,s.MAX_EXT])}return e}const v3=0,b3=1,T3=2,w3=3,S3=4,C3=5,d_=class df{constructor(e){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[v3]=this.setBlend,this.map[b3]=this.setOffset,this.map[T3]=this.setCullFace,this.map[w3]=this.setDepthTest,this.map[S3]=this.setFrontFace,this.map[C3]=this.setDepthMask,this.checks=[],this.defaultState=ft.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=!e.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=y3(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,s=0;for(;t;)t&1&&this.map[s].call(this,!!(e.data&1<<s)),t>>=1,s++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||(e=this.defaultState);for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(e){this._updateCheck(df._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck(df._checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}setCullFace(e){this._cullFace=e,this.gl[e?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;const t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?"CW":"CCW"]))}setBlendMode(e){if(this.blendModesMap[e]||(e="normal"),e===this.blendMode)return;this.blendMode=e;const t=this.blendModesMap[e],s=this.gl;t.length===2?s.blendFunc(t[0],t[1]):s.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,s.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,s.blendEquationSeparate(s.FUNC_ADD,s.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(e,t){const s=this.checks.indexOf(e);t&&s===-1?this.checks.push(e):!t&&s!==-1&&this.checks.splice(s,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};d_.extension={type:[b.WebGLSystem],name:"state"};let A3=d_;class E3{constructor(e){this.target=W0.TEXTURE_2D,this.texture=e,this.width=-1,this.height=-1,this.type=te.UNSIGNED_BYTE,this.internalFormat=Ed.RGBA,this.format=Ed.RGBA,this.samplerType=0}}const I3={id:"buffer",upload(i,e,t){e.width===i.width||e.height===i.height?t.texSubImage2D(t.TEXTURE_2D,0,0,0,i.width,i.height,e.format,e.type,i.resource):t.texImage2D(e.target,0,e.internalFormat,i.width,i.height,0,e.format,e.type,i.resource),e.width=i.width,e.height=i.height}},P3={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},R3={id:"compressed",upload(i,e,t){t.pixelStorei(t.UNPACK_ALIGNMENT,4);let s=i.pixelWidth,r=i.pixelHeight;const n=!!P3[i.format];for(let o=0;o<i.resource.length;o++){const a=i.resource[o];n?t.compressedTexImage2D(t.TEXTURE_2D,o,e.internalFormat,s,r,0,a):t.texImage2D(t.TEXTURE_2D,o,e.internalFormat,s,r,0,e.format,e.type,a),s=Math.max(s>>1,1),r=Math.max(r>>1,1)}}},f_={id:"image",upload(i,e,t,s){const r=e.width,n=e.height,o=i.pixelWidth,a=i.pixelHeight,l=i.resourceWidth,c=i.resourceHeight;l<o||c<a?((r!==o||n!==a)&&t.texImage2D(e.target,0,e.internalFormat,o,a,0,e.format,e.type,null),s===2?t.texSubImage2D(t.TEXTURE_2D,0,0,0,l,c,e.format,e.type,i.resource):t.texSubImage2D(t.TEXTURE_2D,0,0,0,e.format,e.type,i.resource)):r===o&&n===a?t.texSubImage2D(t.TEXTURE_2D,0,0,0,e.format,e.type,i.resource):s===2?t.texImage2D(e.target,0,e.internalFormat,o,a,0,e.format,e.type,i.resource):t.texImage2D(e.target,0,e.internalFormat,e.format,e.type,i.resource),e.width=o,e.height=a}},M3={id:"video",upload(i,e,t,s){if(!i.isValid){t.texImage2D(e.target,0,e.internalFormat,1,1,0,e.format,e.type,null);return}f_.upload(i,e,t,s)}},p_={linear:9729,nearest:9728},k3={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},kd={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},F3={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function m_(i,e,t,s,r,n,o,a){const l=n;if(!a||i.addressModeU!=="repeat"||i.addressModeV!=="repeat"||i.addressModeW!=="repeat"){const c=kd[o?"clamp-to-edge":i.addressModeU],h=kd[o?"clamp-to-edge":i.addressModeV],u=kd[o?"clamp-to-edge":i.addressModeW];e[r](l,e.TEXTURE_WRAP_S,c),e[r](l,e.TEXTURE_WRAP_T,h),e.TEXTURE_WRAP_R&&e[r](l,e.TEXTURE_WRAP_R,u)}if((!a||i.magFilter!=="linear")&&e[r](l,e.TEXTURE_MAG_FILTER,p_[i.magFilter]),t){if(!a||i.mipmapFilter!=="linear"){const c=k3[i.minFilter][i.mipmapFilter];e[r](l,e.TEXTURE_MIN_FILTER,c)}}else e[r](l,e.TEXTURE_MIN_FILTER,p_[i.minFilter]);if(s&&i.maxAnisotropy>1){const c=Math.min(i.maxAnisotropy,e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[r](l,s.TEXTURE_MAX_ANISOTROPY_EXT,c)}i.compare&&e[r](l,e.TEXTURE_COMPARE_FUNC,F3[i.compare])}function B3(i){return{r8unorm:i.RED,r8snorm:i.RED,r8uint:i.RED,r8sint:i.RED,r16uint:i.RED,r16sint:i.RED,r16float:i.RED,rg8unorm:i.RG,rg8snorm:i.RG,rg8uint:i.RG,rg8sint:i.RG,r32uint:i.RED,r32sint:i.RED,r32float:i.RED,rg16uint:i.RG,rg16sint:i.RG,rg16float:i.RG,rgba8unorm:i.RGBA,"rgba8unorm-srgb":i.RGBA,rgba8snorm:i.RGBA,rgba8uint:i.RGBA,rgba8sint:i.RGBA,bgra8unorm:i.RGBA,"bgra8unorm-srgb":i.RGBA,rgb9e5ufloat:i.RGB,rgb10a2unorm:i.RGBA,rg11b10ufloat:i.RGB,rg32uint:i.RG,rg32sint:i.RG,rg32float:i.RG,rgba16uint:i.RGBA,rgba16sint:i.RGBA,rgba16float:i.RGBA,rgba32uint:i.RGBA,rgba32sint:i.RGBA,rgba32float:i.RGBA,stencil8:i.STENCIL_INDEX8,depth16unorm:i.DEPTH_COMPONENT,depth24plus:i.DEPTH_COMPONENT,"depth24plus-stencil8":i.DEPTH_STENCIL,depth32float:i.DEPTH_COMPONENT,"depth32float-stencil8":i.DEPTH_STENCIL}}function U3(i,e){let t={},s=i.RGBA;return i instanceof Y.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":i.SRGB8_ALPHA8,"bgra8unorm-srgb":i.SRGB8_ALPHA8},s=i.RGBA8),{r8unorm:i.R8,r8snorm:i.R8_SNORM,r8uint:i.R8UI,r8sint:i.R8I,r16uint:i.R16UI,r16sint:i.R16I,r16float:i.R16F,rg8unorm:i.RG8,rg8snorm:i.RG8_SNORM,rg8uint:i.RG8UI,rg8sint:i.RG8I,r32uint:i.R32UI,r32sint:i.R32I,r32float:i.R32F,rg16uint:i.RG16UI,rg16sint:i.RG16I,rg16float:i.RG16F,rgba8unorm:i.RGBA,...t,rgba8snorm:i.RGBA8_SNORM,rgba8uint:i.RGBA8UI,rgba8sint:i.RGBA8I,bgra8unorm:s,rgb9e5ufloat:i.RGB9_E5,rgb10a2unorm:i.RGB10_A2,rg11b10ufloat:i.R11F_G11F_B10F,rg32uint:i.RG32UI,rg32sint:i.RG32I,rg32float:i.RG32F,rgba16uint:i.RGBA16UI,rgba16sint:i.RGBA16I,rgba16float:i.RGBA16F,rgba32uint:i.RGBA32UI,rgba32sint:i.RGBA32I,rgba32float:i.RGBA32F,stencil8:i.STENCIL_INDEX8,depth16unorm:i.DEPTH_COMPONENT16,depth24plus:i.DEPTH_COMPONENT24,"depth24plus-stencil8":i.DEPTH24_STENCIL8,depth32float:i.DEPTH_COMPONENT32F,"depth32float-stencil8":i.DEPTH32F_STENCIL8,...e.s3tc?{"bc1-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...e.s3tc_sRGB?{"bc1-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...e.rgtc?{"bc4-r-unorm":e.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":e.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":e.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":e.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...e.bptc?{"bc6h-rgb-float":e.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":e.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":e.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":e.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...e.etc?{"etc2-rgb8unorm":e.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":e.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":e.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":e.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":e.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":e.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":e.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":e.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...e.astc?{"astc-4x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function O3(i){return{r8unorm:i.UNSIGNED_BYTE,r8snorm:i.BYTE,r8uint:i.UNSIGNED_BYTE,r8sint:i.BYTE,r16uint:i.UNSIGNED_SHORT,r16sint:i.SHORT,r16float:i.HALF_FLOAT,rg8unorm:i.UNSIGNED_BYTE,rg8snorm:i.BYTE,rg8uint:i.UNSIGNED_BYTE,rg8sint:i.BYTE,r32uint:i.UNSIGNED_INT,r32sint:i.INT,r32float:i.FLOAT,rg16uint:i.UNSIGNED_SHORT,rg16sint:i.SHORT,rg16float:i.HALF_FLOAT,rgba8unorm:i.UNSIGNED_BYTE,"rgba8unorm-srgb":i.UNSIGNED_BYTE,rgba8snorm:i.BYTE,rgba8uint:i.UNSIGNED_BYTE,rgba8sint:i.BYTE,bgra8unorm:i.UNSIGNED_BYTE,"bgra8unorm-srgb":i.UNSIGNED_BYTE,rgb9e5ufloat:i.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:i.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:i.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:i.UNSIGNED_INT,rg32sint:i.INT,rg32float:i.FLOAT,rgba16uint:i.UNSIGNED_SHORT,rgba16sint:i.SHORT,rgba16float:i.HALF_FLOAT,rgba32uint:i.UNSIGNED_INT,rgba32sint:i.INT,rgba32float:i.FLOAT,stencil8:i.UNSIGNED_BYTE,depth16unorm:i.UNSIGNED_SHORT,depth24plus:i.UNSIGNED_INT,"depth24plus-stencil8":i.UNSIGNED_INT_24_8,depth32float:i.FLOAT,"depth32float-stencil8":i.FLOAT_32_UNSIGNED_INT_24_8_REV}}const D3=4;class g_{constructor(e){this.managedTextures=[],this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._uploads={image:f_,buffer:I3,video:M3,compressed:R3},this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_glTextures"),this._renderer.renderableGC.addManagedHash(this,"_glSamplers")}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=U3(e,this._renderer.context.extensions),this._mapFormatToType=O3(e),this._mapFormatToFormat=B3(e)),this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let t=0;t<16;t++)this.bind(M.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const s=e.source;e?(this.bindSource(s,t),this._useSeparateSamplers&&this._bindSampler(s.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const s=this._gl;if(e._touched=this._renderer.textureGC.count,this._boundTextures[t]!==e){this._boundTextures[t]=e,this._activateLocation(t),e||(e=M.EMPTY.source);const r=this.getGlSource(e);s.bindTexture(r.target,r.texture)}}_bindSampler(e,t=0){const s=this._gl;if(!e){this._boundSamplers[t]=null,s.bindSampler(t,null);return}const r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,s.bindSampler(t,r))}unbind(e){const t=e.source,s=this._boundTextures,r=this._gl;for(let n=0;n<s.length;n++)if(s[n]===t){this._activateLocation(n);const o=this.getGlSource(t);r.bindTexture(o.target,null),s[n]=null}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,s=new E3(t.createTexture());if(s.type=this._mapFormatToType[e.format],s.internalFormat=this._mapFormatToInternalFormat[e.format],s.format=this._mapFormatToFormat[e.format],e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const r=Math.max(e.width,e.height);e.mipLevelCount=Math.floor(Math.log2(r))+1}return this._glTextures[e.uid]=s,this.managedTextures.includes(e)||(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceUpdate,this),e.on("styleChange",this.onStyleChange,this),e.on("destroy",this.onSourceDestroy,this),e.on("unload",this.onSourceUnload,this),e.on("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.push(e)),this.onSourceUpdate(e),this.updateStyle(e,!1),s}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const s=this._gl,r=this.getGlSource(e);s.bindTexture(s.TEXTURE_2D,r.texture),this._boundTextures[this._activeTextureLocation]=e,m_(e.style,s,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",s.TEXTURE_2D,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e){const t=this._glTextures[e.uid];t&&(this.unbind(e),this._glTextures[e.uid]=null,this._gl.deleteTexture(t.texture))}onSourceUpdate(e){const t=this._gl,s=this.getGlSource(e);t.bindTexture(t.TEXTURE_2D,s.texture),this._boundTextures[this._activeTextureLocation]=e;const r=e.alphaMode==="premultiply-alpha-on-upload";this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId]?this._uploads[e.uploadMethodId].upload(e,s,t,this._renderer.context.webGLVersion):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.pixelWidth,e.pixelHeight,0,t.RGBA,t.UNSIGNED_BYTE,null),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const s=this.getGlSource(e);this._gl.generateMipmap(s.target)}onSourceDestroy(e){e.off("destroy",this.onSourceDestroy,this),e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceUpdate,this),e.off("unload",this.onSourceUnload,this),e.off("styleChange",this.onStyleChange,this),e.off("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.splice(this.managedTextures.indexOf(e),1),this.onSourceUnload(e)}_initSampler(e){const t=this._gl,s=this._gl.createSampler();return this._glSamplers[e._resourceId]=s,m_(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",s,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return this._glTextures[e.uid]||this._initSource(e)}generateCanvas(e){const{pixels:t,width:s,height:r}=this.getPixels(e),n=Y.get().createCanvas();n.width=s,n.height=r;const o=n.getContext("2d");if(o){const a=o.createImageData(s,r);a.data.set(t),o.putImageData(a,0,0)}return n}getPixels(e){const t=e.source.resolution,s=e.frame,r=Math.max(Math.round(s.width*t),1),n=Math.max(Math.round(s.height*t),1),o=new Uint8Array(D3*r*n),a=this._renderer,l=a.renderTarget.getRenderTarget(e),c=a.renderTarget.getGpuRenderTarget(l),h=a.gl;return h.bindFramebuffer(h.FRAMEBUFFER,c.resolveTargetFramebuffer),h.readPixels(Math.round(s.x*t),Math.round(s.y*t),r,n,h.RGBA,h.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:r,height:n}}destroy(){this.managedTextures.slice().forEach(e=>this.onSourceDestroy(e)),this.managedTextures=null,this._glTextures=null,this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(M.EMPTY.source),this._boundSamplers=Object.create(null);const e=this._gl;this._premultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}g_.extension={type:[b.WebGLSystem],name:"texture"};class __{contextChange(e){const t=new He({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),s=e.limits.maxBatchableTextures,r=Fs({name:"graphics",bits:[Zu,td(s),Cd,Us]});this.shader=new ot({glProgram:r,resources:{localUniforms:t,batchSamplers:id(s)}})}execute(e,t){const s=t.context,r=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s);r.groups[0]=n.globalUniforms.bindGroup,n.state.set(e.state),n.shader.bind(r),n.geometry.bind(a.geometry,r.glProgram);const c=l.instructions;for(let h=0;h<l.instructionSize;h++){const u=c[h];if(u.size){for(let d=0;d<u.textures.count;d++)n.texture.bind(u.textures.textures[d],d);n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}__.extension={type:[b.WebGLPipesAdaptor],name:"graphics"};class x_{init(){const e=Fs({name:"mesh",bits:[Cd,WI,Us]});this._shader=new ot({glProgram:e,resources:{uTexture:M.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new O}}}})}execute(e,t){const s=e.renderer;let r=t._shader;if(r){if(!r.glProgram){L("Mesh shader has no glProgram",t.shader);return}}else{r=this._shader;const n=t.texture,o=n.source;r.resources.uTexture=o,r.resources.uSampler=o.style,r.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}r.groups[100]=s.globalUniforms.bindGroup,r.groups[101]=e.localUniformsBindGroup,s.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}x_.extension={type:[b.WebGLPipesAdaptor],name:"mesh"};class y_{constructor(e){this._renderer=e}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}}y_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"customRender"};class dn{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){}}function Fd(i,e){const t=i.instructionSet,s=t.instructions;for(let r=0;r<t.instructionSize;r++){const n=s[r];e[n.renderPipeId].execute(n)}}const G3=new O;class v_{constructor(e){this._renderer=e}addRenderGroup(e,t){e.isCachedAsTexture?this._addRenderableCacheAsTexture(e,t):this._addRenderableDirect(e,t)}execute(e){e.isRenderable&&(e.isCachedAsTexture?this._executeCacheAsTexture(e):this._executeDirect(e))}destroy(){this._renderer=null}_addRenderableDirect(e,t){this._renderer.renderPipes.batch.break(t),e._batchableRenderGroup&&(Se.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const s=e._batchableRenderGroup??(e._batchableRenderGroup=Se.get(dn));s.renderable=e.root,s.transform=e.root.relativeGroupTransform,s.texture=e.texture,s.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(s,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=G3.identity().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push(e.texture,!0,null,e.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),Fd(e,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}e._batchableRenderGroup._batcher.updateElement(e._batchableRenderGroup),e._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(e){this._renderer.globalUniforms.push({worldTransformMatrix:e.inverseParentTextureTransform,worldColor:e.worldColorAlpha}),Fd(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}v_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"renderGroup"};function Bd(i,e){e||(e=0);for(let t=e;t<i.length&&i[t];t++)i[t]=null}const z3=new re,b_=ps|Dr|yu;function T_(i,e=!1){N3(i);const t=i.childrenToUpdate,s=i.updateTick++;for(const r in t){const n=Number(r),o=t[r],a=o.list,l=o.index;for(let c=0;c<l;c++){const h=a[c];h.parentRenderGroup===i&&h.relativeRenderGroupDepth===n&&w_(h,s,0)}Bd(a,l),o.index=0}if(e)for(let r=0;r<i.renderGroupChildren.length;r++)T_(i.renderGroupChildren[r],e)}function N3(i){const e=i.root;let t;if(i.renderGroupParent){const s=i.renderGroupParent;i.worldTransform.appendFrom(e.relativeGroupTransform,s.worldTransform),i.worldColor=Fr(e.groupColor,s.worldColor),t=e.groupAlpha*s.worldAlpha}else i.worldTransform.copyFrom(e.localTransform),i.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,i.worldAlpha=t,i.worldColorAlpha=i.worldColor+((t*255|0)<<24)}function w_(i,e,t){if(e===i.updateTick)return;i.updateTick=e,i.didChange=!1;const s=i.localTransform;i.updateLocalTransform();const r=i.parent;if(r&&!r.renderGroup?(t|=i._updateFlags,i.relativeGroupTransform.appendFrom(s,r.relativeGroupTransform),t&b_&&S_(i,r,t)):(t=i._updateFlags,i.relativeGroupTransform.copyFrom(s),t&b_&&S_(i,z3,t)),!i.renderGroup){const n=i.children,o=n.length;for(let c=0;c<o;c++)w_(n[c],e,t);const a=i.parentRenderGroup,l=i;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function S_(i,e,t){if(t&Dr){i.groupColor=Fr(i.localColor,e.groupColor);let s=i.localAlpha*e.groupAlpha;s=s<0?0:s>1?1:s,i.groupAlpha=s,i.groupColorAlpha=i.groupColor+((s*255|0)<<24)}t&yu&&(i.groupBlendMode=i.localBlendMode==="inherit"?e.groupBlendMode:i.localBlendMode),t&ps&&(i.globalDisplayStatus=i.localDisplayStatus&e.globalDisplayStatus),i._updateFlags=0}function L3(i,e){const{list:t}=i.childrenRenderablesToUpdate;let s=!1;for(let r=0;r<i.childrenRenderablesToUpdate.index;r++){const n=t[r];if(s=e[n.renderPipeId].validateRenderable(n),s)break}return i.structureDidChange=s,s}const H3=new O;class C_{constructor(e){this._renderer=e}render({container:e,transform:t}){const s=e.parent,r=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,o=H3;t&&(o.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));const a=n.renderPipes;this._updateCachedRenderGroups(e.renderGroup,null),this._updateRenderGroups(e.renderGroup),n.globalUniforms.start({worldTransformMatrix:t?e.renderGroup.localTransform:e.renderGroup.worldTransform,worldColor:e.renderGroup.worldColorAlpha}),Fd(e.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(o),e.parent=s,e.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let s=e.renderGroupChildren.length-1;s>=0;s--)this._updateCachedRenderGroups(e.renderGroupChildren[s],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const s=e.root.getLocalBounds();s.ceil();const r=e.texture;e.texture&&ve.returnTexture(e.texture,!0);const n=this._renderer,o=e.textureOptions.resolution||n.view.resolution,a=e.textureOptions.antialias??n.view.antialias,l=e.textureOptions.scaleMode??"linear",c=ve.getOptimalTexture(s.width,s.height,o,a);c._source.style=new wt({scaleMode:l}),e.texture=c,e._textureBounds||(e._textureBounds=new De),e._textureBounds.copyFrom(s),r!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(ve.returnTexture(e.texture,!0),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,s=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=s,e.structureDidChange?Bd(e.childrenRenderablesToUpdate.list,0):L3(e,s),T_(e),e.structureDidChange?(e.structureDidChange=!1,this._buildInstructions(e,t)):this._updateRenderables(e),e.childrenRenderablesToUpdate.index=0,t.renderPipes.batch.upload(e.instructionSet),!(e.isCachedAsTexture&&!e.textureNeedsUpdate))for(let r=0;r<e.renderGroupChildren.length;r++)this._updateRenderGroups(e.renderGroupChildren[r])}_updateRenderables(e){const{list:t,index:s}=e.childrenRenderablesToUpdate;for(let r=0;r<s;r++){const n=t[r];n.didViewUpdate&&e.updateRenderable(n)}Bd(t,s)}_buildInstructions(e,t){const s=e.root,r=e.instructionSet;r.reset();const n=t.renderPipes?t:t.batch.renderer,o=n.renderPipes;o.batch.buildStart(r),o.blendMode.buildStart(),o.colorMask.buildStart(),s.sortableChildren&&s.sortChildren(),s.collectRenderablesWithEffects(r,n,null),o.batch.buildEnd(r),o.blendMode.buildEnd(r)}}C_.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"renderGroup"};class A_{constructor(e){this._renderer=e}addRenderable(e,t){const s=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,s),this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.bounds=e.visualBounds,t.texture=e._texture}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=new dn;return t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.bounds=e.visualBounds,t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}A_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"sprite"};const Ud=class uy{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new ue(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...uy.defaultOptions,...e},this.clearBeforeRender=e.clearBeforeRender,this.color=e.background||e.backgroundColor||this._backgroundColor,this.alpha=e.backgroundAlpha,this._backgroundColor.setAlpha(e.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){ue.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&L("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};Ud.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"background",priority:0},Ud.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let W3=Ud;const $s={};V.handle(b.BlendMode,i=>{if(!i.name)throw new Error("BlendMode extension must have a name property");$s[i.name]=i.ref},i=>{delete $s[i.name]});class E_{constructor(e){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(e,t,s){this._blendModeStack.push(t),this.setBlendMode(e,t,s)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,s){const r=e instanceof gu;if(this._activeBlendMode===t){this._isAdvanced&&e&&!r&&this._renderableList?.push(e);return}this._isAdvanced&&this._endAdvancedBlendMode(s),this._activeBlendMode=t,e&&(this._isAdvanced=!!$s[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,s))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const s=this._activeBlendMode;if(!$s[s]){L(`Unable to assign BlendMode: '${s}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const r=this._ensureFilterEffect(s),n=e instanceof gu,o={renderPipeId:"filter",action:"pushFilter",filterEffect:r,renderables:n?null:[e],container:n?e.root:null,canBundle:!1};this._renderableList=o.renderables,t.add(o)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new kr,t.filters=[new $s[e]]),t}_endAdvancedBlendMode(e){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(const e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}}E_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"blendMode"};const Od={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},Dd=class dy{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof re||e instanceof M?{target:e,...t}:{...t,...e}}async image(e){const t=Y.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,dy.defaultImageOptions);const{format:t,quality:s}=e,r=this.canvas(e);if(r.toBlob!==void 0)return new Promise((n,o)=>{r.toBlob(a=>{if(!a){o(new Error("ICanvas.toBlob failed!"));return}const l=new FileReader;l.onload=()=>n(l.result),l.onerror=o,l.readAsDataURL(a)},Od[t],s)});if(r.toDataURL!==void 0)return r.toDataURL(Od[t],s);if(r.convertToBlob!==void 0){const n=await r.convertToBlob({type:Od[t],quality:s});return new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o(l.result),l.onerror=a,l.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer;if(t instanceof M)return s.texture.generateCanvas(t);const r=s.textureGenerator.generateTexture(e),n=s.texture.generateCanvas(r);return r.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer,r=t instanceof M?t:s.textureGenerator.generateTexture(e),n=s.texture.getPixels(r);return t instanceof re&&r.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof M?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),s=document.createElement("a");s.download=e.filename??"image.png",s.href=t.toDataURL("image/png"),document.body.appendChild(s),s.click(),document.body.removeChild(s)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const s=this.canvas(e),r=s.toDataURL();console.log(`[Pixi Texture] ${s.width}px ${s.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${r}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};Dd.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"extract"},Dd.defaultImageOptions={format:"png",quality:1};let V3=Dd;class Ge extends M{static create(e){return new Ge({source:new Ee(e)})}resize(e,t,s){return this.source.resize(e,t,s),this}}const $3=new H,X3=new De,Y3=[0,0,0,0];class I_{constructor(e){this._renderer=e}generateTexture(e){e instanceof re&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,s=e.antialias||this._renderer.view.antialias,r=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:ue.shared.setValue(n).toArray():n=Y3;const o=e.frame?.copyTo($3)||mu(r,X3).rectangle;o.width=Math.max(o.width,1/t)|0,o.height=Math.max(o.height,1/t)|0;const a=Ge.create({...e.textureSourceOptions,width:o.width,height:o.height,resolution:t,antialias:s}),l=O.shared.translate(-o.x,-o.y);return this._renderer.render({container:r,transform:l,target:a,clearColor:n}),a.source.updateMipmaps(),a}destroy(){this._renderer=null}}I_.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"textureGenerator"};function Xs(i,e,t){const s=(i>>24&255)/255;e[t++]=(i&255)/255*s,e[t++]=(i>>8&255)/255*s,e[t++]=(i>>16&255)/255*s,e[t++]=s}class P_{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e<this._activeUniforms.length;e++)this._uniformsPool.push(this._activeUniforms[e]);for(let e=0;e<this._activeBindGroups.length;e++)this._bindGroupPool.push(this._activeBindGroups[e]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(e){this.reset(),this.push(e)}bind({size:e,projectionMatrix:t,worldTransformMatrix:s,worldColor:r,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new O,worldColor:4294967295,offset:new X},l={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||o.size,worldTransformMatrix:s||a.worldTransformMatrix,worldColor:r||a.worldColor,offset:n||a.offset,bindGroup:null},c=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(c);const h=c.uniforms;h.uProjectionMatrix=l.projectionMatrix,h.uResolution=l.resolution,h.uWorldTransformMatrix.copyFrom(l.worldTransformMatrix),h.uWorldTransformMatrix.tx-=l.offset.x,h.uWorldTransformMatrix.ty-=l.offset.y,Xs(l.worldColor,h.uWorldColorAlpha,0),c.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(c,!1):(u=this._bindGroupPool.pop()||new Ot,this._activeBindGroups.push(u),u.setResource(c,0)),l.bindGroup=u,this._currentGlobalUniformData=l}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===Qe.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new He({uProjectionMatrix:{value:new O,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new O,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}P_.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"globalUniforms"};let q3=1;class R_{constructor(){this._tasks=[],this._offset=0}init(){Ze.system.add(this._update,this)}repeat(e,t,s=!0){const r=q3++;let n=0;return s&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:r}),r}cancel(e){for(let t=0;t<this._tasks.length;t++)if(this._tasks[t].id===e){this._tasks.splice(t,1);return}}_update(){const e=performance.now();for(let t=0;t<this._tasks.length;t++){const s=this._tasks[t];if(e-s.offset-s.last>=s.duration){const r=e-s.start;s.func(r),s.last=e}}}destroy(){Ze.system.remove(this._update,this),this._tasks.length=0}}R_.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"scheduler",priority:0};let M_=!1;function K3(i){if(!M_){if(Y.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${qr} (${i}) http://www.pixijs.com/
|
|
1082
|
+
`))}class ux{constructor(e){this._cache={},this._uniformGroupSyncHash={},this._renderer=e,this.gl=null,this._cache={}}contextChange(e){this.gl=e}updateUniformGroup(e,t,s){const r=this._renderer.shader._getProgramData(t);(!e.isStatic||e._dirtyId!==r.uniformDirtyGroups[e.uid])&&(r.uniformDirtyGroups[e.uid]=e._dirtyId,this._getUniformSyncFunction(e,t)(r.uniformData,e.uniforms,this._renderer,s))}_getUniformSyncFunction(e,t){return this._uniformGroupSyncHash[e._signature]?.[t._key]||this._createUniformSyncFunction(e,t)}_createUniformSyncFunction(e,t){const s=this._uniformGroupSyncHash[e._signature]||(this._uniformGroupSyncHash[e._signature]={}),r=this._getSignature(e,t._uniformData,"u");return this._cache[r]||(this._cache[r]=this._generateUniformsSync(e,t._uniformData)),s[t._key]=this._cache[r],s[t._key]}_generateUniformsSync(e,t){return _3(e,t)}_getSignature(e,t,s){const r=e.uniforms,n=[`${s}-`];for(const o in r)n.push(o),t[o]&&n.push(t[o].type);return n.join("-")}destroy(){this._renderer=null,this._cache=null}}ux.extension={type:[b.WebGLSystem],name:"uniformGroup"};function y3(i){const e={};if(e.normal=[i.ONE,i.ONE_MINUS_SRC_ALPHA],e.add=[i.ONE,i.ONE],e.multiply=[i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.screen=[i.ONE,i.ONE_MINUS_SRC_COLOR,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.none=[0,0],e["normal-npm"]=[i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA],e["add-npm"]=[i.SRC_ALPHA,i.ONE,i.ONE,i.ONE],e["screen-npm"]=[i.SRC_ALPHA,i.ONE_MINUS_SRC_COLOR,i.ONE,i.ONE_MINUS_SRC_ALPHA],e.erase=[i.ZERO,i.ONE_MINUS_SRC_ALPHA],!(i instanceof Y.get().getWebGLRenderingContext()))e.min=[i.ONE,i.ONE,i.ONE,i.ONE,i.MIN,i.MIN],e.max=[i.ONE,i.ONE,i.ONE,i.ONE,i.MAX,i.MAX];else{const s=i.getExtension("EXT_blend_minmax");s&&(e.min=[i.ONE,i.ONE,i.ONE,i.ONE,s.MIN_EXT,s.MIN_EXT],e.max=[i.ONE,i.ONE,i.ONE,i.ONE,s.MAX_EXT,s.MAX_EXT])}return e}const v3=0,b3=1,T3=2,w3=3,S3=4,C3=5,dx=class df{constructor(e){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[v3]=this.setBlend,this.map[b3]=this.setOffset,this.map[T3]=this.setCullFace,this.map[w3]=this.setDepthTest,this.map[S3]=this.setFrontFace,this.map[C3]=this.setDepthMask,this.checks=[],this.defaultState=ft.for2d(),e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){this._invertFrontFace=!e.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(e){this.gl=e,this.blendModesMap=y3(e),this.resetState()}set(e){if(e||(e=this.defaultState),this.stateId!==e.data){let t=this.stateId^e.data,s=0;for(;t;)t&1&&this.map[s].call(this,!!(e.data&1<<s)),t>>=1,s++;this.stateId=e.data}for(let t=0;t<this.checks.length;t++)this.checks[t](this,e)}forceState(e){e||(e=this.defaultState);for(let t=0;t<this.map.length;t++)this.map[t].call(this,!!(e.data&1<<t));for(let t=0;t<this.checks.length;t++)this.checks[t](this,e);this.stateId=e.data}setBlend(e){this._updateCheck(df._checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this._updateCheck(df._checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(e){this.gl[e?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(e){this.gl.depthMask(e)}setCullFace(e){this._cullFace=e,this.gl[e?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(e){this._frontFace=e,this._frontFaceDirty=!1;const t=this._invertFrontFace?!e:e;this._glFrontFace!==t&&(this._glFrontFace=t,this.gl.frontFace(this.gl[t?"CW":"CCW"]))}setBlendMode(e){if(this.blendModesMap[e]||(e="normal"),e===this.blendMode)return;this.blendMode=e;const t=this.blendModesMap[e],s=this.gl;t.length===2?s.blendFunc(t[0],t[1]):s.blendFuncSeparate(t[0],t[1],t[2],t[3]),t.length===6?(this._blendEq=!0,s.blendEquationSeparate(t[4],t[5])):this._blendEq&&(this._blendEq=!1,s.blendEquationSeparate(s.FUNC_ADD,s.FUNC_ADD))}setPolygonOffset(e,t){this.gl.polygonOffset(e,t)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(e,t){const s=this.checks.indexOf(e);t&&s===-1?this.checks.push(e):!t&&s!==-1&&this.checks.splice(s,1)}static _checkBlendMode(e,t){e.setBlendMode(t.blendMode)}static _checkPolygonOffset(e,t){e.setPolygonOffset(1,t.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};dx.extension={type:[b.WebGLSystem],name:"state"};let A3=dx;class E3{constructor(e){this.target=W0.TEXTURE_2D,this.texture=e,this.width=-1,this.height=-1,this.type=te.UNSIGNED_BYTE,this.internalFormat=Ed.RGBA,this.format=Ed.RGBA,this.samplerType=0}}const I3={id:"buffer",upload(i,e,t){e.width===i.width||e.height===i.height?t.texSubImage2D(t.TEXTURE_2D,0,0,0,i.width,i.height,e.format,e.type,i.resource):t.texImage2D(e.target,0,e.internalFormat,i.width,i.height,0,e.format,e.type,i.resource),e.width=i.width,e.height=i.height}},P3={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},R3={id:"compressed",upload(i,e,t){t.pixelStorei(t.UNPACK_ALIGNMENT,4);let s=i.pixelWidth,r=i.pixelHeight;const n=!!P3[i.format];for(let o=0;o<i.resource.length;o++){const a=i.resource[o];n?t.compressedTexImage2D(t.TEXTURE_2D,o,e.internalFormat,s,r,0,a):t.texImage2D(t.TEXTURE_2D,o,e.internalFormat,s,r,0,e.format,e.type,a),s=Math.max(s>>1,1),r=Math.max(r>>1,1)}}},fx={id:"image",upload(i,e,t,s){const r=e.width,n=e.height,o=i.pixelWidth,a=i.pixelHeight,l=i.resourceWidth,c=i.resourceHeight;l<o||c<a?((r!==o||n!==a)&&t.texImage2D(e.target,0,e.internalFormat,o,a,0,e.format,e.type,null),s===2?t.texSubImage2D(t.TEXTURE_2D,0,0,0,l,c,e.format,e.type,i.resource):t.texSubImage2D(t.TEXTURE_2D,0,0,0,e.format,e.type,i.resource)):r===o&&n===a?t.texSubImage2D(t.TEXTURE_2D,0,0,0,e.format,e.type,i.resource):s===2?t.texImage2D(e.target,0,e.internalFormat,o,a,0,e.format,e.type,i.resource):t.texImage2D(e.target,0,e.internalFormat,e.format,e.type,i.resource),e.width=o,e.height=a}},M3={id:"video",upload(i,e,t,s){if(!i.isValid){t.texImage2D(e.target,0,e.internalFormat,1,1,0,e.format,e.type,null);return}fx.upload(i,e,t,s)}},px={linear:9729,nearest:9728},k3={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},kd={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},F3={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function mx(i,e,t,s,r,n,o,a){const l=n;if(!a||i.addressModeU!=="repeat"||i.addressModeV!=="repeat"||i.addressModeW!=="repeat"){const c=kd[o?"clamp-to-edge":i.addressModeU],h=kd[o?"clamp-to-edge":i.addressModeV],u=kd[o?"clamp-to-edge":i.addressModeW];e[r](l,e.TEXTURE_WRAP_S,c),e[r](l,e.TEXTURE_WRAP_T,h),e.TEXTURE_WRAP_R&&e[r](l,e.TEXTURE_WRAP_R,u)}if((!a||i.magFilter!=="linear")&&e[r](l,e.TEXTURE_MAG_FILTER,px[i.magFilter]),t){if(!a||i.mipmapFilter!=="linear"){const c=k3[i.minFilter][i.mipmapFilter];e[r](l,e.TEXTURE_MIN_FILTER,c)}}else e[r](l,e.TEXTURE_MIN_FILTER,px[i.minFilter]);if(s&&i.maxAnisotropy>1){const c=Math.min(i.maxAnisotropy,e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT));e[r](l,s.TEXTURE_MAX_ANISOTROPY_EXT,c)}i.compare&&e[r](l,e.TEXTURE_COMPARE_FUNC,F3[i.compare])}function B3(i){return{r8unorm:i.RED,r8snorm:i.RED,r8uint:i.RED,r8sint:i.RED,r16uint:i.RED,r16sint:i.RED,r16float:i.RED,rg8unorm:i.RG,rg8snorm:i.RG,rg8uint:i.RG,rg8sint:i.RG,r32uint:i.RED,r32sint:i.RED,r32float:i.RED,rg16uint:i.RG,rg16sint:i.RG,rg16float:i.RG,rgba8unorm:i.RGBA,"rgba8unorm-srgb":i.RGBA,rgba8snorm:i.RGBA,rgba8uint:i.RGBA,rgba8sint:i.RGBA,bgra8unorm:i.RGBA,"bgra8unorm-srgb":i.RGBA,rgb9e5ufloat:i.RGB,rgb10a2unorm:i.RGBA,rg11b10ufloat:i.RGB,rg32uint:i.RG,rg32sint:i.RG,rg32float:i.RG,rgba16uint:i.RGBA,rgba16sint:i.RGBA,rgba16float:i.RGBA,rgba32uint:i.RGBA,rgba32sint:i.RGBA,rgba32float:i.RGBA,stencil8:i.STENCIL_INDEX8,depth16unorm:i.DEPTH_COMPONENT,depth24plus:i.DEPTH_COMPONENT,"depth24plus-stencil8":i.DEPTH_STENCIL,depth32float:i.DEPTH_COMPONENT,"depth32float-stencil8":i.DEPTH_STENCIL}}function U3(i,e){let t={},s=i.RGBA;return i instanceof Y.get().getWebGLRenderingContext()?e.srgb&&(t={"rgba8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":e.srgb.SRGB8_ALPHA8_EXT}):(t={"rgba8unorm-srgb":i.SRGB8_ALPHA8,"bgra8unorm-srgb":i.SRGB8_ALPHA8},s=i.RGBA8),{r8unorm:i.R8,r8snorm:i.R8_SNORM,r8uint:i.R8UI,r8sint:i.R8I,r16uint:i.R16UI,r16sint:i.R16I,r16float:i.R16F,rg8unorm:i.RG8,rg8snorm:i.RG8_SNORM,rg8uint:i.RG8UI,rg8sint:i.RG8I,r32uint:i.R32UI,r32sint:i.R32I,r32float:i.R32F,rg16uint:i.RG16UI,rg16sint:i.RG16I,rg16float:i.RG16F,rgba8unorm:i.RGBA,...t,rgba8snorm:i.RGBA8_SNORM,rgba8uint:i.RGBA8UI,rgba8sint:i.RGBA8I,bgra8unorm:s,rgb9e5ufloat:i.RGB9_E5,rgb10a2unorm:i.RGB10_A2,rg11b10ufloat:i.R11F_G11F_B10F,rg32uint:i.RG32UI,rg32sint:i.RG32I,rg32float:i.RG32F,rgba16uint:i.RGBA16UI,rgba16sint:i.RGBA16I,rgba16float:i.RGBA16F,rgba32uint:i.RGBA32UI,rgba32sint:i.RGBA32I,rgba32float:i.RGBA32F,stencil8:i.STENCIL_INDEX8,depth16unorm:i.DEPTH_COMPONENT16,depth24plus:i.DEPTH_COMPONENT24,"depth24plus-stencil8":i.DEPTH24_STENCIL8,depth32float:i.DEPTH_COMPONENT32F,"depth32float-stencil8":i.DEPTH32F_STENCIL8,...e.s3tc?{"bc1-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":e.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...e.s3tc_sRGB?{"bc1-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":e.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...e.rgtc?{"bc4-r-unorm":e.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":e.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":e.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":e.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...e.bptc?{"bc6h-rgb-float":e.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":e.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":e.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":e.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...e.etc?{"etc2-rgb8unorm":e.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":e.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":e.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":e.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":e.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":e.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":e.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":e.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...e.astc?{"astc-4x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":e.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":e.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function O3(i){return{r8unorm:i.UNSIGNED_BYTE,r8snorm:i.BYTE,r8uint:i.UNSIGNED_BYTE,r8sint:i.BYTE,r16uint:i.UNSIGNED_SHORT,r16sint:i.SHORT,r16float:i.HALF_FLOAT,rg8unorm:i.UNSIGNED_BYTE,rg8snorm:i.BYTE,rg8uint:i.UNSIGNED_BYTE,rg8sint:i.BYTE,r32uint:i.UNSIGNED_INT,r32sint:i.INT,r32float:i.FLOAT,rg16uint:i.UNSIGNED_SHORT,rg16sint:i.SHORT,rg16float:i.HALF_FLOAT,rgba8unorm:i.UNSIGNED_BYTE,"rgba8unorm-srgb":i.UNSIGNED_BYTE,rgba8snorm:i.BYTE,rgba8uint:i.UNSIGNED_BYTE,rgba8sint:i.BYTE,bgra8unorm:i.UNSIGNED_BYTE,"bgra8unorm-srgb":i.UNSIGNED_BYTE,rgb9e5ufloat:i.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:i.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:i.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:i.UNSIGNED_INT,rg32sint:i.INT,rg32float:i.FLOAT,rgba16uint:i.UNSIGNED_SHORT,rgba16sint:i.SHORT,rgba16float:i.HALF_FLOAT,rgba32uint:i.UNSIGNED_INT,rgba32sint:i.INT,rgba32float:i.FLOAT,stencil8:i.UNSIGNED_BYTE,depth16unorm:i.UNSIGNED_SHORT,depth24plus:i.UNSIGNED_INT,"depth24plus-stencil8":i.UNSIGNED_INT_24_8,depth32float:i.FLOAT,"depth32float-stencil8":i.FLOAT_32_UNSIGNED_INT_24_8_REV}}const D3=4;class gx{constructor(e){this.managedTextures=[],this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._uploads={image:fx,buffer:I3,video:M3,compressed:R3},this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_glTextures"),this._renderer.renderableGC.addManagedHash(this,"_glSamplers")}contextChange(e){this._gl=e,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=U3(e,this._renderer.context.extensions),this._mapFormatToType=O3(e),this._mapFormatToFormat=B3(e)),this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let t=0;t<16;t++)this.bind(M.EMPTY,t)}initSource(e){this.bind(e)}bind(e,t=0){const s=e.source;e?(this.bindSource(s,t),this._useSeparateSamplers&&this._bindSampler(s.style,t)):(this.bindSource(null,t),this._useSeparateSamplers&&this._bindSampler(null,t))}bindSource(e,t=0){const s=this._gl;if(e._touched=this._renderer.textureGC.count,this._boundTextures[t]!==e){this._boundTextures[t]=e,this._activateLocation(t),e||(e=M.EMPTY.source);const r=this.getGlSource(e);s.bindTexture(r.target,r.texture)}}_bindSampler(e,t=0){const s=this._gl;if(!e){this._boundSamplers[t]=null,s.bindSampler(t,null);return}const r=this._getGlSampler(e);this._boundSamplers[t]!==r&&(this._boundSamplers[t]=r,s.bindSampler(t,r))}unbind(e){const t=e.source,s=this._boundTextures,r=this._gl;for(let n=0;n<s.length;n++)if(s[n]===t){this._activateLocation(n);const o=this.getGlSource(t);r.bindTexture(o.target,null),s[n]=null}}_activateLocation(e){this._activeTextureLocation!==e&&(this._activeTextureLocation=e,this._gl.activeTexture(this._gl.TEXTURE0+e))}_initSource(e){const t=this._gl,s=new E3(t.createTexture());if(s.type=this._mapFormatToType[e.format],s.internalFormat=this._mapFormatToInternalFormat[e.format],s.format=this._mapFormatToFormat[e.format],e.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||e.isPowerOfTwo)){const r=Math.max(e.width,e.height);e.mipLevelCount=Math.floor(Math.log2(r))+1}return this._glTextures[e.uid]=s,this.managedTextures.includes(e)||(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceUpdate,this),e.on("styleChange",this.onStyleChange,this),e.on("destroy",this.onSourceDestroy,this),e.on("unload",this.onSourceUnload,this),e.on("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.push(e)),this.onSourceUpdate(e),this.updateStyle(e,!1),s}onStyleChange(e){this.updateStyle(e,!1)}updateStyle(e,t){const s=this._gl,r=this.getGlSource(e);s.bindTexture(s.TEXTURE_2D,r.texture),this._boundTextures[this._activeTextureLocation]=e,mx(e.style,s,e.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",s.TEXTURE_2D,!this._renderer.context.supports.nonPowOf2wrapping&&!e.isPowerOfTwo,t)}onSourceUnload(e){const t=this._glTextures[e.uid];t&&(this.unbind(e),this._glTextures[e.uid]=null,this._gl.deleteTexture(t.texture))}onSourceUpdate(e){const t=this._gl,s=this.getGlSource(e);t.bindTexture(t.TEXTURE_2D,s.texture),this._boundTextures[this._activeTextureLocation]=e;const r=e.alphaMode==="premultiply-alpha-on-upload";this._premultiplyAlpha!==r&&(this._premultiplyAlpha=r,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,r)),this._uploads[e.uploadMethodId]?this._uploads[e.uploadMethodId].upload(e,s,t,this._renderer.context.webGLVersion):t.texImage2D(t.TEXTURE_2D,0,t.RGBA,e.pixelWidth,e.pixelHeight,0,t.RGBA,t.UNSIGNED_BYTE,null),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e,!1)}onUpdateMipmaps(e,t=!0){t&&this.bindSource(e,0);const s=this.getGlSource(e);this._gl.generateMipmap(s.target)}onSourceDestroy(e){e.off("destroy",this.onSourceDestroy,this),e.off("update",this.onSourceUpdate,this),e.off("resize",this.onSourceUpdate,this),e.off("unload",this.onSourceUnload,this),e.off("styleChange",this.onStyleChange,this),e.off("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.splice(this.managedTextures.indexOf(e),1),this.onSourceUnload(e)}_initSampler(e){const t=this._gl,s=this._gl.createSampler();return this._glSamplers[e._resourceId]=s,mx(e,t,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",s,!1,!0),this._glSamplers[e._resourceId]}_getGlSampler(e){return this._glSamplers[e._resourceId]||this._initSampler(e)}getGlSource(e){return this._glTextures[e.uid]||this._initSource(e)}generateCanvas(e){const{pixels:t,width:s,height:r}=this.getPixels(e),n=Y.get().createCanvas();n.width=s,n.height=r;const o=n.getContext("2d");if(o){const a=o.createImageData(s,r);a.data.set(t),o.putImageData(a,0,0)}return n}getPixels(e){const t=e.source.resolution,s=e.frame,r=Math.max(Math.round(s.width*t),1),n=Math.max(Math.round(s.height*t),1),o=new Uint8Array(D3*r*n),a=this._renderer,l=a.renderTarget.getRenderTarget(e),c=a.renderTarget.getGpuRenderTarget(l),h=a.gl;return h.bindFramebuffer(h.FRAMEBUFFER,c.resolveTargetFramebuffer),h.readPixels(Math.round(s.x*t),Math.round(s.y*t),r,n,h.RGBA,h.UNSIGNED_BYTE,o),{pixels:new Uint8ClampedArray(o.buffer),width:r,height:n}}destroy(){this.managedTextures.slice().forEach(e=>this.onSourceDestroy(e)),this.managedTextures=null,this._glTextures=null,this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(M.EMPTY.source),this._boundSamplers=Object.create(null);const e=this._gl;this._premultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}gx.extension={type:[b.WebGLSystem],name:"texture"};class xx{contextChange(e){const t=new He({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),s=e.limits.maxBatchableTextures,r=Fs({name:"graphics",bits:[Zu,td(s),Cd,Us]});this.shader=new ot({glProgram:r,resources:{localUniforms:t,batchSamplers:id(s)}})}execute(e,t){const s=t.context,r=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s);r.groups[0]=n.globalUniforms.bindGroup,n.state.set(e.state),n.shader.bind(r),n.geometry.bind(a.geometry,r.glProgram);const c=l.instructions;for(let h=0;h<l.instructionSize;h++){const u=c[h];if(u.size){for(let d=0;d<u.textures.count;d++)n.texture.bind(u.textures.textures[d],d);n.geometry.draw(u.topology,u.size,u.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}xx.extension={type:[b.WebGLPipesAdaptor],name:"graphics"};class _x{init(){const e=Fs({name:"mesh",bits:[Cd,WI,Us]});this._shader=new ot({glProgram:e,resources:{uTexture:M.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new O}}}})}execute(e,t){const s=e.renderer;let r=t._shader;if(r){if(!r.glProgram){L("Mesh shader has no glProgram",t.shader);return}}else{r=this._shader;const n=t.texture,o=n.source;r.resources.uTexture=o,r.resources.uSampler=o.style,r.resources.textureUniforms.uniforms.uTextureMatrix=n.textureMatrix.mapCoord}r.groups[100]=s.globalUniforms.bindGroup,r.groups[101]=e.localUniformsBindGroup,s.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}_x.extension={type:[b.WebGLPipesAdaptor],name:"mesh"};class yx{constructor(e){this._renderer=e}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}execute(e){e.isRenderable&&e.render(this._renderer)}destroy(){this._renderer=null}}yx.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"customRender"};class dn{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){}}function Fd(i,e){const t=i.instructionSet,s=t.instructions;for(let r=0;r<t.instructionSize;r++){const n=s[r];e[n.renderPipeId].execute(n)}}const G3=new O;class vx{constructor(e){this._renderer=e}addRenderGroup(e,t){e.isCachedAsTexture?this._addRenderableCacheAsTexture(e,t):this._addRenderableDirect(e,t)}execute(e){e.isRenderable&&(e.isCachedAsTexture?this._executeCacheAsTexture(e):this._executeDirect(e))}destroy(){this._renderer=null}_addRenderableDirect(e,t){this._renderer.renderPipes.batch.break(t),e._batchableRenderGroup&&(Se.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const s=e._batchableRenderGroup??(e._batchableRenderGroup=Se.get(dn));s.renderable=e.root,s.transform=e.root.relativeGroupTransform,s.texture=e.texture,s.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(s,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=G3.identity().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push(e.texture,!0,null,e.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),Fd(e,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}e._batchableRenderGroup._batcher.updateElement(e._batchableRenderGroup),e._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(e){this._renderer.globalUniforms.push({worldTransformMatrix:e.inverseParentTextureTransform,worldColor:e.worldColorAlpha}),Fd(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}vx.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"renderGroup"};function Bd(i,e){e||(e=0);for(let t=e;t<i.length&&i[t];t++)i[t]=null}const z3=new re,bx=ps|Dr|yu;function Tx(i,e=!1){N3(i);const t=i.childrenToUpdate,s=i.updateTick++;for(const r in t){const n=Number(r),o=t[r],a=o.list,l=o.index;for(let c=0;c<l;c++){const h=a[c];h.parentRenderGroup===i&&h.relativeRenderGroupDepth===n&&wx(h,s,0)}Bd(a,l),o.index=0}if(e)for(let r=0;r<i.renderGroupChildren.length;r++)Tx(i.renderGroupChildren[r],e)}function N3(i){const e=i.root;let t;if(i.renderGroupParent){const s=i.renderGroupParent;i.worldTransform.appendFrom(e.relativeGroupTransform,s.worldTransform),i.worldColor=Fr(e.groupColor,s.worldColor),t=e.groupAlpha*s.worldAlpha}else i.worldTransform.copyFrom(e.localTransform),i.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,i.worldAlpha=t,i.worldColorAlpha=i.worldColor+((t*255|0)<<24)}function wx(i,e,t){if(e===i.updateTick)return;i.updateTick=e,i.didChange=!1;const s=i.localTransform;i.updateLocalTransform();const r=i.parent;if(r&&!r.renderGroup?(t|=i._updateFlags,i.relativeGroupTransform.appendFrom(s,r.relativeGroupTransform),t&bx&&Sx(i,r,t)):(t=i._updateFlags,i.relativeGroupTransform.copyFrom(s),t&bx&&Sx(i,z3,t)),!i.renderGroup){const n=i.children,o=n.length;for(let c=0;c<o;c++)wx(n[c],e,t);const a=i.parentRenderGroup,l=i;l.renderPipeId&&!a.structureDidChange&&a.updateRenderable(l)}}function Sx(i,e,t){if(t&Dr){i.groupColor=Fr(i.localColor,e.groupColor);let s=i.localAlpha*e.groupAlpha;s=s<0?0:s>1?1:s,i.groupAlpha=s,i.groupColorAlpha=i.groupColor+((s*255|0)<<24)}t&yu&&(i.groupBlendMode=i.localBlendMode==="inherit"?e.groupBlendMode:i.localBlendMode),t&ps&&(i.globalDisplayStatus=i.localDisplayStatus&e.globalDisplayStatus),i._updateFlags=0}function L3(i,e){const{list:t}=i.childrenRenderablesToUpdate;let s=!1;for(let r=0;r<i.childrenRenderablesToUpdate.index;r++){const n=t[r];if(s=e[n.renderPipeId].validateRenderable(n),s)break}return i.structureDidChange=s,s}const H3=new O;class Cx{constructor(e){this._renderer=e}render({container:e,transform:t}){const s=e.parent,r=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,o=H3;t&&(o.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));const a=n.renderPipes;this._updateCachedRenderGroups(e.renderGroup,null),this._updateRenderGroups(e.renderGroup),n.globalUniforms.start({worldTransformMatrix:t?e.renderGroup.localTransform:e.renderGroup.worldTransform,worldColor:e.renderGroup.worldColorAlpha}),Fd(e.renderGroup,a),a.uniformBatch&&a.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(o),e.parent=s,e.renderGroup.renderGroupParent=r}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let s=e.renderGroupChildren.length-1;s>=0;s--)this._updateCachedRenderGroups(e.renderGroupChildren[s],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const s=e.root.getLocalBounds();s.ceil();const r=e.texture;e.texture&&ve.returnTexture(e.texture,!0);const n=this._renderer,o=e.textureOptions.resolution||n.view.resolution,a=e.textureOptions.antialias??n.view.antialias,l=e.textureOptions.scaleMode??"linear",c=ve.getOptimalTexture(s.width,s.height,o,a);c._source.style=new wt({scaleMode:l}),e.texture=c,e._textureBounds||(e._textureBounds=new De),e._textureBounds.copyFrom(s),r!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(ve.returnTexture(e.texture,!0),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,s=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=s,e.structureDidChange?Bd(e.childrenRenderablesToUpdate.list,0):L3(e,s),Tx(e),e.structureDidChange?(e.structureDidChange=!1,this._buildInstructions(e,t)):this._updateRenderables(e),e.childrenRenderablesToUpdate.index=0,t.renderPipes.batch.upload(e.instructionSet),!(e.isCachedAsTexture&&!e.textureNeedsUpdate))for(let r=0;r<e.renderGroupChildren.length;r++)this._updateRenderGroups(e.renderGroupChildren[r])}_updateRenderables(e){const{list:t,index:s}=e.childrenRenderablesToUpdate;for(let r=0;r<s;r++){const n=t[r];n.didViewUpdate&&e.updateRenderable(n)}Bd(t,s)}_buildInstructions(e,t){const s=e.root,r=e.instructionSet;r.reset();const n=t.renderPipes?t:t.batch.renderer,o=n.renderPipes;o.batch.buildStart(r),o.blendMode.buildStart(),o.colorMask.buildStart(),s.sortableChildren&&s.sortChildren(),s.collectRenderablesWithEffects(r,n,null),o.batch.buildEnd(r),o.blendMode.buildEnd(r)}}Cx.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"renderGroup"};class Ax{constructor(e){this._renderer=e}addRenderable(e,t){const s=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,s),this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.bounds=e.visualBounds,t.texture=e._texture}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=new dn;return t.renderable=e,t.transform=e.groupTransform,t.texture=e._texture,t.bounds=e.visualBounds,t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}Ax.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"sprite"};const Ud=class uy{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new ue(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...uy.defaultOptions,...e},this.clearBeforeRender=e.clearBeforeRender,this.color=e.background||e.backgroundColor||this._backgroundColor,this.alpha=e.backgroundAlpha,this._backgroundColor.setAlpha(e.backgroundAlpha)}get color(){return this._backgroundColor}set color(e){ue.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&L("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(e)}get alpha(){return this._backgroundColor.alpha}set alpha(e){this._backgroundColor.setAlpha(e)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};Ud.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"background",priority:0},Ud.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let W3=Ud;const $s={};V.handle(b.BlendMode,i=>{if(!i.name)throw new Error("BlendMode extension must have a name property");$s[i.name]=i.ref},i=>{delete $s[i.name]});class Ex{constructor(e){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=e,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(e,t,s){this._blendModeStack.push(t),this.setBlendMode(e,t,s)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,s){const r=e instanceof gu;if(this._activeBlendMode===t){this._isAdvanced&&e&&!r&&this._renderableList?.push(e);return}this._isAdvanced&&this._endAdvancedBlendMode(s),this._activeBlendMode=t,e&&(this._isAdvanced=!!$s[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,s))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const s=this._activeBlendMode;if(!$s[s]){L(`Unable to assign BlendMode: '${s}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const r=this._ensureFilterEffect(s),n=e instanceof gu,o={renderPipeId:"filter",action:"pushFilter",filterEffect:r,renderables:n?null:[e],container:n?e.root:null,canBundle:!1};this._renderableList=o.renderables,t.add(o)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new kr,t.filters=[new $s[e]]),t}_endAdvancedBlendMode(e){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(e),e.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(e){this._isAdvanced&&this._endAdvancedBlendMode(e)}destroy(){this._renderer=null,this._renderableList=null;for(const e in this._filterHash)this._filterHash[e].destroy();this._filterHash=null}}Ex.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"blendMode"};const Od={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},Dd=class dy{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof re||e instanceof M?{target:e,...t}:{...t,...e}}async image(e){const t=Y.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,dy.defaultImageOptions);const{format:t,quality:s}=e,r=this.canvas(e);if(r.toBlob!==void 0)return new Promise((n,o)=>{r.toBlob(a=>{if(!a){o(new Error("ICanvas.toBlob failed!"));return}const l=new FileReader;l.onload=()=>n(l.result),l.onerror=o,l.readAsDataURL(a)},Od[t],s)});if(r.toDataURL!==void 0)return r.toDataURL(Od[t],s);if(r.convertToBlob!==void 0){const n=await r.convertToBlob({type:Od[t],quality:s});return new Promise((o,a)=>{const l=new FileReader;l.onload=()=>o(l.result),l.onerror=a,l.readAsDataURL(n)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer;if(t instanceof M)return s.texture.generateCanvas(t);const r=s.textureGenerator.generateTexture(e),n=s.texture.generateCanvas(r);return r.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,s=this._renderer,r=t instanceof M?t:s.textureGenerator.generateTexture(e),n=s.texture.getPixels(r);return t instanceof re&&r.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof M?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),s=document.createElement("a");s.download=e.filename??"image.png",s.href=t.toDataURL("image/png"),document.body.appendChild(s),s.click(),document.body.removeChild(s)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const s=this.canvas(e),r=s.toDataURL();console.log(`[Pixi Texture] ${s.width}px ${s.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${r}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};Dd.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"extract"},Dd.defaultImageOptions={format:"png",quality:1};let V3=Dd;class Ge extends M{static create(e){return new Ge({source:new Ee(e)})}resize(e,t,s){return this.source.resize(e,t,s),this}}const $3=new H,X3=new De,Y3=[0,0,0,0];class Ix{constructor(e){this._renderer=e}generateTexture(e){e instanceof re&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,s=e.antialias||this._renderer.view.antialias,r=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:ue.shared.setValue(n).toArray():n=Y3;const o=e.frame?.copyTo($3)||mu(r,X3).rectangle;o.width=Math.max(o.width,1/t)|0,o.height=Math.max(o.height,1/t)|0;const a=Ge.create({...e.textureSourceOptions,width:o.width,height:o.height,resolution:t,antialias:s}),l=O.shared.translate(-o.x,-o.y);return this._renderer.render({container:r,transform:l,target:a,clearColor:n}),a.source.updateMipmaps(),a}destroy(){this._renderer=null}}Ix.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"textureGenerator"};function Xs(i,e,t){const s=(i>>24&255)/255;e[t++]=(i&255)/255*s,e[t++]=(i>>8&255)/255*s,e[t++]=(i>>16&255)/255*s,e[t++]=s}class Px{constructor(e){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=e}reset(){this._stackIndex=0;for(let e=0;e<this._activeUniforms.length;e++)this._uniformsPool.push(this._activeUniforms[e]);for(let e=0;e<this._activeBindGroups.length;e++)this._bindGroupPool.push(this._activeBindGroups[e]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(e){this.reset(),this.push(e)}bind({size:e,projectionMatrix:t,worldTransformMatrix:s,worldColor:r,offset:n}){const o=this._renderer.renderTarget.renderTarget,a=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new O,worldColor:4294967295,offset:new X},l={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||o.size,worldTransformMatrix:s||a.worldTransformMatrix,worldColor:r||a.worldColor,offset:n||a.offset,bindGroup:null},c=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(c);const h=c.uniforms;h.uProjectionMatrix=l.projectionMatrix,h.uResolution=l.resolution,h.uWorldTransformMatrix.copyFrom(l.worldTransformMatrix),h.uWorldTransformMatrix.tx-=l.offset.x,h.uWorldTransformMatrix.ty-=l.offset.y,Xs(l.worldColor,h.uWorldColorAlpha,0),c.update();let u;this._renderer.renderPipes.uniformBatch?u=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(c,!1):(u=this._bindGroupPool.pop()||new Ot,this._activeBindGroups.push(u),u.setResource(c,0)),l.bindGroup=u,this._currentGlobalUniformData=l}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===Qe.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new He({uProjectionMatrix:{value:new O,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new O,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}Px.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"globalUniforms"};let q3=1;class Rx{constructor(){this._tasks=[],this._offset=0}init(){Ze.system.add(this._update,this)}repeat(e,t,s=!0){const r=q3++;let n=0;return s&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:r}),r}cancel(e){for(let t=0;t<this._tasks.length;t++)if(this._tasks[t].id===e){this._tasks.splice(t,1);return}}_update(){const e=performance.now();for(let t=0;t<this._tasks.length;t++){const s=this._tasks[t];if(e-s.offset-s.last>=s.duration){const r=e-s.start;s.func(r),s.last=e}}}destroy(){Ze.system.remove(this._update,this),this._tasks.length=0}}Rx.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"scheduler",priority:0};let Mx=!1;function K3(i){if(!Mx){if(Y.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c %c %c %c %c PixiJS %c v${qr} (${i}) http://www.pixijs.com/
|
|
1083
1083
|
|
|
1084
|
-
`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...e)}else globalThis.console&&globalThis.console.log(`PixiJS ${qr} - ${i} - http://www.pixijs.com/`);M_=!0}}class Gd{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===Qe.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),K3(t)}}}Gd.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"hello",priority:-2},Gd.defaultOptions={hello:!1};function j3(i){let e=!1;for(const s in i)if(i[s]==null){e=!0;break}if(!e)return i;const t=Object.create(null);for(const s in i){const r=i[s];r&&(t[s]=r)}return t}function Z3(i){let e=0;for(let t=0;t<i.length;t++)i[t]==null?e++:i[t-e]=i[t];return i.length-=e,i}let J3=0;const zd=class fy{constructor(e){this._managedRenderables=[],this._managedHashes=[],this._managedArrays=[],this._renderer=e}init(e){e={...fy.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime,this._frequency=e.renderableGCFrequency,this.enabled=e.renderableGCActive}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>this.run(),this._frequency,!1),this._hashHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedHashes)t.context[t.hash]=j3(t.context[t.hash])},this._frequency),this._arrayHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedArrays)Z3(t.context[t.hash])},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._hashHandler),this._renderer.scheduler.cancel(this._arrayHandler)))}addManagedHash(e,t){this._managedHashes.push({context:e,hash:t})}addManagedArray(e,t){this._managedArrays.push({context:e,hash:t})}prerender({container:e}){this._now=performance.now(),e.renderGroup.gcTick=J3++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}addRenderable(e){this.enabled&&(e._lastUsed===-1&&(this._managedRenderables.push(e),e.once("destroyed",this._removeRenderable,this)),e._lastUsed=this._now)}run(){const e=this._now,t=this._managedRenderables,s=this._renderer.renderPipes;let r=0;for(let n=0;n<t.length;n++){const o=t[n];if(o===null){r++;continue}const a=o.renderGroup??o.parentRenderGroup,l=a?.instructionSet?.gcTick??-1;if((a?.gcTick??0)===l&&(o._lastUsed=e),e-o._lastUsed>this.maxUnusedTime){if(!o.destroyed){const c=s;a&&(a.structureDidChange=!0),c[o.renderPipeId].destroyRenderable(o)}o._lastUsed=-1,r++,o.off("destroyed",this._removeRenderable,this)}else t[n-r]=o}t.length-=r}destroy(){this.enabled=!1,this._renderer=null,this._managedRenderables.length=0,this._managedHashes.length=0,this._managedArrays.length=0}_removeRenderable(e){const t=this._managedRenderables.indexOf(e);t>=0&&(e.off("destroyed",this._removeRenderable,this),this._managedRenderables[t]=null)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t;for(const s of e.renderGroupChildren)this._updateInstructionGCTick(s,t)}};zd.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"renderableGC",priority:0},zd.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Q3=zd;const Nd=class py{constructor(e){this._renderer=e,this.count=0,this.checkCount=0}init(e){e={...py.defaultOptions,...e},this.checkCountMax=e.textureGCCheckCountMax,this.maxIdle=e.textureGCAMaxIdle??e.textureGCMaxIdle,this.active=e.textureGCActive}postrender(){this._renderer.renderingToScreen&&(this.count++,this.active&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())))}run(){const e=this._renderer.texture.managedTextures;for(let t=0;t<e.length;t++){const s=e[t];s.autoGarbageCollect&&s.resource&&s._touched>-1&&this.count-s._touched>this.maxIdle&&(s._touched=-1,s.unload())}}destroy(){this._renderer=null}};Nd.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"textureGC"},Nd.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let eP=Nd;const Ld=class my{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(e){this.texture.source.autoDensity=e}get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}init(e){e={...my.defaultOptions,...e},e.view&&(W(Q,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new H(0,0,e.width,e.height),this.canvas=e.canvas||Y.get().createCanvas(),this.antialias=!!e.antialias,this.texture=t_(this.canvas,e),this.renderTarget=new Pd({colorTextures:[this.texture],depth:!!e.depth,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.resolution=e.resolution}resize(e,t,s){this.texture.source.resize(e,t,s),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!e?.removeView)&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};Ld.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"view",priority:0},Ld.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const k_=[W3,P_,Gd,Ld,C_,eP,I_,V3,og,Q3,R_],F_=[E_,D0,A_,v_,G0,N0,z0,y_],tP=[...k_,e_,JI,YI,q0,L0,g_,r_,$0,u_,h_,Y0,A3,K0,X0],iP=[...F_],sP=[U0,x_,__],B_=[],U_=[],O_=[];V.handleByNamedList(b.WebGLSystem,B_),V.handleByNamedList(b.WebGLPipes,U_),V.handleByNamedList(b.WebGLPipesAdaptor,O_),V.add(...tP,...iP,...sP);class rP extends $r{constructor(){const e={name:"webgl",type:Qe.WEBGL,systems:B_,renderPipes:U_,renderPipeAdaptors:O_};super(e)}}const nP=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:rP},Symbol.toStringTag,{value:"Module"}));class D_{constructor(e){this._hash=Object.create(null),this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_hash")}contextChange(e){this._gpu=e}getBindGroup(e,t,s){return e._updateKey(),this._hash[e._key]||this._createBindGroup(e,t,s)}_createBindGroup(e,t,s){const r=this._gpu.device,n=t.layout[s],o=[],a=this._renderer;for(const h in n){const u=e.resources[h]??e.resources[n[h]];let d;if(u._resourceType==="uniformGroup"){const f=u;a.ubo.updateUniformGroup(f);const p=f.buffer;d={buffer:a.buffer.getGPUBuffer(p),offset:0,size:p.descriptor.size}}else if(u._resourceType==="buffer"){const f=u;d={buffer:a.buffer.getGPUBuffer(f),offset:0,size:f.descriptor.size}}else if(u._resourceType==="bufferResource"){const f=u;d={buffer:a.buffer.getGPUBuffer(f.buffer),offset:f.offset,size:f.size}}else if(u._resourceType==="textureSampler"){const f=u;d=a.texture.getGpuSampler(f)}else if(u._resourceType==="textureSource"){const f=u;d=a.texture.getGpuSource(f).createView({})}o.push({binding:n[h],resource:d})}const l=a.shader.getProgramData(t).bindGroups[s],c=r.createBindGroup({layout:l,entries:o});return this._hash[e._key]=c,c}destroy(){for(const e of Object.keys(this._hash))this._hash[e]=null;this._hash=null,this._renderer=null}}D_.extension={type:[b.WebGPUSystem],name:"bindGroup"};class G_{constructor(e){this._gpuBuffers=Object.create(null),e.renderableGC.addManagedHash(this,"_gpuBuffers")}contextChange(e){this._gpu=e}getGPUBuffer(e){return this._gpuBuffers[e.uid]||this.createGPUBuffer(e)}updateBuffer(e){const t=this._gpuBuffers[e.uid]||this.createGPUBuffer(e),s=e.data;return e._updateID&&s&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,0,s.buffer,0,(e._updateSize||s.byteLength)+3&-4)),t}destroyAll(){for(const e in this._gpuBuffers)this._gpuBuffers[e]?.destroy();this._gpuBuffers={}}createGPUBuffer(e){this._gpuBuffers[e.uid]||(e.on("update",this.updateBuffer,this),e.on("change",this.onBufferChange,this),e.on("destroy",this.onBufferDestroy,this));const t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e.data&&(qu(e.data.buffer,t.getMappedRange()),t.unmap()),this._gpuBuffers[e.uid]=t,t}onBufferChange(e){this._gpuBuffers[e.uid].destroy(),e._updateID=0,this._gpuBuffers[e.uid]=this.createGPUBuffer(e)}onBufferDestroy(e){this._destroyBuffer(e)}destroy(){this.destroyAll(),this._gpuBuffers={}}_destroyBuffer(e){if(e.off("update",this.updateBuffer,this),e.off("change",this.onBufferChange,this),e.off("destroy",this.onBufferDestroy,this),!this._gpuBuffers[e.uid])return;this._gpuBuffers[e.uid].destroy(),this._gpuBuffers[e.uid]=null}}G_.extension={type:[b.WebGPUSystem],name:"buffer"};class oP{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${e*4}`);const t=this.byteIndex;let s=t+e*4;if(s=Math.ceil(s/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,s>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=s,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let s=0;s<e.length;s++)this.data[t/4+s]=e[s];return t}destroy(){this.data=null}}class z_{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}}z_.extension={type:[b.WebGPUSystem],name:"colorMask"};class Hd{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>{this.gpu=t,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await Y.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter}),s=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(n=>t.features.has(n)),r=await t.requestDevice({requiredFeatures:s});return{adapter:t,device:r}}destroy(){this.gpu=null,this._renderer=null}}Hd.extension={type:[b.WebGPUSystem],name:"device"},Hd.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class N_{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(e.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(e){this.renderPassEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setPipelineFromGeometryProgramAndState(e,t,s,r){const n=this._renderer.pipeline.getPipeline(e,t,s,r);this.setPipeline(n)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;const t=e.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){this._boundBindGroup[e]=null}setBindGroup(e,t,s){if(this._boundBindGroup[e]===t)return;this._boundBindGroup[e]=t,t._touch(this._renderer.textureGC.count);const r=this._renderer.bindGroup.getBindGroup(t,s,e);this.renderPassEncoder.setBindGroup(e,r)}setGeometry(e,t){const s=this._renderer.pipeline.getBufferNamesToBind(e,t);for(const r in s)this._setVertexBuffer(parseInt(r,10),e.attributes[s[r]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){for(const s in e.groups){const r=e.groups[s];t||this._syncBindGroup(r),this.setBindGroup(s,r,e.gpuProgram)}}_syncBindGroup(e){for(const t in e.resources){const s=e.resources[t];s.isUniformGroup&&this._renderer.ubo.updateUniformGroup(s)}}draw(e){const{geometry:t,shader:s,state:r,topology:n,size:o,start:a,instanceCount:l,skipSync:c}=e;this.setPipelineFromGeometryProgramAndState(t,s.gpuProgram,r,n),this.setGeometry(t,s.gpuProgram),this._setShaderBindGroups(s,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexBuffer.data.length,l??t.instanceCount,a||0):this.renderPassEncoder.draw(o||t.getSize(),l??t.instanceCount,a||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const e=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1]);this.renderPassEncoder=this.commandEncoder.beginRenderPass(e);const t=this._boundPipeline,s={...this._boundVertexBuffer},r=this._boundIndexBuffer,n={...this._boundBindGroup};this._clearCache();const o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(t);for(const a in s)this._setVertexBuffer(a,s[a]);for(const a in n)this.setBindGroup(a,n[a],null);this._setIndexBuffer(r)}_clearCache(){for(let e=0;e<16;e++)this._boundBindGroup[e]=null,this._boundVertexBuffer[e]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(e){this._gpu=e}}N_.extension={type:[b.WebGPUSystem],name:"encoder",priority:1};class L_{constructor(e){this._renderer=e}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}L_.extension={type:[b.WebGPUSystem],name:"limits"};class H_{constructor(e){this._renderTargetStencilState=Object.create(null),this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:be.DISABLED,stencilReference:0}),this._activeRenderTarget=e,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const s=this._renderTargetStencilState[this._activeRenderTarget.uid];s.stencilMode=e,s.stencilReference=t;const r=this._renderer;r.pipeline.setStencilMode(e),r.encoder.renderPassEncoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}H_.extension={type:[b.WebGPUSystem],name:"stencil"};const fn={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function aP(i){const e=i.map(s=>({data:s,offset:0,size:0}));let t=0;for(let s=0;s<e.length;s++){const r=e[s];let n=fn[r.data.type].size;const o=fn[r.data.type].align;if(!fn[r.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(n=Math.max(n,o)*r.data.size),t=Math.ceil(t/o)*o,r.size=n,r.offset=t,t+=n}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function lP(i,e){const{size:t,align:s}=fn[i.data.type],r=(s-t)/4,n=i.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
1084
|
+
`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...e)}else globalThis.console&&globalThis.console.log(`PixiJS ${qr} - ${i} - http://www.pixijs.com/`);Mx=!0}}class Gd{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===Qe.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),K3(t)}}}Gd.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"hello",priority:-2},Gd.defaultOptions={hello:!1};function j3(i){let e=!1;for(const s in i)if(i[s]==null){e=!0;break}if(!e)return i;const t=Object.create(null);for(const s in i){const r=i[s];r&&(t[s]=r)}return t}function Z3(i){let e=0;for(let t=0;t<i.length;t++)i[t]==null?e++:i[t-e]=i[t];return i.length-=e,i}let J3=0;const zd=class fy{constructor(e){this._managedRenderables=[],this._managedHashes=[],this._managedArrays=[],this._renderer=e}init(e){e={...fy.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime,this._frequency=e.renderableGCFrequency,this.enabled=e.renderableGCActive}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>this.run(),this._frequency,!1),this._hashHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedHashes)t.context[t.hash]=j3(t.context[t.hash])},this._frequency),this._arrayHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedArrays)Z3(t.context[t.hash])},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._hashHandler),this._renderer.scheduler.cancel(this._arrayHandler)))}addManagedHash(e,t){this._managedHashes.push({context:e,hash:t})}addManagedArray(e,t){this._managedArrays.push({context:e,hash:t})}prerender({container:e}){this._now=performance.now(),e.renderGroup.gcTick=J3++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}addRenderable(e){this.enabled&&(e._lastUsed===-1&&(this._managedRenderables.push(e),e.once("destroyed",this._removeRenderable,this)),e._lastUsed=this._now)}run(){const e=this._now,t=this._managedRenderables,s=this._renderer.renderPipes;let r=0;for(let n=0;n<t.length;n++){const o=t[n];if(o===null){r++;continue}const a=o.renderGroup??o.parentRenderGroup,l=a?.instructionSet?.gcTick??-1;if((a?.gcTick??0)===l&&(o._lastUsed=e),e-o._lastUsed>this.maxUnusedTime){if(!o.destroyed){const c=s;a&&(a.structureDidChange=!0),c[o.renderPipeId].destroyRenderable(o)}o._lastUsed=-1,r++,o.off("destroyed",this._removeRenderable,this)}else t[n-r]=o}t.length-=r}destroy(){this.enabled=!1,this._renderer=null,this._managedRenderables.length=0,this._managedHashes.length=0,this._managedArrays.length=0}_removeRenderable(e){const t=this._managedRenderables.indexOf(e);t>=0&&(e.off("destroyed",this._removeRenderable,this),this._managedRenderables[t]=null)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t;for(const s of e.renderGroupChildren)this._updateInstructionGCTick(s,t)}};zd.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"renderableGC",priority:0},zd.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Q3=zd;const Nd=class py{constructor(e){this._renderer=e,this.count=0,this.checkCount=0}init(e){e={...py.defaultOptions,...e},this.checkCountMax=e.textureGCCheckCountMax,this.maxIdle=e.textureGCAMaxIdle??e.textureGCMaxIdle,this.active=e.textureGCActive}postrender(){this._renderer.renderingToScreen&&(this.count++,this.active&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())))}run(){const e=this._renderer.texture.managedTextures;for(let t=0;t<e.length;t++){const s=e[t];s.autoGarbageCollect&&s.resource&&s._touched>-1&&this.count-s._touched>this.maxIdle&&(s._touched=-1,s.unload())}}destroy(){this._renderer=null}};Nd.extension={type:[b.WebGLSystem,b.WebGPUSystem],name:"textureGC"},Nd.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let eP=Nd;const Ld=class my{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(e){this.texture.source.autoDensity=e}get resolution(){return this.texture.source._resolution}set resolution(e){this.texture.source.resize(this.texture.source.width,this.texture.source.height,e)}init(e){e={...my.defaultOptions,...e},e.view&&(W(Q,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new H(0,0,e.width,e.height),this.canvas=e.canvas||Y.get().createCanvas(),this.antialias=!!e.antialias,this.texture=tx(this.canvas,e),this.renderTarget=new Pd({colorTextures:[this.texture],depth:!!e.depth,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.resolution=e.resolution}resize(e,t,s){this.texture.source.resize(e,t,s),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(e=!1){(typeof e=="boolean"?e:!!e?.removeView)&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};Ld.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"view",priority:0},Ld.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const kx=[W3,Px,Gd,Ld,Cx,eP,Ix,V3,og,Q3,Rx],Fx=[Ex,D0,Ax,vx,G0,N0,z0,yx],tP=[...kx,ex,JI,YI,q0,L0,gx,rx,$0,ux,hx,Y0,A3,K0,X0],iP=[...Fx],sP=[U0,_x,xx],Bx=[],Ux=[],Ox=[];V.handleByNamedList(b.WebGLSystem,Bx),V.handleByNamedList(b.WebGLPipes,Ux),V.handleByNamedList(b.WebGLPipesAdaptor,Ox),V.add(...tP,...iP,...sP);class rP extends $r{constructor(){const e={name:"webgl",type:Qe.WEBGL,systems:Bx,renderPipes:Ux,renderPipeAdaptors:Ox};super(e)}}const nP=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:rP},Symbol.toStringTag,{value:"Module"}));class Dx{constructor(e){this._hash=Object.create(null),this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_hash")}contextChange(e){this._gpu=e}getBindGroup(e,t,s){return e._updateKey(),this._hash[e._key]||this._createBindGroup(e,t,s)}_createBindGroup(e,t,s){const r=this._gpu.device,n=t.layout[s],o=[],a=this._renderer;for(const h in n){const u=e.resources[h]??e.resources[n[h]];let d;if(u._resourceType==="uniformGroup"){const f=u;a.ubo.updateUniformGroup(f);const p=f.buffer;d={buffer:a.buffer.getGPUBuffer(p),offset:0,size:p.descriptor.size}}else if(u._resourceType==="buffer"){const f=u;d={buffer:a.buffer.getGPUBuffer(f),offset:0,size:f.descriptor.size}}else if(u._resourceType==="bufferResource"){const f=u;d={buffer:a.buffer.getGPUBuffer(f.buffer),offset:f.offset,size:f.size}}else if(u._resourceType==="textureSampler"){const f=u;d=a.texture.getGpuSampler(f)}else if(u._resourceType==="textureSource"){const f=u;d=a.texture.getGpuSource(f).createView({})}o.push({binding:n[h],resource:d})}const l=a.shader.getProgramData(t).bindGroups[s],c=r.createBindGroup({layout:l,entries:o});return this._hash[e._key]=c,c}destroy(){for(const e of Object.keys(this._hash))this._hash[e]=null;this._hash=null,this._renderer=null}}Dx.extension={type:[b.WebGPUSystem],name:"bindGroup"};class Gx{constructor(e){this._gpuBuffers=Object.create(null),e.renderableGC.addManagedHash(this,"_gpuBuffers")}contextChange(e){this._gpu=e}getGPUBuffer(e){return this._gpuBuffers[e.uid]||this.createGPUBuffer(e)}updateBuffer(e){const t=this._gpuBuffers[e.uid]||this.createGPUBuffer(e),s=e.data;return e._updateID&&s&&(e._updateID=0,this._gpu.device.queue.writeBuffer(t,0,s.buffer,0,(e._updateSize||s.byteLength)+3&-4)),t}destroyAll(){for(const e in this._gpuBuffers)this._gpuBuffers[e]?.destroy();this._gpuBuffers={}}createGPUBuffer(e){this._gpuBuffers[e.uid]||(e.on("update",this.updateBuffer,this),e.on("change",this.onBufferChange,this),e.on("destroy",this.onBufferDestroy,this));const t=this._gpu.device.createBuffer(e.descriptor);return e._updateID=0,e.data&&(qu(e.data.buffer,t.getMappedRange()),t.unmap()),this._gpuBuffers[e.uid]=t,t}onBufferChange(e){this._gpuBuffers[e.uid].destroy(),e._updateID=0,this._gpuBuffers[e.uid]=this.createGPUBuffer(e)}onBufferDestroy(e){this._destroyBuffer(e)}destroy(){this.destroyAll(),this._gpuBuffers={}}_destroyBuffer(e){if(e.off("update",this.updateBuffer,this),e.off("change",this.onBufferChange,this),e.off("destroy",this.onBufferDestroy,this),!this._gpuBuffers[e.uid])return;this._gpuBuffers[e.uid].destroy(),this._gpuBuffers[e.uid]=null}}Gx.extension={type:[b.WebGPUSystem],name:"buffer"};class oP{constructor({minUniformOffsetAlignment:e}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=e,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(e){if(e>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${e*4}`);const t=this.byteIndex;let s=t+e*4;if(s=Math.ceil(s/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,s>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=s,t}addGroup(e){const t=this.addEmptyGroup(e.length);for(let s=0;s<e.length;s++)this.data[t/4+s]=e[s];return t}destroy(){this.data=null}}class zx{constructor(e){this._colorMaskCache=15,this._renderer=e}setMask(e){this._colorMaskCache!==e&&(this._colorMaskCache=e,this._renderer.pipeline.setColorMask(e))}destroy(){this._renderer=null,this._colorMaskCache=null}}zx.extension={type:[b.WebGPUSystem],name:"colorMask"};class Hd{constructor(e){this._renderer=e}async init(e){return this._initPromise?this._initPromise:(this._initPromise=(e.gpu?Promise.resolve(e.gpu):this._createDeviceAndAdaptor(e)).then(t=>{this.gpu=t,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(e){this._renderer.gpu=e}async _createDeviceAndAdaptor(e){const t=await Y.get().getNavigator().gpu.requestAdapter({powerPreference:e.powerPreference,forceFallbackAdapter:e.forceFallbackAdapter}),s=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(n=>t.features.has(n)),r=await t.requestDevice({requiredFeatures:s});return{adapter:t,device:r}}destroy(){this.gpu=null,this._renderer=null}}Hd.extension={type:[b.WebGPUSystem],name:"device"},Hd.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class Nx{constructor(e){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=e}renderStart(){this.commandFinished=new Promise(e=>{this._resolveCommandFinished=e}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(e){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(e.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(e){this.renderPassEncoder.setViewport(e.x,e.y,e.width,e.height,0,1)}setPipelineFromGeometryProgramAndState(e,t,s,r){const n=this._renderer.pipeline.getPipeline(e,t,s,r);this.setPipeline(n)}setPipeline(e){this._boundPipeline!==e&&(this._boundPipeline=e,this.renderPassEncoder.setPipeline(e))}_setVertexBuffer(e,t){this._boundVertexBuffer[e]!==t&&(this._boundVertexBuffer[e]=t,this.renderPassEncoder.setVertexBuffer(e,this._renderer.buffer.updateBuffer(t)))}_setIndexBuffer(e){if(this._boundIndexBuffer===e)return;this._boundIndexBuffer=e;const t=e.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(e),t)}resetBindGroup(e){this._boundBindGroup[e]=null}setBindGroup(e,t,s){if(this._boundBindGroup[e]===t)return;this._boundBindGroup[e]=t,t._touch(this._renderer.textureGC.count);const r=this._renderer.bindGroup.getBindGroup(t,s,e);this.renderPassEncoder.setBindGroup(e,r)}setGeometry(e,t){const s=this._renderer.pipeline.getBufferNamesToBind(e,t);for(const r in s)this._setVertexBuffer(parseInt(r,10),e.attributes[s[r]].buffer);e.indexBuffer&&this._setIndexBuffer(e.indexBuffer)}_setShaderBindGroups(e,t){for(const s in e.groups){const r=e.groups[s];t||this._syncBindGroup(r),this.setBindGroup(s,r,e.gpuProgram)}}_syncBindGroup(e){for(const t in e.resources){const s=e.resources[t];s.isUniformGroup&&this._renderer.ubo.updateUniformGroup(s)}}draw(e){const{geometry:t,shader:s,state:r,topology:n,size:o,start:a,instanceCount:l,skipSync:c}=e;this.setPipelineFromGeometryProgramAndState(t,s.gpuProgram,r,n),this.setGeometry(t,s.gpuProgram),this._setShaderBindGroups(s,c),t.indexBuffer?this.renderPassEncoder.drawIndexed(o||t.indexBuffer.data.length,l??t.instanceCount,a||0):this.renderPassEncoder.draw(o||t.getSize(),l??t.instanceCount,a||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const e=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1]);this.renderPassEncoder=this.commandEncoder.beginRenderPass(e);const t=this._boundPipeline,s={...this._boundVertexBuffer},r=this._boundIndexBuffer,n={...this._boundBindGroup};this._clearCache();const o=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(o.x,o.y,o.width,o.height,0,1),this.setPipeline(t);for(const a in s)this._setVertexBuffer(a,s[a]);for(const a in n)this.setBindGroup(a,n[a],null);this._setIndexBuffer(r)}_clearCache(){for(let e=0;e<16;e++)this._boundBindGroup[e]=null,this._boundVertexBuffer[e]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(e){this._gpu=e}}Nx.extension={type:[b.WebGPUSystem],name:"encoder",priority:1};class Lx{constructor(e){this._renderer=e}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}Lx.extension={type:[b.WebGPUSystem],name:"limits"};class Hx{constructor(e){this._renderTargetStencilState=Object.create(null),this._renderer=e,e.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(e){let t=this._renderTargetStencilState[e.uid];t||(t=this._renderTargetStencilState[e.uid]={stencilMode:be.DISABLED,stencilReference:0}),this._activeRenderTarget=e,this.setStencilMode(t.stencilMode,t.stencilReference)}setStencilMode(e,t){const s=this._renderTargetStencilState[this._activeRenderTarget.uid];s.stencilMode=e,s.stencilReference=t;const r=this._renderer;r.pipeline.setStencilMode(e),r.encoder.renderPassEncoder.setStencilReference(t)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}Hx.extension={type:[b.WebGPUSystem],name:"stencil"};const fn={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function aP(i){const e=i.map(s=>({data:s,offset:0,size:0}));let t=0;for(let s=0;s<e.length;s++){const r=e[s];let n=fn[r.data.type].size;const o=fn[r.data.type].align;if(!fn[r.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${r.data.type}`);r.data.size>1&&(n=Math.max(n,o)*r.data.size),t=Math.ceil(t/o)*o,r.size=n,r.offset=t,t+=n}return t=Math.ceil(t/16)*16,{uboElements:e,size:t}}function lP(i,e){const{size:t,align:s}=fn[i.data.type],r=(s-t)/4,n=i.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
1085
1085
|
v = uv.${i.data.name};
|
|
1086
1086
|
${e!==0?`offset += ${e};`:""}
|
|
1087
1087
|
|
|
@@ -1097,7 +1097,7 @@ fn mainFragment(
|
|
|
1097
1097
|
}
|
|
1098
1098
|
${r!==0?`arrayOffset += ${r};`:""}
|
|
1099
1099
|
}
|
|
1100
|
-
`}function cP(i){return J0(i,"uboWgsl",lP,t3)}class W_ extends j0{constructor(){super({createUboElements:aP,generateUboSync:cP})}}W_.extension={type:[b.WebGPUSystem],name:"ubo"};const Qt=128;class V_{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_bindGroupHash"),this._batchBuffer=new oP({minUniformOffsetAlignment:Qt});const t=256/Qt;for(let s=0;s<t;s++){let r=j.UNIFORM|j.COPY_DST;s===0&&(r|=j.COPY_SRC),this._buffers.push(new tt({data:this._batchBuffer.data,usage:r}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){for(const e in this._bindGroupHash)this._bindGroupHash[e]=null;this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);const s=e.buffer.data,r=this._batchBuffer.addEmptyGroup(s.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,r/4),this._bindGroupHash[e.uid]=this._getBindGroup(r/Qt),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,s=this._batchBuffer.addGroup(t);return this._getBufferResource(s/Qt)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/Qt)}getArrayBufferResource(e){const s=this._batchBuffer.addGroup(e)/Qt;return this._getBufferResource(s)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new Rd({buffer:t,offset:(e/2|0)*256,size:Qt})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new Ot({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){const e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);const s=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){const n=this._buffers[r];s.copyBufferToBuffer(e.getGPUBuffer(t),Qt,e.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([s.finish()])}destroy(){for(let e=0;e<this._bindGroups.length;e++)this._bindGroups[e]?.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let e=0;e<this._buffers.length;e++)this._buffers[e].destroy();this._buffers=null;for(let e=0;e<this._bufferResources.length;e++)this._bufferResources[e].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._bindGroupHash=null,this._renderer=null}}V_.extension={type:[b.WebGPUPipes],name:"uniformBatch"};const hP={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function uP(i,e,t,s,r){return i<<24|e<<16|t<<10|s<<5|r}function dP(i,e,t,s){return t<<6|i<<3|s<<1|e}class $_{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._renderer=e}contextChange(e){this._gpu=e,this.setStencilMode(be.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){this._multisampleCount=e.msaaSamples,this._depthStencilAttachment=e.descriptor.depthStencilAttachment?1:0,this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=Jt[e],this._updatePipeHash())}setPipeline(e,t,s,r){const n=this.getPipeline(e,t,s);r.setPipeline(n)}getPipeline(e,t,s,r){e._layoutKey||(H0(e,t.attributeData),this._generateBufferKey(e)),r||(r=e.topology);const n=uP(e._layoutKey,t._layoutKey,s.data,s._blendModeId,hP[r]);return this._pipeCache[n]?this._pipeCache[n]:(this._pipeCache[n]=this._createPipeline(e,t,s,r),this._pipeCache[n])}_createPipeline(e,t,s,r){const n=this._gpu.device,o=this._createVertexBufferLayouts(e,t),a=this._renderer.state.getColorTargets(s);a[0].writeMask=this._stencilMode===be.RENDERING_MASK_ADD?0:this._colorMask;const l=this._renderer.shader.getProgramData(t).pipeline,c={vertex:{module:this._getModule(t.vertex.source),entryPoint:t.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(t.fragment.source),entryPoint:t.fragment.entryPoint,targets:a},primitive:{topology:r,cullMode:s.cullMode},layout:l,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(c.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:s.depthTest,depthCompare:s.depthTest?"less":"always"}),n.createRenderPipeline(c)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){const t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){const t=[];let s=0;const r=Object.keys(e.attributes).sort();for(let o=0;o<r.length;o++){const a=e.attributes[r[o]];t[s++]=a.offset,t[s++]=a.format,t[s++]=a.stride,t[s++]=a.instance}const n=t.join("|");return e._layoutKey=xs(n,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let s=0;const r=Object.keys(e.attributeData).sort();for(let o=0;o<r.length;o++){const a=e.attributeData[r[o]];t[s++]=a.location}const n=t.join("|");return e._attributeLocationsKey=xs(n,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[s])return this._bindingNamesCache[s];const r=this._createVertexBufferLayouts(e,t),n=Object.create(null),o=t.attributeData;for(let a=0;a<r.length;a++){const c=Object.values(r[a].attributes)[0].shaderLocation;for(const h in o)if(o[h].location===c){n[a]=h;break}}return this._bindingNamesCache[s]=n,n}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[s])return this._bufferLayoutsCache[s];const r=[];return e.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in t.attributeData){const c=e.attributes[l];(c.divisor??1)!==1&&L(`Attribute ${l} has an invalid divisor value of '${c.divisor}'. WebGPU only supports a divisor value of 1`),c.buffer===n&&(o.arrayStride=c.stride,o.stepMode=c.instance?"instance":"vertex",a.push({shaderLocation:t.attributeData[l].location,offset:c.offset,format:c.format}))}a.length&&r.push(o)}),this._bufferLayoutsCache[s]=r,r}_updatePipeHash(){const e=dP(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment);this._pipeStateCaches[e]||(this._pipeStateCaches[e]=Object.create(null)),this._pipeCache=this._pipeStateCaches[e]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}$_.extension={type:[b.WebGPUSystem],name:"pipeline"};class fP{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class pP{init(e,t){this._renderer=e,this._renderTargetSystem=t}copyToTexture(e,t,s,r,n){const o=this._renderer,a=this._getGpuColorTexture(e),l=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:s},{texture:l,origin:n},r),t}startRenderPass(e,t=!0,s,r){const o=this._renderTargetSystem.getGpuRenderTarget(e),a=this.getDescriptor(e,t,s);o.descriptor=a,this._renderer.pipeline.setRenderTarget(o),this._renderer.encoder.beginRenderPass(o),this._renderer.encoder.setViewport(r)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);return t.contexts[0]?t.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(e.colorTextures[0].source)}getDescriptor(e,t,s){typeof t=="boolean"&&(t=t?et.ALL:et.NONE);const r=this._renderTargetSystem,n=r.getGpuRenderTarget(e),o=e.colorTextures.map((c,h)=>{const u=n.contexts[h];let d,f;u?d=u.getCurrentTexture().createView():d=this._renderer.texture.getGpuSource(c).createView({mipLevelCount:1}),n.msaaTextures[h]&&(f=d,d=this._renderer.texture.getTextureView(n.msaaTextures[h]));const p=t&et.COLOR?"clear":"load";return s??(s=r.defaultClearColor),{view:d,resolveTarget:f,clearValue:s,storeOp:"store",loadOp:p}});let a;if((e.stencil||e.depth)&&!e.depthStencilTexture&&(e.ensureDepthStencilTexture(),e.depthStencilTexture.source.sampleCount=n.msaa?4:1),e.depthStencilTexture){const c=t&et.STENCIL?"clear":"load",h=t&et.DEPTH?"clear":"load";a={view:this._renderer.texture.getGpuSource(e.depthStencilTexture.source).createView(),stencilStoreOp:"store",stencilLoadOp:c,depthClearValue:1,depthLoadOp:h,depthStoreOp:"store"}}return{colorAttachments:o,depthStencilAttachment:a}}clear(e,t=!0,s,r){if(!t)return;const{gpu:n,encoder:o}=this._renderer,a=n.device;if(o.commandEncoder===null){const c=a.createCommandEncoder(),h=this.getDescriptor(e,t,s),u=c.beginRenderPass(h);u.setViewport(r.x,r.y,r.width,r.height,0,1),u.end();const d=c.finish();a.queue.submit([d])}else this.startRenderPass(e,t,s,r)}initGpuRenderTarget(e){e.isRoot=!0;const t=new fP;return e.colorTextures.forEach((s,r)=>{if(s instanceof Ft){const n=s.resource.getContext("webgpu"),o=s.transparent?"premultiplied":"opaque";try{n.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(a){console.error(a)}t.contexts[r]=n}if(t.msaa=s.source.antialias,s.source.antialias){const n=new Ee({width:0,height:0,sampleCount:4});t.msaaTextures[r]=n}}),t.msaa&&(t.msaaSamples=4,e.depthStencilTexture&&(e.depthStencilTexture.source.sampleCount=4)),t}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);e.depthStencilTexture&&t.msaa&&(e.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorTextures.forEach((s,r)=>{t.msaaTextures[r]?.resize(s.source.width,s.source.height,s.source._resolution)})}}class X_ extends s_{constructor(e){super(e),this.adaptor=new pP,this.adaptor.init(e,this)}}X_.extension={type:[b.WebGPUSystem],name:"renderTarget"};class Y_{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,s=e.gpuLayout.map(n=>t.createBindGroupLayout({entries:n})),r={bindGroupLayouts:s};return this._gpuProgramData[e._layoutKey]={bindGroups:s,pipeline:t.createPipelineLayout(r)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}Y_.extension={type:[b.WebGPUSystem],name:"shader"};const Ye={};Ye.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},Ye.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},Ye.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},Ye.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Ye.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Ye.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},Ye["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},Ye["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},Ye["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},Ye.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},Ye.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},Ye.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class q_{constructor(){this.defaultState=new ft,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e){return[{format:"bgra8unorm",writeMask:0,blend:Ye[e.blendMode]||Ye.normal}]}destroy(){this.gpu=null}}q_.extension={type:[b.WebGPUSystem],name:"state"};const mP={type:"image",upload(i,e,t){const s=i.resource,r=(i.pixelWidth|0)*(i.pixelHeight|0),n=s.byteLength/r;t.device.queue.writeTexture({texture:e},s,{offset:0,rowsPerImage:i.pixelHeight,bytesPerRow:i.pixelWidth*n},{width:i.pixelWidth,height:i.pixelHeight,depthOrArrayLayers:1})}},K_={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},gP={blockBytes:4,blockWidth:1,blockHeight:1},_P={type:"compressed",upload(i,e,t){let s=i.pixelWidth,r=i.pixelHeight;const n=K_[i.format]||gP;for(let o=0;o<i.resource.length;o++){const a=i.resource[o],l=Math.ceil(s/n.blockWidth)*n.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:o},a,{offset:0,bytesPerRow:l},{width:Math.ceil(s/n.blockWidth)*n.blockWidth,height:Math.ceil(r/n.blockHeight)*n.blockHeight,depthOrArrayLayers:1}),s=Math.max(s>>1,1),r=Math.max(r>>1,1)}}},j_={type:"image",upload(i,e,t){const s=i.resource;if(!s)return;if(globalThis.HTMLImageElement&&s instanceof HTMLImageElement){const a=Y.get().createCanvas(s.width,s.height);a.getContext("2d").drawImage(s,0,0,s.width,s.height),i.resource=a,L("ImageSource: Image element passed, converting to canvas and replacing resource.")}const r=Math.min(e.width,i.resourceWidth||i.pixelWidth),n=Math.min(e.height,i.resourceHeight||i.pixelHeight),o=i.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:s},{texture:e,premultipliedAlpha:o},{width:r,height:n})}},xP={type:"video",upload(i,e,t){j_.upload(i,e,t)}};class yP{constructor(e){this.device=e,this.sampler=e.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(e){let t=this.pipelines[e];return t||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
|
|
1100
|
+
`}function cP(i){return J0(i,"uboWgsl",lP,t3)}class Wx extends j0{constructor(){super({createUboElements:aP,generateUboSync:cP})}}Wx.extension={type:[b.WebGPUSystem],name:"ubo"};const Qt=128;class Vx{constructor(e){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=e,this._renderer.renderableGC.addManagedHash(this,"_bindGroupHash"),this._batchBuffer=new oP({minUniformOffsetAlignment:Qt});const t=256/Qt;for(let s=0;s<t;s++){let r=j.UNIFORM|j.COPY_DST;s===0&&(r|=j.COPY_SRC),this._buffers.push(new tt({data:this._batchBuffer.data,usage:r}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){for(const e in this._bindGroupHash)this._bindGroupHash[e]=null;this._batchBuffer.clear()}getUniformBindGroup(e,t){if(!t&&this._bindGroupHash[e.uid])return this._bindGroupHash[e.uid];this._renderer.ubo.ensureUniformGroup(e);const s=e.buffer.data,r=this._batchBuffer.addEmptyGroup(s.length);return this._renderer.ubo.syncUniformGroup(e,this._batchBuffer.data,r/4),this._bindGroupHash[e.uid]=this._getBindGroup(r/Qt),this._bindGroupHash[e.uid]}getUboResource(e){this._renderer.ubo.updateUniformGroup(e);const t=e.buffer.data,s=this._batchBuffer.addGroup(t);return this._getBufferResource(s/Qt)}getArrayBindGroup(e){const t=this._batchBuffer.addGroup(e);return this._getBindGroup(t/Qt)}getArrayBufferResource(e){const s=this._batchBuffer.addGroup(e)/Qt;return this._getBufferResource(s)}_getBufferResource(e){if(!this._bufferResources[e]){const t=this._buffers[e%2];this._bufferResources[e]=new Rd({buffer:t,offset:(e/2|0)*256,size:Qt})}return this._bufferResources[e]}_getBindGroup(e){if(!this._bindGroups[e]){const t=new Ot({0:this._getBufferResource(e)});this._bindGroups[e]=t}return this._bindGroups[e]}_uploadBindGroups(){const e=this._renderer.buffer,t=this._buffers[0];t.update(this._batchBuffer.byteIndex),e.updateBuffer(t);const s=this._renderer.gpu.device.createCommandEncoder();for(let r=1;r<this._buffers.length;r++){const n=this._buffers[r];s.copyBufferToBuffer(e.getGPUBuffer(t),Qt,e.getGPUBuffer(n),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([s.finish()])}destroy(){for(let e=0;e<this._bindGroups.length;e++)this._bindGroups[e]?.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let e=0;e<this._buffers.length;e++)this._buffers[e].destroy();this._buffers=null;for(let e=0;e<this._bufferResources.length;e++)this._bufferResources[e].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._bindGroupHash=null,this._renderer=null}}Vx.extension={type:[b.WebGPUPipes],name:"uniformBatch"};const hP={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function uP(i,e,t,s,r){return i<<24|e<<16|t<<10|s<<5|r}function dP(i,e,t,s){return t<<6|i<<3|s<<1|e}class $x{constructor(e){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._renderer=e}contextChange(e){this._gpu=e,this.setStencilMode(be.DISABLED),this._updatePipeHash()}setMultisampleCount(e){this._multisampleCount!==e&&(this._multisampleCount=e,this._updatePipeHash())}setRenderTarget(e){this._multisampleCount=e.msaaSamples,this._depthStencilAttachment=e.descriptor.depthStencilAttachment?1:0,this._updatePipeHash()}setColorMask(e){this._colorMask!==e&&(this._colorMask=e,this._updatePipeHash())}setStencilMode(e){this._stencilMode!==e&&(this._stencilMode=e,this._stencilState=Jt[e],this._updatePipeHash())}setPipeline(e,t,s,r){const n=this.getPipeline(e,t,s);r.setPipeline(n)}getPipeline(e,t,s,r){e._layoutKey||(H0(e,t.attributeData),this._generateBufferKey(e)),r||(r=e.topology);const n=uP(e._layoutKey,t._layoutKey,s.data,s._blendModeId,hP[r]);return this._pipeCache[n]?this._pipeCache[n]:(this._pipeCache[n]=this._createPipeline(e,t,s,r),this._pipeCache[n])}_createPipeline(e,t,s,r){const n=this._gpu.device,o=this._createVertexBufferLayouts(e,t),a=this._renderer.state.getColorTargets(s);a[0].writeMask=this._stencilMode===be.RENDERING_MASK_ADD?0:this._colorMask;const l=this._renderer.shader.getProgramData(t).pipeline,c={vertex:{module:this._getModule(t.vertex.source),entryPoint:t.vertex.entryPoint,buffers:o},fragment:{module:this._getModule(t.fragment.source),entryPoint:t.fragment.entryPoint,targets:a},primitive:{topology:r,cullMode:s.cullMode},layout:l,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(c.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:s.depthTest,depthCompare:s.depthTest?"less":"always"}),n.createRenderPipeline(c)}_getModule(e){return this._moduleCache[e]||this._createModule(e)}_createModule(e){const t=this._gpu.device;return this._moduleCache[e]=t.createShaderModule({code:e}),this._moduleCache[e]}_generateBufferKey(e){const t=[];let s=0;const r=Object.keys(e.attributes).sort();for(let o=0;o<r.length;o++){const a=e.attributes[r[o]];t[s++]=a.offset,t[s++]=a.format,t[s++]=a.stride,t[s++]=a.instance}const n=t.join("|");return e._layoutKey=_s(n,"geometry"),e._layoutKey}_generateAttributeLocationsKey(e){const t=[];let s=0;const r=Object.keys(e.attributeData).sort();for(let o=0;o<r.length;o++){const a=e.attributeData[r[o]];t[s++]=a.location}const n=t.join("|");return e._attributeLocationsKey=_s(n,"programAttributes"),e._attributeLocationsKey}getBufferNamesToBind(e,t){const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bindingNamesCache[s])return this._bindingNamesCache[s];const r=this._createVertexBufferLayouts(e,t),n=Object.create(null),o=t.attributeData;for(let a=0;a<r.length;a++){const c=Object.values(r[a].attributes)[0].shaderLocation;for(const h in o)if(o[h].location===c){n[a]=h;break}}return this._bindingNamesCache[s]=n,n}_createVertexBufferLayouts(e,t){t._attributeLocationsKey||this._generateAttributeLocationsKey(t);const s=e._layoutKey<<16|t._attributeLocationsKey;if(this._bufferLayoutsCache[s])return this._bufferLayoutsCache[s];const r=[];return e.buffers.forEach(n=>{const o={arrayStride:0,stepMode:"vertex",attributes:[]},a=o.attributes;for(const l in t.attributeData){const c=e.attributes[l];(c.divisor??1)!==1&&L(`Attribute ${l} has an invalid divisor value of '${c.divisor}'. WebGPU only supports a divisor value of 1`),c.buffer===n&&(o.arrayStride=c.stride,o.stepMode=c.instance?"instance":"vertex",a.push({shaderLocation:t.attributeData[l].location,offset:c.offset,format:c.format}))}a.length&&r.push(o)}),this._bufferLayoutsCache[s]=r,r}_updatePipeHash(){const e=dP(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment);this._pipeStateCaches[e]||(this._pipeStateCaches[e]=Object.create(null)),this._pipeCache=this._pipeStateCaches[e]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}$x.extension={type:[b.WebGPUSystem],name:"pipeline"};class fP{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class pP{init(e,t){this._renderer=e,this._renderTargetSystem=t}copyToTexture(e,t,s,r,n){const o=this._renderer,a=this._getGpuColorTexture(e),l=o.texture.getGpuSource(t.source);return o.encoder.commandEncoder.copyTextureToTexture({texture:a,origin:s},{texture:l,origin:n},r),t}startRenderPass(e,t=!0,s,r){const o=this._renderTargetSystem.getGpuRenderTarget(e),a=this.getDescriptor(e,t,s);o.descriptor=a,this._renderer.pipeline.setRenderTarget(o),this._renderer.encoder.beginRenderPass(o),this._renderer.encoder.setViewport(r)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);return t.contexts[0]?t.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(e.colorTextures[0].source)}getDescriptor(e,t,s){typeof t=="boolean"&&(t=t?et.ALL:et.NONE);const r=this._renderTargetSystem,n=r.getGpuRenderTarget(e),o=e.colorTextures.map((c,h)=>{const u=n.contexts[h];let d,f;u?d=u.getCurrentTexture().createView():d=this._renderer.texture.getGpuSource(c).createView({mipLevelCount:1}),n.msaaTextures[h]&&(f=d,d=this._renderer.texture.getTextureView(n.msaaTextures[h]));const p=t&et.COLOR?"clear":"load";return s??(s=r.defaultClearColor),{view:d,resolveTarget:f,clearValue:s,storeOp:"store",loadOp:p}});let a;if((e.stencil||e.depth)&&!e.depthStencilTexture&&(e.ensureDepthStencilTexture(),e.depthStencilTexture.source.sampleCount=n.msaa?4:1),e.depthStencilTexture){const c=t&et.STENCIL?"clear":"load",h=t&et.DEPTH?"clear":"load";a={view:this._renderer.texture.getGpuSource(e.depthStencilTexture.source).createView(),stencilStoreOp:"store",stencilLoadOp:c,depthClearValue:1,depthLoadOp:h,depthStoreOp:"store"}}return{colorAttachments:o,depthStencilAttachment:a}}clear(e,t=!0,s,r){if(!t)return;const{gpu:n,encoder:o}=this._renderer,a=n.device;if(o.commandEncoder===null){const c=a.createCommandEncoder(),h=this.getDescriptor(e,t,s),u=c.beginRenderPass(h);u.setViewport(r.x,r.y,r.width,r.height,0,1),u.end();const d=c.finish();a.queue.submit([d])}else this.startRenderPass(e,t,s,r)}initGpuRenderTarget(e){e.isRoot=!0;const t=new fP;return e.colorTextures.forEach((s,r)=>{if(s instanceof Ft){const n=s.resource.getContext("webgpu"),o=s.transparent?"premultiplied":"opaque";try{n.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:o})}catch(a){console.error(a)}t.contexts[r]=n}if(t.msaa=s.source.antialias,s.source.antialias){const n=new Ee({width:0,height:0,sampleCount:4});t.msaaTextures[r]=n}}),t.msaa&&(t.msaaSamples=4,e.depthStencilTexture&&(e.depthStencilTexture.source.sampleCount=4)),t}destroyGpuRenderTarget(e){e.contexts.forEach(t=>{t.unconfigure()}),e.msaaTextures.forEach(t=>{t.destroy()}),e.msaaTextures.length=0,e.contexts.length=0}ensureDepthStencilTexture(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);e.depthStencilTexture&&t.msaa&&(e.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(e){const t=this._renderTargetSystem.getGpuRenderTarget(e);t.width=e.width,t.height=e.height,t.msaa&&e.colorTextures.forEach((s,r)=>{t.msaaTextures[r]?.resize(s.source.width,s.source.height,s.source._resolution)})}}class Xx extends sx{constructor(e){super(e),this.adaptor=new pP,this.adaptor.init(e,this)}}Xx.extension={type:[b.WebGPUSystem],name:"renderTarget"};class Yx{constructor(){this._gpuProgramData=Object.create(null)}contextChange(e){this._gpu=e}getProgramData(e){return this._gpuProgramData[e._layoutKey]||this._createGPUProgramData(e)}_createGPUProgramData(e){const t=this._gpu.device,s=e.gpuLayout.map(n=>t.createBindGroupLayout({entries:n})),r={bindGroupLayouts:s};return this._gpuProgramData[e._layoutKey]={bindGroups:s,pipeline:t.createPipelineLayout(r)},this._gpuProgramData[e._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}Yx.extension={type:[b.WebGPUSystem],name:"shader"};const Ye={};Ye.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},Ye.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},Ye.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},Ye.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Ye.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},Ye.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},Ye["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},Ye["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},Ye["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},Ye.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},Ye.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},Ye.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class qx{constructor(){this.defaultState=new ft,this.defaultState.blend=!0}contextChange(e){this.gpu=e}getColorTargets(e){return[{format:"bgra8unorm",writeMask:0,blend:Ye[e.blendMode]||Ye.normal}]}destroy(){this.gpu=null}}qx.extension={type:[b.WebGPUSystem],name:"state"};const mP={type:"image",upload(i,e,t){const s=i.resource,r=(i.pixelWidth|0)*(i.pixelHeight|0),n=s.byteLength/r;t.device.queue.writeTexture({texture:e},s,{offset:0,rowsPerImage:i.pixelHeight,bytesPerRow:i.pixelWidth*n},{width:i.pixelWidth,height:i.pixelHeight,depthOrArrayLayers:1})}},Kx={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},gP={blockBytes:4,blockWidth:1,blockHeight:1},xP={type:"compressed",upload(i,e,t){let s=i.pixelWidth,r=i.pixelHeight;const n=Kx[i.format]||gP;for(let o=0;o<i.resource.length;o++){const a=i.resource[o],l=Math.ceil(s/n.blockWidth)*n.blockBytes;t.device.queue.writeTexture({texture:e,mipLevel:o},a,{offset:0,bytesPerRow:l},{width:Math.ceil(s/n.blockWidth)*n.blockWidth,height:Math.ceil(r/n.blockHeight)*n.blockHeight,depthOrArrayLayers:1}),s=Math.max(s>>1,1),r=Math.max(r>>1,1)}}},jx={type:"image",upload(i,e,t){const s=i.resource;if(!s)return;if(globalThis.HTMLImageElement&&s instanceof HTMLImageElement){const a=Y.get().createCanvas(s.width,s.height);a.getContext("2d").drawImage(s,0,0,s.width,s.height),i.resource=a,L("ImageSource: Image element passed, converting to canvas and replacing resource.")}const r=Math.min(e.width,i.resourceWidth||i.pixelWidth),n=Math.min(e.height,i.resourceHeight||i.pixelHeight),o=i.alphaMode==="premultiply-alpha-on-upload";t.device.queue.copyExternalImageToTexture({source:s},{texture:e,premultipliedAlpha:o},{width:r,height:n})}},_P={type:"video",upload(i,e,t){jx.upload(i,e,t)}};class yP{constructor(e){this.device=e,this.sampler=e.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(e){let t=this.pipelines[e];return t||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
|
|
1101
1101
|
var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
|
|
1102
1102
|
vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0));
|
|
1103
1103
|
|
|
@@ -1121,7 +1121,7 @@ fn mainFragment(
|
|
|
1121
1121
|
fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
|
|
1122
1122
|
return textureSample(img, imgSampler, texCoord);
|
|
1123
1123
|
}
|
|
1124
|
-
`})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){const t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let s=e;const r=e.depthOrArrayLayers||1,n=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};s=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<r;++l){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),h=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const d=s.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),f=o.beginRenderPass({colorAttachments:[{view:d,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),p=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});f.setPipeline(t),f.setBindGroup(0,p),f.draw(3,1,0,0),f.end(),c=d}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:s,mipLevel:c-1},{texture:e,mipLevel:c},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||s.destroy(),e}}class Z_{constructor(e){this.managedTextures=[],this._gpuSources=Object.create(null),this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._textureViewHash=Object.create(null),this._uploads={image:j_,buffer:mP,video:xP,compressed:_P},this._renderer=e,e.renderableGC.addManagedHash(this,"_gpuSources"),e.renderableGC.addManagedHash(this,"_gpuSamplers"),e.renderableGC.addManagedHash(this,"_bindGroupHash"),e.renderableGC.addManagedHash(this,"_textureViewHash")}contextChange(e){this._gpu=e}initSource(e){return this._gpuSources[e.uid]?this._gpuSources[e.uid]:this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){const l=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(l))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);const s=K_[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/s.blockWidth)*s.blockWidth,n=Math.ceil(e.pixelHeight/s.blockHeight)*s.blockHeight,o={label:e.label,size:{width:r,height:n},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},a=this._gpuSources[e.uid]=this._gpu.device.createTexture(o);return this.managedTextures.includes(e)||(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("destroy",this.onSourceDestroy,this),e.on("unload",this.onSourceUnload,this),e.on("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.push(e)),this.onSourceUpdate(e),a}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onSourceUnload(e){const t=this._gpuSources[e.uid];t&&(this._gpuSources[e.uid]=null,t.destroy())}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new yP(this._gpu.device));const t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceDestroy(e){e.off("update",this.onSourceUpdate,this),e.off("unload",this.onSourceUnload,this),e.off("destroy",this.onSourceDestroy,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.splice(this.managedTextures.indexOf(e),1),this.onSourceUnload(e)}onSourceResize(e){const t=this._gpuSources[e.uid];t?(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(this._textureViewHash[e.uid]=null,this._bindGroupHash[e.uid]=null,this.onSourceUnload(e),this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){return this._gpuSources[e.uid]||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]??this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new Ot({0:t,1:t.style,2:new He({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){const t=e.source;return this._textureViewHash[t.uid]??this._createTextureView(t)}_createTextureView(e){return this._textureViewHash[e.uid]=this.getGpuSource(e).createView(),this._textureViewHash[e.uid]}generateCanvas(e){const t=this._renderer,s=t.gpu.device.createCommandEncoder(),r=Y.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:Y.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),s.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([s.finish()]),r}getPixels(e){const t=this.generateCanvas(e),s=Gt.getOptimalCanvasAndContext(t.width,t.height),r=s.context;r.drawImage(t,0,0);const{width:n,height:o}=t,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return Gt.returnCanvasAndContext(s),{pixels:l,width:n,height:o}}destroy(){this.managedTextures.slice().forEach(e=>this.onSourceDestroy(e)),this.managedTextures=null;for(const e of Object.keys(this._bindGroupHash)){const t=Number(e);this._bindGroupHash[t]?.destroy(),this._bindGroupHash[t]=null}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSources=null,this._bindGroupHash=null,this._textureViewHash=null,this._gpuSamplers=null}}Z_.extension={type:[b.WebGPUSystem],name:"texture"};class J_{constructor(){this._maxTextures=0}contextChange(e){const t=new He({uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const s=ks({name:"graphics",bits:[ju,Qu(this._maxTextures),LI,Bs]});this.shader=new ot({gpuProgram:s,resources:{localUniforms:t}})}execute(e,t){const s=t.context,r=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s),c=n.encoder;c.setGeometry(a.geometry,r.gpuProgram);const h=n.globalUniforms.bindGroup;c.setBindGroup(0,h,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);c.setBindGroup(2,u,r.gpuProgram);const d=l.instructions;let f=null;for(let p=0;p<l.instructionSize;p++){const g=d[p];if(g.topology!==f&&(f=g.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,g.topology)),r.groups[1]=g.bindGroup,!g.gpuBindGroup){const m=g.textures;g.bindGroup=Yu(m.textures,m.count,this._maxTextures),g.gpuBindGroup=n.bindGroup.getBindGroup(g.bindGroup,r.gpuProgram,1)}c.setBindGroup(1,g.bindGroup,r.gpuProgram),c.renderPassEncoder.drawIndexed(g.size,1,g.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}J_.extension={type:[b.WebGPUPipesAdaptor],name:"graphics"};class Q_{init(){const e=ks({name:"mesh",bits:[Vs,HI,Bs]});this._shader=new ot({gpuProgram:e,resources:{uTexture:M.EMPTY._source,uSampler:M.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new O}}}})}execute(e,t){const s=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=s.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){L("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=s.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=s.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}s.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Q_.extension={type:[b.WebGPUPipesAdaptor],name:"mesh"};const vP=[...k_,W_,N_,Hd,L_,G_,Z_,X_,Y_,q_,$_,z_,H_,D_],bP=[...F_,V_],TP=[O0,Q_,J_],ex=[],tx=[],ix=[];V.handleByNamedList(b.WebGPUSystem,ex),V.handleByNamedList(b.WebGPUPipes,tx),V.handleByNamedList(b.WebGPUPipesAdaptor,ix),V.add(...vP,...bP,...TP);class wP extends $r{constructor(){const e={name:"webgpu",type:Qe.WEBGPU,systems:ex,renderPipes:tx,renderPipeAdaptors:ix};super(e)}}const SP=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:wP},Symbol.toStringTag,{value:"Module"}));class CP{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Se.return(e)}),this.batches.length=0}}class sx{constructor(e,t){this.state=ft.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this)}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,s=!!e._gpuData,r=this.renderer.graphicsContext.updateGpuContext(t);return!!(r.isBatchable||s!==r.isBatchable)}addRenderable(e,t){const s=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),s.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const s=this._getGpuDataForRenderable(e).batches;for(let r=0;r<s.length;r++){const n=s[r];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,s=e.context;if(!t.graphicsContext.getGpuContext(s).batches.length)return;const n=s.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const o=n.resources.localUniforms.uniforms;o.uTransformMatrix=e.groupTransform,o.uRound=t._roundPixels|e._roundPixels,Xs(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),s=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),s.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const s=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let n=0;n<r.length;n++){const o=r[n];s.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new CP;return e._gpuData[this.renderer.uid]=t,t}_updateBatchesForRenderable(e,t){const s=e.context,r=this.renderer.graphicsContext.getGpuContext(s),n=this.renderer._roundPixels|e._roundPixels;t.batches=r.batches.map(o=>{const a=Se.get(rd);return o.copyTo(a),a.renderable=e,a.roundPixels=n,a})}destroy(){this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}sx.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"graphics"};const rx=class gy extends wd{constructor(...e){super({});let t=e[0]??{};typeof t=="number"&&(W(Q,"PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead"),t={width:t,height:e[1],verticesX:e[2],verticesY:e[3]}),this.build(t)}build(e){e={...gy.defaultOptions,...e},this.verticesX=this.verticesX??e.verticesX,this.verticesY=this.verticesY??e.verticesY,this.width=this.width??e.width,this.height=this.height??e.height;const t=this.verticesX*this.verticesY,s=[],r=[],n=[],o=this.verticesX-1,a=this.verticesY-1,l=this.width/o,c=this.height/a;for(let u=0;u<t;u++){const d=u%this.verticesX,f=u/this.verticesX|0;s.push(d*l,f*c),r.push(d/o,f/a)}const h=o*a;for(let u=0;u<h;u++){const d=u%o,f=u/o|0,p=f*this.verticesX+d,g=f*this.verticesX+d+1,m=(f+1)*this.verticesX+d,_=(f+1)*this.verticesX+d+1;n.push(p,g,m,g,_,m)}this.buffers[0].data=new Float32Array(s),this.buffers[1].data=new Float32Array(r),this.indexBuffer.data=new Uint32Array(n),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};rx.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};let AP=rx;class Wd{constructor(){this.batcherName="default",this.packAsQuad=!1,this.indexOffset=0,this.attributeOffset=0,this.roundPixels=0,this._batcher=null,this._batch=null,this._textureMatrixUpdateId=-1,this._uvUpdateId=-1}get blendMode(){return this.renderable.groupBlendMode}get topology(){return this._topology||this.geometry.topology}set topology(e){this._topology=e}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.geometry=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}setTexture(e){this.texture!==e&&(this.texture=e,this._textureMatrixUpdateId=-1)}get uvs(){const t=this.geometry.getBuffer("aUV"),s=t.data;let r=s;const n=this.texture.textureMatrix;return n.isSimple||(r=this._transformedUvs,(this._textureMatrixUpdateId!==n._updateID||this._uvUpdateId!==t._updateID)&&((!r||r.length<s.length)&&(r=this._transformedUvs=new Float32Array(s.length)),this._textureMatrixUpdateId=n._updateID,this._uvUpdateId=t._updateID,n.multiplyUvs(s,r))),r}get positions(){return this.geometry.positions}get indices(){return this.geometry.indices}get color(){return this.renderable.groupColorAlpha}get groupTransform(){return this.renderable.groupTransform}get attributeSize(){return this.geometry.positions.length/2}get indexSize(){return this.geometry.indices.length}}class nx{destroy(){}}class ox{constructor(e,t){this.localUniforms=new He({uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new Ot({0:this.localUniforms}),this.renderer=e,this._adaptor=t,this._adaptor.init()}validateRenderable(e){const t=this._getMeshData(e),s=t.batched,r=e.batched;if(t.batched=r,s!==r)return!0;if(r){const n=e._geometry;if(n.indices.length!==t.indexSize||n.positions.length!==t.vertexSize)return t.indexSize=n.indices.length,t.vertexSize=n.positions.length,!0;const o=this._getBatchableMesh(e);return o.texture.uid!==e._texture.uid&&(o._textureMatrixUpdateId=-1),!o._batcher.checkAndUpdateTexture(o,e._texture)}return!1}addRenderable(e,t){const s=this.renderer.renderPipes.batch,r=this._getMeshData(e);if(e.didViewUpdate&&(r.indexSize=e._geometry.indices?.length,r.vertexSize=e._geometry.positions?.length),r.batched){const n=this._getBatchableMesh(e);n.setTexture(e._texture),n.geometry=e._geometry,s.addToBatch(n,t)}else s.break(t),t.add(e)}updateRenderable(e){if(e.batched){const t=this._getBatchableMesh(e);t.setTexture(e._texture),t.geometry=e._geometry,t._batcher.updateElement(t)}}execute(e){if(!e.isRenderable)return;e.state.blendMode=Is(e.groupBlendMode,e.texture._source);const t=this.localUniforms;t.uniforms.uTransformMatrix=e.groupTransform,t.uniforms.uRound=this.renderer._roundPixels|e._roundPixels,t.update(),Xs(e.groupColorAlpha,t.uniforms.uColor,0),this._adaptor.execute(this,e)}_getMeshData(e){var t,s;return(t=e._gpuData)[s=this.renderer.uid]||(t[s]=new nx),e._gpuData[this.renderer.uid].meshData||this._initMeshData(e)}_initMeshData(e){return e._gpuData[this.renderer.uid].meshData={batched:e.batched,indexSize:0,vertexSize:0},e._gpuData[this.renderer.uid].meshData}_getBatchableMesh(e){var t,s;return(t=e._gpuData)[s=this.renderer.uid]||(t[s]=new nx),e._gpuData[this.renderer.uid].batchableMesh||this._initBatchableMesh(e)}_initBatchableMesh(e){const t=new Wd;return t.renderable=e,t.setTexture(e._texture),t.transform=e.groupTransform,t.roundPixels=this.renderer._roundPixels|e._roundPixels,e._gpuData[this.renderer.uid].batchableMesh=t,t}destroy(){this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}}ox.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"mesh"};class EP{execute(e,t){const s=e.state,r=e.renderer,n=t.shader||e.defaultShader;n.resources.uTexture=t.texture._source,n.resources.uniforms=e.localUniforms;const o=r.gl,a=e.getBuffers(t);r.shader.bind(n),r.state.set(s),r.geometry.bind(a.geometry,n.glProgram);const c=a.geometry.indexBuffer.data.BYTES_PER_ELEMENT===2?o.UNSIGNED_SHORT:o.UNSIGNED_INT;o.drawElements(o.TRIANGLES,t.particleChildren.length*6,c,0)}}class IP{execute(e,t){const s=e.renderer,r=t.shader||e.defaultShader;r.groups[0]=s.renderPipes.uniformBatch.getUniformBindGroup(e.localUniforms,!0),r.groups[1]=s.texture.getTextureBindGroup(t.texture);const n=e.state,o=e.getBuffers(t);s.encoder.draw({geometry:o.geometry,shader:t.shader||e.defaultShader,state:n,size:t.particleChildren.length*6})}}function ax(i,e=null){const t=i*6;if(t>65535?e||(e=new Uint32Array(t)):e||(e=new Uint16Array(t)),e.length!==t)throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${t}`);for(let s=0,r=0;s<t;s+=6,r+=4)e[s+0]=r+0,e[s+1]=r+1,e[s+2]=r+2,e[s+3]=r+0,e[s+4]=r+2,e[s+5]=r+3;return e}function PP(i){return{dynamicUpdate:lx(i,!0),staticUpdate:lx(i,!1)}}function lx(i,e){const t=[];t.push(`
|
|
1124
|
+
`})),t=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:e}]}}),this.pipelines[e]=t),t}generateMipmap(e){const t=this._getMipmapPipeline(e.format);if(e.dimension==="3d"||e.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let s=e;const r=e.depthOrArrayLayers||1,n=e.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!n){const l={size:{width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r},format:e.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:e.mipLevelCount-1};s=this.device.createTexture(l)}const o=this.device.createCommandEncoder({}),a=t.getBindGroupLayout(0);for(let l=0;l<r;++l){let c=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),h=n?1:0;for(let u=1;u<e.mipLevelCount;++u){const d=s.createView({baseMipLevel:h++,mipLevelCount:1,dimension:"2d",baseArrayLayer:l,arrayLayerCount:1}),f=o.beginRenderPass({colorAttachments:[{view:d,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),p=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.sampler},{binding:1,resource:c}]});f.setPipeline(t),f.setBindGroup(0,p),f.draw(3,1,0,0),f.end(),c=d}}if(!n){const l={width:Math.ceil(e.width/2),height:Math.ceil(e.height/2),depthOrArrayLayers:r};for(let c=1;c<e.mipLevelCount;++c)o.copyTextureToTexture({texture:s,mipLevel:c-1},{texture:e,mipLevel:c},l),l.width=Math.ceil(l.width/2),l.height=Math.ceil(l.height/2)}return this.device.queue.submit([o.finish()]),n||s.destroy(),e}}class Zx{constructor(e){this.managedTextures=[],this._gpuSources=Object.create(null),this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._textureViewHash=Object.create(null),this._uploads={image:jx,buffer:mP,video:_P,compressed:xP},this._renderer=e,e.renderableGC.addManagedHash(this,"_gpuSources"),e.renderableGC.addManagedHash(this,"_gpuSamplers"),e.renderableGC.addManagedHash(this,"_bindGroupHash"),e.renderableGC.addManagedHash(this,"_textureViewHash")}contextChange(e){this._gpu=e}initSource(e){return this._gpuSources[e.uid]?this._gpuSources[e.uid]:this._initSource(e)}_initSource(e){if(e.autoGenerateMipmaps){const l=Math.max(e.pixelWidth,e.pixelHeight);e.mipLevelCount=Math.floor(Math.log2(l))+1}let t=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;e.uploadMethodId!=="compressed"&&(t|=GPUTextureUsage.RENDER_ATTACHMENT,t|=GPUTextureUsage.COPY_SRC);const s=Kx[e.format]||{blockWidth:1,blockHeight:1},r=Math.ceil(e.pixelWidth/s.blockWidth)*s.blockWidth,n=Math.ceil(e.pixelHeight/s.blockHeight)*s.blockHeight,o={label:e.label,size:{width:r,height:n},format:e.format,sampleCount:e.sampleCount,mipLevelCount:e.mipLevelCount,dimension:e.dimension,usage:t},a=this._gpuSources[e.uid]=this._gpu.device.createTexture(o);return this.managedTextures.includes(e)||(e.on("update",this.onSourceUpdate,this),e.on("resize",this.onSourceResize,this),e.on("destroy",this.onSourceDestroy,this),e.on("unload",this.onSourceUnload,this),e.on("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.push(e)),this.onSourceUpdate(e),a}onSourceUpdate(e){const t=this.getGpuSource(e);t&&(this._uploads[e.uploadMethodId]&&this._uploads[e.uploadMethodId].upload(e,t,this._gpu),e.autoGenerateMipmaps&&e.mipLevelCount>1&&this.onUpdateMipmaps(e))}onSourceUnload(e){const t=this._gpuSources[e.uid];t&&(this._gpuSources[e.uid]=null,t.destroy())}onUpdateMipmaps(e){this._mipmapGenerator||(this._mipmapGenerator=new yP(this._gpu.device));const t=this.getGpuSource(e);this._mipmapGenerator.generateMipmap(t)}onSourceDestroy(e){e.off("update",this.onSourceUpdate,this),e.off("unload",this.onSourceUnload,this),e.off("destroy",this.onSourceDestroy,this),e.off("resize",this.onSourceResize,this),e.off("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.splice(this.managedTextures.indexOf(e),1),this.onSourceUnload(e)}onSourceResize(e){const t=this._gpuSources[e.uid];t?(t.width!==e.pixelWidth||t.height!==e.pixelHeight)&&(this._textureViewHash[e.uid]=null,this._bindGroupHash[e.uid]=null,this.onSourceUnload(e),this.initSource(e)):this.initSource(e)}_initSampler(e){return this._gpuSamplers[e._resourceId]=this._gpu.device.createSampler(e),this._gpuSamplers[e._resourceId]}getGpuSampler(e){return this._gpuSamplers[e._resourceId]||this._initSampler(e)}getGpuSource(e){return this._gpuSources[e.uid]||this.initSource(e)}getTextureBindGroup(e){return this._bindGroupHash[e.uid]??this._createTextureBindGroup(e)}_createTextureBindGroup(e){const t=e.source;return this._bindGroupHash[e.uid]=new Ot({0:t,1:t.style,2:new He({uTextureMatrix:{type:"mat3x3<f32>",value:e.textureMatrix.mapCoord}})}),this._bindGroupHash[e.uid]}getTextureView(e){const t=e.source;return this._textureViewHash[t.uid]??this._createTextureView(t)}_createTextureView(e){return this._textureViewHash[e.uid]=this.getGpuSource(e).createView(),this._textureViewHash[e.uid]}generateCanvas(e){const t=this._renderer,s=t.gpu.device.createCommandEncoder(),r=Y.get().createCanvas();r.width=e.source.pixelWidth,r.height=e.source.pixelHeight;const n=r.getContext("webgpu");return n.configure({device:t.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:Y.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),s.copyTextureToTexture({texture:t.texture.getGpuSource(e.source),origin:{x:0,y:0}},{texture:n.getCurrentTexture()},{width:r.width,height:r.height}),t.gpu.device.queue.submit([s.finish()]),r}getPixels(e){const t=this.generateCanvas(e),s=Gt.getOptimalCanvasAndContext(t.width,t.height),r=s.context;r.drawImage(t,0,0);const{width:n,height:o}=t,a=r.getImageData(0,0,n,o),l=new Uint8ClampedArray(a.data.buffer);return Gt.returnCanvasAndContext(s),{pixels:l,width:n,height:o}}destroy(){this.managedTextures.slice().forEach(e=>this.onSourceDestroy(e)),this.managedTextures=null;for(const e of Object.keys(this._bindGroupHash)){const t=Number(e);this._bindGroupHash[t]?.destroy(),this._bindGroupHash[t]=null}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSources=null,this._bindGroupHash=null,this._textureViewHash=null,this._gpuSamplers=null}}Zx.extension={type:[b.WebGPUSystem],name:"texture"};class Jx{constructor(){this._maxTextures=0}contextChange(e){const t=new He({uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=e.limits.maxBatchableTextures;const s=ks({name:"graphics",bits:[ju,Qu(this._maxTextures),LI,Bs]});this.shader=new ot({gpuProgram:s,resources:{localUniforms:t}})}execute(e,t){const s=t.context,r=s.customShader||this.shader,n=e.renderer,o=n.graphicsContext,{batcher:a,instructions:l}=o.getContextRenderData(s),c=n.encoder;c.setGeometry(a.geometry,r.gpuProgram);const h=n.globalUniforms.bindGroup;c.setBindGroup(0,h,r.gpuProgram);const u=n.renderPipes.uniformBatch.getUniformBindGroup(r.resources.localUniforms,!0);c.setBindGroup(2,u,r.gpuProgram);const d=l.instructions;let f=null;for(let p=0;p<l.instructionSize;p++){const g=d[p];if(g.topology!==f&&(f=g.topology,c.setPipelineFromGeometryProgramAndState(a.geometry,r.gpuProgram,e.state,g.topology)),r.groups[1]=g.bindGroup,!g.gpuBindGroup){const m=g.textures;g.bindGroup=Yu(m.textures,m.count,this._maxTextures),g.gpuBindGroup=n.bindGroup.getBindGroup(g.bindGroup,r.gpuProgram,1)}c.setBindGroup(1,g.bindGroup,r.gpuProgram),c.renderPassEncoder.drawIndexed(g.size,1,g.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}Jx.extension={type:[b.WebGPUPipesAdaptor],name:"graphics"};class Qx{init(){const e=ks({name:"mesh",bits:[Vs,HI,Bs]});this._shader=new ot({gpuProgram:e,resources:{uTexture:M.EMPTY._source,uSampler:M.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new O}}}})}execute(e,t){const s=e.renderer;let r=t._shader;if(!r)r=this._shader,r.groups[2]=s.texture.getTextureBindGroup(t.texture);else if(!r.gpuProgram){L("Mesh shader has no gpuProgram",t.shader);return}const n=r.gpuProgram;if(n.autoAssignGlobalUniforms&&(r.groups[0]=s.globalUniforms.bindGroup),n.autoAssignLocalUniforms){const o=e.localUniforms;r.groups[1]=s.renderPipes.uniformBatch.getUniformBindGroup(o,!0)}s.encoder.draw({geometry:t._geometry,shader:r,state:t.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Qx.extension={type:[b.WebGPUPipesAdaptor],name:"mesh"};const vP=[...kx,Wx,Nx,Hd,Lx,Gx,Zx,Xx,Yx,qx,$x,zx,Hx,Dx],bP=[...Fx,Vx],TP=[O0,Qx,Jx],e_=[],t_=[],i_=[];V.handleByNamedList(b.WebGPUSystem,e_),V.handleByNamedList(b.WebGPUPipes,t_),V.handleByNamedList(b.WebGPUPipesAdaptor,i_),V.add(...vP,...bP,...TP);class wP extends $r{constructor(){const e={name:"webgpu",type:Qe.WEBGPU,systems:e_,renderPipes:t_,renderPipeAdaptors:i_};super(e)}}const SP=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:wP},Symbol.toStringTag,{value:"Module"}));class CP{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Se.return(e)}),this.batches.length=0}}class s_{constructor(e,t){this.state=ft.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this)}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,s=!!e._gpuData,r=this.renderer.graphicsContext.updateGpuContext(t);return!!(r.isBatchable||s!==r.isBatchable)}addRenderable(e,t){const s=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),s.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const s=this._getGpuDataForRenderable(e).batches;for(let r=0;r<s.length;r++){const n=s[r];n._batcher.updateElement(n)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,s=e.context;if(!t.graphicsContext.getGpuContext(s).batches.length)return;const n=s.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const o=n.resources.localUniforms.uniforms;o.uTransformMatrix=e.groupTransform,o.uRound=t._roundPixels|e._roundPixels,Xs(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),s=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),s.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const s=this.renderer.renderPipes.batch,r=this._getGpuDataForRenderable(e).batches;for(let n=0;n<r.length;n++){const o=r[n];s.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new CP;return e._gpuData[this.renderer.uid]=t,t}_updateBatchesForRenderable(e,t){const s=e.context,r=this.renderer.graphicsContext.getGpuContext(s),n=this.renderer._roundPixels|e._roundPixels;t.batches=r.batches.map(o=>{const a=Se.get(rd);return o.copyTo(a),a.renderable=e,a.roundPixels=n,a})}destroy(){this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}s_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"graphics"};const r_=class gy extends wd{constructor(...e){super({});let t=e[0]??{};typeof t=="number"&&(W(Q,"PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead"),t={width:t,height:e[1],verticesX:e[2],verticesY:e[3]}),this.build(t)}build(e){e={...gy.defaultOptions,...e},this.verticesX=this.verticesX??e.verticesX,this.verticesY=this.verticesY??e.verticesY,this.width=this.width??e.width,this.height=this.height??e.height;const t=this.verticesX*this.verticesY,s=[],r=[],n=[],o=this.verticesX-1,a=this.verticesY-1,l=this.width/o,c=this.height/a;for(let u=0;u<t;u++){const d=u%this.verticesX,f=u/this.verticesX|0;s.push(d*l,f*c),r.push(d/o,f/a)}const h=o*a;for(let u=0;u<h;u++){const d=u%o,f=u/o|0,p=f*this.verticesX+d,g=f*this.verticesX+d+1,m=(f+1)*this.verticesX+d,x=(f+1)*this.verticesX+d+1;n.push(p,g,m,g,x,m)}this.buffers[0].data=new Float32Array(s),this.buffers[1].data=new Float32Array(r),this.indexBuffer.data=new Uint32Array(n),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};r_.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};let AP=r_;class Wd{constructor(){this.batcherName="default",this.packAsQuad=!1,this.indexOffset=0,this.attributeOffset=0,this.roundPixels=0,this._batcher=null,this._batch=null,this._textureMatrixUpdateId=-1,this._uvUpdateId=-1}get blendMode(){return this.renderable.groupBlendMode}get topology(){return this._topology||this.geometry.topology}set topology(e){this._topology=e}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.geometry=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}setTexture(e){this.texture!==e&&(this.texture=e,this._textureMatrixUpdateId=-1)}get uvs(){const t=this.geometry.getBuffer("aUV"),s=t.data;let r=s;const n=this.texture.textureMatrix;return n.isSimple||(r=this._transformedUvs,(this._textureMatrixUpdateId!==n._updateID||this._uvUpdateId!==t._updateID)&&((!r||r.length<s.length)&&(r=this._transformedUvs=new Float32Array(s.length)),this._textureMatrixUpdateId=n._updateID,this._uvUpdateId=t._updateID,n.multiplyUvs(s,r))),r}get positions(){return this.geometry.positions}get indices(){return this.geometry.indices}get color(){return this.renderable.groupColorAlpha}get groupTransform(){return this.renderable.groupTransform}get attributeSize(){return this.geometry.positions.length/2}get indexSize(){return this.geometry.indices.length}}class n_{destroy(){}}class o_{constructor(e,t){this.localUniforms=new He({uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new Ot({0:this.localUniforms}),this.renderer=e,this._adaptor=t,this._adaptor.init()}validateRenderable(e){const t=this._getMeshData(e),s=t.batched,r=e.batched;if(t.batched=r,s!==r)return!0;if(r){const n=e._geometry;if(n.indices.length!==t.indexSize||n.positions.length!==t.vertexSize)return t.indexSize=n.indices.length,t.vertexSize=n.positions.length,!0;const o=this._getBatchableMesh(e);return o.texture.uid!==e._texture.uid&&(o._textureMatrixUpdateId=-1),!o._batcher.checkAndUpdateTexture(o,e._texture)}return!1}addRenderable(e,t){const s=this.renderer.renderPipes.batch,r=this._getMeshData(e);if(e.didViewUpdate&&(r.indexSize=e._geometry.indices?.length,r.vertexSize=e._geometry.positions?.length),r.batched){const n=this._getBatchableMesh(e);n.setTexture(e._texture),n.geometry=e._geometry,s.addToBatch(n,t)}else s.break(t),t.add(e)}updateRenderable(e){if(e.batched){const t=this._getBatchableMesh(e);t.setTexture(e._texture),t.geometry=e._geometry,t._batcher.updateElement(t)}}execute(e){if(!e.isRenderable)return;e.state.blendMode=Is(e.groupBlendMode,e.texture._source);const t=this.localUniforms;t.uniforms.uTransformMatrix=e.groupTransform,t.uniforms.uRound=this.renderer._roundPixels|e._roundPixels,t.update(),Xs(e.groupColorAlpha,t.uniforms.uColor,0),this._adaptor.execute(this,e)}_getMeshData(e){var t,s;return(t=e._gpuData)[s=this.renderer.uid]||(t[s]=new n_),e._gpuData[this.renderer.uid].meshData||this._initMeshData(e)}_initMeshData(e){return e._gpuData[this.renderer.uid].meshData={batched:e.batched,indexSize:0,vertexSize:0},e._gpuData[this.renderer.uid].meshData}_getBatchableMesh(e){var t,s;return(t=e._gpuData)[s=this.renderer.uid]||(t[s]=new n_),e._gpuData[this.renderer.uid].batchableMesh||this._initBatchableMesh(e)}_initBatchableMesh(e){const t=new Wd;return t.renderable=e,t.setTexture(e._texture),t.transform=e.groupTransform,t.roundPixels=this.renderer._roundPixels|e._roundPixels,e._gpuData[this.renderer.uid].batchableMesh=t,t}destroy(){this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}}o_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"mesh"};class EP{execute(e,t){const s=e.state,r=e.renderer,n=t.shader||e.defaultShader;n.resources.uTexture=t.texture._source,n.resources.uniforms=e.localUniforms;const o=r.gl,a=e.getBuffers(t);r.shader.bind(n),r.state.set(s),r.geometry.bind(a.geometry,n.glProgram);const c=a.geometry.indexBuffer.data.BYTES_PER_ELEMENT===2?o.UNSIGNED_SHORT:o.UNSIGNED_INT;o.drawElements(o.TRIANGLES,t.particleChildren.length*6,c,0)}}class IP{execute(e,t){const s=e.renderer,r=t.shader||e.defaultShader;r.groups[0]=s.renderPipes.uniformBatch.getUniformBindGroup(e.localUniforms,!0),r.groups[1]=s.texture.getTextureBindGroup(t.texture);const n=e.state,o=e.getBuffers(t);s.encoder.draw({geometry:o.geometry,shader:t.shader||e.defaultShader,state:n,size:t.particleChildren.length*6})}}function a_(i,e=null){const t=i*6;if(t>65535?e||(e=new Uint32Array(t)):e||(e=new Uint16Array(t)),e.length!==t)throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${t}`);for(let s=0,r=0;s<t;s+=6,r+=4)e[s+0]=r+0,e[s+1]=r+1,e[s+2]=r+2,e[s+3]=r+0,e[s+4]=r+2,e[s+5]=r+3;return e}function PP(i){return{dynamicUpdate:l_(i,!0),staticUpdate:l_(i,!1)}}function l_(i,e){const t=[];t.push(`
|
|
1125
1125
|
|
|
1126
1126
|
var index = 0;
|
|
1127
1127
|
|
|
@@ -1135,7 +1135,7 @@ fn mainFragment(
|
|
|
1135
1135
|
`),t.unshift(`
|
|
1136
1136
|
var stride = ${s};
|
|
1137
1137
|
`);const r=t.join(`
|
|
1138
|
-
`);return new Function("ps","f32v","u32v",r)}class RP{constructor(e){this._size=0,this._generateParticleUpdateCache={};const t=this._size=e.size??1e3,s=e.properties;let r=0,n=0;for(const h in s){const u=s[h],d=jt(u.format);u.dynamic?n+=d.stride:r+=d.stride}this._dynamicStride=n/4,this._staticStride=r/4,this.staticAttributeBuffer=new Ni(t*4*r),this.dynamicAttributeBuffer=new Ni(t*4*n),this.indexBuffer=
|
|
1138
|
+
`);return new Function("ps","f32v","u32v",r)}class RP{constructor(e){this._size=0,this._generateParticleUpdateCache={};const t=this._size=e.size??1e3,s=e.properties;let r=0,n=0;for(const h in s){const u=s[h],d=jt(u.format);u.dynamic?n+=d.stride:r+=d.stride}this._dynamicStride=n/4,this._staticStride=r/4,this.staticAttributeBuffer=new Ni(t*4*r),this.dynamicAttributeBuffer=new Ni(t*4*n),this.indexBuffer=a_(t);const o=new Ms;let a=0,l=0;this._staticBuffer=new tt({data:new Float32Array(1),label:"static-particle-buffer",shrinkToFit:!1,usage:j.VERTEX|j.COPY_DST}),this._dynamicBuffer=new tt({data:new Float32Array(1),label:"dynamic-particle-buffer",shrinkToFit:!1,usage:j.VERTEX|j.COPY_DST});for(const h in s){const u=s[h],d=jt(u.format);u.dynamic?(o.addAttribute(u.attributeName,{buffer:this._dynamicBuffer,stride:this._dynamicStride*4,offset:a*4,format:u.format}),a+=d.size):(o.addAttribute(u.attributeName,{buffer:this._staticBuffer,stride:this._staticStride*4,offset:l*4,format:u.format}),l+=d.size)}o.addIndex(this.indexBuffer);const c=this.getParticleUpdate(s);this._dynamicUpload=c.dynamicUpdate,this._staticUpload=c.staticUpdate,this.geometry=o}getParticleUpdate(e){const t=MP(e);return this._generateParticleUpdateCache[t]?this._generateParticleUpdateCache[t]:(this._generateParticleUpdateCache[t]=this.generateParticleUpdate(e),this._generateParticleUpdateCache[t])}generateParticleUpdate(e){return PP(e)}update(e,t){e.length>this._size&&(t=!0,this._size=Math.max(e.length,this._size*1.5|0),this.staticAttributeBuffer=new Ni(this._size*this._staticStride*4*4),this.dynamicAttributeBuffer=new Ni(this._size*this._dynamicStride*4*4),this.indexBuffer=a_(this._size),this.geometry.indexBuffer.setDataWithSize(this.indexBuffer,this.indexBuffer.byteLength,!0));const s=this.dynamicAttributeBuffer;if(this._dynamicUpload(e,s.float32View,s.uint32View),this._dynamicBuffer.setDataWithSize(this.dynamicAttributeBuffer.float32View,e.length*this._dynamicStride*4,!0),t){const r=this.staticAttributeBuffer;this._staticUpload(e,r.float32View,r.uint32View),this._staticBuffer.setDataWithSize(r.float32View,e.length*this._staticStride*4,!0)}}destroy(){this._staticBuffer.destroy(),this._dynamicBuffer.destroy(),this.geometry.destroy()}}function MP(i){const e=[];for(const t in i){const s=i[t];e.push(t,s.code,s.dynamic?"d":"s")}return e.join("_")}var kP=`varying vec2 vUV;
|
|
1139
1139
|
varying vec4 vColor;
|
|
1140
1140
|
|
|
1141
1141
|
uniform sampler2D uTexture;
|
|
@@ -1182,7 +1182,7 @@ void main(void){
|
|
|
1182
1182
|
vUV = aUV;
|
|
1183
1183
|
vColor = vec4(aColor.rgb * aColor.a, aColor.a) * uColor;
|
|
1184
1184
|
}
|
|
1185
|
-
`,
|
|
1185
|
+
`,c_=`
|
|
1186
1186
|
struct ParticleUniforms {
|
|
1187
1187
|
uTranslationMatrix:mat3x3<f32>,
|
|
1188
1188
|
uColor:vec4<f32>,
|
|
@@ -1244,7 +1244,7 @@ fn mainFragment(
|
|
|
1244
1244
|
var sample = textureSample(uTexture, uSampler, uv) * color;
|
|
1245
1245
|
|
|
1246
1246
|
return sample;
|
|
1247
|
-
}`;class BP extends ot{constructor(){const e=At.from({vertex:FP,fragment:kP}),t=Ut.from({fragment:{source:
|
|
1247
|
+
}`;class BP extends ot{constructor(){const e=At.from({vertex:FP,fragment:kP}),t=Ut.from({fragment:{source:c_,entryPoint:"mainFragment"},vertex:{source:c_,entryPoint:"mainVertex"}});super({glProgram:e,gpuProgram:t,resources:{uTexture:M.WHITE.source,uSampler:new wt({}),uniforms:{uTranslationMatrix:{value:new O,type:"mat3x3<f32>"},uColor:{value:new ue(16777215),type:"vec4<f32>"},uRound:{value:1,type:"f32"},uResolution:{value:[0,0],type:"vec2<f32>"}}}})}}class h_{constructor(e,t){this.state=ft.for2d(),this.localUniforms=new He({uTranslationMatrix:{value:new O,type:"mat3x3<f32>"},uColor:{value:new Float32Array(4),type:"vec4<f32>"},uRound:{value:1,type:"f32"},uResolution:{value:[0,0],type:"vec2<f32>"}}),this.renderer=e,this.adaptor=t,this.defaultShader=new BP,this.state=ft.for2d()}validateRenderable(e){return!1}addRenderable(e,t){this.renderer.renderPipes.batch.break(t),t.add(e)}getBuffers(e){return e._gpuData[this.renderer.uid]||this._initBuffer(e)}_initBuffer(e){return e._gpuData[this.renderer.uid]=new RP({size:e.particleChildren.length,properties:e._properties}),e._gpuData[this.renderer.uid]}updateRenderable(e){}execute(e){const t=e.particleChildren;if(t.length===0)return;const s=this.renderer,r=this.getBuffers(e);e.texture||(e.texture=t[0].texture);const n=this.state;r.update(t,e._childrenDirty),e._childrenDirty=!1,n.blendMode=Is(e.blendMode,e.texture._source);const o=this.localUniforms.uniforms,a=o.uTranslationMatrix;e.worldTransform.copyTo(a),a.prepend(s.globalUniforms.globalUniformData.projectionMatrix),o.uResolution=s.globalUniforms.globalUniformData.resolution,o.uRound=s._roundPixels|e._roundPixels,Xs(e.groupColorAlpha,o.uColor,0),this.adaptor.execute(this,e)}destroy(){this.renderer=null,this.defaultShader&&(this.defaultShader.destroy(),this.defaultShader=null)}}class u_ extends h_{constructor(e){super(e,new EP)}}u_.extension={type:[b.WebGLPipes],name:"particle"};class d_ extends h_{constructor(e){super(e,new IP)}}d_.extension={type:[b.WebGPUPipes],name:"particle"};const f_=class xy extends AP{constructor(e={}){e={...xy.defaultOptions,...e},super({width:e.width,height:e.height,verticesX:4,verticesY:4}),this.update(e)}update(e){this.width=e.width??this.width,this.height=e.height??this.height,this._originalWidth=e.originalWidth??this._originalWidth,this._originalHeight=e.originalHeight??this._originalHeight,this._leftWidth=e.leftWidth??this._leftWidth,this._rightWidth=e.rightWidth??this._rightWidth,this._topHeight=e.topHeight??this._topHeight,this._bottomHeight=e.bottomHeight??this._bottomHeight,this._anchorX=e.anchor?.x,this._anchorY=e.anchor?.y,this.updateUvs(),this.updatePositions()}updatePositions(){const e=this.positions,{width:t,height:s,_leftWidth:r,_rightWidth:n,_topHeight:o,_bottomHeight:a,_anchorX:l,_anchorY:c}=this,h=r+n,u=t>h?1:t/h,d=o+a,f=s>d?1:s/d,p=Math.min(u,f),g=l*t,m=c*s;e[0]=e[8]=e[16]=e[24]=-g,e[2]=e[10]=e[18]=e[26]=r*p-g,e[4]=e[12]=e[20]=e[28]=t-n*p-g,e[6]=e[14]=e[22]=e[30]=t-g,e[1]=e[3]=e[5]=e[7]=-m,e[9]=e[11]=e[13]=e[15]=o*p-m,e[17]=e[19]=e[21]=e[23]=s-a*p-m,e[25]=e[27]=e[29]=e[31]=s-m,this.getBuffer("aPosition").update()}updateUvs(){const e=this.uvs;e[0]=e[8]=e[16]=e[24]=0,e[1]=e[3]=e[5]=e[7]=0,e[6]=e[14]=e[22]=e[30]=1,e[25]=e[27]=e[29]=e[31]=1;const t=1/this._originalWidth,s=1/this._originalHeight;e[2]=e[10]=e[18]=e[26]=t*this._leftWidth,e[9]=e[11]=e[13]=e[15]=s*this._topHeight,e[4]=e[12]=e[20]=e[28]=1-t*this._rightWidth,e[17]=e[19]=e[21]=e[23]=1-s*this._bottomHeight,this.getBuffer("aUV").update()}};f_.defaultOptions={width:100,height:100,leftWidth:10,topHeight:10,rightWidth:10,bottomHeight:10,originalWidth:100,originalHeight:100};let UP=f_;class OP extends Wd{constructor(){super(),this.geometry=new UP}destroy(){this.geometry.destroy()}}class p_{constructor(e){this._renderer=e}addRenderable(e,t){const s=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,s),this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const t=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,t),t._batcher.updateElement(t)}validateRenderable(e){const t=this._getGpuSprite(e);return!t._batcher.checkAndUpdateTexture(t,e._texture)}_updateBatchableSprite(e,t){t.geometry.update(e),t.setTexture(e._texture)}_getGpuSprite(e){return e._gpuData[this._renderer.uid]||this._initGPUSprite(e)}_initGPUSprite(e){const t=e._gpuData[this._renderer.uid]=new OP,s=t;return s.renderable=e,s.transform=e.groupTransform,s.texture=e._texture,s.roundPixels=this._renderer._roundPixels|e._roundPixels,e.didViewUpdate||this._updateBatchableSprite(e,s),t}destroy(){this._renderer=null}}p_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"nineSliceSprite"};const DP={name:"tiling-bit",vertex:{header:`
|
|
1248
1248
|
struct TilingUniforms {
|
|
1249
1249
|
uMapCoord:mat3x3<f32>,
|
|
1250
1250
|
uClampFrame:vec4<f32>,
|
|
@@ -1309,7 +1309,7 @@ fn mainFragment(
|
|
|
1309
1309
|
|
|
1310
1310
|
outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0
|
|
1311
1311
|
|
|
1312
|
-
`}};let Vd,$d;class zP extends ot{constructor(){Vd??(Vd=ks({name:"tiling-sprite-shader",bits:[Vs,DP,Bs]})),$d??($d=Fs({name:"tiling-sprite-shader",bits:[Cd,GP,Us]}));const e=new He({uMapCoord:{value:new O,type:"mat3x3<f32>"},uClampFrame:{value:new Float32Array([0,0,1,1]),type:"vec4<f32>"},uClampOffset:{value:new Float32Array([0,0]),type:"vec2<f32>"},uTextureTransform:{value:new O,type:"mat3x3<f32>"},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:"vec4<f32>"}});super({glProgram:$d,gpuProgram:Vd,resources:{localUniforms:new He({uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),tilingUniforms:e,uTexture:M.EMPTY.source,uSampler:M.EMPTY.source.style}})}updateUniforms(e,t,s,r,n,o){const a=this.resources.tilingUniforms,l=o.width,c=o.height,h=o.textureMatrix,u=a.uniforms.uTextureTransform;u.set(s.a*l/e,s.b*l/t,s.c*c/e,s.d*c/t,s.tx/e,s.ty/t),u.invert(),a.uniforms.uMapCoord=h.mapCoord,a.uniforms.uClampFrame=h.uClampFrame,a.uniforms.uClampOffset=h.uClampOffset,a.uniforms.uTextureTransform=u,a.uniforms.uSizeAnchor[0]=e,a.uniforms.uSizeAnchor[1]=t,a.uniforms.uSizeAnchor[2]=r,a.uniforms.uSizeAnchor[3]=n,o&&(this.resources.uTexture=o.source,this.resources.uSampler=o.source.style)}}class NP extends wd{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}}function LP(i,e){const t=i.anchor.x,s=i.anchor.y;e[0]=-t*i.width,e[1]=-s*i.height,e[2]=(1-t)*i.width,e[3]=-s*i.height,e[4]=(1-t)*i.width,e[5]=(1-s)*i.height,e[6]=-t*i.width,e[7]=(1-s)*i.height}function HP(i,e,t,s){let r=0;const n=i.length/e,o=s.a,a=s.b,l=s.c,c=s.d,h=s.tx,u=s.ty;for(t*=e;r<n;){const d=i[t],f=i[t+1];i[t]=o*d+l*f+h,i[t+1]=a*d+c*f+u,t+=e,r++}}function WP(i,e){const t=i.texture,s=t.frame.width,r=t.frame.height;let n=0,o=0;i.applyAnchorToTexture&&(n=i.anchor.x,o=i.anchor.y),e[0]=e[6]=-n,e[2]=e[4]=1-n,e[1]=e[3]=-o,e[5]=e[7]=1-o;const a=O.shared;a.copyFrom(i._tileTransform.matrix),a.tx/=i.width,a.ty/=i.height,a.invert(),a.scale(i.width/s,i.height/r),HP(e,2,0,a)}const pn=new NP;class VP{constructor(){this.canBatch=!0,this.geometry=new wd({indices:pn.indices.slice(),positions:pn.positions.slice(),uvs:pn.uvs.slice()})}destroy(){this.geometry.destroy(),this.shader?.destroy()}}class
|
|
1312
|
+
`}};let Vd,$d;class zP extends ot{constructor(){Vd??(Vd=ks({name:"tiling-sprite-shader",bits:[Vs,DP,Bs]})),$d??($d=Fs({name:"tiling-sprite-shader",bits:[Cd,GP,Us]}));const e=new He({uMapCoord:{value:new O,type:"mat3x3<f32>"},uClampFrame:{value:new Float32Array([0,0,1,1]),type:"vec4<f32>"},uClampOffset:{value:new Float32Array([0,0]),type:"vec2<f32>"},uTextureTransform:{value:new O,type:"mat3x3<f32>"},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:"vec4<f32>"}});super({glProgram:$d,gpuProgram:Vd,resources:{localUniforms:new He({uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),tilingUniforms:e,uTexture:M.EMPTY.source,uSampler:M.EMPTY.source.style}})}updateUniforms(e,t,s,r,n,o){const a=this.resources.tilingUniforms,l=o.width,c=o.height,h=o.textureMatrix,u=a.uniforms.uTextureTransform;u.set(s.a*l/e,s.b*l/t,s.c*c/e,s.d*c/t,s.tx/e,s.ty/t),u.invert(),a.uniforms.uMapCoord=h.mapCoord,a.uniforms.uClampFrame=h.uClampFrame,a.uniforms.uClampOffset=h.uClampOffset,a.uniforms.uTextureTransform=u,a.uniforms.uSizeAnchor[0]=e,a.uniforms.uSizeAnchor[1]=t,a.uniforms.uSizeAnchor[2]=r,a.uniforms.uSizeAnchor[3]=n,o&&(this.resources.uTexture=o.source,this.resources.uSampler=o.source.style)}}class NP extends wd{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}}function LP(i,e){const t=i.anchor.x,s=i.anchor.y;e[0]=-t*i.width,e[1]=-s*i.height,e[2]=(1-t)*i.width,e[3]=-s*i.height,e[4]=(1-t)*i.width,e[5]=(1-s)*i.height,e[6]=-t*i.width,e[7]=(1-s)*i.height}function HP(i,e,t,s){let r=0;const n=i.length/e,o=s.a,a=s.b,l=s.c,c=s.d,h=s.tx,u=s.ty;for(t*=e;r<n;){const d=i[t],f=i[t+1];i[t]=o*d+l*f+h,i[t+1]=a*d+c*f+u,t+=e,r++}}function WP(i,e){const t=i.texture,s=t.frame.width,r=t.frame.height;let n=0,o=0;i.applyAnchorToTexture&&(n=i.anchor.x,o=i.anchor.y),e[0]=e[6]=-n,e[2]=e[4]=1-n,e[1]=e[3]=-o,e[5]=e[7]=1-o;const a=O.shared;a.copyFrom(i._tileTransform.matrix),a.tx/=i.width,a.ty/=i.height,a.invert(),a.scale(i.width/s,i.height/r),HP(e,2,0,a)}const pn=new NP;class VP{constructor(){this.canBatch=!0,this.geometry=new wd({indices:pn.indices.slice(),positions:pn.positions.slice(),uvs:pn.uvs.slice()})}destroy(){this.geometry.destroy(),this.shader?.destroy()}}class m_{constructor(e){this._state=ft.default2d,this._renderer=e}validateRenderable(e){const t=this._getTilingSpriteData(e),s=t.canBatch;this._updateCanBatch(e);const r=t.canBatch;if(r&&r===s){const{batchableMesh:n}=t;return!n._batcher.checkAndUpdateTexture(n,e.texture)}return s!==r}addRenderable(e,t){const s=this._renderer.renderPipes.batch;this._updateCanBatch(e);const r=this._getTilingSpriteData(e),{geometry:n,canBatch:o}=r;if(o){r.batchableMesh||(r.batchableMesh=new Wd);const a=r.batchableMesh;e.didViewUpdate&&(this._updateBatchableMesh(e),a.geometry=n,a.renderable=e,a.transform=e.groupTransform,a.setTexture(e._texture)),a.roundPixels=this._renderer._roundPixels|e._roundPixels,s.addToBatch(a,t)}else s.break(t),r.shader||(r.shader=new zP),this.updateRenderable(e),t.add(e)}execute(e){const{shader:t}=this._getTilingSpriteData(e);t.groups[0]=this._renderer.globalUniforms.bindGroup;const s=t.resources.localUniforms.uniforms;s.uTransformMatrix=e.groupTransform,s.uRound=this._renderer._roundPixels|e._roundPixels,Xs(e.groupColorAlpha,s.uColor,0),this._state.blendMode=Is(e.groupBlendMode,e.texture._source),this._renderer.encoder.draw({geometry:pn,shader:t,state:this._state})}updateRenderable(e){const t=this._getTilingSpriteData(e),{canBatch:s}=t;if(s){const{batchableMesh:r}=t;e.didViewUpdate&&this._updateBatchableMesh(e),r._batcher.updateElement(r)}else if(e.didViewUpdate){const{shader:r}=t;r.updateUniforms(e.width,e.height,e._tileTransform.matrix,e.anchor.x,e.anchor.y,e.texture)}}_getTilingSpriteData(e){return e._gpuData[this._renderer.uid]||this._initTilingSpriteData(e)}_initTilingSpriteData(e){const t=new VP;return t.renderable=e,e._gpuData[this._renderer.uid]=t,t}_updateBatchableMesh(e){const t=this._getTilingSpriteData(e),{geometry:s}=t,r=e.texture.source.style;r.addressMode!=="repeat"&&(r.addressMode="repeat",r.update()),WP(e,s.uvs),LP(e,s.positions)}destroy(){this._renderer=null}_updateCanBatch(e){const t=this._getTilingSpriteData(e),s=e.texture;let r=!0;return this._renderer.type===Qe.WEBGL&&(r=this._renderer.context.supports.nonPowOf2wrapping),t.canBatch=s.textureMatrix.isSimple&&(r||s.source.isPowerOfTwo),t.canBatch}}m_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"tilingSprite"};const $P={name:"local-uniform-msdf-bit",vertex:{header:`
|
|
1313
1313
|
struct LocalUniforms {
|
|
1314
1314
|
uColor:vec4<f32>,
|
|
1315
1315
|
uTransformMatrix:mat3x3<f32>,
|
|
@@ -1406,14 +1406,14 @@ fn mainFragment(
|
|
|
1406
1406
|
|
|
1407
1407
|
return coverage;
|
|
1408
1408
|
}
|
|
1409
|
-
`}};let Xd,Yd;class KP extends ot{constructor(e){const t=new He({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uDistance:{value:4,type:"f32"},uRound:{value:0,type:"f32"}});Xd??(Xd=ks({name:"sdf-shader",bits:[ju,Qu(e),$P,YP,Bs]})),Yd??(Yd=Fs({name:"sdf-shader",bits:[Zu,td(e),XP,qP,Us]})),super({glProgram:Yd,gpuProgram:Xd,resources:{localUniforms:t,batchSamplers:id(e)}})}}class jP extends
|
|
1409
|
+
`}};let Xd,Yd;class KP extends ot{constructor(e){const t=new He({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new O,type:"mat3x3<f32>"},uDistance:{value:4,type:"f32"},uRound:{value:0,type:"f32"}});Xd??(Xd=ks({name:"sdf-shader",bits:[ju,Qu(e),$P,YP,Bs]})),Yd??(Yd=Fs({name:"sdf-shader",bits:[Zu,td(e),XP,qP,Us]})),super({glProgram:Yd,gpuProgram:Xd,resources:{localUniforms:t,batchSamplers:id(e)}})}}class jP extends xe{destroy(){this.context.customShader&&this.context.customShader.destroy(),super.destroy()}}class g_{constructor(e){this._renderer=e}validateRenderable(e){const t=this._getGpuBitmapText(e);return this._renderer.renderPipes.graphics.validateRenderable(t)}addRenderable(e,t){const s=this._getGpuBitmapText(e);x_(e,s),e._didTextUpdate&&(e._didTextUpdate=!1,this._updateContext(e,s)),this._renderer.renderPipes.graphics.addRenderable(s,t),s.context.customShader&&this._updateDistanceField(e)}updateRenderable(e){const t=this._getGpuBitmapText(e);x_(e,t),this._renderer.renderPipes.graphics.updateRenderable(t),t.context.customShader&&this._updateDistanceField(e)}_updateContext(e,t){const{context:s}=t,r=Ns.getFont(e.text,e._style);s.clear(),r.distanceField.type!=="none"&&(s.customShader||(s.customShader=new KP(this._renderer.limits.maxBatchableTextures)));const n=$e.graphemeSegmenter(e.text),o=e._style;let a=r.baseLineOffset;const l=fd(n,o,r,!0),c=o.padding,h=l.scale;let u=l.width,d=l.height+l.offsetY;o._stroke&&(u+=o._stroke.width/h,d+=o._stroke.width/h),s.translate(-e._anchor._x*u-c,-e._anchor._y*d-c).scale(h,h);const f=r.applyFillAsTint?o._fill.color:16777215;let p=r.fontMetrics.fontSize,g=r.lineHeight;o.lineHeight&&(p=o.fontSize/h,g=o.lineHeight/h);let m=(g-p)/2;m-r.baseLineOffset<0&&(m=0);for(let x=0;x<l.lines.length;x++){const _=l.lines[x];for(let y=0;y<_.charPositions.length;y++){const v=_.chars[y],T=r.chars[v];if(T?.texture){const S=T.texture;s.texture(S,f||"black",Math.round(_.charPositions[y]+T.xOffset),Math.round(a+T.yOffset+m),S.orig.width,S.orig.height)}}a+=g}}_getGpuBitmapText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){const t=new jP;return e._gpuData[this._renderer.uid]=t,this._updateContext(e,t),t}_updateDistanceField(e){const t=this._getGpuBitmapText(e).context,s=e._style.fontFamily,r=ae.get(`${s}-bitmap`),{a:n,b:o,c:a,d:l}=e.groupTransform,c=Math.sqrt(n*n+o*o),h=Math.sqrt(a*a+l*l),u=(Math.abs(c)+Math.abs(h))/2,d=r.baseRenderedFontSize/e._style.fontSize,f=u*r.distanceField.range*(1/d);t.customShader.resources.localUniforms.uniforms.uDistance=f}destroy(){this._renderer=null}}g_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"bitmapText"};function x_(i,e){e.groupTransform=i.groupTransform,e.groupColorAlpha=i.groupColorAlpha,e.groupColor=i.groupColor,e.groupBlendMode=i.groupBlendMode,e.globalDisplayStatus=i.globalDisplayStatus,e.groupTransform=i.groupTransform,e.localDisplayStatus=i.localDisplayStatus,e.groupAlpha=i.groupAlpha,e._roundPixels=i._roundPixels}function ZP(i){const{text:e,style:t,chars:s}=i,r=t,n=Ns.getFont(e,r),o=$e.graphemeSegmenter(e),a=fd(o,r,n,!0),l=a.scale,c=[],h=[],u=[],d=t.lineHeight?t.lineHeight:n.lineHeight*l;let f=0;for(const p of a.lines){if(p.chars.length===0)continue;const g=new re({label:"line"});g.y=f,u.push(g);let m=new re({label:"word"}),x=0;for(let _=0;_<p.chars.length;_++){const y=p.chars[_];if(!y||!n.chars[y])continue;const T=y===" ",S=_===p.chars.length-1;let w;s.length>0?(w=s.shift(),w.text=y,w.style=r,w.label=`char-${y}`,w.x=p.charPositions[_]*l-p.charPositions[x]*l):w=new zI({text:y,style:r,label:`char-${y}`,x:p.charPositions[_]*l-p.charPositions[x]*l}),T||(c.push(w),m.addChild(w)),(T||S)&&m.children.length>0&&(m.x=p.charPositions[x]*l,h.push(m),g.addChild(m),m=new re({label:"word"}),x=_+1)}f+=d}return{chars:c,lines:u,words:h}}class JP extends dn{constructor(e){super(),this.generatingTexture=!1,this.currentKey="--",this._renderer=e,e.runners.resolutionChange.add(this)}resolutionChange(){const e=this.renderable;e._autoResolution&&e.onViewUpdate()}destroy(){const{htmlText:e}=this._renderer;e.getReferenceCount(this.currentKey)===null?e.returnTexturePromise(this.texturePromise):e.decreaseReferenceCount(this.currentKey),this._renderer.runners.resolutionChange.remove(this),this.texturePromise=null,this._renderer=null}}function qd(i,e){const{texture:t,bounds:s}=i,r=e._style._getFinalPadding();Xp(s,e._anchor,t);const n=e._anchor._x*r*2,o=e._anchor._y*r*2;s.minX-=r-n,s.minY-=r-o,s.maxX-=r-n,s.maxY-=r-o}class __{constructor(e){this._renderer=e}validateRenderable(e){const t=this._getGpuText(e),s=e.styleKey;return t.currentKey!==s}addRenderable(e,t){const s=this._getGpuText(e);if(e._didTextUpdate){const r=e._autoResolution?this._renderer.resolution:e.resolution;(s.currentKey!==e.styleKey||e.resolution!==r)&&this._updateGpuText(e).catch(n=>{console.error(n)}),e._didTextUpdate=!1,qd(s,e)}this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const t=this._getGpuText(e);t._batcher.updateElement(t)}async _updateGpuText(e){e._didTextUpdate=!1;const t=this._getGpuText(e);if(t.generatingTexture)return;const s=t.texturePromise;t.texturePromise=null,t.generatingTexture=!0,e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;let r=this._renderer.htmlText.getTexturePromise(e);s&&(r=r.finally(()=>{this._renderer.htmlText.decreaseReferenceCount(t.currentKey),this._renderer.htmlText.returnTexturePromise(s)})),t.texturePromise=r,t.currentKey=e.styleKey,t.texture=await r;const n=e.renderGroup||e.parentRenderGroup;n&&(n.structureDidChange=!0),t.generatingTexture=!1,qd(t,e)}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){const t=new JP(this._renderer);return t.renderable=e,t.transform=e.groupTransform,t.texture=M.EMPTY,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}__.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"htmlText"};function QP(){const{userAgent:i}=Y.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(i)}const eR=new De;function y_(i,e,t,s){const r=eR;r.minX=0,r.minY=0,r.maxX=i.width/s|0,r.maxY=i.height/s|0;const n=ve.getOptimalTexture(r.width,r.height,s,!1);return n.source.uploadMethodId="image",n.source.resource=i,n.source.alphaMode="premultiply-alpha-on-upload",n.frame.width=e/s,n.frame.height=t/s,n.source.emit("update",n.source),n.updateUvs(),n}function tR(i,e){const t=e.fontFamily,s=[],r={},n=/font-family:([^;"\s]+)/g,o=i.match(n);function a(l){r[l]||(s.push(l),r[l]=!0)}if(Array.isArray(t))for(let l=0;l<t.length;l++)a(t[l]);else a(t);o&&o.forEach(l=>{const c=l.split(":")[1].trim();a(c)});for(const l in e.tagStyles){const c=e.tagStyles[l].fontFamily;a(c)}return s}async function iR(i){const t=await(await Y.get().fetch(i)).blob(),s=new FileReader;return await new Promise((n,o)=>{s.onloadend=()=>n(s.result),s.onerror=o,s.readAsDataURL(t)})}async function sR(i,e){const t=await iR(e);return`@font-face {
|
|
1410
1410
|
font-family: "${i.fontFamily}";
|
|
1411
1411
|
font-weight: ${i.fontWeight};
|
|
1412
1412
|
font-style: ${i.fontStyle};
|
|
1413
1413
|
src: url('${t}');
|
|
1414
1414
|
}`}const Kd=new Map;async function rR(i){const e=i.filter(t=>ae.has(`${t}-and-url`)).map(t=>{if(!Kd.has(t)){const{entries:s}=ae.get(`${t}-and-url`),r=[];s.forEach(n=>{const o=n.url,l=n.faces.map(c=>({weight:c.weight,style:c.style}));r.push(...l.map(c=>sR({fontWeight:c.weight,fontStyle:c.style,fontFamily:t},o)))}),Kd.set(t,Promise.all(r).then(n=>n.join(`
|
|
1415
1415
|
`)))}return Kd.get(t)});return(await Promise.all(e)).join(`
|
|
1416
|
-
`)}function nR(i,e,t,s,r){const{domElement:n,styleElement:o,svgRoot:a}=r;n.innerHTML=`<style>${e.cssStyle}</style><div style='padding:0;'>${i}</div>`,n.setAttribute("style",`transform: scale(${t});transform-origin: top left; display: inline-block`),o.textContent=s;const{width:l,height:c}=r.image;return a.setAttribute("width",l.toString()),a.setAttribute("height",c.toString()),new XMLSerializer().serializeToString(a)}function oR(i,e){const t=Gt.getOptimalCanvasAndContext(i.width,i.height,e),{context:s}=t;return s.clearRect(0,0,i.width,i.height),s.drawImage(i,0,0),t}function aR(i,e,t){return new Promise(async s=>{t&&await new Promise(r=>setTimeout(r,100)),i.onload=()=>{s()},i.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(e)}`,i.crossOrigin="anonymous"})}class vx{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===Qe.WEBGPU}getTexture(e){return this.getTexturePromise(e)}getManagedTexture(e){const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].promise;const s=this._buildTexturePromise(e).then(r=>(this._activeTextures[t].texture=r,r));return this._activeTextures[t]={texture:null,promise:s,usageCount:1},s}getReferenceCount(e){return this._activeTextures[e]?.usageCount??null}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(t.texture?this._cleanUp(t.texture):t.promise.then(s=>{t.texture=s,this._cleanUp(t.texture)}).catch(()=>{L("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[e]=null))}getTexturePromise(e){return this._buildTexturePromise(e)}async _buildTexturePromise(e){const{text:t,style:s,resolution:r,textureStyle:n}=e,o=Se.get(F0),a=tR(t,s),l=await rR(a),c=NI(t,s,l,o),h=Math.ceil(Math.ceil(Math.max(1,c.width)+s.padding*2)*r),u=Math.ceil(Math.ceil(Math.max(1,c.height)+s.padding*2)*r),d=o.image,f=2;d.width=(h|0)+f,d.height=(u|0)+f;const p=nR(t,s,r,l,o);await aR(d,p,QP()&&a.length>0);const g=d;let m;this._createCanvas&&(m=oR(d,r));const _=yx(m?m.canvas:g,d.width-f,d.height-f,r);return n&&(_.source.style=n),this._createCanvas&&(this._renderer.texture.initSource(_.source),Gt.returnCanvasAndContext(m)),Se.return(o),_}returnTexturePromise(e){e.then(t=>{this._cleanUp(t)}).catch(()=>{L("HTMLTextSystem: Failed to clean texture")})}_cleanUp(e){ve.returnTexture(e,!0),e.source.resource=null,e.source.uploadMethodId="unknown"}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexturePromise(this._activeTextures[e].promise);this._activeTextures=null}}vx.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"htmlText"};class lR extends re{constructor(e){const{text:t,style:s,autoSplit:r,lineAnchor:n,wordAnchor:o,charAnchor:a,...l}=e;super(l),this._dirty=!1,this._canReuseChars=!1,this.chars=[],this.words=[],this.lines=[],this._originalText=t,this._autoSplit=r,this._lineAnchor=n,this._wordAnchor=o,this._charAnchor=a,this.style=s}split(){const e=this.splitFn();this.chars=e.chars,this.words=e.words,this.lines=e.lines,this.addChild(...this.lines),this.charAnchor=this._charAnchor,this.wordAnchor=this._wordAnchor,this.lineAnchor=this._lineAnchor,this._dirty=!1,this._canReuseChars=!0}get text(){return this._originalText}set text(e){this._originalText=e,this.lines.forEach(t=>t.destroy({children:!0})),this.lines.length=0,this.words.length=0,this.chars.length=0,this._canReuseChars=!1,this.onTextUpdate()}_setOrigin(e,t,s){let r;typeof e=="number"?r={x:e,y:e}:r={x:e.x,y:e.y},t.forEach(n=>{const o=n.getLocalBounds(),a=o.minX+o.width*r.x,l=o.minY+o.height*r.y;n.origin.set(a,l)}),this[s]=e}get lineAnchor(){return this._lineAnchor}set lineAnchor(e){this._setOrigin(e,this.lines,"_lineAnchor")}get wordAnchor(){return this._wordAnchor}set wordAnchor(e){this._setOrigin(e,this.words,"_wordAnchor")}get charAnchor(){return this._charAnchor}set charAnchor(e){this._setOrigin(e,this.chars,"_charAnchor")}get style(){return this._style}set style(e){e||(e={}),this._style=new Xe(e),this.words.forEach(t=>t.destroy()),this.words.length=0,this.lines.forEach(t=>t.destroy()),this.lines.length=0,this._canReuseChars=!0,this.onTextUpdate()}onTextUpdate(){this._dirty=!0,this._autoSplit&&this.split()}destroy(e){super.destroy(e),this.chars=[],this.words=[],this.lines=[],(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._originalText=""}}const bx=class xn extends lR{constructor(e){const t={...xn.defaultOptions,...e};super(t)}static from(e,t){const s={...xn.defaultOptions,...t,text:e.text,style:new Xe(e.style)};return new xn({...s})}splitFn(){return ZP({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};bx.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let cR=bx;class hR extends dn{constructor(e){super(),this._renderer=e,e.runners.resolutionChange.add(this)}resolutionChange(){const e=this.renderable;e._autoResolution&&e.onViewUpdate()}destroy(){const{canvasText:e}=this._renderer;e.getReferenceCount(this.currentKey)>0?e.decreaseReferenceCount(this.currentKey):this.texture&&e.returnTexture(this.texture),this._renderer.runners.resolutionChange.remove(this),this._renderer=null}}class Tx{constructor(e){this._renderer=e}validateRenderable(e){const t=this._getGpuText(e),s=e.styleKey;return t.currentKey!==s?!0:e._didTextUpdate}addRenderable(e,t){const s=this._getGpuText(e);if(e._didTextUpdate){const r=e._autoResolution?this._renderer.resolution:e.resolution;(s.currentKey!==e.styleKey||e.resolution!==r)&&this._updateGpuText(e),e._didTextUpdate=!1,qd(s,e)}this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){const t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){const t=new hR(this._renderer);return t.currentKey="--",t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}Tx.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"text"};class wx{constructor(e){this._activeTextures={},this._renderer=e}getTexture(e,t,s,r){typeof e=="string"&&(W("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:s,resolution:t}),e.style instanceof Xe||(e.style=new Xe(e.style)),e.textureStyle instanceof wt||(e.textureStyle=new wt(e.textureStyle)),typeof e.text!="string"&&(e.text=e.text.toString());const{text:n,style:o,textureStyle:a}=e,l=e.resolution??this._renderer.resolution,{frame:c,canvasAndContext:h}=Ws.getCanvasAndContext({text:n,style:o,resolution:l}),u=yx(h.canvas,c.width,c.height,l);if(a&&(u.source.style=a),o.trim&&(c.pad(o.padding),u.frame.copyFrom(c),u.frame.scale(1/l),u.updateUvs()),o.filters){const d=this._applyFilters(u,o.filters);return this.returnTexture(u),Ws.returnCanvasAndContext(h),d}return this._renderer.texture.initSource(u._source),Ws.returnCanvasAndContext(h),u}returnTexture(e){const t=e.source;t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",ve.returnTexture(e,!0)}renderTextToCanvas(){W("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;const s=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle});return this._activeTextures[t]={texture:s,usageCount:1},s}decreaseReferenceCount(e){const t=this._activeTextures[e];t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null)}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){const s=this._renderer.renderTarget.renderTarget,r=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind(s,!1),r}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}}wx.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"canvasText"},V.add(D1,G1);function Te(i){if(i!=null){if(typeof i=="number")return i;if(typeof i=="string"){if(i==="transparent")return;if(i.startsWith("#")){const t=parseInt(i.slice(1),16);if(!isNaN(t))return t}if(i.startsWith("0x")){const t=parseInt(i,16);if(!isNaN(t))return t}const e=parseInt(i,16);if(!isNaN(e))return e;try{return new ue(i).toNumber()}catch{return}}}}const Sx=i=>i==="transparent",_i=(i,e=16777215)=>Sx(i)?{color:e,alpha:0}:{color:Te(i)??e,alpha:1};class ei extends qt{type="Caption";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}text;get style(){if(!this.originalOpts)return{};const e=this.originalOpts;return{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,color:e.fill,align:e.align,textCase:e.textCase,stroke:e.stroke?typeof e.stroke=="object"?{color:e.stroke.color,width:e.stroke.width}:{color:e.stroke,width:e.strokeWidth??0}:void 0,shadow:e.dropShadow?{color:e.dropShadow.color??"#000000",alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,distance:e.dropShadow.distance??0,angle:e.dropShadow.angle??0}:void 0}}set style(e){this.updateStyle(e)}get fontFamily(){return this.opts.fontFamily}set fontFamily(e){this.updateStyle({fontFamily:e})}get fontUrl(){return this.opts.fontUrl}set fontUrl(e){this.updateStyle({fontUrl:e})}get fontSize(){return this.opts.fontSize}set fontSize(e){this.updateStyle({fontSize:e})}get fontWeight(){return this.opts.fontWeight}set fontWeight(e){this.updateStyle({fontWeight:e})}get fontStyle(){return this.opts.fontStyle}set fontStyle(e){this.updateStyle({fontStyle:e})}get fill(){return this.opts.fill}set fill(e){this.updateStyle({fill:e})}get align(){return this.opts.align}set align(e){this.updateStyle({align:e})}get stroke(){return this.originalOpts?.stroke}set stroke(e){this.updateStyle({stroke:e})}get strokeWidth(){return this.opts.strokeWidth}set strokeWidth(e){this.updateStyle({strokeWidth:e})}get dropShadow(){return this.originalOpts?.dropShadow}set dropShadow(e){this.updateStyle({dropShadow:e})}get caption(){return this.originalOpts?.caption}set caption(e){this.updateStyle({caption:e})}bottomOffset;get textCase(){return this.originalOpts?.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;get mediaId(){return this.opts.mediaId}set mediaId(e){this.opts.mediaId=e,this.originalOpts&&(this.originalOpts.mediaId=e)}effects=[];get words(){return this.opts.words}set words(e){this.opts.words=e,this.originalOpts&&(this.originalOpts.caption?this.originalOpts.caption.words=e:this.originalOpts.words=e),this.text=e.map(t=>t.text).filter(t=>t&&t.trim()!=="").join(" "),this.refreshCaptions().then(()=>{this.emit("propsChange",{})})}opts;pixiTextContainer=null;renderTexture=null;wordTexts=[];extraPadding=0;textStyle;externalRenderer=null;pixiApp=null;originalOpts=null;constructor(e,t={},s){super(),this.text=e,this.originalOpts={...t},this.externalRenderer=s??null,this.opts={fontSize:t.fontSize??30,fontFamily:t.fontFamily??"Arial",fontUrl:t.fontUrl??"",fontWeight:t.fontWeight??"normal",fontStyle:t.fontStyle??"normal",fill:t.fill??"#ffffff",strokeWidth:t.strokeWidth??0,align:t.align??"center",wordWrapWidth:t.wordWrapWidth??0,wordWrap:t.wordWrap??!1,lineHeight:t.lineHeight??1,letterSpacing:t.letterSpacing??0,textCase:t.textCase??"none",videoWidth:t.caption?.positioning?.videoWidth??t.videoWidth??1280,videoHeight:t.caption?.positioning?.videoHeight??t.videoHeight??720,bottomOffset:t.caption?.positioning?.bottomOffset??t.bottomOffset??30,keyword:t.caption?.colors?.keyword??t.colors?.keyword??"#ffff00",background:t.caption?.colors?.background??t.colors?.background??"#000000",active:t.caption?.colors?.active??t.colors?.active??"#ffffff",activeFill:t.caption?.colors?.activeFill??t.colors?.activeFill??"#00ff00",appeared:t.caption?.colors?.appeared??t.colors?.appeared??"#ffffff",words:t.caption?.words??t.words??[],preserveKeywordColor:t.caption?.preserveKeywordColor??t.preserveKeywordColor??!1,mediaId:t.mediaId};const r={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(t.fill&&typeof t.fill=="object"&&t.fill.type==="gradient"){const a=new at(t.fill.x0,t.fill.y0,t.fill.x1,t.fill.y1);t.fill.colors.forEach(({ratio:l,color:c})=>{const h=typeof c=="number"?c:Te(c)??16777215;a.addColorStop(l,h)}),r.fill={fill:a}}else{let a;t.fill==="transparent"?a=16777215:(typeof t.fill=="string"||typeof t.fill=="number")&&(a=Te(t.fill)),r.fill=a??16777215}const n=a=>a==="transparent";if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke){if(!n(t.stroke.color)){const a=Te(t.stroke.color);a!==void 0&&(r.stroke={color:a,width:t.stroke.width},t.stroke.join&&(r.stroke.join=t.stroke.join))}}else if(!n(t.stroke)){const a=Te(t.stroke);a!==void 0?r.stroke={color:a,width:this.opts.strokeWidth??0}:this.opts.strokeWidth&&this.opts.strokeWidth>0&&(r.stroke={color:0,width:this.opts.strokeWidth})}if(t.dropShadow){const a=Te(t.dropShadow.color);a!==void 0&&(r.dropShadow={color:a,alpha:t.dropShadow.alpha??.5,blur:t.dropShadow.blur??4,angle:t.dropShadow.angle??Math.PI/6,distance:t.dropShadow.distance??2})}const o=new Xe(r);this.textStyle=o,this.ready=(async()=>{await this.refreshCaptions();const a={...this._meta};return K.info("CaptionClip ready:",a),a})()}async updateStyle(e){this.originalOpts||(this.originalOpts={}),this.originalOpts={...this.originalOpts,...e},e.fontSize!==void 0&&(this.opts.fontSize=e.fontSize),e.fontFamily!==void 0&&(this.opts.fontFamily=e.fontFamily),e.fontUrl!==void 0&&(this.opts.fontUrl=e.fontUrl),e.fontWeight!==void 0&&(this.opts.fontWeight=e.fontWeight),e.fontStyle!==void 0&&(this.opts.fontStyle=e.fontStyle),e.fill!==void 0&&(this.opts.fill=e.fill),e.align!==void 0&&(this.opts.align=e.align),e.letterSpacing!==void 0&&(this.opts.letterSpacing=e.letterSpacing),e.lineHeight!==void 0&&(this.opts.lineHeight=e.lineHeight),e.textCase!==void 0&&(this.opts.textCase=e.textCase),e.caption?.colors&&(e.caption.colors.appeared!==void 0&&(this.opts.appeared=e.caption.colors.appeared),e.caption.colors.active!==void 0&&(this.opts.active=e.caption.colors.active),e.caption.colors.activeFill!==void 0&&(this.opts.activeFill=e.caption.colors.activeFill),e.caption.colors.background!==void 0&&(this.opts.background=e.caption.colors.background),e.caption.colors.keyword!==void 0&&(this.opts.keyword=e.caption.colors.keyword)),e.caption?.preserveKeywordColor!==void 0&&(this.opts.preserveKeywordColor=e.caption.preserveKeywordColor);const t={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(this.opts.fill&&typeof this.opts.fill=="object"&&this.opts.fill.type==="gradient"){const r=new at(this.opts.fill.x0,this.opts.fill.y0,this.opts.fill.x1,this.opts.fill.y1);this.opts.fill.colors.forEach(({ratio:n,color:o})=>{const a=typeof o=="number"?o:Te(o)??16777215;r.addColorStop(n,a)}),t.fill={fill:r}}else{const r=typeof this.opts.fill=="string"||typeof this.opts.fill=="number"?Te(this.opts.fill):void 0;t.fill=r??16777215}if(e.stroke!==void 0||e.strokeWidth!==void 0)if(this.originalOpts.stroke&&typeof this.originalOpts.stroke=="object"&&"color"in this.originalOpts.stroke){const r=Te(this.originalOpts.stroke.color);r!==void 0&&(t.stroke={color:r,width:this.originalOpts.stroke.width},this.originalOpts.stroke.join&&(t.stroke.join=this.originalOpts.stroke.join))}else{const r=Te(this.originalOpts.stroke),n=e.strokeWidth??this.originalOpts.strokeWidth??0;r!==void 0?t.stroke={color:r,width:n}:n>0&&(t.stroke={color:0,width:n})}const s=e.dropShadow??this.originalOpts.dropShadow;if(s){const r=Te(s.color);r!==void 0&&(t.dropShadow={color:r,alpha:s.alpha??.5,blur:s.blur??4,angle:s.angle??Math.PI/6,distance:s.distance??2})}this.textStyle=new Xe(t),await this.refreshCaptions(),this.emit("propsChange",e)}async refreshCaptions(){this.pixiTextContainer?this.pixiTextContainer.removeChildren():this.pixiTextContainer=new re;const e=this.textStyle;let t=0,s=0,r=0;const n=this.opts.textCase,o=$e.measureText(" ",this.textStyle);this.wordTexts=this.opts.words.map(S=>{let w=S.text;if(!w||w.trim()===""){const D=new re;return D.label="emptyWord",this.pixiTextContainer.addChild(D),D}n==="uppercase"?w=w.toUpperCase():n==="lowercase"?w=w.toLowerCase():n==="title"&&(w=w.replace(/\w\S*/g,D=>D.charAt(0).toUpperCase()+D.substring(1).toLowerCase()));const E=new cR({text:w,style:e});E.x=t,E.y=0;const P=E.getLocalBounds(),C=Math.ceil(P.width||E.width),A=Math.ceil(P.height||E.height);s=Math.max(s,A),t+=C+o.width,r=t-o.width,this.pixiTextContainer.addChild(E);const U=Te(this.opts.fill);return E.tint=U??16777215,E});const a=r,l=s,c=new _e;c.label="containerBackground";const h=this.opts.background==="transparent"||!this.opts.background,u=h?0:Te(this.opts.background),d=h?0:1,f=15;c.roundRect(0,0,a+f*2,l+f*2,10),c.fill({color:u,alpha:d}),this.wordTexts.forEach(S=>{this.extraPadding=0,S.pivot.y=0,S.pivot.x=0,S.y=f-this.extraPadding,S.x+=f}),this.pixiTextContainer.addChildAt(c,0);const g=a+f*2,m=l+f*2;this.renderTexture?this.renderTexture.resize(g,m):this.renderTexture=Ge.create({width:g,height:m});try{(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture})}catch(S){K.warn("CaptionClip: Could not render captions during refresh",S)}this._meta.width=g,this._meta.height=m,this._meta.duration=1/0;const _=this.opts.videoWidth,x=this.opts.videoHeight,y=this.opts.bottomOffset,v=x-m-y,T=(_-g)/2;this.update({width:g,height:m,top:v,left:T})}lastLoggedTime=-1;updateState(e){const t=e/1e3,s=Math.floor(e/1e6);s!==this.lastLoggedTime&&(this.lastLoggedTime=s),this.opts.words.forEach((r,n)=>{const o=t>=r.from&&t<r.to,a=t>=r.to,l=r.isKeyWord&&!Sx(this.opts.keyword);let c=16777215,h=1;r.isKeyWord&&o&&l?{color:c,alpha:h}=_i(this.opts.keyword):o?{color:c,alpha:h}=_i(this.opts.active):a&&this.opts.preserveKeywordColor&&l?{color:c,alpha:h}=_i(this.opts.keyword):a?{color:c,alpha:h}=_i(this.opts.appeared):{color:c,alpha:h}=_i(this.opts.fill);const u=this.wordTexts[n];if(!u){console.warn(`¡WARNING: SplitBitmapText was not found for word "${r.text}"!`);return}u.children.forEach(f=>{f.label!=="bgRect"&&(f.tint=c,f.alpha=h)});const d=u.getChildByLabel("bgRect");if(o){const{color:f,alpha:p}=_i(this.opts.activeFill,16753920),g=10;d&&(d.visible=!1);const m=u.getLocalBounds();d&&(d.visible=!0);const _=16,x=d??new _e;x.label="bgRect",x.clear(),x.roundRect(m.x-g/2,m.y-g/2+this.extraPadding,m.width+g,m.height+g,_),x.fill({color:f,alpha:p}),x.tint=16777215,d||u.addChildAt(x,0)}else d&&(u.removeChild(d),d.destroy())})}async getTexture(){if(this.pixiTextContainer==null||this.renderTexture==null)return console.log("[CaptionClip] getTexture returning null - container or texture not ready"),null;try{return(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture}catch(e){return console.error("[CaptionClip] Error in getTexture:",e),null}}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("CaptionClip: No renderer available. Provide a renderer via setRenderer().");return this.pixiApp.renderer}async tick(e){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("CaptionClip not initialized");this.updateState(e);const t=await this.getRenderer();t.render({container:this.pixiTextContainer,target:this.renderTexture});const s=this.renderTexture.source?.resource?.source;let r;if(s instanceof HTMLCanvasElement)r=await createImageBitmap(s);else if(s instanceof OffscreenCanvas)r=await createImageBitmap(s);else{const o=t.extract.canvas(this.renderTexture);if(o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas)r=await createImageBitmap(o);else throw new Error("Unable to extract canvas from render texture")}return{video:r,state:"success"}}async split(e){await this.ready;const t=await this.clone(),s=await this.clone();return[t,s]}addEffect(e){this.effects.push(e)}editEffect(e,t){const s=this.effects.find(r=>r.id===e);s&&Object.assign(s,t)}removeEffect(e){const t=this.effects.findIndex(s=>s.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.originalOpts||{},t=new ei(this.text,e);return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){if(!this.destroyed){K.info("Caption destroy");try{this.wordTexts.forEach(e=>{e!=null&&!e.destroyed&&e.destroy({children:!0})})}catch{}finally{this.wordTexts=[]}try{this.pixiTextContainer!=null&&this.pixiTextContainer.destroyed!==!0&&this.pixiTextContainer.destroy({children:!0})}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),s={};if(this.originalOpts){const u=this.originalOpts;u.fontSize!==void 0&&(s.fontSize=u.fontSize),u.fontFamily!==void 0&&(s.fontFamily=u.fontFamily),u.fontWeight!==void 0&&(s.fontWeight=u.fontWeight),u.fontStyle!==void 0&&(s.fontStyle=u.fontStyle),u.fill!==void 0&&(s.color=u.fill),u.align!==void 0&&(s.align=u.align),u.textCase!==void 0&&(s.textCase=u.textCase),u.fontUrl!==void 0&&(s.fontUrl=u.fontUrl),u.stroke&&(typeof u.stroke=="object"?s.stroke={color:u.stroke.color,width:u.stroke.width}:s.stroke={color:u.stroke,width:u.strokeWidth??0}),u.dropShadow&&(s.shadow={color:u.dropShadow.color??"#000000",alpha:u.dropShadow.alpha??.5,blur:u.dropShadow.blur??4,distance:u.dropShadow.distance??0,angle:u.dropShadow.angle??0})}const r={};this.opts.words&&this.opts.words.length>0&&(r.words=this.opts.words);const n={},o=this.originalOpts?.caption?.colors??this.originalOpts?.colors;o?.appeared!==void 0&&(n.appeared=o.appeared),o?.active!==void 0&&(n.active=o.active),o?.activeFill!==void 0&&(n.activeFill=o.activeFill),o?.background!==void 0&&(n.background=o.background),o?.keyword!==void 0&&(n.keyword=o.keyword);let a;this.originalOpts?.caption?.preserveKeywordColor!==void 0?a=this.originalOpts.caption.preserveKeywordColor:this.originalOpts?.preserveKeywordColor!==void 0&&(a=this.originalOpts.preserveKeywordColor),Object.keys(n).length>0&&(r.colors=n),a!==void 0&&(r.preserveKeywordColor=a);const l={};this.bottomOffset!==void 0&&(l.bottomOffset=this.bottomOffset);const c=this.originalOpts?.caption?.positioning?.videoWidth??this.originalOpts?.videoWidth,h=this.originalOpts?.caption?.positioning?.videoHeight??this.originalOpts?.videoHeight;return c!==void 0&&(l.videoWidth=c),h!==void 0&&(l.videoHeight=h),Object.keys(l).length>0&&(r.positioning=l),{...t,type:"Caption",text:this.text,style:s,caption:Object.keys(r).length>0?r:void 0,id:this.id,effects:this.effects,mediaId:this.mediaId}}static async fromObject(e){if(e.type!=="Caption")throw new Error(`Expected Caption, got ${e.type}`);const t=e.text||"",s=e.style||{},r={};s.fontSize!==void 0&&(r.fontSize=s.fontSize),s.fontFamily!==void 0&&(r.fontFamily=s.fontFamily),s.fontWeight!==void 0&&(r.fontWeight=s.fontWeight),s.fontStyle!==void 0&&(r.fontStyle=s.fontStyle),s.color!==void 0&&(r.fill=s.color),s.align!==void 0&&(r.align=s.align),s.textCase!==void 0&&(r.textCase=s.textCase),s.fontUrl!==void 0?r.fontUrl=s.fontUrl:e.fontUrl!==void 0&&(r.fontUrl=e.fontUrl),e.mediaId&&(r.mediaId=e.mediaId),s.stroke&&(r.stroke=s.stroke.color,r.strokeWidth=s.stroke.width),s.shadow&&(r.dropShadow={color:s.shadow.color,alpha:s.shadow.alpha,blur:s.shadow.blur,distance:s.shadow.distance,angle:s.shadow.angle}),e.caption?r.caption=e.caption:(e.bottomOffset!==void 0&&(r.bottomOffset=e.bottomOffset),e.words!==void 0&&(r.words=e.words),(e.appearedColor!==void 0||e.activeColor!==void 0||e.activeFillColor!==void 0||e.backgroundColor!==void 0||e.isKeyWordColor!==void 0)&&(r.colors={},e.appearedColor!==void 0&&(r.colors.appeared=e.appearedColor),e.activeColor!==void 0&&(r.colors.active=e.activeColor),e.activeFillColor!==void 0&&(r.colors.activeFill=e.activeFillColor),e.backgroundColor!==void 0&&(r.colors.background=e.backgroundColor),e.isKeyWordColor!==void 0&&(r.colors.keyword=e.isKeyWordColor)),e.preservedColorKeyWord!==void 0&&(r.preserveKeywordColor=e.preservedColorKeyWord),e.videoWidth!==void 0&&(r.videoWidth=e.videoWidth),e.videoHeight!==void 0&&(r.videoHeight=e.videoHeight));const n=new ei(t,r);return n.left=e.left,n.top=e.top,n.width=e.width,n.height=e.height,n.angle=e.angle,n.display.from=e.display.from,n.display.to=e.display.to,n.duration=e.duration,n.playbackRate=e.playbackRate,n.zIndex=e.zIndex,n.opacity=e.opacity,n.flip=e.flip,e.animation&&n.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(n.id=e.id),e.effects&&(n.effects=e.effects),await n.ready,n}}let xi=class si extends qt{type="Image";ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t){const s=await Ls.load(e),r=s.source?.resource?.source;let n;try{if(r instanceof HTMLCanvasElement||r instanceof OffscreenCanvas)n=await createImageBitmap(r);else if(r instanceof HTMLImageElement){const a=new OffscreenCanvas(r.width,r.height),l=a.getContext("2d");if(l==null)throw new Error("Failed to create 2d context");l.drawImage(r,0,0),n=await createImageBitmap(a)}else if(r instanceof ImageBitmap)n=await createImageBitmap(r);else{const a=await fetch(e);if(!a.ok)throw new Error(`Failed to fetch image: ${a.status} ${a.statusText}`);const l=await a.blob();n=await createImageBitmap(l)}}catch{const l=await fetch(e);if(!l.ok)throw new Error(`Failed to fetch image: ${l.status} ${l.statusText}`);const c=await l.blob();n=await createImageBitmap(c)}const o=new si(n,t||e);return o.pixiTexture=s,o}getTexture(){return this.pixiTexture}constructor(e,t){super(),this.src=t!==void 0?t:"";const s=r=>{this.img=r,this._meta.width=r.width,this._meta.height=r.height,this._meta.duration=1/0;const n={...this._meta};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),n};if(e instanceof ReadableStream)this.ready=new Response(e).blob().then(r=>createImageBitmap(r)).then(s);else if(e instanceof ImageBitmap)this.ready=Promise.resolve(s(e));else if(Array.isArray(e)&&e.every(r=>r instanceof VideoFrame)){this.frames=e;const r=this.frames[0];if(r==null)throw Error("The frame count must be greater than 0");this._meta={width:r.displayWidth,height:r.displayHeight,duration:this.frames.reduce((o,a)=>o+(a.duration??0),0)};const n={...this._meta,duration:1/0};this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(n)}else if("type"in e)this.ready=this.initAnimateImg(e.stream,e.type).then(()=>{const r={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?r.width:this.width,this.height=this.height===0?r.height:this.height,this.duration===0&&r.duration!==1/0&&(this.duration=r.duration,this.display.to=this.display.from+this.duration),r});else throw Error("Illegal arguments")}async initAnimateImg(e,t){this.frames=await k1(e,t);const s=this.frames[0];if(s==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((r,n)=>r+(n.duration??0),0),width:s.codedWidth,height:s.codedHeight},K.info("Image ready:",this._meta)}tickInterceptor=async(e,t)=>t;async tick(e){if(this.img!=null)return await this.tickInterceptor(e,{video:await createImageBitmap(this.img),state:"success"});const t=e%this._meta.duration;return await this.tickInterceptor(e,{video:(this.frames.find(s=>t>=s.timestamp&&t<=s.timestamp+(s.duration??0))??this.frames[0]).clone(),state:"success"})}async split(e){if(await this.ready,this.img!=null)return[new si(await createImageBitmap(this.img),this.src),new si(await createImageBitmap(this.img),this.src)];let t=-1;for(let n=0;n<this.frames.length;n++){const o=this.frames[n];if(!(e>o.timestamp)){t=n;break}}if(t===-1)throw Error("Not found frame by time");const s=this.frames.slice(0,t).map(n=>new VideoFrame(n)),r=this.frames.slice(t).map(n=>new VideoFrame(n,{timestamp:n.timestamp-e}));return[new si(s,this.src),new si(r,this.src)]}async clone(){await this.ready;const e=this.img==null?this.frames.map(s=>s.clone()):await createImageBitmap(this.img),t=new si(e,this.src);return t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t.transition=this.transition,t}addEffect(e){this.effects.push(e)}editEffect(e,t){const s=this.effects.find(r=>r.id===e);s&&Object.assign(s,t)}removeEffect(e){const t=this.effects.findIndex(s=>s.id===e);t!==-1&&this.effects.splice(t,1)}destroy(){K.info("Image destroy"),this.img?.close(),this.frames.forEach(e=>e.close()),this.pixiTexture=null,super.destroy()}toJSON(e=!1){return{...super.toJSON(e),type:"Image",id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Image")throw new Error(`Expected Image, got ${e.type}`);if(!e.src||e.src.trim()==="")throw new Error("Image requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let t;try{const s=await fetch(e.src);if(!s.ok)throw new Error(`Failed to fetch image from ${e.src}: ${s.status} ${s.statusText}. Make sure the file exists in the public directory.`);const r=await s.blob();if(!r.type.startsWith("image/"))throw new Error(`Invalid image format: ${r.type}. Expected an image file.`);t=new si(await createImageBitmap(r),e.src)}catch(s){throw s instanceof Error&&s.message.includes("could not be decoded")?new Error(`Failed to decode image from ${e.src}. The image may be corrupted, in an unsupported format, or there may be CORS issues.`):s}return await t.ready,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.style&&(t.style={...t.style,...e.style}),e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),e.effects&&(t.effects=e.effects),e.transition&&(t.transition=e.transition),t}};function jd(i,e){const t={},s=e.videoTracks[0];if(s!=null){const n=dR(i.getTrackById(s.id))?.buffer,o=uR(s.codec);o&&(t.videoTrackConf={timescale:s.timescale,duration:s.duration,width:s.video.width,height:s.video.height,brands:e.brands,type:o.type,[o.descKey]:n}),t.videoDecoderConf={codec:s.codec,codedHeight:s.video.height,codedWidth:s.video.width,description:n}}const r=e.audioTracks[0];if(r!=null){const n=fR(i),o=n?pR(n):{};t.audioTrackConf={timescale:r.timescale,samplerate:o.sampleRate??r.audio.sample_rate,channel_count:o.numberOfChannels??r.audio.channel_count,hdlr:"soun",type:r.codec.startsWith("mp4a")?"mp4a":r.codec,description:n},t.audioDecoderConf={codec:o.codec??le.codec,numberOfChannels:o.numberOfChannels??r.audio.channel_count,sampleRate:o.sampleRate??r.audio.sample_rate}}return t}function uR(i){return i.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:i.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:null}function dR(i){for(const e of i.mdia.minf.stbl.stsd.entries){const t=e.avcC??e.hvcC??e.av1C??e.vpcC;if(t!=null){const s=new oi.DataStream(void 0,0,void 0);return t.write(s),new Uint8Array(s.buffer.slice(8))}}}function fR(i,e="mp4a"){return i.moov?.traks.flatMap(t=>t.mdia.minf.stbl.stsd.entries).find(t=>t.type===e)}function pR(i){const e=i.esd?.descs?.[0];if(!e)return{};let t=`mp4a.${e.oti.toString(16)}`;const s=e.descs?.[0];if(!s)return t.endsWith(".40")&&(t+=".2"),{codec:t};const r=s.data;if(!r)return{codec:t};const n=(r[0]&248)>>3;t+=`.${n}`;const o=(r[0]&7)<<1|r[1]>>7,a=(r[1]&120)>>3;return{codec:t,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][o],numberOfChannels:a}}async function mR(i,e,t){const s=oi.createFile(!1);s.onReady=o=>{e({mp4boxFile:s,info:o}),[o.videoTracks[0],o.audioTracks[0]].forEach(a=>{if(a){const l=a.video?"video":"audio";s.setExtractionOptions(a.id,l,{nbSamples:100})}}),s.start()},s.onSamples=t;let r=0;const n=30*1024*1024;for(;;){const o=await i.read(n,{at:r});if(o.byteLength===0)break;o.fileStart=r;const a=s.appendBuffer(o);if(a==null)break;r=a}s.stop()}function gR(i){if(i?.length!==9)return{};const e=new Int32Array(i.buffer),t=h=>h/65536,s=t(e[0]),r=t(e[1]),n=t(e[3]),o=t(e[4]),a=t(e[6]),l=t(e[7]),c=e[8]/(1<<30);return{scaleX:Math.sqrt(s*s+n*n),scaleY:Math.sqrt(r*r+o*o),rotationRad:Math.atan2(n,s),rotationDeg:Math.atan2(n,s)*180/Math.PI,translateX:a,translateY:l,perspective:c}}function _R(i,e,t){const s=(Math.round(t/90)*90+360)%360;if(s===0)return c=>c;const r=s===90||s===270,n=r?e:i,o=r?i:e,a=new OffscreenCanvas(n,o),l=a.getContext("2d");return l.translate(n/2,o/2),l.rotate(-s*Math.PI/180),l.translate(-i/2,-e/2),c=>{if(!c)return null;l.drawImage(c,0,0);const h=new VideoFrame(a,{timestamp:c.timestamp,duration:c.duration??void 0});return c.close(),h}}class Cx{static async getCacheKey(e){const s=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-1",s);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static getPath(e){return`assets/${e}`}static async get(e){const t=await this.getCacheKey(e),s=this.getPath(t),r=ai(s);return await r.exists()?r:null}static async put(e,t){const s=await this.getCacheKey(e),r=this.getPath(s),n=ai(r);return await Ei(n,t),n}}let Zd=0;function Jd(i){return i.kind==="file"&&i.createReader instanceof Function}class Me extends qt{type="Video";insId=Zd++;logger=K.create(`Video id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const e=await this.localFile.getOriginFile();if(e==null)throw Error("Video localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:t,size:s})=>e.slice(t,t+s))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=e=>e;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t={}){const s=await Cx.get(e);if(s){const u=new Me(s,{},e);return await u.ready,t.x!==void 0&&(u.left=t.x),t.y!==void 0&&(u.top=t.y),t.width!==void 0&&(u.width=t.width),t.height!==void 0&&(u.height=t.height),u}const r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch video from ${e}: ${r.status} ${r.statusText}`);const n=r.body,[o,a]=n.tee(),l=(async()=>{const u=new Me(o,{},e);return await u.ready,u})(),c=Cx.put(e,a),[h]=await Promise.all([l,c]);return t.x!==void 0&&(h.left=t.x),t.y!==void 0&&(h.top=t.y),t.width!==void 0&&(h.width=t.width),t.height!==void 0&&(h.height=t.height),h}constructor(e,t={},s){if(super(),this.src=s!==void 0?s:"",!(e instanceof ReadableStream)&&!Jd(e)&&!Array.isArray(e.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...t},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof t.audio=="object"&&"volume"in t.audio?t.audio.volume:t.volume??1;const r=async n=>(await Ei(this.localFile,n),this.localFile);this.localFile=Jd(e)?e:"localFile"in e?e.localFile:Xh(),this.ready=(e instanceof ReadableStream?r(e).then(n=>Ax(n,this.opts)):Jd(e)?Ax(e,this.opts):Promise.resolve(e)).then(async({videoSamples:n,audioSamples:o,decoderConf:a,headerBoxPos:l,parsedMatrix:c})=>{this.videoSamples=n,this.audioSamples=o,this.decoderConf=a,this.headerBoxPos=l,this.parsedMatrix=c;const{videoFrameFinder:h,audioFrameFinder:u}=yR({video:a.video==null?null:{...a.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:a.audio},await this.localFile.createReader(),n,o,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=h,this.audioFrameFinder=u;const{codedWidth:d,codedHeight:f}=a.video??{};d&&f&&(this.vfRotater=_R(d,f,c.rotationDeg)),this._meta=xR(a,n,o,c.rotationDeg),this.logger.info("Video meta:",this._meta);const p={...this._meta};this.width=this.width===0?p.width:this.width,this.height=this.height===0?p.height:this.height,this.trim.to=this.trim.to===0?p.duration:Math.min(this.trim.to,p.duration),this.trim.from=Math.min(this.trim.from,this.trim.to);const g=(this.trim.to-this.trim.from)/this.playbackRate;return this.duration=this.duration===0?g:this.duration,Math.abs(this.duration-g)>1&&(this.duration=g),this.display.to=this.display.from+this.duration,this.on("propsChange",m=>{m.volume!==void 0&&this.audioFrameFinder&&this.audioFrameFinder.setVolume(m.volume)}),p})}tickInterceptor=async(e,t)=>t;async tick(e){const t=e+this.trim.from;if(t>=this.trim.to||t>=this._meta.duration)return await this.tickInterceptor(e,{audio:await this.audioFrameFinder?.find(t)??[],state:"done"});const[s,r]=await Promise.all([this.audioFrameFinder?.find(t)??[],this.videoFrameFinder?.find(t).then(this.vfRotater)]);return r==null?await this.tickInterceptor(e,{audio:s,state:"success"}):await this.tickInterceptor(e,{video:r,audio:s,state:"success"})}thumbAborter=new AbortController;thumbFinder=null;async thumbnails(e=100,t){this.thumbAborter.abort(),this.thumbAborter=new AbortController;const s=this.thumbAborter.signal;await this.ready;const r="generate thumbnails aborted";if(s.aborted)throw Error(r);const{width:n,height:o}=this._meta,a=IR(e,Math.round(o*(e/n)),{quality:.1,type:"image/png"});return new Promise(async(l,c)=>{let h=[];const u=this.decoderConf.video;if(u==null||this.videoSamples.length===0){d();return}s.addEventListener("abort",()=>{c(Error(r))});async function d(){s.aborted||l(await Promise.all(h.map(async _=>({ts:_.ts,img:await _.img}))))}function f(_){h.push({ts:_.timestamp,img:a(_)})}const{start:p=0,end:g=this._meta.duration,step:m}=t??{};if(m){let _=p;for(this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null),this.thumbFinder=new Ix(await this.localFile.createReader(),this.videoSamples,{...u,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__});_<=g&&!s.aborted;){const x=await this.thumbFinder.find(_);x&&f(x),_+=m}await this.thumbFinder.destroy(),this.thumbFinder=null,d()}else await ER(this.videoSamples,this.localFile,u,s,{start:p,end:g},(_,x)=>{_!=null&&f(_),x&&d()})})}async split(e){if(await this.ready,e<=0||e>=this._meta.duration)throw Error("time out of bounds");const[t,s]=SR(this.videoSamples,e),[r,n]=CR(this.audioSamples,e),o=new Me({localFile:this.localFile,videoSamples:t??[],audioSamples:r??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),a=new Me({localFile:this.localFile,videoSamples:s??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await Promise.all([o.ready,a.ready]),[o,a]}addEffect(e){this.effects.push(e)}editEffect(e,t){const s=this.effects.find(r=>r.id===e);s&&Object.assign(s,t)}removeEffect(e){const t=this.effects.findIndex(s=>s.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=new Me({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await e.ready,e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e.id=this.id,e.effects=[...this.effects],e}async splitTrack(){await this.ready;const e=[];if(this.videoSamples.length>0){const t=new Me({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[],decoderConf:{video:this.decoderConf.video,audio:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}if(this.audioSamples.length>0){const t=new Me({localFile:this.localFile,videoSamples:[],audioSamples:[...this.audioSamples],decoderConf:{audio:this.decoderConf.audio,video:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}return e}cleanupThumbnails=async()=>{this.thumbAborter.abort(),this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null)};destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("Video destroy"),super.destroy(),this.thumbAborter.abort(),this.thumbFinder?.destroy(),this.thumbFinder=null,this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(e=!1){return{...super.toJSON(e),type:"Video",audio:this.audio,volume:this.volume,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Video")throw new Error(`Expected Video, got ${e.type}`);const t=await fetch(e.src);if(!t.ok)throw new Error(`Failed to fetch video from ${e.src}: ${t.status} ${t.statusText}. Make sure the file exists in the public directory.`);const s=e.audio!==void 0?{audio:e.audio,volume:e.volume}:{volume:e.volume},r=new Me(t.body,s,e.src);return await r.ready,r.left=e.left,r.top=e.top,r.width=e.width,r.height=e.height,r.angle=e.angle,r.display.from=e.display.from,r.display.to=e.display.to,r.duration=e.duration,r.playbackRate=e.playbackRate,r.zIndex=e.zIndex,r.opacity=e.opacity,r.flip=e.flip,e.style&&(r.style={...r.style,...e.style}),e.animation&&r.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(r.id=e.id),e.effects&&(r.effects=e.effects),e.transition&&(r.transition=e.transition),e.trim&&(r.trim.from=e.trim.from<1e6?e.trim.from*1e6:e.trim.from,r.trim.to=e.trim.to<1e6?e.trim.to*1e6:e.trim.to),e.volume!==void 0&&(r.volume=e.volume),r}async createPlaybackElement(){await this.ready;const t=this.localFile;if(!t||typeof t.getOriginFile!="function")throw new Error("Video does not have a local file for playback");const s=await t.getOriginFile();if(!s)throw new Error("Failed to get origin file from VideoClip");const r=URL.createObjectURL(s),n=document.createElement("video");return n.crossOrigin="anonymous",n.muted=!0,n.autoplay=!1,n.playsInline=!0,n.preload="auto",n.loop=!1,n.src=r,await new Promise((o,a)=>{const l=()=>{n.removeEventListener("loadeddata",l),n.removeEventListener("error",c),n.pause(),n.currentTime=0,o()},c=()=>{n.removeEventListener("loadeddata",l),n.removeEventListener("error",c),a(new Error("Failed to load video"))};n.addEventListener("loadeddata",l,{once:!0}),n.addEventListener("error",c,{once:!0}),n.load()}),{element:n,objectUrl:r}}async play(e,t){const s=e,r=t+this.trim.from/1e6;if(Math.abs(s.currentTime-r)>.1&&(s.currentTime=r),s.muted=!1,s.paused)try{await s.play()}catch{try{await s.play()}catch(o){console.warn("Failed to play video:",o)}}}pause(e){const t=e;t.pause(),t.muted=!0}async seek(e,t){const s=e,r=t+this.trim.from/1e6;return s.pause(),s.currentTime=r,new Promise(n=>{if(Math.abs(s.currentTime-t)<.01){n();return}const o=()=>{s.removeEventListener("seeked",o),n()};s.addEventListener("seeked",o,{once:!0}),setTimeout(()=>{s.removeEventListener("seeked",o),n()},500)})}syncPlayback(e,t,s){const r=e,n=(this.trim.to-this.trim.from)/1e6,o=s>=0&&s<n,a=s+this.trim.from/1e6;r.volume=this.volume,t&&o?r.paused?this.play(r,s).catch(console.warn):(r.muted&&(r.muted=!1),(r.ended||r.currentTime>=this.trim.to/1e6)&&(r.currentTime=a,r.play().catch(console.warn))):(r.paused||r.pause(),r.muted=!0,o&&Math.abs(r.currentTime-a)>.1&&(r.currentTime=a))}cleanupPlayback(e,t){const s=e;s.pause(),s.removeAttribute("src"),s.load(),t&&URL.revokeObjectURL(t)}async scaleToFit(e,t){await this.ready;const{width:s,height:r}=this.meta;if(s===0||r===0)return;const n=Math.min(e/s,t/r);this.width=s*n,this.height=r*n}async scaleToFill(e,t){await this.ready;const{width:s,height:r}=this.meta;if(s===0||r===0)return;const n=Math.max(e/s,t/r);this.width=s*n,this.height=r*n}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}}function xR(i,e,t,s){const r={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(i.video!=null&&e.length>0){r.width=i.video.codedWidth??0,r.height=i.video.codedHeight??0;const a=(Math.round(s/90)*90+360)%360;(a===90||a===270)&&([r.width,r.height]=[r.height,r.width])}i.audio!=null&&t.length>0&&(r.audioSampleRate=le.sampleRate,r.audioChanCount=le.channelCount);let n=0,o=0;if(e.length>0)for(let a=e.length-1;a>=0;a--){const l=e[a];if(!l.deleted){n=l.cts+l.duration;break}}if(t.length>0){const a=t.at(-1);o=a.cts+a.duration}return r.duration=Math.max(n,o),r}function yR(i,e,t,s,r){return{audioFrameFinder:r===0||i.audio==null||s.length===0?null:new bR(e,s,i.audio,{volume:r,targetSampleRate:le.sampleRate}),videoFrameFinder:i.video==null||t.length===0?null:new Ix(e,t,i.video)}}async function Ax(i,e={}){let t=null;const s={video:null,audio:null};let r=[],n=[],o=[];const a={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let l=-1,c=-1;const h=await i.createReader();await mR(h,async d=>{t=d.info;const f=d.mp4boxFile.ftyp;o.push({start:f.start,size:f.size});const p=d.mp4boxFile.moov;o.push({start:p.start,size:p.size}),Object.assign(a,gR(t.videoTracks[0]?.matrix));let{videoDecoderConf:g,audioDecoderConf:m}=jd(d.mp4boxFile,d.info);if(s.video=g??null,s.audio=m??null,g==null&&m==null&&K.error("Video no video and audio track"),m!=null){const{supported:_}=await AudioDecoder.isConfigSupported(m);_||K.error(`Video audio codec is not supported: ${m.codec}`)}if(g!=null){const{supported:_}=await VideoDecoder.isConfigSupported(g);_||K.error(`Video video codec is not supported: ${g.codec}`)}K.info("mp4BoxFile moov ready",{...d.info,tracks:null,videoTracks:null,audioTracks:null},s)},(d,f,p)=>{if(f==="video"){l===-1&&(l=p[0].dts);for(const g of p)r.push(Ex(g,l,"video"))}else if(f==="audio"&&e.audio){c===-1&&(c=p[0].dts);for(const g of p)n.push(Ex(g,c,"audio"))}}),await h.close();const u=r.at(-1)??n.at(-1);if(t==null)throw Error("Video stream is done, but not emit ready");if(u==null)throw Error("Video stream not contain any sample");return ef(r),K.info("mp4 stream parsed"),{videoSamples:r,audioSamples:n,decoderConf:s,headerBoxPos:o,parsedMatrix:a}}function Ex(i,e=0,t){let s=i.offset;const r=t==="video"&&i.is_sync?AR(i.data,i.description.type):-1;let n=i.size;return r>0&&(s+=r,n-=r),{...i,is_idr:r>=0,offset:s,size:n,cts:(i.cts-e)/i.timescale*1e6,dts:(i.dts-e)/i.timescale*1e6,duration:i.duration/i.timescale*1e6,timescale:1e6,data:t==="video"?null:i.data}}class Ix{constructor(e,t,s){this.localFileReader=e,this.samples=t,this.conf=s}decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async e=>{(this.decoder==null||this.decoder.state==="closed"||e<=this.timestamp||e-this.timestamp>3e6)&&this.reset(e),this.curAborter.abort=!0,this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const t=await this.parseFrame(e,this.decoder,this.curAborter);return this.sleepCnt=0,t};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;parseFrame=async(e,t,s)=>{if(t==null||t.state==="closed"||s.abort)return null;if(this.videoFrames.length>0){const r=this.videoFrames[0];return e<r.timestamp?null:(this.videoFrames.shift(),e>r.timestamp+(r.duration??0)?(r.close(),await this.parseFrame(e,t,s)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(t).catch(n=>{throw this.predecodeErr=!0,this.reset(e),n}),r))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&t.decodeQueueSize>0){if(performance.now()-s.st>6e3)throw Error(`Video.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await jh(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(t)}catch(r){throw this.reset(e),r}}return await this.parseFrame(e,t,s)};decoding=!1;startDecode=async e=>{if(this.decoding||e.decodeQueueSize>600)return;let t=this.videoDecCursorIdx+1;if(t>this.samples.length)return;this.decoding=!0;let s=!1;for(;t<this.samples.length;t++){const r=this.samples[t];if(!s&&!r.deleted&&(s=!0),r.is_idr)break}if(s){const r=this.samples.slice(this.videoDecCursorIdx,t);if(r[0]?.is_idr!==!0)K.warn("First sample not idr frame");else{const n=performance.now(),o=await Rx(r,this.localFileReader),a=performance.now()-n;if(a>1e3){const l=r[0],c=r.at(-1),h=c.offset+c.size-l.offset;K.warn(`Read video samples time cost: ${Math.round(a)}ms, file chunk size: ${h}`)}if(e.state==="closed")return;this.lastVfDur=o[0]?.duration??0,Qd(e,o,{onDecodingError:l=>{if(this.downgradeSoftDecode)throw l;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,K.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=o.length}}this.videoDecCursorIdx=t,this.decoding=!1};reset=e=>{if(this.decoding=!1,this.videoFrames.forEach(s=>s.close()),this.videoFrames=[],e==null||e===0)this.videoDecCursorIdx=0;else{let s=0;for(let r=0;r<this.samples.length;r++){const n=this.samples[r];if(n.is_idr&&(s=r),!(n.cts<e)){this.videoDecCursorIdx=s;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const t={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:s=>{if(this.outputFrameCnt+=1,s.timestamp===-1){s.close();return}let r=s;s.duration==null&&(r=new VideoFrame(s,{duration:this.lastVfDur}),s.close()),this.videoFrames.push(r)},error:s=>{if(s.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,K.warn(s.message);return}const r=`VideoFinder VideoDecoder err: ${s.message}, config: ${JSON.stringify(t)}, state: ${JSON.stringify(this.getState())}`;throw K.error(r),Error(r)}}),this.decoder.configure(t)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:Zd,sleepCnt:this.sleepCnt,memInfo:Mx()});destroy=async()=>{if(this.curAborter.abort=!0,this.videoFrames.forEach(e=>e.close()),this.videoFrames=[],this.decoder&&this.decoder.state!=="closed"){try{await this.decoder.flush()}catch{}try{this.decoder.close()}catch{}}this.decoder=null,this.localFileReader.close()}}function vR(i,e){for(let t=0;t<e.length;t++){const s=e[t];if(i>=s.cts&&i<s.cts+s.duration)return t;if(s.cts>i)break}return 0}class bR{constructor(e,t,s,r){this.localFileReader=e,this.samples=t,this.conf=s,this.volume=r.volume,this.sampleRate=r.targetSampleRate}volume=1;sampleRate;setVolume(e){this.volume=e,this.reset()}decoder=null;curAborter={abort:!1,st:performance.now()};find=async e=>{const t=e<=this.timestamp||e-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||t)&&this.reset(),t&&(this.timestamp=e,this.decCursorIdx=vR(e,this.samples)),this.curAborter.abort=!0;const s=e-this.timestamp;this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const r=await this.parseFrame(Math.ceil(s*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,r};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(e,t=null,s)=>{if(t==null||s.abort||t.state==="closed"||e===0)return[];const r=this.pcmData.frameCnt-e;if(r>0)return r<le.sampleRate/10&&this.startDecode(t),Px(this.pcmData,e);if(t.decoding){if(performance.now()-s.st>3e3)throw s.abort=!0,Error(`Video.tick audio timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await jh(15)}else{if(this.decCursorIdx>=this.samples.length-1)return Px(this.pcmData,this.pcmData.frameCnt);this.startDecode(t)}return this.parseFrame(e,t,s)};startDecode=e=>{if(e.decodeQueueSize>10)return;const s=[];let r=this.decCursorIdx;for(;r<this.samples.length;){const n=this.samples[r];if(r+=1,!n.deleted&&(s.push(n),s.length>=10))break}this.decCursorIdx=r,e.decode(s.map(n=>new EncodedAudioChunk({type:"key",timestamp:n.cts,duration:n.duration,data:n.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=TR(this.conf,{resampleRate:le.sampleRate,volume:this.volume},e=>{this.pcmData.data.push(e),this.pcmData.frameCnt+=e[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:Zd,sleepCnt:this.sleepCnt,memInfo:Mx()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function TR(i,e,t){let s=0,r=0;const n=h=>{if(r+=1,h.length!==0){if(e.volume!==1)for(const u of h)for(let d=0;d<u.length;d++)u[d]*=e.volume;h.length===1&&(h=[h[0],h[0]]),t(h)}},o=wR(n),a=e.resampleRate!==i.sampleRate;let l=new AudioDecoder({output:h=>{const u=Rp(h);a?o(()=>c1(u,h.sampleRate,{rate:e.resampleRate,chanCount:h.numberOfChannels})):n(u),h.close()},error:h=>{h.message.includes("Codec reclaimed due to inactivity")||c("Video AudioDecoder err",h)}});l.configure(i);function c(h,u){const d=`${h}: ${u.message}, state: ${JSON.stringify({qSize:l.decodeQueueSize,state:l.state,inputCnt:s,outputCnt:r})}`;throw K.error(d),Error(d)}return{decode(h){s+=h.length;try{for(const u of h)l.decode(u)}catch(u){c("decode audio chunk error",u)}},close(){l.state!=="closed"&&l.close()},get decoding(){return s>r&&l.decodeQueueSize>0},get state(){return l.state},get decodeQueueSize(){return l.decodeQueueSize}}}function wR(i){const e=[];let t=0;function s(o,a){e[a]=o,r()}function r(){const o=e[t];o!=null&&(i(o),t+=1,r())}let n=0;return o=>{const a=n;n+=1,o().then(l=>s(l,a)).catch(l=>s(l,a))}}function Px(i,e){const t=[new Float32Array(e),new Float32Array(e)];let s=0,r=0;for(;r<i.data.length;){const[n,o]=i.data[r];if(s+n.length>e){const a=e-s;t[0].set(n.subarray(0,a),s),t[1].set(o.subarray(0,a),s),i.data[r][0]=n.subarray(a,n.length),i.data[r][1]=o.subarray(a,o.length);break}else t[0].set(n,s),t[1].set(o,s),s+=n.length,r++}return i.data=i.data.slice(r),i.frameCnt-=e,t}async function Rx(i,e){const t=i[0],s=i.at(-1);if(s==null)return[];const r=s.offset+s.size-t.offset;if(r<3e7){const n=new Uint8Array(await e.read(r,{at:t.offset}));return i.map(o=>{const a=o.offset-t.offset;return new EncodedVideoChunk({type:o.is_sync?"key":"delta",timestamp:o.cts,duration:o.duration,data:n.subarray(a,a+o.size)})})}return await Promise.all(i.map(async n=>new EncodedVideoChunk({type:n.is_sync?"key":"delta",timestamp:n.cts,duration:n.duration,data:await e.read(n.size,{at:n.offset})})))}function SR(i,e){if(i.length===0)return[];let t=0,s=0,r=-1;for(let l=0;l<i.length;l++){const c=i[l];if(r===-1&&e<c.cts&&(r=l-1),c.is_idr)if(r===-1)t=l;else{s=l;break}}const n=i[r];if(n==null)throw Error("Not found video sample by time");const o=i.slice(0,s===0?i.length:s).map(l=>({...l}));for(let l=t;l<o.length;l++){const c=o[l];e<c.cts&&(c.deleted=!0,c.cts=-1)}ef(o);const a=i.slice(n.is_idr?r:t).map(l=>({...l,cts:l.cts-e}));for(const l of a)l.cts<0&&(l.deleted=!0,l.cts=-1);return ef(a),[o,a]}function CR(i,e){if(i.length===0)return[];let t=-1;for(let n=0;n<i.length;n++){const o=i[n];if(!(e>o.cts)){t=n;break}}if(t===-1)throw Error("Not found audio sample by time");const s=i.slice(0,t).map(n=>({...n})),r=i.slice(t).map(n=>({...n,cts:n.cts-e}));return[s,r]}function Qd(i,e,t){if(i.state==="configured"){for(let s=0;s<e.length;s++)i.decode(e[s]);i.flush().catch(s=>{if(!(s instanceof Error))throw s;if(s.message.includes("Decoding error")&&t.onDecodingError!=null){t.onDecodingError(s);return}if(!s.message.includes("Aborted due to close"))throw s})}}function AR(i,e){if(e!=="avc1"&&e!=="hvc1")return 0;const t=new DataView(i.buffer);for(let s=0;s<i.byteLength-4;){if(e==="avc1"){const r=t.getUint8(s+4)&31;if(r===5||r===7||r===8)return s}else if(e==="hvc1"){const r=t.getUint8(s+4)>>1&63;if(r===19||r===20||r===32||r===33||r===34)return s}s+=t.getUint32(s)+4}return-1}function ef(i){let e=0,t=null;for(const s of i)if(!s.deleted){if(s.is_sync&&(e+=1),e>=2)break;(t==null||s.cts<t.cts)&&(t=s)}t!=null&&t.cts<2e5&&(t.duration+=t.cts,t.cts=0)}function Mx(){try{const i=performance.memory;return{jsHeapSizeLimit:i.jsHeapSizeLimit,totalJSHeapSize:i.totalJSHeapSize,usedJSHeapSize:i.usedJSHeapSize,percentUsed:(i.usedJSHeapSize/i.jsHeapSizeLimit).toFixed(3),percentTotal:(i.totalJSHeapSize/i.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}async function ER(i,e,t,s,r,n){const o=await e.createReader(),a=await Rx(i.filter(h=>!h.deleted&&h.is_sync&&h.cts>=r.start&&h.cts<=r.end),o);if(a.length===0||s.aborted){n(null,!0);return}let l=0;Qd(c(),a,{onDecodingError:h=>{K.warn("thumbnailsByKeyFrame",h),l===0?Qd(c(!0),a,{onDecodingError:u=>{o.close(),K.error("thumbnailsByKeyFrame retry soft deocde",u)}}):(n(null,!0),o.close())}});function c(h=!1){const u={...t,...h?{hardwareAcceleration:"prefer-software"}:{}},d=new VideoDecoder({output:f=>{l+=1;const p=l===a.length;n(f,p),p&&(o.close(),d.state!=="closed"&&d.close())},error:f=>{const p=`thumbnails decoder error: ${f.message}, config: ${JSON.stringify(u)}, state: ${JSON.stringify({qSize:d.decodeQueueSize,state:d.state,outputCnt:l,inputCnt:a.length})}`;throw K.error(p),Error(p)}});return s.addEventListener("abort",()=>{o.close(),d.state!=="closed"&&d.close()}),d.configure(u),d}}function IR(i,e,t){const s=new OffscreenCanvas(i,e),r=s.getContext("2d");return async n=>(r.drawImage(n,0,0,i,e),n.close(),await s.convertToBlob(t))}class gt extends qt{type="Text";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}get width(){return this._width}set width(e){this.width!==e&&(this._width=e,this.refreshText(),this.emit("propsChange",{width:e}))}get height(){return this._height}set height(e){this.height!==e&&(this._height=e,this.refreshText(),this.emit("propsChange",{height:e}))}_lastContentWidth=0;_lastContentHeight=0;_text="";get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this.originalOpts&&this.textStyle&&this.refreshText())}get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,fill:this.originalOpts.fill,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,dropShadow:this.originalOpts.dropShadow?{color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}:void 0,wordWrap:this.originalOpts.wordWrap,wordWrapWidth:this.originalOpts.wordWrapWidth,lineHeight:this.originalOpts.lineHeight,letterSpacing:this.originalOpts.letterSpacing,textCase:this.originalOpts.textCase,textDecoration:this.originalOpts.textDecoration}}set style(e){this.updateStyle(e)}get textAlign(){return this.originalOpts.align||this.originalOpts.textAlign||"left"}set textAlign(e){this.updateStyle({align:e})}get verticalAlign(){return this.originalOpts.verticalAlign||this.originalOpts.textDecoration||"top"}set verticalAlign(e){["underline","overline","strikethrough","line-through"].includes(e)?(this.updateStyle({textDecoration:e==="strikethrough"?"line-through":e}),this.originalOpts.verticalAlign=e):this.updateStyle({verticalAlign:e})}get textCase(){return this.originalOpts.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}pixiText=null;textStyle;renderTexture=null;externalRenderer=null;pixiApp=null;originalOpts;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];constructor(e,t={},s){super(),this.originalOpts={...t},this.text=e,this.externalRenderer=s??null;const r=this.createStyleFromOpts(t),n=new Xe(r);this.textStyle=n,this.ready=(async()=>(await this.refreshText(),{...this._meta}))()}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("TextClip: Failed to create renderer. Please provide a renderer via constructor or setRenderer() method.");return this.pixiApp.renderer}async getTexture(){return this.pixiText==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture}),this.renderTexture)}async tick(e){if(await this.ready,this.pixiText==null||this.renderTexture==null)throw new Error("Text not initialized");if(this.renderTexture.width<=0||this.renderTexture.height<=0)throw new Error(`Invalid RenderTexture dimensions: ${this.renderTexture.width}x${this.renderTexture.height}`);(await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture});const s=this.renderTexture.source?.resource?.source;let r;if(s instanceof HTMLCanvasElement)r=await createImageBitmap(s);else if(s instanceof OffscreenCanvas)r=await createImageBitmap(s);else{const a=(await this.getRenderer()).extract.canvas(this.renderTexture);if(a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas)r=await createImageBitmap(a);else{const l=this.renderTexture.width,c=this.renderTexture.height;throw new OffscreenCanvas(l,c).getContext("2d")==null?new Error("Failed to create 2d context for fallback rendering"):new Error("Unable to extract canvas from render texture")}}return{video:r,state:"success"}}async split(e){await this.ready;const t=await this.clone(),s=await this.clone();return[t,s]}addEffect(e){this.effects.push(e)}editEffect(e,t){const s=this.effects.find(r=>r.id===e);s&&Object.assign(s,t)}removeEffect(e){const t=this.effects.findIndex(s=>s.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.textStyle,t=this.originalOpts||{},s=o=>{if(o!=null){if(typeof o=="number")return o;if(o instanceof ue)return o.toNumber()}},r={fontSize:t.fontSize??e.fontSize,fontFamily:t.fontFamily??(Array.isArray(e.fontFamily)?e.fontFamily[0]:typeof e.fontFamily=="string"?e.fontFamily:"Roboto"),fontWeight:t.fontWeight??e.fontWeight,fontStyle:t.fontStyle??e.fontStyle,align:t.align??(e.align==="justify"?"left":e.align),textCase:t.textCase,textDecoration:t.textDecoration};if(t.fill&&typeof t.fill=="object"&&"type"in t.fill&&t.fill.type==="gradient")r.fill=t.fill;else{const o=s(e.fill);r.fill=o??16777215}if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke)r.stroke=t.stroke;else{const o=s(e.stroke);o!==void 0&&(r.stroke=o),r.strokeWidth=t.strokeWidth??e.strokeThickness??0}if(t.dropShadow)r.dropShadow=t.dropShadow;else if(e.dropShadow){const o=e.dropShadow,a=s(o.color);a!==void 0&&(r.dropShadow={color:a,alpha:o.alpha,blur:o.blur,angle:o.angle,distance:o.distance})}if(t.wordWrap!==void 0?(r.wordWrap=t.wordWrap,r.wordWrapWidth=t.wordWrapWidth):e.wordWrap&&(r.wordWrap=e.wordWrap,r.wordWrapWidth=e.wordWrapWidth),t.lineHeight!==void 0)r.lineHeight=t.lineHeight;else if(e.lineHeight!==void 0){const o=r.fontSize??e.fontSize??40;r.lineHeight=e.lineHeight/o}t.letterSpacing!==void 0?r.letterSpacing=t.letterSpacing:e.letterSpacing!==void 0&&(r.letterSpacing=e.letterSpacing);const n=new gt(this.text,r);return await n.ready,this.copyStateTo(n),n.id=this.id,n.effects=[...this.effects],n}async updateStyle(e){this.originalOpts={...this.originalOpts,...e};const t=this.createStyleFromOpts(this.originalOpts),s=new Xe(t);this.textStyle=s,await this.refreshText()}async refreshText(){const e=this.textStyle;let t=this.text;const s=this.originalOpts.textCase;s==="uppercase"?t=t.toUpperCase():s==="lowercase"?t=t.toLowerCase():s==="title"&&(t=t.replace(/\w\S*/g,m=>m.charAt(0).toUpperCase()+m.substring(1).toLowerCase())),this.pixiText?(this.pixiText.text=t,this.pixiText.style=e,this.pixiText.children.forEach(m=>{m instanceof _e&&m.destroy()}),this.pixiText.removeChildren()):this.pixiText=new GI({text:t,style:e});const r=this.originalOpts.textDecoration||this.originalOpts.verticalAlign;if(r&&r!=="none"&&["underline","overline","strikethrough","line-through"].includes(r)){const m=r==="strikethrough"?"line-through":r,_=$e.measureText(t,e),x=e.fontSize??40,y=Math.max(1,x/12);let v=16777215;typeof e.fill=="number"?v=e.fill:e.fill&&typeof e.fill=="object"&&"fill"in e.fill&&(v=16777215);const T=new _e,S=e.lineHeight??_.lineHeight;for(let w=0;w<_.lines.length;w++){const E=_.lineWidths[w];let P=0;e.align==="center"?P=(_.maxLineWidth-E)/2:e.align==="right"&&(P=_.maxLineWidth-E);const C=w*S;let A=0;m==="underline"?A=S:m==="line-through"?A=S/2:m==="overline"&&(A=0);const U=C+A;T.rect(P,U,E,y),T.fill(v)}this.pixiText.addChild(T)}const n=this.pixiText.getLocalBounds(),o=Math.ceil(n.width||this.pixiText.width||1),a=Math.ceil(n.height||this.pixiText.height||1);let l=o;e.wordWrap&&e.wordWrapWidth>0&&(l=Math.max(l,e.wordWrapWidth));const c=a,h=this.width===0||Math.abs(this.width-this._lastContentWidth)<.1,u=this.height===0||Math.abs(this.height-this._lastContentHeight)<.1,d=h?l:Math.max(l,this.width||0),f=u?c:Math.max(c,this.height||0);this._lastContentWidth=l,this._lastContentHeight=c;const p=this.textAlign;p==="center"?this.pixiText.x=(d-o)/2:p==="right"?this.pixiText.x=d-o:this.pixiText.x=0;const g=this.originalOpts.verticalAlign||"top";g==="center"?this.pixiText.y=(f-a)/2:g==="bottom"?this.pixiText.y=f-a:this.pixiText.y=0,this.renderTexture&&this.renderTexture.destroy(),this.renderTexture=Ge.create({width:d,height:f}),this._meta.width=d,this._meta.height=f,this._width=d,this._height=f,this.duration===0&&this._meta.duration!==1/0&&(this.duration=this._meta.duration,this.display.to=this.display.from+this.duration)}createStyleFromOpts(e){const t=e.fontSize??40,s=e.lineHeight??1,r={fontSize:t,fontFamily:e.fontFamily??"Roboto",fontWeight:e.fontWeight??"normal",fontStyle:e.fontStyle??"normal",align:e.align??"left",wordWrap:e.wordWrap??!1,wordWrapWidth:e.wordWrapWidth??100,lineHeight:t*s,letterSpacing:e.letterSpacing??0};if(e.fill&&typeof e.fill=="object"&&e.fill.type==="gradient"){const n=new at(e.fill.x0,e.fill.y0,e.fill.x1,e.fill.y1);e.fill.colors.forEach(({ratio:o,color:a})=>{const l=typeof a=="number"?a:Te(a)??16777215;n.addColorStop(o,l)}),r.fill={fill:n}}else{const{color:n,alpha:o}=_i(e.fill);r.fill=n,o<1&&(r.fillAlpha=o)}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const n=Te(e.stroke.color);n!==void 0&&(r.stroke={color:n,width:e.stroke.width},e.stroke.join&&(r.stroke.join=e.stroke.join),e.stroke.cap&&(r.stroke.cap=e.stroke.cap),e.stroke.miterLimit&&(r.stroke.miterLimit=e.stroke.miterLimit))}else{const n=Te(e.stroke),o=e.strokeWidth??0;n!==void 0&&o>0?r.stroke={color:n,width:o}:e.strokeWidth&&e.strokeWidth>0&&(r.stroke={color:0,width:e.strokeWidth})}if(e.dropShadow){const n=Te(e.dropShadow.color);n!==void 0&&(r.dropShadow={color:n,alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,angle:e.dropShadow.angle??Math.PI/6,distance:e.dropShadow.distance??2})}return r}destroy(){if(!this.destroyed){K.info("Text destroy");try{this.pixiText!=null&&this.pixiText.destroyed!==!0&&this.pixiText.destroy({children:!0})}catch{}finally{this.pixiText=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),s={};return this.originalOpts.fontSize!==void 0&&(s.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(s.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontWeight!==void 0&&(s.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(s.fontStyle=this.originalOpts.fontStyle),this.originalOpts.fill!==void 0&&(s.color=this.originalOpts.fill),this.originalOpts.align!==void 0&&(s.align=this.originalOpts.align),this.originalOpts.wordWrap!==void 0&&(s.wordWrap=this.originalOpts.wordWrap),this.originalOpts.wordWrapWidth!==void 0&&(s.wordWrapWidth=this.originalOpts.wordWrapWidth),this.originalOpts.lineHeight!==void 0&&(s.lineHeight=this.originalOpts.lineHeight),this.originalOpts.letterSpacing!==void 0&&(s.letterSpacing=this.originalOpts.letterSpacing),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?s.stroke={color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:s.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.dropShadow&&(s.shadow={color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}),{...t,type:"Text",text:this.text,style:s,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Text")throw new Error(`Expected Text, got ${e.type}`);const t=e.text||"",s=e.style||{},r={};s.fontSize!==void 0&&(r.fontSize=s.fontSize),s.fontFamily!==void 0&&(r.fontFamily=s.fontFamily),s.fontWeight!==void 0&&(r.fontWeight=s.fontWeight),s.fontStyle!==void 0&&(r.fontStyle=s.fontStyle),s.color!==void 0&&(r.fill=s.color),s.align!==void 0&&(r.align=s.align),s.wordWrap!==void 0&&(r.wordWrap=s.wordWrap),s.wordWrapWidth!==void 0&&(r.wordWrapWidth=s.wordWrapWidth),s.lineHeight!==void 0&&(r.lineHeight=s.lineHeight),s.letterSpacing!==void 0&&(r.letterSpacing=s.letterSpacing),s.stroke&&(s.stroke.join||s.stroke.cap||s.stroke.miterLimit!==void 0?r.stroke={color:s.stroke.color,width:s.stroke.width,join:s.stroke.join,cap:s.stroke.cap,miterLimit:s.stroke.miterLimit}:(r.stroke=s.stroke.color,r.strokeWidth=s.stroke.width)),s.shadow&&(r.dropShadow={color:s.shadow.color,alpha:s.shadow.alpha,blur:s.shadow.blur,distance:s.shadow.distance,angle:s.shadow.angle});const n=new gt(t,r);return n.left=e.left,n.top=e.top,n.width=e.width,n.height=e.height,n.angle=e.angle,n.display.from=e.display.from,n.display.to=e.display.to,n.duration=e.duration,n.playbackRate=e.playbackRate,n.zIndex=e.zIndex,n.opacity=e.opacity,n.flip=e.flip,e.animation&&n.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(n.id=e.id),e.effects&&(n.effects=e.effects),await n.ready,n}getVisibleHandles(){return["mr","mb","br","rot"]}}class ct extends qt{type="Effect";ready;_meta={duration:5e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effect;constructor(e){super(),this.effect={id:`eff_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new ct(this.effect.key);return this.copyStateTo(e),e.id=this.id,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),s=await this.clone();return[t,s]}toJSON(e=!1){return{...super.toJSON(e),type:"Effect",effect:this.effect,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Effect")throw new Error(`Expected Effect, got ${e.type}`);const t=new ct(e.effect.key);return t.effect=e.effect,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}class mn extends qt{type="Placeholder";meta={width:0,height:0,duration:0};constructor(e,t={},s="Placeholder"){super(),this.type=s,this.src=e,this.meta={width:t.width||1280,height:t.height||720,duration:t.duration||5e6},this.width=this.meta.width,this.height=this.meta.height,this.duration=this.meta.duration,this.trim.to=this.duration,this.display.to=this.display.from+this.duration,this.ready=Promise.resolve(this.meta)}placeholderFrame=null;async tick(e){if(!this.placeholderFrame){const t=document.createElement("canvas");t.width=this.meta.width,t.height=this.meta.height;const s=t.getContext("2d");s&&(s.fillStyle="#1e1e1e",s.fillRect(0,0,t.width,t.height),s.fillStyle="#ffffff",s.font=`${Math.floor(t.height/10)}px sans-serif`,s.textAlign="center",s.textBaseline="middle",s.fillText("Loading...",t.width/2,t.height/2),s.strokeStyle="#333333",s.lineWidth=10,s.strokeRect(0,0,t.width,t.height)),this.placeholderFrame=await createImageBitmap(t)}return{video:this.placeholderFrame,state:e>=this.duration?"done":"success",audio:[]}}async clone(){const e=new mn(this.src,this.meta);return this.copyStateTo(e),e.id=this.id,e}async split(e){const t=await this.clone(),s=await this.clone();return t.trim.to=e+this.trim.from,s.trim.from=e+this.trim.from,t.duration=t.trim.to-t.trim.from,s.duration=s.trim.to-s.trim.from,t.display.to=t.display.from+t.duration,s.display.from=t.display.to,s.display.to=s.display.from+s.duration,[t,s]}}class Lt extends qt{type="Transition";ready;_meta={duration:2e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;transitionEffect;fromClipId=null;toClipId=null;constructor(e){super(),this.transitionEffect={id:`trans_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Lt(this.transitionEffect.key);return this.copyStateTo(e),e.fromClipId=this.fromClipId,e.toClipId=this.toClipId,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),s=await this.clone();return[t,s]}toJSON(e=!1){return{...super.toJSON(e),type:"Transition",transitionEffect:this.transitionEffect,fromClipId:this.fromClipId,toClipId:this.toClipId,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Transition")throw new Error(`Expected Transition, got ${e.type}`);const t=new Lt(e.transitionEffect.key);return t.transitionEffect=e.transitionEffect,t.fromClipId=e.fromClipId||null,t.toClipId=e.toClipId||null,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}function kx(i,e){let t=!1;async function s(){const r=i.getReader();for(;!t;){const{value:n,done:o}=await r.read();if(o){e.onDone();return}await e.onChunk(n)}r.releaseLock(),await i.cancel()}return s().catch(console.error),()=>{t=!0}}function Fx(i,e,t){let s=0,r=0;const n=i.boxes;let o=!1;const a=()=>{if(!o)if(n.find(p=>p.type==="moof")!=null)o=!0;else return null;if(r>=n.length)return null;const d=new oi.DataStream;let f=r;try{for(;f<n.length;)n[f].write(d),delete n[f],f+=1}catch(p){const g=n[f];throw p instanceof Error&&g!=null?Error(`${p.message} | deltaBuf( boxType: ${g.type}, boxSize: ${g.size}, boxDataLen: ${g.data?.length??-1})`):p}return PR(i),r=n.length,new Uint8Array(d.buffer)};let l=!1,c=!1,h=null;return{stream:new ReadableStream({start(d){s=self.setInterval(()=>{const f=a();f!=null&&!c&&d.enqueue(f)},e),h=f=>{if(clearInterval(s),i.flush(),f!=null){d.error(f);return}const p=a();p!=null&&!c&&d.enqueue(p),c||d.close()},l&&h()},cancel(){c=!0,clearInterval(s),t?.()}}),stop:d=>{l||(l=!0,h?.(d))}}}function PR(i){if(i.moov!=null){for(var e=0;e<i.moov.traks.length;e++)i.moov.traks[e].samples=[];i.mdats=[],i.moofs=[]}}class Bx{readable;writable;inputBufOffset=0;isStreamCancelled=!1;constructor(){const e=oi.createFile();this.readable=new ReadableStream({start:t=>this.initMP4Box(e,t),cancel:()=>{this.isStreamCancelled=!0,e.stop()}},{highWaterMark:50}),this.writable=new WritableStream({write:async t=>{if(this.isStreamCancelled)throw new Error("Stream cancelled");const s=t.buffer;s.fileStart=this.inputBufOffset,this.inputBufOffset+=s.byteLength,e.appendBuffer(s)},close:()=>{e.flush(),e.stop(),e.onFlush?.()},abort:t=>{RR.error("SampleTransform writable aborted:",t),e.stop()}})}initMP4Box(e,t){e.onReady=r=>{[r.videoTracks[0],r.audioTracks[0]].forEach(n=>{n&&e.setExtractionOptions(n.id,n.video?"video":"audio",{nbSamples:100})}),t.enqueue({chunkType:"ready",data:{info:r,file:e}}),e.start()};const s={};e.onSamples=(r,n,o)=>{const a=o.map(l=>({...l}));t.enqueue({chunkType:"samples",data:{id:r,type:n,samples:a}}),s[r]=(s[r]??0)+o.length,e.releaseUsedSamples(r,s[r])},e.onFlush=()=>{t.close()},e.onError=r=>{t.error(new Error(`mp4box error: ${r}`))}}}const RR={error:(...i)=>console.error("[SampleTransform]",...i)};function MR(i){let e=0;const t=i.boxes,s=[];let r=0;async function n(){const p=f(t,e);e=t.length,s.forEach(({track:g,id:m})=>{const _=g.samples.at(-1);_!=null&&(r=Math.max(r,_.cts+_.duration)),i.releaseUsedSamples(m,g.samples.length),g.samples=[]}),i.mdats=[],i.moofs=[],p!=null&&await h?.write(p)}let o=[];function a(){if(o.length>0)return!0;const p=t.findIndex(g=>g.type==="moov");if(p===-1)return!1;if(o=t.slice(0,p+1),e=p+1,s.length===0)for(let g=1;;g+=1){const m=i.getTrackById(g);if(m==null)break;s.push({track:m,id:g})}return!0}let l=0;const c=Xh();let h=null;const u=(async()=>{h=await c.createWriter(),l=self.setInterval(()=>{a()&&n()},100)})();let d=!1;return async()=>{if(d)throw Error("File exported");if(d=!0,await u,clearInterval(l),!a()||h==null)return null;i.flush(),await n(),await h?.close();const p=o.find(_=>_.type==="moov");if(p==null)return null;p.mvhd.duration=r;const g=Xh(),m=f(o,0);return await Ei(g,m.slice()),await Ei(g,c,{overwrite:!1}),await g.stream()};function f(p,g){if(g>=p.length)return null;const m=new oi.DataStream;for(let _=g;_<p.length;_++)p[_]!==null&&(p[_].write(m),delete p[_]);return new Uint8Array(m.buffer).slice()}}function kR(i){const e=new ArrayBuffer(i.byteLength);i.copyTo(e);const t=i.timestamp;return{duration:i.duration??0,dts:t,cts:t,is_sync:i.type==="key",data:e}}async function Ux(i){const e=oi.createFile(),t=MR(e);await FR(i,e);const s=await t();if(s==null)throw Error("Can not generate file from streams");return s}async function FR(i,e){let t=0,s=0,r=0,n=0,o=0,a=0,l=null,c=null;for(const h of i){let u=null,d=null,f=null,p=null;if(await new Promise(async g=>{kx(h.pipeThrough(new Bx),{onDone:g,onChunk:async({chunkType:m,data:_})=>{if(m==="ready"){const{videoTrackConf:x,audioTrackConf:y}=jd(_.file,_.info);t===0&&x!=null&&(t=e.addTrack(x)),n===0&&y!=null&&(n=e.addTrack(y))}else if(m==="samples"){const{type:x,samples:y}=_,v=x==="video"?t:n,T=x==="video"?s:o,S=x==="video"?r:a;y.forEach(E=>{let P,C;x==="video"?(u===null&&(u=E.dts,d=E.cts),P=E.dts-u,C=E.cts-(d??0)):(f===null&&(f=E.dts,p=E.cts),P=E.dts-f,C=E.cts-(p??0)),e.addSample(v,new Uint8Array(E.data),{duration:E.duration,dts:P+T,cts:C+S,is_sync:E.is_sync})});const w=y.at(-1);if(w==null)return;x==="video"?l=w:x==="audio"&&(c=w)}}})}),l!=null&&u!==null&&d!==null){const g=l.dts-u+l.duration,m=l.cts-d+l.duration;s+=g,r+=m}if(c!=null&&l!=null){const g=c.timescale/l.timescale;o=Math.round(s*g),a=Math.round(r*g)}}}async function BR(i){return await Ux([i])}function UR(i){let e=[];const t=new AudioDecoder({output:s=>{e.push(s)},error:K.error});return t.configure(i),{decode:async s=>{s.forEach(n=>{t.decode(new EncodedAudioChunk({type:n.is_sync?"key":"delta",timestamp:1e6*n.cts/n.timescale,duration:1e6*n.duration/n.timescale,data:n.data}))}),await t.flush();const r=e;return e=[],r},close:()=>{t.close()}}}function OR(i,e){const t={codec:i.codec,sampleRate:i.sampleRate,numberOfChannels:i.numberOfChannels},s=new AudioEncoder({output:o=>{e(kR(o))},error:o=>{K.error("AudioEncoder error:",o,", config:",t)}});s.configure(t);let r=null;function n(o,a){return new AudioData({timestamp:a,numberOfChannels:i.numberOfChannels,numberOfFrames:o.length/i.numberOfChannels,sampleRate:i.sampleRate,format:"f32-planar",data:new Float32Array(o)})}return{encode:async(o,a)=>{r!=null&&s.encode(n(r.data,r.ts)),r={data:o,ts:a}},stop:async()=>{r!=null&&(DR(r.data,i.numberOfChannels,i.sampleRate),s.encode(n(r.data,r.ts)),r=null),await s.flush(),s.close()}}}function DR(i,e,t){const s=i.length-1,r=Math.min(t/2,s);for(let n=0;n<r;n++)for(let o=1;o<=e;o++)i[Math.floor(s/o)-n]*=n/r}function GR(i,e){K.info("mixinMP4AndAudio, opts:",{volume:e.volume,loop:e.loop});const t=oi.createFile(),{stream:s,stop:r}=Fx(t,500);let n=null,o=null,a=[],l=0,c=0,h=0,u=!0,d=le.sampleRate;kx(i.pipeThrough(new Bx),{onDone:async()=>{await o?.stop(),n?.close(),r()},onChunk:async({chunkType:m,data:_})=>{if(m==="ready"){const{videoTrackConf:x,audioTrackConf:y,audioDecoderConf:v}=jd(_.file,_.info);l===0&&x!=null&&(l=t.addTrack(x));const T=y??{timescale:1e6,samplerate:d,channel_count:le.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};c===0&&(c=t.addTrack(T),d=y?.samplerate??d,u=y!=null);const S=new AudioContext({sampleRate:d});a=Yh(await S.decodeAudioData(await new Response(e.stream).arrayBuffer())),v!=null&&(n=UR(v)),o=OR(v??{codec:T.type==="mp4a"?le.codec:T.type,numberOfChannels:T.channel_count,sampleRate:T.samplerate},w=>t.addSample(c,new Uint8Array(w.data),w))}else if(m==="samples"){const{id:x,type:y,samples:v}=_;if(y==="video"){v.forEach(T=>t.addSample(x,new Uint8Array(T.data),T)),u||await p(v);return}y==="audio"&&await g(v)}}});function f(m){const _=a.map(x=>e.loop?qh(x,h,h+m):x.slice(h,h+m));if(h+=m,e.volume!==1)for(const x of _)for(let y=0;y<x.length;y++)x[y]*=e.volume;return _}async function p(m){const _=m[0],x=m[m.length-1],y=Math.floor((x.cts+x.duration-_.cts)/_.timescale*d),v=Mp([f(y)]);v.length!==0&&o?.encode(v,_.cts/_.timescale*1e6)}async function g(m){if(n==null)return;const _=(await n.decode(m)).map(Rp),x=Pp(_),y=f(x[0].length),v=m[0];o?.encode(Mp([x,y]),v.cts/v.timescale*1e6)}return s}const zR=`
|
|
1416
|
+
`)}function nR(i,e,t,s,r){const{domElement:n,styleElement:o,svgRoot:a}=r;n.innerHTML=`<style>${e.cssStyle}</style><div style='padding:0;'>${i}</div>`,n.setAttribute("style",`transform: scale(${t});transform-origin: top left; display: inline-block`),o.textContent=s;const{width:l,height:c}=r.image;return a.setAttribute("width",l.toString()),a.setAttribute("height",c.toString()),new XMLSerializer().serializeToString(a)}function oR(i,e){const t=Gt.getOptimalCanvasAndContext(i.width,i.height,e),{context:s}=t;return s.clearRect(0,0,i.width,i.height),s.drawImage(i,0,0),t}function aR(i,e,t){return new Promise(async s=>{t&&await new Promise(r=>setTimeout(r,100)),i.onload=()=>{s()},i.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(e)}`,i.crossOrigin="anonymous"})}class v_{constructor(e){this._activeTextures={},this._renderer=e,this._createCanvas=e.type===Qe.WEBGPU}getTexture(e){return this.getTexturePromise(e)}getManagedTexture(e){const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].promise;const s=this._buildTexturePromise(e).then(r=>(this._activeTextures[t].texture=r,r));return this._activeTextures[t]={texture:null,promise:s,usageCount:1},s}getReferenceCount(e){return this._activeTextures[e]?.usageCount??null}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(t.texture?this._cleanUp(t.texture):t.promise.then(s=>{t.texture=s,this._cleanUp(t.texture)}).catch(()=>{L("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[e]=null))}getTexturePromise(e){return this._buildTexturePromise(e)}async _buildTexturePromise(e){const{text:t,style:s,resolution:r,textureStyle:n}=e,o=Se.get(F0),a=tR(t,s),l=await rR(a),c=NI(t,s,l,o),h=Math.ceil(Math.ceil(Math.max(1,c.width)+s.padding*2)*r),u=Math.ceil(Math.ceil(Math.max(1,c.height)+s.padding*2)*r),d=o.image,f=2;d.width=(h|0)+f,d.height=(u|0)+f;const p=nR(t,s,r,l,o);await aR(d,p,QP()&&a.length>0);const g=d;let m;this._createCanvas&&(m=oR(d,r));const x=y_(m?m.canvas:g,d.width-f,d.height-f,r);return n&&(x.source.style=n),this._createCanvas&&(this._renderer.texture.initSource(x.source),Gt.returnCanvasAndContext(m)),Se.return(o),x}returnTexturePromise(e){e.then(t=>{this._cleanUp(t)}).catch(()=>{L("HTMLTextSystem: Failed to clean texture")})}_cleanUp(e){ve.returnTexture(e,!0),e.source.resource=null,e.source.uploadMethodId="unknown"}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexturePromise(this._activeTextures[e].promise);this._activeTextures=null}}v_.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"htmlText"};class lR extends re{constructor(e){const{text:t,style:s,autoSplit:r,lineAnchor:n,wordAnchor:o,charAnchor:a,...l}=e;super(l),this._dirty=!1,this._canReuseChars=!1,this.chars=[],this.words=[],this.lines=[],this._originalText=t,this._autoSplit=r,this._lineAnchor=n,this._wordAnchor=o,this._charAnchor=a,this.style=s}split(){const e=this.splitFn();this.chars=e.chars,this.words=e.words,this.lines=e.lines,this.addChild(...this.lines),this.charAnchor=this._charAnchor,this.wordAnchor=this._wordAnchor,this.lineAnchor=this._lineAnchor,this._dirty=!1,this._canReuseChars=!0}get text(){return this._originalText}set text(e){this._originalText=e,this.lines.forEach(t=>t.destroy({children:!0})),this.lines.length=0,this.words.length=0,this.chars.length=0,this._canReuseChars=!1,this.onTextUpdate()}_setOrigin(e,t,s){let r;typeof e=="number"?r={x:e,y:e}:r={x:e.x,y:e.y},t.forEach(n=>{const o=n.getLocalBounds(),a=o.minX+o.width*r.x,l=o.minY+o.height*r.y;n.origin.set(a,l)}),this[s]=e}get lineAnchor(){return this._lineAnchor}set lineAnchor(e){this._setOrigin(e,this.lines,"_lineAnchor")}get wordAnchor(){return this._wordAnchor}set wordAnchor(e){this._setOrigin(e,this.words,"_wordAnchor")}get charAnchor(){return this._charAnchor}set charAnchor(e){this._setOrigin(e,this.chars,"_charAnchor")}get style(){return this._style}set style(e){e||(e={}),this._style=new Xe(e),this.words.forEach(t=>t.destroy()),this.words.length=0,this.lines.forEach(t=>t.destroy()),this.lines.length=0,this._canReuseChars=!0,this.onTextUpdate()}onTextUpdate(){this._dirty=!0,this._autoSplit&&this.split()}destroy(e){super.destroy(e),this.chars=[],this.words=[],this.lines=[],(typeof e=="boolean"?e:e?.style)&&this._style.destroy(e),this._style=null,this._originalText=""}}const b_=class _n extends lR{constructor(e){const t={..._n.defaultOptions,...e};super(t)}static from(e,t){const s={..._n.defaultOptions,...t,text:e.text,style:new Xe(e.style)};return new _n({...s})}splitFn(){return ZP({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};b_.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let cR=b_;class hR extends dn{constructor(e){super(),this._renderer=e,e.runners.resolutionChange.add(this)}resolutionChange(){const e=this.renderable;e._autoResolution&&e.onViewUpdate()}destroy(){const{canvasText:e}=this._renderer;e.getReferenceCount(this.currentKey)>0?e.decreaseReferenceCount(this.currentKey):this.texture&&e.returnTexture(this.texture),this._renderer.runners.resolutionChange.remove(this),this._renderer=null}}class T_{constructor(e){this._renderer=e}validateRenderable(e){const t=this._getGpuText(e),s=e.styleKey;return t.currentKey!==s?!0:e._didTextUpdate}addRenderable(e,t){const s=this._getGpuText(e);if(e._didTextUpdate){const r=e._autoResolution?this._renderer.resolution:e.resolution;(s.currentKey!==e.styleKey||e.resolution!==r)&&this._updateGpuText(e),e._didTextUpdate=!1,qd(s,e)}this._renderer.renderPipes.batch.addToBatch(s,t)}updateRenderable(e){const t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){const t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){const t=new hR(this._renderer);return t.currentKey="--",t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,t}destroy(){this._renderer=null}}T_.extension={type:[b.WebGLPipes,b.WebGPUPipes,b.CanvasPipes],name:"text"};class w_{constructor(e){this._activeTextures={},this._renderer=e}getTexture(e,t,s,r){typeof e=="string"&&(W("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:s,resolution:t}),e.style instanceof Xe||(e.style=new Xe(e.style)),e.textureStyle instanceof wt||(e.textureStyle=new wt(e.textureStyle)),typeof e.text!="string"&&(e.text=e.text.toString());const{text:n,style:o,textureStyle:a}=e,l=e.resolution??this._renderer.resolution,{frame:c,canvasAndContext:h}=Ws.getCanvasAndContext({text:n,style:o,resolution:l}),u=y_(h.canvas,c.width,c.height,l);if(a&&(u.source.style=a),o.trim&&(c.pad(o.padding),u.frame.copyFrom(c),u.frame.scale(1/l),u.updateUvs()),o.filters){const d=this._applyFilters(u,o.filters);return this.returnTexture(u),Ws.returnCanvasAndContext(h),d}return this._renderer.texture.initSource(u._source),Ws.returnCanvasAndContext(h),u}returnTexture(e){const t=e.source;t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",ve.returnTexture(e,!0)}renderTextToCanvas(){W("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;const s=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle});return this._activeTextures[t]={texture:s,usageCount:1},s}decreaseReferenceCount(e){const t=this._activeTextures[e];t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null)}getReferenceCount(e){return this._activeTextures[e]?.usageCount??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){const s=this._renderer.renderTarget.renderTarget,r=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind(s,!1),r}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}}w_.extension={type:[b.WebGLSystem,b.WebGPUSystem,b.CanvasSystem],name:"canvasText"},V.add(D1,G1);function Te(i){if(i!=null){if(typeof i=="number")return i;if(typeof i=="string"){if(i==="transparent")return;if(i.startsWith("#")){const t=parseInt(i.slice(1),16);if(!isNaN(t))return t}if(i.startsWith("0x")){const t=parseInt(i,16);if(!isNaN(t))return t}const e=parseInt(i,16);if(!isNaN(e))return e;try{return new ue(i).toNumber()}catch{return}}}}const S_=i=>i==="transparent",xi=(i,e=16777215)=>S_(i)?{color:e,alpha:0}:{color:Te(i)??e,alpha:1};class ei extends qt{type="Caption";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}text;get style(){if(!this.originalOpts)return{};const e=this.originalOpts;return{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,fontStyle:e.fontStyle,color:e.fill,align:e.align,textCase:e.textCase,stroke:e.stroke?typeof e.stroke=="object"?{color:e.stroke.color,width:e.stroke.width}:{color:e.stroke,width:e.strokeWidth??0}:void 0,shadow:e.dropShadow?{color:e.dropShadow.color??"#000000",alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,distance:e.dropShadow.distance??0,angle:e.dropShadow.angle??0}:void 0}}set style(e){this.updateStyle(e)}get fontFamily(){return this.opts.fontFamily}set fontFamily(e){this.updateStyle({fontFamily:e})}get fontUrl(){return this.opts.fontUrl}set fontUrl(e){this.updateStyle({fontUrl:e})}get fontSize(){return this.opts.fontSize}set fontSize(e){this.updateStyle({fontSize:e})}get fontWeight(){return this.opts.fontWeight}set fontWeight(e){this.updateStyle({fontWeight:e})}get fontStyle(){return this.opts.fontStyle}set fontStyle(e){this.updateStyle({fontStyle:e})}get fill(){return this.opts.fill}set fill(e){this.updateStyle({fill:e})}get align(){return this.opts.align}set align(e){this.updateStyle({align:e})}get stroke(){return this.originalOpts?.stroke}set stroke(e){this.updateStyle({stroke:e})}get strokeWidth(){return this.opts.strokeWidth}set strokeWidth(e){this.updateStyle({strokeWidth:e})}get dropShadow(){return this.originalOpts?.dropShadow}set dropShadow(e){this.updateStyle({dropShadow:e})}get caption(){return this.originalOpts?.caption}set caption(e){this.updateStyle({caption:e})}bottomOffset;get textCase(){return this.originalOpts?.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;get mediaId(){return this.opts.mediaId}set mediaId(e){this.opts.mediaId=e,this.originalOpts&&(this.originalOpts.mediaId=e)}effects=[];get words(){return this.opts.words}set words(e){this.opts.words=e,this.originalOpts&&(this.originalOpts.caption?this.originalOpts.caption.words=e:this.originalOpts.words=e),this.text=e.map(t=>t.text).filter(t=>t&&t.trim()!=="").join(" "),this.refreshCaptions().then(()=>{this.emit("propsChange",{})})}opts;pixiTextContainer=null;renderTexture=null;wordTexts=[];extraPadding=0;textStyle;externalRenderer=null;pixiApp=null;originalOpts=null;constructor(e,t={},s){super(),this.text=e,this.originalOpts={...t},this.externalRenderer=s??null,this.opts={fontSize:t.fontSize??30,fontFamily:t.fontFamily??"Arial",fontUrl:t.fontUrl??"",fontWeight:t.fontWeight??"normal",fontStyle:t.fontStyle??"normal",fill:t.fill??"#ffffff",strokeWidth:t.strokeWidth??0,align:t.align??"center",wordWrapWidth:t.wordWrapWidth??0,wordWrap:t.wordWrap??!1,lineHeight:t.lineHeight??1,letterSpacing:t.letterSpacing??0,textCase:t.textCase??"none",videoWidth:t.caption?.positioning?.videoWidth??t.videoWidth??1280,videoHeight:t.caption?.positioning?.videoHeight??t.videoHeight??720,bottomOffset:t.caption?.positioning?.bottomOffset??t.bottomOffset??30,keyword:t.caption?.colors?.keyword??t.colors?.keyword??"#ffff00",background:t.caption?.colors?.background??t.colors?.background??"#000000",active:t.caption?.colors?.active??t.colors?.active??"#ffffff",activeFill:t.caption?.colors?.activeFill??t.colors?.activeFill??"#00ff00",appeared:t.caption?.colors?.appeared??t.colors?.appeared??"#ffffff",words:t.caption?.words??t.words??[],preserveKeywordColor:t.caption?.preserveKeywordColor??t.preserveKeywordColor??!1,mediaId:t.mediaId};const r={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(t.fill&&typeof t.fill=="object"&&t.fill.type==="gradient"){const a=new at(t.fill.x0,t.fill.y0,t.fill.x1,t.fill.y1);t.fill.colors.forEach(({ratio:l,color:c})=>{const h=typeof c=="number"?c:Te(c)??16777215;a.addColorStop(l,h)}),r.fill={fill:a}}else{let a;t.fill==="transparent"?a=16777215:(typeof t.fill=="string"||typeof t.fill=="number")&&(a=Te(t.fill)),r.fill=a??16777215}const n=a=>a==="transparent";if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke){if(!n(t.stroke.color)){const a=Te(t.stroke.color);a!==void 0&&(r.stroke={color:a,width:t.stroke.width},t.stroke.join&&(r.stroke.join=t.stroke.join))}}else if(!n(t.stroke)){const a=Te(t.stroke);a!==void 0?r.stroke={color:a,width:this.opts.strokeWidth??0}:this.opts.strokeWidth&&this.opts.strokeWidth>0&&(r.stroke={color:0,width:this.opts.strokeWidth})}if(t.dropShadow){const a=Te(t.dropShadow.color);a!==void 0&&(r.dropShadow={color:a,alpha:t.dropShadow.alpha??.5,blur:t.dropShadow.blur??4,angle:t.dropShadow.angle??Math.PI/6,distance:t.dropShadow.distance??2})}const o=new Xe(r);this.textStyle=o,this.ready=(async()=>{await this.refreshCaptions();const a={...this._meta};return q.info("CaptionClip ready:",a),a})()}async updateStyle(e){this.originalOpts||(this.originalOpts={}),this.originalOpts={...this.originalOpts,...e},e.fontSize!==void 0&&(this.opts.fontSize=e.fontSize),e.fontFamily!==void 0&&(this.opts.fontFamily=e.fontFamily),e.fontUrl!==void 0&&(this.opts.fontUrl=e.fontUrl),e.fontWeight!==void 0&&(this.opts.fontWeight=e.fontWeight),e.fontStyle!==void 0&&(this.opts.fontStyle=e.fontStyle),e.fill!==void 0&&(this.opts.fill=e.fill),e.align!==void 0&&(this.opts.align=e.align),e.letterSpacing!==void 0&&(this.opts.letterSpacing=e.letterSpacing),e.lineHeight!==void 0&&(this.opts.lineHeight=e.lineHeight),e.textCase!==void 0&&(this.opts.textCase=e.textCase),e.caption?.colors&&(e.caption.colors.appeared!==void 0&&(this.opts.appeared=e.caption.colors.appeared),e.caption.colors.active!==void 0&&(this.opts.active=e.caption.colors.active),e.caption.colors.activeFill!==void 0&&(this.opts.activeFill=e.caption.colors.activeFill),e.caption.colors.background!==void 0&&(this.opts.background=e.caption.colors.background),e.caption.colors.keyword!==void 0&&(this.opts.keyword=e.caption.colors.keyword)),e.caption?.preserveKeywordColor!==void 0&&(this.opts.preserveKeywordColor=e.caption.preserveKeywordColor);const t={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(this.opts.fill&&typeof this.opts.fill=="object"&&this.opts.fill.type==="gradient"){const r=new at(this.opts.fill.x0,this.opts.fill.y0,this.opts.fill.x1,this.opts.fill.y1);this.opts.fill.colors.forEach(({ratio:n,color:o})=>{const a=typeof o=="number"?o:Te(o)??16777215;r.addColorStop(n,a)}),t.fill={fill:r}}else{const r=typeof this.opts.fill=="string"||typeof this.opts.fill=="number"?Te(this.opts.fill):void 0;t.fill=r??16777215}if(e.stroke!==void 0||e.strokeWidth!==void 0)if(this.originalOpts.stroke&&typeof this.originalOpts.stroke=="object"&&"color"in this.originalOpts.stroke){const r=Te(this.originalOpts.stroke.color);r!==void 0&&(t.stroke={color:r,width:this.originalOpts.stroke.width},this.originalOpts.stroke.join&&(t.stroke.join=this.originalOpts.stroke.join))}else{const r=Te(this.originalOpts.stroke),n=e.strokeWidth??this.originalOpts.strokeWidth??0;r!==void 0?t.stroke={color:r,width:n}:n>0&&(t.stroke={color:0,width:n})}const s=e.dropShadow??this.originalOpts.dropShadow;if(s){const r=Te(s.color);r!==void 0&&(t.dropShadow={color:r,alpha:s.alpha??.5,blur:s.blur??4,angle:s.angle??Math.PI/6,distance:s.distance??2})}this.textStyle=new Xe(t),await this.refreshCaptions(),this.emit("propsChange",e)}async refreshCaptions(){this.pixiTextContainer?this.pixiTextContainer.removeChildren():this.pixiTextContainer=new re;const e=this.textStyle;let t=0,s=0,r=0;const n=this.opts.textCase,o=$e.measureText(" ",this.textStyle);this.wordTexts=this.opts.words.map(S=>{let w=S.text;if(!w||w.trim()===""){const D=new re;return D.label="emptyWord",this.pixiTextContainer.addChild(D),D}n==="uppercase"?w=w.toUpperCase():n==="lowercase"?w=w.toLowerCase():n==="title"&&(w=w.replace(/\w\S*/g,D=>D.charAt(0).toUpperCase()+D.substring(1).toLowerCase()));const E=new cR({text:w,style:e});E.x=t,E.y=0;const P=E.getLocalBounds(),C=Math.ceil(P.width||E.width),A=Math.ceil(P.height||E.height);s=Math.max(s,A),t+=C+o.width,r=t-o.width,this.pixiTextContainer.addChild(E);const U=Te(this.opts.fill);return E.tint=U??16777215,E});const a=r,l=s,c=new xe;c.label="containerBackground";const h=this.opts.background==="transparent"||!this.opts.background,u=h?0:Te(this.opts.background),d=h?0:1,f=15;c.roundRect(0,0,a+f*2,l+f*2,10),c.fill({color:u,alpha:d}),this.wordTexts.forEach(S=>{this.extraPadding=0,S.pivot.y=0,S.pivot.x=0,S.y=f-this.extraPadding,S.x+=f}),this.pixiTextContainer.addChildAt(c,0);const g=a+f*2,m=l+f*2;this.renderTexture?this.renderTexture.resize(g,m):this.renderTexture=Ge.create({width:g,height:m});try{(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture})}catch(S){q.warn("CaptionClip: Could not render captions during refresh",S)}this._meta.width=g,this._meta.height=m,this._meta.duration=1/0;const x=this.opts.videoWidth,_=this.opts.videoHeight,y=this.opts.bottomOffset,v=_-m-y,T=(x-g)/2;this.update({width:g,height:m,top:v,left:T})}lastLoggedTime=-1;updateState(e){const t=e/1e3,s=Math.floor(e/1e6);s!==this.lastLoggedTime&&(this.lastLoggedTime=s),this.opts.words.forEach((r,n)=>{const o=t>=r.from&&t<r.to,a=t>=r.to,l=r.isKeyWord&&!S_(this.opts.keyword);let c=16777215,h=1;r.isKeyWord&&o&&l?{color:c,alpha:h}=xi(this.opts.keyword):o?{color:c,alpha:h}=xi(this.opts.active):a&&this.opts.preserveKeywordColor&&l?{color:c,alpha:h}=xi(this.opts.keyword):a?{color:c,alpha:h}=xi(this.opts.appeared):{color:c,alpha:h}=xi(this.opts.fill);const u=this.wordTexts[n];if(!u){console.warn(`¡WARNING: SplitBitmapText was not found for word "${r.text}"!`);return}u.children.forEach(f=>{f.label!=="bgRect"&&(f.tint=c,f.alpha=h)});const d=u.getChildByLabel("bgRect");if(o){const{color:f,alpha:p}=xi(this.opts.activeFill,16753920),g=10;d&&(d.visible=!1);const m=u.getLocalBounds();d&&(d.visible=!0);const x=16,_=d??new xe;_.label="bgRect",_.clear(),_.roundRect(m.x-g/2,m.y-g/2+this.extraPadding,m.width+g,m.height+g,x),_.fill({color:f,alpha:p}),_.tint=16777215,d||u.addChildAt(_,0)}else d&&(u.removeChild(d),d.destroy())})}async getTexture(){if(this.pixiTextContainer==null||this.renderTexture==null)return console.log("[CaptionClip] getTexture returning null - container or texture not ready"),null;try{return(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture}catch(e){return console.error("[CaptionClip] Error in getTexture:",e),null}}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("CaptionClip: No renderer available. Provide a renderer via setRenderer().");return this.pixiApp.renderer}async tick(e){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("CaptionClip not initialized");this.updateState(e);const t=await this.getRenderer();t.render({container:this.pixiTextContainer,target:this.renderTexture});const s=this.renderTexture.source?.resource?.source;let r;if(s instanceof HTMLCanvasElement)r=await createImageBitmap(s);else if(s instanceof OffscreenCanvas)r=await createImageBitmap(s);else{const o=t.extract.canvas(this.renderTexture);if(o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas)r=await createImageBitmap(o);else throw new Error("Unable to extract canvas from render texture")}return{video:r,state:"success"}}async split(e){await this.ready;const t=await this.clone(),s=await this.clone();return[t,s]}addEffect(e){this.effects.push(e)}editEffect(e,t){const s=this.effects.find(r=>r.id===e);s&&Object.assign(s,t)}removeEffect(e){const t=this.effects.findIndex(s=>s.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.originalOpts||{},t=new ei(this.text,e);return this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t}destroy(){if(!this.destroyed){q.info("Caption destroy");try{this.wordTexts.forEach(e=>{e!=null&&!e.destroyed&&e.destroy({children:!0})})}catch{}finally{this.wordTexts=[]}try{this.pixiTextContainer!=null&&this.pixiTextContainer.destroyed!==!0&&this.pixiTextContainer.destroy({children:!0})}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),s={};if(this.originalOpts){const u=this.originalOpts;u.fontSize!==void 0&&(s.fontSize=u.fontSize),u.fontFamily!==void 0&&(s.fontFamily=u.fontFamily),u.fontWeight!==void 0&&(s.fontWeight=u.fontWeight),u.fontStyle!==void 0&&(s.fontStyle=u.fontStyle),u.fill!==void 0&&(s.color=u.fill),u.align!==void 0&&(s.align=u.align),u.textCase!==void 0&&(s.textCase=u.textCase),u.fontUrl!==void 0&&(s.fontUrl=u.fontUrl),u.stroke&&(typeof u.stroke=="object"?s.stroke={color:u.stroke.color,width:u.stroke.width}:s.stroke={color:u.stroke,width:u.strokeWidth??0}),u.dropShadow&&(s.shadow={color:u.dropShadow.color??"#000000",alpha:u.dropShadow.alpha??.5,blur:u.dropShadow.blur??4,distance:u.dropShadow.distance??0,angle:u.dropShadow.angle??0})}const r={};this.opts.words&&this.opts.words.length>0&&(r.words=this.opts.words);const n={},o=this.originalOpts?.caption?.colors??this.originalOpts?.colors;o?.appeared!==void 0&&(n.appeared=o.appeared),o?.active!==void 0&&(n.active=o.active),o?.activeFill!==void 0&&(n.activeFill=o.activeFill),o?.background!==void 0&&(n.background=o.background),o?.keyword!==void 0&&(n.keyword=o.keyword);let a;this.originalOpts?.caption?.preserveKeywordColor!==void 0?a=this.originalOpts.caption.preserveKeywordColor:this.originalOpts?.preserveKeywordColor!==void 0&&(a=this.originalOpts.preserveKeywordColor),Object.keys(n).length>0&&(r.colors=n),a!==void 0&&(r.preserveKeywordColor=a);const l={};this.bottomOffset!==void 0&&(l.bottomOffset=this.bottomOffset);const c=this.originalOpts?.caption?.positioning?.videoWidth??this.originalOpts?.videoWidth,h=this.originalOpts?.caption?.positioning?.videoHeight??this.originalOpts?.videoHeight;return c!==void 0&&(l.videoWidth=c),h!==void 0&&(l.videoHeight=h),Object.keys(l).length>0&&(r.positioning=l),{...t,type:"Caption",text:this.text,style:s,caption:Object.keys(r).length>0?r:void 0,id:this.id,effects:this.effects,mediaId:this.mediaId}}static async fromObject(e){if(e.type!=="Caption")throw new Error(`Expected Caption, got ${e.type}`);const t=e.text||"",s=e.style||{},r={};s.fontSize!==void 0&&(r.fontSize=s.fontSize),s.fontFamily!==void 0&&(r.fontFamily=s.fontFamily),s.fontWeight!==void 0&&(r.fontWeight=s.fontWeight),s.fontStyle!==void 0&&(r.fontStyle=s.fontStyle),s.color!==void 0&&(r.fill=s.color),s.align!==void 0&&(r.align=s.align),s.textCase!==void 0&&(r.textCase=s.textCase),s.fontUrl!==void 0?r.fontUrl=s.fontUrl:e.fontUrl!==void 0&&(r.fontUrl=e.fontUrl),e.mediaId&&(r.mediaId=e.mediaId),s.stroke&&(r.stroke=s.stroke.color,r.strokeWidth=s.stroke.width),s.shadow&&(r.dropShadow={color:s.shadow.color,alpha:s.shadow.alpha,blur:s.shadow.blur,distance:s.shadow.distance,angle:s.shadow.angle}),e.caption?r.caption=e.caption:(e.bottomOffset!==void 0&&(r.bottomOffset=e.bottomOffset),e.words!==void 0&&(r.words=e.words),(e.appearedColor!==void 0||e.activeColor!==void 0||e.activeFillColor!==void 0||e.backgroundColor!==void 0||e.isKeyWordColor!==void 0)&&(r.colors={},e.appearedColor!==void 0&&(r.colors.appeared=e.appearedColor),e.activeColor!==void 0&&(r.colors.active=e.activeColor),e.activeFillColor!==void 0&&(r.colors.activeFill=e.activeFillColor),e.backgroundColor!==void 0&&(r.colors.background=e.backgroundColor),e.isKeyWordColor!==void 0&&(r.colors.keyword=e.isKeyWordColor)),e.preservedColorKeyWord!==void 0&&(r.preserveKeywordColor=e.preservedColorKeyWord),e.videoWidth!==void 0&&(r.videoWidth=e.videoWidth),e.videoHeight!==void 0&&(r.videoHeight=e.videoHeight));const n=new ei(t,r);return n.left=e.left,n.top=e.top,n.width=e.width,n.height=e.height,n.angle=e.angle,n.display.from=e.display.from,n.display.to=e.display.to,n.duration=e.duration,n.playbackRate=e.playbackRate,n.zIndex=e.zIndex,n.opacity=e.opacity,n.flip=e.flip,e.animation&&n.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(n.id=e.id),e.effects&&(n.effects=e.effects),await n.ready,n}}let _i=class si extends qt{type="Image";ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t){let s=null,r=null;if(e.startsWith("blob:"))try{const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch image: ${o.status} ${o.statusText}`);const a=await o.blob();r=await createImageBitmap(a);try{s=M.from(r)}catch(l){q.warn("Failed to create Pixi texture from bitmap:",l)}}catch(o){throw q.error(`Failed to load blob image from ${e}`,o),o}else{try{if(s=await Ls.load(e),s){const o=s.source?.resource?.source;if(o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas)r=await createImageBitmap(o);else if(o instanceof HTMLImageElement){const a=new OffscreenCanvas(o.width,o.height),l=a.getContext("2d");if(l==null)throw new Error("Failed to create 2d context");l.drawImage(o,0,0),r=await createImageBitmap(a)}else o instanceof ImageBitmap&&(r=await createImageBitmap(o))}}catch(o){q.warn(`Failed to load texture via Assets.load for ${e}, using fallback`,o)}if(!r)try{const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch image: ${o.status} ${o.statusText}`);const a=await o.blob();r=await createImageBitmap(a)}catch(o){throw q.error(`Failed to load image from ${e}`,o),o}}const n=new si(r,t||e);return s&&(n.pixiTexture=s),n}getTexture(){return this.pixiTexture}constructor(e,t){super(),this.src=t!==void 0?t:"";const s=r=>{this.img=r,this._meta.width=r.width,this._meta.height=r.height,this._meta.duration=1/0;const n={...this._meta};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),n};if(e instanceof ReadableStream)this.ready=new Response(e).blob().then(r=>createImageBitmap(r)).then(s);else if(e instanceof ImageBitmap)this.ready=Promise.resolve(s(e));else if(Array.isArray(e)&&e.every(r=>r instanceof VideoFrame)){this.frames=e;const r=this.frames[0];if(r==null)throw Error("The frame count must be greater than 0");this._meta={width:r.displayWidth,height:r.displayHeight,duration:this.frames.reduce((o,a)=>o+(a.duration??0),0)};const n={...this._meta,duration:1/0};this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(n)}else if("type"in e)this.ready=this.initAnimateImg(e.stream,e.type).then(()=>{const r={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?r.width:this.width,this.height=this.height===0?r.height:this.height,this.duration===0&&r.duration!==1/0&&(this.duration=r.duration,this.display.to=this.display.from+this.duration),r});else throw Error("Illegal arguments")}async initAnimateImg(e,t){this.frames=await k1(e,t);const s=this.frames[0];if(s==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((r,n)=>r+(n.duration??0),0),width:s.codedWidth,height:s.codedHeight},q.info("Image ready:",this._meta)}tickInterceptor=async(e,t)=>t;async tick(e){if(this.img!=null)return await this.tickInterceptor(e,{video:await createImageBitmap(this.img),state:"success"});const t=e%this._meta.duration;return await this.tickInterceptor(e,{video:(this.frames.find(s=>t>=s.timestamp&&t<=s.timestamp+(s.duration??0))??this.frames[0]).clone(),state:"success"})}async split(e){if(await this.ready,this.img!=null)return[new si(await createImageBitmap(this.img),this.src),new si(await createImageBitmap(this.img),this.src)];let t=-1;for(let n=0;n<this.frames.length;n++){const o=this.frames[n];if(!(e>o.timestamp)){t=n;break}}if(t===-1)throw Error("Not found frame by time");const s=this.frames.slice(0,t).map(n=>new VideoFrame(n)),r=this.frames.slice(t).map(n=>new VideoFrame(n,{timestamp:n.timestamp-e}));return[new si(s,this.src),new si(r,this.src)]}async clone(){await this.ready;const e=this.img==null?this.frames.map(s=>s.clone()):await createImageBitmap(this.img),t=new si(e,this.src);return t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t.id=this.id,t.effects=[...this.effects],t.transition=this.transition,t}addEffect(e){this.effects.push(e)}editEffect(e,t){const s=this.effects.find(r=>r.id===e);s&&Object.assign(s,t)}removeEffect(e){const t=this.effects.findIndex(s=>s.id===e);t!==-1&&this.effects.splice(t,1)}destroy(){q.info("Image destroy"),this.img?.close(),this.frames.forEach(e=>e.close()),this.pixiTexture=null,super.destroy()}toJSON(e=!1){return{...super.toJSON(e),type:"Image",id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Image")throw new Error(`Expected Image, got ${e.type}`);if(!e.src||e.src.trim()==="")throw new Error("Image requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let t;try{const s=await fetch(e.src);if(!s.ok)throw new Error(`Failed to fetch image from ${e.src}: ${s.status} ${s.statusText}. Make sure the file exists in the public directory.`);const r=await s.blob();r.type.startsWith("image/")||q.warn(`Image blob has unexpected type: ${r.type}. Attempting to load anyway.`),t=new si(await createImageBitmap(r),e.src)}catch(s){throw s instanceof Error&&s.message.includes("could not be decoded")?new Error(`Failed to decode image from ${e.src}. The image may be corrupted, in an unsupported format, or there may be CORS issues.`):s}return await t.ready,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.style&&(t.style={...t.style,...e.style}),e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),e.effects&&(t.effects=e.effects),e.transition&&(t.transition=e.transition),t}};function jd(i,e){const t={},s=e.videoTracks[0];if(s!=null){const n=dR(i.getTrackById(s.id))?.buffer,o=uR(s.codec);o&&(t.videoTrackConf={timescale:s.timescale,duration:s.duration,width:s.video.width,height:s.video.height,brands:e.brands,type:o.type,[o.descKey]:n}),t.videoDecoderConf={codec:s.codec,codedHeight:s.video.height,codedWidth:s.video.width,description:n}}const r=e.audioTracks[0];if(r!=null){const n=fR(i),o=n?pR(n):{};t.audioTrackConf={timescale:r.timescale,samplerate:o.sampleRate??r.audio.sample_rate,channel_count:o.numberOfChannels??r.audio.channel_count,hdlr:"soun",type:r.codec.startsWith("mp4a")?"mp4a":r.codec,description:n},t.audioDecoderConf={codec:o.codec??le.codec,numberOfChannels:o.numberOfChannels??r.audio.channel_count,sampleRate:o.sampleRate??r.audio.sample_rate}}return t}function uR(i){return i.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:i.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:null}function dR(i){for(const e of i.mdia.minf.stbl.stsd.entries){const t=e.avcC??e.hvcC??e.av1C??e.vpcC;if(t!=null){const s=new oi.DataStream(void 0,0,void 0);return t.write(s),new Uint8Array(s.buffer.slice(8))}}}function fR(i,e="mp4a"){return i.moov?.traks.flatMap(t=>t.mdia.minf.stbl.stsd.entries).find(t=>t.type===e)}function pR(i){const e=i.esd?.descs?.[0];if(!e)return{};let t=`mp4a.${e.oti.toString(16)}`;const s=e.descs?.[0];if(!s)return t.endsWith(".40")&&(t+=".2"),{codec:t};const r=s.data;if(!r)return{codec:t};const n=(r[0]&248)>>3;t+=`.${n}`;const o=(r[0]&7)<<1|r[1]>>7,a=(r[1]&120)>>3;return{codec:t,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][o],numberOfChannels:a}}async function mR(i,e,t){const s=oi.createFile(!1);s.onReady=o=>{e({mp4boxFile:s,info:o}),[o.videoTracks[0],o.audioTracks[0]].forEach(a=>{if(a){const l=a.video?"video":"audio";s.setExtractionOptions(a.id,l,{nbSamples:100})}}),s.start()},s.onSamples=t;let r=0;const n=30*1024*1024;for(;;){const o=await i.read(n,{at:r});if(o.byteLength===0)break;o.fileStart=r;const a=s.appendBuffer(o);if(a==null)break;r=a}s.stop()}function gR(i){if(i?.length!==9)return{};const e=new Int32Array(i.buffer),t=h=>h/65536,s=t(e[0]),r=t(e[1]),n=t(e[3]),o=t(e[4]),a=t(e[6]),l=t(e[7]),c=e[8]/(1<<30);return{scaleX:Math.sqrt(s*s+n*n),scaleY:Math.sqrt(r*r+o*o),rotationRad:Math.atan2(n,s),rotationDeg:Math.atan2(n,s)*180/Math.PI,translateX:a,translateY:l,perspective:c}}function xR(i,e,t){const s=(Math.round(t/90)*90+360)%360;if(s===0)return c=>c;const r=s===90||s===270,n=r?e:i,o=r?i:e,a=new OffscreenCanvas(n,o),l=a.getContext("2d");return l.translate(n/2,o/2),l.rotate(-s*Math.PI/180),l.translate(-i/2,-e/2),c=>{if(!c)return null;l.drawImage(c,0,0);const h=new VideoFrame(a,{timestamp:c.timestamp,duration:c.duration??void 0});return c.close(),h}}class C_{static async getCacheKey(e){const s=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-1",s);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("")}static getPath(e){return`assets/${e}`}static async get(e){const t=await this.getCacheKey(e),s=this.getPath(t),r=ai(s);return await r.exists()?r:null}static async put(e,t){const s=await this.getCacheKey(e),r=this.getPath(s),n=ai(r);return await Ei(n,t),n}}let Zd=0;function Jd(i){return i.kind==="file"&&i.createReader instanceof Function}class Me extends qt{type="Video";insId=Zd++;logger=q.create(`Video id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const e=await this.localFile.getOriginFile();if(e==null)throw Error("Video localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:t,size:s})=>e.slice(t,t+s))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=e=>e;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];static async fromUrl(e,t={}){const s=await C_.get(e);if(s){const u=new Me(s,{},e);return await u.ready,t.x!==void 0&&(u.left=t.x),t.y!==void 0&&(u.top=t.y),t.width!==void 0&&(u.width=t.width),t.height!==void 0&&(u.height=t.height),u}const r=await fetch(e);if(!r.ok)throw new Error(`Failed to fetch video from ${e}: ${r.status} ${r.statusText}`);const n=r.body,[o,a]=n.tee(),l=(async()=>{const u=new Me(o,{},e);return await u.ready,u})(),c=C_.put(e,a),[h]=await Promise.all([l,c]);return t.x!==void 0&&(h.left=t.x),t.y!==void 0&&(h.top=t.y),t.width!==void 0&&(h.width=t.width),t.height!==void 0&&(h.height=t.height),h}constructor(e,t={},s){if(super(),this.src=s!==void 0?s:"",!(e instanceof ReadableStream)&&!Jd(e)&&!Array.isArray(e.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...t},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof t.audio=="object"&&"volume"in t.audio?t.audio.volume:t.volume??1;const r=async n=>(await Ei(this.localFile,n),this.localFile);this.localFile=Jd(e)?e:"localFile"in e?e.localFile:Xh(),this.ready=(e instanceof ReadableStream?r(e).then(n=>A_(n,this.opts)):Jd(e)?A_(e,this.opts):Promise.resolve(e)).then(async({videoSamples:n,audioSamples:o,decoderConf:a,headerBoxPos:l,parsedMatrix:c})=>{this.videoSamples=n,this.audioSamples=o,this.decoderConf=a,this.headerBoxPos=l,this.parsedMatrix=c;const{videoFrameFinder:h,audioFrameFinder:u}=yR({video:a.video==null?null:{...a.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:a.audio},await this.localFile.createReader(),n,o,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=h,this.audioFrameFinder=u;const{codedWidth:d,codedHeight:f}=a.video??{};d&&f&&(this.vfRotater=xR(d,f,c.rotationDeg)),this._meta=_R(a,n,o,c.rotationDeg),this.logger.info("Video meta:",this._meta);const p={...this._meta};this.width=this.width===0?p.width:this.width,this.height=this.height===0?p.height:this.height,this.trim.to=this.trim.to===0?p.duration:Math.min(this.trim.to,p.duration),this.trim.from=Math.min(this.trim.from,this.trim.to);const g=(this.trim.to-this.trim.from)/this.playbackRate;return this.duration=this.duration===0?g:this.duration,Math.abs(this.duration-g)>1&&(this.duration=g),this.display.to=this.display.from+this.duration,this.on("propsChange",m=>{m.volume!==void 0&&this.audioFrameFinder&&this.audioFrameFinder.setVolume(m.volume)}),p})}tickInterceptor=async(e,t)=>t;async tick(e){const t=e+this.trim.from;if(t>=this.trim.to||t>=this._meta.duration)return await this.tickInterceptor(e,{audio:await this.audioFrameFinder?.find(t)??[],state:"done"});const[s,r]=await Promise.all([this.audioFrameFinder?.find(t)??[],this.videoFrameFinder?.find(t).then(this.vfRotater)]);return r==null?await this.tickInterceptor(e,{audio:s,state:"success"}):await this.tickInterceptor(e,{video:r,audio:s,state:"success"})}thumbAborter=new AbortController;thumbFinder=null;async thumbnails(e=100,t){this.thumbAborter.abort(),this.thumbAborter=new AbortController;const s=this.thumbAborter.signal;await this.ready;const r="generate thumbnails aborted";if(s.aborted)throw Error(r);const{width:n,height:o}=this._meta,a=IR(e,Math.round(o*(e/n)),{quality:.1,type:"image/png"});return new Promise(async(l,c)=>{let h=[];const u=this.decoderConf.video;if(u==null||this.videoSamples.length===0){d();return}s.addEventListener("abort",()=>{c(Error(r))});async function d(){s.aborted||l(await Promise.all(h.map(async x=>({ts:x.ts,img:await x.img}))))}function f(x){h.push({ts:x.timestamp,img:a(x)})}const{start:p=0,end:g=this._meta.duration,step:m}=t??{};if(m){let x=p;for(this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null),this.thumbFinder=new I_(await this.localFile.createReader(),this.videoSamples,{...u,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__});x<=g&&!s.aborted;){const _=await this.thumbFinder.find(x);_&&f(_),x+=m}await this.thumbFinder.destroy(),this.thumbFinder=null,d()}else await ER(this.videoSamples,this.localFile,u,s,{start:p,end:g},(x,_)=>{x!=null&&f(x),_&&d()})})}async split(e){if(await this.ready,e<=0||e>=this._meta.duration)throw Error("time out of bounds");const[t,s]=SR(this.videoSamples,e),[r,n]=CR(this.audioSamples,e),o=new Me({localFile:this.localFile,videoSamples:t??[],audioSamples:r??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),a=new Me({localFile:this.localFile,videoSamples:s??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await Promise.all([o.ready,a.ready]),[o,a]}addEffect(e){this.effects.push(e)}editEffect(e,t){const s=this.effects.find(r=>r.id===e);s&&Object.assign(s,t)}removeEffect(e){const t=this.effects.findIndex(s=>s.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=new Me({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await e.ready,e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e.id=this.id,e.effects=[...this.effects],e}async splitTrack(){await this.ready;const e=[];if(this.videoSamples.length>0){const t=new Me({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[],decoderConf:{video:this.decoderConf.video,audio:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}if(this.audioSamples.length>0){const t=new Me({localFile:this.localFile,videoSamples:[],audioSamples:[...this.audioSamples],decoderConf:{audio:this.decoderConf.audio,video:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await t.ready,t.tickInterceptor=this.tickInterceptor,e.push(t)}return e}cleanupThumbnails=async()=>{this.thumbAborter.abort(),this.thumbFinder&&(await this.thumbFinder.destroy(),this.thumbFinder=null)};destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("Video destroy"),super.destroy(),this.thumbAborter.abort(),this.thumbFinder?.destroy(),this.thumbFinder=null,this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(e=!1){return{...super.toJSON(e),type:"Video",audio:this.audio,volume:this.volume,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Video")throw new Error(`Expected Video, got ${e.type}`);const t=await fetch(e.src);if(!t.ok)throw new Error(`Failed to fetch video from ${e.src}: ${t.status} ${t.statusText}. Make sure the file exists in the public directory.`);const s=e.audio!==void 0?{audio:e.audio,volume:e.volume}:{volume:e.volume},r=new Me(t.body,s,e.src);return await r.ready,r.left=e.left,r.top=e.top,r.width=e.width,r.height=e.height,r.angle=e.angle,r.display.from=e.display.from,r.display.to=e.display.to,r.duration=e.duration,r.playbackRate=e.playbackRate,r.zIndex=e.zIndex,r.opacity=e.opacity,r.flip=e.flip,e.style&&(r.style={...r.style,...e.style}),e.animation&&r.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(r.id=e.id),e.effects&&(r.effects=e.effects),e.transition&&(r.transition=e.transition),e.trim&&(r.trim.from=e.trim.from<1e6?e.trim.from*1e6:e.trim.from,r.trim.to=e.trim.to<1e6?e.trim.to*1e6:e.trim.to),e.volume!==void 0&&(r.volume=e.volume),r}async createPlaybackElement(){await this.ready;const t=this.localFile;if(!t||typeof t.getOriginFile!="function")throw new Error("Video does not have a local file for playback");const s=await t.getOriginFile();if(!s)throw new Error("Failed to get origin file from VideoClip");const r=URL.createObjectURL(s),n=document.createElement("video");return n.crossOrigin="anonymous",n.muted=!0,n.autoplay=!1,n.playsInline=!0,n.preload="auto",n.loop=!1,n.src=r,await new Promise((o,a)=>{const l=()=>{n.removeEventListener("loadeddata",l),n.removeEventListener("error",c),n.pause(),n.currentTime=0,o()},c=()=>{n.removeEventListener("loadeddata",l),n.removeEventListener("error",c),a(new Error("Failed to load video"))};n.addEventListener("loadeddata",l,{once:!0}),n.addEventListener("error",c,{once:!0}),n.load()}),{element:n,objectUrl:r}}async play(e,t){const s=e,r=t+this.trim.from/1e6;if(Math.abs(s.currentTime-r)>.1&&(s.currentTime=r),s.muted=!1,s.paused)try{await s.play()}catch{try{await s.play()}catch(o){console.warn("Failed to play video:",o)}}}pause(e){const t=e;t.pause(),t.muted=!0}async seek(e,t){const s=e,r=t+this.trim.from/1e6;return s.pause(),s.currentTime=r,new Promise(n=>{if(Math.abs(s.currentTime-t)<.01){n();return}const o=()=>{s.removeEventListener("seeked",o),n()};s.addEventListener("seeked",o,{once:!0}),setTimeout(()=>{s.removeEventListener("seeked",o),n()},500)})}syncPlayback(e,t,s){const r=e,n=(this.trim.to-this.trim.from)/1e6,o=s>=0&&s<n,a=s+this.trim.from/1e6;r.volume=this.volume,t&&o?r.paused?this.play(r,s).catch(console.warn):(r.muted&&(r.muted=!1),(r.ended||r.currentTime>=this.trim.to/1e6)&&(r.currentTime=a,r.play().catch(console.warn))):(r.paused||r.pause(),r.muted=!0,o&&Math.abs(r.currentTime-a)>.1&&(r.currentTime=a))}cleanupPlayback(e,t){const s=e;s.pause(),s.removeAttribute("src"),s.load(),t&&URL.revokeObjectURL(t)}async scaleToFit(e,t){await this.ready;const{width:s,height:r}=this.meta;if(s===0||r===0)return;const n=Math.min(e/s,t/r);this.width=s*n,this.height=r*n}async scaleToFill(e,t){await this.ready;const{width:s,height:r}=this.meta;if(s===0||r===0)return;const n=Math.max(e/s,t/r);this.width=s*n,this.height=r*n}centerInScene(e,t){this.left=(e-this.width)/2,this.top=(t-this.height)/2}}function _R(i,e,t,s){const r={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(i.video!=null&&e.length>0){r.width=i.video.codedWidth??0,r.height=i.video.codedHeight??0;const a=(Math.round(s/90)*90+360)%360;(a===90||a===270)&&([r.width,r.height]=[r.height,r.width])}i.audio!=null&&t.length>0&&(r.audioSampleRate=le.sampleRate,r.audioChanCount=le.channelCount);let n=0,o=0;if(e.length>0)for(let a=e.length-1;a>=0;a--){const l=e[a];if(!l.deleted){n=l.cts+l.duration;break}}if(t.length>0){const a=t.at(-1);o=a.cts+a.duration}return r.duration=Math.max(n,o),r}function yR(i,e,t,s,r){return{audioFrameFinder:r===0||i.audio==null||s.length===0?null:new bR(e,s,i.audio,{volume:r,targetSampleRate:le.sampleRate}),videoFrameFinder:i.video==null||t.length===0?null:new I_(e,t,i.video)}}async function A_(i,e={}){let t=null;const s={video:null,audio:null};let r=[],n=[],o=[];const a={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let l=-1,c=-1;const h=await i.createReader();await mR(h,async d=>{t=d.info;const f=d.mp4boxFile.ftyp;o.push({start:f.start,size:f.size});const p=d.mp4boxFile.moov;o.push({start:p.start,size:p.size}),Object.assign(a,gR(t.videoTracks[0]?.matrix));let{videoDecoderConf:g,audioDecoderConf:m}=jd(d.mp4boxFile,d.info);if(s.video=g??null,s.audio=m??null,g==null&&m==null&&q.error("Video no video and audio track"),m!=null){const{supported:x}=await AudioDecoder.isConfigSupported(m);x||q.error(`Video audio codec is not supported: ${m.codec}`)}if(g!=null){const{supported:x}=await VideoDecoder.isConfigSupported(g);x||q.error(`Video video codec is not supported: ${g.codec}`)}q.info("mp4BoxFile moov ready",{...d.info,tracks:null,videoTracks:null,audioTracks:null},s)},(d,f,p)=>{if(f==="video"){l===-1&&(l=p[0].dts);for(const g of p)r.push(E_(g,l,"video"))}else if(f==="audio"&&e.audio){c===-1&&(c=p[0].dts);for(const g of p)n.push(E_(g,c,"audio"))}}),await h.close();const u=r.at(-1)??n.at(-1);if(t==null)throw Error("Video stream is done, but not emit ready");if(u==null)throw Error("Video stream not contain any sample");return ef(r),q.info("mp4 stream parsed"),{videoSamples:r,audioSamples:n,decoderConf:s,headerBoxPos:o,parsedMatrix:a}}function E_(i,e=0,t){let s=i.offset;const r=t==="video"&&i.is_sync?AR(i.data,i.description.type):-1;let n=i.size;return r>0&&(s+=r,n-=r),{...i,is_idr:r>=0,offset:s,size:n,cts:(i.cts-e)/i.timescale*1e6,dts:(i.dts-e)/i.timescale*1e6,duration:i.duration/i.timescale*1e6,timescale:1e6,data:t==="video"?null:i.data}}class I_{constructor(e,t,s){this.localFileReader=e,this.samples=t,this.conf=s}decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async e=>{(this.decoder==null||this.decoder.state==="closed"||e<=this.timestamp||e-this.timestamp>3e6)&&this.reset(e),this.curAborter.abort=!0,this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const t=await this.parseFrame(e,this.decoder,this.curAborter);return this.sleepCnt=0,t};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;parseFrame=async(e,t,s)=>{if(t==null||t.state==="closed"||s.abort)return null;if(this.videoFrames.length>0){const r=this.videoFrames[0];return e<r.timestamp?null:(this.videoFrames.shift(),e>r.timestamp+(r.duration??0)?(r.close(),await this.parseFrame(e,t,s)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(t).catch(n=>{throw this.predecodeErr=!0,this.reset(e),n}),r))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&t.decodeQueueSize>0){if(performance.now()-s.st>6e3)throw Error(`Video.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await jh(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(t)}catch(r){throw this.reset(e),r}}return await this.parseFrame(e,t,s)};decoding=!1;startDecode=async e=>{if(this.decoding||e.decodeQueueSize>600)return;let t=this.videoDecCursorIdx+1;if(t>this.samples.length)return;this.decoding=!0;let s=!1;for(;t<this.samples.length;t++){const r=this.samples[t];if(!s&&!r.deleted&&(s=!0),r.is_idr)break}if(s){const r=this.samples.slice(this.videoDecCursorIdx,t);if(r[0]?.is_idr!==!0)q.warn("First sample not idr frame");else{const n=performance.now(),o=await R_(r,this.localFileReader),a=performance.now()-n;if(a>1e3){const l=r[0],c=r.at(-1),h=c.offset+c.size-l.offset;q.warn(`Read video samples time cost: ${Math.round(a)}ms, file chunk size: ${h}`)}if(e.state==="closed")return;this.lastVfDur=o[0]?.duration??0,Qd(e,o,{onDecodingError:l=>{if(this.downgradeSoftDecode)throw l;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,q.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=o.length}}this.videoDecCursorIdx=t,this.decoding=!1};reset=e=>{if(this.decoding=!1,this.videoFrames.forEach(s=>s.close()),this.videoFrames=[],e==null||e===0)this.videoDecCursorIdx=0;else{let s=0;for(let r=0;r<this.samples.length;r++){const n=this.samples[r];if(n.is_idr&&(s=r),!(n.cts<e)){this.videoDecCursorIdx=s;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const t={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:s=>{if(this.outputFrameCnt+=1,s.timestamp===-1){s.close();return}let r=s;s.duration==null&&(r=new VideoFrame(s,{duration:this.lastVfDur}),s.close()),this.videoFrames.push(r)},error:s=>{if(s.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,q.warn(s.message);return}const r=`VideoFinder VideoDecoder err: ${s.message}, config: ${JSON.stringify(t)}, state: ${JSON.stringify(this.getState())}`;throw q.error(r),Error(r)}}),this.decoder.configure(t)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:Zd,sleepCnt:this.sleepCnt,memInfo:M_()});destroy=async()=>{if(this.curAborter.abort=!0,this.videoFrames.forEach(e=>e.close()),this.videoFrames=[],this.decoder&&this.decoder.state!=="closed"){try{await this.decoder.flush()}catch{}try{this.decoder.close()}catch{}}this.decoder=null,this.localFileReader.close()}}function vR(i,e){for(let t=0;t<e.length;t++){const s=e[t];if(i>=s.cts&&i<s.cts+s.duration)return t;if(s.cts>i)break}return 0}class bR{constructor(e,t,s,r){this.localFileReader=e,this.samples=t,this.conf=s,this.volume=r.volume,this.sampleRate=r.targetSampleRate}volume=1;sampleRate;setVolume(e){this.volume=e,this.reset()}decoder=null;curAborter={abort:!1,st:performance.now()};find=async e=>{const t=e<=this.timestamp||e-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||t)&&this.reset(),t&&(this.timestamp=e,this.decCursorIdx=vR(e,this.samples)),this.curAborter.abort=!0;const s=e-this.timestamp;this.timestamp=e,this.curAborter={abort:!1,st:performance.now()};const r=await this.parseFrame(Math.ceil(s*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,r};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(e,t=null,s)=>{if(t==null||s.abort||t.state==="closed"||e===0)return[];const r=this.pcmData.frameCnt-e;if(r>0)return r<le.sampleRate/10&&this.startDecode(t),P_(this.pcmData,e);if(t.decoding){if(performance.now()-s.st>3e3)throw s.abort=!0,Error(`Video.tick audio timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await jh(15)}else{if(this.decCursorIdx>=this.samples.length-1)return P_(this.pcmData,this.pcmData.frameCnt);this.startDecode(t)}return this.parseFrame(e,t,s)};startDecode=e=>{if(e.decodeQueueSize>10)return;const s=[];let r=this.decCursorIdx;for(;r<this.samples.length;){const n=this.samples[r];if(r+=1,!n.deleted&&(s.push(n),s.length>=10))break}this.decCursorIdx=r,e.decode(s.map(n=>new EncodedAudioChunk({type:"key",timestamp:n.cts,duration:n.duration,data:n.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=TR(this.conf,{resampleRate:le.sampleRate,volume:this.volume},e=>{this.pcmData.data.push(e),this.pcmData.frameCnt+=e[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:Zd,sleepCnt:this.sleepCnt,memInfo:M_()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function TR(i,e,t){let s=0,r=0;const n=h=>{if(r+=1,h.length!==0){if(e.volume!==1)for(const u of h)for(let d=0;d<u.length;d++)u[d]*=e.volume;h.length===1&&(h=[h[0],h[0]]),t(h)}},o=wR(n),a=e.resampleRate!==i.sampleRate;let l=new AudioDecoder({output:h=>{const u=Rp(h);a?o(()=>c1(u,h.sampleRate,{rate:e.resampleRate,chanCount:h.numberOfChannels})):n(u),h.close()},error:h=>{h.message.includes("Codec reclaimed due to inactivity")||c("Video AudioDecoder err",h)}});l.configure(i);function c(h,u){const d=`${h}: ${u.message}, state: ${JSON.stringify({qSize:l.decodeQueueSize,state:l.state,inputCnt:s,outputCnt:r})}`;throw q.error(d),Error(d)}return{decode(h){s+=h.length;try{for(const u of h)l.decode(u)}catch(u){c("decode audio chunk error",u)}},close(){l.state!=="closed"&&l.close()},get decoding(){return s>r&&l.decodeQueueSize>0},get state(){return l.state},get decodeQueueSize(){return l.decodeQueueSize}}}function wR(i){const e=[];let t=0;function s(o,a){e[a]=o,r()}function r(){const o=e[t];o!=null&&(i(o),t+=1,r())}let n=0;return o=>{const a=n;n+=1,o().then(l=>s(l,a)).catch(l=>s(l,a))}}function P_(i,e){const t=[new Float32Array(e),new Float32Array(e)];let s=0,r=0;for(;r<i.data.length;){const[n,o]=i.data[r];if(s+n.length>e){const a=e-s;t[0].set(n.subarray(0,a),s),t[1].set(o.subarray(0,a),s),i.data[r][0]=n.subarray(a,n.length),i.data[r][1]=o.subarray(a,o.length);break}else t[0].set(n,s),t[1].set(o,s),s+=n.length,r++}return i.data=i.data.slice(r),i.frameCnt-=e,t}async function R_(i,e){const t=i[0],s=i.at(-1);if(s==null)return[];const r=s.offset+s.size-t.offset;if(r<3e7){const n=new Uint8Array(await e.read(r,{at:t.offset}));return i.map(o=>{const a=o.offset-t.offset;return new EncodedVideoChunk({type:o.is_sync?"key":"delta",timestamp:o.cts,duration:o.duration,data:n.subarray(a,a+o.size)})})}return await Promise.all(i.map(async n=>new EncodedVideoChunk({type:n.is_sync?"key":"delta",timestamp:n.cts,duration:n.duration,data:await e.read(n.size,{at:n.offset})})))}function SR(i,e){if(i.length===0)return[];let t=0,s=0,r=-1;for(let l=0;l<i.length;l++){const c=i[l];if(r===-1&&e<c.cts&&(r=l-1),c.is_idr)if(r===-1)t=l;else{s=l;break}}const n=i[r];if(n==null)throw Error("Not found video sample by time");const o=i.slice(0,s===0?i.length:s).map(l=>({...l}));for(let l=t;l<o.length;l++){const c=o[l];e<c.cts&&(c.deleted=!0,c.cts=-1)}ef(o);const a=i.slice(n.is_idr?r:t).map(l=>({...l,cts:l.cts-e}));for(const l of a)l.cts<0&&(l.deleted=!0,l.cts=-1);return ef(a),[o,a]}function CR(i,e){if(i.length===0)return[];let t=-1;for(let n=0;n<i.length;n++){const o=i[n];if(!(e>o.cts)){t=n;break}}if(t===-1)throw Error("Not found audio sample by time");const s=i.slice(0,t).map(n=>({...n})),r=i.slice(t).map(n=>({...n,cts:n.cts-e}));return[s,r]}function Qd(i,e,t){if(i.state==="configured"){for(let s=0;s<e.length;s++)i.decode(e[s]);i.flush().catch(s=>{if(!(s instanceof Error))throw s;if(s.message.includes("Decoding error")&&t.onDecodingError!=null){t.onDecodingError(s);return}if(!s.message.includes("Aborted due to close"))throw s})}}function AR(i,e){if(e!=="avc1"&&e!=="hvc1")return 0;const t=new DataView(i.buffer);for(let s=0;s<i.byteLength-4;){if(e==="avc1"){const r=t.getUint8(s+4)&31;if(r===5||r===7||r===8)return s}else if(e==="hvc1"){const r=t.getUint8(s+4)>>1&63;if(r===19||r===20||r===32||r===33||r===34)return s}s+=t.getUint32(s)+4}return-1}function ef(i){let e=0,t=null;for(const s of i)if(!s.deleted){if(s.is_sync&&(e+=1),e>=2)break;(t==null||s.cts<t.cts)&&(t=s)}t!=null&&t.cts<2e5&&(t.duration+=t.cts,t.cts=0)}function M_(){try{const i=performance.memory;return{jsHeapSizeLimit:i.jsHeapSizeLimit,totalJSHeapSize:i.totalJSHeapSize,usedJSHeapSize:i.usedJSHeapSize,percentUsed:(i.usedJSHeapSize/i.jsHeapSizeLimit).toFixed(3),percentTotal:(i.totalJSHeapSize/i.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}async function ER(i,e,t,s,r,n){const o=await e.createReader(),a=await R_(i.filter(h=>!h.deleted&&h.is_sync&&h.cts>=r.start&&h.cts<=r.end),o);if(a.length===0||s.aborted){n(null,!0);return}let l=0;Qd(c(),a,{onDecodingError:h=>{q.warn("thumbnailsByKeyFrame",h),l===0?Qd(c(!0),a,{onDecodingError:u=>{o.close(),q.error("thumbnailsByKeyFrame retry soft deocde",u)}}):(n(null,!0),o.close())}});function c(h=!1){const u={...t,...h?{hardwareAcceleration:"prefer-software"}:{}},d=new VideoDecoder({output:f=>{l+=1;const p=l===a.length;n(f,p),p&&(o.close(),d.state!=="closed"&&d.close())},error:f=>{const p=`thumbnails decoder error: ${f.message}, config: ${JSON.stringify(u)}, state: ${JSON.stringify({qSize:d.decodeQueueSize,state:d.state,outputCnt:l,inputCnt:a.length})}`;throw q.error(p),Error(p)}});return s.addEventListener("abort",()=>{o.close(),d.state!=="closed"&&d.close()}),d.configure(u),d}}function IR(i,e,t){const s=new OffscreenCanvas(i,e),r=s.getContext("2d");return async n=>(r.drawImage(n,0,0,i,e),n.close(),await s.convertToBlob(t))}class gt extends qt{type="Text";ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}get width(){return this._width}set width(e){this.width!==e&&(this._width=e,this.refreshText(),this.emit("propsChange",{width:e}))}get height(){return this._height}set height(e){this.height!==e&&(this._height=e,this.refreshText(),this.emit("propsChange",{height:e}))}_lastContentWidth=0;_lastContentHeight=0;_text="";get text(){return this._text}set text(e){this._text!==e&&(this._text=e,this.originalOpts&&this.textStyle&&this.refreshText())}get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,fill:this.originalOpts.fill,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,dropShadow:this.originalOpts.dropShadow?{color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}:void 0,wordWrap:this.originalOpts.wordWrap,wordWrapWidth:this.originalOpts.wordWrapWidth,lineHeight:this.originalOpts.lineHeight,letterSpacing:this.originalOpts.letterSpacing,textCase:this.originalOpts.textCase,textDecoration:this.originalOpts.textDecoration}}set style(e){this.updateStyle(e)}get textAlign(){return this.originalOpts.align||this.originalOpts.textAlign||"left"}set textAlign(e){this.updateStyle({align:e})}get verticalAlign(){return this.originalOpts.verticalAlign||this.originalOpts.textDecoration||"top"}set verticalAlign(e){["underline","overline","strikethrough","line-through"].includes(e)?(this.updateStyle({textDecoration:e==="strikethrough"?"line-through":e}),this.originalOpts.verticalAlign=e):this.updateStyle({verticalAlign:e})}get textCase(){return this.originalOpts.textCase||"none"}set textCase(e){this.updateStyle({textCase:e})}pixiText=null;textStyle;renderTexture=null;externalRenderer=null;pixiApp=null;originalOpts;id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effects=[];constructor(e,t={},s){super(),this.originalOpts={...t},this.text=e,this.externalRenderer=s??null;const r=this.createStyleFromOpts(t),n=new Xe(r);this.textStyle=n,this.ready=(async()=>(await this.refreshText(),{...this._meta}))()}setRenderer(e){this.externalRenderer=e}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("TextClip: Failed to create renderer. Please provide a renderer via constructor or setRenderer() method.");return this.pixiApp.renderer}async getTexture(){return this.pixiText==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture}),this.renderTexture)}async tick(e){if(await this.ready,this.pixiText==null||this.renderTexture==null)throw new Error("Text not initialized");if(this.renderTexture.width<=0||this.renderTexture.height<=0)throw new Error(`Invalid RenderTexture dimensions: ${this.renderTexture.width}x${this.renderTexture.height}`);(await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture});const s=this.renderTexture.source?.resource?.source;let r;if(s instanceof HTMLCanvasElement)r=await createImageBitmap(s);else if(s instanceof OffscreenCanvas)r=await createImageBitmap(s);else{const a=(await this.getRenderer()).extract.canvas(this.renderTexture);if(a instanceof HTMLCanvasElement||a instanceof OffscreenCanvas)r=await createImageBitmap(a);else{const l=this.renderTexture.width,c=this.renderTexture.height;throw new OffscreenCanvas(l,c).getContext("2d")==null?new Error("Failed to create 2d context for fallback rendering"):new Error("Unable to extract canvas from render texture")}}return{video:r,state:"success"}}async split(e){await this.ready;const t=await this.clone(),s=await this.clone();return[t,s]}addEffect(e){this.effects.push(e)}editEffect(e,t){const s=this.effects.find(r=>r.id===e);s&&Object.assign(s,t)}removeEffect(e){const t=this.effects.findIndex(s=>s.id===e);t!==-1&&this.effects.splice(t,1)}async clone(){await this.ready;const e=this.textStyle,t=this.originalOpts||{},s=o=>{if(o!=null){if(typeof o=="number")return o;if(o instanceof ue)return o.toNumber()}},r={fontSize:t.fontSize??e.fontSize,fontFamily:t.fontFamily??(Array.isArray(e.fontFamily)?e.fontFamily[0]:typeof e.fontFamily=="string"?e.fontFamily:"Roboto"),fontWeight:t.fontWeight??e.fontWeight,fontStyle:t.fontStyle??e.fontStyle,align:t.align??(e.align==="justify"?"left":e.align),textCase:t.textCase,textDecoration:t.textDecoration};if(t.fill&&typeof t.fill=="object"&&"type"in t.fill&&t.fill.type==="gradient")r.fill=t.fill;else{const o=s(e.fill);r.fill=o??16777215}if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke)r.stroke=t.stroke;else{const o=s(e.stroke);o!==void 0&&(r.stroke=o),r.strokeWidth=t.strokeWidth??e.strokeThickness??0}if(t.dropShadow)r.dropShadow=t.dropShadow;else if(e.dropShadow){const o=e.dropShadow,a=s(o.color);a!==void 0&&(r.dropShadow={color:a,alpha:o.alpha,blur:o.blur,angle:o.angle,distance:o.distance})}if(t.wordWrap!==void 0?(r.wordWrap=t.wordWrap,r.wordWrapWidth=t.wordWrapWidth):e.wordWrap&&(r.wordWrap=e.wordWrap,r.wordWrapWidth=e.wordWrapWidth),t.lineHeight!==void 0)r.lineHeight=t.lineHeight;else if(e.lineHeight!==void 0){const o=r.fontSize??e.fontSize??40;r.lineHeight=e.lineHeight/o}t.letterSpacing!==void 0?r.letterSpacing=t.letterSpacing:e.letterSpacing!==void 0&&(r.letterSpacing=e.letterSpacing);const n=new gt(this.text,r);return await n.ready,this.copyStateTo(n),n.id=this.id,n.effects=[...this.effects],n}async updateStyle(e){this.originalOpts={...this.originalOpts,...e};const t=this.createStyleFromOpts(this.originalOpts),s=new Xe(t);this.textStyle=s,await this.refreshText()}async refreshText(){const e=this.textStyle;let t=this.text;const s=this.originalOpts.textCase;s==="uppercase"?t=t.toUpperCase():s==="lowercase"?t=t.toLowerCase():s==="title"&&(t=t.replace(/\w\S*/g,m=>m.charAt(0).toUpperCase()+m.substring(1).toLowerCase())),this.pixiText?(this.pixiText.text=t,this.pixiText.style=e,this.pixiText.children.forEach(m=>{m instanceof xe&&m.destroy()}),this.pixiText.removeChildren()):this.pixiText=new GI({text:t,style:e});const r=this.originalOpts.textDecoration||this.originalOpts.verticalAlign;if(r&&r!=="none"&&["underline","overline","strikethrough","line-through"].includes(r)){const m=r==="strikethrough"?"line-through":r,x=$e.measureText(t,e),_=e.fontSize??40,y=Math.max(1,_/12);let v=16777215;typeof e.fill=="number"?v=e.fill:e.fill&&typeof e.fill=="object"&&"fill"in e.fill&&(v=16777215);const T=new xe,S=e.lineHeight??x.lineHeight;for(let w=0;w<x.lines.length;w++){const E=x.lineWidths[w];let P=0;e.align==="center"?P=(x.maxLineWidth-E)/2:e.align==="right"&&(P=x.maxLineWidth-E);const C=w*S;let A=0;m==="underline"?A=S:m==="line-through"?A=S/2:m==="overline"&&(A=0);const U=C+A;T.rect(P,U,E,y),T.fill(v)}this.pixiText.addChild(T)}const n=this.pixiText.getLocalBounds(),o=Math.ceil(n.width||this.pixiText.width||1),a=Math.ceil(n.height||this.pixiText.height||1);let l=o;e.wordWrap&&e.wordWrapWidth>0&&(l=Math.max(l,e.wordWrapWidth));const c=a,h=this.width===0||Math.abs(this.width-this._lastContentWidth)<.1,u=this.height===0||Math.abs(this.height-this._lastContentHeight)<.1,d=h?l:Math.max(l,this.width||0),f=u?c:Math.max(c,this.height||0);this._lastContentWidth=l,this._lastContentHeight=c;const p=this.textAlign;p==="center"?this.pixiText.x=(d-o)/2:p==="right"?this.pixiText.x=d-o:this.pixiText.x=0;const g=this.originalOpts.verticalAlign||"top";g==="center"?this.pixiText.y=(f-a)/2:g==="bottom"?this.pixiText.y=f-a:this.pixiText.y=0,this.renderTexture&&this.renderTexture.destroy(),this.renderTexture=Ge.create({width:d,height:f}),this._meta.width=d,this._meta.height=f,this._width=d,this._height=f,this.duration===0&&this._meta.duration!==1/0&&(this.duration=this._meta.duration,this.display.to=this.display.from+this.duration)}createStyleFromOpts(e){const t=e.fontSize??40,s=e.lineHeight??1,r={fontSize:t,fontFamily:e.fontFamily??"Roboto",fontWeight:e.fontWeight??"normal",fontStyle:e.fontStyle??"normal",align:e.align??"left",wordWrap:e.wordWrap??!1,wordWrapWidth:e.wordWrapWidth??100,lineHeight:t*s,letterSpacing:e.letterSpacing??0};if(e.fill&&typeof e.fill=="object"&&e.fill.type==="gradient"){const n=new at(e.fill.x0,e.fill.y0,e.fill.x1,e.fill.y1);e.fill.colors.forEach(({ratio:o,color:a})=>{const l=typeof a=="number"?a:Te(a)??16777215;n.addColorStop(o,l)}),r.fill={fill:n}}else{const{color:n,alpha:o}=xi(e.fill);r.fill=n,o<1&&(r.fillAlpha=o)}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const n=Te(e.stroke.color);n!==void 0&&(r.stroke={color:n,width:e.stroke.width},e.stroke.join&&(r.stroke.join=e.stroke.join),e.stroke.cap&&(r.stroke.cap=e.stroke.cap),e.stroke.miterLimit&&(r.stroke.miterLimit=e.stroke.miterLimit))}else{const n=Te(e.stroke),o=e.strokeWidth??0;n!==void 0&&o>0?r.stroke={color:n,width:o}:e.strokeWidth&&e.strokeWidth>0&&(r.stroke={color:0,width:e.strokeWidth})}if(e.dropShadow){const n=Te(e.dropShadow.color);n!==void 0&&(r.dropShadow={color:n,alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,angle:e.dropShadow.angle??Math.PI/6,distance:e.dropShadow.distance??2})}return r}destroy(){if(!this.destroyed){q.info("Text destroy");try{this.pixiText!=null&&this.pixiText.destroyed!==!0&&this.pixiText.destroy({children:!0})}catch{}finally{this.pixiText=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const e=this.pixiApp;e.destroyed!==!0&&e.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(e=!1){const t=super.toJSON(e),s={};return this.originalOpts.fontSize!==void 0&&(s.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(s.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontWeight!==void 0&&(s.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(s.fontStyle=this.originalOpts.fontStyle),this.originalOpts.fill!==void 0&&(s.color=this.originalOpts.fill),this.originalOpts.align!==void 0&&(s.align=this.originalOpts.align),this.originalOpts.wordWrap!==void 0&&(s.wordWrap=this.originalOpts.wordWrap),this.originalOpts.wordWrapWidth!==void 0&&(s.wordWrapWidth=this.originalOpts.wordWrapWidth),this.originalOpts.lineHeight!==void 0&&(s.lineHeight=this.originalOpts.lineHeight),this.originalOpts.letterSpacing!==void 0&&(s.letterSpacing=this.originalOpts.letterSpacing),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?s.stroke={color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:s.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.dropShadow&&(s.shadow={color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,distance:this.originalOpts.dropShadow.distance??0,angle:this.originalOpts.dropShadow.angle??0}),{...t,type:"Text",text:this.text,style:s,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Text")throw new Error(`Expected Text, got ${e.type}`);const t=e.text||"",s=e.style||{},r={};s.fontSize!==void 0&&(r.fontSize=s.fontSize),s.fontFamily!==void 0&&(r.fontFamily=s.fontFamily),s.fontWeight!==void 0&&(r.fontWeight=s.fontWeight),s.fontStyle!==void 0&&(r.fontStyle=s.fontStyle),s.color!==void 0&&(r.fill=s.color),s.align!==void 0&&(r.align=s.align),s.wordWrap!==void 0&&(r.wordWrap=s.wordWrap),s.wordWrapWidth!==void 0&&(r.wordWrapWidth=s.wordWrapWidth),s.lineHeight!==void 0&&(r.lineHeight=s.lineHeight),s.letterSpacing!==void 0&&(r.letterSpacing=s.letterSpacing),s.stroke&&(s.stroke.join||s.stroke.cap||s.stroke.miterLimit!==void 0?r.stroke={color:s.stroke.color,width:s.stroke.width,join:s.stroke.join,cap:s.stroke.cap,miterLimit:s.stroke.miterLimit}:(r.stroke=s.stroke.color,r.strokeWidth=s.stroke.width)),s.shadow&&(r.dropShadow={color:s.shadow.color,alpha:s.shadow.alpha,blur:s.shadow.blur,distance:s.shadow.distance,angle:s.shadow.angle});const n=new gt(t,r);return n.left=e.left,n.top=e.top,n.width=e.width,n.height=e.height,n.angle=e.angle,n.display.from=e.display.from,n.display.to=e.display.to,n.duration=e.duration,n.playbackRate=e.playbackRate,n.zIndex=e.zIndex,n.opacity=e.opacity,n.flip=e.flip,e.animation&&n.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(n.id=e.id),e.effects&&(n.effects=e.effects),await n.ready,n}getVisibleHandles(){return["mr","mb","br","rot"]}}class ct extends qt{type="Effect";ready;_meta={duration:5e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;effect;constructor(e){super(),this.effect={id:`eff_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new ct(this.effect.key);return this.copyStateTo(e),e.id=this.id,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),s=await this.clone();return[t,s]}toJSON(e=!1){return{...super.toJSON(e),type:"Effect",effect:this.effect,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Effect")throw new Error(`Expected Effect, got ${e.type}`);const t=new ct(e.effect.key);return t.effect=e.effect,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}class mn extends qt{type="Placeholder";meta={width:0,height:0,duration:0};constructor(e,t={},s="Placeholder"){super(),this.type=s,this.src=e,this.meta={width:t.width||1280,height:t.height||720,duration:t.duration||5e6},this.width=this.meta.width,this.height=this.meta.height,this.duration=this.meta.duration,this.trim.to=this.duration,this.display.to=this.display.from+this.duration,this.ready=Promise.resolve(this.meta)}placeholderFrame=null;async tick(e){if(!this.placeholderFrame){const t=document.createElement("canvas");t.width=this.meta.width,t.height=this.meta.height;const s=t.getContext("2d");s&&(s.fillStyle="#1e1e1e",s.fillRect(0,0,t.width,t.height),s.fillStyle="#ffffff",s.font=`${Math.floor(t.height/10)}px sans-serif`,s.textAlign="center",s.textBaseline="middle",s.fillText("Loading...",t.width/2,t.height/2),s.strokeStyle="#333333",s.lineWidth=10,s.strokeRect(0,0,t.width,t.height)),this.placeholderFrame=await createImageBitmap(t)}return{video:this.placeholderFrame,state:e>=this.duration?"done":"success",audio:[]}}async clone(){const e=new mn(this.src,this.meta);return this.copyStateTo(e),e.id=this.id,e}async split(e){const t=await this.clone(),s=await this.clone();return t.trim.to=e+this.trim.from,s.trim.from=e+this.trim.from,t.duration=t.trim.to-t.trim.from,s.duration=s.trim.to-s.trim.from,t.display.to=t.display.from+t.duration,s.display.from=t.display.to,s.display.to=s.display.from+s.duration,[t,s]}}class Lt extends qt{type="Transition";ready;_meta={duration:2e6,width:0,height:0};get meta(){return{...this._meta}}id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;transitionEffect;fromClipId=null;toClipId=null;constructor(e){super(),this.transitionEffect={id:`trans_${Date.now()}`,key:e,name:e},this.ready=Promise.resolve(this._meta),this.duration=this._meta.duration}async clone(){const e=new Lt(this.transitionEffect.key);return this.copyStateTo(e),e.fromClipId=this.fromClipId,e.toClipId=this.toClipId,e}async tick(e){return{video:void 0,state:"success"}}async split(e){const t=await this.clone(),s=await this.clone();return[t,s]}toJSON(e=!1){return{...super.toJSON(e),type:"Transition",transitionEffect:this.transitionEffect,fromClipId:this.fromClipId,toClipId:this.toClipId,id:this.id,effects:this.effects}}static async fromObject(e){if(e.type!=="Transition")throw new Error(`Expected Transition, got ${e.type}`);const t=new Lt(e.transitionEffect.key);return t.transitionEffect=e.transitionEffect,t.fromClipId=e.fromClipId||null,t.toClipId=e.toClipId||null,t.left=e.left,t.top=e.top,t.width=e.width,t.height=e.height,t.angle=e.angle,t.display.from=e.display.from,t.display.to=e.display.to,t.duration=e.duration,t.playbackRate=e.playbackRate,t.zIndex=e.zIndex,t.opacity=e.opacity,t.flip=e.flip,e.animation&&t.setAnimation(e.animation.keyFrames,e.animation.opts),e.id&&(t.id=e.id),await t.ready,t}}function k_(i,e){let t=!1;async function s(){const r=i.getReader();for(;!t;){const{value:n,done:o}=await r.read();if(o){e.onDone();return}await e.onChunk(n)}r.releaseLock(),await i.cancel()}return s().catch(console.error),()=>{t=!0}}function F_(i,e,t){let s=0,r=0;const n=i.boxes;let o=!1;const a=()=>{if(!o)if(n.find(p=>p.type==="moof")!=null)o=!0;else return null;if(r>=n.length)return null;const d=new oi.DataStream;let f=r;try{for(;f<n.length;)n[f].write(d),delete n[f],f+=1}catch(p){const g=n[f];throw p instanceof Error&&g!=null?Error(`${p.message} | deltaBuf( boxType: ${g.type}, boxSize: ${g.size}, boxDataLen: ${g.data?.length??-1})`):p}return PR(i),r=n.length,new Uint8Array(d.buffer)};let l=!1,c=!1,h=null;return{stream:new ReadableStream({start(d){s=self.setInterval(()=>{const f=a();f!=null&&!c&&d.enqueue(f)},e),h=f=>{if(clearInterval(s),i.flush(),f!=null){d.error(f);return}const p=a();p!=null&&!c&&d.enqueue(p),c||d.close()},l&&h()},cancel(){c=!0,clearInterval(s),t?.()}}),stop:d=>{l||(l=!0,h?.(d))}}}function PR(i){if(i.moov!=null){for(var e=0;e<i.moov.traks.length;e++)i.moov.traks[e].samples=[];i.mdats=[],i.moofs=[]}}class B_{readable;writable;inputBufOffset=0;isStreamCancelled=!1;constructor(){const e=oi.createFile();this.readable=new ReadableStream({start:t=>this.initMP4Box(e,t),cancel:()=>{this.isStreamCancelled=!0,e.stop()}},{highWaterMark:50}),this.writable=new WritableStream({write:async t=>{if(this.isStreamCancelled)throw new Error("Stream cancelled");const s=t.buffer;s.fileStart=this.inputBufOffset,this.inputBufOffset+=s.byteLength,e.appendBuffer(s)},close:()=>{e.flush(),e.stop(),e.onFlush?.()},abort:t=>{RR.error("SampleTransform writable aborted:",t),e.stop()}})}initMP4Box(e,t){e.onReady=r=>{[r.videoTracks[0],r.audioTracks[0]].forEach(n=>{n&&e.setExtractionOptions(n.id,n.video?"video":"audio",{nbSamples:100})}),t.enqueue({chunkType:"ready",data:{info:r,file:e}}),e.start()};const s={};e.onSamples=(r,n,o)=>{const a=o.map(l=>({...l}));t.enqueue({chunkType:"samples",data:{id:r,type:n,samples:a}}),s[r]=(s[r]??0)+o.length,e.releaseUsedSamples(r,s[r])},e.onFlush=()=>{t.close()},e.onError=r=>{t.error(new Error(`mp4box error: ${r}`))}}}const RR={error:(...i)=>console.error("[SampleTransform]",...i)};function MR(i){let e=0;const t=i.boxes,s=[];let r=0;async function n(){const p=f(t,e);e=t.length,s.forEach(({track:g,id:m})=>{const x=g.samples.at(-1);x!=null&&(r=Math.max(r,x.cts+x.duration)),i.releaseUsedSamples(m,g.samples.length),g.samples=[]}),i.mdats=[],i.moofs=[],p!=null&&await h?.write(p)}let o=[];function a(){if(o.length>0)return!0;const p=t.findIndex(g=>g.type==="moov");if(p===-1)return!1;if(o=t.slice(0,p+1),e=p+1,s.length===0)for(let g=1;;g+=1){const m=i.getTrackById(g);if(m==null)break;s.push({track:m,id:g})}return!0}let l=0;const c=Xh();let h=null;const u=(async()=>{h=await c.createWriter(),l=self.setInterval(()=>{a()&&n()},100)})();let d=!1;return async()=>{if(d)throw Error("File exported");if(d=!0,await u,clearInterval(l),!a()||h==null)return null;i.flush(),await n(),await h?.close();const p=o.find(x=>x.type==="moov");if(p==null)return null;p.mvhd.duration=r;const g=Xh(),m=f(o,0);return await Ei(g,m.slice()),await Ei(g,c,{overwrite:!1}),await g.stream()};function f(p,g){if(g>=p.length)return null;const m=new oi.DataStream;for(let x=g;x<p.length;x++)p[x]!==null&&(p[x].write(m),delete p[x]);return new Uint8Array(m.buffer).slice()}}function kR(i){const e=new ArrayBuffer(i.byteLength);i.copyTo(e);const t=i.timestamp;return{duration:i.duration??0,dts:t,cts:t,is_sync:i.type==="key",data:e}}async function U_(i){const e=oi.createFile(),t=MR(e);await FR(i,e);const s=await t();if(s==null)throw Error("Can not generate file from streams");return s}async function FR(i,e){let t=0,s=0,r=0,n=0,o=0,a=0,l=null,c=null;for(const h of i){let u=null,d=null,f=null,p=null;if(await new Promise(async g=>{k_(h.pipeThrough(new B_),{onDone:g,onChunk:async({chunkType:m,data:x})=>{if(m==="ready"){const{videoTrackConf:_,audioTrackConf:y}=jd(x.file,x.info);t===0&&_!=null&&(t=e.addTrack(_)),n===0&&y!=null&&(n=e.addTrack(y))}else if(m==="samples"){const{type:_,samples:y}=x,v=_==="video"?t:n,T=_==="video"?s:o,S=_==="video"?r:a;y.forEach(E=>{let P,C;_==="video"?(u===null&&(u=E.dts,d=E.cts),P=E.dts-u,C=E.cts-(d??0)):(f===null&&(f=E.dts,p=E.cts),P=E.dts-f,C=E.cts-(p??0)),e.addSample(v,new Uint8Array(E.data),{duration:E.duration,dts:P+T,cts:C+S,is_sync:E.is_sync})});const w=y.at(-1);if(w==null)return;_==="video"?l=w:_==="audio"&&(c=w)}}})}),l!=null&&u!==null&&d!==null){const g=l.dts-u+l.duration,m=l.cts-d+l.duration;s+=g,r+=m}if(c!=null&&l!=null){const g=c.timescale/l.timescale;o=Math.round(s*g),a=Math.round(r*g)}}}async function BR(i){return await U_([i])}function UR(i){let e=[];const t=new AudioDecoder({output:s=>{e.push(s)},error:q.error});return t.configure(i),{decode:async s=>{s.forEach(n=>{t.decode(new EncodedAudioChunk({type:n.is_sync?"key":"delta",timestamp:1e6*n.cts/n.timescale,duration:1e6*n.duration/n.timescale,data:n.data}))}),await t.flush();const r=e;return e=[],r},close:()=>{t.close()}}}function OR(i,e){const t={codec:i.codec,sampleRate:i.sampleRate,numberOfChannels:i.numberOfChannels},s=new AudioEncoder({output:o=>{e(kR(o))},error:o=>{q.error("AudioEncoder error:",o,", config:",t)}});s.configure(t);let r=null;function n(o,a){return new AudioData({timestamp:a,numberOfChannels:i.numberOfChannels,numberOfFrames:o.length/i.numberOfChannels,sampleRate:i.sampleRate,format:"f32-planar",data:new Float32Array(o)})}return{encode:async(o,a)=>{r!=null&&s.encode(n(r.data,r.ts)),r={data:o,ts:a}},stop:async()=>{r!=null&&(DR(r.data,i.numberOfChannels,i.sampleRate),s.encode(n(r.data,r.ts)),r=null),await s.flush(),s.close()}}}function DR(i,e,t){const s=i.length-1,r=Math.min(t/2,s);for(let n=0;n<r;n++)for(let o=1;o<=e;o++)i[Math.floor(s/o)-n]*=n/r}function GR(i,e){q.info("mixinMP4AndAudio, opts:",{volume:e.volume,loop:e.loop});const t=oi.createFile(),{stream:s,stop:r}=F_(t,500);let n=null,o=null,a=[],l=0,c=0,h=0,u=!0,d=le.sampleRate;k_(i.pipeThrough(new B_),{onDone:async()=>{await o?.stop(),n?.close(),r()},onChunk:async({chunkType:m,data:x})=>{if(m==="ready"){const{videoTrackConf:_,audioTrackConf:y,audioDecoderConf:v}=jd(x.file,x.info);l===0&&_!=null&&(l=t.addTrack(_));const T=y??{timescale:1e6,samplerate:d,channel_count:le.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};c===0&&(c=t.addTrack(T),d=y?.samplerate??d,u=y!=null);const S=new AudioContext({sampleRate:d});a=Yh(await S.decodeAudioData(await new Response(e.stream).arrayBuffer())),v!=null&&(n=UR(v)),o=OR(v??{codec:T.type==="mp4a"?le.codec:T.type,numberOfChannels:T.channel_count,sampleRate:T.samplerate},w=>t.addSample(c,new Uint8Array(w.data),w))}else if(m==="samples"){const{id:_,type:y,samples:v}=x;if(y==="video"){v.forEach(T=>t.addSample(_,new Uint8Array(T.data),T)),u||await p(v);return}y==="audio"&&await g(v)}}});function f(m){const x=a.map(_=>e.loop?qh(_,h,h+m):_.slice(h,h+m));if(h+=m,e.volume!==1)for(const _ of x)for(let y=0;y<_.length;y++)_[y]*=e.volume;return x}async function p(m){const x=m[0],_=m[m.length-1],y=Math.floor((_.cts+_.duration-x.cts)/x.timescale*d),v=Mp([f(y)]);v.length!==0&&o?.encode(v,x.cts/x.timescale*1e6)}async function g(m){if(n==null)return;const x=(await n.decode(m)).map(Rp),_=Pp(x),y=f(_[0].length),v=m[0];o?.encode(Mp([_,y]),v.cts/v.timescale*1e6)}return s}const zR=`
|
|
1417
1417
|
in vec2 aPosition;
|
|
1418
1418
|
out vec2 vTextureCoord;
|
|
1419
1419
|
|
|
@@ -1680,7 +1680,7 @@ void main(void)
|
|
|
1680
1680
|
|
|
1681
1681
|
gl_FragColor = vec4(col, 1.0);
|
|
1682
1682
|
}
|
|
1683
|
-
`,QR={uTime:{value:0,type:"f32"},intensity:{value:.5,type:"f32"},sliceCount:{value:12,type:"f32"},rgbShift:{value:.01,type:"f32"}},
|
|
1683
|
+
`,QR={uTime:{value:0,type:"f32"},intensity:{value:.5,type:"f32"},sliceCount:{value:12,type:"f32"},rgbShift:{value:.01,type:"f32"}},O_=`
|
|
1684
1684
|
in vec2 vTextureCoord;
|
|
1685
1685
|
in vec4 vColor;
|
|
1686
1686
|
|
|
@@ -1711,7 +1711,7 @@ void main(void)
|
|
|
1711
1711
|
|
|
1712
1712
|
gl_FragColor = color;
|
|
1713
1713
|
}
|
|
1714
|
-
`,
|
|
1714
|
+
`,D_={pixelSize:{value:.02,type:"f32"},uTime:{value:0,type:"f32"},jitterStrength:{value:.8,type:"f32"}},tf={...{rotationMovement:{label:"Rotation Movement",fragment:NR,uniforms:LR},redGradient:{label:"Red Gradient",fragment:HR,uniforms:WR},bubbleSparkles:{label:"Bubble Sparkles",fragment:VR,uniforms:$R},sepia:{label:"Sepia",fragment:XR,uniforms:YR},uvGradient:{label:"UV Gradient",fragment:qR,uniforms:KR},rainbow:{label:"Rainbow",fragment:jR,uniforms:ZR},glitch:{label:"Glitch",fragment:JR,uniforms:QR},pixelate:{label:"Pixelate",fragment:O_,uniforms:D_},rgbGlitch:{label:"RGB Glitch",fragment:`
|
|
1715
1715
|
precision highp float;
|
|
1716
1716
|
|
|
1717
1717
|
varying vec2 vTextureCoord;
|
|
@@ -4353,7 +4353,7 @@ void main() {
|
|
|
4353
4353
|
|
|
4354
4354
|
gl_FragColor = color;
|
|
4355
4355
|
}
|
|
4356
|
-
`,uniforms:{uTime:{value:0,type:"f32"},uZoomSpeed:{value:5,type:"f32"},uMaxZoom:{value:2,type:"f32"},uBlurStrength:{value:.01,type:"f32"}}}}},eM=Object.entries(tf).map(([i,e])=>({key:i,label:e.label,previewStatic:`https://cdn.subgen.co/previews/effects/static/effect_${i}_static.webp`,previewDynamic:`https://cdn.subgen.co/previews/effects/dynamic/effect_${i}_dynamic.webp`}));function sf({name:i,renderer:e}){let t;const s=Object.keys(tf).find(u=>u.toLowerCase()===i.toLowerCase());s&&(t=tf[s]);const{fragment:r,uniforms:n,label:o}=t,a=new Ue,l=Ge.create({width:e.width,height:e.height}),c=new At({vertex:zR,fragment:r,name:`${o}-shader`}),h=new Gi({glProgram:c,resources:{effectUniforms:{...n}}});return a.filters=[h],{filter:h,render({width:u,height:d,canvasTexture:f,progress:p}){(l.width!==u||l.height!==d)&&l.resize(u,d);const g=f instanceof Ge?f:M.from(f);a.texture=g,a.width=u,a.height=d;const m=h.resources.effectUniforms.uniforms;return m.uTime=p,e.render({container:a,target:l,clear:!0}),l}}}function tM(i,e){const{opacity:t,zIndex:s,flip:r,left:n,top:o,width:a,height:l,angle:c}=i;e.x=n,e.y=o,e.width=Math.abs(a),e.height=Math.abs(l),e.angle=c,e.alpha=t,e.zIndex=s,r==="horizontal"?e.scale.x=-Math.abs(e.scale.x):r==="vertical"&&(e.scale.y=-Math.abs(e.scale.y))}class gn{constructor(e,t,s=null){this.sprite=t,this.targetContainer=s,!s&&e&&(this.targetContainer=e.stage),this.resolution=e?.renderer?.resolution??1,this.canvas=new OffscreenCanvas(1,1);const r=this.canvas.getContext("2d");if(r==null)throw new Error("Failed to create 2d context for PixiSpriteRenderer");this.context=r,this.root=new re,this.root.visible=!1,this.targetContainer&&this.targetContainer.addChild(this.root)}pixiSprite=null;texture=null;canvas;context;root=null;strokeGraphics=null;maskGraphics=null;shadowGraphics=null;shadowContainer=null;resolution=1;destroyed=!1;async updateFrame(e){if(this.destroyed)return;if(e==null){this.root!=null&&(this.root.visible=!1,this.applySpriteTransforms());return}if(e instanceof M||e&&typeof e.source<"u"){if(e.width===0||e.height===0){console.warn("PixiSpriteRenderer: Texture has zero dimensions",e.width,e.height);return}this.pixiSprite==null?(this.pixiSprite=new Ue(e),this.pixiSprite.label="MainSprite",this.root.addChild(this.pixiSprite),this.applySpriteTransforms()):this.pixiSprite.texture=e,this.root!=null&&(this.root.visible=!0,this.applySpriteTransforms());return}const s=e.width,r=e.height;if(typeof s!="number"||typeof r!="number"||s<=0||r<=0){console.warn("PixiSpriteRenderer: Invalid frame dimensions",s,r);return}const n=this.texture==null||this.pixiSprite==null,o=Math.floor(s),a=Math.floor(r);if(this.canvas.width!==o||this.canvas.height!==a||n){if(this.canvas.width=o,this.canvas.height=a,this.texture!=null&&(this.texture.destroy(!0),this.texture=null),this.texture=M.from(this.canvas),!this.texture||!this.texture.source){console.error("PixiSpriteRenderer: Failed to create valid texture");return}this.pixiSprite==null?(this.pixiSprite=new Ue(this.texture),this.pixiSprite.label="MainSprite",this.root.addChild(this.pixiSprite),this.applySpriteTransforms()):this.pixiSprite.texture=this.texture}if(this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(e,0,0),this.texture!=null&&this.texture.source!=null){const c=this.texture.source;if(c.resource){const h=c.resource;h.update&&h.update()}typeof c.update=="function"&&c.update()}this.root!=null&&(this.root.visible=!0,this.applySpriteTransforms())}applySpriteTransforms(){if(this.pixiSprite==null||this.root==null||this.destroyed)return;const{flip:e,center:t,width:s,height:r,angle:n,opacity:o,zIndex:a}=this.sprite;this.root.x=t.x,this.root.y=t.y,this.root.angle=(e==null?1:-1)*n,this.root.alpha=o,this.root.zIndex=a,this.root.scale.set(1,1),this.pixiSprite.anchor.set(.5,.5),this.pixiSprite.position.set(0,0);const l=this.pixiSprite.texture?.width??1,c=this.pixiSprite.texture?.height??1,h=s&&s!==0?Math.abs(s)/l:1,u=r&&r!==0?Math.abs(r)/c:1;e==="horizontal"?(this.pixiSprite.scale.x=-h,this.pixiSprite.scale.y=u):e==="vertical"?(this.pixiSprite.scale.x=h,this.pixiSprite.scale.y=-u):(this.pixiSprite.scale.x=h,this.pixiSprite.scale.y=u),this.applyStyle()}applyStyle(){if(this.pixiSprite==null||this.destroyed)return;const e=this.sprite.style||{},t=this.pixiSprite.texture?.width??0,s=this.pixiSprite.texture?.height??0;if(t===0||s===0)return;const r=e.borderRadius||0;r>0?(this.maskGraphics==null&&(this.maskGraphics=new _e,this.pixiSprite.addChild(this.maskGraphics),this.pixiSprite.mask=this.maskGraphics),this.maskGraphics.clear(),this.maskGraphics.roundRect(-t/2,-s/2,t,s,Math.min(r,t/2,s/2)),this.maskGraphics.fill({color:16777215,alpha:1}),this.maskGraphics.visible=!0):this.maskGraphics&&(this.maskGraphics.visible=!1,this.pixiSprite.mask=null),this.sprite.type!=="Text"&&this.sprite.type!=="Caption"?this.applyStroke(e,t,s):this.strokeGraphics&&(this.strokeGraphics.visible=!1),this.sprite.type!=="Text"&&this.sprite.type!=="Caption"?this.applyShadow(e):this.shadowContainer&&(this.shadowContainer.visible=!1,this.shadowContainer.filters=[])}applyStroke(e,t,s){const r=e.stroke;if(r&&r.width>0){this.strokeGraphics==null&&(this.strokeGraphics=new _e,this.pixiSprite.addChild(this.strokeGraphics)),this.strokeGraphics.clear();const n=Te(r.color)??16777215,o=r.width,a=e.borderRadius||0;if(this.strokeGraphics.setStrokeStyle({width:o,color:n,alignment:1}),a>0){const l=Math.min(a,t/2,s/2);this.strokeGraphics.roundRect(-t/2,-s/2,t,s,l)}else this.strokeGraphics.rect(-t/2,-s/2,t,s);this.strokeGraphics.stroke(),this.strokeGraphics.visible=!0}else this.strokeGraphics!=null&&(this.strokeGraphics.visible=!1)}applyShadow(e){const t=e.dropShadow,s=Math.abs(this.sprite.width??0),r=Math.abs(this.sprite.height??0);if(t&&s>0&&r>0&&(t.blur>0||t.distance>0)){this.shadowContainer==null&&(this.shadowContainer=new re,this.shadowContainer.label="ShadowContainer",this.shadowGraphics=new _e,this.shadowContainer.addChild(this.shadowGraphics),this.root.addChildAt(this.shadowContainer,0));const n=Te(t.color)??0,o=t.alpha??.5,a=t.blur??0,l=t.distance??0,c=t.angle??0,h=Math.cos(c)*l,u=Math.sin(c)*l;this.shadowContainer.position.set(h,u),this.shadowGraphics.clear();const d=e.borderRadius||0;if(d>0){const f=Math.min(d,s/2,r/2);this.shadowGraphics.roundRect(-s/2,-r/2,s,r,f)}else this.shadowGraphics.rect(-s/2,-r/2,s,r);if(this.shadowGraphics.fill({color:n,alpha:o}),a>0){(!this.shadowContainer.filters||this.shadowContainer.filters.length===0)&&(this.shadowContainer.filters=[new y0]);const f=this.shadowContainer.filters[0],p=this.root?Math.sqrt(this.root.worldTransform.a**2+this.root.worldTransform.b**2):1;f.strength=a*p,f.resolution=this.resolution,f.padding=Math.max(a*2*p,20)}else this.shadowContainer.filters=[];this.shadowContainer.visible=!0}else this.shadowContainer!=null&&(this.shadowContainer.visible=!1,this.shadowContainer.filters=[])}updateTransforms(){this.root!=null&&!this.destroyed&&this.applySpriteTransforms()}getSprite(){return this.pixiSprite}getRoot(){return this.root}destroy(){this.destroyed||(this.destroyed=!0,this.root!=null&&(this.root.parent&&this.root.parent.removeChild(this.root),this.root.destroy({children:!0}),this.root=null,this.pixiSprite=null),this.strokeGraphics!=null&&(this.strokeGraphics.destroy(),this.strokeGraphics=null),this.maskGraphics!=null&&(this.maskGraphics.destroy(),this.maskGraphics=null),this.shadowGraphics!=null&&(this.shadowGraphics.destroy(),this.shadowGraphics=null),this.shadowContainer!=null&&(this.shadowContainer.destroy({children:!0}),this.shadowContainer=null),this.texture!=null&&(this.texture.destroy(),this.texture=null))}}function Ys(i,e=!1){return i.toJSON(e)}async function Ki(i){let e,t=null;switch(i.type){case"Video":t=Me;break;case"Audio":t=Ke;break;case"Image":return e=await xi.fromObject(i),e;case"Text":t=gt;break;case"Caption":t=ei;break;case"Effect":t=ct;break;case"Transition":t=Lt;break;case"Placeholder":t=mn;break}if(t&&typeof t.fromObject=="function")return await t.fromObject(i);switch(i.type){case"Video":{const s=await fetch(i.src);if(!s.ok)throw new Error(`Failed to fetch video from ${i.src}: ${s.status} ${s.statusText}. Make sure the file exists in the public directory.`);const r=i.audio!==void 0?{audio:i.audio,volume:i.volume}:{volume:i.volume};e=new Me(s.body,r,i.src);break}case"Audio":{if(!i.src||i.src.trim()==="")throw new Error("Audio requires a valid source URL");const s={};i.loop!==void 0&&(s.loop=i.loop),i.volume!==void 0&&(s.volume=i.volume),e=await Ke.fromUrl(i.src,s);break}case"Text":{const s=i.text||"",r=i.style||{},n={fontSize:r.fontSize,fontFamily:r.fontFamily,fontWeight:r.fontWeight,fontStyle:r.fontStyle,fill:r.color,align:r.align};r.stroke&&(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width),r.shadow&&(n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:r.shadow.distance,angle:r.shadow.angle}),e=new gt(s,n);break}case"Caption":{const s=i.text||"",r=i.style||{},n={fontSize:r.fontSize,fontFamily:r.fontFamily,fontWeight:r.fontWeight,fontStyle:r.fontStyle,fill:r.color,align:r.align};if(r.fontUrl!==void 0?n.fontUrl=r.fontUrl:i.fontUrl!==void 0&&(n.fontUrl=i.fontUrl),r.stroke&&(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width),r.shadow&&(n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:r.shadow.distance,angle:r.shadow.angle}),i.caption){const o=i.caption;o.words&&(n.words=o.words),o.colors&&(o.colors.appeared!==void 0&&(n.appearedColor=o.colors.appeared),o.colors.active!==void 0&&(n.activeColor=o.colors.active),o.colors.activeFill!==void 0&&(n.activeFillColor=o.colors.activeFill),o.colors.background!==void 0&&(n.backgroundColor=o.colors.background),o.colors.keyword!==void 0&&(n.isKeyWordColor=o.colors.keyword)),o.preserveKeywordColor!==void 0&&(n.preservedColorKeyWord=o.preserveKeywordColor),o.positioning&&(o.positioning.bottomOffset!==void 0&&(n.bottomOffset=o.positioning.bottomOffset),o.positioning.videoWidth!==void 0&&(n.videoWidth=o.positioning.videoWidth),o.positioning.videoHeight!==void 0&&(n.videoHeight=o.positioning.videoHeight))}else i.bottomOffset!==void 0&&(n.bottomOffset=i.bottomOffset),i.words&&(n.words=i.words),i.appearedColor!==void 0&&(n.appearedColor=i.appearedColor),i.activeColor!==void 0&&(n.activeColor=i.activeColor),i.activeFillColor!==void 0&&(n.activeFillColor=i.activeFillColor),i.backgroundColor!==void 0&&(n.backgroundColor=i.backgroundColor),i.isKeyWordColor!==void 0&&(n.isKeyWordColor=i.isKeyWordColor),i.preservedColorKeyWord!==void 0&&(n.preservedColorKeyWord=i.preservedColorKeyWord),i.videoWidth!==void 0&&(n.videoWidth=i.videoWidth),i.videoHeight!==void 0&&(n.videoHeight=i.videoHeight);i.mediaId&&(n.mediaId=i.mediaId),e=new ei(s,n);break}case"Effect":{e=new ct(i.effect.key),e.effect=i.effect;break}default:throw new Error(`Unsupported clip type: ${i.type}`)}return e.left=i.left,e.top=i.top,e.width=i.width,e.height=i.height,e.angle=i.angle,e.display.from=i.display.from,e.display.to=i.display.to,e.duration=i.duration,e.playbackRate=i.playbackRate,e.zIndex=i.zIndex,e.opacity=i.opacity,e.flip=i.flip,i.style&&(e.style={...e.style,...i.style}),i.animation&&e.setAnimation(i.animation.keyFrames,i.animation.opts),i.id&&(e.id=i.id),i.effects&&(e.effects=i.effects),i.trim&&(e.trim.from=i.trim.from<1e6?i.trim.from*1e6:i.trim.from,e.trim.to=i.trim.to<1e6?i.trim.to*1e6:i.trim.to),e}var rf,Gx;function iM(){return Gx||(Gx=1,rf=[{name:"Bounce",paramsTypes:{shadow_colour:"vec4",shadow_height:"float",bounces:"float"},defaultParams:{shadow_colour:[0,0,0,.6],shadow_height:.075,bounces:3},glsl:`// Author: Adrian Purser
|
|
4356
|
+
`,uniforms:{uTime:{value:0,type:"f32"},uZoomSpeed:{value:5,type:"f32"},uMaxZoom:{value:2,type:"f32"},uBlurStrength:{value:.01,type:"f32"}}}}},eM=Object.entries(tf).map(([i,e])=>({key:i,label:e.label,previewStatic:`https://cdn.subgen.co/previews/effects/static/effect_${i}_static.webp`,previewDynamic:`https://cdn.subgen.co/previews/effects/dynamic/effect_${i}_dynamic.webp`}));function sf({name:i,renderer:e}){let t;const s=Object.keys(tf).find(u=>u.toLowerCase()===i.toLowerCase());s&&(t=tf[s]);const{fragment:r,uniforms:n,label:o}=t,a=new Ue,l=Ge.create({width:e.width,height:e.height}),c=new At({vertex:zR,fragment:r,name:`${o}-shader`}),h=new Gi({glProgram:c,resources:{effectUniforms:{...n}}});return a.filters=[h],{filter:h,render({width:u,height:d,canvasTexture:f,progress:p}){(l.width!==u||l.height!==d)&&l.resize(u,d);const g=f instanceof Ge?f:M.from(f);a.texture=g,a.width=u,a.height=d;const m=h.resources.effectUniforms.uniforms;return m.uTime=p,e.render({container:a,target:l,clear:!0}),l}}}function tM(i,e){const{opacity:t,zIndex:s,flip:r,left:n,top:o,width:a,height:l,angle:c}=i;e.x=n,e.y=o,e.width=Math.abs(a),e.height=Math.abs(l),e.angle=c,e.alpha=t,e.zIndex=s,r==="horizontal"?e.scale.x=-Math.abs(e.scale.x):r==="vertical"&&(e.scale.y=-Math.abs(e.scale.y))}class gn{constructor(e,t,s=null){this.sprite=t,this.targetContainer=s,!s&&e&&(this.targetContainer=e.stage),this.resolution=e?.renderer?.resolution??1,this.canvas=new OffscreenCanvas(1,1);const r=this.canvas.getContext("2d");if(r==null)throw new Error("Failed to create 2d context for PixiSpriteRenderer");this.context=r,this.root=new re,this.root.visible=!1,this.targetContainer&&this.targetContainer.addChild(this.root)}pixiSprite=null;texture=null;canvas;context;root=null;strokeGraphics=null;maskGraphics=null;shadowGraphics=null;shadowContainer=null;resolution=1;destroyed=!1;async updateFrame(e){if(this.destroyed)return;if(e==null){this.root!=null&&(this.root.visible=!1,this.applySpriteTransforms());return}if(e instanceof M||e&&typeof e.source<"u"){if(e.width===0||e.height===0){console.warn("PixiSpriteRenderer: Texture has zero dimensions",e.width,e.height);return}this.pixiSprite==null?(this.pixiSprite=new Ue(e),this.pixiSprite.label="MainSprite",this.root.addChild(this.pixiSprite),this.applySpriteTransforms()):this.pixiSprite.texture=e,this.root!=null&&(this.root.visible=!0,this.applySpriteTransforms());return}const s=e.width,r=e.height;if(typeof s!="number"||typeof r!="number"||s<=0||r<=0){console.warn("PixiSpriteRenderer: Invalid frame dimensions",s,r);return}const n=this.texture==null||this.pixiSprite==null,o=Math.floor(s),a=Math.floor(r);if(this.canvas.width!==o||this.canvas.height!==a||n){if(this.canvas.width=o,this.canvas.height=a,this.texture!=null&&(this.texture.destroy(!0),this.texture=null),this.texture=M.from(this.canvas),!this.texture||!this.texture.source){console.error("PixiSpriteRenderer: Failed to create valid texture");return}this.pixiSprite==null?(this.pixiSprite=new Ue(this.texture),this.pixiSprite.label="MainSprite",this.root.addChild(this.pixiSprite),this.applySpriteTransforms()):this.pixiSprite.texture=this.texture}if(this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(e,0,0),this.texture!=null&&this.texture.source!=null){const c=this.texture.source;if(c.resource){const h=c.resource;h.update&&h.update()}typeof c.update=="function"&&c.update()}this.root!=null&&(this.root.visible=!0,this.applySpriteTransforms())}applySpriteTransforms(){if(this.pixiSprite==null||this.root==null||this.destroyed)return;const{flip:e,center:t,width:s,height:r,angle:n,opacity:o,zIndex:a}=this.sprite;this.root.x=t.x,this.root.y=t.y,this.root.angle=(e==null?1:-1)*n,this.root.alpha=o,this.root.zIndex=a,this.root.scale.set(1,1),this.pixiSprite.anchor.set(.5,.5),this.pixiSprite.position.set(0,0);const l=this.pixiSprite.texture?.width??1,c=this.pixiSprite.texture?.height??1,h=s&&s!==0?Math.abs(s)/l:1,u=r&&r!==0?Math.abs(r)/c:1;e==="horizontal"?(this.pixiSprite.scale.x=-h,this.pixiSprite.scale.y=u):e==="vertical"?(this.pixiSprite.scale.x=h,this.pixiSprite.scale.y=-u):(this.pixiSprite.scale.x=h,this.pixiSprite.scale.y=u),this.applyStyle()}applyStyle(){if(this.pixiSprite==null||this.destroyed)return;const e=this.sprite.style||{},t=this.pixiSprite.texture?.width??0,s=this.pixiSprite.texture?.height??0;if(t===0||s===0)return;const r=e.borderRadius||0;r>0?(this.maskGraphics==null&&(this.maskGraphics=new xe,this.pixiSprite.addChild(this.maskGraphics),this.pixiSprite.mask=this.maskGraphics),this.maskGraphics.clear(),this.maskGraphics.roundRect(-t/2,-s/2,t,s,Math.min(r,t/2,s/2)),this.maskGraphics.fill({color:16777215,alpha:1}),this.maskGraphics.visible=!0):this.maskGraphics&&(this.maskGraphics.visible=!1,this.pixiSprite.mask=null),this.sprite.type!=="Text"&&this.sprite.type!=="Caption"?this.applyStroke(e,t,s):this.strokeGraphics&&(this.strokeGraphics.visible=!1),this.sprite.type!=="Text"&&this.sprite.type!=="Caption"?this.applyShadow(e):this.shadowContainer&&(this.shadowContainer.visible=!1,this.shadowContainer.filters=[])}applyStroke(e,t,s){const r=e.stroke;if(r&&r.width>0){this.strokeGraphics==null&&(this.strokeGraphics=new xe,this.pixiSprite.addChild(this.strokeGraphics)),this.strokeGraphics.clear();const n=Te(r.color)??16777215,o=r.width,a=e.borderRadius||0;if(this.strokeGraphics.setStrokeStyle({width:o,color:n,alignment:1}),a>0){const l=Math.min(a,t/2,s/2);this.strokeGraphics.roundRect(-t/2,-s/2,t,s,l)}else this.strokeGraphics.rect(-t/2,-s/2,t,s);this.strokeGraphics.stroke(),this.strokeGraphics.visible=!0}else this.strokeGraphics!=null&&(this.strokeGraphics.visible=!1)}applyShadow(e){const t=e.dropShadow,s=Math.abs(this.sprite.width??0),r=Math.abs(this.sprite.height??0);if(t&&s>0&&r>0&&(t.blur>0||t.distance>0)){this.shadowContainer==null&&(this.shadowContainer=new re,this.shadowContainer.label="ShadowContainer",this.shadowGraphics=new xe,this.shadowContainer.addChild(this.shadowGraphics),this.root.addChildAt(this.shadowContainer,0));const n=Te(t.color)??0,o=t.alpha??.5,a=t.blur??0,l=t.distance??0,c=t.angle??0,h=Math.cos(c)*l,u=Math.sin(c)*l;this.shadowContainer.position.set(h,u),this.shadowGraphics.clear();const d=e.borderRadius||0;if(d>0){const f=Math.min(d,s/2,r/2);this.shadowGraphics.roundRect(-s/2,-r/2,s,r,f)}else this.shadowGraphics.rect(-s/2,-r/2,s,r);if(this.shadowGraphics.fill({color:n,alpha:o}),a>0){(!this.shadowContainer.filters||this.shadowContainer.filters.length===0)&&(this.shadowContainer.filters=[new y0]);const f=this.shadowContainer.filters[0],p=this.root?Math.sqrt(this.root.worldTransform.a**2+this.root.worldTransform.b**2):1;f.strength=a*p,f.resolution=this.resolution,f.padding=Math.max(a*2*p,20)}else this.shadowContainer.filters=[];this.shadowContainer.visible=!0}else this.shadowContainer!=null&&(this.shadowContainer.visible=!1,this.shadowContainer.filters=[])}updateTransforms(){this.root!=null&&!this.destroyed&&this.applySpriteTransforms()}getSprite(){return this.pixiSprite}getRoot(){return this.root}destroy(){this.destroyed||(this.destroyed=!0,this.root!=null&&(this.root.parent&&this.root.parent.removeChild(this.root),this.root.destroy({children:!0}),this.root=null,this.pixiSprite=null),this.strokeGraphics!=null&&(this.strokeGraphics.destroy(),this.strokeGraphics=null),this.maskGraphics!=null&&(this.maskGraphics.destroy(),this.maskGraphics=null),this.shadowGraphics!=null&&(this.shadowGraphics.destroy(),this.shadowGraphics=null),this.shadowContainer!=null&&(this.shadowContainer.destroy({children:!0}),this.shadowContainer=null),this.texture!=null&&(this.texture.destroy(),this.texture=null))}}function Ys(i,e=!1){return i.toJSON(e)}async function Ki(i){let e,t=null;switch(i.type){case"Video":t=Me;break;case"Audio":t=Ke;break;case"Image":return e=await _i.fromObject(i),e;case"Text":t=gt;break;case"Caption":t=ei;break;case"Effect":t=ct;break;case"Transition":t=Lt;break;case"Placeholder":t=mn;break}if(t&&typeof t.fromObject=="function")return await t.fromObject(i);switch(i.type){case"Video":{const s=await fetch(i.src);if(!s.ok)throw new Error(`Failed to fetch video from ${i.src}: ${s.status} ${s.statusText}. Make sure the file exists in the public directory.`);const r=i.audio!==void 0?{audio:i.audio,volume:i.volume}:{volume:i.volume};e=new Me(s.body,r,i.src);break}case"Audio":{if(!i.src||i.src.trim()==="")throw new Error("Audio requires a valid source URL");const s={};i.loop!==void 0&&(s.loop=i.loop),i.volume!==void 0&&(s.volume=i.volume),e=await Ke.fromUrl(i.src,s);break}case"Text":{const s=i.text||"",r=i.style||{},n={fontSize:r.fontSize,fontFamily:r.fontFamily,fontWeight:r.fontWeight,fontStyle:r.fontStyle,fill:r.color,align:r.align};r.stroke&&(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width),r.shadow&&(n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:r.shadow.distance,angle:r.shadow.angle}),e=new gt(s,n);break}case"Caption":{const s=i.text||"",r=i.style||{},n={fontSize:r.fontSize,fontFamily:r.fontFamily,fontWeight:r.fontWeight,fontStyle:r.fontStyle,fill:r.color,align:r.align};if(r.fontUrl!==void 0?n.fontUrl=r.fontUrl:i.fontUrl!==void 0&&(n.fontUrl=i.fontUrl),r.stroke&&(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width),r.shadow&&(n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:r.shadow.distance,angle:r.shadow.angle}),i.caption){const o=i.caption;o.words&&(n.words=o.words),o.colors&&(o.colors.appeared!==void 0&&(n.appearedColor=o.colors.appeared),o.colors.active!==void 0&&(n.activeColor=o.colors.active),o.colors.activeFill!==void 0&&(n.activeFillColor=o.colors.activeFill),o.colors.background!==void 0&&(n.backgroundColor=o.colors.background),o.colors.keyword!==void 0&&(n.isKeyWordColor=o.colors.keyword)),o.preserveKeywordColor!==void 0&&(n.preservedColorKeyWord=o.preserveKeywordColor),o.positioning&&(o.positioning.bottomOffset!==void 0&&(n.bottomOffset=o.positioning.bottomOffset),o.positioning.videoWidth!==void 0&&(n.videoWidth=o.positioning.videoWidth),o.positioning.videoHeight!==void 0&&(n.videoHeight=o.positioning.videoHeight))}else i.bottomOffset!==void 0&&(n.bottomOffset=i.bottomOffset),i.words&&(n.words=i.words),i.appearedColor!==void 0&&(n.appearedColor=i.appearedColor),i.activeColor!==void 0&&(n.activeColor=i.activeColor),i.activeFillColor!==void 0&&(n.activeFillColor=i.activeFillColor),i.backgroundColor!==void 0&&(n.backgroundColor=i.backgroundColor),i.isKeyWordColor!==void 0&&(n.isKeyWordColor=i.isKeyWordColor),i.preservedColorKeyWord!==void 0&&(n.preservedColorKeyWord=i.preservedColorKeyWord),i.videoWidth!==void 0&&(n.videoWidth=i.videoWidth),i.videoHeight!==void 0&&(n.videoHeight=i.videoHeight);i.mediaId&&(n.mediaId=i.mediaId),e=new ei(s,n);break}case"Effect":{e=new ct(i.effect.key),e.effect=i.effect;break}default:throw new Error(`Unsupported clip type: ${i.type}`)}return e.left=i.left,e.top=i.top,e.width=i.width,e.height=i.height,e.angle=i.angle,e.display.from=i.display.from,e.display.to=i.display.to,e.duration=i.duration,e.playbackRate=i.playbackRate,e.zIndex=i.zIndex,e.opacity=i.opacity,e.flip=i.flip,i.style&&(e.style={...e.style,...i.style}),i.animation&&e.setAnimation(i.animation.keyFrames,i.animation.opts),i.id&&(e.id=i.id),i.effects&&(e.effects=i.effects),i.trim&&(e.trim.from=i.trim.from<1e6?i.trim.from*1e6:i.trim.from,e.trim.to=i.trim.to<1e6?i.trim.to*1e6:i.trim.to),e}var rf,G_;function iM(){return G_||(G_=1,rf=[{name:"Bounce",paramsTypes:{shadow_colour:"vec4",shadow_height:"float",bounces:"float"},defaultParams:{shadow_colour:[0,0,0,.6],shadow_height:.075,bounces:3},glsl:`// Author: Adrian Purser
|
|
4357
4357
|
// License: MIT
|
|
4358
4358
|
|
|
4359
4359
|
uniform vec4 shadow_colour; // = vec4(0.,0.,0.,.6)
|
|
@@ -6921,7 +6921,7 @@ vec4 transition (vec2 p) {
|
|
|
6921
6921
|
float a = (1.0 - step(progress, 0.0)) * step(squaremin.x, squarep.x) * step(squaremin.y, squarep.y) * step(squarep.x, squaremax.x) * step(squarep.y, squaremax.y);
|
|
6922
6922
|
return mix(getFromColor(p), getToColor(p), a);
|
|
6923
6923
|
}
|
|
6924
|
-
`,gM={squares:{value:[10,10],type:"vec2<i32>"},direction:{value:[1,-.5],type:"vec2<f32>"},smoothness:{value:1.6,type:"f32"}},
|
|
6924
|
+
`,gM={squares:{value:[10,10],type:"vec2<i32>"},direction:{value:[1,-.5],type:"vec2<f32>"},smoothness:{value:1.6,type:"f32"}},xM=`
|
|
6925
6925
|
#define PI 3.14159265359
|
|
6926
6926
|
|
|
6927
6927
|
uniform float rotations;
|
|
@@ -6949,7 +6949,7 @@ vec4 transition (vec2 uv) {
|
|
|
6949
6949
|
|
|
6950
6950
|
return mix(getFromColor(rotatedUv), getToColor(rotatedUv), progress);
|
|
6951
6951
|
}
|
|
6952
|
-
`,
|
|
6952
|
+
`,_M={center:{value:[.5,.5],type:"vec2<f32>"},rotations:{value:1,type:"f32"},scale:{value:8,type:"f32"},backColor:{value:[.15,.15,.15,1],type:"vec4<f32>"}},yM=`
|
|
6953
6953
|
uniform ivec2 size;
|
|
6954
6954
|
uniform float smoothness;
|
|
6955
6955
|
|
|
@@ -7347,7 +7347,7 @@ vec4 transition (vec2 uv) {
|
|
|
7347
7347
|
float m = smoothstep(-smoothness, 0.0, SQRT_2*distance(center, uv) - x*(1.0+smoothness));
|
|
7348
7348
|
return mix(getFromColor(uv), getToColor(uv), opening > 0.5 ? 1.0 - m : m);
|
|
7349
7349
|
}
|
|
7350
|
-
`,
|
|
7350
|
+
`,z_={smoothness:{value:.3,type:"f32"},opening:{value:1,type:"f32"}},VM=`
|
|
7351
7351
|
vec4 transition (vec2 uv) {
|
|
7352
7352
|
if(progress == 0.0){
|
|
7353
7353
|
return getFromColor(uv);
|
|
@@ -7788,4 +7788,4 @@ vec4 transition(vec2 uv) {
|
|
|
7788
7788
|
bool nextImage = distance(fract(uv * dots), vec2(0.5, 0.5)) < ( progress / distance(uv, center));
|
|
7789
7789
|
return nextImage ? getToColor(uv) : getFromColor(uv);
|
|
7790
7790
|
}
|
|
7791
|
-
`,tk={radialSwipe:{label:"Radial Swipe",fragment:aM}},Zi={...ji.reduce((i,e)=>(i[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:`transition: ${e.name}`},i),{}),...tk},ik=Object.entries(Zi).map(([i,e])=>({key:i,label:e.label,previewStatic:`https://cdn.subgen.co/previews/static/transition_${i}_static.webp`,previewDynamic:`https://cdn.subgen.co/previews/dynamic/transition_${i}_dynamic.webp`}));function nf({name:i,renderer:e}){let t=ji.find(N=>N.name===i);if(!t){const N=Object.keys(Zi).find(q=>q.toLowerCase()===i.toLowerCase());N&&(t=Zi[N])}if(t||(t=ji.find(N=>N.name.toLowerCase()===i.toLowerCase())),!t){const N=[i,i.toLowerCase(),i.charAt(0).toUpperCase()+i.slice(1).toLowerCase(),i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),i.replace(/_/g,"")];for(const q of N){if(t=ji.find(Ie=>Ie.name.toLowerCase()===q.toLowerCase()),t)break;const me=Object.keys(Zi).find(Ie=>Ie.toLowerCase()===q.toLowerCase());if(me){t=Zi[me];break}}}if(!t){const N=ji.length,q=ji.slice(0,5).map(Ie=>Ie.name).join(", "),me=Object.keys(Zi).slice(0,3).join(", ");throw console.error(`Transition not found: "${i}". Available in gl-transitions (${N} total):`,q+"..."),console.error("Available locally:",me+"..."),new Error(`Transition "${i}" not found in gl-transitions library or local definitions`)}const s=new Ue(M.WHITE),r=Ge.create({width:e.width,height:e.height}),n=new Ct({}),o=new Ct({}),a=t.name==="displacement"||i.toLowerCase()==="displacement"||t.label==="displacement",l=a?new Ct({}):void 0;let c=null;if(a){c=document.createElement("canvas"),c.width=256,c.height=256;const N=c.getContext("2d");if(N){const q=N.createImageData(256,256);for(let me=0;me<q.data.length;me+=4){const Ie=Math.random();q.data[me]=Ie*255,q.data[me+1]=Ie*255,q.data[me+2]=Ie*255,q.data[me+3]=255}N.putImageData(q,0,0)}}let h=t.glsl||t.fragment;if(!h)throw new Error(`Transition "${i}" has no glsl or fragment code`);let u={...de.basics,...de.custom(t)};Object.entries(u).forEach(([,N])=>{N.type==="int<f32>"&&(N.type="i32",typeof N.value=="number"&&(N.value=Math.trunc(N.value))),N.type==="ivec2<f32>"&&(N.type="vec2<f32>")});const d=t.name==="GridFlip"||i.toLowerCase()==="gridflip"||t.label==="gridflip",f=t.name==="circle"||i.toLowerCase()==="circle"||t.label==="circle",p=t.name==="directional"||i.toLowerCase()==="directional"||t.label==="directional",g=t.name==="UndulatingBurnOut"||i.toLowerCase()==="undulatingburnout"||t.label==="undulatingBurnOut",m=t.name==="SquaresWire"||i.toLowerCase()==="squareswire"||t.label==="squaresWire",_=t.name==="rotate_scale_fade"||i.toLowerCase()==="rotatescalefade"||t.label==="rotateScaleFade",x=t.name==="RandomSquares"||i.toLowerCase()==="randomsquares"||t.label==="randomSquares",y=t.name==="polar_function"||i.toLowerCase()==="polar_function"||t.label==="polar_function",v=t.name==="pixelate"||i.toLowerCase()==="pixelate"||t.label==="pixelate",T=t.name==="perlin"||i.toLowerCase()==="perlin"||t.label==="perlin",S=t.name==="luma"||i.toLowerCase()==="luma"||t.label==="luma",w=t.name==="luminance_melt"||i.toLowerCase()==="luminance_melt"||i.toLowerCase()==="luminancemelt"||t.label==="luminance_melt",E=t.name==="hexagonalize"||i.toLowerCase()==="hexagonalize"||t.label==="hexagonalize",P=t.name==="heart"||i.toLowerCase()==="heart"||t.label==="heart",C=t.name==="displacement"||i.toLowerCase()==="displacement"||t.label==="displacement",A=t.name==="directionalwipe"||i.toLowerCase()==="directionalwipe"||i.toLowerCase()==="directional_wipe"||t.label==="directionalwipe",U=t.name==="directionalwarp"||i.toLowerCase()==="directionalwarp"||i.toLowerCase()==="directional_warp"||t.label==="directionalwarp",D=t.name==="crosshatch"||i.toLowerCase()==="crosshatch"||t.label==="crosshatch",$=t.name==="circleopen"||i.toLowerCase()==="circleopen"||i.toLowerCase()==="circle_open"||t.label==="circleopen",pe=t.name==="cannabisleaf"||i.toLowerCase()==="cannabisleaf"||i.toLowerCase()==="cannabis_leaf"||t.label==="cannabisleaf",k=t.name==="StereoViewer"||i.toLowerCase()==="stereoviewer"||i.toLowerCase()==="stereo_viewer"||t.label==="StereoViewer",F=t.name==="GlitchDisplace"||i.toLowerCase()==="glitchDisplace"||t.label==="GlitchDisplace",ne=t.name==="CrossZoom"||i.toLowerCase()==="crosszoom"||t.label==="CrossZoom",G=t.name==="CrazyParametricFun"||i.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",ie=t.name==="BowTieHorizontal"||i.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",we=t.name==="PolkaDotsCurtain"||i.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",ce=t.name==="Pixelize"||i.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(h=lM,u={...de.basics,...cM}),f&&(h=hM,u={...de.basics,...zx}),p&&(h=uM,u={...de.basics,...dM}),g&&(h=fM,u={...de.basics,...pM}),m&&(h=mM,u={...de.basics,...gM}),_&&(h=_M,u={...de.basics,...xM}),x&&(h=yM,u={...de.basics,...vM}),y&&(h=bM,u={...de.basics,...TM}),v&&(h=Ox,u={...de.basics,...Dx}),T&&(h=CM,u={...de.basics,...AM}),S&&(h=EM,u={...de.basics,...IM}),w&&(h=PM,u={...de.basics,...RM}),E&&(h=MM,u={...de.basics,...kM}),P&&(h=FM,u={...de.basics,...BM}),C&&(h=UM,u={...de.basics,...OM}),A&&(h=DM,u={...de.basics,...GM}),U&&(h=zM,u={...de.basics,...NM}),D&&(h=LM,u={...de.basics,...HM}),$&&(h=WM,u={...de.basics,...zx}),pe&&(h=VM,u={...de.basics,...$M}),k&&(h=XM,u={...de.basics,...YM}),F&&(h=qM),ne&&(h=KM,u={...de.basics,...jM}),G&&(h=ZM,u={...de.basics,...JM}),ie&&(h=QM),we&&(h=ek),ce&&(h=wM,u={...de.basics,...SM});const Ce={from:n,to:o,uniforms:u};a&&l&&(Ce.displacementMap=l,c&&(l.resource=c,l.update()));const Oe=new Gi({glProgram:new At({vertex:rM,fragment:oM(h)}),resources:Ce});return s.filters=[Oe],{render({width:N,height:q,from:me,to:Ie,progress:Qi}){if((s.width!==N||s.height!==q)&&(s.setSize({width:N,height:q}),r.resize(N,q)),me instanceof M?Oe.resources.from=me.source:(n.resource=me,n.update(),Oe.resources.from=n),Ie instanceof M?Oe.resources.to=Ie.source:(o.resource=Ie,o.update(),Oe.resources.to=o),a&&l&&c){if(c.width!==N||c.height!==q){c.width=N,c.height=q;const ti=c.getContext("2d");if(ti){const Et=ti.createImageData(N,q);for(let qe=0;qe<Et.data.length;qe+=4){const _t=Math.random();Et.data[qe]=_t*255,Et.data[qe+1]=_t*255,Et.data[qe+2]=_t*255,Et.data[qe+3]=255}ti.putImageData(Et,0,0)}}l.resource=c,l.update()}return Oe.resources.uniforms.uniforms.progress=Qi,e.render({container:s,target:r,clear:!1,width:N,height:q}),r},destroy(){r.destroy(),s.destroy({children:!0})}}}let sk=0;async function Nx(i){i()>50&&(await jh(15),await Nx(i))}class rk extends Zh{static async isSupported(e={}){return(self.OffscreenCanvas!=null&&self.VideoEncoder!=null&&self.VideoDecoder!=null&&self.VideoFrame!=null&&self.AudioEncoder!=null&&self.AudioDecoder!=null&&self.AudioData!=null&&((await self.VideoEncoder.isConfigSupported({codec:e.videoCodec??"avc1.42E032",width:e.width??1920,height:e.height??1080,bitrate:e.bitrate??7e6})).supported??!1)&&(await self.AudioEncoder.isConfigSupported({codec:(await Bp()).codec,sampleRate:le.sampleRate,numberOfChannels:le.channelCount})).supported)??!1}logger=K.create(`id:${sk++},`);destroyed=!1;sprites=[];canvas;pixiApp=null;stopOutput=null;opts;hasVideoTrack;constructor(e={}){super();const{width:t=0,height:s=0}=e;this.canvas=new OffscreenCanvas(t,s),this.opts=Object.assign({bgColor:"#000",width:0,height:0,videoCodec:"avc1.42E032",audio:!0,bitrate:5e6,fps:30,metaDataTags:null},e),this.hasVideoTrack=t*s>0,Bp().catch(r=>{this.logger.warn("Failed to detect audio codec:",r)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new Lu,await this.pixiApp.init({canvas:this.canvas,width:e,height:t,backgroundColor:0,antialias:!1,autoDensity:!1,resolution:1,preference:"webgl"}),this.pixiApp.renderer==null||this.pixiApp.stage==null)throw new Error("Pixi.js Application failed to initialize properly");try{const s=this.pixiApp;s.ticker&&typeof s.ticker.stop=="function"&&s.ticker.stop()}catch{}}async addSprite(e,t={}){const s={rect:{x:e.left,y:e.top,w:e.width,h:e.height},display:{...e.display},duration:e.duration,playbackRate:e.playbackRate,zIndex:e.zIndex};this.logger.info("Compositor add clip",s);const r=await e.clone();this.pixiApp!=null&&this.pixiApp.renderer!=null&&typeof r.setRenderer=="function"&&r.setRenderer(this.pixiApp.renderer),this.logger.info("Compositor add clip ready"),this.sprites.push(Object.assign(r,{main:t.main??!1,expired:!1})),this.sprites.sort((n,o)=>n.zIndex-o.zIndex)}initMuxer(e){const{fps:t,width:s,height:r,videoCodec:n,bitrate:o,audio:a,metaDataTags:l}=this.opts,c=this.sprites.some(d=>d.width>0&&d.height>0),h=this.hasVideoTrack&&c;return Bw({video:h?{width:s,height:r,expectFPS:t,codec:n,bitrate:o,__unsafe_hardwareAcceleration__:this.opts.__unsafe_hardwareAcceleration__}:null,audio:a===!1?null:{codec:le.codecType,sampleRate:le.sampleRate,channelCount:le.channelCount},duration:e,metaDataTags:l})}output(e={}){if(this.sprites.length===0)throw Error("No sprite added");const t=this.sprites.find(u=>u.main),r=this.sprites.map(u=>u.display.from+u.duration).filter(u=>u!==1/0),n=e.maxTime??(t!=null?t.display.from+t.duration:r.length>0?Math.max(...r):1/0);if(n===1/0||n<=0)throw Error("Unable to determine the end time, please specify a main sprite, or limit the duration of Image, Audio");n===-1&&this.logger.warn("Unable to determine the end time, process value don't update"),this.logger.info(`start combinate video, maxTime:${n}`);const o=this.initMuxer(n);let a=performance.now();const l=this.runEncoding(o,n,{onProgress:u=>{this.logger.debug("OutputProgress:",u),this.emit("OutputProgress",u)},onEnded:async()=>{await o.flush(),this.logger.info("===== output ended =====, cost:",performance.now()-a),this.emit("OutputProgress",1),this.destroy()},onError:u=>{this.emit("error",u),h(u),this.destroy()}});this.stopOutput=()=>{l(),o.close(),h()};const{stream:c,stop:h}=Fx(o.mp4file,500,this.destroy);return c}destroy(){if(!this.destroyed&&(this.destroyed=!0,this.stopOutput?.(),this.off("OutputProgress"),this.off("error"),this.pixiApp!=null))try{const e=this.pixiApp;if(e.destroyed===!0){this.pixiApp=null;return}if(e.ticker&&typeof e.ticker.stop=="function")try{e.ticker.stop()}catch{}if(e.renderer!=null){const t=e.renderer.gl;if(t&&t.isContextLost()){this.pixiApp=null;return}this.pixiApp.destroy()}}catch(e){console.warn("Error while destroying Pixi application:",e)}finally{this.pixiApp=null}}runEncoding(e,t,{onProgress:s,onEnded:r,onError:n}){let o=0;const a={aborted:!1};let l=null,c=null;const h=async()=>{const{fps:f,bgColor:p,audio:g}=this.opts,m=Math.round(1e6/f),_=this.sprites.some(v=>v.width>0&&v.height>0);c=nk({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const x=ok({muxer:e,canvas:this.canvas,outputAudio:g,hasVideoTrack:this.hasVideoTrack&&_,timeSlice:m,fps:f});let y=0;for(;;){if(l!=null)return;if(a.aborted||t!==-1&&y>t||this.sprites.length===0){u(),await r();return}o=y/t;const{audios:v,mainSprDone:T,hasVideo:S}=await c.render(y);if(T){u(),await r();return}if(a.aborted)return;this.hasVideoTrack&&S&&await new Promise(w=>requestAnimationFrame(w)),x(y,v,S),y+=m,await Nx(e.getEncodeQueueSize)}},u=()=>{a.aborted||(a.aborted=!0,clearInterval(d),c?.cleanup(),this.sprites.forEach(f=>{f.destroy()}))};h().catch(f=>{l=f,this.logger.error(f),u(),n(f)});const d=setInterval(()=>{s(o)},500);return u}exportToJSON(){const e=this.sprites.map(s=>Ys(s,s.main)),t=[];return this.sprites.forEach(s=>{if(s.transition){const r=this.sprites.filter(n=>n.id!==s.id&&n.zIndex===s.zIndex&&n.display.from<s.display.from&&(n instanceof Me||n instanceof xi)).sort((n,o)=>o.display.to-n.display.to)[0];r&&t.push({key:s.transition.name,duration:s.transition.duration,clips:[r.id,s.id]})}}),{clips:e,settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor,videoCodec:this.opts.videoCodec,bitrate:this.opts.bitrate,audio:this.opts.audio,metaDataTags:this.opts.metaDataTags}}}async loadFromJSON(e){this.sprites.forEach(t=>{t.destroy()}),this.sprites=[],e.settings&&(e.settings.width!==void 0&&(this.opts.width=e.settings.width),e.settings.height!==void 0&&(this.opts.height=e.settings.height),e.settings.fps!==void 0&&(this.opts.fps=e.settings.fps),e.settings.bgColor!==void 0&&(this.opts.bgColor=e.settings.bgColor),e.settings.videoCodec!==void 0&&(this.opts.videoCodec=e.settings.videoCodec),e.settings.bitrate!==void 0&&(this.opts.bitrate=e.settings.bitrate),e.settings.audio!==void 0&&(this.opts.audio=e.settings.audio===!1?!1:void 0),e.settings.metaDataTags!==void 0&&(this.opts.metaDataTags=e.settings.metaDataTags));for(const t of e.clips){const s=await Ki(t);if(await this.addSprite(s,{main:t.main||!1}),t.type==="Transition"){const r=t.toClipId,n=this.sprites.find(o=>o.id===r);n?n.transition={name:t.transitionEffect.key,duration:t.duration,prevClipId:t.fromClipId||""}:console.warn(`[Compositor] Could not find target clip ${r} for transition ${t.transitionEffect.key}`)}}}}function nk(i){const{pixiApp:e,sprites:t,aborter:s}=i,r=e!=null,n=new Map,o=new Map,a=new Map,l=Ge.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),c=Ge.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),h=new _e().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),u=new Map,d=T=>t.filter(S=>S.id!==T.id&&S.zIndex===T.zIndex&&S.display.from<T.display.from&&(S instanceof Me||S instanceof xi)).sort((S,w)=>w.display.to-S.display.to)[0]||null,f=async(T,S,w)=>{let E=null;if(T.transition?.prevClipId&&(E=t.find(U=>U.id===T.transition.prevClipId)||null),E||(E=d(T)),!E)return null;const P=E.duration>0?E.duration:0,C=Math.max(0,Math.min(S-E.display.from,P)),{video:A}=await w(E,C);return A},p=(T,S,w)=>{if(!e)return;e.renderer.render({container:h,target:w,clear:!0});const E=new Ue(S instanceof M?S:M.from(S));E.x=T.center.x,E.y=T.center.y,E.anchor.set(.5,.5);const P=E.texture.width||1,C=E.texture.height||1,A=T.width&&T.width!==0?Math.abs(T.width)/P:1,U=T.height&&T.height!==0?Math.abs(T.height)/C:1;T.flip==="horizontal"?(E.scale.x=-A,E.scale.y=U):T.flip==="vertical"?(E.scale.x=A,E.scale.y=-U):(E.scale.x=A,E.scale.y=U),E.rotation=(T.flip==null?1:-1)*T.angle,E.alpha=T.opacity;const D=T.style||{},$=D.borderRadius||0;let pe=null;$>0&&(pe=new _e,pe.roundRect(-P/2,-C/2,P,C,Math.min($,P/2,C/2)),pe.fill({color:16777215,alpha:1}),E.addChild(pe),E.mask=pe);const k=D.stroke;let F=null;if(k&&k.width>0){F=new _e;const ie=Te(k.color)??16777215,we=k.width;if(F.setStrokeStyle({width:we,color:ie,alignment:1}),$>0){const ce=Math.min($,P/2,C/2);F.roundRect(-P/2,-C/2,P,C,ce)}else F.rect(-P/2,-C/2,P,C);F.stroke(),E.addChild(F)}const ne=D.dropShadow;let G=null;if(ne&&(ne.blur>0||ne.distance>0)){G=new _e;const ie=Te(ne.color)??0,we=ne.alpha??.5,ce=ne.distance??0,Ce=ne.angle??0,Oe=Math.cos(Ce)*ce,N=Math.sin(Ce)*ce;if($>0){const q=Math.min($,P/2,C/2);G.roundRect(-P/2+Oe,-C/2+N,P,C,q)}else G.rect(-P/2+Oe,-C/2+N,P,C);G.fill({color:ie,alpha:we}),E.addChildAt(G,0)}e.renderer.render({container:E,target:w,clear:!1}),S instanceof M||E.texture.destroy(!0),F&&F.destroy(),pe&&pe.destroy(),G&&G.destroy(),E.destroy()};let g=null,m=null,_=null;r&&e!=null&&(g=new re,m=new re,_=new re,m.sortableChildren=!0,_.sortableChildren=!0,e.stage.addChild(m),e.stage.addChild(_),g.visible=!1,e.stage.addChild(g));const x=[...t].sort((T,S)=>T.zIndex-S.zIndex);return{render:async T=>{const S=[];let w=!1,E=!1;const P=new Map,C=async(A,U)=>{const D=`${A.id}_${U}`;if(P.has(D))return P.get(D);const $=await A.getFrame(U);return P.set(D,$),$};for(const A of a.values())A.visible=!1;for(const A of x){if(s.aborted)break;if(T<A.display.from||A.expired){if(r&&e!=null){const F=n.get(A);F&&await F.updateFrame(null)}continue}const U=T-A.display.from,D=U*A.playbackRate;A.animate(D);const{video:$,audio:pe,done:k}=await C(A,U);if(S.push(pe),r&&e!=null&&m!=null){if((A instanceof Me||A instanceof xi)&&A.transition&&U>=0&&U<=A.transition.duration){const G=await f(A,T,C),ie=$;if(G&&ie){const we=U/A.transition.duration,ce=d(A);ce?p(ce,G,l):e.renderer.render({container:h,target:l,clear:!0}),p(A,ie,c);let Ce=o.get(A.id);Ce||(Ce=nf({name:A.transition.name,renderer:e.renderer}),o.set(A.id,Ce));const Oe=Ce.render({width:e.renderer.width,height:e.renderer.height,from:l,to:c,progress:we});let N=a.get(A.id);N||(N=new Ue,N.label=`TransitionSprite_${A.id}`,a.set(A.id,N),m.addChild(N)),N.texture=Oe,N.visible=!0,N.x=0,N.y=0,N.width=e.renderer.width,N.height=e.renderer.height,N.anchor.set(0,0),N.zIndex=A.zIndex,E=!0;const q=n.get(A);if(q){const me=q.getRoot();me&&(me.visible=!1)}if(ce){const me=n.get(ce);if(me){const Ie=me.getRoot();Ie&&(Ie.visible=!1)}}continue}}let ne=n.get(A);ne==null&&$!=null&&(ne=new gn(e,A,m),n.set(A,ne)),ne!=null&&($!=null?(E=!0,await ne.updateFrame($)):await ne.updateFrame(null)),ne?.updateTransforms()}if(A.duration>0&&T>A.display.from+A.duration||k){if(A.main&&(w=!0),A.expired=!0,r){const F=n.get(A);if(F!=null){const ne=F.getRoot();ne&&(ne.visible=!1)}}}else if(r){const F=n.get(A);F?.updateTransforms()}}if(r&&e!=null&&g!=null&&m!=null&&_!=null){let A=null;for(const U of t)if(U instanceof ct&&T>=U.display.from&&T<U.display.from+U.duration){A={id:U.id,key:U.effect.key,startTime:U.display.from,duration:U.duration};break}if(!A)for(const U of t){if(U.effects&&U.effects.length>0){for(const D of U.effects)if(T>=D.startTime&&T<D.startTime+D.duration){A=D;break}}if(A)break}_.removeChildren();for(const U of n.values()){const D=U.getRoot();D&&D.parent!==m&&(D.parent&&D.parent.removeChild(D),m.addChild(D))}if(A){const{key:U,startTime:D,duration:$,id:pe}=A,k=T-D,F=$>0?Math.min(Math.max(k/$,0),1):0,ne=t.some(G=>G.id===pe&&G instanceof ct);for(const G of t){let ie=!1;if(ne?ie=G.id!==pe&&!(G instanceof ct):ie=!!G.effects&&G.effects.some(we=>we.id===pe),ie){const we=n.get(G);if(we){const ce=we.getRoot();ce&&(ce.parent&&ce.parent.removeChild(ce),g.addChild(ce))}}}if(g.children.length>0){let G=u.get(pe);if(!G)try{const ie=sf({name:U,renderer:e.renderer});ie&&ie.filter&&(G={filter:ie.filter,render:ie.render},u.set(pe,G))}catch(ie){console.warn("Failed to create effect",U,ie)}if(G){const{filter:ie,render:we}=G;ie.resources&&ie.resources.effectUniforms&&(ie.resources.effectUniforms.uniforms.uTime=F);const ce=e.renderer.width,Ce=e.renderer.height,Oe=Ge.create({width:ce,height:Ce});if(g.visible=!0,e.renderer.render({container:g,target:Oe,clear:!0}),g.visible=!1,we){const N=we({canvasTexture:Oe,progress:F,width:ce,height:Ce}),q=new Ue(N);q.width=ce,q.height=Ce,_.addChild(q)}}}}}return r&&e!=null&&e.render(),{audios:S,mainSprDone:w,hasVideo:E}},cleanup:()=>{l&&l.destroy(!0),c&&c.destroy(!0),h&&h.destroy(!0);for(const T of a.values())T.destroy();a.clear(),o.clear(),g&&g.destroy({children:!0}),m&&m.destroy({children:!0}),_&&_.destroy({children:!0}),n.forEach(T=>{T.destroy()}),n.clear()}}}function ok(i){const{canvas:e,outputAudio:t,muxer:s,hasVideoTrack:r,timeSlice:n}=i;let o=0;const a=Math.floor(3*i.fps),l=ak(1024);return(c,h,u)=>{if(t!==!1)for(const d of l(c,h))s.encodeAudio(d);if(r&&u)try{const d=new VideoFrame(e,{duration:n,timestamp:c});s.encodeVideo(d,{keyFrame:o%a===0}),o+=1}catch(d){console.warn("Failed to create VideoFrame from canvas, skipping frame:",d)}}}function ak(i){const e=i*le.channelCount,t=new Float32Array(e*3);let s=0,r=0;const n=i/le.sampleRate*1e6,o=new Float32Array(e),a=l=>{let c=0;const h=Math.floor(s/e),u=[];for(let d=0;d<h;d++)u.push(new AudioData({timestamp:r,numberOfChannels:le.channelCount,numberOfFrames:i,sampleRate:le.sampleRate,format:"f32",data:t.subarray(c,c+e)})),c+=e,r+=n;for(t.set(t.subarray(c,s),0),s-=c;l-r>n;)u.push(new AudioData({timestamp:r,numberOfChannels:le.channelCount,numberOfFrames:i,sampleRate:le.sampleRate,format:"f32",data:o})),r+=n;return u};return(l,c)=>{const h=Math.max(...c.map(u=>u[0]?.length??0));for(let u=0;u<h;u++){let d=0,f=0;for(let p=0;p<c.length;p++){const g=c[p][0]?.[u]??0,m=c[p][1]?.[u]??g;d+=g,f+=m}t[s]=d,t[s+1]=f,s+=2}return a(l)}}class lk extends _e{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(e,t=1){const r=1.5*t;this.clear(),this.setStrokeStyle({width:r,color:165063}).rect(e.x,e.y,e.width,e.height).stroke(),this.hitArea=e}}class Ht extends _e{#e=!1;handle;cursor;callbacks;constructor(e,t,s){super(),this.handle=e,this.cursor=t,this.callbacks=s,this.eventMode="static",this.#a(),this.on("pointerdown",this.#i),this.on("globalpointermove",this.#r),this.on("pointerup",this.#l),this.on("pointerupoutside",this.#l)}#a(){this.clear();const e=165063;if(this.handle==="rot")this.circle(0,0,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:13421772}),this.moveTo(0,-4),this.arc(0,0,4,-Math.PI/2,Math.PI,!1),this.stroke({width:1,color:0}),this.moveTo(0,-8),this.lineTo(-3,-5),this.lineTo(0,-2),this.stroke({width:1,color:0,cap:"round",join:"round"}),this.hitArea=new Zr(0,0,24);else if(["ml","mr","mt","mb"].includes(this.handle)){const t=this.handle==="ml"||this.handle==="mr",s=t?6:24,r=t?24:6;this.roundRect(-s/2,-r/2,s,r,3),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new H(-15,-15,30,30)}else this.rect(-4,-4,8,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new H(-15,-15,30,30)}#i=e=>{this.#e=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,e.global),e.stopPropagation()};#r=e=>{this.#e&&(this.callbacks.updateDrag(this.handle,e.global),e.stopPropagation())};#l=e=>{this.#e&&(this.#e=!1,this.cursor="pointer",this.callbacks.endDrag(),e.stopPropagation())}}const Lx={delta:new O};class ck extends re{group;wireframe=new lk;selectionOutlines=new _e;isDragging=!1;lastPointer=new X;activeHandle=null;#e;#a=new Map;#i=new X;#r=0;#l=0;#c=new H;#s=new X;#h=new H;#t=[new X,new X,new X,new X];#n=1;#o=1;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static";const t={beginDrag:(s,r)=>this.#v(s,r),updateDrag:(s,r)=>this.#b(s,r),endDrag:()=>this.#m()};this.#e={tl:new Ht("tl","nwse-resize",t),tr:new Ht("tr","nesw-resize",t),bl:new Ht("bl","nesw-resize",t),br:new Ht("br","nwse-resize",t),ml:new Ht("ml","ew-resize",t),mr:new Ht("mr","ew-resize",t),mt:new Ht("mt","ns-resize",t),mb:new Ht("mb","ns-resize",t),rot:new Ht("rot","crosshair",{beginDrag:(s,r)=>this.#w(r),updateDrag:(s,r)=>this.#S(r),endDrag:()=>this.#m()})},this.addChild(this.selectionOutlines,this.wireframe,...Object.values(this.#e)),this.#_(),this.visible=!1,Ze.shared.addOnce(()=>{!this.destroyed&&this.parent&&(this.#u(),this.visible=!0)})}#_(){this.on("pointerdown",this.#x),this.on("pointerup",this.#p),this.on("pointerupoutside",this.#p),this.on("globalpointermove",this.#y)}#u(){if(this.group.length===1){const e=this.group[0];this.#r=e.rotation;const t=this.#f(e);let s,r;this.opts.clip?(s=this.opts.clip.width,r=this.opts.clip.height):(s=t.width,r=t.height);const n=e.toGlobal(new X(0,0));this.#i.set(n.x,n.y),this.#h.copyFrom(new H(-s/2,-r/2,s,r))}else{let e=1/0,t=1/0,s=-1/0,r=-1/0;if(this.parent)for(const c of this.group){const h=this.#f(c);this.#t[0].set(h.x,h.y),this.#t[1].set(h.x+h.width,h.y),this.#t[2].set(h.x+h.width,h.y+h.height),this.#t[3].set(h.x,h.y+h.height);for(const u of this.#t)c.toGlobal(u,u),this.toLocal(u,void 0,u),e=Math.min(e,u.x),t=Math.min(t,u.y),s=Math.max(s,u.x),r=Math.max(r,u.y)}const n=s-e,o=r-t,a=e+n/2,l=t+o/2;if(this.#h.copyFrom(new H(-n/2,-o/2,n,o)),this.parent){const c=this.toGlobal(new X(a,l));this.#i.set(c.x,c.y)}}this.#d()}#f(e){const t=e.children.filter(l=>l.label!=="ShadowContainer");if(t.length===0){const l=e.getLocalBounds();return new H(l.minX,l.minY,l.maxX-l.minX,l.maxY-l.minY)}const s=t.find(l=>l.label==="MainSprite");if(s){const l=s.getLocalBounds(),c=s.localTransform,h=c.apply(new X(l.x,l.y)),u=c.apply(new X(l.x+l.width,l.y)),d=c.apply(new X(l.x+l.width,l.y+l.height)),f=c.apply(new X(l.x,l.y+l.height)),p=Math.min(h.x,u.x,d.x,f.x),g=Math.max(h.x,u.x,d.x,f.x),m=Math.min(h.y,u.y,d.y,f.y),_=Math.max(h.y,u.y,d.y,f.y);return new H(p,m,g-p,_-m)}let r=1/0,n=1/0,o=-1/0,a=-1/0;for(const l of t){const c=l.getBounds(),h=e.toLocal(new X(c.minX,c.minY)),u=e.toLocal(new X(c.maxX,c.maxY));r=Math.min(r,h.x,u.x),n=Math.min(n,h.y,u.y),o=Math.max(o,h.x,u.x),a=Math.max(a,h.y,u.y)}return new H(r,n,o-r,a-n)}updateBounds(){this.#u()}#x=e=>{this.#u(),this.isDragging=!0,this.lastPointer.copyFrom(e.global),this.cursor="grabbing"};#p=()=>{this.isDragging&&this.emit("transformEnd"),this.isDragging=!1,this.activeHandle=null,this.cursor="default"};#y=e=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const t=this.parent.toLocal(this.lastPointer),s=this.parent.toLocal(e.global),r=s.x-t.x,n=s.y-t.y;for(const l of this.group)l.x+=r,l.y+=n;const o=e.global.x-this.lastPointer.x,a=e.global.y-this.lastPointer.y;this.#i.x+=o,this.#i.y+=a,this.lastPointer.copyFrom(e.global),this.#d(),this.emit("transforming")};#v(e,t){this.#u(),this.isDragging=!0,this.activeHandle=e,this.#a.clear();for(const s of this.group)this.#a.set(s,s.localTransform.clone());this.rotation=this.#r,this.#c.copyFrom(this.#h),this.#A(e)}#b(e,t){this.#T(e,t)}async#T(e,t){const s=this.#s,r=this.#E(e,this.toLocal(t),s),n=r.width/this.#c.width,o=r.height/this.#c.height,a=this.toGlobal(s);if(this.opts.clip&&this.opts.clip.type==="Text"){const c=r.width;this.emit("textClipResize",{handle:e,newWidth:c,newHeight:r.height,pivotWorld:a,proposed:r,sx:n,sy:o})}else this.#g(this.#I(a,this.#r,n,o));this.#h.copyFrom(r),this.#d(),this.emit("transforming")}#w(e){this.#u(),this.isDragging=!0,this.activeHandle="rot",this.#a.clear();for(const t of this.group)this.#a.set(t,t.localTransform.clone());this.#l=Math.atan2(e.y-this.#i.y,e.x-this.#i.x)}#S(e){const s=Math.atan2(e.y-this.#i.y,e.x-this.#i.x)-this.#l,r=this.#r+s;this.#g(this.#P(this.#i,s)),this.rotation=r,this.#d(r),this.emit("transforming")}#m(){this.isDragging=!1,this.#r=this.rotation,this.activeHandle=null,this.#d(this.#r),this.emit("transformEnd")}#d(e=this.#r){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#i)),this.rotation=e;const s=1/((this.parent?Math.abs(this.parent.worldTransform.a):1)||1),r=this.#h;this.wireframe.draw(r,s);const n=r.x+r.width/2,o=r.y+r.height/2,a=this.opts.clip?.getVisibleHandles?.()??["tl","tr","bl","br","ml","mr","mt","mb","rot"],l=[this.#e.tl,this.#e.tr,this.#e.bl,this.#e.br,this.#e.ml,this.#e.mr,this.#e.mt,this.#e.mb,this.#e.rot];for(const c of l)c.scale.set(s);this.#e.tl.visible=a.includes("tl"),this.#e.tr.visible=a.includes("tr"),this.#e.bl.visible=a.includes("bl"),this.#e.br.visible=a.includes("br"),this.#e.ml.visible=a.includes("ml"),this.#e.mr.visible=a.includes("mr"),this.#e.mt.visible=a.includes("mt"),this.#e.mb.visible=a.includes("mb"),this.#e.rot.visible=a.includes("rot"),this.#e.tl.position.set(r.x,r.y),this.#e.tr.position.set(r.x+r.width,r.y),this.#e.bl.position.set(r.x,r.y+r.height),this.#e.br.position.set(r.x+r.width,r.y+r.height),this.#e.ml.position.set(r.x,o),this.#e.mr.position.set(r.x+r.width,o),this.#e.mt.position.set(n,r.y),this.#e.mb.position.set(n,r.y+r.height),this.#e.rot.position.set(n,r.y-30*s),this.#C(s)}#C(e){if(this.selectionOutlines.clear(),this.group.length<=1||!this.parent)return;const t={width:1*e,color:43775,alpha:1};for(const s of this.group){const r=this.#f(s);this.#t[0].set(r.x,r.y),this.#t[1].set(r.x+r.width,r.y),this.#t[2].set(r.x+r.width,r.y+r.height),this.#t[3].set(r.x,r.y+r.height);for(const n of this.#t)s.toGlobal(n,n),this.toLocal(n,void 0,n);this.selectionOutlines.moveTo(this.#t[0].x,this.#t[0].y).lineTo(this.#t[1].x,this.#t[1].y).lineTo(this.#t[2].x,this.#t[2].y).lineTo(this.#t[3].x,this.#t[3].y).closePath().stroke(t)}}#A(e){const t=this.#c;if(this.opts.centeredScaling){this.#s.set(t.x+t.width/2,t.y+t.height/2);return}e==="tl"?this.#s.set(t.x+t.width,t.y+t.height):e==="tr"?this.#s.set(t.x,t.y+t.height):e==="bl"?this.#s.set(t.x+t.width,t.y):e==="br"?this.#s.set(t.x,t.y):e==="ml"?this.#s.set(t.x+t.width,t.y+t.height/2):e==="mr"?this.#s.set(t.x,t.y+t.height/2):e==="mt"?this.#s.set(t.x+t.width/2,t.y+t.height):e==="mb"&&this.#s.set(t.x+t.width/2,t.y)}#E(e,t,s){if(this.opts.centeredScaling){const n=Math.max(this.#n,Math.abs(t.x-s.x)*2),o=Math.max(this.#o,Math.abs(t.y-s.y)*2);return new H(s.x-n/2,s.y-o/2,n,o)}if(e==="tl"){const n=Math.min(t.x,s.x-this.#n),o=Math.min(t.y,s.y-this.#o);return new H(n,o,s.x-n,s.y-o)}if(e==="tr"){const n=Math.max(t.x,s.x+this.#n),o=Math.min(t.y,s.y-this.#o);return new H(s.x,o,n-s.x,s.y-o)}if(e==="bl"){const n=Math.min(t.x,s.x-this.#n),o=Math.max(t.y,s.y+this.#o);return new H(n,s.y,s.x-n,o-s.y)}if(e==="br"){const n=Math.max(t.x,s.x+this.#n),o=Math.max(t.y,s.y+this.#o);return new H(s.x,s.y,n-s.x,o-s.y)}const r=this.#c;if(e==="ml"){const n=Math.min(t.x,s.x-this.#n);return new H(n,r.y,s.x-n,r.height)}if(e==="mr"){const n=Math.max(t.x,s.x+this.#n);return new H(s.x,r.y,n-s.x,r.height)}if(e==="mt"){const n=Math.min(t.y,s.y-this.#o);return new H(r.x,n,r.width,s.y-n)}if(e==="mb"){const n=Math.max(t.y,s.y+this.#o);return new H(r.x,s.y,r.width,n-s.y)}return new H(s.x,s.y,this.#n,this.#o)}#I(e,t,s,r){return Lx.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(s,r).rotate(t).translate(e.x,e.y)}#P(e,t){return Lx.delta.identity().translate(-e.x,-e.y).rotate(t).translate(e.x,e.y)}#g(e){for(const t of this.group){const s=this.#a.get(t),r=t.parent;if(!s||!r)continue;const n=r.worldTransform.clone().invert(),o=r.worldTransform.clone().append(s),a=e.clone().append(o),l=n.clone().append(a);t.setFromMatrix(l)}}}class hk{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new X;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;init(e,t){this.selectionGraphics=new _e,this.selectionGraphics.visible=!1,this.selectionGraphics.zIndex=1e3,t.addChild(this.selectionGraphics),e.stage.eventMode="static",e.stage.hitArea=e.screen,e.stage.on("pointerdown",s=>this.onStagePointerDown(s)),e.stage.on("globalpointermove",s=>this.onStagePointerMove(s)),e.stage.on("pointerup",()=>this.onStagePointerUp()),e.stage.on("pointerupoutside",()=>this.onStagePointerUp())}onStagePointerDown(e){e.target===this.studio.pixiApp?.stage&&(e.shiftKey||this.deselectClip(),this.isDragSelecting=!0,this.studio.artboard?.toLocal(e.global,void 0,this.dragSelectionStart),this.selectionGraphics&&(this.selectionGraphics.clear(),this.selectionGraphics.visible=!0))}onStagePointerMove(e){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const t=this.studio.artboard.toLocal(e.global),s=Math.min(this.dragSelectionStart.x,t.x),r=Math.min(this.dragSelectionStart.y,t.y),n=Math.abs(t.x-this.dragSelectionStart.x),o=Math.abs(t.y-this.dragSelectionStart.y);this.selectionGraphics.clear(),this.selectionGraphics.rect(s,r,n,o).fill({color:703971,alpha:.3}),this.selectionGraphics.rect(s,r,n,o).stroke({width:2,color:703971})}}onStagePointerUp(){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const e=this.selectionGraphics.getBounds(),t=[],s=new H(e.x,e.y,e.width,e.height);if(s.width>2||s.height>2){for(const r of this.studio.clips){const n=this.studio.spriteRenderers.get(r);if(!n)continue;const o=n.getRoot();if(!o||!o.visible)continue;const a=o.getBounds();s.x<a.x+a.width&&s.x+s.width>a.x&&s.y<a.y+a.height&&s.y+s.height>a.y&&t.push(r)}if(t.length>0)for(const r of t)this.selectClip(r,!0)}this.selectionGraphics.clear(),this.selectionGraphics.visible=!1,this.isDragSelecting=!1}}setupSpriteInteractivity(e){if(this.interactiveClips.has(e))return;const t=this.studio.spriteRenderers.get(e);if(t==null)return;const s=t.getRoot();s!=null&&(s.eventMode="static",s.cursor="pointer",s.on("pointerdown",r=>{const n=this.getTopmostClipAtPoint(r.global);n&&this.selectClip(n,r.shiftKey)}),this.interactiveClips.add(e))}getTopmostClipAtPoint(e){if(!this.studio.pixiApp)return null;let t=null,s=-1/0;for(const r of this.interactiveClips){const n=this.studio.spriteRenderers.get(r);if(!n)continue;const o=n.getRoot();if(!o||!o.visible)continue;const a=o.toLocal(e),l=o.getLocalBounds();a.x>=l.minX&&a.x<=l.maxX&&a.y>=l.minY&&a.y<=l.maxY&&r.zIndex>s&&(s=r.zIndex,t=r)}return t}selectClip(e,t=!1){if(!(this.studio.destroyed||this.studio.pixiApp==null)){if(t||this.deselectClip(),t&&this.selectedClips.has(e)){this.selectedClips.delete(e),this.recreateTransformer(),this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)});return}this.selectedClips.add(e),this.recreateTransformer(),t?this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)}):this.studio.emit("selection:created",{selected:Array.from(this.selectedClips)})}}selectClipsByIds(e){const t=this.studio.clips.filter(s=>e.includes(s.id));this.setSelection(t)}setSelection(e){if(!(this.studio.destroyed||this.studio.pixiApp==null)&&!(this.selectedClips.size===e.length&&e.every(t=>this.selectedClips.has(t)))){for(const t of this.selectedClips)this.syncSpriteToClipProperties(t);this.destroyTransformer(),this.selectedClips.clear();for(const t of e)this.selectedClips.add(t);this.selectedClips.size>0?(this.createTransformer(),this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)})):this.studio.emit("selection:cleared",{deselected:[]})}}deselectClip(){if(this.selectedClips.size>0)for(const t of this.selectedClips)this.syncSpriteToClipProperties(t);this.destroyTransformer();const e=Array.from(this.selectedClips);this.selectedClips.clear(),e.length>0&&this.studio.emit("selection:cleared",{deselected:e})}async move(e,t){if(this.selectedClips.size===0)return;const s=[];for(const r of this.selectedClips)s.push({id:r.id,updates:{left:(r.left??0)+e,top:(r.top??0)+t}});await this.studio.updateClips(s),this.activeTransformer&&this.activeTransformer.updateBounds()}clear(){this.deselectClip(),this.interactiveClips.clear()}recreateTransformer(){this.destroyTransformer(),this.selectedClips.size>0&&this.createTransformer()}destroyTransformer(){this.activeTransformer!=null&&(this.activeTransformer.parent!=null&&this.activeTransformer.parent.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null)}createTransformer(){if(this.studio.destroyed||this.studio.artboard==null||this.selectedClips.size===0)return;const e=[];let t=null;for(const r of this.selectedClips){const n=this.studio.spriteRenderers.get(r);if(n==null)continue;const o=n.getRoot();o!=null&&(e.push(o),this.selectedClips.size===1&&(t=r))}if(e.length===0){console.warn("Cannot create transformer: no sprites found");return}this.activeTransformer=new ck({group:e,clip:t});let s=null;this.activeTransformer.on("transforming",()=>{s===null&&(s=requestAnimationFrame(()=>{s=null,this.syncSelectedClipsTransformsRealtime()}))}),this.activeTransformer.on("textClipResize",r=>{this.textClipResizedWidth=r.newWidth,this.textClipResizeHandle=r.handle,this.textClipResizedSx=r.sx,this.textClipResizedSy=r.sy}),this.activeTransformer.on("transformEnd",async()=>{s!==null&&(cancelAnimationFrame(s),s=null),await this.syncSelectedClipsTransforms();for(const r of this.selectedClips)this.studio.emit("clip:updated",{clip:r})}),this.activeTransformer.on("pointerdown",r=>{const n=this.getTopmostClipAtPoint(r.global);n&&!this.selectedClips.has(n)&&(this.selectClip(n,r.shiftKey),r.stopPropagation())}),this.studio.artboard.addChild(this.activeTransformer)}async syncSelectedClipsTransformsRealtime(){if(!(this.selectedClips.size===0||this.activeTransformer==null)&&!this.isUpdatingTextRealtime){this.isUpdatingTextRealtime=!0;try{const e=this.activeTransformer.activeHandle;if(e!=="mr"&&e!=="ml")return;for(const t of this.selectedClips){if(!(t instanceof gt))continue;const s=this.studio.spriteRenderers.get(t);if(s==null)continue;const r=s.getRoot(),n=s.getSprite();if(r==null||n==null||n.texture==null)continue;const o=Math.abs(r.scale.x*n.scale.x);if(o===1)continue;const a=t.left,l=t.top,c=t.width,h=n.texture.width,u=o*h;await t.updateStyle({wordWrap:!0,wordWrapWidth:u});const d=await t.getTexture();d&&(await s.updateFrame(d),n.scale.set(1,1),r.scale.set(1,1),e==="ml"?t.left=a+c-t.width:t.left=a,t.top=l,r.x=t.left+t.width/2,r.y=t.top+t.height/2,this.activeTransformer.updateBounds())}}finally{this.isUpdatingTextRealtime=!1}}}async syncSelectedClipsTransforms(){if(!(this.selectedClips.size===0||this.activeTransformer==null)){for(const e of this.selectedClips){const t=this.studio.spriteRenderers.get(e);if(t==null)continue;const s=t.getRoot(),r=t.getSprite();if(s==null||r==null||r.texture==null)continue;const n=r.texture.width,o=r.texture.height,a=Math.abs(s.scale.x*r.scale.x)*n,l=Math.abs(s.scale.y*r.scale.y)*o,c=(e instanceof gt||e instanceof ei)&&this.textClipResizedWidth!==null?this.textClipResizedWidth:a,h=e.width,d=(e.style?.fontSize??16)*Math.max(this.textClipResizedSx||1,this.textClipResizedSy||1);let f=s.x;const p=s.y-l/2,g=s.x-c/2;if(e instanceof gt&&this.textClipResizedWidth!==null){const _={wordWrap:!0,wordWrapWidth:c};this.textClipResizeHandle==="mr"?(f=e.left+c/2,s.x=f):this.textClipResizeHandle==="ml"?(f=e.left+c/2-(c-h),s.x=f):["br","tr"].includes(this.textClipResizeHandle)?(f=e.left+c/2,_.fontSize=d):["bl","tl"].includes(this.textClipResizeHandle)&&(f=e.left+c/2-(c-h),_.fontSize=d),await e.updateStyle(_);const x=await e.getTexture();x&&(await t.updateFrame(x),e.width=c,e.height=x.height,this.textClipResizedWidth=null,e.left=f-e.width/2,e.top=s.y-e.height/2,r.scale.set(1,1),s.scale.set(1,1))}else{e.left=g,e.top=p,e.width=a,e.height=l;const _=e.flip==null?1:-1;e.angle=_*s.angle}}this.activeTransformer!=null&&this.activeTransformer.updateBounds();for(const e of this.selectedClips){const t=this.studio.spriteRenderers.get(e);t?.updateTransforms()}}}syncSpriteToClipProperties(e){const t=this.studio.spriteRenderers.get(e);if(t!=null){const s=t.getRoot(),r=t.getSprite();if(s!=null&&r!=null&&r.texture!=null){const n=r.texture.width,o=r.texture.height,a=Math.abs(s.scale.x*r.scale.x)*n,l=Math.abs(s.scale.y*r.scale.y)*o,c=s.x-a/2,h=s.y-l/2;e.left=c,e.top=h,e.width=a,e.height=l;const u=e.flip==null?1:-1;e.angle=u*s.angle,t.updateTransforms(),this.studio.emit("clip:updated",{clip:e})}}}async deleteSelected(){return this.studio.deleteSelected()}}class uk{constructor(e){this.studio=e}isPlaying=!1;currentTime=0;maxDuration=0;playStartTime=0;playStartTimestamp=0;rafId=null;playbackElements=new Map;setMaxDuration(e){this.maxDuration=e}async play(){if(!(this.isPlaying||this.studio.destroyed)){if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){console.warn("Cannot play: invalid duration",this.maxDuration);return}this.isPlaying||(this.isPlaying=!0),this.playStartTime=this.currentTime,this.playStartTimestamp=performance.now();for(const[e,{element:t}]of this.playbackElements.entries()){if(!(this.currentTime>=e.display.from&&(e.display.to===0||this.currentTime<=e.display.to))){this.isPlaybackCapable(e)&&e.pause(t);continue}const r=(this.currentTime-e.display.from)/1e6;this.isPlaybackCapable(e)&&await e.play(t,r)}this.renderLoop(),this.studio.emit("play",{isPlaying:!0})}}pause(){this.isPlaying=!1,this.rafId!=null&&(cancelAnimationFrame(this.rafId),this.rafId=null);for(const[e,{element:t}]of this.playbackElements.entries())this.isPlaybackCapable(e)&&e.pause(t);this.studio.emit("pause",{isPlaying:!1})}async stop(){this.pause(),await this.seek(0)}async seek(e){if(this.studio.destroyed)return;const t=this.isPlaying;this.playStartTime=Math.max(0,Math.min(e,this.maxDuration)),this.playStartTimestamp=performance.now(),this.currentTime=this.playStartTime;for(const[s,{element:r}]of this.playbackElements.entries()){if(!(this.currentTime>=s.display.from&&(s.display.to===0||this.currentTime<=s.display.to))){this.isPlaybackCapable(s)&&s.pause(r);continue}const o=(this.currentTime-s.display.from)/1e6;this.isPlaybackCapable(s)&&await s.seek(r,o)}if(await this.studio.updateFrame(this.currentTime),this.studio.emit("currentTime",{currentTime:this.currentTime}),t){this.isPlaying=!0;for(const[s,{element:r}]of this.playbackElements.entries()){if(!(this.currentTime>=s.display.from&&(s.display.to===0||this.currentTime<=s.display.to)))continue;const o=(this.currentTime-s.display.from)/1e6;this.isPlaybackCapable(s)&&await s.play(r,o)}}}async frameNext(){const t=1e6/(this.studio.opts.fps||30),s=Math.min(this.currentTime+t,this.maxDuration);await this.seek(s)}async framePrev(){const t=1e6/(this.studio.opts.fps||30),s=Math.max(0,this.currentTime-t);await this.seek(s)}async renderLoop(){if(!this.isPlaying||this.studio.destroyed||this.studio.pixiApp==null)return;if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){this.pause();return}const e=async()=>{if(!this.isPlaying||this.studio.destroyed||this.studio.pixiApp==null)return;if(this.currentTime>=this.maxDuration){this.currentTime=this.maxDuration,this.pause();return}const s=(performance.now()-this.playStartTimestamp)*1e3;this.currentTime=Math.min(this.playStartTime+s,this.maxDuration),this.studio.emit("currentTime",{currentTime:this.currentTime});try{await this.studio.updateFrame(this.currentTime)}catch(r){console.warn("Error updating frame:",r)}this.isPlaying&&(this.rafId=requestAnimationFrame(e))};e()}isPlaybackCapable(e){return"play"in e&&"pause"in e&&"seek"in e}}class Ji{static instance;fonts=new Map;constructor(){}static getInstance(){return Ji.instance||(Ji.instance=new Ji),Ji.instance}async addFont(e){if(!this.fonts.has(e.name))try{const s=await new FontFace(e.name,`url(${e.url})`).load();document.fonts.add(s),this.fonts.set(e.name,s)}catch(t){console.error(`Failed to load font ${e.name}:`,t)}}async loadFonts(e){await Promise.all(e.map(t=>this.addFont(t)))}removeFont(e){const t=this.fonts.get(e);t&&(document.fonts.delete(t),this.fonts.delete(e))}clear(){this.fonts.forEach(e=>{document.fonts.delete(e)}),this.fonts.clear()}getLoadedFonts(){return Array.from(this.fonts.keys())}}const Hx=Ji.getInstance();class dk{constructor(e){this.studio=e}tracks=[];clips=[];getTrackById(e){return this.tracks.find(t=>t.id===e)}getClipById(e){return this.clips.find(t=>t.id===e)}findTrackIdByClipId(e){for(const t of this.tracks)if(t.clipIds.includes(e))return t.id}getTrackIndex(e){return this.tracks.findIndex(t=>t.id===e)}addTrack(e){const t={id:e.id||`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:e.name,type:e.type,clipIds:[]};return this.tracks.push(t),this.studio.emit("track:added",{track:t}),t}async removeTrack(e){const t=this.tracks.findIndex(n=>n.id===e);if(t===-1)return;const r=[...this.tracks[t].clipIds];for(const n of r)await this.removeClipById(n);this.tracks.splice(t,1),this.studio.emit("track:removed",{trackId:e})}async addTransition(e,t=2e6,s,r){if(this.studio.destroyed)return;let n=null,o=null;if(console.log("[Studio] addTransition",{fromClipId:s,toClipId:r}),s&&r&&(n=this.getClipById(s)??null,o=this.getClipById(r)??null,console.log("[Studio] Found clips",{clipA:n,clipB:o})),!n||!o){console.warn("[Studio] Invalid fromClipId or toClipId",{fromClipId:s,toClipId:r});return}await Promise.all([n.ready,o.ready]);const a=t,l=o.display.from-a/2,c=l+a,h={key:e,name:e,duration:a,fromClipId:n.id,toClipId:o.id,start:Math.max(0,l),end:c},u=this.findTrackIdByClipId(o.id);if(u){const f=this.tracks.find(p=>p.id===u);if(f){const p=f.clipIds.map(g=>this.getClipById(g)).filter(g=>{if(!g||g.type!=="Transition")return!1;const m=g;return m.fromClipId===n.id&&m.toClipId===o.id});for(const g of p)await this.removeClip(g)}}this.studio.transitionRenderers.has(n.id)&&(this.studio.transitionRenderers.get(n.id)?.destroy(),this.studio.transitionRenderers.delete(n.id)),this.studio.transitionRenderers.has(o.id)&&(this.studio.transitionRenderers.get(o.id)?.destroy(),this.studio.transitionRenderers.delete(o.id)),n.transition={...h},o.transition={...h};const d=new Lt(e);d.duration=a,d.fromClipId=Math.max(0,l)===0?null:n.id,d.toClipId=o.id,d.fromClipId===null&&n&&(d.fromClipId=n.id),d.display.from=Math.max(0,l),d.display.to=c,await this.addClip(d,{trackId:u}),this.studio.seek(this.studio.currentTime)}async addClip(e,t){const s=Array.isArray(e)?e:[e];if(s.length===0)return;const{trackId:r,audioSource:n}=this.normalizeAddClipOptions(t);if(this.studio.destroyed)return;if(this.studio.pixiApp==null)throw new Error("Failed to initialize Pixi.js Application");const o=[];for(const a of s)await this.prepareClipForTimeline(a,r),o.push(a);await this.recalculateMaxDuration();for(const a of o)await this.setupClipVisuals(a,n);await this.studio.updateFrame(this.studio.currentTime),this.emitAddClipEvents(o,r)}normalizeAddClipOptions(e){let t,s;if(e&&(typeof e=="string"||e instanceof File||e instanceof Blob))t=e;else if(typeof e=="object"&&e!==null&&!("size"in e)){const r=e;t=r.audioSource,s=r.trackId}return{trackId:s,audioSource:t}}async prepareClipForTimeline(e,t){e.id||(e.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.includes(e)||this.clips.push(e),this.addClipToTrack(e,t);const s=async()=>{await this.studio.updateFrame(this.studio.currentTime);const r=this.studio.selection;r.activeTransformer!=null&&r.selectedClips.has(e)&&typeof r.activeTransformer.updateBounds=="function"&&r.activeTransformer.updateBounds()};e.on("propsChange",s),this.studio.clipListeners.set(e,s),this.studio.pixiApp!=null&&typeof e.setRenderer=="function"&&e.setRenderer(this.studio.pixiApp.renderer),await e.ready}addClipToTrack(e,t){if(t){const s=this.tracks.find(r=>r.id===t);if(s)s.clipIds.includes(e.id)||s.clipIds.push(e.id);else{const r={id:t,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(r),this.studio.emit("track:added",{track:r})}}else{const r={id:`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(r),this.studio.emit("track:added",{track:r})}}async setupClipVisuals(e,t){const s=this.studio.spriteRenderers.get(e);if(s){const n=this.studio.clipsNormalContainer,o=s.getRoot();o&&!o.parent&&n.addChild(o);return}const r=await e.ready;if(await this.setupPlaybackForClip(e,t),r.width>0&&r.height>0){const n=this.studio.clipsNormalContainer,o=e.type==="Video"&&this.isPlaybackCapable(e);if(!o||o&&e.tickInterceptor!=null){const a=new gn(this.studio.pixiApp,e,n);this.studio.spriteRenderers.set(e,a)}}this.studio.opts.interactivity&&this.studio.selection.setupSpriteInteractivity(e)}emitAddClipEvents(e,t){if(e.length!==0)if(e.length===1){const s=e[0],r=t||this.tracks.find(n=>n.clipIds.includes(s.id))?.id||"";this.studio.emit("clip:added",{clip:s,trackId:r})}else this.studio.emit("clips:added",{clips:e,trackId:t})}async removeClip(e,t={permanent:!0}){const{permanent:s}=t,r=this.clips.findIndex(h=>h===e);if(r===-1)return;if(e instanceof Lt){if(e.fromClipId){const h=this.getClipById(e.fromClipId);h&&"transition"in h&&delete h.transition}if(e.toClipId){const h=this.getClipById(e.toClipId);h&&"transition"in h&&delete h.transition}}this.studio.selection.selectedClips.has(e)&&this.studio.selection.deselectClip(),this.clips.splice(r,1);const n=[];for(const h of this.tracks){const u=h.clipIds.indexOf(e.id);u!==-1&&(h.clipIds.splice(u,1),n.push(h.id))}for(const h of n){const u=this.tracks.findIndex(d=>d.id===h);u!==-1&&this.tracks[u].clipIds.length===0&&(this.tracks.splice(u,1),this.studio.emit("track:removed",{trackId:h}))}this.studio.selection.interactiveClips.delete(e);const o=this.studio.clipListeners.get(e);o&&(e.off("propsChange",o),this.studio.clipListeners.delete(e));const a=this.studio.spriteRenderers.get(e);if(a!=null)if(s)a.destroy(),this.studio.spriteRenderers.delete(e);else{const h=a.getRoot();h&&h.parent&&h.parent.removeChild(h)}const l=this.studio.transport.playbackElements.get(e);l!=null&&s&&this.isPlaybackCapable(e)&&(e.cleanupPlayback(l.element,l.objectUrl),this.studio.transport.playbackElements.delete(e));const c=this.studio.videoSprites.get(e);c!=null&&this.studio.pixiApp!=null&&(c.parent&&c.parent.removeChild(c),s&&(c.destroy(),this.studio.videoSprites.delete(e))),await this.recalculateMaxDuration(),this.studio.emit("clip:removed",{clipId:e.id})}async removeClips(e,t={permanent:!0}){if(e.length!==0){for(const s of e){const r=this.clips.findIndex(c=>c===s);if(r===-1)continue;if(s instanceof Lt){if(s.fromClipId){const c=this.getClipById(s.fromClipId);c&&"transition"in c&&delete c.transition}if(s.toClipId){const c=this.getClipById(s.toClipId);c&&"transition"in c&&delete c.transition}}this.studio.selection.selectedClips.has(s)&&this.studio.selection.deselectClip(),this.clips.splice(r,1);for(const c of this.tracks){const h=c.clipIds.indexOf(s.id);h!==-1&&c.clipIds.splice(h,1)}this.studio.selection.interactiveClips.delete(s);const n=this.studio.clipListeners.get(s);n&&(s.off("propsChange",n),this.studio.clipListeners.delete(s));const o=this.studio.spriteRenderers.get(s);if(o!=null)if(t.permanent)o.destroy(),this.studio.spriteRenderers.delete(s);else{const c=o.getRoot();c&&c.parent&&c.parent.removeChild(c)}const a=this.studio.transport.playbackElements.get(s);a!=null&&t.permanent&&this.isPlaybackCapable(s)&&(s.cleanupPlayback(a.element,a.objectUrl),this.studio.transport.playbackElements.delete(s));const l=this.studio.videoSprites.get(s);l!=null&&this.studio.pixiApp!=null&&(l.parent&&l.parent.removeChild(l),t.permanent&&(l.destroy(),this.studio.videoSprites.delete(s)))}for(let s=this.tracks.length-1;s>=0;s--)if(this.tracks[s].clipIds.length===0){const r=this.tracks[s].id;this.tracks.splice(s,1),this.studio.emit("track:removed",{trackId:r})}await this.recalculateMaxDuration(),this.studio.emit("clips:removed",{clipIds:e.map(s=>s.id)})}}async removeClipById(e){const t=this.clips.find(s=>s.id===e);t&&await this.removeClip(t)}async updateClip(e,t){const s=this.clips.find(r=>r.id===e);s&&(await this.applyClipUpdate(s,t),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(s),this.studio.emit("clip:updated",{clip:s}))}async updateClips(e){const t=[];for(const{id:s,updates:r}of e){const n=this.clips.find(o=>o.id===s);n&&(await this.applyClipUpdate(n,r),t.push(n))}if(t.length!==0){await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime);for(const s of t)this.updateTransformer(s),this.studio.emit("clip:updated",{clip:s})}}async replaceClipsBySource(e,t){const s=this.clips.filter(r=>r.src===e);if(s.length!==0){this.studio.suspendRendering();for(const r of s){if(!this.clips.includes(r))continue;const n=this.findTrackIdByClipId(r.id);if(!n)continue;const o=this.getTrackById(n);if(!o)continue;const a=await t(r),l=async()=>{await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(a)};a.on("propsChange",l),this.studio.clipListeners.set(a,l),this.studio.pixiApp!=null&&typeof a.setRenderer=="function"&&a.setRenderer(this.studio.pixiApp.renderer),await a.ready;const c=this.clips.indexOf(r);c!==-1&&(this.clips[c]=a);const h=o.clipIds.indexOf(r.id);h!==-1&&(o.clipIds[h]=a.id),await this.setupClipVisuals(a);const u=this.studio.spriteRenderers.get(r);u&&(u.destroy(),this.studio.spriteRenderers.delete(r));const d=this.studio.videoSprites.get(r);d&&(d.parent&&d.parent.removeChild(d),d.destroy(),this.studio.videoSprites.delete(r));const f=this.studio.clipListeners.get(r);f&&(r.off("propsChange",f),this.studio.clipListeners.delete(r)),this.studio.selection.selectedClips.has(r)&&(this.studio.selection.selectedClips.delete(r),this.studio.selection.selectedClips.add(a)),this.studio.emit("clip:replaced",{oldClip:r,newClip:a,trackId:n})}await this.recalculateMaxDuration(),this.studio.resumeRendering(),await this.studio.updateFrame(this.studio.currentTime)}}async applyClipUpdate(e,t){if(e instanceof gt&&(await e.updateStyle(t),"style"in t&&delete t.style),Object.assign(e,t),t.display&&!t.duration?e.duration=t.display.to-t.display.from:t.duration&&(!t.display||!t.display.to)&&(e.display||(e.display={from:0,to:t.duration}),e.display.to=e.display.from+t.duration),t.display&&t.duration){const s=t.display.to-t.display.from;s!==t.duration&&(e.duration=s)}else e.display&&(e.display.to=e.display.from+e.duration)}updateTransformer(e){const t=this.studio.selection;t.selectedClips.has(e)&&t.activeTransformer&&t.activeTransformer.updateBounds()}exportToJSON(){const e=this.clips.map(r=>Ys(r,!1)),t=this.tracks.map(r=>({id:r.id,name:r.name,type:r.type,clipIds:[...r.clipIds]})),s=[];return this.clips.forEach(r=>{if(r.transition){const n=this.tracks.find(o=>o.clipIds.includes(r.id));if(n){const o=n.clipIds.indexOf(r.id);if(o>0){const a=n.clipIds[o-1];s.push({key:r.transition.name,duration:r.transition.duration,clips:[a,r.id]})}}}}),{tracks:t,clips:e,settings:{width:this.studio.opts.width,height:this.studio.opts.height,fps:this.studio.opts.fps,bgColor:this.studio.opts.bgColor}}}async loadFromJSON(e){if(await this.clear(),e.settings){const s=e.settings.width&&e.settings.width!==this.studio.opts.width||e.settings.height&&e.settings.height!==this.studio.opts.height;if(e.settings.width&&(this.studio.opts.width=e.settings.width),e.settings.height&&(this.studio.opts.height=e.settings.height),e.settings.fps&&(this.studio.opts.fps=e.settings.fps),e.settings.bgColor&&(this.studio.opts.bgColor=e.settings.bgColor),s&&this.studio.pixiApp!=null){const r=this.studio.opts.width,n=this.studio.opts.height;this.studio.pixiApp.renderer.resize(r,n),this.studio.opts.canvas&&(this.studio.opts.canvas.width=r,this.studio.opts.canvas.height=n)}}const t=[];if(e.clips){await this.ensureFontsForClips(e.clips);const s=new Map;if(e.tracks){for(const n of e.tracks)if(n.clipIds)for(const o of n.clipIds)s.set(o,n.id)}if(e.tracks)for(const n of e.tracks)this.tracks.push({id:n.id,name:n.name,type:n.type,clipIds:[]});for(const n of e.clips)t.push((async()=>{try{let o=n.id?s.get(n.id):void 0;if(n.type==="Transition"){const l=n,c=l.toClipId||l.fromClipId;c&&(o=s.get(c))}if(n.type!=="Text"&&n.type!=="Caption"&&n.type!=="Effect"&&n.type!=="Transition"&&(!n.src||n.src.trim()===""))return console.warn(`Skipping clip ${n.type} with empty source`,n),{clip:null};const a=await Ki(n);return(a.type==="Video"||a.type==="Image")&&(!n.width||!n.height)&&this.studio.opts.width&&this.studio.opts.height&&(typeof a.scaleToFit=="function"&&await a.scaleToFit(this.studio.opts.width,this.studio.opts.height),typeof a.centerInScene=="function"&&a.centerInScene(this.studio.opts.width,this.studio.opts.height)),{clip:a,intendedTrackId:o}}catch(o){return console.error(`Failed to load clip ${n.id||"unknown"}:`,o),{clip:null}}})());const r=await Promise.all(t);for(const{clip:n,intendedTrackId:o}of r)n&&(n.id||(n.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.push(n),this.addClipToTrack(n,o))}this.studio.pixiApp&&await Promise.all(this.clips.map(async s=>{const r=async()=>{await this.studio.updateFrame(this.studio.currentTime);const n=this.studio.selection;n.activeTransformer!=null&&n.selectedClips.has(s)&&typeof n.activeTransformer.updateBounds=="function"&&n.activeTransformer.updateBounds()};s.on("propsChange",r),this.studio.clipListeners.set(s,r),typeof s.setRenderer=="function"&&s.setRenderer(this.studio.pixiApp.renderer),await s.ready,await this.setupClipVisuals(s)}));for(const s of this.clips){const r=s.effects;if(Array.isArray(r))for(const n of r)this.studio.globalEffects.has(n.id)||this.studio.globalEffects.set(n.id,{id:n.id,key:n.key,startTime:n.startTime,duration:n.duration})}for(const s of this.clips)if(s instanceof Lt){const r={name:s.transitionEffect.key,key:s.transitionEffect.key,duration:s.duration,fromClipId:s.fromClipId,toClipId:s.toClipId,start:s.display.from,end:s.display.to};if(s.fromClipId){const n=this.getClipById(s.fromClipId);n&&(n.transition={...r})}if(s.toClipId){const n=this.getClipById(s.toClipId);n&&(n.transition={...r})}}await this.recalculateMaxDuration();try{await this.studio.updateFrame(this.studio.currentTime)}catch(s){console.error("[Studio] Failed to update initial frame:",s)}this.studio.emit("studio:restored",{clips:this.clips,tracks:this.tracks,settings:this.studio.opts})}async deleteSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e);if(t.length!==0)for(const s of t)await this.removeClip(s)}async duplicateSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e);if(t.length===0)return;const s=[];for(const r of t){const n=this.findTrackIdByClipId(r.id);if(!n)continue;const o=this.tracks.find(u=>u.id===n);if(!o)continue;const a=Ys(r,!1),l=await Ki(a);l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const c=`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=`${o.name} (Copy)`;this.addTrack({id:c,name:h,type:o.type}),await this.addClip(l,{trackId:c}),s.push(l.id)}s.length>0&&this.studio.selection.selectClipsByIds(s)}async splitSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==1){console.warn("[Studio] Split requires exactly one selected clip");return}const s=t[0],r=e??this.studio.currentTime;if(r<=s.display.from||s.display.to>0&&r>=s.display.to){console.warn("[Studio] Split time is outside clip bounds");return}const n=Ys(s,!1),o=r-s.display.from,a=s.playbackRate||1,l=o*a,c={duration:o,display:{from:s.display.from,to:r}};s.trim&&(c.trim={from:s.trim.from,to:s.trim.from+l}),await this.updateClip(s.id,c);const h={...n};h.display={from:r,to:n.display.to},h.duration=n.duration-o,h.trim&&(h.trim={from:h.trim.from+l,to:h.trim.to});const u=await Ki(h);u.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const d=this.findTrackIdByClipId(s.id);d&&(await this.addClip(u,{trackId:d}),this.studio.selection.selectClipsByIds([u.id]))}async trimSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==1){console.warn("[Studio] Trim requires exactly one selected clip");return}const s=t[0],r=e*1e6,n=s.playbackRate||1,o=r*n;if(r>=s.duration){console.warn("[Studio] Trim amount exceeds clip duration");return}const a=s.duration-r,l=s.display.from+r,c=s.display.to,h={duration:a,display:{from:l,to:c}};if(s.trim)h.trim={from:s.trim.from+o,to:s.trim.to};else{const u=s.sourceDuration||s.duration;h.trim={from:o,to:u}}await this.updateClip(s.id,h)}async updateSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==0)for(const s of t)await this.updateClip(s.id,e)}async setTracks(e){this.tracks=JSON.parse(JSON.stringify(e)),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}async ensureFontsForClips(e){const t=new Map;for(const s of e){if(s.type==="Text"){const r=s.style?.fontUrl||s.fontUrl;r&&t.set(r,{name:s.style?.fontFamily||s.fontFamily||"CustomFont",url:r})}if(s.type==="Caption"){const r=s.style?.fontUrl||s.fontUrl;r&&t.set(r,{name:s.style?.fontFamily||s.fontFamily||"CustomFont",url:r})}}if(t.size>0)try{await Hx.loadFonts(Array.from(t.values()))}catch(s){console.warn("Failed to load some fonts:",s)}}async recalculateMaxDuration(){let e=0;for(const t of this.clips){t.display.to===0&&t.duration!==1/0&&!isNaN(t.duration)&&t.duration>0;const s=t.duration>0?t.duration:0;if(s===1/0)continue;const r=t.display.to>0?t.display.to:t.display.from+s;r>e&&(e=r)}this.studio.maxDuration=e}async setupPlaybackForClip(e,t){if(this.studio.pixiApp!=null){if(!this.isPlaybackCapable(e)){if(this.studio.pixiApp!=null&&(await e.ready).width>0&&(await e.ready).height>0){const s=new gn(this.studio.pixiApp,e,this.studio.clipsNormalContainer);this.studio.spriteRenderers.set(e,s)}return}try{const s=e;if(e.type==="Audio"&&t&&typeof t!="string"){const o=URL.createObjectURL(t);e.src=o}const{element:r,objectUrl:n}=await s.createPlaybackElement();if(e.type==="Video"){const o=M.from(r),a=new Ue(o);a.visible=!1,this.studio.clipsNormalContainer&&this.studio.clipsNormalContainer.addChild(a),this.studio.videoSprites.set(e,a)}this.studio.transport.playbackElements.set(e,{element:r,objectUrl:n})}catch(s){if(console.warn(`Failed to setup playback for ${e.constructor.name}`,s),this.studio.pixiApp!=null&&(await e.ready).width>0&&(await e.ready).height>0){const r=new gn(this.studio.pixiApp,e,this.studio.artboard);this.studio.spriteRenderers.set(e,r)}}}}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async clear(){this.studio.selection.deselectClip(),this.studio.selection.interactiveClips.clear();for(const[e,t]of this.studio.clipListeners)e.off("propsChange",t);this.studio.clipListeners.clear(),this.studio.globalEffects.clear(),this.studio.effectFilters.clear(),this.studio.transitionRenderers.forEach(e=>e.destroy()),this.studio.transitionRenderers.clear(),this.studio.transitionSprites.forEach(e=>{e.parent&&e.parent.removeChild(e),e.destroy()}),this.studio.transitionSprites.clear(),this.studio.spriteRenderers.forEach(e=>e.destroy()),this.studio.spriteRenderers.clear();for(const[e,t]of this.studio.transport.playbackElements)this.isPlaybackCapable(e)&&e.cleanupPlayback(t.element,t.objectUrl);this.studio.transport.playbackElements.clear();for(const e of this.studio.videoSprites.values())e.destroy();this.studio.videoSprites.clear(),this.tracks=[],this.clips=[],this.studio.maxDuration=0,this.studio.currentTime=0,this.studio.emit("reset")}async rippleDelete(e,t){if(e>=t)return;const s=t-e,r=[...this.clips];for(const n of r){const o=n.display.from,a=n.display.to;if(!(a<=e)){if(o>=t){await this.updateClip(n.id,{display:{from:n.display.from-s,to:n.display.to-s}});continue}if(o>=e&&a<=t){await this.removeClip(n);continue}if(o<e&&a>t){const l=await n.clone();l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const c=e,h=e+(a-t),u=n.trim.from+(t-o)*n.playbackRate,d=n.trim.to,f=this.tracks.find(p=>p.clipIds.includes(n.id));f&&(await this.addClip(l,{trackId:f.id}),await this.updateClip(l.id,{display:{from:c,to:h},trim:{from:u,to:d}})),await this.updateClip(n.id,{display:{from:n.display.from,to:e},trim:{from:n.trim.from,to:n.trim.from+(e-o)*n.playbackRate}});continue}if(o<e&&a<=t){await this.updateClip(n.id,{display:{from:n.display.from,to:e},trim:{from:n.trim.from,to:n.trim.from+(e-o)*n.playbackRate}});continue}if(o>=e&&a>t){await this.updateClip(n.id,{display:{from:e,to:e+(a-t)},trim:{from:n.trim.from+(t-o)*n.playbackRate,to:n.trim.to}});continue}}}await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}}const fk={Date:!0,RegExp:!0,String:!0,Number:!0};function Wx(i,e,t={cyclesFix:!0},s=[]){let r=[];const n=Array.isArray(i);for(const a in i){const l=i[a],c=n?+a:a;if(!(a in e)){r.push({type:"REMOVE",path:[c],oldValue:i[a]});continue}const h=e[a],u=typeof l=="object"&&typeof h=="object"&&Array.isArray(l)===Array.isArray(h);l&&h&&u&&!fk[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!s.includes(l))?r.push.apply(r,Wx(l,h,t,t.cyclesFix?s.concat([l]):[]).map(d=>(d.path.unshift(c),d))):l!==h&&!(Number.isNaN(l)&&Number.isNaN(h))&&!(u&&(isNaN(l)?l+""==h+"":+l==+h))&&r.push({path:[c],type:"CHANGE",value:h,oldValue:l})}const o=Array.isArray(e);for(const a in e)a in i||r.push({type:"CREATE",path:[o?+a:a],value:e[a]});return r}class pk{past=[];future=[];lastState=null;maxSize;constructor(e={}){this.maxSize=e.maxSize||50}projectToHistoryState(e){const t={},s=JSON.parse(JSON.stringify(e.tracks||[]));return e.clips.forEach(r=>{r.id&&(t[r.id]=JSON.parse(JSON.stringify(r)))}),{clips:t,tracks:s,settings:JSON.parse(JSON.stringify(e.settings||{}))}}init(e){this.lastState=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),this.past=[],this.future=[]}push(e){if(!this.lastState){this.init(e);return}const t=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),s=Wx(this.lastState,t);s.length!==0&&(this.past.push(s),this.past.length>this.maxSize&&this.past.shift(),this.future=[],this.lastState=t)}undo(e){const t=this.past.pop();if(!t)return null;const s=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),r=this.applyPatches(s,t,!0);return this.future.push(t),this.lastState=r,{patches:t,state:r}}redo(e){const t=this.future.pop();if(!t)return null;const s=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),r=this.applyPatches(s,t,!1);return this.past.push(t),this.lastState=r,{patches:t,state:r}}applyPatches(e,t,s){const r=JSON.parse(JSON.stringify(e)),n=s?[...t].reverse():t;for(const o of n){const{type:a,path:l}=o,c=o.value,h=o.oldValue;let u=r,d=!1;for(let p=0;p<l.length-1;p++){if(u[l[p]]===void 0||u[l[p]]===null){d=!0;break}u=u[l[p]]}if(d)continue;const f=l[l.length-1];if(s)switch(a){case"CREATE":Array.isArray(u)?u.splice(f,1):delete u[f];break;case"REMOVE":u[f]=h&&typeof h=="object"?JSON.parse(JSON.stringify(h)):h;break;case"CHANGE":u[f]=h&&typeof h=="object"?JSON.parse(JSON.stringify(h)):h;break}else switch(a){case"CREATE":u[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break;case"REMOVE":Array.isArray(u)?u.splice(f,1):delete u[f];break;case"CHANGE":u[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break}}return r}canUndo(){return this.past.length>0}canRedo(){return this.future.length>0}}class mk extends Zh{selection;transport;timeline;history;pixiApp=null;get tracks(){return this.timeline.tracks}get clips(){return this.timeline.clips}spriteRenderers=new Map;artboard=null;clipContainer=null;artboardMask=null;artboardBg=null;get activeTransformer(){return this.selection.activeTransformer}set activeTransformer(e){this.selection.activeTransformer=e}get selectedClips(){return this.selection.selectedClips}set selectedClips(e){this.selection.selectedClips=e}get interactiveClips(){return this.selection.interactiveClips}set interactiveClips(e){this.selection.interactiveClips=e}get playbackElements(){return this.transport.playbackElements}videoSprites=new Map;clipListeners=new Map;get isPlaying(){return this.transport.isPlaying}set isPlaying(e){this.transport.isPlaying=e}get currentTime(){return this.transport.currentTime}set currentTime(e){this.transport.currentTime=e}get maxDuration(){return this.transport.maxDuration}set maxDuration(e){this.transport.maxDuration=e}opts;destroyed=!1;renderingSuspended=!1;historyPaused=!1;processingHistory=!1;historyGroupDepth=0;clipCache=new Map;globalEffects=new Map;activeGlobalEffect=null;currentGlobalEffectSprite=null;effectFilters=new Map;transitionRenderers=new Map;transitionSprites=new Map;transFromTexture=null;transToTexture=null;transBgGraphics=null;clipsNormalContainer=null;clipsEffectContainer=null;videoTextureCache=new WeakMap;lastFromFrame=null;lastToFrame=null;hexToNumber(e){const t=e.startsWith("#")?e.slice(1):e;return parseInt(t,16)}ready;constructor(e){super(),this.opts={fps:30,bgColor:"#000000",interactivity:!0,spacing:0,...e},this.selection=new hk(this),this.transport=new uk(this),this.timeline=new dk(this),this.history=new pk,this.ready=this.initPixiApp().then(()=>{this.history.init(this.exportToJSON())}),this.on("clip:removed",this.handleClipRemoved),this.on("clips:removed",this.handleClipsRemoved),this.on("clip:updated",this.handleTimelineChange),this.on("clip:added",this.handleTimelineChange),this.on("clips:added",this.handleTimelineChange),this.on("track:removed",this.handleTimelineChange),this.on("track:added",this.handleTimelineChange)}handleTimelineChange=()=>{this.updateFrame(this.currentTime),this.saveHistory()};saveHistory(){this.historyPaused||this.processingHistory||(this.history.push(this.exportToJSON()),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()}))}beginHistoryGroup(){this.historyGroupDepth++,this.historyPaused=!0}endHistoryGroup(){this.historyGroupDepth=Math.max(0,this.historyGroupDepth-1),this.historyGroupDepth===0&&(this.historyPaused=!1,this.saveHistory())}setPath(e,t,s){let r=e;for(let n=0;n<t.length-1;n++){const o=t[n];r[o]||(r[o]=typeof t[n+1]=="number"?[]:{}),r=r[o]}r[t[t.length-1]]=s}async applyHistoryPatches(e,t,s){const r=new Map,n=new Map,o=new Set;for(const a of e){const{type:l,path:c}=a,h=a.value,u=a.oldValue;if(c[0]==="clips"){const d=c[1];s?l==="CREATE"?o.add(d):l==="REMOVE"?n.set(d,u):l==="CHANGE"&&(r.has(d)||r.set(d,{}),this.setPath(r.get(d),c.slice(2),u)):l==="CREATE"?n.set(d,h):l==="REMOVE"?o.add(d):l==="CHANGE"&&(r.has(d)||r.set(d,{}),this.setPath(r.get(d),c.slice(2),h))}else c[0]==="settings"&&(s?this.setPath(this.opts,c.slice(1),u):this.setPath(this.opts,c.slice(1),h))}for(const a of o){const l=this.timeline.getClipById(a);l&&await this.removeClip(l)}for(const[a,l]of n){let c=this.clipCache.get(a);c||(c=await Ki(l),this.clipCache.set(a,c));let h;for(const u of t.tracks)if(u.clipIds.includes(a)){h=u.id;break}await this.addClip(c,{trackId:h})}for(const[a,l]of r)await this.updateClip(a,l);this.timeline.setTracks(t.tracks),this.emit("studio:restored",{clips:this.clips,tracks:this.tracks,settings:this.opts})}async undo(){if(!(!this.history.canUndo()||this.processingHistory)){this.processingHistory=!0,this.historyPaused=!0;try{const e=this.history.undo(this.exportToJSON());e&&await this.applyHistoryPatches(e.patches,e.state,!0),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}finally{this.historyPaused=!1,this.processingHistory=!1}}}async redo(){if(!(!this.history.canRedo()||this.processingHistory)){this.processingHistory=!0,this.historyPaused=!0;try{const e=this.history.redo(this.exportToJSON());e&&await this.applyHistoryPatches(e.patches,e.state,!1),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}finally{this.historyPaused=!1,this.processingHistory=!1}}}cleanupClipVisuals=e=>{for(const[r,n]of this.spriteRenderers)if(r.id===e){const o=n.getRoot();o&&o.parent&&o.parent.removeChild(o),n.destroy(),this.spriteRenderers.delete(r);break}const t=this.transitionSprites.get(e);t&&(t.parent&&t.parent.removeChild(t),t.destroy(),this.transitionSprites.delete(e)),this.transitionRenderers.get(e)&&this.transitionRenderers.delete(e);for(const[r,n]of this.videoSprites)if(r.id===e){n.parent&&n.parent.removeChild(n),n.destroy(),this.videoSprites.delete(r);break}for(const[r]of this.clipListeners)if(r.id===e){this.clipListeners.delete(r);break}};handleClipRemoved=({clipId:e})=>{this.cleanupClipVisuals(e),this.updateFrame(this.currentTime),this.saveHistory()};handleClipsRemoved=({clipIds:e})=>{for(const t of e)this.cleanupClipVisuals(t);this.updateFrame(this.currentTime),this.saveHistory()};async initPixiApp(){if(this.destroyed)return;const e=this.opts.canvas||document.createElement("canvas");e.width=this.opts.width,e.height=this.opts.height;const t=new Lu,s=e.parentElement||window;await t.init({canvas:e,resizeTo:s,backgroundColor:this.hexToNumber(this.opts.bgColor),antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.pixiApp=t,t.stage.eventMode="static",t.stage.hitArea=t.screen,this.artboard=new re,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new _e,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new re,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new _e,this.artboardMask.rect(0,0,this.opts.width,this.opts.height).fill({color:16777215}),this.clipContainer.addChild(this.artboardMask),this.clipContainer.mask=this.artboardMask,this.clipsEffectContainer=new re,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new re,this.clipsNormalContainer.label="ClipsNormal",this.clipsNormalContainer.zIndex=10,this.clipsNormalContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsNormalContainer),this.transFromTexture=Ge.create({width:this.opts.width,height:this.opts.height}),this.transToTexture=Ge.create({width:this.opts.width,height:this.opts.height}),this.transBgGraphics=new _e,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}),this.clipContainer.sortableChildren=!0,this.updateArtboardLayout(),t.renderer.on("resize",()=>{this.handleResize()})}getOptions(){return this.opts}updateDimensions(e,t){this.opts.width=e,this.opts.height=t,this.artboardBg&&this.artboardBg.clear().rect(0,0,e,t).fill({color:3355443}),this.artboardMask&&this.artboardMask.clear().rect(0,0,e,t).fill({color:16777215}),this.transFromTexture&&this.transFromTexture.resize(e,t),this.transToTexture&&this.transToTexture.resize(e,t),this.transBgGraphics&&this.transBgGraphics.clear().rect(0,0,e,t).fill({color:0,alpha:0}),this.updateArtboardLayout(),this.updateFrame(this.currentTime)}handleResize=()=>{this.destroyed||!this.pixiApp||this.updateArtboardLayout()};updateArtboardLayout(){if(!this.pixiApp||!this.artboard)return;const e=this.pixiApp.canvas.width,t=this.pixiApp.canvas.height,s=this.opts.width,r=this.opts.height,n=this.pixiApp.canvas.parentElement?.clientWidth||e,o=this.pixiApp.canvas.parentElement?.clientHeight||t,a=this.opts.spacing||0,l=Math.max(0,n-a*2),c=Math.max(0,o-a*2),h=l/s,u=c/r,d=Math.min(h,u);this.artboard.scale.set(d),this.artboard.x=(n-s*d)/2,this.artboard.y=(o-r*d)/2}getCanvas(){if(this.opts.canvas)return this.opts.canvas;if(this.pixiApp?.canvas)return this.pixiApp.canvas;throw new Error("Canvas not initialized yet. Wait for initPixiApp to complete.")}async addTransition(e,t=2e6,s,r){return this.timeline.addTransition(e,t,s,r)}findTrackIdByClipId(e){return this.timeline.findTrackIdByClipId(e)}async addClip(e,t){(Array.isArray(e)?e:[e]).forEach(r=>this.clipCache.set(r.id,r)),this.beginHistoryGroup();try{return await this.timeline.addClip(e,t)}finally{this.endHistoryGroup()}}addTrack(e){return this.timeline.addTrack(e)}async setTracks(e){return this.timeline.setTracks(e)}async removeTrack(e){return this.timeline.removeTrack(e)}getClipById(e){return this.timeline.getClipById(e)}async updateClip(e,t){return this.timeline.updateClip(e,t)}async centerClip(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=(this.opts.width-t.width)/2,r=(this.opts.height-t.height)/2;return this.updateClip(t.id,{left:s,top:r})}async centerClipH(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=(this.opts.width-t.width)/2;return this.updateClip(t.id,{left:s})}async centerClipV(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=(this.opts.height-t.height)/2;return this.updateClip(t.id,{top:s})}async scaleToFit(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=await t.ready,{width:r,height:n}=s;if(r===0||n===0)return;const o=Math.min(this.opts.width/r,this.opts.height/n),a=r*o,l=n*o;return this.updateClip(t.id,{width:a,height:l})}async scaleToCover(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=await t.ready,{width:r,height:n}=s;if(r===0||n===0)return;const o=Math.max(this.opts.width/r,this.opts.height/n),a=r*o,l=n*o;return this.updateClip(t.id,{width:a,height:l})}async updateClips(e){this.suspendRendering(),await this.timeline.updateClips(e),this.resumeRendering(),this.updateFrame(this.currentTime)}suspendRendering(){this.renderingSuspended=!0}resumeRendering(){this.renderingSuspended=!1}getTracks(){return this.timeline.tracks}getClip(e){return this.timeline.getClipById(e)}setupSpriteInteractivity(e){this.selection.setupSpriteInteractivity(e)}async removeClip(e){this.beginHistoryGroup();try{return this.clipCache.set(e.id,e),this.timeline.removeClip(e,{permanent:!this.processingHistory})}finally{this.endHistoryGroup()}}async removeClips(e){this.beginHistoryGroup();try{return e.forEach(t=>this.clipCache.set(t.id,t)),this.timeline.removeClips(e,{permanent:!this.processingHistory})}finally{this.endHistoryGroup()}}async removeClipById(e){const t=this.timeline.getClipById(e);if(t)return this.removeClip(t)}async removeClipsById(e){const t=e.map(s=>this.timeline.getClipById(s)).filter(Boolean);return this.removeClips(t)}async deleteSelected(){const e=this.selection.selectedClips;if(e.size!==0){this.beginHistoryGroup();try{await this.removeClips(Array.from(e))}finally{this.endHistoryGroup()}}}async duplicateSelected(){this.beginHistoryGroup();try{return await this.timeline.duplicateSelected()}finally{this.endHistoryGroup()}}async splitSelected(e){this.beginHistoryGroup();try{return await this.timeline.splitSelected(e)}finally{this.endHistoryGroup()}}async trimSelected(e){return this.timeline.trimSelected(e)}async updateSelected(e){return this.timeline.updateSelected(e)}async clear(){await this.timeline.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null),this.emit("reset")}async play(){return this.transport.play()}pause(){this.transport.pause()}async stop(){return this.transport.stop()}async seek(e){return this.transport.seek(e)}async frameNext(){return this.transport.frameNext()}async framePrev(){return this.transport.framePrev()}getCurrentTime(){return this.transport.currentTime}getMaxDuration(){return this.transport.maxDuration}getIsPlaying(){return this.transport.isPlaying}getSelectedClips(){return Array.from(this.selectedClips)}getVideoTexture(e){let t=this.videoTextureCache.get(e);return t||(t=M.from(e),this.videoTextureCache.set(e,t)),t}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async updateFrame(e){if(this.destroyed||this.pixiApp==null||this.renderingSuspended)return;this.updateActiveGlobalEffect(e);const t=new Set,s=this.tracks.length;for(const n of this.clips){const o=this.getTrackIndex(n.id);if(o!==-1){const a=(s-o)*10;n.zIndex=a;const l=this.spriteRenderers.get(n);if(l){const c=l.getRoot();c&&(c.zIndex=a)}}}const r=[...this.clips].sort((n,o)=>n.zIndex-o.zIndex);for(const n of r){if(e<n.display.from){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const _=this.playbackElements.get(n);_!=null&&this.isPlaybackCapable(n)&&n.pause(_.element);continue}if(n.display.to>0&&e>=n.display.to){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const _=this.playbackElements.get(n);_!=null&&this.isPlaybackCapable(n)&&n.pause(_.element);continue}const o=e-n.display.from,a=o*n.playbackRate;n.animate(a);const l=await n.ready,c=n.duration||l.duration;if(c>0&&o>=c){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const _=this.playbackElements.get(n);_!=null&&this.isPlaybackCapable(n)&&n.pause(_.element);continue}const h=this.playbackElements.get(n),u=n.type==="Video"||n.type==="Image",d=n.transition?n.transition.start:0,f=n.transition?n.transition.end:0,p=u&&n.transition&&e>=d&&e<f;if(h!=null&&this.isPlaybackCapable(n)){const m=o/1e6;if(n.syncPlayback(h.element,this.isPlaying,m),n.type==="Video"&&this.isPlaybackCapable(n)){const _=this.videoSprites.get(n);if(_!=null){const x=n.meta.duration/1e6;if(this.spriteRenderers.has(n))_.visible=!1;else if(_.visible=!p&&m>=0&&m<x,_.visible&&tM(n,_),!p)continue}}else continue}if(p){this.transFromTexture||(this.transFromTexture=Ge.create({width:this.opts.width,height:this.opts.height})),this.transToTexture||(this.transToTexture=Ge.create({width:this.opts.width,height:this.opts.height})),this.transBgGraphics||(this.transBgGraphics=new _e,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}));const m=this.getClipById(n?.transition?.fromClipId),_=this.getClipById(n?.transition?.toClipId);let x=null,y=null;if(m){const v=Math.max(0,e-m.display.from),{video:T}=await m.getFrame(v);T instanceof HTMLVideoElement?x=this.getVideoTexture(T):x=T,x&&(this.lastFromFrame=x)}if(_){const v=Math.max(0,e-_.display.from),{video:T}=await _.getFrame(v);T instanceof HTMLVideoElement?y=this.getVideoTexture(T):y=T,y&&(this.lastToFrame=y)}if(x||(x=this.lastFromFrame),y||(y=this.lastToFrame),!x||!y)continue;if(x&&y&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const v=(e-d)/n?.transition?.duration;m&&x&&this.renderClipToTransitionTexture(m,x,this.transFromTexture),_&&y&&this.renderClipToTransitionTexture(_,y,this.transToTexture);let T=this.transitionRenderers.get(n.id);if(!T)try{T=nf({name:n?.transition?.name,renderer:this.pixiApp.renderer}),this.transitionRenderers.set(n.id,T)}catch(S){console.error("[Studio] Failed to create transition renderer:",S)}if(T){const S=T.render({width:this.opts.width,height:this.opts.height,from:this.transFromTexture,to:this.transToTexture,progress:v});let w=this.transitionSprites.get(n.id);w||(w=new Ue,w.label=`TransitionSprite_${n.id}`,this.transitionSprites.set(n.id,w),this.clipsNormalContainer&&this.clipsNormalContainer.addChild(w)),w.texture=S,w.visible=!0,w.x=0,w.y=0,w.width=this.opts.width,w.height=this.opts.height,w.anchor.set(0,0),w.zIndex=n.zIndex,t.add(n.id);const E=this.spriteRenderers.get(n);E?.getRoot()&&(E.getRoot().visible=!1);const P=this.videoSprites.get(n);if(P&&(P.visible=!1),m){const C=this.spriteRenderers.get(m);C?.getRoot()&&(C.getRoot().visible=!1);const A=this.videoSprites.get(m);A&&(A.visible=!1)}continue}}}const g=this.spriteRenderers.get(n);if(g!=null){const m=this.selectedClips.has(n);if(n.type!=="Text"&&n.type!=="Caption"&&typeof n.getTexture=="function"&&n.getTexture()!=null){const x=n.getTexture();if(x!=null){await g.updateFrame(x),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}if(n.type==="Text"){const x=n;this.pixiApp?.renderer&&typeof x.setRenderer=="function"&&x.setRenderer(this.pixiApp.renderer);const y=await x.getTexture();if(y!=null){await g.updateFrame(y),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}if(n.type==="Caption"){n.updateState(o);const x=n;this.pixiApp?.renderer&&typeof x.setRenderer=="function"&&x.setRenderer(this.pixiApp.renderer);const y=await x.getTexture();if(y!=null){await g.updateFrame(y),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}const{video:_}=await n.getFrame(o);await g.updateFrame(_),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n)}}if(this.activeGlobalEffect&&this.clipsNormalContainer&&this.clipsEffectContainer){const{startTime:n,duration:o}=this.activeGlobalEffect,a=e-n,l=Math.min(Math.max(a/o,0),1);if(l>0&&l<1){try{for(const h of this.clips)this.moveClipToEffectContainer(h,!1);const c=this.clips.some(h=>h.id===this.activeGlobalEffect.id&&h instanceof ct);for(const h of this.clips){let u=!1;if(c){const d=this.activeGlobalEffect.trackIndex??-1,f=this.getTrackIndex(h.id);u=h.id!==this.activeGlobalEffect.id&&!(h instanceof ct)&&f>d}else{const d=h.effects;u=Array.isArray(d)&&d.some(f=>f&&f.id===this.activeGlobalEffect.id)}u&&this.moveClipToEffectContainer(h,!0)}}catch(c){console.warn("Failed to reparent clips for effect; falling back to full-scene render",c)}this.clipsNormalContainer.visible=!0,await this.applyGlobalEffectIfNeeded(e)}else{for(const c of this.clips)try{this.moveClipToEffectContainer(c,!1)}catch{}this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}}else if(this.clipsNormalContainer){for(const n of this.clips)try{this.moveClipToEffectContainer(n,!1)}catch{}this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}for(const[n,o]of this.transitionSprites.entries())t.has(n)||(o.visible=!1);this.pixiApp!=null&&this.pixiApp.render()}moveClipToEffectContainer(e,t=!0){if(!this.clipsNormalContainer||!this.clipsEffectContainer)return;const s=t?this.clipsEffectContainer:this.clipsNormalContainer,r=this.spriteRenderers.get(e);if(r){const o=r.getRoot();if(o&&o.parent!==s){try{o.parent&&o.parent.removeChild&&o.parent.removeChild(o)}catch(a){console.warn("moveClipToEffectContainer: could not remove root from parent",a)}s.addChild(o)}}const n=this.transitionSprites.get(e.id);if(n&&n.parent!==s){try{n.parent&&n.parent.removeChild&&n.parent.removeChild(n)}catch(o){console.warn("moveClipToEffectContainer: could not remove transSprite from parent",o)}s.addChild(n)}}applyGlobalEffect(e,t,s){const r=t.id||`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={id:r,key:e,startTime:t.startTime,duration:t.duration??1e6};for(const o of s)o instanceof xi&&o.addEffect(n),o instanceof Me&&o.addEffect(n),o instanceof gt&&o.addEffect(n),o instanceof ei&&o.addEffect(n);return this.globalEffects.set(r,n),r}getTrackIndex(e){return this.tracks.findIndex(t=>t.clipIds.includes(e))}async getTransitionFromFrame(e,t){let s=null;if(e.transition?.prevClipId&&(s=this.clips.find(a=>a.id===e.transition.prevClipId)||null),s||(s=this.getPreviousClipOnTrack(e)),!s)return null;const r=s.duration>0?s.duration:0,n=Math.max(0,Math.min(t-s.display.from,r)),{video:o}=await s.getFrame(n);return o}getPreviousClipOnTrack(e){const t=this.getTrackIndex(e.id);return t===-1?null:this.clips.filter(s=>s.id!==e.id&&this.getTrackIndex(s.id)===t&&s.display.from<e.display.from&&(s instanceof Me||s instanceof xi)).sort((s,r)=>r.display.to-s.display.to)[0]||null}renderClipToTransitionTexture(e,t,s){if(!this.pixiApp||!this.transBgGraphics)return;const r=this.pixiApp.renderer.background.alpha;this.pixiApp.renderer.background.alpha=0,this.pixiApp.renderer.render({container:this.transBgGraphics,target:s,clear:!0}),this.pixiApp.renderer.background.alpha=r;const n=new Ue(t instanceof M?t:M.from(t));n.x=e.center.x,n.y=e.center.y,n.anchor.set(.5,.5);const o=n.texture.width||1,a=n.texture.height||1,l=e.width&&e.width!==0?Math.abs(e.width)/o:1,c=e.height&&e.height!==0?Math.abs(e.height)/a:1;e.flip==="horizontal"?(n.scale.x=-l,n.scale.y=c):e.flip==="vertical"?(n.scale.x=l,n.scale.y=-c):(n.scale.x=l,n.scale.y=c),n.rotation=(e.flip==null?1:-1)*e.angle,n.alpha=e.opacity,this.pixiApp.renderer.render({container:n,target:s,clear:!1}),t instanceof M||n.texture.destroy(!0),n.destroy()}removeGlobalEffect(e){this.globalEffects.delete(e)}clearGlobalEffects(){this.globalEffects.clear()}updateActiveGlobalEffect(e){let t=null;for(const s of this.clips)if(s instanceof ct&&e>=s.display.from&&(s.display.to===0||e<s.display.to)){t={id:s.id,key:s.effect.key,startTime:s.display.from,duration:s.duration>0?s.duration:s.display.to-s.display.from,trackIndex:this.getTrackIndex(s.id)};break}if(!t)for(const s of this.globalEffects.values()){const r=s.startTime+s.duration;if(e>=s.startTime&&e<r){t={id:s.id,key:s.key,startTime:s.startTime,duration:s.duration,trackIndex:-1};break}}this.activeGlobalEffect=t}async applyGlobalEffectIfNeeded(e){if(this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null),!this.activeGlobalEffect||!this.pixiApp||!this.clipContainer||!this.artboard||!this.clipsNormalContainer||!this.clipsEffectContainer)return;const{key:t,startTime:s,duration:r}=this.activeGlobalEffect,n=e-s,o=Math.min(Math.max(n/r,0),1);if(o<=0||o>=1)return;this.clipsEffectContainer.visible=!0;let a=this.effectFilters.get(t);if(!a)try{if(a=sf({name:t.toLowerCase(),renderer:this.pixiApp.renderer}),a)this.effectFilters.set(t,a);else return}catch(f){console.error(f);return}const l=this.opts.width,c=this.opts.height,h=Ge.create({width:l,height:c});this.pixiApp.renderer.render({container:this.clipsEffectContainer,target:h,clear:!0}),this.clipsEffectContainer.visible=!1;const u=a.render({canvasTexture:h,progress:o,width:l,height:c}),d=new Ue(u);d.x=0,d.y=0,d.width=l,d.height=c,d.scale.set(1),d.zIndex=5,this.clipContainer.addChild(d),this.currentGlobalEffectSprite=d,h.destroy(!0)}destroy(){if(!this.destroyed){window.removeEventListener("resize",this.handleResize),this.destroyed=!0,this.stop(),this.clear(),this.transitionRenderers.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null);for(const e of this.transitionSprites.values())e.destroy();this.transitionSprites.clear(),this.pixiApp&&(this.pixiApp.destroy(!0,{children:!0,texture:!0}),this.pixiApp=null)}}selectClip(e,t=!1){this.selection.selectClip(e,t)}setSelection(e){this.selection.setSelection(e)}selectClipsByIds(e){this.selection.selectClipsByIds(e)}deselectClip(){this.selection.deselectClip()}exportToJSON(){return this.timeline.exportToJSON()}async loadFromJSON(e){return this.timeline.loadFromJSON(e)}}V.add(VS),V.mixin(re,$S),V.add(lg),V.add(cg),V.add(g0),V.mixin(re,xI),V.add(m0),V.add(sx),V.add(od),V.add(ox),V.add(ux),V.add(dx),V.add(wx),V.add(Tx),V.add(gx),V.add(vx),V.add(xx),V.add(mx),V.add(px),V.add(w0),V.add(b0);const gk=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),_k=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));se.Audio=Ke,se.Caption=ei,se.Compositor=rk,se.DEFAULT_AUDIO_CONF=le,se.Effect=ct,se.GL_EFFECT_OPTIONS=eM,se.GL_TRANSITION_OPTIONS=ik,se.Image=xi,se.Log=K,se.MP4Clip=Me,se.Placeholder=mn,se.Studio=mk,se.Text=gt,se.Transition=Lt,se.Video=Me,se.clipToJSON=Ys,se.createChromakey=S1,se.fastConcatMP4=Ux,se.fixFMP4Duration=BR,se.fontManager=Hx,se.jsonToClip=Ki,se.makeEffect=sf,se.makeTransition=nf,se.mixinMP4AndAudio=GR,se.renderTxt2ImgBitmap=M1,Object.defineProperty(se,Symbol.toStringTag,{value:"Module"})}));
|
|
7791
|
+
`,tk={radialSwipe:{label:"Radial Swipe",fragment:aM}},Zi={...ji.reduce((i,e)=>(i[e.name]={label:e.name,fragment:e.glsl,uniforms:e.defaultParams,previewDynamic:`transition: ${e.name}`},i),{}),...tk},ik=Object.entries(Zi).map(([i,e])=>({key:i,label:e.label,previewStatic:`https://cdn.subgen.co/previews/static/transition_${i}_static.webp`,previewDynamic:`https://cdn.subgen.co/previews/dynamic/transition_${i}_dynamic.webp`}));function nf({name:i,renderer:e}){let t=ji.find(N=>N.name===i);if(!t){const N=Object.keys(Zi).find(K=>K.toLowerCase()===i.toLowerCase());N&&(t=Zi[N])}if(t||(t=ji.find(N=>N.name.toLowerCase()===i.toLowerCase())),!t){const N=[i,i.toLowerCase(),i.charAt(0).toUpperCase()+i.slice(1).toLowerCase(),i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),i.replace(/_/g,"")];for(const K of N){if(t=ji.find(Ie=>Ie.name.toLowerCase()===K.toLowerCase()),t)break;const me=Object.keys(Zi).find(Ie=>Ie.toLowerCase()===K.toLowerCase());if(me){t=Zi[me];break}}}if(!t){const N=ji.length,K=ji.slice(0,5).map(Ie=>Ie.name).join(", "),me=Object.keys(Zi).slice(0,3).join(", ");throw console.error(`Transition not found: "${i}". Available in gl-transitions (${N} total):`,K+"..."),console.error("Available locally:",me+"..."),new Error(`Transition "${i}" not found in gl-transitions library or local definitions`)}const s=new Ue(M.WHITE),r=Ge.create({width:e.width,height:e.height}),n=new Ct({}),o=new Ct({}),a=t.name==="displacement"||i.toLowerCase()==="displacement"||t.label==="displacement",l=a?new Ct({}):void 0;let c=null;if(a){c=document.createElement("canvas"),c.width=256,c.height=256;const N=c.getContext("2d");if(N){const K=N.createImageData(256,256);for(let me=0;me<K.data.length;me+=4){const Ie=Math.random();K.data[me]=Ie*255,K.data[me+1]=Ie*255,K.data[me+2]=Ie*255,K.data[me+3]=255}N.putImageData(K,0,0)}}let h=t.glsl||t.fragment;if(!h)throw new Error(`Transition "${i}" has no glsl or fragment code`);let u={...de.basics,...de.custom(t)};Object.entries(u).forEach(([,N])=>{N.type==="int<f32>"&&(N.type="i32",typeof N.value=="number"&&(N.value=Math.trunc(N.value))),N.type==="ivec2<f32>"&&(N.type="vec2<f32>")});const d=t.name==="GridFlip"||i.toLowerCase()==="gridflip"||t.label==="gridflip",f=t.name==="circle"||i.toLowerCase()==="circle"||t.label==="circle",p=t.name==="directional"||i.toLowerCase()==="directional"||t.label==="directional",g=t.name==="UndulatingBurnOut"||i.toLowerCase()==="undulatingburnout"||t.label==="undulatingBurnOut",m=t.name==="SquaresWire"||i.toLowerCase()==="squareswire"||t.label==="squaresWire",x=t.name==="rotate_scale_fade"||i.toLowerCase()==="rotatescalefade"||t.label==="rotateScaleFade",_=t.name==="RandomSquares"||i.toLowerCase()==="randomsquares"||t.label==="randomSquares",y=t.name==="polar_function"||i.toLowerCase()==="polar_function"||t.label==="polar_function",v=t.name==="pixelate"||i.toLowerCase()==="pixelate"||t.label==="pixelate",T=t.name==="perlin"||i.toLowerCase()==="perlin"||t.label==="perlin",S=t.name==="luma"||i.toLowerCase()==="luma"||t.label==="luma",w=t.name==="luminance_melt"||i.toLowerCase()==="luminance_melt"||i.toLowerCase()==="luminancemelt"||t.label==="luminance_melt",E=t.name==="hexagonalize"||i.toLowerCase()==="hexagonalize"||t.label==="hexagonalize",P=t.name==="heart"||i.toLowerCase()==="heart"||t.label==="heart",C=t.name==="displacement"||i.toLowerCase()==="displacement"||t.label==="displacement",A=t.name==="directionalwipe"||i.toLowerCase()==="directionalwipe"||i.toLowerCase()==="directional_wipe"||t.label==="directionalwipe",U=t.name==="directionalwarp"||i.toLowerCase()==="directionalwarp"||i.toLowerCase()==="directional_warp"||t.label==="directionalwarp",D=t.name==="crosshatch"||i.toLowerCase()==="crosshatch"||t.label==="crosshatch",$=t.name==="circleopen"||i.toLowerCase()==="circleopen"||i.toLowerCase()==="circle_open"||t.label==="circleopen",pe=t.name==="cannabisleaf"||i.toLowerCase()==="cannabisleaf"||i.toLowerCase()==="cannabis_leaf"||t.label==="cannabisleaf",k=t.name==="StereoViewer"||i.toLowerCase()==="stereoviewer"||i.toLowerCase()==="stereo_viewer"||t.label==="StereoViewer",F=t.name==="GlitchDisplace"||i.toLowerCase()==="glitchDisplace"||t.label==="GlitchDisplace",ne=t.name==="CrossZoom"||i.toLowerCase()==="crosszoom"||t.label==="CrossZoom",G=t.name==="CrazyParametricFun"||i.toLowerCase()==="crazyparametricfun"||t.label==="CrazyParametricFun",ie=t.name==="BowTieHorizontal"||i.toLowerCase()==="bowtiehorizontal"||t.label==="BowTieHorizontal",we=t.name==="PolkaDotsCurtain"||i.toLowerCase()==="polkadotscurtain"||t.label==="PolkaDotsCurtain",ce=t.name==="Pixelize"||i.toLowerCase()==="pixelize"||t.label==="Pixelize";d&&(h=lM,u={...de.basics,...cM}),f&&(h=hM,u={...de.basics,...z_}),p&&(h=uM,u={...de.basics,...dM}),g&&(h=fM,u={...de.basics,...pM}),m&&(h=mM,u={...de.basics,...gM}),x&&(h=xM,u={...de.basics,..._M}),_&&(h=yM,u={...de.basics,...vM}),y&&(h=bM,u={...de.basics,...TM}),v&&(h=O_,u={...de.basics,...D_}),T&&(h=CM,u={...de.basics,...AM}),S&&(h=EM,u={...de.basics,...IM}),w&&(h=PM,u={...de.basics,...RM}),E&&(h=MM,u={...de.basics,...kM}),P&&(h=FM,u={...de.basics,...BM}),C&&(h=UM,u={...de.basics,...OM}),A&&(h=DM,u={...de.basics,...GM}),U&&(h=zM,u={...de.basics,...NM}),D&&(h=LM,u={...de.basics,...HM}),$&&(h=WM,u={...de.basics,...z_}),pe&&(h=VM,u={...de.basics,...$M}),k&&(h=XM,u={...de.basics,...YM}),F&&(h=qM),ne&&(h=KM,u={...de.basics,...jM}),G&&(h=ZM,u={...de.basics,...JM}),ie&&(h=QM),we&&(h=ek),ce&&(h=wM,u={...de.basics,...SM});const Ce={from:n,to:o,uniforms:u};a&&l&&(Ce.displacementMap=l,c&&(l.resource=c,l.update()));const Oe=new Gi({glProgram:new At({vertex:rM,fragment:oM(h)}),resources:Ce});return s.filters=[Oe],{render({width:N,height:K,from:me,to:Ie,progress:Qi}){if((s.width!==N||s.height!==K)&&(s.setSize({width:N,height:K}),r.resize(N,K)),me instanceof M?Oe.resources.from=me.source:(n.resource=me,n.update(),Oe.resources.from=n),Ie instanceof M?Oe.resources.to=Ie.source:(o.resource=Ie,o.update(),Oe.resources.to=o),a&&l&&c){if(c.width!==N||c.height!==K){c.width=N,c.height=K;const ti=c.getContext("2d");if(ti){const Et=ti.createImageData(N,K);for(let qe=0;qe<Et.data.length;qe+=4){const xt=Math.random();Et.data[qe]=xt*255,Et.data[qe+1]=xt*255,Et.data[qe+2]=xt*255,Et.data[qe+3]=255}ti.putImageData(Et,0,0)}}l.resource=c,l.update()}return Oe.resources.uniforms.uniforms.progress=Qi,e.render({container:s,target:r,clear:!1,width:N,height:K}),r},destroy(){r.destroy(),s.destroy({children:!0})}}}let sk=0;async function N_(i){i()>50&&(await jh(15),await N_(i))}class rk extends Zh{static async isSupported(e={}){return(self.OffscreenCanvas!=null&&self.VideoEncoder!=null&&self.VideoDecoder!=null&&self.VideoFrame!=null&&self.AudioEncoder!=null&&self.AudioDecoder!=null&&self.AudioData!=null&&((await self.VideoEncoder.isConfigSupported({codec:e.videoCodec??"avc1.42E032",width:e.width??1920,height:e.height??1080,bitrate:e.bitrate??7e6})).supported??!1)&&(await self.AudioEncoder.isConfigSupported({codec:(await Bp()).codec,sampleRate:le.sampleRate,numberOfChannels:le.channelCount})).supported)??!1}logger=q.create(`id:${sk++},`);destroyed=!1;sprites=[];canvas;pixiApp=null;stopOutput=null;opts;hasVideoTrack;constructor(e={}){super();const{width:t=0,height:s=0}=e;this.canvas=new OffscreenCanvas(t,s),this.opts=Object.assign({bgColor:"#000",width:0,height:0,videoCodec:"avc1.42E032",audio:!0,bitrate:5e6,fps:30,metaDataTags:null},e),this.hasVideoTrack=t*s>0,Bp().catch(r=>{this.logger.warn("Failed to detect audio codec:",r)})}async initPixiApp(){const{width:e,height:t}=this.opts;if(this.pixiApp=new Lu,await this.pixiApp.init({canvas:this.canvas,width:e,height:t,backgroundColor:0,antialias:!1,autoDensity:!1,resolution:1,preference:"webgl"}),this.pixiApp.renderer==null||this.pixiApp.stage==null)throw new Error("Pixi.js Application failed to initialize properly");try{const s=this.pixiApp;s.ticker&&typeof s.ticker.stop=="function"&&s.ticker.stop()}catch{}}async addSprite(e,t={}){const s={rect:{x:e.left,y:e.top,w:e.width,h:e.height},display:{...e.display},duration:e.duration,playbackRate:e.playbackRate,zIndex:e.zIndex};this.logger.info("Compositor add clip",s);const r=await e.clone();this.pixiApp!=null&&this.pixiApp.renderer!=null&&typeof r.setRenderer=="function"&&r.setRenderer(this.pixiApp.renderer),this.logger.info("Compositor add clip ready"),this.sprites.push(Object.assign(r,{main:t.main??!1,expired:!1})),this.sprites.sort((n,o)=>n.zIndex-o.zIndex)}initMuxer(e){const{fps:t,width:s,height:r,videoCodec:n,bitrate:o,audio:a,metaDataTags:l}=this.opts,c=this.sprites.some(d=>d.width>0&&d.height>0),h=this.hasVideoTrack&&c;return Bw({video:h?{width:s,height:r,expectFPS:t,codec:n,bitrate:o,__unsafe_hardwareAcceleration__:this.opts.__unsafe_hardwareAcceleration__}:null,audio:a===!1?null:{codec:le.codecType,sampleRate:le.sampleRate,channelCount:le.channelCount},duration:e,metaDataTags:l})}output(e={}){if(this.sprites.length===0)throw Error("No sprite added");const t=this.sprites.find(u=>u.main),r=this.sprites.map(u=>u.display.from+u.duration).filter(u=>u!==1/0),n=e.maxTime??(t!=null?t.display.from+t.duration:r.length>0?Math.max(...r):1/0);if(n===1/0||n<=0)throw Error("Unable to determine the end time, please specify a main sprite, or limit the duration of Image, Audio");n===-1&&this.logger.warn("Unable to determine the end time, process value don't update"),this.logger.info(`start combinate video, maxTime:${n}`);const o=this.initMuxer(n);let a=performance.now();const l=this.runEncoding(o,n,{onProgress:u=>{this.logger.debug("OutputProgress:",u),this.emit("OutputProgress",u)},onEnded:async()=>{await o.flush(),this.logger.info("===== output ended =====, cost:",performance.now()-a),this.emit("OutputProgress",1),this.destroy()},onError:u=>{this.emit("error",u),h(u),this.destroy()}});this.stopOutput=()=>{l(),o.close(),h()};const{stream:c,stop:h}=F_(o.mp4file,500,this.destroy);return c}destroy(){if(!this.destroyed&&(this.destroyed=!0,this.stopOutput?.(),this.off("OutputProgress"),this.off("error"),this.pixiApp!=null))try{const e=this.pixiApp;if(e.destroyed===!0){this.pixiApp=null;return}if(e.ticker&&typeof e.ticker.stop=="function")try{e.ticker.stop()}catch{}if(e.renderer!=null){const t=e.renderer.gl;if(t&&t.isContextLost()){this.pixiApp=null;return}this.pixiApp.destroy()}}catch(e){console.warn("Error while destroying Pixi application:",e)}finally{this.pixiApp=null}}runEncoding(e,t,{onProgress:s,onEnded:r,onError:n}){let o=0;const a={aborted:!1};let l=null,c=null;const h=async()=>{const{fps:f,bgColor:p,audio:g}=this.opts,m=Math.round(1e6/f),x=this.sprites.some(v=>v.width>0&&v.height>0);c=nk({pixiApp:this.pixiApp,sprites:this.sprites,aborter:a});const _=ok({muxer:e,canvas:this.canvas,outputAudio:g,hasVideoTrack:this.hasVideoTrack&&x,timeSlice:m,fps:f});let y=0;for(;;){if(l!=null)return;if(a.aborted||t!==-1&&y>t||this.sprites.length===0){u(),await r();return}o=y/t;const{audios:v,mainSprDone:T,hasVideo:S}=await c.render(y);if(T){u(),await r();return}if(a.aborted)return;this.hasVideoTrack&&S&&await new Promise(w=>requestAnimationFrame(w)),_(y,v,S),y+=m,await N_(e.getEncodeQueueSize)}},u=()=>{a.aborted||(a.aborted=!0,clearInterval(d),c?.cleanup(),this.sprites.forEach(f=>{f.destroy()}))};h().catch(f=>{l=f,this.logger.error(f),u(),n(f)});const d=setInterval(()=>{s(o)},500);return u}exportToJSON(){const e=this.sprites.map(s=>Ys(s,s.main)),t=[];return this.sprites.forEach(s=>{if(s.transition){const r=this.sprites.filter(n=>n.id!==s.id&&n.zIndex===s.zIndex&&n.display.from<s.display.from&&(n instanceof Me||n instanceof _i)).sort((n,o)=>o.display.to-n.display.to)[0];r&&t.push({key:s.transition.name,duration:s.transition.duration,clips:[r.id,s.id]})}}),{clips:e,settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor,videoCodec:this.opts.videoCodec,bitrate:this.opts.bitrate,audio:this.opts.audio,metaDataTags:this.opts.metaDataTags}}}async loadFromJSON(e){this.sprites.forEach(t=>{t.destroy()}),this.sprites=[],e.settings&&(e.settings.width!==void 0&&(this.opts.width=e.settings.width),e.settings.height!==void 0&&(this.opts.height=e.settings.height),e.settings.fps!==void 0&&(this.opts.fps=e.settings.fps),e.settings.bgColor!==void 0&&(this.opts.bgColor=e.settings.bgColor),e.settings.videoCodec!==void 0&&(this.opts.videoCodec=e.settings.videoCodec),e.settings.bitrate!==void 0&&(this.opts.bitrate=e.settings.bitrate),e.settings.audio!==void 0&&(this.opts.audio=e.settings.audio===!1?!1:void 0),e.settings.metaDataTags!==void 0&&(this.opts.metaDataTags=e.settings.metaDataTags));for(const t of e.clips){const s=await Ki(t);if(await this.addSprite(s,{main:t.main||!1}),t.type==="Transition"){const r=t.toClipId,n=this.sprites.find(o=>o.id===r);n?n.transition={name:t.transitionEffect.key,duration:t.duration,prevClipId:t.fromClipId||""}:console.warn(`[Compositor] Could not find target clip ${r} for transition ${t.transitionEffect.key}`)}}}}function nk(i){const{pixiApp:e,sprites:t,aborter:s}=i,r=e!=null,n=new Map,o=new Map,a=new Map,l=Ge.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),c=Ge.create({width:e?.renderer.width||0,height:e?.renderer.height||0}),h=new xe().rect(0,0,e?.renderer.width||0,e?.renderer.height||0).fill({color:0}),u=new Map,d=T=>t.filter(S=>S.id!==T.id&&S.zIndex===T.zIndex&&S.display.from<T.display.from&&(S instanceof Me||S instanceof _i)).sort((S,w)=>w.display.to-S.display.to)[0]||null,f=async(T,S,w)=>{let E=null;if(T.transition?.prevClipId&&(E=t.find(U=>U.id===T.transition.prevClipId)||null),E||(E=d(T)),!E)return null;const P=E.duration>0?E.duration:0,C=Math.max(0,Math.min(S-E.display.from,P)),{video:A}=await w(E,C);return A},p=(T,S,w)=>{if(!e)return;e.renderer.render({container:h,target:w,clear:!0});const E=new Ue(S instanceof M?S:M.from(S));E.x=T.center.x,E.y=T.center.y,E.anchor.set(.5,.5);const P=E.texture.width||1,C=E.texture.height||1,A=T.width&&T.width!==0?Math.abs(T.width)/P:1,U=T.height&&T.height!==0?Math.abs(T.height)/C:1;T.flip==="horizontal"?(E.scale.x=-A,E.scale.y=U):T.flip==="vertical"?(E.scale.x=A,E.scale.y=-U):(E.scale.x=A,E.scale.y=U),E.rotation=(T.flip==null?1:-1)*T.angle,E.alpha=T.opacity;const D=T.style||{},$=D.borderRadius||0;let pe=null;$>0&&(pe=new xe,pe.roundRect(-P/2,-C/2,P,C,Math.min($,P/2,C/2)),pe.fill({color:16777215,alpha:1}),E.addChild(pe),E.mask=pe);const k=D.stroke;let F=null;if(k&&k.width>0){F=new xe;const ie=Te(k.color)??16777215,we=k.width;if(F.setStrokeStyle({width:we,color:ie,alignment:1}),$>0){const ce=Math.min($,P/2,C/2);F.roundRect(-P/2,-C/2,P,C,ce)}else F.rect(-P/2,-C/2,P,C);F.stroke(),E.addChild(F)}const ne=D.dropShadow;let G=null;if(ne&&(ne.blur>0||ne.distance>0)){G=new xe;const ie=Te(ne.color)??0,we=ne.alpha??.5,ce=ne.distance??0,Ce=ne.angle??0,Oe=Math.cos(Ce)*ce,N=Math.sin(Ce)*ce;if($>0){const K=Math.min($,P/2,C/2);G.roundRect(-P/2+Oe,-C/2+N,P,C,K)}else G.rect(-P/2+Oe,-C/2+N,P,C);G.fill({color:ie,alpha:we}),E.addChildAt(G,0)}e.renderer.render({container:E,target:w,clear:!1}),S instanceof M||E.texture.destroy(!0),F&&F.destroy(),pe&&pe.destroy(),G&&G.destroy(),E.destroy()};let g=null,m=null,x=null;r&&e!=null&&(g=new re,m=new re,x=new re,m.sortableChildren=!0,x.sortableChildren=!0,e.stage.addChild(m),e.stage.addChild(x),g.visible=!1,e.stage.addChild(g));const _=[...t].sort((T,S)=>T.zIndex-S.zIndex);return{render:async T=>{const S=[];let w=!1,E=!1;const P=new Map,C=async(A,U)=>{const D=`${A.id}_${U}`;if(P.has(D))return P.get(D);const $=await A.getFrame(U);return P.set(D,$),$};for(const A of a.values())A.visible=!1;for(const A of _){if(s.aborted)break;if(T<A.display.from||A.expired){if(r&&e!=null){const F=n.get(A);F&&await F.updateFrame(null)}continue}const U=T-A.display.from,D=U*A.playbackRate;A.animate(D);const{video:$,audio:pe,done:k}=await C(A,U);if(S.push(pe),r&&e!=null&&m!=null){if((A instanceof Me||A instanceof _i)&&A.transition&&U>=0&&U<=A.transition.duration){const G=await f(A,T,C),ie=$;if(G&&ie){const we=U/A.transition.duration,ce=d(A);ce?p(ce,G,l):e.renderer.render({container:h,target:l,clear:!0}),p(A,ie,c);let Ce=o.get(A.id);Ce||(Ce=nf({name:A.transition.name,renderer:e.renderer}),o.set(A.id,Ce));const Oe=Ce.render({width:e.renderer.width,height:e.renderer.height,from:l,to:c,progress:we});let N=a.get(A.id);N||(N=new Ue,N.label=`TransitionSprite_${A.id}`,a.set(A.id,N),m.addChild(N)),N.texture=Oe,N.visible=!0,N.x=0,N.y=0,N.width=e.renderer.width,N.height=e.renderer.height,N.anchor.set(0,0),N.zIndex=A.zIndex,E=!0;const K=n.get(A);if(K){const me=K.getRoot();me&&(me.visible=!1)}if(ce){const me=n.get(ce);if(me){const Ie=me.getRoot();Ie&&(Ie.visible=!1)}}continue}}let ne=n.get(A);ne==null&&$!=null&&(ne=new gn(e,A,m),n.set(A,ne)),ne!=null&&($!=null?(E=!0,await ne.updateFrame($)):await ne.updateFrame(null)),ne?.updateTransforms()}if(A.duration>0&&T>A.display.from+A.duration||k){if(A.main&&(w=!0),A.expired=!0,r){const F=n.get(A);if(F!=null){const ne=F.getRoot();ne&&(ne.visible=!1)}}}else if(r){const F=n.get(A);F?.updateTransforms()}}if(r&&e!=null&&g!=null&&m!=null&&x!=null){let A=null;for(const U of t)if(U instanceof ct&&T>=U.display.from&&T<U.display.from+U.duration){A={id:U.id,key:U.effect.key,startTime:U.display.from,duration:U.duration};break}if(!A)for(const U of t){if(U.effects&&U.effects.length>0){for(const D of U.effects)if(T>=D.startTime&&T<D.startTime+D.duration){A=D;break}}if(A)break}x.removeChildren();for(const U of n.values()){const D=U.getRoot();D&&D.parent!==m&&(D.parent&&D.parent.removeChild(D),m.addChild(D))}if(A){const{key:U,startTime:D,duration:$,id:pe}=A,k=T-D,F=$>0?Math.min(Math.max(k/$,0),1):0,ne=t.some(G=>G.id===pe&&G instanceof ct);for(const G of t){let ie=!1;if(ne?ie=G.id!==pe&&!(G instanceof ct):ie=!!G.effects&&G.effects.some(we=>we.id===pe),ie){const we=n.get(G);if(we){const ce=we.getRoot();ce&&(ce.parent&&ce.parent.removeChild(ce),g.addChild(ce))}}}if(g.children.length>0){let G=u.get(pe);if(!G)try{const ie=sf({name:U,renderer:e.renderer});ie&&ie.filter&&(G={filter:ie.filter,render:ie.render},u.set(pe,G))}catch(ie){console.warn("Failed to create effect",U,ie)}if(G){const{filter:ie,render:we}=G;ie.resources&&ie.resources.effectUniforms&&(ie.resources.effectUniforms.uniforms.uTime=F);const ce=e.renderer.width,Ce=e.renderer.height,Oe=Ge.create({width:ce,height:Ce});if(g.visible=!0,e.renderer.render({container:g,target:Oe,clear:!0}),g.visible=!1,we){const N=we({canvasTexture:Oe,progress:F,width:ce,height:Ce}),K=new Ue(N);K.width=ce,K.height=Ce,x.addChild(K)}}}}}return r&&e!=null&&e.render(),{audios:S,mainSprDone:w,hasVideo:E}},cleanup:()=>{l&&l.destroy(!0),c&&c.destroy(!0),h&&h.destroy(!0);for(const T of a.values())T.destroy();a.clear(),o.clear(),g&&g.destroy({children:!0}),m&&m.destroy({children:!0}),x&&x.destroy({children:!0}),n.forEach(T=>{T.destroy()}),n.clear()}}}function ok(i){const{canvas:e,outputAudio:t,muxer:s,hasVideoTrack:r,timeSlice:n}=i;let o=0;const a=Math.floor(3*i.fps),l=ak(1024);return(c,h,u)=>{if(t!==!1)for(const d of l(c,h))s.encodeAudio(d);if(r&&u)try{const d=new VideoFrame(e,{duration:n,timestamp:c});s.encodeVideo(d,{keyFrame:o%a===0}),o+=1}catch(d){console.warn("Failed to create VideoFrame from canvas, skipping frame:",d)}}}function ak(i){const e=i*le.channelCount,t=new Float32Array(e*3);let s=0,r=0;const n=i/le.sampleRate*1e6,o=new Float32Array(e),a=l=>{let c=0;const h=Math.floor(s/e),u=[];for(let d=0;d<h;d++)u.push(new AudioData({timestamp:r,numberOfChannels:le.channelCount,numberOfFrames:i,sampleRate:le.sampleRate,format:"f32",data:t.subarray(c,c+e)})),c+=e,r+=n;for(t.set(t.subarray(c,s),0),s-=c;l-r>n;)u.push(new AudioData({timestamp:r,numberOfChannels:le.channelCount,numberOfFrames:i,sampleRate:le.sampleRate,format:"f32",data:o})),r+=n;return u};return(l,c)=>{const h=Math.max(...c.map(u=>u[0]?.length??0));for(let u=0;u<h;u++){let d=0,f=0;for(let p=0;p<c.length;p++){const g=c[p][0]?.[u]??0,m=c[p][1]?.[u]??g;d+=g,f+=m}t[s]=d,t[s+1]=f,s+=2}return a(l)}}class lk extends xe{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(e,t=1){const r=1.5*t;this.clear(),this.setStrokeStyle({width:r,color:165063}).rect(e.x,e.y,e.width,e.height).stroke(),this.hitArea=e}}class Ht extends xe{#e=!1;handle;cursor;callbacks;constructor(e,t,s){super(),this.handle=e,this.cursor=t,this.callbacks=s,this.eventMode="static",this.#a(),this.on("pointerdown",this.#i),this.on("globalpointermove",this.#r),this.on("pointerup",this.#l),this.on("pointerupoutside",this.#l)}#a(){this.clear();const e=165063;if(this.handle==="rot")this.circle(0,0,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:13421772}),this.moveTo(0,-4),this.arc(0,0,4,-Math.PI/2,Math.PI,!1),this.stroke({width:1,color:0}),this.moveTo(0,-8),this.lineTo(-3,-5),this.lineTo(0,-2),this.stroke({width:1,color:0,cap:"round",join:"round"}),this.hitArea=new Zr(0,0,24);else if(["ml","mr","mt","mb"].includes(this.handle)){const t=this.handle==="ml"||this.handle==="mr",s=t?6:24,r=t?24:6;this.roundRect(-s/2,-r/2,s,r,3),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new H(-15,-15,30,30)}else this.rect(-4,-4,8,8),this.fill({color:"#ffffff"}),this.stroke({width:1,color:e}),this.hitArea=new H(-15,-15,30,30)}#i=e=>{this.#e=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,e.global),e.stopPropagation()};#r=e=>{this.#e&&(this.callbacks.updateDrag(this.handle,e.global),e.stopPropagation())};#l=e=>{this.#e&&(this.#e=!1,this.cursor="pointer",this.callbacks.endDrag(),e.stopPropagation())}}const L_={delta:new O};class ck extends re{group;wireframe=new lk;selectionOutlines=new xe;isDragging=!1;lastPointer=new X;activeHandle=null;#e;#a=new Map;#i=new X;#r=0;#l=0;#c=new H;#s=new X;#h=new H;#t=[new X,new X,new X,new X];#n=1;#o=1;opts;constructor(e){super(),this.opts=e,this.group=e.group,this.eventMode="static";const t={beginDrag:(s,r)=>this.#v(s,r),updateDrag:(s,r)=>this.#b(s,r),endDrag:()=>this.#m()};this.#e={tl:new Ht("tl","nwse-resize",t),tr:new Ht("tr","nesw-resize",t),bl:new Ht("bl","nesw-resize",t),br:new Ht("br","nwse-resize",t),ml:new Ht("ml","ew-resize",t),mr:new Ht("mr","ew-resize",t),mt:new Ht("mt","ns-resize",t),mb:new Ht("mb","ns-resize",t),rot:new Ht("rot","crosshair",{beginDrag:(s,r)=>this.#w(r),updateDrag:(s,r)=>this.#S(r),endDrag:()=>this.#m()})},this.addChild(this.selectionOutlines,this.wireframe,...Object.values(this.#e)),this.#x(),this.visible=!1,Ze.shared.addOnce(()=>{!this.destroyed&&this.parent&&(this.#u(),this.visible=!0)})}#x(){this.on("pointerdown",this.#_),this.on("pointerup",this.#p),this.on("pointerupoutside",this.#p),this.on("globalpointermove",this.#y)}#u(){if(this.group.length===1){const e=this.group[0];this.#r=e.rotation;const t=this.#f(e);let s,r;this.opts.clip?(s=this.opts.clip.width,r=this.opts.clip.height):(s=t.width,r=t.height);const n=e.toGlobal(new X(0,0));this.#i.set(n.x,n.y),this.#h.copyFrom(new H(-s/2,-r/2,s,r))}else{let e=1/0,t=1/0,s=-1/0,r=-1/0;if(this.parent)for(const c of this.group){const h=this.#f(c);this.#t[0].set(h.x,h.y),this.#t[1].set(h.x+h.width,h.y),this.#t[2].set(h.x+h.width,h.y+h.height),this.#t[3].set(h.x,h.y+h.height);for(const u of this.#t)c.toGlobal(u,u),this.toLocal(u,void 0,u),e=Math.min(e,u.x),t=Math.min(t,u.y),s=Math.max(s,u.x),r=Math.max(r,u.y)}const n=s-e,o=r-t,a=e+n/2,l=t+o/2;if(this.#h.copyFrom(new H(-n/2,-o/2,n,o)),this.parent){const c=this.toGlobal(new X(a,l));this.#i.set(c.x,c.y)}}this.#d()}#f(e){const t=e.children.filter(l=>l.label!=="ShadowContainer");if(t.length===0){const l=e.getLocalBounds();return new H(l.minX,l.minY,l.maxX-l.minX,l.maxY-l.minY)}const s=t.find(l=>l.label==="MainSprite");if(s){const l=s.getLocalBounds(),c=s.localTransform,h=c.apply(new X(l.x,l.y)),u=c.apply(new X(l.x+l.width,l.y)),d=c.apply(new X(l.x+l.width,l.y+l.height)),f=c.apply(new X(l.x,l.y+l.height)),p=Math.min(h.x,u.x,d.x,f.x),g=Math.max(h.x,u.x,d.x,f.x),m=Math.min(h.y,u.y,d.y,f.y),x=Math.max(h.y,u.y,d.y,f.y);return new H(p,m,g-p,x-m)}let r=1/0,n=1/0,o=-1/0,a=-1/0;for(const l of t){const c=l.getBounds(),h=e.toLocal(new X(c.minX,c.minY)),u=e.toLocal(new X(c.maxX,c.maxY));r=Math.min(r,h.x,u.x),n=Math.min(n,h.y,u.y),o=Math.max(o,h.x,u.x),a=Math.max(a,h.y,u.y)}return new H(r,n,o-r,a-n)}updateBounds(){this.#u()}#_=e=>{this.#u(),this.isDragging=!0,this.lastPointer.copyFrom(e.global),this.cursor="grabbing"};#p=()=>{this.isDragging&&this.emit("transformEnd"),this.isDragging=!1,this.activeHandle=null,this.cursor="default"};#y=e=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const t=this.parent.toLocal(this.lastPointer),s=this.parent.toLocal(e.global),r=s.x-t.x,n=s.y-t.y;for(const l of this.group)l.x+=r,l.y+=n;const o=e.global.x-this.lastPointer.x,a=e.global.y-this.lastPointer.y;this.#i.x+=o,this.#i.y+=a,this.lastPointer.copyFrom(e.global),this.#d(),this.emit("transforming")};#v(e,t){this.#u(),this.isDragging=!0,this.activeHandle=e,this.#a.clear();for(const s of this.group)this.#a.set(s,s.localTransform.clone());this.rotation=this.#r,this.#c.copyFrom(this.#h),this.#A(e)}#b(e,t){this.#T(e,t)}async#T(e,t){const s=this.#s,r=this.#E(e,this.toLocal(t),s),n=r.width/this.#c.width,o=r.height/this.#c.height,a=this.toGlobal(s);if(this.opts.clip&&this.opts.clip.type==="Text"){const c=r.width;this.emit("textClipResize",{handle:e,newWidth:c,newHeight:r.height,pivotWorld:a,proposed:r,sx:n,sy:o})}else this.#g(this.#I(a,this.#r,n,o));this.#h.copyFrom(r),this.#d(),this.emit("transforming")}#w(e){this.#u(),this.isDragging=!0,this.activeHandle="rot",this.#a.clear();for(const t of this.group)this.#a.set(t,t.localTransform.clone());this.#l=Math.atan2(e.y-this.#i.y,e.x-this.#i.x)}#S(e){const s=Math.atan2(e.y-this.#i.y,e.x-this.#i.x)-this.#l,r=this.#r+s;this.#g(this.#P(this.#i,s)),this.rotation=r,this.#d(r),this.emit("transforming")}#m(){this.isDragging=!1,this.#r=this.rotation,this.activeHandle=null,this.#d(this.#r),this.emit("transformEnd")}#d(e=this.#r){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#i)),this.rotation=e;const s=1/((this.parent?Math.abs(this.parent.worldTransform.a):1)||1),r=this.#h;this.wireframe.draw(r,s);const n=r.x+r.width/2,o=r.y+r.height/2,a=this.opts.clip?.getVisibleHandles?.()??["tl","tr","bl","br","ml","mr","mt","mb","rot"],l=[this.#e.tl,this.#e.tr,this.#e.bl,this.#e.br,this.#e.ml,this.#e.mr,this.#e.mt,this.#e.mb,this.#e.rot];for(const c of l)c.scale.set(s);this.#e.tl.visible=a.includes("tl"),this.#e.tr.visible=a.includes("tr"),this.#e.bl.visible=a.includes("bl"),this.#e.br.visible=a.includes("br"),this.#e.ml.visible=a.includes("ml"),this.#e.mr.visible=a.includes("mr"),this.#e.mt.visible=a.includes("mt"),this.#e.mb.visible=a.includes("mb"),this.#e.rot.visible=a.includes("rot"),this.#e.tl.position.set(r.x,r.y),this.#e.tr.position.set(r.x+r.width,r.y),this.#e.bl.position.set(r.x,r.y+r.height),this.#e.br.position.set(r.x+r.width,r.y+r.height),this.#e.ml.position.set(r.x,o),this.#e.mr.position.set(r.x+r.width,o),this.#e.mt.position.set(n,r.y),this.#e.mb.position.set(n,r.y+r.height),this.#e.rot.position.set(n,r.y-30*s),this.#C(s)}#C(e){if(this.selectionOutlines.clear(),this.group.length<=1||!this.parent)return;const t={width:1*e,color:43775,alpha:1};for(const s of this.group){const r=this.#f(s);this.#t[0].set(r.x,r.y),this.#t[1].set(r.x+r.width,r.y),this.#t[2].set(r.x+r.width,r.y+r.height),this.#t[3].set(r.x,r.y+r.height);for(const n of this.#t)s.toGlobal(n,n),this.toLocal(n,void 0,n);this.selectionOutlines.moveTo(this.#t[0].x,this.#t[0].y).lineTo(this.#t[1].x,this.#t[1].y).lineTo(this.#t[2].x,this.#t[2].y).lineTo(this.#t[3].x,this.#t[3].y).closePath().stroke(t)}}#A(e){const t=this.#c;if(this.opts.centeredScaling){this.#s.set(t.x+t.width/2,t.y+t.height/2);return}e==="tl"?this.#s.set(t.x+t.width,t.y+t.height):e==="tr"?this.#s.set(t.x,t.y+t.height):e==="bl"?this.#s.set(t.x+t.width,t.y):e==="br"?this.#s.set(t.x,t.y):e==="ml"?this.#s.set(t.x+t.width,t.y+t.height/2):e==="mr"?this.#s.set(t.x,t.y+t.height/2):e==="mt"?this.#s.set(t.x+t.width/2,t.y+t.height):e==="mb"&&this.#s.set(t.x+t.width/2,t.y)}#E(e,t,s){if(this.opts.centeredScaling){const n=Math.max(this.#n,Math.abs(t.x-s.x)*2),o=Math.max(this.#o,Math.abs(t.y-s.y)*2);return new H(s.x-n/2,s.y-o/2,n,o)}if(e==="tl"){const n=Math.min(t.x,s.x-this.#n),o=Math.min(t.y,s.y-this.#o);return new H(n,o,s.x-n,s.y-o)}if(e==="tr"){const n=Math.max(t.x,s.x+this.#n),o=Math.min(t.y,s.y-this.#o);return new H(s.x,o,n-s.x,s.y-o)}if(e==="bl"){const n=Math.min(t.x,s.x-this.#n),o=Math.max(t.y,s.y+this.#o);return new H(n,s.y,s.x-n,o-s.y)}if(e==="br"){const n=Math.max(t.x,s.x+this.#n),o=Math.max(t.y,s.y+this.#o);return new H(s.x,s.y,n-s.x,o-s.y)}const r=this.#c;if(e==="ml"){const n=Math.min(t.x,s.x-this.#n);return new H(n,r.y,s.x-n,r.height)}if(e==="mr"){const n=Math.max(t.x,s.x+this.#n);return new H(s.x,r.y,n-s.x,r.height)}if(e==="mt"){const n=Math.min(t.y,s.y-this.#o);return new H(r.x,n,r.width,s.y-n)}if(e==="mb"){const n=Math.max(t.y,s.y+this.#o);return new H(r.x,s.y,r.width,n-s.y)}return new H(s.x,s.y,this.#n,this.#o)}#I(e,t,s,r){return L_.delta.identity().translate(-e.x,-e.y).rotate(-t).scale(s,r).rotate(t).translate(e.x,e.y)}#P(e,t){return L_.delta.identity().translate(-e.x,-e.y).rotate(t).translate(e.x,e.y)}#g(e){for(const t of this.group){const s=this.#a.get(t),r=t.parent;if(!s||!r)continue;const n=r.worldTransform.clone().invert(),o=r.worldTransform.clone().append(s),a=e.clone().append(o),l=n.clone().append(a);t.setFromMatrix(l)}}}class hk{constructor(e){this.studio=e}selectedClips=new Set;activeTransformer=null;interactiveClips=new Set;selectionGraphics=null;isDragSelecting=!1;dragSelectionStart=new X;isUpdatingTextRealtime=!1;textClipResizedWidth=null;textClipResizeHandle=null;textClipResizedSx=null;textClipResizedSy=null;init(e,t){this.selectionGraphics=new xe,this.selectionGraphics.visible=!1,this.selectionGraphics.zIndex=1e3,t.addChild(this.selectionGraphics),e.stage.eventMode="static",e.stage.hitArea=e.screen,e.stage.on("pointerdown",s=>this.onStagePointerDown(s)),e.stage.on("globalpointermove",s=>this.onStagePointerMove(s)),e.stage.on("pointerup",()=>this.onStagePointerUp()),e.stage.on("pointerupoutside",()=>this.onStagePointerUp())}onStagePointerDown(e){e.target===this.studio.pixiApp?.stage&&(e.shiftKey||this.deselectClip(),this.isDragSelecting=!0,this.studio.artboard?.toLocal(e.global,void 0,this.dragSelectionStart),this.selectionGraphics&&(this.selectionGraphics.clear(),this.selectionGraphics.visible=!0))}onStagePointerMove(e){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const t=this.studio.artboard.toLocal(e.global),s=Math.min(this.dragSelectionStart.x,t.x),r=Math.min(this.dragSelectionStart.y,t.y),n=Math.abs(t.x-this.dragSelectionStart.x),o=Math.abs(t.y-this.dragSelectionStart.y);this.selectionGraphics.clear(),this.selectionGraphics.rect(s,r,n,o).fill({color:703971,alpha:.3}),this.selectionGraphics.rect(s,r,n,o).stroke({width:2,color:703971})}}onStagePointerUp(){if(this.isDragSelecting&&this.selectionGraphics&&this.studio.artboard){const e=this.selectionGraphics.getBounds(),t=[],s=new H(e.x,e.y,e.width,e.height);if(s.width>2||s.height>2){for(const r of this.studio.clips){const n=this.studio.spriteRenderers.get(r);if(!n)continue;const o=n.getRoot();if(!o||!o.visible)continue;const a=o.getBounds();s.x<a.x+a.width&&s.x+s.width>a.x&&s.y<a.y+a.height&&s.y+s.height>a.y&&t.push(r)}if(t.length>0)for(const r of t)this.selectClip(r,!0)}this.selectionGraphics.clear(),this.selectionGraphics.visible=!1,this.isDragSelecting=!1}}setupSpriteInteractivity(e){if(this.interactiveClips.has(e))return;const t=this.studio.spriteRenderers.get(e);if(t==null)return;const s=t.getRoot();s!=null&&(s.eventMode="static",s.cursor="pointer",s.on("pointerdown",r=>{const n=this.getTopmostClipAtPoint(r.global);n&&this.selectClip(n,r.shiftKey)}),this.interactiveClips.add(e))}getTopmostClipAtPoint(e){if(!this.studio.pixiApp)return null;let t=null,s=-1/0;for(const r of this.interactiveClips){const n=this.studio.spriteRenderers.get(r);if(!n)continue;const o=n.getRoot();if(!o||!o.visible)continue;const a=o.toLocal(e),l=o.getLocalBounds();a.x>=l.minX&&a.x<=l.maxX&&a.y>=l.minY&&a.y<=l.maxY&&r.zIndex>s&&(s=r.zIndex,t=r)}return t}selectClip(e,t=!1){if(!(this.studio.destroyed||this.studio.pixiApp==null)){if(t||this.deselectClip(),t&&this.selectedClips.has(e)){this.selectedClips.delete(e),this.recreateTransformer(),this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)});return}this.selectedClips.add(e),this.recreateTransformer(),t?this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)}):this.studio.emit("selection:created",{selected:Array.from(this.selectedClips)})}}selectClipsByIds(e){const t=this.studio.clips.filter(s=>e.includes(s.id));this.setSelection(t)}setSelection(e){if(!(this.studio.destroyed||this.studio.pixiApp==null)&&!(this.selectedClips.size===e.length&&e.every(t=>this.selectedClips.has(t)))){for(const t of this.selectedClips)this.syncSpriteToClipProperties(t);this.destroyTransformer(),this.selectedClips.clear();for(const t of e)this.selectedClips.add(t);this.selectedClips.size>0?(this.createTransformer(),this.studio.emit("selection:updated",{selected:Array.from(this.selectedClips)})):this.studio.emit("selection:cleared",{deselected:[]})}}deselectClip(){if(this.selectedClips.size>0)for(const t of this.selectedClips)this.syncSpriteToClipProperties(t);this.destroyTransformer();const e=Array.from(this.selectedClips);this.selectedClips.clear(),e.length>0&&this.studio.emit("selection:cleared",{deselected:e})}async move(e,t){if(this.selectedClips.size===0)return;const s=[];for(const r of this.selectedClips)s.push({id:r.id,updates:{left:(r.left??0)+e,top:(r.top??0)+t}});await this.studio.updateClips(s),this.activeTransformer&&this.activeTransformer.updateBounds()}clear(){this.deselectClip(),this.interactiveClips.clear()}recreateTransformer(){this.destroyTransformer(),this.selectedClips.size>0&&this.createTransformer()}destroyTransformer(){this.activeTransformer!=null&&(this.activeTransformer.parent!=null&&this.activeTransformer.parent.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null)}createTransformer(){if(this.studio.destroyed||this.studio.artboard==null||this.selectedClips.size===0)return;const e=[];let t=null;for(const r of this.selectedClips){const n=this.studio.spriteRenderers.get(r);if(n==null)continue;const o=n.getRoot();o!=null&&(e.push(o),this.selectedClips.size===1&&(t=r))}if(e.length===0){console.warn("Cannot create transformer: no sprites found");return}this.activeTransformer=new ck({group:e,clip:t});let s=null;this.activeTransformer.on("transforming",()=>{s===null&&(s=requestAnimationFrame(()=>{s=null,this.syncSelectedClipsTransformsRealtime()}))}),this.activeTransformer.on("textClipResize",r=>{this.textClipResizedWidth=r.newWidth,this.textClipResizeHandle=r.handle,this.textClipResizedSx=r.sx,this.textClipResizedSy=r.sy}),this.activeTransformer.on("transformEnd",async()=>{s!==null&&(cancelAnimationFrame(s),s=null),await this.syncSelectedClipsTransforms();for(const r of this.selectedClips)this.studio.emit("clip:updated",{clip:r})}),this.activeTransformer.on("pointerdown",r=>{const n=this.getTopmostClipAtPoint(r.global);n&&!this.selectedClips.has(n)&&(this.selectClip(n,r.shiftKey),r.stopPropagation())}),this.studio.artboard.addChild(this.activeTransformer)}async syncSelectedClipsTransformsRealtime(){if(!(this.selectedClips.size===0||this.activeTransformer==null)&&!this.isUpdatingTextRealtime){this.isUpdatingTextRealtime=!0;try{const e=this.activeTransformer.activeHandle;if(e!=="mr"&&e!=="ml")return;for(const t of this.selectedClips){if(!(t instanceof gt))continue;const s=this.studio.spriteRenderers.get(t);if(s==null)continue;const r=s.getRoot(),n=s.getSprite();if(r==null||n==null||n.texture==null)continue;const o=Math.abs(r.scale.x*n.scale.x);if(o===1)continue;const a=t.left,l=t.top,c=t.width,h=n.texture.width,u=o*h;await t.updateStyle({wordWrap:!0,wordWrapWidth:u});const d=await t.getTexture();d&&(await s.updateFrame(d),n.scale.set(1,1),r.scale.set(1,1),e==="ml"?t.left=a+c-t.width:t.left=a,t.top=l,r.x=t.left+t.width/2,r.y=t.top+t.height/2,this.activeTransformer.updateBounds())}}finally{this.isUpdatingTextRealtime=!1}}}async syncSelectedClipsTransforms(){if(!(this.selectedClips.size===0||this.activeTransformer==null)){for(const e of this.selectedClips){const t=this.studio.spriteRenderers.get(e);if(t==null)continue;const s=t.getRoot(),r=t.getSprite();if(s==null||r==null||r.texture==null)continue;const n=r.texture.width,o=r.texture.height,a=Math.abs(s.scale.x*r.scale.x)*n,l=Math.abs(s.scale.y*r.scale.y)*o,c=(e instanceof gt||e instanceof ei)&&this.textClipResizedWidth!==null?this.textClipResizedWidth:a,h=e.width,d=(e.style?.fontSize??16)*Math.max(this.textClipResizedSx||1,this.textClipResizedSy||1);let f=s.x;const p=s.y-l/2,g=s.x-c/2;if(e instanceof gt&&this.textClipResizedWidth!==null){const x={wordWrap:!0,wordWrapWidth:c};this.textClipResizeHandle==="mr"?(f=e.left+c/2,s.x=f):this.textClipResizeHandle==="ml"?(f=e.left+c/2-(c-h),s.x=f):["br","tr"].includes(this.textClipResizeHandle)?(f=e.left+c/2,x.fontSize=d):["bl","tl"].includes(this.textClipResizeHandle)&&(f=e.left+c/2-(c-h),x.fontSize=d),await e.updateStyle(x);const _=await e.getTexture();_&&(await t.updateFrame(_),e.width=c,e.height=_.height,this.textClipResizedWidth=null,e.left=f-e.width/2,e.top=s.y-e.height/2,r.scale.set(1,1),s.scale.set(1,1))}else{e.left=g,e.top=p,e.width=a,e.height=l;const x=e.flip==null?1:-1;e.angle=x*s.angle}}this.activeTransformer!=null&&this.activeTransformer.updateBounds();for(const e of this.selectedClips){const t=this.studio.spriteRenderers.get(e);t?.updateTransforms()}}}syncSpriteToClipProperties(e){const t=this.studio.spriteRenderers.get(e);if(t!=null){const s=t.getRoot(),r=t.getSprite();if(s!=null&&r!=null&&r.texture!=null){const n=r.texture.width,o=r.texture.height,a=Math.abs(s.scale.x*r.scale.x)*n,l=Math.abs(s.scale.y*r.scale.y)*o,c=s.x-a/2,h=s.y-l/2;e.left=c,e.top=h,e.width=a,e.height=l;const u=e.flip==null?1:-1;e.angle=u*s.angle,t.updateTransforms(),this.studio.emit("clip:updated",{clip:e})}}}async deleteSelected(){return this.studio.deleteSelected()}}class uk{constructor(e){this.studio=e}isPlaying=!1;currentTime=0;maxDuration=0;playStartTime=0;playStartTimestamp=0;rafId=null;playbackElements=new Map;setMaxDuration(e){this.maxDuration=e}async play(){if(!(this.isPlaying||this.studio.destroyed)){if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){console.warn("Cannot play: invalid duration",this.maxDuration);return}this.isPlaying||(this.isPlaying=!0),this.playStartTime=this.currentTime,this.playStartTimestamp=performance.now();for(const[e,{element:t}]of this.playbackElements.entries()){if(!(this.currentTime>=e.display.from&&(e.display.to===0||this.currentTime<=e.display.to))){this.isPlaybackCapable(e)&&e.pause(t);continue}const r=(this.currentTime-e.display.from)/1e6;this.isPlaybackCapable(e)&&await e.play(t,r)}this.renderLoop(),this.studio.emit("play",{isPlaying:!0})}}pause(){this.isPlaying=!1,this.rafId!=null&&(cancelAnimationFrame(this.rafId),this.rafId=null);for(const[e,{element:t}]of this.playbackElements.entries())this.isPlaybackCapable(e)&&e.pause(t);this.studio.emit("pause",{isPlaying:!1})}async stop(){this.pause(),await this.seek(0)}async seek(e){if(this.studio.destroyed)return;const t=this.isPlaying;this.playStartTime=Math.max(0,Math.min(e,this.maxDuration)),this.playStartTimestamp=performance.now(),this.currentTime=this.playStartTime;for(const[s,{element:r}]of this.playbackElements.entries()){if(!(this.currentTime>=s.display.from&&(s.display.to===0||this.currentTime<=s.display.to))){this.isPlaybackCapable(s)&&s.pause(r);continue}const o=(this.currentTime-s.display.from)/1e6;this.isPlaybackCapable(s)&&await s.seek(r,o)}if(await this.studio.updateFrame(this.currentTime),this.studio.emit("currentTime",{currentTime:this.currentTime}),t){this.isPlaying=!0;for(const[s,{element:r}]of this.playbackElements.entries()){if(!(this.currentTime>=s.display.from&&(s.display.to===0||this.currentTime<=s.display.to)))continue;const o=(this.currentTime-s.display.from)/1e6;this.isPlaybackCapable(s)&&await s.play(r,o)}}}async frameNext(){const t=1e6/(this.studio.opts.fps||30),s=Math.min(this.currentTime+t,this.maxDuration);await this.seek(s)}async framePrev(){const t=1e6/(this.studio.opts.fps||30),s=Math.max(0,this.currentTime-t);await this.seek(s)}async renderLoop(){if(!this.isPlaying||this.studio.destroyed||this.studio.pixiApp==null)return;if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){this.pause();return}const e=async()=>{if(!this.isPlaying||this.studio.destroyed||this.studio.pixiApp==null)return;if(this.currentTime>=this.maxDuration){this.currentTime=this.maxDuration,this.pause();return}const s=(performance.now()-this.playStartTimestamp)*1e3;this.currentTime=Math.min(this.playStartTime+s,this.maxDuration),this.studio.emit("currentTime",{currentTime:this.currentTime});try{await this.studio.updateFrame(this.currentTime)}catch(r){console.warn("Error updating frame:",r)}this.isPlaying&&(this.rafId=requestAnimationFrame(e))};e()}isPlaybackCapable(e){return"play"in e&&"pause"in e&&"seek"in e}}class Ji{static instance;fonts=new Map;constructor(){}static getInstance(){return Ji.instance||(Ji.instance=new Ji),Ji.instance}async addFont(e){if(!this.fonts.has(e.name))try{const s=await new FontFace(e.name,`url(${e.url})`).load();document.fonts.add(s),this.fonts.set(e.name,s)}catch(t){console.error(`Failed to load font ${e.name}:`,t)}}async loadFonts(e){await Promise.all(e.map(t=>this.addFont(t)))}removeFont(e){const t=this.fonts.get(e);t&&(document.fonts.delete(t),this.fonts.delete(e))}clear(){this.fonts.forEach(e=>{document.fonts.delete(e)}),this.fonts.clear()}getLoadedFonts(){return Array.from(this.fonts.keys())}}const H_=Ji.getInstance();class dk{constructor(e){this.studio=e}tracks=[];clips=[];getTrackById(e){return this.tracks.find(t=>t.id===e)}getClipById(e){return this.clips.find(t=>t.id===e)}findTrackIdByClipId(e){for(const t of this.tracks)if(t.clipIds.includes(e))return t.id}getTrackIndex(e){return this.tracks.findIndex(t=>t.id===e)}addTrack(e){const t={id:e.id||`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:e.name,type:e.type,clipIds:[]};return this.tracks.push(t),this.studio.emit("track:added",{track:t}),t}async removeTrack(e){const t=this.tracks.findIndex(n=>n.id===e);if(t===-1)return;const r=[...this.tracks[t].clipIds];for(const n of r)await this.removeClipById(n);this.tracks.splice(t,1),this.studio.emit("track:removed",{trackId:e})}async addTransition(e,t=2e6,s,r){if(this.studio.destroyed)return;let n=null,o=null;if(console.log("[Studio] addTransition",{fromClipId:s,toClipId:r}),s&&r&&(n=this.getClipById(s)??null,o=this.getClipById(r)??null,console.log("[Studio] Found clips",{clipA:n,clipB:o})),!n||!o){console.warn("[Studio] Invalid fromClipId or toClipId",{fromClipId:s,toClipId:r});return}await Promise.all([n.ready,o.ready]);const a=t,l=o.display.from-a/2,c=l+a,h={key:e,name:e,duration:a,fromClipId:n.id,toClipId:o.id,start:Math.max(0,l),end:c},u=this.findTrackIdByClipId(o.id);if(u){const f=this.tracks.find(p=>p.id===u);if(f){const p=f.clipIds.map(g=>this.getClipById(g)).filter(g=>{if(!g||g.type!=="Transition")return!1;const m=g;return m.fromClipId===n.id&&m.toClipId===o.id});for(const g of p)await this.removeClip(g)}}this.studio.transitionRenderers.has(n.id)&&(this.studio.transitionRenderers.get(n.id)?.destroy(),this.studio.transitionRenderers.delete(n.id)),this.studio.transitionRenderers.has(o.id)&&(this.studio.transitionRenderers.get(o.id)?.destroy(),this.studio.transitionRenderers.delete(o.id)),n.transition={...h},o.transition={...h};const d=new Lt(e);d.duration=a,d.fromClipId=Math.max(0,l)===0?null:n.id,d.toClipId=o.id,d.fromClipId===null&&n&&(d.fromClipId=n.id),d.display.from=Math.max(0,l),d.display.to=c,await this.addClip(d,{trackId:u}),this.studio.seek(this.studio.currentTime)}async addClip(e,t){const s=Array.isArray(e)?e:[e];if(s.length===0)return;const{trackId:r,audioSource:n}=this.normalizeAddClipOptions(t);if(this.studio.destroyed)return;if(this.studio.pixiApp==null)throw new Error("Failed to initialize Pixi.js Application");const o=[];for(const a of s)await this.prepareClipForTimeline(a,r),o.push(a);await this.recalculateMaxDuration();for(const a of o)await this.setupClipVisuals(a,n);await this.studio.updateFrame(this.studio.currentTime),this.emitAddClipEvents(o,r)}normalizeAddClipOptions(e){let t,s;if(e&&(typeof e=="string"||e instanceof File||e instanceof Blob))t=e;else if(typeof e=="object"&&e!==null&&!("size"in e)){const r=e;t=r.audioSource,s=r.trackId}return{trackId:s,audioSource:t}}async prepareClipForTimeline(e,t){e.id||(e.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.includes(e)||this.clips.push(e),this.addClipToTrack(e,t);const s=async()=>{await this.studio.updateFrame(this.studio.currentTime);const r=this.studio.selection;r.activeTransformer!=null&&r.selectedClips.has(e)&&typeof r.activeTransformer.updateBounds=="function"&&r.activeTransformer.updateBounds()};e.on("propsChange",s),this.studio.clipListeners.set(e,s),this.studio.pixiApp!=null&&typeof e.setRenderer=="function"&&e.setRenderer(this.studio.pixiApp.renderer),await e.ready}addClipToTrack(e,t){if(t){const s=this.tracks.find(r=>r.id===t);if(s)s.clipIds.includes(e.id)||s.clipIds.push(e.id);else{const r={id:t,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(r),this.studio.emit("track:added",{track:r})}}else{const r={id:`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,name:`Track ${this.tracks.length+1}`,type:e.type,clipIds:[e.id]};this.tracks.unshift(r),this.studio.emit("track:added",{track:r})}}async setupClipVisuals(e,t){const s=this.studio.spriteRenderers.get(e);if(s){const n=this.studio.clipsNormalContainer,o=s.getRoot();o&&!o.parent&&n.addChild(o);return}const r=await e.ready;if(await this.setupPlaybackForClip(e,t),r.width>0&&r.height>0){const n=this.studio.clipsNormalContainer,o=e.type==="Video"&&this.isPlaybackCapable(e);if(!o||o&&e.tickInterceptor!=null){const a=new gn(this.studio.pixiApp,e,n);this.studio.spriteRenderers.set(e,a)}}this.studio.opts.interactivity&&this.studio.selection.setupSpriteInteractivity(e)}emitAddClipEvents(e,t){if(e.length!==0)if(e.length===1){const s=e[0],r=t||this.tracks.find(n=>n.clipIds.includes(s.id))?.id||"";this.studio.emit("clip:added",{clip:s,trackId:r})}else this.studio.emit("clips:added",{clips:e,trackId:t})}async removeClip(e,t={permanent:!0}){const{permanent:s}=t,r=this.clips.findIndex(h=>h===e);if(r===-1)return;if(e instanceof Lt){if(e.fromClipId){const h=this.getClipById(e.fromClipId);h&&"transition"in h&&delete h.transition}if(e.toClipId){const h=this.getClipById(e.toClipId);h&&"transition"in h&&delete h.transition}}this.studio.selection.selectedClips.has(e)&&this.studio.selection.deselectClip(),this.clips.splice(r,1);const n=[];for(const h of this.tracks){const u=h.clipIds.indexOf(e.id);u!==-1&&(h.clipIds.splice(u,1),n.push(h.id))}for(const h of n){const u=this.tracks.findIndex(d=>d.id===h);u!==-1&&this.tracks[u].clipIds.length===0&&(this.tracks.splice(u,1),this.studio.emit("track:removed",{trackId:h}))}this.studio.selection.interactiveClips.delete(e);const o=this.studio.clipListeners.get(e);o&&(e.off("propsChange",o),this.studio.clipListeners.delete(e));const a=this.studio.spriteRenderers.get(e);if(a!=null)if(s)a.destroy(),this.studio.spriteRenderers.delete(e);else{const h=a.getRoot();h&&h.parent&&h.parent.removeChild(h)}const l=this.studio.transport.playbackElements.get(e);l!=null&&s&&this.isPlaybackCapable(e)&&(e.cleanupPlayback(l.element,l.objectUrl),this.studio.transport.playbackElements.delete(e));const c=this.studio.videoSprites.get(e);c!=null&&this.studio.pixiApp!=null&&(c.parent&&c.parent.removeChild(c),s&&(c.destroy(),this.studio.videoSprites.delete(e))),await this.recalculateMaxDuration(),this.studio.emit("clip:removed",{clipId:e.id})}async removeClips(e,t={permanent:!0}){if(e.length!==0){for(const s of e){const r=this.clips.findIndex(c=>c===s);if(r===-1)continue;if(s instanceof Lt){if(s.fromClipId){const c=this.getClipById(s.fromClipId);c&&"transition"in c&&delete c.transition}if(s.toClipId){const c=this.getClipById(s.toClipId);c&&"transition"in c&&delete c.transition}}this.studio.selection.selectedClips.has(s)&&this.studio.selection.deselectClip(),this.clips.splice(r,1);for(const c of this.tracks){const h=c.clipIds.indexOf(s.id);h!==-1&&c.clipIds.splice(h,1)}this.studio.selection.interactiveClips.delete(s);const n=this.studio.clipListeners.get(s);n&&(s.off("propsChange",n),this.studio.clipListeners.delete(s));const o=this.studio.spriteRenderers.get(s);if(o!=null)if(t.permanent)o.destroy(),this.studio.spriteRenderers.delete(s);else{const c=o.getRoot();c&&c.parent&&c.parent.removeChild(c)}const a=this.studio.transport.playbackElements.get(s);a!=null&&t.permanent&&this.isPlaybackCapable(s)&&(s.cleanupPlayback(a.element,a.objectUrl),this.studio.transport.playbackElements.delete(s));const l=this.studio.videoSprites.get(s);l!=null&&this.studio.pixiApp!=null&&(l.parent&&l.parent.removeChild(l),t.permanent&&(l.destroy(),this.studio.videoSprites.delete(s)))}for(let s=this.tracks.length-1;s>=0;s--)if(this.tracks[s].clipIds.length===0){const r=this.tracks[s].id;this.tracks.splice(s,1),this.studio.emit("track:removed",{trackId:r})}await this.recalculateMaxDuration(),this.studio.emit("clips:removed",{clipIds:e.map(s=>s.id)})}}async removeClipById(e){const t=this.clips.find(s=>s.id===e);t&&await this.removeClip(t)}async updateClip(e,t){const s=this.clips.find(r=>r.id===e);s&&(await this.applyClipUpdate(s,t),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(s),this.studio.emit("clip:updated",{clip:s}))}async updateClips(e){const t=[];for(const{id:s,updates:r}of e){const n=this.clips.find(o=>o.id===s);n&&(await this.applyClipUpdate(n,r),t.push(n))}if(t.length!==0){await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime);for(const s of t)this.updateTransformer(s),this.studio.emit("clip:updated",{clip:s})}}async replaceClipsBySource(e,t){const s=this.clips.filter(r=>r.src===e);if(s.length!==0){this.studio.suspendRendering();for(const r of s){if(!this.clips.includes(r))continue;const n=this.findTrackIdByClipId(r.id);if(!n)continue;const o=this.getTrackById(n);if(!o)continue;const a=await t(r),l=async()=>{await this.studio.updateFrame(this.studio.currentTime),this.updateTransformer(a)};a.on("propsChange",l),this.studio.clipListeners.set(a,l),this.studio.pixiApp!=null&&typeof a.setRenderer=="function"&&a.setRenderer(this.studio.pixiApp.renderer),await a.ready;const c=this.clips.indexOf(r);c!==-1&&(this.clips[c]=a);const h=o.clipIds.indexOf(r.id);h!==-1&&(o.clipIds[h]=a.id),await this.setupClipVisuals(a);const u=this.studio.spriteRenderers.get(r);u&&(u.destroy(),this.studio.spriteRenderers.delete(r));const d=this.studio.videoSprites.get(r);d&&(d.parent&&d.parent.removeChild(d),d.destroy(),this.studio.videoSprites.delete(r));const f=this.studio.clipListeners.get(r);f&&(r.off("propsChange",f),this.studio.clipListeners.delete(r)),this.studio.selection.selectedClips.has(r)&&(this.studio.selection.selectedClips.delete(r),this.studio.selection.selectedClips.add(a)),this.studio.emit("clip:replaced",{oldClip:r,newClip:a,trackId:n})}await this.recalculateMaxDuration(),this.studio.resumeRendering(),await this.studio.updateFrame(this.studio.currentTime)}}async applyClipUpdate(e,t){if(e instanceof gt&&(await e.updateStyle(t),"style"in t&&delete t.style),Object.assign(e,t),t.display&&!t.duration?e.duration=t.display.to-t.display.from:t.duration&&(!t.display||!t.display.to)&&(e.display||(e.display={from:0,to:t.duration}),e.display.to=e.display.from+t.duration),t.display&&t.duration){const s=t.display.to-t.display.from;s!==t.duration&&(e.duration=s)}else e.display&&(e.display.to=e.display.from+e.duration)}updateTransformer(e){const t=this.studio.selection;t.selectedClips.has(e)&&t.activeTransformer&&t.activeTransformer.updateBounds()}exportToJSON(){const e=this.clips.map(r=>Ys(r,!1)),t=this.tracks.map(r=>({id:r.id,name:r.name,type:r.type,clipIds:[...r.clipIds]})),s=[];return this.clips.forEach(r=>{if(r.transition){const n=this.tracks.find(o=>o.clipIds.includes(r.id));if(n){const o=n.clipIds.indexOf(r.id);if(o>0){const a=n.clipIds[o-1];s.push({key:r.transition.name,duration:r.transition.duration,clips:[a,r.id]})}}}}),{tracks:t,clips:e,settings:{width:this.studio.opts.width,height:this.studio.opts.height,fps:this.studio.opts.fps,bgColor:this.studio.opts.bgColor}}}async loadFromJSON(e){if(await this.clear(),e.settings){const s=e.settings.width&&e.settings.width!==this.studio.opts.width||e.settings.height&&e.settings.height!==this.studio.opts.height;if(e.settings.width&&(this.studio.opts.width=e.settings.width),e.settings.height&&(this.studio.opts.height=e.settings.height),e.settings.fps&&(this.studio.opts.fps=e.settings.fps),e.settings.bgColor&&(this.studio.opts.bgColor=e.settings.bgColor),s&&this.studio.pixiApp!=null){const r=this.studio.opts.width,n=this.studio.opts.height;this.studio.pixiApp.renderer.resize(r,n),this.studio.opts.canvas&&(this.studio.opts.canvas.width=r,this.studio.opts.canvas.height=n)}}const t=[];if(e.clips){await this.ensureFontsForClips(e.clips);const s=new Map;if(e.tracks){for(const n of e.tracks)if(n.clipIds)for(const o of n.clipIds)s.set(o,n.id)}if(e.tracks)for(const n of e.tracks)this.tracks.push({id:n.id,name:n.name,type:n.type,clipIds:[]});for(const n of e.clips)t.push((async()=>{try{let o=n.id?s.get(n.id):void 0;if(n.type==="Transition"){const l=n,c=l.toClipId||l.fromClipId;c&&(o=s.get(c))}if(n.type!=="Text"&&n.type!=="Caption"&&n.type!=="Effect"&&n.type!=="Transition"&&(!n.src||n.src.trim()===""))return console.warn(`Skipping clip ${n.type} with empty source`,n),{clip:null};const a=await Ki(n);return(a.type==="Video"||a.type==="Image")&&(!n.width||!n.height)&&this.studio.opts.width&&this.studio.opts.height&&(typeof a.scaleToFit=="function"&&await a.scaleToFit(this.studio.opts.width,this.studio.opts.height),typeof a.centerInScene=="function"&&a.centerInScene(this.studio.opts.width,this.studio.opts.height)),{clip:a,intendedTrackId:o}}catch(o){return console.error(`Failed to load clip ${n.id||"unknown"}:`,o),{clip:null}}})());const r=await Promise.all(t);for(const{clip:n,intendedTrackId:o}of r)n&&(n.id||(n.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`),this.clips.push(n),this.addClipToTrack(n,o))}this.studio.pixiApp&&await Promise.all(this.clips.map(async s=>{const r=async()=>{await this.studio.updateFrame(this.studio.currentTime);const n=this.studio.selection;n.activeTransformer!=null&&n.selectedClips.has(s)&&typeof n.activeTransformer.updateBounds=="function"&&n.activeTransformer.updateBounds()};s.on("propsChange",r),this.studio.clipListeners.set(s,r),typeof s.setRenderer=="function"&&s.setRenderer(this.studio.pixiApp.renderer),await s.ready,await this.setupClipVisuals(s)}));for(const s of this.clips){const r=s.effects;if(Array.isArray(r))for(const n of r)this.studio.globalEffects.has(n.id)||this.studio.globalEffects.set(n.id,{id:n.id,key:n.key,startTime:n.startTime,duration:n.duration})}for(const s of this.clips)if(s instanceof Lt){const r={name:s.transitionEffect.key,key:s.transitionEffect.key,duration:s.duration,fromClipId:s.fromClipId,toClipId:s.toClipId,start:s.display.from,end:s.display.to};if(s.fromClipId){const n=this.getClipById(s.fromClipId);n&&(n.transition={...r})}if(s.toClipId){const n=this.getClipById(s.toClipId);n&&(n.transition={...r})}}await this.recalculateMaxDuration();try{await this.studio.updateFrame(this.studio.currentTime)}catch(s){console.error("[Studio] Failed to update initial frame:",s)}this.studio.emit("studio:restored",{clips:this.clips,tracks:this.tracks,settings:this.studio.opts})}async deleteSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e);if(t.length!==0)for(const s of t)await this.removeClip(s)}async duplicateSelected(){const e=this.studio.selection.selectedClips,t=Array.from(e);if(t.length===0)return;const s=[];for(const r of t){const n=this.findTrackIdByClipId(r.id);if(!n)continue;const o=this.tracks.find(u=>u.id===n);if(!o)continue;const a=Ys(r,!1),l=await Ki(a);l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const c=`track_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=`${o.name} (Copy)`;this.addTrack({id:c,name:h,type:o.type}),await this.addClip(l,{trackId:c}),s.push(l.id)}s.length>0&&this.studio.selection.selectClipsByIds(s)}async splitSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==1){console.warn("[Studio] Split requires exactly one selected clip");return}const s=t[0],r=e??this.studio.currentTime;if(r<=s.display.from||s.display.to>0&&r>=s.display.to){console.warn("[Studio] Split time is outside clip bounds");return}const n=Ys(s,!1),o=r-s.display.from,a=s.playbackRate||1,l=o*a,c={duration:o,display:{from:s.display.from,to:r}};s.trim&&(c.trim={from:s.trim.from,to:s.trim.from+l}),await this.updateClip(s.id,c);const h={...n};h.display={from:r,to:n.display.to},h.duration=n.duration-o,h.trim&&(h.trim={from:h.trim.from+l,to:h.trim.to});const u=await Ki(h);u.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const d=this.findTrackIdByClipId(s.id);d&&(await this.addClip(u,{trackId:d}),this.studio.selection.selectClipsByIds([u.id]))}async trimSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==1){console.warn("[Studio] Trim requires exactly one selected clip");return}const s=t[0],r=e*1e6,n=s.playbackRate||1,o=r*n;if(r>=s.duration){console.warn("[Studio] Trim amount exceeds clip duration");return}const a=s.duration-r,l=s.display.from+r,c=s.display.to,h={duration:a,display:{from:l,to:c}};if(s.trim)h.trim={from:s.trim.from+o,to:s.trim.to};else{const u=s.sourceDuration||s.duration;h.trim={from:o,to:u}}await this.updateClip(s.id,h)}async updateSelected(e){const t=Array.from(this.studio.selection.selectedClips);if(t.length!==0)for(const s of t)await this.updateClip(s.id,e)}async setTracks(e){this.tracks=JSON.parse(JSON.stringify(e)),await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}async ensureFontsForClips(e){const t=new Map;for(const s of e){if(s.type==="Text"){const r=s.style?.fontUrl||s.fontUrl;r&&t.set(r,{name:s.style?.fontFamily||s.fontFamily||"CustomFont",url:r})}if(s.type==="Caption"){const r=s.style?.fontUrl||s.fontUrl;r&&t.set(r,{name:s.style?.fontFamily||s.fontFamily||"CustomFont",url:r})}}if(t.size>0)try{await H_.loadFonts(Array.from(t.values()))}catch(s){console.warn("Failed to load some fonts:",s)}}async recalculateMaxDuration(){let e=0;for(const t of this.clips){t.display.to===0&&t.duration!==1/0&&!isNaN(t.duration)&&t.duration>0;const s=t.duration>0?t.duration:0;if(s===1/0)continue;const r=t.display.to>0?t.display.to:t.display.from+s;r>e&&(e=r)}this.studio.maxDuration=e}async setupPlaybackForClip(e,t){if(this.studio.pixiApp!=null){if(!this.isPlaybackCapable(e)){if(this.studio.pixiApp!=null&&(await e.ready).width>0&&(await e.ready).height>0){const s=new gn(this.studio.pixiApp,e,this.studio.clipsNormalContainer);this.studio.spriteRenderers.set(e,s)}return}try{const s=e;if(e.type==="Audio"&&t&&typeof t!="string"){const o=URL.createObjectURL(t);e.src=o}const{element:r,objectUrl:n}=await s.createPlaybackElement();if(e.type==="Video"){const o=M.from(r),a=new Ue(o);a.visible=!1,this.studio.clipsNormalContainer&&this.studio.clipsNormalContainer.addChild(a),this.studio.videoSprites.set(e,a)}this.studio.transport.playbackElements.set(e,{element:r,objectUrl:n})}catch(s){if(console.warn(`Failed to setup playback for ${e.constructor.name}`,s),this.studio.pixiApp!=null&&(await e.ready).width>0&&(await e.ready).height>0){const r=new gn(this.studio.pixiApp,e,this.studio.artboard);this.studio.spriteRenderers.set(e,r)}}}}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async clear(){this.studio.selection.deselectClip(),this.studio.selection.interactiveClips.clear();for(const[e,t]of this.studio.clipListeners)e.off("propsChange",t);this.studio.clipListeners.clear(),this.studio.globalEffects.clear(),this.studio.effectFilters.clear(),this.studio.transitionRenderers.forEach(e=>e.destroy()),this.studio.transitionRenderers.clear(),this.studio.transitionSprites.forEach(e=>{e.parent&&e.parent.removeChild(e),e.destroy()}),this.studio.transitionSprites.clear(),this.studio.spriteRenderers.forEach(e=>e.destroy()),this.studio.spriteRenderers.clear();for(const[e,t]of this.studio.transport.playbackElements)this.isPlaybackCapable(e)&&e.cleanupPlayback(t.element,t.objectUrl);this.studio.transport.playbackElements.clear();for(const e of this.studio.videoSprites.values())e.destroy();this.studio.videoSprites.clear(),this.tracks=[],this.clips=[],this.studio.maxDuration=0,this.studio.currentTime=0,this.studio.emit("reset")}async rippleDelete(e,t){if(e>=t)return;const s=t-e,r=[...this.clips];for(const n of r){const o=n.display.from,a=n.display.to;if(!(a<=e)){if(o>=t){await this.updateClip(n.id,{display:{from:n.display.from-s,to:n.display.to-s}});continue}if(o>=e&&a<=t){await this.removeClip(n);continue}if(o<e&&a>t){const l=await n.clone();l.id=`clip_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;const c=e,h=e+(a-t),u=n.trim.from+(t-o)*n.playbackRate,d=n.trim.to,f=this.tracks.find(p=>p.clipIds.includes(n.id));f&&(await this.addClip(l,{trackId:f.id}),await this.updateClip(l.id,{display:{from:c,to:h},trim:{from:u,to:d}})),await this.updateClip(n.id,{display:{from:n.display.from,to:e},trim:{from:n.trim.from,to:n.trim.from+(e-o)*n.playbackRate}});continue}if(o<e&&a<=t){await this.updateClip(n.id,{display:{from:n.display.from,to:e},trim:{from:n.trim.from,to:n.trim.from+(e-o)*n.playbackRate}});continue}if(o>=e&&a>t){await this.updateClip(n.id,{display:{from:e,to:e+(a-t)},trim:{from:n.trim.from+(t-o)*n.playbackRate,to:n.trim.to}});continue}}}await this.recalculateMaxDuration(),await this.studio.updateFrame(this.studio.currentTime)}}const fk={Date:!0,RegExp:!0,String:!0,Number:!0};function W_(i,e,t={cyclesFix:!0},s=[]){let r=[];const n=Array.isArray(i);for(const a in i){const l=i[a],c=n?+a:a;if(!(a in e)){r.push({type:"REMOVE",path:[c],oldValue:i[a]});continue}const h=e[a],u=typeof l=="object"&&typeof h=="object"&&Array.isArray(l)===Array.isArray(h);l&&h&&u&&!fk[Object.getPrototypeOf(l)?.constructor?.name]&&(!t.cyclesFix||!s.includes(l))?r.push.apply(r,W_(l,h,t,t.cyclesFix?s.concat([l]):[]).map(d=>(d.path.unshift(c),d))):l!==h&&!(Number.isNaN(l)&&Number.isNaN(h))&&!(u&&(isNaN(l)?l+""==h+"":+l==+h))&&r.push({path:[c],type:"CHANGE",value:h,oldValue:l})}const o=Array.isArray(e);for(const a in e)a in i||r.push({type:"CREATE",path:[o?+a:a],value:e[a]});return r}class pk{past=[];future=[];lastState=null;maxSize;constructor(e={}){this.maxSize=e.maxSize||50}projectToHistoryState(e){const t={},s=JSON.parse(JSON.stringify(e.tracks||[]));return e.clips.forEach(r=>{r.id&&(t[r.id]=JSON.parse(JSON.stringify(r)))}),{clips:t,tracks:s,settings:JSON.parse(JSON.stringify(e.settings||{}))}}init(e){this.lastState=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),this.past=[],this.future=[]}push(e){if(!this.lastState){this.init(e);return}const t=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),s=W_(this.lastState,t);s.length!==0&&(this.past.push(s),this.past.length>this.maxSize&&this.past.shift(),this.future=[],this.lastState=t)}undo(e){const t=this.past.pop();if(!t)return null;const s=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),r=this.applyPatches(s,t,!0);return this.future.push(t),this.lastState=r,{patches:t,state:r}}redo(e){const t=this.future.pop();if(!t)return null;const s=this.projectToHistoryState(JSON.parse(JSON.stringify(e))),r=this.applyPatches(s,t,!1);return this.past.push(t),this.lastState=r,{patches:t,state:r}}applyPatches(e,t,s){const r=JSON.parse(JSON.stringify(e)),n=s?[...t].reverse():t;for(const o of n){const{type:a,path:l}=o,c=o.value,h=o.oldValue;let u=r,d=!1;for(let p=0;p<l.length-1;p++){if(u[l[p]]===void 0||u[l[p]]===null){d=!0;break}u=u[l[p]]}if(d)continue;const f=l[l.length-1];if(s)switch(a){case"CREATE":Array.isArray(u)?u.splice(f,1):delete u[f];break;case"REMOVE":u[f]=h&&typeof h=="object"?JSON.parse(JSON.stringify(h)):h;break;case"CHANGE":u[f]=h&&typeof h=="object"?JSON.parse(JSON.stringify(h)):h;break}else switch(a){case"CREATE":u[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break;case"REMOVE":Array.isArray(u)?u.splice(f,1):delete u[f];break;case"CHANGE":u[f]=c&&typeof c=="object"?JSON.parse(JSON.stringify(c)):c;break}}return r}canUndo(){return this.past.length>0}canRedo(){return this.future.length>0}}class mk extends Zh{selection;transport;timeline;history;pixiApp=null;get tracks(){return this.timeline.tracks}get clips(){return this.timeline.clips}spriteRenderers=new Map;artboard=null;clipContainer=null;artboardMask=null;artboardBg=null;get activeTransformer(){return this.selection.activeTransformer}set activeTransformer(e){this.selection.activeTransformer=e}get selectedClips(){return this.selection.selectedClips}set selectedClips(e){this.selection.selectedClips=e}get interactiveClips(){return this.selection.interactiveClips}set interactiveClips(e){this.selection.interactiveClips=e}get playbackElements(){return this.transport.playbackElements}videoSprites=new Map;clipListeners=new Map;get isPlaying(){return this.transport.isPlaying}set isPlaying(e){this.transport.isPlaying=e}get currentTime(){return this.transport.currentTime}set currentTime(e){this.transport.currentTime=e}get maxDuration(){return this.transport.maxDuration}set maxDuration(e){this.transport.maxDuration=e}opts;destroyed=!1;renderingSuspended=!1;historyPaused=!1;processingHistory=!1;historyGroupDepth=0;clipCache=new Map;globalEffects=new Map;activeGlobalEffect=null;currentGlobalEffectSprite=null;effectFilters=new Map;transitionRenderers=new Map;transitionSprites=new Map;transFromTexture=null;transToTexture=null;transBgGraphics=null;clipsNormalContainer=null;clipsEffectContainer=null;videoTextureCache=new WeakMap;lastFromFrame=null;lastToFrame=null;hexToNumber(e){const t=e.startsWith("#")?e.slice(1):e;return parseInt(t,16)}ready;constructor(e){super(),this.opts={fps:30,bgColor:"#000000",interactivity:!0,spacing:0,...e},this.selection=new hk(this),this.transport=new uk(this),this.timeline=new dk(this),this.history=new pk,this.ready=this.initPixiApp().then(()=>{this.history.init(this.exportToJSON())}),this.on("clip:removed",this.handleClipRemoved),this.on("clips:removed",this.handleClipsRemoved),this.on("clip:updated",this.handleTimelineChange),this.on("clip:added",this.handleTimelineChange),this.on("clips:added",this.handleTimelineChange),this.on("track:removed",this.handleTimelineChange),this.on("track:added",this.handleTimelineChange)}handleTimelineChange=()=>{this.updateFrame(this.currentTime),this.saveHistory()};saveHistory(){this.historyPaused||this.processingHistory||(this.history.push(this.exportToJSON()),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()}))}beginHistoryGroup(){this.historyGroupDepth++,this.historyPaused=!0}endHistoryGroup(){this.historyGroupDepth=Math.max(0,this.historyGroupDepth-1),this.historyGroupDepth===0&&(this.historyPaused=!1,this.saveHistory())}setPath(e,t,s){let r=e;for(let n=0;n<t.length-1;n++){const o=t[n];r[o]||(r[o]=typeof t[n+1]=="number"?[]:{}),r=r[o]}r[t[t.length-1]]=s}async applyHistoryPatches(e,t,s){const r=new Map,n=new Map,o=new Set;for(const a of e){const{type:l,path:c}=a,h=a.value,u=a.oldValue;if(c[0]==="clips"){const d=c[1];s?l==="CREATE"?o.add(d):l==="REMOVE"?n.set(d,u):l==="CHANGE"&&(r.has(d)||r.set(d,{}),this.setPath(r.get(d),c.slice(2),u)):l==="CREATE"?n.set(d,h):l==="REMOVE"?o.add(d):l==="CHANGE"&&(r.has(d)||r.set(d,{}),this.setPath(r.get(d),c.slice(2),h))}else c[0]==="settings"&&(s?this.setPath(this.opts,c.slice(1),u):this.setPath(this.opts,c.slice(1),h))}for(const a of o){const l=this.timeline.getClipById(a);l&&await this.removeClip(l)}for(const[a,l]of n){let c=this.clipCache.get(a);c||(c=await Ki(l),this.clipCache.set(a,c));let h;for(const u of t.tracks)if(u.clipIds.includes(a)){h=u.id;break}await this.addClip(c,{trackId:h})}for(const[a,l]of r)await this.updateClip(a,l);this.timeline.setTracks(t.tracks),this.emit("studio:restored",{clips:this.clips,tracks:this.tracks,settings:this.opts})}async undo(){if(!(!this.history.canUndo()||this.processingHistory)){this.processingHistory=!0,this.historyPaused=!0;try{const e=this.history.undo(this.exportToJSON());e&&await this.applyHistoryPatches(e.patches,e.state,!0),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}finally{this.historyPaused=!1,this.processingHistory=!1}}}async redo(){if(!(!this.history.canRedo()||this.processingHistory)){this.processingHistory=!0,this.historyPaused=!0;try{const e=this.history.redo(this.exportToJSON());e&&await this.applyHistoryPatches(e.patches,e.state,!1),this.emit("history:changed",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}finally{this.historyPaused=!1,this.processingHistory=!1}}}cleanupClipVisuals=e=>{for(const[r,n]of this.spriteRenderers)if(r.id===e){const o=n.getRoot();o&&o.parent&&o.parent.removeChild(o),n.destroy(),this.spriteRenderers.delete(r);break}const t=this.transitionSprites.get(e);t&&(t.parent&&t.parent.removeChild(t),t.destroy(),this.transitionSprites.delete(e)),this.transitionRenderers.get(e)&&this.transitionRenderers.delete(e);for(const[r,n]of this.videoSprites)if(r.id===e){n.parent&&n.parent.removeChild(n),n.destroy(),this.videoSprites.delete(r);break}for(const[r]of this.clipListeners)if(r.id===e){this.clipListeners.delete(r);break}};handleClipRemoved=({clipId:e})=>{this.cleanupClipVisuals(e),this.updateFrame(this.currentTime),this.saveHistory()};handleClipsRemoved=({clipIds:e})=>{for(const t of e)this.cleanupClipVisuals(t);this.updateFrame(this.currentTime),this.saveHistory()};async initPixiApp(){if(this.destroyed)return;const e=this.opts.canvas||document.createElement("canvas");e.width=this.opts.width,e.height=this.opts.height;const t=new Lu,s=e.parentElement||window;await t.init({canvas:e,resizeTo:s,backgroundColor:this.hexToNumber(this.opts.bgColor),antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.pixiApp=t,t.stage.eventMode="static",t.stage.hitArea=t.screen,this.artboard=new re,this.artboard.label="ArtboardRoot",t.stage.addChild(this.artboard),this.selection.init(t,this.artboard),this.artboardBg=new xe,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:0}),this.artboard.addChild(this.artboardBg),this.clipContainer=new re,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardMask=new xe,this.artboardMask.rect(0,0,this.opts.width,this.opts.height).fill({color:16777215}),this.clipContainer.addChild(this.artboardMask),this.clipContainer.mask=this.artboardMask,this.clipsEffectContainer=new re,this.clipsEffectContainer.label="ClipsEffect",this.clipsEffectContainer.visible=!1,this.clipsEffectContainer.zIndex=1,this.clipsEffectContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsEffectContainer),this.clipsNormalContainer=new re,this.clipsNormalContainer.label="ClipsNormal",this.clipsNormalContainer.zIndex=10,this.clipsNormalContainer.sortableChildren=!0,this.clipContainer.addChild(this.clipsNormalContainer),this.transFromTexture=Ge.create({width:this.opts.width,height:this.opts.height}),this.transToTexture=Ge.create({width:this.opts.width,height:this.opts.height}),this.transBgGraphics=new xe,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}),this.clipContainer.sortableChildren=!0,this.updateArtboardLayout(),t.renderer.on("resize",()=>{this.handleResize()})}getOptions(){return this.opts}setSize(e,t){this.updateDimensions(e,t)}updateDimensions(e,t){this.opts.width=e,this.opts.height=t,this.artboardBg&&this.artboardBg.clear().rect(0,0,e,t).fill({color:0}),this.artboardMask&&this.artboardMask.clear().rect(0,0,e,t).fill({color:16777215}),this.transFromTexture&&this.transFromTexture.resize(e,t),this.transToTexture&&this.transToTexture.resize(e,t),this.transBgGraphics&&this.transBgGraphics.clear().rect(0,0,e,t).fill({color:0,alpha:0}),this.updateArtboardLayout(),this.updateFrame(this.currentTime)}handleResize=()=>{this.destroyed||!this.pixiApp||this.updateArtboardLayout()};updateArtboardLayout(){if(!this.pixiApp||!this.artboard)return;const e=this.pixiApp.canvas.width,t=this.pixiApp.canvas.height,s=this.opts.width,r=this.opts.height,n=this.pixiApp.canvas.parentElement?.clientWidth||e,o=this.pixiApp.canvas.parentElement?.clientHeight||t,a=this.opts.spacing||0,l=Math.max(0,n-a*2),c=Math.max(0,o-a*2),h=l/s,u=c/r,d=Math.min(h,u);this.artboard.scale.set(d),this.artboard.x=(n-s*d)/2,this.artboard.y=(o-r*d)/2}getCanvas(){if(this.opts.canvas)return this.opts.canvas;if(this.pixiApp?.canvas)return this.pixiApp.canvas;throw new Error("Canvas not initialized yet. Wait for initPixiApp to complete.")}async addTransition(e,t=2e6,s,r){return this.timeline.addTransition(e,t,s,r)}findTrackIdByClipId(e){return this.timeline.findTrackIdByClipId(e)}async addClip(e,t){(Array.isArray(e)?e:[e]).forEach(r=>this.clipCache.set(r.id,r)),this.beginHistoryGroup();try{return await this.timeline.addClip(e,t)}finally{this.endHistoryGroup()}}addTrack(e){return this.timeline.addTrack(e)}async setTracks(e){return this.timeline.setTracks(e)}async removeTrack(e){return this.timeline.removeTrack(e)}getClipById(e){return this.timeline.getClipById(e)}async updateClip(e,t){return this.timeline.updateClip(e,t)}async centerClip(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=(this.opts.width-t.width)/2,r=(this.opts.height-t.height)/2;if(this.getClipById(t.id))return this.updateClip(t.id,{left:s,top:r});t.left=s,t.top=r}async centerClipH(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=(this.opts.width-t.width)/2;if(this.getClipById(t.id))return this.updateClip(t.id,{left:s});t.left=s}async centerClipV(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=(this.opts.height-t.height)/2;if(this.getClipById(t.id))return this.updateClip(t.id,{top:s});t.top=s}async scaleToFit(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=await t.ready,{width:r,height:n}=s;if(r===0||n===0)return;const o=Math.min(this.opts.width/r,this.opts.height/n),a=r*o,l=n*o;if(this.getClipById(t.id))return this.updateClip(t.id,{width:a,height:l});t.width=a,t.height=l}async scaleToCover(e){const t=typeof e=="string"?this.getClipById(e):e;if(!t)return;const s=await t.ready,{width:r,height:n}=s;if(r===0||n===0)return;const o=Math.max(this.opts.width/r,this.opts.height/n),a=r*o,l=n*o;if(this.getClipById(t.id))return this.updateClip(t.id,{width:a,height:l});t.width=a,t.height=l}async updateClips(e){this.suspendRendering(),await this.timeline.updateClips(e),this.resumeRendering(),this.updateFrame(this.currentTime)}suspendRendering(){this.renderingSuspended=!0}resumeRendering(){this.renderingSuspended=!1}getTracks(){return this.timeline.tracks}getClip(e){return this.timeline.getClipById(e)}setupSpriteInteractivity(e){this.selection.setupSpriteInteractivity(e)}async removeClip(e){this.beginHistoryGroup();try{return this.clipCache.set(e.id,e),this.timeline.removeClip(e,{permanent:!this.processingHistory})}finally{this.endHistoryGroup()}}async removeClips(e){this.beginHistoryGroup();try{return e.forEach(t=>this.clipCache.set(t.id,t)),this.timeline.removeClips(e,{permanent:!this.processingHistory})}finally{this.endHistoryGroup()}}async removeClipById(e){const t=this.timeline.getClipById(e);if(t)return this.removeClip(t)}async removeClipsById(e){const t=e.map(s=>this.timeline.getClipById(s)).filter(Boolean);return this.removeClips(t)}async deleteSelected(){const e=this.selection.selectedClips;if(e.size!==0){this.beginHistoryGroup();try{await this.removeClips(Array.from(e))}finally{this.endHistoryGroup()}}}async duplicateSelected(){this.beginHistoryGroup();try{return await this.timeline.duplicateSelected()}finally{this.endHistoryGroup()}}async splitSelected(e){this.beginHistoryGroup();try{return await this.timeline.splitSelected(e)}finally{this.endHistoryGroup()}}async trimSelected(e){return this.timeline.trimSelected(e)}async updateSelected(e){return this.timeline.updateSelected(e)}async clear(){await this.timeline.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null),this.emit("reset")}async play(){return this.transport.play()}pause(){this.transport.pause()}async stop(){return this.transport.stop()}async seek(e){return this.transport.seek(e)}async frameNext(){return this.transport.frameNext()}async framePrev(){return this.transport.framePrev()}getCurrentTime(){return this.transport.currentTime}getMaxDuration(){return this.transport.maxDuration}getIsPlaying(){return this.transport.isPlaying}getSelectedClips(){return Array.from(this.selectedClips)}getVideoTexture(e){let t=this.videoTextureCache.get(e);return t||(t=M.from(e),this.videoTextureCache.set(e,t)),t}isPlaybackCapable(e){return"createPlaybackElement"in e&&"play"in e&&"pause"in e&&"seek"in e&&"syncPlayback"in e&&"cleanupPlayback"in e}async updateFrame(e){if(this.destroyed||this.pixiApp==null||this.renderingSuspended)return;this.updateActiveGlobalEffect(e);const t=new Set,s=this.tracks.length;for(const n of this.clips){const o=this.getTrackIndex(n.id);if(o!==-1){const a=(s-o)*10;n.zIndex=a;const l=this.spriteRenderers.get(n);if(l){const c=l.getRoot();c&&(c.zIndex=a)}}}const r=[...this.clips].sort((n,o)=>n.zIndex-o.zIndex);for(const n of r){if(e<n.display.from){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const x=this.playbackElements.get(n);x!=null&&this.isPlaybackCapable(n)&&n.pause(x.element);continue}if(n.display.to>0&&e>=n.display.to){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const x=this.playbackElements.get(n);x!=null&&this.isPlaybackCapable(n)&&n.pause(x.element);continue}const o=e-n.display.from,a=o*n.playbackRate;n.animate(a);const l=await n.ready,c=n.duration||l.duration;if(c>0&&o>=c){const m=this.spriteRenderers.get(n);m!=null&&await m.updateFrame(null);const x=this.playbackElements.get(n);x!=null&&this.isPlaybackCapable(n)&&n.pause(x.element);continue}const h=this.playbackElements.get(n),u=n.type==="Video"||n.type==="Image",d=n.transition?n.transition.start:0,f=n.transition?n.transition.end:0,p=u&&n.transition&&e>=d&&e<f;if(h!=null&&this.isPlaybackCapable(n)){const m=o/1e6;if(n.syncPlayback(h.element,this.isPlaying,m),n.type==="Video"&&this.isPlaybackCapable(n)){const x=this.videoSprites.get(n);if(x!=null){const _=n.meta.duration/1e6;if(this.spriteRenderers.has(n))x.visible=!1;else if(x.visible=!p&&m>=0&&m<_,x.visible&&tM(n,x),!p)continue}}else continue}if(p){this.transFromTexture||(this.transFromTexture=Ge.create({width:this.opts.width,height:this.opts.height})),this.transToTexture||(this.transToTexture=Ge.create({width:this.opts.width,height:this.opts.height})),this.transBgGraphics||(this.transBgGraphics=new xe,this.transBgGraphics.rect(0,0,this.opts.width,this.opts.height).fill({color:0,alpha:0}));const m=this.getClipById(n?.transition?.fromClipId),x=this.getClipById(n?.transition?.toClipId);let _=null,y=null;if(m){const v=Math.max(0,e-m.display.from),{video:T}=await m.getFrame(v);T instanceof HTMLVideoElement?_=this.getVideoTexture(T):_=T,_&&(this.lastFromFrame=_)}if(x){const v=Math.max(0,e-x.display.from),{video:T}=await x.getFrame(v);T instanceof HTMLVideoElement?y=this.getVideoTexture(T):y=T,y&&(this.lastToFrame=y)}if(_||(_=this.lastFromFrame),y||(y=this.lastToFrame),!_||!y)continue;if(_&&y&&this.pixiApp&&this.transFromTexture&&this.transToTexture){const v=(e-d)/n?.transition?.duration;m&&_&&this.renderClipToTransitionTexture(m,_,this.transFromTexture),x&&y&&this.renderClipToTransitionTexture(x,y,this.transToTexture);let T=this.transitionRenderers.get(n.id);if(!T)try{T=nf({name:n?.transition?.name,renderer:this.pixiApp.renderer}),this.transitionRenderers.set(n.id,T)}catch(S){console.error("[Studio] Failed to create transition renderer:",S)}if(T){const S=T.render({width:this.opts.width,height:this.opts.height,from:this.transFromTexture,to:this.transToTexture,progress:v});let w=this.transitionSprites.get(n.id);w||(w=new Ue,w.label=`TransitionSprite_${n.id}`,this.transitionSprites.set(n.id,w),this.clipsNormalContainer&&this.clipsNormalContainer.addChild(w)),w.texture=S,w.visible=!0,w.x=0,w.y=0,w.width=this.opts.width,w.height=this.opts.height,w.anchor.set(0,0),w.zIndex=n.zIndex,t.add(n.id);const E=this.spriteRenderers.get(n);E?.getRoot()&&(E.getRoot().visible=!1);const P=this.videoSprites.get(n);if(P&&(P.visible=!1),m){const C=this.spriteRenderers.get(m);C?.getRoot()&&(C.getRoot().visible=!1);const A=this.videoSprites.get(m);A&&(A.visible=!1)}continue}}}const g=this.spriteRenderers.get(n);if(g!=null){const m=this.selectedClips.has(n);if(n.type!=="Text"&&n.type!=="Caption"&&typeof n.getTexture=="function"&&n.getTexture()!=null){const _=n.getTexture();if(_!=null){await g.updateFrame(_),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}if(n.type==="Text"){const _=n;this.pixiApp?.renderer&&typeof _.setRenderer=="function"&&_.setRenderer(this.pixiApp.renderer);const y=await _.getTexture();if(y!=null){await g.updateFrame(y),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}if(n.type==="Caption"){n.updateState(o);const _=n;this.pixiApp?.renderer&&typeof _.setRenderer=="function"&&_.setRenderer(this.pixiApp.renderer);const y=await _.getTexture();if(y!=null){await g.updateFrame(y),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n);continue}}const{video:x}=await n.getFrame(o);await g.updateFrame(x),m||g.updateTransforms(),this.opts.interactivity&&this.selection.setupSpriteInteractivity(n)}}if(this.activeGlobalEffect&&this.clipsNormalContainer&&this.clipsEffectContainer){const{startTime:n,duration:o}=this.activeGlobalEffect,a=e-n,l=Math.min(Math.max(a/o,0),1);if(l>0&&l<1){try{for(const h of this.clips)this.moveClipToEffectContainer(h,!1);const c=this.clips.some(h=>h.id===this.activeGlobalEffect.id&&h instanceof ct);for(const h of this.clips){let u=!1;if(c){const d=this.activeGlobalEffect.trackIndex??-1,f=this.getTrackIndex(h.id);u=h.id!==this.activeGlobalEffect.id&&!(h instanceof ct)&&f>d}else{const d=h.effects;u=Array.isArray(d)&&d.some(f=>f&&f.id===this.activeGlobalEffect.id)}u&&this.moveClipToEffectContainer(h,!0)}}catch(c){console.warn("Failed to reparent clips for effect; falling back to full-scene render",c)}this.clipsNormalContainer.visible=!0,await this.applyGlobalEffectIfNeeded(e)}else{for(const c of this.clips)try{this.moveClipToEffectContainer(c,!1)}catch{}this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}}else if(this.clipsNormalContainer){for(const n of this.clips)try{this.moveClipToEffectContainer(n,!1)}catch{}this.clipsNormalContainer.visible=!0,this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null)}for(const[n,o]of this.transitionSprites.entries())t.has(n)||(o.visible=!1);this.pixiApp!=null&&this.pixiApp.render()}moveClipToEffectContainer(e,t=!0){if(!this.clipsNormalContainer||!this.clipsEffectContainer)return;const s=t?this.clipsEffectContainer:this.clipsNormalContainer,r=this.spriteRenderers.get(e);if(r){const o=r.getRoot();if(o&&o.parent!==s){try{o.parent&&o.parent.removeChild&&o.parent.removeChild(o)}catch(a){console.warn("moveClipToEffectContainer: could not remove root from parent",a)}s.addChild(o)}}const n=this.transitionSprites.get(e.id);if(n&&n.parent!==s){try{n.parent&&n.parent.removeChild&&n.parent.removeChild(n)}catch(o){console.warn("moveClipToEffectContainer: could not remove transSprite from parent",o)}s.addChild(n)}}applyGlobalEffect(e,t,s){const r=t.id||`${e}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,n={id:r,key:e,startTime:t.startTime,duration:t.duration??1e6};for(const o of s)o instanceof _i&&o.addEffect(n),o instanceof Me&&o.addEffect(n),o instanceof gt&&o.addEffect(n),o instanceof ei&&o.addEffect(n);return this.globalEffects.set(r,n),r}getTrackIndex(e){return this.tracks.findIndex(t=>t.clipIds.includes(e))}async getTransitionFromFrame(e,t){let s=null;if(e.transition?.prevClipId&&(s=this.clips.find(a=>a.id===e.transition.prevClipId)||null),s||(s=this.getPreviousClipOnTrack(e)),!s)return null;const r=s.duration>0?s.duration:0,n=Math.max(0,Math.min(t-s.display.from,r)),{video:o}=await s.getFrame(n);return o}getPreviousClipOnTrack(e){const t=this.getTrackIndex(e.id);return t===-1?null:this.clips.filter(s=>s.id!==e.id&&this.getTrackIndex(s.id)===t&&s.display.from<e.display.from&&(s instanceof Me||s instanceof _i)).sort((s,r)=>r.display.to-s.display.to)[0]||null}renderClipToTransitionTexture(e,t,s){if(!this.pixiApp||!this.transBgGraphics)return;const r=this.pixiApp.renderer.background.alpha;this.pixiApp.renderer.background.alpha=0,this.pixiApp.renderer.render({container:this.transBgGraphics,target:s,clear:!0}),this.pixiApp.renderer.background.alpha=r;const n=new Ue(t instanceof M?t:M.from(t));n.x=e.center.x,n.y=e.center.y,n.anchor.set(.5,.5);const o=n.texture.width||1,a=n.texture.height||1,l=e.width&&e.width!==0?Math.abs(e.width)/o:1,c=e.height&&e.height!==0?Math.abs(e.height)/a:1;e.flip==="horizontal"?(n.scale.x=-l,n.scale.y=c):e.flip==="vertical"?(n.scale.x=l,n.scale.y=-c):(n.scale.x=l,n.scale.y=c),n.rotation=(e.flip==null?1:-1)*e.angle,n.alpha=e.opacity,this.pixiApp.renderer.render({container:n,target:s,clear:!1}),t instanceof M||n.texture.destroy(!0),n.destroy()}removeGlobalEffect(e){this.globalEffects.delete(e)}clearGlobalEffects(){this.globalEffects.clear()}updateActiveGlobalEffect(e){let t=null;for(const s of this.clips)if(s instanceof ct&&e>=s.display.from&&(s.display.to===0||e<s.display.to)){t={id:s.id,key:s.effect.key,startTime:s.display.from,duration:s.duration>0?s.duration:s.display.to-s.display.from,trackIndex:this.getTrackIndex(s.id)};break}if(!t)for(const s of this.globalEffects.values()){const r=s.startTime+s.duration;if(e>=s.startTime&&e<r){t={id:s.id,key:s.key,startTime:s.startTime,duration:s.duration,trackIndex:-1};break}}this.activeGlobalEffect=t}async applyGlobalEffectIfNeeded(e){if(this.currentGlobalEffectSprite&&(this.currentGlobalEffectSprite.parent&&this.currentGlobalEffectSprite.parent.removeChild(this.currentGlobalEffectSprite),this.currentGlobalEffectSprite.destroy(),this.currentGlobalEffectSprite=null),!this.activeGlobalEffect||!this.pixiApp||!this.clipContainer||!this.artboard||!this.clipsNormalContainer||!this.clipsEffectContainer)return;const{key:t,startTime:s,duration:r}=this.activeGlobalEffect,n=e-s,o=Math.min(Math.max(n/r,0),1);if(o<=0||o>=1)return;this.clipsEffectContainer.visible=!0;let a=this.effectFilters.get(t);if(!a)try{if(a=sf({name:t.toLowerCase(),renderer:this.pixiApp.renderer}),a)this.effectFilters.set(t,a);else return}catch(f){console.error(f);return}const l=this.opts.width,c=this.opts.height,h=Ge.create({width:l,height:c});this.pixiApp.renderer.render({container:this.clipsEffectContainer,target:h,clear:!0}),this.clipsEffectContainer.visible=!1;const u=a.render({canvasTexture:h,progress:o,width:l,height:c}),d=new Ue(u);d.x=0,d.y=0,d.width=l,d.height=c,d.scale.set(1),d.zIndex=5,this.clipContainer.addChild(d),this.currentGlobalEffectSprite=d,h.destroy(!0)}destroy(){if(!this.destroyed){window.removeEventListener("resize",this.handleResize),this.destroyed=!0,this.stop(),this.clear(),this.transitionRenderers.clear(),this.transFromTexture&&(this.transFromTexture.destroy(!0),this.transFromTexture=null),this.transToTexture&&(this.transToTexture.destroy(!0),this.transToTexture=null),this.transBgGraphics&&(this.transBgGraphics.destroy(!0),this.transBgGraphics=null);for(const e of this.transitionSprites.values())e.destroy();this.transitionSprites.clear(),this.pixiApp&&(this.pixiApp.destroy(!0,{children:!0,texture:!0}),this.pixiApp=null)}}selectClip(e,t=!1){this.selection.selectClip(e,t)}setSelection(e){this.selection.setSelection(e)}selectClipsByIds(e){this.selection.selectClipsByIds(e)}deselectClip(){this.selection.deselectClip()}exportToJSON(){return this.timeline.exportToJSON()}async loadFromJSON(e){return this.timeline.loadFromJSON(e)}}V.add(VS),V.mixin(re,$S),V.add(lg),V.add(cg),V.add(g0),V.mixin(re,_I),V.add(m0),V.add(s_),V.add(od),V.add(o_),V.add(u_),V.add(d_),V.add(w_),V.add(T_),V.add(g_),V.add(v_),V.add(__),V.add(m_),V.add(p_),V.add(w0),V.add(b0);const gk=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),xk=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));se.Audio=Ke,se.Caption=ei,se.Compositor=rk,se.DEFAULT_AUDIO_CONF=le,se.Effect=ct,se.GL_EFFECT_OPTIONS=eM,se.GL_TRANSITION_OPTIONS=ik,se.Image=_i,se.Log=q,se.MP4Clip=Me,se.Placeholder=mn,se.Studio=mk,se.Text=gt,se.Transition=Lt,se.Video=Me,se.clipToJSON=Ys,se.createChromakey=S1,se.fastConcatMP4=U_,se.fixFMP4Duration=BR,se.fontManager=H_,se.jsonToClip=Ki,se.makeEffect=sf,se.makeTransition=nf,se.mixinMP4AndAudio=GR,se.renderTxt2ImgBitmap=M1,Object.defineProperty(se,Symbol.toStringTag,{value:"Module"})}));
|