/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Clamp = require('../math/Clamp');
var Class = require('../utils/Class');
var Events = require('./events');
var GetFastValue = require('../utils/object/GetFastValue');
var PluginCache = require('../plugins/PluginCache');

/**
 * @classdesc
 * A proxy class to the Global Scene Manager.
 *
 * @class ScenePlugin
 * @memberof Phaser.Scenes
 * @constructor
 * @since 3.0.0
 *
 * @param {Phaser.Scene} scene - The Scene that this ScenePlugin belongs to.
 */
var ScenePlugin = new Class({

    initialize:

    function ScenePlugin (scene)
    {
        /**
         * The Scene that this ScenePlugin belongs to.
         *
         * @name Phaser.Scenes.ScenePlugin#scene
         * @type {Phaser.Scene}
         * @since 3.0.0
         */
        this.scene = scene;

        /**
         * The Scene Systems instance of the Scene that this ScenePlugin belongs to.
         *
         * @name Phaser.Scenes.ScenePlugin#systems
         * @type {Phaser.Scenes.Systems}
         * @since 3.0.0
         */
        this.systems = scene.sys;

        /**
         * The settings of the Scene this ScenePlugin belongs to.
         *
         * @name Phaser.Scenes.ScenePlugin#settings
         * @type {Phaser.Types.Scenes.SettingsObject}
         * @since 3.0.0
         */
        this.settings = scene.sys.settings;

        /**
         * The key of the Scene this ScenePlugin belongs to.
         *
         * @name Phaser.Scenes.ScenePlugin#key
         * @type {string}
         * @since 3.0.0
         */
        this.key = scene.sys.settings.key;

        /**
         * The Game's SceneManager.
         *
         * @name Phaser.Scenes.ScenePlugin#manager
         * @type {Phaser.Scenes.SceneManager}
         * @since 3.0.0
         */
        this.manager = scene.sys.game.scene;

        /**
         * If this Scene is currently transitioning to another, this holds
         * the current percentage of the transition progress, between 0 and 1.
         *
         * @name Phaser.Scenes.ScenePlugin#transitionProgress
         * @type {number}
         * @since 3.5.0
         */
        this.transitionProgress = 0;

        /**
         * Transition elapsed timer.
         *
         * @name Phaser.Scenes.ScenePlugin#_elapsed
         * @type {number}
         * @private
         * @since 3.5.0
         */
        this._elapsed = 0;

        /**
         * Transition elapsed timer.
         *
         * @name Phaser.Scenes.ScenePlugin#_target
         * @type {?Phaser.Scenes.Scene}
         * @private
         * @since 3.5.0
         */
        this._target = null;

        /**
         * Transition duration.
         *
         * @name Phaser.Scenes.ScenePlugin#_duration
         * @type {number}
         * @private
         * @since 3.5.0
         */
        this._duration = 0;

        /**
         * Transition callback.
         *
         * @name Phaser.Scenes.ScenePlugin#_onUpdate
         * @type {function}
         * @private
         * @since 3.5.0
         */
        this._onUpdate;

        /**
         * Transition callback scope.
         *
         * @name Phaser.Scenes.ScenePlugin#_onUpdateScope
         * @type {object}
         * @private
         * @since 3.5.0
         */
        this._onUpdateScope;

        /**
         * Will this Scene sleep (true) after the transition, or stop (false)
         *
         * @name Phaser.Scenes.ScenePlugin#_willSleep
         * @type {boolean}
         * @private
         * @since 3.5.0
         */
        this._willSleep = false;

        /**
         * Will this Scene be removed from the Scene Manager after the transition completes?
         *
         * @name Phaser.Scenes.ScenePlugin#_willRemove
         * @type {boolean}
         * @private
         * @since 3.5.0
         */
        this._willRemove = false;

        scene.sys.events.once(Events.BOOT, this.boot, this);
        scene.sys.events.on(Events.START, this.pluginStart, this);
    },

    /**
     * This method is called automatically, only once, when the Scene is first created.
     * Do not invoke it directly.
     *
     * @method Phaser.Scenes.ScenePlugin#boot
     * @private
     * @since 3.0.0
     */
    boot: function ()
    {
        this.systems.events.once(Events.DESTROY, this.destroy, this);
    },

    /**
     * This method is called automatically by the Scene when it is starting up.
     * It is responsible for creating local systems, properties and listening for Scene events.
     * Do not invoke it directly.
     *
     * @method Phaser.Scenes.ScenePlugin#pluginStart
     * @private
     * @since 3.5.0
     */
    pluginStart: function ()
    {
        this._target = null;

        this.systems.events.once(Events.SHUTDOWN, this.shutdown, this);
    },

    /**
     * Shutdown this Scene and run the given one.
     *
     * This will happen at the next Scene Manager update, not immediately.
     *
     * @method Phaser.Scenes.ScenePlugin#start
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to start.
     * @param {object} [data] - The Scene data.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    start: function (key, data)
    {
        if (key === undefined) { key = this.key; }

        this.manager.queueOp('stop', this.key);
        this.manager.queueOp('start', key, data);

        return this;
    },

    /**
     * Restarts this Scene.
     *
     * This will happen at the next Scene Manager update, not immediately.
     *
     * @method Phaser.Scenes.ScenePlugin#restart
     * @since 3.4.0
     *
     * @param {object} [data] - The Scene data.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    restart: function (data)
    {
        var key = this.key;

        this.manager.queueOp('stop', key);
        this.manager.queueOp('start', key, data);

        return this;
    },

    /**
     * This will start a transition from the current Scene to the target Scene given.
     *
     * The transition will last for the duration specified in milliseconds.
     *
     * You can have the target Scene moved above or below this one in the display list.
     *
     * You can specify an update callback. This callback will be invoked _every frame_ for the duration
     * of the transition.
     *
     * This Scene can either be sent to sleep at the end of the transition, or stopped. The default is to stop.
     *
     * There are also 5 transition related events: This scene will emit the event `transitionout` when
     * the transition begins, which is typically the frame after calling this method.
     *
     * The target Scene will emit the event `transitioninit` when that Scene's `init` method is called.
     * It will then emit the event `transitionstart` when its `create` method is called.
     * If the Scene was sleeping and has been woken up, it will emit the event `transitionwake` instead of these two,
     * as the Scenes `init` and `create` methods are not invoked when a Scene wakes up.
     *
     * When the duration of the transition has elapsed it will emit the event `transitioncomplete`.
     * These events are cleared of all listeners when the Scene shuts down, but not if it is sent to sleep.
     *
     * It's important to understand that the duration of the transition begins the moment you call this method.
     * If the Scene you are transitioning to includes delayed processes, such as waiting for files to load, the
     * time still counts down even while that is happening. If the game itself pauses, or something else causes
     * this Scenes update loop to stop, then the transition will also pause for that duration. There are
     * checks in place to prevent you accidentally stopping a transitioning Scene but if you've got code to
     * override this understand that until the target Scene completes it might never be unlocked for input events.
     *
     * @method Phaser.Scenes.ScenePlugin#transition
     * @fires Phaser.Scenes.Events#TRANSITION_OUT
     * @since 3.5.0
     *
     * @param {Phaser.Types.Scenes.SceneTransitionConfig} config - The transition configuration object.
     *
     * @return {boolean} `true` is the transition was started, otherwise `false`.
     */
    transition: function (config)
    {
        if (config === undefined) { config = {}; }

        var key = GetFastValue(config, 'target', false);

        var target = this.manager.getScene(key);

        if (!key || !this.checkValidTransition(target))
        {
            return false;
        }

        var duration = GetFastValue(config, 'duration', 1000);

        this._elapsed = 0;
        this._target = target;
        this._duration = duration;
        this._willSleep = GetFastValue(config, 'sleep', false);
        this._willRemove = GetFastValue(config, 'remove', false);

        var callback = GetFastValue(config, 'onUpdate', null);

        if (callback)
        {
            this._onUpdate = callback;
            this._onUpdateScope = GetFastValue(config, 'onUpdateScope', this.scene);
        }

        var allowInput = GetFastValue(config, 'allowInput', false);

        this.settings.transitionAllowInput = allowInput;

        var targetSettings = target.sys.settings;

        targetSettings.isTransition = true;
        targetSettings.transitionFrom = this.scene;
        targetSettings.transitionDuration = duration;
        targetSettings.transitionAllowInput = allowInput;

        if (GetFastValue(config, 'moveAbove', false))
        {
            this.manager.moveAbove(this.key, key);
        }
        else if (GetFastValue(config, 'moveBelow', false))
        {
            this.manager.moveBelow(this.key, key);
        }

        if (target.sys.isSleeping())
        {
            target.sys.wake(GetFastValue(config, 'data'));
        }
        else
        {
            this.manager.start(key, GetFastValue(config, 'data'));
        }

        this.systems.events.emit(Events.TRANSITION_OUT, target, duration);

        this.systems.events.on(Events.UPDATE, this.step, this);

        return true;
    },

    /**
     * Checks to see if this Scene can transition to the target Scene or not.
     *
     * @method Phaser.Scenes.ScenePlugin#checkValidTransition
     * @private
     * @since 3.5.0
     *
     * @param {Phaser.Scene} target - The Scene to test against.
     *
     * @return {boolean} `true` if this Scene can transition, otherwise `false`.
     */
    checkValidTransition: function (target)
    {
        //  Not a valid target if it doesn't exist, isn't active or is already transitioning in or out
        if (!target || target.sys.isActive() || target.sys.isTransitioning() || target === this.scene || this.systems.isTransitioning())
        {
            return false;
        }

        return true;
    },

    /**
     * A single game step. This is only called if the parent Scene is transitioning
     * out to another Scene.
     *
     * @method Phaser.Scenes.ScenePlugin#step
     * @private
     * @since 3.5.0
     *
     * @param {number} time - The current time. Either a High Resolution Timer value if it comes from Request Animation Frame, or Date.now if using SetTimeout.
     * @param {number} delta - The delta time in ms since the last frame. This is a smoothed and capped value based on the FPS rate.
     */
    step: function (time, delta)
    {
        this._elapsed += delta;

        this.transitionProgress = Clamp(this._elapsed / this._duration, 0, 1);

        if (this._onUpdate)
        {
            this._onUpdate.call(this._onUpdateScope, this.transitionProgress);
        }

        if (this._elapsed >= this._duration)
        {
            this.transitionComplete();
        }
    },

    /**
     * Called by `step` when the transition out of this scene to another is over.
     *
     * @method Phaser.Scenes.ScenePlugin#transitionComplete
     * @private
     * @fires Phaser.Scenes.Events#TRANSITION_COMPLETE
     * @since 3.5.0
     */
    transitionComplete: function ()
    {
        var targetSys = this._target.sys;
        var targetSettings = this._target.sys.settings;

        //  Stop the step
        this.systems.events.off(Events.UPDATE, this.step, this);

        //  Notify target scene
        targetSys.events.emit(Events.TRANSITION_COMPLETE, this.scene);

        //  Clear target scene settings
        targetSettings.isTransition = false;
        targetSettings.transitionFrom = null;

        //  Clear local settings
        this._duration = 0;
        this._target = null;
        this._onUpdate = null;
        this._onUpdateScope = null;

        //  Now everything is clear we can handle what happens to this Scene
        if (this._willRemove)
        {
            this.manager.remove(this.key);
        }
        else if (this._willSleep)
        {
            this.systems.sleep();
        }
        else
        {
            this.manager.stop(this.key);
        }
    },

    /**
     * Add the Scene into the Scene Manager and start it if 'autoStart' is true or the Scene config 'active' property is set.
     *
     * @method Phaser.Scenes.ScenePlugin#add
     * @since 3.0.0
     *
     * @param {string} key - The Scene key.
     * @param {(Phaser.Scene|Phaser.Types.Scenes.SettingsConfig|Phaser.Types.Scenes.CreateSceneFromObjectConfig|function)} sceneConfig - The config for the Scene.
     * @param {boolean} autoStart - Whether to start the Scene after it's added.
     * @param {object} [data] - Optional data object. This will be set as Scene.settings.data and passed to `Scene.init`.
     *
     * @return {Phaser.Scene} An instance of the Scene that was added to the Scene Manager.
     */
    add: function (key, sceneConfig, autoStart, data)
    {
        return this.manager.add(key, sceneConfig, autoStart, data);
    },

    /**
     * Launch the given Scene and run it in parallel with this one.
     *
     * This will happen at the next Scene Manager update, not immediately.
     *
     * @method Phaser.Scenes.ScenePlugin#launch
     * @since 3.0.0
     *
     * @param {string} key - The Scene to launch.
     * @param {object} [data] - The Scene data.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    launch: function (key, data)
    {
        if (key && key !== this.key)
        {
            this.manager.queueOp('start', key, data);
        }

        return this;
    },

    /**
     * Runs the given Scene, but does not change the state of this Scene.
     *
     * This will happen at the next Scene Manager update, not immediately.
     *
     * If the given Scene is paused, it will resume it. If sleeping, it will wake it.
     * If not running at all, it will be started.
     *
     * Use this if you wish to open a modal Scene by calling `pause` on the current
     * Scene, then `run` on the modal Scene.
     *
     * @method Phaser.Scenes.ScenePlugin#run
     * @since 3.10.0
     *
     * @param {string} key - The Scene to run.
     * @param {object} [data] - A data object that will be passed to the Scene and emitted in its ready, wake, or resume events.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    run: function (key, data)
    {
        if (key && key !== this.key)
        {
            this.manager.queueOp('run', key, data);
        }

        return this;
    },

    /**
     * Pause the Scene - this stops the update step from happening but it still renders.
     *
     * This will happen at the next Scene Manager update, not immediately.
     *
     * @method Phaser.Scenes.ScenePlugin#pause
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to pause.
     * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its pause event.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    pause: function (key, data)
    {
        if (key === undefined) { key = this.key; }

        this.manager.queueOp('pause', key, data);

        return this;
    },

    /**
     * Resume the Scene - starts the update loop again.
     *
     * This will happen at the next Scene Manager update, not immediately.
     *
     * @method Phaser.Scenes.ScenePlugin#resume
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to resume.
     * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its resume event.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    resume: function (key, data)
    {
        if (key === undefined) { key = this.key; }

        this.manager.queueOp('resume', key, data);

        return this;
    },

    /**
     * Makes the Scene sleep (no update, no render) but doesn't shutdown.
     *
     * This will happen at the next Scene Manager update, not immediately.
     *
     * @method Phaser.Scenes.ScenePlugin#sleep
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to put to sleep.
     * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its sleep event.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    sleep: function (key, data)
    {
        if (key === undefined) { key = this.key; }

        this.manager.queueOp('sleep', key, data);

        return this;
    },

    /**
     * Makes the Scene wake-up (starts update and render)
     *
     * This will happen at the next Scene Manager update, not immediately.
     *
     * @method Phaser.Scenes.ScenePlugin#wake
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to wake up.
     * @param {object} [data] - An optional data object that will be passed to the Scene and emitted in its wake event.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    wake: function (key, data)
    {
        if (key === undefined) { key = this.key; }

        this.manager.queueOp('wake', key, data);

        return this;
    },

    /**
     * Makes this Scene sleep then starts the Scene given.
     *
     * This will happen at the next Scene Manager update, not immediately.
     *
     * @method Phaser.Scenes.ScenePlugin#switch
     * @since 3.0.0
     *
     * @param {string} key - The Scene to start.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    switch: function (key)
    {
        if (key !== this.key)
        {
            this.manager.queueOp('switch', this.key, key);
        }

        return this;
    },

    /**
     * Shutdown the Scene, clearing display list, timers, etc.
     *
     * This happens at the next Scene Manager update, not immediately.
     *
     * @method Phaser.Scenes.ScenePlugin#stop
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to stop.
     * @param {any} [data] - Optional data object to pass to Scene.Systems.shutdown.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    stop: function (key, data)
    {
        if (key === undefined) { key = this.key; }

        this.manager.queueOp('stop', key, data);

        return this;
    },

    /**
     * Sets the active state of the given Scene.
     *
     * @method Phaser.Scenes.ScenePlugin#setActive
     * @since 3.0.0
     *
     * @param {boolean} value - If `true` the Scene will be resumed. If `false` it will be paused.
     * @param {string} [key] - The Scene to set the active state of.
     * @param {object} [data] - An optional data object that will be passed to the Scene and emitted with its events.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    setActive: function (value, key, data)
    {
        if (key === undefined) { key = this.key; }

        var scene = this.manager.getScene(key);

        if (scene)
        {
            scene.sys.setActive(value, data);
        }

        return this;
    },

    /**
     * Sets the visible state of the given Scene.
     *
     * @method Phaser.Scenes.ScenePlugin#setVisible
     * @since 3.0.0
     *
     * @param {boolean} value - The visible value.
     * @param {string} [key] - The Scene to set the visible state for.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    setVisible: function (value, key)
    {
        if (key === undefined) { key = this.key; }

        var scene = this.manager.getScene(key);

        if (scene)
        {
            scene.sys.setVisible(value);
        }

        return this;
    },

    /**
     * Checks if the given Scene is sleeping or not?
     *
     * @method Phaser.Scenes.ScenePlugin#isSleeping
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to check.
     *
     * @return {boolean} Whether the Scene is sleeping.
     */
    isSleeping: function (key)
    {
        if (key === undefined) { key = this.key; }

        return this.manager.isSleeping(key);
    },

    /**
     * Checks if the given Scene is running or not?
     *
     * @method Phaser.Scenes.ScenePlugin#isActive
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to check.
     *
     * @return {boolean} Whether the Scene is running.
     */
    isActive: function (key)
    {
        if (key === undefined) { key = this.key; }

        return this.manager.isActive(key);
    },

    /**
     * Checks if the given Scene is paused or not?
     *
     * @method Phaser.Scenes.ScenePlugin#isPaused
     * @since 3.17.0
     *
     * @param {string} [key] - The Scene to check.
     *
     * @return {boolean} Whether the Scene is paused.
     */
    isPaused: function (key)
    {
        if (key === undefined) { key = this.key; }

        return this.manager.isPaused(key);
    },

    /**
     * Checks if the given Scene is visible or not?
     *
     * @method Phaser.Scenes.ScenePlugin#isVisible
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to check.
     *
     * @return {boolean} Whether the Scene is visible.
     */
    isVisible: function (key)
    {
        if (key === undefined) { key = this.key; }

        return this.manager.isVisible(key);
    },

    /**
     * Swaps the position of two scenes in the Scenes list.
     *
     * This controls the order in which they are rendered and updated.
     *
     * @method Phaser.Scenes.ScenePlugin#swapPosition
     * @since 3.2.0
     *
     * @param {string} keyA - The first Scene to swap.
     * @param {string} [keyB] - The second Scene to swap. If none is given it defaults to this Scene.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    swapPosition: function (keyA, keyB)
    {
        if (keyB === undefined) { keyB = this.key; }

        if (keyA !== keyB)
        {
            this.manager.swapPosition(keyA, keyB);
        }

        return this;
    },

    /**
     * Swaps the position of two scenes in the Scenes list, so that Scene B is directly above Scene A.
     *
     * This controls the order in which they are rendered and updated.
     *
     * @method Phaser.Scenes.ScenePlugin#moveAbove
     * @since 3.2.0
     *
     * @param {string} keyA - The Scene that Scene B will be moved to be above.
     * @param {string} [keyB] - The Scene to be moved. If none is given it defaults to this Scene.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    moveAbove: function (keyA, keyB)
    {
        if (keyB === undefined) { keyB = this.key; }

        if (keyA !== keyB)
        {
            this.manager.moveAbove(keyA, keyB);
        }

        return this;
    },

    /**
     * Swaps the position of two scenes in the Scenes list, so that Scene B is directly below Scene A.
     *
     * This controls the order in which they are rendered and updated.
     *
     * @method Phaser.Scenes.ScenePlugin#moveBelow
     * @since 3.2.0
     *
     * @param {string} keyA - The Scene that Scene B will be moved to be below.
     * @param {string} [keyB] - The Scene to be moved. If none is given it defaults to this Scene.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    moveBelow: function (keyA, keyB)
    {
        if (keyB === undefined) { keyB = this.key; }

        if (keyA !== keyB)
        {
            this.manager.moveBelow(keyA, keyB);
        }

        return this;
    },

    /**
     * Removes a Scene from the SceneManager.
     *
     * The Scene is removed from the local scenes array, it's key is cleared from the keys
     * cache and Scene.Systems.destroy is then called on it.
     *
     * If the SceneManager is processing the Scenes when this method is called it will
     * queue the operation for the next update sequence.
     *
     * @method Phaser.Scenes.ScenePlugin#remove
     * @since 3.2.0
     *
     * @param {(string|Phaser.Scene)} [key] - The Scene to be removed.
     *
     * @return {Phaser.Scenes.SceneManager} This SceneManager.
     */
    remove: function (key)
    {
        if (key === undefined) { key = this.key; }

        this.manager.remove(key);

        return this;
    },

    /**
     * Moves a Scene up one position in the Scenes list.
     *
     * @method Phaser.Scenes.ScenePlugin#moveUp
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to move.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    moveUp: function (key)
    {
        if (key === undefined) { key = this.key; }

        this.manager.moveUp(key);

        return this;
    },

    /**
     * Moves a Scene down one position in the Scenes list.
     *
     * @method Phaser.Scenes.ScenePlugin#moveDown
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to move.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    moveDown: function (key)
    {
        if (key === undefined) { key = this.key; }

        this.manager.moveDown(key);

        return this;
    },

    /**
     * Brings a Scene to the top of the Scenes list.
     *
     * This means it will render above all other Scenes.
     *
     * @method Phaser.Scenes.ScenePlugin#bringToTop
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to move.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    bringToTop: function (key)
    {
        if (key === undefined) { key = this.key; }

        this.manager.bringToTop(key);

        return this;
    },

    /**
     * Sends a Scene to the back of the Scenes list.
     *
     * This means it will render below all other Scenes.
     *
     * @method Phaser.Scenes.ScenePlugin#sendToBack
     * @since 3.0.0
     *
     * @param {string} [key] - The Scene to move.
     *
     * @return {Phaser.Scenes.ScenePlugin} This ScenePlugin object.
     */
    sendToBack: function (key)
    {
        if (key === undefined) { key = this.key; }

        this.manager.sendToBack(key);

        return this;
    },

    /**
     * Retrieve a Scene.
     *
     * @method Phaser.Scenes.ScenePlugin#get
     * @since 3.0.0
     *
     * @param {string} key - The Scene to retrieve.
     *
     * @return {Phaser.Scene} The Scene.
     */
    get: function (key)
    {
        return this.manager.getScene(key);
    },

    /**
     * Retrieves the numeric index of a Scene in the Scenes list.
     *
     * @method Phaser.Scenes.ScenePlugin#getIndex
     * @since 3.7.0
     *
     * @param {(string|Phaser.Scene)} [key] - The Scene to get the index of.
     *
     * @return {number} The index of the Scene.
     */
    getIndex: function (key)
    {
        if (key === undefined) { key = this.key; }

        return this.manager.getIndex(key);
    },

    /**
     * The Scene that owns this plugin is shutting down.
     * We need to kill and reset all internal properties as well as stop listening to Scene events.
     *
     * @method Phaser.Scenes.ScenePlugin#shutdown
     * @private
     * @since 3.0.0
     */
    shutdown: function ()
    {
        var eventEmitter = this.systems.events;

        eventEmitter.off(Events.SHUTDOWN, this.shutdown, this);
        eventEmitter.off(Events.POST_UPDATE, this.step, this);
        eventEmitter.off(Events.TRANSITION_OUT);
    },

    /**
     * The Scene that owns this plugin is being destroyed.
     * We need to shutdown and then kill off all external references.
     *
     * @method Phaser.Scenes.ScenePlugin#destroy
     * @private
     * @since 3.0.0
     */
    destroy: function ()
    {
        this.shutdown();

        this.scene.sys.events.off(Events.START, this.start, this);

        this.scene = null;
        this.systems = null;
        this.settings = null;
        this.manager = null;
    }

});

PluginCache.register('ScenePlugin', ScenePlugin, 'scenePlugin');

module.exports = ScenePlugin;


glFunc.call(gl, location, value.x, value.y, value.z, value.w);

keep keep keep keep replace keep keep keep keep

/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var renderWebGL = require('../../utils/NOOP');
var renderCanvas = require('../../utils/NOOP');

if (typeof WEBGL_RENDERER)
{
    renderWebGL = require('./ShaderWebGLRenderer');
}

if (typeof CANVAS_RENDERER)
{
    renderCanvas = require('./ShaderCanvasRenderer');
}

module.exports = {

    renderWebGL: renderWebGL,
    renderCanvas: renderCanvas

};


if (pipeline === undefined && this.previous)

keep keep keep keep keep replace replace replace replace replace keep keep keep keep keep

/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var Class = require('../../utils/Class');
var Components = require('../components');
var GameObject = require('../GameObject');
var GetFastValue = require('../../utils/object/GetFastValue');
var Extend = require('../../utils/object/Extend');
var SetValue = require('../../utils/object/SetValue');
var ShaderRender = require('./ShaderRender');
var TransformMatrix = require('../components/TransformMatrix');

/**
 * @classdesc
 * A Shader Game Object.
 *
 * This Game Object allows you to easily add a quad with its own shader into the display list, and manipulate it
 * as you would any other Game Object, including scaling, rotating, positioning and adding to Containers. Shaders
 * can be masked with either Bitmap or Geometry masks and can also be used as a Bitmap Mask for a Camera or other
 * Game Object. They can also be made interactive and used for input events.
 *
 * It works by taking a reference to a `Phaser.Display.BaseShader` instance, as found in the Shader Cache. These can
 * be created dynamically at runtime, or loaded in via the GLSL File Loader:
 *
 * ```javascript
 * function preload ()
 * {
 *     this.load.glsl('fire', 'shaders/fire.glsl.js');
 * }
 *
 * function create ()
 * {
 *     this.add.shader('fire', 400, 300, 512, 512);
 * }
 * ```
 *
 * Please see the Phaser 3 Examples GitHub repo for examples of loading and creating shaders dynamically.
 *
 * Due to the way in which they work, you cannot directly change the alpha or blend mode of a Shader. This should
 * be handled via exposed uniforms in the shader code itself.
 *
 * By default a Shader will be created with a standard set of uniforms. These were added to match those
 * found on sites such as ShaderToy or GLSLSandbox, and provide common functionality a shader may need,
 * such as the timestamp, resolution or pointer position. You can replace them by specifying your own uniforms
 * in the Base Shader.
 *
 * These Shaders work by halting the current pipeline during rendering, creating a viewport matched to the
 * size of this Game Object and then renders a quad using the bound shader. At the end, the pipeline is restored.
 *
 * Because it blocks the pipeline it means it will interrupt any batching that is currently going on, so you should
 * use these Game Objects sparingly. If you need to have a fully batched custom shader, then please look at using
 * a custom pipeline instead. However, for background or special masking effects, they are extremely effective.
 *
 * @class Shader
 * @extends Phaser.GameObjects.GameObject
 * @memberof Phaser.GameObjects
 * @constructor
 * @webglOnly
 * @since 3.17.0
 *
 * @extends Phaser.GameObjects.Components.ComputedSize
 * @extends Phaser.GameObjects.Components.Depth
 * @extends Phaser.GameObjects.Components.GetBounds
 * @extends Phaser.GameObjects.Components.Mask
 * @extends Phaser.GameObjects.Components.Origin
 * @extends Phaser.GameObjects.Components.ScrollFactor
 * @extends Phaser.GameObjects.Components.Transform
 * @extends Phaser.GameObjects.Components.Visible
 *
 * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
 * @param {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance.
 * @param {number} [x=0] - The horizontal position of this Game Object in the world.
 * @param {number} [y=0] - The vertical position of this Game Object in the world.
 * @param {number} [width=128] - The width of the Game Object.
 * @param {number} [height=128] - The height of the Game Object.
 * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager.
 * @param {any} [textureData] - Additional texture data if you want to create shader with none NPOT textures.
 */
var Shader = new Class({

    Extends: GameObject,

    Mixins: [
        Components.ComputedSize,
        Components.Depth,
        Components.GetBounds,
        Components.Mask,
        Components.Origin,
        Components.ScrollFactor,
        Components.Transform,
        Components.Visible,
        ShaderRender
    ],

    initialize:

    function Shader (scene, key, x, y, width, height, textures, textureData)
    {
        if (x === undefined) { x = 0; }
        if (y === undefined) { y = 0; }
        if (width === undefined) { width = 128; }
        if (height === undefined) { height = 128; }

        GameObject.call(this, scene, 'Shader');

        /**
         * This Game Object cannot have a blend mode, so skip all checks.
         *
         * @name Phaser.GameObjects.Shader#blendMode
         * @type {number}
         * @private
         * @since 3.17.0
         */
        this.blendMode = -1;

        /**
         * The underlying shader object being used.
         * Empty by default and set during a call to the `setShader` method.
         *
         * @name Phaser.GameObjects.Shader#shader
         * @type {Phaser.Display.BaseShader}
         * @since 3.17.0
         */
        this.shader;

        var renderer = scene.sys.renderer;

        /**
         * A reference to the current renderer.
         * Shaders only work with the WebGL Renderer.
         *
         * @name Phaser.GameObjects.Shader#renderer
         * @type {(Phaser.Renderer.Canvas.CanvasRenderer|Phaser.Renderer.WebGL.WebGLRenderer)}
         * @since 3.17.0
         */
        this.renderer = renderer;

        /**
         * The WebGL context belonging to the renderer.
         *
         * @name Phaser.GameObjects.Shader#gl
         * @type {WebGLRenderingContext}
         * @since 3.17.0
         */
        this.gl = renderer.gl;

        /**
         * Raw byte buffer of vertices this Shader uses.
         *
         * @name Phaser.GameObjects.Shader#vertexData
         * @type {ArrayBuffer}
         * @since 3.17.0
         */
        this.vertexData = new ArrayBuffer(6 * (Float32Array.BYTES_PER_ELEMENT * 2));

        /**
         * The WebGL vertex buffer object this shader uses.
         *
         * @name Phaser.GameObjects.Shader#vertexBuffer
         * @type {WebGLBuffer}
         * @since 3.17.0
         */
        this.vertexBuffer = renderer.createVertexBuffer(this.vertexData.byteLength, this.gl.STREAM_DRAW);

        /**
         * The WebGL shader program this shader uses.
         *
         * @name Phaser.GameObjects.Shader#program
         * @type {WebGLProgram}
         * @since 3.17.0
         */
        this.program = null;

        /**
         * Uint8 view to the vertex raw buffer. Used for uploading vertex buffer resources to the GPU.
         *
         * @name Phaser.GameObjects.Shader#bytes
         * @type {Uint8Array}
         * @since 3.17.0
         */
        this.bytes = new Uint8Array(this.vertexData);

        /**
         * Float32 view of the array buffer containing the shaders vertices.
         *
         * @name Phaser.GameObjects.Shader#vertexViewF32
         * @type {Float32Array}
         * @since 3.17.0
         */
        this.vertexViewF32 = new Float32Array(this.vertexData);

        /**
         * A temporary Transform Matrix, re-used internally during batching.
         *
         * @name Phaser.GameObjects.Shader#_tempMatrix1
         * @private
         * @type {Phaser.GameObjects.Components.TransformMatrix}
         * @since 3.17.0
         */
        this._tempMatrix1 = new TransformMatrix();

        /**
         * A temporary Transform Matrix, re-used internally during batching.
         *
         * @name Phaser.GameObjects.Shader#_tempMatrix2
         * @private
         * @type {Phaser.GameObjects.Components.TransformMatrix}
         * @since 3.17.0
         */
        this._tempMatrix2 = new TransformMatrix();

        /**
         * A temporary Transform Matrix, re-used internally during batching.
         *
         * @name Phaser.GameObjects.Shader#_tempMatrix3
         * @private
         * @type {Phaser.GameObjects.Components.TransformMatrix}
         * @since 3.17.0
         */
        this._tempMatrix3 = new TransformMatrix();

        /**
         * The view matrix the shader uses during rendering.
         *
         * @name Phaser.GameObjects.Shader#viewMatrix
         * @type {Float32Array}
         * @readonly
         * @since 3.17.0
         */
        this.viewMatrix = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]);

        /**
         * The projection matrix the shader uses during rendering.
         *
         * @name Phaser.GameObjects.Shader#projectionMatrix
         * @type {Float32Array}
         * @readonly
         * @since 3.17.0
         */
        this.projectionMatrix = new Float32Array([ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]);

        /**
         * The default uniform mappings. These can be added to (or replaced) by specifying your own uniforms when
         * creating this shader game object. The uniforms are updated automatically during the render step.
         *
         * The defaults are:
         *
         * `resolution` (2f) - Set to the size of this shader.
         * `time` (1f) - The elapsed game time, in seconds.
         * `mouse` (2f) - If a pointer has been bound (with `setPointer`), this uniform contains its position each frame.
         * `date` (4fv) - A vec4 containing the year, month, day and time in seconds.
         * `sampleRate` (1f) - Sound sample rate. 44100 by default.
         * `iChannel0...3` (sampler2D) - Input channels 0 to 3. `null` by default.
         *
         * @name Phaser.GameObjects.Shader#uniforms
         * @type {any}
         * @since 3.17.0
         */
        this.uniforms = {};

        /**
         * The pointer bound to this shader, if any.
         * Set via the chainable `setPointer` method, or by modifying this property directly.
         *
         * @name Phaser.GameObjects.Shader#pointer
         * @type {Phaser.Input.Pointer}
         * @since 3.17.0
         */
        this.pointer = null;

        /**
         * The cached width of the renderer.
         *
         * @name Phaser.GameObjects.Shader#_rendererWidth
         * @type {number}
         * @private
         * @since 3.17.0
         */
        this._rendererWidth = renderer.width;

        /**
         * The cached height of the renderer.
         *
         * @name Phaser.GameObjects.Shader#_rendererHeight
         * @type {number}
         * @private
         * @since 3.17.0
         */
        this._rendererHeight = renderer.height;

        /**
         * Internal texture count tracker.
         *
         * @name Phaser.GameObjects.Shader#_textureCount
         * @type {number}
         * @private
         * @since 3.17.0
         */
        this._textureCount = 0;

        /**
         * A reference to the GL Frame Buffer this Shader is drawing to.
         * This property is only set if you have called `Shader.setRenderToTexture`.
         *
         * @name Phaser.GameObjects.Shader#framebuffer
         * @type {?WebGLFramebuffer}
         * @since 3.19.0
         */
        this.framebuffer = null;

        /**
         * A reference to the WebGLTexture this Shader is rendering to.
         * This property is only set if you have called `Shader.setRenderToTexture`.
         *
         * @name Phaser.GameObjects.Shader#glTexture
         * @type {?WebGLTexture}
         * @since 3.19.0
         */
        this.glTexture = null;

        /**
         * A flag that indicates if this Shader has been set to render to a texture instead of the display list.
         *
         * This property is `true` if you have called `Shader.setRenderToTexture`, otherwise it's `false`.
         *
         * A Shader that is rendering to a texture _does not_ appear on the display list.
         *
         * @name Phaser.GameObjects.Shader#renderToTexture
         * @type {boolean}
         * @readonly
         * @since 3.19.0
         */
        this.renderToTexture = false;

        /**
         * A reference to the Phaser.Textures.Texture that has been stored in the Texture Manager for this Shader.
         *
         * This property is only set if you have called `Shader.setRenderToTexture`, otherwise it is `null`.
         *
         * @name Phaser.GameObjects.Shader#texture
         * @type {Phaser.Textures.Texture}
         * @since 3.19.0
         */
        this.texture = null;

        this.setPosition(x, y);
        this.setSize(width, height);
        this.setOrigin(0.5, 0.5);
        this.setShader(key, textures, textureData);
    },

    /**
     * Compares the renderMask with the renderFlags to see if this Game Object will render or not.
     * Also checks the Game Object against the given Cameras exclusion list.
     *
     * @method Phaser.GameObjects.Shader#willRender
     * @since 3.0.0
     *
     * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera to check against this Game Object.
     *
     * @return {boolean} True if the Game Object should be rendered, otherwise false.
     */
    willRender: function (camera)
    {
        if (this.renderToTexture)
        {
            return true;
        }
        else
        {
            return !(GameObject.RENDER_MASK !== this.renderFlags || (this.cameraFilter !== 0 && (this.cameraFilter & camera.id)));
        }
    },

    /**
     * Changes this Shader so instead of rendering to the display list it renders to a
     * WebGL Framebuffer and WebGL Texture instead. This allows you to use the output
     * of this shader as an input for another shader, by mapping a sampler2D uniform
     * to it.
     *
     * After calling this method the `Shader.framebuffer` and `Shader.glTexture` properties
     * are populated.
     *
     * Additionally, you can provide a key to this method. Doing so will create a Phaser Texture
     * from this Shader and save it into the Texture Manager, allowing you to then use it for
     * any texture-based Game Object, such as a Sprite or Image:
     *
     * ```javascript
     * var shader = this.add.shader('myShader', x, y, width, height);
     *
     * shader.setRenderToTexture('doodle');
     *
     * this.add.image(400, 300, 'doodle');
     * ```
     *
     * Note that it stores an active reference to this Shader. That means as this shader updates,
     * so does the texture and any object using it to render with. Also, if you destroy this
     * shader, be sure to clear any objects that may have been using it as a texture too.
     *
     * You can access the Phaser Texture that is created via the `Shader.texture` property.
     *
     * By default it will create a single base texture. You can add frames to the texture
     * by using the `Texture.add` method. After doing this, you can then allow Game Objects
     * to use a specific frame from a Render Texture.
     *
     * @method Phaser.GameObjects.Shader#setRenderToTexture
     * @since 3.19.0
     *
     * @param {string} [key] - The unique key to store the texture as within the global Texture Manager.
     * @param {boolean} [flipY=false] - Does this texture need vertically flipping before rendering? This should usually be set to `true` if being fed from a buffer.
     *
     * @return {this} This Shader instance.
     */
    setRenderToTexture: function (key, flipY)
    {
        if (flipY === undefined) { flipY = false; }

        if (!this.renderToTexture)
        {
            var width = this.width;
            var height = this.height;
            var renderer = this.renderer;

            this.glTexture = renderer.createTextureFromSource(null, width, height, 0);

            this.glTexture.flipY = flipY;

            this.framebuffer = renderer.createFramebuffer(width, height, this.glTexture, false);

            this._rendererWidth = width;
            this._rendererHeight = height;

            this.renderToTexture = true;

            this.projOrtho(0, this.width, this.height, 0);

            if (key)
            {
                this.texture = this.scene.sys.textures.addGLTexture(key, this.glTexture, width, height);
            }
        }

        //  And now render at least once, so our texture isn't blank on the first update

        if (this.shader)
        {
            renderer.pipelines.clear();

            this.load();
            this.flush();

            renderer.pipelines.rebind();
        }

        return this;
    },

    /**
     * Sets the fragment and, optionally, the vertex shader source code that this Shader will use.
     * This will immediately delete the active shader program, if set, and then create a new one
     * with the given source. Finally, the shader uniforms are initialized.
     *
     * @method Phaser.GameObjects.Shader#setShader
     * @since 3.17.0
     *
     * @param {(string|Phaser.Display.BaseShader)} key - The key of the shader to use from the shader cache, or a BaseShader instance.
     * @param {string[]} [textures] - Optional array of texture keys to bind to the iChannel0...3 uniforms. The textures must already exist in the Texture Manager.
     * @param {any} [textureData] - Additional texture data.
     *
     * @return {this} This Shader instance.
     */
    setShader: function (key, textures, textureData)
    {
        if (textures === undefined) { textures = []; }

        if (typeof key === 'string')
        {
            var cache = this.scene.sys.cache.shader;

            if (!cache.has(key))
            {
                console.warn('Shader missing: ' + key);
                return this;
            }

            this.shader = cache.get(key);
        }
        else
        {
            this.shader = key;
        }

        var gl = this.gl;
        var renderer = this.renderer;

        if (this.program)
        {
            gl.deleteProgram(this.program);
        }

        var program = renderer.createProgram(this.shader.vertexSrc, this.shader.fragmentSrc);

        //  The default uniforms available within the vertex shader
        gl.uniformMatrix4fv(gl.getUniformLocation(program, 'uViewMatrix'), false, this.viewMatrix);
        gl.uniformMatrix4fv(gl.getUniformLocation(program, 'uProjectionMatrix'), false, this.projectionMatrix);
        gl.uniform2f(gl.getUniformLocation(program, 'uResolution'), this.width, this.height);

        this.program = program;

        var d = new Date();

        //  The default uniforms available within the fragment shader
        var defaultUniforms = {
            resolution: { type: '2f', value: { x: this.width, y: this.height } },
            time: { type: '1f', value: 0 },
            mouse: { type: '2f', value: { x: this.width / 2, y: this.height / 2 } },
            date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() * 60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] },
            sampleRate: { type: '1f', value: 44100.0 },
            iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } },
            iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } },
            iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } },
            iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } }
        };

        if (this.shader.uniforms)
        {
            this.uniforms = Extend(true, {}, this.shader.uniforms, defaultUniforms);
        }
        else
        {
            this.uniforms = defaultUniforms;
        }

        for (var i = 0; i < 4; i++)
        {
            if (textures[i])
            {
                this.setSampler2D('iChannel' + i, textures[i], i, textureData);
            }
        }

        this.initUniforms();

        this.projOrtho(0, this._rendererWidth, this._rendererHeight, 0);

        return this;
    },

    /**
     * Binds a Phaser Pointer object to this Shader.
     *
     * The screen position of the pointer will be set in to the shaders `mouse` uniform
     * automatically every frame. Call this method with no arguments to unbind the pointer.
     *
     * @method Phaser.GameObjects.Shader#setPointer
     * @since 3.17.0
     *
     * @param {Phaser.Input.Pointer} [pointer] - The Pointer to bind to this shader.
     *
     * @return {this} This Shader instance.
     */
    setPointer: function (pointer)
    {
        this.pointer = pointer;

        return this;
    },

    /**
     * Sets this shader to use an orthographic projection matrix.
     * This matrix is stored locally in the `projectionMatrix` property,
     * as well as being bound to the `uProjectionMatrix` uniform.
     *
     * @method Phaser.GameObjects.Shader#projOrtho
     * @since 3.17.0
     *
     * @param {number} left - The left value.
     * @param {number} right - The right value.
     * @param {number} bottom - The bottom value.
     * @param {number} top - The top value.
     */
    projOrtho: function (left, right, bottom, top)
    {
        var near = -1000;
        var far = 1000;

        var leftRight = 1 / (left - right);
        var bottomTop = 1 / (bottom - top);
        var nearFar = 1 / (near - far);

        var pm = this.projectionMatrix;

        pm[0] = -2 * leftRight;
        pm[5] = -2 * bottomTop;
        pm[10] = 2 * nearFar;
        pm[12] = (left + right) * leftRight;
        pm[13] = (top + bottom) * bottomTop;
        pm[14] = (far + near) * nearFar;

        var program = this.program;

        var gl = this.gl;
        var renderer = this.renderer;

        renderer.setProgram(program);

        gl.uniformMatrix4fv(gl.getUniformLocation(program, 'uProjectionMatrix'), false, this.projectionMatrix);

        this._rendererWidth = right;
        this._rendererHeight = bottom;
    },

    // Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/
    // http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf

    /**
     * Initializes all of the uniforms this shader uses.
     *
     * @method Phaser.GameObjects.Shader#initUniforms
     * @private
     * @since 3.17.0
     */
    initUniforms: function ()
    {
        var gl = this.gl;
        var map = this.renderer.glFuncMap;
        var program = this.program;

        this._textureCount = 0;

        for (var key in this.uniforms)
        {
            var uniform = this.uniforms[key];

            var type = uniform.type;
            var data = map[type];

            uniform.uniformLocation = gl.getUniformLocation(program, key);

            if (type !== 'sampler2D')
            {
                uniform.glMatrix = data.matrix;
                uniform.glValueLength = data.length;
                uniform.glFunc = data.func;
            }
        }
    },

    /**
     * Sets a sampler2D uniform on this shader where the source texture is a WebGLTexture.
     *
     * This allows you to feed the output from one Shader into another:
     *
     * ```javascript
     * let shader1 = this.add.shader(baseShader1, 0, 0, 512, 512).setRenderToTexture();
     * let shader2 = this.add.shader(baseShader2, 0, 0, 512, 512).setRenderToTexture('output');
     *
     * shader1.setSampler2DBuffer('iChannel0', shader2.glTexture, 512, 512);
     * shader2.setSampler2DBuffer('iChannel0', shader1.glTexture, 512, 512);
     * ```
     *
     * In the above code, the result of baseShader1 is fed into Shader2 as the `iChannel0` sampler2D uniform.
     * The result of baseShader2 is then fed back into shader1 again, creating a feedback loop.
     *
     * If you wish to use an image from the Texture Manager as a sampler2D input for this shader,
     * see the `Shader.setSampler2D` method.
     *
     * @method Phaser.GameObjects.Shader#setSampler2DBuffer
     * @since 3.19.0
     *
     * @param {string} uniformKey - The key of the sampler2D uniform to be updated, i.e. `iChannel0`.
     * @param {WebGLTexture} texture - A WebGLTexture reference.
     * @param {number} width - The width of the texture.
     * @param {number} height - The height of the texture.
     * @param {number} [textureIndex=0] - The texture index.
     * @param {any} [textureData] - Additional texture data.
     *
     * @return {this} This Shader instance.
     */
    setSampler2DBuffer: function (uniformKey, texture, width, height, textureIndex, textureData)
    {
        if (textureIndex === undefined) { textureIndex = 0; }
        if (textureData === undefined) { textureData = {}; }

        var uniform = this.uniforms[uniformKey];

        uniform.value = texture;

        textureData.width = width;
        textureData.height = height;

        uniform.textureData = textureData;

        this._textureCount = textureIndex;

        this.initSampler2D(uniform);

        return this;
    },

    /**
     * Sets a sampler2D uniform on this shader.
     *
     * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame
     * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized.
     *
     * If you wish to use another Shader as a sampler2D input for this shader, see the `Shader.setSampler2DBuffer` method.
     *
     * @method Phaser.GameObjects.Shader#setSampler2D
     * @since 3.17.0
     *
     * @param {string} uniformKey - The key of the sampler2D uniform to be updated, i.e. `iChannel0`.
     * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded.
     * @param {number} [textureIndex=0] - The texture index.
     * @param {any} [textureData] - Additional texture data.
     *
     * @return {this} This Shader instance.
     */
    setSampler2D: function (uniformKey, textureKey, textureIndex, textureData)
    {
        if (textureIndex === undefined) { textureIndex = 0; }

        var textureManager = this.scene.sys.textures;

        if (textureManager.exists(textureKey))
        {
            var frame = textureManager.getFrame(textureKey);
            var uniform = this.uniforms[uniformKey];
            var source = frame.source;

            uniform.textureKey = textureKey;
            uniform.source = source.image;
            uniform.value = frame.glTexture;

            if (source.isGLTexture)
            {
                if (!textureData)
                {
                    textureData = {};
                }

                textureData.width = source.width;
                textureData.height = source.height;
            }

            if (textureData)
            {
                uniform.textureData = textureData;
            }

            this._textureCount = textureIndex;

            this.initSampler2D(uniform);
        }

        return this;
    },

    /**
     * Sets a property of a uniform already present on this shader.
     *
     * To modify the value of a uniform such as a 1f or 1i use the `value` property directly:
     *
     * ```javascript
     * shader.setUniform('size.value', 16);
     * ```
     *
     * You can use dot notation to access deeper values, for example:
     *
     * ```javascript
     * shader.setUniform('resolution.value.x', 512);
     * ```
     *
     * The change to the uniform will take effect the next time the shader is rendered.
     *
     * @method Phaser.GameObjects.Shader#setUniform
     * @since 3.17.0
     *
     * @param {string} key - The key of the uniform to modify. Use dots for deep properties, i.e. `resolution.value.x`.
     * @param {any} value - The value to set into the uniform.
     *
     * @return {this} This Shader instance.
     */
    setUniform: function (key, value)
    {
        SetValue(this.uniforms, key, value);

        return this;
    },

    /**
     * Returns the uniform object for the given key, or `null` if the uniform couldn't be found.
     *
     * @method Phaser.GameObjects.Shader#getUniform
     * @since 3.17.0
     *
     * @param {string} key - The key of the uniform to return the value for.
     *
     * @return {any} A reference to the uniform object. This is not a copy, so modifying it will update the original object also.
     */
    getUniform: function (key)
    {
        return GetFastValue(this.uniforms, key, null);
    },

    /**
     * A short-cut method that will directly set the texture being used by the `iChannel0` sampler2D uniform.
     *
     * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame
     * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized.
     *
     * @method Phaser.GameObjects.Shader#setChannel0
     * @since 3.17.0
     *
     * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded.
     * @param {any} [textureData] - Additional texture data.
     *
     * @return {this} This Shader instance.
     */
    setChannel0: function (textureKey, textureData)
    {
        return this.setSampler2D('iChannel0', textureKey, 0, textureData);
    },

    /**
     * A short-cut method that will directly set the texture being used by the `iChannel1` sampler2D uniform.
     *
     * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame
     * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized.
     *
     * @method Phaser.GameObjects.Shader#setChannel1
     * @since 3.17.0
     *
     * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded.
     * @param {any} [textureData] - Additional texture data.
     *
     * @return {this} This Shader instance.
     */
    setChannel1: function (textureKey, textureData)
    {
        return this.setSampler2D('iChannel1', textureKey, 1, textureData);
    },

    /**
     * A short-cut method that will directly set the texture being used by the `iChannel2` sampler2D uniform.
     *
     * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame
     * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized.
     *
     * @method Phaser.GameObjects.Shader#setChannel2
     * @since 3.17.0
     *
     * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded.
     * @param {any} [textureData] - Additional texture data.
     *
     * @return {this} This Shader instance.
     */
    setChannel2: function (textureKey, textureData)
    {
        return this.setSampler2D('iChannel2', textureKey, 2, textureData);
    },

    /**
     * A short-cut method that will directly set the texture being used by the `iChannel3` sampler2D uniform.
     *
     * The textureKey given is the key from the Texture Manager cache. You cannot use a single frame
     * from a texture, only the full image. Also, lots of shaders expect textures to be power-of-two sized.
     *
     * @method Phaser.GameObjects.Shader#setChannel3
     * @since 3.17.0
     *
     * @param {string} textureKey - The key of the texture, as stored in the Texture Manager. Must already be loaded.
     * @param {any} [textureData] - Additional texture data.
     *
     * @return {this} This Shader instance.
     */
    setChannel3: function (textureKey, textureData)
    {
        return this.setSampler2D('iChannel3', textureKey, 3, textureData);
    },

    /**
     * Internal method that takes a sampler2D uniform and prepares it for use by setting the
     * gl texture parameters.
     *
     * @method Phaser.GameObjects.Shader#initSampler2D
     * @private
     * @since 3.17.0
     *
     * @param {any} uniform - The sampler2D uniform to process.
     */
    initSampler2D: function (uniform)
    {
        if (!uniform.value)
        {
            return;
        }

        var gl = this.gl;

        gl.activeTexture(gl.TEXTURE0 + this._textureCount);
        gl.bindTexture(gl.TEXTURE_2D, uniform.value);

        //  Extended texture data

        var data = uniform.textureData;

        if (data)
        {
            // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texImage2D

            //  mag / minFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST
            //  wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT
            //  format can be: gl.LUMINANCE or gl.RGBA

            var magFilter = gl[GetFastValue(data, 'magFilter', 'linear').toUpperCase()];
            var minFilter = gl[GetFastValue(data, 'minFilter', 'linear').toUpperCase()];
            var wrapS = gl[GetFastValue(data, 'wrapS', 'repeat').toUpperCase()];
            var wrapT = gl[GetFastValue(data, 'wrapT', 'repeat').toUpperCase()];
            var format = gl[GetFastValue(data, 'format', 'rgba').toUpperCase()];

            if (data.repeat)
            {
                wrapS = gl.REPEAT;
                wrapT = gl.REPEAT;
            }

            gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY);

            if (data.width)
            {
                var width = GetFastValue(data, 'width', 512);
                var height = GetFastValue(data, 'height', 2);
                var border = GetFastValue(data, 'border', 0);

                //  texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels)
                gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null);
            }
            else
            {
                //  texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels)
                gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, uniform.source);
            }

            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT);
        }

        this.renderer.setProgram(this.program);

        gl.uniform1i(uniform.uniformLocation, this._textureCount);

        this._textureCount++;
    },

    /**
     * Synchronizes all of the uniforms this shader uses.
     * Each uniforms gl function is called in turn.
     *
     * @method Phaser.GameObjects.Shader#syncUniforms
     * @private
     * @since 3.17.0
     */
    syncUniforms: function ()
    {
        var gl = this.gl;

        var uniforms = this.uniforms;
        var uniform;
        var length;
        var glFunc;
        var location;
        var value;
        var textureCount = 0;

        for (var key in uniforms)
        {
            uniform = uniforms[key];

            glFunc = uniform.glFunc;
            length = uniform.glValueLength;
            location = uniform.uniformLocation;
            value = uniform.value;

            if (value === null)
            {
                continue;
            }

            if (length === 1)
            {
                if (uniform.glMatrix)
                {
                    glFunc.call(gl, location, uniform.transpose, value);
                }
                else
                {
                    glFunc.call(gl, location, value);
                }
            }
            else if (length === 2)
            {
                glFunc.call(gl, location, value.x, value.y);
            }
            else if (length === 3)
            {
                glFunc.call(gl, location, value.x, value.y, value.z);
            }
            else if (length === 4)
            {
                glFunc.call(gl, location, value.x, value.y, value.z, value.w);
            }
            else if (uniform.type === 'sampler2D')
            {
                gl.activeTexture(gl['TEXTURE' + textureCount]);

                gl.bindTexture(gl.TEXTURE_2D, value);

                gl.uniform1i(location, textureCount);

                textureCount++;
            }
        }
    },

    /**
     * Called automatically during render.
     *
     * This method performs matrix ITRS and then stores the resulting value in the `uViewMatrix` uniform.
     * It then sets up the vertex buffer and shader, updates and syncs the uniforms ready
     * for flush to be called.
     *
     * @method Phaser.GameObjects.Shader#load
     * @since 3.17.0
     *
     * @param {Phaser.GameObjects.Components.TransformMatrix} [matrix2D] - The transform matrix to use during rendering.
     */
    load: function (matrix2D)
    {
        //  ITRS

        var gl = this.gl;
        var width = this.width;
        var height = this.height;
        var renderer = this.renderer;
        var program = this.program;
        var vm = this.viewMatrix;

        if (!this.renderToTexture)
        {
            var x = -this._displayOriginX;
            var y = -this._displayOriginY;

            vm[0] = matrix2D[0];
            vm[1] = matrix2D[1];
            vm[4] = matrix2D[2];
            vm[5] = matrix2D[3];
            vm[8] = matrix2D[4];
            vm[9] = matrix2D[5];
            vm[12] = vm[0] * x + vm[4] * y;
            vm[13] = vm[1] * x + vm[5] * y;
        }

        //  Update vertex shader uniforms

        gl.useProgram(program);

        gl.uniformMatrix4fv(gl.getUniformLocation(program, 'uViewMatrix'), false, vm);
        gl.uniform2f(gl.getUniformLocation(program, 'uResolution'), this.width, this.height);

        //  Update fragment shader uniforms

        var uniforms = this.uniforms;
        var res = uniforms.resolution;

        res.value.x = width;
        res.value.y = height;

        uniforms.time.value = renderer.game.loop.getDuration();

        var pointer = this.pointer;

        if (pointer)
        {
            var mouse = uniforms.mouse;

            var px = pointer.x / width;
            var py = 1 - pointer.y / height;

            mouse.value.x = px.toFixed(2);
            mouse.value.y = py.toFixed(2);
        }

        this.syncUniforms();
    },

    /**
     * Called automatically during render.
     *
     * Sets the active shader, loads the vertex buffer and then draws.
     *
     * @method Phaser.GameObjects.Shader#flush
     * @since 3.17.0
     */
    flush: function ()
    {
        //  Bind

        var width = this.width;
        var height = this.height;
        var program = this.program;

        var gl = this.gl;
        var vertexBuffer = this.vertexBuffer;
        var renderer = this.renderer;
        var vertexSize = Float32Array.BYTES_PER_ELEMENT * 2;

        if (this.renderToTexture)
        {
            renderer.setFramebuffer(this.framebuffer);

            gl.clearColor(0, 0, 0, 0);

            gl.clear(gl.COLOR_BUFFER_BIT);
        }

        gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);

        var location = gl.getAttribLocation(program, 'inPosition');

        if (location !== -1)
        {
            gl.enableVertexAttribArray(location);

            gl.vertexAttribPointer(location, 2, gl.FLOAT, false, vertexSize, 0);
        }

        //  Draw

        var vf = this.vertexViewF32;

        vf[3] = height;
        vf[4] = width;
        vf[5] = height;
        vf[8] = width;
        vf[9] = height;
        vf[10] = width;

        //  Flush

        var vertexCount = 6;

        gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.bytes.subarray(0, vertexCount * vertexSize));

        gl.drawArrays(gl.TRIANGLES, 0, vertexCount);

        if (this.renderToTexture)
        {
            renderer.setFramebuffer(null, false);
        }
    },

    /**
     * A NOOP method so you can pass a Shader to a Container.
     * Calling this method will do nothing. It is intentionally empty.
     *
     * @method Phaser.GameObjects.Shader#setAlpha
     * @private
     * @since 3.17.0
     */
    setAlpha: function ()
    {
    },

    /**
     * A NOOP method so you can pass a Shader to a Container.
     * Calling this method will do nothing. It is intentionally empty.
     *
     * @method Phaser.GameObjects.Shader#setBlendMode
     * @private
     * @since 3.17.0
     */
    setBlendMode: function ()
    {
    },

    /**
     * Internal destroy handler, called as part of the destroy process.
     *
     * @method Phaser.GameObjects.Shader#preDestroy
     * @protected
     * @since 3.17.0
     */
    preDestroy: function ()
    {
        var gl = this.gl;

        gl.deleteProgram(this.program);
        gl.deleteBuffer(this.vertexBuffer);

        if (this.renderToTexture)
        {
            this.renderer.deleteFramebuffer(this.framebuffer);

            this.texture.destroy();

            this.framebuffer = null;
            this.glTexture = null;
            this.texture = null;
        }
    }

});

module.exports = Shader;


/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

var CONST = require('../const/ORIENTATION_CONST');
var NOOP = require('../../utils/NOOP');
var WorldToTileX = require('./WorldToTileX');

/**
 * Gets the correct function to use to translate tiles, based on the map orientation.
 *
 * @function Phaser.Tilemaps.Components.GetWorldToTileXFunction
 * @since 3.50.0
 *
 * @param {number} orientation - The Tilemap orientation constant.
 *
 * @return {function} The function to use to translate tiles for the given map type.
 */
var GetWorldToTileXFunction = function (orientation)
{
    if (orientation === CONST.ORTHOGONAL)
    {
        return WorldToTileX;
    }
    else
    {
        return NOOP;
    }
};

module.exports = GetWorldToTileXFunction;


/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

/**
 * @namespace Phaser.Scenes.Events
 */

module.exports = {

    ADDED_TO_SCENE: require('./ADDED_TO_SCENE_EVENT'),
    BOOT: require('./BOOT_EVENT'),
    CREATE: require('./CREATE_EVENT'),
    DESTROY: require('./DESTROY_EVENT'),
    PAUSE: require('./PAUSE_EVENT'),
    POST_UPDATE: require('./POST_UPDATE_EVENT'),
    PRE_UPDATE: require('./PRE_UPDATE_EVENT'),
    READY: require('./READY_EVENT'),
    REMOVED_FROM_SCENE: require('./REMOVED_FROM_SCENE_EVENT'),
    RENDER: require('./RENDER_EVENT'),
    RESUME: require('./RESUME_EVENT'),
    SHUTDOWN: require('./SHUTDOWN_EVENT'),
    SLEEP: require('./SLEEP_EVENT'),
    START: require('./START_EVENT'),
    TRANSITION_COMPLETE: require('./TRANSITION_COMPLETE_EVENT'),
    TRANSITION_INIT: require('./TRANSITION_INIT_EVENT'),
    TRANSITION_OUT: require('./TRANSITION_OUT_EVENT'),
    TRANSITION_START: require('./TRANSITION_START_EVENT'),
    TRANSITION_WAKE: require('./TRANSITION_WAKE_EVENT'),
    UPDATE: require('./UPDATE_EVENT'),
    WAKE: require('./WAKE_EVENT')

};


/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2020 Photon Storm Ltd.
 * @license      {@link https://opensource.org/licenses/MIT|MIT License}
 */

/**
 * Provides methods used for setting the acceleration properties of an Arcade Physics Body.
 *
 * @namespace Phaser.Physics.Arcade.Components.Acceleration
 * @since 3.0.0
 */
var Acceleration = {

    /**
     * Sets the body's horizontal and vertical acceleration. If the vertical acceleration value is not provided, the vertical acceleration is set to the same value as the horizontal acceleration.
     *
     * @method Phaser.Physics.Arcade.Components.Acceleration#setAcceleration
     * @since 3.0.0
     *
     * @param {number} x - The horizontal acceleration
     * @param {number} [y=x] - The vertical acceleration
     *
     * @return {this} This Game Object.
     */
    setAcceleration: function (x, y)
    {
        this.body.acceleration.set(x, y);

        return this;
    },

    /**
     * Sets the body's horizontal acceleration.
     *
     * @method Phaser.Physics.Arcade.Components.Acceleration#setAccelerationX
     * @since 3.0.0
     *
     * @param {number} value - The horizontal acceleration
     *
     * @return {this} This Game Object.
     */
    setAccelerationX: function (value)
    {
        this.body.acceleration.x = value;

        return this;
    },

    /**
     * Sets the body's vertical acceleration.
     *
     * @method Phaser.Physics.Arcade.Components.Acceleration#setAccelerationY
     * @since 3.0.0
     *
     * @param {number} value - The vertical acceleration
     *
     * @return {this} This Game Object.
     */
    setAccelerationY: function (value)
    {
        this.body.acceleration.y = value;

        return this;
    }

};

module.exports = Acceleration;