import { Matrix } from '../../maths/Matrix.mjs';
import { Point } from '../../maths/Point.mjs';
import { Filter } from '../../rendering/filters/shared/Filter.mjs';
import { GlProgram } from '../../rendering/renderers/gl/shader/GlProgram.mjs';
import { GpuProgram } from '../../rendering/renderers/gpu/shader/GpuProgram.mjs';
import { UniformGroup } from '../../rendering/renderers/shared/shader/UniformGroup.mjs';
import { Sprite } from '../../rendering/sprite/shared/Sprite.mjs';
import { deprecation, v8_0_0 } from '../../utils/logging/deprecation.mjs';
import fragment from './displacement.mjs';
import vertex from './displacement2.mjs';
import source from './displacement3.mjs';

class DisplacementFilter extends Filter {
  constructor(...args) {
    let options = args[0];
    if (options instanceof Sprite) {
      if (args[1]) {
        deprecation(v8_0_0, "DisplacementFilter now uses options object instead of params. {sprite, scale}");
      }
      options = { sprite: options, scale: args[1] };
    }
    let scale = options.scale ?? 20;
    if (typeof scale === "number") {
      scale = new Point(scale, scale);
    }
    const filterUniforms = new UniformGroup({
      filterMatrix: { value: new Matrix(), type: "mat3x3<f32>" },
      scale: { value: scale, type: "vec2<f32>" },
      rotation: { value: new Float32Array([0, 0, 0, 0]), type: "vec4<f32>" }
    });
    const glProgram = GlProgram.from({
      vertex,
      fragment,
      name: "displacement-filter"
    });
    const gpuProgram = GpuProgram.from({
      vertex: {
        source,
        entryPoint: "mainVertex"
      },
      fragment: {
        source,
        entryPoint: "mainFragment"
      }
    });
    const textureSource = options.sprite.texture.source;
    super({
      gpuProgram,
      glProgram,
      resources: {
        filterUniforms,
        mapTexture: textureSource,
        mapSampler: textureSource.style
      }
    });
    this._sprite = options.sprite;
    this._sprite.renderable = false;
  }
  apply(filterManager, input, output, clearMode) {
    const uniforms = this.resources.filterUniforms.uniforms;
    filterManager.calculateSpriteMatrix(
      uniforms.filterMatrix,
      this._sprite
    );
    const wt = this._sprite.worldTransform;
    const lenX = Math.sqrt(wt.a * wt.a + wt.b * wt.b);
    const lenY = Math.sqrt(wt.c * wt.c + wt.d * wt.d);
    if (lenX !== 0 && lenY !== 0) {
      uniforms.rotation[0] = wt.a / lenX;
      uniforms.rotation[1] = wt.b / lenX;
      uniforms.rotation[2] = wt.c / lenY;
      uniforms.rotation[3] = wt.d / lenY;
    }
    this.resources.mapTexture = this._sprite.texture.source;
    filterManager.applyFilter(this, input, output, clearMode);
  }
  get scale() {
    return this.resources.filterUniforms.uniforms.scale;
  }
}

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