import{W as $e,M as x,w as S,a as _,t as d,y as Y,X as I,Y as qe,B as $,T as M,Z as ue,h as Ke,Q as U,_ as ae,$ as pe,a0 as fe,a1 as me,a2 as ge,e as L,L as Xe,C as W,D as q,N as w,R as P,a3 as Je,P as Qe,z as ie,a4 as oe,I as f,p as Ze,v as V,G as et,J as tt,a5 as rt,a6 as st}from"./sprite-view-Br3916N3.js";import{B as _e}from"./BatchableSprite-qOYjpB38.js";import{U as xe,G as nt,b as at,a as it,R as O,B as ot}from"./Geometry-BsDB1n4r.js";import{D as be,S as T,b as lt}from"./colorToUniform-DJvpt7jY.js";import{F as dt}from"./Filter-DL3E8wYn.js";var ct=`in vec2 vMaskCoord;
in vec2 vTextureCoord;

uniform sampler2D uTexture;
uniform sampler2D uMaskTexture;

uniform float uAlpha;
uniform vec4 uMaskClamp;
uniform float uInverse;
uniform float uChannel;

out vec4 finalColor;

void main(void)
{
    float clip = step(3.5,
        step(uMaskClamp.x, vMaskCoord.x) +
        step(uMaskClamp.y, vMaskCoord.y) +
        step(vMaskCoord.x, uMaskClamp.z) +
        step(vMaskCoord.y, uMaskClamp.w));

    // TODO look into why this is needed
    float npmAlpha = uAlpha;
    vec4 original = texture(uTexture, vTextureCoord);
    vec4 masky = texture(uMaskTexture, vMaskCoord);

    float a;
    if (uChannel == 1.0) {
        a = masky.a * npmAlpha * clip;
    } else {
        float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);
        a = alphaMul * masky.r * npmAlpha * clip;
    }

    if (uInverse == 1.0) {
        a = 1.0 - a;
    }

    finalColor = original * a;
}
`,ht=`in vec2 aPosition;

out vec2 vTextureCoord;
out vec2 vMaskCoord;


uniform vec4 uInputSize;
uniform vec4 uOutputFrame;
uniform vec4 uOutputTexture;
uniform mat3 uFilterMatrix;

vec4 filterVertexPosition(  vec2 aPosition )
{
    vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
       
    position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
    position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;

    return vec4(position, 0.0, 1.0);
}

vec2 filterTextureCoord(  vec2 aPosition )
{
    return aPosition * (uOutputFrame.zw * uInputSize.zw);
}

vec2 getFilterCoord( vec2 aPosition )
{
    return  ( uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0)  ).xy;
}   

void main(void)
{
    gl_Position = filterVertexPosition(aPosition);
    vTextureCoord = filterTextureCoord(aPosition);
    vMaskCoord = getFilterCoord(aPosition);
}
`,le=`struct GlobalFilterUniforms {
  uInputSize:vec4<f32>,
  uInputPixel:vec4<f32>,
  uInputClamp:vec4<f32>,
  uOutputFrame:vec4<f32>,
  uGlobalFrame:vec4<f32>,
  uOutputTexture:vec4<f32>,
};

struct MaskUniforms {
  uFilterMatrix:mat3x3<f32>,
  uMaskClamp:vec4<f32>,
  uAlpha:f32,
  uInverse:f32,
  uChannel:f32,
};

@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
@group(0) @binding(1) var uTexture: texture_2d<f32>;
@group(0) @binding(2) var uSampler : sampler;

@group(1) @binding(0) var<uniform> filterUniforms : MaskUniforms;
@group(1) @binding(1) var uMaskTexture: texture_2d<f32>;

struct VSOutput {
    @builtin(position) position: vec4<f32>,
    @location(0) uv : vec2<f32>,
    @location(1) filterUv : vec2<f32>,
};

fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>
{
    var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;

    position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
    position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;

    return vec4(position, 0.0, 1.0);
}

fn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
{
    return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
}

fn globalTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
{
  return  (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw);
}

fn getFilterCoord(aPosition:vec2<f32> ) -> vec2<f32>
{
  return ( filterUniforms.uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0)  ).xy;
}

fn getSize() -> vec2<f32>
{
  return gfu.uGlobalFrame.zw;
}

@vertex
fn mainVertex(
  @location(0) aPosition : vec2<f32>,
) -> VSOutput {
  return VSOutput(
   filterVertexPosition(aPosition),
   filterTextureCoord(aPosition),
   getFilterCoord(aPosition)
  );
}

@fragment
fn mainFragment(
  @location(0) uv: vec2<f32>,
  @location(1) filterUv: vec2<f32>,
  @builtin(position) position: vec4<f32>
) -> @location(0) vec4<f32> {

    var maskClamp = filterUniforms.uMaskClamp;
    var uAlpha = filterUniforms.uAlpha;

    var clip = step(3.5,
      step(maskClamp.x, filterUv.x) +
      step(maskClamp.y, filterUv.y) +
      step(filterUv.x, maskClamp.z) +
      step(filterUv.y, maskClamp.w));

    var mask = textureSample(uMaskTexture, uSampler, filterUv);
    var source = textureSample(uTexture, uSampler, uv);

    var a: f32;
    if (filterUniforms.uChannel == 1.0) {
        a = mask.a * uAlpha * clip;
    } else {
        var alphaMul = 1.0 - uAlpha * (1.0 - mask.a);
        a = alphaMul * mask.r * uAlpha * clip;
    }

    if (filterUniforms.uInverse == 1.0) {
        a = 1.0 - a;
    }

    return source * a;
}
`;class ut extends dt{constructor(e){const{sprite:t,...r}=e,s=new $e(t.texture),n=new xe({uFilterMatrix:{value:new x,type:"mat3x3<f32>"},uMaskClamp:{value:s.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:e.inverse?1:0,type:"f32"},uChannel:{value:e.channel==="alpha"?1:0,type:"f32"}}),i=nt.from({vertex:{source:le,entryPoint:"mainVertex"},fragment:{source:le,entryPoint:"mainFragment"}}),l=at.from({vertex:ht,fragment:ct,name:"mask-filter"});super({...r,gpuProgram:i,glProgram:l,clipToViewport:!1,resources:{filterUniforms:n,uMaskTexture:t.texture.source}}),this.sprite=t,this._textureMatrix=s}setSprite(e){this.sprite=e;const t=this._getSafeTexture();this._textureMatrix.texture=t,this.resources.uMaskTexture=t.source}set inverse(e){this.resources.filterUniforms.uniforms.uInverse=e?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}set channel(e){this.resources.filterUniforms.uniforms.uChannel=e==="alpha"?1:0}get channel(){return this.resources.filterUniforms.uniforms.uChannel===1?"alpha":"red"}apply(e,t,r,s){const n=this._getSafeTexture();this._textureMatrix.texture=n,e.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=n.source,e.applyFilter(this,t,r,s)}_getSafeTexture(){const e=this.sprite.texture;return e.destroyed||!e.source||e.source.destroyed?(S("[MaskFilter] The mask texture was destroyed while the mask is still in use. Remove the mask before destroying its texture."),_.EMPTY):e}destroy(e=!1){this._textureMatrix.destroy(),super.destroy(e)}}const K=class ye{constructor(e,t){this.state=it.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=e,this._adaptor=t,this._adaptor.init?.(this)}static getBatcher(e,t){return new this._availableBatchers[e]({maxTextures:t})}buildStart(e){let t=this._batchersByInstructionSet[e.uid];t||(t=this._batchersByInstructionSet[e.uid]=Object.create(null),t.default||(t.default=new be({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=t,this._activeBatch=this._activeBatches.default;for(const r in this._activeBatches)this._activeBatches[r].begin()}addToBatch(e,t){if(this._activeBatch.name!==e.batcherName){this._activeBatch.break(t);let r=this._activeBatches[e.batcherName];r||(r=this._activeBatches[e.batcherName]=ye.getBatcher(e.batcherName,this.renderer.limits.maxBatchableTextures),r.begin()),this._activeBatch=r}this._activeBatch.add(e)}break(e){this._activeBatch.break(e)}buildEnd(e){this._activeBatch.break(e);const t=this._activeBatches;for(const r in t){const s=t[r],n=s.geometry;n.indexBuffer.setDataWithSize(s.indexBuffer,s.indexSize,!0),n.buffers[0].setDataWithSize(s.attributeBuffer.float32View,s.attributeSize,!1)}}upload(e){const t=this._batchersByInstructionSet[e.uid];for(const r in t){const s=t[r],n=s.geometry;s.dirty&&(s.dirty=!1,n.buffers[0].update(s.attributeSize*4))}}execute(e){if(e.action==="startBatch"){const t=e.batcher,r=t.geometry,s=t.shader;this._adaptor.start(this,r,s)}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}};K.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"batch"};K._availableBatchers=Object.create(null);let Te=K;Y.handleByMap(d.Batcher,Te._availableBatchers);Y.add(be);const pt=new $;class ft extends ue{constructor(){super(),this._placeholderSprite=new Ke(_.EMPTY),this.filters=[new ut({sprite:this._placeholderSprite,inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(e){this.filters[0].setSprite(e)}get inverse(){return this.filters[0].inverse}set inverse(e){this.filters[0].inverse=e}get channel(){return this.filters[0].channel}set channel(e){this.filters[0].channel=e}reset(){this._placeholderSprite.texture=_.EMPTY,this.sprite=this._placeholderSprite}}class ve{constructor(e){this._activeMaskStage=[],this._usedEffects=[],this._renderer=e,e.runners.postrender.add(this)}push(e,t,r){const s=this._renderer;if(s.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1,maskedContainer:t}),e.inverse=t._maskOptions.inverse,e.channel=t._maskOptions.channel??"red",e.renderMaskToTexture){const n=e.mask;n.includeInBuild=!0,n.collectRenderables(r,s,null),n.includeInBuild=!1}s.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:e,maskedContainer:t,inverse:t._maskOptions.inverse,canBundle:!1})}pop(e,t,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1})}execute(e){const t=this._renderer,r=e.mask.renderMaskToTexture;if(e.action==="pushMaskBegin"){const s=I.get(ft);if(s.inverse=e.inverse,s.channel=e.mask.channel,r){e.mask.mask.measurable=!0;const n=qe(e.mask.mask,!0,pt);e.mask.mask.measurable=!1,n.ceil();const i=t.renderTarget.renderTarget.colorTexture.source,l=M.getOptimalTexture(n.width,n.height,i._resolution,i.antialias);t.renderTarget.push({target:l,clear:!0}),t.globalUniforms.push({offset:n,worldColor:4294967295});const o=s.sprite;o.texture=l,o.worldTransform.tx=n.minX,o.worldTransform.ty=n.minY,this._activeMaskStage.push({filterEffect:s,maskedContainer:e.maskedContainer,filterTexture:l})}else s.sprite=e.mask.mask,this._activeMaskStage.push({filterEffect:s,maskedContainer:e.maskedContainer})}else if(e.action==="pushMaskEnd"){const s=this._activeMaskStage[this._activeMaskStage.length-1];r&&(t.type===O.WEBGL&&t.renderTarget.finishRenderPass(),t.renderTarget.pop(),t.globalUniforms.pop()),t.filter.push({renderPipeId:"filter",action:"pushFilter",container:s.maskedContainer,filterEffect:s.filterEffect,canBundle:!1})}else if(e.action==="popMaskEnd"){t.filter.pop();const s=this._activeMaskStage.pop();r&&M.returnTexture(s.filterTexture),this._usedEffects.push(s.filterEffect)}}postrender(){const e=this._usedEffects;for(let t=0;t<e.length;t++)I.return(e[t]);e.length=0}destroy(){this.postrender(),this._renderer.runners.postrender.remove(this),this._renderer=null,this._activeMaskStage=null,this._usedEffects=null}}ve.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"alphaMask"};class Ce{constructor(e){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=e}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(e,t,r){this._renderer.renderPipes.batch.break(r);const n=this._colorStack;n[this._colorStackIndex]=n[this._colorStackIndex-1]&e.mask;const i=this._colorStack[this._colorStackIndex];i!==this._currentColor&&(this._currentColor=i,r.add({renderPipeId:"colorMask",colorMask:i,canBundle:!1})),this._colorStackIndex++}pop(e,t,r){this._renderer.renderPipes.batch.break(r);const n=this._colorStack;this._colorStackIndex--;const i=n[this._colorStackIndex-1];i!==this._currentColor&&(this._currentColor=i,r.add({renderPipeId:"colorMask",colorMask:i,canBundle:!1}))}execute(e){this._renderer.colorMask.setMask(e.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}Ce.extension={type:[d.WebGLPipes,d.WebGPUPipes],name:"colorMask"};class ke{constructor(e){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=e}push(e,t,r){var s;const n=e,i=this._renderer;i.renderPipes.batch.break(r),i.renderPipes.blendMode.setBlendMode(n.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const l=n.mask;l.includeInBuild=!0,this._maskHash.has(n)||this._maskHash.set(n,{instructionsStart:0,instructionsLength:0});const o=this._maskHash.get(n);o.instructionsStart=r.instructionSize,l.collectRenderables(r,i,null),l.includeInBuild=!1,i.renderPipes.batch.break(r),r.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:e,inverse:t._maskOptions.inverse,canBundle:!1});const h=r.instructionSize-o.instructionsStart-1;o.instructionsLength=h;const c=i.renderTarget.renderTarget.uid;(s=this._maskStackHash)[c]??(s[c]=0)}pop(e,t,r){const s=e,n=this._renderer;n.renderPipes.batch.break(r),n.renderPipes.blendMode.setBlendMode(s.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:t._maskOptions.inverse,canBundle:!1});const i=this._maskHash.get(e);for(let l=0;l<i.instructionsLength;l++)r.instructions[r.instructionSize++]=r.instructions[i.instructionsStart++];r.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(e){var t;const r=this._renderer,s=r,n=r.renderTarget.renderTarget.uid;let i=(t=this._maskStackHash)[n]??(t[n]=0);e.action==="pushMaskBegin"?(s.renderTarget.ensureDepthStencil(),s.stencil.setStencilMode(T.RENDERING_MASK_ADD,i),i++,s.colorMask.setMask(0)):e.action==="pushMaskEnd"?(e.inverse?s.stencil.setStencilMode(T.INVERSE_MASK_ACTIVE,i):s.stencil.setStencilMode(T.MASK_ACTIVE,i),s.colorMask.setMask(15)):e.action==="popMaskBegin"?(s.colorMask.setMask(0),i!==0?s.stencil.setStencilMode(T.RENDERING_MASK_REMOVE,i):(s.renderTarget.clear(null,U.STENCIL),s.stencil.setStencilMode(T.DISABLED,i)),i--):e.action==="popMaskEnd"&&(e.inverse?s.stencil.setStencilMode(T.INVERSE_MASK_ACTIVE,i):s.stencil.setStencilMode(T.MASK_ACTIVE,i),s.colorMask.setMask(15)),this._maskStackHash[n]=i}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}ke.extension={type:[d.WebGLPipes,d.WebGPUPipes],name:"stencilMask"};class Se{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}}Se.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"customRender"};function N(a,e){const t=a.instructionSet,r=t.instructions;for(let s=0;s<t.instructionSize;s++){const n=r[s];e[n.renderPipeId].execute(n)}}class Re{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&&(I.return(e._batchableRenderGroup),e._batchableRenderGroup=null),t.add(e)}_addRenderableCacheAsTexture(e,t){const r=e._batchableRenderGroup??(e._batchableRenderGroup=I.get(_e));r.renderable=e.root,r.transform=e.root.relativeGroupTransform,r.texture=e.texture,r.bounds=e._textureBounds,t.add(e),this._renderer.renderPipes.blendMode.pushBlendMode(e,e.root.groupBlendMode,t),this._renderer.renderPipes.batch.addToBatch(r,t),this._renderer.renderPipes.blendMode.popBlendMode(t)}_executeCacheAsTexture(e){if(e.textureNeedsUpdate){e.textureNeedsUpdate=!1;const t=new x().translate(-e._textureBounds.x,-e._textureBounds.y);this._renderer.renderTarget.push({target:e.texture,clear:!0,frame:e.texture.frame}),this._renderer.globalUniforms.push({worldTransformMatrix:t,worldColor:4294967295,offset:{x:0,y:0}}),N(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}),N(e,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}Re.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"renderGroup"};class Me{constructor(e){this._renderer=e}addRenderable(e,t){const r=this._getGpuSprite(e);e.didViewUpdate&&this._updateBatchableSprite(e,r),this._renderer.renderPipes.batch.addToBatch(r,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 _e;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}}Me.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"sprite"};const B={};Y.handle(d.BlendMode,a=>{if(!a.name)throw new Error("BlendMode extension must have a name property");B[a.name]=a.ref},a=>{delete B[a.name]});class we{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,r){this._blendModeStack.push(t),this.setBlendMode(e,t,r)}popBlendMode(e){this._blendModeStack.pop();const t=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,t,e)}setBlendMode(e,t,r){const s=e instanceof ae;if(this._activeBlendMode===t){this._isAdvanced&&e&&!s&&this._renderableList?.push(e);return}this._isAdvanced&&this._endAdvancedBlendMode(r),this._activeBlendMode=t,e&&(this._isAdvanced=!!B[t],this._isAdvanced&&this._beginAdvancedBlendMode(e,r))}_beginAdvancedBlendMode(e,t){this._renderer.renderPipes.batch.break(t);const r=this._activeBlendMode;if(!B[r]){S(`Unable to assign BlendMode: '${r}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const s=this._ensureFilterEffect(r),n=e instanceof ae,i={renderPipeId:"filter",action:"pushFilter",filterEffect:s,renderables:n?null:[e],container:n?e.root:null,canBundle:!1};this._renderableList=i.renderables,t.add(i)}_ensureFilterEffect(e){let t=this._filterHash[e];return t||(t=this._filterHash[e]=new ue,t.filters=[new B[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}}we.extension={type:[d.WebGLPipes,d.WebGPUPipes,d.CanvasPipes],name:"blendMode"};function j(a,e){e||(e=0);for(let t=e;t<a.length&&a[t];t++)a[t]=null}const mt=new L,de=fe|me|ge;function Pe(a,e=!1){gt(a);const t=a.childrenToUpdate,r=a.updateTick++;for(const s in t){const n=Number(s),i=t[s],l=i.list,o=i.index;for(let h=0;h<o;h++){const c=l[h];c.parentRenderGroup===a&&c.relativeRenderGroupDepth===n&&Be(c,r,0)}j(l,o),i.index=0}if(e)for(let s=0;s<a.renderGroupChildren.length;s++)Pe(a.renderGroupChildren[s],e)}function gt(a){const e=a.root;let t;if(a.renderGroupParent){const r=a.renderGroupParent;a.worldTransform.appendFrom(e.relativeGroupTransform,r.worldTransform),a.worldColor=pe(e.groupColor,r.worldColor),t=e.groupAlpha*r.worldAlpha}else a.worldTransform.copyFrom(e.localTransform),a.worldColor=e.localColor,t=e.localAlpha;t=t<0?0:t>1?1:t,a.worldAlpha=t,a.worldColorAlpha=a.worldColor+((t*255|0)<<24)}function Be(a,e,t){if(e===a.updateTick)return;a.updateTick=e,a.didChange=!1;const r=a.localTransform;a.updateLocalTransform();const s=a.parent;if(s&&!s.renderGroup?(t|=a._updateFlags,a.relativeGroupTransform.appendFrom(r,s.relativeGroupTransform),t&de&&ce(a,s,t)):(t=a._updateFlags,a.relativeGroupTransform.copyFrom(r),t&de&&ce(a,mt,t)),!a.renderGroup){const n=a.children,i=n.length;for(let h=0;h<i;h++)Be(n[h],e,t);const l=a.parentRenderGroup,o=a;o.renderPipeId&&!l.structureDidChange&&l.updateRenderable(o)}}function ce(a,e,t){if(t&me){a.groupColor=pe(a.localColor,e.groupColor);let r=a.localAlpha*e.groupAlpha;r=r<0?0:r>1?1:r,a.groupAlpha=r,a.groupColorAlpha=a.groupColor+((r*255|0)<<24)}t&ge&&(a.groupBlendMode=a.localBlendMode==="inherit"?e.groupBlendMode:a.localBlendMode),t&fe&&(a.globalDisplayStatus=a.localDisplayStatus&e.globalDisplayStatus),a._updateFlags=0}function _t(a,e){const{list:t}=a.childrenRenderablesToUpdate;let r=!1;for(let s=0;s<a.childrenRenderablesToUpdate.index;s++){const n=t[s];if(r=e[n.renderPipeId].validateRenderable(n),r)break}return a.structureDidChange=r,r}const xt=new x;class Ge{constructor(e){this._renderer=e}render({container:e,transform:t}){const r=e.parent,s=e.renderGroup.renderGroupParent;e.parent=null,e.renderGroup.renderGroupParent=null;const n=this._renderer,i=xt;t&&(i.copyFrom(e.renderGroup.localTransform),e.renderGroup.localTransform.copyFrom(t));const l=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}),N(e.renderGroup,l),l.uniformBatch&&l.uniformBatch.renderEnd(),t&&e.renderGroup.localTransform.copyFrom(i),e.parent=r,e.renderGroup.renderGroupParent=s}destroy(){this._renderer=null}_updateCachedRenderGroups(e,t){if(e._parentCacheAsTextureRenderGroup=t,e.isCachedAsTexture){if(!e.textureNeedsUpdate)return;t=e}for(let r=e.renderGroupChildren.length-1;r>=0;r--)this._updateCachedRenderGroups(e.renderGroupChildren[r],t);if(e.invalidateMatrices(),e.isCachedAsTexture){if(e.textureNeedsUpdate){const r=e.root.getLocalBounds(),s=this._renderer,n=e.textureOptions.resolution||s.view.resolution,i=e.textureOptions.antialias??s.view.antialias,l=e.textureOptions.scaleMode??"linear",o=e.texture;r.ceil(),e.texture&&M.returnTexture(e.texture,!0);const h=M.getOptimalTexture(r.width,r.height,n,i);h._source.style=new Xe({scaleMode:l}),e.texture=h,e._textureBounds||(e._textureBounds=new $),e._textureBounds.copyFrom(r),o!==e.texture&&e.renderGroupParent&&(e.renderGroupParent.structureDidChange=!0)}}else e.texture&&(M.returnTexture(e.texture,!0),e.texture=null)}_updateRenderGroups(e){const t=this._renderer,r=t.renderPipes;if(e.runOnRender(t),e.instructionSet.renderPipes=r,e.structureDidChange?j(e.childrenRenderablesToUpdate.list,0):_t(e,r),Pe(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 s=0;s<e.renderGroupChildren.length;s++)this._updateRenderGroups(e.renderGroupChildren[s])}_updateRenderables(e){const{list:t,index:r}=e.childrenRenderablesToUpdate;for(let s=0;s<r;s++){const n=t[s];n.didViewUpdate&&e.updateRenderable(n)}j(t,r)}_buildInstructions(e,t){const r=e.root,s=e.instructionSet;s.reset();const n=t.renderPipes?t:t.batch.renderer,i=n.renderPipes;i.batch.buildStart(s),i.blendMode.buildStart(),i.colorMask.buildStart(),r.sortableChildren&&r.sortChildren(),r.collectRenderablesWithEffects(s,n,null),i.batch.buildEnd(s),i.blendMode.buildEnd(s)}}Ge.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"renderGroup"};const X=class Ae{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new W(0),this.color=this._backgroundColor,this.alpha=1}init(e){e={...Ae.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){W.shared.setValue(e).alpha<1&&this._backgroundColor.alpha===1&&S("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(){}};X.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"background",priority:0};X.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let bt=X;const H={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},J=class Ue{constructor(e){this._renderer=e}_normalizeOptions(e,t={}){return e instanceof L||e instanceof _?{target:e,...t}:{...t,...e}}async image(e){const t=q.get().createImage();return t.src=await this.base64(e),t}async base64(e){e=this._normalizeOptions(e,Ue.defaultImageOptions);const{format:t,quality:r}=e,s=this.canvas(e);if(s.toBlob!==void 0)return new Promise((n,i)=>{s.toBlob(l=>{if(!l){i(new Error("ICanvas.toBlob failed!"));return}const o=new FileReader;o.onload=()=>n(o.result),o.onerror=i,o.readAsDataURL(l)},H[t],r)});if(s.toDataURL!==void 0)return s.toDataURL(H[t],r);if(s.convertToBlob!==void 0){const n=await s.convertToBlob({type:H[t],quality:r});return new Promise((i,l)=>{const o=new FileReader;o.onload=()=>i(o.result),o.onerror=l,o.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,r=this._renderer;if(t instanceof _)return r.texture.generateCanvas(t);const s=r.textureGenerator.generateTexture(e),n=r.texture.generateCanvas(s);return s.destroy(!0),n}pixels(e){e=this._normalizeOptions(e);const t=e.target,r=this._renderer,s=t instanceof _?t:r.textureGenerator.generateTexture(e),n=r.texture.getPixels(s);return t instanceof L&&s.destroy(!0),n}texture(e){return e=this._normalizeOptions(e),e.target instanceof _?e.target:this._renderer.textureGenerator.generateTexture(e)}download(e){e=this._normalizeOptions(e);const t=this.canvas(e),r=document.createElement("a");r.download=e.filename??"image.png",r.href=t.toDataURL("image/png"),document.body.appendChild(r),r.click(),document.body.removeChild(r)}log(e){const t=e.width??200;e=this._normalizeOptions(e);const r=this.canvas(e),s=r.toDataURL();console.log(`[Pixi Texture] ${r.width}px ${r.height}px`);const n=["font-size: 1px;",`padding: ${t}px 300px;`,`background: url(${s}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",n)}destroy(){this._renderer=null}};J.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"extract"};J.defaultImageOptions={format:"png",quality:1};let yt=J;class Q extends _{static create(e){const{dynamic:t,textureOptions:r,...s}=e;return new Q({...r,source:new w(s),dynamic:t??!1})}resize(e,t,r){return this.source.resize(e,t,r),this}}const Tt=new P,vt=new $,Ct=[0,0,0,0];class De{constructor(e){this._renderer=e}generateTexture(e){e instanceof L&&(e={target:e,frame:void 0,textureSourceOptions:{},resolution:void 0});const t=e.resolution||this._renderer.resolution,r=e.antialias||this._renderer.view.antialias,s=e.target;let n=e.clearColor;n?n=Array.isArray(n)&&n.length===4?n:W.shared.setValue(n).toArray():n=Ct;const i=e.frame?.copyTo(Tt)||Je(s,vt).rectangle,l=e.defaultAnchor&&{defaultAnchor:e.defaultAnchor};i.width=Math.max(i.width,1/t)|0,i.height=Math.max(i.height,1/t)|0;const o=Q.create({...e.textureSourceOptions,width:i.width,height:i.height,resolution:t,antialias:r,textureOptions:l}),h=x.shared.translate(-i.x,-i.y);return this._renderer.render({container:s,transform:h,target:o,clearColor:n}),o.source.updateMipmaps(),o}destroy(){this._renderer=null}}De.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"textureGenerator"};function kt(a){let e=!1;for(const r in a)if(a[r]==null){e=!0;break}if(!e)return a;const t=Object.create(null);for(const r in a){const s=a[r];s&&(t[r]=s)}return t}function St(a){let e=0;for(let t=0;t<a.length;t++)a[t]==null?e++:a[t-e]=a[t];return a.length-=e,a}const Z=class Ee{constructor(e){this._managedResources=[],this._managedResourceHashes=[],this._managedCollections=[],this._ready=!1,this._renderer=e}init(e){e={...Ee.defaultOptions,...e},this.maxUnusedTime=e.gcMaxUnusedTime,this._frequency=e.gcFrequency,this.enabled=e.gcActive,this.now=performance.now()}get enabled(){return!!this._handler}set enabled(e){this.enabled!==e&&(e?(this._handler=this._renderer.scheduler.repeat(()=>{this._ready=!0},this._frequency,!1),this._collectionsHandler=this._renderer.scheduler.repeat(()=>{for(const t of this._managedCollections){const{context:r,collection:s,type:n}=t;n==="hash"?r[s]=kt(r[s]):r[s]=St(r[s])}},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._collectionsHandler),this._handler=0,this._collectionsHandler=0))}prerender({container:e}){this.now=performance.now(),e.renderGroup.gcTick=this._renderer.tick++,this._updateInstructionGCTick(e.renderGroup,e.renderGroup.gcTick)}postrender(){!this._ready||!this.enabled||(this.run(),this._ready=!1)}_updateInstructionGCTick(e,t){e.instructionSet.gcTick=t,e.gcTick=t;for(const r of e.renderGroupChildren)this._updateInstructionGCTick(r,t)}addCollection(e,t,r){this._managedCollections.push({context:e,collection:t,type:r})}addResource(e,t){if(e._gcLastUsed!==-1){e._gcLastUsed=this.now,e._onTouch?.(this.now);return}const r=this._managedResources.length;e._gcData={index:r,type:t},e._gcLastUsed=this.now,e._onTouch?.(this.now),e.once("unload",this.removeResource,this),this._managedResources.push(e)}removeResource(e){const t=e._gcData;if(!t)return;const r=t.index,s=this._managedResources.length-1;if(r!==s){const n=this._managedResources[s];this._managedResources[r]=n,n._gcData.index=r}this._managedResources.length--,e._gcData=null,e._gcLastUsed=-1}addResourceHash(e,t,r,s=0){this._managedResourceHashes.push({context:e,hash:t,type:r,priority:s}),this._managedResourceHashes.sort((n,i)=>n.priority-i.priority)}run(){const e=performance.now(),t=this._managedResourceHashes;for(const s of t)this.runOnHash(s,e);let r=0;for(let s=0;s<this._managedResources.length;s++){const n=this._managedResources[s];r=this.runOnResource(n,e,r)}this._managedResources.length=r}updateRenderableGCTick(e,t){const r=e.renderGroup??e.parentRenderGroup,s=r?.instructionSet?.gcTick??-1;(r?.gcTick??0)===s&&(e._gcLastUsed=t,e._onTouch?.(t))}runOnResource(e,t,r){const s=e._gcData;return s.type==="renderable"&&this.updateRenderableGCTick(e,t),t-e._gcLastUsed<this.maxUnusedTime||!e.autoGarbageCollect?(this._managedResources[r]=e,s.index=r,r++):(e.unload(),e._gcData=null,e._gcLastUsed=-1,e.off("unload",this.removeResource,this)),r}_createHashClone(e,t){const r=Object.create(null);for(const s in e){if(s===t)break;e[s]!==null&&(r[s]=e[s])}return r}runOnHash(e,t){const{context:r,hash:s,type:n}=e,i=r[s];let l=null,o=0;for(const h in i){const c=i[h];if(c===null){o++,o===1e4&&!l&&(l=this._createHashClone(i,h));continue}if(c._gcLastUsed===-1){c._gcLastUsed=t,c._onTouch?.(t),l&&(l[h]=c);continue}if(n==="renderable"&&this.updateRenderableGCTick(c,t),!(t-c._gcLastUsed<this.maxUnusedTime)&&c.autoGarbageCollect){if(n==="renderable"){const p=c,u=p.renderGroup??p.parentRenderGroup;u&&(u.structureDidChange=!0)}c.unload(),c._gcData=null,c._gcLastUsed=-1,l||(o+1!==1e4?(i[h]=null,o++):l=this._createHashClone(i,h))}else l&&(l[h]=c)}l&&(r[s]=l)}destroy(){this.enabled=!1,this._managedResources.forEach(e=>{e.off("unload",this.removeResource,this)}),this._managedResources.length=0,this._managedResourceHashes.length=0,this._managedCollections.length=0,this._renderer=null}};Z.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"gc",priority:0};Z.defaultOptions={gcActive:!0,gcMaxUnusedTime:6e4,gcFrequency:3e4};let Rt=Z;class Ie{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:r,worldColor:s,offset:n}){const i=this._renderer.renderTarget.renderTarget,l=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new x,worldColor:4294967295,offset:new Qe},o={projectionMatrix:t||this._renderer.renderTarget.projectionMatrix,resolution:e||i.size,worldTransformMatrix:r||l.worldTransformMatrix,worldColor:s||l.worldColor,offset:n||l.offset,bindGroup:null},h=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(h);const c=h.uniforms;c.uProjectionMatrix=o.projectionMatrix,c.uResolution=o.resolution,c.uWorldTransformMatrix.copyFrom(o.worldTransformMatrix),c.uWorldTransformMatrix.tx-=o.offset.x,c.uWorldTransformMatrix.ty-=o.offset.y,lt(o.worldColor,c.uWorldColorAlpha,0),h.update();let m;this._renderer.renderPipes.uniformBatch?m=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(h,!1):(m=this._bindGroupPool.pop()||new ot,this._activeBindGroups.push(m),m.setResource(h,0)),o.bindGroup=m,this._currentGlobalUniformData=o}push(e){this.bind(e),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===O.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 xe({uProjectionMatrix:{value:new x,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new x,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}}Ie.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"globalUniforms"};let Mt=1;class Le{constructor(){this._tasks=[],this._offset=0}init(){ie.system.add(this._update,this)}repeat(e,t,r=!0){const s=Mt++;let n=0;return r&&(this._offset+=1e3,n=this._offset),this._tasks.push({func:e,duration:t,start:performance.now(),offset:n,last:performance.now(),repeat:!0,id:s}),s}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 r=this._tasks[t];if(e-r.offset-r.last>=r.duration){const s=e-r.start;r.func(s),r.last=e}}}destroy(){ie.system.remove(this._update,this),this._tasks.length=0}}Le.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"scheduler",priority:0};let he=!1;function wt(a){if(!he){if(q.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const e=[`%c  %c  %c  %c  %c PixiJS %c v${oe} (${a}) http://www.pixijs.com/

`,"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 ${oe} - ${a} - http://www.pixijs.com/`);he=!0}}class ee{constructor(e){this._renderer=e}init(e){if(e.hello){let t=this._renderer.name;this._renderer.type===O.WEBGL&&(t+=` ${this._renderer.context.webGLVersion}`),wt(t)}}}ee.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"hello",priority:-2};ee.defaultOptions={hello:!1};const te=class Oe{constructor(e){this._renderer=e}init(e){e={...Oe.defaultOptions,...e},this.maxUnusedTime=e.renderableGCMaxUnusedTime}get enabled(){return f("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled}set enabled(e){f("8.15.0","RenderableGCSystem.enabled is deprecated, please use the GCSystem.enabled instead."),this._renderer.gc.enabled=e}addManagedHash(e,t){f("8.15.0","RenderableGCSystem.addManagedHash is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"hash")}addManagedArray(e,t){f("8.15.0","RenderableGCSystem.addManagedArray is deprecated, please use the GCSystem.addCollection instead."),this._renderer.gc.addCollection(e,t,"array")}addRenderable(e){f("8.15.0","RenderableGCSystem.addRenderable is deprecated, please use the GCSystem instead."),this._renderer.gc.addResource(e,"renderable")}run(){f("8.15.0","RenderableGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};te.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"renderableGC",priority:0};te.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Pt=te;const re=class D{get count(){return this._renderer.tick}get checkCount(){return this._checkCount}set checkCount(e){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._checkCount=e}get maxIdle(){return this._renderer.gc.maxUnusedTime/1e3*60}set maxIdle(e){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.maxUnusedTime=e/60*1e3}get checkCountMax(){return Math.floor(this._renderer.gc._frequency/1e3)}set checkCountMax(e){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead.")}get active(){return this._renderer.gc.enabled}set active(e){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.enabled=e}constructor(e){this._renderer=e,this._checkCount=0}init(e){e.textureGCActive!==D.defaultOptions.textureGCActive&&(this.active=e.textureGCActive),e.textureGCMaxIdle!==D.defaultOptions.textureGCMaxIdle&&(this.maxIdle=e.textureGCMaxIdle),e.textureGCCheckCountMax!==D.defaultOptions.textureGCCheckCountMax&&(this.checkCountMax=e.textureGCCheckCountMax)}run(){f("8.15.0","TextureGCSystem.run is deprecated, please use the GCSystem instead."),this._renderer.gc.run()}destroy(){this._renderer=null}};re.extension={type:[d.WebGLSystem,d.WebGPUSystem],name:"textureGC"};re.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:60*60,textureGCCheckCountMax:600};let Bt=re;const Fe=class ze{constructor(e={}){this.uid=Ze("renderTarget"),this.colorAttachments=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,this._depth=!1,this._stencil=!1,this._colorTextures=null;const t="colorAttachments"in e?e:this._normalizeOptions(e);if(this.isRoot=t.isRoot??!1,this.label=t.label,this.colorAttachments=t.colorAttachments,this.depthStencilAttachment=t.depthStencilAttachment,this.depthStencilAttachment){const r=this.depthStencilAttachment.texture.format;this._depth||(this._depth=r.includes("depth")),this._stencil||(this._stencil=r.includes("stencil"))}if(this.colorAttachments.length===0&&!this.depthStencilAttachment)throw new Error("[RenderTarget] no color textures or depth textures were provided. Provide a depthStencilTexture or set depth/stencil to true when using colorTextures: 0.");if(this.colorAttachments.length>0){const r=this.colorTexture;this.resize(r.width,r.height,r._resolution)}this.sizeSource&&this.sizeSource.on("resize",this.onSourceResize,this)}_normalizeOptions(e){const t={...ze.defaultOptions,...e},r=[];let s;if(typeof t.colorTextures=="number"){if(t.colorTextures>0){this._managedColorTextures=!0;for(let i=0;i<t.colorTextures;i++)r.push({texture:new w({width:t.width,height:t.height,resolution:t.resolution,antialias:t.antialias}),loadOp:"clear",storeOp:"store"})}}else t.colorTextures.forEach(i=>{r.push({texture:i.source,loadOp:"clear",storeOp:"store"})});const n=t.depthStencilTexture===!0;if(this._depth=!!(t.depth||n),this._stencil=!!(t.stencil||n),t.depthStencilTexture instanceof _||t.depthStencilTexture instanceof w){if(t.isRoot)throw new Error("[RenderTarget] cannot attach a depth-stencil texture to the screen — the canvas owns its own depth/stencil buffers. Render to a texture target instead.");s={texture:t.depthStencilTexture.source}}else(n&&!t.isRoot||(t.stencil||t.depth)&&r.length===0)&&(s=this._createDepthStencilTexture(t.width,t.height,t.resolution));return{colorAttachments:r,depthStencilAttachment:s,isRoot:t.isRoot,label:t.label}}get size(){const e=this._size;return e[0]=this.pixelWidth,e[1]=this.pixelHeight,e}get width(){return this.sizeSource.width}get height(){return this.sizeSource.height}get pixelWidth(){return this.sizeSource.pixelWidth}get pixelHeight(){return this.sizeSource.pixelHeight}get resolution(){return this.sizeSource._resolution}get colorTextures(){return this._colorTextures||(this._colorTextures=this.colorAttachments.map(e=>e.texture)),this._colorTextures}get depthStencilTexture(){return this.depthStencilAttachment?.texture??null}get depth(){return this._depth}get stencil(){return this._stencil}get colorTexture(){return this.colorAttachments[0]?.texture}get sizeSource(){return this.colorAttachments[0]?.texture??this.depthStencilAttachment?.texture}onSourceResize(e){this.resize(e.width,e.height,e._resolution,!0)}ensureDepthStencilTexture(){this._createDepthStencilTexture(this.sizeSource.width,this.sizeSource.height,this.sizeSource._resolution),this._depth=!0,this._stencil=!0}resize(e,t,r=this.resolution,s=!1){if(this.dirtyId++,this.colorAttachments.forEach((n,i)=>{s&&i===0||n.texture.resize(e,t,r)}),this.depthStencilAttachment){if(s&&this.colorAttachments.length===0)return;this.depthStencilAttachment.texture.resize(e,t,r)}}destroy(){!this.colorAttachments&&!this.depthStencilAttachment||(this.sizeSource.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorAttachments.forEach(e=>{e.texture.destroy()}),this.depthStencilAttachment&&(this.depthStencilAttachment.texture.destroy(),delete this.depthStencilAttachment),this.colorAttachments=null,this._colorTextures=null)}_createDepthStencilTexture(e,t,r){return this.depthStencilAttachment??(this.depthStencilAttachment={texture:new w({width:e,height:t,resolution:r,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1})}),this.depthStencilAttachment}};Fe.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let E=Fe;const k=new Map;et.register(k);function He(a,e){if(!k.has(a)){const t=new _({source:new V({resource:a,...e})}),r=()=>{k.get(a)===t&&k.delete(a)};t.once("destroy",r),t.source.once("destroy",r),k.set(a,t)}return k.get(a)}const se=class We{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={...We.defaultOptions,...e},e.view&&(f(tt,"ViewSystem.view has been renamed to ViewSystem.canvas"),e.canvas=e.view),this.screen=new P(0,0,e.width,e.height),this.canvas=e.canvas||q.get().createCanvas(),this.antialias=!!e.antialias,this.texture=He(this.canvas,e),this.renderTarget=new E({colorTextures:[this.texture],depth:!!e.depth,isRoot:!0}),this.texture.source.transparent=e.backgroundAlpha<1,this.resolution=e.resolution}resize(e,t,r){this.texture.source.resize(e,t,r),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()}};se.extension={type:[d.WebGLSystem,d.WebGPUSystem,d.CanvasSystem],name:"view",priority:0};se.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};let Gt=se;const Ft=[bt,Ie,ee,Gt,Ge,Rt,Bt,De,yt,rt,Pt,Le],zt=[we,Te,Me,Re,ve,ke,Ce,Se];function At(a,e,t,r,s,n){const i=n?1:-1;return a.identity(),a.a=1/r*2,a.d=i*(1/s*2),a.tx=-1-e*a.a,a.ty=-i-t*a.d,a}function Ut(a){if(a.colorAttachments.length===0)return!1;const e=a.colorTexture.resource;return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement&&document.body.contains(e)}class Ht{constructor(e){this.rootViewPort=new P,this.viewport=new P,this.onRenderTargetChange=new st("onRenderTargetChange"),this.projectionMatrix=new x,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._bindState={target:null,frame:void 0,mipLevel:0,layer:0,flipY:!1},this._bindFrame=new P,this._renderer=e,e.gc.addCollection(this,"_gpuRenderTargetHash","hash")}get renderSurface(){return this._bindState.target}get mipLevel(){return this._bindState.mipLevel}get layer(){return this._bindState.layer}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart(e){this._renderTargetStack.length=0,this.push(e),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=Ut(this.rootRenderTarget),this.adaptor.prerender?.(this.rootRenderTarget)}postrender(){this.adaptor.postrender?.(this.rootRenderTarget)}bind(e,t=!0,r,s,n=0,i=0,l){let o;"target"in e?o=e:(f("8.20.0","RenderTargetSystem.bind: positional arguments are deprecated, please use an options object instead: bind({ target, clear, clearColor, frame, mipLevel, layer, flipY })"),o={target:e,clear:t,clearColor:r,frame:s,mipLevel:n,layer:i,flipY:l});const h=o.target;t=o.clear??!0,r=o.clearColor,n=(o.mipLevel??0)|0,i=(o.layer??0)|0,l=o.flipY,s=o.frame;const c=this.getRenderTarget(h),m=this.renderTarget!==c;this.renderTarget=c;const p=this.getGpuRenderTarget(c);(c.pixelWidth!==p.width||c.pixelHeight!==p.height)&&(this.adaptor.resizeGpuRenderTarget(c),p.width=c.pixelWidth,p.height=c.pixelHeight);const u=c.colorAttachments[0]?.texture||c.depthStencilAttachment?.texture,g=this.viewport,ne=u.arrayLayerCount||1;if(i<0||i>=ne)throw new Error(`[RenderTargetSystem] layer ${i} is out of bounds (arrayLayerCount=${ne}).`);const R=this._bindState;R.target=h,R.frame=s?this._bindFrame.copyFrom(s):void 0,R.mipLevel=n,R.layer=i,R.flipY=l;const F=Math.max(u.pixelWidth>>n,1),z=Math.max(u.pixelHeight>>n,1);if(!s&&h instanceof _&&(s=h.frame),s){const G=u._resolution,A=1<<Math.max(n,0),Ve=s.x*G+.5|0,Ne=s.y*G+.5|0,je=s.width*G+.5|0,Ye=s.height*G+.5|0;let b=Math.floor(Ve/A),y=Math.floor(Ne/A),v=Math.ceil(je/A),C=Math.ceil(Ye/A);b<0&&(v+=b,b=0),y<0&&(C+=y,y=0),b=Math.min(b,F-1),y=Math.min(y,z-1),v=Math.min(v,F-b),C=Math.min(C,z-y),v=Math.max(v,1),C=Math.max(C,1),g.x=b,g.y=y,g.width=v,g.height=C}else g.x=0,g.y=0,g.width=F,g.height=z;return c.flipY=l,At(this.projectionMatrix,0,0,g.width/u.resolution,g.height/u.resolution,!c.isRoot!=!!c.flipY),this.adaptor.startRenderPass(c,t,r,g,n,i),m&&this.onRenderTargetChange.emit(c),c}getBindState(e){if(!this.renderTarget)throw new Error("[RenderTargetSystem] getBindState is only valid while a render surface is bound");const t=this._bindState;return e??(e={}),e.target=t.target,e.clear=U.NONE,e.clearColor=void 0,t.frame?e.frame?e.frame.copyFrom(t.frame):e.frame=t.frame.clone():e.frame=void 0,e.mipLevel=t.mipLevel,e.layer=t.layer,e.flipY=!!t.flipY,e}get frontFaceInverted(){const e=this.renderTarget;if(!e)return!1;const t=this._renderer.type===O.WEBGL&&!e.isRoot;return!!e.flipY!==t}clear(e,t=U.ALL,r,s=this.mipLevel,n=this.layer){t&&(e&&(e=this.getRenderTarget(e)),this.adaptor.clear(e||this.renderTarget,t,r,this.viewport,s,n))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(e,t=U.ALL,r,s,n=0,i=0,l){let o;"target"in e?o=e:(f("8.20.0","RenderTargetSystem.push: positional arguments are deprecated, please use an options object instead: push({ target, clear, clearColor, frame, mipLevel, layer, flipY })"),o={target:e,clear:t,clearColor:r,frame:s,mipLevel:n,layer:i,flipY:l});const h=this.bind(o);return this._renderTargetStack.push({target:o.target,clear:!1,clearColor:void 0,frame:o.frame?o.frame.clone():void 0,mipLevel:o.mipLevel,layer:o.layer,flipY:o.flipY}),h}pop(){this._renderTargetStack.pop();const e=this._renderTargetStack[this._renderTargetStack.length-1];if(!e)throw new Error("[RenderTargetSystem] pop: no previous binding to restore (unbalanced pop)");return this.bind(e)}getRenderTarget(e){return e.isTexture&&(e=e.source),this._renderSurfaceToRenderTargetHash.get(e)??this._initRenderTarget(e)}copyToTexture(e,t,r,s,n){const i=this.getRenderTarget(e);r.x<0&&(s.width+=r.x,n.x-=r.x,r.x=0),r.y<0&&(s.height+=r.y,n.y-=r.y,r.y=0);const{pixelWidth:l,pixelHeight:o}=i;return s.width=Math.min(s.width,l-r.x),s.height=Math.min(s.height,o-r.y),this.adaptor.copyToTexture(i,t,r,s,n)}copyDepthTexture(e,t,r,s,n={x:0,y:0}){const i=this.getRenderTarget(e);if(!i.depthStencilAttachment){S("[RenderTargetSystem] copyDepthTexture: the source render target has no depth attachment to copy from");return}const l=t.source;if(!l.format.includes("depth")&&!l.format.includes("stencil")){S(`[RenderTargetSystem] copyDepthTexture: the destination texture must have a depth/stencil format (got '${l.format}')`);return}let o=r.x,h=r.y,c=n.x,m=n.y,p=s.width,u=s.height;o<0&&(p+=o,c-=o,o=0),h<0&&(u+=h,m-=h,h=0),p=Math.min(p,i.pixelWidth-o),u=Math.min(u,i.pixelHeight-h),p=Math.min(p,l.pixelWidth-c),u=Math.min(u,l.pixelHeight-m),!(p<=0||u<=0)&&this.adaptor.copyDepthTexture(i,t,{x:o,y:h},{width:p,height:u},{x:c,y:m})}ensureDepthStencil(){if(!this.renderTarget.stencil){if(this.renderTarget.depthStencilTexture){S(`[RenderTargetSystem] a stencil mask is being used, but the render target's depthStencilTexture format '${this.renderTarget.depthStencilTexture.format}' has no stencil aspect, so masking cannot work here. Use a 'depth24plus-stencil8' texture instead.`);return}this.renderTarget._depth=!0,this.renderTarget._stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport,0,this.layer)}}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((e,t)=>{e!==t&&this._releaseRenderTarget(t,e)}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(e){let t=null;if(V.test(e)&&(e=He(e).source),e instanceof E)t=e;else if(e instanceof w){const r=e.format;t=r.includes("depth")||r.includes("stencil")?new E({colorTextures:0,depthStencilTexture:e}):new E({colorTextures:[e]}),e.source instanceof V&&(t.isRoot=!0),e.once("destroy",this._onRenderSurfaceDestroy,this)}return this._renderSurfaceToRenderTargetHash.set(e,t),t}_onRenderSurfaceDestroy(e){const t=this._renderSurfaceToRenderTargetHash.get(e);t&&this._releaseRenderTarget(e,t)}_releaseRenderTarget(e,t){t.destroy(),this._renderSurfaceToRenderTargetHash.delete(e),e.off("destroy",this._onRenderSurfaceDestroy,this);const r=this._gpuRenderTargetHash[t.uid];r&&(this._gpuRenderTargetHash[t.uid]=null,this.adaptor.destroyGpuRenderTarget(r))}getGpuRenderTarget(e){return this._gpuRenderTargetHash[e.uid]||(this._gpuRenderTargetHash[e.uid]=this.adaptor.initGpuRenderTarget(e))}resetState(){this.renderTarget=null,this._bindState.target=null}}export{ve as A,we as B,Se as C,Ht as R,Ft as S,Te as a,Me as b,Re as c,zt as d};
