var KTMap = (function (exports, three) {
	'use strict';

	var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

	var collectionUtils = {exports: {}};

	var utils$3 = collectionUtils.exports = {};

	/**
	 * Loops through the collection and calls the callback for each element. if the callback returns truthy, the loop is broken and returns the same value.
	 * @public
	 * @param {*} collection The collection to loop through. Needs to have a length property set and have indices set from 0 to length - 1.
	 * @param {function} callback The callback to be called for each element. The element will be given as a parameter to the callback. If this callback returns truthy, the loop is broken and the same value is returned.
	 * @returns {*} The value that a callback has returned (if truthy). Otherwise nothing.
	 */
	utils$3.forEach = function(collection, callback) {
	    for(var i = 0; i < collection.length; i++) {
	        var result = callback(collection[i]);
	        if(result) {
	            return result;
	        }
	    }
	};

	var elementUtils = function(options) {
	    var getState = options.stateHandler.getState;

	    /**
	     * Tells if the element has been made detectable and ready to be listened for resize events.
	     * @public
	     * @param {element} The element to check.
	     * @returns {boolean} True or false depending on if the element is detectable or not.
	     */
	    function isDetectable(element) {
	        var state = getState(element);
	        return state && !!state.isDetectable;
	    }

	    /**
	     * Marks the element that it has been made detectable and ready to be listened for resize events.
	     * @public
	     * @param {element} The element to mark.
	     */
	    function markAsDetectable(element) {
	        getState(element).isDetectable = true;
	    }

	    /**
	     * Tells if the element is busy or not.
	     * @public
	     * @param {element} The element to check.
	     * @returns {boolean} True or false depending on if the element is busy or not.
	     */
	    function isBusy(element) {
	        return !!getState(element).busy;
	    }

	    /**
	     * Marks the object is busy and should not be made detectable.
	     * @public
	     * @param {element} element The element to mark.
	     * @param {boolean} busy If the element is busy or not.
	     */
	    function markBusy(element, busy) {
	        getState(element).busy = !!busy;
	    }

	    return {
	        isDetectable: isDetectable,
	        markAsDetectable: markAsDetectable,
	        isBusy: isBusy,
	        markBusy: markBusy
	    };
	};

	var listenerHandler = function(idHandler) {
	    var eventListeners = {};

	    /**
	     * Gets all listeners for the given element.
	     * @public
	     * @param {element} element The element to get all listeners for.
	     * @returns All listeners for the given element.
	     */
	    function getListeners(element) {
	        var id = idHandler.get(element);

	        if (id === undefined) {
	            return [];
	        }

	        return eventListeners[id] || [];
	    }

	    /**
	     * Stores the given listener for the given element. Will not actually add the listener to the element.
	     * @public
	     * @param {element} element The element that should have the listener added.
	     * @param {function} listener The callback that the element has added.
	     */
	    function addListener(element, listener) {
	        var id = idHandler.get(element);

	        if(!eventListeners[id]) {
	            eventListeners[id] = [];
	        }

	        eventListeners[id].push(listener);
	    }

	    function removeListener(element, listener) {
	        var listeners = getListeners(element);
	        for (var i = 0, len = listeners.length; i < len; ++i) {
	            if (listeners[i] === listener) {
	              listeners.splice(i, 1);
	              break;
	            }
	        }
	    }

	    function removeAllListeners(element) {
	      var listeners = getListeners(element);
	      if (!listeners) { return; }
	      listeners.length = 0;
	    }

	    return {
	        get: getListeners,
	        add: addListener,
	        removeListener: removeListener,
	        removeAllListeners: removeAllListeners
	    };
	};

	var idGenerator = function() {
	    var idCount = 1;

	    /**
	     * Generates a new unique id in the context.
	     * @public
	     * @returns {number} A unique id in the context.
	     */
	    function generate() {
	        return idCount++;
	    }

	    return {
	        generate: generate
	    };
	};

	var idHandler = function(options) {
	    var idGenerator     = options.idGenerator;
	    var getState        = options.stateHandler.getState;

	    /**
	     * Gets the resize detector id of the element.
	     * @public
	     * @param {element} element The target element to get the id of.
	     * @returns {string|number|null} The id of the element. Null if it has no id.
	     */
	    function getId(element) {
	        var state = getState(element);

	        if (state && state.id !== undefined) {
	            return state.id;
	        }

	        return null;
	    }

	    /**
	     * Sets the resize detector id of the element. Requires the element to have a resize detector state initialized.
	     * @public
	     * @param {element} element The target element to set the id of.
	     * @returns {string|number|null} The id of the element.
	     */
	    function setId(element) {
	        var state = getState(element);

	        if (!state) {
	            throw new Error("setId required the element to have a resize detection state.");
	        }

	        var id = idGenerator.generate();

	        state.id = id;

	        return id;
	    }

	    return {
	        get: getId,
	        set: setId
	    };
	};

	/* global console: false */

	/**
	 * Reporter that handles the reporting of logs, warnings and errors.
	 * @public
	 * @param {boolean} quiet Tells if the reporter should be quiet or not.
	 */
	var reporter = function(quiet) {
	    function noop() {
	        //Does nothing.
	    }

	    var reporter = {
	        log: noop,
	        warn: noop,
	        error: noop
	    };

	    if(!quiet && window.console) {
	        var attachFunction = function(reporter, name) {
	            //The proxy is needed to be able to call the method with the console context,
	            //since we cannot use bind.
	            reporter[name] = function reporterProxy() {
	                var f = console[name];
	                if (f.apply) { //IE9 does not support console.log.apply :)
	                    f.apply(console, arguments);
	                } else {
	                    for (var i = 0; i < arguments.length; i++) {
	                        f(arguments[i]);
	                    }
	                }
	            };
	        };

	        attachFunction(reporter, "log");
	        attachFunction(reporter, "warn");
	        attachFunction(reporter, "error");
	    }

	    return reporter;
	};

	var browserDetector$2 = {exports: {}};

	var detector = browserDetector$2.exports = {};

	detector.isIE = function(version) {
	    function isAnyIeVersion() {
	        var agent = navigator.userAgent.toLowerCase();
	        return agent.indexOf("msie") !== -1 || agent.indexOf("trident") !== -1 || agent.indexOf(" edge/") !== -1;
	    }

	    if(!isAnyIeVersion()) {
	        return false;
	    }

	    if(!version) {
	        return true;
	    }

	    //Shamelessly stolen from https://gist.github.com/padolsey/527683
	    var ieVersion = (function(){
	        var undef,
	            v = 3,
	            div = document.createElement("div"),
	            all = div.getElementsByTagName("i");

	        do {
	            div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->";
	        }
	        while (all[0]);

	        return v > 4 ? v : undef;
	    }());

	    return version === ieVersion;
	};

	detector.isLegacyOpera = function() {
	    return !!window.opera;
	};

	var utils$2 = {exports: {}};

	var utils$1 = utils$2.exports = {};

	utils$1.getOption = getOption$1;

	function getOption$1(options, name, defaultValue) {
	    var value = options[name];

	    if((value === undefined || value === null) && defaultValue !== undefined) {
	        return defaultValue;
	    }

	    return value;
	}

	var utils = utils$2.exports;

	var batchProcessor = function batchProcessorMaker(options) {
	    options             = options || {};
	    var reporter        = options.reporter;
	    var asyncProcess    = utils.getOption(options, "async", true);
	    var autoProcess     = utils.getOption(options, "auto", true);

	    if(autoProcess && !asyncProcess) {
	        reporter && reporter.warn("Invalid options combination. auto=true and async=false is invalid. Setting async=true.");
	        asyncProcess = true;
	    }

	    var batch = Batch();
	    var asyncFrameHandler;
	    var isProcessing = false;

	    function addFunction(level, fn) {
	        if(!isProcessing && autoProcess && asyncProcess && batch.size() === 0) {
	            // Since this is async, it is guaranteed to be executed after that the fn is added to the batch.
	            // This needs to be done before, since we're checking the size of the batch to be 0.
	            processBatchAsync();
	        }

	        batch.add(level, fn);
	    }

	    function processBatch() {
	        // Save the current batch, and create a new batch so that incoming functions are not added into the currently processing batch.
	        // Continue processing until the top-level batch is empty (functions may be added to the new batch while processing, and so on).
	        isProcessing = true;
	        while (batch.size()) {
	            var processingBatch = batch;
	            batch = Batch();
	            processingBatch.process();
	        }
	        isProcessing = false;
	    }

	    function forceProcessBatch(localAsyncProcess) {
	        if (isProcessing) {
	            return;
	        }

	        if(localAsyncProcess === undefined) {
	            localAsyncProcess = asyncProcess;
	        }

	        if(asyncFrameHandler) {
	            cancelFrame(asyncFrameHandler);
	            asyncFrameHandler = null;
	        }

	        if(localAsyncProcess) {
	            processBatchAsync();
	        } else {
	            processBatch();
	        }
	    }

	    function processBatchAsync() {
	        asyncFrameHandler = requestFrame(processBatch);
	    }

	    function cancelFrame(listener) {
	        // var cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.clearTimeout;
	        var cancel = clearTimeout;
	        return cancel(listener);
	    }

	    function requestFrame(callback) {
	        // var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function(fn) { return window.setTimeout(fn, 20); };
	        var raf = function(fn) { return setTimeout(fn, 0); };
	        return raf(callback);
	    }

	    return {
	        add: addFunction,
	        force: forceProcessBatch
	    };
	};

	function Batch() {
	    var batch       = {};
	    var size        = 0;
	    var topLevel    = 0;
	    var bottomLevel = 0;

	    function add(level, fn) {
	        if(!fn) {
	            fn = level;
	            level = 0;
	        }

	        if(level > topLevel) {
	            topLevel = level;
	        } else if(level < bottomLevel) {
	            bottomLevel = level;
	        }

	        if(!batch[level]) {
	            batch[level] = [];
	        }

	        batch[level].push(fn);
	        size++;
	    }

	    function process() {
	        for(var level = bottomLevel; level <= topLevel; level++) {
	            var fns = batch[level];

	            for(var i = 0; i < fns.length; i++) {
	                var fn = fns[i];
	                fn();
	            }
	        }
	    }

	    function getSize() {
	        return size;
	    }

	    return {
	        add: add,
	        process: process,
	        size: getSize
	    };
	}

	var prop = "_erd";

	function initState(element) {
	    element[prop] = {};
	    return getState(element);
	}

	function getState(element) {
	    return element[prop];
	}

	function cleanState(element) {
	    delete element[prop];
	}

	var stateHandler$1 = {
	    initState: initState,
	    getState: getState,
	    cleanState: cleanState
	};

	/**
	 * Resize detection strategy that injects objects to elements in order to detect resize events.
	 * Heavily inspired by: http://www.backalleycoder.com/2013/03/18/cross-browser-event-based-element-resize-detection/
	 */

	var browserDetector$1 = browserDetector$2.exports;

	var object = function(options) {
	    options             = options || {};
	    var reporter        = options.reporter;
	    var batchProcessor  = options.batchProcessor;
	    var getState        = options.stateHandler.getState;

	    if(!reporter) {
	        throw new Error("Missing required dependency: reporter.");
	    }

	    /**
	     * Adds a resize event listener to the element.
	     * @public
	     * @param {element} element The element that should have the listener added.
	     * @param {function} listener The listener callback to be called for each resize event of the element. The element will be given as a parameter to the listener callback.
	     */
	    function addListener(element, listener) {
	        function listenerProxy() {
	            listener(element);
	        }

	        if(browserDetector$1.isIE(8)) {
	            //IE 8 does not support object, but supports the resize event directly on elements.
	            getState(element).object = {
	                proxy: listenerProxy
	            };
	            element.attachEvent("onresize", listenerProxy);
	        } else {
	            var object = getObject(element);

	            if(!object) {
	                throw new Error("Element is not detectable by this strategy.");
	            }

	            object.contentDocument.defaultView.addEventListener("resize", listenerProxy);
	        }
	    }

	    function buildCssTextString(rules) {
	        var seperator = options.important ? " !important; " : "; ";

	        return (rules.join(seperator) + seperator).trim();
	    }

	    /**
	     * Makes an element detectable and ready to be listened for resize events. Will call the callback when the element is ready to be listened for resize changes.
	     * @private
	     * @param {object} options Optional options object.
	     * @param {element} element The element to make detectable
	     * @param {function} callback The callback to be called when the element is ready to be listened for resize changes. Will be called with the element as first parameter.
	     */
	    function makeDetectable(options, element, callback) {
	        if (!callback) {
	            callback = element;
	            element = options;
	            options = null;
	        }

	        options = options || {};
	        options.debug;

	        function injectObject(element, callback) {
	            var OBJECT_STYLE = buildCssTextString(["display: block", "position: absolute", "top: 0", "left: 0", "width: 100%", "height: 100%", "border: none", "padding: 0", "margin: 0", "opacity: 0", "z-index: -1000", "pointer-events: none"]);

	            //The target element needs to be positioned (everything except static) so the absolute positioned object will be positioned relative to the target element.

	            // Position altering may be performed directly or on object load, depending on if style resolution is possible directly or not.
	            var positionCheckPerformed = false;

	            // The element may not yet be attached to the DOM, and therefore the style object may be empty in some browsers.
	            // Since the style object is a reference, it will be updated as soon as the element is attached to the DOM.
	            var style = window.getComputedStyle(element);
	            var width = element.offsetWidth;
	            var height = element.offsetHeight;

	            getState(element).startSize = {
	                width: width,
	                height: height
	            };

	            function mutateDom() {
	                function alterPositionStyles() {
	                    if(style.position === "static") {
	                        element.style.setProperty("position", "relative", options.important ? "important" : "");

	                        var removeRelativeStyles = function(reporter, element, style, property) {
	                            function getNumericalValue(value) {
	                                return value.replace(/[^-\d\.]/g, "");
	                            }

	                            var value = style[property];

	                            if(value !== "auto" && getNumericalValue(value) !== "0") {
	                                reporter.warn("An element that is positioned static has style." + property + "=" + value + " which is ignored due to the static positioning. The element will need to be positioned relative, so the style." + property + " will be set to 0. Element: ", element);
	                                element.style.setProperty(property, "0", options.important ? "important" : "");
	                            }
	                        };

	                        //Check so that there are no accidental styles that will make the element styled differently now that is is relative.
	                        //If there are any, set them to 0 (this should be okay with the user since the style properties did nothing before [since the element was positioned static] anyway).
	                        removeRelativeStyles(reporter, element, style, "top");
	                        removeRelativeStyles(reporter, element, style, "right");
	                        removeRelativeStyles(reporter, element, style, "bottom");
	                        removeRelativeStyles(reporter, element, style, "left");
	                    }
	                }

	                function onObjectLoad() {
	                    // The object has been loaded, which means that the element now is guaranteed to be attached to the DOM.
	                    if (!positionCheckPerformed) {
	                        alterPositionStyles();
	                    }

	                    /*jshint validthis: true */

	                    function getDocument(element, callback) {
	                        //Opera 12 seem to call the object.onload before the actual document has been created.
	                        //So if it is not present, poll it with an timeout until it is present.
	                        //TODO: Could maybe be handled better with object.onreadystatechange or similar.
	                        if(!element.contentDocument) {
	                            var state = getState(element);
	                            if (state.checkForObjectDocumentTimeoutId) {
	                                window.clearTimeout(state.checkForObjectDocumentTimeoutId);
	                            }
	                            state.checkForObjectDocumentTimeoutId = setTimeout(function checkForObjectDocument() {
	                                state.checkForObjectDocumentTimeoutId = 0;
	                                getDocument(element, callback);
	                            }, 100);

	                            return;
	                        }

	                        callback(element.contentDocument);
	                    }

	                    //Mutating the object element here seems to fire another load event.
	                    //Mutating the inner document of the object element is fine though.
	                    var objectElement = this;

	                    //Create the style element to be added to the object.
	                    getDocument(objectElement, function onObjectDocumentReady(objectDocument) {
	                        //Notify that the element is ready to be listened to.
	                        callback(element);
	                    });
	                }

	                // The element may be detached from the DOM, and some browsers does not support style resolving of detached elements.
	                // The alterPositionStyles needs to be delayed until we know the element has been attached to the DOM (which we are sure of when the onObjectLoad has been fired), if style resolution is not possible.
	                if (style.position !== "") {
	                    alterPositionStyles();
	                    positionCheckPerformed = true;
	                }

	                //Add an object element as a child to the target element that will be listened to for resize events.
	                var object = document.createElement("object");
	                object.style.cssText = OBJECT_STYLE;
	                object.tabIndex = -1;
	                object.type = "text/html";
	                object.setAttribute("aria-hidden", "true");
	                object.onload = onObjectLoad;

	                //Safari: This must occur before adding the object to the DOM.
	                //IE: Does not like that this happens before, even if it is also added after.
	                if(!browserDetector$1.isIE()) {
	                    object.data = "about:blank";
	                }

	                if (!getState(element)) {
	                    // The element has been uninstalled before the actual loading happened.
	                    return;
	                }

	                element.appendChild(object);
	                getState(element).object = object;

	                //IE: This must occur after adding the object to the DOM.
	                if(browserDetector$1.isIE()) {
	                    object.data = "about:blank";
	                }
	            }

	            if(batchProcessor) {
	                batchProcessor.add(mutateDom);
	            } else {
	                mutateDom();
	            }
	        }

	        if(browserDetector$1.isIE(8)) {
	            //IE 8 does not support objects properly. Luckily they do support the resize event.
	            //So do not inject the object and notify that the element is already ready to be listened to.
	            //The event handler for the resize event is attached in the utils.addListener instead.
	            callback(element);
	        } else {
	            injectObject(element, callback);
	        }
	    }

	    /**
	     * Returns the child object of the target element.
	     * @private
	     * @param {element} element The target element.
	     * @returns The object element of the target.
	     */
	    function getObject(element) {
	        return getState(element).object;
	    }

	    function uninstall(element) {
	        if (!getState(element)) {
	            return;
	        }

	        var object = getObject(element);

	        if (!object) {
	            return;
	        }

	        if (browserDetector$1.isIE(8)) {
	            element.detachEvent("onresize", object.proxy);
	        } else {
	            element.removeChild(object);
	        }

	        if (getState(element).checkForObjectDocumentTimeoutId) {
	            window.clearTimeout(getState(element).checkForObjectDocumentTimeoutId);
	        }

	        delete getState(element).object;
	    }

	    return {
	        makeDetectable: makeDetectable,
	        addListener: addListener,
	        uninstall: uninstall
	    };
	};

	/**
	 * Resize detection strategy that injects divs to elements in order to detect resize events on scroll events.
	 * Heavily inspired by: https://github.com/marcj/css-element-queries/blob/master/src/ResizeSensor.js
	 */

	var forEach$1 = collectionUtils.exports.forEach;

	var scroll = function(options) {
	    options             = options || {};
	    var reporter        = options.reporter;
	    var batchProcessor  = options.batchProcessor;
	    var getState        = options.stateHandler.getState;
	    options.stateHandler.hasState;
	    var idHandler       = options.idHandler;

	    if (!batchProcessor) {
	        throw new Error("Missing required dependency: batchProcessor");
	    }

	    if (!reporter) {
	        throw new Error("Missing required dependency: reporter.");
	    }

	    //TODO: Could this perhaps be done at installation time?
	    var scrollbarSizes = getScrollbarSizes();

	    var styleId = "erd_scroll_detection_scrollbar_style";
	    var detectionContainerClass = "erd_scroll_detection_container";

	    function initDocument(targetDocument) {
	        // Inject the scrollbar styling that prevents them from appearing sometimes in Chrome.
	        // The injected container needs to have a class, so that it may be styled with CSS (pseudo elements).
	        injectScrollStyle(targetDocument, styleId, detectionContainerClass);
	    }

	    initDocument(window.document);

	    function buildCssTextString(rules) {
	        var seperator = options.important ? " !important; " : "; ";

	        return (rules.join(seperator) + seperator).trim();
	    }

	    function getScrollbarSizes() {
	        var width = 500;
	        var height = 500;

	        var child = document.createElement("div");
	        child.style.cssText = buildCssTextString(["position: absolute", "width: " + width*2 + "px", "height: " + height*2 + "px", "visibility: hidden", "margin: 0", "padding: 0"]);

	        var container = document.createElement("div");
	        container.style.cssText = buildCssTextString(["position: absolute", "width: " + width + "px", "height: " + height + "px", "overflow: scroll", "visibility: none", "top: " + -width*3 + "px", "left: " + -height*3 + "px", "visibility: hidden", "margin: 0", "padding: 0"]);

	        container.appendChild(child);

	        document.body.insertBefore(container, document.body.firstChild);

	        var widthSize = width - container.clientWidth;
	        var heightSize = height - container.clientHeight;

	        document.body.removeChild(container);

	        return {
	            width: widthSize,
	            height: heightSize
	        };
	    }

	    function injectScrollStyle(targetDocument, styleId, containerClass) {
	        function injectStyle(style, method) {
	            method = method || function (element) {
	                targetDocument.head.appendChild(element);
	            };

	            var styleElement = targetDocument.createElement("style");
	            styleElement.innerHTML = style;
	            styleElement.id = styleId;
	            method(styleElement);
	            return styleElement;
	        }

	        if (!targetDocument.getElementById(styleId)) {
	            var containerAnimationClass = containerClass + "_animation";
	            var containerAnimationActiveClass = containerClass + "_animation_active";
	            var style = "/* Created by the element-resize-detector library. */\n";
	            style += "." + containerClass + " > div::-webkit-scrollbar { " + buildCssTextString(["display: none"]) + " }\n\n";
	            style += "." + containerAnimationActiveClass + " { " + buildCssTextString(["-webkit-animation-duration: 0.1s", "animation-duration: 0.1s", "-webkit-animation-name: " + containerAnimationClass, "animation-name: " + containerAnimationClass]) + " }\n";
	            style += "@-webkit-keyframes " + containerAnimationClass +  " { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } }\n";
	            style += "@keyframes " + containerAnimationClass +          " { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } }";
	            injectStyle(style);
	        }
	    }

	    function addAnimationClass(element) {
	        element.className += " " + detectionContainerClass + "_animation_active";
	    }

	    function addEvent(el, name, cb) {
	        if (el.addEventListener) {
	            el.addEventListener(name, cb);
	        } else if(el.attachEvent) {
	            el.attachEvent("on" + name, cb);
	        } else {
	            return reporter.error("[scroll] Don't know how to add event listeners.");
	        }
	    }

	    function removeEvent(el, name, cb) {
	        if (el.removeEventListener) {
	            el.removeEventListener(name, cb);
	        } else if(el.detachEvent) {
	            el.detachEvent("on" + name, cb);
	        } else {
	            return reporter.error("[scroll] Don't know how to remove event listeners.");
	        }
	    }

	    function getExpandElement(element) {
	        return getState(element).container.childNodes[0].childNodes[0].childNodes[0];
	    }

	    function getShrinkElement(element) {
	        return getState(element).container.childNodes[0].childNodes[0].childNodes[1];
	    }

	    /**
	     * Adds a resize event listener to the element.
	     * @public
	     * @param {element} element The element that should have the listener added.
	     * @param {function} listener The listener callback to be called for each resize event of the element. The element will be given as a parameter to the listener callback.
	     */
	    function addListener(element, listener) {
	        var listeners = getState(element).listeners;

	        if (!listeners.push) {
	            throw new Error("Cannot add listener to an element that is not detectable.");
	        }

	        getState(element).listeners.push(listener);
	    }

	    /**
	     * Makes an element detectable and ready to be listened for resize events. Will call the callback when the element is ready to be listened for resize changes.
	     * @private
	     * @param {object} options Optional options object.
	     * @param {element} element The element to make detectable
	     * @param {function} callback The callback to be called when the element is ready to be listened for resize changes. Will be called with the element as first parameter.
	     */
	    function makeDetectable(options, element, callback) {
	        if (!callback) {
	            callback = element;
	            element = options;
	            options = null;
	        }

	        options = options || {};

	        function debug() {
	            if (options.debug) {
	                var args = Array.prototype.slice.call(arguments);
	                args.unshift(idHandler.get(element), "Scroll: ");
	                if (reporter.log.apply) {
	                    reporter.log.apply(null, args);
	                } else {
	                    for (var i = 0; i < args.length; i++) {
	                        reporter.log(args[i]);
	                    }
	                }
	            }
	        }

	        function isDetached(element) {
	            function isInDocument(element) {
	                var isInShadowRoot = element.getRootNode && element.getRootNode().contains(element);
	                return element === element.ownerDocument.body || element.ownerDocument.body.contains(element) || isInShadowRoot;
	            }

	            if (!isInDocument(element)) {
	                return true;
	            }

	            // FireFox returns null style in hidden iframes. See https://github.com/wnr/element-resize-detector/issues/68 and https://bugzilla.mozilla.org/show_bug.cgi?id=795520
	            if (window.getComputedStyle(element) === null) {
	                return true;
	            }

	            return false;
	        }

	        function isUnrendered(element) {
	            // Check the absolute positioned container since the top level container is display: inline.
	            var container = getState(element).container.childNodes[0];
	            var style = window.getComputedStyle(container);
	            return !style.width || style.width.indexOf("px") === -1; //Can only compute pixel value when rendered.
	        }

	        function getStyle() {
	            // Some browsers only force layouts when actually reading the style properties of the style object, so make sure that they are all read here,
	            // so that the user of the function can be sure that it will perform the layout here, instead of later (important for batching).
	            var elementStyle            = window.getComputedStyle(element);
	            var style                   = {};
	            style.position              = elementStyle.position;
	            style.width                 = element.offsetWidth;
	            style.height                = element.offsetHeight;
	            style.top                   = elementStyle.top;
	            style.right                 = elementStyle.right;
	            style.bottom                = elementStyle.bottom;
	            style.left                  = elementStyle.left;
	            style.widthCSS              = elementStyle.width;
	            style.heightCSS             = elementStyle.height;
	            return style;
	        }

	        function storeStartSize() {
	            var style = getStyle();
	            getState(element).startSize = {
	                width: style.width,
	                height: style.height
	            };
	            debug("Element start size", getState(element).startSize);
	        }

	        function initListeners() {
	            getState(element).listeners = [];
	        }

	        function storeStyle() {
	            debug("storeStyle invoked.");
	            if (!getState(element)) {
	                debug("Aborting because element has been uninstalled");
	                return;
	            }

	            var style = getStyle();
	            getState(element).style = style;
	        }

	        function storeCurrentSize(element, width, height) {
	            getState(element).lastWidth = width;
	            getState(element).lastHeight  = height;
	        }

	        function getExpandChildElement(element) {
	            return getExpandElement(element).childNodes[0];
	        }

	        function getWidthOffset() {
	            return 2 * scrollbarSizes.width + 1;
	        }

	        function getHeightOffset() {
	            return 2 * scrollbarSizes.height + 1;
	        }

	        function getExpandWidth(width) {
	            return width + 10 + getWidthOffset();
	        }

	        function getExpandHeight(height) {
	            return height + 10 + getHeightOffset();
	        }

	        function getShrinkWidth(width) {
	            return width * 2 + getWidthOffset();
	        }

	        function getShrinkHeight(height) {
	            return height * 2 + getHeightOffset();
	        }

	        function positionScrollbars(element, width, height) {
	            var expand          = getExpandElement(element);
	            var shrink          = getShrinkElement(element);
	            var expandWidth     = getExpandWidth(width);
	            var expandHeight    = getExpandHeight(height);
	            var shrinkWidth     = getShrinkWidth(width);
	            var shrinkHeight    = getShrinkHeight(height);
	            expand.scrollLeft   = expandWidth;
	            expand.scrollTop    = expandHeight;
	            shrink.scrollLeft   = shrinkWidth;
	            shrink.scrollTop    = shrinkHeight;
	        }

	        function injectContainerElement() {
	            var container = getState(element).container;

	            if (!container) {
	                container                   = document.createElement("div");
	                container.className         = detectionContainerClass;
	                container.style.cssText     = buildCssTextString(["visibility: hidden", "display: inline", "width: 0px", "height: 0px", "z-index: -1", "overflow: hidden", "margin: 0", "padding: 0"]);
	                getState(element).container = container;
	                addAnimationClass(container);
	                element.appendChild(container);

	                var onAnimationStart = function () {
	                    getState(element).onRendered && getState(element).onRendered();
	                };

	                addEvent(container, "animationstart", onAnimationStart);

	                // Store the event handler here so that they may be removed when uninstall is called.
	                // See uninstall function for an explanation why it is needed.
	                getState(element).onAnimationStart = onAnimationStart;
	            }

	            return container;
	        }

	        function injectScrollElements() {
	            function alterPositionStyles() {
	                var style = getState(element).style;

	                if(style.position === "static") {
	                    element.style.setProperty("position", "relative",options.important ? "important" : "");

	                    var removeRelativeStyles = function(reporter, element, style, property) {
	                        function getNumericalValue(value) {
	                            return value.replace(/[^-\d\.]/g, "");
	                        }

	                        var value = style[property];

	                        if(value !== "auto" && getNumericalValue(value) !== "0") {
	                            reporter.warn("An element that is positioned static has style." + property + "=" + value + " which is ignored due to the static positioning. The element will need to be positioned relative, so the style." + property + " will be set to 0. Element: ", element);
	                            element.style[property] = 0;
	                        }
	                    };

	                    //Check so that there are no accidental styles that will make the element styled differently now that is is relative.
	                    //If there are any, set them to 0 (this should be okay with the user since the style properties did nothing before [since the element was positioned static] anyway).
	                    removeRelativeStyles(reporter, element, style, "top");
	                    removeRelativeStyles(reporter, element, style, "right");
	                    removeRelativeStyles(reporter, element, style, "bottom");
	                    removeRelativeStyles(reporter, element, style, "left");
	                }
	            }

	            function getLeftTopBottomRightCssText(left, top, bottom, right) {
	                left = (!left ? "0" : (left + "px"));
	                top = (!top ? "0" : (top + "px"));
	                bottom = (!bottom ? "0" : (bottom + "px"));
	                right = (!right ? "0" : (right + "px"));

	                return ["left: " + left, "top: " + top, "right: " + right, "bottom: " + bottom];
	            }

	            debug("Injecting elements");

	            if (!getState(element)) {
	                debug("Aborting because element has been uninstalled");
	                return;
	            }

	            alterPositionStyles();

	            var rootContainer = getState(element).container;

	            if (!rootContainer) {
	                rootContainer = injectContainerElement();
	            }

	            // Due to this WebKit bug https://bugs.webkit.org/show_bug.cgi?id=80808 (currently fixed in Blink, but still present in WebKit browsers such as Safari),
	            // we need to inject two containers, one that is width/height 100% and another that is left/top -1px so that the final container always is 1x1 pixels bigger than
	            // the targeted element.
	            // When the bug is resolved, "containerContainer" may be removed.

	            // The outer container can occasionally be less wide than the targeted when inside inline elements element in WebKit (see https://bugs.webkit.org/show_bug.cgi?id=152980).
	            // This should be no problem since the inner container either way makes sure the injected scroll elements are at least 1x1 px.

	            var scrollbarWidth          = scrollbarSizes.width;
	            var scrollbarHeight         = scrollbarSizes.height;
	            var containerContainerStyle = buildCssTextString(["position: absolute", "flex: none", "overflow: hidden", "z-index: -1", "visibility: hidden", "width: 100%", "height: 100%", "left: 0px", "top: 0px"]);
	            var containerStyle          = buildCssTextString(["position: absolute", "flex: none", "overflow: hidden", "z-index: -1", "visibility: hidden"].concat(getLeftTopBottomRightCssText(-(1 + scrollbarWidth), -(1 + scrollbarHeight), -scrollbarHeight, -scrollbarWidth)));
	            var expandStyle             = buildCssTextString(["position: absolute", "flex: none", "overflow: scroll", "z-index: -1", "visibility: hidden", "width: 100%", "height: 100%"]);
	            var shrinkStyle             = buildCssTextString(["position: absolute", "flex: none", "overflow: scroll", "z-index: -1", "visibility: hidden", "width: 100%", "height: 100%"]);
	            var expandChildStyle        = buildCssTextString(["position: absolute", "left: 0", "top: 0"]);
	            var shrinkChildStyle        = buildCssTextString(["position: absolute", "width: 200%", "height: 200%"]);

	            var containerContainer      = document.createElement("div");
	            var container               = document.createElement("div");
	            var expand                  = document.createElement("div");
	            var expandChild             = document.createElement("div");
	            var shrink                  = document.createElement("div");
	            var shrinkChild             = document.createElement("div");

	            // Some browsers choke on the resize system being rtl, so force it to ltr. https://github.com/wnr/element-resize-detector/issues/56
	            // However, dir should not be set on the top level container as it alters the dimensions of the target element in some browsers.
	            containerContainer.dir              = "ltr";

	            containerContainer.style.cssText    = containerContainerStyle;
	            containerContainer.className        = detectionContainerClass;
	            container.className                 = detectionContainerClass;
	            container.style.cssText             = containerStyle;
	            expand.style.cssText                = expandStyle;
	            expandChild.style.cssText           = expandChildStyle;
	            shrink.style.cssText                = shrinkStyle;
	            shrinkChild.style.cssText           = shrinkChildStyle;

	            expand.appendChild(expandChild);
	            shrink.appendChild(shrinkChild);
	            container.appendChild(expand);
	            container.appendChild(shrink);
	            containerContainer.appendChild(container);
	            rootContainer.appendChild(containerContainer);

	            function onExpandScroll() {
	                var state = getState(element);
	                if (state && state.onExpand) {
	                    state.onExpand();
	                } else {
	                    debug("Aborting expand scroll handler: element has been uninstalled");
	                }
	            }

	            function onShrinkScroll() {
	                var state = getState(element);
	                if (state && state.onShrink) {
	                    state.onShrink();
	                } else {
	                    debug("Aborting shrink scroll handler: element has been uninstalled");
	                }
	            }

	            addEvent(expand, "scroll", onExpandScroll);
	            addEvent(shrink, "scroll", onShrinkScroll);

	            // Store the event handlers here so that they may be removed when uninstall is called.
	            // See uninstall function for an explanation why it is needed.
	            getState(element).onExpandScroll = onExpandScroll;
	            getState(element).onShrinkScroll = onShrinkScroll;
	        }

	        function registerListenersAndPositionElements() {
	            function updateChildSizes(element, width, height) {
	                var expandChild             = getExpandChildElement(element);
	                var expandWidth             = getExpandWidth(width);
	                var expandHeight            = getExpandHeight(height);
	                expandChild.style.setProperty("width", expandWidth + "px", options.important ? "important" : "");
	                expandChild.style.setProperty("height", expandHeight + "px", options.important ? "important" : "");
	            }

	            function updateDetectorElements(done) {
	                var width           = element.offsetWidth;
	                var height          = element.offsetHeight;

	                // Check whether the size has actually changed since last time the algorithm ran. If not, some steps may be skipped.
	                var sizeChanged = width !== getState(element).lastWidth || height !== getState(element).lastHeight;

	                debug("Storing current size", width, height);

	                // Store the size of the element sync here, so that multiple scroll events may be ignored in the event listeners.
	                // Otherwise the if-check in handleScroll is useless.
	                storeCurrentSize(element, width, height);

	                // Since we delay the processing of the batch, there is a risk that uninstall has been called before the batch gets to execute.
	                // Since there is no way to cancel the fn executions, we need to add an uninstall guard to all fns of the batch.

	                batchProcessor.add(0, function performUpdateChildSizes() {
	                    if (!sizeChanged) {
	                        return;
	                    }

	                    if (!getState(element)) {
	                        debug("Aborting because element has been uninstalled");
	                        return;
	                    }

	                    if (!areElementsInjected()) {
	                        debug("Aborting because element container has not been initialized");
	                        return;
	                    }

	                    if (options.debug) {
	                        var w = element.offsetWidth;
	                        var h = element.offsetHeight;

	                        if (w !== width || h !== height) {
	                            reporter.warn(idHandler.get(element), "Scroll: Size changed before updating detector elements.");
	                        }
	                    }

	                    updateChildSizes(element, width, height);
	                });

	                batchProcessor.add(1, function updateScrollbars() {
	                    // This function needs to be invoked event though the size is unchanged. The element could have been resized very quickly and then
	                    // been restored to the original size, which will have changed the scrollbar positions.

	                    if (!getState(element)) {
	                        debug("Aborting because element has been uninstalled");
	                        return;
	                    }

	                    if (!areElementsInjected()) {
	                        debug("Aborting because element container has not been initialized");
	                        return;
	                    }

	                    positionScrollbars(element, width, height);
	                });

	                if (sizeChanged && done) {
	                    batchProcessor.add(2, function () {
	                        if (!getState(element)) {
	                            debug("Aborting because element has been uninstalled");
	                            return;
	                        }

	                        if (!areElementsInjected()) {
	                          debug("Aborting because element container has not been initialized");
	                          return;
	                        }

	                        done();
	                    });
	                }
	            }

	            function areElementsInjected() {
	                return !!getState(element).container;
	            }

	            function notifyListenersIfNeeded() {
	                function isFirstNotify() {
	                    return getState(element).lastNotifiedWidth === undefined;
	                }

	                debug("notifyListenersIfNeeded invoked");

	                var state = getState(element);

	                // Don't notify if the current size is the start size, and this is the first notification.
	                if (isFirstNotify() && state.lastWidth === state.startSize.width && state.lastHeight === state.startSize.height) {
	                    return debug("Not notifying: Size is the same as the start size, and there has been no notification yet.");
	                }

	                // Don't notify if the size already has been notified.
	                if (state.lastWidth === state.lastNotifiedWidth && state.lastHeight === state.lastNotifiedHeight) {
	                    return debug("Not notifying: Size already notified");
	                }


	                debug("Current size not notified, notifying...");
	                state.lastNotifiedWidth = state.lastWidth;
	                state.lastNotifiedHeight = state.lastHeight;
	                forEach$1(getState(element).listeners, function (listener) {
	                    listener(element);
	                });
	            }

	            function handleRender() {
	                debug("startanimation triggered.");

	                if (isUnrendered(element)) {
	                    debug("Ignoring since element is still unrendered...");
	                    return;
	                }

	                debug("Element rendered.");
	                var expand = getExpandElement(element);
	                var shrink = getShrinkElement(element);
	                if (expand.scrollLeft === 0 || expand.scrollTop === 0 || shrink.scrollLeft === 0 || shrink.scrollTop === 0) {
	                    debug("Scrollbars out of sync. Updating detector elements...");
	                    updateDetectorElements(notifyListenersIfNeeded);
	                }
	            }

	            function handleScroll() {
	                debug("Scroll detected.");

	                if (isUnrendered(element)) {
	                    // Element is still unrendered. Skip this scroll event.
	                    debug("Scroll event fired while unrendered. Ignoring...");
	                    return;
	                }

	                updateDetectorElements(notifyListenersIfNeeded);
	            }

	            debug("registerListenersAndPositionElements invoked.");

	            if (!getState(element)) {
	                debug("Aborting because element has been uninstalled");
	                return;
	            }

	            getState(element).onRendered = handleRender;
	            getState(element).onExpand = handleScroll;
	            getState(element).onShrink = handleScroll;

	            var style = getState(element).style;
	            updateChildSizes(element, style.width, style.height);
	        }

	        function finalizeDomMutation() {
	            debug("finalizeDomMutation invoked.");

	            if (!getState(element)) {
	                debug("Aborting because element has been uninstalled");
	                return;
	            }

	            var style = getState(element).style;
	            storeCurrentSize(element, style.width, style.height);
	            positionScrollbars(element, style.width, style.height);
	        }

	        function ready() {
	            callback(element);
	        }

	        function install() {
	            debug("Installing...");
	            initListeners();
	            storeStartSize();

	            batchProcessor.add(0, storeStyle);
	            batchProcessor.add(1, injectScrollElements);
	            batchProcessor.add(2, registerListenersAndPositionElements);
	            batchProcessor.add(3, finalizeDomMutation);
	            batchProcessor.add(4, ready);
	        }

	        debug("Making detectable...");

	        if (isDetached(element)) {
	            debug("Element is detached");

	            injectContainerElement();

	            debug("Waiting until element is attached...");

	            getState(element).onRendered = function () {
	                debug("Element is now attached");
	                install();
	            };
	        } else {
	            install();
	        }
	    }

	    function uninstall(element) {
	        var state = getState(element);

	        if (!state) {
	            // Uninstall has been called on a non-erd element.
	            return;
	        }

	        // Uninstall may have been called in the following scenarios:
	        // (1) Right between the sync code and async batch (here state.busy = true, but nothing have been registered or injected).
	        // (2) In the ready callback of the last level of the batch by another element (here, state.busy = true, but all the stuff has been injected).
	        // (3) After the installation process (here, state.busy = false and all the stuff has been injected).
	        // So to be on the safe side, let's check for each thing before removing.

	        // We need to remove the event listeners, because otherwise the event might fire on an uninstall element which results in an error when trying to get the state of the element.
	        state.onExpandScroll && removeEvent(getExpandElement(element), "scroll", state.onExpandScroll);
	        state.onShrinkScroll && removeEvent(getShrinkElement(element), "scroll", state.onShrinkScroll);
	        state.onAnimationStart && removeEvent(state.container, "animationstart", state.onAnimationStart);

	        state.container && element.removeChild(state.container);
	    }

	    return {
	        makeDetectable: makeDetectable,
	        addListener: addListener,
	        uninstall: uninstall,
	        initDocument: initDocument
	    };
	};

	var forEach                 = collectionUtils.exports.forEach;
	var elementUtilsMaker       = elementUtils;
	var listenerHandlerMaker    = listenerHandler;
	var idGeneratorMaker        = idGenerator;
	var idHandlerMaker          = idHandler;
	var reporterMaker           = reporter;
	var browserDetector         = browserDetector$2.exports;
	var batchProcessorMaker     = batchProcessor;
	var stateHandler            = stateHandler$1;

	//Detection strategies.
	var objectStrategyMaker     = object;
	var scrollStrategyMaker     = scroll;

	function isCollection(obj) {
	    return Array.isArray(obj) || obj.length !== undefined;
	}

	function toArray(collection) {
	    if (!Array.isArray(collection)) {
	        var array = [];
	        forEach(collection, function (obj) {
	            array.push(obj);
	        });
	        return array;
	    } else {
	        return collection;
	    }
	}

	function isElement(obj) {
	    return obj && obj.nodeType === 1;
	}

	/**
	 * @typedef idHandler
	 * @type {object}
	 * @property {function} get Gets the resize detector id of the element.
	 * @property {function} set Generate and sets the resize detector id of the element.
	 */

	/**
	 * @typedef Options
	 * @type {object}
	 * @property {boolean} callOnAdd    Determines if listeners should be called when they are getting added.
	                                    Default is true. If true, the listener is guaranteed to be called when it has been added.
	                                    If false, the listener will not be guarenteed to be called when it has been added (does not prevent it from being called).
	 * @property {idHandler} idHandler  A custom id handler that is responsible for generating, setting and retrieving id's for elements.
	                                    If not provided, a default id handler will be used.
	 * @property {reporter} reporter    A custom reporter that handles reporting logs, warnings and errors.
	                                    If not provided, a default id handler will be used.
	                                    If set to false, then nothing will be reported.
	 * @property {boolean} debug        If set to true, the the system will report debug messages as default for the listenTo method.
	 */

	/**
	 * Creates an element resize detector instance.
	 * @public
	 * @param {Options?} options Optional global options object that will decide how this instance will work.
	 */
	var elementResizeDetector = function(options) {
	    options = options || {};

	    //idHandler is currently not an option to the listenTo function, so it should not be added to globalOptions.
	    var idHandler;

	    if (options.idHandler) {
	        // To maintain compatability with idHandler.get(element, readonly), make sure to wrap the given idHandler
	        // so that readonly flag always is true when it's used here. This may be removed next major version bump.
	        idHandler = {
	            get: function (element) { return options.idHandler.get(element, true); },
	            set: options.idHandler.set
	        };
	    } else {
	        var idGenerator = idGeneratorMaker();
	        var defaultIdHandler = idHandlerMaker({
	            idGenerator: idGenerator,
	            stateHandler: stateHandler
	        });
	        idHandler = defaultIdHandler;
	    }

	    //reporter is currently not an option to the listenTo function, so it should not be added to globalOptions.
	    var reporter = options.reporter;

	    if(!reporter) {
	        //If options.reporter is false, then the reporter should be quiet.
	        var quiet = reporter === false;
	        reporter = reporterMaker(quiet);
	    }

	    //batchProcessor is currently not an option to the listenTo function, so it should not be added to globalOptions.
	    var batchProcessor = getOption(options, "batchProcessor", batchProcessorMaker({ reporter: reporter }));

	    //Options to be used as default for the listenTo function.
	    var globalOptions = {};
	    globalOptions.callOnAdd     = !!getOption(options, "callOnAdd", true);
	    globalOptions.debug         = !!getOption(options, "debug", false);

	    var eventListenerHandler    = listenerHandlerMaker(idHandler);
	    var elementUtils            = elementUtilsMaker({
	        stateHandler: stateHandler
	    });

	    //The detection strategy to be used.
	    var detectionStrategy;
	    var desiredStrategy = getOption(options, "strategy", "object");
	    var importantCssRules = getOption(options, "important", false);
	    var strategyOptions = {
	        reporter: reporter,
	        batchProcessor: batchProcessor,
	        stateHandler: stateHandler,
	        idHandler: idHandler,
	        important: importantCssRules
	    };

	    if(desiredStrategy === "scroll") {
	        if (browserDetector.isLegacyOpera()) {
	            reporter.warn("Scroll strategy is not supported on legacy Opera. Changing to object strategy.");
	            desiredStrategy = "object";
	        } else if (browserDetector.isIE(9)) {
	            reporter.warn("Scroll strategy is not supported on IE9. Changing to object strategy.");
	            desiredStrategy = "object";
	        }
	    }

	    if(desiredStrategy === "scroll") {
	        detectionStrategy = scrollStrategyMaker(strategyOptions);
	    } else if(desiredStrategy === "object") {
	        detectionStrategy = objectStrategyMaker(strategyOptions);
	    } else {
	        throw new Error("Invalid strategy name: " + desiredStrategy);
	    }

	    //Calls can be made to listenTo with elements that are still being installed.
	    //Also, same elements can occur in the elements list in the listenTo function.
	    //With this map, the ready callbacks can be synchronized between the calls
	    //so that the ready callback can always be called when an element is ready - even if
	    //it wasn't installed from the function itself.
	    var onReadyCallbacks = {};

	    /**
	     * Makes the given elements resize-detectable and starts listening to resize events on the elements. Calls the event callback for each event for each element.
	     * @public
	     * @param {Options?} options Optional options object. These options will override the global options. Some options may not be overriden, such as idHandler.
	     * @param {element[]|element} elements The given array of elements to detect resize events of. Single element is also valid.
	     * @param {function} listener The callback to be executed for each resize event for each element.
	     */
	    function listenTo(options, elements, listener) {
	        function onResizeCallback(element) {
	            var listeners = eventListenerHandler.get(element);
	            forEach(listeners, function callListenerProxy(listener) {
	                listener(element);
	            });
	        }

	        function addListener(callOnAdd, element, listener) {
	            eventListenerHandler.add(element, listener);

	            if(callOnAdd) {
	                listener(element);
	            }
	        }

	        //Options object may be omitted.
	        if(!listener) {
	            listener = elements;
	            elements = options;
	            options = {};
	        }

	        if(!elements) {
	            throw new Error("At least one element required.");
	        }

	        if(!listener) {
	            throw new Error("Listener required.");
	        }

	        if (isElement(elements)) {
	            // A single element has been passed in.
	            elements = [elements];
	        } else if (isCollection(elements)) {
	            // Convert collection to array for plugins.
	            // TODO: May want to check so that all the elements in the collection are valid elements.
	            elements = toArray(elements);
	        } else {
	            return reporter.error("Invalid arguments. Must be a DOM element or a collection of DOM elements.");
	        }

	        var elementsReady = 0;

	        var callOnAdd = getOption(options, "callOnAdd", globalOptions.callOnAdd);
	        var onReadyCallback = getOption(options, "onReady", function noop() {});
	        var debug = getOption(options, "debug", globalOptions.debug);

	        forEach(elements, function attachListenerToElement(element) {
	            if (!stateHandler.getState(element)) {
	                stateHandler.initState(element);
	                idHandler.set(element);
	            }

	            var id = idHandler.get(element);

	            debug && reporter.log("Attaching listener to element", id, element);

	            if(!elementUtils.isDetectable(element)) {
	                debug && reporter.log(id, "Not detectable.");
	                if(elementUtils.isBusy(element)) {
	                    debug && reporter.log(id, "System busy making it detectable");

	                    //The element is being prepared to be detectable. Do not make it detectable.
	                    //Just add the listener, because the element will soon be detectable.
	                    addListener(callOnAdd, element, listener);
	                    onReadyCallbacks[id] = onReadyCallbacks[id] || [];
	                    onReadyCallbacks[id].push(function onReady() {
	                        elementsReady++;

	                        if(elementsReady === elements.length) {
	                            onReadyCallback();
	                        }
	                    });
	                    return;
	                }

	                debug && reporter.log(id, "Making detectable...");
	                //The element is not prepared to be detectable, so do prepare it and add a listener to it.
	                elementUtils.markBusy(element, true);
	                return detectionStrategy.makeDetectable({ debug: debug, important: importantCssRules }, element, function onElementDetectable(element) {
	                    debug && reporter.log(id, "onElementDetectable");

	                    if (stateHandler.getState(element)) {
	                        elementUtils.markAsDetectable(element);
	                        elementUtils.markBusy(element, false);
	                        detectionStrategy.addListener(element, onResizeCallback);
	                        addListener(callOnAdd, element, listener);

	                        // Since the element size might have changed since the call to "listenTo", we need to check for this change,
	                        // so that a resize event may be emitted.
	                        // Having the startSize object is optional (since it does not make sense in some cases such as unrendered elements), so check for its existance before.
	                        // Also, check the state existance before since the element may have been uninstalled in the installation process.
	                        var state = stateHandler.getState(element);
	                        if (state && state.startSize) {
	                            var width = element.offsetWidth;
	                            var height = element.offsetHeight;
	                            if (state.startSize.width !== width || state.startSize.height !== height) {
	                                onResizeCallback(element);
	                            }
	                        }

	                        if(onReadyCallbacks[id]) {
	                            forEach(onReadyCallbacks[id], function(callback) {
	                                callback();
	                            });
	                        }
	                    } else {
	                        // The element has been unisntalled before being detectable.
	                        debug && reporter.log(id, "Element uninstalled before being detectable.");
	                    }

	                    delete onReadyCallbacks[id];

	                    elementsReady++;
	                    if(elementsReady === elements.length) {
	                        onReadyCallback();
	                    }
	                });
	            }

	            debug && reporter.log(id, "Already detecable, adding listener.");

	            //The element has been prepared to be detectable and is ready to be listened to.
	            addListener(callOnAdd, element, listener);
	            elementsReady++;
	        });

	        if(elementsReady === elements.length) {
	            onReadyCallback();
	        }
	    }

	    function uninstall(elements) {
	        if(!elements) {
	            return reporter.error("At least one element is required.");
	        }

	        if (isElement(elements)) {
	            // A single element has been passed in.
	            elements = [elements];
	        } else if (isCollection(elements)) {
	            // Convert collection to array for plugins.
	            // TODO: May want to check so that all the elements in the collection are valid elements.
	            elements = toArray(elements);
	        } else {
	            return reporter.error("Invalid arguments. Must be a DOM element or a collection of DOM elements.");
	        }

	        forEach(elements, function (element) {
	            eventListenerHandler.removeAllListeners(element);
	            detectionStrategy.uninstall(element);
	            stateHandler.cleanState(element);
	        });
	    }

	    function initDocument(targetDocument) {
	        detectionStrategy.initDocument && detectionStrategy.initDocument(targetDocument);
	    }

	    return {
	        listenTo: listenTo,
	        removeListener: eventListenerHandler.removeListener,
	        removeAllListeners: eventListenerHandler.removeAllListeners,
	        uninstall: uninstall,
	        initDocument: initDocument
	    };
	};

	function getOption(options, name, defaultValue) {
	    var value = options[name];

	    if((value === undefined || value === null) && defaultValue !== undefined) {
	        return defaultValue;
	    }

	    return value;
	}

	var elementResizeDetectorMaker = elementResizeDetector;

	var global$1 = (typeof global !== "undefined" ? global :
	  typeof self !== "undefined" ? self :
	  typeof window !== "undefined" ? window : {});

	/** Detect free variable `global` from Node.js. */
	var freeGlobal = typeof global$1 == 'object' && global$1 && global$1.Object === Object && global$1;

	var freeGlobal$1 = freeGlobal;

	/** Detect free variable `self`. */
	var freeSelf = typeof self == 'object' && self && self.Object === Object && self;

	/** Used as a reference to the global object. */
	var root = freeGlobal$1 || freeSelf || Function('return this')();

	var root$1 = root;

	/** Built-in value references. */
	var Symbol = root$1.Symbol;

	var Symbol$1 = Symbol;

	/** Used for built-in method references. */
	var objectProto$1 = Object.prototype;

	/** Used to check objects for own properties. */
	var hasOwnProperty = objectProto$1.hasOwnProperty;

	/**
	 * Used to resolve the
	 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
	 * of values.
	 */
	var nativeObjectToString$1 = objectProto$1.toString;

	/** Built-in value references. */
	var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined;

	/**
	 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
	 *
	 * @private
	 * @param {*} value The value to query.
	 * @returns {string} Returns the raw `toStringTag`.
	 */
	function getRawTag(value) {
	  var isOwn = hasOwnProperty.call(value, symToStringTag$1),
	      tag = value[symToStringTag$1];

	  try {
	    value[symToStringTag$1] = undefined;
	    var unmasked = true;
	  } catch (e) {}

	  var result = nativeObjectToString$1.call(value);
	  if (unmasked) {
	    if (isOwn) {
	      value[symToStringTag$1] = tag;
	    } else {
	      delete value[symToStringTag$1];
	    }
	  }
	  return result;
	}

	/** Used for built-in method references. */
	var objectProto = Object.prototype;

	/**
	 * Used to resolve the
	 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
	 * of values.
	 */
	var nativeObjectToString = objectProto.toString;

	/**
	 * Converts `value` to a string using `Object.prototype.toString`.
	 *
	 * @private
	 * @param {*} value The value to convert.
	 * @returns {string} Returns the converted string.
	 */
	function objectToString(value) {
	  return nativeObjectToString.call(value);
	}

	/** `Object#toString` result references. */
	var nullTag = '[object Null]',
	    undefinedTag = '[object Undefined]';

	/** Built-in value references. */
	var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined;

	/**
	 * The base implementation of `getTag` without fallbacks for buggy environments.
	 *
	 * @private
	 * @param {*} value The value to query.
	 * @returns {string} Returns the `toStringTag`.
	 */
	function baseGetTag(value) {
	  if (value == null) {
	    return value === undefined ? undefinedTag : nullTag;
	  }
	  return (symToStringTag && symToStringTag in Object(value))
	    ? getRawTag(value)
	    : objectToString(value);
	}

	/**
	 * Checks if `value` is object-like. A value is object-like if it's not `null`
	 * and has a `typeof` result of "object".
	 *
	 * @static
	 * @memberOf _
	 * @since 4.0.0
	 * @category Lang
	 * @param {*} value The value to check.
	 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
	 * @example
	 *
	 * _.isObjectLike({});
	 * // => true
	 *
	 * _.isObjectLike([1, 2, 3]);
	 * // => true
	 *
	 * _.isObjectLike(_.noop);
	 * // => false
	 *
	 * _.isObjectLike(null);
	 * // => false
	 */
	function isObjectLike(value) {
	  return value != null && typeof value == 'object';
	}

	/** `Object#toString` result references. */
	var symbolTag = '[object Symbol]';

	/**
	 * Checks if `value` is classified as a `Symbol` primitive or object.
	 *
	 * @static
	 * @memberOf _
	 * @since 4.0.0
	 * @category Lang
	 * @param {*} value The value to check.
	 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
	 * @example
	 *
	 * _.isSymbol(Symbol.iterator);
	 * // => true
	 *
	 * _.isSymbol('abc');
	 * // => false
	 */
	function isSymbol(value) {
	  return typeof value == 'symbol' ||
	    (isObjectLike(value) && baseGetTag(value) == symbolTag);
	}

	/** Used to match a single whitespace character. */
	var reWhitespace = /\s/;

	/**
	 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
	 * character of `string`.
	 *
	 * @private
	 * @param {string} string The string to inspect.
	 * @returns {number} Returns the index of the last non-whitespace character.
	 */
	function trimmedEndIndex(string) {
	  var index = string.length;

	  while (index-- && reWhitespace.test(string.charAt(index))) {}
	  return index;
	}

	/** Used to match leading whitespace. */
	var reTrimStart = /^\s+/;

	/**
	 * The base implementation of `_.trim`.
	 *
	 * @private
	 * @param {string} string The string to trim.
	 * @returns {string} Returns the trimmed string.
	 */
	function baseTrim(string) {
	  return string
	    ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
	    : string;
	}

	/**
	 * Checks if `value` is the
	 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
	 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
	 *
	 * @static
	 * @memberOf _
	 * @since 0.1.0
	 * @category Lang
	 * @param {*} value The value to check.
	 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
	 * @example
	 *
	 * _.isObject({});
	 * // => true
	 *
	 * _.isObject([1, 2, 3]);
	 * // => true
	 *
	 * _.isObject(_.noop);
	 * // => true
	 *
	 * _.isObject(null);
	 * // => false
	 */
	function isObject(value) {
	  var type = typeof value;
	  return value != null && (type == 'object' || type == 'function');
	}

	/** Used as references for various `Number` constants. */
	var NAN = 0 / 0;

	/** Used to detect bad signed hexadecimal string values. */
	var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;

	/** Used to detect binary string values. */
	var reIsBinary = /^0b[01]+$/i;

	/** Used to detect octal string values. */
	var reIsOctal = /^0o[0-7]+$/i;

	/** Built-in method references without a dependency on `root`. */
	var freeParseInt = parseInt;

	/**
	 * Converts `value` to a number.
	 *
	 * @static
	 * @memberOf _
	 * @since 4.0.0
	 * @category Lang
	 * @param {*} value The value to process.
	 * @returns {number} Returns the number.
	 * @example
	 *
	 * _.toNumber(3.2);
	 * // => 3.2
	 *
	 * _.toNumber(Number.MIN_VALUE);
	 * // => 5e-324
	 *
	 * _.toNumber(Infinity);
	 * // => Infinity
	 *
	 * _.toNumber('3.2');
	 * // => 3.2
	 */
	function toNumber(value) {
	  if (typeof value == 'number') {
	    return value;
	  }
	  if (isSymbol(value)) {
	    return NAN;
	  }
	  if (isObject(value)) {
	    var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
	    value = isObject(other) ? (other + '') : other;
	  }
	  if (typeof value != 'string') {
	    return value === 0 ? value : +value;
	  }
	  value = baseTrim(value);
	  var isBinary = reIsBinary.test(value);
	  return (isBinary || reIsOctal.test(value))
	    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
	    : (reIsBadHex.test(value) ? NAN : +value);
	}

	/**
	 * Gets the timestamp of the number of milliseconds that have elapsed since
	 * the Unix epoch (1 January 1970 00:00:00 UTC).
	 *
	 * @static
	 * @memberOf _
	 * @since 2.4.0
	 * @category Date
	 * @returns {number} Returns the timestamp.
	 * @example
	 *
	 * _.defer(function(stamp) {
	 *   console.log(_.now() - stamp);
	 * }, _.now());
	 * // => Logs the number of milliseconds it took for the deferred invocation.
	 */
	var now = function() {
	  return root$1.Date.now();
	};

	var now$1 = now;

	/** Error message constants. */
	var FUNC_ERROR_TEXT = 'Expected a function';

	/* Built-in method references for those with the same name as other `lodash` methods. */
	var nativeMax = Math.max,
	    nativeMin = Math.min;

	/**
	 * Creates a debounced function that delays invoking `func` until after `wait`
	 * milliseconds have elapsed since the last time the debounced function was
	 * invoked. The debounced function comes with a `cancel` method to cancel
	 * delayed `func` invocations and a `flush` method to immediately invoke them.
	 * Provide `options` to indicate whether `func` should be invoked on the
	 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
	 * with the last arguments provided to the debounced function. Subsequent
	 * calls to the debounced function return the result of the last `func`
	 * invocation.
	 *
	 * **Note:** If `leading` and `trailing` options are `true`, `func` is
	 * invoked on the trailing edge of the timeout only if the debounced function
	 * is invoked more than once during the `wait` timeout.
	 *
	 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
	 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
	 *
	 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
	 * for details over the differences between `_.debounce` and `_.throttle`.
	 *
	 * @static
	 * @memberOf _
	 * @since 0.1.0
	 * @category Function
	 * @param {Function} func The function to debounce.
	 * @param {number} [wait=0] The number of milliseconds to delay.
	 * @param {Object} [options={}] The options object.
	 * @param {boolean} [options.leading=false]
	 *  Specify invoking on the leading edge of the timeout.
	 * @param {number} [options.maxWait]
	 *  The maximum time `func` is allowed to be delayed before it's invoked.
	 * @param {boolean} [options.trailing=true]
	 *  Specify invoking on the trailing edge of the timeout.
	 * @returns {Function} Returns the new debounced function.
	 * @example
	 *
	 * // Avoid costly calculations while the window size is in flux.
	 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
	 *
	 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
	 * jQuery(element).on('click', _.debounce(sendMail, 300, {
	 *   'leading': true,
	 *   'trailing': false
	 * }));
	 *
	 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
	 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
	 * var source = new EventSource('/stream');
	 * jQuery(source).on('message', debounced);
	 *
	 * // Cancel the trailing debounced invocation.
	 * jQuery(window).on('popstate', debounced.cancel);
	 */
	function debounce(func, wait, options) {
	  var lastArgs,
	      lastThis,
	      maxWait,
	      result,
	      timerId,
	      lastCallTime,
	      lastInvokeTime = 0,
	      leading = false,
	      maxing = false,
	      trailing = true;

	  if (typeof func != 'function') {
	    throw new TypeError(FUNC_ERROR_TEXT);
	  }
	  wait = toNumber(wait) || 0;
	  if (isObject(options)) {
	    leading = !!options.leading;
	    maxing = 'maxWait' in options;
	    maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
	    trailing = 'trailing' in options ? !!options.trailing : trailing;
	  }

	  function invokeFunc(time) {
	    var args = lastArgs,
	        thisArg = lastThis;

	    lastArgs = lastThis = undefined;
	    lastInvokeTime = time;
	    result = func.apply(thisArg, args);
	    return result;
	  }

	  function leadingEdge(time) {
	    // Reset any `maxWait` timer.
	    lastInvokeTime = time;
	    // Start the timer for the trailing edge.
	    timerId = setTimeout(timerExpired, wait);
	    // Invoke the leading edge.
	    return leading ? invokeFunc(time) : result;
	  }

	  function remainingWait(time) {
	    var timeSinceLastCall = time - lastCallTime,
	        timeSinceLastInvoke = time - lastInvokeTime,
	        timeWaiting = wait - timeSinceLastCall;

	    return maxing
	      ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
	      : timeWaiting;
	  }

	  function shouldInvoke(time) {
	    var timeSinceLastCall = time - lastCallTime,
	        timeSinceLastInvoke = time - lastInvokeTime;

	    // Either this is the first call, activity has stopped and we're at the
	    // trailing edge, the system time has gone backwards and we're treating
	    // it as the trailing edge, or we've hit the `maxWait` limit.
	    return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
	      (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
	  }

	  function timerExpired() {
	    var time = now$1();
	    if (shouldInvoke(time)) {
	      return trailingEdge(time);
	    }
	    // Restart the timer.
	    timerId = setTimeout(timerExpired, remainingWait(time));
	  }

	  function trailingEdge(time) {
	    timerId = undefined;

	    // Only invoke if we have `lastArgs` which means `func` has been
	    // debounced at least once.
	    if (trailing && lastArgs) {
	      return invokeFunc(time);
	    }
	    lastArgs = lastThis = undefined;
	    return result;
	  }

	  function cancel() {
	    if (timerId !== undefined) {
	      clearTimeout(timerId);
	    }
	    lastInvokeTime = 0;
	    lastArgs = lastCallTime = lastThis = timerId = undefined;
	  }

	  function flush() {
	    return timerId === undefined ? result : trailingEdge(now$1());
	  }

	  function debounced() {
	    var time = now$1(),
	        isInvoking = shouldInvoke(time);

	    lastArgs = arguments;
	    lastThis = this;
	    lastCallTime = time;

	    if (isInvoking) {
	      if (timerId === undefined) {
	        return leadingEdge(lastCallTime);
	      }
	      if (maxing) {
	        // Handle invocations in a tight loop.
	        clearTimeout(timerId);
	        timerId = setTimeout(timerExpired, wait);
	        return invokeFunc(lastCallTime);
	      }
	    }
	    if (timerId === undefined) {
	      timerId = setTimeout(timerExpired, wait);
	    }
	    return result;
	  }
	  debounced.cancel = cancel;
	  debounced.flush = flush;
	  return debounced;
	}

	/*!
	 * camera-controls
	 * https://github.com/yomotsu/camera-controls
	 * (c) 2017 @yomotsu
	 * Released under the MIT License.
	 */
	// see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons#value
	const MOUSE_BUTTON = {
	    LEFT: 1,
	    RIGHT: 2,
	    MIDDLE: 4,
	};
	const ACTION = Object.freeze({
	    NONE: 0,
	    ROTATE: 1,
	    TRUCK: 2,
	    OFFSET: 4,
	    DOLLY: 8,
	    ZOOM: 16,
	    TOUCH_ROTATE: 32,
	    TOUCH_TRUCK: 64,
	    TOUCH_OFFSET: 128,
	    TOUCH_DOLLY: 256,
	    TOUCH_ZOOM: 512,
	    TOUCH_DOLLY_TRUCK: 1024,
	    TOUCH_DOLLY_OFFSET: 2048,
	    TOUCH_DOLLY_ROTATE: 4096,
	    TOUCH_ZOOM_TRUCK: 8192,
	    TOUCH_ZOOM_OFFSET: 16384,
	    TOUCH_ZOOM_ROTATE: 32768,
	});
	function isPerspectiveCamera(camera) {
	    return camera.isPerspectiveCamera;
	}
	function isOrthographicCamera(camera) {
	    return camera.isOrthographicCamera;
	}

	const PI_2 = Math.PI * 2;
	const PI_HALF = Math.PI / 2;

	const EPSILON = 1e-5;
	function approxZero(number, error = EPSILON) {
	    return Math.abs(number) < error;
	}
	function approxEquals(a, b, error = EPSILON) {
	    return approxZero(a - b, error);
	}
	function roundToStep(value, step) {
	    return Math.round(value / step) * step;
	}
	function infinityToMaxNumber(value) {
	    if (isFinite(value))
	        return value;
	    if (value < 0)
	        return -Number.MAX_VALUE;
	    return Number.MAX_VALUE;
	}
	function maxNumberToInfinity(value) {
	    if (Math.abs(value) < Number.MAX_VALUE)
	        return value;
	    return value * Infinity;
	}

	function extractClientCoordFromEvent(pointers, out) {
	    out.set(0, 0);
	    pointers.forEach((pointer) => {
	        out.x += pointer.clientX;
	        out.y += pointer.clientY;
	    });
	    out.x /= pointers.length;
	    out.y /= pointers.length;
	}

	function notSupportedInOrthographicCamera(camera, message) {
	    if (isOrthographicCamera(camera)) {
	        console.warn(`${message} is not supported in OrthographicCamera`);
	        return true;
	    }
	    return false;
	}

	/**
	 * A compat function for `Quaternion.invert()` / `Quaternion.inverse()`.
	 * `Quaternion.invert()` is introduced in r123 and `Quaternion.inverse()` emits a warning.
	 * We are going to use this compat for a while.
	 * @param target A target quaternion
	 */
	function quatInvertCompat(target) {
	    if (target.invert) {
	        target.invert();
	    }
	    else {
	        target.inverse();
	    }
	    return target;
	}

	class EventDispatcher {
	    constructor() {
	        this._listeners = {};
	    }
	    /**
	     * Adds the specified event listener.
	     * @param type event name
	     * @param listener handler function
	     * @category Methods
	     */
	    addEventListener(type, listener) {
	        const listeners = this._listeners;
	        if (listeners[type] === undefined)
	            listeners[type] = [];
	        if (listeners[type].indexOf(listener) === -1)
	            listeners[type].push(listener);
	    }
	    // hasEventListener( type: string, listener: Listener ): boolean {
	    // 	const listeners = this._listeners;
	    // 	return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
	    // }
	    /**
	     * Removes the specified event listener
	     * @param type event name
	     * @param listener handler function
	     * @category Methods
	     */
	    removeEventListener(type, listener) {
	        const listeners = this._listeners;
	        const listenerArray = listeners[type];
	        if (listenerArray !== undefined) {
	            const index = listenerArray.indexOf(listener);
	            if (index !== -1)
	                listenerArray.splice(index, 1);
	        }
	    }
	    /**
	     * Removes all event listeners
	     * @param type event name
	     * @category Methods
	     */
	    removeAllEventListeners(type) {
	        if (!type) {
	            this._listeners = {};
	            return;
	        }
	        if (Array.isArray(this._listeners[type]))
	            this._listeners[type].length = 0;
	    }
	    /**
	     * Fire an event type.
	     * @param event DispatcherEvent
	     * @category Methods
	     */
	    dispatchEvent(event) {
	        const listeners = this._listeners;
	        const listenerArray = listeners[event.type];
	        if (listenerArray !== undefined) {
	            event.target = this;
	            const array = listenerArray.slice(0);
	            for (let i = 0, l = array.length; i < l; i++) {
	                array[i].call(this, event);
	            }
	        }
	    }
	}

	const isBrowser = typeof window !== 'undefined';
	const isMac = isBrowser && /Mac/.test(navigator.platform);
	const isPointerEventsNotSupported = !(isBrowser && 'PointerEvent' in window); // Safari 12 does not support PointerEvents API
	const TOUCH_DOLLY_FACTOR = 1 / 8;
	let THREE;
	let _ORIGIN;
	let _AXIS_Y;
	let _AXIS_Z;
	let _v2;
	let _v3A$1;
	let _v3B;
	let _v3C;
	let _xColumn;
	let _yColumn;
	let _zColumn;
	let _deltaTarget;
	let _deltaOffset;
	let _sphericalA;
	let _sphericalB;
	let _box3A;
	let _box3B;
	let _sphere;
	let _quaternionA;
	let _quaternionB;
	let _rotationMatrix;
	let _raycaster;
	class CameraControls extends EventDispatcher {
	    /**
	     * Creates a `CameraControls` instance.
	     *
	     * Note:
	     * You **must install** three.js before using camera-controls. see [#install](#install)
	     * Not doing so will lead to runtime errors (`undefined` references to THREE).
	     *
	     * e.g.
	     * ```
	     * CameraControls.install( { THREE } );
	     * const cameraControls = new CameraControls( camera, domElement );
	     * ```
	     *
	     * @param camera A `THREE.PerspectiveCamera` or `THREE.OrthographicCamera` to be controlled.
	     * @param domElement A `HTMLElement` for the draggable area, usually `renderer.domElement`.
	     * @category Constructor
	     */
	    constructor(camera, domElement) {
	        super();
	        /**
	         * Minimum vertical angle in radians.
	         * The angle has to be between `0` and `.maxPolarAngle` inclusive.
	         * The default value is `0`.
	         *
	         * e.g.
	         * ```
	         * cameraControls.maxPolarAngle = 0;
	         * ```
	         * @category Properties
	         */
	        this.minPolarAngle = 0; // radians
	        /**
	         * Maximum vertical angle in radians.
	         * The angle has to be between `.maxPolarAngle` and `Math.PI` inclusive.
	         * The default value is `Math.PI`.
	         *
	         * e.g.
	         * ```
	         * cameraControls.maxPolarAngle = Math.PI;
	         * ```
	         * @category Properties
	         */
	        this.maxPolarAngle = Math.PI; // radians
	        /**
	         * Minimum horizontal angle in radians.
	         * The angle has to be less than `.maxAzimuthAngle`.
	         * The default value is `- Infinity`.
	         *
	         * e.g.
	         * ```
	         * cameraControls.minAzimuthAngle = - Infinity;
	         * ```
	         * @category Properties
	         */
	        this.minAzimuthAngle = -Infinity; // radians
	        /**
	         * Maximum horizontal angle in radians.
	         * The angle has to be greater than `.minAzimuthAngle`.
	         * The default value is `Infinity`.
	         *
	         * e.g.
	         * ```
	         * cameraControls.maxAzimuthAngle = Infinity;
	         * ```
	         * @category Properties
	         */
	        this.maxAzimuthAngle = Infinity; // radians
	        // How far you can dolly in and out ( PerspectiveCamera only )
	        /**
	         * Minimum distance for dolly. The value must be higher than `0`.
	         * PerspectiveCamera only.
	         * @category Properties
	         */
	        this.minDistance = 0;
	        /**
	         * Maximum distance for dolly. The value must be higher than `minDistance`.
	         * PerspectiveCamera only.
	         * @category Properties
	         */
	        this.maxDistance = Infinity;
	        /**
	         * `true` to enable Infinity Dolly.
	         * When the Dolly distance is less than the `minDistance`, radius of the sphere will be set `minDistance` automatically.
	         * @category Properties
	         */
	        this.infinityDolly = false;
	        /**
	         * Minimum camera zoom.
	         * @category Properties
	         */
	        this.minZoom = 0.01;
	        /**
	         * Maximum camera zoom.
	         * @category Properties
	         */
	        this.maxZoom = Infinity;
	        /**
	         * The damping inertia.
	         * The value must be between `Math.EPSILON` to `1` inclusive.
	         * Setting `1` to disable smooth transitions.
	         * @category Properties
	         */
	        this.dampingFactor = 0.05;
	        /**
	         * The damping inertia while dragging.
	         * The value must be between `Math.EPSILON` to `1` inclusive.
	         * Setting `1` to disable smooth transitions.
	         * @category Properties
	         */
	        this.draggingDampingFactor = 0.25;
	        /**
	         * Speed of azimuth (horizontal) rotation.
	         * @category Properties
	         */
	        this.azimuthRotateSpeed = 1.0;
	        /**
	         * Speed of polar (vertical) rotation.
	         * @category Properties
	         */
	        this.polarRotateSpeed = 1.0;
	        /**
	         * Speed of mouse-wheel dollying.
	         * @category Properties
	         */
	        this.dollySpeed = 1.0;
	        /**
	         * Speed of drag for truck and pedestal.
	         * @category Properties
	         */
	        this.truckSpeed = 2.0;
	        /**
	         * `true` to enable Dolly-in to the mouse cursor coords.
	         * @category Properties
	         */
	        this.dollyToCursor = false;
	        /**
	         * @category Properties
	         */
	        this.dragToOffset = false;
	        /**
	         * The same as `.screenSpacePanning` in three.js's OrbitControls.
	         * @category Properties
	         */
	        this.verticalDragToForward = false;
	        /**
	         * Friction ratio of the boundary.
	         * @category Properties
	         */
	        this.boundaryFriction = 0.0;
	        /**
	         * Controls how soon the `rest` event fires as the camera slows.
	         * @category Properties
	         */
	        this.restThreshold = 0.01;
	        /**
	         * An array of Meshes to collide with camera.
	         * Be aware colliderMeshes may decrease performance. The collision test uses 4 raycasters from the camera since the near plane has 4 corners.
	         * @category Properties
	         */
	        this.colliderMeshes = [];
	        /**
	         * Force cancel user dragging.
	         * @category Methods
	         */
	        // cancel will be overwritten in the constructor.
	        this.cancel = () => { };
	        this._enabled = true;
	        this._state = ACTION.NONE;
	        this._viewport = null;
	        this._dollyControlAmount = 0;
	        this._hasRested = true;
	        this._boundaryEnclosesCamera = false;
	        this._needsUpdate = true;
	        this._updatedLastTime = false;
	        this._elementRect = new DOMRect();
	        this._activePointers = [];
	        this._truckInternal = (deltaX, deltaY, dragToOffset) => {
	            if (isPerspectiveCamera(this._camera)) {
	                const offset = _v3A$1.copy(this._camera.position).sub(this._target);
	                // half of the fov is center to top of screen
	                const fov = this._camera.getEffectiveFOV() * THREE.MathUtils.DEG2RAD;
	                const targetDistance = offset.length() * Math.tan(fov * 0.5);
	                const truckX = (this.truckSpeed * deltaX * targetDistance / this._elementRect.height);
	                const pedestalY = (this.truckSpeed * deltaY * targetDistance / this._elementRect.height);
	                if (this.verticalDragToForward) {
	                    dragToOffset ?
	                        this.setFocalOffset(this._focalOffsetEnd.x + truckX, this._focalOffsetEnd.y, this._focalOffsetEnd.z, true) :
	                        this.truck(truckX, 0, true);
	                    this.forward(-pedestalY, true);
	                }
	                else {
	                    dragToOffset ?
	                        this.setFocalOffset(this._focalOffsetEnd.x + truckX, this._focalOffsetEnd.y + pedestalY, this._focalOffsetEnd.z, true) :
	                        this.truck(truckX, pedestalY, true);
	                }
	            }
	            else if (isOrthographicCamera(this._camera)) {
	                // orthographic
	                const camera = this._camera;
	                const truckX = deltaX * (camera.right - camera.left) / camera.zoom / this._elementRect.width;
	                const pedestalY = deltaY * (camera.top - camera.bottom) / camera.zoom / this._elementRect.height;
	                dragToOffset ?
	                    this.setFocalOffset(this._focalOffsetEnd.x + truckX, this._focalOffsetEnd.y + pedestalY, this._focalOffsetEnd.z, true) :
	                    this.truck(truckX, pedestalY, true);
	            }
	        };
	        this._rotateInternal = (deltaX, deltaY) => {
	            const theta = PI_2 * this.azimuthRotateSpeed * deltaX / this._elementRect.height; // divide by *height* to refer the resolution
	            const phi = PI_2 * this.polarRotateSpeed * deltaY / this._elementRect.height;
	            this.rotate(theta, phi, true);
	        };
	        this._dollyInternal = (delta, x, y) => {
	            const dollyScale = Math.pow(0.95, -delta * this.dollySpeed);
	            const distance = this._sphericalEnd.radius * dollyScale;
	            const prevRadius = this._sphericalEnd.radius;
	            const signedPrevRadius = prevRadius * (delta >= 0 ? -1 : 1);
	            this.dollyTo(distance);
	            if (this.infinityDolly && (distance < this.minDistance || this.maxDistance === this.minDistance)) {
	                this._camera.getWorldDirection(_v3A$1);
	                this._targetEnd.add(_v3A$1.normalize().multiplyScalar(signedPrevRadius));
	                this._target.add(_v3A$1.normalize().multiplyScalar(signedPrevRadius));
	            }
	            if (this.dollyToCursor) {
	                this._dollyControlAmount += this._sphericalEnd.radius - prevRadius;
	                if (this.infinityDolly && (distance < this.minDistance || this.maxDistance === this.minDistance)) {
	                    this._dollyControlAmount -= signedPrevRadius;
	                }
	                this._dollyControlCoord.set(x, y);
	            }
	            return;
	        };
	        this._zoomInternal = (delta, x, y) => {
	            const zoomScale = Math.pow(0.95, delta * this.dollySpeed);
	            // for both PerspectiveCamera and OrthographicCamera
	            this.zoomTo(this._zoom * zoomScale);
	            if (this.dollyToCursor) {
	                this._dollyControlAmount = this._zoomEnd;
	                this._dollyControlCoord.set(x, y);
	            }
	            return;
	        };
	        // Check if the user has installed THREE
	        if (typeof THREE === 'undefined') {
	            console.error('camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information.');
	        }
	        this._camera = camera;
	        this._yAxisUpSpace = new THREE.Quaternion().setFromUnitVectors(this._camera.up, _AXIS_Y);
	        this._yAxisUpSpaceInverse = quatInvertCompat(this._yAxisUpSpace.clone());
	        this._state = ACTION.NONE;
	        this._domElement = domElement;
	        this._domElement.style.touchAction = 'none';
	        this._domElement.style.userSelect = 'none';
	        this._domElement.style.webkitUserSelect = 'none';
	        // the location
	        this._target = new THREE.Vector3();
	        this._targetEnd = this._target.clone();
	        this._focalOffset = new THREE.Vector3();
	        this._focalOffsetEnd = this._focalOffset.clone();
	        // rotation
	        this._spherical = new THREE.Spherical().setFromVector3(_v3A$1.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace));
	        this._sphericalEnd = this._spherical.clone();
	        this._zoom = this._camera.zoom;
	        this._zoomEnd = this._zoom;
	        // collisionTest uses nearPlane.s
	        this._nearPlaneCorners = [
	            new THREE.Vector3(),
	            new THREE.Vector3(),
	            new THREE.Vector3(),
	            new THREE.Vector3(),
	        ];
	        this._updateNearPlaneCorners();
	        // Target cannot move outside of this box
	        this._boundary = new THREE.Box3(new THREE.Vector3(-Infinity, -Infinity, -Infinity), new THREE.Vector3(Infinity, Infinity, Infinity));
	        // reset
	        this._target0 = this._target.clone();
	        this._position0 = this._camera.position.clone();
	        this._zoom0 = this._zoom;
	        this._focalOffset0 = this._focalOffset.clone();
	        this._dollyControlAmount = 0;
	        this._dollyControlCoord = new THREE.Vector2();
	        // configs
	        this.mouseButtons = {
	            left: ACTION.ROTATE,
	            middle: ACTION.DOLLY,
	            right: ACTION.TRUCK,
	            wheel: isPerspectiveCamera(this._camera) ? ACTION.DOLLY :
	                isOrthographicCamera(this._camera) ? ACTION.ZOOM :
	                    ACTION.NONE,
	        };
	        this.touches = {
	            one: ACTION.TOUCH_ROTATE,
	            two: isPerspectiveCamera(this._camera) ? ACTION.TOUCH_DOLLY_TRUCK :
	                isOrthographicCamera(this._camera) ? ACTION.TOUCH_ZOOM_TRUCK :
	                    ACTION.NONE,
	            three: ACTION.TOUCH_TRUCK,
	        };
	        if (this._domElement) {
	            const dragStartPosition = new THREE.Vector2();
	            const lastDragPosition = new THREE.Vector2();
	            const dollyStart = new THREE.Vector2();
	            const onPointerDown = (event) => {
	                if (!this._enabled)
	                    return;
	                // Don't call `event.preventDefault()` on the pointerdown event
	                // to keep receiving pointermove evens outside dragging iframe
	                // https://taye.me/blog/tips/2015/11/16/mouse-drag-outside-iframe/
	                const pointer = {
	                    pointerId: event.pointerId,
	                    clientX: event.clientX,
	                    clientY: event.clientY,
	                    deltaX: 0,
	                    deltaY: 0,
	                };
	                this._activePointers.push(pointer);
	                // eslint-disable-next-line no-undef
	                this._domElement.ownerDocument.removeEventListener('pointermove', onPointerMove, { passive: false });
	                this._domElement.ownerDocument.removeEventListener('pointerup', onPointerUp);
	                this._domElement.ownerDocument.addEventListener('pointermove', onPointerMove, { passive: false });
	                this._domElement.ownerDocument.addEventListener('pointerup', onPointerUp);
	                startDragging(event);
	            };
	            const onMouseDown = (event) => {
	                if (!this._enabled)
	                    return;
	                const pointer = {
	                    pointerId: 0,
	                    clientX: event.clientX,
	                    clientY: event.clientY,
	                    deltaX: 0,
	                    deltaY: 0,
	                };
	                this._activePointers.push(pointer);
	                // see https://github.com/microsoft/TypeScript/issues/32912#issuecomment-522142969
	                // eslint-disable-next-line no-undef
	                this._domElement.ownerDocument.removeEventListener('mousemove', onMouseMove);
	                this._domElement.ownerDocument.removeEventListener('mouseup', onMouseUp);
	                this._domElement.ownerDocument.addEventListener('mousemove', onMouseMove);
	                this._domElement.ownerDocument.addEventListener('mouseup', onMouseUp);
	                startDragging(event);
	            };
	            const onTouchStart = (event) => {
	                if (!this._enabled)
	                    return;
	                event.preventDefault();
	                Array.prototype.forEach.call(event.changedTouches, (touch) => {
	                    const pointer = {
	                        pointerId: touch.identifier,
	                        clientX: touch.clientX,
	                        clientY: touch.clientY,
	                        deltaX: 0,
	                        deltaY: 0,
	                    };
	                    this._activePointers.push(pointer);
	                });
	                // eslint-disable-next-line no-undef
	                this._domElement.ownerDocument.removeEventListener('touchmove', onTouchMove, { passive: false });
	                this._domElement.ownerDocument.removeEventListener('touchend', onTouchEnd);
	                this._domElement.ownerDocument.addEventListener('touchmove', onTouchMove, { passive: false });
	                this._domElement.ownerDocument.addEventListener('touchend', onTouchEnd);
	                startDragging(event);
	            };
	            const onPointerMove = (event) => {
	                if (event.cancelable)
	                    event.preventDefault();
	                const pointerId = event.pointerId;
	                const pointer = this._findPointerById(pointerId);
	                if (!pointer)
	                    return;
	                pointer.clientX = event.clientX;
	                pointer.clientY = event.clientY;
	                pointer.deltaX = event.movementX;
	                pointer.deltaY = event.movementY;
	                if (event.pointerType === 'touch') {
	                    switch (this._activePointers.length) {
	                        case 1:
	                            this._state = this.touches.one;
	                            break;
	                        case 2:
	                            this._state = this.touches.two;
	                            break;
	                        case 3:
	                            this._state = this.touches.three;
	                            break;
	                    }
	                }
	                else {
	                    this._state = 0;
	                    if ((event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT) {
	                        this._state = this._state | this.mouseButtons.left;
	                    }
	                    if ((event.buttons & MOUSE_BUTTON.MIDDLE) === MOUSE_BUTTON.MIDDLE) {
	                        this._state = this._state | this.mouseButtons.middle;
	                    }
	                    if ((event.buttons & MOUSE_BUTTON.RIGHT) === MOUSE_BUTTON.RIGHT) {
	                        this._state = this._state | this.mouseButtons.right;
	                    }
	                }
	                dragging();
	            };
	            const onMouseMove = (event) => {
	                const pointer = this._findPointerById(0);
	                if (!pointer)
	                    return;
	                pointer.clientX = event.clientX;
	                pointer.clientY = event.clientY;
	                pointer.deltaX = event.movementX;
	                pointer.deltaY = event.movementY;
	                this._state = 0;
	                if ((event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT) {
	                    this._state = this._state | this.mouseButtons.left;
	                }
	                if ((event.buttons & MOUSE_BUTTON.MIDDLE) === MOUSE_BUTTON.MIDDLE) {
	                    this._state = this._state | this.mouseButtons.middle;
	                }
	                if ((event.buttons & MOUSE_BUTTON.RIGHT) === MOUSE_BUTTON.RIGHT) {
	                    this._state = this._state | this.mouseButtons.right;
	                }
	                dragging();
	            };
	            const onTouchMove = (event) => {
	                if (event.cancelable)
	                    event.preventDefault();
	                Array.prototype.forEach.call(event.changedTouches, (touch) => {
	                    const pointerId = touch.identifier;
	                    const pointer = this._findPointerById(pointerId);
	                    if (!pointer)
	                        return;
	                    pointer.clientX = touch.clientX;
	                    pointer.clientY = touch.clientY;
	                    // touch event does not have movementX and movementY.
	                });
	                dragging();
	            };
	            const onPointerUp = (event) => {
	                const pointerId = event.pointerId;
	                const pointer = this._findPointerById(pointerId);
	                pointer && this._activePointers.splice(this._activePointers.indexOf(pointer), 1);
	                if (event.pointerType === 'touch') {
	                    switch (this._activePointers.length) {
	                        case 0:
	                            this._state = ACTION.NONE;
	                            break;
	                        case 1:
	                            this._state = this.touches.one;
	                            break;
	                        case 2:
	                            this._state = this.touches.two;
	                            break;
	                        case 3:
	                            this._state = this.touches.three;
	                            break;
	                    }
	                }
	                else {
	                    this._state = ACTION.NONE;
	                }
	                endDragging();
	            };
	            const onMouseUp = () => {
	                const pointer = this._findPointerById(0);
	                pointer && this._activePointers.splice(this._activePointers.indexOf(pointer), 1);
	                this._state = ACTION.NONE;
	                endDragging();
	            };
	            const onTouchEnd = (event) => {
	                Array.prototype.forEach.call(event.changedTouches, (touch) => {
	                    const pointerId = touch.identifier;
	                    const pointer = this._findPointerById(pointerId);
	                    pointer && this._activePointers.splice(this._activePointers.indexOf(pointer), 1);
	                });
	                switch (this._activePointers.length) {
	                    case 0:
	                        this._state = ACTION.NONE;
	                        break;
	                    case 1:
	                        this._state = this.touches.one;
	                        break;
	                    case 2:
	                        this._state = this.touches.two;
	                        break;
	                    case 3:
	                        this._state = this.touches.three;
	                        break;
	                }
	                endDragging();
	            };
	            let lastScrollTimeStamp = -1;
	            const onMouseWheel = (event) => {
	                if (!this._enabled || this.mouseButtons.wheel === ACTION.NONE)
	                    return;
	                event.preventDefault();
	                if (this.dollyToCursor ||
	                    this.mouseButtons.wheel === ACTION.ROTATE ||
	                    this.mouseButtons.wheel === ACTION.TRUCK) {
	                    const now = performance.now();
	                    // only need to fire this at scroll start.
	                    if (lastScrollTimeStamp - now < 1000)
	                        this._getClientRect(this._elementRect);
	                    lastScrollTimeStamp = now;
	                }
	                // Ref: https://github.com/cedricpinson/osgjs/blob/00e5a7e9d9206c06fdde0436e1d62ab7cb5ce853/sources/osgViewer/input/source/InputSourceMouse.js#L89-L103
	                const deltaYFactor = isMac ? -1 : -3;
	                const delta = (event.deltaMode === 1) ? event.deltaY / deltaYFactor : event.deltaY / (deltaYFactor * 10);
	                const x = this.dollyToCursor ? (event.clientX - this._elementRect.x) / this._elementRect.width * 2 - 1 : 0;
	                const y = this.dollyToCursor ? (event.clientY - this._elementRect.y) / this._elementRect.height * -2 + 1 : 0;
	                switch (this.mouseButtons.wheel) {
	                    case ACTION.ROTATE: {
	                        this._rotateInternal(event.deltaX, event.deltaY);
	                        break;
	                    }
	                    case ACTION.TRUCK: {
	                        this._truckInternal(event.deltaX, event.deltaY, false);
	                        break;
	                    }
	                    case ACTION.OFFSET: {
	                        this._truckInternal(event.deltaX, event.deltaY, true);
	                        break;
	                    }
	                    case ACTION.DOLLY: {
	                        this._dollyInternal(-delta, x, y);
	                        break;
	                    }
	                    case ACTION.ZOOM: {
	                        this._zoomInternal(-delta, x, y);
	                        break;
	                    }
	                }
	                this.dispatchEvent({ type: 'control' });
	            };
	            const onContextMenu = (event) => {
	                if (!this._enabled)
	                    return;
	                event.preventDefault();
	            };
	            const startDragging = (event) => {
	                if (!this._enabled)
	                    return;
	                extractClientCoordFromEvent(this._activePointers, _v2);
	                this._getClientRect(this._elementRect);
	                dragStartPosition.copy(_v2);
	                lastDragPosition.copy(_v2);
	                const isMultiTouch = this._activePointers.length >= 2;
	                if (isMultiTouch) {
	                    // 2 finger pinch
	                    const dx = _v2.x - this._activePointers[1].clientX;
	                    const dy = _v2.y - this._activePointers[1].clientY;
	                    const distance = Math.sqrt(dx * dx + dy * dy);
	                    dollyStart.set(0, distance);
	                    // center coords of 2 finger truck
	                    const x = (this._activePointers[0].clientX + this._activePointers[1].clientX) * 0.5;
	                    const y = (this._activePointers[0].clientY + this._activePointers[1].clientY) * 0.5;
	                    lastDragPosition.set(x, y);
	                }
	                if ('touches' in event ||
	                    'pointerType' in event && event.pointerType === 'touch') {
	                    switch (this._activePointers.length) {
	                        case 1:
	                            this._state = this.touches.one;
	                            break;
	                        case 2:
	                            this._state = this.touches.two;
	                            break;
	                        case 3:
	                            this._state = this.touches.three;
	                            break;
	                    }
	                }
	                else {
	                    this._state = 0;
	                    if ((event.buttons & MOUSE_BUTTON.LEFT) === MOUSE_BUTTON.LEFT) {
	                        this._state = this._state | this.mouseButtons.left;
	                    }
	                    if ((event.buttons & MOUSE_BUTTON.MIDDLE) === MOUSE_BUTTON.MIDDLE) {
	                        this._state = this._state | this.mouseButtons.middle;
	                    }
	                    if ((event.buttons & MOUSE_BUTTON.RIGHT) === MOUSE_BUTTON.RIGHT) {
	                        this._state = this._state | this.mouseButtons.right;
	                    }
	                }
	                this.dispatchEvent({ type: 'controlstart' });
	            };
	            const dragging = () => {
	                if (!this._enabled)
	                    return;
	                extractClientCoordFromEvent(this._activePointers, _v2);
	                // When pointer lock is enabled clientX, clientY, screenX, and screenY remain 0.
	                // If pointer lock is enabled, use the Delta directory, and assume active-pointer is not multiple.
	                const isPointerLockActive = this._domElement && document.pointerLockElement === this._domElement;
	                const deltaX = isPointerLockActive ? -this._activePointers[0].deltaX : lastDragPosition.x - _v2.x;
	                const deltaY = isPointerLockActive ? -this._activePointers[0].deltaY : lastDragPosition.y - _v2.y;
	                lastDragPosition.copy(_v2);
	                if ((this._state & ACTION.ROTATE) === ACTION.ROTATE ||
	                    (this._state & ACTION.TOUCH_ROTATE) === ACTION.TOUCH_ROTATE ||
	                    (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE ||
	                    (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) {
	                    this._rotateInternal(deltaX, deltaY);
	                }
	                if ((this._state & ACTION.DOLLY) === ACTION.DOLLY ||
	                    (this._state & ACTION.ZOOM) === ACTION.ZOOM) {
	                    const dollyX = this.dollyToCursor ? (dragStartPosition.x - this._elementRect.x) / this._elementRect.width * 2 - 1 : 0;
	                    const dollyY = this.dollyToCursor ? (dragStartPosition.y - this._elementRect.y) / this._elementRect.height * -2 + 1 : 0;
	                    this._state === ACTION.DOLLY ?
	                        this._dollyInternal(deltaY * TOUCH_DOLLY_FACTOR, dollyX, dollyY) :
	                        this._zoomInternal(deltaY * TOUCH_DOLLY_FACTOR, dollyX, dollyY);
	                }
	                if ((this._state & ACTION.TOUCH_DOLLY) === ACTION.TOUCH_DOLLY ||
	                    (this._state & ACTION.TOUCH_ZOOM) === ACTION.TOUCH_ZOOM ||
	                    (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK ||
	                    (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK ||
	                    (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET ||
	                    (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET ||
	                    (this._state & ACTION.TOUCH_DOLLY_ROTATE) === ACTION.TOUCH_DOLLY_ROTATE ||
	                    (this._state & ACTION.TOUCH_ZOOM_ROTATE) === ACTION.TOUCH_ZOOM_ROTATE) {
	                    const dx = _v2.x - this._activePointers[1].clientX;
	                    const dy = _v2.y - this._activePointers[1].clientY;
	                    const distance = Math.sqrt(dx * dx + dy * dy);
	                    const dollyDelta = dollyStart.y - distance;
	                    dollyStart.set(0, distance);
	                    const dollyX = this.dollyToCursor ? (lastDragPosition.x - this._elementRect.x) / this._elementRect.width * 2 - 1 : 0;
	                    const dollyY = this.dollyToCursor ? (lastDragPosition.y - this._elementRect.y) / this._elementRect.height * -2 + 1 : 0;
	                    this._state === ACTION.TOUCH_DOLLY ||
	                        this._state === ACTION.TOUCH_DOLLY_ROTATE ||
	                        this._state === ACTION.TOUCH_DOLLY_TRUCK ||
	                        this._state === ACTION.TOUCH_DOLLY_OFFSET ?
	                        this._dollyInternal(dollyDelta * TOUCH_DOLLY_FACTOR, dollyX, dollyY) :
	                        this._zoomInternal(dollyDelta * TOUCH_DOLLY_FACTOR, dollyX, dollyY);
	                }
	                if ((this._state & ACTION.TRUCK) === ACTION.TRUCK ||
	                    (this._state & ACTION.TOUCH_TRUCK) === ACTION.TOUCH_TRUCK ||
	                    (this._state & ACTION.TOUCH_DOLLY_TRUCK) === ACTION.TOUCH_DOLLY_TRUCK ||
	                    (this._state & ACTION.TOUCH_ZOOM_TRUCK) === ACTION.TOUCH_ZOOM_TRUCK) {
	                    this._truckInternal(deltaX, deltaY, false);
	                }
	                if ((this._state & ACTION.OFFSET) === ACTION.OFFSET ||
	                    (this._state & ACTION.TOUCH_OFFSET) === ACTION.TOUCH_OFFSET ||
	                    (this._state & ACTION.TOUCH_DOLLY_OFFSET) === ACTION.TOUCH_DOLLY_OFFSET ||
	                    (this._state & ACTION.TOUCH_ZOOM_OFFSET) === ACTION.TOUCH_ZOOM_OFFSET) {
	                    this._truckInternal(deltaX, deltaY, true);
	                }
	                this.dispatchEvent({ type: 'control' });
	            };
	            const endDragging = () => {
	                extractClientCoordFromEvent(this._activePointers, _v2);
	                lastDragPosition.copy(_v2);
	                if (this._activePointers.length === 0) {
	                    // eslint-disable-next-line no-undef
	                    this._domElement.ownerDocument.removeEventListener('pointermove', onPointerMove, { passive: false });
	                    this._domElement.ownerDocument.removeEventListener('pointerup', onPointerUp);
	                    // eslint-disable-next-line no-undef
	                    this._domElement.ownerDocument.removeEventListener('touchmove', onTouchMove, { passive: false });
	                    this._domElement.ownerDocument.removeEventListener('touchend', onTouchEnd);
	                    this.dispatchEvent({ type: 'controlend' });
	                }
	            };
	            this._domElement.addEventListener('pointerdown', onPointerDown);
	            isPointerEventsNotSupported && this._domElement.addEventListener('mousedown', onMouseDown);
	            isPointerEventsNotSupported && this._domElement.addEventListener('touchstart', onTouchStart);
	            this._domElement.addEventListener('pointercancel', onPointerUp);
	            this._domElement.addEventListener('wheel', onMouseWheel, { passive: false });
	            this._domElement.addEventListener('contextmenu', onContextMenu);
	            this._removeAllEventListeners = () => {
	                this._domElement.removeEventListener('pointerdown', onPointerDown);
	                this._domElement.removeEventListener('mousedown', onMouseDown);
	                this._domElement.removeEventListener('touchstart', onTouchStart);
	                this._domElement.removeEventListener('pointercancel', onPointerUp);
	                // https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#matching_event_listeners_for_removal
	                // > it's probably wise to use the same values used for the call to `addEventListener()` when calling `removeEventListener()`
	                // see https://github.com/microsoft/TypeScript/issues/32912#issuecomment-522142969
	                // eslint-disable-next-line no-undef
	                this._domElement.removeEventListener('wheel', onMouseWheel, { passive: false });
	                this._domElement.removeEventListener('contextmenu', onContextMenu);
	                // eslint-disable-next-line no-undef
	                this._domElement.ownerDocument.removeEventListener('pointermove', onPointerMove, { passive: false });
	                this._domElement.ownerDocument.removeEventListener('mousemove', onMouseMove);
	                // eslint-disable-next-line no-undef
	                this._domElement.ownerDocument.removeEventListener('touchmove', onTouchMove, { passive: false });
	                this._domElement.ownerDocument.removeEventListener('pointerup', onPointerUp);
	                this._domElement.ownerDocument.removeEventListener('mouseup', onMouseUp);
	                this._domElement.ownerDocument.removeEventListener('touchend', onTouchEnd);
	            };
	            this.cancel = () => {
	                if (this._state === ACTION.NONE)
	                    return;
	                this._state = ACTION.NONE;
	                this._activePointers.length = 0;
	                endDragging();
	            };
	        }
	        this.update(0);
	    }
	    /**
	     * Injects THREE as the dependency. You can then proceed to use CameraControls.
	     *
	     * e.g
	     * ```javascript
	     * CameraControls.install( { THREE: THREE } );
	     * ```
	     *
	     * Note: If you do not wish to use enter three.js to reduce file size(tree-shaking for example), make a subset to install.
	     *
	     * ```js
	     * import {
	     * 	Vector2,
	     * 	Vector3,
	     * 	Vector4,
	     * 	Quaternion,
	     * 	Matrix4,
	     * 	Spherical,
	     * 	Box3,
	     * 	Sphere,
	     * 	Raycaster,
	     * 	MathUtils,
	     * } from 'three';
	     *
	     * const subsetOfTHREE = {
	     * 	Vector2   : Vector2,
	     * 	Vector3   : Vector3,
	     * 	Vector4   : Vector4,
	     * 	Quaternion: Quaternion,
	     * 	Matrix4   : Matrix4,
	     * 	Spherical : Spherical,
	     * 	Box3      : Box3,
	     * 	Sphere    : Sphere,
	     * 	Raycaster : Raycaster,
	     * 	MathUtils : {
	     * 		DEG2RAD: MathUtils.DEG2RAD,
	     * 		clamp: MathUtils.clamp,
	     * 	},
	     * };

	     * CameraControls.install( { THREE: subsetOfTHREE } );
	     * ```
	     * @category Statics
	     */
	    static install(libs) {
	        THREE = libs.THREE;
	        _ORIGIN = Object.freeze(new THREE.Vector3(0, 0, 0));
	        _AXIS_Y = Object.freeze(new THREE.Vector3(0, 1, 0));
	        _AXIS_Z = Object.freeze(new THREE.Vector3(0, 0, 1));
	        _v2 = new THREE.Vector2();
	        _v3A$1 = new THREE.Vector3();
	        _v3B = new THREE.Vector3();
	        _v3C = new THREE.Vector3();
	        _xColumn = new THREE.Vector3();
	        _yColumn = new THREE.Vector3();
	        _zColumn = new THREE.Vector3();
	        _deltaTarget = new THREE.Vector3();
	        _deltaOffset = new THREE.Vector3();
	        _sphericalA = new THREE.Spherical();
	        _sphericalB = new THREE.Spherical();
	        _box3A = new THREE.Box3();
	        _box3B = new THREE.Box3();
	        _sphere = new THREE.Sphere();
	        _quaternionA = new THREE.Quaternion();
	        _quaternionB = new THREE.Quaternion();
	        _rotationMatrix = new THREE.Matrix4();
	        _raycaster = new THREE.Raycaster();
	    }
	    /**
	     * list all ACTIONs
	     * @category Statics
	     */
	    static get ACTION() {
	        return ACTION;
	    }
	    /**
	     * The camera to be controlled
	     * @category Properties
	     */
	    get camera() {
	        return this._camera;
	    }
	    set camera(camera) {
	        this._camera = camera;
	        this.updateCameraUp();
	        this._camera.updateProjectionMatrix();
	        this._updateNearPlaneCorners();
	        this._needsUpdate = true;
	    }
	    /**
	     * Whether or not the controls are enabled.
	     * `false` to disable user dragging/touch-move, but all methods works.
	     * @category Properties
	     */
	    get enabled() {
	        return this._enabled;
	    }
	    set enabled(enabled) {
	        this._enabled = enabled;
	        if (enabled) {
	            this._domElement.style.touchAction = 'none';
	            this._domElement.style.userSelect = 'none';
	            this._domElement.style.webkitUserSelect = 'none';
	        }
	        else {
	            this.cancel();
	            this._domElement.style.touchAction = '';
	            this._domElement.style.userSelect = '';
	            this._domElement.style.webkitUserSelect = '';
	        }
	    }
	    /**
	     * Returns `true` if the controls are active updating.
	     * readonly value.
	     * @category Properties
	     */
	    get active() {
	        return !this._hasRested;
	    }
	    /**
	     * Getter for the current `ACTION`.
	     * readonly value.
	     * @category Properties
	     */
	    get currentAction() {
	        return this._state;
	    }
	    /**
	     * get/set Current distance.
	     * @category Properties
	     */
	    get distance() {
	        return this._spherical.radius;
	    }
	    set distance(distance) {
	        if (this._spherical.radius === distance &&
	            this._sphericalEnd.radius === distance)
	            return;
	        this._spherical.radius = distance;
	        this._sphericalEnd.radius = distance;
	        this._needsUpdate = true;
	    }
	    // horizontal angle
	    /**
	     * get/set the azimuth angle (horizontal) in radians.
	     * Every 360 degrees turn is added to `.azimuthAngle` value, which is accumulative.
	     * @category Properties
	     */
	    get azimuthAngle() {
	        return this._spherical.theta;
	    }
	    set azimuthAngle(azimuthAngle) {
	        if (this._spherical.theta === azimuthAngle &&
	            this._sphericalEnd.theta === azimuthAngle)
	            return;
	        this._spherical.theta = azimuthAngle;
	        this._sphericalEnd.theta = azimuthAngle;
	        this._needsUpdate = true;
	    }
	    // vertical angle
	    /**
	     * get/set the polar angle (vertical) in radians.
	     * @category Properties
	     */
	    get polarAngle() {
	        return this._spherical.phi;
	    }
	    set polarAngle(polarAngle) {
	        if (this._spherical.phi === polarAngle &&
	            this._sphericalEnd.phi === polarAngle)
	            return;
	        this._spherical.phi = polarAngle;
	        this._sphericalEnd.phi = polarAngle;
	        this._needsUpdate = true;
	    }
	    /**
	     * Whether camera position should be enclosed in the boundary or not.
	     * @category Properties
	     */
	    get boundaryEnclosesCamera() {
	        return this._boundaryEnclosesCamera;
	    }
	    set boundaryEnclosesCamera(boundaryEnclosesCamera) {
	        this._boundaryEnclosesCamera = boundaryEnclosesCamera;
	        this._needsUpdate = true;
	    }
	    /**
	     * Adds the specified event listener.
	     * Applicable event types (which is `K`) are:
	     * | Event name          | Timing |
	     * | ------------------- | ------ |
	     * | `'controlstart'`    | When the user starts to control the camera via mouse / touches. ¹ |
	     * | `'control'`         | When the user controls the camera (dragging). |
	     * | `'controlend'`      | When the user ends to control the camera. ¹ |
	     * | `'transitionstart'` | When any kind of transition starts, either user control or using a method with `enableTransition = true` |
	     * | `'update'`          | When the camera position is updated. |
	     * | `'wake'`            | When the camera starts moving. |
	     * | `'rest'`            | When the camera movement is below `.restThreshold` ². |
	     * | `'sleep'`           | When the camera end moving. |
	     *
	     * 1. `mouseButtons.wheel` (Mouse wheel control) does not emit `'controlstart'` and `'controlend'`. `mouseButtons.wheel` uses scroll-event internally, and scroll-event happens intermittently. That means "start" and "end" cannot be detected.
	     * 2. Due to damping, `sleep` will usually fire a few seconds after the camera _appears_ to have stopped moving. If you want to do something (e.g. enable UI, perform another transition) at the point when the camera has stopped, you probably want the `rest` event. This can be fine tuned using the `.restThreshold` parameter. See the [Rest and Sleep Example](https://yomotsu.github.io/camera-controls/examples/rest-and-sleep.html).
	     *
	     * e.g.
	     * ```
	     * cameraControl.addEventListener( 'controlstart', myCallbackFunction );
	     * ```
	     * @param type event name
	     * @param listener handler function
	     * @category Methods
	     */
	    addEventListener(type, listener) {
	        super.addEventListener(type, listener);
	    }
	    /**
	     * Removes the specified event listener
	     * e.g.
	     * ```
	     * cameraControl.addEventListener( 'controlstart', myCallbackFunction );
	     * ```
	     * @param type event name
	     * @param listener handler function
	     * @category Methods
	     */
	    removeEventListener(type, listener) {
	        super.removeEventListener(type, listener);
	    }
	    /**
	     * Rotate azimuthal angle(horizontal) and polar angle(vertical).
	     * Every value is added to the current value.
	     * @param azimuthAngle Azimuth rotate angle. In radian.
	     * @param polarAngle Polar rotate angle. In radian.
	     * @param enableTransition Whether to move smoothly or immediately
	     * @category Methods
	     */
	    rotate(azimuthAngle, polarAngle, enableTransition = false) {
	        return this.rotateTo(this._sphericalEnd.theta + azimuthAngle, this._sphericalEnd.phi + polarAngle, enableTransition);
	    }
	    /**
	     * Rotate azimuthal angle(horizontal) to the given angle and keep the same polar angle(vertical) target.
	     *
	     * e.g.
	     * ```
	     * cameraControls.rotateAzimuthTo( 30 * THREE.MathUtils.DEG2RAD, true );
	     * ```
	     * @param azimuthAngle Azimuth rotate angle. In radian.
	     * @param enableTransition Whether to move smoothly or immediately
	     * @category Methods
	     */
	    rotateAzimuthTo(azimuthAngle, enableTransition = false) {
	        return this.rotateTo(azimuthAngle, this._sphericalEnd.phi, enableTransition);
	    }
	    /**
	     * Rotate polar angle(vertical) to the given angle and keep the same azimuthal angle(horizontal) target.
	     *
	     * e.g.
	     * ```
	     * cameraControls.rotatePolarTo( 30 * THREE.MathUtils.DEG2RAD, true );
	     * ```
	     * @param polarAngle Polar rotate angle. In radian.
	     * @param enableTransition Whether to move smoothly or immediately
	     * @category Methods
	     */
	    rotatePolarTo(polarAngle, enableTransition = false) {
	        return this.rotateTo(this._sphericalEnd.theta, polarAngle, enableTransition);
	    }
	    /**
	     * Rotate azimuthal angle(horizontal) and polar angle(vertical) to the given angle.
	     * Camera view will rotate over the orbit pivot absolutely:
	     *
	     * azimuthAngle
	     * ```
	     *       0º
	     *         \
	     * 90º -----+----- -90º
	     *           \
	     *           180º
	     * ```
	     * | direction | angle                  |
	     * | --------- | ---------------------- |
	     * | front     | 0º                     |
	     * | left      | 90º (`Math.PI / 2`)    |
	     * | right     | -90º (`- Math.PI / 2`) |
	     * | back      | 180º (`Math.PI`)       |
	     *
	     * polarAngle
	     * ```
	     *     180º
	     *      |
	     *      90º
	     *      |
	     *      0º
	     * ```
	     * | direction            | angle                  |
	     * | -------------------- | ---------------------- |
	     * | top/sky              | 180º (`Math.PI`)       |
	     * | horizontal from view | 90º (`Math.PI / 2`)    |
	     * | bottom/floor         | 0º                     |
	     *
	     * @param azimuthAngle Azimuth rotate angle to. In radian.
	     * @param polarAngle Polar rotate angle to. In radian.
	     * @param enableTransition  Whether to move smoothly or immediately
	     * @category Methods
	     */
	    rotateTo(azimuthAngle, polarAngle, enableTransition = false) {
	        const theta = THREE.MathUtils.clamp(azimuthAngle, this.minAzimuthAngle, this.maxAzimuthAngle);
	        const phi = THREE.MathUtils.clamp(polarAngle, this.minPolarAngle, this.maxPolarAngle);
	        this._sphericalEnd.theta = theta;
	        this._sphericalEnd.phi = phi;
	        this._sphericalEnd.makeSafe();
	        this._needsUpdate = true;
	        if (!enableTransition) {
	            this._spherical.theta = this._sphericalEnd.theta;
	            this._spherical.phi = this._sphericalEnd.phi;
	        }
	        const resolveImmediately = !enableTransition ||
	            approxEquals(this._spherical.theta, this._sphericalEnd.theta, this.restThreshold) &&
	                approxEquals(this._spherical.phi, this._sphericalEnd.phi, this.restThreshold);
	        return this._createOnRestPromise(resolveImmediately);
	    }
	    /**
	     * Dolly in/out camera position.
	     * @param distance Distance of dollyIn. Negative number for dollyOut.
	     * @param enableTransition Whether to move smoothly or immediately.
	     * @category Methods
	     */
	    dolly(distance, enableTransition = false) {
	        return this.dollyTo(this._sphericalEnd.radius - distance, enableTransition);
	    }
	    /**
	     * Dolly in/out camera position to given distance.
	     * @param distance Distance of dolly.
	     * @param enableTransition Whether to move smoothly or immediately.
	     * @category Methods
	     */
	    dollyTo(distance, enableTransition = false) {
	        const lastRadius = this._sphericalEnd.radius;
	        const newRadius = THREE.MathUtils.clamp(distance, this.minDistance, this.maxDistance);
	        const hasCollider = this.colliderMeshes.length >= 1;
	        if (hasCollider) {
	            const maxDistanceByCollisionTest = this._collisionTest();
	            const isCollided = approxEquals(maxDistanceByCollisionTest, this._spherical.radius);
	            const isDollyIn = lastRadius > newRadius;
	            if (!isDollyIn && isCollided)
	                return Promise.resolve();
	            this._sphericalEnd.radius = Math.min(newRadius, maxDistanceByCollisionTest);
	        }
	        else {
	            this._sphericalEnd.radius = newRadius;
	        }
	        this._needsUpdate = true;
	        if (!enableTransition) {
	            this._spherical.radius = this._sphericalEnd.radius;
	        }
	        const resolveImmediately = !enableTransition || approxEquals(this._spherical.radius, this._sphericalEnd.radius, this.restThreshold);
	        return this._createOnRestPromise(resolveImmediately);
	    }
	    /**
	     * Zoom in/out camera. The value is added to camera zoom.
	     * Limits set with `.minZoom` and `.maxZoom`
	     * @param zoomStep zoom scale
	     * @param enableTransition Whether to move smoothly or immediately
	     * @category Methods
	     */
	    zoom(zoomStep, enableTransition = false) {
	        return this.zoomTo(this._zoomEnd + zoomStep, enableTransition);
	    }
	    /**
	     * Zoom in/out camera to given scale. The value overwrites camera zoom.
	     * Limits set with .minZoom and .maxZoom
	     * @param zoom
	     * @param enableTransition
	     * @category Methods
	     */
	    zoomTo(zoom, enableTransition = false) {
	        this._zoomEnd = THREE.MathUtils.clamp(zoom, this.minZoom, this.maxZoom);
	        this._needsUpdate = true;
	        if (!enableTransition) {
	            this._zoom = this._zoomEnd;
	        }
	        const resolveImmediately = !enableTransition || approxEquals(this._zoom, this._zoomEnd, this.restThreshold);
	        return this._createOnRestPromise(resolveImmediately);
	    }
	    /**
	     * @deprecated `pan()` has been renamed to `truck()`
	     * @category Methods
	     */
	    pan(x, y, enableTransition = false) {
	        console.warn('`pan` has been renamed to `truck`');
	        return this.truck(x, y, enableTransition);
	    }
	    /**
	     * Truck and pedestal camera using current azimuthal angle
	     * @param x Horizontal translate amount
	     * @param y Vertical translate amount
	     * @param enableTransition Whether to move smoothly or immediately
	     * @category Methods
	     */
	    truck(x, y, enableTransition = false) {
	        this._camera.updateMatrix();
	        _xColumn.setFromMatrixColumn(this._camera.matrix, 0);
	        _yColumn.setFromMatrixColumn(this._camera.matrix, 1);
	        _xColumn.multiplyScalar(x);
	        _yColumn.multiplyScalar(-y);
	        const offset = _v3A$1.copy(_xColumn).add(_yColumn);
	        const to = _v3B.copy(this._targetEnd).add(offset);
	        return this.moveTo(to.x, to.y, to.z, enableTransition);
	    }
	    /**
	     * Move forward / backward.
	     * @param distance Amount to move forward / backward. Negative value to move backward
	     * @param enableTransition Whether to move smoothly or immediately
	     * @category Methods
	     */
	    forward(distance, enableTransition = false) {
	        _v3A$1.setFromMatrixColumn(this._camera.matrix, 0);
	        _v3A$1.crossVectors(this._camera.up, _v3A$1);
	        _v3A$1.multiplyScalar(distance);
	        const to = _v3B.copy(this._targetEnd).add(_v3A$1);
	        return this.moveTo(to.x, to.y, to.z, enableTransition);
	    }
	    /**
	     * Move target position to given point.
	     * @param x x coord to move center position
	     * @param y y coord to move center position
	     * @param z z coord to move center position
	     * @param enableTransition Whether to move smoothly or immediately
	     * @category Methods
	     */
	    moveTo(x, y, z, enableTransition = false) {
	        const offset = _v3A$1.set(x, y, z).sub(this._targetEnd);
	        this._encloseToBoundary(this._targetEnd, offset, this.boundaryFriction);
	        this._needsUpdate = true;
	        if (!enableTransition) {
	            this._target.copy(this._targetEnd);
	        }
	        const resolveImmediately = !enableTransition ||
	            approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) &&
	                approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) &&
	                approxEquals(this._target.z, this._targetEnd.z, this.restThreshold);
	        return this._createOnRestPromise(resolveImmediately);
	    }
	    /**
	     * Fit the viewport to the box or the bounding box of the object, using the nearest axis. paddings are in unit.
	     * set `cover: true` to fill enter screen.
	     * e.g.
	     * ```
	     * cameraControls.fitToBox( myMesh );
	     * ```
	     * @param box3OrObject Axis aligned bounding box to fit the view.
	     * @param enableTransition Whether to move smoothly or immediately.
	     * @param options | `<object>` { cover: boolean, paddingTop: number, paddingLeft: number, paddingBottom: number, paddingRight: number }
	     * @returns Transition end promise
	     * @category Methods
	     */
	    fitToBox(box3OrObject, enableTransition, { cover = false, paddingLeft = 0, paddingRight = 0, paddingBottom = 0, paddingTop = 0 } = {}) {
	        const promises = [];
	        const aabb = box3OrObject.isBox3
	            ? _box3A.copy(box3OrObject)
	            : _box3A.setFromObject(box3OrObject);
	        if (aabb.isEmpty()) {
	            console.warn('camera-controls: fitTo() cannot be used with an empty box. Aborting');
	            Promise.resolve();
	        }
	        // round to closest axis ( forward | backward | right | left | top | bottom )
	        const theta = roundToStep(this._sphericalEnd.theta, PI_HALF);
	        const phi = roundToStep(this._sphericalEnd.phi, PI_HALF);
	        promises.push(this.rotateTo(theta, phi, enableTransition));
	        const normal = _v3A$1.setFromSpherical(this._sphericalEnd).normalize();
	        const rotation = _quaternionA.setFromUnitVectors(normal, _AXIS_Z);
	        const viewFromPolar = approxEquals(Math.abs(normal.y), 1);
	        if (viewFromPolar) {
	            rotation.multiply(_quaternionB.setFromAxisAngle(_AXIS_Y, theta));
	        }
	        rotation.multiply(this._yAxisUpSpaceInverse);
	        // make oriented bounding box
	        const bb = _box3B.makeEmpty();
	        // left bottom back corner
	        _v3B.copy(aabb.min).applyQuaternion(rotation);
	        bb.expandByPoint(_v3B);
	        // right bottom back corner
	        _v3B.copy(aabb.min).setX(aabb.max.x).applyQuaternion(rotation);
	        bb.expandByPoint(_v3B);
	        // left top back corner
	        _v3B.copy(aabb.min).setY(aabb.max.y).applyQuaternion(rotation);
	        bb.expandByPoint(_v3B);
	        // right top back corner
	        _v3B.copy(aabb.max).setZ(aabb.min.z).applyQuaternion(rotation);
	        bb.expandByPoint(_v3B);
	        // left bottom front corner
	        _v3B.copy(aabb.min).setZ(aabb.max.z).applyQuaternion(rotation);
	        bb.expandByPoint(_v3B);
	        // right bottom front corner
	        _v3B.copy(aabb.max).setY(aabb.min.y).applyQuaternion(rotation);
	        bb.expandByPoint(_v3B);
	        // left top front corner
	        _v3B.copy(aabb.max).setX(aabb.min.x).applyQuaternion(rotation);
	        bb.expandByPoint(_v3B);
	        // right top front corner
	        _v3B.copy(aabb.max).applyQuaternion(rotation);
	        bb.expandByPoint(_v3B);
	        // add padding
	        bb.min.x -= paddingLeft;
	        bb.min.y -= paddingBottom;
	        bb.max.x += paddingRight;
	        bb.max.y += paddingTop;
	        rotation.setFromUnitVectors(_AXIS_Z, normal);
	        if (viewFromPolar) {
	            rotation.premultiply(_quaternionB.invert());
	        }
	        rotation.premultiply(this._yAxisUpSpace);
	        const bbSize = bb.getSize(_v3A$1);
	        const center = bb.getCenter(_v3B).applyQuaternion(rotation);
	        if (isPerspectiveCamera(this._camera)) {
	            const distance = this.getDistanceToFitBox(bbSize.x, bbSize.y, bbSize.z, cover);
	            promises.push(this.moveTo(center.x, center.y, center.z, enableTransition));
	            promises.push(this.dollyTo(distance, enableTransition));
	            promises.push(this.setFocalOffset(0, 0, 0, enableTransition));
	        }
	        else if (isOrthographicCamera(this._camera)) {
	            const camera = this._camera;
	            const width = camera.right - camera.left;
	            const height = camera.top - camera.bottom;
	            const zoom = cover ? Math.max(width / bbSize.x, height / bbSize.y) : Math.min(width / bbSize.x, height / bbSize.y);
	            promises.push(this.moveTo(center.x, center.y, center.z, enableTransition));
	            promises.push(this.zoomTo(zoom, enableTransition));
	            promises.push(this.setFocalOffset(0, 0, 0, enableTransition));
	        }
	        return Promise.all(promises);
	    }
	    /**
	     * Fit the viewport to the sphere or the bounding sphere of the object.
	     * @param sphereOrMesh
	     * @param enableTransition
	     * @category Methods
	     */
	    fitToSphere(sphereOrMesh, enableTransition) {
	        const promises = [];
	        const isSphere = sphereOrMesh instanceof THREE.Sphere;
	        const boundingSphere = isSphere ?
	            _sphere.copy(sphereOrMesh) :
	            createBoundingSphere(sphereOrMesh, _sphere);
	        promises.push(this.moveTo(boundingSphere.center.x, boundingSphere.center.y, boundingSphere.center.z, enableTransition));
	        if (isPerspectiveCamera(this._camera)) {
	            const distanceToFit = this.getDistanceToFitSphere(boundingSphere.radius);
	            promises.push(this.dollyTo(distanceToFit, enableTransition));
	        }
	        else if (isOrthographicCamera(this._camera)) {
	            const width = this._camera.right - this._camera.left;
	            const height = this._camera.top - this._camera.bottom;
	            const diameter = 2 * boundingSphere.radius;
	            const zoom = Math.min(width / diameter, height / diameter);
	            promises.push(this.zoomTo(zoom, enableTransition));
	        }
	        promises.push(this.setFocalOffset(0, 0, 0, enableTransition));
	        return Promise.all(promises);
	    }
	    /**
	     * Make an orbit with given points.
	     * @param positionX
	     * @param positionY
	     * @param positionZ
	     * @param targetX
	     * @param targetY
	     * @param targetZ
	     * @param enableTransition
	     * @category Methods
	     */
	    setLookAt(positionX, positionY, positionZ, targetX, targetY, targetZ, enableTransition = false) {
	        const target = _v3B.set(targetX, targetY, targetZ);
	        const position = _v3A$1.set(positionX, positionY, positionZ);
	        this._targetEnd.copy(target);
	        this._sphericalEnd.setFromVector3(position.sub(target).applyQuaternion(this._yAxisUpSpace));
	        this.normalizeRotations();
	        this._needsUpdate = true;
	        if (!enableTransition) {
	            this._target.copy(this._targetEnd);
	            this._spherical.copy(this._sphericalEnd);
	        }
	        const resolveImmediately = !enableTransition ||
	            approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) &&
	                approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) &&
	                approxEquals(this._target.z, this._targetEnd.z, this.restThreshold) &&
	                approxEquals(this._spherical.theta, this._sphericalEnd.theta, this.restThreshold) &&
	                approxEquals(this._spherical.phi, this._sphericalEnd.phi, this.restThreshold) &&
	                approxEquals(this._spherical.radius, this._sphericalEnd.radius, this.restThreshold);
	        return this._createOnRestPromise(resolveImmediately);
	    }
	    /**
	     * Similar to setLookAt, but it interpolates between two states.
	     * @param positionAX
	     * @param positionAY
	     * @param positionAZ
	     * @param targetAX
	     * @param targetAY
	     * @param targetAZ
	     * @param positionBX
	     * @param positionBY
	     * @param positionBZ
	     * @param targetBX
	     * @param targetBY
	     * @param targetBZ
	     * @param t
	     * @param enableTransition
	     * @category Methods
	     */
	    lerpLookAt(positionAX, positionAY, positionAZ, targetAX, targetAY, targetAZ, positionBX, positionBY, positionBZ, targetBX, targetBY, targetBZ, t, enableTransition = false) {
	        const targetA = _v3A$1.set(targetAX, targetAY, targetAZ);
	        const positionA = _v3B.set(positionAX, positionAY, positionAZ);
	        _sphericalA.setFromVector3(positionA.sub(targetA).applyQuaternion(this._yAxisUpSpace));
	        const targetB = _v3C.set(targetBX, targetBY, targetBZ);
	        const positionB = _v3B.set(positionBX, positionBY, positionBZ);
	        _sphericalB.setFromVector3(positionB.sub(targetB).applyQuaternion(this._yAxisUpSpace));
	        this._targetEnd.copy(targetA.lerp(targetB, t)); // tricky
	        const deltaTheta = _sphericalB.theta - _sphericalA.theta;
	        const deltaPhi = _sphericalB.phi - _sphericalA.phi;
	        const deltaRadius = _sphericalB.radius - _sphericalA.radius;
	        this._sphericalEnd.set(_sphericalA.radius + deltaRadius * t, _sphericalA.phi + deltaPhi * t, _sphericalA.theta + deltaTheta * t);
	        this.normalizeRotations();
	        this._needsUpdate = true;
	        if (!enableTransition) {
	            this._target.copy(this._targetEnd);
	            this._spherical.copy(this._sphericalEnd);
	        }
	        const resolveImmediately = !enableTransition ||
	            approxEquals(this._target.x, this._targetEnd.x, this.restThreshold) &&
	                approxEquals(this._target.y, this._targetEnd.y, this.restThreshold) &&
	                approxEquals(this._target.z, this._targetEnd.z, this.restThreshold) &&
	                approxEquals(this._spherical.theta, this._sphericalEnd.theta, this.restThreshold) &&
	                approxEquals(this._spherical.phi, this._sphericalEnd.phi, this.restThreshold) &&
	                approxEquals(this._spherical.radius, this._sphericalEnd.radius, this.restThreshold);
	        return this._createOnRestPromise(resolveImmediately);
	    }
	    /**
	     * setLookAt without target, keep gazing at the current target
	     * @param positionX
	     * @param positionY
	     * @param positionZ
	     * @param enableTransition
	     * @category Methods
	     */
	    setPosition(positionX, positionY, positionZ, enableTransition = false) {
	        return this.setLookAt(positionX, positionY, positionZ, this._targetEnd.x, this._targetEnd.y, this._targetEnd.z, enableTransition);
	    }
	    /**
	     * setLookAt without position, Stay still at the position.
	     * @param targetX
	     * @param targetY
	     * @param targetZ
	     * @param enableTransition
	     * @category Methods
	     */
	    setTarget(targetX, targetY, targetZ, enableTransition = false) {
	        const pos = this.getPosition(_v3A$1);
	        return this.setLookAt(pos.x, pos.y, pos.z, targetX, targetY, targetZ, enableTransition);
	    }
	    /**
	     * Set focal offset using the screen parallel coordinates. z doesn't affect in Orthographic as with Dolly.
	     * @param x
	     * @param y
	     * @param z
	     * @param enableTransition
	     * @category Methods
	     */
	    setFocalOffset(x, y, z, enableTransition = false) {
	        this._focalOffsetEnd.set(x, y, z);
	        this._needsUpdate = true;
	        if (!enableTransition) {
	            this._focalOffset.copy(this._focalOffsetEnd);
	        }
	        const resolveImmediately = !enableTransition ||
	            approxEquals(this._focalOffset.x, this._focalOffsetEnd.x, this.restThreshold) &&
	                approxEquals(this._focalOffset.y, this._focalOffsetEnd.y, this.restThreshold) &&
	                approxEquals(this._focalOffset.z, this._focalOffsetEnd.z, this.restThreshold);
	        return this._createOnRestPromise(resolveImmediately);
	    }
	    /**
	     * Set orbit point without moving the camera.
	     * SHOULD NOT RUN DURING ANIMATIONS. `setOrbitPoint()` will immediately fix the positions.
	     * @param targetX
	     * @param targetY
	     * @param targetZ
	     * @category Methods
	     */
	    setOrbitPoint(targetX, targetY, targetZ) {
	        this._camera.updateMatrixWorld();
	        _xColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 0);
	        _yColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 1);
	        _zColumn.setFromMatrixColumn(this._camera.matrixWorldInverse, 2);
	        const position = _v3A$1.set(targetX, targetY, targetZ);
	        const distance = position.distanceTo(this._camera.position);
	        const cameraToPoint = position.sub(this._camera.position);
	        _xColumn.multiplyScalar(cameraToPoint.x);
	        _yColumn.multiplyScalar(cameraToPoint.y);
	        _zColumn.multiplyScalar(cameraToPoint.z);
	        _v3A$1.copy(_xColumn).add(_yColumn).add(_zColumn);
	        _v3A$1.z = _v3A$1.z + distance;
	        this.dollyTo(distance, false);
	        this.setFocalOffset(-_v3A$1.x, _v3A$1.y, -_v3A$1.z, false);
	        this.moveTo(targetX, targetY, targetZ, false);
	    }
	    /**
	     * Set the boundary box that encloses the target of the camera. box3 is in THREE.Box3
	     * @param box3
	     * @category Methods
	     */
	    setBoundary(box3) {
	        if (!box3) {
	            this._boundary.min.set(-Infinity, -Infinity, -Infinity);
	            this._boundary.max.set(Infinity, Infinity, Infinity);
	            this._needsUpdate = true;
	            return;
	        }
	        this._boundary.copy(box3);
	        this._boundary.clampPoint(this._targetEnd, this._targetEnd);
	        this._needsUpdate = true;
	    }
	    /**
	     * Set (or unset) the current viewport.
	     * Set this when you want to use renderer viewport and .dollyToCursor feature at the same time.
	     * @param viewportOrX
	     * @param y
	     * @param width
	     * @param height
	     * @category Methods
	     */
	    setViewport(viewportOrX, y, width, height) {
	        if (viewportOrX === null) { // null
	            this._viewport = null;
	            return;
	        }
	        this._viewport = this._viewport || new THREE.Vector4();
	        if (typeof viewportOrX === 'number') { // number
	            this._viewport.set(viewportOrX, y, width, height);
	        }
	        else { // Vector4
	            this._viewport.copy(viewportOrX);
	        }
	    }
	    /**
	     * Calculate the distance to fit the box.
	     * @param width box width
	     * @param height box height
	     * @param depth box depth
	     * @returns distance
	     * @category Methods
	     */
	    getDistanceToFitBox(width, height, depth, cover = false) {
	        if (notSupportedInOrthographicCamera(this._camera, 'getDistanceToFitBox'))
	            return this._spherical.radius;
	        const boundingRectAspect = width / height;
	        const fov = this._camera.getEffectiveFOV() * THREE.MathUtils.DEG2RAD;
	        const aspect = this._camera.aspect;
	        const heightToFit = (cover ? boundingRectAspect > aspect : boundingRectAspect < aspect) ? height : width / aspect;
	        return heightToFit * 0.5 / Math.tan(fov * 0.5) + depth * 0.5;
	    }
	    /**
	     * Calculate the distance to fit the sphere.
	     * @param radius sphere radius
	     * @returns distance
	     * @category Methods
	     */
	    getDistanceToFitSphere(radius) {
	        if (notSupportedInOrthographicCamera(this._camera, 'getDistanceToFitSphere'))
	            return this._spherical.radius;
	        // https://stackoverflow.com/a/44849975
	        const vFOV = this._camera.getEffectiveFOV() * THREE.MathUtils.DEG2RAD;
	        const hFOV = Math.atan(Math.tan(vFOV * 0.5) * this._camera.aspect) * 2;
	        const fov = 1 < this._camera.aspect ? vFOV : hFOV;
	        return radius / (Math.sin(fov * 0.5));
	    }
	    /**
	     * Returns its current gazing target, which is the center position of the orbit.
	     * @param out current gazing target
	     * @category Methods
	     */
	    getTarget(out) {
	        const _out = !!out && out.isVector3 ? out : new THREE.Vector3();
	        return _out.copy(this._targetEnd);
	    }
	    /**
	     * Returns its current position.
	     * @param out current position
	     * @category Methods
	     */
	    getPosition(out) {
	        const _out = !!out && out.isVector3 ? out : new THREE.Vector3();
	        return _out.setFromSpherical(this._sphericalEnd).applyQuaternion(this._yAxisUpSpaceInverse).add(this._targetEnd);
	    }
	    /**
	     * Returns its current focal offset, which is how much the camera appears to be translated in screen parallel coordinates.
	     * @param out current focal offset
	     * @category Methods
	     */
	    getFocalOffset(out) {
	        const _out = !!out && out.isVector3 ? out : new THREE.Vector3();
	        return _out.copy(this._focalOffsetEnd);
	    }
	    /**
	     * Normalize camera azimuth angle rotation between 0 and 360 degrees.
	     * @category Methods
	     */
	    normalizeRotations() {
	        this._sphericalEnd.theta = this._sphericalEnd.theta % PI_2;
	        if (this._sphericalEnd.theta < 0)
	            this._sphericalEnd.theta += PI_2;
	        this._spherical.theta += PI_2 * Math.round((this._sphericalEnd.theta - this._spherical.theta) / PI_2);
	    }
	    /**
	     * Reset all rotation and position to defaults.
	     * @param enableTransition
	     * @category Methods
	     */
	    reset(enableTransition = false) {
	        const promises = [
	            this.setLookAt(this._position0.x, this._position0.y, this._position0.z, this._target0.x, this._target0.y, this._target0.z, enableTransition),
	            this.setFocalOffset(this._focalOffset0.x, this._focalOffset0.y, this._focalOffset0.z, enableTransition),
	            this.zoomTo(this._zoom0, enableTransition),
	        ];
	        return Promise.all(promises);
	    }
	    /**
	     * Set current camera position as the default position.
	     * @category Methods
	     */
	    saveState() {
	        this.getTarget(this._target0);
	        this.getPosition(this._position0);
	        this._zoom0 = this._zoom;
	        this._focalOffset0.copy(this._focalOffset);
	    }
	    /**
	     * Sync camera-up direction.
	     * When camera-up vector is changed, `.updateCameraUp()` must be called.
	     * @category Methods
	     */
	    updateCameraUp() {
	        this._yAxisUpSpace.setFromUnitVectors(this._camera.up, _AXIS_Y);
	        quatInvertCompat(this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace));
	    }
	    /**
	     * Update camera position and directions.
	     * This should be called in your tick loop every time, and returns true if re-rendering is needed.
	     * @param delta
	     * @returns updated
	     * @category Methods
	     */
	    update(delta) {
	        const dampingFactor = this._state === ACTION.NONE ? this.dampingFactor : this.draggingDampingFactor;
	        // The original THREE.OrbitControls assume 60 FPS fixed and does NOT rely on delta time.
	        // (that must be a problem of the original one though)
	        // To to emulate the speed of the original one under 60 FPS, multiply `60` to delta,
	        // but ours are more flexible to any FPS unlike the original.
	        const lerpRatio = Math.min(dampingFactor * delta * 60, 1);
	        const deltaTheta = this._sphericalEnd.theta - this._spherical.theta;
	        const deltaPhi = this._sphericalEnd.phi - this._spherical.phi;
	        const deltaRadius = this._sphericalEnd.radius - this._spherical.radius;
	        const deltaTarget = _deltaTarget.subVectors(this._targetEnd, this._target);
	        const deltaOffset = _deltaOffset.subVectors(this._focalOffsetEnd, this._focalOffset);
	        if (!approxZero(deltaTheta) ||
	            !approxZero(deltaPhi) ||
	            !approxZero(deltaRadius) ||
	            !approxZero(deltaTarget.x) ||
	            !approxZero(deltaTarget.y) ||
	            !approxZero(deltaTarget.z) ||
	            !approxZero(deltaOffset.x) ||
	            !approxZero(deltaOffset.y) ||
	            !approxZero(deltaOffset.z)) {
	            this._spherical.set(this._spherical.radius + deltaRadius * lerpRatio, this._spherical.phi + deltaPhi * lerpRatio, this._spherical.theta + deltaTheta * lerpRatio);
	            this._target.add(deltaTarget.multiplyScalar(lerpRatio));
	            this._focalOffset.add(deltaOffset.multiplyScalar(lerpRatio));
	            this._needsUpdate = true;
	        }
	        else {
	            this._spherical.copy(this._sphericalEnd);
	            this._target.copy(this._targetEnd);
	            this._focalOffset.copy(this._focalOffsetEnd);
	        }
	        if (this._dollyControlAmount !== 0) {
	            if (isPerspectiveCamera(this._camera)) {
	                const camera = this._camera;
	                const direction = _v3A$1.setFromSpherical(this._sphericalEnd).applyQuaternion(this._yAxisUpSpaceInverse).normalize().negate();
	                const planeX = _v3B.copy(direction).cross(camera.up).normalize();
	                if (planeX.lengthSq() === 0)
	                    planeX.x = 1.0;
	                const planeY = _v3C.crossVectors(planeX, direction);
	                const worldToScreen = this._sphericalEnd.radius * Math.tan(camera.getEffectiveFOV() * THREE.MathUtils.DEG2RAD * 0.5);
	                const prevRadius = this._sphericalEnd.radius - this._dollyControlAmount;
	                const lerpRatio = (prevRadius - this._sphericalEnd.radius) / this._sphericalEnd.radius;
	                const cursor = _v3A$1.copy(this._targetEnd)
	                    .add(planeX.multiplyScalar(this._dollyControlCoord.x * worldToScreen * camera.aspect))
	                    .add(planeY.multiplyScalar(this._dollyControlCoord.y * worldToScreen));
	                this._targetEnd.lerp(cursor, lerpRatio);
	                this._target.copy(this._targetEnd);
	                // target position may be moved beyond boundary.
	                this._boundary.clampPoint(this._targetEnd, this._targetEnd);
	            }
	            else if (isOrthographicCamera(this._camera)) {
	                const camera = this._camera;
	                const worldPosition = _v3A$1.set(this._dollyControlCoord.x, this._dollyControlCoord.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera);
	                const quaternion = _v3B.set(0, 0, -1).applyQuaternion(camera.quaternion);
	                const divisor = quaternion.dot(camera.up);
	                const distance = approxZero(divisor) ? -worldPosition.dot(camera.up) : -worldPosition.dot(camera.up) / divisor;
	                const cursor = _v3C.copy(worldPosition).add(quaternion.multiplyScalar(distance));
	                this._targetEnd.lerp(cursor, 1 - camera.zoom / this._dollyControlAmount);
	                this._target.copy(this._targetEnd);
	                // target position may be moved beyond boundary.
	                this._boundary.clampPoint(this._targetEnd, this._targetEnd);
	            }
	            this._dollyControlAmount = 0;
	        }
	        const maxDistance = this._collisionTest();
	        this._spherical.radius = Math.min(this._spherical.radius, maxDistance);
	        // decompose spherical to the camera position
	        this._spherical.makeSafe();
	        this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target);
	        this._camera.lookAt(this._target);
	        // set offset after the orbit movement
	        const affectOffset = !approxZero(this._focalOffset.x) ||
	            !approxZero(this._focalOffset.y) ||
	            !approxZero(this._focalOffset.z);
	        if (affectOffset) {
	            this._camera.updateMatrix();
	            _xColumn.setFromMatrixColumn(this._camera.matrix, 0);
	            _yColumn.setFromMatrixColumn(this._camera.matrix, 1);
	            _zColumn.setFromMatrixColumn(this._camera.matrix, 2);
	            _xColumn.multiplyScalar(this._focalOffset.x);
	            _yColumn.multiplyScalar(-this._focalOffset.y);
	            _zColumn.multiplyScalar(this._focalOffset.z); // notice: z-offset will not affect in Orthographic.
	            _v3A$1.copy(_xColumn).add(_yColumn).add(_zColumn);
	            this._camera.position.add(_v3A$1);
	        }
	        if (this._boundaryEnclosesCamera) {
	            this._encloseToBoundary(this._camera.position.copy(this._target), _v3A$1.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse), 1.0);
	        }
	        // zoom
	        const deltaZoom = this._zoomEnd - this._zoom;
	        this._zoom += deltaZoom * lerpRatio;
	        if (this._camera.zoom !== this._zoom) {
	            if (approxZero(deltaZoom))
	                this._zoom = this._zoomEnd;
	            this._camera.zoom = this._zoom;
	            this._camera.updateProjectionMatrix();
	            this._updateNearPlaneCorners();
	            this._needsUpdate = true;
	        }
	        const updated = this._needsUpdate;
	        if (updated && !this._updatedLastTime) {
	            this._hasRested = false;
	            this.dispatchEvent({ type: 'wake' });
	            this.dispatchEvent({ type: 'update' });
	        }
	        else if (updated) {
	            this.dispatchEvent({ type: 'update' });
	            if (approxZero(deltaTheta, this.restThreshold) &&
	                approxZero(deltaPhi, this.restThreshold) &&
	                approxZero(deltaRadius, this.restThreshold) &&
	                approxZero(deltaTarget.x, this.restThreshold) &&
	                approxZero(deltaTarget.y, this.restThreshold) &&
	                approxZero(deltaTarget.z, this.restThreshold) &&
	                approxZero(deltaOffset.x, this.restThreshold) &&
	                approxZero(deltaOffset.y, this.restThreshold) &&
	                approxZero(deltaOffset.z, this.restThreshold) &&
	                approxZero(deltaZoom, this.restThreshold) &&
	                !this._hasRested) {
	                this._hasRested = true;
	                this.dispatchEvent({ type: 'rest' });
	            }
	        }
	        else if (!updated && this._updatedLastTime) {
	            this.dispatchEvent({ type: 'sleep' });
	        }
	        this._updatedLastTime = updated;
	        this._needsUpdate = false;
	        return updated;
	    }
	    /**
	     * Get all state in JSON string
	     * @category Methods
	     */
	    toJSON() {
	        return JSON.stringify({
	            enabled: this._enabled,
	            minDistance: this.minDistance,
	            maxDistance: infinityToMaxNumber(this.maxDistance),
	            minZoom: this.minZoom,
	            maxZoom: infinityToMaxNumber(this.maxZoom),
	            minPolarAngle: this.minPolarAngle,
	            maxPolarAngle: infinityToMaxNumber(this.maxPolarAngle),
	            minAzimuthAngle: infinityToMaxNumber(this.minAzimuthAngle),
	            maxAzimuthAngle: infinityToMaxNumber(this.maxAzimuthAngle),
	            dampingFactor: this.dampingFactor,
	            draggingDampingFactor: this.draggingDampingFactor,
	            dollySpeed: this.dollySpeed,
	            truckSpeed: this.truckSpeed,
	            dollyToCursor: this.dollyToCursor,
	            verticalDragToForward: this.verticalDragToForward,
	            target: this._targetEnd.toArray(),
	            position: _v3A$1.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),
	            zoom: this._zoomEnd,
	            focalOffset: this._focalOffsetEnd.toArray(),
	            target0: this._target0.toArray(),
	            position0: this._position0.toArray(),
	            zoom0: this._zoom0,
	            focalOffset0: this._focalOffset0.toArray(),
	        });
	    }
	    /**
	     * Reproduce the control state with JSON. enableTransition is where anim or not in a boolean.
	     * @param json
	     * @param enableTransition
	     * @category Methods
	     */
	    fromJSON(json, enableTransition = false) {
	        const obj = JSON.parse(json);
	        const position = _v3A$1.fromArray(obj.position);
	        this.enabled = obj.enabled;
	        this.minDistance = obj.minDistance;
	        this.maxDistance = maxNumberToInfinity(obj.maxDistance);
	        this.minZoom = obj.minZoom;
	        this.maxZoom = maxNumberToInfinity(obj.maxZoom);
	        this.minPolarAngle = obj.minPolarAngle;
	        this.maxPolarAngle = maxNumberToInfinity(obj.maxPolarAngle);
	        this.minAzimuthAngle = maxNumberToInfinity(obj.minAzimuthAngle);
	        this.maxAzimuthAngle = maxNumberToInfinity(obj.maxAzimuthAngle);
	        this.dampingFactor = obj.dampingFactor;
	        this.draggingDampingFactor = obj.draggingDampingFactor;
	        this.dollySpeed = obj.dollySpeed;
	        this.truckSpeed = obj.truckSpeed;
	        this.dollyToCursor = obj.dollyToCursor;
	        this.verticalDragToForward = obj.verticalDragToForward;
	        this._target0.fromArray(obj.target0);
	        this._position0.fromArray(obj.position0);
	        this._zoom0 = obj.zoom0;
	        this._focalOffset0.fromArray(obj.focalOffset0);
	        this.moveTo(obj.target[0], obj.target[1], obj.target[2], enableTransition);
	        _sphericalA.setFromVector3(position.sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace));
	        this.rotateTo(_sphericalA.theta, _sphericalA.phi, enableTransition);
	        this.zoomTo(obj.zoom, enableTransition);
	        this.setFocalOffset(obj.focalOffset[0], obj.focalOffset[1], obj.focalOffset[2], enableTransition);
	        this._needsUpdate = true;
	    }
	    /**
	     * Dispose the cameraControls instance itself, remove all eventListeners.
	     * @category Methods
	     */
	    dispose() {
	        this._removeAllEventListeners();
	    }
	    _findPointerById(pointerId) {
	        // to support IE11 use some instead of Array#find (will be removed when IE11 is deprecated)
	        let pointer = null;
	        this._activePointers.some((activePointer) => {
	            if (activePointer.pointerId === pointerId) {
	                pointer = activePointer;
	                return true;
	            }
	            return false;
	        });
	        return pointer;
	    }
	    _encloseToBoundary(position, offset, friction) {
	        const offsetLength2 = offset.lengthSq();
	        if (offsetLength2 === 0.0) { // sanity check
	            return position;
	        }
	        // See: https://twitter.com/FMS_Cat/status/1106508958640988161
	        const newTarget = _v3B.copy(offset).add(position); // target
	        const clampedTarget = this._boundary.clampPoint(newTarget, _v3C); // clamped target
	        const deltaClampedTarget = clampedTarget.sub(newTarget); // newTarget -> clampedTarget
	        const deltaClampedTargetLength2 = deltaClampedTarget.lengthSq(); // squared length of deltaClampedTarget
	        if (deltaClampedTargetLength2 === 0.0) { // when the position doesn't have to be clamped
	            return position.add(offset);
	        }
	        else if (deltaClampedTargetLength2 === offsetLength2) { // when the position is completely stuck
	            return position;
	        }
	        else if (friction === 0.0) {
	            return position.add(offset).add(deltaClampedTarget);
	        }
	        else {
	            const offsetFactor = 1.0 + friction * deltaClampedTargetLength2 / offset.dot(deltaClampedTarget);
	            return position
	                .add(_v3B.copy(offset).multiplyScalar(offsetFactor))
	                .add(deltaClampedTarget.multiplyScalar(1.0 - friction));
	        }
	    }
	    _updateNearPlaneCorners() {
	        if (isPerspectiveCamera(this._camera)) {
	            const camera = this._camera;
	            const near = camera.near;
	            const fov = camera.getEffectiveFOV() * THREE.MathUtils.DEG2RAD;
	            const heightHalf = Math.tan(fov * 0.5) * near; // near plain half height
	            const widthHalf = heightHalf * camera.aspect; // near plain half width
	            this._nearPlaneCorners[0].set(-widthHalf, -heightHalf, 0);
	            this._nearPlaneCorners[1].set(widthHalf, -heightHalf, 0);
	            this._nearPlaneCorners[2].set(widthHalf, heightHalf, 0);
	            this._nearPlaneCorners[3].set(-widthHalf, heightHalf, 0);
	        }
	        else if (isOrthographicCamera(this._camera)) {
	            const camera = this._camera;
	            const zoomInv = 1 / camera.zoom;
	            const left = camera.left * zoomInv;
	            const right = camera.right * zoomInv;
	            const top = camera.top * zoomInv;
	            const bottom = camera.bottom * zoomInv;
	            this._nearPlaneCorners[0].set(left, top, 0);
	            this._nearPlaneCorners[1].set(right, top, 0);
	            this._nearPlaneCorners[2].set(right, bottom, 0);
	            this._nearPlaneCorners[3].set(left, bottom, 0);
	        }
	    }
	    // lateUpdate
	    _collisionTest() {
	        let distance = Infinity;
	        const hasCollider = this.colliderMeshes.length >= 1;
	        if (!hasCollider)
	            return distance;
	        if (notSupportedInOrthographicCamera(this._camera, '_collisionTest'))
	            return distance;
	        // divide by distance to normalize, lighter than `Vector3.prototype.normalize()`
	        const direction = _v3A$1.setFromSpherical(this._spherical).divideScalar(this._spherical.radius);
	        _rotationMatrix.lookAt(_ORIGIN, direction, this._camera.up);
	        for (let i = 0; i < 4; i++) {
	            const nearPlaneCorner = _v3B.copy(this._nearPlaneCorners[i]);
	            nearPlaneCorner.applyMatrix4(_rotationMatrix);
	            const origin = _v3C.addVectors(this._target, nearPlaneCorner);
	            _raycaster.set(origin, direction);
	            _raycaster.far = this._spherical.radius + 1;
	            const intersects = _raycaster.intersectObjects(this.colliderMeshes);
	            if (intersects.length !== 0 && intersects[0].distance < distance) {
	                distance = intersects[0].distance;
	            }
	        }
	        return distance;
	    }
	    /**
	     * Get its client rect and package into given `DOMRect` .
	     */
	    _getClientRect(target) {
	        const rect = this._domElement.getBoundingClientRect();
	        target.x = rect.left;
	        target.y = rect.top;
	        if (this._viewport) {
	            target.x += this._viewport.x;
	            target.y += rect.height - this._viewport.w - this._viewport.y;
	            target.width = this._viewport.z;
	            target.height = this._viewport.w;
	        }
	        else {
	            target.width = rect.width;
	            target.height = rect.height;
	        }
	        return target;
	    }
	    _createOnRestPromise(resolveImmediately) {
	        if (resolveImmediately)
	            return Promise.resolve();
	        this._hasRested = false;
	        this.dispatchEvent({ type: 'transitionstart' });
	        return new Promise((resolve) => {
	            const onResolve = () => {
	                this.removeEventListener('rest', onResolve);
	                resolve();
	            };
	            this.addEventListener('rest', onResolve);
	        });
	    }
	    _removeAllEventListeners() { }
	}
	function createBoundingSphere(object3d, out) {
	    const boundingSphere = out;
	    const center = boundingSphere.center;
	    _box3A.makeEmpty();
	    // find the center
	    object3d.traverseVisible((object) => {
	        if (!object.isMesh)
	            return;
	        _box3A.expandByObject(object);
	    });
	    _box3A.getCenter(center);
	    // find the radius
	    let maxRadiusSq = 0;
	    object3d.traverseVisible((object) => {
	        if (!object.isMesh)
	            return;
	        const mesh = object;
	        const geometry = mesh.geometry.clone();
	        geometry.applyMatrix4(mesh.matrixWorld);
	        if (geometry.isBufferGeometry) {
	            const bufferGeometry = geometry;
	            const position = bufferGeometry.attributes.position;
	            for (let i = 0, l = position.count; i < l; i++) {
	                _v3A$1.fromBufferAttribute(position, i);
	                maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_v3A$1));
	            }
	        }
	        else {
	            // for old three.js, which supports both BufferGeometry and Geometry
	            // this condition block will be removed in the near future.
	            const position = geometry.attributes.position;
	            const vector = new THREE.Vector3();
	            for (let i = 0, l = position.count; i < l; i++) {
	                vector.fromBufferAttribute(position, i);
	                maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(vector));
	            }
	        }
	    });
	    boundingSphere.radius = Math.sqrt(maxRadiusSq);
	    return boundingSphere;
	}

	const _v3A = new three.Vector3();
	class MyCameraControls extends CameraControls {
	    constructor() {
	        super(...arguments);
	        Object.defineProperty(this, "truckYDisabled", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: false
	        });
	        // @ts-ignore 重写 CameraControls 方法
	        Object.defineProperty(this, "_truckInternal", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: (deltaX, deltaY, dragToOffset) => {
	                const _this = this;
	                const offset = _v3A.copy(_this._camera.position).sub(_this._target);
	                // @ts-ignore
	                const fov = _this._camera.getEffectiveFOV() * three.MathUtils.DEG2RAD;
	                const targetDistance = offset.length() * Math.tan(fov * 0.5);
	                const truckX = (_this.truckSpeed * deltaX * targetDistance) / _this._elementRect.width;
	                const pedestalY = (_this.truckSpeed * deltaY * targetDistance) / _this._elementRect.width;
	                if (_this.verticalDragToForward) {
	                    dragToOffset
	                        ? _this.setFocalOffset(_this._focalOffsetEnd.x + truckX, _this._focalOffsetEnd.y, _this._focalOffsetEnd.z, true)
	                        : _this.truck(truckX, 0, true);
	                    _this.forward(-pedestalY, true);
	                }
	                else {
	                    dragToOffset
	                        ? _this.setFocalOffset(_this._focalOffsetEnd.x + truckX, _this._focalOffsetEnd.y + pedestalY, _this._focalOffsetEnd.z, true)
	                        : _this.truck(this.truckYDisabled ? 0 : truckX, pedestalY, true);
	                }
	                // const offset = _v3A.copy(this._camera.position).sub(this._target);
	                // // half of the fov is center to top of screen
	                // // @ts-ignore
	                // const fov = this._camera.getEffectiveFOV() * MathUtils.DEG2RAD;
	                // const targetDistance = offset.length() * Math.tan(fov * 0.5);
	                // const truckX =
	                //   (this.truckSpeed * deltaX * targetDistance) / this._elementRect.w;
	                // const truckY =
	                //   (this.truckSpeed * deltaY * targetDistance) / this._elementRect.w;
	                // this.truck(this.truckYDisabled ? 0 : truckX, truckY, true);
	            }
	        });
	    }
	}

	// import CameraControls from 'camera-controls';
	// import { IObjectBaseConfig, IType } from './parkingLayer/types';
	// let timer = 0
	// export const reDraw = (time = 3000) => {
	//   // @ts-ignore
	//   CameraControls.viewChanged = true
	//   clearTimeout(timer)
	//   timer = setTimeout(() => {
	//     // @ts-ignore
	//     CameraControls.viewChanged = false
	//   }, time)
	// }
	/**
	 * @desc 射线拾取
	 */
	function getIntersects({ event, $map, scene, camera, objects }) {
	    const { top, left } = $map.getBoundingClientRect();
	    // 声明raycaster和mouse变量
	    const raycaster = new three.Raycaster();
	    const mouse = new three.Vector2();
	    // 通过鼠标点击的位置计算出raycaster所需要的点的位置，以屏幕中心为原点，值的范围为-1到1.
	    mouse.x = ((event.clientX - left) / $map.clientWidth) * 2 - 1;
	    mouse.y = -((event.clientY - top) / $map.clientHeight) * 2 + 1;
	    // 通过鼠标点的位置和当前相机的矩阵计算出raycaster
	    raycaster.setFromCamera(mouse, camera);
	    // 获取raycaster直线和所有模型相交的数组集合，注意：true表示返回的值会递归，找到更深层次的模型
	    const intersects = raycaster.intersectObjects(objects || scene.children, true);
	    // 2d 场景下会存在bug，就是选择点的时候，跑到中心点去了，数组第一个是对象 AxesHelper 导致的，这里进行过滤
	    // intersects = intersects.filter(item => !(item.object instanceof AxesHelper))
	    // if (filter) {
	    //   intersects = filter(intersects)
	    // }
	    return intersects;
	}
	/**
	 * @desc 射线拾取对象，获取世界坐标
	 * objects 传入需要被射线拾取的物体。精准判断情况，不传入 objects， 获取被射线拾取的所有对象，然后再判断第一个对象是否被命中，即可判断当前是否点击了想要的对象。
	 * @return 返回第一个点和所有被射线拾取的对象
	 */
	function getWorldPosition({ event, $map, scene, camera, objects }) {
	    const intersects = getIntersects({ event, $map, scene, camera, objects });
	    const points = intersects.map(item => item.point);
	    const worldPosition = new three.Vector3();
	    if (points.length > 0) {
	        worldPosition.set(points[0].x, points[0].y, points[0].z);
	        return { worldPosition, intersects };
	    }
	    return {};
	}
	/**
	 * @desc 根据 name 获取对应的对象集合
	 */
	function getObjectsByName(name, parent) {
	    // scene.getObjectByName 只会返回第一个
	    // return scene.getObjectByName(name);
	    // 不能深层遍历
	    // return scene.children.filter(item => item.name === name);
	    // 较优算法
	    const arr = [];
	    parent.traverse(item => {
	        if (item.name === name)
	            arr.push(item);
	    });
	    return arr;
	}

	var stats_min = {exports: {}};

	(function (module, exports) {
		// stats.js - http://github.com/mrdoob/stats.js
		(function(f,e){module.exports=e();})(commonjsGlobal,function(){var f=function(){function e(a){c.appendChild(a.dom);return a}function u(a){for(var d=0;d<c.children.length;d++)c.children[d].style.display=d===a?"block":"none";l=a;}var l=0,c=document.createElement("div");c.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000";c.addEventListener("click",function(a){a.preventDefault();
		u(++l%c.children.length);},!1);var k=(performance||Date).now(),g=k,a=0,r=e(new f.Panel("FPS","#0ff","#002")),h=e(new f.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var t=e(new f.Panel("MB","#f08","#201"));u(0);return {REVISION:16,dom:c,addPanel:e,showPanel:u,begin:function(){k=(performance||Date).now();},end:function(){a++;var c=(performance||Date).now();h.update(c-k,200);if(c>g+1E3&&(r.update(1E3*a/(c-g),100),g=c,a=0,t)){var d=performance.memory;t.update(d.usedJSHeapSize/
		1048576,d.jsHeapSizeLimit/1048576);}return c},update:function(){k=this.end();},domElement:c,setMode:u}};f.Panel=function(e,f,l){var c=Infinity,k=0,g=Math.round,a=g(window.devicePixelRatio||1),r=80*a,h=48*a,t=3*a,v=2*a,d=3*a,m=15*a,n=74*a,p=30*a,q=document.createElement("canvas");q.width=r;q.height=h;q.style.cssText="width:80px;height:48px";var b=q.getContext("2d");b.font="bold "+9*a+"px Helvetica,Arial,sans-serif";b.textBaseline="top";b.fillStyle=l;b.fillRect(0,0,r,h);b.fillStyle=f;b.fillText(e,t,v);
		b.fillRect(d,m,n,p);b.fillStyle=l;b.globalAlpha=.9;b.fillRect(d,m,n,p);return {dom:q,update:function(h,w){c=Math.min(c,h);k=Math.max(k,h);b.fillStyle=l;b.globalAlpha=1;b.fillRect(0,0,r,m);b.fillStyle=f;b.fillText(g(h)+" "+e+" ("+g(c)+"-"+g(k)+")",t,v);b.drawImage(q,d+a,m,n-a,p,d,m,n-a,p);b.fillRect(d+n-a,m,a,p);b.fillStyle=l;b.globalAlpha=.9;b.fillRect(d+n-a,m,a,g((1-h/w)*p));}}};return f});
	} (stats_min));

	var Stats = stats_min.exports;

	function createStats(container) {
	    var _a, _b;
	    const stats = new Stats();
	    stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
	    (_a = document.querySelector(`.${container}__stats-wrapper`)) === null || _a === void 0 ? void 0 : _a.remove();
	    (_b = document.getElementById(container)) === null || _b === void 0 ? void 0 : _b.appendChild(stats.dom);
	    stats.dom.className = `.${container}__stats-wrapper`;
	    stats.dom.style.cssText =
	        'position: absolute; bottom: 0px; right: 0px; cursor: pointer; opacity: 0.9; z-index: 10000;';
	    return stats;
	}

	function mitt(n){return {all:n=n||new Map,on:function(t,e){var i=n.get(t);i?i.push(e):n.set(t,[e]);},off:function(t,e){var i=n.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):n.set(t,[]));},emit:function(t,e){var i=n.get(t);i&&i.slice().map(function(n){n(e);}),(i=n.get("*"))&&i.slice().map(function(n){n(t,e);});}}}

	/**
	 * 获取屏幕坐标
	 */
	const getScreenPostion = ({ worldPosition, $map, scene, camera }) => {
	    const { top, left, width, height } = $map.getBoundingClientRect();
	    const standardVector = new three.Vector3().copy(worldPosition).project(camera);
	    const halfWidth = width / 2;
	    const halfHeight = height / 2;
	    const x = Math.round(standardVector.x * halfWidth + halfWidth);
	    const y = Math.round(-standardVector.y * halfHeight + halfHeight);
	    return {
	        x: x + left,
	        y: y + top
	    };
	};
	const getDollys = (targetMesh, controls, offset = 5) => {
	    if (!targetMesh) {
	        return { fitDistance: 0, dollys: [0] };
	    }
	    const bb = new three.Box3().setFromObject(targetMesh);
	    const fitDistance = controls.getDistanceToFitBox(bb.max.x - bb.min.x, bb.max.y - bb.min.y, bb.max.z - bb.min.z);
	    const minDollys = [...new Array(offset)]
	        .map((_, i) => fitDistance / (i + 2))
	        .reverse();
	    const maxDollys = [...new Array(offset)].map((_, i) => fitDistance * (i + 2));
	    const dollys = [...minDollys, fitDistance, ...maxDollys];
	    return { fitDistance, dollys };
	};

	const subsetOfTHREE = {
	    MOUSE: three.MOUSE,
	    Vector2: three.Vector2,
	    Vector3: three.Vector3,
	    Vector4: three.Vector4,
	    Quaternion: three.Quaternion,
	    Matrix4: three.Matrix4,
	    Spherical: three.Spherical,
	    Box3: three.Box3,
	    Sphere: three.Sphere,
	    Raycaster: three.Raycaster,
	    MathUtils: {
	        DEG2RAD: three.MathUtils.DEG2RAD,
	        clamp: three.MathUtils.clamp
	    }
	};
	class _Map {
	    constructor(container, { style = 'normal', showStats = false, viewMode = '3D' } = {}) {
	        Object.defineProperty(this, "container", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: container
	        });
	        Object.defineProperty(this, "options", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	        Object.defineProperty(this, "stats", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	        Object.defineProperty(this, "scene", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	        Object.defineProperty(this, "camera", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	        Object.defineProperty(this, "$map", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	        Object.defineProperty(this, "renderer", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	        Object.defineProperty(this, "domElement", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	        Object.defineProperty(this, "updateSizeMap", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: new Map()
	        });
	        Object.defineProperty(this, "tweenGroupMap", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: new Map()
	        });
	        Object.defineProperty(this, "emitter", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: mitt()
	        });
	        Object.defineProperty(this, "timer", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: 0
	        });
	        Object.defineProperty(this, "viewChanged", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: false
	        });
	        Object.defineProperty(this, "cameraControls", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	        /**
	         * 存储 map 的一些相关信息
	         */
	        Object.defineProperty(this, "info", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: {
	                fitDistance: 0,
	                boundingClientRect: {
	                    x: 0,
	                    y: 0,
	                    left: 0,
	                    top: 0,
	                    right: 0,
	                    bottom: 0,
	                    width: 0,
	                    height: 0
	                }
	            }
	        });
	        /**
	         * @desc 重渲染，为了提高性能，往场景添加元素，需要调用 redraw
	         * 箭头函数，保证 this 指向正确
	         */
	        Object.defineProperty(this, "reDraw", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: (time = 3000) => {
	                this.viewChanged = true;
	                clearTimeout(this.timer);
	                this.timer = setTimeout(() => {
	                    this.viewChanged = false;
	                }, time);
	            }
	        });
	        this.options = { style, showStats, viewMode };
	        const { scene, camera, cameraControls, $map, renderer } = this.init();
	        this.scene = scene;
	        this.camera = camera;
	        this.cameraControls = cameraControls;
	        this.$map = $map;
	        this.renderer = renderer;
	        // 画布元素
	        this.domElement = renderer.domElement;
	        // 配置相机相关的参数
	        this.reset();
	        this.setShowStats(showStats);
	        // #region 开始事件注册相关
	        let isMousedonw = false;
	        let time = 0;
	        const onMouseDown = (ev) => {
	            if (ev.button === 2)
	                return;
	            isMousedonw = true;
	            time = +new Date();
	        };
	        const onMouseUp = (ev) => {
	            if (!isMousedonw)
	                return;
	            const newTime = +new Date();
	            if (newTime - time > 300) ;
	            else {
	                const { scene, camera, $map } = this;
	                // 世界坐标相关
	                const obj = getWorldPosition({
	                    event: ev,
	                    scene,
	                    camera,
	                    $map
	                });
	                // 如果有获取到屏幕坐标的话，默认会携带当前地图屏幕坐标，用于其他操作
	                let screenPosition;
	                if (obj.worldPosition) {
	                    // TODO:这里没有必要使用 getScreenPostion ，直接使用鼠标的 clientX，clientY + $map 的 left top
	                    screenPosition = getScreenPostion({
	                        worldPosition: obj.worldPosition,
	                        $map,
	                        scene,
	                        camera
	                    });
	                }
	                // @ts-ignore
	                this.emitter.emit('click', Object.assign(Object.assign(Object.assign({}, ev), obj), { screenPosition }));
	            }
	            isMousedonw = false;
	        };
	        const onMouseMove = (ev) => {
	            const { scene, camera, $map } = this;
	            // 世界坐标相关
	            const obj = getWorldPosition({
	                event: ev,
	                scene,
	                camera,
	                $map
	            });
	            // 如果有获取到屏幕坐标的话，默认会携带当前地图屏幕坐标，用于其他操作
	            let screenPosition;
	            if (obj.worldPosition) {
	                screenPosition = getScreenPostion({
	                    worldPosition: obj.worldPosition,
	                    $map,
	                    scene,
	                    camera
	                });
	            }
	            // @ts-ignore
	            this.emitter.emit('mousemove', Object.assign(Object.assign(Object.assign({}, ev), obj), { screenPosition }));
	        };
	        // 这里注册到 canvas 上面，防止弹窗点击事件冒泡，需要再进行一些额外的冒泡控制
	        this.domElement.removeEventListener('mousedown', onMouseDown);
	        this.domElement.removeEventListener('mouseup', onMouseUp);
	        this.domElement.ownerDocument.removeEventListener('mousemove', onMouseMove);
	        this.domElement.addEventListener('mousedown', onMouseDown);
	        this.domElement.addEventListener('mouseup', onMouseUp);
	        this.domElement.ownerDocument.addEventListener('mousemove', onMouseMove);
	        // this.$map.removeEventListener('mousedown', onMouseDown);
	        // this.$map.removeEventListener('mouseup', onMouseUp);
	        // this.$map.ownerDocument.removeEventListener('mousemove', onMouseMove);
	        // this.$map.addEventListener('mousedown', onMouseDown);
	        // this.$map.addEventListener('mouseup', onMouseUp);
	        // this.$map.ownerDocument.addEventListener('mousemove', onMouseMove);
	        // #endregion
	        console.log('map init success');
	    }
	    /**
	     * 生成图片
	     */
	    generateImage(type = 'image/png', quality = 1) {
	        // 获取canvas对象
	        const canvas = this.renderer.domElement;
	        const img = canvas.toDataURL(type, quality);
	        return img;
	    }
	    getScene() {
	        return this.scene;
	    }
	    /**
	     * @desc 二封 scene.add
	     * to do：
	     * - 需要判断新增的 layer 是否重名，判断 name 属性
	     */
	    add(...objects) {
	        for (const item of objects) {
	            // 表示自定义对象
	            if (!(item instanceof three.Object3D)) {
	                // 📝 ElementType 是 @ktmap/plugins 扩展的，只要是继承了 Element 类的都有 __inject 和 __init 两个方法
	                // @ts-ignore
	                item.__inject(this);
	                // @ts-ignore
	                item.__init();
	            }
	            else {
	                this.scene.add(item);
	            }
	        }
	        // https://blog.csdn.net/sujun10/article/details/64924125
	        // switch (obj?.constructor?.name) {
	        // @ts-ignore
	        // switch (obj?.NAME) {
	        //   // case 'PoisLayer':
	        //   //   obj = obj as PoisLayer;
	        //   //   // 判断如果当前如果添加的是一个 marker 就需要添加到一个数组，后续会根据这个数组循环 updateSize
	        //   //   // 注入需要的参数
	        //   //   obj._inject(this);
	        //   //   obj._init();
	        //   //   this.updateSizeMap.set(obj, obj._updateSize.bind(obj));
	        //   //   console.log('add-this.updateSizeMap :>> ', this.updateSizeMap);
	        //   //   break;
	        //   case 'ParkingLayer':
	        //     obj = obj as ParkingLayer;
	        //     // 判断如果当前如果添加的是一个 marker 就需要添加到一个数组，后续会根据这个数组循环 updateSize
	        //     obj._inject(this);
	        //     obj._init();
	        //     this.updateSizeMap.set(obj, obj._updateSize.bind(obj));
	        //     console.log('add-this.updateSizeMap :>> ', this.updateSizeMap);
	        //     break;
	        //   default:
	        //     // @ts-ignore
	        //     this.scene.add(...object);
	        //     break;
	        // }
	        this.reDraw();
	        // console.log('add-current-scene :>> ', this.scene);
	        return this;
	    }
	    remove(...object) {
	        // let obj = object[0];
	        // // switch (obj?.constructor?.name) {
	        // // @ts-ignore
	        // switch (obj?.NAME) {
	        //   case 'PoisLayer':
	        //     obj = obj as PoisLayer;
	        //     // 判断如果当前如果添加的是一个 marker 就需要添加到一个数组，后续会根据这个数组循环 updateSize
	        //     this.updateSizeMap.delete(obj);
	        //     console.log('delete-this.updateSizeMap :>> ', this.updateSizeMap);
	        //     this.scene.remove(obj._group);
	        //     break;
	        //   default:
	        //     // @ts-ignore
	        //     this.scene.remove(...object);
	        //     break;
	        // }
	        // this.reDraw();
	        // console.log('add-current-scene :>> ', this.scene);
	        // return this;
	    }
	    // private eventExtMap
	    on(type, handler
	    // ext?: Record<string, any>
	    ) {
	        // mitt 监听
	        this.emitter.on(type, handler);
	        // switch (type) {
	        //   case 'click': {
	        //     // 直接设置 click 和 cameraControls 的左键拖拽混乱，使用时间间隔判断，当前是否在拖拽，把 click 拆分
	        //     this.domElement.addEventListener('mousedown', () => {});
	        //     // this.domElement.addEventListener(
	        //     //   'mouseup',
	        //     //   this.onMouseUp.bind(this, ext)
	        //     // );
	        //     break;
	        //   }
	        //   case 'mousemove': {
	        //     // this.domElement.addEventListener('mousemove', ev => {
	        //     //   const { scene, camera, $map } = this;
	        //     //   const obj = getWorldPosition({
	        //     //     event: ev,
	        //     //     scene,
	        //     //     camera,
	        //     //     $map,
	        //     //     objects: ext?.objects?.()
	        //     //   });
	        //     //   // 如果有获取到屏幕坐标的话，默认会携带当前地图屏幕坐标，用于其他操作
	        //     //   let screenPosition;
	        //     //   if (obj.worldPosition) {
	        //     //     screenPosition = getScreenPostion({
	        //     //       worldPosition: obj.worldPosition,
	        //     //       $map,
	        //     //       scene,
	        //     //       camera
	        //     //     });
	        //     //   }
	        //     //   this.emitter.emit('mousemove', {
	        //     //     ...ev,
	        //     //     ...obj,
	        //     //     screenPosition
	        //     //   });
	        //     // });
	        //     break;
	        //   }
	        //   default:
	        //     break;
	        // }
	        return this;
	    }
	    off(type, handler) {
	        // switch (type) {
	        //   case 'click':
	        //     this.domElement.removeEventListener('mousedown', this.onMouseDown);
	        //     // this.domElement.removeEventListener('mouseup', this.onMouseUp);
	        //     break;
	        //   default:
	        //     break;
	        // }
	        this.emitter.off(type, handler);
	        return this;
	    }
	    /**
	     * @desc 初始化地图：场景，相机，灯光，渲染器，rendererResize，轨道控制器
	     */
	    init() {
	        const $map = document.getElementById(this.container);
	        // #region 场景
	        const scene = new three.Scene();
	        // #endregion
	        // #region 相机
	        const width = $map.clientWidth;
	        const height = $map.clientHeight;
	        const k = width / height;
	        /**
	         * 后面两个参数的概念，就像人的眼睛
	         * 第三个参数想象成距离人的眼睛，多近才会看不到，比如 0.1，表示小于0.1，人才会看不到
	         * 第四个参数想象成距离人的眼睛，多远才会看不到，比如 10000，表示大于10000，人才会看不到
	         */
	        // const camera = new THREE.PerspectiveCamera(45, k, 0.01, 83150);
	        // 最后一个参数是要进行判断，还是说直接设置一个很大的值？？
	        // const camera = new THREE.PerspectiveCamera(45, k, 0.01, 1000000);
	        // const camera = new PerspectiveCamera(45, k, 0.01, Math.pow(10, 100));
	        const camera = new three.PerspectiveCamera(45, k, 0.01, Math.pow(10, 100));
	        // const camera = new PerspectiveCamera(45, k, 0.01, Math.pow(10, 100));
	        // const camera = new PerspectiveCamera(45, k, Math.pow(0.01, 100), 100);
	        // const camera = new THREE.PerspectiveCamera(45, k, 0.01, 2000);
	        // 把z轴向上
	        camera.up.x = 0;
	        camera.up.y = 0;
	        camera.up.z = 1;
	        // 设置相机方向(指向的场景对象)
	        // camera.position.set(0, -736903.9005224737, 425451.6653335355)
	        camera.lookAt(scene.position);
	        // #endregion
	        // #region 灯光
	        const light = new three.HemisphereLight('#ffffff', '#e7e7e7', 1.0);
	        light.name = 'light';
	        light.position.set(-100, -100, 0);
	        scene.add(light);
	        // #endregion
	        // #region 渲染器
	        const renderer = new three.WebGLRenderer({
	            // 如果想保存three.js canvas画布上的信息，注意设置preserveDrawingBuffer
	            preserveDrawingBuffer: true,
	            // 抗锯齿，开启来会比较卡，按情况开启
	            antialias: true,
	            alpha: true,
	            logarithmicDepthBuffer: true
	        });
	        renderer.setSize($map.clientWidth, $map.clientHeight);
	        // 设置背景颜色
	        renderer.setClearColor('#e7f2fe', 1);
	        // renderer.setClearColor(0xd3df56, 1) // 设置背景颜色
	        // 暗黑模式
	        // renderer.setClearColor(THEME.dark.renderer.color, 1); //设置背景颜色
	        renderer.setPixelRatio(window.devicePixelRatio);
	        $map.appendChild(renderer.domElement);
	        renderer.render(scene, camera);
	        // #endregion
	        // #region rendererResize
	        const onWindowResize = debounce(() => {
	            const boundingClientRect = $map.getBoundingClientRect();
	            // ✨ 将 boundingClientRect 赋值到 map info 避免其他地方获取 $map 宽高导致重排，性能下降
	            this.info.boundingClientRect = JSON.parse(JSON.stringify(boundingClientRect));
	            const { width, height } = this.info.boundingClientRect;
	            camera.aspect = width / height;
	            camera.updateProjectionMatrix();
	            renderer.setSize(width, height);
	            this.reDraw();
	        }, 100);
	        const observer = elementResizeDetectorMaker();
	        observer.listenTo($map, onWindowResize);
	        // #endregion
	        // #region 相机控制器
	        const cameraControls = this.createCameraControls($map, scene, camera, renderer, () => {
	            for (const [, value] of this.updateSizeMap) {
	                value === null || value === void 0 ? void 0 : value();
	            }
	        }, this.tweenGroupMap);
	        // #endregion
	        // 地图渲染完毕
	        // emitter.emit('complete')
	        return { scene, camera, cameraControls, $map, renderer };
	    }
	    /**
	     * @desc 相机控制器
	     */
	    createCameraControls($map, scene, camera, renderer, updateFn, tweenGroupMap) {
	        MyCameraControls.install({ THREE: subsetOfTHREE });
	        const clock = new three.Clock();
	        // ❌
	        // const controls = new MyCameraControls(camera, renderer.domElement);
	        // ✨ 事件要注册到外层 map 上，否则会导致窗体不能进行 wheel 事件
	        const controls = new MyCameraControls(camera, $map);
	        const _this = this;
	        (function anim() {
	            var _a, _b;
	            (_a = _this.stats) === null || _a === void 0 ? void 0 : _a.begin();
	            // snip
	            const delta = clock.getDelta();
	            const hasControlsUpdated = controls.update(delta);
	            requestAnimationFrame(anim);
	            // you can skip this condition to render though
	            // 不再把 viewChanged 放置 CameraControls 作为静态属性，这样子不能保证多例，因为静态属性会共享一个副本
	            // if (hasControlsUpdated || CameraControls.viewChanged) {
	            // //  只有相机被改变才触发
	            // if (hasControlsUpdated) {
	            //   updateFn();
	            // }
	            if (hasControlsUpdated || _this.viewChanged) {
	                // 一些会受到相机改变影响的方法
	                updateFn();
	                renderer.render(scene, camera);
	                // 一些会受到相机改变影响的方法，移动至 render 之前
	                // updateFn();
	            }
	            // http://tweenjs.github.io/tween.js/docs/user_guide.html#controlling-groups-of-tweens
	            // 补间动画，必须要加入 group 作用域，否则会影响到其他动画
	            // TWEEN.update();
	            for (const [k] of tweenGroupMap)
	                k === null || k === void 0 ? void 0 : k.update();
	            (_b = _this.stats) === null || _b === void 0 ? void 0 : _b.end();
	            // requestAnimationFrame(anim);
	        })();
	        // renderer.render(scene, camera);
	        return controls;
	    }
	    /**
	     * @desc 恢复到相机的初始状态
	     */
	    reset() {
	        const { cameraControls, camera } = this;
	        // 休息阈值，默认 0.0025，调整会影响到 await 的过渡时长
	        // controls.restThreshold = 0.0025;
	        // controls.restThreshold = 0.01;
	        // controls.restThreshold = 10;
	        // 阻尼惯性，默认 0.05，调整会影响到 await 的过渡时长
	        // cameraControls.dampingFactor = 0.05 * 2;
	        cameraControls.dampingFactor = 1;
	        // 拖动时的阻尼惯性，默认 0.25
	        cameraControls.draggingDampingFactor = 0.25 * 2;
	        // controls.azimuthRotateSpeed = 1 * 2;
	        // controls.polarRotateSpeed = 1 * 2;
	        // controls.dollySpeed = 1 * 1.5;
	        cameraControls.dollySpeed = 1 * 1.5;
	        // 为了2d精灵图世界转屏幕性能，这里提高地图的放大缩放阈值
	        // cameraControls.dollySpeed = 1 * 3;
	        // 如果为true，表示前后（远近）
	        cameraControls.verticalDragToForward = true;
	        // 上下
	        cameraControls.minPolarAngle = 0;
	        cameraControls.maxPolarAngle = Math.PI;
	        // dolly
	        cameraControls.minDistance = 0;
	        cameraControls.maxDistance = Infinity;
	        // 左右
	        cameraControls.minAzimuthAngle = -Infinity;
	        cameraControls.maxAzimuthAngle = Infinity;
	        // 改变相机 fov
	        camera.fov = 45;
	        camera.updateProjectionMatrix();
	        return this;
	    }
	    destroy() { }
	    // /**
	    //  * @desc 添加地图上的控件，如二三维切换器，缩放器等
	    //  */
	    // addControl(control: IControl) {
	    //   control
	    //     ._inject(this)
	    //     // 初始化挂载
	    //     ._init();
	    //   return this;
	    // }
	    /**
	     * @desc 添加地图上的辅助对象，如灯光线条或者
	     */
	    addHelper() {
	        return this;
	    }
	    // #region 一些控制地图的方法
	    // 皮肤变化
	    setStyle(style) {
	        // this.options.style = style
	        return this;
	    }
	    setShowStats(showStats) {
	        if (showStats) {
	            this.stats = createStats(this.container);
	            this.reDraw();
	        }
	        return this;
	    }
	    // 维度变化
	    setViewMode(viewMode) {
	        this.options.viewMode = viewMode;
	        viewMode === '3D' ? this.fitToBox3d() : this.fitToBox2d();
	        return this;
	    }
	    // mesh 获取当前楼层为基准
	    fitToBox2d() {
	        const _getTarget = () => {
	            // const allLevelObjs = getObjectsByName(OBJECT_NAME.level, this.scene);
	            const allLevelObjs = getObjectsByName('level', this.scene);
	            // 最高楼层
	            return allLevelObjs[allLevelObjs.length - 1];
	        };
	        // const levelObj = getCurrentLevelObj(unref(currentLotInfo).zIndex)
	        const target = _getTarget();
	        const { fitDistance, dollys } = getDollys(target, this.cameraControls);
	        const enableTransition = true;
	        // 控制水平垂直旋转
	        this.cameraControls.minPolarAngle =
	            this.cameraControls.maxPolarAngle =
	                this.cameraControls.minAzimuthAngle =
	                    this.cameraControls.maxAzimuthAngle =
	                        0;
	        // @ts-ignore
	        this.cameraControls.dollyTo(fitDistance, enableTransition);
	        this.cameraControls.rotateTo(0, 0, enableTransition);
	        // moveTo 到合适的位置
	        // this.cameraControls.moveTo(0, 0, levelObj?.position.z!, true)
	        this.cameraControls.moveTo(0, 0, 0, true);
	    }
	    fitToBox3d() {
	        // 开启只能上下移动的模式
	        // this.cameraControls.truckYDisabled = true
	        // this.cameraControls.verticalDragToForward = false
	        const _getTarget = () => {
	            // const allLevelObjs = getObjectsByName(OBJECT_NAME.level, this.scene);
	            const allLevelObjs = getObjectsByName('level', this.scene);
	            // 最高楼层
	            return allLevelObjs[allLevelObjs.length - 1];
	        };
	        const enableTransition = true;
	        // [多层] to do... 判断以面积最小的楼层来设置 dollys
	        // if (stateLevelSwitcher.mode === 'multi') {
	        //   // 上下旋转范围
	        //   global.controls.minPolarAngle = Math.PI * (60 / 180)
	        //   global.controls.maxPolarAngle = Math.PI * (60 / 180)
	        // } else {
	        //   // 上下旋转范围
	        //   global.controls.minPolarAngle = 0
	        //   global.controls.maxPolarAngle = Math.PI * (60 / 180)
	        // }
	        // 控制上下旋转
	        // this.cameraControls.maxPolarAngle = Math.PI * (60 / 180); // radians
	        // 左右
	        this.cameraControls.minAzimuthAngle = -Infinity;
	        this.cameraControls.maxAzimuthAngle = Infinity;
	        const target = _getTarget();
	        const { fitDistance, dollys } = getDollys(target, this.cameraControls);
	        if (fitDistance) {
	            this.cameraControls.dollyTo(fitDistance, enableTransition);
	            Object.assign(this.info, {
	                fitDistance
	            });
	        }
	        this.cameraControls.rotateTo(0, Math.PI * (60 / 180), enableTransition);
	        this.cameraControls.moveTo(0, 0, 0, true);
	    }
	}

	/**
	 * mitt 事件总程
	 */
	class MyMitt {
	    constructor() {
	        Object.defineProperty(this, "emitter", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: mitt()
	        });
	    }
	    on(type, handler) {
	        this.emitter.on(type, handler);
	        return this;
	    }
	    off(type, handler) {
	        this.emitter.off(type, handler);
	        return this;
	    }
	}

	/**
	 * 基类，element
	 *
	 * 被添加到地图上的元素
	 *
	 * 若当前扩展类不需要 mitt，在继承时，泛型填写 any，如：
	 *
	 * ```ts
	 * class Foo extends Element<any>{
	 *
	 * }
	 * ```
	 */
	class Element extends MyMitt {
	    constructor() {
	        super();
	        /**
	         * NAME
	         * 一般为子类的类名（防止工具压缩把类名压缩了，导致一些拿类名判断的逻辑失效，所以手动加上类名）
	         */
	        // abstract NAME: string;
	        Object.defineProperty(this, "map", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	    }
	    /**
	     * __inject
	     * 当元素被 map.add 之后，会注入整个 map 对象到子类，提供子类使用 map
	     */
	    __inject(map) {
	        this.map = map;
	        return this;
	    }
	}

	/**
	 * TODO:Control 基类，待实现
	 */
	class Control extends MyMitt {
	    constructor() {
	        super();
	        // abstract NAME: string;
	        Object.defineProperty(this, "map", {
	            enumerable: true,
	            configurable: true,
	            writable: true,
	            value: void 0
	        });
	    }
	    __inject(map) {
	        this.map = map;
	        return this;
	    }
	}

	// 📝 https://www.zhihu.com/question/276314390
	/**
	 * Service 服务类
	 */
	class Service extends MyMitt {
	    constructor() {
	        super();
	    }
	}

	/**
	 * 信息窗体
	 */
	class InfoWindow extends MyMitt {
	    constructor() {
	        super();
	    }
	}

	// 📝 https://www.zhihu.com/question/276314390
	// 目前不好约束子类 static 成员，只能在运行时检测
	/**
	 * 右键菜单
	 */
	class ContextMenu {
	    constructor() { }
	}

	// @ts-ignore
	const KTMap = {
	    Map: _Map,
	    use(plugins) {
	        plugins = Array.isArray(plugins) ? plugins : [plugins];
	        for (const item of plugins) {
	            // @ts-ignore
	            this[item.NAME] = item;
	        }
	        return this;
	    }
	};
	// // eslint-disable-next-line @typescript-eslint/no-namespace
	// declare namespace KTMap {
	//   type foo = string;
	// }

	exports.ContextMenu = ContextMenu;
	exports.Control = Control;
	exports.Element = Element;
	exports.InfoWindow = InfoWindow;
	exports.MyMitt = MyMitt;
	exports.Service = Service;
	exports["default"] = KTMap;

	Object.defineProperty(exports, '__esModule', { value: true });

	return exports;

})({}, THREE);
