import { ExtensionType } from '../../../extensions/Extensions.mjs';
import { BigPool } from '../../../utils/pool/PoolGroup.mjs';
import { BatchableSprite } from './BatchableSprite.mjs';

let gpuSpriteHash;
class SpritePipe {
  constructor(renderer) {
    this._gpuSpriteHash = /* @__PURE__ */ Object.create(null);
    this._renderer = renderer;
    gpuSpriteHash = this._gpuSpriteHash;
  }
  addRenderable(renderable, _instructionSet) {
    const gpuSprite = this._getGpuSprite(renderable);
    if (renderable.view._didUpdate)
      this._updateBatchableSprite(renderable, gpuSprite);
    this._renderer.renderPipes.batch.addToBatch(gpuSprite);
  }
  updateRenderable(renderable) {
    const gpuSprite = gpuSpriteHash[renderable.uid];
    if (renderable.view._didUpdate)
      this._updateBatchableSprite(renderable, gpuSprite);
    gpuSprite.batcher.updateElement(gpuSprite);
  }
  validateRenderable(renderable) {
    const texture = renderable.view._texture;
    const gpuSprite = this._getGpuSprite(renderable);
    if (gpuSprite.texture._source !== texture._source) {
      return !gpuSprite.batcher.checkAndUpdateTexture(gpuSprite, texture);
    }
    return false;
  }
  destroyRenderable(renderable) {
    const batchableSprite = gpuSpriteHash[renderable.uid];
    BigPool.return(batchableSprite);
    gpuSpriteHash[renderable.uid] = null;
  }
  _updateBatchableSprite(renderable, batchableSprite) {
    const view = renderable.view;
    view._didUpdate = false;
    batchableSprite.bounds = view.bounds;
    batchableSprite.texture = view._texture;
  }
  _getGpuSprite(renderable) {
    return gpuSpriteHash[renderable.uid] || this._initGPUSprite(renderable);
  }
  _initGPUSprite(renderable) {
    const batchableSprite = BigPool.get(BatchableSprite);
    batchableSprite.sprite = renderable;
    batchableSprite.texture = renderable.view._texture;
    batchableSprite.bounds = renderable.view.bounds;
    gpuSpriteHash[renderable.uid] = batchableSprite;
    renderable.view._didUpdate = false;
    renderable.on("destroyed", () => {
      this.destroyRenderable(renderable);
    });
    return batchableSprite;
  }
  destroy() {
    for (const i in this._gpuSpriteHash) {
      BigPool.return(this._gpuSpriteHash[i]);
    }
    this._gpuSpriteHash = null;
    this._renderer = null;
  }
}
/** @ignore */
SpritePipe.extension = {
  type: [
    ExtensionType.WebGLPipes,
    ExtensionType.WebGPUPipes,
    ExtensionType.CanvasPipes
  ],
  name: "sprite"
};

export { SpritePipe };
//# sourceMappingURL=SpritePipe.mjs.map
