const pc = window.pc;
import { Debugger as p, loadAsset as A, loadFontAsset as Q, ViverseApp as $, createLayer as X, Billboard as Y } from "./core.mjs";
import { ActionToggleOption as S, ActionPlaybackOption as R, CompletionType as k, PostEffectType as E, BillboardTargetType as P } from "./types.mjs";
function K(r) {
  return r && r.__esModule && Object.prototype.hasOwnProperty.call(r, "default") ? r.default : r;
}
var N = { exports: {} }, F;
function J() {
  return F || (F = 1, function(r) {
    var e = Object.prototype.hasOwnProperty, t = "~";
    function i() {
    }
    Object.create && (i.prototype = /* @__PURE__ */ Object.create(null), new i().__proto__ || (t = !1));
    function o(h, a, d) {
      this.fn = h, this.context = a, this.once = d || !1;
    }
    function s(h, a, d, l, v) {
      if (typeof d != "function")
        throw new TypeError("The listener must be a function");
      var f = new o(d, l || h, v), _ = t ? t + a : a;
      return h._events[_] ? h._events[_].fn ? h._events[_] = [h._events[_], f] : h._events[_].push(f) : (h._events[_] = f, h._eventsCount++), h;
    }
    function n(h, a) {
      --h._eventsCount === 0 ? h._events = new i() : delete h._events[a];
    }
    function c() {
      this._events = new i(), this._eventsCount = 0;
    }
    c.prototype.eventNames = function() {
      var a = [], d, l;
      if (this._eventsCount === 0) return a;
      for (l in d = this._events)
        e.call(d, l) && a.push(t ? l.slice(1) : l);
      return Object.getOwnPropertySymbols ? a.concat(Object.getOwnPropertySymbols(d)) : a;
    }, c.prototype.listeners = function(a) {
      var d = t ? t + a : a, l = this._events[d];
      if (!l) return [];
      if (l.fn) return [l.fn];
      for (var v = 0, f = l.length, _ = new Array(f); v < f; v++)
        _[v] = l[v].fn;
      return _;
    }, c.prototype.listenerCount = function(a) {
      var d = t ? t + a : a, l = this._events[d];
      return l ? l.fn ? 1 : l.length : 0;
    }, c.prototype.emit = function(a, d, l, v, f, _) {
      var y = t ? t + a : a;
      if (!this._events[y]) return !1;
      var u = this._events[y], b = arguments.length, C, m;
      if (u.fn) {
        switch (u.once && this.removeListener(a, u.fn, void 0, !0), b) {
          case 1:
            return u.fn.call(u.context), !0;
          case 2:
            return u.fn.call(u.context, d), !0;
          case 3:
            return u.fn.call(u.context, d, l), !0;
          case 4:
            return u.fn.call(u.context, d, l, v), !0;
          case 5:
            return u.fn.call(u.context, d, l, v, f), !0;
          case 6:
            return u.fn.call(u.context, d, l, v, f, _), !0;
        }
        for (m = 1, C = new Array(b - 1); m < b; m++)
          C[m - 1] = arguments[m];
        u.fn.apply(u.context, C);
      } else {
        var Z = u.length, B;
        for (m = 0; m < Z; m++)
          switch (u[m].once && this.removeListener(a, u[m].fn, void 0, !0), b) {
            case 1:
              u[m].fn.call(u[m].context);
              break;
            case 2:
              u[m].fn.call(u[m].context, d);
              break;
            case 3:
              u[m].fn.call(u[m].context, d, l);
              break;
            case 4:
              u[m].fn.call(u[m].context, d, l, v);
              break;
            default:
              if (!C) for (B = 1, C = new Array(b - 1); B < b; B++)
                C[B - 1] = arguments[B];
              u[m].fn.apply(u[m].context, C);
          }
      }
      return !0;
    }, c.prototype.on = function(a, d, l) {
      return s(this, a, d, l, !1);
    }, c.prototype.once = function(a, d, l) {
      return s(this, a, d, l, !0);
    }, c.prototype.removeListener = function(a, d, l, v) {
      var f = t ? t + a : a;
      if (!this._events[f]) return this;
      if (!d)
        return n(this, f), this;
      var _ = this._events[f];
      if (_.fn)
        _.fn === d && (!v || _.once) && (!l || _.context === l) && n(this, f);
      else {
        for (var y = 0, u = [], b = _.length; y < b; y++)
          (_[y].fn !== d || v && !_[y].once || l && _[y].context !== l) && u.push(_[y]);
        u.length ? this._events[f] = u.length === 1 ? u[0] : u : n(this, f);
      }
      return this;
    }, c.prototype.removeAllListeners = function(a) {
      var d;
      return a ? (d = t ? t + a : a, this._events[d] && n(this, d)) : (this._events = new i(), this._eventsCount = 0), this;
    }, c.prototype.off = c.prototype.removeListener, c.prototype.addListener = c.prototype.on, c.prefixed = t, c.EventEmitter = c, r.exports = c;
  }(N)), N.exports;
}
var ee = J();
const V = /* @__PURE__ */ K(ee);
class M extends V {
  static instance;
  _eventNameMap = /* @__PURE__ */ new Map();
  constructor() {
    super();
  }
  static getInstance() {
    return M.instance || (M.instance = new M()), M.instance;
  }
  getTriggerEventName(e) {
    return "viverse-trigger-condition:" + e;
  }
  fireTriggerEvent(e) {
    this.emit(this.getTriggerEventName(e));
  }
  hasTriggerEvent(e) {
    return this._eventNameMap.has(e);
  }
  hasDuplicateTriggerEvent(e) {
    const t = this._eventNameMap.get(e) || 0;
    return this.hasTriggerEvent(e) && t > 1;
  }
  addTriggerEvent(e) {
    if (this.hasTriggerEvent(e)) {
      const t = this._eventNameMap.get(e) || 0;
      this._eventNameMap.set(e, t + 1);
    } else
      this._eventNameMap.set(e, 1);
  }
  removeTriggerEvent(e) {
    const i = (this._eventNameMap.get(e) || 0) - 1;
    i <= 0 ? this._eventNameMap.delete(e) : this._eventNameMap.set(e, i);
  }
}
class L extends V {
  _viverseApp;
  _config;
  _cooldown = 0;
  _cooldownTimer = 0;
  _isCooldownComplete = !1;
  constructor(e, t) {
    super(), this._viverseApp = e, this._config = t, this._config?.cooldown && (this._cooldown = this._config?.cooldown), this._cooldown > 0 ? this._cooldownTimer = this._cooldown + 1 : this._resetCooldownTimer(!0), this._viverseApp.pcApp.on("update", this._update, this);
  }
  _resetCooldownTimer(e) {
    this._cooldownTimer = 0, this._isCooldownComplete = e;
  }
  _update(e) {
    this._isCooldownComplete || (this._cooldownTimer <= this._cooldown ? this._cooldownTimer += e : this._resetCooldownTimer(!0));
  }
  destroy() {
    this._viverseApp.pcApp.off("update", this._update, this);
  }
}
class I extends L {
  _entity;
  _collisionEventName = "";
  _tagsFilterSet;
  constructor(e, t, i) {
    super(t, i), this._entity = i.entity, this._collisionEventName = e, i.tagsFilter && (this._tagsFilterSet = new Set(i.tagsFilter));
    const o = this._entity.collision;
    if (!o) {
      p.warn(
        `[ViverseTrigger] Entity '${this._entity.name}' has no collision component for collision triggers.`
      );
      return;
    }
    o.on(this._collisionEventName, this._handleEvent, this);
  }
  _handleEvent() {
  }
  _isPlayer(e) {
    const t = this._viverseApp.systems.localPlayer?.playerEntity;
    return !!t && e === t;
  }
  _hasTag(e) {
    return this._tagsFilterSet ? e.some((t) => this._tagsFilterSet?.has(t)) : !0;
  }
  _canFireEvent(e) {
    if (!this._isCooldownComplete)
      return !1;
    const t = !!this._config.filterByPlayer, i = !!this._tagsFilterSet;
    return t && i ? this._isPlayer(e) || this._hasTag(e.tags.list()) : t ? this._isPlayer(e) : i ? this._hasTag(e.tags.list()) : !0;
  }
  destroy() {
    super.destroy(), this._entity.collision && this._entity.collision.off(this._collisionEventName, this._handleEvent, this);
  }
}
class re extends I {
  constructor(e, t) {
    super("triggerenter", e, t);
  }
  _handleEvent(e) {
    e && this._canFireEvent(e) && (this._resetCooldownTimer(!1), this.emit("triggered", e));
  }
  destroy() {
    super.destroy(), this.removeAllListeners("triggered");
  }
}
class ne extends I {
  constructor(e, t) {
    super("triggerleave", e, t);
  }
  _handleEvent(e) {
    e && this._canFireEvent(e) && (this._resetCooldownTimer(!1), this.emit("triggered", e));
  }
  destroy() {
    super.destroy(), this.removeAllListeners("triggered");
  }
}
class ae extends I {
  constructor(e, t) {
    super("collisionstart", e, t);
  }
  _handleEvent(e) {
    e && this._canFireEvent(e.other) && (this._resetCooldownTimer(!1), this.emit("triggered", e));
  }
  destroy() {
    super.destroy(), this.removeAllListeners("triggered");
  }
}
class le extends I {
  constructor(e, t) {
    super("collisionend", e, t);
  }
  _handleEvent(e) {
    e && this._canFireEvent(e) && (this._resetCooldownTimer(!1), this.emit("triggered", e));
  }
  destroy() {
    super.destroy(), this.removeAllListeners("triggered");
  }
}
class O extends L {
  _entity;
  _animEventName = "";
  constructor(e, t, i) {
    super(t, i), this._entity = i.entity, this._animEventName = e;
    const o = this._entity.anim;
    if (!o) {
      p.warn(
        `[ViverseTrigger] Entity '${this._entity.name}' has no anim component for animation triggers.`
      );
      return;
    }
    o.on(this._animEventName, this._handleEvent, this);
  }
  _handleEvent() {
  }
  _canFireEvent() {
    return this._isCooldownComplete;
  }
  destroy() {
    super.destroy(), this._entity.anim && this._entity.anim.off(this._animEventName, this._handleEvent, this);
  }
}
class ce extends O {
  constructor(e, t) {
    super("start", e, t);
  }
  _handleEvent() {
    this._canFireEvent() && (this._resetCooldownTimer(!1), this.emit("triggered"));
  }
  destroy() {
    super.destroy(), this.removeAllListeners("triggered");
  }
}
class ue extends O {
  constructor(e, t) {
    super("end", e, t);
  }
  _handleEvent() {
    this._canFireEvent() && (this._resetCooldownTimer(!1), this.emit("triggered"));
  }
  destroy() {
    super.destroy(), this.removeAllListeners("triggered");
  }
}
class he extends O {
  constructor(e, t) {
    super(t.eventName, e, t);
  }
  _handleEvent() {
    this._canFireEvent() && (this._resetCooldownTimer(!1), this.emit("triggered"));
  }
  destroy() {
    super.destroy(), this.removeAllListeners("triggered");
  }
}
class G extends L {
  constructor(e, t) {
    super(e, t), this._viverseApp.on("interaction:sitting", this._handleSitting, this);
  }
  _getSeat(e) {
    const t = this._viverseApp.systems.localPlayer?.modules.interaction;
    if (!t)
      throw new Error("[ViverseTrigger] Interaction module not found for local player.");
    const i = t.sitHandler;
    if (!i)
      throw new Error("[ViverseTrigger] SitHandler not enabled in Interaction module.");
    const o = i.getSeat(e);
    if (!o)
      throw new Error("[ViverseTrigger] Seat not found. Entity must be registered as a seat.");
    return o;
  }
  destroy() {
    super.destroy(), this._viverseApp.off("interaction:sitting", this._handleSitting, this);
  }
}
class de extends G {
  _handleSitting(e, t) {
    if (!e) return;
    const i = this._getSeat(this._config.entity);
    t === i && this.emit("triggered");
  }
}
class pe extends G {
  _handleSitting(e, t) {
    if (e) return;
    const i = this._getSeat(this._config.entity);
    t === i && this.emit("triggered");
  }
}
class x extends V {
  static instance;
  constructor() {
    super();
  }
  static getInstance() {
    return x.instance || (x.instance = new x()), x.instance;
  }
}
class _e extends L {
  _notificationName;
  _dispatcher = x.getInstance();
  constructor(e, t) {
    super(e, t), this._notificationName = this._config.notificationName, this._dispatcher.on(this._notificationName, this._onNotified, this);
  }
  _onNotified() {
    this.emit("triggered");
  }
  destroy() {
    super.destroy(), this._dispatcher.off(this._notificationName, this._onNotified, this);
  }
}
class me extends L {
  _entity;
  _pcApp;
  _localPlayerSystem;
  _inputSources = [];
  _inputSourceCallbacks = /* @__PURE__ */ new Map();
  _selectionExcludeTags;
  constructor(e, t) {
    if (super(e, t), this._entity = t.entity, this._pcApp = this._viverseApp.pcApp, this._selectionExcludeTags = new Set(t.selectionExcludeTags || []), this._localPlayerSystem = this._viverseApp.systems.localPlayer, !this._localPlayerSystem) {
      p.warn("[ViverseTrigger] LocalPlayerSystem is not available in the ViverseApp.");
      return;
    }
    this._localPlayerSystem.modules.camera ? this._pcApp.mouse?.on(pc.EVENT_MOUSEDOWN, this._onMouseDown, this) : p.warn(
      "[ViverseTrigger] CameraModule is not available in the LocalPlayerSystem. Mouse input will be disabled."
    ), this._pcApp.xr && (this._pcApp.xr.input.on("add", this._addInputSource, this), this._pcApp.xr.input.on("remove", this._removeInputSource, this));
  }
  _performRaycast(e, t) {
    const i = (s) => !s.tags.list().some((h) => this._selectionExcludeTags.has(h)), o = this._pcApp.systems.rigidbody?.raycastFirst(e, t, {
      ...this._selectionExcludeTags.size > 0 && { filterCallback: i }
    });
    o && o.entity === this._entity && this.emit("triggered");
  }
  _onMouseDown(e) {
    const t = this._localPlayerSystem?.modules.camera?.currentCamera?.entity.camera;
    if (!t) return;
    const i = t.screenToWorld(e.x, e.y, t.nearClip), o = t.screenToWorld(e.x, e.y, t.farClip);
    this._performRaycast(i, o);
  }
  _addInputSource(e) {
    if (this._inputSources.includes(e)) return;
    this._inputSources.push(e);
    const t = () => this._onInputSelectStart(e);
    this._inputSourceCallbacks.set(e, t), e.on("selectstart", t, this);
  }
  _removeInputSource(e) {
    const t = this._inputSources.indexOf(e);
    if (t !== -1) {
      this._inputSources.splice(t, 1);
      const i = this._inputSourceCallbacks.get(e);
      i && e.off("selectstart", i, this), this._inputSourceCallbacks.delete(e);
    }
  }
  _onInputSelectStart(e) {
    const t = e.getOrigin(), i = t.clone().add(e.getDirection().clone().mulScalar(1e3));
    this._performRaycast(t, i);
  }
  destroy() {
    super.destroy(), this._viverseApp.pcApp.mouse?.off(pc.EVENT_MOUSEDOWN, this._onMouseDown, this), this._pcApp.xr?.input.off("add", this._addInputSource, this), this._pcApp.xr?.input.off("remove", this._removeInputSource, this), this._inputSourceCallbacks.size > 0 && this._inputSourceCallbacks.forEach((e, t) => {
      t.off("selectstart", e, this);
    }), this._inputSourceCallbacks.clear(), this._inputSources = [];
  }
}
class fe extends L {
  _localPlayerSystem;
  _interactionModule;
  constructor(e, t) {
    if (super(e, t), this._localPlayerSystem = this._viverseApp.systems.localPlayer, !this._localPlayerSystem) {
      p.warn("[ViverseTrigger] LocalPlayerSystem is not available in the ViverseApp.");
      return;
    }
    if (this._interactionModule = this._localPlayerSystem.modules.interaction, !this._interactionModule) {
      p.warn(
        "[ViverseTrigger] InteractionModule is not available in the LocalPlayerSystem."
      );
      return;
    }
    this._viverseApp.on("interaction:pick-action-executing", this._handleEvent, this);
  }
  _canFireEvent(e) {
    return this._isCooldownComplete && e;
  }
  _handleEvent(e, t) {
    this._canFireEvent(t) && (this._resetCooldownTimer(!1), this.emit("triggered", e));
  }
  destroy() {
    super.destroy(), this._viverseApp && this._viverseApp.off("interaction:pick-action-executing", this._handleEvent, this);
  }
}
class g {
  _viverseApp;
  _config;
  _delay = 0;
  _delayTimer = null;
  constructor(e, t) {
    this._viverseApp = e, this._config = t, this._create();
  }
  _create() {
    this._config?.delay && (this._delay = this._config?.delay);
  }
  _execute() {
  }
  execute() {
    if (this._delayTimer !== null) {
      p.warn(
        "[ViverseAction] This action is about to be executed. Please wait until the current execution is complete before trying again."
      );
      return;
    }
    this._delay > 0 ? this._delayTimer = setTimeout(() => {
      this._execute(), this._delayTimer = null;
    }, this._delay) : this._execute();
  }
  destroy() {
    this._delayTimer !== null && clearTimeout(this._delayTimer);
  }
}
class ve extends g {
  _entity;
  _state = S.Toggle;
  constructor(e, t) {
    super(e, t), this._entity = t.entity, this._state = t.state;
  }
  _execute() {
    this._state === S.Enable ? this._entity.enabled = !0 : this._state === S.Disable ? this._entity.enabled = !1 : this._state === S.Toggle && (this._entity.enabled = !this._entity.enabled);
  }
}
class ge extends g {
  _entity;
  constructor(e, t) {
    super(e, t), this._entity = t.entity;
  }
  _execute() {
    this._entity.destroy();
  }
}
class ye extends g {
  _entity;
  _state = S.Toggle;
  constructor(e, t) {
    super(e, t), this._entity = t.entity, this._state = t.state;
  }
  _execute() {
    this._entity.collision && (this._state === S.Enable ? this._entity.collision.enabled = !0 : this._state === S.Disable ? this._entity.collision.enabled = !1 : this._state === S.Toggle && (this._entity.collision.enabled = !this._entity.collision.enabled));
  }
}
class Se extends g {
  _entity;
  _state = S.Toggle;
  constructor(e, t) {
    super(e, t), this._entity = t.entity, this._state = t.state;
  }
  _execute() {
    this._entity.rigidbody && (this._state === S.Enable ? this._entity.rigidbody.enabled = !0 : this._state === S.Disable ? this._entity.rigidbody.enabled = !1 : this._state === S.Toggle && (this._entity.rigidbody.enabled = !this._entity.rigidbody.enabled));
  }
}
class be extends g {
  _entity;
  constructor(e, t) {
    super(e, t), this._entity = t.entity;
  }
  _execute() {
    const e = this._config.soundName, t = this._config.state;
    this._entity.sound && e && (t === R.Play ? this._entity.sound.play(e) : t === R.Stop && this._entity.sound.stop(e));
  }
}
class Ce extends g {
  _execute() {
    const e = this._viverseApp.systems.localPlayer;
    if (!e) {
      p.warn("[ViverseAction] LocalPlayerSystem is not available in the ViverseApp.");
      return;
    }
    const t = this._config.spawnPoints;
    if (!t || t.length === 0) {
      p.warn("[ViverseAction] No spawn points provided for SetSpawnPointAction.");
      return;
    }
    e.setSpawnPoint(t);
  }
}
class Ee extends g {
  _execute() {
    const e = this._viverseApp.systems.localPlayer;
    if (!e) {
      p.warn("[ViverseAction] LocalPlayerSystem is not available in the ViverseApp.");
      return;
    }
    const t = this._config.position;
    if (!t) {
      p.warn("[ViverseAction] No position provided for TeleportPlayerAction.");
      return;
    }
    e.teleport(t);
  }
}
class Ae extends g {
  _dispatcher = x.getInstance();
  _execute() {
    const e = this._config.notificationName;
    this._dispatcher.emit(e);
  }
}
class xe extends g {
  _execute() {
    const e = this._viverseApp.systems.quest;
    if (!e) {
      p.warn("[ViverseAction] Quest system is not available.");
      return;
    }
    switch (this._config.type) {
      case "addTaskProgress":
        this._handleAddTaskProgress(e);
        break;
      case "completeTask":
        this._handleCompleteTask(e);
        break;
      case "resetQuest":
        this._handleResetQuest(e);
        break;
      case "startQuest":
        this._handleStartQuest(e);
        break;
    }
  }
  _getTargetQuest(e) {
    const { questName: t } = this._config, i = e.getQuestByName(t);
    return i || (p.warn(`[ViverseAction] Quest with name "${t}" not found in Quest system.`), null);
  }
  _getTargetTask(e) {
    const t = this._getTargetQuest(e);
    if (!t) return null;
    const { taskName: i } = this._config;
    if (!i)
      return p.warn("[ViverseAction] Task name is required."), null;
    const o = t.getTaskByName(i);
    return o || (p.warn(`[ViverseAction] Task with name "${i}" not found in "${t.name}".`), null);
  }
  _handleAddTaskProgress(e) {
    const t = this._getTargetTask(e);
    if (!t) return;
    if (t.type !== k.Progress) {
      p.error(
        `[ViverseAction] Can't add progress to task '${t.name}' because it is not a progress task.`
      );
      return;
    }
    const i = t, o = this._config.increment ?? 0;
    i.addProgress(o);
  }
  _handleCompleteTask(e) {
    const t = this._getTargetTask(e);
    if (t)
      if (t.type === k.Progress) {
        const i = t;
        i.addProgress(i.totalProgress);
        return;
      } else t.type === k.Simple ? t.complete() : p.error(`[ViverseAction] Task "${t.name}" has an unknown type.`);
  }
  _handleResetQuest(e) {
    const t = this._getTargetQuest(e);
    t && t.reset();
  }
  _handleStartQuest(e) {
    const t = this._getTargetQuest(e);
    t && t.start();
  }
}
class W extends g {
  _entity;
  _materials;
  _elements;
  _duration;
  _elapsedTime = 0;
  constructor(e, t) {
    super(e, t), this._entity = t.entity, this._duration = t.duration ?? 0.25, this._materials = this._handleMaterials(), this._elements = this._handleElements();
  }
  _convertMaterialBlendType(e) {
    [
      pc.BLEND_NORMAL,
      pc.BLEND_PREMULTIPLIED,
      pc.BLEND_ADDITIVEALPHA
    ].includes(e.blendType) || (e.blendType = pc.BLEND_PREMULTIPLIED, e.update());
  }
  _prepareMaterial(e) {
    const t = e.material;
    if (!(t instanceof pc.StandardMaterial)) return null;
    const i = t;
    if (i.originalOpacity !== void 0)
      return i;
    const o = i.clone();
    return o.originalOpacity = i.opacity, this._convertMaterialBlendType(o), e.material = o, o;
  }
  _handleMaterials() {
    const t = this._entity.findComponents("render").map((o) => o.meshInstances).flat(), i = [];
    return t.forEach((o) => {
      const s = this._prepareMaterial(o);
      s && i.push(s);
    }), i;
  }
  _handleElements() {
    const e = this._entity.findComponents("element");
    return e.forEach((t) => {
      const i = t;
      i.originalOpacity === void 0 && (i.originalOpacity = i.opacity);
    }), e;
  }
  _execute() {
    this._storeOpacityMaps(), this._elapsedTime = 0, this._viverseApp.pcApp.on("update", this._update, this);
  }
  _update(e) {
    this._elapsedTime += e;
    const t = Math.min(this._elapsedTime / this._duration, 1);
    this._updateProgress(t), t >= 1 && this._onComplete();
  }
  _onComplete() {
    this._viverseApp.pcApp.off("update", this._update, this);
  }
  destroy() {
    super.destroy(), this._onComplete();
  }
}
class Te extends W {
  _materialFromOpacities = /* @__PURE__ */ new Map();
  _materialToOpacities = /* @__PURE__ */ new Map();
  _elementFromOpacities = /* @__PURE__ */ new Map();
  _elementToOpacities = /* @__PURE__ */ new Map();
  _storeOpacityMaps() {
    this._materials.forEach((e) => {
      const t = e.originalOpacity ?? 1;
      this._materialFromOpacities.set(e, e.opacity), this._materialToOpacities.set(e, t);
    }), this._elements.forEach((e) => {
      const t = e.originalOpacity ?? 1;
      this._elementFromOpacities.set(e, e.opacity), this._elementToOpacities.set(e, t);
    });
  }
  _updateProgress(e) {
    this._materials.forEach((t) => {
      const i = this._materialFromOpacities.get(t) ?? 0, o = this._materialToOpacities.get(t) ?? 1, s = i + (o - i) * e;
      t.opacity = s, t.update();
    }), this._elements.forEach((t) => {
      const i = this._elementFromOpacities.get(t) ?? 0, o = this._elementToOpacities.get(t) ?? 1, s = i + (o - i) * e;
      t.opacity = s;
    });
  }
  _onComplete() {
    super._onComplete(), this._materialFromOpacities.clear(), this._materialToOpacities.clear(), this._elementFromOpacities.clear(), this._elementToOpacities.clear();
  }
}
class we extends W {
  _fromMaterialOpacities = /* @__PURE__ */ new Map();
  _fromElementOpacities = /* @__PURE__ */ new Map();
  _storeOpacityMaps() {
    this._materials.forEach((e) => {
      this._fromMaterialOpacities.set(e, e.opacity);
    }), this._elements.forEach((e) => {
      this._fromElementOpacities.set(e, e.opacity);
    });
  }
  _updateProgress(e) {
    this._materials.forEach((t) => {
      const o = (this._fromMaterialOpacities.get(t) ?? 1) * (1 - e);
      t.opacity = o, t.update();
    }), this._elements.forEach((t) => {
      const o = (this._fromElementOpacities.get(t) ?? 1) * (1 - e);
      t.opacity = o;
    });
  }
  _onComplete() {
    super._onComplete(), this._fromElementOpacities.clear(), this._fromMaterialOpacities.clear();
  }
}
class Le extends g {
  _entity;
  constructor(e, t) {
    super(e, t), this._entity = t.entity;
  }
  _execute() {
    if (!this._entity.rigidbody || !this._entity.collision) {
      p.warn(
        "[ViverseAction] The target entity does not have a rigidbody or collision component."
      );
      return;
    }
    this._entity.rigidbody.type !== "dynamic" && p.warn("[ViverseAction] The target entity's rigidbody is not dynamic. ");
    const e = this._config.impulse;
    this._entity.rigidbody.applyImpulse(e);
  }
}
class Be extends g {
  _entity;
  _stateName;
  _transitionDuration;
  constructor(e, t) {
    super(e, t), this._entity = t.entity, this._stateName = t.stateName, this._transitionDuration = t.transitionDuration ?? 0.25;
  }
  _execute() {
    const e = this._entity.anim;
    if (!e) {
      p.warn("[ViverseAction] The entity does not have an anim component.");
      return;
    }
    const t = e.baseLayer;
    if (!t) {
      p.warn("[ViverseAction] The anim component does not have a base layer.");
      return;
    }
    if (!t.states.some((s) => s === this._stateName)) {
      p.warn(`[ViverseAction] Animation state '${this._stateName}' does not exist.`);
      return;
    }
    if (e.playing || (e.playing = !0), t.playing || (t.playing = !0), t.activeState === this._stateName) return;
    const o = this._transitionDuration;
    t.transition(this._stateName, o);
  }
}
class Pe extends g {
  _entity;
  constructor(e, t) {
    super(e, t), this._entity = t.entity;
  }
  _execute() {
    const e = this._entity.particlesystem;
    if (!e) {
      p.warn("[ViverseAction] The entity does not have a particlesystem component.");
      return;
    }
    e.reset(), e.play();
  }
}
class Me extends g {
  _title;
  _description;
  _duration;
  constructor(e, t) {
    super(e, t), this._title = t.title, this._description = t.description || "", this._duration = t.duration ?? 4;
  }
  _execute() {
    this._viverseApp.emit("ui:open-toast-message", {
      title: this._title,
      description: this._description,
      duration: this._duration
    });
  }
}
class Ve extends g {
  _execute() {
    const e = this._getSeat(), t = this._viverseApp.systems.localPlayer?.modules.interaction;
    if (!t)
      throw new Error("[ViverseAction] Interaction module not found for local player.");
    const i = t.sitHandler;
    if (!i)
      throw new Error("[ViverseAction] SitHandler not enabled in Interaction module.");
    i.sit(e.name);
  }
  _getSeat() {
    const e = this._viverseApp.systems.localPlayer?.modules.interaction;
    if (!e)
      throw new Error("[ViverseAction] Interaction module not found for local player.");
    const t = e.sitHandler;
    if (!t)
      throw new Error("[ViverseAction] SitHandler not enabled in Interaction module.");
    const i = t.getSeat(this._config.entity);
    if (!i)
      throw new Error("[ViverseTrigger] Seat not found. Entity must be registered as a seat.");
    return i;
  }
}
class Ie extends g {
  _execute() {
    const e = this._viverseApp.systems.localPlayer?.modules.interaction;
    if (!e)
      throw new Error("[ViverseAction] Interaction module not found for local player.");
    const t = e.sitHandler;
    if (!t)
      throw new Error("[ViverseAction] SitHandler not enabled in Interaction module.");
    t.standUp();
  }
}
class ke extends g {
  _link;
  _openInNewTab;
  constructor(e, t) {
    super(e, t), this._link = t.link, this._openInNewTab = t.openInNewTab;
  }
  _execute() {
    this._openInNewTab ? window.open(this._link, "_blank") : window.top ? window.top.location.href = this._link : window.location.href = this._link;
  }
}
class Ne extends g {
  _entity;
  constructor(e, t) {
    super(e, t), this._entity = t.entity;
  }
  _execute() {
    if (!this._entity) {
      p.warn("[ViverseAction] The target entity is not specified.");
      return;
    }
    if (!this._config.eventName) {
      p.warn("[ViverseAction] The event name is not specified.");
      return;
    }
    this._entity.fire(this._config.eventName);
  }
}
class q extends V {
  _viverseApp;
  _entity;
  _config;
  constructor(e, t, i) {
    super(), this._viverseApp = e, this._entity = t, this._config = i;
  }
  _getInteractionModule() {
    const e = this._viverseApp.systems.localPlayer;
    if (!e)
      return p.warn("[ViverseInteraction] localPlayerSystem is not available"), null;
    const t = e.modules?.interaction;
    return t || (p.warn("[ViverseInteraction] interactionModule is not available"), null);
  }
  destroy() {
  }
}
class Oe extends q {
  _item = null;
  constructor(e, t, i) {
    super(e, t, i), this._addPickableItem();
  }
  _addPickableItem() {
    const e = this._getInteractionModule();
    if (!e) return;
    const { name: t, gripPoint: i } = this._config;
    this._item = e.addPickableItem(t, this._entity, {
      ...i && { gripPoint: i }
    });
  }
  destroy() {
    if (super.destroy(), !this._item) return;
    this._getInteractionModule()?.removePickableItem(this._item.name);
  }
}
class Re extends q {
  constructor(e, t, i) {
    super(e, t, i), this._addSeat(), i.exitPoint && this._viverseApp.pcApp.on("update", this._update, this);
  }
  _addSeat() {
    const e = this._getInteractionModule();
    if (!e) return;
    const t = {
      ...this._config,
      ...this._config.exitPoint && { exitPosition: this._config.exitPoint.getPosition().clone() }
    };
    e.addSeat(this._config.name, this._entity, t);
  }
  _updateExitPoint() {
    const e = this._config.exitPoint;
    if (!e) return;
    const t = this._getInteractionModule();
    if (!t) return;
    const i = t.sitHandler;
    if (!i) return;
    const o = this._config.name, s = i.seats.get(o);
    s && s.exitPosition && s.exitPosition.copy(e.getPosition());
  }
  _update() {
    this._updateExitPoint();
  }
  destroy() {
    super.destroy(), this._getInteractionModule()?.sitHandler?.removeSeat(this._config.name);
  }
}
class Fe {
  _pcApp;
  _parentEntity;
  _entity = null;
  constructor(e, t, i, o) {
    this._pcApp = e, this._parentEntity = t;
    const s = new pc.Asset(i, "container", { url: o });
    this._pcApp.assets.add(s), s.once("load", () => {
      const n = s.resource;
      if (!n) {
        p.error("Failed to load container resource");
        return;
      }
      if (n.data.gltf.extensionsUsed.includes("EXT_mesh_gpu_instancing") || p.error("GLB Asset does not contain the EXT_mesh_gpu_instancing extension"), this._entity = n.instantiateRenderEntity?.(), !this._entity) {
        p.error("Failed to instantiate GLTF entity");
        return;
      }
      this._entity.name = `GpuInstancingRender:${i}`, this._parentEntity.addChild(this._entity);
    }), this._pcApp.assets.load(s);
  }
  destroy() {
    this._pcApp = null, this._entity && (this._parentEntity.removeChild(this._entity), this._entity.destroy());
  }
}
class te extends pc.Script {
  static scriptName = "videoAudioScript";
  video = null;
  positional = !0;
  defaultVolume = 1;
  _gainNode = null;
  _muteNode = null;
  _panner = null;
  _mutedByCall = !1;
  _mutedByDisable = !1;
  initialize() {
    this._createGainNode(), this.on("state", this._handleStateChange, this), this.on("destroy", this.destroy, this);
  }
  update() {
    this._updatePannerPosition();
  }
  destroy() {
    this._disconnectNodes();
  }
  _createGainNode() {
    const e = this.app.systems.sound?.context;
    if (!e) {
      p.warn("VideoAudioScript: AudioContext not available.");
      return;
    }
    if (!this.video) {
      p.warn("VideoAudioScript: Video element not available.");
      return;
    }
    const t = e.createMediaElementSource(this.video), i = e.createGain(), o = e.createGain();
    if (this._gainNode = i, this._muteNode = o, this.positional) {
      const s = e.createPanner();
      s.distanceModel = "linear", t.connect(i), i.connect(o), o.connect(s), s.connect(e.destination), this._panner = s;
    } else
      t.connect(i), i.connect(o), o.connect(e.destination);
    this.setVolume(this.defaultVolume), this._checkMuteState();
  }
  _updatePannerPosition() {
    if (!this._panner) return;
    const e = this.entity.getPosition();
    this._panner.positionX.value = e.x, this._panner.positionY.value = e.y, this._panner.positionZ.value = e.z;
  }
  _disconnectNodes() {
    this._gainNode?.disconnect(), this._muteNode?.disconnect(), this._panner?.disconnect(), this._gainNode = null, this._muteNode = null, this._panner = null;
  }
  _handleStateChange(e) {
    this._mutedByDisable = !e, this._checkMuteState();
  }
  _checkMuteState() {
    if (!this._muteNode) return;
    const e = this._mutedByDisable || this._mutedByCall;
    this._muteNode.gain.value = e ? 0 : 1;
  }
  setVolume(e) {
    const t = Math.max(0, Math.min(1, e));
    this.defaultVolume = t, this._gainNode && (this._gainNode.gain.value = t);
  }
  getVolume() {
    return this._gainNode?.gain.value ?? 1;
  }
  muteAudio() {
    this._mutedByCall = !0, this._checkMuteState();
  }
  unmuteAudio() {
    this._mutedByCall = !1, this._checkMuteState();
  }
}
class ie {
  _script = null;
  constructor(e, t, i) {
    e.script || e.addComponent("script"), this._script = e.script.create(te, {
      properties: {
        video: t,
        positional: i.positional,
        defaultVolume: i.defaultVolume
      }
    });
  }
  get volume() {
    return this.getVolume();
  }
  setVolume(e) {
    this._script?.setVolume(e);
  }
  getVolume() {
    return this._script?.getVolume() ?? 1;
  }
  muteAudio() {
    this._script?.muteAudio();
  }
  unmuteAudio() {
    this._script?.unmuteAudio();
  }
  destroy() {
    this._script && (this._script.destroy(), this._script = null);
  }
}
class De {
  _pcApp;
  _texture;
  _rootEntity;
  _entity;
  _video;
  _audio;
  _frameRateTimer = 0;
  _videoFrameRate = 1 / 30;
  projection;
  renderSide;
  positional;
  src = "";
  _autoPlay;
  _defaultLoop;
  _defaultMuted;
  constructor(e, t, i, o) {
    this._pcApp = e, this._rootEntity = t, this.src = i, this.projection = o?.projection || "flat", this.renderSide = o?.renderSide || "double", this.positional = o?.positional ?? !0, this._autoPlay = o?.autoPlay ?? !0, this._defaultLoop = o?.loop ?? !0, this._defaultMuted = o?.muted ?? !0, this._texture = this._createTexture(), this._video = this._createVideoDomElement(), this._entity = this._createVideoEntity(), this._rootEntity.addChild(this._entity);
    const s = o?.volume ?? 1, n = {
      positional: this.positional,
      defaultVolume: s
    };
    this._audio = new ie(this._entity, this._video, n), this._pcApp.on("update", this._update, this), t.once("destroy", this.destroy, this);
  }
  get videoElement() {
    return this._video;
  }
  get entity() {
    return this._entity;
  }
  get rootEntity() {
    return this._rootEntity;
  }
  get aspectRatio() {
    return this._getVideoAspectRatio(this._video);
  }
  get audioVolume() {
    return this._audio.getVolume();
  }
  setAudioVolume(e) {
    this._audio.setVolume(e);
  }
  muteAudio() {
    this._audio.muteAudio();
  }
  unmuteAudio() {
    this._audio.unmuteAudio();
  }
  async _attemptAutoPlay(e) {
    const t = e.paused || e.ended;
    if (!this._autoPlay || !t) return;
    const i = async () => {
      try {
        return await e.play(), !0;
      } catch (n) {
        return p.warn("VideoTexture auto-play attempt failed:", n), !1;
      }
    };
    if (await i()) return;
    const s = async () => {
      await i() && (document.removeEventListener("click", s), document.removeEventListener("keydown", s), document.removeEventListener("touchstart", s));
    };
    document.addEventListener("click", s), document.addEventListener("keydown", s), document.addEventListener("touchstart", s);
  }
  _getVideoAspectRatio(e) {
    return (e.videoWidth || 1) / (e.videoHeight || 1);
  }
  _adjustEntityScale(e) {
    if (this.projection === "flat") {
      const t = this._getVideoAspectRatio(e);
      this._entity.setLocalScale(t, 1, 1);
    }
  }
  _bindVideoEvents(e) {
    e.addEventListener(
      "loadedmetadata",
      () => {
        this._texture.resize(e.videoWidth, e.videoHeight);
      },
      { once: !0 }
    ), e.addEventListener(
      "canplaythrough",
      () => {
        this._texture.setSource(e), this._adjustEntityScale(e), this._entity.enabled = !0;
      },
      { once: !0 }
    ), e.addEventListener(
      "loadeddata",
      () => {
        e.muted = this._defaultMuted, this._attemptAutoPlay(e);
      },
      { once: !0 }
    );
  }
  _createVideoDomElement() {
    const e = document.createElement("video");
    return this._bindVideoEvents(e), e.loop = this._defaultLoop, e.playsInline = !0, e.crossOrigin = "anonymous", e.autoplay = !0, e.defaultMuted = !0, e.muted = !0, e.style.display = "block", e.style.width = "1px", e.style.height = "1px", e.style.position = "absolute", e.style.opacity = "0", e.style.zIndex = "-1000", e.style.top = "0px", e.style.pointerEvents = "none", e.src = this.src, e.load(), e;
  }
  _getCullMode() {
    switch (this.renderSide) {
      case "double":
        return pc.CULLFACE_NONE;
      case "back":
        return pc.CULLFACE_FRONT;
      case "front":
      default:
        return pc.CULLFACE_BACK;
    }
  }
  _createVideoEntity() {
    const e = new pc.Entity(`VideoTexture_${this.src}`);
    e.enabled = !1;
    const t = new pc.StandardMaterial();
    return t.useLighting = !1, t.useSkybox = !1, t.emissiveMap = this._texture, t.emissive = pc.Color.WHITE, t.cull = this._getCullMode(), t.update(), this.projection === "flat" && e.rotateLocal(90, 0, 0), e.addComponent("render", {
      type: this.projection === "spherical" ? "sphere" : "plane",
      material: t,
      castShadows: !1,
      receiveShadows: !1
    }), e;
  }
  _createTexture() {
    return new pc.Texture(this._pcApp.graphicsDevice, {
      format: pc.PIXELFORMAT_R8_G8_B8_A8,
      mipmaps: !1,
      minFilter: pc.FILTER_LINEAR,
      magFilter: pc.FILTER_LINEAR,
      addressU: pc.ADDRESS_CLAMP_TO_EDGE,
      addressV: pc.ADDRESS_CLAMP_TO_EDGE
    });
  }
  _uploadTexture(e) {
    this._frameRateTimer > this._videoFrameRate ? (this._frameRateTimer = 0, this._texture.upload()) : this._frameRateTimer += e;
  }
  _update(e) {
    this._uploadTexture(e);
  }
  destroy() {
    this._audio.destroy(), this._pcApp.off("update", this._update, this);
  }
}
class Ue extends pc.PostEffect {
  _graphicsDevice;
  _blendMap;
  name = E.BlendEffect;
  shader;
  mixRatio;
  blendMapAssetId;
  color;
  pcApp;
  constructor(e, t) {
    super(e), this._graphicsDevice = e, this.mixRatio = 0.5, this.color = new pc.Color(1, 1, 1), this.applyConfig(
      t || {
        mixRatio: this.mixRatio,
        blendMap: this.blendMap,
        blendMapAssetId: this.blendMapAssetId,
        color: this.color,
        pcApp: this.pcApp
      }
    ), this.shader = this.createShader();
  }
  get blendMap() {
    return this._blendMap;
  }
  set blendMap(e) {
    e !== this._blendMap && (this._blendMap = e, this.shader = this.createShader());
  }
  get canUseBlendMap() {
    return !!this._blendMap;
  }
  createShader() {
    const t = [
      this.canUseBlendMap ? `#define USE_BLENDMAP
` : "",
      "uniform float uMixRatio;",
      "uniform sampler2D uColorBuffer;",
      "uniform vec4 uColor;",
      "#ifdef USE_BLENDMAP",
      "uniform sampler2D uBlendMap;",
      "#endif",
      "",
      "varying vec2 vUv0;",
      "",
      "void main(void)",
      "{",
      "    vec4 texel1 = texture2D(uColorBuffer, vUv0);",
      "#ifdef USE_BLENDMAP",
      "    vec4 texel2 = texture2D(uBlendMap, vUv0);",
      "    gl_FragColor = mix(texel1, texel2, uMixRatio);",
      "#else",
      "    gl_FragColor = mix(texel1, uColor, uMixRatio);",
      "#endif",
      "}"
    ].join(`
`);
    return pc.ShaderUtils.createShader(this._graphicsDevice, {
      uniqueName: "BlendShader",
      attributes: { aPosition: pc.SEMANTIC_POSITION },
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: t
    });
  }
  render(e, t, i) {
    const s = this.device.scope;
    s.resolve("uMixRatio").setValue(this.mixRatio), s.resolve("uColorBuffer").setValue(e.colorBuffer), s.resolve("uBlendMap").setValue(this._blendMap), s.resolve("uColor").setValue(this.color.toArray()), this.drawQuad(t, this.shader, i);
  }
  applyConfig(e) {
    if (e.mixRatio !== void 0 && (this.mixRatio = pc.math.clamp(e.mixRatio, 0, 1)), e.blendMap !== void 0 && (this.blendMap = e.blendMap), e.blendMapAssetId !== void 0 && e.pcApp !== void 0) {
      this.blendMapAssetId = e.blendMapAssetId;
      const t = e.pcApp.assets.get(e.blendMapAssetId);
      t && (t?.resource ? this.blendMap = t.resource : (t.once("load", () => {
        this.blendMap = t.resource;
      }), e.pcApp.assets.load(t)));
    }
    e.color !== void 0 && (this.color = Array.isArray(e.color) ? new pc.Color(...e.color) : e.color);
  }
  clone() {
    const e = this.constructor;
    return new e(this.device, {
      mixRatio: this.mixRatio,
      blendMap: this.blendMap,
      blendMapAssetId: this.blendMapAssetId,
      color: this.color,
      pcApp: this.pcApp
    });
  }
}
const T = 15;
function D(r, e) {
  return 1 / Math.sqrt(2 * Math.PI * e) * Math.exp(-(r * r) / (2 * e * e));
}
function U(r, e, t, i, o) {
  r[0] = D(0, o), e[0] = 0, e[1] = 0;
  let s = r[0], n, c;
  for (n = 0, c = Math.floor(T / 2); n < c; n++) {
    const h = D(n + 1, o);
    r[n * 2] = h, r[n * 2 + 1] = h, s += h * 2;
    const a = n * 2 + 1.5;
    e[n * 4] = t * a, e[n * 4 + 1] = i * a, e[n * 4 + 2] = -t * a, e[n * 4 + 3] = -i * a;
  }
  for (n = 0, c = r.length; n < c; n++)
    r[n] /= s;
}
class He extends pc.PostEffect {
  name = E.BloomEffect;
  extractShader;
  blurShader;
  combineShader;
  targets;
  sampleWeights;
  sampleOffsets;
  width = 0;
  height = 0;
  bloomThreshold;
  blurAmount;
  bloomIntensity;
  constructor(e, t) {
    super(e);
    const i = {
      aPosition: pc.SEMANTIC_POSITION
    }, o = [
      "varying vec2 vUv0;",
      "",
      "uniform sampler2D uBaseTexture;",
      "uniform float uBloomThreshold;",
      "",
      "void main(void)",
      "{",
      // Look up the original image color.
      "    vec4 color = texture2D(uBaseTexture, vUv0);",
      "",
      // Adjust it to keep only values brighter than the specified threshold.
      "    gl_FragColor = clamp((color - uBloomThreshold) / (1.0 - uBloomThreshold), 0.0, 1.0);",
      "}"
    ].join(`
`), s = [
      `#define SAMPLE_COUNT ${T}`,
      "",
      "varying vec2 vUv0;",
      "",
      "uniform sampler2D uBloomTexture;",
      `uniform vec2 uBlurOffsets[${T}];`,
      `uniform float uBlurWeights[${T}];`,
      "",
      "void main(void)",
      "{",
      "    vec4 color = vec4(0.0);",
      // Combine a number of weighted image filter taps.
      "    for (int i = 0; i < SAMPLE_COUNT; i++)",
      "    {",
      "        color += texture2D(uBloomTexture, vUv0 + uBlurOffsets[i]) * uBlurWeights[i];",
      "    }",
      "",
      "    gl_FragColor = color;",
      "}"
    ].join(`
`), n = [
      "varying vec2 vUv0;",
      "",
      "uniform float uBloomEffectIntensity;",
      "uniform sampler2D uBaseTexture;",
      "uniform sampler2D uBloomTexture;",
      "",
      "void main(void)",
      "{",
      // Look up the bloom and original base image colors.
      "    vec4 bloom = texture2D(uBloomTexture, vUv0) * uBloomEffectIntensity;",
      "    vec4 base = texture2D(uBaseTexture, vUv0);",
      "",
      // Darken down the base image in areas where there is a lot of bloom,
      // to prevent things looking excessively burned-out.
      "    base *= (1.0 - clamp(bloom, 0.0, 1.0));",
      "",
      // Combine the two images.
      "    gl_FragColor = base + bloom;",
      "}"
    ].join(`
`);
    this.extractShader = pc.ShaderUtils.createShader(e, {
      uniqueName: "BloomExtractShader",
      attributes: i,
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: o
    }), this.blurShader = pc.ShaderUtils.createShader(e, {
      uniqueName: "BloomBlurShader",
      attributes: i,
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: s
    }), this.combineShader = pc.ShaderUtils.createShader(e, {
      uniqueName: "BloomCombineShader",
      attributes: i,
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: n
    }), this.targets = [], this.bloomThreshold = 0.25, this.blurAmount = 4, this.bloomIntensity = 1.25, this.sampleWeights = new Float32Array(T), this.sampleOffsets = new Float32Array(T * 2), this.applyConfig(
      t || {
        bloomThreshold: this.bloomThreshold,
        blurAmount: this.blurAmount,
        bloomIntensity: this.bloomIntensity
      }
    );
  }
  render(e, t, i) {
    this._resize(e);
    const s = this.device.scope;
    s.resolve("uBloomThreshold").setValue(this.bloomThreshold), s.resolve("uBaseTexture").setValue(e.colorBuffer), this.drawQuad(this.targets[0], this.extractShader), U(
      this.sampleWeights,
      this.sampleOffsets,
      1 / this.targets[1].width,
      0,
      this.blurAmount
    ), s.resolve("uBlurWeights[0]").setValue(this.sampleWeights), s.resolve("uBlurOffsets[0]").setValue(this.sampleOffsets), s.resolve("uBloomTexture").setValue(this.targets[0].colorBuffer), this.drawQuad(this.targets[1], this.blurShader), U(
      this.sampleWeights,
      this.sampleOffsets,
      0,
      1 / this.targets[0].height,
      this.blurAmount
    ), s.resolve("uBlurWeights[0]").setValue(this.sampleWeights), s.resolve("uBlurOffsets[0]").setValue(this.sampleOffsets), s.resolve("uBloomTexture").setValue(this.targets[1].colorBuffer), this.drawQuad(this.targets[0], this.blurShader), s.resolve("uBloomEffectIntensity").setValue(this.bloomIntensity), s.resolve("uBloomTexture").setValue(this.targets[0].colorBuffer), s.resolve("uBaseTexture").setValue(e.colorBuffer), this.drawQuad(t, this.combineShader, i);
  }
  _destroy() {
    if (this.targets) {
      let e;
      for (e = 0; e < this.targets.length; e++)
        this.targets[e].destroyTextureBuffers(), this.targets[e].destroy();
    }
    this.targets.length = 0;
  }
  _resize(e) {
    const t = e.colorBuffer.width, i = e.colorBuffer.height;
    if (t === this.width && i === this.height)
      return;
    this.width = t, this.height = i, this._destroy();
    let o;
    for (o = 0; o < 2; o++) {
      const s = new pc.Texture(this.device, {
        name: `Bloom Texture${o}`,
        format: pc.PIXELFORMAT_RGBA8,
        width: t >> 1,
        height: i >> 1,
        mipmaps: !1
      });
      s.minFilter = pc.FILTER_LINEAR, s.magFilter = pc.FILTER_LINEAR, s.addressU = pc.ADDRESS_CLAMP_TO_EDGE, s.addressV = pc.ADDRESS_CLAMP_TO_EDGE, s.name = `pe-bloom-${o}`;
      const n = new pc.RenderTarget({
        name: `Bloom Render Target ${o}`,
        colorBuffer: s,
        depth: !1
      });
      this.targets.push(n);
    }
  }
  applyConfig(e) {
    e.bloomThreshold !== void 0 && (this.bloomThreshold = pc.math.clamp(e.bloomThreshold, 0, 1)), e.blurAmount !== void 0 && (this.blurAmount = Math.max(e.blurAmount, 1)), e.bloomIntensity !== void 0 && (this.bloomIntensity = Math.max(e.bloomIntensity, 0));
  }
  clone() {
    const e = this.constructor;
    return new e(this.device, {
      bloomThreshold: this.bloomThreshold,
      blurAmount: this.blurAmount,
      bloomIntensity: this.bloomIntensity
    });
  }
}
function H(r) {
  return Math.sign(r) * (r * r);
}
class Ge extends pc.PostEffect {
  name = E.BrightnessContrastEffect;
  shader;
  brightness;
  contrast;
  constructor(e, t) {
    super(e);
    const i = [
      "uniform sampler2D uColorBuffer;",
      "uniform float uBrightness;",
      "uniform float uContrast;",
      "",
      "varying vec2 vUv0;",
      "",
      "void main() {",
      "    gl_FragColor = texture2D( uColorBuffer, vUv0 );",
      "    gl_FragColor.rgb += uBrightness;",
      "",
      "    if (uContrast > 0.0) {",
      "        gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) / (1.0 - uContrast) + 0.5;",
      "    } else {",
      "        gl_FragColor.rgb = (gl_FragColor.rgb - 0.5) * (1.0 + uContrast) + 0.5;",
      "    }",
      "}"
    ].join(`
`);
    this.shader = pc.ShaderUtils.createShader(e, {
      uniqueName: "BrightnessContrastShader",
      attributes: { aPosition: pc.SEMANTIC_POSITION },
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: i
    }), this.brightness = 0, this.contrast = 0, this.applyConfig(
      t || {
        brightness: this.brightness,
        contrast: this.contrast
      }
    );
  }
  render(e, t, i) {
    const s = this.device.scope;
    s.resolve("uBrightness").setValue(H(this.brightness)), s.resolve("uContrast").setValue(H(this.contrast)), s.resolve("uColorBuffer").setValue(e.colorBuffer), this.drawQuad(t, this.shader, i);
  }
  applyConfig(e) {
    e.brightness !== void 0 && (this.brightness = pc.math.clamp(e.brightness, -1, 1)), e.contrast !== void 0 && (this.contrast = pc.math.clamp(e.contrast, -1, 1));
  }
  clone() {
    const e = this.constructor;
    return new e(this.device, {
      brightness: this.brightness,
      contrast: this.contrast
    });
  }
}
class We extends pc.PostEffect {
  name = E.EdgeDetectEffect;
  shader;
  resolution;
  intensity;
  color;
  constructor(e, t) {
    super(e);
    const i = [
      "uniform sampler2D uColorBuffer;",
      "varying vec2 vUv0;",
      "uniform vec2 uResolution;",
      "uniform float uIntensity;",
      "uniform vec4 uColor;",
      "",
      "mat3 G[2];",
      "",
      "const mat3 g0 = mat3( 1.0, 2.0, 1.0, 0.0, 0.0, 0.0, -1.0, -2.0, -1.0 );",
      "const mat3 g1 = mat3( 1.0, 0.0, -1.0, 2.0, 0.0, -2.0, 1.0, 0.0, -1.0 );",
      "",
      "void main(void)",
      "{",
      "    mat3 I;",
      "    float cnv[2];",
      "    vec3 sample0;",
      "",
      "    G[0] = g0;",
      "    G[1] = g1;",
      "",
      /* Fetch the 3x3 neighbourhood and use the RGB vector's length as intensity value */
      "    for (float i = 0.0; i < 3.0; i++)",
      "    {",
      "        for (float j = 0.0; j < 3.0; j++)",
      "        {",
      "            sample0 = texture2D(uColorBuffer, vUv0 + uResolution * vec2(i - 1.0, j - 1.0)).rgb;",
      "            I[int(i)][int(j)] = length(sample0);",
      "         }",
      "    }",
      "",
      /* Calculate the convolution values for all the masks */
      "    for (int i=0; i<2; i++)",
      "    {",
      "        float dp3 = dot(G[i][0], I[0]) + dot(G[i][1], I[1]) + dot(G[i][2], I[2]);",
      "        cnv[i] = dp3 * dp3; ",
      "    }",
      "",
      "    gl_FragColor = uIntensity * uColor * vec4(sqrt(cnv[0]*cnv[0]+cnv[1]*cnv[1]));",
      "}"
    ].join(`
`);
    this.shader = pc.ShaderUtils.createShader(e, {
      uniqueName: "EdgeDetectShader",
      attributes: { aPosition: pc.SEMANTIC_POSITION },
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: i
    }), this.resolution = new Float32Array(2), this.intensity = 1, this.color = new pc.Color(0.5, 0.5, 0.5), this.applyConfig(
      t || {
        intensity: this.intensity,
        color: this.color
      }
    );
  }
  render(e, t, i) {
    const s = this.device.scope;
    this.resolution[0] = 1 / e.width, this.resolution[1] = 1 / e.height, s.resolve("uResolution").setValue(this.resolution), s.resolve("uColorBuffer").setValue(e.colorBuffer), s.resolve("uColor").setValue(this.color.toArray()), s.resolve("uIntensity").setValue(this.intensity), this.drawQuad(t, this.shader, i);
  }
  applyConfig(e) {
    e.intensity !== void 0 && (this.intensity = pc.math.clamp(e.intensity, 0, 2)), e.color !== void 0 && (this.color = Array.isArray(e.color) ? new pc.Color(...e.color) : e.color);
  }
  clone() {
    const e = this.constructor;
    return new e(this.device, {
      intensity: this.intensity,
      color: this.color
    });
  }
}
class qe extends pc.PostEffect {
  name = E.FxaaEffect;
  fxaaShader;
  resolution;
  constructor(e) {
    super(e);
    const t = [
      "uniform sampler2D uColorBuffer;",
      "uniform vec2 uResolution;",
      "",
      "#define FXAA_REDUCE_MIN   (1.0/128.0)",
      "#define FXAA_REDUCE_MUL   (1.0/8.0)",
      "#define FXAA_SPAN_MAX     8.0",
      "",
      "void main()",
      "{",
      "    vec3 rgbNW = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( -1.0, -1.0 ) ) * uResolution ).xyz;",
      "    vec3 rgbNE = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( 1.0, -1.0 ) ) * uResolution ).xyz;",
      "    vec3 rgbSW = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( -1.0, 1.0 ) ) * uResolution ).xyz;",
      "    vec3 rgbSE = texture2D( uColorBuffer, ( gl_FragCoord.xy + vec2( 1.0, 1.0 ) ) * uResolution ).xyz;",
      "    vec4 rgbaM  = texture2D( uColorBuffer,  gl_FragCoord.xy  * uResolution );",
      "    vec3 rgbM  = rgbaM.xyz;",
      "    float opacity  = rgbaM.w;",
      "",
      "    vec3 luma = vec3( 0.299, 0.587, 0.114 );",
      "",
      "    float lumaNW = dot( rgbNW, luma );",
      "    float lumaNE = dot( rgbNE, luma );",
      "    float lumaSW = dot( rgbSW, luma );",
      "    float lumaSE = dot( rgbSE, luma );",
      "    float lumaM  = dot( rgbM,  luma );",
      "    float lumaMin = min( lumaM, min( min( lumaNW, lumaNE ), min( lumaSW, lumaSE ) ) );",
      "    float lumaMax = max( lumaM, max( max( lumaNW, lumaNE) , max( lumaSW, lumaSE ) ) );",
      "",
      "    vec2 dir;",
      "    dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));",
      "    dir.y =  ((lumaNW + lumaSW) - (lumaNE + lumaSE));",
      "",
      "    float dirReduce = max( ( lumaNW + lumaNE + lumaSW + lumaSE ) * ( 0.25 * FXAA_REDUCE_MUL ), FXAA_REDUCE_MIN );",
      "",
      "    float rcpDirMin = 1.0 / ( min( abs( dir.x ), abs( dir.y ) ) + dirReduce );",
      "    dir = min( vec2( FXAA_SPAN_MAX, FXAA_SPAN_MAX), max( vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX), dir * rcpDirMin)) * uResolution;",
      "",
      "    vec3 rgbA = 0.5 * (",
      "        texture2D( uColorBuffer, gl_FragCoord.xy  * uResolution + dir * ( 1.0 / 3.0 - 0.5 ) ).xyz +",
      "        texture2D( uColorBuffer, gl_FragCoord.xy  * uResolution + dir * ( 2.0 / 3.0 - 0.5 ) ).xyz );",
      "",
      "    vec3 rgbB = rgbA * 0.5 + 0.25 * (",
      "        texture2D( uColorBuffer, gl_FragCoord.xy  * uResolution + dir * -0.5 ).xyz +",
      "        texture2D( uColorBuffer, gl_FragCoord.xy  * uResolution + dir * 0.5 ).xyz );",
      "",
      "    float lumaB = dot( rgbB, luma );",
      "",
      "    if ( ( lumaB < lumaMin ) || ( lumaB > lumaMax ) )",
      "    {",
      "        gl_FragColor = vec4( rgbA, opacity );",
      "    }",
      "    else",
      "    {",
      "        gl_FragColor = vec4( rgbB, opacity );",
      "    }",
      "}"
    ].join(`
`);
    this.fxaaShader = pc.ShaderUtils.createShader(e, {
      uniqueName: "FxaaShader",
      attributes: { aPosition: pc.SEMANTIC_POSITION },
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: t
    }), this.resolution = new Float32Array(2);
  }
  render(e, t, i) {
    const s = this.device.scope;
    this.resolution[0] = 1 / e.width, this.resolution[1] = 1 / e.height, s.resolve("uResolution").setValue(this.resolution), s.resolve("uColorBuffer").setValue(e.colorBuffer), this.drawQuad(t, this.fxaaShader, i);
  }
  clone() {
    const e = this.constructor;
    return new e(this.device);
  }
}
class ze extends pc.PostEffect {
  name = E.HorizontalTiltShiftEffect;
  shader;
  focus;
  constructor(e, t) {
    super(e);
    const i = [
      "uniform sampler2D uColorBuffer;",
      "uniform float uH;",
      "uniform float uR;",
      "",
      "varying vec2 vUv0;",
      "",
      "void main() {",
      "    vec4 sum = vec4( 0.0 );",
      "    float hh = uH * abs( uR - vUv0.x );",
      "",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x - 4.0 * hh, vUv0.y ) ) * 0.051;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x - 3.0 * hh, vUv0.y ) ) * 0.0918;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x - 2.0 * hh, vUv0.y ) ) * 0.12245;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x - 1.0 * hh, vUv0.y ) ) * 0.1531;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y ) ) * 0.1633;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x + 1.0 * hh, vUv0.y ) ) * 0.1531;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x + 2.0 * hh, vUv0.y ) ) * 0.12245;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x + 3.0 * hh, vUv0.y ) ) * 0.0918;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x + 4.0 * hh, vUv0.y ) ) * 0.051;",
      "",
      "    gl_FragColor = sum;",
      "}"
    ].join(`
`);
    this.shader = pc.ShaderUtils.createShader(e, {
      uniqueName: "HorizontalTiltShiftShader",
      attributes: { aPosition: pc.SEMANTIC_POSITION },
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: i
    }), this.focus = 0.35, this.applyConfig(
      t || {
        focus: this.focus
      }
    );
  }
  render(e, t, i) {
    const s = this.device.scope;
    s.resolve("uH").setValue(1 / e.width), s.resolve("uR").setValue(this.focus), s.resolve("uColorBuffer").setValue(e.colorBuffer), this.drawQuad(t, this.shader, i);
  }
  applyConfig(e) {
    e.focus !== void 0 && (this.focus = pc.math.clamp(e.focus, 0, 1));
  }
  clone() {
    const e = this.constructor;
    return new e(this.device, {
      focus: this.focus
    });
  }
}
class je extends pc.PostEffect {
  name = E.HueSaturationEffect;
  shader;
  hue;
  saturation;
  constructor(e, t) {
    super(e);
    const i = [
      "uniform sampler2D uColorBuffer;",
      "uniform float uHue;",
      "uniform float uSaturation;",
      "",
      "varying vec2 vUv0;",
      "",
      "void main() {",
      "    gl_FragColor = texture2D( uColorBuffer, vUv0 );",
      "",
      // uHue
      "    float angle = uHue * 3.14159265;",
      "    float s = sin(angle), c = cos(angle);",
      "    vec3 weights = (vec3(2.0 * c, -sqrt(3.0) * s - c, sqrt(3.0) * s - c) + 1.0) / 3.0;",
      "    float len = length(gl_FragColor.rgb);",
      "    gl_FragColor.rgb = vec3(",
      "        dot(gl_FragColor.rgb, weights.xyz),",
      "        dot(gl_FragColor.rgb, weights.zxy),",
      "        dot(gl_FragColor.rgb, weights.yzx)",
      "    );",
      "",
      // uSaturation
      "    float average = (gl_FragColor.r + gl_FragColor.g + gl_FragColor.b) / 3.0;",
      "    if (uSaturation > 0.0) {",
      "        gl_FragColor.rgb += (average - gl_FragColor.rgb) * (1.0 - 1.0 / (1.001 - uSaturation));",
      "    } else {",
      "        gl_FragColor.rgb += (average - gl_FragColor.rgb) * (-uSaturation);",
      "    }",
      "}"
    ].join(`
`);
    this.shader = pc.ShaderUtils.createShader(e, {
      uniqueName: "HueSaturationShader",
      attributes: { aPosition: pc.SEMANTIC_POSITION },
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: i
    }), this.hue = 0, this.saturation = 0, this.applyConfig(
      t || {
        hue: this.hue,
        saturation: this.saturation
      }
    );
  }
  render(e, t, i) {
    const s = this.device.scope;
    s.resolve("uHue").setValue(this.hue), s.resolve("uSaturation").setValue(this.saturation), s.resolve("uColorBuffer").setValue(e.colorBuffer), this.drawQuad(t, this.shader, i);
  }
  applyConfig(e) {
    e.hue !== void 0 && (this.hue = pc.math.clamp(e.hue, -1, 1)), e.saturation !== void 0 && (this.saturation = pc.math.clamp(e.saturation, -1, 1));
  }
  clone() {
    const e = this.constructor;
    return new e(this.device, {
      hue: this.hue,
      saturation: this.saturation
    });
  }
}
class Ze extends pc.PostEffect {
  name = E.SSAOEffect;
  ssaoShader;
  blurShader;
  outputShader;
  width = 0;
  height = 0;
  target = null;
  blurTarget = null;
  cameraEntity = null;
  radius;
  brightness;
  samples;
  downscale;
  constructor(e, t) {
    super(e), this.needsDepthBuffer = !0;
    const i = [
      pc.ShaderChunks.get(e, pc.SHADERLANGUAGE_GLSL).get("screenDepthPS"),
      "",
      "varying vec2 vUv0;",
      "",
      "//uniform sampler2D uColorBuffer;",
      "uniform vec4 uResolution;",
      "",
      "uniform float uAspect;",
      "",
      "#define saturate(x) clamp(x,0.0,1.0)",
      "",
      "// Largely based on 'Dominant Light Shadowing'",
      "// 'Lighting Technology of The Last of Us Part II' by Hawar Doghramachi, Naughty Dog, LLC",
      "",
      "const float kSSCTLog2LodRate = 3.0;",
      "",
      "highp float getWFromProjectionMatrix(const mat4 p, const vec3 v) {",
      "    // this essentially returns (p * vec4(v, 1.0)).w, but we make some assumptions",
      "    // this assumes a perspective projection",
      "    return -v.z;",
      "    // this assumes a perspective or ortho projection",
      "    // return p[2][3] * v.z + p[3][3];",
      "}",
      "",
      "highp float getViewSpaceZFromW(const mat4 p, const float w) {",
      "    // this assumes a perspective projection",
      "    return -w;",
      "    // this assumes a perspective or ortho projection",
      "   // return (w - p[3][3]) / p[2][3];",
      "}",
      "",
      "",
      "const float kLog2LodRate = 3.0;",
      "",
      "vec2 sq(const vec2 a) {",
      "    return a * a;",
      "}",
      "",
      "uniform float uInvFarPlane;",
      "",
      "vec2 pack(highp float depth) {",
      "// we need 16-bits of precision",
      "    highp float z = clamp(depth * uInvFarPlane, 0.0, 1.0);",
      "    highp float t = floor(256.0 * z);",
      "    mediump float hi = t * (1.0 / 256.0);   // we only need 8-bits of precision",
      "    mediump float lo = (256.0 * z) - t;     // we only need 8-bits of precision",
      "    return vec2(hi, lo);",
      "}",
      "",
      "// random number between 0 and 1, using interleaved gradient noise",
      "float random(const highp vec2 w) {",
      "    const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);",
      "    return fract(m.z * fract(dot(w, m.xy)));",
      "}",
      "",
      "// returns the frag coord in the GL convention with (0, 0) at the bottom-left",
      "highp vec2 getFragCoord() {",
      "    return gl_FragCoord.xy;",
      "}",
      "",
      "highp vec3 computeViewSpacePositionFromDepth(highp vec2 uv, highp float linearDepth) {",
      "    return vec3((0.5 - uv) * vec2(uAspect, 1.0) * linearDepth, linearDepth);",
      "}",
      "",
      "highp vec3 faceNormal(highp vec3 dpdx, highp vec3 dpdy) {",
      "    return normalize(cross(dpdx, dpdy));",
      "}",
      "",
      "// Compute normals using derivatives, which essentially results in half-resolution normals",
      "// this creates arifacts around geometry edges.",
      "// Note: when using the spirv optimizer, this results in much slower execution time because",
      "//       this whole expression is inlined in the AO loop below.",
      "highp vec3 computeViewSpaceNormal(const highp vec3 position) {",
      "    return faceNormal(dFdx(position), dFdy(position));",
      "}",
      "",
      "// Compute normals directly from the depth texture, resulting in full resolution normals",
      "// Note: This is actually as cheap as using derivatives because the texture fetches",
      "//       are essentially equivalent to textureGather (which we don't have on ES3.0),",
      "//       and this is executed just once.",
      "highp vec3 computeViewSpaceNormal(const highp vec3 position, const highp vec2 uv) {",
      "    highp vec2 uvdx = uv + vec2(uResolution.z, 0.0);",
      "    highp vec2 uvdy = uv + vec2(0.0, uResolution.w);",
      "    highp vec3 px = computeViewSpacePositionFromDepth(uvdx, -getLinearScreenDepth(uvdx));",
      "    highp vec3 py = computeViewSpacePositionFromDepth(uvdy, -getLinearScreenDepth(uvdy));",
      "    highp vec3 dpdx = px - position;",
      "    highp vec3 dpdy = py - position;",
      "    return faceNormal(dpdx, dpdy);",
      "}",
      "",
      "// Ambient Occlusion, largely inspired from:",
      "// 'The Alchemy Screen-Space Ambient Obscurance Algorithm' by Morgan McGuire",
      "// 'Scalable Ambient Obscurance' by Morgan McGuire, Michael Mara and David Luebke",
      "",
      "uniform vec2 uSampleCount;",
      "uniform float uSpiralTurns;",
      "",
      "#define PI (3.14159)",
      "",
      "vec3 tapLocation(float i, const float noise) {",
      "    float offset = ((2.0 * PI) * 2.4) * noise;",
      "    float angle = ((i * uSampleCount.y) * uSpiralTurns) * (2.0 * PI) + offset;",
      "    float radius = (i + noise + 0.5) * uSampleCount.y;",
      "    return vec3(cos(angle), sin(angle), radius * radius);",
      "}",
      "",
      "highp vec2 startPosition(const float noise) {",
      "    float angle = ((2.0 * PI) * 2.4) * noise;",
      "    return vec2(cos(angle), sin(angle));",
      "}",
      "",
      "uniform vec2 uAngleIncCosSin;",
      "",
      "highp mat2 tapAngleStep() {",
      "    highp vec2 t = uAngleIncCosSin;",
      "    return mat2(t.x, t.y, -t.y, t.x);",
      "}",
      "",
      "vec3 tapLocationFast(float i, vec2 p, const float noise) {",
      "    float radius = (i + noise + 0.5) * uSampleCount.y;",
      "    return vec3(p, radius * radius);",
      "}",
      "",
      "uniform float uMaxLevel;",
      "uniform float uInvRadiusSquared;",
      "uniform float uMinHorizonAngleSineSquared;",
      "uniform float uBias;",
      "uniform float uPeak2;",
      "",
      "void computeAmbientOcclusionSAO(inout float occlusion, float i, float ssDiskRadius,",
      "        const highp vec2 uv,  const highp vec3 origin, const vec3 normal,",
      "        const vec2 tapPosition, const float noise) {",
      "",
      "    vec3 tap = tapLocationFast(i, tapPosition, noise);",
      "",
      "    float ssRadius = max(1.0, tap.z * ssDiskRadius);",
      // at least 1 pixel screen-space radius
      "",
      "    vec2 uvSamplePos = uv + vec2(ssRadius * tap.xy) * uResolution.zw;",
      "",
      "    float level = clamp(floor(log2(ssRadius)) - kLog2LodRate, 0.0, float(uMaxLevel));",
      "    highp float occlusionDepth = -getLinearScreenDepth(uvSamplePos);",
      "    highp vec3 p = computeViewSpacePositionFromDepth(uvSamplePos, occlusionDepth);",
      "",
      "    // now we have the sample, compute AO",
      "    vec3 v = p - origin;        // sample vector",
      "    float vv = dot(v, v);       // squared distance",
      "    float vn = dot(v, normal);  // distance * cos(v, normal)",
      "",
      "    // discard samples that are outside of the radius, preventing distant geometry to",
      "    // cast shadows -- there are many functions that work and choosing one is an artistic",
      "    // decision.",
      "    float w = max(0.0, 1.0 - vv * uInvRadiusSquared);",
      "    w = w*w;",
      "",
      "    // discard samples that are too close to the horizon to reduce shadows cast by geometry",
      "    // not sufficiently tessellated. The goal is to discard samples that form an angle 'beta'",
      "    // smaller than 'epsilon' with the horizon. We already have dot(v,n) which is equal to the",
      "    // sin(beta) * |v|. So the test simplifies to vn^2 < vv * sin(epsilon)^2.",
      "    w *= step(vv * uMinHorizonAngleSineSquared, vn * vn);",
      "",
      "    occlusion += w * max(0.0, vn + origin.z * uBias) / (vv + uPeak2);",
      "}",
      "",
      "uniform float uProjectionScaleRadius;",
      "uniform float uIntensity;",
      "",
      "float scalableAmbientObscurance(highp vec2 uv, highp vec3 origin, vec3 normal) {",
      "    float noise = random(getFragCoord());",
      "    highp vec2 tapPosition = startPosition(noise);",
      "    highp mat2 angleStep = tapAngleStep();",
      "",
      "    // Choose the screen-space sample radius",
      "    // proportional to the projected area of the sphere",
      "    float ssDiskRadius = -(uProjectionScaleRadius / origin.z);",
      "",
      "    float occlusion = 0.0;",
      "    for (float i = 0.0; i < uSampleCount.x; i += 1.0) {",
      "        computeAmbientOcclusionSAO(occlusion, i, ssDiskRadius, uv, origin, normal, tapPosition, noise);",
      "        tapPosition = angleStep * tapPosition;",
      "    }",
      "    return sqrt(occlusion * uIntensity);",
      "}",
      "",
      "uniform float uPower;",
      "",
      "void main() {",
      "    highp vec2 uv = vUv0; //variable_vertex.xy; // interpolated to pixel center",
      "",
      "    highp float depth = -getLinearScreenDepth(vUv0);",
      "    highp vec3 origin = computeViewSpacePositionFromDepth(uv, depth);",
      "    vec3 normal = computeViewSpaceNormal(origin, uv);",
      "",
      "    float occlusion = 0.0;",
      "",
      "    if (uIntensity > 0.0) {",
      "        occlusion = scalableAmbientObscurance(uv, origin, normal);",
      "    }",
      "",
      "    // occlusion to visibility",
      "    float aoVisibility = pow(saturate(1.0 - occlusion), uPower);",
      "",
      "    vec4 inCol = vec4(1.0, 1.0, 1.0, 1.0); //texture2D( uColorBuffer,  uv );",
      "",
      "    gl_FragColor.r = aoVisibility; //postProcess.color.rgb = vec3(aoVisibility, pack(origin.z));",
      "}",
      "",
      "void main_old()",
      "{",
      "    vec2 aspectCorrect = vec2( 1.0, uAspect );",
      "",
      "    float depth = getLinearScreenDepth(vUv0);",
      "    gl_FragColor.r = fract(floor(depth*256.0*256.0)),fract(floor(depth*256.0)),fract(depth);",
      "}"
    ].join(`
`), o = [
      pc.ShaderChunks.get(e, pc.SHADERLANGUAGE_GLSL).get("screenDepthPS"),
      "",
      "varying vec2 vUv0;",
      "",
      "uniform sampler2D uSSAOBuffer;",
      "uniform vec4 uResolution;",
      "",
      "uniform float uAspect;",
      "",
      "uniform int uBilatSampleCount;",
      "uniform float uFarPlaneOverEdgeDistance;",
      "uniform float uBrightness;",
      "",
      "float random(const highp vec2 w) {",
      "    const vec3 m = vec3(0.06711056, 0.00583715, 52.9829189);",
      "    return fract(m.z * fract(dot(w, m.xy)));",
      "}",
      "",
      "float bilateralWeight(in float depth, in float sampleDepth) {",
      "    float diff = (sampleDepth - depth) * uFarPlaneOverEdgeDistance;",
      "    return max(0.0, 1.0 - diff * diff);",
      "}",
      "",
      "void tap(inout float sum, inout float totalWeight, float weight, float depth, vec2 position) {",
      "    // ambient occlusion sample",
      "    float ssao = texture2D( uSSAOBuffer, position ).r;",
      "    float tdepth = -getLinearScreenDepth( position );",
      "",
      "    // bilateral sample",
      "    float bilateral = bilateralWeight(depth, tdepth);",
      "    bilateral *= weight;",
      "    sum += ssao * bilateral;",
      "    totalWeight += bilateral;",
      "}",
      "",
      "void main() {",
      "    highp vec2 uv = vUv0; // variable_vertex.xy; // interpolated at pixel's center",
      "",
      "    // we handle the center pixel separately because it doesn't participate in bilateral filtering",
      "    float depth = -getLinearScreenDepth(vUv0); // unpack(data.gb);",
      "    float totalWeight = 0.0; // float(uBilatSampleCount*2+1)*float(uBilatSampleCount*2+1);",
      "    float ssao = texture2D( uSSAOBuffer, vUv0 ).r;",
      "    float sum = ssao * totalWeight;",
      "",
      "    for (int x = -uBilatSampleCount; x <= uBilatSampleCount; x++) {",
      "       for (int y = -uBilatSampleCount; y < uBilatSampleCount; y++) {",
      "           float weight = 1.0;",
      "           vec2 offset = vec2(x,y)*uResolution.zw;",
      "           tap(sum, totalWeight, weight, depth, uv + offset);",
      "       }",
      "    }",
      "",
      "    float ao = sum / totalWeight;",
      "",
      "    // simple dithering helps a lot (assumes 8 bits target)",
      "    // this is most useful with high quality/large blurs",
      "    // ao += ((random(gl_FragCoord.xy) - 0.5) / 255.0);",
      "",
      "    ao = mix(ao, 1.0, uBrightness);",
      "    gl_FragColor.a = ao;",
      "}"
    ].join(`
`), s = [
      "varying vec2 vUv0;",
      "uniform sampler2D uColorBuffer;",
      "uniform sampler2D uSSAOBuffer;",
      "",
      "void main(void)",
      "{",
      "    vec4 inCol = texture2D( uColorBuffer, vUv0 );",
      "    float ssao = texture2D( uSSAOBuffer, vUv0 ).a;",
      "    gl_FragColor.rgb = inCol.rgb * ssao;",
      "    gl_FragColor.a = inCol.a;",
      "}"
    ].join(`
`), n = {
      aPosition: pc.SEMANTIC_POSITION
    };
    this.ssaoShader = pc.ShaderUtils.createShader(e, {
      uniqueName: "SsaoShader",
      attributes: n,
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: i
    }), this.blurShader = pc.ShaderUtils.createShader(e, {
      uniqueName: "SsaoBlurShader",
      attributes: n,
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: o
    }), this.outputShader = pc.ShaderUtils.createShader(e, {
      uniqueName: "SsaoOutputShader",
      attributes: n,
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: s
    }), this.radius = 4, this.brightness = 0, this.samples = 20, this.downscale = 1, this.applyConfig(
      t || {
        cameraEntity: this.cameraEntity,
        radius: this.radius,
        brightness: this.brightness,
        samples: this.samples,
        downscale: this.downscale
      }
    );
  }
  render(e, t, i) {
    this._resize(e);
    const o = this.device, s = o.scope, n = this.samples, c = 10, h = 1 / (n - 0.5) * c * 2 * 3.141, a = this.radius, d = 1e-3, l = 0.1 * a, v = l * 2 * 3.141 * 0.125, f = 0.5 * o.height, _ = this.cameraEntity?.camera ? this.cameraEntity?.camera.farClip : 1e3;
    s.resolve("uAspect").setValue(this.width / this.height), s.resolve("uResolution").setValue([this.width, this.height, 1 / this.width, 1 / this.height]), s.resolve("uBrightness").setValue(this.brightness), s.resolve("uInvFarPlane").setValue(1 / _), s.resolve("uSampleCount").setValue([n, 1 / n]), s.resolve("uSpiralTurns").setValue(c), s.resolve("uAngleIncCosSin").setValue([Math.cos(h), Math.sin(h)]), s.resolve("uMaxLevel").setValue(0), s.resolve("uInvRadiusSquared").setValue(1 / (a * a)), s.resolve("uMinHorizonAngleSineSquared").setValue(0), s.resolve("uBias").setValue(d), s.resolve("uPeak2").setValue(l * l), s.resolve("uIntensity").setValue(v), s.resolve("uPower").setValue(1), s.resolve("uProjectionScaleRadius").setValue(f * a), this.drawQuad(this.target, this.ssaoShader, i), s.resolve("uSSAOBuffer").setValue(this.target?.colorBuffer), s.resolve("uFarPlaneOverEdgeDistance").setValue(1), s.resolve("uBilatSampleCount").setValue(4), this.drawQuad(this.blurTarget, this.blurShader, i), s.resolve("uSSAOBuffer").setValue(this.blurTarget?.colorBuffer), s.resolve("uColorBuffer").setValue(e.colorBuffer), this.drawQuad(t, this.outputShader, i);
  }
  _resize(e) {
    const t = Math.ceil(e.colorBuffer.width / this.downscale), i = Math.ceil(e.colorBuffer.height / this.downscale);
    if (t === this.width && i === this.height)
      return;
    this.width = t, this.height = i, this._destroy();
    const o = new pc.Texture(this.device, {
      format: pc.PIXELFORMAT_RGBA8,
      minFilter: pc.FILTER_LINEAR,
      magFilter: pc.FILTER_LINEAR,
      addressU: pc.ADDRESS_CLAMP_TO_EDGE,
      addressV: pc.ADDRESS_CLAMP_TO_EDGE,
      width: this.width,
      height: this.height,
      mipmaps: !1
    });
    o.name = "SSAO Result", this.target = new pc.RenderTarget({
      name: "SSAO Result Render Target",
      colorBuffer: o,
      depth: !1
    });
    const s = new pc.Texture(this.device, {
      format: pc.PIXELFORMAT_RGBA8,
      minFilter: pc.FILTER_LINEAR,
      magFilter: pc.FILTER_LINEAR,
      addressU: pc.ADDRESS_CLAMP_TO_EDGE,
      addressV: pc.ADDRESS_CLAMP_TO_EDGE,
      width: this.width,
      height: this.height,
      mipmaps: !1
    });
    s.name = "SSAO Blur", this.blurTarget = new pc.RenderTarget({
      name: "SSAO Blur Render Target",
      colorBuffer: s,
      depth: !1
    });
  }
  _destroy() {
    this.target && (this.target.destroyTextureBuffers(), this.target.destroy(), this.target = null), this.blurTarget && (this.blurTarget.destroyTextureBuffers(), this.blurTarget.destroy(), this.blurTarget = null);
  }
  applyConfig(e) {
    e.cameraEntity !== void 0 && (this.cameraEntity = e.cameraEntity), e.radius !== void 0 && (this.radius = pc.math.clamp(e.radius, 0, 20)), e.brightness !== void 0 && (this.brightness = pc.math.clamp(e.brightness, 0, 1)), e.samples !== void 0 && (this.samples = pc.math.clamp(e.samples, 1, 256)), e.downscale !== void 0 && (this.downscale = pc.math.clamp(e.downscale, 1, 4));
  }
  clone() {
    const e = this.constructor;
    return new e(this.device, {
      cameraEntity: this.cameraEntity,
      radius: this.radius,
      brightness: this.brightness,
      samples: this.samples,
      downscale: this.downscale
    });
  }
}
class Qe extends pc.PostEffect {
  name = E.VerticalTiltShiftEffect;
  shader;
  focus;
  constructor(e, t) {
    super(e);
    const i = [
      "uniform sampler2D uColorBuffer;",
      "uniform float uV;",
      "uniform float uR;",
      "",
      "varying vec2 vUv0;",
      "",
      "void main() {",
      "    vec4 sum = vec4( 0.0 );",
      "    float vv = uV * abs( uR - vUv0.y );",
      "",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 4.0 * vv ) ) * 0.051;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 3.0 * vv ) ) * 0.0918;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 2.0 * vv ) ) * 0.12245;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y - 1.0 * vv ) ) * 0.1531;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y ) ) * 0.1633;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 1.0 * vv ) ) * 0.1531;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 2.0 * vv ) ) * 0.12245;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 3.0 * vv ) ) * 0.0918;",
      "    sum += texture2D( uColorBuffer, vec2( vUv0.x, vUv0.y + 4.0 * vv ) ) * 0.051;",
      "",
      "    gl_FragColor = sum;",
      "}"
    ].join(`
`);
    this.shader = pc.ShaderUtils.createShader(e, {
      uniqueName: "VerticalTiltShiftShader",
      attributes: { aPosition: pc.SEMANTIC_POSITION },
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: i
    }), this.focus = 0.35, this.applyConfig(
      t || {
        focus: this.focus
      }
    );
  }
  render(e, t, i) {
    const s = this.device.scope;
    s.resolve("uV").setValue(1 / e.height), s.resolve("uR").setValue(this.focus), s.resolve("uColorBuffer").setValue(e.colorBuffer), this.drawQuad(t, this.shader, i);
  }
  applyConfig(e) {
    e.focus !== void 0 && (this.focus = pc.math.clamp(e.focus, 0, 1));
  }
  clone() {
    const e = this.constructor;
    return new e(this.device, {
      focus: this.focus
    });
  }
}
class $e extends pc.PostEffect {
  name = E.VignetteEffect;
  vignetteShader;
  offset;
  darkness;
  constructor(e, t) {
    super(e);
    const i = [
      "uniform sampler2D uColorBuffer;",
      "uniform float uDarkness;",
      "uniform float uOffset;",
      "",
      "varying vec2 vUv0;",
      "",
      "void main() {",
      "    vec4 texel = texture2D(uColorBuffer, vUv0);",
      "    vec2 uv = (vUv0 - vec2(0.5)) * vec2(uOffset);",
      "    gl_FragColor = vec4(mix(texel.rgb, vec3(1.0 - uDarkness), dot(uv, uv)), texel.a);",
      "}"
    ].join(`
`);
    this.vignetteShader = pc.ShaderUtils.createShader(e, {
      uniqueName: "VignetteShader",
      attributes: { aPosition: pc.SEMANTIC_POSITION },
      vertexGLSL: pc.PostEffect.quadVertexShader,
      fragmentGLSL: i
    }), this.offset = 1, this.darkness = 1, this.applyConfig(
      t || {
        offset: this.offset,
        darkness: this.darkness
      }
    );
  }
  render(e, t, i) {
    const s = this.device.scope;
    s.resolve("uColorBuffer").setValue(e.colorBuffer), s.resolve("uOffset").setValue(this.offset), s.resolve("uDarkness").setValue(this.darkness), this.drawQuad(t, this.vignetteShader, i);
  }
  applyConfig(e) {
    e.offset !== void 0 && (this.offset = Math.max(e.offset, 0)), e.darkness !== void 0 && (this.darkness = e.darkness);
  }
  clone() {
    const e = this.constructor;
    return new e(this.device, {
      offset: this.offset,
      darkness: this.darkness
    });
  }
}
class w {
  static _CONTROLS_LAYER_NAME = "MediaControlsUiLayer";
  static _TRIGGER_SCREEN_PRIORITY = 1;
  static _LABELS_SCREEN_PRIORITY = 2;
  static _BUTTONS_SCREEN_PRIORITY = 3;
  _pcApp;
  _rootEntity;
  _panelWidth;
  _panelHeight;
  _callbacks;
  _viverseApp;
  _controlsLayer = null;
  _triggerScreen = null;
  _labelsScreen = null;
  _buttonsScreen = null;
  _triggerPanel = null;
  _backdrop = null;
  _labels = null;
  _buttons = null;
  _volumeLabelSpacer = null;
  _triggerHovered = !1;
  _triggerSelected = !1;
  _buttonHovered = !1;
  _buttonSelected = !1;
  _visibilityUpdateHandle = null;
  _playButton = null;
  _pauseButton = null;
  _volumeUpButton = null;
  _volumeDownButton = null;
  _seekBackButton = null;
  _seekFwdButton = null;
  _volumeLabel = null;
  _timeLabel = null;
  constructor(e, t, i, o, s, n) {
    this._pcApp = e, this._rootEntity = t, this._panelWidth = i, this._panelHeight = o, this._callbacks = s, this._viverseApp = n ?? null;
  }
  async initialize(e = {}) {
    const t = await this._loadAssets();
    this._controlsLayer = this._getControlsLayer(), this._getViverseApp() ? (this._bindCameraEvents(), this._attachLayerToModuleCameras()) : this._bindViverseAppStartEvent(), this._triggerScreen = this._createScreen(
      "MediaControlsTriggerScreen",
      w._TRIGGER_SCREEN_PRIORITY
    ), this._labelsScreen = this._createScreen(
      "MediaControlsLabelsScreen",
      w._LABELS_SCREEN_PRIORITY
    ), this._buttonsScreen = this._createScreen(
      "MediaControlsButtonsScreen",
      w._BUTTONS_SCREEN_PRIORITY
    ), this._triggerPanel = this._createTriggerPanel(), this._bindTriggerEvents(), (e.useBackdrop ?? !0) && (this._backdrop = this._createBackdrop(), this._triggerScreen.addChild(this._backdrop)), this._labels = this._createLabelsContainer(t), this._buttons = this._createButtonsContainer(t), this._bindButtonEvents(), this._syncVolumeLabelSpacerWidth(), this._hideControls(), this._triggerScreen.addChild(this._triggerPanel), this._labelsScreen.addChild(this._labels), this._buttonsScreen.addChild(this._buttons), this._applyScreenTransform(this._triggerScreen, e), this._applyScreenTransform(this._labelsScreen, e), this._applyScreenTransform(this._buttonsScreen, e), this._rootEntity.addChild(this._triggerScreen), this._rootEntity.addChild(this._labelsScreen), this._rootEntity.addChild(this._buttonsScreen), this._triggerScreen.screen?.syncDrawOrder(), this._labelsScreen.screen?.syncDrawOrder(), this._buttonsScreen.screen?.syncDrawOrder();
  }
  updateTimeLabel(e, t) {
    if (!this._timeLabel?.element) return;
    const i = this._getTimeLabel(e, t), o = this._timeLabel.element.text;
    i !== o && (this._timeLabel.element.text = i);
  }
  updateVolumeLabel(e, t) {
    this._volumeLabel?.element && (this._volumeLabel.element.text = this._getVolumeLabel(e, t), this._syncVolumeLabelSpacerWidth());
  }
  updatePlaybackButtons(e) {
    this._playButton && (this._playButton.enabled = !e), this._pauseButton && (this._pauseButton.enabled = e);
  }
  async _loadAssets() {
    const e = "/textures/media/", t = [
      A(this._pcApp, "play.png", e, "extension", "texture"),
      A(this._pcApp, "pause.png", e, "extension", "texture"),
      A(this._pcApp, "volume-up.png", e, "extension", "texture"),
      A(this._pcApp, "volume-down.png", e, "extension", "texture"),
      A(this._pcApp, "seek-back.png", e, "extension", "texture"),
      A(this._pcApp, "seek-forward.png", e, "extension", "texture"),
      Q(this._pcApp, "roboto-medium", "/fonts/", "extension")
    ];
    return Promise.all(t);
  }
  _showControls() {
    this._labels && (this._labels.enabled = !0), this._buttons && (this._buttons.enabled = !0), this._backdrop && (this._backdrop.enabled = !0);
  }
  _hideControls() {
    this._labels && (this._labels.enabled = !1), this._buttons && (this._buttons.enabled = !1), this._backdrop && (this._backdrop.enabled = !1);
  }
  _timeFormat(e) {
    const t = Math.floor(e / 3600), i = Math.floor(e % 3600 / 60), o = Math.floor(e % 60), s = String(t).padStart(2, "0"), n = String(i).padStart(2, "0"), c = String(o).padStart(2, "0");
    return t ? `${s}:${n}:${c}` : `${n}:${c}`;
  }
  _getTimeLabel(e, t) {
    const i = this._timeFormat(e), o = this._timeFormat(t);
    return `${i}/${o}`;
  }
  _getVolumeLabel(e, t) {
    if (e <= 0 || t) return "MUTE";
    const i = Math.max(0, Math.min(e, 1)), o = Math.round(i * 20), s = "|".repeat(o), n = " ".repeat(20 - o);
    return `[${s}${n}]`;
  }
  _syncVolumeLabelSpacerWidth() {
    !this._volumeLabelSpacer?.element || !this._volumeLabel?.element || (this._volumeLabelSpacer.element.width = this._volumeLabel.element.width);
  }
  _scheduleVisibilityUpdate() {
    this._visibilityUpdateHandle && clearTimeout(this._visibilityUpdateHandle), this._visibilityUpdateHandle = setTimeout(() => {
      if (this._visibilityUpdateHandle = null, this._triggerHovered || this._triggerSelected || this._buttonHovered || this._buttonSelected) {
        this._showControls();
        return;
      }
      this._hideControls();
    }, 0);
  }
  _onTriggerMouseEnter() {
    this._triggerHovered = !0, this._scheduleVisibilityUpdate();
  }
  _onTriggerMouseLeave() {
    this._triggerHovered = !1, this._scheduleVisibilityUpdate();
  }
  _onTriggerSelectEnter() {
    this._triggerSelected = !0, this._scheduleVisibilityUpdate();
  }
  _onTriggerSelectLeave() {
    this._triggerSelected = !1, this._scheduleVisibilityUpdate();
  }
  _onButtonMouseEnter() {
    this._buttonHovered = !0, this._scheduleVisibilityUpdate();
  }
  _onButtonMouseLeave() {
    this._buttonHovered = !1, this._scheduleVisibilityUpdate();
  }
  _onButtonSelectEnter() {
    this._buttonSelected = !0, this._scheduleVisibilityUpdate();
  }
  _onButtonSelectLeave() {
    this._buttonSelected = !1, this._scheduleVisibilityUpdate();
  }
  _getControlsLayer() {
    return this._controlsLayer ? this._controlsLayer : (this._controlsLayer = this._getOrCreateUiLayer(
      w._CONTROLS_LAYER_NAME,
      pc.LAYERID_WORLD,
      !0
    ), this._controlsLayer);
  }
  _getViverseApp() {
    return this._viverseApp ? this._viverseApp : (this._viverseApp = $.getApplication(), this._viverseApp);
  }
  _getCameraModule() {
    return this._getViverseApp()?.systems.localPlayer?.modules.camera;
  }
  _getCurrentCameraComponent() {
    const e = this._getCameraModule(), t = e?.currentCamera?.entity.camera;
    if (t)
      return t;
    const i = Object.values(e?.cameras ?? {}).find(
      (s) => s.entity.enabled && !!s.entity.camera
    );
    return i?.entity.camera ? i.entity.camera : e?.cameraOrders.map((s) => e.cameras[s]).find((s) => !!s?.entity.camera)?.entity.camera ?? null;
  }
  _getModuleCameraComponents() {
    const e = this._getCameraModule();
    if (!e)
      return [];
    const i = (e.cameraOrders ?? []).map((s) => e.cameras[s]).filter((s) => !!s).map((s) => s.entity.camera).filter((s) => !!s), o = e.currentCamera?.entity.camera;
    return o && !i.includes(o) && i.unshift(o), i;
  }
  _attachLayerToCamera(e, t) {
    const i = t ?? this._controlsLayer;
    return !i || !e || e.layers.includes(i.id) ? !1 : (e.layers = [...e.layers, i.id], !0);
  }
  _attachLayerToCurrentCamera() {
    return this._attachLayerToCamera(this._getCurrentCameraComponent(), this._getControlsLayer());
  }
  _attachLayerToModuleCameras() {
    const e = this._getControlsLayer();
    let t = !1;
    return this._getModuleCameraComponents().forEach((i) => {
      t = this._attachLayerToCamera(i, e) || t;
    }), t || this._attachLayerToCurrentCamera();
  }
  _onViverseAppStart(e) {
    e ? this._viverseApp = e : this._viverseApp = this._getViverseApp(), this._unbindViverseAppStartEvent(), this._viverseApp && (this._bindCameraEvents(), this._attachLayerToModuleCameras());
  }
  _bindViverseAppStartEvent() {
    this._pcApp.off("viverse-app:start", this._onViverseAppStart, this), this._pcApp.on("viverse-app:start", this._onViverseAppStart, this);
  }
  _unbindViverseAppStartEvent() {
    this._pcApp.off("viverse-app:start", this._onViverseAppStart, this);
  }
  _bindCameraEvents() {
    const e = this._getViverseApp()?.systems.localPlayer;
    e && (e.on("camera:changed", this._onCameraChanged, this), e.on("camera:entity-replaced", this._onCameraEntityReplaced, this));
  }
  _unbindCameraEvents() {
    const e = this._getViverseApp()?.systems.localPlayer;
    e && (e.off("camera:changed", this._onCameraChanged, this), e.off("camera:entity-replaced", this._onCameraEntityReplaced, this));
  }
  _onCameraChanged({ newCamera: e }) {
    this._attachLayerToCamera(e.entity.camera);
  }
  _onCameraEntityReplaced({ camera: e }) {
    this._attachLayerToCamera(e.entity.camera);
  }
  _getOrCreateUiLayer(e, t, i) {
    const o = this._pcApp;
    let s = o.scene.layers.getLayerByName(e);
    s ? (s.opaqueSortMode = pc.SORTMODE_MANUAL, s.transparentSortMode = pc.SORTMODE_MANUAL) : s = X(o, e, {
      opaqueSortMode: pc.SORTMODE_MANUAL,
      transparentSortMode: pc.SORTMODE_MANUAL
    });
    const n = o.scene.layers.layerList.findIndex(
      (c) => c.id === t
    );
    if (n >= 0) {
      const c = i ? n + 1 : n;
      o.scene.layers.layerList.findIndex(
        (a) => a.id === s.id
      ) !== c && (o.scene.layers.remove(s), o.scene.layers.insert(s, Math.min(c, o.scene.layers.layerList.length)));
    }
    return s;
  }
  _createScreen(e, t) {
    const i = new pc.Entity(e);
    return i.addComponent("screen", {
      screenSpace: !1,
      referenceResolution: [this._panelWidth, this._panelHeight],
      priority: t
    }), i;
  }
  _applyScreenTransform(e, t) {
    const i = t.offset || [0, 0, 0.01];
    e.setLocalPosition(i[0], i[1], i[2]);
    const o = t.rotation || [0, 0, 0];
    e.setLocalEulerAngles(o[0], o[1], o[2]);
  }
  _bindTriggerEvents() {
    this._triggerPanel?.button && (this._triggerPanel.button.on("mouseenter", this._onTriggerMouseEnter, this), this._triggerPanel.button.on("mouseleave", this._onTriggerMouseLeave, this), this._triggerPanel.button.on("selectenter", this._onTriggerSelectEnter, this), this._triggerPanel.button.on("selectleave", this._onTriggerSelectLeave, this));
  }
  _unbindTriggerEvents() {
    this._triggerPanel?.button && (this._triggerPanel.button.off("mouseenter", this._onTriggerMouseEnter, this), this._triggerPanel.button.off("mouseleave", this._onTriggerMouseLeave, this), this._triggerPanel.button.off("selectenter", this._onTriggerSelectEnter, this), this._triggerPanel.button.off("selectleave", this._onTriggerSelectLeave, this));
  }
  _createTriggerPanel() {
    const e = this._getControlsLayer(), t = new pc.Entity("MediaControlsTriggerPanel");
    return t.addComponent("element", {
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: this._panelWidth,
      height: this._panelHeight,
      type: pc.ELEMENTTYPE_GROUP,
      useInput: !0,
      layers: [e.id]
    }), t.addComponent("button", {
      imageEntity: t
    }), t;
  }
  _createBackdrop() {
    const e = this._getControlsLayer(), t = new pc.Entity("MediaControlsBackdrop");
    return t.addComponent("element", {
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: this._panelWidth,
      height: this._panelHeight,
      type: pc.ELEMENTTYPE_IMAGE,
      color: pc.Color.BLACK,
      opacity: 0.7,
      useInput: !1,
      layers: [e.id]
    }), t;
  }
  _createButton(e, t, i) {
    const o = this._getControlsLayer(), s = new pc.Entity(e), n = new pc.Color().fromString("#009DE7");
    return s.addComponent("element", {
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: t,
      height: t,
      type: pc.ELEMENTTYPE_IMAGE,
      opacity: 1,
      useInput: !0,
      textureAsset: i,
      layers: [o.id]
    }), s.addComponent("button", {
      hoverTint: n,
      inactiveTint: n,
      pressedTint: n,
      transitionMode: pc.BUTTON_TRANSITION_MODE_TINT,
      imageEntity: s
    }), s;
  }
  _getContainerRatio() {
    const e = this._panelWidth / 1280, t = this._panelHeight / 720;
    return Math.min(e, t);
  }
  _createControlsRootContainer(e) {
    const t = this._getControlsLayer(), i = this._getContainerRatio(), o = 100 * i, s = 200 * i, n = 100 * i, c = 1280 * i, h = 720 * i, a = o + s + n, d = (h * 0.8 - a) / 2, l = new pc.Entity(e);
    return l.addComponent("element", {
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      type: pc.ELEMENTTYPE_GROUP,
      layers: [t.id]
    }), l.addComponent("layoutgroup", {
      orientation: pc.ORIENTATION_VERTICAL,
      alignment: new pc.Vec2(0.5, 0.5),
      widthFitting: pc.FITTING_NONE,
      heightFitting: pc.FITTING_NONE
    }), l.element.width = c, l.element.height = h, l.layoutgroup.spacing = new pc.Vec2(0, d), l;
  }
  _createLabelsContainer(e) {
    const t = this._getContainerRatio(), i = 100 * t, o = 200 * t, s = 100 * t, n = 1280 * t, c = e[6], h = this._createControlsRootContainer("MediaControlsLabelsContainer"), a = this._createLayoutContainer("VolumeLabelRow", pc.ORIENTATION_HORIZONTAL);
    a.element.width = n, a.element.height = i, this._volumeLabel = this._createLabel("VolumeLabel", c, ""), a.addChild(this._volumeLabel);
    const d = this._createLayoutContainer(
      "PlaybackSpacerRow",
      pc.ORIENTATION_HORIZONTAL
    );
    d.element.width = n, d.element.height = o;
    const l = this._createLayoutContainer("TimeLabelRow", pc.ORIENTATION_HORIZONTAL);
    return l.element.width = n, l.element.height = s, this._timeLabel = this._createLabel("TimeLabel", c, ""), l.addChild(this._timeLabel), h.addChild(a), h.addChild(d), h.addChild(l), h;
  }
  _createButtonsContainer(e) {
    const t = this._getContainerRatio(), i = 100 * t, o = 200 * t, s = 100 * t, n = 1280 * t, [c, h, a, d, l, v] = e, f = this._createControlsRootContainer("MediaControlsButtonsContainer"), _ = this._createLayoutContainer("VolumeButtonsRow", pc.ORIENTATION_HORIZONTAL);
    _.element.width = n, _.element.height = i, _.layoutgroup.spacing = new pc.Vec2(48 * t, 0);
    const y = 100 * t;
    this._volumeDownButton = this._createButton(
      "VolumeDownButton",
      y,
      d
    ), this._volumeUpButton = this._createButton("VolumeUpButton", y, a), this._volumeLabelSpacer = this._createSpacer("VolumeLabelSpacer", 0, i), _.addChild(this._volumeDownButton), _.addChild(this._volumeLabelSpacer), _.addChild(this._volumeUpButton);
    const u = this._createLayoutContainer(
      "PlaybackButtonsRow",
      pc.ORIENTATION_HORIZONTAL
    );
    u.element.width = n, u.element.height = o, u.layoutgroup.spacing = new pc.Vec2(150 * t, 0);
    const b = 200 * t;
    this._playButton = this._createButton("PlayButton", b, c), this._pauseButton = this._createButton("PauseButton", b, h);
    const C = 120 * t;
    this._seekBackButton = this._createButton("SeekBackButton", C, l), this._seekFwdButton = this._createButton("SeekFwdButton", C, v), u.addChild(this._seekBackButton), u.addChild(this._playButton), u.addChild(this._pauseButton), u.addChild(this._seekFwdButton);
    const m = this._createLayoutContainer("TimeSpacerRow", pc.ORIENTATION_HORIZONTAL);
    return m.element.width = n, m.element.height = s, f.addChild(_), f.addChild(u), f.addChild(m), f;
  }
  _bindButtonEvents() {
    this._playButton?.button?.on("click", this._callbacks.onPlay, this), this._pauseButton?.button?.on("click", this._callbacks.onPause, this), this._volumeUpButton?.button?.on("click", this._callbacks.onVolumeUp, this), this._volumeDownButton?.button?.on("click", this._callbacks.onVolumeDown, this), this._seekBackButton?.button?.on("click", this._callbacks.onSeekBack, this), this._seekFwdButton?.button?.on("click", this._callbacks.onSeekForward, this), this._getInteractiveButtons().forEach((e) => {
      e.button?.on("mouseenter", this._onButtonMouseEnter, this), e.button?.on("mouseleave", this._onButtonMouseLeave, this), e.button?.on("selectenter", this._onButtonSelectEnter, this), e.button?.on("selectleave", this._onButtonSelectLeave, this);
    });
  }
  _unbindButtonEvents() {
    this._playButton?.button?.off("click", this._callbacks.onPlay, this), this._pauseButton?.button?.off("click", this._callbacks.onPause, this), this._volumeUpButton?.button?.off("click", this._callbacks.onVolumeUp, this), this._volumeDownButton?.button?.off("click", this._callbacks.onVolumeDown, this), this._seekBackButton?.button?.off("click", this._callbacks.onSeekBack, this), this._seekFwdButton?.button?.off("click", this._callbacks.onSeekForward, this), this._getInteractiveButtons().forEach((e) => {
      e.button?.off("mouseenter", this._onButtonMouseEnter, this), e.button?.off("mouseleave", this._onButtonMouseLeave, this), e.button?.off("selectenter", this._onButtonSelectEnter, this), e.button?.off("selectleave", this._onButtonSelectLeave, this);
    });
  }
  _getInteractiveButtons() {
    return [
      this._playButton,
      this._pauseButton,
      this._volumeUpButton,
      this._volumeDownButton,
      this._seekBackButton,
      this._seekFwdButton
    ].filter((e) => !!e);
  }
  _createLabel(e, t, i = "") {
    const o = this._getControlsLayer(), s = new pc.Entity(e), n = this._getContainerRatio();
    return s.addComponent("element", {
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      fontSize: 64 * n,
      autoWidth: !0,
      autoHeight: !0,
      type: pc.ELEMENTTYPE_TEXT,
      color: pc.Color.WHITE,
      alignment: [0.5, 0.5],
      fontAsset: t,
      text: i,
      layers: [o.id]
    }), s;
  }
  _createLayoutContainer(e, t) {
    const i = this._getControlsLayer(), o = new pc.Entity(e);
    return o.addComponent("element", {
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      type: pc.ELEMENTTYPE_GROUP,
      layers: [i.id]
    }), o.addComponent("layoutgroup", {
      orientation: t,
      alignment: new pc.Vec2(0.5, 0.5),
      widthFitting: pc.FITTING_NONE,
      heightFitting: pc.FITTING_NONE
    }), o;
  }
  _createSpacer(e, t, i) {
    const o = this._getControlsLayer(), s = new pc.Entity(e);
    return s.addComponent("element", {
      anchor: [0.5, 0.5, 0.5, 0.5],
      pivot: [0.5, 0.5],
      width: t,
      height: i,
      type: pc.ELEMENTTYPE_GROUP,
      layers: [o.id]
    }), s;
  }
  destroy() {
    this._unbindViverseAppStartEvent(), this._unbindCameraEvents(), this._unbindTriggerEvents(), this._unbindButtonEvents(), this._triggerHovered = !1, this._triggerSelected = !1, this._buttonHovered = !1, this._buttonSelected = !1, this._visibilityUpdateHandle && (clearTimeout(this._visibilityUpdateHandle), this._visibilityUpdateHandle = null), this._triggerScreen?.destroy(), this._labelsScreen?.destroy(), this._buttonsScreen?.destroy();
  }
}
class z {
  _pcApp;
  _viverseApp;
  _rootEntity;
  _controlsUis = [];
  constructor(e, t, i) {
    this._pcApp = e, this._viverseApp = i ?? null, this._rootEntity = t, this._pcApp.on("update", this._update, this), t.once("destroy", this.destroy, this);
  }
  async _createControls(e, t, i = {}) {
    const o = new w(
      this._pcApp,
      this._rootEntity,
      e,
      t,
      {
        onPlay: this._onPlay.bind(this),
        onPause: this._onPause.bind(this),
        onVolumeUp: this._onVolumeUp.bind(this),
        onVolumeDown: this._onVolumeDown.bind(this),
        onSeekBack: this._onSeekBack.bind(this),
        onSeekForward: this._onSeekForward.bind(this)
      },
      this._viverseApp ?? void 0
    );
    await o.initialize(i), this._controlsUis.push(o), o.updatePlaybackButtons(this._playing), o.updateVolumeLabel(this._volume, this._muted), o.updateTimeLabel(this._currentTime, this._duration);
  }
  _onPlay() {
    this._play(), this._updatePlaybackButtons();
  }
  _onPause() {
    this._pause(), this._updatePlaybackButtons();
  }
  _onVolumeUp() {
    this._changeVolume(0.1), this._updateVolumeLabels();
  }
  _onVolumeDown() {
    this._changeVolume(-0.1), this._updateVolumeLabels();
  }
  _onSeekBack() {
    this._seek(-5), this._updateTimeLabels();
  }
  _onSeekForward() {
    this._seek(5), this._updateTimeLabels();
  }
  _updatePlaybackButtons() {
    this._controlsUis.forEach((e) => e.updatePlaybackButtons(this._playing));
  }
  _updateVolumeLabels() {
    this._controlsUis.forEach((e) => e.updateVolumeLabel(this._volume, this._muted));
  }
  _updateTimeLabels() {
    this._controlsUis.forEach((e) => e.updateTimeLabel(this._currentTime, this._duration));
  }
  _update() {
    this._updateTimeLabels();
  }
  destroy() {
    this._controlsUis.forEach((e) => e.destroy()), this._controlsUis = [], this._pcApp.off("update", this._update, this);
  }
}
class Xe extends z {
  _videoTexture;
  _video;
  _bindOnVideoLoaded;
  _bindOnStateChanged;
  constructor(e, t, i) {
    super(e, t.rootEntity, i), this._videoTexture = t, this._video = t.videoElement, this._bindOnVideoLoaded = this._onVideoLoaded.bind(this), this._bindOnStateChanged = this._onStateChanged.bind(this), this._bindVideoEvents();
  }
  get _currentTime() {
    return this._video.currentTime;
  }
  get _duration() {
    return this._video.duration;
  }
  get _volume() {
    return this._videoTexture.audioVolume;
  }
  get _muted() {
    return this._video.muted;
  }
  get _playing() {
    return !this._video.paused;
  }
  _bindVideoEvents() {
    this._video.addEventListener("loadedmetadata", this._bindOnVideoLoaded, { once: !0 }), this._video.addEventListener("playing", this._bindOnStateChanged), this._video.addEventListener("pause", this._bindOnStateChanged), this._video.addEventListener("ended", this._bindOnStateChanged), this._video.addEventListener("volumechange", this._bindOnStateChanged);
  }
  _unbindVideoEvents() {
    this._video.removeEventListener("loadedmetadata", this._bindOnVideoLoaded), this._video.removeEventListener("playing", this._bindOnStateChanged), this._video.removeEventListener("pause", this._bindOnStateChanged), this._video.removeEventListener("ended", this._bindOnStateChanged), this._video.removeEventListener("volumechange", this._bindOnStateChanged);
  }
  _createSphericalControls() {
    const e = { useBackdrop: !1, offset: [0, 0, 0.5] }, t = { useBackdrop: !1, offset: [0, 0, -0.5], rotation: [0, 180, 0] };
    this._createControls(1, 1, e), this._createControls(1, 1, t);
  }
  _createFlatControls() {
    const e = this._videoTexture.aspectRatio, t = this._videoTexture.renderSide, i = e, o = 1;
    if (t === "front" || t === "double") {
      const c = { useBackdrop: !0 };
      this._createControls(i, o, c);
    }
    if (t === "back" || t === "double") {
      const c = { useBackdrop: !0, offset: [0, 0, -0.01], rotation: [0, 180, 0] };
      this._createControls(i, o, c);
    }
  }
  _onVideoLoaded() {
    this._videoTexture.projection === "spherical" ? this._createSphericalControls() : this._createFlatControls();
  }
  _onStateChanged() {
    this._updatePlaybackButtons(), this._updateVolumeLabels();
  }
  _pause() {
    this._video.pause();
  }
  _play() {
    this._video.play();
  }
  _changeVolume(e) {
    this._muted && (this._video.muted = !1);
    const t = Math.round(this._videoTexture.audioVolume * 100) / 100, i = pc.math.clamp(t + e, 0, 1);
    this._videoTexture.setAudioVolume(i);
  }
  _seek(e) {
    this._video.currentTime += e;
  }
  destroy() {
    super.destroy(), this._unbindVideoEvents();
  }
}
class Ye extends z {
  _soundComponent;
  _slot;
  _coverTexture = null;
  _coverRenderSide = "double";
  constructor(e, t, i, o) {
    super(e, t.entity, o), this._soundComponent = t;
    const s = i?.slotName || Object.keys(this._soundComponent.slots)[0] || "";
    if (this._slot = this._soundComponent.slots[s] || null, !this._slot) throw new Error("SoundControls: No sound slots available.");
    const { coverTexture: n, coverRenderSide: c } = i || {};
    n && (this._coverTexture = n), c && (this._coverRenderSide = c), this._createCoverEntity(), this._createSoundControls(), this._bindSoundEvents();
  }
  get _currentTime() {
    return this._getSlotCurrentTime();
  }
  get _duration() {
    return this._slot.duration;
  }
  get _volume() {
    return this._slot.volume;
  }
  get _muted() {
    return this._slot.volume === 0;
  }
  get _playing() {
    return this._slot.isPlaying;
  }
  _getSlotCurrentTime() {
    return this._slot.instances.length === 0 ? 0 : this._slot.instances[this._slot.instances.length - 1].currentTime || 0;
  }
  _onSoundPlay(e) {
    e === this._slot && this._updatePlaybackButtons();
  }
  _onSoundPause(e) {
    e === this._slot && this._updatePlaybackButtons();
  }
  _onSoundStop(e) {
    e === this._slot && this._updatePlaybackButtons();
  }
  _bindSoundEvents() {
    this._soundComponent.on("play", this._onSoundPlay, this), this._soundComponent.on("pause", this._onSoundPause, this), this._soundComponent.on("stop", this._onSoundStop, this);
  }
  _unbindSoundEvents() {
    this._soundComponent.off("play", this._onSoundPlay, this), this._soundComponent.off("pause", this._onSoundPause, this), this._soundComponent.off("stop", this._onSoundStop, this);
  }
  async _createDefaultCoverTexture() {
    return (await A(
      this._pcApp,
      "audio-cover.png",
      "/textures/media/",
      "extension",
      "texture"
    )).resource;
  }
  _getCullMode() {
    switch (this._coverRenderSide) {
      case "double":
        return pc.CULLFACE_NONE;
      case "back":
        return pc.CULLFACE_FRONT;
      case "front":
      default:
        return pc.CULLFACE_BACK;
    }
  }
  async _createCoverEntity() {
    const e = new pc.Entity("SoundCover");
    this._rootEntity.addChild(e), this._coverTexture || (this._coverTexture = await this._createDefaultCoverTexture());
    const t = new pc.StandardMaterial();
    t.useLighting = !1, t.useSkybox = !1, t.emissiveMap = this._coverTexture, t.emissive = pc.Color.WHITE, t.cull = this._getCullMode(), t.update(), e.rotateLocal(90, 0, 0), e.addComponent("render", {
      type: "plane",
      material: t,
      castShadows: !1,
      receiveShadows: !1
    });
  }
  _createSoundControls() {
    const e = this._coverRenderSide;
    (e === "front" || e === "double") && this._createControls(1, 1, { useBackdrop: !0 }), (e === "back" || e === "double") && this._createControls(1, 1, {
      useBackdrop: !0,
      offset: [0, 0, -0.01],
      rotation: [0, 180, 0]
    });
  }
  _pause() {
    this._slot.pause();
  }
  _play() {
    this._slot.isPaused ? this._slot.resume() : this._slot.play();
  }
  _changeVolume(e) {
    const t = Math.round(this._slot.volume * 100) / 100, i = pc.math.clamp(t + e, 0, 1);
    this._slot.volume = i;
  }
  _seek(e) {
    this._slot.instances.forEach((i) => {
      const o = pc.math.clamp(i.currentTime + e, 0, i.duration);
      i.currentTime = o;
    });
  }
  destroy() {
    super.destroy(), this._unbindSoundEvents();
  }
}
class j {
  _viverseApp;
  _scale = new pc.Vec3(5, 5, 5);
  _rootEntity;
  _audioZoneBox;
  _isInZone = !1;
  _targetEntity = null;
  _checkTimer = 0;
  _checkInterval = 0.5;
  constructor(e, t, i) {
    this._viverseApp = e, this._rootEntity = t, i?.scale && (this._scale = i.scale), this._audioZoneBox = this._createAudioZone(), this._viverseApp.pcApp.on("update", this._update, this), t.once("destroy", this.destroy, this);
  }
  get audioZoneBox() {
    return this._audioZoneBox;
  }
  _createAudioZone() {
    const e = this._rootEntity.getLocalScale(), t = new pc.Vec3().mul2(e, this._scale);
    return new pc.BoundingBox(this._rootEntity.getPosition(), t.divScalar(2));
  }
  _handleZoneStateChange(e) {
    e ? this._onEnterZone() : this._onExitZone();
  }
  _checkIsTargetInZone() {
    const e = this._viverseApp.systems.localPlayer, t = this._targetEntity || e?.playerEntity;
    if (!t) {
      e || p.warn("AudioZone has no target entity to check.");
      return;
    }
    const i = t.getPosition(), o = this._audioZoneBox.containsPoint(i);
    o !== this._isInZone && (this._isInZone = o, this._handleZoneStateChange(o));
  }
  _updateAudioZoneBox() {
    this._audioZoneBox.center.copy(this._rootEntity.getPosition());
  }
  _update(e) {
    this._updateAudioZoneBox(), this._checkTimer += e, this._checkTimer >= this._checkInterval && (this._checkIsTargetInZone(), this._checkTimer = 0);
  }
  destroy() {
    this._viverseApp.pcApp.off("update", this._update, this);
  }
}
class Ke extends j {
  _videoTexture;
  constructor(e, t, i) {
    super(e, t.entity, i), this._videoTexture = t, this._onExitZone();
  }
  _onEnterZone() {
    this._videoTexture.unmuteAudio();
  }
  _onExitZone() {
    this._videoTexture.muteAudio();
  }
}
class Je extends j {
  _sound;
  constructor(e, t, i) {
    super(e, t.entity, i), this._sound = t, this._onExitZone();
  }
  _onEnterZone() {
    this._sound.volume = 1;
  }
  _onExitZone() {
    this._sound.volume = 0;
  }
}
class et {
  _viverseApp;
  _entity;
  _targetType;
  _scriptAttributes;
  constructor(e, t, i, o) {
    if (this._viverseApp = e, this._entity = t, this._targetType = i, this._scriptAttributes = o, this._targetType === P.ViverseCamera) {
      const s = this._viverseApp.systems.localPlayer?.modules.camera?.currentCamera;
      this._scriptAttributes.targetEntity = s?.entity || null, this._scriptAttributes.targetPosition = null;
      const n = this._viverseApp.systems.localPlayer;
      n && (n.on("camera:changed", this._onCameraChanged, this), n.on("camera:entity-replaced", this._onCameraReplaced, this));
    } else if (this._targetType === P.Entity) {
      if (!this._scriptAttributes.targetEntity) {
        p.warn("Billboard: Target entity is not available");
        return;
      }
      this._scriptAttributes.targetPosition = null;
    } else if (this._targetType === P.Position) {
      if (!this._scriptAttributes.targetPosition) {
        p.warn("Billboard: Target position is not available");
        return;
      }
      this._scriptAttributes.targetEntity = null;
    }
    this._entity.script || this._entity.addComponent("script"), this._entity.script && this._entity.script.create(Y, {
      properties: this._scriptAttributes
    });
  }
  _onCameraChanged({ newCamera: e }) {
    this._targetType === P.ViverseCamera && (this._scriptAttributes.targetEntity = e.entity, this._entity.fire("billboard:set-target", e.entity));
  }
  _onCameraReplaced({
    camera: e,
    previousEntity: t
  }) {
    this._targetType !== P.ViverseCamera || this._scriptAttributes.targetEntity !== t || (this._scriptAttributes.targetEntity = e.entity, this._entity.fire("billboard:set-target", e.entity));
  }
  destroy() {
    const e = this._viverseApp.systems.localPlayer;
    e && (e.off("camera:changed", this._onCameraChanged, this), e.off("camera:entity-replaced", this._onCameraReplaced, this));
  }
}
export {
  j as AudioZone,
  et as Billboard,
  Ue as BlendEffect,
  He as BloomEffect,
  Ge as BrightnessContrastEffect,
  be as ControlEntitySoundAction,
  ge as DestroyEntityAction,
  We as EdgeDetectEffect,
  he as EntityAnimCustomEventTrigger,
  ue as EntityAnimEndTrigger,
  ce as EntityAnimStartTrigger,
  le as EntityCollisionEndTrigger,
  ae as EntityCollisionStartTrigger,
  me as EntitySelectedTrigger,
  re as EntityTriggerEnterTrigger,
  ne as EntityTriggerLeaveTrigger,
  Te as FadeInEntityAction,
  we as FadeOutEntityAction,
  Ne as FireEntityEventAction,
  qe as FxaaEffect,
  Fe as GpuInstancingRender,
  ze as HorizontalTiltShiftEffect,
  je as HueSaturationEffect,
  fe as InteractionExecutingTrigger,
  Ie as LeaveSeatAction,
  z as MediaControls,
  ke as OpenLinkAction,
  Oe as PickInteraction,
  Be as PlayEntityAnimationAction,
  Pe as PlayEntityParticleSystemAction,
  Ae as PublishNotificationAction,
  Le as PushEntityWithPhysicsAction,
  xe as QuestAction,
  Ze as SSAOEffect,
  de as SeatOccupiedTrigger,
  pe as SeatVacatedTrigger,
  Ce as SetSpawnPointAction,
  Me as ShowToastMessageAction,
  Re as SitInteraction,
  Ve as SitOnSeatAction,
  Je as SoundAudioZone,
  Ye as SoundControls,
  _e as SubscribeNotificationTrigger,
  Ee as TeleportPlayerAction,
  ve as ToggleEntityAction,
  ye as ToggleEntityCollisionAction,
  Se as ToggleEntityRigidbodyAction,
  M as TriggerDispatcher,
  Qe as VerticalTiltShiftEffect,
  De as VideoTexture,
  Ke as VideoTextureAudioZone,
  Xe as VideoTextureControls,
  $e as VignetteEffect
};
