define(["@jupyter-widgets/base"], function(__WEBPACK_EXTERNAL_MODULE_22__) { return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 109);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery JavaScript Library v3.7.1
 * https://jquery.com/
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2023-08-28T13:37Z
 */
( function( global, factory ) {

	"use strict";

	if ( typeof module === "object" && typeof module.exports === "object" ) {

		// For CommonJS and CommonJS-like environments where a proper `window`
		// is present, execute the factory and get jQuery.
		// For environments that do not have a `window` with a `document`
		// (such as Node.js), expose a factory as module.exports.
		// This accentuates the need for the creation of a real `window`.
		// e.g. var jQuery = require("jquery")(window);
		// See ticket trac-14549 for more info.
		module.exports = global.document ?
			factory( global, true ) :
			function( w ) {
				if ( !w.document ) {
					throw new Error( "jQuery requires a window with a document" );
				}
				return factory( w );
			};
	} else {
		factory( global );
	}

// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";

var arr = [];

var getProto = Object.getPrototypeOf;

var slice = arr.slice;

var flat = arr.flat ? function( array ) {
	return arr.flat.call( array );
} : function( array ) {
	return arr.concat.apply( [], array );
};


var push = arr.push;

var indexOf = arr.indexOf;

var class2type = {};

var toString = class2type.toString;

var hasOwn = class2type.hasOwnProperty;

var fnToString = hasOwn.toString;

var ObjectFunctionString = fnToString.call( Object );

var support = {};

var isFunction = function isFunction( obj ) {

		// Support: Chrome <=57, Firefox <=52
		// In some browsers, typeof returns "function" for HTML <object> elements
		// (i.e., `typeof document.createElement( "object" ) === "function"`).
		// We don't want to classify *any* DOM node as a function.
		// Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5
		// Plus for old WebKit, typeof returns "function" for HTML collections
		// (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756)
		return typeof obj === "function" && typeof obj.nodeType !== "number" &&
			typeof obj.item !== "function";
	};


var isWindow = function isWindow( obj ) {
		return obj != null && obj === obj.window;
	};


var document = window.document;



	var preservedScriptAttributes = {
		type: true,
		src: true,
		nonce: true,
		noModule: true
	};

	function DOMEval( code, node, doc ) {
		doc = doc || document;

		var i, val,
			script = doc.createElement( "script" );

		script.text = code;
		if ( node ) {
			for ( i in preservedScriptAttributes ) {

				// Support: Firefox 64+, Edge 18+
				// Some browsers don't support the "nonce" property on scripts.
				// On the other hand, just using `getAttribute` is not enough as
				// the `nonce` attribute is reset to an empty string whenever it
				// becomes browsing-context connected.
				// See https://github.com/whatwg/html/issues/2369
				// See https://html.spec.whatwg.org/#nonce-attributes
				// The `node.getAttribute` check was added for the sake of
				// `jQuery.globalEval` so that it can fake a nonce-containing node
				// via an object.
				val = node[ i ] || node.getAttribute && node.getAttribute( i );
				if ( val ) {
					script.setAttribute( i, val );
				}
			}
		}
		doc.head.appendChild( script ).parentNode.removeChild( script );
	}


function toType( obj ) {
	if ( obj == null ) {
		return obj + "";
	}

	// Support: Android <=2.3 only (functionish RegExp)
	return typeof obj === "object" || typeof obj === "function" ?
		class2type[ toString.call( obj ) ] || "object" :
		typeof obj;
}
/* global Symbol */
// Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module



var version = "3.7.1",

	rhtmlSuffix = /HTML$/i,

	// Define a local copy of jQuery
	jQuery = function( selector, context ) {

		// The jQuery object is actually just the init constructor 'enhanced'
		// Need init if jQuery is called (just allow error to be thrown if not included)
		return new jQuery.fn.init( selector, context );
	};

jQuery.fn = jQuery.prototype = {

	// The current version of jQuery being used
	jquery: version,

	constructor: jQuery,

	// The default length of a jQuery object is 0
	length: 0,

	toArray: function() {
		return slice.call( this );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {

		// Return all the elements in a clean array
		if ( num == null ) {
			return slice.call( this );
		}

		// Return just the one element from the set
		return num < 0 ? this[ num + this.length ] : this[ num ];
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems ) {

		// Build a new jQuery matched element set
		var ret = jQuery.merge( this.constructor(), elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	each: function( callback ) {
		return jQuery.each( this, callback );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map( this, function( elem, i ) {
			return callback.call( elem, i, elem );
		} ) );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ) );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	even: function() {
		return this.pushStack( jQuery.grep( this, function( _elem, i ) {
			return ( i + 1 ) % 2;
		} ) );
	},

	odd: function() {
		return this.pushStack( jQuery.grep( this, function( _elem, i ) {
			return i % 2;
		} ) );
	},

	eq: function( i ) {
		var len = this.length,
			j = +i + ( i < 0 ? len : 0 );
		return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
	},

	end: function() {
		return this.prevObject || this.constructor();
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: arr.sort,
	splice: arr.splice
};

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[ 0 ] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;

		// Skip the boolean and the target
		target = arguments[ i ] || {};
		i++;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !isFunction( target ) ) {
		target = {};
	}

	// Extend jQuery itself if only one argument is passed
	if ( i === length ) {
		target = this;
		i--;
	}

	for ( ; i < length; i++ ) {

		// Only deal with non-null/undefined values
		if ( ( options = arguments[ i ] ) != null ) {

			// Extend the base object
			for ( name in options ) {
				copy = options[ name ];

				// Prevent Object.prototype pollution
				// Prevent never-ending loop
				if ( name === "__proto__" || target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
					( copyIsArray = Array.isArray( copy ) ) ) ) {
					src = target[ name ];

					// Ensure proper type for the source value
					if ( copyIsArray && !Array.isArray( src ) ) {
						clone = [];
					} else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {
						clone = {};
					} else {
						clone = src;
					}
					copyIsArray = false;

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend( {

	// Unique for each copy of jQuery on the page
	expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),

	// Assume jQuery is ready without the ready module
	isReady: true,

	error: function( msg ) {
		throw new Error( msg );
	},

	noop: function() {},

	isPlainObject: function( obj ) {
		var proto, Ctor;

		// Detect obvious negatives
		// Use toString instead of jQuery.type to catch host objects
		if ( !obj || toString.call( obj ) !== "[object Object]" ) {
			return false;
		}

		proto = getProto( obj );

		// Objects with no prototype (e.g., `Object.create( null )`) are plain
		if ( !proto ) {
			return true;
		}

		// Objects with prototype are plain iff they were constructed by a global Object function
		Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
		return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
	},

	isEmptyObject: function( obj ) {
		var name;

		for ( name in obj ) {
			return false;
		}
		return true;
	},

	// Evaluates a script in a provided context; falls back to the global one
	// if not specified.
	globalEval: function( code, options, doc ) {
		DOMEval( code, { nonce: options && options.nonce }, doc );
	},

	each: function( obj, callback ) {
		var length, i = 0;

		if ( isArrayLike( obj ) ) {
			length = obj.length;
			for ( ; i < length; i++ ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		} else {
			for ( i in obj ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		}

		return obj;
	},


	// Retrieve the text value of an array of DOM nodes
	text: function( elem ) {
		var node,
			ret = "",
			i = 0,
			nodeType = elem.nodeType;

		if ( !nodeType ) {

			// If no nodeType, this is expected to be an array
			while ( ( node = elem[ i++ ] ) ) {

				// Do not traverse comment nodes
				ret += jQuery.text( node );
			}
		}
		if ( nodeType === 1 || nodeType === 11 ) {
			return elem.textContent;
		}
		if ( nodeType === 9 ) {
			return elem.documentElement.textContent;
		}
		if ( nodeType === 3 || nodeType === 4 ) {
			return elem.nodeValue;
		}

		// Do not include comment or processing instruction nodes

		return ret;
	},

	// results is for internal usage only
	makeArray: function( arr, results ) {
		var ret = results || [];

		if ( arr != null ) {
			if ( isArrayLike( Object( arr ) ) ) {
				jQuery.merge( ret,
					typeof arr === "string" ?
						[ arr ] : arr
				);
			} else {
				push.call( ret, arr );
			}
		}

		return ret;
	},

	inArray: function( elem, arr, i ) {
		return arr == null ? -1 : indexOf.call( arr, elem, i );
	},

	isXMLDoc: function( elem ) {
		var namespace = elem && elem.namespaceURI,
			docElem = elem && ( elem.ownerDocument || elem ).documentElement;

		// Assume HTML when documentElement doesn't yet exist, such as inside
		// document fragments.
		return !rhtmlSuffix.test( namespace || docElem && docElem.nodeName || "HTML" );
	},

	// Support: Android <=4.0 only, PhantomJS 1 only
	// push.apply(_, arraylike) throws on ancient WebKit
	merge: function( first, second ) {
		var len = +second.length,
			j = 0,
			i = first.length;

		for ( ; j < len; j++ ) {
			first[ i++ ] = second[ j ];
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, invert ) {
		var callbackInverse,
			matches = [],
			i = 0,
			length = elems.length,
			callbackExpect = !invert;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( ; i < length; i++ ) {
			callbackInverse = !callback( elems[ i ], i );
			if ( callbackInverse !== callbackExpect ) {
				matches.push( elems[ i ] );
			}
		}

		return matches;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var length, value,
			i = 0,
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArrayLike( elems ) ) {
			length = elems.length;
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}
		}

		// Flatten any nested arrays
		return flat( ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// jQuery.support is not used in Core but other projects attach their
	// properties to it so it needs to exist.
	support: support
} );

if ( typeof Symbol === "function" ) {
	jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}

// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
	function( _i, name ) {
		class2type[ "[object " + name + "]" ] = name.toLowerCase();
	} );

function isArrayLike( obj ) {

	// Support: real iOS 8.2 only (not reproducible in simulator)
	// `in` check used to prevent JIT error (gh-2145)
	// hasOwn isn't used here due to false negatives
	// regarding Nodelist length in IE
	var length = !!obj && "length" in obj && obj.length,
		type = toType( obj );

	if ( isFunction( obj ) || isWindow( obj ) ) {
		return false;
	}

	return type === "array" || length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}


function nodeName( elem, name ) {

	return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();

}
var pop = arr.pop;


var sort = arr.sort;


var splice = arr.splice;


var whitespace = "[\\x20\\t\\r\\n\\f]";


var rtrimCSS = new RegExp(
	"^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$",
	"g"
);




// Note: an element does not contain itself
jQuery.contains = function( a, b ) {
	var bup = b && b.parentNode;

	return a === bup || !!( bup && bup.nodeType === 1 && (

		// Support: IE 9 - 11+
		// IE doesn't have `contains` on SVG.
		a.contains ?
			a.contains( bup ) :
			a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
	) );
};




// CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g;

function fcssescape( ch, asCodePoint ) {
	if ( asCodePoint ) {

		// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
		if ( ch === "\0" ) {
			return "\uFFFD";
		}

		// Control characters and (dependent upon position) numbers get escaped as code points
		return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
	}

	// Other potentially-special ASCII characters get backslash-escaped
	return "\\" + ch;
}

jQuery.escapeSelector = function( sel ) {
	return ( sel + "" ).replace( rcssescape, fcssescape );
};




var preferredDoc = document,
	pushNative = push;

( function() {

var i,
	Expr,
	outermostContext,
	sortInput,
	hasDuplicate,
	push = pushNative,

	// Local document vars
	document,
	documentElement,
	documentIsHTML,
	rbuggyQSA,
	matches,

	// Instance-specific data
	expando = jQuery.expando,
	dirruns = 0,
	done = 0,
	classCache = createCache(),
	tokenCache = createCache(),
	compilerCache = createCache(),
	nonnativeSelectorCache = createCache(),
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
		}
		return 0;
	},

	booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|" +
		"loop|multiple|open|readonly|required|scoped",

	// Regular expressions

	// https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
	identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace +
		"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",

	// Attribute selectors: https://www.w3.org/TR/selectors/#attribute-selectors
	attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +

		// Operator (capture 2)
		"*([*^$|!~]?=)" + whitespace +

		// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" +
		whitespace + "*\\]",

	pseudos = ":(" + identifier + ")(?:\\((" +

		// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
		// 1. quoted (capture 3; capture 4 or capture 5)
		"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +

		// 2. simple (capture 6)
		"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +

		// 3. anything else (capture 2)
		".*" +
		")\\)|)",

	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
	rwhitespace = new RegExp( whitespace + "+", "g" ),

	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
	rleadingCombinator = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" +
		whitespace + "*" ),
	rdescend = new RegExp( whitespace + "|>" ),

	rpseudo = new RegExp( pseudos ),
	ridentifier = new RegExp( "^" + identifier + "$" ),

	matchExpr = {
		ID: new RegExp( "^#(" + identifier + ")" ),
		CLASS: new RegExp( "^\\.(" + identifier + ")" ),
		TAG: new RegExp( "^(" + identifier + "|[*])" ),
		ATTR: new RegExp( "^" + attributes ),
		PSEUDO: new RegExp( "^" + pseudos ),
		CHILD: new RegExp(
			"^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" +
				whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" +
				whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
		bool: new RegExp( "^(?:" + booleans + ")$", "i" ),

		// For use in libraries implementing .is()
		// We use this for POS matching in `select`
		needsContext: new RegExp( "^" + whitespace +
			"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
			"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
	},

	rinputs = /^(?:input|select|textarea|button)$/i,
	rheader = /^h\d$/i,

	// Easily-parseable/retrievable ID or TAG or CLASS selectors
	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,

	rsibling = /[+~]/,

	// CSS escapes
	// https://www.w3.org/TR/CSS21/syndata.html#escaped-characters
	runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace +
		"?|\\\\([^\\r\\n\\f])", "g" ),
	funescape = function( escape, nonHex ) {
		var high = "0x" + escape.slice( 1 ) - 0x10000;

		if ( nonHex ) {

			// Strip the backslash prefix from a non-hex escape sequence
			return nonHex;
		}

		// Replace a hexadecimal escape sequence with the encoded Unicode code point
		// Support: IE <=11+
		// For values outside the Basic Multilingual Plane (BMP), manually construct a
		// surrogate pair
		return high < 0 ?
			String.fromCharCode( high + 0x10000 ) :
			String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
	},

	// Used for iframes; see `setDocument`.
	// Support: IE 9 - 11+, Edge 12 - 18+
	// Removing the function wrapper causes a "Permission Denied"
	// error in IE/Edge.
	unloadHandler = function() {
		setDocument();
	},

	inDisabledFieldset = addCombinator(
		function( elem ) {
			return elem.disabled === true && nodeName( elem, "fieldset" );
		},
		{ dir: "parentNode", next: "legend" }
	);

// Support: IE <=9 only
// Accessing document.activeElement can throw unexpectedly
// https://bugs.jquery.com/ticket/13393
function safeActiveElement() {
	try {
		return document.activeElement;
	} catch ( err ) { }
}

// Optimize for push.apply( _, NodeList )
try {
	push.apply(
		( arr = slice.call( preferredDoc.childNodes ) ),
		preferredDoc.childNodes
	);

	// Support: Android <=4.0
	// Detect silently failing push.apply
	// eslint-disable-next-line no-unused-expressions
	arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
	push = {
		apply: function( target, els ) {
			pushNative.apply( target, slice.call( els ) );
		},
		call: function( target ) {
			pushNative.apply( target, slice.call( arguments, 1 ) );
		}
	};
}

function find( selector, context, results, seed ) {
	var m, i, elem, nid, match, groups, newSelector,
		newContext = context && context.ownerDocument,

		// nodeType defaults to 9, since context defaults to document
		nodeType = context ? context.nodeType : 9;

	results = results || [];

	// Return early from calls with invalid selector or context
	if ( typeof selector !== "string" || !selector ||
		nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {

		return results;
	}

	// Try to shortcut find operations (as opposed to filters) in HTML documents
	if ( !seed ) {
		setDocument( context );
		context = context || document;

		if ( documentIsHTML ) {

			// If the selector is sufficiently simple, try using a "get*By*" DOM method
			// (excepting DocumentFragment context, where the methods don't exist)
			if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) {

				// ID selector
				if ( ( m = match[ 1 ] ) ) {

					// Document context
					if ( nodeType === 9 ) {
						if ( ( elem = context.getElementById( m ) ) ) {

							// Support: IE 9 only
							// getElementById can match elements by name instead of ID
							if ( elem.id === m ) {
								push.call( results, elem );
								return results;
							}
						} else {
							return results;
						}

					// Element context
					} else {

						// Support: IE 9 only
						// getElementById can match elements by name instead of ID
						if ( newContext && ( elem = newContext.getElementById( m ) ) &&
							find.contains( context, elem ) &&
							elem.id === m ) {

							push.call( results, elem );
							return results;
						}
					}

				// Type selector
				} else if ( match[ 2 ] ) {
					push.apply( results, context.getElementsByTagName( selector ) );
					return results;

				// Class selector
				} else if ( ( m = match[ 3 ] ) && context.getElementsByClassName ) {
					push.apply( results, context.getElementsByClassName( m ) );
					return results;
				}
			}

			// Take advantage of querySelectorAll
			if ( !nonnativeSelectorCache[ selector + " " ] &&
				( !rbuggyQSA || !rbuggyQSA.test( selector ) ) ) {

				newSelector = selector;
				newContext = context;

				// qSA considers elements outside a scoping root when evaluating child or
				// descendant combinators, which is not what we want.
				// In such cases, we work around the behavior by prefixing every selector in the
				// list with an ID selector referencing the scope context.
				// The technique has to be used as well when a leading combinator is used
				// as such selectors are not recognized by querySelectorAll.
				// Thanks to Andrew Dupont for this technique.
				if ( nodeType === 1 &&
					( rdescend.test( selector ) || rleadingCombinator.test( selector ) ) ) {

					// Expand context for sibling selectors
					newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
						context;

					// We can use :scope instead of the ID hack if the browser
					// supports it & if we're not changing the context.
					// Support: IE 11+, Edge 17 - 18+
					// IE/Edge sometimes throw a "Permission denied" error when
					// strict-comparing two documents; shallow comparisons work.
					// eslint-disable-next-line eqeqeq
					if ( newContext != context || !support.scope ) {

						// Capture the context ID, setting it first if necessary
						if ( ( nid = context.getAttribute( "id" ) ) ) {
							nid = jQuery.escapeSelector( nid );
						} else {
							context.setAttribute( "id", ( nid = expando ) );
						}
					}

					// Prefix every selector in the list
					groups = tokenize( selector );
					i = groups.length;
					while ( i-- ) {
						groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " +
							toSelector( groups[ i ] );
					}
					newSelector = groups.join( "," );
				}

				try {
					push.apply( results,
						newContext.querySelectorAll( newSelector )
					);
					return results;
				} catch ( qsaError ) {
					nonnativeSelectorCache( selector, true );
				} finally {
					if ( nid === expando ) {
						context.removeAttribute( "id" );
					}
				}
			}
		}
	}

	// All others
	return select( selector.replace( rtrimCSS, "$1" ), context, results, seed );
}

/**
 * Create key-value caches of limited size
 * @returns {function(string, object)} Returns the Object data after storing it on itself with
 *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
 *	deleting the oldest entry
 */
function createCache() {
	var keys = [];

	function cache( key, value ) {

		// Use (key + " ") to avoid collision with native prototype properties
		// (see https://github.com/jquery/sizzle/issues/157)
		if ( keys.push( key + " " ) > Expr.cacheLength ) {

			// Only keep the most recent entries
			delete cache[ keys.shift() ];
		}
		return ( cache[ key + " " ] = value );
	}
	return cache;
}

/**
 * Mark a function for special use by jQuery selector module
 * @param {Function} fn The function to mark
 */
function markFunction( fn ) {
	fn[ expando ] = true;
	return fn;
}

/**
 * Support testing using an element
 * @param {Function} fn Passed the created element and returns a boolean result
 */
function assert( fn ) {
	var el = document.createElement( "fieldset" );

	try {
		return !!fn( el );
	} catch ( e ) {
		return false;
	} finally {

		// Remove from its parent by default
		if ( el.parentNode ) {
			el.parentNode.removeChild( el );
		}

		// release memory in IE
		el = null;
	}
}

/**
 * Returns a function to use in pseudos for input types
 * @param {String} type
 */
function createInputPseudo( type ) {
	return function( elem ) {
		return nodeName( elem, "input" ) && elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for buttons
 * @param {String} type
 */
function createButtonPseudo( type ) {
	return function( elem ) {
		return ( nodeName( elem, "input" ) || nodeName( elem, "button" ) ) &&
			elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for :enabled/:disabled
 * @param {Boolean} disabled true for :disabled; false for :enabled
 */
function createDisabledPseudo( disabled ) {

	// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
	return function( elem ) {

		// Only certain elements can match :enabled or :disabled
		// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
		// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
		if ( "form" in elem ) {

			// Check for inherited disabledness on relevant non-disabled elements:
			// * listed form-associated elements in a disabled fieldset
			//   https://html.spec.whatwg.org/multipage/forms.html#category-listed
			//   https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
			// * option elements in a disabled optgroup
			//   https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
			// All such elements have a "form" property.
			if ( elem.parentNode && elem.disabled === false ) {

				// Option elements defer to a parent optgroup if present
				if ( "label" in elem ) {
					if ( "label" in elem.parentNode ) {
						return elem.parentNode.disabled === disabled;
					} else {
						return elem.disabled === disabled;
					}
				}

				// Support: IE 6 - 11+
				// Use the isDisabled shortcut property to check for disabled fieldset ancestors
				return elem.isDisabled === disabled ||

					// Where there is no isDisabled, check manually
					elem.isDisabled !== !disabled &&
						inDisabledFieldset( elem ) === disabled;
			}

			return elem.disabled === disabled;

		// Try to winnow out elements that can't be disabled before trusting the disabled property.
		// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
		// even exist on them, let alone have a boolean value.
		} else if ( "label" in elem ) {
			return elem.disabled === disabled;
		}

		// Remaining elements are neither :enabled nor :disabled
		return false;
	};
}

/**
 * Returns a function to use in pseudos for positionals
 * @param {Function} fn
 */
function createPositionalPseudo( fn ) {
	return markFunction( function( argument ) {
		argument = +argument;
		return markFunction( function( seed, matches ) {
			var j,
				matchIndexes = fn( [], seed.length, argument ),
				i = matchIndexes.length;

			// Match elements found at the specified indexes
			while ( i-- ) {
				if ( seed[ ( j = matchIndexes[ i ] ) ] ) {
					seed[ j ] = !( matches[ j ] = seed[ j ] );
				}
			}
		} );
	} );
}

/**
 * Checks a node for validity as a jQuery selector context
 * @param {Element|Object=} context
 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
 */
function testContext( context ) {
	return context && typeof context.getElementsByTagName !== "undefined" && context;
}

/**
 * Sets document-related variables once based on the current document
 * @param {Element|Object} [node] An element or document object to use to set the document
 * @returns {Object} Returns the current document
 */
function setDocument( node ) {
	var subWindow,
		doc = node ? node.ownerDocument || node : preferredDoc;

	// Return early if doc is invalid or already selected
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) {
		return document;
	}

	// Update global variables
	document = doc;
	documentElement = document.documentElement;
	documentIsHTML = !jQuery.isXMLDoc( document );

	// Support: iOS 7 only, IE 9 - 11+
	// Older browsers didn't support unprefixed `matches`.
	matches = documentElement.matches ||
		documentElement.webkitMatchesSelector ||
		documentElement.msMatchesSelector;

	// Support: IE 9 - 11+, Edge 12 - 18+
	// Accessing iframe documents after unload throws "permission denied" errors
	// (see trac-13936).
	// Limit the fix to IE & Edge Legacy; despite Edge 15+ implementing `matches`,
	// all IE 9+ and Edge Legacy versions implement `msMatchesSelector` as well.
	if ( documentElement.msMatchesSelector &&

		// Support: IE 11+, Edge 17 - 18+
		// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
		// two documents; shallow comparisons work.
		// eslint-disable-next-line eqeqeq
		preferredDoc != document &&
		( subWindow = document.defaultView ) && subWindow.top !== subWindow ) {

		// Support: IE 9 - 11+, Edge 12 - 18+
		subWindow.addEventListener( "unload", unloadHandler );
	}

	// Support: IE <10
	// Check if getElementById returns elements by name
	// The broken getElementById methods don't pick up programmatically-set names,
	// so use a roundabout getElementsByName test
	support.getById = assert( function( el ) {
		documentElement.appendChild( el ).id = jQuery.expando;
		return !document.getElementsByName ||
			!document.getElementsByName( jQuery.expando ).length;
	} );

	// Support: IE 9 only
	// Check to see if it's possible to do matchesSelector
	// on a disconnected node.
	support.disconnectedMatch = assert( function( el ) {
		return matches.call( el, "*" );
	} );

	// Support: IE 9 - 11+, Edge 12 - 18+
	// IE/Edge don't support the :scope pseudo-class.
	support.scope = assert( function() {
		return document.querySelectorAll( ":scope" );
	} );

	// Support: Chrome 105 - 111 only, Safari 15.4 - 16.3 only
	// Make sure the `:has()` argument is parsed unforgivingly.
	// We include `*` in the test to detect buggy implementations that are
	// _selectively_ forgiving (specifically when the list includes at least
	// one valid selector).
	// Note that we treat complete lack of support for `:has()` as if it were
	// spec-compliant support, which is fine because use of `:has()` in such
	// environments will fail in the qSA path and fall back to jQuery traversal
	// anyway.
	support.cssHas = assert( function() {
		try {
			document.querySelector( ":has(*,:jqfake)" );
			return false;
		} catch ( e ) {
			return true;
		}
	} );

	// ID filter and find
	if ( support.getById ) {
		Expr.filter.ID = function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				return elem.getAttribute( "id" ) === attrId;
			};
		};
		Expr.find.ID = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
				var elem = context.getElementById( id );
				return elem ? [ elem ] : [];
			}
		};
	} else {
		Expr.filter.ID =  function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				var node = typeof elem.getAttributeNode !== "undefined" &&
					elem.getAttributeNode( "id" );
				return node && node.value === attrId;
			};
		};

		// Support: IE 6 - 7 only
		// getElementById is not reliable as a find shortcut
		Expr.find.ID = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
				var node, i, elems,
					elem = context.getElementById( id );

				if ( elem ) {

					// Verify the id attribute
					node = elem.getAttributeNode( "id" );
					if ( node && node.value === id ) {
						return [ elem ];
					}

					// Fall back on getElementsByName
					elems = context.getElementsByName( id );
					i = 0;
					while ( ( elem = elems[ i++ ] ) ) {
						node = elem.getAttributeNode( "id" );
						if ( node && node.value === id ) {
							return [ elem ];
						}
					}
				}

				return [];
			}
		};
	}

	// Tag
	Expr.find.TAG = function( tag, context ) {
		if ( typeof context.getElementsByTagName !== "undefined" ) {
			return context.getElementsByTagName( tag );

		// DocumentFragment nodes don't have gEBTN
		} else {
			return context.querySelectorAll( tag );
		}
	};

	// Class
	Expr.find.CLASS = function( className, context ) {
		if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
			return context.getElementsByClassName( className );
		}
	};

	/* QSA/matchesSelector
	---------------------------------------------------------------------- */

	// QSA and matchesSelector support

	rbuggyQSA = [];

	// Build QSA regex
	// Regex strategy adopted from Diego Perini
	assert( function( el ) {

		var input;

		documentElement.appendChild( el ).innerHTML =
			"<a id='" + expando + "' href='' disabled='disabled'></a>" +
			"<select id='" + expando + "-\r\\' disabled='disabled'>" +
			"<option selected=''></option></select>";

		// Support: iOS <=7 - 8 only
		// Boolean attributes and "value" are not treated correctly in some XML documents
		if ( !el.querySelectorAll( "[selected]" ).length ) {
			rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
		}

		// Support: iOS <=7 - 8 only
		if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
			rbuggyQSA.push( "~=" );
		}

		// Support: iOS 8 only
		// https://bugs.webkit.org/show_bug.cgi?id=136851
		// In-page `selector#id sibling-combinator selector` fails
		if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
			rbuggyQSA.push( ".#.+[+~]" );
		}

		// Support: Chrome <=105+, Firefox <=104+, Safari <=15.4+
		// In some of the document kinds, these selectors wouldn't work natively.
		// This is probably OK but for backwards compatibility we want to maintain
		// handling them through jQuery traversal in jQuery 3.x.
		if ( !el.querySelectorAll( ":checked" ).length ) {
			rbuggyQSA.push( ":checked" );
		}

		// Support: Windows 8 Native Apps
		// The type and name attributes are restricted during .innerHTML assignment
		input = document.createElement( "input" );
		input.setAttribute( "type", "hidden" );
		el.appendChild( input ).setAttribute( "name", "D" );

		// Support: IE 9 - 11+
		// IE's :disabled selector does not pick up the children of disabled fieldsets
		// Support: Chrome <=105+, Firefox <=104+, Safari <=15.4+
		// In some of the document kinds, these selectors wouldn't work natively.
		// This is probably OK but for backwards compatibility we want to maintain
		// handling them through jQuery traversal in jQuery 3.x.
		documentElement.appendChild( el ).disabled = true;
		if ( el.querySelectorAll( ":disabled" ).length !== 2 ) {
			rbuggyQSA.push( ":enabled", ":disabled" );
		}

		// Support: IE 11+, Edge 15 - 18+
		// IE 11/Edge don't find elements on a `[name='']` query in some cases.
		// Adding a temporary attribute to the document before the selection works
		// around the issue.
		// Interestingly, IE 10 & older don't seem to have the issue.
		input = document.createElement( "input" );
		input.setAttribute( "name", "" );
		el.appendChild( input );
		if ( !el.querySelectorAll( "[name='']" ).length ) {
			rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" +
				whitespace + "*(?:''|\"\")" );
		}
	} );

	if ( !support.cssHas ) {

		// Support: Chrome 105 - 110+, Safari 15.4 - 16.3+
		// Our regular `try-catch` mechanism fails to detect natively-unsupported
		// pseudo-classes inside `:has()` (such as `:has(:contains("Foo"))`)
		// in browsers that parse the `:has()` argument as a forgiving selector list.
		// https://drafts.csswg.org/selectors/#relational now requires the argument
		// to be parsed unforgivingly, but browsers have not yet fully adjusted.
		rbuggyQSA.push( ":has" );
	}

	rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) );

	/* Sorting
	---------------------------------------------------------------------- */

	// Document order sorting
	sortOrder = function( a, b ) {

		// Flag for duplicate removal
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		// Sort on method existence if only one input has compareDocumentPosition
		var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
		if ( compare ) {
			return compare;
		}

		// Calculate position if both inputs belong to the same document
		// Support: IE 11+, Edge 17 - 18+
		// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
		// two documents; shallow comparisons work.
		// eslint-disable-next-line eqeqeq
		compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ?
			a.compareDocumentPosition( b ) :

			// Otherwise we know they are disconnected
			1;

		// Disconnected nodes
		if ( compare & 1 ||
			( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) {

			// Choose the first element that is related to our preferred document
			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			// eslint-disable-next-line eqeqeq
			if ( a === document || a.ownerDocument == preferredDoc &&
				find.contains( preferredDoc, a ) ) {
				return -1;
			}

			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			// eslint-disable-next-line eqeqeq
			if ( b === document || b.ownerDocument == preferredDoc &&
				find.contains( preferredDoc, b ) ) {
				return 1;
			}

			// Maintain original order
			return sortInput ?
				( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
				0;
		}

		return compare & 4 ? -1 : 1;
	};

	return document;
}

find.matches = function( expr, elements ) {
	return find( expr, null, null, elements );
};

find.matchesSelector = function( elem, expr ) {
	setDocument( elem );

	if ( documentIsHTML &&
		!nonnativeSelectorCache[ expr + " " ] &&
		( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {

		try {
			var ret = matches.call( elem, expr );

			// IE 9's matchesSelector returns false on disconnected nodes
			if ( ret || support.disconnectedMatch ||

					// As well, disconnected nodes are said to be in a document
					// fragment in IE 9
					elem.document && elem.document.nodeType !== 11 ) {
				return ret;
			}
		} catch ( e ) {
			nonnativeSelectorCache( expr, true );
		}
	}

	return find( expr, document, null, [ elem ] ).length > 0;
};

find.contains = function( context, elem ) {

	// Set document vars if needed
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( ( context.ownerDocument || context ) != document ) {
		setDocument( context );
	}
	return jQuery.contains( context, elem );
};


find.attr = function( elem, name ) {

	// Set document vars if needed
	// Support: IE 11+, Edge 17 - 18+
	// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
	// two documents; shallow comparisons work.
	// eslint-disable-next-line eqeqeq
	if ( ( elem.ownerDocument || elem ) != document ) {
		setDocument( elem );
	}

	var fn = Expr.attrHandle[ name.toLowerCase() ],

		// Don't get fooled by Object.prototype properties (see trac-13807)
		val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
			fn( elem, name, !documentIsHTML ) :
			undefined;

	if ( val !== undefined ) {
		return val;
	}

	return elem.getAttribute( name );
};

find.error = function( msg ) {
	throw new Error( "Syntax error, unrecognized expression: " + msg );
};

/**
 * Document sorting and removing duplicates
 * @param {ArrayLike} results
 */
jQuery.uniqueSort = function( results ) {
	var elem,
		duplicates = [],
		j = 0,
		i = 0;

	// Unless we *know* we can detect duplicates, assume their presence
	//
	// Support: Android <=4.0+
	// Testing for detecting duplicates is unpredictable so instead assume we can't
	// depend on duplicate detection in all browsers without a stable sort.
	hasDuplicate = !support.sortStable;
	sortInput = !support.sortStable && slice.call( results, 0 );
	sort.call( results, sortOrder );

	if ( hasDuplicate ) {
		while ( ( elem = results[ i++ ] ) ) {
			if ( elem === results[ i ] ) {
				j = duplicates.push( i );
			}
		}
		while ( j-- ) {
			splice.call( results, duplicates[ j ], 1 );
		}
	}

	// Clear input after sorting to release objects
	// See https://github.com/jquery/sizzle/pull/225
	sortInput = null;

	return results;
};

jQuery.fn.uniqueSort = function() {
	return this.pushStack( jQuery.uniqueSort( slice.apply( this ) ) );
};

Expr = jQuery.expr = {

	// Can be adjusted by the user
	cacheLength: 50,

	createPseudo: markFunction,

	match: matchExpr,

	attrHandle: {},

	find: {},

	relative: {
		">": { dir: "parentNode", first: true },
		" ": { dir: "parentNode" },
		"+": { dir: "previousSibling", first: true },
		"~": { dir: "previousSibling" }
	},

	preFilter: {
		ATTR: function( match ) {
			match[ 1 ] = match[ 1 ].replace( runescape, funescape );

			// Move the given value to match[3] whether quoted or unquoted
			match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" )
				.replace( runescape, funescape );

			if ( match[ 2 ] === "~=" ) {
				match[ 3 ] = " " + match[ 3 ] + " ";
			}

			return match.slice( 0, 4 );
		},

		CHILD: function( match ) {

			/* matches from matchExpr["CHILD"]
				1 type (only|nth|...)
				2 what (child|of-type)
				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
				4 xn-component of xn+y argument ([+-]?\d*n|)
				5 sign of xn-component
				6 x of xn-component
				7 sign of y-component
				8 y of y-component
			*/
			match[ 1 ] = match[ 1 ].toLowerCase();

			if ( match[ 1 ].slice( 0, 3 ) === "nth" ) {

				// nth-* requires argument
				if ( !match[ 3 ] ) {
					find.error( match[ 0 ] );
				}

				// numeric x and y parameters for Expr.filter.CHILD
				// remember that false/true cast respectively to 0/1
				match[ 4 ] = +( match[ 4 ] ?
					match[ 5 ] + ( match[ 6 ] || 1 ) :
					2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" )
				);
				match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" );

			// other types prohibit arguments
			} else if ( match[ 3 ] ) {
				find.error( match[ 0 ] );
			}

			return match;
		},

		PSEUDO: function( match ) {
			var excess,
				unquoted = !match[ 6 ] && match[ 2 ];

			if ( matchExpr.CHILD.test( match[ 0 ] ) ) {
				return null;
			}

			// Accept quoted arguments as-is
			if ( match[ 3 ] ) {
				match[ 2 ] = match[ 4 ] || match[ 5 ] || "";

			// Strip excess characters from unquoted arguments
			} else if ( unquoted && rpseudo.test( unquoted ) &&

				// Get excess from tokenize (recursively)
				( excess = tokenize( unquoted, true ) ) &&

				// advance to the next closing parenthesis
				( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) {

				// excess is a negative index
				match[ 0 ] = match[ 0 ].slice( 0, excess );
				match[ 2 ] = unquoted.slice( 0, excess );
			}

			// Return only captures needed by the pseudo filter method (type and argument)
			return match.slice( 0, 3 );
		}
	},

	filter: {

		TAG: function( nodeNameSelector ) {
			var expectedNodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
			return nodeNameSelector === "*" ?
				function() {
					return true;
				} :
				function( elem ) {
					return nodeName( elem, expectedNodeName );
				};
		},

		CLASS: function( className ) {
			var pattern = classCache[ className + " " ];

			return pattern ||
				( pattern = new RegExp( "(^|" + whitespace + ")" + className +
					"(" + whitespace + "|$)" ) ) &&
				classCache( className, function( elem ) {
					return pattern.test(
						typeof elem.className === "string" && elem.className ||
							typeof elem.getAttribute !== "undefined" &&
								elem.getAttribute( "class" ) ||
							""
					);
				} );
		},

		ATTR: function( name, operator, check ) {
			return function( elem ) {
				var result = find.attr( elem, name );

				if ( result == null ) {
					return operator === "!=";
				}
				if ( !operator ) {
					return true;
				}

				result += "";

				if ( operator === "=" ) {
					return result === check;
				}
				if ( operator === "!=" ) {
					return result !== check;
				}
				if ( operator === "^=" ) {
					return check && result.indexOf( check ) === 0;
				}
				if ( operator === "*=" ) {
					return check && result.indexOf( check ) > -1;
				}
				if ( operator === "$=" ) {
					return check && result.slice( -check.length ) === check;
				}
				if ( operator === "~=" ) {
					return ( " " + result.replace( rwhitespace, " " ) + " " )
						.indexOf( check ) > -1;
				}
				if ( operator === "|=" ) {
					return result === check || result.slice( 0, check.length + 1 ) === check + "-";
				}

				return false;
			};
		},

		CHILD: function( type, what, _argument, first, last ) {
			var simple = type.slice( 0, 3 ) !== "nth",
				forward = type.slice( -4 ) !== "last",
				ofType = what === "of-type";

			return first === 1 && last === 0 ?

				// Shortcut for :nth-*(n)
				function( elem ) {
					return !!elem.parentNode;
				} :

				function( elem, _context, xml ) {
					var cache, outerCache, node, nodeIndex, start,
						dir = simple !== forward ? "nextSibling" : "previousSibling",
						parent = elem.parentNode,
						name = ofType && elem.nodeName.toLowerCase(),
						useCache = !xml && !ofType,
						diff = false;

					if ( parent ) {

						// :(first|last|only)-(child|of-type)
						if ( simple ) {
							while ( dir ) {
								node = elem;
								while ( ( node = node[ dir ] ) ) {
									if ( ofType ?
										nodeName( node, name ) :
										node.nodeType === 1 ) {

										return false;
									}
								}

								// Reverse direction for :only-* (if we haven't yet done so)
								start = dir = type === "only" && !start && "nextSibling";
							}
							return true;
						}

						start = [ forward ? parent.firstChild : parent.lastChild ];

						// non-xml :nth-child(...) stores cache data on `parent`
						if ( forward && useCache ) {

							// Seek `elem` from a previously-cached index
							outerCache = parent[ expando ] || ( parent[ expando ] = {} );
							cache = outerCache[ type ] || [];
							nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
							diff = nodeIndex && cache[ 2 ];
							node = nodeIndex && parent.childNodes[ nodeIndex ];

							while ( ( node = ++nodeIndex && node && node[ dir ] ||

								// Fallback to seeking `elem` from the start
								( diff = nodeIndex = 0 ) || start.pop() ) ) {

								// When found, cache indexes on `parent` and break
								if ( node.nodeType === 1 && ++diff && node === elem ) {
									outerCache[ type ] = [ dirruns, nodeIndex, diff ];
									break;
								}
							}

						} else {

							// Use previously-cached element index if available
							if ( useCache ) {
								outerCache = elem[ expando ] || ( elem[ expando ] = {} );
								cache = outerCache[ type ] || [];
								nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
								diff = nodeIndex;
							}

							// xml :nth-child(...)
							// or :nth-last-child(...) or :nth(-last)?-of-type(...)
							if ( diff === false ) {

								// Use the same loop as above to seek `elem` from the start
								while ( ( node = ++nodeIndex && node && node[ dir ] ||
									( diff = nodeIndex = 0 ) || start.pop() ) ) {

									if ( ( ofType ?
										nodeName( node, name ) :
										node.nodeType === 1 ) &&
										++diff ) {

										// Cache the index of each encountered element
										if ( useCache ) {
											outerCache = node[ expando ] ||
												( node[ expando ] = {} );
											outerCache[ type ] = [ dirruns, diff ];
										}

										if ( node === elem ) {
											break;
										}
									}
								}
							}
						}

						// Incorporate the offset, then check against cycle size
						diff -= last;
						return diff === first || ( diff % first === 0 && diff / first >= 0 );
					}
				};
		},

		PSEUDO: function( pseudo, argument ) {

			// pseudo-class names are case-insensitive
			// https://www.w3.org/TR/selectors/#pseudo-classes
			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
			// Remember that setFilters inherits from pseudos
			var args,
				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
					find.error( "unsupported pseudo: " + pseudo );

			// The user may use createPseudo to indicate that
			// arguments are needed to create the filter function
			// just as jQuery does
			if ( fn[ expando ] ) {
				return fn( argument );
			}

			// But maintain support for old signatures
			if ( fn.length > 1 ) {
				args = [ pseudo, pseudo, "", argument ];
				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
					markFunction( function( seed, matches ) {
						var idx,
							matched = fn( seed, argument ),
							i = matched.length;
						while ( i-- ) {
							idx = indexOf.call( seed, matched[ i ] );
							seed[ idx ] = !( matches[ idx ] = matched[ i ] );
						}
					} ) :
					function( elem ) {
						return fn( elem, 0, args );
					};
			}

			return fn;
		}
	},

	pseudos: {

		// Potentially complex pseudos
		not: markFunction( function( selector ) {

			// Trim the selector passed to compile
			// to avoid treating leading and trailing
			// spaces as combinators
			var input = [],
				results = [],
				matcher = compile( selector.replace( rtrimCSS, "$1" ) );

			return matcher[ expando ] ?
				markFunction( function( seed, matches, _context, xml ) {
					var elem,
						unmatched = matcher( seed, null, xml, [] ),
						i = seed.length;

					// Match elements unmatched by `matcher`
					while ( i-- ) {
						if ( ( elem = unmatched[ i ] ) ) {
							seed[ i ] = !( matches[ i ] = elem );
						}
					}
				} ) :
				function( elem, _context, xml ) {
					input[ 0 ] = elem;
					matcher( input, null, xml, results );

					// Don't keep the element
					// (see https://github.com/jquery/sizzle/issues/299)
					input[ 0 ] = null;
					return !results.pop();
				};
		} ),

		has: markFunction( function( selector ) {
			return function( elem ) {
				return find( selector, elem ).length > 0;
			};
		} ),

		contains: markFunction( function( text ) {
			text = text.replace( runescape, funescape );
			return function( elem ) {
				return ( elem.textContent || jQuery.text( elem ) ).indexOf( text ) > -1;
			};
		} ),

		// "Whether an element is represented by a :lang() selector
		// is based solely on the element's language value
		// being equal to the identifier C,
		// or beginning with the identifier C immediately followed by "-".
		// The matching of C against the element's language value is performed case-insensitively.
		// The identifier C does not have to be a valid language name."
		// https://www.w3.org/TR/selectors/#lang-pseudo
		lang: markFunction( function( lang ) {

			// lang value must be a valid identifier
			if ( !ridentifier.test( lang || "" ) ) {
				find.error( "unsupported lang: " + lang );
			}
			lang = lang.replace( runescape, funescape ).toLowerCase();
			return function( elem ) {
				var elemLang;
				do {
					if ( ( elemLang = documentIsHTML ?
						elem.lang :
						elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) {

						elemLang = elemLang.toLowerCase();
						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
					}
				} while ( ( elem = elem.parentNode ) && elem.nodeType === 1 );
				return false;
			};
		} ),

		// Miscellaneous
		target: function( elem ) {
			var hash = window.location && window.location.hash;
			return hash && hash.slice( 1 ) === elem.id;
		},

		root: function( elem ) {
			return elem === documentElement;
		},

		focus: function( elem ) {
			return elem === safeActiveElement() &&
				document.hasFocus() &&
				!!( elem.type || elem.href || ~elem.tabIndex );
		},

		// Boolean properties
		enabled: createDisabledPseudo( false ),
		disabled: createDisabledPseudo( true ),

		checked: function( elem ) {

			// In CSS3, :checked should return both checked and selected elements
			// https://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			return ( nodeName( elem, "input" ) && !!elem.checked ) ||
				( nodeName( elem, "option" ) && !!elem.selected );
		},

		selected: function( elem ) {

			// Support: IE <=11+
			// Accessing the selectedIndex property
			// forces the browser to treat the default option as
			// selected when in an optgroup.
			if ( elem.parentNode ) {
				// eslint-disable-next-line no-unused-expressions
				elem.parentNode.selectedIndex;
			}

			return elem.selected === true;
		},

		// Contents
		empty: function( elem ) {

			// https://www.w3.org/TR/selectors/#empty-pseudo
			// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
			//   but not by others (comment: 8; processing instruction: 7; etc.)
			// nodeType < 6 works because attributes (2) do not appear as children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				if ( elem.nodeType < 6 ) {
					return false;
				}
			}
			return true;
		},

		parent: function( elem ) {
			return !Expr.pseudos.empty( elem );
		},

		// Element/input types
		header: function( elem ) {
			return rheader.test( elem.nodeName );
		},

		input: function( elem ) {
			return rinputs.test( elem.nodeName );
		},

		button: function( elem ) {
			return nodeName( elem, "input" ) && elem.type === "button" ||
				nodeName( elem, "button" );
		},

		text: function( elem ) {
			var attr;
			return nodeName( elem, "input" ) && elem.type === "text" &&

				// Support: IE <10 only
				// New HTML5 attribute values (e.g., "search") appear
				// with elem.type === "text"
				( ( attr = elem.getAttribute( "type" ) ) == null ||
					attr.toLowerCase() === "text" );
		},

		// Position-in-collection
		first: createPositionalPseudo( function() {
			return [ 0 ];
		} ),

		last: createPositionalPseudo( function( _matchIndexes, length ) {
			return [ length - 1 ];
		} ),

		eq: createPositionalPseudo( function( _matchIndexes, length, argument ) {
			return [ argument < 0 ? argument + length : argument ];
		} ),

		even: createPositionalPseudo( function( matchIndexes, length ) {
			var i = 0;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} ),

		odd: createPositionalPseudo( function( matchIndexes, length ) {
			var i = 1;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} ),

		lt: createPositionalPseudo( function( matchIndexes, length, argument ) {
			var i;

			if ( argument < 0 ) {
				i = argument + length;
			} else if ( argument > length ) {
				i = length;
			} else {
				i = argument;
			}

			for ( ; --i >= 0; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} ),

		gt: createPositionalPseudo( function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; ++i < length; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		} )
	}
};

Expr.pseudos.nth = Expr.pseudos.eq;

// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
	Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
	Expr.pseudos[ i ] = createButtonPseudo( i );
}

// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();

function tokenize( selector, parseOnly ) {
	var matched, match, tokens, type,
		soFar, groups, preFilters,
		cached = tokenCache[ selector + " " ];

	if ( cached ) {
		return parseOnly ? 0 : cached.slice( 0 );
	}

	soFar = selector;
	groups = [];
	preFilters = Expr.preFilter;

	while ( soFar ) {

		// Comma and first run
		if ( !matched || ( match = rcomma.exec( soFar ) ) ) {
			if ( match ) {

				// Don't consume trailing commas as valid
				soFar = soFar.slice( match[ 0 ].length ) || soFar;
			}
			groups.push( ( tokens = [] ) );
		}

		matched = false;

		// Combinators
		if ( ( match = rleadingCombinator.exec( soFar ) ) ) {
			matched = match.shift();
			tokens.push( {
				value: matched,

				// Cast descendant combinators to space
				type: match[ 0 ].replace( rtrimCSS, " " )
			} );
			soFar = soFar.slice( matched.length );
		}

		// Filters
		for ( type in Expr.filter ) {
			if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] ||
				( match = preFilters[ type ]( match ) ) ) ) {
				matched = match.shift();
				tokens.push( {
					value: matched,
					type: type,
					matches: match
				} );
				soFar = soFar.slice( matched.length );
			}
		}

		if ( !matched ) {
			break;
		}
	}

	// Return the length of the invalid excess
	// if we're just parsing
	// Otherwise, throw an error or return tokens
	if ( parseOnly ) {
		return soFar.length;
	}

	return soFar ?
		find.error( selector ) :

		// Cache the tokens
		tokenCache( selector, groups ).slice( 0 );
}

function toSelector( tokens ) {
	var i = 0,
		len = tokens.length,
		selector = "";
	for ( ; i < len; i++ ) {
		selector += tokens[ i ].value;
	}
	return selector;
}

function addCombinator( matcher, combinator, base ) {
	var dir = combinator.dir,
		skip = combinator.next,
		key = skip || dir,
		checkNonElements = base && key === "parentNode",
		doneName = done++;

	return combinator.first ?

		// Check against closest ancestor/preceding element
		function( elem, context, xml ) {
			while ( ( elem = elem[ dir ] ) ) {
				if ( elem.nodeType === 1 || checkNonElements ) {
					return matcher( elem, context, xml );
				}
			}
			return false;
		} :

		// Check against all ancestor/preceding elements
		function( elem, context, xml ) {
			var oldCache, outerCache,
				newCache = [ dirruns, doneName ];

			// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
			if ( xml ) {
				while ( ( elem = elem[ dir ] ) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						if ( matcher( elem, context, xml ) ) {
							return true;
						}
					}
				}
			} else {
				while ( ( elem = elem[ dir ] ) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						outerCache = elem[ expando ] || ( elem[ expando ] = {} );

						if ( skip && nodeName( elem, skip ) ) {
							elem = elem[ dir ] || elem;
						} else if ( ( oldCache = outerCache[ key ] ) &&
							oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {

							// Assign to newCache so results back-propagate to previous elements
							return ( newCache[ 2 ] = oldCache[ 2 ] );
						} else {

							// Reuse newcache so results back-propagate to previous elements
							outerCache[ key ] = newCache;

							// A match means we're done; a fail means we have to keep checking
							if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) {
								return true;
							}
						}
					}
				}
			}
			return false;
		};
}

function elementMatcher( matchers ) {
	return matchers.length > 1 ?
		function( elem, context, xml ) {
			var i = matchers.length;
			while ( i-- ) {
				if ( !matchers[ i ]( elem, context, xml ) ) {
					return false;
				}
			}
			return true;
		} :
		matchers[ 0 ];
}

function multipleContexts( selector, contexts, results ) {
	var i = 0,
		len = contexts.length;
	for ( ; i < len; i++ ) {
		find( selector, contexts[ i ], results );
	}
	return results;
}

function condense( unmatched, map, filter, context, xml ) {
	var elem,
		newUnmatched = [],
		i = 0,
		len = unmatched.length,
		mapped = map != null;

	for ( ; i < len; i++ ) {
		if ( ( elem = unmatched[ i ] ) ) {
			if ( !filter || filter( elem, context, xml ) ) {
				newUnmatched.push( elem );
				if ( mapped ) {
					map.push( i );
				}
			}
		}
	}

	return newUnmatched;
}

function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
	if ( postFilter && !postFilter[ expando ] ) {
		postFilter = setMatcher( postFilter );
	}
	if ( postFinder && !postFinder[ expando ] ) {
		postFinder = setMatcher( postFinder, postSelector );
	}
	return markFunction( function( seed, results, context, xml ) {
		var temp, i, elem, matcherOut,
			preMap = [],
			postMap = [],
			preexisting = results.length,

			// Get initial elements from seed or context
			elems = seed ||
				multipleContexts( selector || "*",
					context.nodeType ? [ context ] : context, [] ),

			// Prefilter to get matcher input, preserving a map for seed-results synchronization
			matcherIn = preFilter && ( seed || !selector ) ?
				condense( elems, preMap, preFilter, context, xml ) :
				elems;

		if ( matcher ) {

			// If we have a postFinder, or filtered seed, or non-seed postFilter
			// or preexisting results,
			matcherOut = postFinder || ( seed ? preFilter : preexisting || postFilter ) ?

				// ...intermediate processing is necessary
				[] :

				// ...otherwise use results directly
				results;

			// Find primary matches
			matcher( matcherIn, matcherOut, context, xml );
		} else {
			matcherOut = matcherIn;
		}

		// Apply postFilter
		if ( postFilter ) {
			temp = condense( matcherOut, postMap );
			postFilter( temp, [], context, xml );

			// Un-match failing elements by moving them back to matcherIn
			i = temp.length;
			while ( i-- ) {
				if ( ( elem = temp[ i ] ) ) {
					matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem );
				}
			}
		}

		if ( seed ) {
			if ( postFinder || preFilter ) {
				if ( postFinder ) {

					// Get the final matcherOut by condensing this intermediate into postFinder contexts
					temp = [];
					i = matcherOut.length;
					while ( i-- ) {
						if ( ( elem = matcherOut[ i ] ) ) {

							// Restore matcherIn since elem is not yet a final match
							temp.push( ( matcherIn[ i ] = elem ) );
						}
					}
					postFinder( null, ( matcherOut = [] ), temp, xml );
				}

				// Move matched elements from seed to results to keep them synchronized
				i = matcherOut.length;
				while ( i-- ) {
					if ( ( elem = matcherOut[ i ] ) &&
						( temp = postFinder ? indexOf.call( seed, elem ) : preMap[ i ] ) > -1 ) {

						seed[ temp ] = !( results[ temp ] = elem );
					}
				}
			}

		// Add elements to results, through postFinder if defined
		} else {
			matcherOut = condense(
				matcherOut === results ?
					matcherOut.splice( preexisting, matcherOut.length ) :
					matcherOut
			);
			if ( postFinder ) {
				postFinder( null, results, matcherOut, xml );
			} else {
				push.apply( results, matcherOut );
			}
		}
	} );
}

function matcherFromTokens( tokens ) {
	var checkContext, matcher, j,
		len = tokens.length,
		leadingRelative = Expr.relative[ tokens[ 0 ].type ],
		implicitRelative = leadingRelative || Expr.relative[ " " ],
		i = leadingRelative ? 1 : 0,

		// The foundational matcher ensures that elements are reachable from top-level context(s)
		matchContext = addCombinator( function( elem ) {
			return elem === checkContext;
		}, implicitRelative, true ),
		matchAnyContext = addCombinator( function( elem ) {
			return indexOf.call( checkContext, elem ) > -1;
		}, implicitRelative, true ),
		matchers = [ function( elem, context, xml ) {

			// Support: IE 11+, Edge 17 - 18+
			// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
			// two documents; shallow comparisons work.
			// eslint-disable-next-line eqeqeq
			var ret = ( !leadingRelative && ( xml || context != outermostContext ) ) || (
				( checkContext = context ).nodeType ?
					matchContext( elem, context, xml ) :
					matchAnyContext( elem, context, xml ) );

			// Avoid hanging onto element
			// (see https://github.com/jquery/sizzle/issues/299)
			checkContext = null;
			return ret;
		} ];

	for ( ; i < len; i++ ) {
		if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) {
			matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
		} else {
			matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches );

			// Return special upon seeing a positional matcher
			if ( matcher[ expando ] ) {

				// Find the next relative operator (if any) for proper handling
				j = ++i;
				for ( ; j < len; j++ ) {
					if ( Expr.relative[ tokens[ j ].type ] ) {
						break;
					}
				}
				return setMatcher(
					i > 1 && elementMatcher( matchers ),
					i > 1 && toSelector(

						// If the preceding token was a descendant combinator, insert an implicit any-element `*`
						tokens.slice( 0, i - 1 )
							.concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } )
					).replace( rtrimCSS, "$1" ),
					matcher,
					i < j && matcherFromTokens( tokens.slice( i, j ) ),
					j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ),
					j < len && toSelector( tokens )
				);
			}
			matchers.push( matcher );
		}
	}

	return elementMatcher( matchers );
}

function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
	var bySet = setMatchers.length > 0,
		byElement = elementMatchers.length > 0,
		superMatcher = function( seed, context, xml, results, outermost ) {
			var elem, j, matcher,
				matchedCount = 0,
				i = "0",
				unmatched = seed && [],
				setMatched = [],
				contextBackup = outermostContext,

				// We must always have either seed elements or outermost context
				elems = seed || byElement && Expr.find.TAG( "*", outermost ),

				// Use integer dirruns iff this is the outermost matcher
				dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ),
				len = elems.length;

			if ( outermost ) {

				// Support: IE 11+, Edge 17 - 18+
				// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
				// two documents; shallow comparisons work.
				// eslint-disable-next-line eqeqeq
				outermostContext = context == document || context || outermost;
			}

			// Add elements passing elementMatchers directly to results
			// Support: iOS <=7 - 9 only
			// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching
			// elements by id. (see trac-14142)
			for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) {
				if ( byElement && elem ) {
					j = 0;

					// Support: IE 11+, Edge 17 - 18+
					// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
					// two documents; shallow comparisons work.
					// eslint-disable-next-line eqeqeq
					if ( !context && elem.ownerDocument != document ) {
						setDocument( elem );
						xml = !documentIsHTML;
					}
					while ( ( matcher = elementMatchers[ j++ ] ) ) {
						if ( matcher( elem, context || document, xml ) ) {
							push.call( results, elem );
							break;
						}
					}
					if ( outermost ) {
						dirruns = dirrunsUnique;
					}
				}

				// Track unmatched elements for set filters
				if ( bySet ) {

					// They will have gone through all possible matchers
					if ( ( elem = !matcher && elem ) ) {
						matchedCount--;
					}

					// Lengthen the array for every element, matched or not
					if ( seed ) {
						unmatched.push( elem );
					}
				}
			}

			// `i` is now the count of elements visited above, and adding it to `matchedCount`
			// makes the latter nonnegative.
			matchedCount += i;

			// Apply set filters to unmatched elements
			// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
			// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
			// no element matchers and no seed.
			// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
			// case, which will result in a "00" `matchedCount` that differs from `i` but is also
			// numerically zero.
			if ( bySet && i !== matchedCount ) {
				j = 0;
				while ( ( matcher = setMatchers[ j++ ] ) ) {
					matcher( unmatched, setMatched, context, xml );
				}

				if ( seed ) {

					// Reintegrate element matches to eliminate the need for sorting
					if ( matchedCount > 0 ) {
						while ( i-- ) {
							if ( !( unmatched[ i ] || setMatched[ i ] ) ) {
								setMatched[ i ] = pop.call( results );
							}
						}
					}

					// Discard index placeholder values to get only actual matches
					setMatched = condense( setMatched );
				}

				// Add matches to results
				push.apply( results, setMatched );

				// Seedless set matches succeeding multiple successful matchers stipulate sorting
				if ( outermost && !seed && setMatched.length > 0 &&
					( matchedCount + setMatchers.length ) > 1 ) {

					jQuery.uniqueSort( results );
				}
			}

			// Override manipulation of globals by nested matchers
			if ( outermost ) {
				dirruns = dirrunsUnique;
				outermostContext = contextBackup;
			}

			return unmatched;
		};

	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

function compile( selector, match /* Internal Use Only */ ) {
	var i,
		setMatchers = [],
		elementMatchers = [],
		cached = compilerCache[ selector + " " ];

	if ( !cached ) {

		// Generate a function of recursive functions that can be used to check each element
		if ( !match ) {
			match = tokenize( selector );
		}
		i = match.length;
		while ( i-- ) {
			cached = matcherFromTokens( match[ i ] );
			if ( cached[ expando ] ) {
				setMatchers.push( cached );
			} else {
				elementMatchers.push( cached );
			}
		}

		// Cache the compiled function
		cached = compilerCache( selector,
			matcherFromGroupMatchers( elementMatchers, setMatchers ) );

		// Save selector and tokenization
		cached.selector = selector;
	}
	return cached;
}

/**
 * A low-level selection function that works with jQuery's compiled
 *  selector functions
 * @param {String|Function} selector A selector or a pre-compiled
 *  selector function built with jQuery selector compile
 * @param {Element} context
 * @param {Array} [results]
 * @param {Array} [seed] A set of elements to match against
 */
function select( selector, context, results, seed ) {
	var i, tokens, token, type, find,
		compiled = typeof selector === "function" && selector,
		match = !seed && tokenize( ( selector = compiled.selector || selector ) );

	results = results || [];

	// Try to minimize operations if there is only one selector in the list and no seed
	// (the latter of which guarantees us context)
	if ( match.length === 1 ) {

		// Reduce context if the leading compound selector is an ID
		tokens = match[ 0 ] = match[ 0 ].slice( 0 );
		if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" &&
				context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) {

			context = ( Expr.find.ID(
				token.matches[ 0 ].replace( runescape, funescape ),
				context
			) || [] )[ 0 ];
			if ( !context ) {
				return results;

			// Precompiled matchers will still verify ancestry, so step up a level
			} else if ( compiled ) {
				context = context.parentNode;
			}

			selector = selector.slice( tokens.shift().value.length );
		}

		// Fetch a seed set for right-to-left matching
		i = matchExpr.needsContext.test( selector ) ? 0 : tokens.length;
		while ( i-- ) {
			token = tokens[ i ];

			// Abort if we hit a combinator
			if ( Expr.relative[ ( type = token.type ) ] ) {
				break;
			}
			if ( ( find = Expr.find[ type ] ) ) {

				// Search, expanding context for leading sibling combinators
				if ( ( seed = find(
					token.matches[ 0 ].replace( runescape, funescape ),
					rsibling.test( tokens[ 0 ].type ) &&
						testContext( context.parentNode ) || context
				) ) ) {

					// If seed is empty or no tokens remain, we can return early
					tokens.splice( i, 1 );
					selector = seed.length && toSelector( tokens );
					if ( !selector ) {
						push.apply( results, seed );
						return results;
					}

					break;
				}
			}
		}
	}

	// Compile and execute a filtering function if one is not provided
	// Provide `match` to avoid retokenization if we modified the selector above
	( compiled || compile( selector, match ) )(
		seed,
		context,
		!documentIsHTML,
		results,
		!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
	);
	return results;
}

// One-time assignments

// Support: Android <=4.0 - 4.1+
// Sort stability
support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando;

// Initialize against the default document
setDocument();

// Support: Android <=4.0 - 4.1+
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert( function( el ) {

	// Should return 1, but returns 4 (following)
	return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1;
} );

jQuery.find = find;

// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.unique = jQuery.uniqueSort;

// These have always been private, but they used to be documented as part of
// Sizzle so let's maintain them for now for backwards compatibility purposes.
find.compile = compile;
find.select = select;
find.setDocument = setDocument;
find.tokenize = tokenize;

find.escape = jQuery.escapeSelector;
find.getText = jQuery.text;
find.isXML = jQuery.isXMLDoc;
find.selectors = jQuery.expr;
find.support = jQuery.support;
find.uniqueSort = jQuery.uniqueSort;

	/* eslint-enable */

} )();


var dir = function( elem, dir, until ) {
	var matched = [],
		truncate = until !== undefined;

	while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
		if ( elem.nodeType === 1 ) {
			if ( truncate && jQuery( elem ).is( until ) ) {
				break;
			}
			matched.push( elem );
		}
	}
	return matched;
};


var siblings = function( n, elem ) {
	var matched = [];

	for ( ; n; n = n.nextSibling ) {
		if ( n.nodeType === 1 && n !== elem ) {
			matched.push( n );
		}
	}

	return matched;
};


var rneedsContext = jQuery.expr.match.needsContext;

var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );



// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
	if ( isFunction( qualifier ) ) {
		return jQuery.grep( elements, function( elem, i ) {
			return !!qualifier.call( elem, i, elem ) !== not;
		} );
	}

	// Single element
	if ( qualifier.nodeType ) {
		return jQuery.grep( elements, function( elem ) {
			return ( elem === qualifier ) !== not;
		} );
	}

	// Arraylike of elements (jQuery, arguments, Array)
	if ( typeof qualifier !== "string" ) {
		return jQuery.grep( elements, function( elem ) {
			return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
		} );
	}

	// Filtered directly for both simple and complex selectors
	return jQuery.filter( qualifier, elements, not );
}

jQuery.filter = function( expr, elems, not ) {
	var elem = elems[ 0 ];

	if ( not ) {
		expr = ":not(" + expr + ")";
	}

	if ( elems.length === 1 && elem.nodeType === 1 ) {
		return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
	}

	return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
		return elem.nodeType === 1;
	} ) );
};

jQuery.fn.extend( {
	find: function( selector ) {
		var i, ret,
			len = this.length,
			self = this;

		if ( typeof selector !== "string" ) {
			return this.pushStack( jQuery( selector ).filter( function() {
				for ( i = 0; i < len; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			} ) );
		}

		ret = this.pushStack( [] );

		for ( i = 0; i < len; i++ ) {
			jQuery.find( selector, self[ i ], ret );
		}

		return len > 1 ? jQuery.uniqueSort( ret ) : ret;
	},
	filter: function( selector ) {
		return this.pushStack( winnow( this, selector || [], false ) );
	},
	not: function( selector ) {
		return this.pushStack( winnow( this, selector || [], true ) );
	},
	is: function( selector ) {
		return !!winnow(
			this,

			// If this is a positional/relative selector, check membership in the returned set
			// so $("p:first").is("p:last") won't return true for a doc with two "p".
			typeof selector === "string" && rneedsContext.test( selector ) ?
				jQuery( selector ) :
				selector || [],
			false
		).length;
	}
} );


// Initialize a jQuery object


// A central reference to the root jQuery(document)
var rootjQuery,

	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (trac-9521)
	// Strict HTML recognition (trac-11290: must start with <)
	// Shortcut simple #id case for speed
	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,

	init = jQuery.fn.init = function( selector, context, root ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// Method init() accepts an alternate rootjQuery
		// so migrate can support jQuery.sub (gh-2101)
		root = root || rootjQuery;

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			if ( selector[ 0 ] === "<" &&
				selector[ selector.length - 1 ] === ">" &&
				selector.length >= 3 ) {

				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = rquickExpr.exec( selector );
			}

			// Match html or make sure no context is specified for #id
			if ( match && ( match[ 1 ] || !context ) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[ 1 ] ) {
					context = context instanceof jQuery ? context[ 0 ] : context;

					// Option to run scripts is true for back-compat
					// Intentionally let the error be thrown if parseHTML is not present
					jQuery.merge( this, jQuery.parseHTML(
						match[ 1 ],
						context && context.nodeType ? context.ownerDocument || context : document,
						true
					) );

					// HANDLE: $(html, props)
					if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
						for ( match in context ) {

							// Properties of context are called as methods if possible
							if ( isFunction( this[ match ] ) ) {
								this[ match ]( context[ match ] );

							// ...and otherwise set as attributes
							} else {
								this.attr( match, context[ match ] );
							}
						}
					}

					return this;

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[ 2 ] );

					if ( elem ) {

						// Inject the element directly into the jQuery object
						this[ 0 ] = elem;
						this.length = 1;
					}
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || root ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(DOMElement)
		} else if ( selector.nodeType ) {
			this[ 0 ] = selector;
			this.length = 1;
			return this;

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( isFunction( selector ) ) {
			return root.ready !== undefined ?
				root.ready( selector ) :

				// Execute immediately if ready is not present
				selector( jQuery );
		}

		return jQuery.makeArray( selector, this );
	};

// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

// Initialize central reference
rootjQuery = jQuery( document );


var rparentsprev = /^(?:parents|prev(?:Until|All))/,

	// Methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend( {
	has: function( target ) {
		var targets = jQuery( target, this ),
			l = targets.length;

		return this.filter( function() {
			var i = 0;
			for ( ; i < l; i++ ) {
				if ( jQuery.contains( this, targets[ i ] ) ) {
					return true;
				}
			}
		} );
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			matched = [],
			targets = typeof selectors !== "string" && jQuery( selectors );

		// Positional selectors never match, since there's no _selection_ context
		if ( !rneedsContext.test( selectors ) ) {
			for ( ; i < l; i++ ) {
				for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {

					// Always skip document fragments
					if ( cur.nodeType < 11 && ( targets ?
						targets.index( cur ) > -1 :

						// Don't pass non-elements to jQuery#find
						cur.nodeType === 1 &&
							jQuery.find.matchesSelector( cur, selectors ) ) ) {

						matched.push( cur );
						break;
					}
				}
			}
		}

		return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
	},

	// Determine the position of an element within the set
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
		}

		// Index in selector
		if ( typeof elem === "string" ) {
			return indexOf.call( jQuery( elem ), this[ 0 ] );
		}

		// Locate the position of the desired element
		return indexOf.call( this,

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[ 0 ] : elem
		);
	},

	add: function( selector, context ) {
		return this.pushStack(
			jQuery.uniqueSort(
				jQuery.merge( this.get(), jQuery( selector, context ) )
			)
		);
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	}
} );

function sibling( cur, dir ) {
	while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
	return cur;
}

jQuery.each( {
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, _i, until ) {
		return dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, _i, until ) {
		return dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, _i, until ) {
		return dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return siblings( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return siblings( elem.firstChild );
	},
	contents: function( elem ) {
		if ( elem.contentDocument != null &&

			// Support: IE 11+
			// <object> elements with no `data` attribute has an object
			// `contentDocument` with a `null` prototype.
			getProto( elem.contentDocument ) ) {

			return elem.contentDocument;
		}

		// Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
		// Treat the template element as a regular one in browsers that
		// don't support it.
		if ( nodeName( elem, "template" ) ) {
			elem = elem.content || elem;
		}

		return jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var matched = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			matched = jQuery.filter( selector, matched );
		}

		if ( this.length > 1 ) {

			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				jQuery.uniqueSort( matched );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				matched.reverse();
			}
		}

		return this.pushStack( matched );
	};
} );
var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );



// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
	var object = {};
	jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) {
		object[ flag ] = true;
	} );
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	options: an optional list of space-separated options that will change how
 *			the callback list behaves or a more traditional option object
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible options:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( options ) {

	// Convert options from String-formatted to Object-formatted if needed
	// (we check in cache first)
	options = typeof options === "string" ?
		createOptions( options ) :
		jQuery.extend( {}, options );

	var // Flag to know if list is currently firing
		firing,

		// Last fire value for non-forgettable lists
		memory,

		// Flag to know if list was already fired
		fired,

		// Flag to prevent firing
		locked,

		// Actual callback list
		list = [],

		// Queue of execution data for repeatable lists
		queue = [],

		// Index of currently firing callback (modified by add/remove as needed)
		firingIndex = -1,

		// Fire callbacks
		fire = function() {

			// Enforce single-firing
			locked = locked || options.once;

			// Execute callbacks for all pending executions,
			// respecting firingIndex overrides and runtime changes
			fired = firing = true;
			for ( ; queue.length; firingIndex = -1 ) {
				memory = queue.shift();
				while ( ++firingIndex < list.length ) {

					// Run callback and check for early termination
					if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
						options.stopOnFalse ) {

						// Jump to end and forget the data so .add doesn't re-fire
						firingIndex = list.length;
						memory = false;
					}
				}
			}

			// Forget the data if we're done with it
			if ( !options.memory ) {
				memory = false;
			}

			firing = false;

			// Clean up if we're done firing for good
			if ( locked ) {

				// Keep an empty list if we have data for future add calls
				if ( memory ) {
					list = [];

				// Otherwise, this object is spent
				} else {
					list = "";
				}
			}
		},

		// Actual Callbacks object
		self = {

			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {

					// If we have memory from a past run, we should fire after adding
					if ( memory && !firing ) {
						firingIndex = list.length - 1;
						queue.push( memory );
					}

					( function add( args ) {
						jQuery.each( args, function( _, arg ) {
							if ( isFunction( arg ) ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg && arg.length && toType( arg ) !== "string" ) {

								// Inspect recursively
								add( arg );
							}
						} );
					} )( arguments );

					if ( memory && !firing ) {
						fire();
					}
				}
				return this;
			},

			// Remove a callback from the list
			remove: function() {
				jQuery.each( arguments, function( _, arg ) {
					var index;
					while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
						list.splice( index, 1 );

						// Handle firing indexes
						if ( index <= firingIndex ) {
							firingIndex--;
						}
					}
				} );
				return this;
			},

			// Check if a given callback is in the list.
			// If no argument is given, return whether or not list has callbacks attached.
			has: function( fn ) {
				return fn ?
					jQuery.inArray( fn, list ) > -1 :
					list.length > 0;
			},

			// Remove all callbacks from the list
			empty: function() {
				if ( list ) {
					list = [];
				}
				return this;
			},

			// Disable .fire and .add
			// Abort any current/pending executions
			// Clear all callbacks and values
			disable: function() {
				locked = queue = [];
				list = memory = "";
				return this;
			},
			disabled: function() {
				return !list;
			},

			// Disable .fire
			// Also disable .add unless we have memory (since it would have no effect)
			// Abort any pending executions
			lock: function() {
				locked = queue = [];
				if ( !memory && !firing ) {
					list = memory = "";
				}
				return this;
			},
			locked: function() {
				return !!locked;
			},

			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				if ( !locked ) {
					args = args || [];
					args = [ context, args.slice ? args.slice() : args ];
					queue.push( args );
					if ( !firing ) {
						fire();
					}
				}
				return this;
			},

			// Call all the callbacks with the given arguments
			fire: function() {
				self.fireWith( this, arguments );
				return this;
			},

			// To know if the callbacks have already been called at least once
			fired: function() {
				return !!fired;
			}
		};

	return self;
};


function Identity( v ) {
	return v;
}
function Thrower( ex ) {
	throw ex;
}

function adoptValue( value, resolve, reject, noValue ) {
	var method;

	try {

		// Check for promise aspect first to privilege synchronous behavior
		if ( value && isFunction( ( method = value.promise ) ) ) {
			method.call( value ).done( resolve ).fail( reject );

		// Other thenables
		} else if ( value && isFunction( ( method = value.then ) ) ) {
			method.call( value, resolve, reject );

		// Other non-thenables
		} else {

			// Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
			// * false: [ value ].slice( 0 ) => resolve( value )
			// * true: [ value ].slice( 1 ) => resolve()
			resolve.apply( undefined, [ value ].slice( noValue ) );
		}

	// For Promises/A+, convert exceptions into rejections
	// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
	// Deferred#then to conditionally suppress rejection.
	} catch ( value ) {

		// Support: Android 4.0 only
		// Strict mode functions invoked without .call/.apply get global-object context
		reject.apply( undefined, [ value ] );
	}
}

jQuery.extend( {

	Deferred: function( func ) {
		var tuples = [

				// action, add listener, callbacks,
				// ... .then handlers, argument index, [final state]
				[ "notify", "progress", jQuery.Callbacks( "memory" ),
					jQuery.Callbacks( "memory" ), 2 ],
				[ "resolve", "done", jQuery.Callbacks( "once memory" ),
					jQuery.Callbacks( "once memory" ), 0, "resolved" ],
				[ "reject", "fail", jQuery.Callbacks( "once memory" ),
					jQuery.Callbacks( "once memory" ), 1, "rejected" ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				"catch": function( fn ) {
					return promise.then( null, fn );
				},

				// Keep pipe for back-compat
				pipe: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;

					return jQuery.Deferred( function( newDefer ) {
						jQuery.each( tuples, function( _i, tuple ) {

							// Map tuples (progress, done, fail) to arguments (done, fail, progress)
							var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];

							// deferred.progress(function() { bind to newDefer or newDefer.notify })
							// deferred.done(function() { bind to newDefer or newDefer.resolve })
							// deferred.fail(function() { bind to newDefer or newDefer.reject })
							deferred[ tuple[ 1 ] ]( function() {
								var returned = fn && fn.apply( this, arguments );
								if ( returned && isFunction( returned.promise ) ) {
									returned.promise()
										.progress( newDefer.notify )
										.done( newDefer.resolve )
										.fail( newDefer.reject );
								} else {
									newDefer[ tuple[ 0 ] + "With" ](
										this,
										fn ? [ returned ] : arguments
									);
								}
							} );
						} );
						fns = null;
					} ).promise();
				},
				then: function( onFulfilled, onRejected, onProgress ) {
					var maxDepth = 0;
					function resolve( depth, deferred, handler, special ) {
						return function() {
							var that = this,
								args = arguments,
								mightThrow = function() {
									var returned, then;

									// Support: Promises/A+ section 2.3.3.3.3
									// https://promisesaplus.com/#point-59
									// Ignore double-resolution attempts
									if ( depth < maxDepth ) {
										return;
									}

									returned = handler.apply( that, args );

									// Support: Promises/A+ section 2.3.1
									// https://promisesaplus.com/#point-48
									if ( returned === deferred.promise() ) {
										throw new TypeError( "Thenable self-resolution" );
									}

									// Support: Promises/A+ sections 2.3.3.1, 3.5
									// https://promisesaplus.com/#point-54
									// https://promisesaplus.com/#point-75
									// Retrieve `then` only once
									then = returned &&

										// Support: Promises/A+ section 2.3.4
										// https://promisesaplus.com/#point-64
										// Only check objects and functions for thenability
										( typeof returned === "object" ||
											typeof returned === "function" ) &&
										returned.then;

									// Handle a returned thenable
									if ( isFunction( then ) ) {

										// Special processors (notify) just wait for resolution
										if ( special ) {
											then.call(
												returned,
												resolve( maxDepth, deferred, Identity, special ),
												resolve( maxDepth, deferred, Thrower, special )
											);

										// Normal processors (resolve) also hook into progress
										} else {

											// ...and disregard older resolution values
											maxDepth++;

											then.call(
												returned,
												resolve( maxDepth, deferred, Identity, special ),
												resolve( maxDepth, deferred, Thrower, special ),
												resolve( maxDepth, deferred, Identity,
													deferred.notifyWith )
											);
										}

									// Handle all other returned values
									} else {

										// Only substitute handlers pass on context
										// and multiple values (non-spec behavior)
										if ( handler !== Identity ) {
											that = undefined;
											args = [ returned ];
										}

										// Process the value(s)
										// Default process is resolve
										( special || deferred.resolveWith )( that, args );
									}
								},

								// Only normal processors (resolve) catch and reject exceptions
								process = special ?
									mightThrow :
									function() {
										try {
											mightThrow();
										} catch ( e ) {

											if ( jQuery.Deferred.exceptionHook ) {
												jQuery.Deferred.exceptionHook( e,
													process.error );
											}

											// Support: Promises/A+ section 2.3.3.3.4.1
											// https://promisesaplus.com/#point-61
											// Ignore post-resolution exceptions
											if ( depth + 1 >= maxDepth ) {

												// Only substitute handlers pass on context
												// and multiple values (non-spec behavior)
												if ( handler !== Thrower ) {
													that = undefined;
													args = [ e ];
												}

												deferred.rejectWith( that, args );
											}
										}
									};

							// Support: Promises/A+ section 2.3.3.3.1
							// https://promisesaplus.com/#point-57
							// Re-resolve promises immediately to dodge false rejection from
							// subsequent errors
							if ( depth ) {
								process();
							} else {

								// Call an optional hook to record the error, in case of exception
								// since it's otherwise lost when execution goes async
								if ( jQuery.Deferred.getErrorHook ) {
									process.error = jQuery.Deferred.getErrorHook();

								// The deprecated alias of the above. While the name suggests
								// returning the stack, not an error instance, jQuery just passes
								// it directly to `console.warn` so both will work; an instance
								// just better cooperates with source maps.
								} else if ( jQuery.Deferred.getStackHook ) {
									process.error = jQuery.Deferred.getStackHook();
								}
								window.setTimeout( process );
							}
						};
					}

					return jQuery.Deferred( function( newDefer ) {

						// progress_handlers.add( ... )
						tuples[ 0 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								isFunction( onProgress ) ?
									onProgress :
									Identity,
								newDefer.notifyWith
							)
						);

						// fulfilled_handlers.add( ... )
						tuples[ 1 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								isFunction( onFulfilled ) ?
									onFulfilled :
									Identity
							)
						);

						// rejected_handlers.add( ... )
						tuples[ 2 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								isFunction( onRejected ) ?
									onRejected :
									Thrower
							)
						);
					} ).promise();
				},

				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return obj != null ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 5 ];

			// promise.progress = list.add
			// promise.done = list.add
			// promise.fail = list.add
			promise[ tuple[ 1 ] ] = list.add;

			// Handle state
			if ( stateString ) {
				list.add(
					function() {

						// state = "resolved" (i.e., fulfilled)
						// state = "rejected"
						state = stateString;
					},

					// rejected_callbacks.disable
					// fulfilled_callbacks.disable
					tuples[ 3 - i ][ 2 ].disable,

					// rejected_handlers.disable
					// fulfilled_handlers.disable
					tuples[ 3 - i ][ 3 ].disable,

					// progress_callbacks.lock
					tuples[ 0 ][ 2 ].lock,

					// progress_handlers.lock
					tuples[ 0 ][ 3 ].lock
				);
			}

			// progress_handlers.fire
			// fulfilled_handlers.fire
			// rejected_handlers.fire
			list.add( tuple[ 3 ].fire );

			// deferred.notify = function() { deferred.notifyWith(...) }
			// deferred.resolve = function() { deferred.resolveWith(...) }
			// deferred.reject = function() { deferred.rejectWith(...) }
			deferred[ tuple[ 0 ] ] = function() {
				deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
				return this;
			};

			// deferred.notifyWith = list.fireWith
			// deferred.resolveWith = list.fireWith
			// deferred.rejectWith = list.fireWith
			deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
		} );

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( singleValue ) {
		var

			// count of uncompleted subordinates
			remaining = arguments.length,

			// count of unprocessed arguments
			i = remaining,

			// subordinate fulfillment data
			resolveContexts = Array( i ),
			resolveValues = slice.call( arguments ),

			// the primary Deferred
			primary = jQuery.Deferred(),

			// subordinate callback factory
			updateFunc = function( i ) {
				return function( value ) {
					resolveContexts[ i ] = this;
					resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
					if ( !( --remaining ) ) {
						primary.resolveWith( resolveContexts, resolveValues );
					}
				};
			};

		// Single- and empty arguments are adopted like Promise.resolve
		if ( remaining <= 1 ) {
			adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject,
				!remaining );

			// Use .then() to unwrap secondary thenables (cf. gh-3000)
			if ( primary.state() === "pending" ||
				isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {

				return primary.then();
			}
		}

		// Multiple arguments are aggregated like Promise.all array elements
		while ( i-- ) {
			adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject );
		}

		return primary.promise();
	}
} );


// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;

// If `jQuery.Deferred.getErrorHook` is defined, `asyncError` is an error
// captured before the async barrier to get the original error cause
// which may otherwise be hidden.
jQuery.Deferred.exceptionHook = function( error, asyncError ) {

	// Support: IE 8 - 9 only
	// Console exists when dev tools are open, which can happen at any time
	if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
		window.console.warn( "jQuery.Deferred exception: " + error.message,
			error.stack, asyncError );
	}
};




jQuery.readyException = function( error ) {
	window.setTimeout( function() {
		throw error;
	} );
};




// The deferred used on DOM ready
var readyList = jQuery.Deferred();

jQuery.fn.ready = function( fn ) {

	readyList
		.then( fn )

		// Wrap jQuery.readyException in a function so that the lookup
		// happens at the time of error handling instead of callback
		// registration.
		.catch( function( error ) {
			jQuery.readyException( error );
		} );

	return this;
};

jQuery.extend( {

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See trac-6781
	readyWait: 1,

	// Handle when the DOM is ready
	ready: function( wait ) {

		// Abort if there are pending holds or we're already ready
		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
			return;
		}

		// Remember that the DOM is ready
		jQuery.isReady = true;

		// If a normal DOM Ready event fired, decrement, and wait if need be
		if ( wait !== true && --jQuery.readyWait > 0 ) {
			return;
		}

		// If there are functions bound, to execute
		readyList.resolveWith( document, [ jQuery ] );
	}
} );

jQuery.ready.then = readyList.then;

// The ready event handler and self cleanup method
function completed() {
	document.removeEventListener( "DOMContentLoaded", completed );
	window.removeEventListener( "load", completed );
	jQuery.ready();
}

// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
	( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {

	// Handle it asynchronously to allow scripts the opportunity to delay ready
	window.setTimeout( jQuery.ready );

} else {

	// Use the handy event callback
	document.addEventListener( "DOMContentLoaded", completed );

	// A fallback to window.onload, that will always work
	window.addEventListener( "load", completed );
}




// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
	var i = 0,
		len = elems.length,
		bulk = key == null;

	// Sets many values
	if ( toType( key ) === "object" ) {
		chainable = true;
		for ( i in key ) {
			access( elems, fn, i, key[ i ], true, emptyGet, raw );
		}

	// Sets one value
	} else if ( value !== undefined ) {
		chainable = true;

		if ( !isFunction( value ) ) {
			raw = true;
		}

		if ( bulk ) {

			// Bulk operations run against the entire set
			if ( raw ) {
				fn.call( elems, value );
				fn = null;

			// ...except when executing function values
			} else {
				bulk = fn;
				fn = function( elem, _key, value ) {
					return bulk.call( jQuery( elem ), value );
				};
			}
		}

		if ( fn ) {
			for ( ; i < len; i++ ) {
				fn(
					elems[ i ], key, raw ?
						value :
						value.call( elems[ i ], i, fn( elems[ i ], key ) )
				);
			}
		}
	}

	if ( chainable ) {
		return elems;
	}

	// Gets
	if ( bulk ) {
		return fn.call( elems );
	}

	return len ? fn( elems[ 0 ], key ) : emptyGet;
};


// Matches dashed string for camelizing
var rmsPrefix = /^-ms-/,
	rdashAlpha = /-([a-z])/g;

// Used by camelCase as callback to replace()
function fcamelCase( _all, letter ) {
	return letter.toUpperCase();
}

// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 15
// Microsoft forgot to hump their vendor prefix (trac-9572)
function camelCase( string ) {
	return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
}
var acceptData = function( owner ) {

	// Accepts only:
	//  - Node
	//    - Node.ELEMENT_NODE
	//    - Node.DOCUMENT_NODE
	//  - Object
	//    - Any
	return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};




function Data() {
	this.expando = jQuery.expando + Data.uid++;
}

Data.uid = 1;

Data.prototype = {

	cache: function( owner ) {

		// Check if the owner object already has a cache
		var value = owner[ this.expando ];

		// If not, create one
		if ( !value ) {
			value = {};

			// We can accept data for non-element nodes in modern browsers,
			// but we should not, see trac-8335.
			// Always return an empty object.
			if ( acceptData( owner ) ) {

				// If it is a node unlikely to be stringify-ed or looped over
				// use plain assignment
				if ( owner.nodeType ) {
					owner[ this.expando ] = value;

				// Otherwise secure it in a non-enumerable property
				// configurable must be true to allow the property to be
				// deleted when data is removed
				} else {
					Object.defineProperty( owner, this.expando, {
						value: value,
						configurable: true
					} );
				}
			}
		}

		return value;
	},
	set: function( owner, data, value ) {
		var prop,
			cache = this.cache( owner );

		// Handle: [ owner, key, value ] args
		// Always use camelCase key (gh-2257)
		if ( typeof data === "string" ) {
			cache[ camelCase( data ) ] = value;

		// Handle: [ owner, { properties } ] args
		} else {

			// Copy the properties one-by-one to the cache object
			for ( prop in data ) {
				cache[ camelCase( prop ) ] = data[ prop ];
			}
		}
		return cache;
	},
	get: function( owner, key ) {
		return key === undefined ?
			this.cache( owner ) :

			// Always use camelCase key (gh-2257)
			owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ];
	},
	access: function( owner, key, value ) {

		// In cases where either:
		//
		//   1. No key was specified
		//   2. A string key was specified, but no value provided
		//
		// Take the "read" path and allow the get method to determine
		// which value to return, respectively either:
		//
		//   1. The entire cache object
		//   2. The data stored at the key
		//
		if ( key === undefined ||
				( ( key && typeof key === "string" ) && value === undefined ) ) {

			return this.get( owner, key );
		}

		// When the key is not a string, or both a key and value
		// are specified, set or extend (existing objects) with either:
		//
		//   1. An object of properties
		//   2. A key and value
		//
		this.set( owner, key, value );

		// Since the "set" path can have two possible entry points
		// return the expected data based on which path was taken[*]
		return value !== undefined ? value : key;
	},
	remove: function( owner, key ) {
		var i,
			cache = owner[ this.expando ];

		if ( cache === undefined ) {
			return;
		}

		if ( key !== undefined ) {

			// Support array or space separated string of keys
			if ( Array.isArray( key ) ) {

				// If key is an array of keys...
				// We always set camelCase keys, so remove that.
				key = key.map( camelCase );
			} else {
				key = camelCase( key );

				// If a key with the spaces exists, use it.
				// Otherwise, create an array by matching non-whitespace
				key = key in cache ?
					[ key ] :
					( key.match( rnothtmlwhite ) || [] );
			}

			i = key.length;

			while ( i-- ) {
				delete cache[ key[ i ] ];
			}
		}

		// Remove the expando if there's no more data
		if ( key === undefined || jQuery.isEmptyObject( cache ) ) {

			// Support: Chrome <=35 - 45
			// Webkit & Blink performance suffers when deleting properties
			// from DOM nodes, so set to undefined instead
			// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
			if ( owner.nodeType ) {
				owner[ this.expando ] = undefined;
			} else {
				delete owner[ this.expando ];
			}
		}
	},
	hasData: function( owner ) {
		var cache = owner[ this.expando ];
		return cache !== undefined && !jQuery.isEmptyObject( cache );
	}
};
var dataPriv = new Data();

var dataUser = new Data();



//	Implementation Summary
//
//	1. Enforce API surface and semantic compatibility with 1.9.x branch
//	2. Improve the module's maintainability by reducing the storage
//		paths to a single mechanism.
//	3. Use the same single mechanism to support "private" and "user" data.
//	4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
//	5. Avoid exposing implementation details on user objects (eg. expando properties)
//	6. Provide a clear path for implementation upgrade to WeakMap in 2014

var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
	rmultiDash = /[A-Z]/g;

function getData( data ) {
	if ( data === "true" ) {
		return true;
	}

	if ( data === "false" ) {
		return false;
	}

	if ( data === "null" ) {
		return null;
	}

	// Only convert to a number if it doesn't change the string
	if ( data === +data + "" ) {
		return +data;
	}

	if ( rbrace.test( data ) ) {
		return JSON.parse( data );
	}

	return data;
}

function dataAttr( elem, key, data ) {
	var name;

	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {
		name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
		data = elem.getAttribute( name );

		if ( typeof data === "string" ) {
			try {
				data = getData( data );
			} catch ( e ) {}

			// Make sure we set the data so it isn't changed later
			dataUser.set( elem, key, data );
		} else {
			data = undefined;
		}
	}
	return data;
}

jQuery.extend( {
	hasData: function( elem ) {
		return dataUser.hasData( elem ) || dataPriv.hasData( elem );
	},

	data: function( elem, name, data ) {
		return dataUser.access( elem, name, data );
	},

	removeData: function( elem, name ) {
		dataUser.remove( elem, name );
	},

	// TODO: Now that all calls to _data and _removeData have been replaced
	// with direct calls to dataPriv methods, these can be deprecated.
	_data: function( elem, name, data ) {
		return dataPriv.access( elem, name, data );
	},

	_removeData: function( elem, name ) {
		dataPriv.remove( elem, name );
	}
} );

jQuery.fn.extend( {
	data: function( key, value ) {
		var i, name, data,
			elem = this[ 0 ],
			attrs = elem && elem.attributes;

		// Gets all values
		if ( key === undefined ) {
			if ( this.length ) {
				data = dataUser.get( elem );

				if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
					i = attrs.length;
					while ( i-- ) {

						// Support: IE 11 only
						// The attrs elements can be null (trac-14894)
						if ( attrs[ i ] ) {
							name = attrs[ i ].name;
							if ( name.indexOf( "data-" ) === 0 ) {
								name = camelCase( name.slice( 5 ) );
								dataAttr( elem, name, data[ name ] );
							}
						}
					}
					dataPriv.set( elem, "hasDataAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each( function() {
				dataUser.set( this, key );
			} );
		}

		return access( this, function( value ) {
			var data;

			// The calling jQuery object (element matches) is not empty
			// (and therefore has an element appears at this[ 0 ]) and the
			// `value` parameter was not undefined. An empty jQuery object
			// will result in `undefined` for elem = this[ 0 ] which will
			// throw an exception if an attempt to read a data cache is made.
			if ( elem && value === undefined ) {

				// Attempt to get data from the cache
				// The key will always be camelCased in Data
				data = dataUser.get( elem, key );
				if ( data !== undefined ) {
					return data;
				}

				// Attempt to "discover" the data in
				// HTML5 custom data-* attrs
				data = dataAttr( elem, key );
				if ( data !== undefined ) {
					return data;
				}

				// We tried really hard, but the data doesn't exist.
				return;
			}

			// Set the data...
			this.each( function() {

				// We always store the camelCased key
				dataUser.set( this, key, value );
			} );
		}, null, value, arguments.length > 1, null, true );
	},

	removeData: function( key ) {
		return this.each( function() {
			dataUser.remove( this, key );
		} );
	}
} );


jQuery.extend( {
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = dataPriv.get( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || Array.isArray( data ) ) {
					queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
				} else {
					queue.push( data );
				}
			}
			return queue || [];
		}
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ),
			startLength = queue.length,
			fn = queue.shift(),
			hooks = jQuery._queueHooks( elem, type ),
			next = function() {
				jQuery.dequeue( elem, type );
			};

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
			startLength--;
		}

		if ( fn ) {

			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift( "inprogress" );
			}

			// Clear up the last queue stop function
			delete hooks.stop;
			fn.call( elem, next, hooks );
		}

		if ( !startLength && hooks ) {
			hooks.empty.fire();
		}
	},

	// Not public - generate a queueHooks object, or return the current one
	_queueHooks: function( elem, type ) {
		var key = type + "queueHooks";
		return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
			empty: jQuery.Callbacks( "once memory" ).add( function() {
				dataPriv.remove( elem, [ type + "queue", key ] );
			} )
		} );
	}
} );

jQuery.fn.extend( {
	queue: function( type, data ) {
		var setter = 2;

		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
			setter--;
		}

		if ( arguments.length < setter ) {
			return jQuery.queue( this[ 0 ], type );
		}

		return data === undefined ?
			this :
			this.each( function() {
				var queue = jQuery.queue( this, type, data );

				// Ensure a hooks for this queue
				jQuery._queueHooks( this, type );

				if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
					jQuery.dequeue( this, type );
				}
			} );
	},
	dequeue: function( type ) {
		return this.each( function() {
			jQuery.dequeue( this, type );
		} );
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	},

	// Get a promise resolved when queues of a certain type
	// are emptied (fx is the type by default)
	promise: function( type, obj ) {
		var tmp,
			count = 1,
			defer = jQuery.Deferred(),
			elements = this,
			i = this.length,
			resolve = function() {
				if ( !( --count ) ) {
					defer.resolveWith( elements, [ elements ] );
				}
			};

		if ( typeof type !== "string" ) {
			obj = type;
			type = undefined;
		}
		type = type || "fx";

		while ( i-- ) {
			tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
			if ( tmp && tmp.empty ) {
				count++;
				tmp.empty.add( resolve );
			}
		}
		resolve();
		return defer.promise( obj );
	}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;

var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );


var cssExpand = [ "Top", "Right", "Bottom", "Left" ];

var documentElement = document.documentElement;



	var isAttached = function( elem ) {
			return jQuery.contains( elem.ownerDocument, elem );
		},
		composed = { composed: true };

	// Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only
	// Check attachment across shadow DOM boundaries when possible (gh-3504)
	// Support: iOS 10.0-10.2 only
	// Early iOS 10 versions support `attachShadow` but not `getRootNode`,
	// leading to errors. We need to check for `getRootNode`.
	if ( documentElement.getRootNode ) {
		isAttached = function( elem ) {
			return jQuery.contains( elem.ownerDocument, elem ) ||
				elem.getRootNode( composed ) === elem.ownerDocument;
		};
	}
var isHiddenWithinTree = function( elem, el ) {

		// isHiddenWithinTree might be called from jQuery#filter function;
		// in that case, element will be second argument
		elem = el || elem;

		// Inline style trumps all
		return elem.style.display === "none" ||
			elem.style.display === "" &&

			// Otherwise, check computed style
			// Support: Firefox <=43 - 45
			// Disconnected elements can have computed display: none, so first confirm that elem is
			// in the document.
			isAttached( elem ) &&

			jQuery.css( elem, "display" ) === "none";
	};



function adjustCSS( elem, prop, valueParts, tween ) {
	var adjusted, scale,
		maxIterations = 20,
		currentValue = tween ?
			function() {
				return tween.cur();
			} :
			function() {
				return jQuery.css( elem, prop, "" );
			},
		initial = currentValue(),
		unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),

		// Starting value computation is required for potential unit mismatches
		initialInUnit = elem.nodeType &&
			( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
			rcssNum.exec( jQuery.css( elem, prop ) );

	if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {

		// Support: Firefox <=54
		// Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
		initial = initial / 2;

		// Trust units reported by jQuery.css
		unit = unit || initialInUnit[ 3 ];

		// Iteratively approximate from a nonzero starting point
		initialInUnit = +initial || 1;

		while ( maxIterations-- ) {

			// Evaluate and update our best guess (doubling guesses that zero out).
			// Finish if the scale equals or crosses 1 (making the old*new product non-positive).
			jQuery.style( elem, prop, initialInUnit + unit );
			if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) {
				maxIterations = 0;
			}
			initialInUnit = initialInUnit / scale;

		}

		initialInUnit = initialInUnit * 2;
		jQuery.style( elem, prop, initialInUnit + unit );

		// Make sure we update the tween properties later on
		valueParts = valueParts || [];
	}

	if ( valueParts ) {
		initialInUnit = +initialInUnit || +initial || 0;

		// Apply relative offset (+=/-=) if specified
		adjusted = valueParts[ 1 ] ?
			initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
			+valueParts[ 2 ];
		if ( tween ) {
			tween.unit = unit;
			tween.start = initialInUnit;
			tween.end = adjusted;
		}
	}
	return adjusted;
}


var defaultDisplayMap = {};

function getDefaultDisplay( elem ) {
	var temp,
		doc = elem.ownerDocument,
		nodeName = elem.nodeName,
		display = defaultDisplayMap[ nodeName ];

	if ( display ) {
		return display;
	}

	temp = doc.body.appendChild( doc.createElement( nodeName ) );
	display = jQuery.css( temp, "display" );

	temp.parentNode.removeChild( temp );

	if ( display === "none" ) {
		display = "block";
	}
	defaultDisplayMap[ nodeName ] = display;

	return display;
}

function showHide( elements, show ) {
	var display, elem,
		values = [],
		index = 0,
		length = elements.length;

	// Determine new display value for elements that need to change
	for ( ; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}

		display = elem.style.display;
		if ( show ) {

			// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
			// check is required in this first loop unless we have a nonempty display value (either
			// inline or about-to-be-restored)
			if ( display === "none" ) {
				values[ index ] = dataPriv.get( elem, "display" ) || null;
				if ( !values[ index ] ) {
					elem.style.display = "";
				}
			}
			if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
				values[ index ] = getDefaultDisplay( elem );
			}
		} else {
			if ( display !== "none" ) {
				values[ index ] = "none";

				// Remember what we're overwriting
				dataPriv.set( elem, "display", display );
			}
		}
	}

	// Set the display of the elements in a second loop to avoid constant reflow
	for ( index = 0; index < length; index++ ) {
		if ( values[ index ] != null ) {
			elements[ index ].style.display = values[ index ];
		}
	}

	return elements;
}

jQuery.fn.extend( {
	show: function() {
		return showHide( this, true );
	},
	hide: function() {
		return showHide( this );
	},
	toggle: function( state ) {
		if ( typeof state === "boolean" ) {
			return state ? this.show() : this.hide();
		}

		return this.each( function() {
			if ( isHiddenWithinTree( this ) ) {
				jQuery( this ).show();
			} else {
				jQuery( this ).hide();
			}
		} );
	}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );

var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i );

var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i );



( function() {
	var fragment = document.createDocumentFragment(),
		div = fragment.appendChild( document.createElement( "div" ) ),
		input = document.createElement( "input" );

	// Support: Android 4.0 - 4.3 only
	// Check state lost if the name is set (trac-11217)
	// Support: Windows Web Apps (WWA)
	// `name` and `type` must use .setAttribute for WWA (trac-14901)
	input.setAttribute( "type", "radio" );
	input.setAttribute( "checked", "checked" );
	input.setAttribute( "name", "t" );

	div.appendChild( input );

	// Support: Android <=4.1 only
	// Older WebKit doesn't clone checked state correctly in fragments
	support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Support: IE <=11 only
	// Make sure textarea (and checkbox) defaultValue is properly cloned
	div.innerHTML = "<textarea>x</textarea>";
	support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;

	// Support: IE <=9 only
	// IE <=9 replaces <option> tags with their contents when inserted outside of
	// the select element.
	div.innerHTML = "<option></option>";
	support.option = !!div.lastChild;
} )();


// We have to close these tags to support XHTML (trac-13200)
var wrapMap = {

	// XHTML parsers do not magically insert elements in the
	// same way that tag soup parsers do. So we cannot shorten
	// this by omitting <tbody> or other required elements.
	thead: [ 1, "<table>", "</table>" ],
	col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
	tr: [ 2, "<table><tbody>", "</tbody></table>" ],
	td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

	_default: [ 0, "", "" ]
};

wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

// Support: IE <=9 only
if ( !support.option ) {
	wrapMap.optgroup = wrapMap.option = [ 1, "<select multiple='multiple'>", "</select>" ];
}


function getAll( context, tag ) {

	// Support: IE <=9 - 11 only
	// Use typeof to avoid zero-argument method invocation on host objects (trac-15151)
	var ret;

	if ( typeof context.getElementsByTagName !== "undefined" ) {
		ret = context.getElementsByTagName( tag || "*" );

	} else if ( typeof context.querySelectorAll !== "undefined" ) {
		ret = context.querySelectorAll( tag || "*" );

	} else {
		ret = [];
	}

	if ( tag === undefined || tag && nodeName( context, tag ) ) {
		return jQuery.merge( [ context ], ret );
	}

	return ret;
}


// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
	var i = 0,
		l = elems.length;

	for ( ; i < l; i++ ) {
		dataPriv.set(
			elems[ i ],
			"globalEval",
			!refElements || dataPriv.get( refElements[ i ], "globalEval" )
		);
	}
}


var rhtml = /<|&#?\w+;/;

function buildFragment( elems, context, scripts, selection, ignored ) {
	var elem, tmp, tag, wrap, attached, j,
		fragment = context.createDocumentFragment(),
		nodes = [],
		i = 0,
		l = elems.length;

	for ( ; i < l; i++ ) {
		elem = elems[ i ];

		if ( elem || elem === 0 ) {

			// Add nodes directly
			if ( toType( elem ) === "object" ) {

				// Support: Android <=4.0 only, PhantomJS 1 only
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );

			// Convert non-html into a text node
			} else if ( !rhtml.test( elem ) ) {
				nodes.push( context.createTextNode( elem ) );

			// Convert html into DOM nodes
			} else {
				tmp = tmp || fragment.appendChild( context.createElement( "div" ) );

				// Deserialize a standard representation
				tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
				wrap = wrapMap[ tag ] || wrapMap._default;
				tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];

				// Descend through wrappers to the right content
				j = wrap[ 0 ];
				while ( j-- ) {
					tmp = tmp.lastChild;
				}

				// Support: Android <=4.0 only, PhantomJS 1 only
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, tmp.childNodes );

				// Remember the top-level container
				tmp = fragment.firstChild;

				// Ensure the created nodes are orphaned (trac-12392)
				tmp.textContent = "";
			}
		}
	}

	// Remove wrapper from fragment
	fragment.textContent = "";

	i = 0;
	while ( ( elem = nodes[ i++ ] ) ) {

		// Skip elements already in the context collection (trac-4087)
		if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
			if ( ignored ) {
				ignored.push( elem );
			}
			continue;
		}

		attached = isAttached( elem );

		// Append to fragment
		tmp = getAll( fragment.appendChild( elem ), "script" );

		// Preserve script evaluation history
		if ( attached ) {
			setGlobalEval( tmp );
		}

		// Capture executables
		if ( scripts ) {
			j = 0;
			while ( ( elem = tmp[ j++ ] ) ) {
				if ( rscriptType.test( elem.type || "" ) ) {
					scripts.push( elem );
				}
			}
		}
	}

	return fragment;
}


var rtypenamespace = /^([^.]*)(?:\.(.+)|)/;

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

function on( elem, types, selector, data, fn, one ) {
	var origFn, type;

	// Types can be a map of types/handlers
	if ( typeof types === "object" ) {

		// ( types-Object, selector, data )
		if ( typeof selector !== "string" ) {

			// ( types-Object, data )
			data = data || selector;
			selector = undefined;
		}
		for ( type in types ) {
			on( elem, type, selector, data, types[ type ], one );
		}
		return elem;
	}

	if ( data == null && fn == null ) {

		// ( types, fn )
		fn = selector;
		data = selector = undefined;
	} else if ( fn == null ) {
		if ( typeof selector === "string" ) {

			// ( types, selector, fn )
			fn = data;
			data = undefined;
		} else {

			// ( types, data, fn )
			fn = data;
			data = selector;
			selector = undefined;
		}
	}
	if ( fn === false ) {
		fn = returnFalse;
	} else if ( !fn ) {
		return elem;
	}

	if ( one === 1 ) {
		origFn = fn;
		fn = function( event ) {

			// Can use an empty set, since event contains the info
			jQuery().off( event );
			return origFn.apply( this, arguments );
		};

		// Use same guid so caller can remove using origFn
		fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
	}
	return elem.each( function() {
		jQuery.event.add( this, types, fn, data, selector );
	} );
}

/*
 * Helper functions for managing events -- not part of the public interface.
 * Props to Dean Edwards' addEvent library for many of the ideas.
 */
jQuery.event = {

	global: {},

	add: function( elem, types, handler, data, selector ) {

		var handleObjIn, eventHandle, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.get( elem );

		// Only attach events to objects that accept data
		if ( !acceptData( elem ) ) {
			return;
		}

		// Caller can pass in an object of custom data in lieu of the handler
		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
			selector = handleObjIn.selector;
		}

		// Ensure that invalid selectors throw exceptions at attach time
		// Evaluate against documentElement in case elem is a non-element node (e.g., document)
		if ( selector ) {
			jQuery.find.matchesSelector( documentElement, selector );
		}

		// Make sure that the handler has a unique ID, used to find/remove it later
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		// Init the element's event structure and main handler, if this is the first
		if ( !( events = elemData.events ) ) {
			events = elemData.events = Object.create( null );
		}
		if ( !( eventHandle = elemData.handle ) ) {
			eventHandle = elemData.handle = function( e ) {

				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
					jQuery.event.dispatch.apply( elem, arguments ) : undefined;
			};
		}

		// Handle multiple events separated by a space
		types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// There *must* be a type, no attaching namespace-only handlers
			if ( !type ) {
				continue;
			}

			// If event changes its type, use the special event handlers for the changed type
			special = jQuery.event.special[ type ] || {};

			// If selector defined, determine special event api type, otherwise given type
			type = ( selector ? special.delegateType : special.bindType ) || type;

			// Update special based on newly reset type
			special = jQuery.event.special[ type ] || {};

			// handleObj is passed to all event handlers
			handleObj = jQuery.extend( {
				type: type,
				origType: origType,
				data: data,
				handler: handler,
				guid: handler.guid,
				selector: selector,
				needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
				namespace: namespaces.join( "." )
			}, handleObjIn );

			// Init the event handler queue if we're the first
			if ( !( handlers = events[ type ] ) ) {
				handlers = events[ type ] = [];
				handlers.delegateCount = 0;

				// Only use addEventListener if the special events handler returns false
				if ( !special.setup ||
					special.setup.call( elem, data, namespaces, eventHandle ) === false ) {

					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add to the element's handler list, delegates in front
			if ( selector ) {
				handlers.splice( handlers.delegateCount++, 0, handleObj );
			} else {
				handlers.push( handleObj );
			}

			// Keep track of which events have ever been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

	},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {

		var j, origCount, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );

		if ( !elemData || !( events = elemData.events ) ) {
			return;
		}

		// Once for each type.namespace in types; type may be omitted
		types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// Unbind all events (on this namespace, if provided) for the element
			if ( !type ) {
				for ( type in events ) {
					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
				}
				continue;
			}

			special = jQuery.event.special[ type ] || {};
			type = ( selector ? special.delegateType : special.bindType ) || type;
			handlers = events[ type ] || [];
			tmp = tmp[ 2 ] &&
				new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );

			// Remove matching events
			origCount = j = handlers.length;
			while ( j-- ) {
				handleObj = handlers[ j ];

				if ( ( mappedTypes || origType === handleObj.origType ) &&
					( !handler || handler.guid === handleObj.guid ) &&
					( !tmp || tmp.test( handleObj.namespace ) ) &&
					( !selector || selector === handleObj.selector ||
						selector === "**" && handleObj.selector ) ) {
					handlers.splice( j, 1 );

					if ( handleObj.selector ) {
						handlers.delegateCount--;
					}
					if ( special.remove ) {
						special.remove.call( elem, handleObj );
					}
				}
			}

			// Remove generic event handler if we removed something and no more handlers exist
			// (avoids potential for endless recursion during removal of special event handlers)
			if ( origCount && !handlers.length ) {
				if ( !special.teardown ||
					special.teardown.call( elem, namespaces, elemData.handle ) === false ) {

					jQuery.removeEvent( elem, type, elemData.handle );
				}

				delete events[ type ];
			}
		}

		// Remove data and the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			dataPriv.remove( elem, "handle events" );
		}
	},

	dispatch: function( nativeEvent ) {

		var i, j, ret, matched, handleObj, handlerQueue,
			args = new Array( arguments.length ),

			// Make a writable jQuery.Event from the native event object
			event = jQuery.event.fix( nativeEvent ),

			handlers = (
				dataPriv.get( this, "events" ) || Object.create( null )
			)[ event.type ] || [],
			special = jQuery.event.special[ event.type ] || {};

		// Use the fix-ed jQuery.Event rather than the (read-only) native event
		args[ 0 ] = event;

		for ( i = 1; i < arguments.length; i++ ) {
			args[ i ] = arguments[ i ];
		}

		event.delegateTarget = this;

		// Call the preDispatch hook for the mapped type, and let it bail if desired
		if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
			return;
		}

		// Determine handlers
		handlerQueue = jQuery.event.handlers.call( this, event, handlers );

		// Run delegates first; they may want to stop propagation beneath us
		i = 0;
		while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
			event.currentTarget = matched.elem;

			j = 0;
			while ( ( handleObj = matched.handlers[ j++ ] ) &&
				!event.isImmediatePropagationStopped() ) {

				// If the event is namespaced, then each handler is only invoked if it is
				// specially universal or its namespaces are a superset of the event's.
				if ( !event.rnamespace || handleObj.namespace === false ||
					event.rnamespace.test( handleObj.namespace ) ) {

					event.handleObj = handleObj;
					event.data = handleObj.data;

					ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
						handleObj.handler ).apply( matched.elem, args );

					if ( ret !== undefined ) {
						if ( ( event.result = ret ) === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
				}
			}
		}

		// Call the postDispatch hook for the mapped type
		if ( special.postDispatch ) {
			special.postDispatch.call( this, event );
		}

		return event.result;
	},

	handlers: function( event, handlers ) {
		var i, handleObj, sel, matchedHandlers, matchedSelectors,
			handlerQueue = [],
			delegateCount = handlers.delegateCount,
			cur = event.target;

		// Find delegate handlers
		if ( delegateCount &&

			// Support: IE <=9
			// Black-hole SVG <use> instance trees (trac-13180)
			cur.nodeType &&

			// Support: Firefox <=42
			// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
			// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
			// Support: IE 11 only
			// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
			!( event.type === "click" && event.button >= 1 ) ) {

			for ( ; cur !== this; cur = cur.parentNode || this ) {

				// Don't check non-elements (trac-13208)
				// Don't process clicks on disabled elements (trac-6911, trac-8165, trac-11382, trac-11764)
				if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
					matchedHandlers = [];
					matchedSelectors = {};
					for ( i = 0; i < delegateCount; i++ ) {
						handleObj = handlers[ i ];

						// Don't conflict with Object.prototype properties (trac-13203)
						sel = handleObj.selector + " ";

						if ( matchedSelectors[ sel ] === undefined ) {
							matchedSelectors[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) > -1 :
								jQuery.find( sel, this, null, [ cur ] ).length;
						}
						if ( matchedSelectors[ sel ] ) {
							matchedHandlers.push( handleObj );
						}
					}
					if ( matchedHandlers.length ) {
						handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
					}
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		cur = this;
		if ( delegateCount < handlers.length ) {
			handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
		}

		return handlerQueue;
	},

	addProp: function( name, hook ) {
		Object.defineProperty( jQuery.Event.prototype, name, {
			enumerable: true,
			configurable: true,

			get: isFunction( hook ) ?
				function() {
					if ( this.originalEvent ) {
						return hook( this.originalEvent );
					}
				} :
				function() {
					if ( this.originalEvent ) {
						return this.originalEvent[ name ];
					}
				},

			set: function( value ) {
				Object.defineProperty( this, name, {
					enumerable: true,
					configurable: true,
					writable: true,
					value: value
				} );
			}
		} );
	},

	fix: function( originalEvent ) {
		return originalEvent[ jQuery.expando ] ?
			originalEvent :
			new jQuery.Event( originalEvent );
	},

	special: {
		load: {

			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},
		click: {

			// Utilize native event to ensure correct state for checkable inputs
			setup: function( data ) {

				// For mutual compressibility with _default, replace `this` access with a local var.
				// `|| data` is dead code meant only to preserve the variable through minification.
				var el = this || data;

				// Claim the first handler
				if ( rcheckableType.test( el.type ) &&
					el.click && nodeName( el, "input" ) ) {

					// dataPriv.set( el, "click", ... )
					leverageNative( el, "click", true );
				}

				// Return false to allow normal processing in the caller
				return false;
			},
			trigger: function( data ) {

				// For mutual compressibility with _default, replace `this` access with a local var.
				// `|| data` is dead code meant only to preserve the variable through minification.
				var el = this || data;

				// Force setup before triggering a click
				if ( rcheckableType.test( el.type ) &&
					el.click && nodeName( el, "input" ) ) {

					leverageNative( el, "click" );
				}

				// Return non-false to allow normal event-path propagation
				return true;
			},

			// For cross-browser consistency, suppress native .click() on links
			// Also prevent it if we're currently inside a leveraged native-event stack
			_default: function( event ) {
				var target = event.target;
				return rcheckableType.test( target.type ) &&
					target.click && nodeName( target, "input" ) &&
					dataPriv.get( target, "click" ) ||
					nodeName( target, "a" );
			}
		},

		beforeunload: {
			postDispatch: function( event ) {

				// Support: Firefox 20+
				// Firefox doesn't alert if the returnValue field is not set.
				if ( event.result !== undefined && event.originalEvent ) {
					event.originalEvent.returnValue = event.result;
				}
			}
		}
	}
};

// Ensure the presence of an event listener that handles manually-triggered
// synthetic events by interrupting progress until reinvoked in response to
// *native* events that it fires directly, ensuring that state changes have
// already occurred before other listeners are invoked.
function leverageNative( el, type, isSetup ) {

	// Missing `isSetup` indicates a trigger call, which must force setup through jQuery.event.add
	if ( !isSetup ) {
		if ( dataPriv.get( el, type ) === undefined ) {
			jQuery.event.add( el, type, returnTrue );
		}
		return;
	}

	// Register the controller as a special universal handler for all event namespaces
	dataPriv.set( el, type, false );
	jQuery.event.add( el, type, {
		namespace: false,
		handler: function( event ) {
			var result,
				saved = dataPriv.get( this, type );

			if ( ( event.isTrigger & 1 ) && this[ type ] ) {

				// Interrupt processing of the outer synthetic .trigger()ed event
				if ( !saved ) {

					// Store arguments for use when handling the inner native event
					// There will always be at least one argument (an event object), so this array
					// will not be confused with a leftover capture object.
					saved = slice.call( arguments );
					dataPriv.set( this, type, saved );

					// Trigger the native event and capture its result
					this[ type ]();
					result = dataPriv.get( this, type );
					dataPriv.set( this, type, false );

					if ( saved !== result ) {

						// Cancel the outer synthetic event
						event.stopImmediatePropagation();
						event.preventDefault();

						return result;
					}

				// If this is an inner synthetic event for an event with a bubbling surrogate
				// (focus or blur), assume that the surrogate already propagated from triggering
				// the native event and prevent that from happening again here.
				// This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the
				// bubbling surrogate propagates *after* the non-bubbling base), but that seems
				// less bad than duplication.
				} else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) {
					event.stopPropagation();
				}

			// If this is a native event triggered above, everything is now in order
			// Fire an inner synthetic event with the original arguments
			} else if ( saved ) {

				// ...and capture the result
				dataPriv.set( this, type, jQuery.event.trigger(
					saved[ 0 ],
					saved.slice( 1 ),
					this
				) );

				// Abort handling of the native event by all jQuery handlers while allowing
				// native handlers on the same element to run. On target, this is achieved
				// by stopping immediate propagation just on the jQuery event. However,
				// the native event is re-wrapped by a jQuery one on each level of the
				// propagation so the only way to stop it for jQuery is to stop it for
				// everyone via native `stopPropagation()`. This is not a problem for
				// focus/blur which don't bubble, but it does also stop click on checkboxes
				// and radios. We accept this limitation.
				event.stopPropagation();
				event.isImmediatePropagationStopped = returnTrue;
			}
		}
	} );
}

jQuery.removeEvent = function( elem, type, handle ) {

	// This "if" is needed for plain objects
	if ( elem.removeEventListener ) {
		elem.removeEventListener( type, handle );
	}
};

jQuery.Event = function( src, props ) {

	// Allow instantiation without the 'new' keyword
	if ( !( this instanceof jQuery.Event ) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = src.defaultPrevented ||
				src.defaultPrevented === undefined &&

				// Support: Android <=2.3 only
				src.returnValue === false ?
			returnTrue :
			returnFalse;

		// Create target properties
		// Support: Safari <=6 - 7 only
		// Target should not be a text node (trac-504, trac-13143)
		this.target = ( src.target && src.target.nodeType === 3 ) ?
			src.target.parentNode :
			src.target;

		this.currentTarget = src.currentTarget;
		this.relatedTarget = src.relatedTarget;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src && src.timeStamp || Date.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	constructor: jQuery.Event,
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse,
	isSimulated: false,

	preventDefault: function() {
		var e = this.originalEvent;

		this.isDefaultPrevented = returnTrue;

		if ( e && !this.isSimulated ) {
			e.preventDefault();
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopPropagation();
		}
	},
	stopImmediatePropagation: function() {
		var e = this.originalEvent;

		this.isImmediatePropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopImmediatePropagation();
		}

		this.stopPropagation();
	}
};

// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
	altKey: true,
	bubbles: true,
	cancelable: true,
	changedTouches: true,
	ctrlKey: true,
	detail: true,
	eventPhase: true,
	metaKey: true,
	pageX: true,
	pageY: true,
	shiftKey: true,
	view: true,
	"char": true,
	code: true,
	charCode: true,
	key: true,
	keyCode: true,
	button: true,
	buttons: true,
	clientX: true,
	clientY: true,
	offsetX: true,
	offsetY: true,
	pointerId: true,
	pointerType: true,
	screenX: true,
	screenY: true,
	targetTouches: true,
	toElement: true,
	touches: true,
	which: true
}, jQuery.event.addProp );

jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) {

	function focusMappedHandler( nativeEvent ) {
		if ( document.documentMode ) {

			// Support: IE 11+
			// Attach a single focusin/focusout handler on the document while someone wants
			// focus/blur. This is because the former are synchronous in IE while the latter
			// are async. In other browsers, all those handlers are invoked synchronously.

			// `handle` from private data would already wrap the event, but we need
			// to change the `type` here.
			var handle = dataPriv.get( this, "handle" ),
				event = jQuery.event.fix( nativeEvent );
			event.type = nativeEvent.type === "focusin" ? "focus" : "blur";
			event.isSimulated = true;

			// First, handle focusin/focusout
			handle( nativeEvent );

			// ...then, handle focus/blur
			//
			// focus/blur don't bubble while focusin/focusout do; simulate the former by only
			// invoking the handler at the lower level.
			if ( event.target === event.currentTarget ) {

				// The setup part calls `leverageNative`, which, in turn, calls
				// `jQuery.event.add`, so event handle will already have been set
				// by this point.
				handle( event );
			}
		} else {

			// For non-IE browsers, attach a single capturing handler on the document
			// while someone wants focusin/focusout.
			jQuery.event.simulate( delegateType, nativeEvent.target,
				jQuery.event.fix( nativeEvent ) );
		}
	}

	jQuery.event.special[ type ] = {

		// Utilize native event if possible so blur/focus sequence is correct
		setup: function() {

			var attaches;

			// Claim the first handler
			// dataPriv.set( this, "focus", ... )
			// dataPriv.set( this, "blur", ... )
			leverageNative( this, type, true );

			if ( document.documentMode ) {

				// Support: IE 9 - 11+
				// We use the same native handler for focusin & focus (and focusout & blur)
				// so we need to coordinate setup & teardown parts between those events.
				// Use `delegateType` as the key as `type` is already used by `leverageNative`.
				attaches = dataPriv.get( this, delegateType );
				if ( !attaches ) {
					this.addEventListener( delegateType, focusMappedHandler );
				}
				dataPriv.set( this, delegateType, ( attaches || 0 ) + 1 );
			} else {

				// Return false to allow normal processing in the caller
				return false;
			}
		},
		trigger: function() {

			// Force setup before trigger
			leverageNative( this, type );

			// Return non-false to allow normal event-path propagation
			return true;
		},

		teardown: function() {
			var attaches;

			if ( document.documentMode ) {
				attaches = dataPriv.get( this, delegateType ) - 1;
				if ( !attaches ) {
					this.removeEventListener( delegateType, focusMappedHandler );
					dataPriv.remove( this, delegateType );
				} else {
					dataPriv.set( this, delegateType, attaches );
				}
			} else {

				// Return false to indicate standard teardown should be applied
				return false;
			}
		},

		// Suppress native focus or blur if we're currently inside
		// a leveraged native-event stack
		_default: function( event ) {
			return dataPriv.get( event.target, type );
		},

		delegateType: delegateType
	};

	// Support: Firefox <=44
	// Firefox doesn't have focus(in | out) events
	// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
	//
	// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
	// focus(in | out) events fire after focus & blur events,
	// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
	// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
	//
	// Support: IE 9 - 11+
	// To preserve relative focusin/focus & focusout/blur event order guaranteed on the 3.x branch,
	// attach a single handler for both events in IE.
	jQuery.event.special[ delegateType ] = {
		setup: function() {

			// Handle: regular nodes (via `this.ownerDocument`), window
			// (via `this.document`) & document (via `this`).
			var doc = this.ownerDocument || this.document || this,
				dataHolder = document.documentMode ? this : doc,
				attaches = dataPriv.get( dataHolder, delegateType );

			// Support: IE 9 - 11+
			// We use the same native handler for focusin & focus (and focusout & blur)
			// so we need to coordinate setup & teardown parts between those events.
			// Use `delegateType` as the key as `type` is already used by `leverageNative`.
			if ( !attaches ) {
				if ( document.documentMode ) {
					this.addEventListener( delegateType, focusMappedHandler );
				} else {
					doc.addEventListener( type, focusMappedHandler, true );
				}
			}
			dataPriv.set( dataHolder, delegateType, ( attaches || 0 ) + 1 );
		},
		teardown: function() {
			var doc = this.ownerDocument || this.document || this,
				dataHolder = document.documentMode ? this : doc,
				attaches = dataPriv.get( dataHolder, delegateType ) - 1;

			if ( !attaches ) {
				if ( document.documentMode ) {
					this.removeEventListener( delegateType, focusMappedHandler );
				} else {
					doc.removeEventListener( type, focusMappedHandler, true );
				}
				dataPriv.remove( dataHolder, delegateType );
			} else {
				dataPriv.set( dataHolder, delegateType, attaches );
			}
		}
	};
} );

// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
	mouseenter: "mouseover",
	mouseleave: "mouseout",
	pointerenter: "pointerover",
	pointerleave: "pointerout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var ret,
				target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj;

			// For mouseenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
} );

jQuery.fn.extend( {

	on: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn );
	},
	one: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		var handleObj, type;
		if ( types && types.preventDefault && types.handleObj ) {

			// ( event )  dispatched jQuery.Event
			handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace ?
					handleObj.origType + "." + handleObj.namespace :
					handleObj.origType,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {

			// ( types-object [, selector] )
			for ( type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {

			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each( function() {
			jQuery.event.remove( this, types, fn, selector );
		} );
	}
} );


var

	// Support: IE <=10 - 11, Edge 12 - 13 only
	// In IE/Edge using regex groups here causes severe slowdowns.
	// See https://connect.microsoft.com/IE/feedback/details/1736512/
	rnoInnerhtml = /<script|<style|<link/i,

	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,

	rcleanScript = /^\s*<!\[CDATA\[|\]\]>\s*$/g;

// Prefer a tbody over its parent table for containing new rows
function manipulationTarget( elem, content ) {
	if ( nodeName( elem, "table" ) &&
		nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {

		return jQuery( elem ).children( "tbody" )[ 0 ] || elem;
	}

	return elem;
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
	elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
	return elem;
}
function restoreScript( elem ) {
	if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) {
		elem.type = elem.type.slice( 5 );
	} else {
		elem.removeAttribute( "type" );
	}

	return elem;
}

function cloneCopyEvent( src, dest ) {
	var i, l, type, pdataOld, udataOld, udataCur, events;

	if ( dest.nodeType !== 1 ) {
		return;
	}

	// 1. Copy private data: events, handlers, etc.
	if ( dataPriv.hasData( src ) ) {
		pdataOld = dataPriv.get( src );
		events = pdataOld.events;

		if ( events ) {
			dataPriv.remove( dest, "handle events" );

			for ( type in events ) {
				for ( i = 0, l = events[ type ].length; i < l; i++ ) {
					jQuery.event.add( dest, type, events[ type ][ i ] );
				}
			}
		}
	}

	// 2. Copy user data
	if ( dataUser.hasData( src ) ) {
		udataOld = dataUser.access( src );
		udataCur = jQuery.extend( {}, udataOld );

		dataUser.set( dest, udataCur );
	}
}

// Fix IE bugs, see support tests
function fixInput( src, dest ) {
	var nodeName = dest.nodeName.toLowerCase();

	// Fails to persist the checked state of a cloned checkbox or radio button.
	if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
		dest.checked = src.checked;

	// Fails to return the selected option to the default selected state when cloning options
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

function domManip( collection, args, callback, ignored ) {

	// Flatten any nested arrays
	args = flat( args );

	var fragment, first, scripts, hasScripts, node, doc,
		i = 0,
		l = collection.length,
		iNoClone = l - 1,
		value = args[ 0 ],
		valueIsFunction = isFunction( value );

	// We can't cloneNode fragments that contain checked, in WebKit
	if ( valueIsFunction ||
			( l > 1 && typeof value === "string" &&
				!support.checkClone && rchecked.test( value ) ) ) {
		return collection.each( function( index ) {
			var self = collection.eq( index );
			if ( valueIsFunction ) {
				args[ 0 ] = value.call( this, index, self.html() );
			}
			domManip( self, args, callback, ignored );
		} );
	}

	if ( l ) {
		fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
		first = fragment.firstChild;

		if ( fragment.childNodes.length === 1 ) {
			fragment = first;
		}

		// Require either new content or an interest in ignored elements to invoke the callback
		if ( first || ignored ) {
			scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
			hasScripts = scripts.length;

			// Use the original fragment for the last item
			// instead of the first because it can end up
			// being emptied incorrectly in certain situations (trac-8070).
			for ( ; i < l; i++ ) {
				node = fragment;

				if ( i !== iNoClone ) {
					node = jQuery.clone( node, true, true );

					// Keep references to cloned scripts for later restoration
					if ( hasScripts ) {

						// Support: Android <=4.0 only, PhantomJS 1 only
						// push.apply(_, arraylike) throws on ancient WebKit
						jQuery.merge( scripts, getAll( node, "script" ) );
					}
				}

				callback.call( collection[ i ], node, i );
			}

			if ( hasScripts ) {
				doc = scripts[ scripts.length - 1 ].ownerDocument;

				// Re-enable scripts
				jQuery.map( scripts, restoreScript );

				// Evaluate executable scripts on first document insertion
				for ( i = 0; i < hasScripts; i++ ) {
					node = scripts[ i ];
					if ( rscriptType.test( node.type || "" ) &&
						!dataPriv.access( node, "globalEval" ) &&
						jQuery.contains( doc, node ) ) {

						if ( node.src && ( node.type || "" ).toLowerCase()  !== "module" ) {

							// Optional AJAX dependency, but won't run scripts if not present
							if ( jQuery._evalUrl && !node.noModule ) {
								jQuery._evalUrl( node.src, {
									nonce: node.nonce || node.getAttribute( "nonce" )
								}, doc );
							}
						} else {

							// Unwrap a CDATA section containing script contents. This shouldn't be
							// needed as in XML documents they're already not visible when
							// inspecting element contents and in HTML documents they have no
							// meaning but we're preserving that logic for backwards compatibility.
							// This will be removed completely in 4.0. See gh-4904.
							DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc );
						}
					}
				}
			}
		}
	}

	return collection;
}

function remove( elem, selector, keepData ) {
	var node,
		nodes = selector ? jQuery.filter( selector, elem ) : elem,
		i = 0;

	for ( ; ( node = nodes[ i ] ) != null; i++ ) {
		if ( !keepData && node.nodeType === 1 ) {
			jQuery.cleanData( getAll( node ) );
		}

		if ( node.parentNode ) {
			if ( keepData && isAttached( node ) ) {
				setGlobalEval( getAll( node, "script" ) );
			}
			node.parentNode.removeChild( node );
		}
	}

	return elem;
}

jQuery.extend( {
	htmlPrefilter: function( html ) {
		return html;
	},

	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var i, l, srcElements, destElements,
			clone = elem.cloneNode( true ),
			inPage = isAttached( elem );

		// Fix IE cloning issues
		if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
				!jQuery.isXMLDoc( elem ) ) {

			// We eschew jQuery#find here for performance reasons:
			// https://jsperf.com/getall-vs-sizzle/2
			destElements = getAll( clone );
			srcElements = getAll( elem );

			for ( i = 0, l = srcElements.length; i < l; i++ ) {
				fixInput( srcElements[ i ], destElements[ i ] );
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			if ( deepDataAndEvents ) {
				srcElements = srcElements || getAll( elem );
				destElements = destElements || getAll( clone );

				for ( i = 0, l = srcElements.length; i < l; i++ ) {
					cloneCopyEvent( srcElements[ i ], destElements[ i ] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length > 0 ) {
			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
		}

		// Return the cloned set
		return clone;
	},

	cleanData: function( elems ) {
		var data, elem, type,
			special = jQuery.event.special,
			i = 0;

		for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
			if ( acceptData( elem ) ) {
				if ( ( data = elem[ dataPriv.expando ] ) ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Support: Chrome <=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataPriv.expando ] = undefined;
				}
				if ( elem[ dataUser.expando ] ) {

					// Support: Chrome <=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataUser.expando ] = undefined;
				}
			}
		}
	}
} );

jQuery.fn.extend( {
	detach: function( selector ) {
		return remove( this, selector, true );
	},

	remove: function( selector ) {
		return remove( this, selector );
	},

	text: function( value ) {
		return access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().each( function() {
					if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
						this.textContent = value;
					}
				} );
		}, null, value, arguments.length );
	},

	append: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		} );
	},

	prepend: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.insertBefore( elem, target.firstChild );
			}
		} );
	},

	before: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		} );
	},

	after: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		} );
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; ( elem = this[ i ] ) != null; i++ ) {
			if ( elem.nodeType === 1 ) {

				// Prevent memory leaks
				jQuery.cleanData( getAll( elem, false ) );

				// Remove any remaining nodes
				elem.textContent = "";
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function() {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		} );
	},

	html: function( value ) {
		return access( this, function( value ) {
			var elem = this[ 0 ] || {},
				i = 0,
				l = this.length;

			if ( value === undefined && elem.nodeType === 1 ) {
				return elem.innerHTML;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

				value = jQuery.htmlPrefilter( value );

				try {
					for ( ; i < l; i++ ) {
						elem = this[ i ] || {};

						// Remove element nodes and prevent memory leaks
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( getAll( elem, false ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch ( e ) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function() {
		var ignored = [];

		// Make the changes, replacing each non-ignored context element with the new content
		return domManip( this, arguments, function( elem ) {
			var parent = this.parentNode;

			if ( jQuery.inArray( this, ignored ) < 0 ) {
				jQuery.cleanData( getAll( this ) );
				if ( parent ) {
					parent.replaceChild( elem, this );
				}
			}

		// Force callback invocation
		}, ignored );
	}
} );

jQuery.each( {
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1,
			i = 0;

		for ( ; i <= last; i++ ) {
			elems = i === last ? this : this.clone( true );
			jQuery( insert[ i ] )[ original ]( elems );

			// Support: Android <=4.0 only, PhantomJS 1 only
			// .get() because push.apply(_, arraylike) throws on ancient WebKit
			push.apply( ret, elems.get() );
		}

		return this.pushStack( ret );
	};
} );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );

var rcustomProp = /^--/;


var getStyles = function( elem ) {

		// Support: IE <=11 only, Firefox <=30 (trac-15098, trac-14150)
		// IE throws on elements created in popups
		// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
		var view = elem.ownerDocument.defaultView;

		if ( !view || !view.opener ) {
			view = window;
		}

		return view.getComputedStyle( elem );
	};

var swap = function( elem, options, callback ) {
	var ret, name,
		old = {};

	// Remember the old values, and insert the new ones
	for ( name in options ) {
		old[ name ] = elem.style[ name ];
		elem.style[ name ] = options[ name ];
	}

	ret = callback.call( elem );

	// Revert the old values
	for ( name in options ) {
		elem.style[ name ] = old[ name ];
	}

	return ret;
};


var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );



( function() {

	// Executing both pixelPosition & boxSizingReliable tests require only one layout
	// so they're executed at the same time to save the second computation.
	function computeStyleTests() {

		// This is a singleton, we need to execute it only once
		if ( !div ) {
			return;
		}

		container.style.cssText = "position:absolute;left:-11111px;width:60px;" +
			"margin-top:1px;padding:0;border:0";
		div.style.cssText =
			"position:relative;display:block;box-sizing:border-box;overflow:scroll;" +
			"margin:auto;border:1px;padding:1px;" +
			"width:60%;top:1%";
		documentElement.appendChild( container ).appendChild( div );

		var divStyle = window.getComputedStyle( div );
		pixelPositionVal = divStyle.top !== "1%";

		// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
		reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12;

		// Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
		// Some styles come back with percentage values, even though they shouldn't
		div.style.right = "60%";
		pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36;

		// Support: IE 9 - 11 only
		// Detect misreporting of content dimensions for box-sizing:border-box elements
		boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36;

		// Support: IE 9 only
		// Detect overflow:scroll screwiness (gh-3699)
		// Support: Chrome <=64
		// Don't get tricked when zoom affects offsetWidth (gh-4029)
		div.style.position = "absolute";
		scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12;

		documentElement.removeChild( container );

		// Nullify the div so it wouldn't be stored in the memory and
		// it will also be a sign that checks already performed
		div = null;
	}

	function roundPixelMeasures( measure ) {
		return Math.round( parseFloat( measure ) );
	}

	var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal,
		reliableTrDimensionsVal, reliableMarginLeftVal,
		container = document.createElement( "div" ),
		div = document.createElement( "div" );

	// Finish early in limited (non-browser) environments
	if ( !div.style ) {
		return;
	}

	// Support: IE <=9 - 11 only
	// Style of cloned element affects source element cloned (trac-8908)
	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	jQuery.extend( support, {
		boxSizingReliable: function() {
			computeStyleTests();
			return boxSizingReliableVal;
		},
		pixelBoxStyles: function() {
			computeStyleTests();
			return pixelBoxStylesVal;
		},
		pixelPosition: function() {
			computeStyleTests();
			return pixelPositionVal;
		},
		reliableMarginLeft: function() {
			computeStyleTests();
			return reliableMarginLeftVal;
		},
		scrollboxSize: function() {
			computeStyleTests();
			return scrollboxSizeVal;
		},

		// Support: IE 9 - 11+, Edge 15 - 18+
		// IE/Edge misreport `getComputedStyle` of table rows with width/height
		// set in CSS while `offset*` properties report correct values.
		// Behavior in IE 9 is more subtle than in newer versions & it passes
		// some versions of this test; make sure not to make it pass there!
		//
		// Support: Firefox 70+
		// Only Firefox includes border widths
		// in computed dimensions. (gh-4529)
		reliableTrDimensions: function() {
			var table, tr, trChild, trStyle;
			if ( reliableTrDimensionsVal == null ) {
				table = document.createElement( "table" );
				tr = document.createElement( "tr" );
				trChild = document.createElement( "div" );

				table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate";
				tr.style.cssText = "box-sizing:content-box;border:1px solid";

				// Support: Chrome 86+
				// Height set through cssText does not get applied.
				// Computed height then comes back as 0.
				tr.style.height = "1px";
				trChild.style.height = "9px";

				// Support: Android 8 Chrome 86+
				// In our bodyBackground.html iframe,
				// display for all div elements is set to "inline",
				// which causes a problem only in Android 8 Chrome 86.
				// Ensuring the div is `display: block`
				// gets around this issue.
				trChild.style.display = "block";

				documentElement
					.appendChild( table )
					.appendChild( tr )
					.appendChild( trChild );

				trStyle = window.getComputedStyle( tr );
				reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) +
					parseInt( trStyle.borderTopWidth, 10 ) +
					parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight;

				documentElement.removeChild( table );
			}
			return reliableTrDimensionsVal;
		}
	} );
} )();


function curCSS( elem, name, computed ) {
	var width, minWidth, maxWidth, ret,
		isCustomProp = rcustomProp.test( name ),

		// Support: Firefox 51+
		// Retrieving style before computed somehow
		// fixes an issue with getting wrong values
		// on detached elements
		style = elem.style;

	computed = computed || getStyles( elem );

	// getPropertyValue is needed for:
	//   .css('filter') (IE 9 only, trac-12537)
	//   .css('--customProperty) (gh-3144)
	if ( computed ) {

		// Support: IE <=9 - 11+
		// IE only supports `"float"` in `getPropertyValue`; in computed styles
		// it's only available as `"cssFloat"`. We no longer modify properties
		// sent to `.css()` apart from camelCasing, so we need to check both.
		// Normally, this would create difference in behavior: if
		// `getPropertyValue` returns an empty string, the value returned
		// by `.css()` would be `undefined`. This is usually the case for
		// disconnected elements. However, in IE even disconnected elements
		// with no styles return `"none"` for `getPropertyValue( "float" )`
		ret = computed.getPropertyValue( name ) || computed[ name ];

		if ( isCustomProp && ret ) {

			// Support: Firefox 105+, Chrome <=105+
			// Spec requires trimming whitespace for custom properties (gh-4926).
			// Firefox only trims leading whitespace. Chrome just collapses
			// both leading & trailing whitespace to a single space.
			//
			// Fall back to `undefined` if empty string returned.
			// This collapses a missing definition with property defined
			// and set to an empty string but there's no standard API
			// allowing us to differentiate them without a performance penalty
			// and returning `undefined` aligns with older jQuery.
			//
			// rtrimCSS treats U+000D CARRIAGE RETURN and U+000C FORM FEED
			// as whitespace while CSS does not, but this is not a problem
			// because CSS preprocessing replaces them with U+000A LINE FEED
			// (which *is* CSS whitespace)
			// https://www.w3.org/TR/css-syntax-3/#input-preprocessing
			ret = ret.replace( rtrimCSS, "$1" ) || undefined;
		}

		if ( ret === "" && !isAttached( elem ) ) {
			ret = jQuery.style( elem, name );
		}

		// A tribute to the "awesome hack by Dean Edwards"
		// Android Browser returns percentage for some values,
		// but width seems to be reliably pixels.
		// This is against the CSSOM draft spec:
		// https://drafts.csswg.org/cssom/#resolved-values
		if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) {

			// Remember the original values
			width = style.width;
			minWidth = style.minWidth;
			maxWidth = style.maxWidth;

			// Put in the new values to get a computed value out
			style.minWidth = style.maxWidth = style.width = ret;
			ret = computed.width;

			// Revert the changed values
			style.width = width;
			style.minWidth = minWidth;
			style.maxWidth = maxWidth;
		}
	}

	return ret !== undefined ?

		// Support: IE <=9 - 11 only
		// IE returns zIndex value as an integer.
		ret + "" :
		ret;
}


function addGetHookIf( conditionFn, hookFn ) {

	// Define the hook, we'll check on the first run if it's really needed.
	return {
		get: function() {
			if ( conditionFn() ) {

				// Hook not needed (or it's not possible to use it due
				// to missing dependency), remove it.
				delete this.get;
				return;
			}

			// Hook needed; redefine it so that the support test is not executed again.
			return ( this.get = hookFn ).apply( this, arguments );
		}
	};
}


var cssPrefixes = [ "Webkit", "Moz", "ms" ],
	emptyStyle = document.createElement( "div" ).style,
	vendorProps = {};

// Return a vendor-prefixed property or undefined
function vendorPropName( name ) {

	// Check for vendor prefixed names
	var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in emptyStyle ) {
			return name;
		}
	}
}

// Return a potentially-mapped jQuery.cssProps or vendor prefixed property
function finalPropName( name ) {
	var final = jQuery.cssProps[ name ] || vendorProps[ name ];

	if ( final ) {
		return final;
	}
	if ( name in emptyStyle ) {
		return name;
	}
	return vendorProps[ name ] = vendorPropName( name ) || name;
}


var

	// Swappable if display is none or starts with table
	// except "table", "table-cell", or "table-caption"
	// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	};

function setPositiveNumber( _elem, value, subtract ) {

	// Any relative (+/-) values have already been
	// normalized at this point
	var matches = rcssNum.exec( value );
	return matches ?

		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
		value;
}

function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) {
	var i = dimension === "width" ? 1 : 0,
		extra = 0,
		delta = 0,
		marginDelta = 0;

	// Adjustment may not be necessary
	if ( box === ( isBorderBox ? "border" : "content" ) ) {
		return 0;
	}

	for ( ; i < 4; i += 2 ) {

		// Both box models exclude margin
		// Count margin delta separately to only add it after scroll gutter adjustment.
		// This is needed to make negative margins work with `outerHeight( true )` (gh-3982).
		if ( box === "margin" ) {
			marginDelta += jQuery.css( elem, box + cssExpand[ i ], true, styles );
		}

		// If we get here with a content-box, we're seeking "padding" or "border" or "margin"
		if ( !isBorderBox ) {

			// Add padding
			delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );

			// For "border" or "margin", add border
			if ( box !== "padding" ) {
				delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );

			// But still keep track of it otherwise
			} else {
				extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}

		// If we get here with a border-box (content + padding + border), we're seeking "content" or
		// "padding" or "margin"
		} else {

			// For "content", subtract padding
			if ( box === "content" ) {
				delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
			}

			// For "content" or "padding", subtract border
			if ( box !== "margin" ) {
				delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		}
	}

	// Account for positive content-box scroll gutter when requested by providing computedVal
	if ( !isBorderBox && computedVal >= 0 ) {

		// offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
		// Assuming integer scroll gutter, subtract the rest and round down
		delta += Math.max( 0, Math.ceil(
			elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
			computedVal -
			delta -
			extra -
			0.5

		// If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter
		// Use an explicit zero to avoid NaN (gh-3964)
		) ) || 0;
	}

	return delta + marginDelta;
}

function getWidthOrHeight( elem, dimension, extra ) {

	// Start with computed style
	var styles = getStyles( elem ),

		// To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322).
		// Fake content-box until we know it's needed to know the true value.
		boxSizingNeeded = !support.boxSizingReliable() || extra,
		isBorderBox = boxSizingNeeded &&
			jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
		valueIsBorderBox = isBorderBox,

		val = curCSS( elem, dimension, styles ),
		offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 );

	// Support: Firefox <=54
	// Return a confounding non-pixel value or feign ignorance, as appropriate.
	if ( rnumnonpx.test( val ) ) {
		if ( !extra ) {
			return val;
		}
		val = "auto";
	}


	// Support: IE 9 - 11 only
	// Use offsetWidth/offsetHeight for when box sizing is unreliable.
	// In those cases, the computed value can be trusted to be border-box.
	if ( ( !support.boxSizingReliable() && isBorderBox ||

		// Support: IE 10 - 11+, Edge 15 - 18+
		// IE/Edge misreport `getComputedStyle` of table rows with width/height
		// set in CSS while `offset*` properties report correct values.
		// Interestingly, in some cases IE 9 doesn't suffer from this issue.
		!support.reliableTrDimensions() && nodeName( elem, "tr" ) ||

		// Fall back to offsetWidth/offsetHeight when value is "auto"
		// This happens for inline elements with no explicit setting (gh-3571)
		val === "auto" ||

		// Support: Android <=4.1 - 4.3 only
		// Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
		!parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) &&

		// Make sure the element is visible & connected
		elem.getClientRects().length ) {

		isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";

		// Where available, offsetWidth/offsetHeight approximate border box dimensions.
		// Where not available (e.g., SVG), assume unreliable box-sizing and interpret the
		// retrieved value as a content box dimension.
		valueIsBorderBox = offsetProp in elem;
		if ( valueIsBorderBox ) {
			val = elem[ offsetProp ];
		}
	}

	// Normalize "" and auto
	val = parseFloat( val ) || 0;

	// Adjust for the element's box model
	return ( val +
		boxModelAdjustment(
			elem,
			dimension,
			extra || ( isBorderBox ? "border" : "content" ),
			valueIsBorderBox,
			styles,

			// Provide the current computed size to request scroll gutter calculation (gh-3589)
			val
		)
	) + "px";
}

jQuery.extend( {

	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {

					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity" );
					return ret === "" ? "1" : ret;
				}
			}
		}
	},

	// Don't automatically add "px" to these possibly-unitless properties
	cssNumber: {
		animationIterationCount: true,
		aspectRatio: true,
		borderImageSlice: true,
		columnCount: true,
		flexGrow: true,
		flexShrink: true,
		fontWeight: true,
		gridArea: true,
		gridColumn: true,
		gridColumnEnd: true,
		gridColumnStart: true,
		gridRow: true,
		gridRowEnd: true,
		gridRowStart: true,
		lineHeight: true,
		opacity: true,
		order: true,
		orphans: true,
		scale: true,
		widows: true,
		zIndex: true,
		zoom: true,

		// SVG-related
		fillOpacity: true,
		floodOpacity: true,
		stopOpacity: true,
		strokeMiterlimit: true,
		strokeOpacity: true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {

		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, hooks,
			origName = camelCase( name ),
			isCustomProp = rcustomProp.test( name ),
			style = elem.style;

		// Make sure that we're working with the right name. We don't
		// want to query the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Gets hook for the prefixed version, then unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// Convert "+=" or "-=" to relative numbers (trac-7345)
			if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
				value = adjustCSS( elem, name, ret );

				// Fixes bug trac-9237
				type = "number";
			}

			// Make sure that null and NaN values aren't set (trac-7116)
			if ( value == null || value !== value ) {
				return;
			}

			// If a number was passed in, add the unit (except for certain CSS properties)
			// The isCustomProp check can be removed in jQuery 4.0 when we only auto-append
			// "px" to a few hardcoded values.
			if ( type === "number" && !isCustomProp ) {
				value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
			}

			// background-* props affect original clone's values
			if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
				style[ name ] = "inherit";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !( "set" in hooks ) ||
				( value = hooks.set( elem, value, extra ) ) !== undefined ) {

				if ( isCustomProp ) {
					style.setProperty( name, value );
				} else {
					style[ name ] = value;
				}
			}

		} else {

			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks &&
				( ret = hooks.get( elem, false, extra ) ) !== undefined ) {

				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra, styles ) {
		var val, num, hooks,
			origName = camelCase( name ),
			isCustomProp = rcustomProp.test( name );

		// Make sure that we're working with the right name. We don't
		// want to modify the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Try prefixed name followed by the unprefixed name
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks ) {
			val = hooks.get( elem, true, extra );
		}

		// Otherwise, if a way to get the computed value exists, use that
		if ( val === undefined ) {
			val = curCSS( elem, name, styles );
		}

		// Convert "normal" to computed value
		if ( val === "normal" && name in cssNormalTransform ) {
			val = cssNormalTransform[ name ];
		}

		// Make numeric if forced or a qualifier was provided and val looks numeric
		if ( extra === "" || extra ) {
			num = parseFloat( val );
			return extra === true || isFinite( num ) ? num || 0 : val;
		}

		return val;
	}
} );

jQuery.each( [ "height", "width" ], function( _i, dimension ) {
	jQuery.cssHooks[ dimension ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {

				// Certain elements can have dimension info if we invisibly show them
				// but it must have a current display style that would benefit
				return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&

					// Support: Safari 8+
					// Table columns in Safari have non-zero offsetWidth & zero
					// getBoundingClientRect().width unless display is changed.
					// Support: IE <=11 only
					// Running getBoundingClientRect on a disconnected node
					// in IE throws an error.
					( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
					swap( elem, cssShow, function() {
						return getWidthOrHeight( elem, dimension, extra );
					} ) :
					getWidthOrHeight( elem, dimension, extra );
			}
		},

		set: function( elem, value, extra ) {
			var matches,
				styles = getStyles( elem ),

				// Only read styles.position if the test has a chance to fail
				// to avoid forcing a reflow.
				scrollboxSizeBuggy = !support.scrollboxSize() &&
					styles.position === "absolute",

				// To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991)
				boxSizingNeeded = scrollboxSizeBuggy || extra,
				isBorderBox = boxSizingNeeded &&
					jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
				subtract = extra ?
					boxModelAdjustment(
						elem,
						dimension,
						extra,
						isBorderBox,
						styles
					) :
					0;

			// Account for unreliable border-box dimensions by comparing offset* to computed and
			// faking a content-box to get border and padding (gh-3699)
			if ( isBorderBox && scrollboxSizeBuggy ) {
				subtract -= Math.ceil(
					elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
					parseFloat( styles[ dimension ] ) -
					boxModelAdjustment( elem, dimension, "border", false, styles ) -
					0.5
				);
			}

			// Convert to pixels if value adjustment is needed
			if ( subtract && ( matches = rcssNum.exec( value ) ) &&
				( matches[ 3 ] || "px" ) !== "px" ) {

				elem.style[ dimension ] = value;
				value = jQuery.css( elem, dimension );
			}

			return setPositiveNumber( elem, value, subtract );
		}
	};
} );

jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
	function( elem, computed ) {
		if ( computed ) {
			return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
				elem.getBoundingClientRect().left -
					swap( elem, { marginLeft: 0 }, function() {
						return elem.getBoundingClientRect().left;
					} )
			) + "px";
		}
	}
);

// These hooks are used by animate to expand properties
jQuery.each( {
	margin: "",
	padding: "",
	border: "Width"
}, function( prefix, suffix ) {
	jQuery.cssHooks[ prefix + suffix ] = {
		expand: function( value ) {
			var i = 0,
				expanded = {},

				// Assumes a single number if not a string
				parts = typeof value === "string" ? value.split( " " ) : [ value ];

			for ( ; i < 4; i++ ) {
				expanded[ prefix + cssExpand[ i ] + suffix ] =
					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
			}

			return expanded;
		}
	};

	if ( prefix !== "margin" ) {
		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
	}
} );

jQuery.fn.extend( {
	css: function( name, value ) {
		return access( this, function( elem, name, value ) {
			var styles, len,
				map = {},
				i = 0;

			if ( Array.isArray( name ) ) {
				styles = getStyles( elem );
				len = name.length;

				for ( ; i < len; i++ ) {
					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
				}

				return map;
			}

			return value !== undefined ?
				jQuery.style( elem, name, value ) :
				jQuery.css( elem, name );
		}, name, value, arguments.length > 1 );
	}
} );


function Tween( elem, options, prop, end, easing ) {
	return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;

Tween.prototype = {
	constructor: Tween,
	init: function( elem, options, prop, end, easing, unit ) {
		this.elem = elem;
		this.prop = prop;
		this.easing = easing || jQuery.easing._default;
		this.options = options;
		this.start = this.now = this.cur();
		this.end = end;
		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
	},
	cur: function() {
		var hooks = Tween.propHooks[ this.prop ];

		return hooks && hooks.get ?
			hooks.get( this ) :
			Tween.propHooks._default.get( this );
	},
	run: function( percent ) {
		var eased,
			hooks = Tween.propHooks[ this.prop ];

		if ( this.options.duration ) {
			this.pos = eased = jQuery.easing[ this.easing ](
				percent, this.options.duration * percent, 0, 1, this.options.duration
			);
		} else {
			this.pos = eased = percent;
		}
		this.now = ( this.end - this.start ) * eased + this.start;

		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		if ( hooks && hooks.set ) {
			hooks.set( this );
		} else {
			Tween.propHooks._default.set( this );
		}
		return this;
	}
};

Tween.prototype.init.prototype = Tween.prototype;

Tween.propHooks = {
	_default: {
		get: function( tween ) {
			var result;

			// Use a property on the element directly when it is not a DOM element,
			// or when there is no matching style property that exists.
			if ( tween.elem.nodeType !== 1 ||
				tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
				return tween.elem[ tween.prop ];
			}

			// Passing an empty string as a 3rd parameter to .css will automatically
			// attempt a parseFloat and fallback to a string if the parse fails.
			// Simple values such as "10px" are parsed to Float;
			// complex values such as "rotate(1rad)" are returned as-is.
			result = jQuery.css( tween.elem, tween.prop, "" );

			// Empty strings, null, undefined and "auto" are converted to 0.
			return !result || result === "auto" ? 0 : result;
		},
		set: function( tween ) {

			// Use step hook for back compat.
			// Use cssHook if its there.
			// Use .style if available and use plain properties where available.
			if ( jQuery.fx.step[ tween.prop ] ) {
				jQuery.fx.step[ tween.prop ]( tween );
			} else if ( tween.elem.nodeType === 1 && (
				jQuery.cssHooks[ tween.prop ] ||
					tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) {
				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
			} else {
				tween.elem[ tween.prop ] = tween.now;
			}
		}
	}
};

// Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
	set: function( tween ) {
		if ( tween.elem.nodeType && tween.elem.parentNode ) {
			tween.elem[ tween.prop ] = tween.now;
		}
	}
};

jQuery.easing = {
	linear: function( p ) {
		return p;
	},
	swing: function( p ) {
		return 0.5 - Math.cos( p * Math.PI ) / 2;
	},
	_default: "swing"
};

jQuery.fx = Tween.prototype.init;

// Back compat <1.8 extension point
jQuery.fx.step = {};




var
	fxNow, inProgress,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rrun = /queueHooks$/;

function schedule() {
	if ( inProgress ) {
		if ( document.hidden === false && window.requestAnimationFrame ) {
			window.requestAnimationFrame( schedule );
		} else {
			window.setTimeout( schedule, jQuery.fx.interval );
		}

		jQuery.fx.tick();
	}
}

// Animations created synchronously will run synchronously
function createFxNow() {
	window.setTimeout( function() {
		fxNow = undefined;
	} );
	return ( fxNow = Date.now() );
}

// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
	var which,
		i = 0,
		attrs = { height: type };

	// If we include width, step value is 1 to do all cssExpand values,
	// otherwise step value is 2 to skip over Left and Right
	includeWidth = includeWidth ? 1 : 0;
	for ( ; i < 4; i += 2 - includeWidth ) {
		which = cssExpand[ i ];
		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
	}

	if ( includeWidth ) {
		attrs.opacity = attrs.width = type;
	}

	return attrs;
}

function createTween( value, prop, animation ) {
	var tween,
		collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
		index = 0,
		length = collection.length;
	for ( ; index < length; index++ ) {
		if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {

			// We're done with this property
			return tween;
		}
	}
}

function defaultPrefilter( elem, props, opts ) {
	var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
		isBox = "width" in props || "height" in props,
		anim = this,
		orig = {},
		style = elem.style,
		hidden = elem.nodeType && isHiddenWithinTree( elem ),
		dataShow = dataPriv.get( elem, "fxshow" );

	// Queue-skipping animations hijack the fx hooks
	if ( !opts.queue ) {
		hooks = jQuery._queueHooks( elem, "fx" );
		if ( hooks.unqueued == null ) {
			hooks.unqueued = 0;
			oldfire = hooks.empty.fire;
			hooks.empty.fire = function() {
				if ( !hooks.unqueued ) {
					oldfire();
				}
			};
		}
		hooks.unqueued++;

		anim.always( function() {

			// Ensure the complete handler is called before this completes
			anim.always( function() {
				hooks.unqueued--;
				if ( !jQuery.queue( elem, "fx" ).length ) {
					hooks.empty.fire();
				}
			} );
		} );
	}

	// Detect show/hide animations
	for ( prop in props ) {
		value = props[ prop ];
		if ( rfxtypes.test( value ) ) {
			delete props[ prop ];
			toggle = toggle || value === "toggle";
			if ( value === ( hidden ? "hide" : "show" ) ) {

				// Pretend to be hidden if this is a "show" and
				// there is still data from a stopped show/hide
				if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
					hidden = true;

				// Ignore all other no-op show/hide data
				} else {
					continue;
				}
			}
			orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
		}
	}

	// Bail out if this is a no-op like .hide().hide()
	propTween = !jQuery.isEmptyObject( props );
	if ( !propTween && jQuery.isEmptyObject( orig ) ) {
		return;
	}

	// Restrict "overflow" and "display" styles during box animations
	if ( isBox && elem.nodeType === 1 ) {

		// Support: IE <=9 - 11, Edge 12 - 15
		// Record all 3 overflow attributes because IE does not infer the shorthand
		// from identically-valued overflowX and overflowY and Edge just mirrors
		// the overflowX value there.
		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];

		// Identify a display type, preferring old show/hide data over the CSS cascade
		restoreDisplay = dataShow && dataShow.display;
		if ( restoreDisplay == null ) {
			restoreDisplay = dataPriv.get( elem, "display" );
		}
		display = jQuery.css( elem, "display" );
		if ( display === "none" ) {
			if ( restoreDisplay ) {
				display = restoreDisplay;
			} else {

				// Get nonempty value(s) by temporarily forcing visibility
				showHide( [ elem ], true );
				restoreDisplay = elem.style.display || restoreDisplay;
				display = jQuery.css( elem, "display" );
				showHide( [ elem ] );
			}
		}

		// Animate inline elements as inline-block
		if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
			if ( jQuery.css( elem, "float" ) === "none" ) {

				// Restore the original display value at the end of pure show/hide animations
				if ( !propTween ) {
					anim.done( function() {
						style.display = restoreDisplay;
					} );
					if ( restoreDisplay == null ) {
						display = style.display;
						restoreDisplay = display === "none" ? "" : display;
					}
				}
				style.display = "inline-block";
			}
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		anim.always( function() {
			style.overflow = opts.overflow[ 0 ];
			style.overflowX = opts.overflow[ 1 ];
			style.overflowY = opts.overflow[ 2 ];
		} );
	}

	// Implement show/hide animations
	propTween = false;
	for ( prop in orig ) {

		// General show/hide setup for this element animation
		if ( !propTween ) {
			if ( dataShow ) {
				if ( "hidden" in dataShow ) {
					hidden = dataShow.hidden;
				}
			} else {
				dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
			}

			// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
			if ( toggle ) {
				dataShow.hidden = !hidden;
			}

			// Show elements before animating them
			if ( hidden ) {
				showHide( [ elem ], true );
			}

			/* eslint-disable no-loop-func */

			anim.done( function() {

				/* eslint-enable no-loop-func */

				// The final step of a "hide" animation is actually hiding the element
				if ( !hidden ) {
					showHide( [ elem ] );
				}
				dataPriv.remove( elem, "fxshow" );
				for ( prop in orig ) {
					jQuery.style( elem, prop, orig[ prop ] );
				}
			} );
		}

		// Per-property setup
		propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
		if ( !( prop in dataShow ) ) {
			dataShow[ prop ] = propTween.start;
			if ( hidden ) {
				propTween.end = propTween.start;
				propTween.start = 0;
			}
		}
	}
}

function propFilter( props, specialEasing ) {
	var index, name, easing, value, hooks;

	// camelCase, specialEasing and expand cssHook pass
	for ( index in props ) {
		name = camelCase( index );
		easing = specialEasing[ name ];
		value = props[ index ];
		if ( Array.isArray( value ) ) {
			easing = value[ 1 ];
			value = props[ index ] = value[ 0 ];
		}

		if ( index !== name ) {
			props[ name ] = value;
			delete props[ index ];
		}

		hooks = jQuery.cssHooks[ name ];
		if ( hooks && "expand" in hooks ) {
			value = hooks.expand( value );
			delete props[ name ];

			// Not quite $.extend, this won't overwrite existing keys.
			// Reusing 'index' because we have the correct "name"
			for ( index in value ) {
				if ( !( index in props ) ) {
					props[ index ] = value[ index ];
					specialEasing[ index ] = easing;
				}
			}
		} else {
			specialEasing[ name ] = easing;
		}
	}
}

function Animation( elem, properties, options ) {
	var result,
		stopped,
		index = 0,
		length = Animation.prefilters.length,
		deferred = jQuery.Deferred().always( function() {

			// Don't match elem in the :animated selector
			delete tick.elem;
		} ),
		tick = function() {
			if ( stopped ) {
				return false;
			}
			var currentTime = fxNow || createFxNow(),
				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),

				// Support: Android 2.3 only
				// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (trac-12497)
				temp = remaining / animation.duration || 0,
				percent = 1 - temp,
				index = 0,
				length = animation.tweens.length;

			for ( ; index < length; index++ ) {
				animation.tweens[ index ].run( percent );
			}

			deferred.notifyWith( elem, [ animation, percent, remaining ] );

			// If there's more to do, yield
			if ( percent < 1 && length ) {
				return remaining;
			}

			// If this was an empty animation, synthesize a final progress notification
			if ( !length ) {
				deferred.notifyWith( elem, [ animation, 1, 0 ] );
			}

			// Resolve the animation and report its conclusion
			deferred.resolveWith( elem, [ animation ] );
			return false;
		},
		animation = deferred.promise( {
			elem: elem,
			props: jQuery.extend( {}, properties ),
			opts: jQuery.extend( true, {
				specialEasing: {},
				easing: jQuery.easing._default
			}, options ),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function( prop, end ) {
				var tween = jQuery.Tween( elem, animation.opts, prop, end,
					animation.opts.specialEasing[ prop ] || animation.opts.easing );
				animation.tweens.push( tween );
				return tween;
			},
			stop: function( gotoEnd ) {
				var index = 0,

					// If we are going to the end, we want to run all the tweens
					// otherwise we skip this part
					length = gotoEnd ? animation.tweens.length : 0;
				if ( stopped ) {
					return this;
				}
				stopped = true;
				for ( ; index < length; index++ ) {
					animation.tweens[ index ].run( 1 );
				}

				// Resolve when we played the last frame; otherwise, reject
				if ( gotoEnd ) {
					deferred.notifyWith( elem, [ animation, 1, 0 ] );
					deferred.resolveWith( elem, [ animation, gotoEnd ] );
				} else {
					deferred.rejectWith( elem, [ animation, gotoEnd ] );
				}
				return this;
			}
		} ),
		props = animation.props;

	propFilter( props, animation.opts.specialEasing );

	for ( ; index < length; index++ ) {
		result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
		if ( result ) {
			if ( isFunction( result.stop ) ) {
				jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
					result.stop.bind( result );
			}
			return result;
		}
	}

	jQuery.map( props, createTween, animation );

	if ( isFunction( animation.opts.start ) ) {
		animation.opts.start.call( elem, animation );
	}

	// Attach callbacks from options
	animation
		.progress( animation.opts.progress )
		.done( animation.opts.done, animation.opts.complete )
		.fail( animation.opts.fail )
		.always( animation.opts.always );

	jQuery.fx.timer(
		jQuery.extend( tick, {
			elem: elem,
			anim: animation,
			queue: animation.opts.queue
		} )
	);

	return animation;
}

jQuery.Animation = jQuery.extend( Animation, {

	tweeners: {
		"*": [ function( prop, value ) {
			var tween = this.createTween( prop, value );
			adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
			return tween;
		} ]
	},

	tweener: function( props, callback ) {
		if ( isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.match( rnothtmlwhite );
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length; index++ ) {
			prop = props[ index ];
			Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
			Animation.tweeners[ prop ].unshift( callback );
		}
	},

	prefilters: [ defaultPrefilter ],

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			Animation.prefilters.unshift( callback );
		} else {
			Animation.prefilters.push( callback );
		}
	}
} );

jQuery.speed = function( speed, easing, fn ) {
	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
		complete: fn || !fn && easing ||
			isFunction( speed ) && speed,
		duration: speed,
		easing: fn && easing || easing && !isFunction( easing ) && easing
	};

	// Go to the end state if fx are off
	if ( jQuery.fx.off ) {
		opt.duration = 0;

	} else {
		if ( typeof opt.duration !== "number" ) {
			if ( opt.duration in jQuery.fx.speeds ) {
				opt.duration = jQuery.fx.speeds[ opt.duration ];

			} else {
				opt.duration = jQuery.fx.speeds._default;
			}
		}
	}

	// Normalize opt.queue - true/undefined/null -> "fx"
	if ( opt.queue == null || opt.queue === true ) {
		opt.queue = "fx";
	}

	// Queueing
	opt.old = opt.complete;

	opt.complete = function() {
		if ( isFunction( opt.old ) ) {
			opt.old.call( this );
		}

		if ( opt.queue ) {
			jQuery.dequeue( this, opt.queue );
		}
	};

	return opt;
};

jQuery.fn.extend( {
	fadeTo: function( speed, to, easing, callback ) {

		// Show any hidden elements after setting opacity to 0
		return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()

			// Animate to the value specified
			.end().animate( { opacity: to }, speed, easing, callback );
	},
	animate: function( prop, speed, easing, callback ) {
		var empty = jQuery.isEmptyObject( prop ),
			optall = jQuery.speed( speed, easing, callback ),
			doAnimation = function() {

				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation( this, jQuery.extend( {}, prop ), optall );

				// Empty animations, or finishing resolves immediately
				if ( empty || dataPriv.get( this, "finish" ) ) {
					anim.stop( true );
				}
			};

		doAnimation.finish = doAnimation;

		return empty || optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},
	stop: function( type, clearQueue, gotoEnd ) {
		var stopQueue = function( hooks ) {
			var stop = hooks.stop;
			delete hooks.stop;
			stop( gotoEnd );
		};

		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue ) {
			this.queue( type || "fx", [] );
		}

		return this.each( function() {
			var dequeue = true,
				index = type != null && type + "queueHooks",
				timers = jQuery.timers,
				data = dataPriv.get( this );

			if ( index ) {
				if ( data[ index ] && data[ index ].stop ) {
					stopQueue( data[ index ] );
				}
			} else {
				for ( index in data ) {
					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
						stopQueue( data[ index ] );
					}
				}
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this &&
					( type == null || timers[ index ].queue === type ) ) {

					timers[ index ].anim.stop( gotoEnd );
					dequeue = false;
					timers.splice( index, 1 );
				}
			}

			// Start the next in the queue if the last step wasn't forced.
			// Timers currently will call their complete callbacks, which
			// will dequeue but only if they were gotoEnd.
			if ( dequeue || !gotoEnd ) {
				jQuery.dequeue( this, type );
			}
		} );
	},
	finish: function( type ) {
		if ( type !== false ) {
			type = type || "fx";
		}
		return this.each( function() {
			var index,
				data = dataPriv.get( this ),
				queue = data[ type + "queue" ],
				hooks = data[ type + "queueHooks" ],
				timers = jQuery.timers,
				length = queue ? queue.length : 0;

			// Enable finishing flag on private data
			data.finish = true;

			// Empty the queue first
			jQuery.queue( this, type, [] );

			if ( hooks && hooks.stop ) {
				hooks.stop.call( this, true );
			}

			// Look for any active animations, and finish them
			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
					timers[ index ].anim.stop( true );
					timers.splice( index, 1 );
				}
			}

			// Look for any animations in the old queue and finish them
			for ( index = 0; index < length; index++ ) {
				if ( queue[ index ] && queue[ index ].finish ) {
					queue[ index ].finish.call( this );
				}
			}

			// Turn off finishing flag
			delete data.finish;
		} );
	}
} );

jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) {
	var cssFn = jQuery.fn[ name ];
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return speed == null || typeof speed === "boolean" ?
			cssFn.apply( this, arguments ) :
			this.animate( genFx( name, true ), speed, easing, callback );
	};
} );

// Generate shortcuts for custom animations
jQuery.each( {
	slideDown: genFx( "show" ),
	slideUp: genFx( "hide" ),
	slideToggle: genFx( "toggle" ),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
} );

jQuery.timers = [];
jQuery.fx.tick = function() {
	var timer,
		i = 0,
		timers = jQuery.timers;

	fxNow = Date.now();

	for ( ; i < timers.length; i++ ) {
		timer = timers[ i ];

		// Run the timer and safely remove it when done (allowing for external removal)
		if ( !timer() && timers[ i ] === timer ) {
			timers.splice( i--, 1 );
		}
	}

	if ( !timers.length ) {
		jQuery.fx.stop();
	}
	fxNow = undefined;
};

jQuery.fx.timer = function( timer ) {
	jQuery.timers.push( timer );
	jQuery.fx.start();
};

jQuery.fx.interval = 13;
jQuery.fx.start = function() {
	if ( inProgress ) {
		return;
	}

	inProgress = true;
	schedule();
};

jQuery.fx.stop = function() {
	inProgress = null;
};

jQuery.fx.speeds = {
	slow: 600,
	fast: 200,

	// Default speed
	_default: 400
};


// Based off of the plugin by Clint Helfers, with permission.
jQuery.fn.delay = function( time, type ) {
	time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
	type = type || "fx";

	return this.queue( type, function( next, hooks ) {
		var timeout = window.setTimeout( next, time );
		hooks.stop = function() {
			window.clearTimeout( timeout );
		};
	} );
};


( function() {
	var input = document.createElement( "input" ),
		select = document.createElement( "select" ),
		opt = select.appendChild( document.createElement( "option" ) );

	input.type = "checkbox";

	// Support: Android <=4.3 only
	// Default value for a checkbox should be "on"
	support.checkOn = input.value !== "";

	// Support: IE <=11 only
	// Must access selectedIndex to make default options select
	support.optSelected = opt.selected;

	// Support: IE <=11 only
	// An input loses its value after becoming a radio
	input = document.createElement( "input" );
	input.value = "t";
	input.type = "radio";
	support.radioValue = input.value === "t";
} )();


var boolHook,
	attrHandle = jQuery.expr.attrHandle;

jQuery.fn.extend( {
	attr: function( name, value ) {
		return access( this, jQuery.attr, name, value, arguments.length > 1 );
	},

	removeAttr: function( name ) {
		return this.each( function() {
			jQuery.removeAttr( this, name );
		} );
	}
} );

jQuery.extend( {
	attr: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set attributes on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === "undefined" ) {
			return jQuery.prop( elem, name, value );
		}

		// Attribute hooks are determined by the lowercase version
		// Grab necessary hook if one is defined
		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
			hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
				( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
		}

		if ( value !== undefined ) {
			if ( value === null ) {
				jQuery.removeAttr( elem, name );
				return;
			}

			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			elem.setAttribute( name, value + "" );
			return value;
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		ret = jQuery.find.attr( elem, name );

		// Non-existent attributes return null, we normalize to undefined
		return ret == null ? undefined : ret;
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				if ( !support.radioValue && value === "radio" &&
					nodeName( elem, "input" ) ) {
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		}
	},

	removeAttr: function( elem, value ) {
		var name,
			i = 0,

			// Attribute names can contain non-HTML whitespace characters
			// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
			attrNames = value && value.match( rnothtmlwhite );

		if ( attrNames && elem.nodeType === 1 ) {
			while ( ( name = attrNames[ i++ ] ) ) {
				elem.removeAttribute( name );
			}
		}
	}
} );

// Hooks for boolean attributes
boolHook = {
	set: function( elem, value, name ) {
		if ( value === false ) {

			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else {
			elem.setAttribute( name, name );
		}
		return name;
	}
};

jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) {
	var getter = attrHandle[ name ] || jQuery.find.attr;

	attrHandle[ name ] = function( elem, name, isXML ) {
		var ret, handle,
			lowercaseName = name.toLowerCase();

		if ( !isXML ) {

			// Avoid an infinite loop by temporarily removing this function from the getter
			handle = attrHandle[ lowercaseName ];
			attrHandle[ lowercaseName ] = ret;
			ret = getter( elem, name, isXML ) != null ?
				lowercaseName :
				null;
			attrHandle[ lowercaseName ] = handle;
		}
		return ret;
	};
} );




var rfocusable = /^(?:input|select|textarea|button)$/i,
	rclickable = /^(?:a|area)$/i;

jQuery.fn.extend( {
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length > 1 );
	},

	removeProp: function( name ) {
		return this.each( function() {
			delete this[ jQuery.propFix[ name ] || name ];
		} );
	}
} );

jQuery.extend( {
	prop: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set properties on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {

			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			return ( elem[ name ] = value );
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		return elem[ name ];
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {

				// Support: IE <=9 - 11 only
				// elem.tabIndex doesn't always return the
				// correct value when it hasn't been explicitly set
				// Use proper attribute retrieval (trac-12072)
				var tabindex = jQuery.find.attr( elem, "tabindex" );

				if ( tabindex ) {
					return parseInt( tabindex, 10 );
				}

				if (
					rfocusable.test( elem.nodeName ) ||
					rclickable.test( elem.nodeName ) &&
					elem.href
				) {
					return 0;
				}

				return -1;
			}
		}
	},

	propFix: {
		"for": "htmlFor",
		"class": "className"
	}
} );

// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if ( !support.optSelected ) {
	jQuery.propHooks.selected = {
		get: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent && parent.parentNode ) {
				parent.parentNode.selectedIndex;
			}
			return null;
		},
		set: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent ) {
				parent.selectedIndex;

				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
		}
	};
}

jQuery.each( [
	"tabIndex",
	"readOnly",
	"maxLength",
	"cellSpacing",
	"cellPadding",
	"rowSpan",
	"colSpan",
	"useMap",
	"frameBorder",
	"contentEditable"
], function() {
	jQuery.propFix[ this.toLowerCase() ] = this;
} );




	// Strip and collapse whitespace according to HTML spec
	// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
	function stripAndCollapse( value ) {
		var tokens = value.match( rnothtmlwhite ) || [];
		return tokens.join( " " );
	}


function getClass( elem ) {
	return elem.getAttribute && elem.getAttribute( "class" ) || "";
}

function classesToArray( value ) {
	if ( Array.isArray( value ) ) {
		return value;
	}
	if ( typeof value === "string" ) {
		return value.match( rnothtmlwhite ) || [];
	}
	return [];
}

jQuery.fn.extend( {
	addClass: function( value ) {
		var classNames, cur, curValue, className, i, finalValue;

		if ( isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		classNames = classesToArray( value );

		if ( classNames.length ) {
			return this.each( function() {
				curValue = getClass( this );
				cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					for ( i = 0; i < classNames.length; i++ ) {
						className = classNames[ i ];
						if ( cur.indexOf( " " + className + " " ) < 0 ) {
							cur += className + " ";
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						this.setAttribute( "class", finalValue );
					}
				}
			} );
		}

		return this;
	},

	removeClass: function( value ) {
		var classNames, cur, curValue, className, i, finalValue;

		if ( isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( !arguments.length ) {
			return this.attr( "class", "" );
		}

		classNames = classesToArray( value );

		if ( classNames.length ) {
			return this.each( function() {
				curValue = getClass( this );

				// This expression is here for better compressibility (see addClass)
				cur = this.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					for ( i = 0; i < classNames.length; i++ ) {
						className = classNames[ i ];

						// Remove *all* instances
						while ( cur.indexOf( " " + className + " " ) > -1 ) {
							cur = cur.replace( " " + className + " ", " " );
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						this.setAttribute( "class", finalValue );
					}
				}
			} );
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var classNames, className, i, self,
			type = typeof value,
			isValidValue = type === "string" || Array.isArray( value );

		if ( isFunction( value ) ) {
			return this.each( function( i ) {
				jQuery( this ).toggleClass(
					value.call( this, i, getClass( this ), stateVal ),
					stateVal
				);
			} );
		}

		if ( typeof stateVal === "boolean" && isValidValue ) {
			return stateVal ? this.addClass( value ) : this.removeClass( value );
		}

		classNames = classesToArray( value );

		return this.each( function() {
			if ( isValidValue ) {

				// Toggle individual class names
				self = jQuery( this );

				for ( i = 0; i < classNames.length; i++ ) {
					className = classNames[ i ];

					// Check each className given, space separated list
					if ( self.hasClass( className ) ) {
						self.removeClass( className );
					} else {
						self.addClass( className );
					}
				}

			// Toggle whole class name
			} else if ( value === undefined || type === "boolean" ) {
				className = getClass( this );
				if ( className ) {

					// Store className if set
					dataPriv.set( this, "__className__", className );
				}

				// If the element has a class name or if we're passed `false`,
				// then remove the whole classname (if there was one, the above saved it).
				// Otherwise bring back whatever was previously saved (if anything),
				// falling back to the empty string if nothing was stored.
				if ( this.setAttribute ) {
					this.setAttribute( "class",
						className || value === false ?
							"" :
							dataPriv.get( this, "__className__" ) || ""
					);
				}
			}
		} );
	},

	hasClass: function( selector ) {
		var className, elem,
			i = 0;

		className = " " + selector + " ";
		while ( ( elem = this[ i++ ] ) ) {
			if ( elem.nodeType === 1 &&
				( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
				return true;
			}
		}

		return false;
	}
} );




var rreturn = /\r/g;

jQuery.fn.extend( {
	val: function( value ) {
		var hooks, ret, valueIsFunction,
			elem = this[ 0 ];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.type ] ||
					jQuery.valHooks[ elem.nodeName.toLowerCase() ];

				if ( hooks &&
					"get" in hooks &&
					( ret = hooks.get( elem, "value" ) ) !== undefined
				) {
					return ret;
				}

				ret = elem.value;

				// Handle most common string cases
				if ( typeof ret === "string" ) {
					return ret.replace( rreturn, "" );
				}

				// Handle cases where value is null/undef or number
				return ret == null ? "" : ret;
			}

			return;
		}

		valueIsFunction = isFunction( value );

		return this.each( function( i ) {
			var val;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( valueIsFunction ) {
				val = value.call( this, i, jQuery( this ).val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";

			} else if ( typeof val === "number" ) {
				val += "";

			} else if ( Array.isArray( val ) ) {
				val = jQuery.map( val, function( value ) {
					return value == null ? "" : value + "";
				} );
			}

			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		} );
	}
} );

jQuery.extend( {
	valHooks: {
		option: {
			get: function( elem ) {

				var val = jQuery.find.attr( elem, "value" );
				return val != null ?
					val :

					// Support: IE <=10 - 11 only
					// option.text throws exceptions (trac-14686, trac-14858)
					// Strip and collapse whitespace
					// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
					stripAndCollapse( jQuery.text( elem ) );
			}
		},
		select: {
			get: function( elem ) {
				var value, option, i,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one",
					values = one ? null : [],
					max = one ? index + 1 : options.length;

				if ( index < 0 ) {
					i = max;

				} else {
					i = one ? index : 0;
				}

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// Support: IE <=9 only
					// IE8-9 doesn't update selected after form reset (trac-2551)
					if ( ( option.selected || i === index ) &&

							// Don't return options that are disabled or in a disabled optgroup
							!option.disabled &&
							( !option.parentNode.disabled ||
								!nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var optionSet, option,
					options = elem.options,
					values = jQuery.makeArray( value ),
					i = options.length;

				while ( i-- ) {
					option = options[ i ];

					/* eslint-disable no-cond-assign */

					if ( option.selected =
						jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
					) {
						optionSet = true;
					}

					/* eslint-enable no-cond-assign */
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	}
} );

// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = {
		set: function( elem, value ) {
			if ( Array.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
			}
		}
	};
	if ( !support.checkOn ) {
		jQuery.valHooks[ this ].get = function( elem ) {
			return elem.getAttribute( "value" ) === null ? "on" : elem.value;
		};
	}
} );




// Return jQuery for attributes-only inclusion
var location = window.location;

var nonce = { guid: Date.now() };

var rquery = ( /\?/ );



// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
	var xml, parserErrorElem;
	if ( !data || typeof data !== "string" ) {
		return null;
	}

	// Support: IE 9 - 11 only
	// IE throws on parseFromString with invalid input.
	try {
		xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
	} catch ( e ) {}

	parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ];
	if ( !xml || parserErrorElem ) {
		jQuery.error( "Invalid XML: " + (
			parserErrorElem ?
				jQuery.map( parserErrorElem.childNodes, function( el ) {
					return el.textContent;
				} ).join( "\n" ) :
				data
		) );
	}
	return xml;
};


var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
	stopPropagationCallback = function( e ) {
		e.stopPropagation();
	};

jQuery.extend( jQuery.event, {

	trigger: function( event, data, elem, onlyHandlers ) {

		var i, cur, tmp, bubbleType, ontype, handle, special, lastElement,
			eventPath = [ elem || document ],
			type = hasOwn.call( event, "type" ) ? event.type : event,
			namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];

		cur = lastElement = tmp = elem = elem || document;

		// Don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf( "." ) > -1 ) {

			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split( "." );
			type = namespaces.shift();
			namespaces.sort();
		}
		ontype = type.indexOf( ":" ) < 0 && "on" + type;

		// Caller can pass in a jQuery.Event object, Object, or just an event type string
		event = event[ jQuery.expando ] ?
			event :
			new jQuery.Event( type, typeof event === "object" && event );

		// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
		event.isTrigger = onlyHandlers ? 2 : 3;
		event.namespace = namespaces.join( "." );
		event.rnamespace = event.namespace ?
			new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
			null;

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data == null ?
			[ event ] :
			jQuery.makeArray( data, [ event ] );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (trac-9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (trac-9724)
		if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			if ( !rfocusMorph.test( bubbleType + type ) ) {
				cur = cur.parentNode;
			}
			for ( ; cur; cur = cur.parentNode ) {
				eventPath.push( cur );
				tmp = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( tmp === ( elem.ownerDocument || document ) ) {
				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
			}
		}

		// Fire handlers on the event path
		i = 0;
		while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
			lastElement = cur;
			event.type = i > 1 ?
				bubbleType :
				special.bindType || type;

			// jQuery handler
			handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] &&
				dataPriv.get( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}

			// Native handler
			handle = ontype && cur[ ontype ];
			if ( handle && handle.apply && acceptData( cur ) ) {
				event.result = handle.apply( cur, data );
				if ( event.result === false ) {
					event.preventDefault();
				}
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers && !event.isDefaultPrevented() ) {

			if ( ( !special._default ||
				special._default.apply( eventPath.pop(), data ) === false ) &&
				acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name as the event.
				// Don't do default actions on window, that's where global variables be (trac-6170)
				if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					tmp = elem[ ontype ];

					if ( tmp ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;

					if ( event.isPropagationStopped() ) {
						lastElement.addEventListener( type, stopPropagationCallback );
					}

					elem[ type ]();

					if ( event.isPropagationStopped() ) {
						lastElement.removeEventListener( type, stopPropagationCallback );
					}

					jQuery.event.triggered = undefined;

					if ( tmp ) {
						elem[ ontype ] = tmp;
					}
				}
			}
		}

		return event.result;
	},

	// Piggyback on a donor event to simulate a different one
	// Used only for `focus(in | out)` events
	simulate: function( type, elem, event ) {
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{
				type: type,
				isSimulated: true
			}
		);

		jQuery.event.trigger( e, null, elem );
	}

} );

jQuery.fn.extend( {

	trigger: function( type, data ) {
		return this.each( function() {
			jQuery.event.trigger( type, data, this );
		} );
	},
	triggerHandler: function( type, data ) {
		var elem = this[ 0 ];
		if ( elem ) {
			return jQuery.event.trigger( type, data, elem, true );
		}
	}
} );


var
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	rsubmittable = /^(?:input|select|textarea|keygen)/i;

function buildParams( prefix, obj, traditional, add ) {
	var name;

	if ( Array.isArray( obj ) ) {

		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {

				// Treat each array item as a scalar.
				add( prefix, v );

			} else {

				// Item is non-scalar (array or object), encode its numeric index.
				buildParams(
					prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
					v,
					traditional,
					add
				);
			}
		} );

	} else if ( !traditional && toType( obj ) === "object" ) {

		// Serialize object item.
		for ( name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {

		// Serialize scalar item.
		add( prefix, obj );
	}
}

// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
	var prefix,
		s = [],
		add = function( key, valueOrFunction ) {

			// If value is a function, invoke it and use its return value
			var value = isFunction( valueOrFunction ) ?
				valueOrFunction() :
				valueOrFunction;

			s[ s.length ] = encodeURIComponent( key ) + "=" +
				encodeURIComponent( value == null ? "" : value );
		};

	if ( a == null ) {
		return "";
	}

	// If an array was passed in, assume that it is an array of form elements.
	if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {

		// Serialize the form elements
		jQuery.each( a, function() {
			add( this.name, this.value );
		} );

	} else {

		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( prefix in a ) {
			buildParams( prefix, a[ prefix ], traditional, add );
		}
	}

	// Return the resulting serialization
	return s.join( "&" );
};

jQuery.fn.extend( {
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map( function() {

			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		} ).filter( function() {
			var type = this.type;

			// Use .is( ":disabled" ) so that fieldset[disabled] works
			return this.name && !jQuery( this ).is( ":disabled" ) &&
				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
				( this.checked || !rcheckableType.test( type ) );
		} ).map( function( _i, elem ) {
			var val = jQuery( this ).val();

			if ( val == null ) {
				return null;
			}

			if ( Array.isArray( val ) ) {
				return jQuery.map( val, function( val ) {
					return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
				} );
			}

			return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		} ).get();
	}
} );


var
	r20 = /%20/g,
	rhash = /#.*$/,
	rantiCache = /([?&])_=[^&]*/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,

	// trac-7653, trac-8125, trac-8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression
	allTypes = "*/".concat( "*" ),

	// Anchor tag for parsing the document origin
	originAnchor = document.createElement( "a" );

originAnchor.href = location.href;

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		var dataType,
			i = 0,
			dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];

		if ( isFunction( func ) ) {

			// For each dataType in the dataTypeExpression
			while ( ( dataType = dataTypes[ i++ ] ) ) {

				// Prepend if requested
				if ( dataType[ 0 ] === "+" ) {
					dataType = dataType.slice( 1 ) || "*";
					( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );

				// Otherwise append
				} else {
					( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
				}
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {

	var inspected = {},
		seekingTransport = ( structure === transports );

	function inspect( dataType ) {
		var selected;
		inspected[ dataType ] = true;
		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
			if ( typeof dataTypeOrTransport === "string" &&
				!seekingTransport && !inspected[ dataTypeOrTransport ] ) {

				options.dataTypes.unshift( dataTypeOrTransport );
				inspect( dataTypeOrTransport );
				return false;
			} else if ( seekingTransport ) {
				return !( selected = dataTypeOrTransport );
			}
		} );
		return selected;
	}

	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes trac-9887
function ajaxExtend( target, src ) {
	var key, deep,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};

	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}

	return target;
}

/* Handles responses to an ajax request:
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {

	var ct, type, finalDataType, firstDataType,
		contents = s.contents,
		dataTypes = s.dataTypes;

	// Remove auto dataType and get content-type in the process
	while ( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {

		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}

		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

/* Chain conversions given the request and the original response
 * Also sets the responseXXX fields on the jqXHR instance
 */
function ajaxConvert( s, response, jqXHR, isSuccess ) {
	var conv2, current, conv, tmp, prev,
		converters = {},

		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice();

	// Create converters map with lowercased keys
	if ( dataTypes[ 1 ] ) {
		for ( conv in s.converters ) {
			converters[ conv.toLowerCase() ] = s.converters[ conv ];
		}
	}

	current = dataTypes.shift();

	// Convert to each sequential dataType
	while ( current ) {

		if ( s.responseFields[ current ] ) {
			jqXHR[ s.responseFields[ current ] ] = response;
		}

		// Apply the dataFilter if provided
		if ( !prev && isSuccess && s.dataFilter ) {
			response = s.dataFilter( response, s.dataType );
		}

		prev = current;
		current = dataTypes.shift();

		if ( current ) {

			// There's only work to do if current dataType is non-auto
			if ( current === "*" ) {

				current = prev;

			// Convert response if prev dataType is non-auto and differs from current
			} else if ( prev !== "*" && prev !== current ) {

				// Seek a direct converter
				conv = converters[ prev + " " + current ] || converters[ "* " + current ];

				// If none found, seek a pair
				if ( !conv ) {
					for ( conv2 in converters ) {

						// If conv2 outputs current
						tmp = conv2.split( " " );
						if ( tmp[ 1 ] === current ) {

							// If prev can be converted to accepted input
							conv = converters[ prev + " " + tmp[ 0 ] ] ||
								converters[ "* " + tmp[ 0 ] ];
							if ( conv ) {

								// Condense equivalence converters
								if ( conv === true ) {
									conv = converters[ conv2 ];

								// Otherwise, insert the intermediate dataType
								} else if ( converters[ conv2 ] !== true ) {
									current = tmp[ 0 ];
									dataTypes.unshift( tmp[ 1 ] );
								}
								break;
							}
						}
					}
				}

				// Apply converter (if not an equivalence)
				if ( conv !== true ) {

					// Unless errors are allowed to bubble, catch and return them
					if ( conv && s.throws ) {
						response = conv( response );
					} else {
						try {
							response = conv( response );
						} catch ( e ) {
							return {
								state: "parsererror",
								error: conv ? e : "No conversion from " + prev + " to " + current
							};
						}
					}
				}
			}
		}
	}

	return { state: "success", data: response };
}

jQuery.extend( {

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {},

	ajaxSettings: {
		url: location.href,
		type: "GET",
		isLocal: rlocalProtocol.test( location.protocol ),
		global: true,
		processData: true,
		async: true,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",

		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		throws: false,
		traditional: false,
		headers: {},
		*/

		accepts: {
			"*": allTypes,
			text: "text/plain",
			html: "text/html",
			xml: "application/xml, text/xml",
			json: "application/json, text/javascript"
		},

		contents: {
			xml: /\bxml\b/,
			html: /\bhtml/,
			json: /\bjson\b/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText",
			json: "responseJSON"
		},

		// Data converters
		// Keys separate source (or catchall "*") and destination types with a single space
		converters: {

			// Convert anything to text
			"* text": String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": JSON.parse,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			url: true,
			context: true
		}
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		return settings ?

			// Building a settings object
			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :

			// Extending ajaxSettings
			ajaxExtend( jQuery.ajaxSettings, target );
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var transport,

			// URL without anti-cache param
			cacheURL,

			// Response headers
			responseHeadersString,
			responseHeaders,

			// timeout handle
			timeoutTimer,

			// Url cleanup var
			urlAnchor,

			// Request state (becomes false upon send and true upon completion)
			completed,

			// To know if global events are to be dispatched
			fireGlobals,

			// Loop variable
			i,

			// uncached part of the url
			uncached,

			// Create the final options object
			s = jQuery.ajaxSetup( {}, options ),

			// Callbacks context
			callbackContext = s.context || s,

			// Context for global events is callbackContext if it is a DOM node or jQuery collection
			globalEventContext = s.context &&
				( callbackContext.nodeType || callbackContext.jquery ) ?
				jQuery( callbackContext ) :
				jQuery.event,

			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks( "once memory" ),

			// Status-dependent callbacks
			statusCode = s.statusCode || {},

			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},

			// Default abort message
			strAbort = "canceled",

			// Fake xhr
			jqXHR = {
				readyState: 0,

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( completed ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[ 1 ].toLowerCase() + " " ] =
									( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] )
										.concat( match[ 2 ] );
							}
						}
						match = responseHeaders[ key.toLowerCase() + " " ];
					}
					return match == null ? null : match.join( ", " );
				},

				// Raw string
				getAllResponseHeaders: function() {
					return completed ? responseHeadersString : null;
				},

				// Caches the header
				setRequestHeader: function( name, value ) {
					if ( completed == null ) {
						name = requestHeadersNames[ name.toLowerCase() ] =
							requestHeadersNames[ name.toLowerCase() ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( completed == null ) {
						s.mimeType = type;
					}
					return this;
				},

				// Status-dependent callbacks
				statusCode: function( map ) {
					var code;
					if ( map ) {
						if ( completed ) {

							// Execute the appropriate callbacks
							jqXHR.always( map[ jqXHR.status ] );
						} else {

							// Lazy-add the new callbacks in a way that preserves old ones
							for ( code in map ) {
								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
							}
						}
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					var finalText = statusText || strAbort;
					if ( transport ) {
						transport.abort( finalText );
					}
					done( 0, finalText );
					return this;
				}
			};

		// Attach deferreds
		deferred.promise( jqXHR );

		// Add protocol if not provided (prefilters might expect it)
		// Handle falsy url in the settings object (trac-10093: consistency with old signature)
		// We also use the url parameter if available
		s.url = ( ( url || s.url || location.href ) + "" )
			.replace( rprotocol, location.protocol + "//" );

		// Alias method option to type as per ticket trac-12004
		s.type = options.method || options.type || s.method || s.type;

		// Extract dataTypes list
		s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];

		// A cross-domain request is in order when the origin doesn't match the current origin.
		if ( s.crossDomain == null ) {
			urlAnchor = document.createElement( "a" );

			// Support: IE <=8 - 11, Edge 12 - 15
			// IE throws exception on accessing the href property if url is malformed,
			// e.g. http://example.com:80x/
			try {
				urlAnchor.href = s.url;

				// Support: IE <=8 - 11 only
				// Anchor's host property isn't correctly set when s.url is relative
				urlAnchor.href = urlAnchor.href;
				s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
					urlAnchor.protocol + "//" + urlAnchor.host;
			} catch ( e ) {

				// If there is an error parsing the URL, assume it is crossDomain,
				// it can be rejected by the transport if it is invalid
				s.crossDomain = true;
			}
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefilter, stop there
		if ( completed ) {
			return jqXHR;
		}

		// We can fire global events as of now if asked to
		// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (trac-15118)
		fireGlobals = jQuery.event && s.global;

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Save the URL in case we're toying with the If-Modified-Since
		// and/or If-None-Match header later on
		// Remove hash to simplify url manipulation
		cacheURL = s.url.replace( rhash, "" );

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// Remember the hash so we can put it back
			uncached = s.url.slice( cacheURL.length );

			// If data is available and should be processed, append data to url
			if ( s.data && ( s.processData || typeof s.data === "string" ) ) {
				cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;

				// trac-9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Add or update anti-cache param if needed
			if ( s.cache === false ) {
				cacheURL = cacheURL.replace( rantiCache, "$1" );
				uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) +
					uncached;
			}

			// Put hash and anti-cache on the URL that will be requested (gh-1732)
			s.url = cacheURL + uncached;

		// Change '%20' to '+' if this is encoded form body content (gh-2658)
		} else if ( s.data && s.processData &&
			( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
			s.data = s.data.replace( r20, "+" );
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			if ( jQuery.lastModified[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
			}
			if ( jQuery.etag[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
				s.accepts[ s.dataTypes[ 0 ] ] +
					( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend &&
			( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {

			// Abort if not done already and return
			return jqXHR.abort();
		}

		// Aborting is no longer a cancellation
		strAbort = "abort";

		// Install callbacks on deferreds
		completeDeferred.add( s.complete );
		jqXHR.done( s.success );
		jqXHR.fail( s.error );

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;

			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}

			// If request was aborted inside ajaxSend, stop there
			if ( completed ) {
				return jqXHR;
			}

			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = window.setTimeout( function() {
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				completed = false;
				transport.send( requestHeaders, done );
			} catch ( e ) {

				// Rethrow post-completion exceptions
				if ( completed ) {
					throw e;
				}

				// Propagate others as results
				done( -1, e );
			}
		}

		// Callback for when everything is done
		function done( status, nativeStatusText, responses, headers ) {
			var isSuccess, success, error, response, modified,
				statusText = nativeStatusText;

			// Ignore repeat invocations
			if ( completed ) {
				return;
			}

			completed = true;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				window.clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status > 0 ? 4 : 0;

			// Determine if successful
			isSuccess = status >= 200 && status < 300 || status === 304;

			// Get response data
			if ( responses ) {
				response = ajaxHandleResponses( s, jqXHR, responses );
			}

			// Use a noop converter for missing script but not if jsonp
			if ( !isSuccess &&
				jQuery.inArray( "script", s.dataTypes ) > -1 &&
				jQuery.inArray( "json", s.dataTypes ) < 0 ) {
				s.converters[ "text script" ] = function() {};
			}

			// Convert no matter what (that way responseXXX fields are always set)
			response = ajaxConvert( s, response, jqXHR, isSuccess );

			// If successful, handle type chaining
			if ( isSuccess ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {
					modified = jqXHR.getResponseHeader( "Last-Modified" );
					if ( modified ) {
						jQuery.lastModified[ cacheURL ] = modified;
					}
					modified = jqXHR.getResponseHeader( "etag" );
					if ( modified ) {
						jQuery.etag[ cacheURL ] = modified;
					}
				}

				// if no content
				if ( status === 204 || s.type === "HEAD" ) {
					statusText = "nocontent";

				// if not modified
				} else if ( status === 304 ) {
					statusText = "notmodified";

				// If we have data, let's convert it
				} else {
					statusText = response.state;
					success = response.data;
					error = response.error;
					isSuccess = !error;
				}
			} else {

				// Extract error from statusText and normalize for non-aborts
				error = statusText;
				if ( status || !statusText ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = ( nativeStatusText || statusText ) + "";

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
					[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );

				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		return jqXHR;
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	}
} );

jQuery.each( [ "get", "post" ], function( _i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {

		// Shift arguments if data argument was omitted
		if ( isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		// The url can be an options object (which then must have .url)
		return jQuery.ajax( jQuery.extend( {
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		}, jQuery.isPlainObject( url ) && url ) );
	};
} );

jQuery.ajaxPrefilter( function( s ) {
	var i;
	for ( i in s.headers ) {
		if ( i.toLowerCase() === "content-type" ) {
			s.contentType = s.headers[ i ] || "";
		}
	}
} );


jQuery._evalUrl = function( url, options, doc ) {
	return jQuery.ajax( {
		url: url,

		// Make this explicit, since user can override this through ajaxSetup (trac-11264)
		type: "GET",
		dataType: "script",
		cache: true,
		async: false,
		global: false,

		// Only evaluate the response if it is successful (gh-4126)
		// dataFilter is not invoked for failure responses, so using it instead
		// of the default converter is kludgy but it works.
		converters: {
			"text script": function() {}
		},
		dataFilter: function( response ) {
			jQuery.globalEval( response, options, doc );
		}
	} );
};


jQuery.fn.extend( {
	wrapAll: function( html ) {
		var wrap;

		if ( this[ 0 ] ) {
			if ( isFunction( html ) ) {
				html = html.call( this[ 0 ] );
			}

			// The elements to wrap the target around
			wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );

			if ( this[ 0 ].parentNode ) {
				wrap.insertBefore( this[ 0 ] );
			}

			wrap.map( function() {
				var elem = this;

				while ( elem.firstElementChild ) {
					elem = elem.firstElementChild;
				}

				return elem;
			} ).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( isFunction( html ) ) {
			return this.each( function( i ) {
				jQuery( this ).wrapInner( html.call( this, i ) );
			} );
		}

		return this.each( function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		} );
	},

	wrap: function( html ) {
		var htmlIsFunction = isFunction( html );

		return this.each( function( i ) {
			jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html );
		} );
	},

	unwrap: function( selector ) {
		this.parent( selector ).not( "body" ).each( function() {
			jQuery( this ).replaceWith( this.childNodes );
		} );
		return this;
	}
} );


jQuery.expr.pseudos.hidden = function( elem ) {
	return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
	return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};




jQuery.ajaxSettings.xhr = function() {
	try {
		return new window.XMLHttpRequest();
	} catch ( e ) {}
};

var xhrSuccessStatus = {

		// File protocol always yields status code 0, assume 200
		0: 200,

		// Support: IE <=9 only
		// trac-1450: sometimes IE returns 1223 when it should be 204
		1223: 204
	},
	xhrSupported = jQuery.ajaxSettings.xhr();

support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;

jQuery.ajaxTransport( function( options ) {
	var callback, errorCallback;

	// Cross domain only allowed if supported through XMLHttpRequest
	if ( support.cors || xhrSupported && !options.crossDomain ) {
		return {
			send: function( headers, complete ) {
				var i,
					xhr = options.xhr();

				xhr.open(
					options.type,
					options.url,
					options.async,
					options.username,
					options.password
				);

				// Apply custom fields if provided
				if ( options.xhrFields ) {
					for ( i in options.xhrFields ) {
						xhr[ i ] = options.xhrFields[ i ];
					}
				}

				// Override mime type if needed
				if ( options.mimeType && xhr.overrideMimeType ) {
					xhr.overrideMimeType( options.mimeType );
				}

				// X-Requested-With header
				// For cross-domain requests, seeing as conditions for a preflight are
				// akin to a jigsaw puzzle, we simply never set it to be sure.
				// (it can always be set on a per-request basis or even using ajaxSetup)
				// For same-domain requests, won't change header if already provided.
				if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
					headers[ "X-Requested-With" ] = "XMLHttpRequest";
				}

				// Set headers
				for ( i in headers ) {
					xhr.setRequestHeader( i, headers[ i ] );
				}

				// Callback
				callback = function( type ) {
					return function() {
						if ( callback ) {
							callback = errorCallback = xhr.onload =
								xhr.onerror = xhr.onabort = xhr.ontimeout =
									xhr.onreadystatechange = null;

							if ( type === "abort" ) {
								xhr.abort();
							} else if ( type === "error" ) {

								// Support: IE <=9 only
								// On a manual native abort, IE9 throws
								// errors on any property access that is not readyState
								if ( typeof xhr.status !== "number" ) {
									complete( 0, "error" );
								} else {
									complete(

										// File: protocol always yields status 0; see trac-8605, trac-14207
										xhr.status,
										xhr.statusText
									);
								}
							} else {
								complete(
									xhrSuccessStatus[ xhr.status ] || xhr.status,
									xhr.statusText,

									// Support: IE <=9 only
									// IE9 has no XHR2 but throws on binary (trac-11426)
									// For XHR2 non-text, let the caller handle it (gh-2498)
									( xhr.responseType || "text" ) !== "text"  ||
									typeof xhr.responseText !== "string" ?
										{ binary: xhr.response } :
										{ text: xhr.responseText },
									xhr.getAllResponseHeaders()
								);
							}
						}
					};
				};

				// Listen to events
				xhr.onload = callback();
				errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" );

				// Support: IE 9 only
				// Use onreadystatechange to replace onabort
				// to handle uncaught aborts
				if ( xhr.onabort !== undefined ) {
					xhr.onabort = errorCallback;
				} else {
					xhr.onreadystatechange = function() {

						// Check readyState before timeout as it changes
						if ( xhr.readyState === 4 ) {

							// Allow onerror to be called first,
							// but that will not handle a native abort
							// Also, save errorCallback to a variable
							// as xhr.onerror cannot be accessed
							window.setTimeout( function() {
								if ( callback ) {
									errorCallback();
								}
							} );
						}
					};
				}

				// Create the abort callback
				callback = callback( "abort" );

				try {

					// Do send the request (this may raise an exception)
					xhr.send( options.hasContent && options.data || null );
				} catch ( e ) {

					// trac-14683: Only rethrow if this hasn't been notified as an error yet
					if ( callback ) {
						throw e;
					}
				}
			},

			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
	if ( s.crossDomain ) {
		s.contents.script = false;
	}
} );

// Install script dataType
jQuery.ajaxSetup( {
	accepts: {
		script: "text/javascript, application/javascript, " +
			"application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /\b(?:java|ecma)script\b/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
} );

// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
	}
} );

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {

	// This transport only deals with cross domain or forced-by-attrs requests
	if ( s.crossDomain || s.scriptAttrs ) {
		var script, callback;
		return {
			send: function( _, complete ) {
				script = jQuery( "<script>" )
					.attr( s.scriptAttrs || {} )
					.prop( { charset: s.scriptCharset, src: s.url } )
					.on( "load error", callback = function( evt ) {
						script.remove();
						callback = null;
						if ( evt ) {
							complete( evt.type === "error" ? 404 : 200, evt.type );
						}
					} );

				// Use native DOM manipulation to avoid our domManip AJAX trickery
				document.head.appendChild( script[ 0 ] );
			},
			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




var oldCallbacks = [],
	rjsonp = /(=)\?(?=&|$)|\?\?/;

// Default jsonp settings
jQuery.ajaxSetup( {
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce.guid++ ) );
		this[ callback ] = true;
		return callback;
	}
} );

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
			"url" :
			typeof s.data === "string" &&
				( s.contentType || "" )
					.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
				rjsonp.test( s.data ) && "data"
		);

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;

		// Insert callback into url or form data
		if ( jsonProp ) {
			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
		} else if ( s.jsonp !== false ) {
			s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters[ "script json" ] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// Force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		overwritten = window[ callbackName ];
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always( function() {

			// If previous value didn't exist - remove it
			if ( overwritten === undefined ) {
				jQuery( window ).removeProp( callbackName );

			// Otherwise restore preexisting value
			} else {
				window[ callbackName ] = overwritten;
			}

			// Save back as free
			if ( s[ callbackName ] ) {

				// Make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// Save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer && isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		} );

		// Delegate to script
		return "script";
	}
} );




// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
	var body = document.implementation.createHTMLDocument( "" ).body;
	body.innerHTML = "<form></form><form></form>";
	return body.childNodes.length === 2;
} )();


// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
	if ( typeof data !== "string" ) {
		return [];
	}
	if ( typeof context === "boolean" ) {
		keepScripts = context;
		context = false;
	}

	var base, parsed, scripts;

	if ( !context ) {

		// Stop scripts or inline event handlers from being executed immediately
		// by using document.implementation
		if ( support.createHTMLDocument ) {
			context = document.implementation.createHTMLDocument( "" );

			// Set the base href for the created document
			// so any parsed elements with URLs
			// are based on the document's URL (gh-2965)
			base = context.createElement( "base" );
			base.href = document.location.href;
			context.head.appendChild( base );
		} else {
			context = document;
		}
	}

	parsed = rsingleTag.exec( data );
	scripts = !keepScripts && [];

	// Single tag
	if ( parsed ) {
		return [ context.createElement( parsed[ 1 ] ) ];
	}

	parsed = buildFragment( [ data ], context, scripts );

	if ( scripts && scripts.length ) {
		jQuery( scripts ).remove();
	}

	return jQuery.merge( [], parsed.childNodes );
};


/**
 * Load a url into a page
 */
jQuery.fn.load = function( url, params, callback ) {
	var selector, type, response,
		self = this,
		off = url.indexOf( " " );

	if ( off > -1 ) {
		selector = stripAndCollapse( url.slice( off ) );
		url = url.slice( 0, off );
	}

	// If it's a function
	if ( isFunction( params ) ) {

		// We assume that it's the callback
		callback = params;
		params = undefined;

	// Otherwise, build a param string
	} else if ( params && typeof params === "object" ) {
		type = "POST";
	}

	// If we have elements to modify, make the request
	if ( self.length > 0 ) {
		jQuery.ajax( {
			url: url,

			// If "type" variable is undefined, then "GET" method will be used.
			// Make value of this field explicit since
			// user can override it through ajaxSetup method
			type: type || "GET",
			dataType: "html",
			data: params
		} ).done( function( responseText ) {

			// Save response for use in complete callback
			response = arguments;

			self.html( selector ?

				// If a selector was specified, locate the right elements in a dummy div
				// Exclude scripts to avoid IE 'Permission Denied' errors
				jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :

				// Otherwise use the full result
				responseText );

		// If the request succeeds, this function gets "data", "status", "jqXHR"
		// but they are ignored because response was set above.
		// If it fails, this function gets "jqXHR", "status", "error"
		} ).always( callback && function( jqXHR, status ) {
			self.each( function() {
				callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
			} );
		} );
	}

	return this;
};




jQuery.expr.pseudos.animated = function( elem ) {
	return jQuery.grep( jQuery.timers, function( fn ) {
		return elem === fn.elem;
	} ).length;
};




jQuery.offset = {
	setOffset: function( elem, options, i ) {
		var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
			position = jQuery.css( elem, "position" ),
			curElem = jQuery( elem ),
			props = {};

		// Set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		curOffset = curElem.offset();
		curCSSTop = jQuery.css( elem, "top" );
		curCSSLeft = jQuery.css( elem, "left" );
		calculatePosition = ( position === "absolute" || position === "fixed" ) &&
			( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;

		// Need to be able to calculate position if either
		// top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;

		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( isFunction( options ) ) {

			// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
			options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );

		} else {
			curElem.css( props );
		}
	}
};

jQuery.fn.extend( {

	// offset() relates an element's border box to the document origin
	offset: function( options ) {

		// Preserve chaining for setter
		if ( arguments.length ) {
			return options === undefined ?
				this :
				this.each( function( i ) {
					jQuery.offset.setOffset( this, options, i );
				} );
		}

		var rect, win,
			elem = this[ 0 ];

		if ( !elem ) {
			return;
		}

		// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
		// Support: IE <=11 only
		// Running getBoundingClientRect on a
		// disconnected node in IE throws an error
		if ( !elem.getClientRects().length ) {
			return { top: 0, left: 0 };
		}

		// Get document-relative position by adding viewport scroll to viewport-relative gBCR
		rect = elem.getBoundingClientRect();
		win = elem.ownerDocument.defaultView;
		return {
			top: rect.top + win.pageYOffset,
			left: rect.left + win.pageXOffset
		};
	},

	// position() relates an element's margin box to its offset parent's padding box
	// This corresponds to the behavior of CSS absolute positioning
	position: function() {
		if ( !this[ 0 ] ) {
			return;
		}

		var offsetParent, offset, doc,
			elem = this[ 0 ],
			parentOffset = { top: 0, left: 0 };

		// position:fixed elements are offset from the viewport, which itself always has zero offset
		if ( jQuery.css( elem, "position" ) === "fixed" ) {

			// Assume position:fixed implies availability of getBoundingClientRect
			offset = elem.getBoundingClientRect();

		} else {
			offset = this.offset();

			// Account for the *real* offset parent, which can be the document or its root element
			// when a statically positioned element is identified
			doc = elem.ownerDocument;
			offsetParent = elem.offsetParent || doc.documentElement;
			while ( offsetParent &&
				( offsetParent === doc.body || offsetParent === doc.documentElement ) &&
				jQuery.css( offsetParent, "position" ) === "static" ) {

				offsetParent = offsetParent.parentNode;
			}
			if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 ) {

				// Incorporate borders into its offset, since they are outside its content origin
				parentOffset = jQuery( offsetParent ).offset();
				parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true );
				parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true );
			}
		}

		// Subtract parent offsets and element margins
		return {
			top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
		};
	},

	// This method will return documentElement in the following cases:
	// 1) For the element inside the iframe without offsetParent, this method will return
	//    documentElement of the parent window
	// 2) For the hidden or detached element
	// 3) For body or html element, i.e. in case of the html node - it will return itself
	//
	// but those exceptions were never presented as a real life use-cases
	// and might be considered as more preferable results.
	//
	// This logic, however, is not guaranteed and can change at any point in the future
	offsetParent: function() {
		return this.map( function() {
			var offsetParent = this.offsetParent;

			while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
				offsetParent = offsetParent.offsetParent;
			}

			return offsetParent || documentElement;
		} );
	}
} );

// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
	var top = "pageYOffset" === prop;

	jQuery.fn[ method ] = function( val ) {
		return access( this, function( elem, method, val ) {

			// Coalesce documents and windows
			var win;
			if ( isWindow( elem ) ) {
				win = elem;
			} else if ( elem.nodeType === 9 ) {
				win = elem.defaultView;
			}

			if ( val === undefined ) {
				return win ? win[ prop ] : elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : win.pageXOffset,
					top ? val : win.pageYOffset
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length );
	};
} );

// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( _i, prop ) {
	jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
		function( elem, computed ) {
			if ( computed ) {
				computed = curCSS( elem, prop );

				// If curCSS returns percentage, fallback to offset
				return rnumnonpx.test( computed ) ?
					jQuery( elem ).position()[ prop ] + "px" :
					computed;
			}
		}
	);
} );


// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
	jQuery.each( {
		padding: "inner" + name,
		content: type,
		"": "outer" + name
	}, function( defaultExtra, funcName ) {

		// Margin is only for outerHeight, outerWidth
		jQuery.fn[ funcName ] = function( margin, value ) {
			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );

			return access( this, function( elem, type, value ) {
				var doc;

				if ( isWindow( elem ) ) {

					// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
					return funcName.indexOf( "outer" ) === 0 ?
						elem[ "inner" + name ] :
						elem.document.documentElement[ "client" + name ];
				}

				// Get document width or height
				if ( elem.nodeType === 9 ) {
					doc = elem.documentElement;

					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
					// whichever is greatest
					return Math.max(
						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
						elem.body[ "offset" + name ], doc[ "offset" + name ],
						doc[ "client" + name ]
					);
				}

				return value === undefined ?

					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css( elem, type, extra ) :

					// Set width or height on the element
					jQuery.style( elem, type, value, extra );
			}, type, chainable ? margin : undefined, chainable );
		};
	} );
} );


jQuery.each( [
	"ajaxStart",
	"ajaxStop",
	"ajaxComplete",
	"ajaxError",
	"ajaxSuccess",
	"ajaxSend"
], function( _i, type ) {
	jQuery.fn[ type ] = function( fn ) {
		return this.on( type, fn );
	};
} );




jQuery.fn.extend( {

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {

		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length === 1 ?
			this.off( selector, "**" ) :
			this.off( types, selector || "**", fn );
	},

	hover: function( fnOver, fnOut ) {
		return this
			.on( "mouseenter", fnOver )
			.on( "mouseleave", fnOut || fnOver );
	}
} );

jQuery.each(
	( "blur focus focusin focusout resize scroll click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup contextmenu" ).split( " " ),
	function( _i, name ) {

		// Handle event binding
		jQuery.fn[ name ] = function( data, fn ) {
			return arguments.length > 0 ?
				this.on( name, null, data, fn ) :
				this.trigger( name );
		};
	}
);




// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
// Require that the "whitespace run" starts from a non-whitespace
// to avoid O(N^2) behavior when the engine would try matching "\s+$" at each space position.
var rtrim = /^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;

// Bind a function to a context, optionally partially applying any
// arguments.
// jQuery.proxy is deprecated to promote standards (specifically Function#bind)
// However, it is not slated for removal any time soon
jQuery.proxy = function( fn, context ) {
	var tmp, args, proxy;

	if ( typeof context === "string" ) {
		tmp = fn[ context ];
		context = fn;
		fn = tmp;
	}

	// Quick check to determine if target is callable, in the spec
	// this throws a TypeError, but we will just return undefined.
	if ( !isFunction( fn ) ) {
		return undefined;
	}

	// Simulated bind
	args = slice.call( arguments, 2 );
	proxy = function() {
		return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
	};

	// Set the guid of unique handler to the same of original handler, so it can be removed
	proxy.guid = fn.guid = fn.guid || jQuery.guid++;

	return proxy;
};

jQuery.holdReady = function( hold ) {
	if ( hold ) {
		jQuery.readyWait++;
	} else {
		jQuery.ready( true );
	}
};
jQuery.isArray = Array.isArray;
jQuery.parseJSON = JSON.parse;
jQuery.nodeName = nodeName;
jQuery.isFunction = isFunction;
jQuery.isWindow = isWindow;
jQuery.camelCase = camelCase;
jQuery.type = toType;

jQuery.now = Date.now;

jQuery.isNumeric = function( obj ) {

	// As of jQuery 3.0, isNumeric is limited to
	// strings and numbers (primitives or objects)
	// that can be coerced to finite numbers (gh-2662)
	var type = jQuery.type( obj );
	return ( type === "number" || type === "string" ) &&

		// parseFloat NaNs numeric-cast false positives ("")
		// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
		// subtraction forces infinities to NaN
		!isNaN( obj - parseFloat( obj ) );
};

jQuery.trim = function( text ) {
	return text == null ?
		"" :
		( text + "" ).replace( rtrim, "$1" );
};



// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.

// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon

if ( true ) {
	!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
		return jQuery;
	}).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}




var

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$;

jQuery.noConflict = function( deep ) {
	if ( window.$ === jQuery ) {
		window.$ = _$;
	}

	if ( deep && window.jQuery === jQuery ) {
		window.jQuery = _jQuery;
	}

	return jQuery;
};

// Expose jQuery and $ identifiers, even in AMD
// (trac-7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (trac-13566)
if ( typeof noGlobal === "undefined" ) {
	window.jQuery = window.$ = jQuery;
}




return jQuery;
} );


/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return VERSION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return root; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ArrayProto; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return ObjProto; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return SymbolProto; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return push; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return slice; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return toString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return hasOwnProperty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return supportsArrayBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return supportsDataView; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return nativeIsArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return nativeKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return nativeCreate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return nativeIsView; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return _isNaN; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return _isFinite; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return hasEnumBug; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return nonEnumerableProps; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return MAX_ARRAY_INDEX; });
// Current version.
var VERSION = '1.13.6';

// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = (typeof self == 'object' && self.self === self && self) ||
          (typeof global == 'object' && global.global === global && global) ||
          Function('return this')() ||
          {};

// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype;
var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;

// Create quick reference variables for speed access to core prototypes.
var push = ArrayProto.push,
    slice = ArrayProto.slice,
    toString = ObjProto.toString,
    hasOwnProperty = ObjProto.hasOwnProperty;

// Modern feature detection.
var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
    supportsDataView = typeof DataView !== 'undefined';

// All **ECMAScript 5+** native function implementations that we hope to use
// are declared here.
var nativeIsArray = Array.isArray,
    nativeKeys = Object.keys,
    nativeCreate = Object.create,
    nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;

// Create references to these builtin functions because we override them.
var _isNaN = isNaN,
    _isFinite = isFinite;

// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
  'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

// The largest integer that can be represented exactly.
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;

/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(115)))

/***/ }),
/* 2 */
/***/ (function(module, exports) {

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function() {
	var list = [];

	// return the list of modules as css string
	list.toString = function toString() {
		var result = [];
		for(var i = 0; i < this.length; i++) {
			var item = this[i];
			if(item[2]) {
				result.push("@media " + item[2] + "{" + item[1] + "}");
			} else {
				result.push(item[1]);
			}
		}
		return result.join("");
	};

	// import a list of modules into the list
	list.i = function(modules, mediaQuery) {
		if(typeof modules === "string")
			modules = [[null, modules, ""]];
		var alreadyImportedModules = {};
		for(var i = 0; i < this.length; i++) {
			var id = this[i][0];
			if(typeof id === "number")
				alreadyImportedModules[id] = true;
		}
		for(i = 0; i < modules.length; i++) {
			var item = modules[i];
			// skip already imported module
			// this implementation is not 100% perfect for weird media query combinations
			//  when a module is imported multiple times with different media queries.
			//  I hope this will never occur (Hey this way we have smaller bundles)
			if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
				if(mediaQuery && !item[2]) {
					item[2] = mediaQuery;
				} else if(mediaQuery) {
					item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
				}
				list.push(item);
			}
		}
	};
	return list;
};


/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.ui = $.ui || {};

return $.ui.version = "1.13.2";

} );


/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = keys;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isObject_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__has_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__collectNonEnumProps_js__ = __webpack_require__(63);





// Retrieve the names of an object's own properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`.
function keys(obj) {
  if (!Object(__WEBPACK_IMPORTED_MODULE_0__isObject_js__["a" /* default */])(obj)) return [];
  if (__WEBPACK_IMPORTED_MODULE_1__setup_js__["m" /* nativeKeys */]) return Object(__WEBPACK_IMPORTED_MODULE_1__setup_js__["m" /* nativeKeys */])(obj);
  var keys = [];
  for (var key in obj) if (Object(__WEBPACK_IMPORTED_MODULE_2__has_js__["a" /* default */])(obj, key)) keys.push(key);
  // Ahem, IE < 9.
  if (__WEBPACK_IMPORTED_MODULE_1__setup_js__["h" /* hasEnumBug */]) Object(__WEBPACK_IMPORTED_MODULE_3__collectNonEnumProps_js__["a" /* default */])(obj, keys);
  return keys;
}


/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = tagTester;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);


// Internal function for creating a `toString`-based type tester.
function tagTester(name) {
  var tag = '[object ' + name + ']';
  return function(obj) {
    return __WEBPACK_IMPORTED_MODULE_0__setup_js__["t" /* toString */].call(obj) === tag;
  };
}


/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = cb;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__baseIteratee_js__ = __webpack_require__(72);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__iteratee_js__ = __webpack_require__(73);




// The function we call internally to generate a callback. It invokes
// `_.iteratee` if overridden, otherwise `baseIteratee`.
function cb(value, context, argCount) {
  if (__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].iteratee !== __WEBPACK_IMPORTED_MODULE_2__iteratee_js__["a" /* default */]) return __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].iteratee(value, context);
  return Object(__WEBPACK_IMPORTED_MODULE_1__baseIteratee_js__["a" /* default */])(value, context, argCount);
}


/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = restArguments;
// Some functions take a variable number of arguments, or a few expected
// arguments at the beginning and then a variable number of values to operate
// on. This helper accumulates all remaining arguments past the function’s
// argument length (or an explicit `startIndex`), into an array that becomes
// the last argument. Similar to ES6’s "rest parameter".
function restArguments(func, startIndex) {
  startIndex = startIndex == null ? func.length - 1 : +startIndex;
  return function() {
    var length = Math.max(arguments.length - startIndex, 0),
        rest = Array(length),
        index = 0;
    for (; index < length; index++) {
      rest[index] = arguments[index + startIndex];
    }
    switch (startIndex) {
      case 0: return func.call(this, rest);
      case 1: return func.call(this, arguments[0], rest);
      case 2: return func.call(this, arguments[0], arguments[1], rest);
    }
    var args = Array(startIndex + 1);
    for (index = 0; index < startIndex; index++) {
      args[index] = arguments[index];
    }
    args[startIndex] = rest;
    return func.apply(this, args);
  };
}


/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = _;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);


// If Underscore is called as a function, it returns a wrapped object that can
// be used OO-style. This wrapper holds altered versions of all functions added
// through `_.mixin`. Wrapped objects may be chained.
function _(obj) {
  if (obj instanceof _) return obj;
  if (!(this instanceof _)) return new _(obj);
  this._wrapped = obj;
}

_.VERSION = __WEBPACK_IMPORTED_MODULE_0__setup_js__["e" /* VERSION */];

// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
  return this._wrapped;
};

// Provide unwrapping proxies for some methods used in engine operations
// such as arithmetic and JSON stringification.
_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;

_.prototype.toString = function() {
  return String(this._wrapped);
};


/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createSizePropertyCheck_js__ = __webpack_require__(61);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getLength_js__ = __webpack_require__(11);



// Internal helper for collection methods to determine whether a collection
// should be iterated as an array or as an object.
// Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createSizePropertyCheck_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__getLength_js__["a" /* default */]));


/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(1);



var isFunction = Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Function');

// Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old
// v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
var nodelist = __WEBPACK_IMPORTED_MODULE_1__setup_js__["p" /* root */].document && __WEBPACK_IMPORTED_MODULE_1__setup_js__["p" /* root */].document.childNodes;
if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
  isFunction = function(obj) {
    return typeof obj == 'function' || false;
  };
}

/* harmony default export */ __webpack_exports__["a"] = (isFunction);


/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__shallowProperty_js__ = __webpack_require__(62);


// Internal helper to obtain the `length` property of an object.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__shallowProperty_js__["a" /* default */])('length'));


/***/ }),
/* 12 */
/***/ (function(module, exports) {

module.exports = {"name":"nglview-js-widgets","version":"3.1.0","description":"nglview-js-widgets","keywords":["ipython","ipywidgets","jupyter","jupyterlab","jupyterlab-extension","molecular graphics","molecular structure","science","widgets"],"homepage":"https://github.com/nglviewer/nglview/js","bugs":{"url":"https://github.com/nglviewer/nglview/issues"},"license":"MIT","author":{"name":"Alexander Rose, Hai Nguyen","email":"alexander.rose@weirdbyte.de, hainm.comp@gmail.com"},"files":["dist","src","lib","style/index.js"],"main":"lib/index.js","repository":{"type":"git","url":"https://github.com/nglviewer/nglview.git"},"scripts":{"prepublish":"yarn build:prod && webpack && yarn run copy:labextension","copy:labextension":"cp -r nglview-js-widgets/labextension/* ../nglview/staticlab/","build":"yarn run build:lib && yarn run build:labextension:dev","build:prod":"yarn run build:lib && yarn run build:labextension","build:labextension":"jupyter labextension build .","build:labextension:dev":"jupyter labextension build --development True .","build:lib":"tsc","clean":"yarn run clean:lib","clean:lib":"rimraf lib tsconfig.tsbuildinfo","clean:labextension":"rimraf myextension/labextension","clean:all":"yarn run clean:lib && yarn run clean:labextension","eslint":"eslint . --ext .ts,.tsx --fix","eslint:check":"eslint . --ext .ts,.tsx","install:extension":"jupyter labextension develop --overwrite .","prepare":"yarn run clean && yarn run build:prod","watch":"run-p watch:src watch:labextension","watch:src":"tsc -w","watch:labextension":"jupyter labextension watch .","test":"mocha"},"dependencies":{"@jupyter-widgets/base":"^1 || ^2.0.2 || ^3 || ^4 || ^5 || ^6","@jupyter-widgets/jupyterlab-manager":"^3.0.0","jquery":"^3.2.1","jquery-ui":"^1.12.1","lodash":"^4.17.4","ngl":"2.2.2","underscore":"^1.8.3"},"devDependencies":{"@jupyterlab/builder":"^3.0.5 || ^4","@types/chai":"^4.1.4","@types/expect.js":"^0.3.29","@types/mocha":"^2.2.48","@types/node":"^16.0.0","@types/requirejs":"^2.1.31","@typescript-eslint/eslint-plugin":"^4.8.1","@typescript-eslint/parser":"^4.8.1","babel-register":"^6.11.6","css-loader":"^0.23.1","eslint":"^7.14.0","file-loader":"^1.1.6","json-loader":"^0.5.4","mkdirp":"^1.0.3","ngl":"2.2.2","npm-run-all":"^4.1.5","prettier":"^2.1.1","rimraf":"^3.0.2","style-loader":"^0.13.1","typescript":"~4.1.3","webpack":"^3.12.0"},"sideEffects":["style/*.css","style/index.js"],"styleModule":"style/index.js","jupyterlab":{"extension":"lib/jupyterlab-plugin","outputDir":"nglview-js-widgets/labextension","sharedPackages":{"@jupyter-widgets/base":{"bundled":false,"singleton":true}}},"directories":{"test":"test"},"packageManager":"yarn@1.22.1"}

/***/ }),
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = has;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);


// Internal function to check whether `key` is an own property name of `obj`.
function has(obj, key) {
  return obj != null && __WEBPACK_IMPORTED_MODULE_0__setup_js__["i" /* hasOwnProperty */].call(obj, key);
}


/***/ }),
/* 14 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isObject;
// Is a given variable an object?
function isObject(obj) {
  var type = typeof obj;
  return type === 'function' || (type === 'object' && !!obj);
}


/***/ }),
/* 15 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__tagTester_js__ = __webpack_require__(5);



// Is a given value an array?
// Delegates to ECMA5's native `Array.isArray`.
/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_0__setup_js__["k" /* nativeIsArray */] || Object(__WEBPACK_IMPORTED_MODULE_1__tagTester_js__["a" /* default */])('Array'));


/***/ }),
/* 16 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = each;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__optimizeCb_js__ = __webpack_require__(26);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__keys_js__ = __webpack_require__(4);




// The cornerstone for collection functions, an `each`
// implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
function each(obj, iteratee, context) {
  iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__optimizeCb_js__["a" /* default */])(iteratee, context);
  var i, length;
  if (Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(obj)) {
    for (i = 0, length = obj.length; i < length; i++) {
      iteratee(obj[i], i, obj);
    }
  } else {
    var _keys = Object(__WEBPACK_IMPORTED_MODULE_2__keys_js__["a" /* default */])(obj);
    for (i = 0, length = _keys.length; i < length; i++) {
      iteratee(obj[_keys[i]], _keys[i], obj);
    }
  }
  return obj;
}


/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Widget 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

var widgetUuid = 0;
var widgetHasOwnProperty = Array.prototype.hasOwnProperty;
var widgetSlice = Array.prototype.slice;

$.cleanData = ( function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {

			// Only trigger remove when necessary to save time
			events = $._data( elem, "events" );
			if ( events && events.remove ) {
				$( elem ).triggerHandler( "remove" );
			}
		}
		orig( elems );
	};
} )( $.cleanData );

$.widget = function( name, base, prototype ) {
	var existingConstructor, constructor, basePrototype;

	// ProxiedPrototype allows the provided prototype to remain unmodified
	// so that it can be used as a mixin for multiple widgets (#8876)
	var proxiedPrototype = {};

	var namespace = name.split( "." )[ 0 ];
	name = name.split( "." )[ 1 ];
	var fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	if ( Array.isArray( prototype ) ) {
		prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
	}

	// Create selector for plugin
	$.expr.pseudos[ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {

		// Allow instantiation without "new" keyword
		if ( !this || !this._createWidget ) {
			return new constructor( options, element );
		}

		// Allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	// Extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,

		// Copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),

		// Track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	} );

	basePrototype = new base();

	// We need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( typeof value !== "function" ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = ( function() {
			function _super() {
				return base.prototype[ prop ].apply( this, arguments );
			}

			function _superApply( args ) {
				return base.prototype[ prop ].apply( this, args );
			}

			return function() {
				var __super = this._super;
				var __superApply = this._superApply;
				var returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		} )();
	} );
	constructor.prototype = $.widget.extend( basePrototype, {

		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? ( basePrototype.widgetEventPrefix || name ) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	} );

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// Redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
				child._proto );
		} );

		// Remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widgetSlice.call( arguments, 1 );
	var inputIndex = 0;
	var inputLength = input.length;
	var key;
	var value;

	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( widgetHasOwnProperty.call( input[ inputIndex ], key ) && value !== undefined ) {

				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :

						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );

				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string";
		var args = widgetSlice.call( arguments, 1 );
		var returnValue = this;

		if ( isMethodCall ) {

			// If this is an empty collection, we need to have the instance method
			// return undefined instead of the jQuery instance
			if ( !this.length && options === "instance" ) {
				returnValue = undefined;
			} else {
				this.each( function() {
					var methodValue;
					var instance = $.data( this, fullName );

					if ( options === "instance" ) {
						returnValue = instance;
						return false;
					}

					if ( !instance ) {
						return $.error( "cannot call methods on " + name +
							" prior to initialization; " +
							"attempted to call method '" + options + "'" );
					}

					if ( typeof instance[ options ] !== "function" ||
						options.charAt( 0 ) === "_" ) {
						return $.error( "no such method '" + options + "' for " + name +
							" widget instance" );
					}

					methodValue = instance[ options ].apply( instance, args );

					if ( methodValue !== instance && methodValue !== undefined ) {
						returnValue = methodValue && methodValue.jquery ?
							returnValue.pushStack( methodValue.get() ) :
							methodValue;
						return false;
					}
				} );
			}
		} else {

			// Allow multiple hashes to be passed on init
			if ( args.length ) {
				options = $.widget.extend.apply( null, [ options ].concat( args ) );
			}

			this.each( function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			} );
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",

	options: {
		classes: {},
		disabled: false,

		// Callbacks
		create: null
	},

	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widgetUuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();
		this.classesElementLookup = {};

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			} );
			this.document = $( element.style ?

				// Element within the document
				element.ownerDocument :

				// Element is window or document
				element.document || element );
			this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();

		if ( this.options.disabled ) {
			this._setOptionDisabled( this.options.disabled );
		}

		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},

	_getCreateOptions: function() {
		return {};
	},

	_getCreateEventData: $.noop,

	_create: $.noop,

	_init: $.noop,

	destroy: function() {
		var that = this;

		this._destroy();
		$.each( this.classesElementLookup, function( key, value ) {
			that._removeClass( value, key );
		} );

		// We can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.off( this.eventNamespace )
			.removeData( this.widgetFullName );
		this.widget()
			.off( this.eventNamespace )
			.removeAttr( "aria-disabled" );

		// Clean up events and states
		this.bindings.off( this.eventNamespace );
	},

	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;
		var parts;
		var curOption;
		var i;

		if ( arguments.length === 0 ) {

			// Don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {

			// Handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},

	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},

	_setOption: function( key, value ) {
		if ( key === "classes" ) {
			this._setOptionClasses( value );
		}

		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this._setOptionDisabled( value );
		}

		return this;
	},

	_setOptionClasses: function( value ) {
		var classKey, elements, currentElements;

		for ( classKey in value ) {
			currentElements = this.classesElementLookup[ classKey ];
			if ( value[ classKey ] === this.options.classes[ classKey ] ||
					!currentElements ||
					!currentElements.length ) {
				continue;
			}

			// We are doing this to create a new jQuery object because the _removeClass() call
			// on the next line is going to destroy the reference to the current elements being
			// tracked. We need to save a copy of this collection so that we can add the new classes
			// below.
			elements = $( currentElements.get() );
			this._removeClass( currentElements, classKey );

			// We don't use _addClass() here, because that uses this.options.classes
			// for generating the string of classes. We want to use the value passed in from
			// _setOption(), this is the new value of the classes option which was passed to
			// _setOption(). We pass this value directly to _classes().
			elements.addClass( this._classes( {
				element: elements,
				keys: classKey,
				classes: value,
				add: true
			} ) );
		}
	},

	_setOptionDisabled: function( value ) {
		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );

		// If the widget is becoming disabled, then nothing is interactive
		if ( value ) {
			this._removeClass( this.hoverable, null, "ui-state-hover" );
			this._removeClass( this.focusable, null, "ui-state-focus" );
		}
	},

	enable: function() {
		return this._setOptions( { disabled: false } );
	},

	disable: function() {
		return this._setOptions( { disabled: true } );
	},

	_classes: function( options ) {
		var full = [];
		var that = this;

		options = $.extend( {
			element: this.element,
			classes: this.options.classes || {}
		}, options );

		function bindRemoveEvent() {
			var nodesToBind = [];

			options.element.each( function( _, element ) {
				var isTracked = $.map( that.classesElementLookup, function( elements ) {
					return elements;
				} )
					.some( function( elements ) {
						return elements.is( element );
					} );

				if ( !isTracked ) {
					nodesToBind.push( element );
				}
			} );

			that._on( $( nodesToBind ), {
				remove: "_untrackClassesElement"
			} );
		}

		function processClassString( classes, checkOption ) {
			var current, i;
			for ( i = 0; i < classes.length; i++ ) {
				current = that.classesElementLookup[ classes[ i ] ] || $();
				if ( options.add ) {
					bindRemoveEvent();
					current = $( $.uniqueSort( current.get().concat( options.element.get() ) ) );
				} else {
					current = $( current.not( options.element ).get() );
				}
				that.classesElementLookup[ classes[ i ] ] = current;
				full.push( classes[ i ] );
				if ( checkOption && options.classes[ classes[ i ] ] ) {
					full.push( options.classes[ classes[ i ] ] );
				}
			}
		}

		if ( options.keys ) {
			processClassString( options.keys.match( /\S+/g ) || [], true );
		}
		if ( options.extra ) {
			processClassString( options.extra.match( /\S+/g ) || [] );
		}

		return full.join( " " );
	},

	_untrackClassesElement: function( event ) {
		var that = this;
		$.each( that.classesElementLookup, function( key, value ) {
			if ( $.inArray( event.target, value ) !== -1 ) {
				that.classesElementLookup[ key ] = $( value.not( event.target ).get() );
			}
		} );

		this._off( $( event.target ) );
	},

	_removeClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, false );
	},

	_addClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, true );
	},

	_toggleClass: function( element, keys, extra, add ) {
		add = ( typeof add === "boolean" ) ? add : extra;
		var shift = ( typeof element === "string" || element === null ),
			options = {
				extra: shift ? keys : extra,
				keys: shift ? element : keys,
				element: shift ? this.element : element,
				add: add
			};
		options.element.toggleClass( this._classes( options ), add );
		return this;
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement;
		var instance = this;

		// No suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// No element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {

				// Allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
						$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// Copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ );
			var eventName = match[ 1 ] + instance.eventNamespace;
			var selector = match[ 2 ];

			if ( selector ) {
				delegateElement.on( eventName, selector, handlerProxy );
			} else {
				element.on( eventName, handlerProxy );
			}
		} );
	},

	_off: function( element, eventName ) {
		eventName = ( eventName || "" ).split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.off( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-hover" );
			},
			mouseleave: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-hover" );
			}
		} );
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				this._addClass( $( event.currentTarget ), null, "ui-state-focus" );
			},
			focusout: function( event ) {
				this._removeClass( $( event.currentTarget ), null, "ui-state-focus" );
			}
		} );
	},

	_trigger: function( type, event, data ) {
		var prop, orig;
		var callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();

		// The original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// Copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( typeof callback === "function" &&
			callback.apply( this.element[ 0 ], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}

		var hasOptions;
		var effectName = !options ?
			method :
			options === true || typeof options === "number" ?
				defaultEffect :
				options.effect || defaultEffect;

		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		} else if ( options === true ) {
			options = {};
		}

		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;

		if ( options.delay ) {
			element.delay( options.delay );
		}

		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue( function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			} );
		}
	};
} );

return $.widget;

} );


/***/ }),
/* 18 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AngleRepresentation", function() { return zh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrowBuffer", function() { return hu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Assembly", function() { return La; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxesRepresentation", function() { return ed; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackboneRepresentation", function() { return rd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BallAndStickRepresentation", function() { return id; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseRepresentation", function() { return sd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoxBuffer", function() { return fu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferRepresentation", function() { return Tc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CartoonRepresentation", function() { return dd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collection", function() { return hl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Colormaker", function() { return zt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColormakerRegistry", function() { return Fe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Component", function() { return ll; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentCollection", function() { return $l; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConeBuffer", function() { return au; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ContactRepresentation", function() { return ud; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Counter", function() { return ui; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CylinderBuffer", function() { return td; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DatasourceRegistry", function() { return Le; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Debug", function() { return De; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DecompressorRegistry", function() { return Ge; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DihedralHistogramRepresentation", function() { return gd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DihedralRepresentation", function() { return md; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DistanceRepresentation", function() { return bd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EllipsoidBuffer", function() { return wu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Frames", function() { return pl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HelixorientRepresentation", function() { return Ad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HyperballRepresentation", function() { return Bd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Kdtree", function() { return $a; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyActions", function() { return ta; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LabelRepresentation", function() { return $d; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LeftMouseButton", function() { return tr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LicoriceRepresentation", function() { return _d; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LineRepresentation", function() { return Rd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ListingDatasource", function() { return We; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MdsrvDatasource", function() { return eg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeasurementDefaultParams", function() { return Te; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshBuffer", function() { return Uo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MiddleMouseButton", function() { return er; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MolecularSurface", function() { return zd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MolecularSurfaceRepresentation", function() { return Vd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MouseActions", function() { return Ko; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctahedronBuffer", function() { return Pu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParserRegistry", function() { return ze; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PdbWriter", function() { return ai; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PickingProxy", function() { return br; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointBuffer", function() { return Wc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointRepresentation", function() { return Gd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Queue", function() { return Nr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepresentationCollection", function() { return dl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepresentationElement", function() { return nl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepresentationRegistry", function() { return Ne; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RibbonRepresentation", function() { return Wd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RightMouseButton", function() { return ir; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RocketRepresentation", function() { return qd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RopeRepresentation", function() { return Xd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScriptExtensions", function() { return Re; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SdfWriter", function() { return ci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Selection", function() { return pe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Shape", function() { return Mc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShapeComponent", function() { return Ll; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpacefillRepresentation", function() { return Yd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpatialHash", function() { return Ts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SphereBuffer", function() { return Gc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Stage", function() { return Fl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StaticDatasource", function() { return tg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StlWriter", function() { return di; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Structure", function() { return Cc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureComponent", function() { return Tl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureComponentDefaultParameters", function() { return Ml; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureRepresentation", function() { return Sh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Superposition", function() { return fl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SurfaceComponent", function() { return Bl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TetrahedronBuffer", function() { return Bu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextBuffer", function() { return Eh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TorusBuffer", function() { return Fu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TraceRepresentation", function() { return Qd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TrajectoryDatasource", function() { return qe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TrajectoryPlayer", function() { return yl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TubeRepresentation", function() { return Jd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UIStageParameters", function() { return og; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnitcellRepresentation", function() { return tu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValidationRepresentation", function() { return eu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Version", function() { return ag; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Viewer", function() { return Ji; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Volume", function() { return Eo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VolumeComponent", function() { return Dl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WidelineBuffer", function() { return Nh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "autoLoad", function() { return ni; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatStructures", function() { return ic; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "download", function() { return dt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flatten", function() { return at; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataInfo", function() { return si; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFileInfo", function() { return ri; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getQuery", function() { return rt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "guessElement", function() { return tc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setDebug", function() { return Oe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setListingDatasource", function() { return Xe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMeasurementDefaultParams", function() { return Be; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setTrajectoryDatasource", function() { return Ye; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "superpose", function() { return kl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return ut; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "uniqueArray", function() { return gt; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_three__ = __webpack_require__(52);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Box3", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["d"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["i"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Euler", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["n"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Matrix3", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["y"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Matrix4", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["z"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Plane", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["H"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Quaternion", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["K"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Vector2", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["X"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Vector3", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["Y"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_chroma_js__ = __webpack_require__(111);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_chroma_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_chroma_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_signals__ = __webpack_require__(33);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_signals___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_2_signals__);
/* harmony reexport (binding) */ if(__webpack_require__.o(__WEBPACK_IMPORTED_MODULE_2_signals__, "Signal")) __webpack_require__.d(__webpack_exports__, "Signal", function() { return __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_sprintf_js__ = __webpack_require__(113);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_sprintf_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__);
function rt(t){if("undefined"==typeof window)return;const e=new RegExp(`${t}=([^&#=]*)`).exec(window.location.search);return e?decodeURIComponent(e[1]):void 0}function st(t,e){return void 0!==t?t:e}function nt(t,e){const i=Object.assign({},t);for(const r in e){void 0===t[r]&&(i[r]=e[r])}return i}function ot(t,e){for(const i in e){const r=e[i];void 0!==r&&(t[i]=r)}return t}function at(t,e){e=st(e,[]);for(let i=0;i<t.length;i++)Array.isArray(t[i])?at(t[i],e):e.push(t[i]);return e}function ct(){const t=window.location.protocol;return null===t.match(/http(s)?:/gi)?"http:":t}function lt(){if("undefined"==typeof window)return!1;const t=window.navigator.userAgent;return/Opera|OPR/.test(t)?"Opera":/Chrome/i.test(t)?"Chrome":/Firefox/i.test(t)?"Firefox":/Mobile(\/.*)? Safari/i.test(t)?"Mobile Safari":/MSIE/i.test(t)?"Internet Explorer":!!/Safari/i.test(t)&&"Safari"}function ht(t){window.open(t,"_blank")||(window.location.href=t)}function dt(t,e="download"){if(!t)return;const i="Safari"===lt(),r=/CriOS\/[\d]+/.test(window.navigator.userAgent),s=document.createElement("a");function n(t){ht(r?t:t.replace(/^data:[^;]*;/,"data:attachment/file;"))}if("undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob)navigator.msSaveOrOpenBlob(t,e);else if((i||r)&&FileReader)if(t instanceof Blob){var o=new FileReader;o.onloadend=function(){n(o.result)},o.readAsDataURL(t)}else n(t);else{let i=!1;t instanceof Blob&&(t=URL.createObjectURL(t),i=!0),"download"in s?(s.style.display="hidden",document.body.appendChild(s),s.href=t,s.download=e,s.target="_blank",s.click(),document.body.removeChild(s)):ht(t),i&&window.URL.revokeObjectURL(t)}}function ut(t,e,i){let r,s,n,o=null,a=0;function c(){a=!1===i.leading?0:Date.now(),o=null,n=t.apply(r,s),o||(r=s=null)}return i||(i={}),function(){var l=Date.now();a||!1!==i.leading||(a=l);var h=e-(l-a);return r=this,s=arguments,h<=0||h>e?(o&&(clearTimeout(o),o=null),a=l,n=t.apply(r,s),o||(r=s=null)):o||!1===i.trailing||(o=setTimeout(c,h)),n}}function mt(t,e){return t<e?-1:t>e?1:0}function pt(t,e,i=mt){let r=0,s=t.length-1;for(;r<=s;){const n=r+s>>1,o=i(e,t[n]);if(o>0)r=n+1;else{if(!(o<0))return n;s=n-1}}return-r-1}function ft(t,e,i){const r=function(t,e){let i=t.length-1;if(t[i]<e)return-1;let r=0;for(;r<=i;){const s=r+i>>1;t[s]>=e?i=s-1:r=s+1}return i+1}(t,e),s=function(t,e){if(t[0]>e)return-1;let i=0,r=t.length-1;for(;i<=r;){const s=i+r>>1;t[s]>e?r=s-1:i=s+1}return i-1}(t,i);return-1===r||-1===s||r>s?0:s-r+1}function gt(t){return t.sort().filter((function(t,e,i){return 0===e||t!==i[e-1]}))}function yt(t){const e=28672;if(t.length>e){const i=[];for(let r=0;r<t.length;r+=e)i.push(String.fromCharCode.apply(null,t.subarray(r,r+e)));return i.join("")}return String.fromCharCode.apply(null,t)}function bt(t,e){switch(t){case"int8":return new Int8Array(e);case"int16":return new Int16Array(e);case"int32":return new Int32Array(e);case"uint8":return new Uint8Array(e);case"uint16":return new Uint16Array(e);case"uint32":return new Uint32Array(e);case"float32":return new Float32Array(e);default:throw new Error("arrayType unknown: "+t)}}function xt(t,e){return new(e>65535?Uint32Array:Uint16Array)(t)}function vt(t){return t.buffer&&t.buffer instanceof ArrayBuffer?t.buffer:t}function wt(t,e){return void 0===t?t=new e:Array.isArray(t)&&(t=(new e).fromArray(t)),t}function At(t){return wt(t,e)}function _t(t){return wt(t,i)}function St(t){return wt(t,r)}function Ct(t){return e=t,i=Float32Array,e instanceof i?e:new i(e);var e,i}function Pt(t){return st(t,"").toString().toLowerCase()}class It{constructor(t){this.name=t,this._dict={}}add(t,e){this._dict[Pt(t)]=e}get(t){return this._dict[Pt(t)]}get names(){return Object.keys(this._dict)}}function kt(t){return.01745*t}const Mt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),Tt=new Array(36);function Bt(){let t,e=0;for(let i=0;i<36;i++)8===i||13===i||18===i||23===i?Tt[i]="-":14===i?Tt[i]="4":(e<=2&&(e=33554432+16777216*Math.random()|0),t=15&e,e>>=4,Tt[i]=Mt[19===i?3&t|8:t]);return Tt.join("")}function Dt(t,e,i){return Math.max(e,Math.min(i,t))}function $t(t,e,i){return t+(e-t)*i}function Ot(t,e,i,r,s,n){const o=(i-t)*n,a=(r-e)*n,c=s*s;return(2*e-2*i+o+a)*(s*c)+(-3*e+3*i-2*o-a)*c+o*s+e}function Rt(t,e,i){var r;return r=function(t,e,i){return(t-e)/(i-e)}(i,t,e),(i=Dt(r,0,1))*i*(3-2*i)}var Et="sRGB";const Ft={scale:"uniform",mode:"hcl",domain:[0,1],value:16777215,reverse:!1},Lt=new s;function Nt(t,e,i){const r=i.value;return i.value=function(t,e){let i=r.bind(this,t,e)();return"linear"==Et?(Lt.set(i),Lt.convertSRGBToLinear(),Lt.getHex()):i},i}class zt{constructor(t={}){this.parameters=nt(t,Ft),"string"==typeof this.parameters.value&&(this.parameters.value=Lt.set(this.parameters.value).getHex()),this.parameters.structure&&(this.atomProxy=this.parameters.structure.getAtomProxy())}getScale(t={}){const e=nt(t,this.parameters);return"rainbow"===e.scale?e.scale=["red","orange","yellow","green","blue"]:"rwb"===e.scale&&(e.scale=["red","white","blue"]),e.reverse&&(e.domain=e.domain.slice().reverse()),__WEBPACK_IMPORTED_MODULE_1_chroma_js__["scale"](e.scale).mode(e.mode).domain(e.domain).out("num")}colorToArray(t,e=[],i=0){return e[i]=(t>>16&255)/255,e[i+1]=(t>>8&255)/255,e[i+2]=(255&t)/255,e}atomColorToArray(t,e,i){return this.colorToArray(this.atomColor?this.atomColor(t):0,e,i)}bondColor(t,e){return this.atomProxy&&this.atomColor?(this.atomProxy.index=e?t.atomIndex1:t.atomIndex2,this.atomColor(this.atomProxy)):0}bondColorToArray(t,e,i,r){return this.colorToArray(this.bondColor(t,e),i,r)}volumeColorToArray(t,e,i){return this.colorToArray(this.volumeColor?this.volumeColor(t):0,e,i)}positionColorToArray(t,e,i){return this.colorToArray(this.positionColor?this.positionColor(t):0,e,i)}}var Vt;!function(t){t[t.PROTEIN=1]="PROTEIN",t[t.NUCLEIC=2]="NUCLEIC",t[t.RNA=3]="RNA",t[t.DNA=4]="DNA",t[t.POLYMER=5]="POLYMER",t[t.WATER=6]="WATER",t[t.HELIX=7]="HELIX",t[t.SHEET=8]="SHEET",t[t.TURN=9]="TURN",t[t.BACKBONE=10]="BACKBONE",t[t.SIDECHAIN=11]="SIDECHAIN",t[t.ALL=12]="ALL",t[t.HETERO=13]="HETERO",t[t.ION=14]="ION",t[t.SACCHARIDE=15]="SACCHARIDE",t[t.SUGAR=15]="SUGAR",t[t.BONDED=16]="BONDED",t[t.RING=17]="RING",t[t.AROMATICRING=18]="AROMATICRING",t[t.METAL=19]="METAL",t[t.POLARH=20]="POLARH",t[t.NONE=21]="NONE"}(Vt||(Vt={}));const Gt=["*","","ALL"],Ut=["NONE"],jt=[Vt.BACKBONE,Vt.SIDECHAIN,Vt.BONDED,Vt.RING,Vt.AROMATICRING,Vt.METAL,Vt.POLARH],Ht=[Vt.POLYMER,Vt.WATER],Wt=["ALA","GLY","SER"],qt=["CYS","SER","THR"],Xt=["ALA","ILE","LEU","MET","PHE","PRO","TRP","VAL"],Yt=["PHE","TRP","TYR","HIS"],Kt=["ASN","GLN"],Zt=["ASP","GLU"],Qt=["ARG","HIS","LYS"],Jt=["ARG","ASP","GLU","HIS","LYS"],te=["ASN","ARG","ASP","CYS","GLY","GLN","GLU","HIS","LYS","SER","THR","TYR"],ee=["ALA","ILE","LEU","MET","PHE","PRO","TRP","VAL"],ie=["HIS","PHE","PRO","TRP","TYR"],re=["ALA","GLY","ILE","LEU","VAL"];function se(t,e){if(void 0===e.atomname&&void 0===e.element&&void 0===e.altloc&&void 0===e.atomindex&&void 0===e.keyword&&void 0===e.inscode&&void 0===e.resname&&void 0===e.sstruc&&void 0===e.resno&&void 0===e.chainname&&void 0===e.model)return-1;if(void 0!==e.keyword){if(e.keyword===Vt.BACKBONE&&!t.isBackbone())return!1;if(e.keyword===Vt.SIDECHAIN&&!t.isSidechain())return!1;if(e.keyword===Vt.BONDED&&!t.isBonded())return!1;if(e.keyword===Vt.RING&&!t.isRing())return!1;if(e.keyword===Vt.AROMATICRING&&!t.isAromatic())return!1;if(e.keyword===Vt.HETERO&&!t.isHetero())return!1;if(e.keyword===Vt.PROTEIN&&!t.isProtein())return!1;if(e.keyword===Vt.NUCLEIC&&!t.isNucleic())return!1;if(e.keyword===Vt.RNA&&!t.isRna())return!1;if(e.keyword===Vt.DNA&&!t.isDna())return!1;if(e.keyword===Vt.POLYMER&&!t.isPolymer())return!1;if(e.keyword===Vt.WATER&&!t.isWater())return!1;if(e.keyword===Vt.HELIX&&!t.isHelix())return!1;if(e.keyword===Vt.SHEET&&!t.isSheet())return!1;if(e.keyword===Vt.TURN&&!t.isTurn())return!1;if(e.keyword===Vt.ION&&!t.isIon())return!1;if(e.keyword===Vt.SACCHARIDE&&!t.isSaccharide())return!1;if(e.keyword===Vt.METAL&&!t.isMetal())return!1;if(e.keyword===Vt.POLARH&&!t.isPolarHydrogen())return!1}if(void 0!==e.atomname&&e.atomname!==t.atomname)return!1;if(void 0!==e.element&&e.element!==t.element)return!1;if(void 0!==e.altloc&&e.altloc!==t.altloc)return!1;if(void 0!==e.atomindex&&pt(e.atomindex,t.index)<0)return!1;if(void 0!==e.resname)if(Array.isArray(e.resname)){if(!e.resname.includes(t.resname))return!1}else if(e.resname!==t.resname)return!1;if(void 0!==e.sstruc&&e.sstruc!==t.sstruc)return!1;if(void 0!==e.resno)if(Array.isArray(e.resno)&&2===e.resno.length){if(e.resno[0]>t.resno||e.resno[1]<t.resno)return!1}else if(e.resno!==t.resno)return!1;return(void 0===e.inscode||e.inscode===t.inscode)&&((void 0===e.chainname||e.chainname===t.chainname)&&(void 0===e.model||e.model===t.modelIndex))}function ne(t,e){if(void 0===e.resname&&void 0===e.resno&&void 0===e.inscode&&void 0===e.sstruc&&void 0===e.model&&void 0===e.chainname&&void 0===e.atomindex&&(void 0===e.keyword||jt.includes(e.keyword)))return-1;if(void 0!==e.keyword){if(e.keyword===Vt.HETERO&&!t.isHetero())return!1;if(e.keyword===Vt.PROTEIN&&!t.isProtein())return!1;if(e.keyword===Vt.NUCLEIC&&!t.isNucleic())return!1;if(e.keyword===Vt.RNA&&!t.isRna())return!1;if(e.keyword===Vt.DNA&&!t.isDna())return!1;if(e.keyword===Vt.POLYMER&&!t.isPolymer())return!1;if(e.keyword===Vt.WATER&&!t.isWater())return!1;if(e.keyword===Vt.HELIX&&!t.isHelix())return!1;if(e.keyword===Vt.SHEET&&!t.isSheet())return!1;if(e.keyword===Vt.TURN&&!t.isTurn())return!1;if(e.keyword===Vt.ION&&!t.isIon())return!1;if(e.keyword===Vt.SACCHARIDE&&!t.isSaccharide())return!1}if(void 0!==e.atomindex&&0===ft(e.atomindex,t.atomOffset,t.atomEnd))return!1;if(void 0!==e.resname)if(Array.isArray(e.resname)){if(!e.resname.includes(t.resname))return!1}else if(e.resname!==t.resname)return!1;if(void 0!==e.sstruc&&e.sstruc!==t.sstruc)return!1;if(void 0!==e.resno)if(Array.isArray(e.resno)&&2===e.resno.length){if(e.resno[0]>t.resno||e.resno[1]<t.resno)return!1}else if(e.resno!==t.resno)return!1;return(void 0===e.inscode||e.inscode===t.inscode)&&((void 0===e.chainname||e.chainname===t.chainname)&&(void 0===e.model||e.model===t.modelIndex))}function oe(t,e){if(!(void 0!==e.chainname||void 0!==e.model||void 0!==e.atomindex||void 0!==e.keyword&&Ht.includes(e.keyword)&&t.entity))return-1;if(void 0!==e.keyword){if(e.keyword===Vt.POLYMER&&!t.entity.isPolymer())return!1;if(e.keyword===Vt.WATER&&!t.entity.isWater())return!1}return(void 0===e.atomindex||0!==ft(e.atomindex,t.atomOffset,t.atomEnd))&&((void 0===e.chainname||e.chainname===t.chainname)&&(void 0===e.model||e.model===t.modelIndex))}function ae(t,e){return void 0===e.model&&void 0===e.atomindex?-1:(void 0===e.atomindex||0!==ft(e.atomindex,t.atomOffset,t.atomEnd))&&(void 0===e.model||e.model===t.index)}function ce(t,e){if(null===t)return!1;if(t.error)return!1;if(!t.rules||0===t.rules.length)return!1;const i=t.rules.length,r=!t.negate,s=!!t.negate,n=[];for(let r=0;r<i;++r){const i=t.rules[r];i.hasOwnProperty("operator")&&(n[r]=ce(i,e))}return function(o){const a="AND"===t.operator;let c=!1;for(let l=0;l<i;++l){const i=t.rules[l];let h;if(i.hasOwnProperty("operator")){const t=n[l];if(h=!1!==t?t(o):-1,-1===h){c=!0;continue}if(!0===h){if(a)continue;return r}if(a)return s}else{if(i.keyword===Vt.ALL){if(a)continue;return r}if(i.keyword===Vt.NONE){if(a)continue;return s}if(h=e(o,i),-1!==h){if(!0===h){if(a)continue;return r}if(a)return s}else c=!0}}return c?-1:a?r:s}}function le(t,e){if(t.error)return t;if(!t.rules||0===t.rules.length)return t;const i=t.rules.length,r={operator:t.operator,rules:[]};t.hasOwnProperty("negate")&&(r.negate=t.negate);for(let s=0;s<i;++s){const i=t.rules[s];if(i.hasOwnProperty("operator")){const t=le(i,e);null!==t&&r.rules.push(t)}else e(i)||r.rules.push(i)}return r.rules.length>0?t:null}function he(t,e=!1){let i=t;return e&&(i=le(t,(function(t){return void 0!==t.keyword&&!jt.includes(t.keyword)||(void 0!==t.model||(void 0!==t.chainname||(void 0!==t.resname||(void 0!==t.resno||void 0!==t.sstruc))))}))),ce(i,se)}function de(t,e=!1){let i=t;return e&&(i=le(t,(function(t){return!(void 0===t.keyword||!jt.includes(t.keyword))||(void 0!==t.model||(void 0!==t.chainname||(void 0!==t.atomname||(void 0!==t.element||void 0!==t.altloc))))}))),ce(i,ne)}function ue(t,e=!1){let i=t;return e&&(i=le(t,(function(t){return void 0!==t.keyword&&!Ht.includes(t.keyword)||(void 0!==t.resname||(void 0!==t.resno||(void 0!==t.atomname||(void 0!==t.element||(void 0!==t.altloc||(void 0!==t.sstruc||void 0!==t.inscode))))))}))),ce(i,oe)}function me(t,e=!1){let i=t;return e&&(i=le(t,(function(t){return void 0!==t.keyword||(void 0!==t.chainname||(void 0!==t.resname||(void 0!==t.resno||(void 0!==t.atomname||(void 0!==t.element||(void 0!==t.altloc||(void 0!==t.sstruc||void 0!==t.inscode)))))))}))),ce(i,ae)}class pe{constructor(t){this.signals={stringChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.setString(t)}get type(){return"selection"}setString(t,e){if(void 0===t&&(t=this.string||""),t===this.string)return;try{this.selection=function(t){let e={operator:void 0,rules:[]};if(!t)return e;let i,r,s=e;const n=[];"("===(t=t.replace(/\(/g," ( ").replace(/\)/g," ) ").trim()).charAt(0)&&")"===t.substr(-1)&&(t=t.slice(1,-1).trim());const o=t.split(/\s+/),a=t=>{i={operator:t,rules:[]},void 0===s?(s=i,e=i):(s.rules.push(i),n.push(s),s=i)},c=function(t){r=s,s=n.pop(),void 0===s&&(a(t),l(r))},l=function(t){s.rules.push(t)};let h=!1;for(let t=0;t<o.length;++t){const e=o[t],i=e.toUpperCase();if("("===e){h=!1,a();continue}if(")"===e){c(),s.negate&&c();continue}if(h>0)if("NOT"===i)h=1;else if(1===h)h=2;else{if(2!==h)throw new Error("something went wrong with 'not'");h=!1,c()}if("AND"===i){if("OR"===s.operator){const t=s.rules.pop();a("AND"),l(t)}else s.operator="AND";continue}if("OR"===i){"AND"===s.operator?c("OR"):s.operator="OR";continue}if("NOT"===e.toUpperCase()){h=1,a(),s.negate=!0;continue}if(+i!=+i){const t=Vt[i];if(void 0!==t){l({keyword:t});continue}}if("HYDROGEN"===i){l({operator:"OR",rules:[{element:"H"},{element:"D"}]});continue}if("SMALL"===i){l({resname:Wt});continue}if("NUCLEOPHILIC"===i){l({resname:qt});continue}if("HYDROPHOBIC"===i){l({resname:Xt});continue}if("AROMATIC"===i){l({resname:Yt});continue}if("AMIDE"===i){l({resname:Kt});continue}if("ACIDIC"===i){l({resname:Zt});continue}if("BASIC"===i){l({resname:Qt});continue}if("CHARGED"===i){l({resname:Jt});continue}if("POLAR"===i){l({resname:te});continue}if("NONPOLAR"===i){l({resname:ee});continue}if("CYCLIC"===i){l({resname:ie});continue}if("ALIPHATIC"===i){l({resname:re});continue}if("SIDECHAINATTACHED"===i){l({operator:"OR",rules:[{keyword:Vt.SIDECHAIN},{operator:"AND",negate:!1,rules:[{keyword:Vt.PROTEIN},{operator:"OR",negate:!1,rules:[{atomname:"CA"},{atomname:"BB"}]}]},{operator:"AND",negate:!1,rules:[{resname:"PRO"},{atomname:"N"}]},{operator:"AND",negate:!1,rules:[{keyword:Vt.NUCLEIC},{operator:"OR",negate:!0,rules:[{atomname:"P"},{atomname:"OP1"},{atomname:"OP2"},{atomname:"O3'"},{atomname:"O3*"},{atomname:"HO3'"},{atomname:"O5'"},{atomname:"O5*"},{atomname:"HO5'"},{atomname:"C5'"},{atomname:"C5*"},{atomname:"H5'"},{atomname:"H5''"}]}]}]});continue}if("APOLARH"===i){l({operator:"AND",negate:!1,rules:[{element:"H"},{negate:!0,operator:void 0,rules:[{keyword:Vt.POLARH}]}]});continue}if("LIGAND"===i){l({operator:"AND",rules:[{operator:"OR",rules:[{operator:"AND",rules:[{keyword:Vt.HETERO},{negate:!0,operator:void 0,rules:[{keyword:Vt.POLYMER}]}]},{negate:!0,operator:void 0,rules:[{keyword:Vt.POLYMER}]}]},{negate:!0,operator:void 0,rules:[{operator:"OR",rules:[{keyword:Vt.WATER},{keyword:Vt.ION}]}]}]});continue}if(-1!==Gt.indexOf(i)){l({keyword:Vt.ALL});continue}if("@"===e.charAt(0)){const t=e.substr(1).split(",").map((t=>parseInt(t)));t.sort((function(t,e){return t-e})),l({atomindex:t});continue}if("#"===e.charAt(0)){console.error("# for element selection deprecated, use _"),l({element:i.substr(1)});continue}if("_"===e.charAt(0)){l({element:i.substr(1)});continue}if("["===e[0]&&"]"===e[e.length-1]){const t=i.substr(1,e.length-2).split(","),r=t.length>1?t:t[0];l({resname:r});continue}if(e.length>=1&&e.length<=4&&"^"!==e[0]&&":"!==e[0]&&"."!==e[0]&&"%"!==e[0]&&"/"!==e[0]&&isNaN(parseInt(e))){l({resname:i});continue}const r={operator:"AND",rules:[]},n=e.split("/");if(n.length>1&&n[1]){if(isNaN(parseInt(n[1])))throw new Error("model must be an integer");r.rules.push({model:parseInt(n[1])})}const d=n[0].split("%");d.length>1&&r.rules.push({altloc:d[1]});const u=d[0].split(".");if(u.length>1&&u[1]){if(u[1].length>4)throw new Error("atomname must be one to four characters");r.rules.push({atomname:u[1].substring(0,4).toUpperCase()})}const m=u[0].split(":");m.length>1&&m[1]&&r.rules.push({chainname:m[1]});const p=m[0].split("^");if(p.length>1&&r.rules.push({inscode:p[1]}),p[0]){let t,e;"-"===p[0][0]&&(p[0]=p[0].substr(1),t=!0),p[0].includes("--")&&(p[0]=p[0].replace("--","-"),e=!0);let i=p[0].split("-");if(1===i.length){let e=parseInt(i[0]);if(isNaN(e))throw new Error("resi must be an integer");t&&(e*=-1),r.rules.push({resno:e})}else{if(2!==i.length)throw new Error("resi range must contain one '-'");{const s=i.map((t=>parseInt(t)));t&&(s[0]*=-1),e&&(s[1]*=-1),r.rules.push({resno:[s[0],s[1]]})}}}if(1===r.rules.length)l(r.rules[0]);else{if(!(r.rules.length>1))throw new Error("empty selection chunk");l(r)}}return void 0===e.operator&&1===e.rules.length&&e.rules[0].hasOwnProperty("operator")&&(e=e.rules[0]),e}(t)}catch(t){this.selection={error:t.message}}const i=this.selection;this.string=t,this.test=he(i),this.residueTest=de(i),this.chainTest=ue(i),this.modelTest=me(i),this.atomOnlyTest=he(i,!0),this.residueOnlyTest=de(i,!0),this.chainOnlyTest=ue(i,!0),this.modelOnlyTest=me(i,!0),e||this.signals.stringChanged.dispatch(this.string)}isAllSelection(){return Gt.includes(this.string.toUpperCase())}isNoneSelection(){return Ut.includes(this.string.toUpperCase())}}class fe extends zt{constructor(t){super(t),this.colormakerList=[],this.selectionList=[];(t.dataList||[]).forEach((t=>{const[e,i,r={}]=t;Fe.hasScheme(e)?Object.assign(r,{scheme:e,structure:this.parameters.structure}):Object.assign(r,{scheme:"uniform",value:new s(e).getHex()}),this.colormakerList.push(Fe.getScheme(r)),this.selectionList.push(new pe(i))}))}atomColor(t){for(let e=0,i=this.selectionList.length;e<i;++e){const i=this.selectionList[e].test;if(i&&i(t))return this.colormakerList[e].atomColor(t)}return 16777215}}const ge={"":"",OrRd:"[S] Orange-Red",PuBu:"[S] Purple-Blue",BuPu:"[S] Blue-Purple",Oranges:"[S] Oranges",BuGn:"[S] Blue-Green",YlOrBr:"[S] Yellow-Orange-Brown",YlGn:"[S] Yellow-Green",Reds:"[S] Reds",RdPu:"[S] Red-Purple",Greens:"[S] Greens",YlGnBu:"[S] Yellow-Green-Blue",Purples:"[S] Purples",GnBu:"[S] Green-Blue",Greys:"[S] Greys",YlOrRd:"[S] Yellow-Orange-Red",PuRd:"[S] Purple-Red",Blues:"[S] Blues",PuBuGn:"[S] Purple-Blue-Green",Viridis:"[D] Viridis",Spectral:"[D] Spectral",RdYlGn:"[D] Red-Yellow-Green",RdBu:"[D] Red-Blue",PiYG:"[D] Pink-Yellowgreen",PRGn:"[D] Purplered-Green",RdYlBu:"[D] Red-Yellow-Blue",BrBG:"[D] Brown-Bluegreen",RdGy:"[D] Red-Grey",PuOr:"[D] Purple-Orange",Set1:"[Q] Set1",Set2:"[Q] Set2",Set3:"[Q] Set3",Dark2:"[Q] Dark2",Paired:"[Q] Paired",Pastel1:"[Q] Pastel1",Pastel2:"[Q] Pastel2",Accent:"[Q] Accent",rainbow:"[?] Rainbow",rwb:"[?] Red-White-Blue"},ye={"":"",rgb:"Red Green Blue",hsv:"Hue Saturation Value",hsl:"Hue Saturation Lightness",hsi:"Hue Saturation Intensity",lab:"CIE L*a*b*",hcl:"Hue Chroma Lightness"};function be(t){const e=t;return t.forEach((function(t){t.__deps&&Array.prototype.push.apply(e,be(t.__deps))})),e}function xe(t){return gt(be(t)).map((function(t){return t.toString()})).join("\n\n\n")}function ve(t){const e=t.data.__name,i=t.data.__postId;if(void 0===e)console.error("message __name undefined");else if(void 0===self.func)console.error("worker func undefined",e);else{const e=function(t,e){t=t||{},void 0!==i&&(t.__postId=i);try{self.postMessage(t,e)}catch(e){console.error("self.postMessage:",e),self.postMessage(t)}};self.func(t,e)}}function we(t,e){let i="'use strict';\n\n"+xe(e);return i+="\n\n\nself.func = "+t.toString()+";",i+="\n\n\nself.onmessage = "+ve.toString()+";",new Blob([i],{type:"application/javascript"})}const Ae=lt();let _e=!1;try{const t=Object.defineProperty({},"passive",{get:function(){_e=!0}});window.addEventListener("test",(t=>{}),t)}catch(t){}const Se="undefined"!=typeof window&&void 0!==window.orientation;let Ce=!1;function Pe(t){Ce=t}let Ie=!1;function ke(t){Ie=t}const Me={log:Function.prototype.bind.call(console.log,console),info:Function.prototype.bind.call(console.info,console),warn:Function.prototype.bind.call(console.warn,console),error:Function.prototype.bind.call(console.error,console),time:Function.prototype.bind.call(console.time,console),timeEnd:Function.prototype.bind.call(console.timeEnd,console)};let Te={color:"green",labelColor:8421504,labelAttachment:"bottom-center",labelSize:.7,labelZOffset:.5,labelYOffset:.1,labelBorder:!0,labelBorderColor:13882323,labelBorderWidth:.25,lineOpacity:.8,linewidth:5,opacity:.6,labelUnit:"angstrom",arcVisible:!0,planeVisible:!1};function Be(t={}){Object.assign(Te,t)}let De=!!($e=rt("debug"))&&("string"!=typeof $e||/^1|true|t|yes|y$/i.test($e));var $e;function Oe(t){De=t}const Re=["ngl","js"],Ee=new class{constructor(){this.activeWorkerCount=0,this._funcDict={},this._depsDict={},this._blobDict={}}add(t,e,i){this._funcDict[t]=e,this._depsDict[t]=i}get(t){return this._blobDict[t]||(this._blobDict[t]=we(this._funcDict[t],this._depsDict[t])),this._blobDict[t]}},Fe=new class{constructor(){this.schemes={},this.userSchemes={}}getScheme(t){const e=((t||{}).scheme||"").toLowerCase();let i;return i=e in this.schemes?this.schemes[e]:e in this.userSchemes?this.userSchemes[e]:zt,new i(t)}getSchemes(){const t={};return Object.keys(this.schemes).forEach((function(e){t[e]=e})),Object.keys(this.userSchemes).forEach((function(e){t[e]=e.split("|")[1]})),t}getScales(){return ge}getModes(){return ye}add(t,e){t=t.toLowerCase(),this.schemes[t]=e}addScheme(t,e){return function(t){return t instanceof zt}(t)||(t=this._createScheme(t)),this._addUserScheme(t,e)}_addUserScheme(t,e){e=e||"";const i=`${Bt()}|${e}`.toLowerCase();return this.userSchemes[i]=t,i}removeScheme(t){t=t.toLowerCase(),delete this.userSchemes[t]}_createScheme(t){return class extends zt{constructor(e){super(e),t.call(this,e)}}}addSelectionScheme(t,e){return this._addUserScheme(class extends fe{constructor(e){super(Object.assign({dataList:t},e))}},e)}hasScheme(t){return(t=t.toLowerCase())in this.schemes||t in this.userSchemes}},Le=new It("datasource"),Ne=new It("representatation"),ze=new class extends It{constructor(){super("parser")}__hasObjName(t,e){const i=this.get(t);return i&&i.prototype.__objName===e}isTrajectory(t){return this.__hasObjName(t,"frames")}isStructure(t){return this.__hasObjName(t,"structure")}isVolume(t){return this.__hasObjName(t,"volume")}isSurface(t){return this.__hasObjName(t,"surface")}isBinary(t){const e=this.get(t);return e&&e.prototype.isBinary}isXml(t){const e=this.get(t);return e&&e.prototype.isXml}isJson(t){const e=this.get(t);return e&&e.prototype.isJson}getTrajectoryExtensions(){return this.names.filter((t=>this.isTrajectory(t)))}getStructureExtensions(){return this.names.filter((t=>this.isStructure(t)))}getVolumeExtensions(){return this.names.filter((t=>this.isVolume(t)))}getSurfaceExtensions(){return this.names.filter((t=>this.isSurface(t)))}},Ve=new It("shader"),Ge=new It("decompressor"),Ue=new It("component"),je=new It("buffer"),He=new It("picker");let We,qe;function Xe(t){We=t}function Ye(t){qe=t}class Ke{constructor(t,e={}){this.chunkSize=10485760,this.newline="\n",this.__pointer=0,this.__partialLine="",this.compressed=st(e.compressed,!1),this.binary=st(e.binary,!1),this.json=st(e.json,!1),this.xml=st(e.xml,!1),this.src=t}isBinary(){return this.binary||this.compressed}read(){return this._read().then((t=>{const e=this.compressed?Ge.get(this.compressed):void 0;return this.compressed&&e?this.data=e(t):((this.binary||this.compressed)&&t instanceof ArrayBuffer&&(t=new Uint8Array(t)),this.data=t),this.data}))}_chunk(t,e){return e=Math.min(this.data.length,e),0===t&&this.data.length===e?this.data:this.isBinary()?this.data.subarray(t,e):this.data.substring(t,e)}chunk(t){const e=t+this.chunkSize;return this._chunk(t,e)}peekLines(t){const e=this.data,i=e.length,r=this.isBinary()?this.newline.charCodeAt(0):this.newline;let s,n=0;for(s=0;s<i&&(e[s]===r&&++n,n!==t);++s);const o=this._chunk(0,s+1);return this.chunkToLines(o,"",s>i).lines}chunkCount(){return Math.floor(this.data.length/this.chunkSize)+1}asText(){return this.isBinary()?yt(this.data):this.data}chunkToLines(t,e,i){const r=this.newline;if(!this.isBinary()&&t.length===this.data.length)return{lines:t.split(r),partialLine:""};let s=[];const n=this.isBinary()?yt(t):t,o=n.lastIndexOf(r);if(-1===o)e+=n;else{const t=e+n.substr(0,o);s=s.concat(t.split(r)),e=o===n.length-r.length?"":n.substr(o+r.length)}return i&&""!==e&&s.push(e),{lines:s,partialLine:e}}nextChunk(){const t=this.__pointer;if(!(t>this.data.length))return this.__pointer+=this.chunkSize,this.chunk(t)}nextChunkOfLines(){const t=this.nextChunk();if(void 0===t)return;const e=this.__pointer>this.data.length,i=this.chunkToLines(t,this.__partialLine,e);return this.__partialLine=i.partialLine,i.lines}eachChunk(t){const e=this.chunkSize,i=this.data.length,r=this.chunkCount();for(let s=0;s<i;s+=e){t(this.chunk(s),Math.round(s/e),r)}}eachChunkOfLines(t){this.eachChunk(((e,i,r)=>{const s=i===r+1,n=this.chunkToLines(e,this.__partialLine,s);this.__partialLine=n.partialLine,t(n.lines,i,r)}))}dispose(){delete this.src}}class Ze extends Ke{_read(){return new Promise(((t,e)=>{const i=this.src,r=new FileReader;r.onload=e=>{e.target&&t(e.target.result)},r.onerror=t=>e(t),this.binary||this.compressed?r.readAsArrayBuffer(i):r.readAsText(i)}))}}class Qe extends Ke{_read(){return new Promise(((t,e)=>{const i=this.src,r=new XMLHttpRequest;r.open("GET",i,!0),r.addEventListener("load",(()=>{if(200===r.status||304===r.status||0===r.status)try{t(r.response)}catch(t){e(t)}else e(r.statusText)}),!1),r.addEventListener("error",(t=>e("network error")),!1),this.isBinary()?r.responseType="arraybuffer":this.json?r.responseType="json":this.xml?r.responseType="document":r.responseType="text",r.send()}))}}class Je{constructor(t,e={}){this.parameters=nt(e,{ext:"",compressed:!1,binary:ze.isBinary(e.ext||""),name:"",dir:"",path:"",protocol:""});const i={compressed:this.parameters.compressed,binary:this.parameters.binary,json:ze.isJson(this.parameters.ext),xml:ze.isXml(this.parameters.ext)};"undefined"!=typeof File&&t instanceof File||"undefined"!=typeof Blob&&t instanceof Blob?this.streamer=new Ze(t,i):this.streamer=new Qe(t,i)}}class ti extends Je{constructor(t,e={}){super(t,e),this.parserParams={voxelSize:e.voxelSize,firstModelOnly:e.firstModelOnly,asTrajectory:e.asTrajectory,cAlphaOnly:e.cAlphaOnly,delimiter:e.delimiter,comment:e.comment,columnNames:e.columnNames,inferBonds:e.inferBonds,name:this.parameters.name,path:this.parameters.path}}load(){return new(ze.get(this.parameters.ext))(this.streamer,this.parserParams).parse()}}class ei{constructor(t,e,i){this.name=e,this.path=i,this.signals={elementAdded:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],elementRemoved:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],nameChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.type="Script",this.dir=i.substring(0,i.lastIndexOf("/")+1);try{this.fn=new Function("stage","__name","__path","__dir",t)}catch(t){Me.error("Script compilation failed",t),this.fn=function(){}}}run(t){return new Promise(((e,i)=>{try{this.fn.apply(null,[t,this.name,this.path,this.dir]),e()}catch(t){Me.error("Script.fn",t),i(t)}}))}}class ii extends Je{load(){return this.streamer.read().then((()=>new ei(this.streamer.asText(),this.parameters.name,this.parameters.path)))}}function ri(t){const e=Ge.names;let i,r,s="";i=t instanceof File?t.name:t instanceof Blob?"":t;const n=i.lastIndexOf("?"),o=-1!==n?i.substring(n):"";i=i.substring(0,-1===n?i.length:n);const a=i.replace(/^.*[\\/]/,"");let c=a.substring(0,a.lastIndexOf("."));const l=a.split(".");let h=l.length>1?(l.pop()||"").toLowerCase():"";const d=i.match(/^(.+):\/\/(.+)$/);d&&(s=d[1].toLowerCase(),i=d[2]||"");const u=i.substring(0,i.lastIndexOf("/")+1);if(e.includes(h)){r=h;const t=i.length-h.length-1;h=(i.substr(0,t).split(".").pop()||"").toLowerCase();const e=c.length-h.length-1;c=c.substr(0,e)}else r=!1;return{path:i,name:a,ext:h,base:c,dir:u,compressed:r,protocol:s,query:o,src:t}}function si(t){let e=ri(t);const i=Le.get(e.protocol);return i&&(e=ri(i.getUrl(e.src)),!e.ext&&i.getExt&&(e.ext=i.getExt(t))),e}function ni(t,e={}){const i=Object.assign(si(t),e);let r;return ze.names.includes(i.ext)?r=new ti(i.src,i):Re.includes(i.ext)&&(r=new ii(i.src,i)),r?r.load():Promise.reject(new Error(`autoLoad: ext '${i.ext}' unknown`))}class oi{getBlob(){return new Blob([this.getData()],{type:this.mimeType})}download(t,e){t=st(t,this.defaultName),e=st(e,this.defaultExt),dt(this.getBlob(),`${t}.${e}`)}}class ai extends oi{constructor(t,e){super(),this.mimeType="text/plain",this.defaultName="structure",this.defaultExt="pdb";const i=Object.assign({},e);this.renumberSerial=st(i.renumberSerial,!0),this.remarks=function(t){return Array.isArray(t)?t:[t]}(st(i.remarks,[])),this.structure=t,this._records=[]}_writeRecords(){this._records.length=0,this._writeTitle(),this._writeRemarks(),this._writeAtoms()}_writeTitle(){this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("TITLE %-74s",this.structure.name))}_writeRemarks(){this.remarks.forEach((t=>{this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("REMARK %-73s",t))})),this.structure.trajectory&&(this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("REMARK %-73s","Trajectory '"+this.structure.trajectory.name+"'")),this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("REMARK %-73s",`Frame ${this.structure.trajectory.frame}`)))}_writeAtoms(){let t=1,e=1,i=" ",r=" ";const s=this.structure.modelStore.count>1;this.structure.eachModel((n=>{s&&this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("MODEL     %4d%-66s",e++,"")),n.eachAtom((e=>{const s=e.hetero?"HETATM%5d %-4s %3s %1s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f      %4s%2s%1s%1s":"ATOM  %5d %-4s %3s %1s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f      %4s%2s%1s%1s",n=this.renumberSerial?t:e.serial;let o=e.atomname;(1===o.length||o.length<4&&1===e.element.length&&o[0]===e.element)&&(o=" "+o),e.formalCharge?(i=Math.abs(e.formalCharge).toPrecision(1),r=e.formalCharge>0?"+":"-"):(i=" ",r=" "),this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])(s,n,o,e.resname,st(e.chainname," "),e.resno,e.x,e.y,e.z,st(e.occupancy,1),st(e.bfactor,0),"",st(e.element,""),i,r)),t+=1}),this.structure.getSelection()),s&&this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("%-80s","ENDMDL"))})),this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("%-80s","END"))}getString(){return console.warn("PdbWriter.getString() is deprecated, use .getData instead"),this.getData()}getData(){return this._writeRecords(),this._records.join("\n")}}class ci extends oi{constructor(t){super(),this.mimeType="text/plain",this.defaultName="structure",this.defaultExt="sdf",this.structure=t,this._records=[]}get idString(){return this.structure.id}get titleString(){return"  "+this.structure.title}get countsString(){return Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("%3i%3i  0  0  0  0  0  0  0  0999 V2000",this.structure.atomCount,this.structure.bondCount)}get chargeLines(){const t=[];this.structure.eachAtom((e=>{null!=e.formalCharge&&0!==e.formalCharge&&t.push([e.index,e.formalCharge])}));const e=[];for(let i=0;i<t.length;i+=8){const r=Math.min(8,t.length-i);let s=Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("M  CHG%3i",r);for(let e=i;e<i+r;e++)s+=Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])(" %3i %3i",t[e][0]+1,t[e][1]);e.push(s)}return e}formatAtom(t){let e=0;null!=t.formalCharge&&0!==t.formalCharge&&(e=4-t.formalCharge);const i=Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("%10.4f%10.4f%10.4f %-3s 0%3i  0  0  0",t.x,t.y,t.z,t.element,e);if(48!==i.length)throw new Error("Incompatible atom for sdf format");return i}formatBond(t){return Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])("%3i%3i%3i  0  0  0",t.atomIndex1+1,t.atomIndex2+1,t.bondOrder)}_writeRecords(){this._records.length=0,this._writeHeader(),this._writeCTab(),this._writeFooter()}_writeHeader(){this._records.push(this.idString,this.titleString,"")}_writeCTab(){this._records.push(this.countsString),this.structure.eachAtom((t=>{this._records.push(this.formatAtom(t))})),this.structure.eachBond((t=>{this._records.push(this.formatBond(t))})),this.chargeLines.forEach((t=>{this._records.push(t)})),this._records.push("M  END")}_writeFooter(){this._records.push("$$$$")}getData(){return this._writeRecords(),this._records.join("\n")}}const li=[];class hi{constructor(t,e={}){this._mark=0,this._marks=[],this.offset=0,this.littleEndian=!0;let i=!1;void 0===t&&(t=8192),"number"==typeof t?t=new ArrayBuffer(t):i=!0;const r=e.offset?e.offset>>>0:0;let s=t.byteLength-r,n=r;t instanceof ArrayBuffer||(t.byteLength!==t.buffer.byteLength&&(n=t.byteOffset+r),t=t.buffer),this._lastWrittenByte=i?s:0,this.buffer=t,this.length=s,this.byteLength=s,this.byteOffset=n,this._data=new DataView(this.buffer,n,s)}available(t){return void 0===t&&(t=1),this.offset+t<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){return this.littleEndian=!0,this}isBigEndian(){return!this.littleEndian}setBigEndian(){return this.littleEndian=!1,this}skip(t){return void 0===t&&(t=1),this.offset+=t,this}seek(t){return this.offset=t,this}mark(){return this._mark=this.offset,this}reset(){return this.offset=this._mark,this}pushMark(){return this._marks.push(this.offset),this}popMark(){const t=this._marks.pop();if(void 0===t)throw new Error("Mark stack empty");return this.seek(t),this}rewind(){return this.offset=0,this}ensureAvailable(t){if(void 0===t&&(t=1),!this.available(t)){const e=2*(this.offset+t),i=new Uint8Array(e);i.set(new Uint8Array(this.buffer)),this.buffer=i.buffer,this.length=this.byteLength=e,this._data=new DataView(this.buffer)}return this}readBoolean(){return 0!==this.readUint8()}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(t){void 0===t&&(t=1);for(var e=new Uint8Array(t),i=0;i<t;i++)e[i]=this.readByte();return e}readInt16(){var t=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,t}readUint16(){var t=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,t}readInt32(){var t=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,t}readUint32(){var t=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat32(){var t=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat64(){var t=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,t}readChar(){return String.fromCharCode(this.readInt8())}readChars(t=1){li.length=t;for(var e=0;e<t;e++)li[e]=this.readChar();return li.join("")}writeBoolean(t=!1){return this.writeUint8(t?255:0),this}writeInt8(t){return this.ensureAvailable(1),this._data.setInt8(this.offset++,t),this._updateLastWrittenByte(),this}writeUint8(t){return this.ensureAvailable(1),this._data.setUint8(this.offset++,t),this._updateLastWrittenByte(),this}writeByte(t){return this.writeUint8(t)}writeBytes(t){this.ensureAvailable(t.length);for(var e=0;e<t.length;e++)this._data.setUint8(this.offset++,t[e]);return this._updateLastWrittenByte(),this}writeInt16(t){return this.ensureAvailable(2),this._data.setInt16(this.offset,t,this.littleEndian),this.offset+=2,this._updateLastWrittenByte(),this}writeUint16(t){return this.ensureAvailable(2),this._data.setUint16(this.offset,t,this.littleEndian),this.offset+=2,this._updateLastWrittenByte(),this}writeInt32(t){return this.ensureAvailable(4),this._data.setInt32(this.offset,t,this.littleEndian),this.offset+=4,this._updateLastWrittenByte(),this}writeUint32(t){return this.ensureAvailable(4),this._data.setUint32(this.offset,t,this.littleEndian),this.offset+=4,this._updateLastWrittenByte(),this}writeFloat32(t){return this.ensureAvailable(4),this._data.setFloat32(this.offset,t,this.littleEndian),this.offset+=4,this._updateLastWrittenByte(),this}writeFloat64(t){return this.ensureAvailable(8),this._data.setFloat64(this.offset,t,this.littleEndian),this.offset+=8,this._updateLastWrittenByte(),this}writeChar(t){return this.writeUint8(t.charCodeAt(0))}writeChars(t){for(var e=0;e<t.length;e++)this.writeUint8(t.charCodeAt(e));return this}toArray(){return new Uint8Array(this.buffer,this.byteOffset,this._lastWrittenByte)}_updateLastWrittenByte(){this.offset>this._lastWrittenByte&&(this._lastWrittenByte=this.offset)}}class di extends oi{constructor(t){super(),this.mimeType="application/vnd.ms-pki.stl",this.defaultName="surface",this.defaultExt="stl",this.surface=t}getData(){const t=this.surface.index.length/3,i=new hi(2*t+3*t*4*4+80+4);i.skip(80),i.writeUint32(t);const r=new e,s=new e,n=new e,o=new e;for(let e=0;e<t;e++){const t=[this.surface.index[3*e],this.surface.index[3*e+1],this.surface.index[3*e+2]];s.fromArray(this.surface.normal,3*t[0]),n.fromArray(this.surface.normal,3*t[1]),o.fromArray(this.surface.normal,3*t[2]),r.addVectors(s,n).add(o).normalize(),i.writeFloat32(r.x),i.writeFloat32(r.y),i.writeFloat32(r.z);for(let e=0;e<3;e++)r.fromArray(this.surface.position,3*t[e]),i.writeFloat32(r.x),i.writeFloat32(r.y),i.writeFloat32(r.z);i.writeUint16(0)}return new DataView(i.buffer)}}class ui{constructor(){this.count=0,this.signals={countChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]}}clear(){this.change(-this.count)}change(t){this.count+=t,this.signals.countChanged.dispatch(t,this.count),this.count<0&&Me.warn("Counter.count below zero",this.count)}increment(){this.change(1)}decrement(){this.change(-1)}listen(t){this.change(t.count),t.signals.countChanged.add(this.change,this)}unlisten(t){const e=t.signals.countChanged;e.has(this.change,this)&&e.remove(this.change,this)}onZeroOnce(t,e){if(0===this.count)t.call(e);else{const i=()=>{0===this.count&&(this.signals.countChanged.remove(i,this),t.call(e))};this.signals.countChanged.add(i,this)}}dispose(){this.clear(),this.signals.countChanged.dispose()}}Ve.add("shader/BasicLine.vert","void main(){\n#include begin_vertex\n#include project_vertex\n}"),Ve.add("shader/BasicLine.frag","uniform vec3 uColor;\n#include common\n#include fog_pars_fragment\nvoid main(){\ngl_FragColor = vec4( uColor, 1.0 );\n#include premultiplied_alpha_fragment\n#include tonemapping_fragment\n#include encodings_fragment\n#include fog_fragment\n}"),Ve.add("shader/Quad.vert","varying vec2 vUv;\nvoid main() {\nvUv = uv;\ngl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"),Ve.add("shader/Quad.frag","varying vec2 vUv;\nuniform sampler2D tForeground;\nuniform float scale;\nvoid main() {\nvec4 foreground = texture2D( tForeground, vUv );\ngl_FragColor = foreground * scale;\n}");class mi{constructor(){this.signals={updated:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.maxDuration=-1/0,this.minDuration=1/0,this.avgDuration=14,this.lastDuration=1/0,this.prevFpsTime=0,this.lastFps=1/0,this.lastFrames=1,this.frames=0,this.count=0,this.begin()}update(){this.startTime=this.end(),this.currentTime=this.startTime,this.signals.updated.dispatch()}begin(){this.startTime=window.performance.now(),this.lastFrames=this.frames}end(){const t=window.performance.now();return this.count+=1,this.frames+=1,this.lastDuration=t-this.startTime,this.minDuration=Math.min(this.minDuration,this.lastDuration),this.maxDuration=Math.max(this.maxDuration,this.lastDuration),this.avgDuration-=this.avgDuration/30,this.avgDuration+=this.lastDuration/30,t>this.prevFpsTime+1e3&&(this.lastFps=this.frames,this.prevFpsTime=t,this.frames=0),t}}Ve.add("shader/chunk/fog_fragment.glsl","#ifdef USE_FOG\nfloat depth = length( vViewPosition );\n#ifdef FOG_EXP2\nfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n#else\nfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n#endif\ngl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"),Ve.add("shader/chunk/interior_fragment.glsl","if( gl_FrontFacing == false ){\n#ifdef USE_INTERIOR_COLOR\noutgoingLight.xyz = interiorColor;\n#else\n#ifdef DIFFUSE_INTERIOR\noutgoingLight.xyz = vColor;\n#endif\n#endif\noutgoingLight.xyz *= 1.0 - interiorDarkening;\n}"),Ve.add("shader/chunk/matrix_scale.glsl","float matrixScale( in mat4 m ){\nvec4 r = m[ 0 ];\nreturn sqrt( r[ 0 ] * r[ 0 ] + r[ 1 ] * r[ 1 ] + r[ 2 ] * r[ 2 ] );\n}"),Ve.add("shader/chunk/nearclip_vertex.glsl","#ifdef NEAR_CLIP\nif( vViewPosition.z < clipNear - 5.0 )\ngl_Position.z = 2.0 * gl_Position.w;\n#endif"),Ve.add("shader/chunk/nearclip_fragment.glsl","#ifdef NEAR_CLIP\nif( vViewPosition.z < clipNear )\ndiscard;\n#endif"),Ve.add("shader/chunk/opaque_back_fragment.glsl","#ifdef OPAQUE_BACK\n#ifdef FLIP_SIDED\nif( gl_FrontFacing == true ){\ngl_FragColor.a = 1.0;\n}\n#else\nif( gl_FrontFacing == false ){\ngl_FragColor.a = 1.0;\n}\n#endif\n#endif"),Ve.add("shader/chunk/radiusclip_vertex.glsl","#ifdef RADIUS_CLIP\nif( distance( vViewPosition, vClipCenter ) > clipRadius + 5.0 )\ngl_Position.z = 2.0 * gl_Position.w;\n#endif"),Ve.add("shader/chunk/radiusclip_fragment.glsl","#ifdef RADIUS_CLIP\nif( distance( vViewPosition, vClipCenter ) > clipRadius )\ndiscard;\n#endif"),Ve.add("shader/chunk/unpack_color.glsl","vec3 unpackColor(float f) {\nvec3 color;\ncolor.r = floor(f / 256.0 / 256.0);\ncolor.g = floor((f - color.r * 256.0 * 256.0) / 256.0);\ncolor.b = floor(f - color.r * 256.0 * 256.0 - color.g * 256.0);\nreturn color / 255.0;\n}");const pi=/^(?!\/\/)\s*#include\s+(\S+)/gim,fi={};function gi(t,e={}){let i=t+"|";for(const t in e)i+=t+":"+e[t];if(!fi[i]){const r=function(t){if(void 0===t)return"";const e=[];for(const i in t){const r=t[i];r&&e.push(`#define ${i} ${r}`)}return e.join("\n")+"\n"}(e);let s=Ve.get(`shader/${t}`);if(!s)throw new Error(`empty shader, '${t}'`);s=s.replace(pi,(function(t,e){const i=`shader/chunk/${e}.glsl`,r=Ve.get(i)||__WEBPACK_IMPORTED_MODULE_0_three__["N" /* ShaderChunk */][e];if(!r)throw new Error(`empty chunk, '${e}'`);return r})),fi[i]=r+s}return fi[i]}if("undefined"!=typeof WebGLRenderingContext){const t=WebGLRenderingContext.prototype,e=t.getShaderParameter;t.getShaderParameter=function(){return!De||e.apply(this,arguments)};const i=t.getShaderInfoLog;t.getShaderInfoLog=function(){return De?i.apply(this,arguments):""};const r=t.getProgramParameter;t.getProgramParameter=function(e,i){return!De&&i===t.LINK_STATUS||r.apply(this,arguments)};const s=t.getProgramInfoLog;t.getProgramInfoLog=function(){return De?s.apply(this,arguments):""}}const yi=[[[0,0]],[[4,4],[-4,-4]],[[-2,-6],[6,-2],[-6,2],[2,6]],[[1,-3],[-1,3],[5,1],[-3,-5],[-5,5],[-7,-1],[3,7],[7,-7]],[[1,1],[-1,-3],[-3,2],[4,-1],[-5,-2],[2,5],[5,3],[3,-5],[-2,6],[0,-7],[-4,-6],[-6,4],[-8,0],[7,-4],[6,7],[-7,-8]],[[-4,-7],[-7,-5],[-3,-5],[-5,-4],[-1,-4],[-2,-2],[-6,-1],[-4,0],[-7,1],[-1,2],[-6,3],[-3,3],[-7,6],[-3,6],[-5,7],[-1,7],[5,-7],[1,-6],[6,-5],[4,-4],[2,-3],[7,-2],[1,-1],[4,-1],[2,1],[6,2],[0,4],[4,4],[2,5],[7,5],[5,6],[3,7]]];yi.forEach((t=>{t.forEach((t=>{t[0]*=.0625,t[1]*=.0625}))}));class bi{constructor(t,e,i,r){this.canvas=document.createElement("canvas"),this._viewer=i,this._factor=st(r.factor,2),this._antialias=st(r.antialias,!1),this._onProgress=r.onProgress,this._onFinish=r.onFinish,this._antialias&&(this._factor*=2),this._n=this._factor*this._factor,this._width=this._viewer.width,this._height=this._viewer.height,this._antialias?(this.canvas.width=this._width*this._factor/2,this.canvas.height=this._height*this._factor/2):(this.canvas.width=this._width*this._factor,this.canvas.height=this._height*this._factor),this._ctx=this.canvas.getContext("2d"),this._viewerSampleLevel=i.sampleLevel,this._viewer.setSampling(-1)}_renderTile(t){const e=this._viewer,i=this._width,r=this._height,s=this._factor,n=t%s*i,o=Math.floor(t/s)*r;if(e.camera.setViewOffset(i*s,r*s,n,o,i,r),e.render(),this._antialias){const t=Math.round((n+i)/2)-Math.round(n/2),s=Math.round((o+r)/2)-Math.round(o/2);this._ctx.drawImage(e.renderer.domElement,Math.round(n/2),Math.round(o/2),t,s)}else this._ctx.drawImage(e.renderer.domElement,Math.floor(n),Math.floor(o),Math.ceil(i),Math.ceil(r));"function"==typeof this._onProgress&&this._onProgress(t+1,this._n,!1)}_finalize(){this._viewer.setSampling(this._viewerSampleLevel),this._viewer.camera.view=null,"function"==typeof this._onFinish&&this._onFinish(this._n+1,this._n,!1)}render(){for(let t=0;t<=this._n;++t)t===this._n?this._finalize():this._renderTile(t)}renderAsync(){let t=0;const e=this._n,i=()=>{t===e?this._finalize():this._renderTile(t),t+=1};for(let t=0;t<=e;++t)setTimeout(i,0)}}const xi=2*Math.PI,vi=180/Math.PI;function wi(t,e,i=1,r=0,s){const n=s?s.length:t.length/i;let o=0,a=0;if(s)for(let c=0;c<n;++c){const n=(t[s[c]*i+r]+e)%e/e*xi-Math.PI;o+=Math.cos(n),a+=Math.sin(n)}else for(let s=r;s<n;s+=i){const i=(t[s]+e)%e/e*xi-Math.PI;o+=Math.cos(i),a+=Math.sin(i)}o/=n,a/=n;return(Math.atan2(a,o)+Math.PI)/xi*e}function Ai(t,e,i,r=0){const s=t.length,n=i||new Float32Array(s);for(let i=0;i<s;i+=3)n[r+i+0]=(t[i+0]+e[i+0])/2,n[r+i+1]=(t[i+1]+e[i+1])/2,n[r+i+2]=(t[i+2]+e[i+2])/2;return n}function _i(t,e){const i=t.length,r=new Float32Array(i);for(let s=0;s<i;s+=3)r[s+0]=e[s+0]-t[s+0],r[s+1]=e[s+1]-t[s+1],r[s+2]=e[s+2]-t[s+2];return r}function Si(t,e,i){const r=i||new Float32Array(t);for(let i=0;i<t;++i)r[i]=e;return r}function Ci(t,e,i,r,s){const n=s||new Float32Array(3*t);for(let s=0;s<t;++s){const t=3*s;n[t+0]=e,n[t+1]=i,n[t+2]=r}return n}function Pi(t){const e=new Float32Array(t);for(let i=0;i<t;++i)e[i]=i;return e}function Ii(t,e,i=0,r){const s=r||new Float32Array(t*e);for(let r=0;r<t;++r){const t=i+r*e;for(let i=0;i<e;++i)s[t+i]=r}return s}function ki(t,e){const i=t.length,r=new Float32Array(i*e);for(let s=0;s<i;++s){const i=s*e,n=t[s];for(let t=0;t<e;++t)r[i+t]=n}return r}function Mi(t,e,i,r,s){for(let n=0;n<s;++n)e[r+n]=t[i+n]}function Ti(t,e,i,r){Mi(t,t,e,i,r)}function Bi(t){let e=-1/0;for(let i=0,r=t.length;i<r;++i)t[i]>e&&(e=t[i]);return e}function Di(t){let e=1/0;for(let i=0,r=t.length;i<r;++i)t[i]<e&&(e=t[i]);return e}function $i(t,e=1,i=0){const r=t.length;let s=0;for(let n=i;n<r;n+=e)s+=t[n];return s}function Oi(t,e=1,i=0){return $i(t,e,i)/(t.length/e)}const Ri={trim:!1,factor:1,antialias:!1,transparent:!1,onProgress:void 0};function Ei(t,e={}){const{trim:i,factor:r,antialias:s,transparent:n}=nt(e,Ri),o=t.renderer,a=t.camera,c=o.getClearAlpha(),l=o.getClearColor();function h(e=!1){let i=r;s&&(i*=2),e&&(i=1/i),t.scene.traverse((function(t){const e=t.material;e&&e.linewidth&&(e.linewidth*=i),e&&e.uniforms&&e.uniforms.size&&void 0===e.uniforms.size.__seen&&(e.uniforms.size.value*=i,e.uniforms.size.__seen=!0),e&&e.uniforms&&e.uniforms.linewidth&&void 0===e.uniforms.linewidth.__seen&&(e.uniforms.linewidth.value*=i,e.uniforms.linewidth.__seen=!0)})),t.scene.traverse((function(t){const e=t.material;e&&e.uniforms&&e.uniforms.size&&delete e.uniforms.size.__seen,e&&e.uniforms&&e.uniforms.linewidth&&delete e.uniforms.linewidth.__seen}))}function d(t){if(i){const e=l;return function(t,e,i,r,s){const n=t.height,o=t.width,a=t.getContext("2d").getImageData(0,0,o,n).data;let c,l,h,d;for(h=!1,l=0;l<n;l++){for(c=0;c<o;c++)if(d=4*(l*o+c),a[d]!==e||a[d+1]!==i||a[d+2]!==r||a[d+3]!==s){h=!0;break}if(h)break}const u=l;for(h=!1,c=0;c<o;c++){for(l=0;l<n;l++)if(d=4*(l*o+c),a[d]!==e||a[d+1]!==i||a[d+2]!==r||a[d+3]!==s){h=!0;break}if(h)break}const m=c;for(h=!1,l=n-1;l>=0;l--){for(c=o-1;c>=0;c--)if(d=4*(l*o+c),a[d]!==e||a[d+1]!==i||a[d+2]!==r||a[d+3]!==s){h=!0;break}if(h)break}const p=l;for(h=!1,c=o-1;c>=0;c--){for(l=n-1;l>=0;l--)if(d=4*(l*o+c),a[d]!==e||a[d+1]!==i||a[d+2]!==r||a[d+3]!==s){h=!0;break}if(h)break}const f=c,g=document.createElement("canvas");return g.width=f-m,g.height=p-u,g.getContext("2d").drawImage(t,m,u,g.width,g.height,0,0,g.width,g.height),g}(t,n?0:255*e.r,n?0:255*e.g,n?0:255*e.b,n?0:255)}return t}function u(t,i,r){"function"==typeof e.onProgress&&e.onProgress(t,i,r)}return new Promise((function(e,i){const l=new bi(o,a,t,{factor:r,antialias:s,onProgress:u,onFinish:function(r,s){d(l.canvas).toBlob((function(r){o.setClearAlpha(c),h(!0),t.requestRender(),u(s,s,!0),r?e(r):i("error creating image")}),"image/png")}});o.setClearAlpha(n?0:1),h(),l.renderAsync()}))}const Fi=new e,Li=new i,Ni=new i;const zi=new t,Vi=new i,Gi=new i;function Ui(t,e){Vi.getInverse(e.projectionMatrix),Gi.copy(e.projectionMatrix).transpose(),t.traverse((function(t){const e=t.material;if(!e)return;const i=e.uniforms;i&&(i.projectionMatrixInverse&&i.projectionMatrixInverse.value.copy(Vi),i.projectionMatrixTranspose&&i.projectionMatrixTranspose.value.copy(Gi))}))}function ji(t,e,i){const r=t.createShader(i);if(!r)return void console.log(`error creating WebGL shader ${i}`);t.shaderSource(r,e),t.compileShader(r);return t.getShaderParameter(r,t.COMPILE_STATUS)?r:(console.log(`error compiling shader ${r}: ${t.getShaderInfoLog(r)}`),t.deleteShader(r),null)}function Hi(t,e){const i=t.getExtension(e);return i||console.log(`extension '${e}' not available`),i}const Wi=new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]);function qi(t){const e=document.createElement("canvas");e.width=16,e.height=16,e.style.width="16px",e.style.height="16px";const i=e.getContext("webgl")||e.getContext("experimental-webgl");if(!i)return console.log(`error creating webgl context for ${t}`),!1;if(!(i instanceof WebGLRenderingContext))return console.log("Got unexpected type for WebGL rendering context"),!1;Hi(i,"OES_texture_float"),Hi(i,"OES_texture_half_float"),Hi(i,"WEBGL_color_buffer_float");const r=ji(i,"\nattribute vec4 a_position;\n\nvoid main() {\n  gl_Position = a_position;\n}",i.VERTEX_SHADER),s=ji(i,"\nprecision mediump float;\nuniform vec4 u_color;\nuniform sampler2D u_texture;\n\nvoid main() {\n  gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n}",i.FRAGMENT_SHADER);if(!r||!s)return!1;const n=function(t,e,i,r){const s=t.createProgram();return s?(e.forEach((e=>t.attachShader(s,e))),i&&i.forEach(((e,i)=>{t.bindAttribLocation(s,r?r[i]:i,e)})),t.linkProgram(s),t.getProgramParameter(s,t.LINK_STATUS)?s:(console.log(`error linking program: ${t.getProgramInfoLog(s)}`),t.deleteProgram(s),null)):void console.log("error creating WebGL program")}(i,[r,s]);if(!n)return console.log("error creating WebGL program"),!1;i.useProgram(n);const o=i.getAttribLocation(n,"a_position"),a=i.getUniformLocation(n,"u_color");if(!a)return console.log("error getting 'u_color' uniform location"),!1;const c=i.createBuffer();i.bindBuffer(i.ARRAY_BUFFER,c),i.bufferData(i.ARRAY_BUFFER,Wi,i.STATIC_DRAW),i.enableVertexAttribArray(o),i.vertexAttribPointer(o,2,i.FLOAT,!1,0,0);const l=i.createTexture(),h=new Uint8Array([255,255,255,255]);i.bindTexture(i.TEXTURE_2D,l),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,h);const d=i.createTexture();i.bindTexture(i.TEXTURE_2D,d),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,1,1,0,i.RGBA,t,null),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST);const u=i.createFramebuffer();i.bindFramebuffer(i.FRAMEBUFFER,u),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,d,0);if(i.checkFramebufferStatus(i.FRAMEBUFFER)!==i.FRAMEBUFFER_COMPLETE)return console.log(`error creating framebuffer for ${t}`),!1;i.bindTexture(i.TEXTURE_2D,l),i.uniform4fv(a,[0,10,20,1]),i.drawArrays(i.TRIANGLES,0,6),i.bindTexture(i.TEXTURE_2D,d),i.bindFramebuffer(i.FRAMEBUFFER,null),i.clearColor(1,0,0,1),i.clear(i.COLOR_BUFFER_BIT),i.uniform4fv(a,[0,.1,.05,1]),i.drawArrays(i.TRIANGLES,0,6);const m=new Uint8Array(4);if(i.readPixels(0,0,1,1,i.RGBA,i.UNSIGNED_BYTE,m),0!==m[0]||m[1]<248||m[2]<248||m[3]<254)return console.log(`not able to actually render to ${t} texture`),!1;if(t===i.FLOAT){i.bindFramebuffer(i.FRAMEBUFFER,u);const t=new Float32Array(4);i.readPixels(0,0,1,1,i.RGBA,i.FLOAT,t);const e=i.getError();if(e)return console.log(`error reading pixels as float: '${function(t,e){switch(e){case t.NO_ERROR:return"no error";case t.INVALID_ENUM:return"invalid enum";case t.INVALID_VALUE:return"invalid value";case t.INVALID_OPERATION:return"invalid operation";case t.INVALID_FRAMEBUFFER_OPERATION:return"invalid framebuffer operation";case t.OUT_OF_MEMORY:return"out of memory";case t.CONTEXT_LOST_WEBGL:return"context lost"}return"unknown error"}(i,e)}'`),!1}return!0}const Xi=new Float32Array(100),Yi=new Uint8Array(100),Ki=[12,7,13,17,11,6,8,18,16,2,14,22,10,1,3,9,19,23,21,15,5,0,4,24,20],Zi=new i;function Qi(t,e,i,r,s){const n=s.uniforms,o=[];if(n&&(n.objectId&&(n.objectId.value=Ce?this.id:this.id/255,o.push("objectId")),(n.modelViewMatrixInverse||n.modelViewMatrixInverseTranspose||n.modelViewProjectionMatrix||n.modelViewProjectionMatrixInverse)&&this.modelViewMatrix.multiplyMatrices(i.matrixWorldInverse,this.matrixWorld),n.modelViewMatrixInverse&&(n.modelViewMatrixInverse.value.getInverse(this.modelViewMatrix),o.push("modelViewMatrixInverse")),n.modelViewMatrixInverseTranspose&&(n.modelViewMatrixInverse?n.modelViewMatrixInverseTranspose.value.copy(n.modelViewMatrixInverse.value).transpose():n.modelViewMatrixInverseTranspose.value.getInverse(this.modelViewMatrix).transpose(),o.push("modelViewMatrixInverseTranspose")),n.modelViewProjectionMatrix&&(n.modelViewProjectionMatrix.value.multiplyMatrices(i.projectionMatrix,this.modelViewMatrix),o.push("modelViewProjectionMatrix")),n.modelViewProjectionMatrixInverse&&(n.modelViewProjectionMatrix?(Zi.copy(n.modelViewProjectionMatrix.value),n.modelViewProjectionMatrixInverse.value.getInverse(Zi)):(Zi.multiplyMatrices(i.projectionMatrix,this.modelViewMatrix),n.modelViewProjectionMatrixInverse.value.getInverse(Zi)),o.push("modelViewProjectionMatrixInverse")),o.length)){const e=t.properties.get(s);if(e.program){const i=t.getContext(),r=e.program;i.useProgram(r.program);const s=r.getUniforms();o.forEach((function(t){s.setValue(i,t,n[t].value)}))}}}class Ji{constructor(t){if(this.boundingBox=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],this.boundingBoxSize=new e,this.boundingBoxLength=0,this.info={memory:{programs:0,geometries:0,textures:0},render:{calls:0,vertices:0,faces:0,points:0}},this.distVector=new e,this.signals={ticked:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],rendered:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},"string"==typeof t){const e=document.getElementById(t);this.container=null===e?document.createElement("div"):e}else t instanceof HTMLElement?this.container=t:this.container=document.createElement("div");if(this.container===document.body)this.width=window.innerWidth||1,this.height=window.innerHeight||1;else{const t=this.container.getBoundingClientRect();this.width=t.width||1,this.height=t.height||1,this.container.style.overflow="hidden"}this.wrapper=document.createElement("div"),this.wrapper.style.position="relative",this.container.appendChild(this.wrapper),this._initParams(),this._initStats(),this._initCamera(),this._initScene(),!1!==this._initRenderer()?(this._initHelper(),this.setBackground(),this.setFog(),this.animate=this.animate.bind(this)):Me.error("Viewer: could not initialize renderer")}_initParams(){this.parameters={fogColor:new s(0),fogNear:50,fogFar:100,backgroundColor:new s(0),cameraType:"perspective",cameraFov:40,cameraEyeSep:.3,cameraZ:-80,clipNear:0,clipFar:100,clipDist:10,clipMode:"scene",clipScale:"relative",lightColor:new s(14540253),lightIntensity:1,ambientColor:new s(14540253),ambientIntensity:.2,sampleLevel:0,rendererEncoding:__WEBPACK_IMPORTED_MODULE_0_three__["w" /* LinearEncoding */]}}_initCamera(){const t=new e(0,0,0),{width:i,height:r}=this;this.perspectiveCamera=new __WEBPACK_IMPORTED_MODULE_0_three__["G" /* PerspectiveCamera */](this.parameters.cameraFov,i/r),this.perspectiveCamera.position.z=this.parameters.cameraZ,this.perspectiveCamera.lookAt(t),this.orthographicCamera=new __WEBPACK_IMPORTED_MODULE_0_three__["F" /* OrthographicCamera */](i/-2,i/2,r/2,r/-2),this.orthographicCamera.position.z=this.parameters.cameraZ,this.orthographicCamera.lookAt(t),this.stereoCamera=new __WEBPACK_IMPORTED_MODULE_0_three__["Q" /* StereoCamera */],this.stereoCamera.aspect=.5,this.stereoCamera.eyeSep=this.parameters.cameraEyeSep;const s=this.parameters.cameraType;if("orthographic"===s)this.camera=this.orthographicCamera;else{if("perspective"!==s&&"stereo"!==s)throw new Error(`Unknown cameraType '${s}'`);this.camera=this.perspectiveCamera}this.camera.updateProjectionMatrix()}_initStats(){this.stats=new mi}_initScene(){this.scene||(this.scene=new __WEBPACK_IMPORTED_MODULE_0_three__["M" /* Scene */],this.scene.name="scene"),this.rotationGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.rotationGroup.name="rotationGroup",this.scene.add(this.rotationGroup),this.translationGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.translationGroup.name="translationGroup",this.rotationGroup.add(this.translationGroup),this.modelGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.modelGroup.name="modelGroup",this.translationGroup.add(this.modelGroup),this.pickingGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.pickingGroup.name="pickingGroup",this.translationGroup.add(this.pickingGroup),this.backgroundGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.backgroundGroup.name="backgroundGroup",this.translationGroup.add(this.backgroundGroup),this.helperGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.helperGroup.name="helperGroup",this.translationGroup.add(this.helperGroup),this.scene.fog=new __WEBPACK_IMPORTED_MODULE_0_three__["q" /* Fog */](this.parameters.fogColor.getHex()),this.spotLight=new __WEBPACK_IMPORTED_MODULE_0_three__["P" /* SpotLight */](this.parameters.lightColor.getHex(),this.parameters.lightIntensity),this.scene.add(this.spotLight),this.ambientLight=new __WEBPACK_IMPORTED_MODULE_0_three__["b" /* AmbientLight */](this.parameters.ambientColor.getHex(),this.parameters.ambientIntensity),this.scene.add(this.ambientLight)}_initRenderer(){const t=window.devicePixelRatio,{width:e,height:i}=this;try{this.renderer=new __WEBPACK_IMPORTED_MODULE_0_three__["_0" /* WebGLRenderer */]({preserveDrawingBuffer:!0,alpha:!0,antialias:!0})}catch(t){return this.wrapper.innerHTML='<div style="display:flex;align-items:center;justify-content:center;height:100%;"><p style="padding:15px;text-align:center;">Your browser/graphics card does not seem to support <a target="_blank" href="https://en.wikipedia.org/wiki/WebGL">WebGL</a>.<br/><br/>Find out how to get it <a target="_blank" href="http://get.webgl.org/">here</a>.</p></div>',!1}this.renderer.setPixelRatio(t),this.renderer.setSize(e,i),this.renderer.autoClear=!1,this.renderer.sortObjects=!0,this.renderer.outputEncoding=this.parameters.rendererEncoding;const r=this.renderer.getContext();this.renderer.capabilities.isWebGL2?(ke(!0),Pe(this.renderer.extensions.get("EXT_color_buffer_float")),this.supportsHalfFloat=!0):(ke(this.renderer.extensions.get("EXT_frag_depth")),this.renderer.extensions.get("OES_element_index_uint"),Pe(this.renderer.extensions.get("OES_texture_float")&&this.renderer.extensions.get("WEBGL_color_buffer_float")||this.renderer.extensions.get("OES_texture_float")&&qi(r.FLOAT)),this.renderer.extensions.get("OES_texture_float"),this.supportsHalfFloat=this.renderer.extensions.get("OES_texture_half_float")&&qi(36193)),this.wrapper.appendChild(this.renderer.domElement);const s=e*t,n=i*t;De&&console.log(JSON.stringify({Browser:Ae,OES_texture_float:!!this.renderer.extensions.get("OES_texture_float"),OES_texture_half_float:!!this.renderer.extensions.get("OES_texture_half_float"),WEBGL_color_buffer_float:!!this.renderer.extensions.get("WEBGL_color_buffer_float"),"testTextureSupport Float":qi(r.FLOAT),"testTextureSupport HalfFloat":qi(36193),"this.supportsHalfFloat":this.supportsHalfFloat,SupportsReadPixelsFloat:Ce},null,2)),this.pickingTarget=new __WEBPACK_IMPORTED_MODULE_0_three__["Z" /* WebGLRenderTarget */](s,n,{minFilter:__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */],magFilter:__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */],stencilBuffer:!1,format:__WEBPACK_IMPORTED_MODULE_0_three__["L" /* RGBAFormat */],type:Ce?__WEBPACK_IMPORTED_MODULE_0_three__["p" /* FloatType */]:__WEBPACK_IMPORTED_MODULE_0_three__["W" /* UnsignedByteType */]}),this.pickingTarget.texture.generateMipmaps=!1,this.pickingTarget.texture.encoding=this.parameters.rendererEncoding,this.renderer.setRenderTarget(this.pickingTarget),this.renderer.clear(),this.renderer.setRenderTarget(null),this.sampleTarget=new __WEBPACK_IMPORTED_MODULE_0_three__["Z" /* WebGLRenderTarget */](s,n,{minFilter:__WEBPACK_IMPORTED_MODULE_0_three__["x" /* LinearFilter */],magFilter:__WEBPACK_IMPORTED_MODULE_0_three__["x" /* LinearFilter */],format:__WEBPACK_IMPORTED_MODULE_0_three__["L" /* RGBAFormat */]}),this.sampleTarget.texture.encoding=this.parameters.rendererEncoding,this.holdTarget=new __WEBPACK_IMPORTED_MODULE_0_three__["Z" /* WebGLRenderTarget */](s,n,{minFilter:__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */],magFilter:__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */],format:__WEBPACK_IMPORTED_MODULE_0_three__["L" /* RGBAFormat */],type:__WEBPACK_IMPORTED_MODULE_0_three__["W" /* UnsignedByteType */]}),this.holdTarget.texture.encoding=this.parameters.rendererEncoding,this.compositeUniforms={tForeground:new __WEBPACK_IMPORTED_MODULE_0_three__["T" /* Uniform */](this.sampleTarget.texture),scale:new __WEBPACK_IMPORTED_MODULE_0_three__["T" /* Uniform */](1)},this.compositeMaterial=new __WEBPACK_IMPORTED_MODULE_0_three__["O" /* ShaderMaterial */]({uniforms:this.compositeUniforms,vertexShader:gi("Quad.vert"),fragmentShader:gi("Quad.frag"),premultipliedAlpha:!0,transparent:!0,blending:__WEBPACK_IMPORTED_MODULE_0_three__["a" /* AdditiveBlending */],depthTest:!1,depthWrite:!1}),this.compositeCamera=new __WEBPACK_IMPORTED_MODULE_0_three__["F" /* OrthographicCamera */](-1,1,1,-1,0,1),this.compositeScene=new __WEBPACK_IMPORTED_MODULE_0_three__["M" /* Scene */],this.compositeScene.name="compositeScene",this.compositeScene.add(new __WEBPACK_IMPORTED_MODULE_0_three__["A" /* Mesh */](new __WEBPACK_IMPORTED_MODULE_0_three__["I" /* PlaneGeometry */](2,2),this.compositeMaterial))}_initHelper(){const t=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),e=new Float32Array(24),i=new __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */];i.setIndex(new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](t,1)),i.setAttribute("position",new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](e,3));const r=new __WEBPACK_IMPORTED_MODULE_0_three__["O" /* ShaderMaterial */]({uniforms:{uColor:{value:new s("skyblue")}},vertexShader:gi("BasicLine.vert"),fragmentShader:gi("BasicLine.frag")});this.boundingBoxMesh=new __WEBPACK_IMPORTED_MODULE_0_three__["v" /* LineSegments */](i,r),this.helperGroup.add(this.boundingBoxMesh)}updateHelper(){const t=this.boundingBoxMesh.geometry.attributes.position,e=t.array,{min:i,max:r}=this.boundingBox;e[0]=r.x,e[1]=r.y,e[2]=r.z,e[3]=i.x,e[4]=r.y,e[5]=r.z,e[6]=i.x,e[7]=i.y,e[8]=r.z,e[9]=r.x,e[10]=i.y,e[11]=r.z,e[12]=r.x,e[13]=r.y,e[14]=i.z,e[15]=i.x,e[16]=r.y,e[17]=i.z,e[18]=i.x,e[19]=i.y,e[20]=i.z,e[21]=r.x,e[22]=i.y,e[23]=i.z,t.needsUpdate=!0,this.boundingBox.isEmpty()||this.boundingBoxMesh.geometry.computeBoundingSphere()}get cameraDistance(){return Math.abs(this.camera.position.z)}set cameraDistance(t){this.camera.position.z=-t}add(t,e){e?e.forEach((e=>this.addBuffer(t,e))):this.addBuffer(t),t.group.name="meshGroup",t.wireframeGroup.name="wireframeGroup",t.parameters.background?(this.backgroundGroup.add(t.group),this.backgroundGroup.add(t.wireframeGroup)):(this.modelGroup.add(t.group),this.modelGroup.add(t.wireframeGroup)),t.pickable&&this.pickingGroup.add(t.pickingGroup),De&&this.updateHelper()}addBuffer(t,e){function i(r){r instanceof __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]?r.children.forEach(i):(r.userData.buffer=t,r.userData.instance=e,r.onBeforeRender=Qi)}const r=t.getMesh();e&&r.applyMatrix4(e.matrix),i(r),t.group.add(r);const s=t.getWireframeMesh();if(e&&(s.matrix.copy(r.matrix),s.position.copy(r.position),s.quaternion.copy(r.quaternion),s.scale.copy(r.scale)),i(s),t.wireframeGroup.add(s),t.pickable){const s=t.getPickingMesh();e&&(s.matrix.copy(r.matrix),s.position.copy(r.position),s.quaternion.copy(r.quaternion),s.scale.copy(r.scale)),i(s),t.pickingGroup.add(s)}e?this._updateBoundingBox(t.geometry,t.matrix,e.matrix):this._updateBoundingBox(t.geometry,t.matrix)}remove(t){this.translationGroup.children.forEach((function(e){e.remove(t.group),e.remove(t.wireframeGroup)})),t.pickable&&this.pickingGroup.remove(t.pickingGroup),this.updateBoundingBox(),De&&this.updateHelper()}_updateBoundingBox(t,e,i){const r=this.boundingBox;function s(t,e,i){null==t.boundingBox&&t.computeBoundingBox();const s=t.boundingBox.clone();e&&s.applyMatrix4(e),i&&s.applyMatrix4(i),s.min.equals(s.max)&&s.expandByScalar(5),r.union(s)}function n(t){if(void 0!==t.geometry){let e,i;t.userData.buffer&&(e=t.userData.buffer.matrix),t.userData.instance&&(i=t.userData.instance.matrix),s(t.geometry,e,i)}}t?s(t,e,i):(r.makeEmpty(),this.modelGroup.traverse(n),this.backgroundGroup.traverse(n)),r.getSize(this.boundingBoxSize),this.boundingBoxLength=this.boundingBoxSize.length()}updateBoundingBox(){this._updateBoundingBox(),De&&this.updateHelper()}getPickingPixels(){const{width:t,height:e}=this,i=t*e*4,r=Ce?new Float32Array(i):new Uint8Array(i);return this.render(!0),this.renderer.readRenderTargetPixels(this.pickingTarget,0,0,t,e,r),r}getImage(t){return new Promise((e=>{if(t){const{width:t,height:i}=this,r=t*i*4;let s=this.getPickingPixels();if(Ce){const t=new Uint8Array(r);for(let e=0;e<r;++e)t[e]=Math.round(255*s[e]);s=t}const n=document.createElement("canvas");n.width=t,n.height=i;const o=n.getContext("2d"),a=o.getImageData(0,0,t,i);a.data.set(s),o.putImageData(a,0,0),n.toBlob(e,"image/png")}else this.renderer.domElement.toBlob(e,"image/png")}))}makeImage(t={}){return Ei(this,t)}setLight(t,e,i,r){const s=this.parameters;void 0!==t&&s.lightColor.set(t),void 0!==e&&(s.lightIntensity=e),void 0!==i&&s.ambientColor.set(i),void 0!==r&&(s.ambientIntensity=r),this.requestRender()}setFog(t,e,i){const r=this.parameters;void 0!==t&&r.fogColor.set(t),void 0!==e&&(r.fogNear=e),void 0!==i&&(r.fogFar=i),this.requestRender()}setBackground(t){const e=this.parameters;t&&e.backgroundColor.set(t),this.setFog(e.backgroundColor),this.renderer.setClearColor(e.backgroundColor,0),this.renderer.domElement.style.backgroundColor=e.backgroundColor.getStyle(),this.requestRender()}setSampling(t){void 0!==t&&(this.parameters.sampleLevel=t,this.sampleLevel=t),this.requestRender()}setOutputEncoding(t){this.parameters.rendererEncoding=t,this.renderer.outputEncoding=t,this.pickingTarget.texture.encoding=t,this.sampleTarget.texture.encoding=t,this.holdTarget.texture.encoding=t}setColorWorkflow(t){if("linear"!=t&&"sRGB"!=t)throw new Error(`setColorWorkflow: invalid color workflow ${t}`);Et="linear"==t?"linear":"sRGB",this.setOutputEncoding("linear"==t?__WEBPACK_IMPORTED_MODULE_0_three__["_1" /* sRGBEncoding */]:__WEBPACK_IMPORTED_MODULE_0_three__["w" /* LinearEncoding */]),this.requestRender()}setCamera(t,e,i){const r=this.parameters;if(t&&(r.cameraType=t),e&&(r.cameraFov=e),i&&(r.cameraEyeSep=i),"orthographic"===r.cameraType)this.camera!==this.orthographicCamera&&(this.camera=this.orthographicCamera,this.camera.position.copy(this.perspectiveCamera.position),this.camera.up.copy(this.perspectiveCamera.up),this.updateZoom());else{if("perspective"!==r.cameraType&&"stereo"!==r.cameraType)throw new Error(`Unknown cameraType '${r.cameraType}'`);this.camera!==this.perspectiveCamera&&(this.camera=this.perspectiveCamera,this.camera.position.copy(this.orthographicCamera.position),this.camera.up.copy(this.orthographicCamera.up))}this.perspectiveCamera.fov=r.cameraFov,this.stereoCamera.eyeSep=r.cameraEyeSep,this.camera.updateProjectionMatrix(),this.requestRender()}setClip(t,e,i,r,s){const n=this.parameters;void 0!==t&&(n.clipNear=t),void 0!==e&&(n.clipFar=e),void 0!==i&&(n.clipDist=i),void 0!==r&&(n.clipMode=r),void 0!==s&&(n.clipScale=s),this.requestRender()}setSize(t,e){this.width=t||1,this.height=e||1,this.perspectiveCamera.aspect=this.width/this.height,this.orthographicCamera.left=-this.width/2,this.orthographicCamera.right=this.width/2,this.orthographicCamera.top=this.height/2,this.orthographicCamera.bottom=-this.height/2,this.camera.updateProjectionMatrix();const i=window.devicePixelRatio;this.renderer.setPixelRatio(i),this.renderer.setSize(t,e);const r=this.width*i,s=this.height*i;this.pickingTarget.setSize(r,s),this.sampleTarget.setSize(r,s),this.holdTarget.setSize(r,s),this.requestRender()}handleResize(){if(this.container===document.body)this.setSize(window.innerWidth,window.innerHeight);else{const t=this.container.getBoundingClientRect();this.setSize(t.width,t.height)}}updateInfo(t){const{memory:e,render:i}=this.info;if(t)e.programs=0,e.geometries=0,e.textures=0,i.calls=0,i.vertices=0,i.points=0;else{const t=this.renderer.info,r=t.memory,s=t.render;e.geometries=r.geometries,e.textures=r.textures,i.calls+=s.calls,i.faces+=s.triangles,i.points+=s.points}}animate(){this.signals.ticked.dispatch(this.stats);if(window.performance.now()-this.stats.startTime>500&&!this.isStill&&this.sampleLevel<3&&-1!==this.sampleLevel){const t=this.sampleLevel;this.sampleLevel=3,this.renderPending=!0,this.render(),this.isStill=!0,this.sampleLevel=t,De&&Me.log("rendered still frame")}this.frameRequest=window.requestAnimationFrame(this.animate)}pick(t,e){if("stereo"===this.parameters.cameraType)return{pid:0,instance:void 0,picker:void 0};t*=window.devicePixelRatio,e*=window.devicePixelRatio,t=Math.max(t-2,0),e=Math.max(e-2,0);let i,r,s=0;const n=Ce?Xi:Yi;this.render(!0),this.renderer.readRenderTargetPixels(this.pickingTarget,t,e,5,5,n);for(let t=0;t<Ki.length;t++){const e=4*Ki[t],o=Math.round(n[e+3]),a=this.pickingGroup.getObjectById(o);a&&(i=a.userData.instance,r=a.userData.buffer.picking,s=Ce?Math.round(255*n[e])<<16&16711680|Math.round(255*n[e+1])<<8&65280|255&Math.round(255*n[e+2]):n[e]<<16|n[e+1]<<8|n[e+2])}return{pid:s,instance:i,picker:r}}requestRender(){this.renderPending||(window.performance.now()-this.stats.startTime>22&&(this.stats.begin(),this.isStill=!1),this.renderPending=!0,window.requestAnimationFrame((()=>{this.render(),this.stats.update()})))}updateZoom(){const t=kt(this.perspectiveCamera.fov),e=2*Math.tan(t/2)*this.cameraDistance;this.orthographicCamera.zoom=this.height/e}absoluteToRelative(t){return 50*(1-t/this.bRadius)}relativeToAbsolute(t){return this.bRadius*(1-t/50)}__updateClipping(){const t=this.parameters;this.bRadius=Math.max(10,.5*this.boundingBoxLength),isFinite(this.bRadius)||(this.bRadius=50),this.camera.getWorldPosition(this.distVector),this.cDist=this.distVector.length(),this.cDist||(this.cameraDistance=Math.abs(t.cameraZ),this.cDist=Math.abs(t.cameraZ));const e=this.scene.fog;if(e.color.set(t.fogColor),"camera"===t.clipMode)this.camera.near=t.clipNear,this.camera.far=t.clipFar,e.near=t.fogNear,e.far=t.fogFar;else if("absolute"===t.clipScale)this.camera.near=this.cDist-t.clipNear,this.camera.far=this.cDist+t.clipFar,e.near=this.cDist-t.fogNear,e.far=this.cDist+t.fogFar;else{const i=(50-t.clipNear)/50,r=-(50-t.clipFar)/50;this.camera.near=this.cDist-this.bRadius*i,this.camera.far=this.cDist+this.bRadius*r;const s=(50-t.fogNear)/50,n=-(50-t.fogFar)/50;e.near=this.cDist-this.bRadius*s,e.far=this.cDist+this.bRadius*n}"camera"!==t.clipMode&&("PerspectiveCamera"===this.camera.type?(this.camera.near=Math.max(.1,t.clipDist,this.camera.near),this.camera.far=Math.max(1,this.camera.far),e.near=Math.max(.1,e.near),e.far=Math.max(1,e.far)):"OrthographicCamera"===this.camera.type&&t.clipDist>0&&(this.camera.near=Math.max(t.clipDist,this.camera.near)))}__updateCamera(){const e=this.camera;e.updateMatrix(),e.updateMatrixWorld(!0),e.updateProjectionMatrix(),function(e,i,r,s,n){let o=new t;r.getSize(o);const a=o.height,c=r.getPixelRatio(),l="OrthographicCamera"===i.type;zi.set(o.width,o.height),Vi.getInverse(i.projectionMatrix),Gi.copy(i.projectionMatrix).transpose(),e.traverse((function(t){const e=t.material;if(!e)return;const i=e.uniforms;if(i){if(e.clipNear){const t=(50-e.clipNear)/50,r=s-n*t;i.clipNear.value=r}i.canvasHeight&&(i.canvasHeight.value=a),i.resolution&&i.resolution.value.copy(zi),i.pixelRatio&&(i.pixelRatio.value=c),i.projectionMatrixInverse&&i.projectionMatrixInverse.value.copy(Vi),i.projectionMatrixTranspose&&i.projectionMatrixTranspose.value.copy(Gi),i.ortho&&(i.ortho.value=l)}}))}(this.scene,e,this.renderer,this.cDist,this.bRadius),function(t,e){t.traverseVisible((function(t){if(!(t instanceof o&&t.userData.buffer.parameters.sortParticles))return;const i=t.geometry.attributes,r=i.position.count;if(0===r)return;let s,n,a,c,l,h,d,u;Li.multiplyMatrices(e.matrixWorldInverse,t.matrixWorld),Ni.multiplyMatrices(e.projectionMatrix,Li),t.userData.sortData?(s=t.userData.sortData,a=s.__zArray,n=s.__sortArray,c=s.__cmpFn):(a=new Float32Array(r),n=new Uint32Array(r),c=function(t,e){const i=a[t],r=a[e];return i>r?1:i<r?-1:0},s={__zArray:a,__sortArray:n,__cmpFn:c},t.userData.sortData=s);for(let t=0;t<r;++t)Fi.fromArray(i.position.array,3*t),Fi.applyMatrix4(Ni),a[t]=-Fi.z,n[t]=t;!function(t,e,i=0,r){e=e||function(t,e){return t>e?1:t<e?-1:0};const s=[];let n,o,a,c=-1,l=i,h=r=(r||t.length)-1;function d(e,i){const r=t[e];t[e]=t[i],t[i]=r}for(;;)if(h-l<=25){for(let i=l+1;i<=h;++i){for(n=t[i],o=i-1;o>=l&&e(t[o],n)>0;)t[o+1]=t[o],--o;t[o+1]=n}if(-1===c)break;h=s[c--],l=s[c--]}else{for(o=l+1,a=h,d(l+h>>1,o),e(t[l],t[h])>0&&d(l,h),e(t[o],t[h])>0&&d(o,h),e(t[l],t[o])>0&&d(l,o),n=t[o];;){do{o++}while(e(t[o],n)<0);do{a--}while(e(t[a],n)>0);if(a<o)break;d(o,a)}t[l+1]=t[a],t[a]=n,h-o+1>=a-l?(s[++c]=o,s[++c]=h,h=a-1):(s[++c]=l,s[++c]=a-1,l=o)}}(n,c);for(let t in i){const e=i[t],o=e.array,a=e.itemSize;s[t]||(s[t]=new Float32Array(a*r)),u=s[t],s[t]=o;for(let t=0;t<r;++t){l=n[t];for(let e=0;e<a;++e)h=l*a+e,d=t*a+e,u[d]=o[h]}i[t].array=u,i[t].needsUpdate=!0}}))}(this.scene,e)}__setVisibility(t,e,i,r){this.modelGroup.visible=t,this.pickingGroup.visible=e,this.backgroundGroup.visible=i,this.helperGroup.visible=r}__updateLights(){this.spotLight.color.set(this.parameters.lightColor),this.spotLight.intensity=this.parameters.lightIntensity,this.distVector.copy(this.camera.position).setLength(100*this.boundingBoxLength),this.spotLight.position.copy(this.camera.position).add(this.distVector),this.ambientLight.color.set(this.parameters.ambientColor),this.ambientLight.intensity=this.parameters.ambientIntensity}__renderPickingGroup(t){this.renderer.setRenderTarget(this.pickingTarget||null),this.renderer.clear(),this.__setVisibility(!1,!0,!1,!1),this.renderer.render(this.scene,t),this.renderer.setRenderTarget(null),this.updateInfo()}__renderModelGroup(t,e){this.renderer.setRenderTarget(e||null),this.renderer.clear(),this.__setVisibility(!1,!1,!0,!1),this.renderer.render(this.scene,t),this.renderer.clear(!1,!0,!0),this.updateInfo(),this.__setVisibility(!0,!1,!1,De),this.renderer.render(this.scene,t),this.renderer.setRenderTarget(null),this.updateInfo()}__renderSuperSample(t,e){const i=yi[Math.max(0,Math.min(this.sampleLevel,5))],r=1/i.length;this.compositeUniforms.tForeground.value=this.sampleTarget.texture;let s=this.sampleTarget.width;const n=this.sampleTarget.height;"stereo"===this.parameters.cameraType&&(s/=2);for(let e=0;e<i.length;++e){const o=i[e];t.setViewOffset(s,n,o[0],o[1],s,n),t.updateProjectionMatrix(),Ui(this.scene,t);let a=r;a+=.03125*((e+.5)/i.length-.5),this.compositeUniforms.scale.value=a,this.__renderModelGroup(t,this.sampleTarget),this.renderer.setRenderTarget(this.holdTarget),0===e&&this.renderer.clear(),this.renderer.render(this.compositeScene,this.compositeCamera)}this.compositeUniforms.scale.value=1,this.compositeUniforms.tForeground.value=this.holdTarget.texture,t.clearViewOffset(),this.renderer.setRenderTarget(e||null),this.renderer.clear(),this.renderer.render(this.compositeScene,this.compositeCamera)}__renderStereo(e=!1,i){const r=this.stereoCamera;r.update(this.perspectiveCamera);const s=this.renderer;let n=new t;s.getSize(n),s.setScissorTest(!0),s.setScissor(0,0,n.width/2,n.height),s.setViewport(0,0,n.width/2,n.height),Ui(this.scene,r.cameraL),this.__render(e,r.cameraL),s.setScissor(n.width/2,0,n.width/2,n.height),s.setViewport(n.width/2,0,n.width/2,n.height),Ui(this.scene,r.cameraR),this.__render(e,r.cameraR),s.setScissorTest(!1),s.setViewport(0,0,n.width,n.height)}__render(t=!1,e,i){t?this.lastRenderedPicking||this.__renderPickingGroup(e):this.sampleLevel>0&&"stereo"!==this.parameters.cameraType?this.__renderSuperSample(e,i):this.__renderModelGroup(e,i)}render(t=!1,e){if(this.rendering)Me.warn("'tried to call 'render' from within 'render'");else{this.rendering=!0;try{this.__updateClipping(),this.__updateCamera(),this.__updateLights(),this.updateInfo(!0),"stereo"===this.parameters.cameraType?this.__renderStereo(t,e):this.__render(t,this.camera,e),this.lastRenderedPicking=t}finally{this.rendering=!1,this.renderPending=!1}this.signals.rendered.dispatch()}}clear(){Me.log("scene cleared"),this.scene.remove(this.rotationGroup),this._initScene(),this.renderer.clear()}dispose(){this.renderer.dispose(),window.cancelAnimationFrame(this.frameRequest)}}const tr=1,er=2,ir=3;function rr(t){const e=t.touches[0].pageX-t.touches[1].pageX,i=t.touches[0].pageY-t.touches[1].pageY;return Math.sqrt(e*e+i*i)}class sr{constructor(e,i={}){this.domElement=e,this.signals={moved:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],scrolled:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],dragged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],dropped:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],clicked:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],hovered:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],doubleClicked:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.position=new t,this.prevPosition=new t,this.down=new t,this.canvasPosition=new t,this.prevClickCP=new t,this.moving=!1,this.hovering=!0,this.scrolled=!1,this.lastMoved=1/0,this.which=0,this.buttons=0,this.pressed=!1,this.altKey=!1,this.ctrlKey=!1,this.metaKey=!1,this.shiftKey=!1,this.domElement.style.touchAction="none",this.hoverTimeout=st(i.hoverTimeout,50),this.handleScroll=st(i.handleScroll,!0),this.doubleClickSpeed=st(i.doubleClickSpeed,500),this._listen=this._listen.bind(this),this._onMousewheel=this._onMousewheel.bind(this),this._onMousemove=this._onMousemove.bind(this),this._onMousedown=this._onMousedown.bind(this),this._onMouseup=this._onMouseup.bind(this),this._onContextmenu=this._onContextmenu.bind(this),this._onTouchstart=this._onTouchstart.bind(this),this._onTouchend=this._onTouchend.bind(this),this._onTouchmove=this._onTouchmove.bind(this),this._listen();const r={passive:!1};document.addEventListener("mousewheel",this._onMousewheel,r),document.addEventListener("wheel",this._onMousewheel,r),document.addEventListener("MozMousePixelScroll",this._onMousewheel,r),document.addEventListener("mousemove",this._onMousemove,r),document.addEventListener("mousedown",this._onMousedown,r),document.addEventListener("mouseup",this._onMouseup,r),document.addEventListener("contextmenu",this._onContextmenu,r),document.addEventListener("touchstart",this._onTouchstart,r),document.addEventListener("touchend",this._onTouchend,r),document.addEventListener("touchmove",this._onTouchmove,r)}get key(){let t=0;return this.altKey&&(t+=1),this.ctrlKey&&(t+=2),this.metaKey&&(t+=4),this.shiftKey&&(t+=8),t}setParameters(t={}){this.hoverTimeout=st(t.hoverTimeout,this.hoverTimeout)}_listen(){const t=window.performance.now(),e=this.canvasPosition;this.doubleClickPending&&t-this.lastClicked>this.doubleClickSpeed&&(this.doubleClickPending=!1),t-this.lastMoved>this.hoverTimeout&&(this.moving=!1),(this.scrolled||!this.moving&&!this.hovering)&&(this.scrolled=!1,-1!==this.hoverTimeout&&this.overElement&&(this.hovering=!0,this.signals.hovered.dispatch(e.x,e.y))),this.frameRequest=window.requestAnimationFrame(this._listen)}_onMousewheel(t){if(t.target!==this.domElement||!this.handleScroll)return;t.preventDefault(),this._setKeys(t);let e=0;"deltaY"in t&&"deltaMode"in t&&void 0!==t.deltaY&&void 0!==t.deltaMode?e=t.deltaMode===WheelEvent.DOM_DELTA_PIXEL?.025*-t.deltaY:t.deltaMode===WheelEvent.DOM_DELTA_LINE?-t.deltaY*(2.5/3):2.5*-t.deltaY:"deltaY"in t&&!("detail"in t)?e=.025*-t.deltaY:void 0!==t.wheelDelta?e=.025*-t.wheelDelta:void 0!==t.wheelDeltaY?e=.025*-t.wheelDeltaY:void 0!==t.detail&&(e=-t.detail/3),this.signals.scrolled.dispatch(e),setTimeout((()=>{this.scrolled=!0}),this.hoverTimeout)}_onMousemove(t){t.target===this.domElement?(t.preventDefault(),this.overElement=!0):this.overElement=!1,this._setKeys(t),this.moving=!0,this.hovering=!1,this.lastMoved=window.performance.now(),this.prevPosition.copy(this.position),this.position.set(t.clientX,t.clientY),this._setCanvasPosition(t);const e=this.prevPosition.x-this.position.x,i=this.prevPosition.y-this.position.y;this.signals.moved.dispatch(e,i),this.pressed&&this.signals.dragged.dispatch(e,i)}_onMousedown(t){t.target===this.domElement&&(t.preventDefault(),this._setKeys(t),this.moving=!1,this.hovering=!1,this.down.set(t.clientX,t.clientY),this.position.set(t.clientX,t.clientY),this.which=t.which,this.buttons=function(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){const e=t.which;if(2===e)return 4;if(3===e)return 2;if(e>0)return 1<<e-1}else if("button"in t){const e=t.button;if(1===e)return 4;if(2===e)return 2;if(e>=0)return 1<<e}}return 0}(t),this.pressed=!0,this._setCanvasPosition(t))}_onMouseup(t){t.target===this.domElement&&t.preventDefault(),this._setKeys(t);const e=this.canvasPosition;this._distance()<4&&(this.lastClicked=window.performance.now(),this.doubleClickPending&&this.prevClickCP.distanceTo(e)<4&&(this.signals.doubleClicked.dispatch(e.x,e.y),this.doubleClickPending=!1),this.signals.clicked.dispatch(e.x,e.y),this.doubleClickPending=!0,this.prevClickCP.copy(e)),this.which=void 0,this.buttons=void 0,this.pressed=void 0}_onContextmenu(t){t.target===this.domElement&&t.preventDefault()}_onTouchstart(t){if(t.target===this.domElement)switch(t.preventDefault(),this.pressed=!0,t.touches.length){case 1:this.moving=!1,this.hovering=!1,this.down.set(t.touches[0].pageX,t.touches[0].pageY),this.position.set(t.touches[0].pageX,t.touches[0].pageY),this._setCanvasPosition(t.touches[0]);break;case 2:this.down.set((t.touches[0].pageX+t.touches[1].pageX)/2,(t.touches[0].pageY+t.touches[1].pageY)/2),this.position.set((t.touches[0].pageX+t.touches[1].pageX)/2,(t.touches[0].pageY+t.touches[1].pageY)/2),this.lastTouchDistance=rr(t)}}_onTouchend(t){t.target===this.domElement&&t.preventDefault(),this.which=void 0,this.buttons=void 0,this.pressed=void 0}_onTouchmove(t){switch(t.target===this.domElement?(t.preventDefault(),this.overElement=!0):this.overElement=!1,t.touches.length){case 1:{this._setKeys(t),this.which=1,this.buttons=1,this.moving=!0,this.hovering=!1,this.lastMoved=window.performance.now(),this.prevPosition.copy(this.position),this.position.set(t.touches[0].pageX,t.touches[0].pageY),this._setCanvasPosition(t.touches[0]);const e=this.prevPosition.x-this.position.x,i=this.prevPosition.y-this.position.y;this.signals.moved.dispatch(e,i),this.pressed&&this.signals.dragged.dispatch(e,i);break}case 2:{const e=rr(t),i=e-this.lastTouchDistance;if(this.lastTouchDistance=e,this.prevPosition.copy(this.position),this.position.set((t.touches[0].pageX+t.touches[1].pageX)/2,(t.touches[0].pageY+t.touches[1].pageY)/2),Math.abs(i)>2&&this.handleScroll&&this.position.distanceTo(this.prevPosition)<2)this.which=0,this.buttons=0,this.signals.scrolled.dispatch(i/2);else{this.which=3,this.buttons=2;const t=this.prevPosition.x-this.position.x,e=this.prevPosition.y-this.position.y;this.signals.moved.dispatch(t,e),this.pressed&&this.signals.dragged.dispatch(t,e)}}}}_distance(){return this.position.distanceTo(this.down)}_setCanvasPosition(t){const e=this.domElement.getBoundingClientRect();let i,r;"clientX"in t&&"clientY"in t?(i=t.clientX-e.left,r=t.clientY-e.top):(i=t.offsetX,r=t.offsetY),this.canvasPosition.set(i,e.height-r)}_setKeys(t){this.altKey=t.altKey,this.ctrlKey=t.ctrlKey,this.metaKey=t.metaKey,this.shiftKey=t.shiftKey}dispose(){document.removeEventListener("mousewheel",this._onMousewheel),document.removeEventListener("wheel",this._onMousewheel),document.removeEventListener("MozMousePixelScroll",this._onMousewheel),document.removeEventListener("mousemove",this._onMousemove),document.removeEventListener("mousedown",this._onMousedown),document.removeEventListener("mouseup",this._onMouseup),document.removeEventListener("contextmenu",this._onContextmenu),document.removeEventListener("touchstart",this._onTouchstart),document.removeEventListener("touchend",this._onTouchend),document.removeEventListener("touchmove",this._onTouchmove),window.cancelAnimationFrame(this.frameRequest)}}const nr=new i,or=new i,ar=new i,cr=new i,lr=new i,hr=new e,dr=new r,ur=new r,mr=new i,pr=new e,fr=new e;class gr{constructor(t,e={}){this.stage=t,this.rotateSpeed=st(e.rotateSpeed,2),this.zoomSpeed=st(e.zoomSpeed,1.2),this.panSpeed=st(e.panSpeed,1),this.viewer=t.viewer,this.mouse=t.mouseObserver,this.controls=t.viewerControls}get component(){return this.stage.transformComponent}get atom(){return this.stage.transformAtom}_setPanVector(t,e,i=0){const r=this.controls.getCanvasScaleFactor(i);pr.set(t,e,0),pr.multiplyScalar(this.panSpeed*r)}_getRotateXY(t,e){return[this.rotateSpeed*-t*.01,this.rotateSpeed*e*.01]}_getCameraRotation(t){return t.extractRotation(this.viewer.camera.matrixWorld),t.multiply(or.makeRotationY(Math.PI)),t}_transformPanVector(){this.component&&(mr.extractRotation(this.component.transform),mr.premultiply(this.viewer.rotationGroup.matrix),mr.getInverse(mr),mr.multiply(this._getCameraRotation(cr)),pr.applyMatrix4(mr))}zoom(t){this.controls.zoom(this.zoomSpeed*t*.02)}pan(t,e){this._setPanVector(t,e),mr.getInverse(this.viewer.rotationGroup.matrix),mr.multiply(this._getCameraRotation(cr)),pr.applyMatrix4(mr),this.controls.translate(pr)}panComponent(t,e){this.component&&(this._setPanVector(t,e),this._transformPanVector(),this.component.position.add(pr),this.component.updateMatrix())}panAtom(t,e){this.atom&&this.component&&(this.atom.positionToVector3(fr),fr.add(this.viewer.translationGroup.position),fr.applyMatrix4(this.viewer.rotationGroup.matrix),this._setPanVector(t,e,fr.z),this._transformPanVector(),this.atom.positionAdd(pr),this.component.updateRepresentations({position:!0}))}rotate(t,e){const[i,r]=this._getRotateXY(t,e);this._getCameraRotation(cr),hr.set(1,0,0),hr.applyMatrix4(cr),dr.setFromAxisAngle(hr,r),hr.set(0,1,0),hr.applyMatrix4(cr),ur.setFromAxisAngle(hr,i),dr.multiply(ur),cr.makeRotationFromQuaternion(dr),this.controls.applyMatrix(cr)}zRotate(t,e){const i=this.rotateSpeed*((-t+e)/-2)*.01;ar.makeRotationZ(i),this.controls.applyMatrix(ar)}rotateComponent(t,e){if(!this.component)return;const[i,r]=this._getRotateXY(t,e);this._getCameraRotation(lr),cr.extractRotation(this.component.transform),cr.premultiply(this.viewer.rotationGroup.matrix),cr.getInverse(cr),cr.premultiply(lr),hr.set(1,0,0),hr.applyMatrix4(cr),nr.makeRotationAxis(hr,r),hr.set(0,1,0),hr.applyMatrix4(cr),or.makeRotationAxis(hr,i),nr.multiply(or),dr.setFromRotationMatrix(nr),this.component.quaternion.premultiply(dr),this.component.quaternion.normalize(),this.component.updateMatrix()}}const yr=new e;class br{constructor(t,e){this.stage=e,this.pid=t.pid,this.picker=t.picker,this.instance=t.instance,this.stage=e,this.controls=e.viewerControls,this.mouse=e.mouseObserver}get type(){return this.picker.type}get altKey(){return this.mouse.altKey}get ctrlKey(){return this.mouse.ctrlKey}get metaKey(){return this.mouse.metaKey}get shiftKey(){return this.mouse.shiftKey}get canvasPosition(){return this.mouse.canvasPosition}get component(){return this.stage.getComponentsByObject(this.picker.data).list[0]}get object(){return this.picker.getObject(this.pid)}get position(){return this.picker.getPosition(this.pid,this.instance,this.component)}get closestBondAtom(){if("bond"!==this.type||!this.bond)return;const t=this.bond,e=this.controls,i=this.canvasPosition,r=t.atom1.positionToVector3(),s=t.atom2.positionToVector3();r.applyMatrix4(this.component.matrix),s.applyMatrix4(this.component.matrix);const n=e.getPositionOnCanvas(r),o=e.getPositionOnCanvas(s);return c=n,l=o,(a=i).distanceTo(c)<a.distanceTo(l)?t.atom1:t.atom2;var a,c,l}get closeAtom(){const t=this.canvasPosition,e=this.closestBondAtom;if(!e)return;const i=e.positionToVector3().applyMatrix4(this.component.matrix),r=this.controls.getPositionOnCanvas(i);e.positionToVector3(yr),this.instance&&yr.applyMatrix4(this.instance.matrix),yr.applyMatrix4(this.component.matrix);const s=this.controls.viewer;yr.add(s.translationGroup.position),yr.applyMatrix4(s.rotationGroup.matrix);const n=this.controls.getCanvasScaleFactor(yr.z),o=this.component.getMaxRepresentationRadius(e.index);return t.distanceTo(r)<=o/n?e:void 0}get arrow(){return this._objectIfType("arrow")}get atom(){return this._objectIfType("atom")}get axes(){return this._objectIfType("axes")}get bond(){return this._objectIfType("bond")}get box(){return this._objectIfType("box")}get cone(){return this._objectIfType("cone")}get clash(){return this._objectIfType("clash")}get contact(){return this._objectIfType("contact")}get cylinder(){return this._objectIfType("cylinder")}get distance(){return this._objectIfType("distance")}get ellipsoid(){return this._objectIfType("ellipsoid")}get octahedron(){return this._objectIfType("octahedron")}get point(){return this._objectIfType("point")}get mesh(){return this._objectIfType("mesh")}get slice(){return this._objectIfType("slice")}get sphere(){return this._objectIfType("sphere")}get tetrahedron(){return this._objectIfType("tetrahedron")}get torus(){return this._objectIfType("torus")}get surface(){return this._objectIfType("surface")}get unitcell(){return this._objectIfType("unitcell")}get unknown(){return this._objectIfType("unknown")}get volume(){return this._objectIfType("volume")}get wideline(){return this._objectIfType("wideline")}_objectIfType(t){return this.type===t?this.object:void 0}getLabel(){const t=this.atom||this.closeAtom;let e="nothing";return this.arrow?e=this.arrow.name:t?e=`atom: ${t.qualifiedName()} (${t.structure.name})`:this.axes?e="axes":this.bond?e=`bond: ${this.bond.atom1.qualifiedName()} - ${this.bond.atom2.qualifiedName()} (${this.bond.structure.name})`:this.box?e=this.box.name:this.cone?e=this.cone.name:this.clash?e=`clash: ${this.clash.clash.sele1} - ${this.clash.clash.sele2}`:this.contact?e=`${this.contact.type}: ${this.contact.atom1.qualifiedName()} - ${this.contact.atom2.qualifiedName()} (${this.contact.atom1.structure.name})`:this.cylinder?e=this.cylinder.name:this.distance?e=`distance: ${this.distance.atom1.qualifiedName()} - ${this.distance.atom2.qualifiedName()} (${this.distance.structure.name})`:this.ellipsoid?e=this.ellipsoid.name:this.octahedron?e=this.octahedron.name:this.point?e=this.point.name:this.mesh?e=`mesh: ${this.mesh.name||this.mesh.serial} (${this.mesh.shape.name})`:this.slice?e=`slice: ${this.slice.value.toPrecision(3)} (${this.slice.volume.name})`:this.sphere?e=this.sphere.name:this.surface?e=`surface: ${this.surface.surface.name}`:this.tetrahedron?e=this.tetrahedron.name:this.torus?e=this.torus.name:this.unitcell?e=`unitcell: ${this.unitcell.unitcell.spacegroup} (${this.unitcell.structure.name})`:this.unknown?e="unknown":this.volume?e=`volume: ${this.volume.value.toPrecision(3)} (${this.volume.volume.name})`:this.wideline&&(e=this.wideline.name),e}}class xr{constructor(t){this.stage=t,this.viewer=t.viewer}pick(t,e){const i=this.viewer.pick(t,e);if(i.picker&&"ignore"!==i.picker.type&&void 0!==i.pid){const t=i.picker.array;if(!(t&&i.pid>=t.length))return new br(i,this.stage);console.error("pid >= picker.array.length")}}}const vr=new r,wr=new e,Ar=new e,_r=new e,Sr=new e,Cr=new i,Pr=new e,Ir=new i;class kr{constructor(t){this.stage=t,this.signals={changed:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.viewer=t.viewer}get position(){return this.viewer.translationGroup.position}get rotation(){return this.viewer.rotationGroup.quaternion}changed(){this.viewer.requestRender(),this.signals.changed.dispatch()}getPositionOnCanvas(e,i){const r=wt(i,t);const s=this.viewer;return _r.copy(e).add(s.translationGroup.position).applyMatrix4(s.rotationGroup.matrix).project(s.camera),r.set((_r.x+1)*s.width/2,(_r.y+1)*s.height/2)}getCanvasScaleFactor(t=0){const e=this.viewer.camera;if(e instanceof __WEBPACK_IMPORTED_MODULE_0_three__["F" /* OrthographicCamera */])return 1/e.zoom;{t=Math.abs(t),t+=this.getCameraDistance();const i=kt(e.fov);return 2*t*Math.tan(i/2)/this.viewer.height}}getOrientation(t){const e=_t(t);e.copy(this.viewer.rotationGroup.matrix);const i=this.getCameraDistance();return e.scale(Sr.set(i,i,i)),e.setPosition(this.viewer.translationGroup.position),e}orient(t){_t(t).decompose(wr,vr,Ar);const e=this.viewer;e.rotationGroup.setRotationFromQuaternion(vr),e.translationGroup.position.copy(wr),e.cameraDistance=Ar.z,e.updateZoom(),this.changed()}translate(t){this.viewer.translationGroup.position.add(At(t)),this.changed()}center(t){this.viewer.translationGroup.position.copy(At(t)).negate(),this.changed()}zoom(t){this.distance(this.getCameraDistance()*(1-t))}getCameraDistance(){return this.viewer.cameraDistance}distance(t){this.viewer.cameraDistance=Math.max(Math.abs(t),.2),this.viewer.updateZoom(),this.changed()}spin(t,e){Cr.getInverse(this.viewer.rotationGroup.matrix),Pr.copy(At(t)).applyMatrix4(Cr),this.viewer.rotationGroup.rotateOnAxis(Pr,e),this.changed()}rotate(t){this.viewer.rotationGroup.setRotationFromQuaternion(St(t)),this.changed()}align(t){Ir.getInverse(_t(t)),this.viewer.rotationGroup.setRotationFromMatrix(Ir),this.changed()}applyMatrix(t){this.viewer.rotationGroup.applyMatrix4(_t(t)),this.changed()}}class Mr{constructor(t,e,...i){this.pausedTime=-1,this.elapsedDuration=0,this.pausedDuration=0,this.ignoreGlobalToggle=!1,this._paused=!1,this._resolveList=[],this.duration=st(t,1e3),this.controls=e,this.startTime=window.performance.now(),this._init(...i)}get done(){return 1===this.alpha}get paused(){return this._paused}tick(t){if(!this._paused)return this.elapsedDuration=t.currentTime-this.startTime-this.pausedDuration,0===this.duration?this.alpha=1:this.alpha=Rt(0,1,this.elapsedDuration/this.duration),this._tick(t),this.done&&this._resolveList.forEach((t=>t())),this.done}pause(t){t&&(this._hold=!0),-1===this.pausedTime&&(this.pausedTime=window.performance.now()),this._paused=!0}resume(t){!t&&this._hold||(this.pausedDuration+=window.performance.now()-this.pausedTime,this._paused=!1,this._hold=!1,this.pausedTime=-1)}toggle(){this._paused?this.resume():this.pause()}then(t){let e;return e=this.done?Promise.resolve():new Promise((t=>this._resolveList.push(t))),e.then(t)}}class Tr extends Mr{constructor(t,e,...i){super(st(t,1/0),e,...i)}_init(t,i){Array.isArray(t)?this.axis=(new e).fromArray(t):this.axis=st(t,new e(0,1,0)),this.angle=st(i,.01)}_tick(t){this.axis&&this.angle&&this.controls.spin(this.axis,this.angle*t.lastDuration/16)}}class Br extends Mr{constructor(t,e,...i){super(st(t,1/0),e,...i),this.angleSum=0,this.direction=1}_init(t,i,r){Array.isArray(t)?this.axis=(new e).fromArray(t):this.axis=st(t,new e(0,1,0)),this.angleStep=st(i,.01),this.angleEnd=st(r,.2)}_tick(t){if(!this.axis||!this.angleStep||!this.angleEnd)return;const e=Rt(0,1,Math.abs(this.angleSum)/this.angleEnd),i=this.angleStep*this.direction*(1.1-e);this.controls.spin(this.axis,i*t.lastDuration/16),this.angleSum+=this.angleStep,this.angleSum>=this.angleEnd&&(this.direction*=-1,this.angleSum=-this.angleEnd)}}class Dr extends Mr{_init(t,i){this.moveFrom=At(st(t,new e)),this.moveTo=At(st(i,new e))}_tick(){this.controls.position.lerpVectors(this.moveFrom,this.moveTo,this.alpha).negate(),this.controls.changed()}}class $r extends Mr{_init(t,e){this.zoomFrom=t,this.zoomTo=e}_tick(){this.controls.distance($t(this.zoomFrom,this.zoomTo,this.alpha))}}class Or extends Mr{constructor(){super(...arguments),this._currentRotation=new r}_init(t,e){this.rotateFrom=St(t),this.rotateTo=St(e),this._currentRotation=new r}_tick(){this._currentRotation.copy(this.rotateFrom).slerp(this.rotateTo,this.alpha),this.controls.rotate(this._currentRotation)}}class Rr extends Mr{_init(t,e,i){this.valueFrom=t,this.valueTo=e,this.callback=i}_tick(){this.callback($t(this.valueFrom,this.valueTo,this.alpha))}}class Er extends Mr{_init(t){this.callback=t}_tick(){1===this.alpha&&this.callback()}}class Fr{constructor(t=[]){this._resolveList=[],this._list=t}get done(){return this._list.every((t=>t.done))}then(t){let e;return e=this.done?Promise.resolve():new Promise((t=>{this._resolveList.push(t),this._list.forEach((t=>{t.then((()=>{this._resolveList.forEach((t=>{t()})),this._resolveList.length=0}))}))})),e.then(t)}}class Lr{constructor(t){this.stage=t,this.animationList=[],this.finishedList=[],this.viewer=t.viewer,this.controls=t.viewerControls}get paused(){return this.animationList.every((t=>t.paused))}add(t){return 0===t.duration?t.tick(this.viewer.stats):this.animationList.push(t),t}remove(t){const e=this.animationList,i=e.indexOf(t);i>-1&&e.splice(i,1)}run(t){const e=this.finishedList,i=this.animationList,r=i.length;for(let s=0;s<r;++s){const r=i[s];r.tick(t)&&e.push(r)}const s=e.length;if(s){for(let t=0;t<s;++t)this.remove(e[t]);e.length=0}}spin(t,e,i){return this.add(new Tr(i,this.controls,t,e))}rock(t,e,i,r){return this.add(new Br(r,this.controls,t,e,i))}rotate(t,e){const i=this.viewer.rotationGroup.quaternion.clone();return this.add(new Or(e,this.controls,i,t))}move(t,e){const i=this.controls.position.clone().negate();return this.add(new Dr(e,this.controls,i,t))}zoom(t,e){const i=this.viewer.camera.position.z;return this.add(new $r(e,this.controls,i,t))}zoomMove(t,e,i){return new Fr([this.move(t,i),this.zoom(e,i)])}orient(t,i){const s=new e,n=new r,o=new e;return _t(t).decompose(s,n,o),new Fr([this.move(s.negate(),i),this.rotate(n,i),this.zoom(-o.x,i)])}value(t,e,i,r){return this.add(new Rr(r,this.controls,t,e,i))}timeout(t,e){return this.add(new Er(e,this.controls,t))}spinComponent(t,e,i,r){return this.add(new Tr(r,t.controls,e,i))}rockComponent(t,e,i,r,s){return this.add(new Br(s,t.controls,e,i,r))}moveComponent(t,e,i){const r=t.controls.position.clone().negate();return this.add(new Dr(i,t.controls,r,e))}pause(){this.animationList.forEach((t=>t.pause()))}resume(){this.animationList.forEach((t=>t.resume()))}toggle(){this.paused?this.resume():this.pause()}clear(){this.animationList.length=0}dispose(){this.clear()}}class Nr{constructor(t,e){if(this.fn=t,this.queue=[],this.pending=!1,this.next=this.next.bind(this),e){for(let t=0,i=e.length;t<i;++t)this.queue.push(e[t]);this.next()}}run(t){this.fn(t,this.next)}next(){const t=this.queue.shift();void 0!==t?(this.pending=!0,setTimeout((()=>this.run(t)))):this.pending=!1}push(t){this.queue.push(t),this.pending||this.next()}kill(){this.queue.length=0}length(){return this.queue.length}}class zr{constructor(t,e,i){this.type="",this.parameters={lazy:{type:"boolean"},clipNear:{type:"range",step:1,max:100,min:0,buffer:!0},clipRadius:{type:"number",precision:1,max:1e3,min:0,buffer:!0},clipCenter:{type:"vector3",precision:1,buffer:!0},flatShaded:{type:"boolean",buffer:!0},opacity:{type:"range",step:.01,max:1,min:0,buffer:!0},depthWrite:{type:"boolean",buffer:!0},side:{type:"select",buffer:!0,options:{front:"front",back:"back",double:"double"}},wireframe:{type:"boolean",buffer:!0},colorData:{type:"hidden",update:"color"},colorScheme:{type:"select",update:"color",options:{}},colorScale:{type:"select",update:"color",options:Fe.getScales()},colorReverse:{type:"boolean",update:"color"},colorValue:{type:"color",update:"color"},colorDomain:{type:"hidden",update:"color"},colorMode:{type:"select",update:"color",options:Fe.getModes()},roughness:{type:"range",step:.01,max:1,min:0,buffer:!0},metalness:{type:"range",step:.01,max:1,min:0,buffer:!0},diffuse:{type:"color",buffer:!0},diffuseInterior:{type:"boolean",buffer:!0},useInteriorColor:{type:"boolean",buffer:!0},interiorColor:{type:"color",buffer:!0},interiorDarkening:{type:"range",step:.01,max:1,min:0,buffer:!0},matrix:{type:"hidden",buffer:!0},disablePicking:{type:"boolean",rebuild:!0}},this.viewer=e,this.tasks=new ui,this.queue=new Nr(this.make.bind(this)),this.bufferList=[],this.parameters.colorScheme&&(this.parameters.colorScheme.options=Fe.getSchemes()),this.toBePrepared=!1}init(t){const r=t||{};this.clipNear=st(r.clipNear,0),this.clipRadius=st(r.clipRadius,0),this.clipCenter=st(r.clipCenter,new e),this.flatShaded=st(r.flatShaded,!1),this.side=st(r.side,"double"),this.opacity=st(r.opacity,1),this.depthWrite=st(r.depthWrite,!0),this.wireframe=st(r.wireframe,!1),this.setColor(r.color,r),this.colorData=st(r.colorData,void 0),this.colorScheme=st(r.colorScheme,"uniform"),this.colorScale=st(r.colorScale,""),this.colorReverse=st(r.colorReverse,!1),this.colorValue=st(r.colorValue,9474192),this.colorDomain=st(r.colorDomain,void 0),this.colorMode=st(r.colorMode,"hcl"),this.visible=st(r.visible,!0),this.quality=st(r.quality,void 0),this.roughness=st(r.roughness,.4),this.metalness=st(r.metalness,0),this.diffuse=st(r.diffuse,16777215),this.diffuseInterior=st(r.diffuseInterior,!1),this.useInteriorColor=st(r.useInteriorColor,!1),this.interiorColor=st(r.interiorColor,2236962),this.interiorDarkening=st(r.interiorDarkening,0),this.lazy=st(r.lazy,!1),this.lazyProps={build:!1,bufferParams:{},what:{}},this.matrix=st(r.matrix,new i),this.disablePicking=st(r.disablePicking,!1);const s=this.parameters;!0===s.sphereDetail&&(s.sphereDetail={type:"integer",max:3,min:0,rebuild:"impostor"}),!0===s.radialSegments&&(s.radialSegments={type:"integer",max:25,min:5,rebuild:"impostor"}),!0===s.openEnded&&(s.openEnded={type:"boolean",rebuild:"impostor",buffer:!0}),!0===s.disableImpostor&&(s.disableImpostor={type:"boolean",rebuild:!0}),"low"===r.quality?(s.sphereDetail&&(this.sphereDetail=0),s.radialSegments&&(this.radialSegments=5)):"medium"===r.quality?(s.sphereDetail&&(this.sphereDetail=1),s.radialSegments&&(this.radialSegments=10)):"high"===r.quality?(s.sphereDetail&&(this.sphereDetail=2),s.radialSegments&&(this.radialSegments=20)):(s.sphereDetail&&(this.sphereDetail=st(r.sphereDetail,1)),s.radialSegments&&(this.radialSegments=st(r.radialSegments,10))),s.openEnded&&(this.openEnded=st(r.openEnded,!0)),s.disableImpostor&&(this.disableImpostor=st(r.disableImpostor,!1))}getColorParams(t){return Object.assign({data:this.colorData,scheme:this.colorScheme,scale:this.colorScale,reverse:this.colorReverse,value:this.colorValue,domain:this.colorDomain,mode:this.colorMode,colorSpace:this.colorSpace},t)}getBufferParams(t={}){return Object.assign({clipNear:this.clipNear,clipRadius:this.clipRadius,clipCenter:this.clipCenter,flatShaded:this.flatShaded,opacity:this.opacity,depthWrite:this.depthWrite,side:this.side,wireframe:this.wireframe,roughness:this.roughness,metalness:this.metalness,diffuse:this.diffuse,diffuseInterior:this.diffuseInterior,useInteriorColor:this.useInteriorColor,interiorColor:this.interiorColor,interiorDarkening:this.interiorDarkening,matrix:this.matrix,disablePicking:this.disablePicking},t)}setColor(t,e){const i=Object.keys(Fe.getSchemes());if("string"==typeof t&&i.includes(t.toLowerCase()))e?e.colorScheme=t:this.setParameters({colorScheme:t});else if(void 0!==t){let i=new s(t).getHex();e?(e.colorScheme="uniform",e.colorValue=i):this.setParameters({colorScheme:"uniform",colorValue:i})}return this}prepare(t){}create(){}update(t){this.build()}build(t){if(!this.lazy||this.visible&&this.opacity){if(!this.toBePrepared)return this.tasks.increment(),void this.make();this.queue.length()>0?(this.tasks.change(1-this.queue.length()),this.queue.kill()):this.tasks.increment(),this.queue.push(t||!1)}else this.lazyProps.build=!0}make(t,e){De&&Me.time("Representation.make "+this.type);const i=()=>{t?(this.update(t),this.viewer.requestRender(),this.tasks.decrement(),e&&e()):(this.clear(),this.create(),this.manualAttach||this.disposed||(De&&Me.time("Representation.attach "+this.type),this.attach((()=>{De&&Me.timeEnd("Representation.attach "+this.type),this.tasks.decrement(),e&&e()})))),De&&Me.timeEnd("Representation.make "+this.type)};this.toBePrepared?this.prepare(i):i()}attach(t){this.setVisibility(this.visible),t()}setVisibility(t,e){if(this.visible=t,this.visible&&this.opacity){const t=this.lazyProps,e=t.bufferParams,i=t.what;if(t.build)return t.build=!1,this.build(),this;(Object.keys(e).length||Object.keys(i).length)&&(t.bufferParams={},t.what={},this.updateParameters(e,i))}return this.bufferList.forEach((function(e){e.setVisibility(t)})),e||this.viewer.requestRender(),this}setParameters(t,e={},i=!1){const r=t||{},s=this.parameters,n={};this.opacity||void 0===r.opacity||(this.lazyProps.build?(this.lazyProps.build=!1,i=!0):(Object.assign(n,this.lazyProps.bufferParams),Object.assign(e,this.lazyProps.what),this.lazyProps.bufferParams={},this.lazyProps.what={})),this.setColor(r.color,r);for(let t in r)if(void 0!==r[t]&&null!=s[t]&&(s[t].int&&(r[t]=parseInt(r[t])),s[t].float&&(r[t]=parseFloat(r[t])),r[t]!==this[t]||r[t].equals&&!r[t].equals(this[t]))){if(this[t]&&this[t].copy&&r[t].copy?this[t].copy(r[t]):this[t]&&this[t].set?this[t].set(r[t]):this[t]=r[t],s[t].buffer)if(!0===s[t].buffer)n[t]=r[t];else{n[s[t].buffer]=r[t]}s[t].update&&(e[s[t].update]=!0),!s[t].rebuild||"impostor"===s[t].rebuild&&Ie&&!this.disableImpostor||(i=!0)}return i?this.build():this.updateParameters(n,e),this}updateParameters(t={},e){if(this.lazy&&(!this.visible||!this.opacity)&&!1===t.hasOwnProperty("opacity"))return Object.assign(this.lazyProps.bufferParams,t),void Object.assign(this.lazyProps.what,e);this.bufferList.forEach((function(e){e.setParameters(t)})),Object.keys(e).length&&this.update(e),this.viewer.requestRender()}getParameters(){const t={lazy:this.lazy,visible:this.visible,quality:this.quality};return Object.keys(this.parameters).forEach((e=>{null!==this.parameters[e]&&(t[e]=this[e])})),t}clear(){this.bufferList.forEach((t=>{this.viewer.remove(t),t.dispose()})),this.bufferList.length=0,this.viewer.requestRender()}dispose(){this.disposed=!0,this.queue.kill(),this.tasks.dispose(),this.clear()}}class Vr{constructor(t){this.pending=0,this.postCount=0,this.onmessageDict={},this.onerrorDict={},this.name=t,this.blobUrl=window.URL.createObjectURL(Ee.get(t)),this.worker=new Worker(this.blobUrl),Ee.activeWorkerCount+=1,this.worker.onmessage=e=>{this.pending-=1;const i=e.data.__postId;De&&Me.timeEnd("Worker.postMessage "+t+" #"+i);const r=this.onmessageDict[i];r&&r.call(this.worker,e),delete this.onmessageDict[i],delete this.onerrorDict[i]},this.worker.onerror=e=>{if(this.pending-=1,e.data){const i=e.data.__postId,r=this.onerrorDict[i];r?r.call(this.worker,e):Me.error("Worker.onerror",i,t,e),delete this.onmessageDict[i],delete this.onerrorDict[i]}else Me.error("Worker.onerror",t,e)}}post(t={},e,i,r){this.onmessageDict[this.postCount]=i,this.onerrorDict[this.postCount]=r,t.__name=this.name,t.__postId=this.postCount,t.__debug=De,De&&Me.time(`Worker.postMessage ${this.name} #${this.postCount}`);try{this.worker.postMessage(t,e)}catch(e){Me.error("worker.post:",e),this.worker.postMessage(t)}return this.pending+=1,this.postCount+=1,this}terminate(){this.worker?(this.worker.terminate(),window.URL.revokeObjectURL(this.blobUrl),Ee.activeWorkerCount-=1):Me.log("no worker to terminate")}}class Gr{constructor(t,e=2){this.pool=[],this.count=0,this.maxCount=Math.min(8,e),this.name=t}post(t={},e,i,r){const s=this.getNextWorker();return s?s.post(t,e,i,r):console.error("unable to get worker from pool"),this}terminate(){this.pool.forEach((function(t){t.terminate()}))}getNextWorker(){let t,e=1/0;for(let i=0;i<this.maxCount;++i){if(i>=this.count){t=new Vr(this.name),this.pool.push(t),this.count+=1;break}const r=this.pool[i];if(0===r.pending){t=r;break}r.pending<e&&(e=r.pending,t=r)}return t}}function Ur(t){const i=t.length,r=i/3;let s=0,n=0,o=0;for(let e=0;e<i;e+=3)s+=t[e+0],n+=t[e+1],o+=t[e+2];return new e(s/r,n/r,o/r)}function jr(t,e,i){return i?t.sub(i).projectOnVector(e).add(i):t.projectOnVector(e),t}function Hr(t){let e=1/0,i=1/0,r=1/0,s=-1/0,n=-1/0,o=-1/0;for(let a=0,c=t.length;a<c;a+=3){const c=t[a],l=t[a+1],h=t[a+2];c<e&&(e=c),l<i&&(i=l),h<r&&(r=h),c>s&&(s=c),l>n&&(n=l),h>o&&(o=h)}return[Yr([e,i,r]),Yr([s,n,o])]}function Wr(t,e){for(let i=0,r=e.length;i<r;i+=3){const r=e[i],s=e[i+1],n=e[i+2];e[i]=t[0]*r+t[4]*s+t[8]*n+t[12],e[i+1]=t[1]*r+t[5]*s+t[9]*n+t[13],e[i+2]=t[2]*r+t[6]*s+t[10]*n+t[14]}}function qr(t,e){for(let i=0,r=e.length;i<r;i+=3){const r=e[i],s=e[i+1],n=e[i+2];e[i]=t[0]*r+t[3]*s+t[6]*n,e[i+1]=t[1]*r+t[4]*s+t[7]*n,e[i+2]=t[2]*r+t[5]*s+t[8]*n}}function Xr(t){for(let e=0,i=t.length;e<i;e+=3){const i=t[e],r=t[e+1],s=t[e+2],n=i*i+r*r+s*s;if(n>0){const o=1/Math.sqrt(n);t[e]=i*o,t[e+1]=r*o,t[e+2]=s*o}}}function Yr(t){return new Float32Array(t||3)}function Kr(t,e,i){const r=e[0],s=e[1],n=e[2],o=i[0],a=i[1],c=i[2];t[0]=s*c-n*a,t[1]=n*o-r*c,t[2]=r*a-s*o}function Zr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function Qr(t,e,i){t[0]=e[0]-i[0],t[1]=e[1]-i[1],t[2]=e[2]-i[2]}function Jr(t,e,i){t[0]=e[0]+i[0],t[1]=e[1]+i[1],t[2]=e[2]+i[2]}function ts(t,e,i=0){t[0]=e[i],t[1]=e[i+1],t[2]=e[i+2]}function es(t,e,i=0){e[i]=t[0],e[i+1]=t[1],e[i+2]=t[2]}function is(t){return t[0]*t[0]+t[1]*t[1]+t[2]*t[2]}function rs(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2])}function ss(t,e,i){ns(t,e,1/i)}function ns(t,e,i){t[0]=e[0]*i,t[1]=e[1]*i,t[2]=e[2]*i}function os(t,e){const i=is(e);0==i?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):ns(t,e,1/Math.sqrt(i))}function as(t,e,i){t[0]=e[0]-i,t[1]=e[1]-i,t[2]=e[2]-i}function cs(t,e,i){t[0]=e[0]+i,t[1]=e[1]+i,t[2]=e[2]+i}function ls(t,e){t[0]=Math.floor(e[0]),t[1]=Math.floor(e[1]),t[2]=Math.floor(e[2])}function hs(t,e){t[0]=Math.ceil(e[0]),t[1]=Math.ceil(e[1]),t[2]=Math.ceil(e[2])}function ds(t,e){t[0]=-e[0],t[1]=-e[1],t[2]=-e[2]}function us(t,e){const i=t[0],r=t[1],s=t[2],n=e[0],o=e[1],a=e[2],c=r*a-s*o,l=s*n-i*a,h=i*o-r*n,d=Math.sqrt(c*c+l*l+h*h),u=i*n+r*o+s*a;return Math.atan2(d,u)}function ms(t,i=9){const r=Math.floor(i/2),s=t.position1.length/3,n=3*(r*s),o=1/i,a=_i(t.position1,t.position2),c=new Float32Array(n),l=new Float32Array(n),h=new e;for(let e=0;e<s;++e){const i=3*e;h.set(a[i],a[i+1],a[i+2]);const s=t.position1[i],n=t.position1[i+1],d=t.position1[i+2];for(let t=0;t<r;++t){const e=r*i+3*t,a=o*(2*t+1),u=o*(2*t+2);c[e]=s+h.x*a,c[e+1]=n+h.y*a,c[e+2]=d+h.z*a,l[e]=s+h.x*u,l[e+1]=n+h.y*u,l[e+2]=d+h.z*u}}const d=Ai(c,l),u=function(t,e){const i=t.length/3,r=new Float32Array(i*e*3);for(let s=0;s<i;++s){const i=3*s,n=s*e*3,o=t[i+0],a=t[i+1],c=t[i+2];for(let t=0;t<e;++t){const e=n+3*t;r[e+0]=o,r[e+1]=a,r[e+2]=c}}return r}(t.color,r),m={position:d,position1:c,position2:l,color:u,color2:u};return t.radius&&(m.radius=ki(t.radius,r)),t.picking&&t.picking.array&&(t.picking.array=ki(t.picking.array,r),m.picking=t.picking),t.primitiveId&&(m.primitiveId=ki(t.primitiveId,r)),m}function ps(t,i=.1){const r=_i(t.position1,t.position2),s=[],n=[],o=[],a=t.radius?[]:void 0,c=t.picking?[]:void 0,l=t.primitiveId?[]:void 0,h=new e,d=t.position1.length/3;let u=0;for(let e=0;e<d;++e){const d=3*e;h.set(r[d],r[d+1],r[d+2]);const m=h.length()/i,p=Math.floor(m/2),f=1/m,g=t.position1[d],y=t.position1[d+1],b=t.position1[d+2];for(let i=0;i<p;++i){const r=3*u+3*i,m=f*(2*i+1),p=f*(2*i+2);s[r]=g+h.x*m,s[r+1]=y+h.y*m,s[r+2]=b+h.z*m,n[r]=g+h.x*p,n[r+1]=y+h.y*p,n[r+2]=b+h.z*p,t.color&&(o[r]=t.color[d],o[r+1]=t.color[d+1],o[r+2]=t.color[d+2]),a&&(a[u+i]=t.radius[e]),c&&(t.picking.array?c[u+i]=t.picking.array[e]:c[u+i]=e),l&&(l[u+i]=t.primitiveId[e])}u+=p}const m=new Float32Array(s),p=new Float32Array(n),f=Ai(m,p),g=new Float32Array(o),y={position:f,position1:m,position2:p,color:g,color2:g};return a&&(y.radius=new Float32Array(a)),c&&t.picking&&(t.picking.array=new Float32Array(c),y.picking=t.picking),l&&(y.primitiveId=new Float32Array(l)),y}function fs(t,i=.1){const r=_i(t.position1,t.position2),s=[],n=[],o=[],a=t.radius?[]:void 0,c=t.picking?[]:void 0,l=t.primitiveId?[]:void 0,h=new e,d=t.position1.length/3;let u=i,m=!0,p=0,f=0,g=0;for(let e=0;e<d;++e){const d=3*e,y=t.position1[d],b=t.position1[d+1],x=t.position1[d+2];h.set(r[d],r[d+1],r[d+2]);const v=h.length();m&&(s[f]=y,s[f+1]=b,s[f+2]=x);let w=u;const A=1/v;for(;w<v;){const t=m?n:s;t[f]=y+h.x*w*A,t[f+1]=b+h.y*w*A,t[f+2]=x+h.z*w*A,m&&(p++,f=3*p),m=!m,u=i,w+=i}m&&(n[f]=t.position2[d],n[f+1]=t.position2[d+1],n[f+2]=t.position2[d+2],p++,f=3*p),u=w-v;for(let i=g;i<p;i++){if(t.color){const e=3*i;o[e]=t.color[d],o[e+1]=t.color[d+1],o[e+2]=t.color[d+2]}a&&(a[i]=t.radius[e]),c&&(t.picking.array?c[i]=t.picking.array[e]:c[i]=e),l&&(l[i]=t.primitiveId[e])}g=p}if(!m&&d>0){const e=3*p;n[e]=t.position2[3*d-3],n[e+1]=t.position2[3*d-2],n[e+1]=t.position2[3*d-1]}const y=new Float32Array(s),b=new Float32Array(n),x=Ai(y,b),v=new Float32Array(o),w={position:x,position1:y,position2:b,color:v,color2:v};return a&&(w.radius=new Float32Array(a)),c&&t.picking&&(t.picking.array=new Float32Array(c),w.picking=t.picking),l&&(w.primitiveId=new Float32Array(l)),w}Gr.prototype.constructor=Gr,Hr.__deps=[Yr],ss.__deps=[ns],os.__deps=[ns,is];const gs=new e;class ys{static get Picker(){return He.get(this.type)}static get Buffer(){return je.get(this.type)}static getShapeKey(t){return this.type+t[0].toUpperCase()+t.substr(1)}static expandBoundingBox(t,e){}static valueToShape(t,e,i){const r=t._primitiveData[this.getShapeKey(e)];switch(this.fields[e]){case"v3":case"c":n=r,void 0!==(s=i).toArray?s=s.toArray():void 0!==s.x?s=[s.x,s.y,s.z]:void 0!==s.r&&(s=[s.r,s.g,s.b]),n.push.apply(n,s);break;default:r.push(i)}var s,n}static objectToShape(t,e){Object.keys(this.fields).forEach((i=>{this.valueToShape(t,i,e[i])})),this.valueToShape(t,"name",e.name),this.expandBoundingBox(t.boundingBox,e)}static valueFromShape(t,i,r){const n=t._primitiveData[this.getShapeKey(r)];switch(this.fields[r]){case"v3":return(new e).fromArray(n,3*i);case"c":return(new s).fromArray(n,3*i);default:return n[i]}}static objectFromShape(t,e){let i=this.valueFromShape(t,e,"name");void 0===i&&(i=`${this.type}: ${e} (${t.name})`);const r={shape:t,name:i};return Object.keys(this.fields).forEach((i=>{r[i]=this.valueFromShape(t,e,i)})),r}static arrayFromShape(t,e){const i=t._primitiveData[this.getShapeKey(e)];return"s"===this.fields[e]?i:new Float32Array(i)}static dataFromShape(t){const e={};return this.Picker&&(e.picking=new this.Picker(t)),Object.keys(this.fields).forEach((i=>{e[i]=this.arrayFromShape(t,i)})),e}static bufferFromShape(t,e){return new this.Buffer(this.dataFromShape(t),e)}}ys.type="",ys.fields={};class bs extends ys{static positionFromShape(t,e){return this.valueFromShape(t,e,"position")}static expandBoundingBox(t,e){t.expandByPoint(gs.fromArray(e.position))}}bs.type="sphere",bs.fields={position:"v3",color:"c",radius:"f"};class xs extends ys{static positionFromShape(t,e){return this.valueFromShape(t,e,"position")}static expandBoundingBox(t,e){t.expandByPoint(gs.fromArray(e.position))}}xs.type="box",xs.fields={position:"v3",color:"c",size:"f",heightAxis:"v3",depthAxis:"v3"};class vs extends xs{}vs.type="octahedron";class ws extends xs{}ws.type="tetrahedron";class As extends ys{static positionFromShape(t,e){const i=this.valueFromShape(t,e,"position1"),r=this.valueFromShape(t,e,"position2");return i.add(r).multiplyScalar(.5)}static expandBoundingBox(t,e){t.expandByPoint(gs.fromArray(e.position1)),t.expandByPoint(gs.fromArray(e.position2))}static bufferFromShape(t,e={}){let i=this.dataFromShape(t);return"cylinder"===this.type&&e.dashedCylinder&&(i=ps(i)),new this.Buffer(i,e)}}As.type="cylinder",As.fields={position1:"v3",position2:"v3",color:"c",radius:"f"};class _s extends As{}_s.type="arrow";class Ss extends As{}Ss.type="cone";class Cs extends bs{}Cs.type="ellipsoid",Cs.fields={position:"v3",color:"c",radius:"f",majorAxis:"v3",minorAxis:"v3"};class Ps extends Cs{}Ps.type="torus";class Is extends ys{static positionFromShape(t,e){return this.valueFromShape(t,e,"position")}static expandBoundingBox(t,e){t.expandByPoint(gs.fromArray(e.position))}}Is.type="text",Is.fields={position:"v3",color:"c",size:"f",text:"s"};class ks extends ys{static positionFromShape(t,e){return this.valueFromShape(t,e,"position")}static expandBoundingBox(t,e){t.expandByPoint(gs.fromArray(e.position))}}ks.type="point",ks.fields={position:"v3",color:"c"};class Ms extends ys{static positionFromShape(t,e){const i=this.valueFromShape(t,e,"position1"),r=this.valueFromShape(t,e,"position2");return i.add(r).multiplyScalar(.5)}static expandBoundingBox(t,e){t.expandByPoint(gs.fromArray(e.position1)),t.expandByPoint(gs.fromArray(e.position2))}}Ms.type="wideline",Ms.fields={position1:"v3",position2:"v3",color:"c"};class Ts{constructor(t,e){this.exp=3;const i=e||function(t){const{x:e,y:i,z:r}=t,s=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],n=e.length,{min:o,max:c}=s;for(let t=0;t<n;t++)o.x=Math.min(e[t],o.x),o.y=Math.min(i[t],o.y),o.z=Math.min(r[t],o.z),c.x=Math.max(e[t],c.x),c.y=Math.max(i[t],c.y),c.z=Math.max(r[t],c.z);return s}(t);this.minX=i.min.x,this.minY=i.min.y,this.minZ=i.min.z,this.boundX=1+(i.max.x-this.minX>>this.exp),this.boundY=1+(i.max.y-this.minY>>this.exp),this.boundZ=1+(i.max.z-this.minZ>>this.exp);const r=this.boundX*this.boundY*this.boundZ,s=void 0!==t.count?t.count:t.x.length,n=t.x,o=t.y,c=t.z;let l=0;const h=new Uint32Array(r),d=new Int32Array(s);for(let t=0;t<s;++t){const e=n[t]-this.minX>>this.exp,i=o[t]-this.minY>>this.exp,r=c[t]-this.minZ>>this.exp,s=(e*this.boundY+i)*this.boundZ+r;1===(h[s]+=1)&&(l+=1),d[t]=s}const u=new Uint16Array(l);for(let t=0,e=0;t<r;++t){const i=h[t];i>0&&(h[t]=e+1,u[e]=i,e+=1)}const m=new Uint32Array(l);for(let t=1;t<l;++t)m[t]+=m[t-1]+u[t-1];const p=new Uint16Array(l),f=new Int32Array(s);for(let t=0;t<s;++t){const e=h[d[t]];if(e>0){const i=e-1;f[m[i]+p[i]]=t,p[i]+=1}}this.grid=h,this.bucketCount=u,this.bucketOffset=m,this.bucketArray=f,this.xArray=n,this.yArray=o,this.zArray=c}within(t,e,i,r){const s=[];return this.eachWithin(t,e,i,r,(t=>s.push(t))),s}eachWithin(t,e,i,r,s){const n=r*r,o=Math.max(0,t-r-this.minX>>this.exp),a=Math.max(0,e-r-this.minY>>this.exp),c=Math.max(0,i-r-this.minZ>>this.exp),l=Math.min(this.boundX,1+(t+r-this.minX>>this.exp)),h=Math.min(this.boundY,1+(e+r-this.minY>>this.exp)),d=Math.min(this.boundZ,1+(i+r-this.minZ>>this.exp));for(let r=o;r<l;++r)for(let o=a;o<h;++o)for(let a=c;a<d;++a){const c=(r*this.boundY+o)*this.boundZ+a,l=this.grid[c];if(l>0){const r=l-1,o=this.bucketOffset[r],a=o+this.bucketCount[r];for(let r=o;r<a;++r){const o=this.bucketArray[r],a=this.xArray[o]-t,c=this.yArray[o]-e,l=this.zArray[o]-i,h=a*a+c*c+l*l;h<=n&&s(o,h)}}}}}class Bs{constructor(t=0){this._fields=this._defaultFields,this._init(0)}get _defaultFields(){return[]}_init(t){this.length=t,this.count=0;for(let t=0,e=this._fields.length;t<e;++t){const[e,i,r]=this._fields[t];this._initField(e,i,r)}}_initField(t,e,i){this[t]=bt(i,this.length*e)}addField(t,e,i){this._fields.push([t,e,i]),this._initField(t,e,i)}resize(t){this.length=Math.round(t||0),this.count=Math.min(this.count,this.length);for(let t=0,e=this._fields.length;t<e;++t){const e=this._fields[t][0],i=this._fields[t][1],r=this.length*i,s=new this[e].constructor(r);this[e].length>r?s.set(this[e].subarray(0,r)):s.set(this[e]),this[e]=s}}growIfFull(){if(this.count>=this.length){const t=Math.round(1.5*this.length);this.resize(Math.max(256,t))}}copyFrom(t,e,i,r){for(let s=0,n=this._fields.length;s<n;++s){const n=this._fields[s][0],o=this._fields[s][1],a=this[n],c=t[n];for(let t=0;t<r;++t){const r=o*(e+t),s=o*(i+t);for(let t=0;t<o;++t)a[r+t]=c[s+t]}}}copyWithin(t,e,i){for(let r=0,s=this._fields.length;r<s;++r){const s=this._fields[r][0],n=this._fields[r][1],o=this[s];for(let r=0;r<i;++r){const i=n*(t+r),s=n*(e+r);for(let t=0;t<n;++t)o[i+t]=o[s+t]}}}sort(t){Me.time("Store.sort");const e=this,i=new this.constructor(1);!function r(s,n){if(s<n){let c=Math.floor((s+n)/2),l=s,h=n;do{for(;t(l,c)<0;)l+=1;for(;t(h,c)>0;)h-=1;l<=h&&(l===c?c=h:h===c&&(c=l),(o=l)!==(a=h)&&(i.copyFrom(e,0,o,1),e.copyWithin(o,a,1),e.copyFrom(i,a,0,1)),l+=1,h-=1)}while(l<=h);r(s,h),r(l,n)}var o,a}(0,this.count-1),Me.timeEnd("Store.sort")}clear(){this.count=0}dispose(){for(let t=0,e=this._fields.length;t<e;++t){delete this[this._fields[t][0]]}}}class Ds extends Bs{get _defaultFields(){return[["index1",1,"int32"],["index2",1,"int32"],["type",1,"int8"]]}addContact(t,e,i){this.growIfFull();const r=this.count;t<e?(this.index1[r]=t,this.index2[r]=e):(this.index2[r]=t,this.index1[r]=e),i&&(this.type[r]=i),this.count+=1}}function $s(t){return 16843009*((t=(858993459&(t-=t>>>1&1431655765))+(t>>>2&858993459))+(t>>>4)&252645135)>>>24}class Os{constructor(t,e){this.length=t,this._words=new Uint32Array(t+32>>>5),!0===e&&this.setAll()}get(t){return 0!=(this._words[t>>>5]&1<<t)}set(t){this._words[t>>>5]|=1<<t}clear(t){this._words[t>>>5]&=~(1<<t)}flip(t){this._words[t>>>5]^=1<<t}_assignRange(t,e,i){if(e<t)return;const r=this._words,s=!0===i?4294967295:0,n=t>>>5,o=e>>>5;for(let t=n+1;t<o;++t)r[t]=s;const a=n<<5,c=o<<5;if(!0===i)if(e-t<32)for(let i=t,s=e+1;i<s;++i)r[i>>>5]|=1<<i;else{for(let e=t,i=a+32;e<i;++e)r[e>>>5]|=1<<e;for(let t=c,i=e+1;t<i;++t)r[t>>>5]|=1<<t}else if(e-t<32)for(let i=t,s=e+1;i<s;++i)r[i>>>5]&=~(1<<i);else{for(let e=t,i=a+32;e<i;++e)r[e>>>5]&=~(1<<e);for(let t=c,i=e+1;t<i;++t)r[t>>>5]&=~(1<<t)}return this}setRange(t,e){return this._assignRange(t,e,!0)}clearRange(t,e){return this._assignRange(t,e,!1)}setBits(...t){const e=this._words,i=t.length;for(let r=0;r<i;++r){const i=t[r];e[i>>>5]|=1<<i}return this}clearBits(...t){const e=this._words,i=t.length;for(let r=0;r<i;++r){const i=t[r];e[i>>>5]&=~(1<<i)}return this}setAll(){return this._assignRange(0,this.length-1,!0)}clearAll(){return this._assignRange(0,this.length-1,!1)}flipAll(){const t=this._words.length,e=this._words,i=32-this.length%32;for(let i=0;i<t-1;++i)e[i]=~e[i];return e[t-1]=~(e[t-1]<<i)>>>i,this}_isRangeValue(t,e,i){if(e<t)return;const r=this._words,s=!0===i?4294967295:0,n=t>>>5,o=e>>>5;for(let t=n+1;t<o;++t)if(r[t]!==s)return!1;if(e-t<32){for(let s=t,n=e+1;s<n;++s)if(!!(r[s>>>5]&1<<s)!==i)return!1}else{const s=o<<5;for(let e=t,s=(n<<5)+32;e<s;++e)if(!!(r[e>>>5]&1<<e)!==i)return!1;for(let t=s,n=e+1;t<n;++t)if(!!(r[t>>>5]&1<<t)!==i)return!1}return!0}isRangeSet(t,e){return this._isRangeValue(t,e,!0)}isRangeClear(t,e){return this._isRangeValue(t,e,!1)}isAllSet(){return this._isRangeValue(0,this.length-1,!0)}isAllClear(){return this._isRangeValue(0,this.length-1,!1)}isSet(...t){const e=this._words,i=t.length;for(let r=0;r<i;++r){const i=t[r];if(0==(e[i>>>5]&1<<i))return!1}return!0}isClear(...t){const e=this._words,i=t.length;for(let r=0;r<i;++r){const i=t[r];if(0!=(e[i>>>5]&1<<i))return!1}return!0}isEqualTo(t){const e=this._words,i=t._words,r=Math.min(e.length,i.length);for(let t=0;t<r;++t)if(e[t]!==i[t])return!1;return!0}getSize(){const t=this._words.length,e=this._words;let i=0;for(let r=0;r<t;++r)i+=$s(e[r]);return i}difference(t){const e=this._words,i=t._words,r=Math.min(e.length,i.length);for(let t=0;t<r;++t)e[t]=e[t]&~i[t];for(let t=e.length;t<r;++t)e[t]=0;return this}union(t){const e=this._words,i=t._words,r=Math.min(e.length,i.length);for(let t=0;t<r;++t)e[t]|=i[t];for(let t=e.length;t<r;++t)e[t]=0;return this}intersection(t){const e=this._words,i=t._words,r=Math.min(e.length,i.length);for(let t=0;t<r;++t)e[t]&=i[t];for(let t=e.length;t<r;++t)e[t]=0;return this}intersects(t){const e=this._words,i=t._words,r=Math.min(e.length,i.length);for(let t=0;t<r;++t)if(0!=(e[t]&i[t]))return!0;return!1}getIntersectionSize(t){const e=this._words,i=t._words,r=Math.min(e.length,i.length);let s=0;for(let t=0;t<r;++t)s+=$s(e[t]&i[t]);return s}makeIntersection(t){const e=this._words,i=t._words,r=Math.min(e.length,i.length),s=new Uint32Array(r),n=Object.create(Os.prototype);n._words=s,n.length=Math.min(this.length,t.length);for(let t=0;t<r;++t)s[t]=e[t]&i[t];return n}forEach(t){const e=this._words.length,i=this._words;let r=0;for(let s=0;s<e;++s){let e=i[s];for(;0!==e;){const i=e&-e;t((s<<5)+$s(i-1),r),e^=i,++r}}}toArray(){const t=this._words,e=new Array(this.getSize()),i=this._words.length;let r=0;for(let s=0;s<i;++s){let i=t[s];for(;0!==i;){const t=i&-i;e[r++]=(s<<5)+$s(t-1),i^=t}}return e}toString(){return"{"+this.toArray().join(",")+"}"}toSeleString(){const t=this.toArray().join(",");return t?"@"+t:"NONE"}clone(){const t=Object.create(Os.prototype);return t.length=this.length,t._words=new Uint32Array(this._words),t}}function Rs(t){const{edgeCount:e,nodeCount:i,nodeArray1:r,nodeArray2:s}=t,n=new Uint8Array(i),o=new Int32Array(i);for(let t=0;t<e;++t)n[r[t]]+=1,n[s[t]]+=1;for(let t=1;t<i;++t)o[t]+=o[t-1]+n[t-1];const a=2*e,c=new Int32Array(a);for(let t=0;t<a;++t)c[t]=-1;for(let t=0;t<e;++t){const e=r[t],i=s[t];let n=o[e];for(;-1!==c[n]&&n<a;)n+=1;c[n]=t;let l=o[i];for(;-1!==c[l]&&l<a;)l+=1;c[l]=t}return{countArray:n,offsetArray:o,indexArray:c}}function Es(t=0,e=0){return{type:t,group:e,x:0,y:0,z:0,atomSet:[]}}function Fs(t,e){t.x+=e.x,t.y+=e.y,t.z+=e.z,t.atomSet.push(e.index)}function Ls(t,e){const i=e.atomSet.length;if(i>0){const{types:r,groups:s,centers:n,atomSets:o}=t;r.push(e.type),s.push(e.group),n.x.push(e.x/i),n.y.push(e.y/i),n.z.push(e.z/i),o.push(e.atomSet)}}const Ns=0,zs=["D-BETA-PEPTIDE, C-GAMMA LINKING","D-GAMMA-PEPTIDE, C-DELTA LINKING","D-PEPTIDE COOH CARBOXY TERMINUS","D-PEPTIDE NH3 AMINO TERMINUS","D-PEPTIDE LINKING","L-BETA-PEPTIDE, C-GAMMA LINKING","L-GAMMA-PEPTIDE, C-DELTA LINKING","L-PEPTIDE COOH CARBOXY TERMINUS","L-PEPTIDE NH3 AMINO TERMINUS","L-PEPTIDE LINKING","PEPTIDE LINKING","PEPTIDE-LIKE"],Vs=["RNA OH 3 PRIME TERMINUS","RNA OH 5 PRIME TERMINUS","RNA LINKING"],Gs=["DNA OH 3 PRIME TERMINUS","DNA OH 5 PRIME TERMINUS","DNA LINKING","L-DNA LINKING","L-RNA LINKING"],Us=["D-SACCHARIDE","D-SACCHARIDE 1,4 AND 1,4 LINKING","D-SACCHARIDE 1,4 AND 1,6 LINKING","L-SACCHARIDE","L-SACCHARIDE 1,4 AND 1,4 LINKING","L-SACCHARIDE 1,4 AND 1,6 LINKING","SACCHARIDE"],js=["NON-POLYMER"].concat(["OTHER"],Us),Hs=["h","g","i"],Ws=["e","b"],qs=["s","t","l",""],Xs={H:1,D:1,T:1,HE:2,LI:3,BE:4,B:5,C:6,N:7,O:8,F:9,NE:10,NA:11,MG:12,AL:13,SI:14,P:15,S:16,CL:17,AR:18,K:19,CA:20,SC:21,TI:22,V:23,CR:24,MN:25,FE:26,CO:27,NI:28,CU:29,ZN:30,GA:31,GE:32,AS:33,SE:34,BR:35,KR:36,RB:37,SR:38,Y:39,ZR:40,NB:41,MO:42,TC:43,RU:44,RH:45,PD:46,AG:47,CD:48,IN:49,SN:50,SB:51,TE:52,I:53,XE:54,CS:55,BA:56,LA:57,CE:58,PR:59,ND:60,PM:61,SM:62,EU:63,GD:64,TB:65,DY:66,HO:67,ER:68,TM:69,YB:70,LU:71,HF:72,TA:73,W:74,RE:75,OS:76,IR:77,PT:78,AU:79,HG:80,TL:81,PB:82,BI:83,PO:84,AT:85,RN:86,FR:87,RA:88,AC:89,TH:90,PA:91,U:92,NP:93,PU:94,AM:95,CM:96,BK:97,CF:98,ES:99,FM:100,MD:101,NO:102,LR:103,RF:104,DB:105,SG:106,BH:107,HS:108,MT:109,DS:110,RG:111,CN:112,NH:113,FL:114,MC:115,LV:116,TS:117,OG:118},Ys={1:1.1,2:1.4,3:1.81,4:1.53,5:1.92,6:1.7,7:1.55,8:1.52,9:1.47,10:1.54,11:2.27,12:1.73,13:1.84,14:2.1,15:1.8,16:1.8,17:1.75,18:1.88,19:2.75,20:2.31,21:2.3,22:2.15,23:2.05,24:2.05,25:2.05,26:2.05,27:2,28:2,29:2,30:2.1,31:1.87,32:2.11,33:1.85,34:1.9,35:1.83,36:2.02,37:3.03,38:2.49,39:2.4,40:2.3,41:2.15,42:2.1,43:2.05,44:2.05,45:2,46:2.05,47:2.1,48:2.2,49:2.2,50:1.93,51:2.17,52:2.06,53:1.98,54:2.16,55:3.43,56:2.68,57:2.5,58:2.48,59:2.47,60:2.45,61:2.43,62:2.42,63:2.4,64:2.38,65:2.37,66:2.35,67:2.33,68:2.32,69:2.3,70:2.28,71:2.27,72:2.25,73:2.2,74:2.1,75:2.05,76:2,77:2,78:2.05,79:2.1,80:2.05,81:1.96,82:2.02,83:2.07,84:1.97,85:2.02,86:2.2,87:3.48,88:2.83,89:2,90:2.4,91:2,92:2.3,93:2,94:2,95:2,96:2,97:2,98:2,99:2,100:2,101:2,102:2,103:2,104:2,105:2,106:2,107:2,108:2,109:2,110:2,111:2,112:2,113:2,114:2,115:2,116:2,117:2,118:2},Ks={1:.31,2:.28,3:1.28,4:.96,5:.84,6:.76,7:.71,8:.66,9:.57,10:.58,11:1.66,12:1.41,13:1.21,14:1.11,15:1.07,16:1.05,17:1.02,18:1.06,19:2.03,20:1.76,21:1.7,22:1.6,23:1.53,24:1.39,25:1.39,26:1.32,27:1.26,28:1.24,29:1.32,30:1.22,31:1.22,32:1.2,33:1.19,34:1.2,35:1.2,36:1.16,37:2.2,38:1.95,39:1.9,40:1.75,41:1.64,42:1.54,43:1.47,44:1.46,45:1.42,46:1.39,47:1.45,48:1.44,49:1.42,50:1.39,51:1.39,52:1.38,53:1.39,54:1.4,55:2.44,56:2.15,57:2.07,58:2.04,59:2.03,60:2.01,61:1.99,62:1.98,63:1.98,64:1.96,65:1.94,66:1.92,67:1.92,68:1.89,69:1.9,70:1.87,71:1.87,72:1.75,73:1.7,74:1.62,75:1.51,76:1.44,77:1.41,78:1.36,79:1.36,80:1.32,81:1.45,82:1.46,83:1.48,84:1.4,85:1.5,86:1.5,87:2.6,88:2.21,89:2.15,90:2.06,91:2,92:1.96,93:1.9,94:1.87,95:1.8,96:1.69,97:1.6,98:1.6,99:1.6,100:1.6,101:1.6,102:1.6,103:1.6,104:1.6,105:1.6,106:1.6,107:1.6,108:1.6,109:1.6,110:1.6,111:1.6,112:1.6,113:1.6,114:1.6,115:1.6,116:1.6,117:1.6,118:1.6},Zs={1:[1],2:[0],3:[1],4:[2],5:[3],6:[4],7:[3],8:[2],9:[1],10:[0],11:[1],12:[2],13:[6],14:[6],15:[3,5,7],16:[2,4,6],17:[1],18:[0],19:[1],20:[2],31:[3],32:[4],33:[3,5],34:[2,4,6],35:[1],36:[0],37:[1],38:[2],49:[3],50:[4],51:[3,5],52:[2],53:[1,2,5],54:[0,2],55:[1],56:[2],81:[3],82:[4],83:[3],84:[2],85:[1],86:[0],87:[1],88:[2]},Qs={1:1,2:2,3:1,4:2,5:3,6:4,7:5,8:6,9:7,10:8,11:1,12:2,13:3,14:4,15:5,16:6,17:7,18:8,19:1,20:2,21:3,22:4,23:5,24:6,25:7,26:8,27:9,28:10,29:11,30:2,31:3,32:4,33:5,34:6,35:7,36:8,37:1,38:2,39:3,40:4,41:5,42:6,43:7,44:8,45:9,46:10,47:11,48:2,49:3,50:4,51:5,52:6,53:7,54:8,55:1,56:2,57:3,58:4,59:3,60:4,61:5,62:6,63:7,64:8,65:9,66:10,67:11,68:12,69:13,70:14,71:15,72:4,73:5,74:6,75:7,76:8,77:9,78:10,79:11,80:2,81:3,82:4,83:5,84:6,85:7,86:8,87:1,88:2,89:3,90:4,91:3,92:4,93:5,94:6,95:7,96:8,97:9,98:10,99:11,100:12,101:13,102:14,103:15,104:2,105:2,106:2,107:2,108:2,109:2,110:2,111:2,112:2,113:3,114:4,115:5,116:6,117:7,118:8},Js={ALA:[.17,.5,.33],ARG:[.81,1.81,1],ASN:[.42,.85,.43],ASP:[1.23,3.64,2.41],ASH:[-.07,.43,.5],CYS:[-.24,-.02,.22],GLN:[.58,.77,.19],GLU:[2.02,3.63,1.61],GLH:[-.01,.11,.12],GLY:[.01,1.15,1.14],HIS:[.17,.11,-.06],ILE:[-.31,-1.12,-.81],LEU:[-.56,-1.25,-.69],LYS:[.99,2.8,1.81],MET:[-.23,-.67,-.44],PHE:[-1.13,-1.71,-.58],PRO:[.45,.14,-.31],SER:[.13,.46,.33],THR:[.14,.25,.11],TRP:[-1.85,-2.09,-.24],TYR:[-.94,-.71,.23],VAL:[.07,-.46,-.53]},tn=[0,0,0],en={HIS:"H",ARG:"R",LYS:"K",ILE:"I",PHE:"F",LEU:"L",TRP:"W",ALA:"A",MET:"M",PRO:"P",CYS:"C",ASN:"N",VAL:"V",GLY:"G",SER:"S",GLN:"Q",TYR:"Y",ASP:"D",GLU:"E",THR:"T",SEC:"U",PYL:"O"},rn=Object.keys(en),sn=["A","C","T","G","U","I"],nn=["DA","DC","DT","DG","DU","DI"],on=["A","G","I","DA","DG","DI"],an=sn.concat(nn),cn=["SOL","WAT","HOH","H2O","W","DOD","D3O","TIP3","TIP4","SPC"],ln=["118","119","1AL","1CU","2FK","2HP","2OF","3CO","3MT","3NI","3OF","3P8","4MO","4PU","543","6MO","ACT","AG","AL","ALF","AM","ATH","AU","AU3","AUC","AZI","BA","BCT","BEF","BF4","BO4","BR","BS3","BSY","CA","CAC","CD","CD1","CD3","CD5","CE","CHT","CL","CO","CO3","CO5","CON","CR","CS","CSB","CU","CU1","CU3","CUA","CUZ","CYN","DME","DMI","DSC","DTI","DY","E4N","EDR","EMC","ER3","EU","EU3","F","FE","FE2","FPO","GA","GD3","GEP","HAI","HG","HGC","IN","IOD","IR","IR3","IRI","IUM","K","KO4","LA","LCO","LCP","LI","LU","MAC","MG","MH2","MH3","MLI","MLT","MMC","MN","MN3","MN5","MN6","MO1","MO2","MO3","MO4","MO5","MO6","MOO","MOS","MOW","MW1","MW2","MW3","NA","NA2","NA5","NA6","NAO","NAW","NCO","NET","NH4","NI","NI1","NI2","NI3","NO2","NO3","NRU","O4M","OAA","OC1","OC2","OC3","OC4","OC5","OC6","OC7","OC8","OCL","OCM","OCN","OCO","OF1","OF2","OF3","OH","OS","OS4","OXL","PB","PBM","PD","PDV","PER","PI","PO3","PO4","PR","PT","PT4","PTN","RB","RH3","RHD","RU","SB","SCN","SE4","SEK","SM","SMO","SO3","SO4","SR","T1A","TB","TBA","TCN","TEA","TH","THE","TL","TMA","TRA","UNX","V","VN3","VO4","W","WO5","Y1","YB","YB2","YH","YT3","ZCM","ZN","ZN2","ZN3","ZNO","ZO3","OHX"],hn=["045","0AT","0BD","0MK","0NZ","0TS","0V4","0XY","0YT","10M","147","149","14T","15L","16G","18T","18Y","1AR","1BW","1GL","1GN","1JB","1LL","1NA","1S3","26M","26Q","26R","26V","26W","26Y","27C","289","291","293","2DG","2F8","2FG","2FL","2FP","2GL","2M4","2M5","32O","34V","3CM","3DO","3DY","3FM","3LR","3MF","3MG","3SA","3ZW","46D","46M","46Z","48Z","4CQ","4GC","4NN","50A","5DI","5GF","5MM","5RP","5SA","5SP","64K","6PG","6SA","7JZ","7SA","A1Q","A2G","AAB","AAL","AAO","ABC","ABD","ABE","ABF","ABL","ACG","ACI","ACR","ACX","ADA","ADG","ADR","AF1","AFD","AFL","AFO","AFP","AFR","AGC","AGH","AGL","AHR","AIG","ALL","ALX","AMU","AOG","AOS","ARA","ARB","ARE","ARI","ASG","ASO","AXP","AXR","B0D","B16","B2G","B4G","B6D","B8D","B9D","BBK","BCD","BDG","BDP","BDR","BEM","BFP","BGC","BGL","BGP","BGS","BHG","BMA","BMX","BNG","BNX","BOG","BRI","BXF","BXP","BXX","BXY","C3X","C4X","C5X","CAP","CBI","CBK","CBS","CDR","CEG","CGF","CHO","CR1","CR6","CRA","CT3","CTO","CTR","CTT","D6G","DAF","DAG","DDA","DDB","DDL","DEL","DFR","DFX","DG0","DGC","DGD","DGM","DGS","DIG","DLF","DLG","DMU","DNO","DOM","DP5","DQQ","DQR","DR2","DR3","DR4","DRI","DSR","DT6","DVC","E4P","E5G","EAG","EBG","EBQ","EGA","EJT","EPG","ERE","ERI","F1P","F1X","F6P","FBP","FCA","FCB","FCT","FDP","FDQ","FFC","FIX","FMO","FRU","FSI","FU4","FUB","FUC","FUD","FUL","FXP","G16","G1P","G2F","G3I","G4D","G4S","G6D","G6P","G6S","GAC","GAD","GAL","GC1","GC4","GCD","GCN","GCO","GCS","GCT","GCU","GCV","GCW","GCX","GE1","GFG","GFP","GIV","GL0","GL2","GL5","GL6","GL7","GL9","GLA","GLB","GLC","GLD","GLF","GLG","GLO","GLP","GLS","GLT","GLW","GMH","GN1","GNX","GP1","GP4","GPH","GPM","GQ1","GQ2","GQ4","GS1","GS4","GSA","GSD","GTE","GTH","GTK","GTR","GTZ","GU0","GU1","GU2","GU3","GU4","GU5","GU6","GU8","GU9","GUF","GUP","GUZ","GYP","GYV","H2P","HDL","HMS","HS2","HSD","HSG","HSH","HSJ","HSQ","HSR","HSU","HSX","HSY","HSZ","IAB","IDG","IDR","IDS","IDT","IDU","IDX","IDY","IMK","IN1","IPT","ISL","KBG","KD2","KDA","KDM","KDO","KFN","KO1","KO2","KTU","L6S","LAG","LAI","LAK","LAO","LAT","LB2","LBT","LCN","LDY","LGC","LGU","LM2","LMT","LMU","LOG","LOX","LPK","LSM","LTM","LVZ","LXB","LXZ","M1F","M3M","M6P","M8C","MA1","MA2","MA3","MAB","MAG","MAL","MAN","MAT","MAV","MAW","MBG","MCU","MDA","MDM","MDP","MFA","MFB","MFU","MG5","MGA","MGL","MLB","MMA","MMN","MN0","MRP","MTT","MUG","MVP","MXY","N1L","N9S","NAA","NAG","NBG","NDG","NED","NG1","NG6","NGA","NGB","NGC","NGE","NGF","NGL","NGS","NGY","NHF","NM6","NM9","NTF","NTO","NTP","NXD","NYT","OPG","OPM","ORP","OX2","P3M","P53","P6P","PA5","PNA","PNG","PNW","PRP","PSJ","PSV","PTQ","QDK","QPS","QV4","R1P","R1X","R2B","R5P","RAA","RAE","RAF","RAM","RAO","RAT","RB5","RBL","RCD","RDP","REL","RER","RF5","RG1","RGG","RHA","RIB","RIP","RNS","RNT","ROB","ROR","RPA","RST","RUB","RUU","RZM","S6P","S7P","SA0","SCR","SDD","SF6","SF9","SG4","SG5","SG6","SG7","SGA","SGC","SGD","SGN","SGS","SHB","SHG","SI3","SIO","SOE","SOL","SSG","SUC","SUP","SUS","T6P","T6T","TAG","TCB","TDG","TGK","TGY","TH1","TIA","TM5","TM6","TM9","TMR","TMX","TOA","TOC","TRE","TYV","UCD","UDC","VG1","X0X","X1X","X2F","X4S","X5S","X6X","XBP","XDN","XDP","XIF","XIM","XLF","XLS","XMM","XUL","XXR","XYP","XYS","YO5","Z3Q","Z6J","Z9M","ZDC","ZDM"],dn=["CA","C","N","O","O1","O2","OC1","OC2","OX1","OXT","OT1","OT2","H","H1","H2","H3","HA","HN","BB"],un=["P","OP1","OP2","HOP2","HOP3","O2'","O3'","O4'","O5'","C1'","C2'","C3'","C4'","C5'","H1'","H2'","H2''","HO2'","H3'","H4'","H5'","H5''","HO3'","HO5'","O2*","O3*","O4*","O5*","C1*","C2*","C3*","C4*","C5*"],mn={1:{trace:"CA",direction1:"C",direction2:["O","OC1","O1","OX1","OXT","OT1","OT2"],backboneStart:"N",backboneEnd:"C"},2:{trace:["C4'","C4*"],direction1:["C1'","C1*"],direction2:["C3'","C3*"],backboneStart:"P",backboneEnd:["O3'","O3*"]},3:{trace:["C3'","C3*"],direction1:["C2'","C2*"],direction2:["O4'","O4*"],backboneStart:"P",backboneEnd:["O3'","O3*"]},4:{trace:["CA","BB"],backboneStart:["CA","BB"],backboneEnd:["CA","BB"]},5:{trace:["C4'","C4*","P"],backboneStart:["C4'","C4*","P"],backboneEnd:["C4'","C4*","P"]},6:{trace:["C3'","C3*","C2'","P"],backboneStart:["C3'","C3*","C2'","P"],backboneEnd:["C3'","C3*","C2'","P"]}};mn[Ns]={};const pn={HD:"H",HS:"H",A:"C",NA:"N",NS:"N",OA:"O",OS:"O",SA:"S",G0:"C",G1:"C",G2:"C",G3:"C",CG0:"C",CG1:"C",CG2:"C",CG3:"C",W:"O"};function fn(t){switch(t){case 0:return 0;case 1:return 1;case 2:return 2;case 3:return 3;case 4:return 4;default:return 8}}const gn=new Map([[2,kt(180)],[3,kt(120)],[4,kt(109.4721)],[6,kt(90)]]);function yn(t,i){let r=[];const s=new e,n=new e;return s.subVectors(i,t),t.eachBondedAtom((e=>{1!==e.number&&(n.subVectors(e,t),r.push(s.angleTo(n)))})),r}function bn(t,i){const r=t.clone(),s=new e;s.subVectors(i,t);const n=[new e,new e];let o=0;if(t.eachBondedAtom((e=>{o>1||1!==e.number&&(r.index=e.index,n[o++].subVectors(e,t))})),1===o&&r.eachBondedAtom((e=>{o>1||1!==e.number&&e.index!==t.index&&n[o++].subVectors(e,t)})),2!==o)return;const a=n[0].cross(n[1]);return Math.abs(Math.PI/2-a.angleTo(s))}function xn(t,e){const i=t.structure,r=i.atomCount,s=new Int8Array(r),n=new Int8Array(r),o=new Int8Array(r),a=new Int8Array(r);return i.eachAtom((t=>{const i=t.index,[r,c,l,h]=function(t,e){const i=t.bondToElementCount(1);let r=t.formalCharge||0;const s="always"===e.assignCharge||"auto"===e.assignCharge&&0===r,n="always"===e.assignH||"auto"===e.assignH&&0===i,o=t.bondCount,a=function(t){let e=0;return t.eachBond((t=>e+=t.bondOrder)),e}(t),c=function(t){const e=t.structure.getBondProxy(),i=t.number,r=8===i||7===i;if(r&&4===t.bondCount)return!1;let s=!1;return t.eachBond((i=>{if(i.bondOrder>1)s=!0;else if(r){const r=i.getOtherAtom(t);r.eachBond((t=>{if(t.bondOrder>1){const e=r.number;if((15===e||16===e)&&8===t.getOtherAtom(r).number)return;s=!0}}),e)}})),s}(t),l=a-o>0;let h=0,d=8;switch(t.number){case 1:s&&(0===o?(r=1,d=0):1===o&&(r=0,d=1));break;case 6:s&&(r=0),n&&(h=Math.max(0,4-a-Math.abs(r))),d=fn(o+h+Math.max(0,-r));break;case 7:if(s)if(n)if(c&&a<4)r=o-i==1&&a-i==2?1:0;else{let e=!1;t.eachBondedAtom((t=>{(16===t.number||t.isMetal())&&(e=!0)})),r=e?0:1}else r=a-3;n&&(h=Math.max(0,3-a+r)),d=fn(c&&!l?o+h-r:o+h+1-r);break;case 8:s&&(n||(r=a-2),1===a&&t.eachBondedAtom((e=>{e.eachBond((i=>{const s=i.getOtherAtom(e);s.index!==t.index&&8===s.number&&2===i.bondOrder&&(r=-1)}))}))),n&&(h=Math.max(0,2-a+r)),d=fn(c&&!l?o+h-r+1:o+h-r+2);break;case 16:s&&(n||(r=a<=3&&!t.bondToElementCount(8)?a-2:0)),n&&a<2&&(h=Math.max(0,2-a+r)),a<=3&&(d=fn(o+h-r+2));break;case 9:case 17:case 35:case 53:case 85:s&&(r=a-1);break;case 3:case 11:case 19:case 37:case 55:case 87:s&&(r=1-a);break;case 4:case 12:case 20:case 38:case 56:case 88:s&&(r=2-a);break;default:console.warn("Requested charge, protonation for an unhandled element",t.element)}return[r,h,h+i,d]}(t,e);s[i]=r,n[i]=c,o[i]=l,a[i]=h})),{charge:s,implicitH:n,totalH:o,idealGeometry:a}}function vn(t){if(t["@valenceModel"])return t["@valenceModel"];const e=xn(t,{assignCharge:"auto",assignH:"auto"});return t["@valenceModel"]=e,e}function wn(t){return 15===t.number&&t.bondToElementCount(8)===t.bondCount}const An=["ARG","HIS","LYS"],_n=["GLU","ASP"];function Sn(t,e){return 2===t&&1===e||1===t&&2===e}function Cn(t,e){return 3===t&&3===e}function Pn(t,e){return 3===t&&1===e||1===t&&3===e}function In(t){return"HIS"===t.resname&&7==t.number&&t.isRing()}function kn(t,e){return 5===t&&4===e||4===t&&5===e}function Mn(t,e){return 9===t&&5===e||5===t&&9===e}const Tn=[3,11,19,37,55,12,20,38,56,13,31,49,81,21,50,82,83,51,80];function Bn(t,e){return 12===t?11===e||12===e:13===t?10===e:void 0}const Dn=[17,35,53,85];const $n=[7,8,16],On=[6,7,15,16];const Rn=kt(180),En=kt(120);function Fn(t,e,i){return!Nn(t,e,i)&&(t.modelIndex!==e.modelIndex||t.altloc&&e.altloc&&t.altloc!==e.altloc)}const Ln={maxHydrophobicDist:4,maxHbondDist:3.5,maxHbondSulfurDist:4.1,maxHbondAccAngle:45,maxHbondDonAngle:45,maxHbondAccPlaneAngle:90,maxHbondDonPlaneAngle:30,maxPiStackingDist:5.5,maxPiStackingOffset:2,maxPiStackingAngle:30,maxCationPiDist:6,maxCationPiOffset:2,maxIonicDist:5,maxHalogenBondDist:4,maxHalogenBondAngle:30,maxMetalDist:3,refineSaltBridges:!0,masterModelIndex:-1,lineOfSightDistFactor:1};function Nn(t,e,i){return t.modelIndex===i&&e.modelIndex!==i||e.modelIndex===i&&t.modelIndex!==i}function zn(t,e,i){return!Nn(t,e,i)&&(t.modelIndex!==e.modelIndex||t.residueIndex===e.residueIndex||t.altloc&&e.altloc&&t.altloc!==e.altloc)}function Vn(t){const e={types:[],groups:[],centers:{x:[],y:[],z:[]},atomSets:[]};return De&&Me.time("calculateFeatures"),function(t,e){const{charge:i}=vn(t.data),r={};t.eachResidue((t=>{if(An.includes(t.resname)){const i=Es(1);t.eachAtom((t=>{7===t.number&&t.isSidechain()&&Fs(i,t)})),Ls(e,i)}else rn.includes(t.resname)||t.isNucleic()||(t.eachAtom((t=>{let i=!1;const s=Es(1);!function(t){let e=0;return 6===t.number&&3===t.bondCount&&3===t.bondToElementCount(7)&&t.eachBondedAtom((t=>{t.bondCount-t.bondToElementCount(1)==1&&++e})),2===e}(t)?function(t){let e=0;return 6===t.number&&3===t.bondCount&&2===t.bondToElementCount(7)&&1===t.bondToElementCount(6)&&t.eachBondedAtom((t=>{t.bondCount-t.bondToElementCount(1)==1&&++e})),2===e}(t)&&(s.group=9,i=!0):(s.group=8,i=!0),i&&(t.eachBondedAtom((t=>{7===t.number&&(r[t.index]=!0,Fs(s,t))})),Ls(e,s))})),t.eachAtom((t=>{const s=Es(1);i[t.index]>0&&(r[t.index]||(Fs(s,t),Ls(e,s)))})))}))}(t,e),function(t,e){const{charge:i}=vn(t.data),r={};t.eachResidue((t=>{if(_n.includes(t.resname)){const i=Es(2);t.eachAtom((t=>{8===t.number&&t.isSidechain()&&Fs(i,t)})),Ls(e,i)}else if(an.includes(t.resname)){const i=Es(2);t.eachAtom((t=>{wn(t)&&(i.group=6,t.eachBondedAtom((t=>{8===t.number&&Fs(i,t)})),Ls(e,i))}))}else rn.includes(t.resname)||an.includes(t.resname)||(t.eachAtom((t=>{let i=!1;const s=Es(2);!function(t){return 16===t.number&&3===t.bondToElementCount(8)}(t)?wn(t)?(s.group=6,i=!0):function(t){return 16===t.number&&4===t.bondToElementCount(8)}(t)?(s.group=5,i=!0):function(t){let e=0;return 6===t.number&&2===t.bondToElementCount(8)&&1===t.bondToElementCount(6)&&t.eachBondedAtom((t=>{8===t.number&&t.bondCount-t.bondToElementCount(1)==1&&++e})),2===e}(t)&&(s.group=10,i=!0):(s.group=4,i=!0),i&&(t.eachBondedAtom((t=>{8===t.number&&(r[t.index]=!0,Fs(s,t))})),Ls(e,s))})),t.eachAtom((t=>{const s=Es(2);i[t.index]<0&&(r[t.index]||(Fs(s,t),Ls(e,s)))})))}))}(t,e),function(t,e){const i=t.getAtomProxy();t.eachResidue((t=>{const r=t.getAromaticRings();if(r){const s=t.atomOffset;r.forEach((t=>{const r=Es(3);t.forEach((t=>{i.index=t+s,Fs(r,i)})),Ls(e,r)}))}}))}(t,e),function(t,e){const{charge:i,implicitH:r,idealGeometry:s}=vn(t.data);t.eachAtom((t=>{const n=Es(5),o=t.number;if(8===o)Fs(n,t),Ls(e,n);else if(7===o){if(In(t))Fs(n,t),Ls(e,n);else if(i[t.index]<1){const i=t.bondCount+r[t.index],o=s[t.index];(4===o&&i<4||3===o&&i<3||2===o&&i<2)&&(Fs(n,t),Ls(e,n))}}else 16===o&&("CYS"!==t.resname&&"MET"!==t.resname&&-1!==t.formalCharge||(Fs(n,t),Ls(e,n)))}))}(t,e),function(t,e){const{totalH:i}=vn(t.data);t.eachAtom((t=>{const r=Es(4),s=t.number;(In(t)||i[t.index]>0&&(7===s||8===s||16===s))&&(Fs(r,t),Ls(e,r))}))}(t,e),function(t,e){const{totalH:i}=vn(t.data);t.eachAtom((t=>{if(6===t.number&&i[t.index]>0&&(t.bondToElementCount(7)>0||t.bondToElementCount(8)>0||function(t){if(!t.isAromatic())return!1;const e=t.residueType.getRings();if(!e)return!1;let i=!1;return e.rings.forEach((e=>{i||e.some((e=>t.index-t.residueAtomOffset===e))&&(i=e.some((e=>{const i=t.residueType.atomTypeIdList[e],r=t.atomMap.get(i).number;return 7===r||8===r})))})),i}(t))){const i=Es(9);Fs(i,t),Ls(e,i)}}))}(t,e),function(t,e){t.eachAtom((t=>{let i=!1,r=!1;const s=rn.includes(t.resname),n=an.includes(t.resname);if(s||n?s?8===t.number?(["ASP","GLU","SER","THR","TYR","ASN","GLN"].includes(t.resname)&&t.isSidechain()||t.isBackbone())&&(i=!0,r=!0):16===t.number&&"CYS"===t.resname?(i=!0,r=!0):7===t.number&&"HIS"===t.resname&&t.isSidechain()&&(i=!0):n&&(8===t.number&&t.isBackbone()?(i=!0,r=!0):["N3","N4","N7"].includes(t.atomname)?i=!0:["O2","O4","O6"].includes(t.atomname)&&(i=!0,r=!0)):t.isHalogen()||8===t.number||16===t.number?(i=!0,r=!0):7===t.number&&(i=!0),i){const i=Es(11);Fs(i,t),Ls(e,i)}if(r){const i=Es(10);Fs(i,t),Ls(e,i)}}))}(t,e),function(t,e){t.eachAtom((t=>{if(t.isTransitionMetal()||30===t.number||48===t.number){const i=Es(12);Fs(i,t),Ls(e,i)}else if(Tn.includes(t.number)){const i=Es(13);Fs(i,t),Ls(e,i)}}))}(t,e),function(t,e){t.eachAtom((t=>{const i=Es(8);let r=!1;6===t.number?(r=!0,t.eachBondedAtom((t=>{const e=t.number;6!==e&&1!==e&&(r=!1)}))):9===t.number&&(r=!0),r&&(Fs(i,t),Ls(e,i))}))}(t,e),function(t,e){t.eachAtom((t=>{if($n.includes(t.number)){let i=!1;if(t.eachBondedAtom((t=>{On.includes(t.number)&&(i=!0)})),i){const i=Es(7);Fs(i,t),Ls(e,i)}}}))}(t,e),function(t,e){t.eachAtom((t=>{if(Dn.includes(t.number)&&1===t.bondToElementCount(6)){const i=Es(6);Fs(i,t),Ls(e,i)}}))}(t,e),De&&Me.timeEnd("calculateFeatures"),e}function Gn(t,i=Ln){const r=function(t){const{types:e,centers:i}=t;return{features:t,spatialHash:new Ts(i),contactStore:new Ds,featureSet:new Os(e.length,!1)}}(Vn(t));De&&Me.time("calculateContacts"),function(t,i,r={}){const s=st(r.maxIonicDist,Ln.maxIonicDist),n=st(r.maxPiStackingDist,Ln.maxPiStackingDist),o=st(r.maxPiStackingOffset,Ln.maxPiStackingOffset),a=st(r.maxPiStackingAngle,Ln.maxPiStackingAngle),c=st(r.maxCationPiDist,Ln.maxCationPiDist),l=st(r.maxCationPiOffset,Ln.maxCationPiOffset),h=st(r.masterModelIndex,Ln.masterModelIndex),d=Math.max(s+2,n,c),u=n*n,m=c*c,{features:p,spatialHash:f,contactStore:g,featureSet:y}=i,{types:b,centers:x,atomSets:v}=p,{x:w,y:A,z:_}=x,S=b.length,C=t.atomStore.x,P=t.atomStore.y,I=t.atomStore.z,k=t.getAtomProxy(),M=t.getAtomProxy(),T=function(t,e,i){const r=t.length,s=e.length;for(let n=0;n<r;++n){k.index=t[n];for(let t=0;t<s;++t)if(M.index=e[t],k.distanceTo(M)<=i)return!0}return!1},B=new e,D=new e,$=new e,O=new e,R=new e,E=new e,F=new e,L=function(t,e){B.set(C[t[0]],P[t[0]],I[t[0]]),D.set(C[t[1]],P[t[1]],I[t[1]]),$.set(C[t[2]],P[t[2]],I[t[2]]),O.subVectors(B,D),R.subVectors(B,$),e.crossVectors(O,R)},N=function(t,e,i){return B.set(w[t],A[t],_[t]),D.set(w[e],A[e],_[e]),B.sub(D).projectOnPlane(i).add(D).distanceTo(D)},z=function(t,e,i){y.setBits(t,e),g.addContact(t,e,i)};for(let t=0;t<S;++t)f.eachWithin(w[t],A[t],_[t],d,((e,i)=>{if(e<=t)return;if(k.index=v[t][0],M.index=v[e][0],zn(k,M,h))return;const r=b[t],n=b[e];if(Sn(r,n))T(v[t],v[e],s)&&z(t,e,1);else if(Cn(r,n)){if(i<=u){L(v[t],E),L(v[e],F);const i=57.29578*E.angleTo(F);Math.min(N(t,e,F),N(e,t,E))<=o&&(i<=a||i>=180-a||i<=a+90&&i>=90-a)&&z(t,e,3)}}else if(Pn(r,n)&&i<=m){const[i,s]=3===r?[t,e]:[e,t];L(v[i],E),N(s,i,E)<=l&&z(i,s,2)}}))}(t,r,i),function(t,e,i={}){const r=st(i.maxHbondDist,Ln.maxHbondDist),s=st(i.maxHbondSulfurDist,Ln.maxHbondSulfurDist),n=kt(st(i.maxHbondAccAngle,Ln.maxHbondAccAngle)),o=kt(st(i.maxHbondDonAngle,Ln.maxHbondDonAngle)),a=kt(st(i.maxHbondAccPlaneAngle,Ln.maxHbondAccPlaneAngle)),c=kt(st(i.maxHbondDonPlaneAngle,Ln.maxHbondDonPlaneAngle)),l=st(i.masterModelIndex,Ln.masterModelIndex),h=Math.max(r,s),d=r*r,{features:u,spatialHash:m,contactStore:p,featureSet:f}=e,{types:g,centers:y,atomSets:b}=u,{x:x,y:v,z:w}=y,A=g.length,{idealGeometry:_}=vn(t.data),S=t.getAtomProxy(),C=t.getAtomProxy();for(let t=0;t<A;++t)m.eachWithin(x[t],v[t],w[t],h,((e,i)=>{if(e<=t)return;const r=g[t],s=g[e],h=Mn(r,s);if(!h&&!kn(r,s))return;const[u,m]=5===s?[t,e]:[e,t];if(S.index=b[u][0],C.index=b[m][0],C.index===S.index)return;if(zn(S,C,l))return;if(16!==S.number&&16!==C.number&&i>d)return;if(S.connectedTo(C))return;const y=yn(S,C),x=gn.get(_[S.index])||kt(120);if(y.some((t=>Math.abs(x-t)>o)))return;if(3===_[S.index]){const t=bn(S,C);if(void 0!==t&&t>c)return}const v=yn(C,S),w=gn.get(_[C.index])||kt(120);if(v.some((t=>w-t>n)))return;if(3===_[C.index]){const t=bn(C,S);if(void 0!==t&&t>a)return}f.setBits(u,m);const A=h?8:function(t,e){return t.isWater()&&e.isWater()}(P=S,I=C)?9:function(t,e){return t.isBackbone()&&e.isBackbone()}(P,I)?10:4;var P,I;p.addContact(u,m,A)}))}(t,r,i),function(t,e,i={}){const r=st(i.maxMetalDist,Ln.maxMetalDist),s=st(i.masterModelIndex,Ln.masterModelIndex),{features:n,spatialHash:o,contactStore:a,featureSet:c}=e,{types:l,centers:h,atomSets:d}=n,{x:u,y:m,z:p}=h,f=l.length,g=t.getAtomProxy(),y=t.getAtomProxy();for(let t=0;t<f;++t)o.eachWithin(u[t],m[t],p[t],r,((e,i)=>{if(e<=t)return;if(g.index=d[t][0],y.index=d[e][0],zn(g,y,s))return;const r=g.isMetal(),n=y.isMetal();if(!r&&!n)return;const[o,h]=r?[l[t],l[e]]:[l[e],l[t]];Bn(o,h)&&(c.setBits(t,e),a.addContact(t,e,7))}))}(t,r,i),function(t,e,i={}){const r=st(i.maxHydrophobicDist,Ln.maxHydrophobicDist),s=st(i.masterModelIndex,Ln.masterModelIndex),{features:n,spatialHash:o,contactStore:a,featureSet:c}=e,{types:l,centers:h,atomSets:d}=n,{x:u,y:m,z:p}=h,f=l.length,g=t.getAtomProxy(),y=t.getAtomProxy();for(let t=0;t<f;++t)o.eachWithin(u[t],m[t],p[t],r,((e,i)=>{var r,n;e<=t||(g.index=d[t][0],y.index=d[e][0],zn(g,y,s)||9===g.number&&9===y.number||g.connectedTo(y)||(r=l[t],n=l[e],8===r&&8===n&&(c.setBits(t,e),a.addContact(t,e,6))))}))}(t,r,i),function(t,e,i={}){const r=st(i.maxHalogenBondDist,Ln.maxHalogenBondDist),s=kt(st(i.maxHalogenBondAngle,Ln.maxHalogenBondAngle)),n=st(i.masterModelIndex,Ln.masterModelIndex),{features:o,spatialHash:a,contactStore:c,featureSet:l}=e,{types:h,centers:d,atomSets:u}=o,{x:m,y:p,z:f}=d,g=h.length,y=t.getAtomProxy(),b=t.getAtomProxy();for(let t=0;t<g;++t)a.eachWithin(m[t],p[t],f[t],r,((e,i)=>{if(e<=t)return;if(y.index=u[t][0],b.index=u[e][0],zn(y,b,n))return;if(r=h[t],o=h[e],!(7===r&&6===o||6===r&&7===o))return;var r,o;const[a,d]=6===h[t]?[y,b]:[b,y],m=yn(a,d);if(1!==m.length)return;if(Rn-m[0]>s)return;const p=yn(d,a);0!==p.length&&(p.some((t=>En-t>s))||(l.setBits(t,e),c.addContact(t,e,5)))}))}(t,r,i);const s=function(t){const{index1:e,index2:i,count:r}=t.contactStore,s=Rs({nodeArray1:e,nodeArray2:i,edgeCount:r,nodeCount:t.featureSet.length}),n=new Os(t.contactStore.count,!0);return Object.assign({adjacencyList:s,contactSet:n},t)}(r);return function(t,i,r={}){De&&Me.time("refineLineOfSight");const s=st(r.lineOfSightDistFactor,Ln.lineOfSightDistFactor),n=st(r.masterModelIndex,Ln.masterModelIndex),o=t.spatialHash,{contactSet:a,contactStore:c,features:l}=i,{index1:h,index2:d}=c,{centers:u,atomSets:m}=l,{x:p,y:f,z:g}=u,y=t.getAtomProxy(),b=t.getAtomProxy(),x=t.getAtomProxy(),v=new e,w=new e,A=3*s,_=s*s;a.forEach((t=>{v.set(p[h[t]],f[h[t]],g[h[t]]),w.set(p[d[t]],f[d[t]],g[d[t]]);const e=(v.x+w.x)/2,i=(v.y+w.y)/2,r=(v.z+w.z)/2,s=m[h[t]],c=m[d[t]];y.index=s[0],b.index=c[0],o.eachWithin(e,i,r,A,((e,i)=>{x.index=e,1!==x.number&&x.vdw*x.vdw*_>i&&!Fn(y,x,n)&&!Fn(b,x,n)&&!s.includes(e)&&!c.includes(e)&&v.distanceToSquared(x)>1&&w.distanceToSquared(x)>1&&(a.clear(t),De&&Me.log("removing",y.qualifiedName(),b.qualifiedName(),"because",x.qualifiedName()))}))})),De&&Me.timeEnd("refineLineOfSight")}(t,s,i),function(t,e){const{contactSet:i,contactStore:r,features:s}=e,{type:n,index1:o,index2:a}=r,{atomSets:c}=s,l=t.getAtomProxy(),h=t.getAtomProxy(),d={},u=function(t,e,r){const[s,n]=d[r]||[1/0,-1];t<s?(-1!==n&&i.clear(n),d[r]=[t,e]):i.clear(e)};i.forEach((t=>{if(6!==n[t])return;l.index=c[o[t]][0],h.index=c[a[t]][0];const e=l.distanceTo(h);u(e,t,`${l.index}|${h.residueIndex}`),u(e,t,`${h.index}|${l.residueIndex}`)}))}(t,s),i.refineSaltBridges&&function(t,e){const{contactSet:i,contactStore:r,features:s}=e,{type:n,index1:o,index2:a}=r,{atomSets:c}=s,l={},h=function(t,e){l[t]||(l[t]=[]),l[t].push(e)};i.forEach((t=>{1===n[t]&&(c[o[t]].forEach((e=>h(e,t))),c[a[t]].forEach((e=>h(e,t))))})),i.forEach((t=>{if(!function(t){return 4===t||9===t||10===t}(n[t]))return;const e=l[c[o[t]][0]],r=l[c[a[t]][0]];if(!e||!r)return;const s=e.length;for(let n=0;n<s;++n)if(r.includes(e[n]))return void i.clear(t)}))}(0,s),function(t,e){const{contactSet:i,contactStore:r,features:s}=e,{type:n,index1:o,index2:a}=r,{atomSets:c}=s,l={},h=function(t,e){l[t]||(l[t]=[]),l[t].push(e)};i.forEach((t=>{3===n[t]&&(c[o[t]].forEach((e=>h(e,t))),c[a[t]].forEach((e=>h(e,t))))})),i.forEach((t=>{if(6!==n[t]&&2!==n[t])return;const e=l[c[o[t]][0]],r=l[c[a[t]][0]];if(!e||!r)return;const s=e.length;for(let n=0;n<s;++n)if(r.includes(e[n]))return void i.clear(t)}))}(0,s),function(t,e){const{contactSet:i,contactStore:r,features:s}=e,{type:n,index1:o,index2:a}=r,{atomSets:c}=s,l={},h=function(t,e){l[t]||(l[t]=[]),l[t].push(e)};i.forEach((t=>{1===n[t]&&(c[o[t]].forEach((e=>h(e,t))),c[a[t]].forEach((e=>h(e,t))))})),i.forEach((t=>{if(7!==n[t])return;const e=l[c[o[t]][0]],r=l[c[a[t]][0]];if(!e||!r)return;const s=e.length;for(let t=0;t<s;++t)if(r.includes(e[t]))return void i.clear(e[t])}))}(0,s),De&&Me.timeEnd("calculateContacts"),s}function Un(t){switch(t){case 4:case 9:case 10:return"hydrogen bond";case 6:return"hydrophobic contact";case 5:return"halogen bond";case 1:return"ionic interaction";case 7:return"metal coordination";case 2:return"cation-pi interaction";case 3:return"pi-pi stacking";case 8:return"weak hydrogen bond";default:return"unknown contact"}}const jn={hydrogenBond:!0,hydrophobic:!0,halogenBond:!0,ionicInteraction:!0,metalCoordination:!0,cationPi:!0,piStacking:!0,weakHydrogenBond:!0,waterHydrogenBond:!0,backboneHydrogenBond:!0,radius:1,filterSele:""},Hn=new s;function Wn(t,e,i){const r=nt(i,jn),s=[];r.hydrogenBond&&s.push(4),r.hydrophobic&&s.push(6),r.halogenBond&&s.push(5),r.ionicInteraction&&s.push(1),r.metalCoordination&&s.push(7),r.cationPi&&s.push(2),r.piStacking&&s.push(3),r.weakHydrogenBond&&s.push(8),r.waterHydrogenBond&&s.push(9),r.backboneHydrogenBond&&s.push(10);const{features:n,contactSet:o,contactStore:a}=t,{centers:c,atomSets:l}=n,{x:h,y:d,z:u}=c,{index1:m,index2:p,type:f}=a,g=[],y=[],b=[],x=[],v=[];let w;return r.filterSele&&(w=Array.isArray(r.filterSele)?r.filterSele.map((t=>e.getAtomSet(new pe(t)))):e.getAtomSet(new pe(r.filterSele))),o.forEach((t=>{const e=f[t];if(!s.includes(e))return;if(w){const e=l[m[t]][0],i=l[p[t]][0];if(Array.isArray(w)){if(!(w[0].isSet(e)&&w[1].isSet(i)||w[1].isSet(e)&&w[0].isSet(i)))return}else if(!w.isSet(e)&&!w.isSet(i))return}const i=m[t],n=p[t];g.push(h[i],d[i],u[i]),y.push(h[n],d[n],u[n]),b.push(...function(t){switch(t){case 4:case 9:case 10:return Hn.setHex(2851770).toArray();case 6:return Hn.setHex(8421504).toArray();case 5:return Hn.setHex(4259775).toArray();case 1:return Hn.setHex(15779860).toArray();case 7:return Hn.setHex(9191577).toArray();case 2:return Hn.setHex(16744448).toArray();case 3:return Hn.setHex(9220966).toArray();case 8:return Hn.setHex(12967404).toArray();default:return Hn.setHex(13421772).toArray()}}(e)),x.push(r.radius),v.push(t)})),{position1:new Float32Array(g),position2:new Float32Array(y),color:new Float32Array(b),color2:new Float32Array(b),radius:new Float32Array(x),picking:new Qn(v,t,e)}}class qn{constructor(t){this.array=t}get type(){return""}get data(){return{}}getIndex(t){return this.array?this.array[t]:t}getObject(t){return{}}_applyTransformations(t,e,i){return e&&t.applyMatrix4(e.matrix),i&&t.applyMatrix4(i.matrix),t}_getPosition(t){return new e}getPosition(t,e,i){return this._applyTransformations(this._getPosition(t),e,i)}}class Xn extends qn{constructor(t){super(),this.shape=t}get primitive(){}get data(){return this.shape}get type(){return this.primitive.type}getObject(t){return this.primitive.objectFromShape(this.shape,this.getIndex(t))}_getPosition(t){return this.primitive.positionFromShape(this.shape,this.getIndex(t))}}class Yn extends qn{constructor(t,e){super(t),this.structure=e}get type(){return"atom"}get data(){return this.structure}getObject(t){return this.structure.getAtomProxy(this.getIndex(t))}_getPosition(t){return(new e).copy(this.getObject(t))}}class Kn extends qn{constructor(t){super(),this.axes=t}get type(){return"axes"}get data(){return this.axes}getObject(){return{axes:this.axes}}_getPosition(){return this.axes.center.clone()}}class Zn extends qn{constructor(t,e,i){super(t),this.structure=e,this.bondStore=i||e.bondStore}get type(){return"bond"}get data(){return this.structure}getObject(t){const e=this.structure.getBondProxy(this.getIndex(t));return e.bondStore=this.bondStore,e}_getPosition(t){const i=this.getObject(t);return(new e).copy(i.atom1).add(i.atom2).multiplyScalar(.5)}}class Qn extends qn{constructor(t,e,i){super(t),this.contacts=e,this.structure=i}get type(){return"contact"}get data(){return this.contacts}getObject(t){const i=this.getIndex(t),{features:r,contactStore:s}=this.contacts,{centers:n,atomSets:o}=r,{x:a,y:c,z:l}=n,{index1:h,index2:d,type:u}=s,m=h[i],p=d[i];return{center1:new e(a[m],c[m],l[m]),center2:new e(a[p],c[p],l[p]),atom1:this.structure.getAtomProxy(o[m][0]),atom2:this.structure.getAtomProxy(o[p][0]),type:Un(u[i])}}_getPosition(t){const{center1:i,center2:r}=this.getObject(t);return(new e).addVectors(i,r).multiplyScalar(.5)}}class Jn extends qn{constructor(t,e,i){super(t),this.validation=e,this.structure=i}get type(){return"clash"}get data(){return this.validation}getObject(t){const e=this.validation,i=this.getIndex(t);return{validation:e,index:i,clash:e.clashArray[i]}}_getAtomProxyFromSele(t){const e=new pe(t),i=this.structure.getAtomIndices(e)[0];return this.structure.getAtomProxy(i)}_getPosition(t){const i=this.getObject(t).clash,r=this._getAtomProxyFromSele(i.sele1),s=this._getAtomProxyFromSele(i.sele2);return(new e).copy(r).add(s).multiplyScalar(.5)}}class to extends Zn{get type(){return"distance"}}class eo extends qn{get type(){return"ignore"}}class io extends Xn{constructor(t,e){super(t),this.mesh=e}get type(){return"mesh"}getObject(){const t=this.mesh;return{shape:this.shape,name:t.name,serial:t.serial}}_getPosition(){return this.__position||(this.__position=Ur(this.mesh.position)),this.__position}}class ro extends qn{constructor(t,e){super(t),this.surface=e}get type(){return"surface"}get data(){return this.surface}getObject(t){return{surface:this.surface,index:this.getIndex(t)}}_getPosition(){return this.surface.center.clone()}}class so extends qn{constructor(t,e){super(),this.unitcell=t,this.structure=e}get type(){return"unitcell"}get data(){return this.unitcell}getObject(){return{unitcell:this.unitcell,structure:this.structure}}_getPosition(){return this.unitcell.getCenter(this.structure)}}class no extends qn{constructor(t,e){super(t),this.volume=e}get type(){return"volume"}get data(){return this.volume}getObject(t){const e=this.volume,i=this.getIndex(t);return{volume:e,index:i,value:e.data[i]}}_getPosition(t){const i=this.volume.position,r=this.getIndex(t);return new e(i[3*r],i[3*r+1],i[3*r+2])}}class oo extends no{get type(){return"slice"}}function ao(){return new Uint32Array([0,265,515,778,1030,1295,1541,1804,2060,2309,2575,2822,3082,3331,3593,3840,400,153,915,666,1430,1183,1941,1692,2460,2197,2975,2710,3482,3219,3993,3728,560,825,51,314,1590,1855,1077,1340,2620,2869,2111,2358,3642,3891,3129,3376,928,681,419,170,1958,1711,1445,1196,2988,2725,2479,2214,4010,3747,3497,3232,1120,1385,1635,1898,102,367,613,876,3180,3429,3695,3942,2154,2403,2665,2912,1520,1273,2035,1786,502,255,1013,764,3580,3317,4095,3830,2554,2291,3065,2800,1616,1881,1107,1370,598,863,85,348,3676,3925,3167,3414,2650,2899,2137,2384,1984,1737,1475,1226,966,719,453,204,4044,3781,3535,3270,3018,2755,2505,2240,2240,2505,2755,3018,3270,3535,3781,4044,204,453,719,966,1226,1475,1737,1984,2384,2137,2899,2650,3414,3167,3925,3676,348,85,863,598,1370,1107,1881,1616,2800,3065,2291,2554,3830,4095,3317,3580,764,1013,255,502,1786,2035,1273,1520,2912,2665,2403,2154,3942,3695,3429,3180,876,613,367,102,1898,1635,1385,1120,3232,3497,3747,4010,2214,2479,2725,2988,1196,1445,1711,1958,170,419,681,928,3376,3129,3891,3642,2358,2111,2869,2620,1340,1077,1855,1590,314,51,825,560,3728,3993,3219,3482,2710,2975,2197,2460,1692,1941,1183,1430,666,915,153,400,3840,3593,3331,3082,2822,2575,2309,2060,1804,1541,1295,1030,778,515,265,0])}function co(){return new Int32Array([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,8,3,9,8,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,2,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,3,1,2,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,2,10,0,2,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,8,3,2,10,8,10,9,8,-1,-1,-1,-1,-1,-1,-1,3,11,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,11,2,8,11,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,9,0,2,3,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,11,2,1,9,11,9,8,11,-1,-1,-1,-1,-1,-1,-1,3,10,1,11,10,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,10,1,0,8,10,8,11,10,-1,-1,-1,-1,-1,-1,-1,3,9,0,3,11,9,11,10,9,-1,-1,-1,-1,-1,-1,-1,9,8,10,10,8,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,7,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,3,0,7,3,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,9,8,4,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,1,9,4,7,1,7,3,1,-1,-1,-1,-1,-1,-1,-1,1,2,10,8,4,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,4,7,3,0,4,1,2,10,-1,-1,-1,-1,-1,-1,-1,9,2,10,9,0,2,8,4,7,-1,-1,-1,-1,-1,-1,-1,2,10,9,2,9,7,2,7,3,7,9,4,-1,-1,-1,-1,8,4,7,3,11,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,4,7,11,2,4,2,0,4,-1,-1,-1,-1,-1,-1,-1,9,0,1,8,4,7,2,3,11,-1,-1,-1,-1,-1,-1,-1,4,7,11,9,4,11,9,11,2,9,2,1,-1,-1,-1,-1,3,10,1,3,11,10,7,8,4,-1,-1,-1,-1,-1,-1,-1,1,11,10,1,4,11,1,0,4,7,11,4,-1,-1,-1,-1,4,7,8,9,0,11,9,11,10,11,0,3,-1,-1,-1,-1,4,7,11,4,11,9,9,11,10,-1,-1,-1,-1,-1,-1,-1,9,5,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,5,4,0,8,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,5,4,1,5,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,5,4,8,3,5,3,1,5,-1,-1,-1,-1,-1,-1,-1,1,2,10,9,5,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,0,8,1,2,10,4,9,5,-1,-1,-1,-1,-1,-1,-1,5,2,10,5,4,2,4,0,2,-1,-1,-1,-1,-1,-1,-1,2,10,5,3,2,5,3,5,4,3,4,8,-1,-1,-1,-1,9,5,4,2,3,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,11,2,0,8,11,4,9,5,-1,-1,-1,-1,-1,-1,-1,0,5,4,0,1,5,2,3,11,-1,-1,-1,-1,-1,-1,-1,2,1,5,2,5,8,2,8,11,4,8,5,-1,-1,-1,-1,10,3,11,10,1,3,9,5,4,-1,-1,-1,-1,-1,-1,-1,4,9,5,0,8,1,8,10,1,8,11,10,-1,-1,-1,-1,5,4,0,5,0,11,5,11,10,11,0,3,-1,-1,-1,-1,5,4,8,5,8,10,10,8,11,-1,-1,-1,-1,-1,-1,-1,9,7,8,5,7,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,3,0,9,5,3,5,7,3,-1,-1,-1,-1,-1,-1,-1,0,7,8,0,1,7,1,5,7,-1,-1,-1,-1,-1,-1,-1,1,5,3,3,5,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,7,8,9,5,7,10,1,2,-1,-1,-1,-1,-1,-1,-1,10,1,2,9,5,0,5,3,0,5,7,3,-1,-1,-1,-1,8,0,2,8,2,5,8,5,7,10,5,2,-1,-1,-1,-1,2,10,5,2,5,3,3,5,7,-1,-1,-1,-1,-1,-1,-1,7,9,5,7,8,9,3,11,2,-1,-1,-1,-1,-1,-1,-1,9,5,7,9,7,2,9,2,0,2,7,11,-1,-1,-1,-1,2,3,11,0,1,8,1,7,8,1,5,7,-1,-1,-1,-1,11,2,1,11,1,7,7,1,5,-1,-1,-1,-1,-1,-1,-1,9,5,8,8,5,7,10,1,3,10,3,11,-1,-1,-1,-1,5,7,0,5,0,9,7,11,0,1,0,10,11,10,0,-1,11,10,0,11,0,3,10,5,0,8,0,7,5,7,0,-1,11,10,5,7,11,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,6,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,3,5,10,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,0,1,5,10,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,8,3,1,9,8,5,10,6,-1,-1,-1,-1,-1,-1,-1,1,6,5,2,6,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,6,5,1,2,6,3,0,8,-1,-1,-1,-1,-1,-1,-1,9,6,5,9,0,6,0,2,6,-1,-1,-1,-1,-1,-1,-1,5,9,8,5,8,2,5,2,6,3,2,8,-1,-1,-1,-1,2,3,11,10,6,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,0,8,11,2,0,10,6,5,-1,-1,-1,-1,-1,-1,-1,0,1,9,2,3,11,5,10,6,-1,-1,-1,-1,-1,-1,-1,5,10,6,1,9,2,9,11,2,9,8,11,-1,-1,-1,-1,6,3,11,6,5,3,5,1,3,-1,-1,-1,-1,-1,-1,-1,0,8,11,0,11,5,0,5,1,5,11,6,-1,-1,-1,-1,3,11,6,0,3,6,0,6,5,0,5,9,-1,-1,-1,-1,6,5,9,6,9,11,11,9,8,-1,-1,-1,-1,-1,-1,-1,5,10,6,4,7,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,3,0,4,7,3,6,5,10,-1,-1,-1,-1,-1,-1,-1,1,9,0,5,10,6,8,4,7,-1,-1,-1,-1,-1,-1,-1,10,6,5,1,9,7,1,7,3,7,9,4,-1,-1,-1,-1,6,1,2,6,5,1,4,7,8,-1,-1,-1,-1,-1,-1,-1,1,2,5,5,2,6,3,0,4,3,4,7,-1,-1,-1,-1,8,4,7,9,0,5,0,6,5,0,2,6,-1,-1,-1,-1,7,3,9,7,9,4,3,2,9,5,9,6,2,6,9,-1,3,11,2,7,8,4,10,6,5,-1,-1,-1,-1,-1,-1,-1,5,10,6,4,7,2,4,2,0,2,7,11,-1,-1,-1,-1,0,1,9,4,7,8,2,3,11,5,10,6,-1,-1,-1,-1,9,2,1,9,11,2,9,4,11,7,11,4,5,10,6,-1,8,4,7,3,11,5,3,5,1,5,11,6,-1,-1,-1,-1,5,1,11,5,11,6,1,0,11,7,11,4,0,4,11,-1,0,5,9,0,6,5,0,3,6,11,6,3,8,4,7,-1,6,5,9,6,9,11,4,7,9,7,11,9,-1,-1,-1,-1,10,4,9,6,4,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,10,6,4,9,10,0,8,3,-1,-1,-1,-1,-1,-1,-1,10,0,1,10,6,0,6,4,0,-1,-1,-1,-1,-1,-1,-1,8,3,1,8,1,6,8,6,4,6,1,10,-1,-1,-1,-1,1,4,9,1,2,4,2,6,4,-1,-1,-1,-1,-1,-1,-1,3,0,8,1,2,9,2,4,9,2,6,4,-1,-1,-1,-1,0,2,4,4,2,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,3,2,8,2,4,4,2,6,-1,-1,-1,-1,-1,-1,-1,10,4,9,10,6,4,11,2,3,-1,-1,-1,-1,-1,-1,-1,0,8,2,2,8,11,4,9,10,4,10,6,-1,-1,-1,-1,3,11,2,0,1,6,0,6,4,6,1,10,-1,-1,-1,-1,6,4,1,6,1,10,4,8,1,2,1,11,8,11,1,-1,9,6,4,9,3,6,9,1,3,11,6,3,-1,-1,-1,-1,8,11,1,8,1,0,11,6,1,9,1,4,6,4,1,-1,3,11,6,3,6,0,0,6,4,-1,-1,-1,-1,-1,-1,-1,6,4,8,11,6,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,10,6,7,8,10,8,9,10,-1,-1,-1,-1,-1,-1,-1,0,7,3,0,10,7,0,9,10,6,7,10,-1,-1,-1,-1,10,6,7,1,10,7,1,7,8,1,8,0,-1,-1,-1,-1,10,6,7,10,7,1,1,7,3,-1,-1,-1,-1,-1,-1,-1,1,2,6,1,6,8,1,8,9,8,6,7,-1,-1,-1,-1,2,6,9,2,9,1,6,7,9,0,9,3,7,3,9,-1,7,8,0,7,0,6,6,0,2,-1,-1,-1,-1,-1,-1,-1,7,3,2,6,7,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,3,11,10,6,8,10,8,9,8,6,7,-1,-1,-1,-1,2,0,7,2,7,11,0,9,7,6,7,10,9,10,7,-1,1,8,0,1,7,8,1,10,7,6,7,10,2,3,11,-1,11,2,1,11,1,7,10,6,1,6,7,1,-1,-1,-1,-1,8,9,6,8,6,7,9,1,6,11,6,3,1,3,6,-1,0,9,1,11,6,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,8,0,7,0,6,3,11,0,11,6,0,-1,-1,-1,-1,7,11,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,6,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,0,8,11,7,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,9,11,7,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,1,9,8,3,1,11,7,6,-1,-1,-1,-1,-1,-1,-1,10,1,2,6,11,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,2,10,3,0,8,6,11,7,-1,-1,-1,-1,-1,-1,-1,2,9,0,2,10,9,6,11,7,-1,-1,-1,-1,-1,-1,-1,6,11,7,2,10,3,10,8,3,10,9,8,-1,-1,-1,-1,7,2,3,6,2,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,7,0,8,7,6,0,6,2,0,-1,-1,-1,-1,-1,-1,-1,2,7,6,2,3,7,0,1,9,-1,-1,-1,-1,-1,-1,-1,1,6,2,1,8,6,1,9,8,8,7,6,-1,-1,-1,-1,10,7,6,10,1,7,1,3,7,-1,-1,-1,-1,-1,-1,-1,10,7,6,1,7,10,1,8,7,1,0,8,-1,-1,-1,-1,0,3,7,0,7,10,0,10,9,6,10,7,-1,-1,-1,-1,7,6,10,7,10,8,8,10,9,-1,-1,-1,-1,-1,-1,-1,6,8,4,11,8,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,6,11,3,0,6,0,4,6,-1,-1,-1,-1,-1,-1,-1,8,6,11,8,4,6,9,0,1,-1,-1,-1,-1,-1,-1,-1,9,4,6,9,6,3,9,3,1,11,3,6,-1,-1,-1,-1,6,8,4,6,11,8,2,10,1,-1,-1,-1,-1,-1,-1,-1,1,2,10,3,0,11,0,6,11,0,4,6,-1,-1,-1,-1,4,11,8,4,6,11,0,2,9,2,10,9,-1,-1,-1,-1,10,9,3,10,3,2,9,4,3,11,3,6,4,6,3,-1,8,2,3,8,4,2,4,6,2,-1,-1,-1,-1,-1,-1,-1,0,4,2,4,6,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,9,0,2,3,4,2,4,6,4,3,8,-1,-1,-1,-1,1,9,4,1,4,2,2,4,6,-1,-1,-1,-1,-1,-1,-1,8,1,3,8,6,1,8,4,6,6,10,1,-1,-1,-1,-1,10,1,0,10,0,6,6,0,4,-1,-1,-1,-1,-1,-1,-1,4,6,3,4,3,8,6,10,3,0,3,9,10,9,3,-1,10,9,4,6,10,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,9,5,7,6,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,3,4,9,5,11,7,6,-1,-1,-1,-1,-1,-1,-1,5,0,1,5,4,0,7,6,11,-1,-1,-1,-1,-1,-1,-1,11,7,6,8,3,4,3,5,4,3,1,5,-1,-1,-1,-1,9,5,4,10,1,2,7,6,11,-1,-1,-1,-1,-1,-1,-1,6,11,7,1,2,10,0,8,3,4,9,5,-1,-1,-1,-1,7,6,11,5,4,10,4,2,10,4,0,2,-1,-1,-1,-1,3,4,8,3,5,4,3,2,5,10,5,2,11,7,6,-1,7,2,3,7,6,2,5,4,9,-1,-1,-1,-1,-1,-1,-1,9,5,4,0,8,6,0,6,2,6,8,7,-1,-1,-1,-1,3,6,2,3,7,6,1,5,0,5,4,0,-1,-1,-1,-1,6,2,8,6,8,7,2,1,8,4,8,5,1,5,8,-1,9,5,4,10,1,6,1,7,6,1,3,7,-1,-1,-1,-1,1,6,10,1,7,6,1,0,7,8,7,0,9,5,4,-1,4,0,10,4,10,5,0,3,10,6,10,7,3,7,10,-1,7,6,10,7,10,8,5,4,10,4,8,10,-1,-1,-1,-1,6,9,5,6,11,9,11,8,9,-1,-1,-1,-1,-1,-1,-1,3,6,11,0,6,3,0,5,6,0,9,5,-1,-1,-1,-1,0,11,8,0,5,11,0,1,5,5,6,11,-1,-1,-1,-1,6,11,3,6,3,5,5,3,1,-1,-1,-1,-1,-1,-1,-1,1,2,10,9,5,11,9,11,8,11,5,6,-1,-1,-1,-1,0,11,3,0,6,11,0,9,6,5,6,9,1,2,10,-1,11,8,5,11,5,6,8,0,5,10,5,2,0,2,5,-1,6,11,3,6,3,5,2,10,3,10,5,3,-1,-1,-1,-1,5,8,9,5,2,8,5,6,2,3,8,2,-1,-1,-1,-1,9,5,6,9,6,0,0,6,2,-1,-1,-1,-1,-1,-1,-1,1,5,8,1,8,0,5,6,8,3,8,2,6,2,8,-1,1,5,6,2,1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,3,6,1,6,10,3,8,6,5,6,9,8,9,6,-1,10,1,0,10,0,6,9,5,0,5,6,0,-1,-1,-1,-1,0,3,8,5,6,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,5,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,5,10,7,5,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,5,10,11,7,5,8,3,0,-1,-1,-1,-1,-1,-1,-1,5,11,7,5,10,11,1,9,0,-1,-1,-1,-1,-1,-1,-1,10,7,5,10,11,7,9,8,1,8,3,1,-1,-1,-1,-1,11,1,2,11,7,1,7,5,1,-1,-1,-1,-1,-1,-1,-1,0,8,3,1,2,7,1,7,5,7,2,11,-1,-1,-1,-1,9,7,5,9,2,7,9,0,2,2,11,7,-1,-1,-1,-1,7,5,2,7,2,11,5,9,2,3,2,8,9,8,2,-1,2,5,10,2,3,5,3,7,5,-1,-1,-1,-1,-1,-1,-1,8,2,0,8,5,2,8,7,5,10,2,5,-1,-1,-1,-1,9,0,1,5,10,3,5,3,7,3,10,2,-1,-1,-1,-1,9,8,2,9,2,1,8,7,2,10,2,5,7,5,2,-1,1,3,5,3,7,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,8,7,0,7,1,1,7,5,-1,-1,-1,-1,-1,-1,-1,9,0,3,9,3,5,5,3,7,-1,-1,-1,-1,-1,-1,-1,9,8,7,5,9,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,8,4,5,10,8,10,11,8,-1,-1,-1,-1,-1,-1,-1,5,0,4,5,11,0,5,10,11,11,3,0,-1,-1,-1,-1,0,1,9,8,4,10,8,10,11,10,4,5,-1,-1,-1,-1,10,11,4,10,4,5,11,3,4,9,4,1,3,1,4,-1,2,5,1,2,8,5,2,11,8,4,5,8,-1,-1,-1,-1,0,4,11,0,11,3,4,5,11,2,11,1,5,1,11,-1,0,2,5,0,5,9,2,11,5,4,5,8,11,8,5,-1,9,4,5,2,11,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,5,10,3,5,2,3,4,5,3,8,4,-1,-1,-1,-1,5,10,2,5,2,4,4,2,0,-1,-1,-1,-1,-1,-1,-1,3,10,2,3,5,10,3,8,5,4,5,8,0,1,9,-1,5,10,2,5,2,4,1,9,2,9,4,2,-1,-1,-1,-1,8,4,5,8,5,3,3,5,1,-1,-1,-1,-1,-1,-1,-1,0,4,5,1,0,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,4,5,8,5,3,9,0,5,0,3,5,-1,-1,-1,-1,9,4,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,11,7,4,9,11,9,10,11,-1,-1,-1,-1,-1,-1,-1,0,8,3,4,9,7,9,11,7,9,10,11,-1,-1,-1,-1,1,10,11,1,11,4,1,4,0,7,4,11,-1,-1,-1,-1,3,1,4,3,4,8,1,10,4,7,4,11,10,11,4,-1,4,11,7,9,11,4,9,2,11,9,1,2,-1,-1,-1,-1,9,7,4,9,11,7,9,1,11,2,11,1,0,8,3,-1,11,7,4,11,4,2,2,4,0,-1,-1,-1,-1,-1,-1,-1,11,7,4,11,4,2,8,3,4,3,2,4,-1,-1,-1,-1,2,9,10,2,7,9,2,3,7,7,4,9,-1,-1,-1,-1,9,10,7,9,7,4,10,2,7,8,7,0,2,0,7,-1,3,7,10,3,10,2,7,4,10,1,10,0,4,0,10,-1,1,10,2,8,7,4,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,9,1,4,1,7,7,1,3,-1,-1,-1,-1,-1,-1,-1,4,9,1,4,1,7,0,8,1,8,7,1,-1,-1,-1,-1,4,0,3,7,4,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,4,8,7,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,10,8,10,11,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,0,9,3,9,11,11,9,10,-1,-1,-1,-1,-1,-1,-1,0,1,10,0,10,8,8,10,11,-1,-1,-1,-1,-1,-1,-1,3,1,10,11,3,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,2,11,1,11,9,9,11,8,-1,-1,-1,-1,-1,-1,-1,3,0,9,3,9,11,1,2,9,2,11,9,-1,-1,-1,-1,0,2,11,8,0,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,3,2,11,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,3,8,2,8,10,10,8,9,-1,-1,-1,-1,-1,-1,-1,9,10,2,0,9,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,3,8,2,8,10,0,1,8,1,10,8,-1,-1,-1,-1,1,10,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,3,8,9,1,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,9,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,3,8,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1])}function lo(t,e,i,r,s){var n,o,a,c,l,h,d,u=[[0,4,4,4,2,0,0,0,2,2,0,0],[4,0,4,4,0,8,0,0,0,8,8,0],[4,4,0,4,0,0,8,0,0,0,8,8],[4,4,4,0,0,0,0,1,1,0,0,1],[2,0,0,0,0,8,8,8,2,2,0,0],[0,8,0,0,8,0,8,8,0,8,8,0],[0,0,8,0,8,8,0,8,0,0,8,8],[0,0,0,1,8,8,8,0,1,0,0,1],[2,0,0,1,2,0,0,1,0,2,0,1],[2,8,0,0,2,8,0,0,2,0,8,0],[0,8,8,0,0,8,8,0,0,8,0,8],[0,0,8,1,0,0,8,1,1,0,8,0]],m=0,p=!1,f=!1,g=!1,y=!1,b=-1,x=e*i*r,v=e,w=e*i,A=new Int32Array(12),_=[],S=[],C=[],P=[],I=ao(),k=co();function M(t,e,i){return t+(e-t)*i}function T(t,s,n){return w*(n=(n+d)%r)+v*(s=(s+h)%i)+(t=(t+l)%e)}function B(t,e,i,r,c,l,h){var d=3*t;if(o[d]<0){var u=(m-l)/(h-l),f=n,g=3*a;if(_[g]=i+u,_[g+1]=r,_[g+2]=c,!p){var y=3*t;S[g]=b*M(f[y],f[y+3],u),S[g+1]=b*M(f[y+1],f[y+4],u),S[g+2]=b*M(f[y+2],f[y+5],u)}s&&(P[a]=s[t+Math.round(u)]),o[d]=a,A[e]=a,a+=1}else A[e]=o[d]}function D(t,e,i,r,c,l,h){var d=3*t+1;if(o[d]<0){var u=(m-l)/(h-l),f=n,g=3*a;if(_[g]=i,_[g+1]=r+u,_[g+2]=c,!p){var y=3*t,x=y+3*v;S[g]=b*M(f[y],f[x],u),S[g+1]=b*M(f[y+1],f[x+1],u),S[g+2]=b*M(f[y+2],f[x+2],u)}s&&(P[a]=s[t+Math.round(u)*v]),o[d]=a,A[e]=a,a+=1}else A[e]=o[d]}function $(t,e,i,r,c,l,h){var d=3*t+2;if(o[d]<0){var u=(m-l)/(h-l),f=n,g=3*a;if(_[g]=i,_[g+1]=r,_[g+2]=c+u,!p){var y=3*t,x=y+3*w;S[g]=b*M(f[y],f[x],u),S[g+1]=b*M(f[y+1],f[x+1],u),S[g+2]=b*M(f[y+2],f[x+2],u)}s&&(P[a]=s[t+Math.round(u)*w]),o[d]=a,A[e]=a,a+=1}else A[e]=o[d]}function O(e){var i=3*e;0===n[i]&&(n[i]=t[(e-1+x)%x]-t[(e+1)%x],n[i+1]=t[(e-v+x)%x]-t[(e+v)%x],n[i+2]=t[(e-w+x)%x]-t[(e+w)%x])}function R(e,i,r,s,n){var o,a,l,h,d,b,x;g?(s=T(e,i,r),o=T(e+1,i,r),a=T(e,i+1,r),l=T(e,i,r+1),h=T(e+1,i+1,r),d=T(e+1,i,r+1),b=T(e,i+1,r+1),x=T(e+1,i+1,r+1)):(o=s+1,h=(a=s+v)+1,d=(l=s+w)+1,x=(b=a+w)+1);var _=0,S=t[s],P=t[o],M=t[a],R=t[h],E=t[l],F=t[d],L=t[b],N=t[x];S<m&&(_|=1),P<m&&(_|=2),M<m&&(_|=8),R<m&&(_|=4),E<m&&(_|=16),F<m&&(_|=32),L<m&&(_|=128),N<m&&(_|=64);var z=I[_];if(0===z)return 0;var V=e+1,G=i+1,U=r+1;1&z&&(p||(O(s),O(o)),B(s,0,e,i,r,S,P)),2&z&&(p||(O(o),O(h)),D(o,1,V,i,r,P,R)),4&z&&(p||(O(a),O(h)),B(a,2,e,G,r,M,R)),8&z&&(p||(O(s),O(a)),D(s,3,e,i,r,S,M)),16&z&&(p||(O(l),O(d)),B(l,4,e,i,U,E,F)),32&z&&(p||(O(d),O(x)),D(d,5,V,i,U,F,N)),64&z&&(p||(O(b),O(x)),B(b,6,e,G,U,L,N)),128&z&&(p||(O(l),O(b)),D(l,7,e,i,U,E,L)),256&z&&(p||(O(s),O(l)),$(s,8,e,i,r,S,E)),512&z&&(p||(O(o),O(d)),$(o,9,V,i,r,P,F)),1024&z&&(p||(O(h),O(x)),$(h,10,V,G,r,R,N)),2048&z&&(p||(O(a),O(b)),$(a,11,e,G,r,M,L));for(var j,H,W,q=_<<4,X=0;-1!==k[q+X];)j=k[q+X],H=k[q+X+1],W=k[q+X+2],f?(u[j][H]&n&&(C[c++]=A[j],C[c++]=A[H]),u[H][W]&n&&(C[c++]=A[H],C[c++]=A[W]),u[j][W]&n&&(C[c++]=A[j],C[c++]=A[W])):(C[c++]=A[y?j:H],C[c++]=A[y?H:j],C[c++]=A[W]),X+=3}function E(s,n,a,c,l,h){let d,u,f,y,b,x,A,_,S,C,P,I,k;if(s=void 0!==s?s:0,n=void 0!==n?n:0,a=void 0!==a?a:0,c=void 0!==c?c:e-1,l=void 0!==l?l:i-1,h=void 0!==h?h:r-1,g||(p?(s=Math.max(0,s),n=Math.max(0,n),a=Math.max(0,a),c=Math.min(e-1,c),l=Math.min(i-1,l),h=Math.min(r-1,h)):(s=Math.max(1,s),n=Math.max(1,n),a=Math.max(1,a),c=Math.min(e-2,c),l=Math.min(i-2,l),h=Math.min(r-2,h))),g)for(_=s-2,S=n-2,C=a-2,P=c+2,I=l+2,k=h+2,b=C;b<k;++b)for(y=S;y<I;++y)for(f=_;f<P;++f)u=3*T(f,y,b),o[u]=-1,o[u+1]=-1,o[u+2]=-1;else for(_=Math.max(0,s-2),S=Math.max(0,n-2),C=Math.max(0,a-2),P=Math.min(e,c+2),I=Math.min(i,l+2),k=Math.min(r,h+2),b=C;b<k;++b)for(A=w*b,y=S;y<I;++y)for(x=A+v*y,f=_;f<P;++f)d=3*(x+f),o[d]=-1,o[d+1]=-1,o[d+2]=-1;if(!g){var M,B=s,D=n,$=a,O=c,E=l,F=h;for(M=!1,b=a;b<h;++b){for(y=n;y<l;++y){for(f=s;f<c;++f)if(d=e*i*b+e*y+f,t[d]>=m){$=b,M=!0;break}if(M)break}if(M)break}for(M=!1,y=n;y<l;++y){for(b=$;b<h;++b){for(f=s;f<c;++f)if(d=e*i*b+e*y+f,t[d]>=m){D=y,M=!0;break}if(M)break}if(M)break}for(M=!1,f=s;f<c;++f){for(y=D;y<l;++y){for(b=$;b<h;++b)if(d=e*i*b+e*y+f,t[d]>=m){B=f,M=!0;break}if(M)break}if(M)break}for(M=!1,b=h;b>=a;--b){for(y=l;y>=n;--y){for(f=c;f>=s;--f)if(d=e*i*b+e*y+f,t[d]>=m){F=b,M=!0;break}if(M)break}if(M)break}for(M=!1,y=l;y>=n;--y){for(b=F;b>=a;--b){for(f=c;f>=s;--f)if(d=e*i*b+e*y+f,t[d]>=m){E=y,M=!0;break}if(M)break}if(M)break}for(M=!1,f=c;f>=s;--f){for(y=E;y>=n;--y){for(b=F;b>=a;--b)if(d=e*i*b+e*y+f,t[d]>=m){O=f,M=!0;break}if(M)break}if(M)break}p?(s=Math.max(0,B-1),n=Math.max(0,D-1),a=Math.max(0,$-1),c=Math.min(e-1,O+1),l=Math.min(i-1,E+1),h=Math.min(r-1,F+1)):(s=Math.max(1,B-1),n=Math.max(1,D-1),a=Math.max(1,$-1),c=Math.min(e-2,O+1),l=Math.min(i-2,E+1),h=Math.min(r-2,F+1))}var L=15;for(b=a;b<h;++b,L&=-5)for(A=w*b,L|=2,y=n;y<l;++y,L&=-3)for(x=A+v*y,L|=1,f=s;f<c;++f,L&=-2)d=x+f,R(f,y,b,d,L)}this.triangulate=function(t,u,v,w,A){y=(m=t)<0,f=w,g=A,(p=u||f)||(b=m>0?-1:1,n||(n=new Float32Array(3*x)));var I=3*x;if(o&&o.length===I||(o=new Int32Array(I)),a=0,c=0,void 0!==v){var k=v[0].map(Math.round),M=v[1].map(Math.round);l=e*Math.ceil(Math.abs(k[0])/e),h=i*Math.ceil(Math.abs(k[1])/i),d=r*Math.ceil(Math.abs(k[2])/r),E(k[0],k[1],k[2],M[0],M[1],M[2])}else l=h=d=0,E();return _.length=3*a,p||(S.length=3*a),C.length=c,s&&(P.length=a),{position:new Float32Array(_),normal:p?void 0:new Float32Array(S),index:xt(C,_.length/3),atomindex:s?new Int32Array(P):void 0,contour:f}}}He.add("arrow",class extends Xn{get primitive(){return _s}}),He.add("box",class extends Xn{get primitive(){return xs}}),He.add("cone",class extends Xn{get primitive(){return Ss}}),He.add("cylinder",class extends Xn{get primitive(){return As}}),He.add("ellipsoid",class extends Xn{get primitive(){return Cs}}),He.add("octahedron",class extends Xn{get primitive(){return vs}}),He.add("sphere",class extends Xn{get primitive(){return bs}}),He.add("tetrahedron",class extends Xn{get primitive(){return ws}}),He.add("torus",class extends Xn{get primitive(){return Ps}}),He.add("point",class extends Xn{get primitive(){return ks}}),He.add("wideline",class extends Xn{get primitive(){return Ms}}),Object.assign(lo,{__deps:[ao,co,xt]});class ho{constructor(t,e){this.cols=t,this.rows=e,this.size=this.cols*this.rows,this.data=new Float32Array(this.size)}copyTo(t){t.data.set(this.data)}}function uo(t,e){let i=0,r=0;const s=e.rows,n=e.cols;let o=0,a=0,c=0;const l=e.data,h=t.data;for(;i<s;a+=1,o+=n,i++)for(c=a,r=0;r<n;c+=s,r++)h[c]=l[o+r]}function mo(t,e,i){let r=0,s=0,n=0,o=0,a=0,c=0,l=0;const h=e.cols,d=e.rows,u=i.rows,m=e.data,p=i.data,f=t.data;let g=0;for(;r<d;o+=h,r++)for(c=0,s=0;s<u;l++,s++){for(a=o,g=0,n=0;n<h;a++,c++,n++)g+=m[a]*p[c];f[l]=g}}function po(t,e,i){const r=t.data,s=e.data,n=i.data,o=s[0],a=s[1],c=s[2],l=s[3],h=s[4],d=s[5],u=s[6],m=s[7],p=s[8],f=n[0],g=n[1],y=n[2],b=n[3],x=n[4],v=n[5],w=n[6],A=n[7],_=n[8];r[0]=o*f+a*b+c*w,r[1]=o*g+a*x+c*A,r[2]=o*y+a*v+c*_,r[3]=l*f+h*b+d*w,r[4]=l*g+h*x+d*A,r[5]=l*y+h*v+d*_,r[6]=u*f+m*b+p*w,r[7]=u*g+m*x+p*A,r[8]=u*y+m*v+p*_}function fo(t){const e=t.rows,i=t.cols,r=t.data,s=new Array(i);for(let t=0;t<i;++t)s[t]=0;for(let t=0,n=0;t<e;++t)for(let t=0;t<i;++t,++n)s[t]+=r[n];for(let t=0;t<i;++t)s[t]/=e;return s}function go(t,e){const i=t.rows,r=t.cols,s=t.data;for(let t=0,n=0;t<i;++t)for(let t=0;t<r;++t,++n)s[n]-=e[t]}function yo(t,e,i,r){r=t[e],t[e]=t[i],t[i]=r}function bo(t,e){return(t=Math.abs(t))>(e=Math.abs(e))?(e/=t,t*Math.sqrt(1+e*e)):e>0?(t/=e,e*Math.sqrt(1+t*t)):0}const xo=1.192092896e-7,vo=1e-37;function wo(t,e,i,r){let s=0,n=0;const o=t.rows,a=t.cols;let c=o,l=a;c<l&&(s=1,n=c,c=l,l=n);const h=new ho(c,c),d=new ho(1,l),u=new ho(l,l);if(0===s)uo(h,t);else{for(n=0;n<a*o;n++)h.data[n]=t.data[n];for(;n<l*c;n++)h.data[n]=0}if(function(t,e,i,r,s,n,o,a){const c=2*xo,l=vo;let h=0,d=0,u=0,m=0;const p=Math.max(n,30);let f=0,g=0,y=0,b=0,x=0,v=0,w=0,A=0,_=0,S=0,C=0,P=0,I=0,k=0,M=0,T=0,B=0,D=4660,$=0,O=0,R=0;const E=new Float64Array(o<<3);for(;h<o;h++){for(u=0,C=0;u<n;u++)A=t[h*e+u],C+=A*A;if(E[h]=C,r){for(u=0;u<o;u++)r[h*s+u]=0;r[h*s+h]=1}}for(;m<p;m++){for(x=0,h=0;h<o-1;h++)for(d=h+1;d<o;d++){for(f=h*e|0,g=d*e|0,M=E[h],T=0,B=E[d],u=2,T+=t[f]*t[g],T+=t[f+1]*t[g+1];u<n;u++)T+=t[f+u]*t[g+u];if(!(Math.abs(T)<=c*Math.sqrt(M*B))){for(T*=2,P=M-B,I=bo(T,P),P<0?(k=.5*(I-P),w=Math.sqrt(k/I),v=T/(I*w*2)):(v=Math.sqrt((I+P)/(2*I)),w=T/(I*v*2)),M=0,B=0,u=2,_=v*t[f]+w*t[g],S=-w*t[f]+v*t[g],t[f]=_,t[g]=S,M+=_*_,B+=S*S,_=v*t[f+1]+w*t[g+1],S=-w*t[f+1]+v*t[g+1],t[f+1]=_,t[g+1]=S,M+=_*_,B+=S*S;u<n;u++)_=v*t[f+u]+w*t[g+u],S=-w*t[f+u]+v*t[g+u],t[f+u]=_,t[g+u]=S,M+=_*_,B+=S*S;if(E[h]=M,E[d]=B,x=1,r)for(y=h*s|0,b=d*s|0,u=2,_=v*r[y]+w*r[b],S=-w*r[y]+v*r[b],r[y]=_,r[b]=S,_=v*r[y+1]+w*r[b+1],S=-w*r[y+1]+v*r[b+1],r[y+1]=_,r[b+1]=S;u<o;u++)_=v*r[y+u]+w*r[b+u],S=-w*r[y+u]+v*r[b+u],r[y+u]=_,r[b+u]=S}}if(0===x)break}for(h=0;h<o;h++){for(u=0,C=0;u<n;u++)A=t[h*e+u],C+=A*A;E[h]=Math.sqrt(C)}for(h=0;h<o-1;h++){for(d=h,u=h+1;u<o;u++)E[d]<E[u]&&(d=u);if(h!==d&&(yo(E,h,d,C),r)){for(u=0;u<n;u++)yo(t,h*e+u,d*e+u,A);for(u=0;u<o;u++)yo(r,h*s+u,d*s+u,A)}}for(h=0;h<o;h++)i[h]=E[h];if(r)for(h=0;h<a;h++){for(C=h<o?E[h]:0;C<=l;){for(O=1/n,u=0;u<n;u++)D=214013*D+2531011,$=0!=(256&D>>16)?O:-O,t[h*e+u]=$;for(m=0;m<2;m++)for(d=0;d<h;d++){for(C=0,u=0;u<n;u++)C+=t[h*e+u]*t[d*e+u];for(R=0,u=0;u<n;u++)A=t[h*e+u]-C*t[d*e+u],t[h*e+u]=A,R+=Math.abs(A);for(R=R?1/R:0,u=0;u<n;u++)t[h*e+u]*=R}for(C=0,u=0;u<n;u++)A=t[h*e+u],C+=A*A;C=Math.sqrt(C)}for(w=1/C,u=0;u<n;u++)t[h*e+u]*=w}}(h.data,c,d.data,u.data,l,c,l,c),e){for(n=0;n<l;n++)e.data[n]=d.data[n];for(;n<a;n++)e.data[n]=0}0===s?(i&&uo(i,h),r&&uo(r,u)):(i&&uo(i,u),r&&uo(r,h))}function Ao(){return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}function _o(t,e,i,r,s,n,o,a,c,l,h,d,u,m,p,f,g){t[0]=e,t[4]=i,t[8]=r,t[12]=s,t[1]=n,t[5]=o,t[9]=a,t[13]=c,t[2]=l,t[6]=h,t[10]=d,t[14]=u,t[3]=m,t[7]=p,t[11]=f,t[15]=g}function So(t,e,i){const r=e[0],s=e[4],n=e[8],o=e[12],a=e[1],c=e[5],l=e[9],h=e[13],d=e[2],u=e[6],m=e[10],p=e[14],f=e[3],g=e[7],y=e[11],b=e[15],x=i[0],v=i[4],w=i[8],A=i[12],_=i[1],S=i[5],C=i[9],P=i[13],I=i[2],k=i[6],M=i[10],T=i[14],B=i[3],D=i[7],$=i[11],O=i[15];t[0]=r*x+s*_+n*I+o*B,t[4]=r*v+s*S+n*k+o*D,t[8]=r*w+s*C+n*M+o*$,t[12]=r*A+s*P+n*T+o*O,t[1]=a*x+c*_+l*I+h*B,t[5]=a*v+c*S+l*k+h*D,t[9]=a*w+c*C+l*M+h*$,t[13]=a*A+c*P+l*T+h*O,t[2]=d*x+u*_+m*I+p*B,t[6]=d*v+u*S+m*k+p*D,t[10]=d*w+u*C+m*M+p*$,t[14]=d*A+u*P+m*T+p*O,t[3]=f*x+g*_+y*I+b*B,t[7]=f*v+g*S+y*k+b*D,t[11]=f*w+g*C+y*M+b*$,t[15]=f*A+g*P+y*T+b*O}function Co(t,e,i,r){_o(t,e,0,0,0,0,i,0,0,0,0,r,0,0,0,0,1)}function Po(t,e,i,r){_o(t,1,0,0,e,0,1,0,i,0,0,1,r,0,0,0,1)}function Io(t,e){const i=Math.cos(e),r=Math.sin(e);_o(t,i,0,r,0,0,1,0,0,-r,0,i,0,0,0,0,1)}function ko(){return new Float32Array([1,0,0,0,1,0,0,0,1])}function Mo(t,e){const i=Yr([e[0],e[1],e[2]]),r=Yr([e[4],e[5],e[6]]),s=Yr([e[8],e[9],e[10]]),n=Yr();Kr(n,r,s),t[0]=n[0],t[1]=n[1],t[2]=n[2],Kr(n,s,i),t[3]=n[0],t[4]=n[1],t[5]=n[2],Kr(n,i,r),t[6]=n[0],t[7]=n[1],t[8]=n[2]}function To(t,e,i,r){i=i||1,r=r||!0;const s=t.length/3,n=e.length/3;let o;r&&(o=new Float32Array(3*s));const a=new Float32Array(3*s);let c;const l=new Array(20);for(c=0;c<20;++c)l[c]=new Uint32Array(s);for(c=0;c<s;++c)l[0][c]=0;let h,d,u;for(c=0;c<n;++c){var m=3*c,p=3*c+1,f=3*c+2;for(u=!0,h=0,d=l[0][e[m]];h<d;++h)if(e[p]===l[h+1][e[m]]){u=!1;break}for(u&&(l[0][e[m]]++,l[l[0][e[m]]][e[m]]=e[p]),u=!0,h=0,d=l[0][e[m]];h<d;++h)if(e[f]===l[h+1][e[m]]){u=!1;break}for(u&&(l[0][e[m]]++,l[l[0][e[m]]][e[m]]=e[f]),u=!0,h=0,d=l[0][e[p]];h<d;++h)if(e[m]===l[h+1][e[p]]){u=!1;break}for(u&&(l[0][e[p]]++,l[l[0][e[p]]][e[p]]=e[m]),u=!0,h=0,d=l[0][e[p]];h<d;++h)if(e[f]===l[h+1][e[p]]){u=!1;break}for(u&&(l[0][e[p]]++,l[l[0][e[p]]][e[p]]=e[f]),u=!0,h=0;h<l[0][e[f]];++h)if(e[m]===l[h+1][e[f]]){u=!1;break}for(u&&(l[0][e[f]]++,l[l[0][e[f]]][e[f]]=e[m]),u=!0,h=0,d=l[0][e[f]];h<d;++h)if(e[p]===l[h+1][e[f]]){u=!1;break}u&&(l[0][e[f]]++,l[l[0][e[f]]][e[f]]=e[p])}for(var g,y,b,x,v,w=.5,A=.75/4.5,_=0;_<i;++_){for(c=0;c<s;++c)if(g=3*c,(b=l[0][c])<3)a[g]=t[g],a[g+1]=t[g+1],a[g+2]=t[g+2];else if(3===b||4===b){for(a[g]=0,a[g+1]=0,a[g+2]=0,h=0;h<b;++h)y=3*l[h+1][c],a[g]+=t[y],a[g+1]+=t[y+1],a[g+2]+=t[y+2];a[g]+=w*t[g],a[g+1]+=w*t[g+1],a[g+2]+=w*t[g+2],v=w+b,a[g]/=v,a[g+1]/=v,a[g+2]/=v}else{for(a[g]=0,a[g+1]=0,a[g+2]=0,h=0;h<b;++h)y=3*l[h+1][c],a[g]+=t[y],a[g+1]+=t[y+1],a[g+2]+=t[y+2];a[g]+=1*t[g],a[g+1]+=1*t[g+1],a[g+2]+=1*t[g+2],x=1+b,a[g]/=x,a[g+1]/=x,a[g+2]/=x}if(t.set(a),r){Bo(t,e,o);var S=3*s;for(g=0;g<S;g+=3)t[g]+=-1*A*o[g],t[g+1]+=-1*A*o[g+1],t[g+2]+=-1*A*o[g+2]}}}function Bo(t,e,i){var r,s;if(void 0===i)i=new Float32Array(t.length);else for(r=0,s=i.length;r<s;r++)i[r]=0;var n=new Float32Array(3),o=new Float32Array(3),a=new Float32Array(3),c=new Float32Array(3),l=new Float32Array(3);if(e)for(r=0,s=e.length;r<s;r+=3){var h=3*e[r],d=3*e[r+1],u=3*e[r+2];ts(n,t,h),ts(o,t,d),ts(a,t,u),Qr(c,a,o),Qr(l,n,o),Kr(c,c,l),i[h]+=c[0],i[h+1]+=c[1],i[h+2]+=c[2],i[d]+=c[0],i[d+1]+=c[1],i[d+2]+=c[2],i[u]+=c[0],i[u+1]+=c[1],i[u+2]+=c[2]}else for(r=0,s=t.length;r<s;r+=9)ts(n,t,r),ts(o,t,r+3),ts(a,t,r+6),Qr(c,a,o),Qr(l,n,o),Kr(c,c,l),i[r]=c[0],i[r+1]=c[1],i[r+2]=c[2],i[r+3]=c[0],i[r+4]=c[1],i[r+5]=c[2],i[r+6]=c[0],i[r+7]=c[1],i[r+8]=c[2];return Xr(i),i}function Do(t){for(var e={},i=0,r=t.length;i<r;++i)e[t[i]]=!0;return e}function $o(t,e,i,r,s){var n=1/r*3;as(t,t,s+(n+=i)),cs(e,e,s+n),ns(t,t,r),ls(t,t),ss(t,t,r),ns(e,e,r),hs(e,e),ss(e,e,r);var o=new Float32Array(3);Qr(o,e,t),ns(o,o,r),hs(o,o),cs(o,o,1);var a=256*Math.pow(10,6),c=o[0]*o[1]*o[2]*3;a<=c&&(ns(t,t,r*=Math.pow(a/c,1/3)),ls(t,t),ss(t,t,r),ns(e,e,r),hs(e,e),ss(e,e,r),Qr(o,e,t),ns(o,o,r),hs(o,o),cs(o,o,1));var l=new Float32Array(t);ds(l,l);var h=Ao(),d=Ao();Io(d,kt(90)),So(h,h,d);var u=Ao();Co(u,-1/r,1/r,1/r),So(h,h,u);var m=Ao();return Po(m,-r*l[2],-r*l[1],-r*l[0]),So(h,h,m),{dim:o,tran:l,matrix:h,scaleFactor:r}}Co.__deps=[_o],Po.__deps=[_o],Io.__deps=[_o],Mo.__deps=[Yr,Kr],Object.assign(To,{__deps:[Bo]}),Object.assign(Bo,{__deps:[Qr,Kr,ts,Xr]}),Object.assign($o,{__deps:[kt,as,cs,ss,ns,ls,hs,Qr,ds,Ao,So,Po,Co,Io]});class Oo{constructor(t,i,r){this.name=t||"",this.path=i||"",this.info={},this.center=new e,this.boundingBox=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],r instanceof __WEBPACK_IMPORTED_MODULE_0_three__["s" /* Geometry */]||r instanceof __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]||r instanceof __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]?this.fromGeometry(r):r&&(this.set(r.position,r.index,r.normal,r.color,r.atomindex,r.contour),this.boundingBox.setFromArray(r.position),this.boundingBox.getCenter(this.center))}get type(){return"Surface"}set(t,e,i,r,s,n=!1){this.position=t,this.index=e,this.normal=i,this.color=r,this.atomindex=s,this.size=t.length/3,this.contour=n}fromGeometry(t){let e,i,r,s;if(De&&Me.time("GeometrySurface.fromGeometry"),t instanceof __WEBPACK_IMPORTED_MODULE_0_three__["s" /* Geometry */]?(t.computeVertexNormals(!0),e=(new __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]).fromGeometry(t)):e=t instanceof __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]?t:t[0],e.boundingBox||e.computeBoundingBox(),this.boundingBox.copy(e.boundingBox),this.boundingBox.getCenter(this.center),e instanceof __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]){const t=e.attributes,n=!!t.normal&&t.normal.array;(!n||0===n[0]&&0===n[1]&&0===n[2])&&e.computeVertexNormals(),i=t.position.array,r=t.index?t.index.array:null,s=t.normal.array}this.set(i,r,s,undefined,void 0),De&&Me.timeEnd("GeometrySurface.setGeometry")}getPosition(){return this.position}getColor(t){const i=t||{};i.surface=this;const r=this.size,n=new Float32Array(3*r),o=Fe.getScheme(i);if(o.volumeColor||"random"===i.scheme)for(let t=0;t<r;++t)o.volumeColorToArray(t,n,3*t);else if(o.positionColor){const t=new e,i=this.position;for(let e=0;e<r;++e){var a=3*e;t.set(i[a],i[a+1],i[a+2]),o.positionColorToArray(t,n,a)}}else if(o.atomColor&&this.atomindex){const t=i.structure.getAtomProxy(),e=this.atomindex;for(let i=0;i<r;++i)t.index=e[i],o.atomColorToArray(t,n,3*i)}else{const t=new s(i.value);Ci(r,t.r,t.g,t.b,n)}return n}getPicking(t){return this.atomindex&&t?new Yn(this.atomindex,t):new ro(Pi(this.size),this)}getNormal(){return this.normal}getSize(t,e){return Si(this.size,t*e)}getIndex(){return this.index}getFilteredIndex(t,e){if(t&&this.atomindex){const i=new pe(t),r=e.getAtomSet(i),s=[],n=this.atomindex,o=this.index,a=o.length,c=this.contour?2:3;let l=0;for(let t=0;t<a;t+=c){let e=!0;for(let i=0;i<c;i++){const s=n[o[t+i]];if(!r.get(s)){e=!1;break}}if(e)for(let e=0;e<c;e++,l++)s[l]=o[t+e]}return xt(s,this.position.length/3)}return this.index}getAtomindex(){return this.atomindex}dispose(){}}function Ro(t,e,i,r,s){var n=new lo(t,e,i,r,s);this.getSurface=function(t,e,i,r,s,o=!1){const a=n.triangulate(t,e,i,s,o);if(e&&!s&&(To(a.position,a.index,e,!0),a.normal=Bo(a.position,a.index)),r&&(Wr(r,a.position),a.normal)){const t=ko();Mo(t,r),qr(t,a.normal)}return a}}Object.assign(Ro,{__deps:[To,Bo,lo,Wr,qr,ko,Mo]}),Ee.add("surf",(function(t,e){const i=t.data.args,r=t.data.params;if(i&&(self.volsurf=new Ro(i[0],i[1],i[2],i[3],i[4])),r){const t=self.volsurf.getSurface(r.isolevel,r.smooth,r.box,r.matrix,r.contour,r.wrap),i=[t.position.buffer,t.index.buffer];t.normal&&i.push(t.normal.buffer),t.atomindex&&i.push(t.atomindex.buffer);e({sd:t,p:r},i)}}),[Ro]);class Eo{constructor(t,r,s,n,o,c,l){this.name=t,this.path=r,this.matrix=new i,this.normalMatrix=new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix3 */],this.inverseMatrix=new i,this.center=new e,this.boundingBox=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],this.setData(s,n,o,c,l)}get type(){return"Volume"}setData(t,e,i,r,s){this.nx=e||1,this.ny=i||1,this.nz=r||1,this.data=t||new Float32Array(1),this.setAtomindex(s),this._position=new Float32Array,delete this._min,delete this._max,delete this._mean,delete this._rms,this.worker&&this.worker.terminate()}setStats(t,e,i,r){this._min=t,this._max=e,this._mean=i,this._rms=r}setMatrix(t){this.matrix.copy(t);const i=this.boundingBox,r=this.center,s=this.nx-1,n=this.ny-1,o=this.nz-1;i.makeEmpty(),i.expandByPoint(r.set(s,n,o)),i.expandByPoint(r.set(s,n,0)),i.expandByPoint(r.set(s,0,o)),i.expandByPoint(r.set(s,0,0)),i.expandByPoint(r.set(0,n,o)),i.expandByPoint(r.set(0,0,o)),i.expandByPoint(r.set(0,n,0)),i.expandByPoint(r.set(0,0,0)),i.applyMatrix4(this.matrix),i.getCenter(this.center);const a=this.matrix.elements,c=new e(a[0],a[1],a[2]),l=new e(a[4],a[5],a[6]),h=new e(a[8],a[9],a[10]),d=new e,u=this.normalMatrix.elements;d.crossVectors(l,h),u[0]=d.x,u[1]=d.y,u[2]=d.z,d.crossVectors(h,c),u[3]=d.x,u[4]=d.y,u[5]=d.z,d.crossVectors(c,l),u[6]=d.x,u[7]=d.y,u[8]=d.z,this.inverseMatrix.getInverse(this.matrix)}setAtomindex(t){this.atomindex=t}getBox(t,e,i){return i||(i=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]),i.set(t,t),i.expandByScalar(e),i.applyMatrix4(this.inverseMatrix),i.min.round(),i.max.round(),i}_getBox(t,e){if(!t||!e)return;this.__box||(this.__box=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]);const i=this.getBox(t,e,this.__box);return[i.min.toArray(),i.max.toArray()]}_makeSurface(t,e,i){const r=this.name+"@"+e.toPrecision(2),s=new Oo(r,"",t);return s.info.isolevel=e,s.info.smooth=i,s.info.volume=this,s}getSurface(t,e,i,r,s,n=!1){t=isNaN(t)?this.getValueForSigma(2):t,e=st(e,0),void 0===this.volsurf&&(this.volsurf=new Ro(this.data,this.nx,this.ny,this.nz,this.atomindex));const o=this._getBox(i,r),a=this.volsurf.getSurface(t,e,o,this.matrix.elements,s,n);return this._makeSurface(a,t,e)}getSurfaceWorker(t,e,i,r,s,n,o){if(t=isNaN(t)?this.getValueForSigma(2):t,e=e||0,window.hasOwnProperty("Worker")){void 0===this.workerPool&&(this.workerPool=new Gr("surf",2));const a={},c=this.workerPool.getNextWorker();0===c.postCount&&Object.assign(a,{args:[this.data,this.nx,this.ny,this.nz,this.atomindex]}),Object.assign(a,{params:{isolevel:t,smooth:e,box:this._getBox(i,r),matrix:this.matrix.elements,contour:s,wrap:n}}),c.post(a,void 0,(t=>{const e=t.data.sd,i=t.data.p;o(this._makeSurface(e,i.isolevel,i.smooth))}),(a=>{console.warn("Volume.getSurfaceWorker error - trying without worker",a);const c=this.getSurface(t,e,i,r,s,n);o(c)}))}else{const a=this.getSurface(t,e,i,r,s,n);o(a)}}getValueForSigma(t){return this.mean+st(t,2)*this.rms}getSigmaForValue(t){return(st(t,0)-this.mean)/this.rms}get position(){if(!this._position){const t=this.nz,e=this.ny,i=this.nx,r=new Float32Array(i*e*t*3);let s=0;for(let n=0;n<t;++n)for(let t=0;t<e;++t)for(let e=0;e<i;++e)r[s+0]=e,r[s+1]=t,r[s+2]=n,s+=3;Wr(this.matrix.elements,r),this._position=r}return this._position}getDataAtomindex(){return this.atomindex}getDataPosition(){return this.position}getDataColor(t){const e=t||{};e.volume=this,e.scale=e.scale||"Spectral",e.domain=e.domain||[this.min,this.max];const i=Fe.getScheme(e),r=this.position.length/3,s=new Float32Array(3*r);for(let t=0;t<r;++t)i.volumeColorToArray(t,s,3*t);return s}getDataPicking(){const t=Pi(this.position.length/3);return new no(t,this)}getDataSize(t,e){const i=this.data,r=this.position.length/3;let s;switch(t){case"value":case"deviation":s=new Float32Array(i);break;case"abs-value":s=new Float32Array(i);for(let t=0;t<r;++t)s[t]=Math.abs(s[t]);break;case"value-min":{s=new Float32Array(i);const t=this.min;for(let e=0;e<r;++e)s[e]-=t;break}default:s=Si(r,t)}if(1!==e)for(let t=0;t<r;++t)s[t]*=e;return s}get min(){return void 0===this._min&&(this._min=Di(this.data)),this._min}get max(){return void 0===this._max&&(this._max=Bi(this.data)),this._max}get sum(){return void 0===this._sum&&(this._sum=$i(this.data)),this._sum}get mean(){return void 0===this._mean&&(this._mean=Oi(this.data)),this._mean}get rms(){return void 0===this._rms&&(this._rms=function(t){const e=t.length;let i=0;for(let r=0;r<e;++r){const e=t[r];i+=e*e}return Math.sqrt(i/e)}(this.data)),this._rms}clone(){const t=new Eo(this.name,this.path,this.data,this.nx,this.ny,this.nz,this.atomindex);return t.matrix.copy(this.matrix),t.header=Object.assign({},this.header),t}dispose(){this.workerPool&&this.workerPool.terminate()}}function Fo(t){return"front"===t?__WEBPACK_IMPORTED_MODULE_0_three__["r" /* FrontSide */]:"back"===t?__WEBPACK_IMPORTED_MODULE_0_three__["c" /* BackSide */]:__WEBPACK_IMPORTED_MODULE_0_three__["m" /* DoubleSide */]}Ve.add("shader/Mesh.vert","#define STANDARD\nuniform float clipNear;\nuniform vec3 clipCenter;\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || ( !defined( PICKING ) && !defined( NOLIGHT ) )\nvarying vec3 vViewPosition;\n#endif\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#if defined( PICKING )\n#include unpack_color\nattribute float primitiveId;\nvarying vec3 vPickingColor;\n#elif defined( NOLIGHT )\nvarying vec3 vColor;\n#else\n#include color_pars_vertex\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#endif\n#include common\nvoid main(){\n#if defined( PICKING )\nvPickingColor = unpackColor( primitiveId );\n#elif defined( NOLIGHT )\nvColor = color;\n#else\n#include color_vertex\n#include beginnormal_vertex\n#include defaultnormal_vertex\n#ifndef FLAT_SHADED\nvNormal = normalize( transformedNormal );\n#endif\n#endif\n#include begin_vertex\n#include project_vertex\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || ( !defined( PICKING ) && !defined( NOLIGHT ) )\nvViewPosition = -mvPosition.xyz;\n#endif\n#if defined( RADIUS_CLIP )\nvClipCenter = -( modelViewMatrix * vec4( clipCenter, 1.0 ) ).xyz;\n#endif\n#include nearclip_vertex\n}"),Ve.add("shader/Mesh.frag","#define STANDARD\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 interiorColor;\nuniform float interiorDarkening;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\nuniform float clipNear;\nuniform float clipRadius;\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || ( !defined( PICKING ) && !defined( NOLIGHT ) )\nvarying vec3 vViewPosition;\n#endif\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#if defined( PICKING )\nuniform float objectId;\nvarying vec3 vPickingColor;\n#elif defined( NOLIGHT )\nvarying vec3 vColor;\n#else\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#include common\n#include color_pars_fragment\n#include fog_pars_fragment\n#include bsdfs\n#include lights_pars_begin\n#include lights_physical_pars_fragment\n#endif\nvoid main(){\n#include nearclip_fragment\n#include radiusclip_fragment\n#if defined( PICKING )\nif( opacity < 0.3 )\ndiscard;\ngl_FragColor = vec4( vPickingColor, objectId );\n#elif defined( NOLIGHT )\ngl_FragColor = vec4( vColor, opacity );\n#else\nvec4 diffuseColor = vec4( diffuse, opacity );\nReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\nvec3 totalEmissiveLight = emissive;\n#include color_fragment\n#include roughnessmap_fragment\n#include metalnessmap_fragment\n#include normal_fragment_begin\n#include lights_physical_fragment\n#include lights_fragment_begin\n#include lights_fragment_end\nvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;\n#include interior_fragment\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );\n#include premultiplied_alpha_fragment\n#include tonemapping_fragment\n#include encodings_fragment\n#include fog_fragment\n#include opaque_back_fragment\n#endif\n}");const Lo={f:1,v2:2,v3:3,c:3};function No(t,e){t.matrix.copy(e),t.matrix.decompose(t.position,t.quaternion,t.scale),t.matrixWorldNeedsUpdate=!0}const zo={opaqueBack:!1,side:"double",opacity:1,depthWrite:!0,clipNear:0,clipRadius:0,clipCenter:new e,flatShaded:!1,wireframe:!1,roughness:.4,metalness:0,diffuse:16777215,diffuseInterior:!1,useInteriorColor:!1,interiorColor:14540253,interiorDarkening:0,forceTransparent:!1,matrix:new i,disablePicking:!1,sortParticles:!1,background:!1},Vo={opaqueBack:{updateShader:!0},side:{updateShader:!0,property:!0},opacity:{uniform:!0},depthWrite:{property:!0},clipNear:{updateShader:!0,property:!0},clipRadius:{updateShader:!0,uniform:!0},clipCenter:{uniform:!0},flatShaded:{updateShader:!0},background:{updateShader:!0},wireframe:{updateVisibility:!0},roughness:{uniform:!0},metalness:{uniform:!0},diffuse:{uniform:!0},diffuseInterior:{updateShader:!0},useInteriorColor:{updateShader:!0},interiorColor:{uniform:!0},interiorDarkening:{uniform:!0},matrix:{}};class Go{constructor(t,e={}){this.parameterTypes=Vo,this.geometry=new __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */],this.indexVersion=0,this.wireframeIndexVersion=-1,this.group=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.wireframeGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.pickingGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.vertexShader="",this.fragmentShader="",this.isImpostor=!1,this.isText=!1,this.isSurface=!1,this.isPoint=!1,this.isLine=!1,this.dynamic=!0,this.visible=!0,this.wireframeIndexCount=0,this.parameters=nt(e,this.defaultParameters),this.uniforms=__WEBPACK_IMPORTED_MODULE_0_three__["V" /* UniformsUtils */].merge([__WEBPACK_IMPORTED_MODULE_0_three__["U" /* UniformsLib */].common,{fogColor:{value:new s(0)},fogNear:{value:0},fogFar:{value:0},opacity:{value:this.parameters.opacity},clipNear:{value:0},clipRadius:{value:this.parameters.clipRadius},clipCenter:{value:this.parameters.clipCenter}},{emissive:{value:new s(0)},roughness:{value:this.parameters.roughness},metalness:{value:this.parameters.metalness},interiorColor:{value:new s(this.parameters.interiorColor)},interiorDarkening:{value:this.parameters.interiorDarkening}},__WEBPACK_IMPORTED_MODULE_0_three__["U" /* UniformsLib */].lights]),this.uniforms.diffuse.value.set(this.parameters.diffuse),this.pickingUniforms={clipNear:{value:0},objectId:{value:0},opacity:{value:this.parameters.opacity}};const i=t.position||t.position1;this._positionDataSize=i?i.length/3:0,t.primitiveId||(t.primitiveId=Pi(this._positionDataSize)),this.addAttributes({position:{type:"v3",value:t.position},color:{type:"c",value:t.color},primitiveId:{type:"f",value:t.primitiveId}}),e.matrix&&(this.matrix=e.matrix),t.index&&this.initIndex(t.index),this.picking=t.picking,this.makeWireframeGeometry()}get defaultParameters(){return zo}set matrix(t){this.setMatrix(t)}get matrix(){return this.group.matrix.clone()}get transparent(){return this.parameters.opacity<1||this.parameters.forceTransparent}get size(){return this._positionDataSize}get attributeSize(){return this.size}get pickable(){return!!this.picking&&!this.parameters.disablePicking}setMatrix(t){No(this.group,t),No(this.wireframeGroup,t),No(this.pickingGroup,t)}initIndex(t){this.geometry.setIndex(new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](t,1));const e=this.geometry.getIndex();e?e.setUsage(this.dynamic?WebGLRenderingContext.DYNAMIC_DRAW:0):Me.error("Index is null")}makeMaterial(){const t=Fo(this.parameters.side),e=new __WEBPACK_IMPORTED_MODULE_0_three__["O" /* ShaderMaterial */]({uniforms:this.uniforms,vertexShader:"",fragmentShader:"",depthTest:!0,transparent:this.transparent,depthWrite:this.parameters.depthWrite,lights:!0,fog:!0,side:t});e.vertexColors=!0,e.extensions.derivatives=!0,e.extensions.fragDepth=this.isImpostor;const i=new __WEBPACK_IMPORTED_MODULE_0_three__["O" /* ShaderMaterial */]({uniforms:this.uniforms,vertexShader:"",fragmentShader:"",depthTest:!0,transparent:this.transparent,depthWrite:this.parameters.depthWrite,lights:!1,fog:!0,side:t});i.vertexColors=!0;const r=new __WEBPACK_IMPORTED_MODULE_0_three__["O" /* ShaderMaterial */]({uniforms:this.pickingUniforms,vertexShader:"",fragmentShader:"",depthTest:!0,transparent:!1,depthWrite:this.parameters.depthWrite,lights:!1,fog:!1,side:t,blending:__WEBPACK_IMPORTED_MODULE_0_three__["C" /* NoBlending */]});r.vertexColors=!0,r.extensions.fragDepth=this.isImpostor,e.clipNear=this.parameters.clipNear,i.clipNear=this.parameters.clipNear,r.clipNear=this.parameters.clipNear,this.material=e,this.wireframeMaterial=i,this.pickingMaterial=r,this.updateShader()}makeWireframeGeometry(){this.makeWireframeIndex();const t=this.geometry,e=this.wireframeIndex,i=new __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */];i.attributes=t.attributes,e&&(i.setIndex(new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](e,1).setUsage(this.dynamic?WebGLRenderingContext.DYNAMIC_DRAW:0)),i.setDrawRange(0,this.wireframeIndexCount)),this.wireframeGeometry=i}makeWireframeIndex(){const t=[];function e(e,i){if(e>i){const t=e;e=i,i=t}const r=t[e];return void 0===r?(t[e]=[i],!0):!r.includes(i)&&(r.push(i),!0)}const i=this.geometry,r=i.index;if(this.parameters.wireframe)if(r){const s=r.array;let n,o=s.length;if(i.drawRange.count!==1/0&&(o=i.drawRange.count),this.wireframeIndex&&this.wireframeIndex.length>2*o)n=this.wireframeIndex;else{n=xt(2*o,i.attributes.position.count)}let a=0;t.length=0;for(let t=0;t<o;t+=3){const i=s[t+0],r=s[t+1],o=s[t+2];e(i,r)&&(n[a+0]=i,n[a+1]=r,a+=2),e(r,o)&&(n[a+0]=r,n[a+1]=o,a+=2),e(o,i)&&(n[a+0]=o,n[a+1]=i,a+=2)}this.wireframeIndex=n,this.wireframeIndexCount=a,this.wireframeIndexVersion=this.indexVersion}else{const t=i.attributes.position.count;let e;e=this.wireframeIndex&&this.wireframeIndex.length>2*t?this.wireframeIndex:xt(2*t,t);for(let i=0,r=0;i<t;i+=3)e[r+0]=i,e[r+1]=i+1,e[r+2]=i+1,e[r+3]=i+2,e[r+4]=i+2,e[r+5]=i,r+=6;this.wireframeIndex=e,this.wireframeIndexCount=2*t,this.wireframeIndexVersion=this.indexVersion}else this.wireframeIndex=new Uint16Array(0),this.wireframeIndexCount=0}updateWireframeIndex(){if(this.wireframeGeometry&&this.wireframeIndex){if(this.wireframeGeometry.setDrawRange(0,1/0),this.wireframeIndexVersion<this.indexVersion&&this.makeWireframeIndex(),this.wireframeGeometry.index&&this.wireframeIndex.length>this.wireframeGeometry.index.array.length)this.wireframeGeometry.setIndex(new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](this.wireframeIndex,1).setUsage(this.dynamic?WebGLRenderingContext.DYNAMIC_DRAW:0));else{const t=this.wireframeGeometry.getIndex();if(!t)return void Me.error("Index is null");t.set(this.wireframeIndex),t.needsUpdate=this.wireframeIndexCount>0,t.updateRange.count=this.wireframeIndexCount}this.wireframeGeometry.setDrawRange(0,this.wireframeIndexCount)}}getRenderOrder(){let t=0;return this.isText?t=1:this.transparent&&(t=this.isSurface?3:2),t}_getMesh(t){this.material||this.makeMaterial();const e=this.geometry,i=this[t];let r;return r=this.isLine?new __WEBPACK_IMPORTED_MODULE_0_three__["v" /* LineSegments */](e,i):this.isPoint?new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Points */](e,i):new __WEBPACK_IMPORTED_MODULE_0_three__["A" /* Mesh */](e,i),r.frustumCulled=!1,r.renderOrder=this.getRenderOrder(),r}getMesh(){return this._getMesh("material")}getWireframeMesh(){let t;return this.material||this.makeMaterial(),this.wireframeGeometry||this.makeWireframeGeometry(),t=new __WEBPACK_IMPORTED_MODULE_0_three__["v" /* LineSegments */](this.wireframeGeometry,this.wireframeMaterial),t.frustumCulled=!1,t.renderOrder=this.getRenderOrder(),t}getPickingMesh(){return this._getMesh("pickingMaterial")}getShader(t,e){return gi(t,this.getDefines(e))}getVertexShader(t){return this.getShader(this.vertexShader,t)}getFragmentShader(t){return this.getShader(this.fragmentShader,t)}getDefines(t){const e={};return this.parameters.clipNear&&(e.NEAR_CLIP=1),this.parameters.clipRadius&&(e.RADIUS_CLIP=1),"picking"===t?e.PICKING=1:(("background"===t||this.parameters.background)&&(e.NOLIGHT=1),this.parameters.flatShaded&&(e.FLAT_SHADED=1),this.parameters.opaqueBack&&(e.OPAQUE_BACK=1),this.parameters.diffuseInterior&&(e.DIFFUSE_INTERIOR=1),this.parameters.useInteriorColor&&(e.USE_INTERIOR_COLOR=1)),e}getParameters(){return this.parameters}addUniforms(t){this.uniforms=__WEBPACK_IMPORTED_MODULE_0_three__["V" /* UniformsUtils */].merge([this.uniforms,t]),this.pickingUniforms=__WEBPACK_IMPORTED_MODULE_0_three__["V" /* UniformsUtils */].merge([this.pickingUniforms,t])}addAttributes(t){for(let e in t){let i;const r=t[e],s=this.attributeSize*Lo[r.type];r.value?(s!==r.value.length&&Me.error("attribute value has wrong length",e),i=r.value):i=bt("float32",s),this.geometry.setAttribute(e,new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](i,Lo[r.type]).setUsage(this.dynamic?WebGLRenderingContext.DYNAMIC_DRAW:0))}}updateRenderOrder(){const t=this.getRenderOrder();function e(e){e.renderOrder=t}this.group.children.forEach(e),this.pickingGroup&&this.pickingGroup.children.forEach(e)}updateShader(){const t=this.material,e=this.wireframeMaterial,i=this.pickingMaterial;t.vertexShader=this.getVertexShader(),t.fragmentShader=this.getFragmentShader(),t.needsUpdate=!0,e.vertexShader=this.getShader("Line.vert"),e.fragmentShader=this.getShader("Line.frag"),e.needsUpdate=!0,i.vertexShader=this.getVertexShader("picking"),i.fragmentShader=this.getFragmentShader("picking"),i.needsUpdate=!0}setParameters(t){const e=t,i=this.parameterTypes,r=this.parameters,s={},n={};let o=!1,a=!1;for(const t in e){const c=e[t];void 0!==c&&(r[t]=c,void 0!==i[t]&&(i[t].property&&(!0!==i[t].property?s[i[t].property]=c:s[t]=c),i[t].uniform&&(!0!==i[t].uniform?n[i[t].uniform]=c:n[t]=c),i[t].updateShader&&(o=!0),i[t].updateVisibility&&(a=!0),this.dynamic&&"wireframe"===t&&!0===c&&this.updateWireframeIndex(),"forceTransparent"===t&&(s.transparent=this.transparent),"matrix"===t&&(this.matrix=c)))}this.setProperties(s),this.setUniforms(n),o&&this.updateShader(),a&&this.setVisibility(this.visible)}setAttributes(t){const e=this.geometry,i=e.attributes;for(const r in t){if("picking"===r)continue;const s=t[r],n=s.length;if("index"===r){const t=e.getIndex();if(!t){Me.error("Index is null");continue}e.setDrawRange(0,1/0),n>t.array.length?e.setIndex(new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](s,1).setUsage(this.dynamic?WebGLRenderingContext.DYNAMIC_DRAW:0)):(t.set(s),t.count=n,t.needsUpdate=n>0,t.updateRange.count=n,e.setDrawRange(0,n)),this.indexVersion++,this.parameters.wireframe&&this.updateWireframeIndex()}else{const t=i[r];n>t.array.length?e.setAttribute(r,new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](s,t.itemSize).setUsage(this.dynamic?WebGLRenderingContext.DYNAMIC_DRAW:0)):(i[r].set(s),i[r].needsUpdate=n>0,i[r].updateRange.count=n)}}}setUniforms(t){if(!t)return;const e=this.material.uniforms,i=this.wireframeMaterial.uniforms,r=this.pickingMaterial.uniforms;for(let s in t)"opacity"===s&&this.setProperties({transparent:this.transparent}),void 0!==e[s]&&(e[s].value.isVector3?e[s].value.copy(t[s]):e[s].value.set?e[s].value.set(t[s]):e[s].value=t[s]),void 0!==i[s]&&(i[s].value.isVector3?i[s].value.copy(t[s]):i[s].value.set?i[s].value.set(t[s]):i[s].value=t[s]),void 0!==r[s]&&(r[s].value.isVector3?r[s].value.copy(t[s]):r[s].value.set?r[s].value.set(t[s]):r[s].value=t[s])}setProperties(t){if(!t)return;const e=this.material,i=this.wireframeMaterial,r=this.pickingMaterial;for(const s in t){const n=s;let o=t[n];"transparent"===n?this.updateRenderOrder():"side"===n&&(o=Fo(o)),e[n]=o,i[n]=o,r[n]=o}e.needsUpdate=!0,i.needsUpdate=!0,r.needsUpdate=!0}setVisibility(t){this.visible=t,this.parameters.wireframe?(this.group.visible=!1,this.wireframeGroup.visible=t,this.pickable&&(this.pickingGroup.visible=!1)):(this.group.visible=t,this.wireframeGroup.visible=!1,this.pickable&&(this.pickingGroup.visible=t))}dispose(){this.material&&this.material.dispose(),this.wireframeMaterial&&this.wireframeMaterial.dispose(),this.pickingMaterial&&this.pickingMaterial.dispose(),this.geometry.dispose(),this.wireframeGeometry&&this.wireframeGeometry.dispose()}toJSON(){var t={};for(var e in this)"group"!==e&&"wireframeGroup"!==e&&"pickingGroup"!=e&&"picking"!==e&&(t[e]=this[e]);return t}}class Uo extends Go{constructor(t,e={}){super(t,e),this.vertexShader="Mesh.vert",this.fragmentShader="Mesh.frag",this.addAttributes({normal:{type:"v3",value:t.normal}}),void 0===t.normal&&this.geometry.computeVertexNormals()}}class jo extends Uo{constructor(){super(...arguments),this.isSurface=!0}}function Ho(t){t.visible=!0}function Wo(t){t.visible=!1}class qo{constructor(t){this.group=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.wireframeGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.pickingGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.frontMeshes=[],this.backMeshes=[],this.size=t.size,this.side=t.parameters.side,this.visible=t.visible,this.geometry=t.geometry,this.picking=t.picking,this.group=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.wireframeGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.pickingGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.matrix=t.matrix;const e=t,i=new t.constructor({position:new Float32Array(0)});e.makeMaterial(),i.makeMaterial(),i.picking=t.picking,i.geometry=t.geometry,i.wireframeGeometry=t.wireframeGeometry,i.setParameters(t.getParameters()),i.updateShader(),e.setParameters({side:"front"}),i.setParameters({side:"back",opacity:i.parameters.opacity}),this.buffer=t,this.frontBuffer=e,this.backBuffer=i}set matrix(t){Go.prototype.setMatrix.call(this,t)}get matrix(){return this.group.matrix.clone()}get pickable(){return!!this.picking&&!this.parameters.disablePicking}get parameters(){return this.buffer.parameters}getParameters(){const t=Object.assign({},this.buffer.parameters);return t.side=this.side,t}getMesh(t){let e,i;return t?(i=this.backBuffer.getPickingMesh(),e=this.frontBuffer.getPickingMesh()):(i=this.backBuffer.getMesh(),e=this.frontBuffer.getMesh()),this.frontMeshes.push(e),this.backMeshes.push(i),this.setParameters({side:this.side}),(new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]).add(i,e)}getWireframeMesh(){return this.buffer.getWireframeMesh()}getPickingMesh(){return this.getMesh(!0)}setAttributes(t){this.buffer.setAttributes(t)}setParameters(t){"front"===(t=Object.assign({},t)).side?(this.frontMeshes.forEach(Ho),this.backMeshes.forEach(Wo)):"back"===t.side?(this.frontMeshes.forEach(Wo),this.backMeshes.forEach(Ho)):"double"===t.side&&(this.frontMeshes.forEach(Ho),this.backMeshes.forEach(Ho)),void 0!==t.side&&(this.side=t.side),delete t.side,void 0!==t.matrix&&(this.matrix=t.matrix),delete t.matrix,this.frontBuffer.setParameters(t),void 0!==t.wireframe&&(this.wireframe=t.wireframe,this.setVisibility(this.visible)),delete t.wireframe,this.backBuffer.setParameters(t)}setVisibility(t){this.visible=t,this.parameters.wireframe?(this.group.visible=!1,this.wireframeGroup.visible=t,this.pickable&&(this.pickingGroup.visible=!1)):(this.group.visible=t,this.wireframeGroup.visible=!1,this.pickable&&(this.pickingGroup.visible=t))}dispose(){this.frontBuffer.dispose(),this.backBuffer.dispose()}toJSON(){var t={};for(var e in this)["side","size","visible","matrix","parameters"].includes(e)&&(t[e]=this[e]);return t}}Ve.add("shader/Line.vert","uniform float clipNear;\nuniform vec3 clipCenter;\nvarying vec3 vViewPosition;\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#include color_pars_vertex\nvoid main(){\n#include color_vertex\n#include begin_vertex\n#include project_vertex\nvViewPosition = -mvPosition.xyz;\n#if defined( RADIUS_CLIP )\nvClipCenter = -( modelViewMatrix * vec4( clipCenter, 1.0 ) ).xyz;\n#endif\n#include nearclip_vertex\n}"),Ve.add("shader/Line.frag","uniform float opacity;\nuniform float clipNear;\nuniform float clipRadius;\nvarying vec3 vViewPosition;\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#include common\n#include color_pars_fragment\n#include fog_pars_fragment\nvoid main(){\n#include nearclip_fragment\n#include radiusclip_fragment\ngl_FragColor = vec4( vColor, opacity );\n#include premultiplied_alpha_fragment\n#include tonemapping_fragment\n#include encodings_fragment\n#include fog_fragment\n}");class Xo extends Go{constructor(){super(...arguments),this.isLine=!0,this.vertexShader="Line.vert",this.fragmentShader="Line.frag"}}class Yo extends zr{constructor(t,r,s){super(t,r,s),this.type="surface",this.parameters=Object.assign({isolevelType:{type:"select",options:{value:"value",sigma:"sigma"}},isolevel:{type:"number",precision:2,max:1e3,min:-1e3},negateIsolevel:{type:"boolean"},isolevelScroll:{type:"boolean"},smooth:{type:"integer",precision:1,max:10,min:0},background:{type:"boolean",rebuild:!0},opaqueBack:{type:"boolean",buffer:!0},boxSize:{type:"integer",precision:1,max:100,min:0},colorVolume:{type:"hidden"},contour:{type:"boolean",rebuild:!0},useWorker:{type:"boolean",rebuild:!0},wrap:{type:"boolean",rebuild:!0}},this.parameters),t instanceof Eo?(this.surface=void 0,this.volume=t):(this.surface=t,this.volume=void 0),this.boxCenter=new e,this.__boxCenter=new e,this.box=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],this.__box=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],this._position=new e,this.inverseMatrix=new i,this.setBox=function(){this._position.copy(r.translationGroup.position).negate(),this._position.applyMatrix4(this.inverseMatrix),this._position.equals(this.boxCenter)||this.setParameters({boxCenter:this._position})},this.toBePrepared=!0,this.viewer.signals.ticked.add(this.setBox,this),this.init(s)}init(t){const e=t||{};e.colorScheme=st(e.colorScheme,"uniform"),e.colorValue=st(e.colorValue,14540253),this.isolevelType=st(e.isolevelType,"sigma"),this.isolevel=st(e.isolevel,2),this.negateIsolevel=st(e.negateIsolevel,!1),this.isolevelScroll=st(e.isolevelScroll,!1),this.smooth=st(e.smooth,0),this.background=st(e.background,!1),this.opaqueBack=st(e.opaqueBack,!0),this.boxSize=st(e.boxSize,0),this.colorVolume=st(e.colorVolume,void 0),this.contour=st(e.contour,!1),this.useWorker=st(e.useWorker,!0),this.wrap=st(e.wrap,!1),super.init(e),this.inverseMatrix.getInverse(this.matrix),this.build()}attach(t){this.bufferList.forEach((t=>{this.viewer.add(t)})),this.setVisibility(this.visible),t()}prepare(t){if(this.volume){let e;if(e="sigma"===this.isolevelType?this.volume.getValueForSigma(this.isolevel):this.isolevel,this.negateIsolevel&&(e*=-1),!this.surface||this.__isolevel!==e||this.__smooth!==this.smooth||this.__contour!==this.contour||this.__wrap!==this.wrap||this.__boxSize!==this.boxSize||this.boxSize>0&&!this.__boxCenter.equals(this.boxCenter)){this.__isolevel=e,this.__smooth=this.smooth,this.__contour=this.contour,this.__wrap=this.wrap,this.__boxSize=this.boxSize,this.__boxCenter.copy(this.boxCenter),this.__box.copy(this.box);const i=e=>{this.surface=e,t()};this.useWorker?this.volume.getSurfaceWorker(e,this.smooth,this.boxCenter,this.boxSize,this.contour,this.wrap,i):i(this.volume.getSurface(e,this.smooth,this.boxCenter,this.boxSize,this.contour,this.wrap))}else t()}else t()}create(){const t={position:this.surface.getPosition(),color:this.surface.getColor(this.getColorParams()),index:this.surface.getIndex()};let e;if(this.contour)e=new Xo(t,this.getBufferParams({wireframe:!1}));else{Object.assign(t,{normal:this.surface.getNormal(),picking:this.surface.getPicking()});const i=new jo(t,this.getBufferParams({background:this.background,opaqueBack:this.opaqueBack,dullInterior:!1}));e=new qo(i)}this.bufferList.push(e)}update(t){if(0===this.bufferList.length)return;const e={};(t=t||{}).position&&(e.position=this.surface.getPosition()),t.color&&(e.color=this.surface.getColor(this.getColorParams())),t.index&&(e.index=this.surface.getIndex()),t.normal&&(e.normal=this.surface.getNormal()),this.bufferList.forEach((function(t){t.setAttributes(e)}))}setParameters(t,e,i){return t&&void 0!==t.isolevelType&&this.volume&&("value"===this.isolevelType&&"sigma"===t.isolevelType?this.isolevel=this.volume.getSigmaForValue(this.isolevel):"sigma"===this.isolevelType&&"value"===t.isolevelType&&(this.isolevel=this.volume.getValueForSigma(this.isolevel)),this.isolevelType=t.isolevelType),t&&t.boxCenter&&(this.boxCenter.copy(t.boxCenter),delete t.boxCenter),t&&t.wireframe&&(t.contour||void 0===t.contour&&this.contour)&&(t.wireframe=!1),super.setParameters(t,e,i),t.matrix&&this.inverseMatrix.getInverse(t.matrix),this.volume&&this.volume.getBox(this.boxCenter,this.boxSize,this.box),t&&void 0!==t.colorVolume&&e&&(e.color=!0),this.surface&&(void 0!==t.isolevel||void 0!==t.negateIsolevel||void 0!==t.smooth||void 0!==t.wrap||void 0!==t.boxSize||this.boxSize>0&&!this.__box.equals(this.box))&&this.build({position:!0,color:!0,index:!0,normal:!this.contour}),this}getColorParams(){const t=super.getColorParams();return t.volume=this.colorVolume,t}dispose(){this.viewer.signals.ticked.remove(this.setBox,this),super.dispose()}}class Ko{static zoomScroll(t,e){t.trackballControls.zoom(e)}static clipNearScroll(t,e){const i=t.getParameters();t.setParameters({clipNear:i.clipNear+e/10})}static focusScroll(t,e){const i=t.getFocus(),r=Math.sign(e)*function(t,e,i){if(t>e)return t;const r=t/e;return((2*i-e)*r+(2*e-3*i))*r*r+i}((100-i)/10,5,.2);t.setFocus(i+r)}static zoomFocusScroll(t,e){t.trackballControls.zoom(e);const i=t.viewer.camera.position.z;t.setFocus(100-Math.abs(i/8))}static isolevelScroll(t,e){const i=Math.sign(e)/10;t.eachRepresentation(((t,e)=>{if(t.repr instanceof Yo){const e=t.getParameters();e.isolevelScroll&&t.setParameters({isolevel:e.isolevel+i})}}))}static panDrag(t,e,i){t.trackballControls.pan(e,i)}static rotateDrag(t,e,i){t.trackballControls.rotate(e,i)}static zRotateDrag(t,e,i){t.trackballControls.zRotate(e,i)}static zoomDrag(t,e,i){t.trackballControls.zoom((e+i)/-2)}static zoomFocusDrag(t,e,i){t.trackballControls.zoom((e+i)/-2);const r=t.viewer.camera.position.z;t.setFocus(100-Math.abs(r/8))}static panComponentDrag(t,e,i){t.trackballControls.panComponent(e,i)}static panAtomDrag(t,e,i){t.trackballControls.panAtom(e,i)}static rotateComponentDrag(t,e,i){t.trackballControls.rotateComponent(e,i)}static movePick(t,e){e&&t.animationControls.move(e.position.clone())}static tooltipPick(t,e){const i=t.tooltip;if(t.getParameters().tooltip&&e){const t=e.mouse.position;i.innerText=e.getLabel(),i.style.bottom=window.innerHeight-t.y+3+"px",i.style.left=t.x+3+"px",i.style.display="block"}else i.style.display="none"}static measurePick(t,e){if(e&&(e.atom||e.bond)){const t=e.atom||e.closestBondAtom;e.component.measurePick(t)}else t.measureClear()}}const Zo={default:[["scroll",Ko.zoomScroll],["scroll-shift",Ko.focusScroll],["scroll-ctrl",Ko.isolevelScroll],["scroll-shift-ctrl",Ko.zoomFocusScroll],["drag-left",Ko.rotateDrag],["drag-right",Ko.panDrag],["drag-ctrl-left",Ko.panDrag],["drag-ctrl-right",Ko.zRotateDrag],["drag-shift-left",Ko.zoomDrag],["drag-middle",Ko.zoomFocusDrag],["drag-ctrl-shift-right",Ko.panComponentDrag],["drag-ctrl-shift-left",Ko.rotateComponentDrag],["clickPick-right",Ko.measurePick],["clickPick-ctrl-left",Ko.measurePick],["clickPick-middle",Ko.movePick],["clickPick-left",Ko.movePick],["hoverPick",Ko.tooltipPick]],pymol:[["drag-left",Ko.rotateDrag],["drag-middle",Ko.panDrag],["drag-right",Ko.zoomDrag],["scroll",Ko.focusScroll],["drag-shift-right",Ko.focusScroll],["clickPick-ctrl+shift-middle",Ko.movePick],["hoverPick",Ko.tooltipPick]],coot:[["scroll",Ko.isolevelScroll],["drag-left",Ko.rotateDrag],["drag-middle",Ko.panDrag],["drag-ctrl-left",Ko.panDrag],["drag-right",Ko.zoomFocusDrag],["drag-ctrl-right",Ko.focusScroll],["clickPick-middle",Ko.movePick],["hoverPick",Ko.tooltipPick]],astexviewer:[["drag-left",Ko.rotateDrag],["drag-ctrl-left",Ko.panDrag],["drag-shift-left",Ko.zoomDrag],["scroll",Ko.focusScroll],["clickPick-middle",Ko.movePick],["hoverPick",Ko.tooltipPick]]};function Qo(t){const e=t.split(/[-+]/);let i="";e.includes("scroll")&&(i="scroll"),e.includes("drag")&&(i="drag"),e.includes("click")&&(i="click"),e.includes("doubleClick")&&(i="doubleClick"),e.includes("hover")&&(i="hover"),e.includes("clickPick")&&(i="clickPick"),e.includes("hoverPick")&&(i="hoverPick");let r=0;e.includes("alt")&&(r+=1),e.includes("ctrl")&&(r+=2),e.includes("meta")&&(r+=4),e.includes("shift")&&(r+=8);let s=0;return e.includes("left")&&(s+=1),e.includes("right")&&(s+=2),e.includes("middle")&&(s+=4),[i,r,s]}class Jo{constructor(t,e={}){this.stage=t,this.actionList=[],this.mouse=t.mouseObserver,this.disabled=e.disabled||!1,this.preset(e.preset||"default")}run(t,...e){if(this.disabled)return;const i=this.mouse.key||0,r=this.mouse.buttons||0;this.actionList.forEach((s=>{s.type===t&&s.key===i&&s.button===r&&s.callback(this.stage,...e)}))}add(t,e){const[i,r,s]=Qo(t);this.actionList.push({type:i,key:r,button:s,callback:e})}remove(t,e){const i=t.includes("*"),[r,s,n]=Qo(t),o=this.actionList.filter((function(t){return!((t.type===r||i&&""===r)&&(t.key===s||i&&0===s)&&(t.button===n||i&&0===n)&&(t.callback===e||void 0===e))}));this.actionList=o}preset(t){this.clear();(Zo[t]||[]).forEach((t=>this.add(t[0],t[1])))}clear(){this.actionList.length=0}}class ta{static autoView(t){t.autoView(1e3)}static toggleAnimations(t){t.animationControls.toggle()}static toggleRock(t){t.toggleRock()}static toggleSpin(t){t.toggleSpin()}static toggleAntialiasing(t){const e=t.getParameters();t.setParameters({sampleLevel:-1===e.sampleLevel?0:-1})}}const ea={default:[["i",ta.toggleSpin],["k",ta.toggleRock],["p",ta.toggleAnimations],["a",ta.toggleAntialiasing],["r",ta.autoView]]};class ia{constructor(t,e={}){this.stage=t,this.actionList=[],this.disabled=e.disabled||!1,this.preset(e.preset||"default")}run(t){this.disabled||this.actionList.forEach((e=>{e.key===t&&e.callback(this.stage)}))}add(t,e){this.actionList.push({key:t,callback:e})}remove(t,e){const i=this.actionList.filter((function(i){return!(i.key===t&&(i.callback===e||void 0===e))}));this.actionList=i}preset(t){this.clear();(ea[t]||[]).forEach((t=>this.add(t[0],t[1])))}clear(){this.actionList.length=0}}class ra{constructor(t){this.stage=t,this.stage=t,this.mouse=t.mouseObserver,this.controls=t.mouseControls,this.mouse.signals.clicked.add(this._onClick,this),this.mouse.signals.hovered.add(this._onHover,this)}_onClick(t,e){const i=this.stage.pickingControls.pick(t,e);this.stage.signals.clicked.dispatch(i),this.controls.run("clickPick",i)}_onHover(t,e){const i=this.stage.pickingControls.pick(t,e);i&&this.mouse.down.equals(this.mouse.position)&&(this.stage.transformComponent=i.component,this.stage.transformAtom=i.atom),this.stage.signals.hovered.dispatch(i),this.controls.run("hoverPick",i)}dispose(){this.mouse.signals.clicked.remove(this._onClick,this),this.mouse.signals.hovered.remove(this._onHover,this)}}class sa{constructor(t){this.stage=t,this.stage=t,this.mouse=t.mouseObserver,this.controls=t.mouseControls,this.mouse.signals.moved.add(this._onMove,this),this.mouse.signals.scrolled.add(this._onScroll,this),this.mouse.signals.dragged.add(this._onDrag,this),this.mouse.signals.clicked.add(this._onClick,this),this.mouse.signals.hovered.add(this._onHover,this),this.mouse.signals.doubleClicked.add(this._onDblclick,this)}_onMove(){this.stage.tooltip.style.display="none"}_onScroll(t){this.controls.run("scroll",t)}_onDrag(t,e){this.controls.run("drag",t,e)}_onClick(t,e){this.controls.run("click",t,e)}_onDblclick(t,e){this.controls.run("doubleClick",t,e)}_onHover(t,e){this.controls.run("hover",t,e)}dispose(){this.mouse.signals.moved.remove(this._onMove,this),this.mouse.signals.scrolled.remove(this._onScroll,this),this.mouse.signals.dragged.remove(this._onDrag,this),this.mouse.signals.clicked.remove(this._onClick,this),this.mouse.signals.hovered.remove(this._onHover,this)}}class na{constructor(t){this.stage=t,this.viewer=t.viewer,this.animationControls=t.animationControls,this.viewer.signals.ticked.add(this._onTick,this)}_onTick(t){this.animationControls.run(t)}dispose(){this.viewer.signals.ticked.remove(this._onTick,this)}}const oa=!!_e&&{passive:!0};class aa{constructor(t){this.stage=t,this.stage=t,this.controls=t.keyControls,this.domElement=t.viewer.renderer.domElement,this.domElement.setAttribute("tabIndex","-1"),this.domElement.style.outline="none",this._focusDomElement=this._focusDomElement.bind(this),this._onKeydown=this._onKeydown.bind(this),this._onKeyup=this._onKeyup.bind(this),this._onKeypress=this._onKeypress.bind(this),this.domElement.addEventListener("mousedown",this._focusDomElement),this.domElement.addEventListener("touchstart",this._focusDomElement,oa),this.domElement.addEventListener("keydown",this._onKeydown),this.domElement.addEventListener("keyup",this._onKeyup),this.domElement.addEventListener("keypress",this._onKeypress)}_onKeydown(){}_onKeyup(){}_onKeypress(t){let e;e="key"in KeyboardEvent.prototype?t.key:String.fromCharCode(t.which||t.keyCode),this.controls.run(e)}_focusDomElement(){this.domElement.focus()}dispose(){this.domElement.removeEventListener("mousedown",this._focusDomElement),this.domElement.removeEventListener("touchstart",this._focusDomElement,oa),this.domElement.removeEventListener("keydown",this._onKeypress),this.domElement.removeEventListener("keyup",this._onKeypress),this.domElement.removeEventListener("keypress",this._onKeypress)}}class ca{constructor(i,r,s,n={}){this.component=i,this.position=r,this.offsetX=st(n.offsetX,0),this.offsetY=st(n.offsetY,0),this.visible=st(n.visible,!0),this.stage=i.stage,this.viewer=i.stage.viewer,this._viewerPosition=new e,this._updateViewerPosition(),this._canvasPosition=new t,this._cameraPosition=new e,this.element=document.createElement("div"),Object.assign(this.element.style,{display:"block",position:"absolute",pointerEvents:"none",whiteSpace:"nowrap",left:"-10000px"}),this.viewer.wrapper.appendChild(this.element),this.setContent(s),this.updateVisibility(),this.viewer.signals.rendered.add(this._update,this),this.component.signals.matrixChanged.add(this._updateViewerPosition,this)}setContent(t){const e=this.element.style.display;if("none"===e&&(this.element.style.left="-10000px",this.element.style.display="block"),t instanceof HTMLElement)this.element.appendChild(t);else{const e=document.createElement("div");e.innerText=t,Object.assign(e.style,{backgroundColor:"rgba( 0, 0, 0, 0.6 )",color:"lightgrey",padding:"8px",fontFamily:"sans-serif"}),this.element.appendChild(e)}this._clientRect=this.element.getBoundingClientRect(),"none"===e&&(this.element.style.display=e)}setVisibility(t){this.visible=t,this.updateVisibility()}getVisibility(){return this.visible&&this.component.parameters.visible}updateVisibility(){this.element.style.display=this.getVisibility()?"block":"none"}_updateViewerPosition(){this._viewerPosition.copy(this.position).applyMatrix4(this.component.matrix)}_update(){if(!this.getVisibility())return;const t=this.element.style,e=this._canvasPosition,i=this._viewerPosition,r=this._clientRect;if(this._cameraPosition.copy(i).add(this.viewer.translationGroup.position).applyMatrix4(this.viewer.rotationGroup.matrix).sub(this.viewer.camera.position),this._cameraPosition.z<0)return void(t.display="none");t.display="block";const s=this._cameraPosition.length(),n=this.viewer.scene.fog;t.opacity=(1-Rt(n.near,n.far,s)).toString(),t.zIndex=Math.round(100*(n.far-s)).toString(),this.stage.viewerControls.getPositionOnCanvas(i,e),t.bottom=this.offsetX+e.y+r.height/2+"px",t.left=this.offsetY+e.x-r.width/2+"px"}dispose(){this.viewer.wrapper.removeChild(this.element),this.viewer.signals.ticked.remove(this._update,this),this.component.signals.matrixChanged.remove(this._updateViewerPosition,this)}}const la=new i,ha=new e,da=new r;class ua{constructor(t){this.component=t,this.signals={changed:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.stage=t.stage,this.viewer=t.stage.viewer}get position(){return this.component.position}get rotation(){return this.component.quaternion}changed(){this.component.updateMatrix(),this.viewer.requestRender(),this.signals.changed.dispatch()}spin(t,e){la.getInverse(this.viewer.rotationGroup.matrix),ha.copy(At(t)).applyMatrix4(la),la.extractRotation(this.component.transform),la.premultiply(this.viewer.rotationGroup.matrix),la.getInverse(la),ha.copy(At(t)),ha.applyMatrix4(la),la.makeRotationAxis(ha,e),da.setFromRotationMatrix(la),this.component.quaternion.premultiply(da),this.changed()}}const ma={"":"",vdw:"by vdW radius",covalent:"by covalent radius",sstruc:"by secondary structure",bfactor:"by bfactor",size:"size",data:"data",explicit:"explicit"};class pa{constructor(t={}){this.max=10,this.type=st(t.type,"size"),this.scale=st(t.scale,1),this.size=st(t.size,1),this.data=st(t.data,{})}atomRadius(t){let e;switch(this.type){case"vdw":e=t.vdw;break;case"covalent":e=t.covalent;break;case"bfactor":e=t.bfactor||1;break;case"sstruc":const i=t.sstruc;e="h"===i||"g"===i||"i"===i||"e"===i||"b"===i?.25:un.includes(t.atomname)?.4:.1;break;case"data":e=st(this.data[t.index],1);break;case"explicit":e=t.radius,null===e&&(e=this.size);break;default:e=this.size}return Math.min(e*this.scale,this.max)}}pa.types=ma;const fa=new e(-1,-1,-1),ga=new i;class ya{constructor(t){const i=t.rows,r=i/3,s=new ho(i,3),n=new ho(3,3),o=new ho(1,3),a=new ho(3,3),c=new ho(3,3),l=fo(t);go(t,l),uo(s,t),mo(n,s,s),wo(n,o,a,c);const h=new e(l[0],l[1],l[2]),d=new e(a.data[0],a.data[3],a.data[6]),u=new e(a.data[1],a.data[4],a.data[7]),m=new e(a.data[2],a.data[5],a.data[8]),p=d.clone().multiplyScalar(Math.sqrt(o.data[0]/r)),f=u.clone().multiplyScalar(Math.sqrt(o.data[1]/r)),g=m.clone().multiplyScalar(Math.sqrt(o.data[2]/r));this.begA=h.clone().sub(p),this.endA=h.clone().add(p),this.begB=h.clone().sub(f),this.endB=h.clone().add(f),this.begC=h.clone().sub(g),this.endC=h.clone().add(g),this.center=h,this.vecA=p,this.vecB=f,this.vecC=g,this.normVecA=d,this.normVecB=u,this.normVecC=m}getBasisMatrix(t=new i){const e=t;return e.makeBasis(this.normVecB,this.normVecA,this.normVecC),e.determinant()<0&&e.scale(fa),e}getRotationQuaternion(t=new r){const e=t;return e.setFromRotationMatrix(this.getBasisMatrix(ga)),e.inverse()}getProjectedScaleForAtoms(t){let i=-1/0,r=-1/0,s=-1/0,n=-1/0,o=-1/0,a=-1/0;const c=new e,l=new e,h=this.center,d=this.normVecA,u=this.normVecB,m=this.normVecC;return t.eachAtom((function(t){jr(c.copy(t),d,h);const e=l.subVectors(c,h).normalize().dot(d),p=c.distanceTo(h);e>0?p>i&&(i=p):p>r&&(r=p),jr(c.copy(t),u,h);const f=l.subVectors(c,h).normalize().dot(u),g=c.distanceTo(h);f>0?g>s&&(s=g):g>n&&(n=g),jr(c.copy(t),m,h);const y=l.subVectors(c,h).normalize().dot(m),b=c.distanceTo(h);y>0?b>o&&(o=b):b>a&&(a=b)})),{d1a:i,d2a:s,d3a:o,d1b:-r,d2b:-n,d3b:-a}}}class ba{constructor(t,e,i,r){this.volume=t,this.setFilter(e,i,r)}get header(){return this.volume.header}get matrix(){return this.volume.matrix}get normalMatrix(){return this.volume.normalMatrix}get inverseMatrix(){return this.volume.inverseMatrix}get center(){return this.volume.center}get boundingBox(){return this.volume.boundingBox}get min(){return this.volume.min}get max(){return this.volume.max}get mean(){return this.volume.mean}get rms(){return this.volume.rms}_getFilterHash(t,e,i){return JSON.stringify([t,e,i])}setFilter(t,e,i){isNaN(t)&&this.header&&(t=this.header.DMEAN+2*this.header.ARMS),t=void 0===t||isNaN(t)?-1/0:t,e=st(e,1/0),i=st(i,!1);const r=this.volume.data,s=this.volume.position,n=this.volume.atomindex,o=this._getFilterHash(t,e,i);if(o!==this._filterHash){if(t===-1/0&&e===1/0)this.data=r,this.position=s,this.atomindex=n;else{const o=r.length;this._dataBuffer||(this._dataBuffer=new ArrayBuffer(4*o),this._positionBuffer=new ArrayBuffer(3*o*4),n&&(this._atomindexBuffer=new ArrayBuffer(4*o)));const a=new Float32Array(this._dataBuffer),c=new Float32Array(this._positionBuffer);let l;n&&(l=new Uint32Array(this._atomindexBuffer));let h=0;for(let d=0;d<o;++d){const o=3*d,u=r[d];if(!i&&u>=t&&u<=e||i&&(u<t||u>e)){const t=3*h;a[h]=u,c[t+0]=s[o+0],c[t+1]=s[o+1],c[t+2]=s[o+2],n&&l&&(l[h]=n[d]),h+=1}}this.data=new Float32Array(this._dataBuffer,0,h),this.position=new Float32Array(this._positionBuffer,0,3*h),n&&(this.atomindex=new Int32Array(this._atomindexBuffer,0,h))}this._filterHash=o}}}ba.prototype.getValueForSigma=Eo.prototype.getValueForSigma,ba.prototype.getSigmaForValue=Eo.prototype.getSigmaForValue,ba.prototype.getDataAtomindex=Eo.prototype.getDataAtomindex,ba.prototype.getDataPosition=Eo.prototype.getDataPosition,ba.prototype.getDataColor=Eo.prototype.getDataColor,ba.prototype.getDataPicking=Eo.prototype.getDataPicking,ba.prototype.getDataSize=Eo.prototype.getDataSize;class xa{constructor(t,e){const i=Rs({nodeArray1:t.atomIndex1,nodeArray2:t.atomIndex2,edgeCount:t.count,nodeCount:e});this.countArray=i.countArray,this.offsetArray=i.offsetArray,this.indexArray=i.indexArray}}class va extends Bs{get _defaultFields(){return[["atomIndex1",1,"int32"],["atomIndex2",1,"int32"],["bondOrder",1,"int8"]]}addBond(t,e,i){this.growIfFull();const r=this.count,s=t.index,n=e.index;s<n?(this.atomIndex1[r]=s,this.atomIndex2[r]=n):(this.atomIndex2[r]=s,this.atomIndex1[r]=n),i&&(this.bondOrder[r]=i),this.count+=1}addBondIfConnected(t,e,i){return!!t.connectedTo(e)&&(this.addBond(t,e,i),!0)}}class wa extends Bs{get _defaultFields(){return[["residueIndex",1,"uint32"],["atomTypeId",1,"uint16"],["x",1,"float32"],["y",1,"float32"],["z",1,"float32"],["serial",1,"int32"],["bfactor",1,"float32"],["altloc",1,"uint8"],["occupancy",1,"float32"]]}setAltloc(t,e){this.altloc[t]=e.charCodeAt(0)}getAltloc(t){const e=this.altloc[t];return e?String.fromCharCode(e):""}}class Aa extends Bs{get _defaultFields(){return[["chainIndex",1,"uint32"],["atomOffset",1,"uint32"],["atomCount",1,"uint32"],["residueTypeId",1,"uint16"],["resno",1,"int32"],["sstruc",1,"uint8"],["inscode",1,"uint8"]]}setSstruc(t,e){this.sstruc[t]=e.charCodeAt(0)}getSstruc(t){const e=this.sstruc[t];return e?String.fromCharCode(e):""}setInscode(t,e){this.inscode[t]=e.charCodeAt(0)}getInscode(t){const e=this.inscode[t];return e?String.fromCharCode(e):""}}class _a extends Bs{get _defaultFields(){return[["entityIndex",1,"uint16"],["modelIndex",1,"uint16"],["residueOffset",1,"uint32"],["residueCount",1,"uint32"],["chainname",4,"uint8"],["chainid",4,"uint8"]]}setChainname(t,e){const i=4*t;this.chainname[i]=e.charCodeAt(0),this.chainname[i+1]=e.charCodeAt(1),this.chainname[i+2]=e.charCodeAt(2),this.chainname[i+3]=e.charCodeAt(3)}getChainname(t){let e="";for(let i=0;i<4;++i){const r=this.chainname[4*t+i];if(!r)break;e+=String.fromCharCode(r)}return e}setChainid(t,e){const i=4*t;this.chainid[i]=e.charCodeAt(0),this.chainid[i+1]=e.charCodeAt(1),this.chainid[i+2]=e.charCodeAt(2),this.chainid[i+3]=e.charCodeAt(3)}getChainid(t){let e="";for(let i=0;i<4;++i){const r=this.chainid[4*t+i];if(!r)break;e+=String.fromCharCode(r)}return e}}class Sa extends Bs{get _defaultFields(){return[["chainOffset",1,"uint32"],["chainCount",1,"uint32"]]}}class Ca{constructor(t){this.polymer=t,this.size=t.residueCount}getCenterIterator(t=0){const i=this.getPosition().center,r=i.length/3;let s=0,n=-1;const o=[new e,new e,new e,new e];return{size:r,next:function(){const t=this.get(n);return n+=1,t},get:function(e){e=Math.min(r-1,Math.max(0,e));const n=o[s%4],a=3*e;if(n.fromArray(i,a),t){const s=Math.min(t,e,r-e-1);for(let t=1;t<=s;++t){const e=3*t,r=(s+1-t)/(s+1);n.x+=r*i[a-e+0]+r*i[a+e+0],n.y+=r*i[a-e+1]+r*i[a+e+1],n.z+=r*i[a-e+2]+r*i[a+e+2]}n.x/=s+1,n.y/=s+1,n.z/=s+1}return s+=1,n},reset:function(){s=0,n=-1}}}getColor(t){const e=this.polymer,i=e.structure,r=e.residueCount,s=e.residueIndexStart,n=new Float32Array(3*r),o=t||{};o.structure=i;const a=Fe.getScheme(o),c=i.getResidueProxy(),l=i.getAtomProxy();for(let t=0;t<r;++t)c.index=s+t,l.index=c.traceAtomIndex,a.atomColorToArray(l,n,3*t);return{color:n}}getPicking(){const t=this.polymer,e=t.structure,i=t.residueCount,r=t.residueIndexStart,s=new Float32Array(i),n=e.getResidueProxy();for(let t=0;t<i;++t)n.index=r+t,s[t]=n.traceAtomIndex;return{picking:new Yn(s,e)}}getSize(t){const e=this.polymer,i=e.structure,r=e.residueCount,s=e.residueIndexStart,n=new Float32Array(r),o=new pa(t),a=i.getResidueProxy(),c=i.getAtomProxy();for(let t=0;t<r;++t)a.index=s+t,c.index=a.traceAtomIndex,n[t]=o.atomRadius(c);return{size:n}}getPosition(){const t=this.polymer,i=t.structure,r=t.residueCount,s=r-3,n=new Float32Array(3*r),o=new Float32Array(3*r),a=new Float32Array(r),c=new Float32Array(r),l=new Float32Array(r),h=new Float32Array(r),d=new Float32Array(3*r),u=new e,m=new e,p=new e,f=new e,g=new e,y=new e,b=new e,x=new e,v=new e,w=new e,A=new e,_=new e(0,0,0),S="trace",C=i.getAtomProxy(),P=i.getAtomProxy(t.getAtomIndexByType(0,S)),I=i.getAtomProxy(t.getAtomIndexByType(1,S)),k=i.getAtomProxy(t.getAtomIndexByType(2,S));for(let e=0;e<s;++e){C.index=P.index,P.index=I.index,I.index=k.index,k.index=t.getAtomIndexByType(e+3,S);const i=3*e;u.subVectors(P,C),m.subVectors(I,P),p.subVectors(k,I),f.subVectors(u,m),g.subVectors(m,p),v.crossVectors(f,g).normalize(),v.toArray(o,i),e>0&&(a[e]=v.angleTo(w));const r=Math.cos(f.angleTo(g));h[e]=180/Math.PI*Math.acos(r);const s=f.length(),x=g.length();c[e]=Math.sqrt(x*s)/Math.max(2,2*(1-r)),l[e]=Math.abs(m.dot(v)),y.copy(f).multiplyScalar(c[e]/s),b.copy(g).multiplyScalar(c[e]/x),y.subVectors(P,y),b.subVectors(I,b),y.toArray(n,i+3),b.toArray(n,i+6),A.subVectors(C,_),A.toArray(d,i),w.copy(v),_.copy(y)}y.fromArray(n,3),b.fromArray(n,6),v.subVectors(y,b).normalize(),C.index=t.getAtomIndexByType(0,S),_.copy(C),x.copy(C),jr(x,v,y),x.toArray(n,0),A.subVectors(_,y),A.toArray(d,0),y.fromArray(n,3*r-6),b.fromArray(n,3*r-9),v.subVectors(y,b).normalize(),C.index=t.getAtomIndexByType(r-1,S),_.copy(C),x.copy(C),jr(x,v,y),x.toArray(n,3*r-3);for(let e=r-3;e<r;++e)y.fromArray(n,3*e),C.index=t.getAtomIndexByType(e,S),_.copy(C),A.subVectors(_,y),A.toArray(d,3*e);const M=new Float32Array(r),T=new Float32Array(r),B=new Float32Array(r),D=new Float32Array(r);M[1]=c[0],T[1]=h[0],B[1]=c[0];for(let t=2;t<r-2;++t)M[t]=.5*(c[t-2]+c[t-1]),T[t]=.5*(h[t-2]+h[t-1]),B[t]=.5*(l[t-2]+l[t-1]),y.fromArray(o,3*(t-2)),b.fromArray(o,3*(t-1)),D[t]=180/Math.PI*Math.acos(Math.cos(y.angleTo(b)));M[r-2]=c[r-4],T[r-2]=h[r-4],B[r-2]=l[r-4];const $=new Float32Array(3*r);Mi(o,$,0,0,3),Mi(o,$,0,3,3);for(let t=2;t<r-2;++t)y.fromArray(o,3*(t-2)),b.fromArray(o,3*(t-1)),v.addVectors(b,y).multiplyScalar(.5).normalize(),v.toArray($,3*t);return Mi(o,$,3*r-12,3*r-6,3),Mi(o,$,3*r-12,3*r-3,3),{center:n,axis:$,bending:D,radius:M,rise:B,twist:T,resdir:d}}}class Pa{constructor(t){this.polymer=t,this.helixorient=new Ca(t),this.position=this.helixorient.getPosition()}getAxis(t,i,r,s,n){t=t||30,i=i||2.5,r=void 0!==r&&r;const o=this.polymer,a=o.structure,c=o.residueCount,l=o.residueIndexStart,h=this.position,d=s||{};d.structure=a;const u=Fe.getScheme(d),m=new pa(n);let p=0,f=0;const g=[],y=[],b=[],x=[],v=[],w=[],A=[],_=[],S=[];let C,P,I=new Float32Array(3*c),k=new Float32Array(3*c);const M=new e,T=new e,B=a.getResidueProxy(),D=a.getResidueProxy(),$=a.getAtomProxy(),O=new e,R=new e;let E=!1;for(let e=0;e<c;++e)if(B.index=l+e,O.fromArray(h.center,3*e),e===c-1?E=!0:(D.index=l+e+1,R.fromArray(h.center,3*e+3),(r&&B.sstruc!==D.sstruc||O.distanceTo(R)>i||h.bending[e]>t)&&(E=!0)),E){if(e-p<4){p=e,E=!1;continue}$.index=B.traceAtomIndex,I=h.axis.subarray(3*p+3,3*e),k=h.center.subarray(3*p,3*e+3),C=Ur(I).normalize(),P=Ur(k),M.fromArray(k),jr(M,C,P),T.fromArray(k,k.length-3),jr(T,C,P),C.subVectors(T,M),C.toArray(g,f),P.toArray(y,f),M.toArray(b,f),T.toArray(x,f),u.atomColorToArray($,v,f),w.push($.index),A.push(m.atomRadius($)),_.push(l+p),S.push(l+e+1-p),f+=3,p=e,E=!1}const F=new Float32Array(w);return{axis:new Float32Array(g),center:new Float32Array(y),begin:new Float32Array(b),end:new Float32Array(x),color:new Float32Array(v),picking:new Yn(F,a),size:new Float32Array(A),residueOffset:_,residueCount:S}}}class Ia{constructor(t){this.scoreFunction=t,this.content=[],this.scoreFunction=t}push(t){this.content.push(t),this.bubbleUp(this.content.length-1)}pop(){const t=this.content[0],e=this.content.pop();return e&&this.content.length>0&&(this.content[0]=e,this.sinkDown(0)),t}peek(){return this.content[0]}remove(t){const e=this.content.length;for(let i=0;i<e;i++)if(this.content[i]===t){const r=this.content.pop();return void(r&&i!==e-1&&(this.content[i]=r,this.scoreFunction(r)<this.scoreFunction(t)?this.bubbleUp(i):this.sinkDown(i)))}throw new Error("Node not found.")}size(){return this.content.length}bubbleUp(t){const e=this.content[t];for(;t>0;){const i=Math.floor((t+1)/2)-1,r=this.content[i];if(!(this.scoreFunction(e)<this.scoreFunction(r)))break;this.content[i]=e,this.content[t]=r,t=i}}sinkDown(t){const e=this.content.length,i=this.content[t],r=this.scoreFunction(i);let s=0,n=0;for(;;){const o=2*(t+1),a=o-1;let c=null;if(a<e){const t=this.content[a];s=this.scoreFunction(t),s<r&&(c=a)}if(o<e){const t=this.content[o];n=this.scoreFunction(t),n<(null===c?r:s)&&(c=o)}if(null===c)break;this.content[t]=this.content[c],this.content[c]=i,t=c}}}
/**
 * Kdtree
 * @class
 * @author Alexander Rose <alexander.rose@weirdbyte.de>, 2016
 * @author Roman Bolzern <roman.bolzern@fhnw.ch>, 2013
 * @author I4DS http://www.fhnw.ch/i4ds, 2013
 * @license MIT License <http://www.opensource.org/licenses/mit-license.php>
 * @description
 * k-d Tree for typed arrays of 3d points (e.g. for Float32Array), in-place
 * provides fast nearest neighbour search
 *
 * Based on https://github.com/ubilabs/kd-tree-javascript by Ubilabs
 *
 * Further information (including mathematical properties)
 * http://en.wikipedia.org/wiki/Binary_tree
 * http://en.wikipedia.org/wiki/K-d_tree
 *
 * @example
 * points: [x, y, z, x, y, z, x, y, z, ...]
 * metric: function(a, b){
 *    return Math.pow(a[0]-b[0], 2) + Math.pow(a[1]-b[1], 2) + Math.pow(a[2]-b[2], 2);
 * }
 *
 * @param {Float32Array} points - points
 * @param {Function} metric - metric
 */class ka{constructor(t,e){this.points=t,this.metric=e,this.maxDepth=0,this.currentNode=0;const i=t.length/3,r=new Uint32Array(i);for(let t=0;t<i;++t)r[t]=t;this.indices=r,this.nodes=new Int32Array(4*i),this.rootIndex=this.buildTree(0,-1,0,i)}buildTree(t,e,i,r){t>this.maxDepth&&(this.maxDepth=t);const s=r-i;if(0===s)return-1;const n=4*this.currentNode,o=this.nodes;if(this.currentNode+=1,1===s)return o[n]=i,o[n+1]=-1,o[n+2]=-1,o[n+3]=e,n;const a=this.indices,c=this.points,l=i+Math.floor(s/2),h=t%3;let d,u,m,p,f,g=i,y=r-1;for(;y>g;){for(m=g+y>>1,p=c[3*a[m]+h],u=a[m],a[m]=a[y],a[y]=u,f=g,d=g;d<y;++d)c[3*a[d]+h]<p&&(u=a[f],a[f]=a[d],a[d]=u,++f);if(u=a[y],a[y]=a[f],a[f]=u,m=f,l===m)break;l<m?y=m-1:g=m+1}return o[n]=l,o[n+1]=this.buildTree(t+1,n,i,l),o[n+2]=this.buildTree(t+1,n,l+1,r),o[n+3]=e,n}getNodeDepth(t){const e=this.nodes[t+3];return-1===e?0:this.getNodeDepth(e)+1}nearest(t,e,i){const r=new Ia((t=>-t[1])),s=this.nodes,n=this.points,o=this.indices,a=c=>{let l,h;const d=this.getNodeDepth(c)%3,u=3*o[s[c]],m=[n[u+0],n[u+1],n[u+2]],p=this.metric(t,m);function f(t,i){r.push([t,i]),r.size()>e&&r.pop()}const g=s[c+1],y=s[c+2];if(-1===y&&-1===g)return void((r.size()<e||p<r.peek()[1])&&p<=i&&f(c,p));l=-1===y?g:-1===g?y:t[d]<=n[u+d]?g:y,a(l),(r.size()<e||p<r.peek()[1])&&p<=i&&f(c,p);const b=[];for(let e=0;e<3;e+=1)b[e]=e===d?t[e]:n[u+e];const x=this.metric(b,m);(r.size()<e||Math.abs(x)<r.peek()[1])&&Math.abs(x)<=i&&(h=l===g?y:g,-1!==h&&a(h))};a(this.rootIndex);const c=[];for(let t=0,i=Math.min(r.size(),e);t<i;t+=1)c.push(r.content[t]);return c}verify(t,e=0){let i=1;if(void 0===t&&(t=this.rootIndex),-1===t)throw new Error("node is null");const r=e%3,s=this.nodes,n=this.points,o=this.indices,a=s[t+1],c=s[t+2];if(-1!==a){if(n[3*o[s[a]]+r]>n[3*o[s[t]]+r])throw new Error("left child is > parent!");i+=this.verify(a,e+1)}if(-1!==c){if(n[3*o[s[c]]+r]<n[3*o[s[t]]+r])throw new Error("right child is < parent!");i+=this.verify(c,e+1)}return i}}class Ma{constructor(t,e=0){this.structure=t,this.index=e,this.chainStore=t.chainStore,this.residueStore=t.residueStore,this.atomStore=t.atomStore,this.residueMap=t.residueMap,this.atomMap=t.atomMap}get bondHash(){return this.structure.bondHash}get entity(){return this.structure.entityList[this.entityIndex]}get entityIndex(){return this.chainStore.entityIndex[this.chainIndex]}get modelIndex(){return this.chainStore.modelIndex[this.chainIndex]}get chainIndex(){return this.residueStore.chainIndex[this.residueIndex]}get residue(){return console.warn("residue - might be expensive"),this.structure.getResidueProxy(this.residueIndex)}get residueIndex(){return this.atomStore.residueIndex[this.index]}set residueIndex(t){this.atomStore.residueIndex[this.index]=t}get sstruc(){return this.residueStore.getSstruc(this.residueIndex)}get inscode(){return this.residueStore.getInscode(this.residueIndex)}get resno(){return this.residueStore.resno[this.residueIndex]}get chainname(){return this.chainStore.getChainname(this.chainIndex)}get chainid(){return this.chainStore.getChainid(this.chainIndex)}get residueType(){return this.residueMap.get(this.residueStore.residueTypeId[this.residueIndex])}get atomType(){return this.atomMap.get(this.atomStore.atomTypeId[this.index])}get residueAtomOffset(){return this.residueStore.atomOffset[this.residueIndex]}get resname(){return this.residueType.resname}get hetero(){return this.residueType.hetero}get atomname(){return this.atomType.atomname}get number(){return this.atomType.number}get element(){return this.atomType.element}get vdw(){return this.atomType.vdw}get covalent(){return this.atomType.covalent}get x(){return this.atomStore.x[this.index]}set x(t){this.atomStore.x[this.index]=t}get y(){return this.atomStore.y[this.index]}set y(t){this.atomStore.y[this.index]=t}get z(){return this.atomStore.z[this.index]}set z(t){this.atomStore.z[this.index]=t}get serial(){return this.atomStore.serial[this.index]}set serial(t){this.atomStore.serial[this.index]=t}get bfactor(){return this.atomStore.bfactor[this.index]}set bfactor(t){this.atomStore.bfactor[this.index]=t}get occupancy(){return this.atomStore.occupancy[this.index]}set occupancy(t){this.atomStore.occupancy[this.index]=t}get altloc(){return this.atomStore.getAltloc(this.index)}set altloc(t){this.atomStore.setAltloc(this.index,t)}get partialCharge(){return this.atomStore.partialCharge?this.atomStore.partialCharge[this.index]:null}set partialCharge(t){this.atomStore.partialCharge&&(this.atomStore.partialCharge[this.index]=t)}get radius(){return this.atomStore.radius?this.atomStore.radius[this.index]:null}set radius(t){this.atomStore.radius&&(this.atomStore.radius[this.index]=t)}get formalCharge(){return this.atomStore.formalCharge?this.atomStore.formalCharge[this.index]:null}set formalCharge(t){this.atomStore.formalCharge&&(this.atomStore.formalCharge[this.index]=t)}get aromatic(){return this.atomStore.aromatic?this.atomStore.aromatic[this.index]:this.residueType.isAromatic(this)?1:0}set aromatic(t){this.atomStore.aromatic&&(this.atomStore.aromatic[this.index]=t)}get bondCount(){return this.bondHash.countArray[this.index]}eachBond(t,e){e=e||this.structure._bp;const i=this.index,r=this.bondHash,s=r.indexArray,n=r.countArray[i],o=r.offsetArray[i];for(let i=0;i<n;++i)e.index=s[o+i],t(e)}eachBondedAtom(t,e){const i=e||this.structure._ap,r=this.index;this.eachBond((function(e){i.index=r!==e.atomIndex1?e.atomIndex1:e.atomIndex2,t(i)})),this.index=r}hasBondTo(t){let e=!1;return this.eachBondedAtom((function(i){t.index===i.index&&(e=!0)})),e}bondToElementCount(t){let e=0;const i=this.index;return this.eachBondedAtom((function(i){i.number===t&&(e+=1)})),this.index=i,e}hasBondToElement(t){return this.bondToElementCount(t)>0}isBackbone(){const t=this.residueType.backboneIndexList;return t.length>0&&t.includes(this.index-this.residueAtomOffset)}isPolymer(){if(this.structure.entityList.length>0)return this.entity.isPolymer();{const t=this.residueType.moleculeType;return 3===t||4===t||5===t}}isSidechain(){return this.isPolymer()&&!this.isBackbone()}isCg(){const t=this.residueType.backboneType;return 4===t||5===t||6===t}isTrace(){return this.index===this.residueType.traceAtomIndex+this.residueAtomOffset}isHetero(){return 1===this.residueType.hetero}isProtein(){return 3===this.residueType.moleculeType}isNucleic(){const t=this.residueType.moleculeType;return 4===t||5===t}isRna(){return 4===this.residueType.moleculeType}isDna(){return 5===this.residueType.moleculeType}isWater(){return 1===this.residueType.moleculeType}isIon(){return 2===this.residueType.moleculeType}isSaccharide(){return 6===this.residueType.moleculeType}isHelix(){return Hs.includes(this.sstruc)}isSheet(){return Ws.includes(this.sstruc)}isTurn(){return qs.includes(this.sstruc)&&this.isProtein()}isBonded(){return 0!==this.bondHash.countArray[this.index]}isRing(){return void 0!==this.residueType.getRings().atomRings[this.index-this.residueAtomOffset]}isAromatic(){return 1===this.aromatic}isPolarHydrogen(){let t=!1;return 1!==this.number||(t=!this.hasBondToElement(6)),t}isMetal(){return this.atomType.isMetal()}isNonmetal(){return this.atomType.isNonmetal()}isMetalloid(){return this.atomType.isMetalloid()}isHalogen(){return this.atomType.isHalogen()}isDiatomicNonmetal(){return this.atomType.isDiatomicNonmetal()}isPolyatomicNonmetal(){return this.atomType.isPolyatomicNonmetal()}isAlkaliMetal(){return this.atomType.isAlkaliMetal()}isAlkalineEarthMetal(){return this.atomType.isAlkalineEarthMetal()}isNobleGas(){return this.atomType.isNobleGas()}isTransitionMetal(){return this.atomType.isTransitionMetal()}isPostTransitionMetal(){return this.atomType.isPostTransitionMetal()}isLanthanide(){return this.atomType.isLanthanide()}isActinide(){return this.atomType.isActinide()}getDefaultValence(){return this.atomType.getDefaultValence()}getValenceList(){return this.atomType.getValenceList()}getOuterShellElectronCount(){return this.atomType.getOuterShellElectronCount()}distanceTo(t){const e=this.atomStore,i=t.atomStore,r=this.index,s=t.index,n=e.x[r]-i.x[s],o=e.y[r]-i.y[s],a=e.z[r]-i.z[s],c=n*n+o*o+a*a;return Math.sqrt(c)}connectedTo(t){const e=this.atomStore,i=t.atomStore,r=this.index,s=t.index;if(e.altloc&&i.altloc){const t=e.altloc[r],n=i.altloc[s];if(0!==t&&0!==n&&32!==t&&32!==n&&t!==n)return!1}const n=e.x[r]-i.x[s],o=e.y[r]-i.y[s],a=e.z[r]-i.z[s],c=n*n+o*o+a*a;if(c<48&&this.isCg())return!0;if(isNaN(c))return!1;const l=this.covalent+t.covalent,h=l+.3,d=l-.5;return c<h*h&&c>d*d}positionFromArray(t,e=0){return this.x=t[e+0],this.y=t[e+1],this.z=t[e+2],this}positionToArray(t=[],e=0){const i=this.index,r=this.atomStore;return t[e+0]=r.x[i],t[e+1]=r.y[i],t[e+2]=r.z[i],t}positionToVector3(t){return void 0===t&&(t=new e),t.x=this.x,t.y=this.y,t.z=this.z,t}positionFromVector3(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}positionAdd(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}positionSub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}getResidueBonds(t=!1){const e=this.residueAtomOffset,i=this.index-this.residueAtomOffset,r=this.residueType.getBonds(),s=r.atomIndices1,n=r.atomIndices2;let o,a,c,l;for(t||(l=[]),o=s.indexOf(i);-1!==o;){if(c=n[o]+e,!l)return c;l.push(c),o=s.indexOf(i,o+1)}for(a=n.indexOf(i);-1!==a;){if(c=s[a]+e,!l)return c;l.push(c),a=n.indexOf(i,a+1)}return l}qualifiedName(t=!1){var e="";return this.resname&&!t&&(e+="["+this.resname+"]"),void 0!==this.resno&&(e+=this.resno),this.inscode&&(e+="^"+this.inscode),this.chainname&&(e+=":"+this.chainname),this.atomname&&(e+="."+this.atomname),this.altloc&&(e+="%"+this.altloc),this.structure.modelStore.count>1&&(e+="/"+this.modelIndex),e}clone(){return new Ma(this.structure,this.index)}toObject(){return{index:this.index,residueIndex:this.residueIndex,resname:this.resname,x:this.x,y:this.y,z:this.z,element:this.element,chainname:this.chainname,resno:this.resno,serial:this.serial,vdw:this.vdw,covalent:this.covalent,hetero:this.hetero,bfactor:this.bfactor,altloc:this.altloc,atomname:this.atomname,modelIndex:this.modelIndex}}}function Ta(t,e){const i=t[0]-e[0],r=t[1]-e[1],s=t[2]-e[2];return i*i+r*r+s*s}function Ba(t,e){return Math.sqrt(Ta(t,e))}const Da=new Float32Array(3);class $a{constructor(t,e=!1){De&&Me.time("Kdtree build");const i=e?Ta:Ba,r=new Float32Array(3*t.atomCount),s=new Uint32Array(t.atomCount);let n=0;t.eachAtom((function(t){r[n+0]=t.x,r[n+1]=t.y,r[n+2]=t.z,s[n/3]=t.index,n+=3})),this.atomIndices=s,this.points=r,this.kdtree=new ka(r,i),De&&Me.timeEnd("Kdtree build")}nearest(t,i,r){t instanceof e?t.toArray(Da):t instanceof Ma&&t.positionToArray(Da);const s=this.kdtree.nearest(Da,i,r),n=this.kdtree.indices,o=this.kdtree.nodes,a=this.atomIndices,c=[];for(let t=0,e=s.length;t<e;++t){const e=s[t],i=e[0],r=e[1];c.push({index:a[n[o[i]]],distance:r})}return c}}const Oa={" ":"X","!":"Y","#":"Z",$:"-X","%":"-Y","&":"-Z","'":"Y+1/2","(":"1/2+X",")":"1/2+Y","*":"1/2-X","+":"1/2+Z",",":"1/2-Y","-":"1/2-Z",".":"X+1/2","/":"Z+1/2",0:"-X+1/2",1:"-Y+1/2",2:"-Z+1/2",3:"1/4+X",4:"1/4-Y",5:"1/4+Z",6:"1/4-X",7:"1/4+Y",8:"3/4-Y",9:"3/4+Z",":":"3/4+Y",";":"3/4+X","<":"3/4-X","=":"1/4-Z",">":"3/4-Z","?":"X-Y","@":"Y-X",A:"Z+1/3",B:"Z+2/3",C:"X+2/3",D:"Y+1/3",E:"-Y+2/3",F:"X-Y+1/3",G:"Y-X+2/3",H:"-X+1/3",I:"X+1/3",J:"Y+2/3",K:"-Y+1/3",L:"X-Y+2/3",M:"Y-X+1/3",N:"-X+2/3",O:"2/3+X",P:"1/3+Y",Q:"1/3+Z",R:"2/3-Y",S:"1/3+X-Y",T:"2/3+Y-X",U:"1/3-X",V:"2/3-X",W:"1/3-Y",X:"1/3-Z",Y:"2/3+Y",Z:"1/3+Y-X","[":"2/3+X-Y","]":"1/3+X","^":"2/3+Z",_:"2/3-Z","`":"5/6+Z",a:"1/6+Z",b:"5/6-Z",c:"1/6-Z",d:"Z+5/6",e:"Z+1/6",f:"Z+1/4",g:"+Y"},Ra={"P 1":" !#","P -1":" !#$%&","P 1 2 1":" !#$!&","P 1 21 1":" !#$'&","C 1 2 1":" !#$!&()#*)&","P 1 m 1":" !# %#","P 1 c 1":" !# %+","C 1 m 1":" !# %#()#(,#","C 1 c 1":" !# %+()#(,+","P 1 2/m 1":" !# %#$!&$%&","P 1 21/m 1":" !#$)&$%& ,#","C 1 2/m 1":" !# %#$!&$%&()#(,#*)&*,&","P 1 2/c 1":" !#$!-$%& %+","P 1 21/c 1":" !#$%&$)- ,+","C 1 2/c 1":" !#$!-$%& %+()#*)-*,&(,+","P 2 2 2":" !#$%#$!& %&","P 2 2 21":" !#$%+$!- %&","P 21 21 2":" !#$%#*)&(,&","P 21 21 21":" !#*%+$)-(,&","C 2 2 21":" !#$%+$!- %&()#*,+*)-(,&","C 2 2 2":" !#$%#$!& %&()#*,#*)&(,&","F 2 2 2":" !#$%#$!& %& )+$,+$)- ,-(!+*%+*!-(%-()#*,#*)&(,&","I 2 2 2":" !#$%# %&$!&.'/01/.120'2","I 21 21 21":" !#*%+$)-(,&()+$,#*!& %-","P m m 2":" !#$%# %#$!#","P m c 21":" !#$%+ %+$!#","P c c 2":" !#$%# %+$!+","P m a 2":" !#$%#(%#*!#","P c a 21":" !#$%+(%#*!+","P n c 2":" !#$%# ,+$)+","P m n 21":" !#*%+(%+$!#","P b a 2":" !#$%#(,#*)#","P n a 21":" !#$%+(,#*)+","P n n 2":" !#$%#(,+*)+","C m m 2":" !#$%# %#$!#()#*,#(,#*)#","C m c 21":" !#$%+ %+$!#()#*,+(,+*)#","C c c 2":" !#$%# %+$!+()#*,#(,+*)+","A m m 2":" !#$%# %#$!# )+$,+ ,+$)+","A b m 2":" !#$%# ,#$)# )+$,+ %+$!+","A m a 2":" !#$%#(%#*!# )+$,+(,+*)+","A b a 2":" !#$%#(,#*)# )+$,+(%+*!+","F m m 2":" !#$%# %#$!# )+$,+ ,+$)+(!+*%+(%+*!+()#*,#(,#*)#","F d d 2":" !#$%#345675 )+$,+3896:9(!+*%+;49<79()#*,#;85<:5","I m m 2":" !#$%# %#$!#()+*,+(,+*)+","I b a 2":" !#$%#(,#*)#()+*,+ %+$!+","I m a 2":" !#$%#(%#*!#()+*,+ ,+$)+","P 2/m 2/m 2/m":" !#$%#$!& %&$%& !& %#$!#","P 2/n 2/n 2/n":" !#$%#$!& %&*,-()-(,+*)+","P 2/c 2/c 2/m":" !#$%#$!- %-$%& !& %+$!+","P 2/b 2/a 2/n":" !#$%#$!& %&*,&()&(,#*)#","P 21/m 2/m 2/a":" !#*%#$!&(%&$%&(!& %#*!#","P 2/n 21/n 2/a":" !#*%#*)- ,-$%&(!&(,+$)+","P 2/m 2/n 21/a":" !#*%+*!- %&$%&(!-(%+$!#","P 21/c 2/c 2/a":" !#*%#$!-(%-$%&(!& %+*!+","P 21/b 21/a 2/m":" !#$%#*)&(,&$%& !&(,#*)#","P 21/c 21/c 2/n":" !#*,#$)-(%-$%&()& ,+*!+","P 2/b 21/c 21/m":" !#$%+$)- ,&$%& !- ,+$)#","P 21/n 21/n 2/m":" !#$%#*)-(,-$%& !&(,+*)+","P 21/m 21/m 2/n":" !#$%#*'&.,&*,&.'& %#$!#","P 21/b 2/c 21/n":" !#*,+$!-(,&$%&()- %+*)#","P 21/b 21/c 21/a":" !#*%+$)-(,&$%&(!- ,+*)#","P 21/n 21/m 21/a":" !#0%/$'&.12$%&.!2 1#0'/","C 2/m 2/c 21/m":" !#$%+$!- %&$%& !- %+$!#()#*,+*)-(,&*,&()-(,+*)#","C 2/m 2/c 21/a":" !#$,+$)- %&$%& )- ,+$!#()#*%+*!-(,&*,&(!-(%+*)#","C 2/m 2/m 2/m":" !#$%#$!& %&$%& !& %#$!#()#*,#*)&(,&*,&()&(,#*)#","C 2/c 2/c 2/m":" !#$%#$!- %-$%& !& %+$!+()#*,#*)-(,-*,&()&(,+*)+","C 2/m 2/m 2/a":" !#$,#$)& %&$%& )& ,#$!#()#*%#*!&(,&*,&(!&(%#*)#","C 2/c 2/c 2/a":" !#*,#$!&(,&$,-(!- ,+*!+()#$%#*)& %&*%- )-(%+$)+","F 2/m 2/m 2/m":" !#$%#$!& %&$%& !& %#$!# )+$,+$)- ,-$,- )- ,+$)+(!+*%+*!-(%-*%-(!-(%+*!+()#*,#*)&(,&*,&()&(,#*)#","F 2/d 2/d 2/d":" !#$%#$!& %&64=37=345675 )+$,+$)- ,-68>3:>3896:9(!+*%+*!-(%-<4>;7>;49<79()#*,#*)&(,&<8=;:=;85<:5","I 2/m 2/m 2/m":" !#$%#$!& %&$%& !& %#$!#()+*,+*)-(,-*,-()-(,+*)+","I 2/b 2/a 2/m":" !#$%#*)&(,&$%& !&(,#*)#()+*,+$!- %-*,-()- %+$!+","I 21/b 21/c 21/a":" !#*%+$)-(,&$%&(!- ,+*)#()+$,#*!& %-*,- )&(%#$!+","I 21/m 21/m 21/a":" !#$,#$)& %&$%& )& ,#$!#()+*%+*!-(,-*,-(!-(%+*)+","P 4":" !#$%#% #!$#","P 41":" !#$%+% 5!$9","P 42":" !#$%#% +!$+","P 43":" !#$%+% 9!$5","I 4":" !#$%#% #!$#()+*,+,(+)*+","I 41":" !#*,+%(5)$9()+$%#, 9!*5","P -4":" !#$%#!$&% &","I -4":" !#$%#!$&% &()+*,+)*-,(-","P 4/m":" !#$%#% #!$#$%& !&!$&% &","P 42/m":" !#$%#% +!$+$%& !&!$-% -","P 4/n":" !#$%#,(#)*#*,&()&!$&% &","P 42/n":" !#$%#,(+)*+*,-()-!$&% &","I 4/m":" !#$%#% #!$#$%& !&!$&% &()+*,+,(+)*+*,-()-)*-,(-","I 41/a":" !#*,+%(5)$9$,=(!>!$&,(-()+$%#, 9!*5*%> )=)*-% &","P 4 2 2":" !#$%#% #!$#$!& %&! &%$&","P 4 21 2":" !#$%#,(#)*#*)&(,&! &%$&","P 41 2 2":" !#$%+% 5!$9$!& %-! >%$=","P 41 21 2":" !#$%+,(5)*9*)=(,>! &%$-","P 42 2 2":" !#$%#% +!$+$!& %&! -%$-","P 42 21 2":" !#$%#,(+)*+*)-(,-! &%$&","P 43 2 2":" !#$%+% 9!$5$!& %-! =%$>","P 43 21 2":" !#$%+,(9)*5*)>(,=! &%$-","I 4 2 2":" !#$%#% #!$#$!& %&! &%$&()+*,+,(+)*+*)-(,-)(-,*-","I 41 2 2":" !#*,+%(5)$9*!> ,=)(-%$&()+$%#, 9!*5$)=(%>! &,*-","P 4 m m":" !#$%#% #!$# %#$!#%$#! #","P 4 b m":" !#$%#% #!$#(,#*)#,*#)(#","P 42 c m":" !#$%#% +!$+ %+$!+%$#! #","P 42 n m":" !#$%#,(+)*+(,+*)+%$#! #","P 4 c c":" !#$%#% #!$# %+$!+%$+! +","P 4 n c":" !#$%#% #!$#(,+*)+,*+)(+","P 42 m c":" !#$%#% +!$+ %#$!#%$+! +","P 42 b c":" !#$%#% +!$+(,#*)#,*+)(+","I 4 m m":" !#$%#% #!$# %#$!#%$#! #()+*,+,(+)*+(,+*)+,*+)(+","I 4 c m":" !#$%#% #!$# %+$!+%$+! +()+*,+,(+)*+(,#*)#,*#)(#","I 41 m d":" !#*,+%(5)$9 %#*)+%*5) 9()+$%#, 9!*5(,+$!#,$9!(5","I 41 c d":" !#*,+%(5)$9 %+*)#%*9) 5()+$%#, 9!*5(,#$!+,$5!(9","P -4 2 m":" !#$%#% &!$&$!& %&%$#! #","P -4 2 c":" !#$%#% &!$&$!- %-%$+! +","P -4 21 m":" !#$%#% &!$&*)&(,&,*#)(#","P -4 21 c":" !#$%#% &!$&*)-(,-,*+)(+","P -4 m 2":" !#$%#!$&% & %#$!#! &%$&","P -4 c 2":" !#$%#% &!$& %+$!+! -%$-","P -4 b 2":" !#$%#% &!$&(,#*)#)(&,*&","P -4 n 2":" !#$%#% &!$&(,+*)+)(-,*-","I -4 m 2":" !#$%#% &!$& %#$!#! &%$&()+*,+,(-)*-(,+*)+)(-,*-","I -4 c 2":" !#$%#% &!$& %+$!+! -%$-()+*,+,(-)*-(,#*)#)(&,*&","I -4 2 m":" !#$%#% &!$&$!& %&%$#! #()+*,+,(-)*-*)-(,-,*+)(+","I -4 2 d":" !#$%#% &!$&*!>(%>,$9) 9()+*,+,(-)*-$)= ,=%*5!(5","P 4/m 2/m 2/m":" !#$%#% #!$#$!& %&! &%$&$%& !&!$&% & %#$!#%$#! #","P 4/m 2/c 2/c":" !#$%#% #!$#$!- %-! -%$-$%& !&!$&% & %+$!+%$+! +","P 4/n 2/b 2/m":" !#$%#% #!$#$!& %&! &%$&*,&()&)*&,(&(,#*)#,*#)(#","P 4/n 2/n 2/c":" !#$%#% #!$#$!& %&! &%$&*,-()-)*-,(-(,+*)+,*+)(+","P 4/m 21/b 2/m":" !#$%#% #!$#*)&(,&)(&,*&$%& !&!$&% &(,#*)#,*#)(#","P 4/m 21/n 2/c":" !#$%#% #!$#*)-(,-)(-,*-$%& !&!$&% &(,+*)+,*+)(+","P 4/n 21/m 2/m":" !#$%#,(#)*#*)&(,&! &%$&*,&()&!$&% & %#$!#,*#)(#","P 4/n 2/c 2/c":" !#$%#,(#)*#*)-(,-! -%$-*,&()&!$&% & %+$!+,*+)(+","P 42/m 2/m 2/c":" !#$%#% +!$+$!& %&! -%$-$%& !&!$-% - %#$!#%$+! +","P 42/m 2/c 2/m":" !#$%#% +!$+$!- %-! &%$&$%& !&!$-% - %+$!+%$#! #","P 42/n 2/b 2/c":" !#$%#,(+)*+$!- %-)(&,*&*,-()-!$&% &(,#*)#%$+! +","P 42/n 2/n 2/m":" !#$%#,(+)*+$!& %&)(-,*-*,-()-!$&% &(,+*)+%$#! #","P 42/m 21/b 2/c":" !#$%#% +!$+*)&(,&)(-,*-$%& !&!$-% -(,#*)#,*+)(+","P 42/m 21/n 2/m":" !#$%#,./'*/*'-.,-! &%$&$%& !&'*-,.-.,/*'/%$#! #","P 42/n 21/m 2/c":" !#$%#,(+)*+*)-(,-! &%$&*,-()-!$&% & %#$!#,*+)(+","P 42/n 21/c 2/m":" !#$%#,(+)*+*)&(,&! -%$-*,-()-!$&% & %+$!+,*#)(#","I 4/m 2/m 2/m":" !#$%#% #!$#$!& %&! &%$&$%& !&!$&% & %#$!#%$#! #()+*,+,(+)*+*)-(,-)(-,*-*,-()-)*-,(-(,+*)+,*+)(+","I 4/m 2/c 2/m":" !#$%#% #!$#$!- %-! -%$-$%& !&!$&% & %+$!+%$+! +()+*,+,(+)*+*)&(,&)(&,*&*,-()-)*-,(-(,#*)#,*#)(#","I 41/a 2/m 2/d":" !#*,+%(5)$9*!> ,=)(-%$&$,=(!>!$&,(-(,+$!#,$9!(5()+$%#, 9!*5$)=(%>! &,*-*%> )=)*-% & %#*)+%*5) 9","I 41/a 2/c 2/d":" !#*,+%(5)$9*!= ,>)(&%$-$,=(!>!$&,(-(,#$!+,$5!(9()+$%#, 9!*5$)>(%=! -,*&*%> )=)*-% & %+*)#%*9) 5","P 3":" !#%?#@$#","P 31":" !#%?A@$B","P 32":" !#%?B@$A","H 3":" !#%?#@$#CDAEFAGHAIJBKLBMNB","R 3":" !## !!# ","P -3":" !#%?#@$#$%&!@&? &","H -3":" !#%?#@$#$%&!@&? &OPQRSQTUQVWXYZX[]X]Y^W[^ZV^UR_PT_SO_","R -3":" !## !!# $%&&$%%&$","P 3 1 2":" !#%?#@$#%$&@!& ?&","P 3 2 1":" !#%?#@$#! &?%&$@&","P 31 1 2":" !#%?Q@$^%$_@!X ?&","P 31 2 1":" !#%?A@$B! &?%_$@X","P 32 1 2":" !#%?^@$Q%$X@!_ ?&","P 32 2 1":" !#%?B@$A! &?%X$@_","H 3 2":" !#%?#@$#! &?%&$@&OPQRSQTUQY]X[WXVZX]Y^W[^ZV^PO_SR_UT_","R 3 2":" !## !!# %$&$&%&%$","P 3 m 1":" !#%?#@$#%$#@!# ?#","P 3 1 m":" !#%?#@$#! #?%#$@#","P 3 c 1":" !#%?#@$#%$+@!+ ?+","P 3 1 c":" !#%?#@$#! +?%+$@+","H 3 m":" !#%?#@$#%$#@!# ?#OPQRSQTUQRUQTPQOSQ]Y^W[^ZV^WV^ZY^][^","R 3 m":" !## !!# ! # #!#! ","H 3 c":" !#%?#@$#%$+@!+ ?+OPQRSQTUQRU`TP`OS`]Y^W[^ZV^WVaZYa][a","R 3 c":" !## !!# '././'/'.","P -3 1 2/m":" !#%?#@$#%$&@!& ?&$%&!@&? &! #?%#$@#","P -3 1 2/c":" !#%?#@$#%$-@!- ?-$%&!@&? &! +?%+$@+","P -3 2/m 1":" !#%?#@$#! &?%&$@&$%&!@&? &%$#@!# ?#","P -3 2/c 1":" !#%?#@$#! -?%-$@-$%&!@&? &%$+@!+ ?+","H -3 2/m":" !#%?#@$#! &?%&$@&$%&!@&? &%$#@!# ?#OPQRSQTUQY]X[WXVZXVWXYZX[]XRUQTPQOSQ]Y^W[^ZV^PO_SR_UT_UR_PT_SO_WV^ZY^][^","R -3 2/m":" !## !!# %$&$&%&%$$%&&$%%&$! # #!#! ","H -3 2/c":" !#%?#@$#! -?%-$@-$%&!@&? &%$+@!+ ?+OPQRSQTUQY]b[WbVZbVWXYZX[]XRU`TP`OS`]Y^W[^ZV^POcSRcUTcUR_PT_SO_WVaZYa][a","R -3 2/c":" !## !!# 102021210$%&&$%%&$'././'/'.","P 6":" !#%?#@$#$%#!@#? #","P 61":" !#%?A@$B$%/!@d? e","P 65":" !#%?B@$A$%/!@e? d","P 62":" !#%?^@$Q$%#!@^? Q","P 64":" !#%?Q@$^$%#!@Q? ^","P 63":" !#%?#@$#$%+!@+? +","P -6":" !#%?#@$# !&%?&@$&","P 6/m":" !#%?#@$#$%#!@#? #$%&!@&? & !&%?&@$&","P 63/m":" !#%?#@$#$%+!@+? +$%&!@&? & !-%?-@$-","P 6 2 2":" !#%?#@$#$%#!@#? #! &?%&$@&%$&@!& ?&","P 61 2 2":" !#%?Q@$^$%+!@`? a! X?%&$@_%$b@!- ?c","P 65 2 2":" !#%?^@$Q$%+!@a? `! _?%&$@X%$c@!- ?b","P 62 2 2":" !#%?^@$Q$%#!@^? Q! _?%&$@X%$_@!& ?X","P 64 2 2":" !#%?Q@$^$%#!@Q? ^! X?%&$@_%$X@!& ?_","P 63 2 2":" !#%?#@$#$%+!@+? +! &?%&$@&%$-@!- ?-","P 6 m m":" !#%?#@$#$%#!@#? #%$#@!# ?#! #?%#$@#","P 6 c c":" !#%?#@$#$%#!@#? #%$+@!+ ?+! +?%+$@+","P 63 c m":" !#%?#@$#$%+!@+? +%$+@!+ ?+! #?%#$@#","P 63 m c":" !#%?#@$#$%+!@+? +%$#@!# ?#! +?%+$@+","P -6 m 2":" !#%?#@$# !&%?&@$&%$#@!# ?#%$&@!& ?&","P -6 c 2":" !#%?#@$# !-%?-@$-%$+@!+ ?+%$&@!& ?&","P -6 2 m":" !#%?#@$# !&%?&@$&! &?%&$@&! #?%#$@#","P -6 2 c":" !#%?#@$# !-%?-@$-! &?%&$@&! +?%+$@+","P 6/m 2/m 2/m":" !#%?#@$#$%#!@#? #! &?%&$@&%$&@!& ?&$%&!@&? & !&@$&%?&%$#@!# ?#! #?%#$@#","P 6/m 2/c 2/c":" !#%?#@$#$%#!@#? #! -?%-$@-%$-@!- ?-$%&!@&? & !&@$&%?&%$+@!+ ?+! +?%+$@+","P 63/m 2/c 2/m":" !#%?#@$#$%+!@+? +! -?%-$@-%$&@!& ?&$%&!@&? & !-@$-%?-%$+@!+ ?+! #?%#$@#","P 63/m 2/m 2/c":" !#%?#@$#$%+!@+? +! &?%&$@&%$-@!- ?-$%&!@&? & !-@$-%?-%$#@!# ?#! +?%+$@+","P 2 3":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ","F 2 3":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%&  )+$,+$)- ,-#()#*,&*)&(,!+(%+*!-*%-((!+*%+*!-(%-+ )+$,-$)- ,)#(,#*)&*,&(()#*,#*)&(,&+(!+*%-*!-(%)+ ,+$)-$,- ","I 2 3":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ()+*,+*)-(,-+()+*,-*)-(,)+(,+*)-*,-(","P 21 3":" !#*%+$)-(,&# !+*%-$)&(,!# %+*)-$,&(","I 21 3":" !#*%+$)-(,&# !+*%-$)&(,!# %+*)-$,&(()+$,#*!& %-+()#$,&*!- %)+(,#$!&*%- ","P 2/m -3":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& $%& !& %#$!#&$%& !# %#$!%&$!& %# !#$","P 2/n -3":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& *,-()-(,+*)+-*,-()+(,+*),-*)-(,+()+*","F 2/m -3":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& $%& !& %#$!#&$%& !# %#$!%&$!& %# !#$ )+$,+$)- ,-#()#*,&*)&(,!+(%+*!-*%-($,- )- ,+$)+&*,&()#(,#*)%-*!-(%+(!+*(!+*%+*!-(%-+ )+$,-$)- ,)#(,#*)&*,&(*%-(!-(%+*!+-$,- )+ ,+$),&*)&(,#()#*()#*,#*)&(,&+(!+*%-*!-(%)+ ,+$)-$,- *,&()&(,#*)#-*%-(!+(%+*!,-$)- ,+ )+$","F 2/d -3":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& 64=37=345675=64=375345674=67=3453756 )+$,+$)- ,-#()#*,&*)&(,!+(%+*!-*%-(68>3:>3896:9=<8=;:5;85<:4><7>;49;79<(!+*%+*!-(%-+ )+$,-$)- ,)#(,#*)&*,&(<4>;7>;49<79>68>3:93896:8=<:=;85;:5<()#*,#*)&(,&+(!+*%-*!-(%)+ ,+$)-$,- <8=;:=;8f<:f><4>;79;49<78>6:>3893:96","I 2/m -3":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& $%& !& %#$!#&$%& !# %#$!%&$!& %# !#$()+*,+*)-(,-+()+*,-*)-(,)+(,+*)-*,-(*,-()-(,+*)+-*,-()+(,+*),-*)-(,+()+*","P 21/a -3":" !#*%+$)-(,&# !+*%-$)&(,!# %+*)-$,&($%&(!- ,+*)#&$%-(!+ ,#*)%&$!-(,+ )#*","I 21/a -3":" !#*%+$)-(,&# !+*%-$)&(,!# %+*)-$,&($%&(!- ,+*)#&$%-(!+ ,#*)%&$!-(,+ )#*()+$,#*g& %-+()#$,&*!- %)+(,#$!&*%- *,- )&(%#$!+-*,& )#(%+$!,-*)& %#(!+$","P 4 3 2":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! &%$&!$#% # #%$#!$&% &!#!$#% &! &%$","P 42 3 2":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& )(-,*-)*+,(+(+,*+)*-,(-)+)*+,(-)(-,*","F 4 3 2":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! &%$&!$#% # #%$#!$&% &!#!$#% &! &%$ )+$,+$)- ,-#()#*,&*)&(,!+(%+*!-*%-(!(-%*-!*+%(+ +,$+)$-, -)#)*#,(&)(&,*(!+*%+*!-(%-+ )+$,-$)- ,)#(,#*)&*,&() -,$-)$+, +(#,*#)*&,(&)+!*+%(-!(-%*()#*,#*)&(,&+(!+*%-*!-(%)+ ,+$)-$,- )(&,*&)*#,(#(+%*+!*-%(-!+)$+, -) -,$","F 41 3 2":" !#$,+*)&(%-# !+$,&*)-(%!# ,+$)&*%-(:3>46=7<98;5;58<976=43>:97<58;>:3=46 )+$%#*!-(,&#()+*%&$!- ,!+(,#*)-$%& :;=4<>765839;94<5:6>83=79:6543>7;=8<(!+*,#$)- %&+ )#$%-*!&(,)#(%+*!&$,- 73=86>:<54;935469:<=8;>7576983=:;>4<()#*%+$!& ,-+(!#*,-$)& %)+ %#$!-*,&(7;>8<=:69435398657<>4;=:5:<94;=73>86","I 4 3 2":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! &%$&!$#% # #%$#!$&% &!#!$#% &! &%$()+*,+*)-(,-+()+*,-*)-(,)+(,+*)-*,-()(-,*-)*+,(+(+,*+)*-,(-)+)*+,(-)(-,*","P 43 3 2":" !#*%+$)-(,&# !+*%-$)&(,!# %+*)-$,&(7;>46=:<5839398<5:6=4;>75:<983>7;=46","P 41 3 2":" !#*%+$)-(,&# !+*%-$)&(,!# %+*)-$,&(:3=8<>7694;5;54697<>83=:97654;=:3>8<","I 41 3 2":" !#*%+$)-(,&# !+*%-$)&(,!# %+*)-$,&(:3=8<>7694;5;54697<>83=:97654;=:3>8<()+$,#*!& %-+()#$,&*!- %)+(,#$!&*%- 7;>46=:<5839398<5:6=4;>75:<983>7;=46","P -4 3 m":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! #%$#!$&% & #!$#%$&! &%#! #%$&!$&% ","F -4 3 m":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! #%$#!$&% & #!$#%$&! &%#! #%$&!$&%  )+$,+$)- ,-#()#*,&*)&(,!+(%+*!-*%-(!(+%*+!*-%(- +)$+,$-) -,#)(#,*&)*&,((!+*%+*!-(%-+ )+$,-$)- ,)#(,#*)&*,&() +,$+)$-, -(#)*#,*&)(&,+!(+%*-!*-%(()#*,#*)&(,&+(!+*%-*!-(%)+ ,+$)-$,- )(#,*#)*&,(&(+!*+%*-!(-%+) +,$-)$-, ","I -4 3 m":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! #%$#!$&% & #!$#%$&! &%#! #%$&!$&% ()+*,+*)-(,-+()+*,-*)-(,)+(,+*)-*,-()(+,*+)*-,(-(+)*+,*-)(-,+)(+,*-)*-,(","P -4 3 n":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& )(+,*+)*-,(-(+)*+,*-)(-,+)(+,*-)*-,(","F -4 3 c":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& )(+,*+)*-,(-(+)*+,*-)(-,+)(+,*-)*-,( )+$,+$)- ,-#()#*,&*)&(,!+(%+*!-*%-() #,$#)$&, &(#!*#%*&!(&%+! +%$-!$-% (!+*%+*!-(%-+ )+$,-$)- ,)#(,#*)&*,&(!(#%*#!*&%(& +!$+%$-! -%#) #,$&)$&, ()#*,#*)&(,&+(!+*%-*!-(%)+ ,+$)-$,- ! +%$+!$-% - #)$#,$&) &,#!(#%*&!*&%(","I -4 3 d":" !#*%+$)-(,&# !+*%-$)&(,!# %+*)-$,&(7354<9:6>8;=357<946>:;=857394<>:6=8;()+$,#*!& %-+()#$,&*!- %)+(,#$!&*%- :;98657<=43>;9:658<=73>49:;586=7<>43","P 4/m -3 2/m":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! &%$&!$#% # #%$#!$&% &!#!$#% &! &%$$%& !& %#$!#&$%& !# %#$!%&$!& %# !#$%$#! #% &!$&$&! &% #!$#%&% &!$#%$#! ","P 4/n -3 2/n":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! &%$&!$#% # #%$#!$&% &!#!$#% &! &%$*,-()-(,+*)+-*,-()+(,+*),-*)-(,+()+*,*+)(+,(-)*-*-)(-,(+)*+,-,(-)*+,*+)(","P 42/m -3 2/n":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& )(-,*-)*+,(+(+,*+)*-,(-)+)*+,(-)(-,*$%& !& %#$!#&$%& !# %#$!%&$!& %# !#$,*+)(+,(-)*-*-)(-,(+)*+,-,(-)*+,*+)(","P 42/n -3 2/m":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& )(-,*-)*+,(+(+,*+)*-,(-)+)*+,(-)(-,**,-()-(,+*)+-*,-()+(,+*),-*)-(,+()+*%$#! #% &!$&$&! &% #!$#%&% &!$#%$#! ","F 4/m -3 2/m":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! &%$&!$#% # #%$#!$&% &!#!$#% &! &%$$%& !& %#$!#&$%& !# %#$!%&$!& %# !#$%$#! #% &!$&$&! &% #!$#%&% &!$#%$#!  )+$,+$)- ,-#()#*,&*)&(,!+(%+*!-*%-(!(-%*-!*+%(+ +,$+)$-, -)#)*#,(&)(&,*$,- )- ,+$)+&*,&()#(,#*)%-*!-(%+(!+*%*+!(+%(-!*-$-) -, +)$+,&,(&)*#,*#)((!+*%+*!-(%-+ )+$,-$)- ,)#(,#*)&*,&() -,$-)$+, +(#,*#)*&,(&)+!*+%(-!(-%**%-(!-(%+*!+-$,- )+ ,+$),&*)&(,#()#*,$+) +, -)$-*&)(&,(#)*#,-%(-!*+%*+!(()#*,#*)&(,&+(!+*%-*!-(%)+ ,+$)-$,- )(&,*&)*#,(#(+%*+!*-%(-!+)$+, -) -,$*,&()&(,#*)#-*%-(!+(%+*!,-$)- ,+ )+$,*#)(#,(&)*&*-!(-%(+!*+%-, -)$+,$+) ","F 4/m -3 2/c":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& )(-,*-)*+,(+(+,*+)*-,(-)+)*+,(-)(-,*$%& !& %#$!#&$%& !# %#$!%&$!& %# !#$,*+)(+,(-)*-*-)(-,(+)*+,-,(-)*+,*+)( )+$,+$)- ,-#()#*,&*)&(,!+(%+*!-*%-() &,$&)$#, #(#%*#!*&%(&!+!$+% -! -%$$,- )- ,+$)+&*,&()#(,#*)%-*!-(%+(!+*,$#) #, &)$&*&!(&%(#!*#%-% -!$+%$+! (!+*%+*!-(%-+ )+$,-$)- ,)#(,#*)&*,&(!(&%*&!*#%(# +%$+!$-% -!#)$#, &) &,$*%-(!-(%+*!+-$,- )+ ,+$),&*)&(,#()#*%*#!(#%(&!*&$-! -% +!$+%&, &)$#,$#) ()#*,#*)&(,&+(!+*%-*!-(%)+ ,+$)-$,- ! -%$-!$+% + #,$#)$&, &)#!*#%(&!(&%**,&()&(,#*)#-*%-(!+(%+*!,-$)- ,+ )+$%$+! +% -!$-$&) &, #)$#,&%(&!*#%*#!(","F 41/d -3 2/m":" !#$,+*)&(%-# !+$,&*)-(%!# ,+$)&*%-(:3>46=7<98;5;58<976=43>:97<58;>:3=4664=3:>;85<79=64>3:5;89<74=6:>385;79<,$+! #%(-)*&*&)(-% #!$+,-%(&)*+,$#!  )+$%#*!-(,&#()+*%&$!- ,!+(,#*)-$%& :;=4<>765839;94<5:6>83=79:6543>7;=8<68>37=;49<:5=<8>;753496:4><:=;893756,*#!(+% &)$-*-!(&, +)$#%-, &!$+%*#)((!+*,#$)- %&+ )#$%-*!&(,)#(%+*!&$,- 73=86>:<54;935469:<=8;>7576983=:;>4<<4>;:=389675>68=379;45<:8=<7>;453:96%$#) +,(&!*-$&! -,(#)*+%&% -)$#,*+!(()#*%+$!& ,-+(!#*,-$)& %)+ %#$!-*,&(7;>8<=:69435398657<>4;=:5:<94;=73>86<8=;7>3456:9><4=;:9385678>67=349;:5<%*+)(#, -!$&$-) &%(+!*#,&,(-!*#%$+) ","F 41/d -3 2/c":" !#$,+*)&(%-# !+$,&*)-(%!# ,+$)&*%-(:3>46=7<98;5;58<976=43>:97<58;>:3=46<8>;7=3496:5><8=;793456:8><7=;493:56%*#)(+, &!$-$-! &,(+)*#%&, -!$#%*+)( )+$%#*!-(,&#()+*%&$!- ,!+(,#*)-$%& :;=4<>765839;94<5:6>83=79:6543>7;=8<<4=;:>385679>64=3:9;85<78=67>345;:9<%$+) #,(-!*&$&) -%(#!*+,&%(-)*#,$+! (!+*,#$)- %&+ )#$%-*!&(,)#(%+*!&$,- 73=86>:<54;935469:<=8;>7576983=:;>4<68=37>;45<:9=<4>;:5389674>6:=389;75<,*+!(#% -)$&*-)(&% +!$#,-,(&!*+%$#) ()#*%+$!& ,-+(!#*,-$)& %)+ %#$!-*,&(7;>8<=:69435398657<>4;=:5:<94;=73>8664>3:=;89<75=68>375;49<:4=<:>;853796,$#! +%(&)*-*&!(-, #)$+%-% &)$+,*#!(","I 4/m -3 2/m":" !#$%#$!& %&# !#$%&$!& %!# %#$!&$%& ! &%$&!$#% # #%$#!$&% &!#!$#% &! &%$$%& !& %#$!#&$%& !# %#$!%&$!& %# !#$%$#! #% &!$&$&! &% #!$#%&% &!$#%$#! ()+*,+*)-(,-+()+*,-*)-(,)+(,+*)-*,-()(-,*-)*+,(+(+,*+)*-,(-)+)*+,(-)(-,**,-()-(,+*)+-*,-()+(,+*),-*)-(,+()+*,*+)(+,(-)*-*-)(-,(+)*+,-,(-)*+,*+)(","I 41/a -3 2/d":" !#*%+$)-(,&# !+*%-$)&(,!# %+*)-$,&(:3=8<>7694;5;54697<>83=:97654;=:3>8<$%&(!- ,+*)#&$%-(!+ ,#*)%&$!-(,+ )#*4<97358;=:6>6>:;=8357<94=8;>:694<573()+$,#*!& %-+()#$,&*!- %)+(,#$!&*%- 7;>46=:<5839398<5:6=4;>75:<983>7;=46*,- )&(%#$!+-*,& )#(%+$!,-*)& %#(!+$865:;943>7<=<=73>4;9:658>43=7<5869:;","P 1 1 2":" !#$%#","P 1 1 21":" !#$%+","B 1 1 2":" !#$%#(g+*%+","A 1 2 1":" !#$!& )+$)-","C 1 21 1":" !#$)&()#*!&","I 1 2 1":" !#$!&.'/0'2","I 1 21 1":" !#$)&.'/0!-","P 1 1 m":" !# !&","P 1 1 b":" !# )&","B 1 1 m":" !# !&(!+(!-","B 1 1 b":" !# )&(!+()-","P 1 1 2/m":" !# !&$%#$%&","P 1 1 21/m":" !#$%+$%& !-","B 1 1 2/m":" !# !&$%#$%&(!+(!-*%+*%-","P 1 1 2/b":" !#$,#$%& )&","P 1 1 21/b":" !#$%&$,+ )-","B 1 1 2/b":" !#$,#$%& )&(!+*,+*%-()-","P 21 2 2":" !#$!&(%&*%#","P 2 21 2":" !# ,&$)&$%#","P 21 21 2 (a)":" !#*,#.%&$'&","P 21 2 21":" !#$!&(%-*%+","P 2 21 21":" !# %&$)-$,+","C 2 2 21a)":" !#*%+(,&$)-()#$,+ %&*!-","C 2 2 2a":" !#*,#.%&$'&()#$%# ,&*!&","F 2 2 2a":" !#*,#.%&$'& '/*%/.12$!2.!/$,/ %20'2.'#$%# 1&0!&","I 2 2 2a":" !#*,#.%&$'&()+$%+*!- ,-","P 21/m 21/m 2/n a":" !#*,#$)&(%&$%&.'& ,#*!#","P 42 21 2a":" !#*,#%.+'$+$'&.%&! -,*-","I 2 3a":" !#*,#.%&$'&!# ,- '&$%/$# !-*!/$%&.%()+$%+ ,-*!-)+(%&(!-*,#*+()&$)#*,- ,"},Ea=/^[1-9]$/;function Fa(t){let e="";return t.length>0&&(e=":"+gt(t).join(" OR :")),new pe(e)}class La{constructor(t=""){this.name=t,this.partList=[]}get type(){return"Assembly"}addPart(t,e){const i=new Na(t,e);return this.partList.push(i),i}getAtomCount(t){return this.partList.reduce(((e,i)=>e+i.getAtomCount(t)),0)}getResidueCount(t){return this.partList.reduce(((e,i)=>e+i.getResidueCount(t)),0)}getInstanceCount(){let t=0;return this.partList.forEach((function(e){t+=e.matrixList.length})),t}isIdentity(t){if(1!==this.partList.length)return!1;const e=this.partList[0];if(1!==e.matrixList.length)return!1;if(!(new i).equals(e.matrixList[0]))return!1;let r=[];return t.eachChain((function(t){r.push(t.chainname)})),r=gt(r),e.chainList.length===r.length}getBoundingBox(t){const e=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */];return this.partList.forEach((function(i){const r=i.getBoundingBox(t);e.expandByPoint(r.min),e.expandByPoint(r.max)})),e}getCenter(t){return this.getBoundingBox(t).getCenter(new e)}getSelection(){let t=[];return this.partList.forEach((function(e){t=t.concat(e.chainList)})),Fa(t)}}class Na{constructor(t=[],e=[]){this.matrixList=t,this.chainList=e}get type(){return"AssemblyPart"}_getCount(t,e){let i=0;return t.eachChain((t=>{(0===this.chainList.length||this.chainList.includes(t.chainname))&&(i+=t[e])})),this.matrixList.length*i}getAtomCount(t){return this._getCount(t,"atomCount")}getResidueCount(t){return this._getCount(t,"residueCount")}getBoundingBox(t){const e=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],i=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],r=this.getSelection(),s=t.getBoundingBox(r);return this.matrixList.forEach((function(t){i.copy(s).applyMatrix4(t),e.expandByPoint(i.min),e.expandByPoint(i.max)})),e}getSelection(){return Fa(this.chainList)}getView(t){const e=this.getSelection();return e?t.getView(e):t}getInstanceList(){const t=[];for(let e=0,i=this.matrixList.length;e<i;++e)t.push({id:e+1,name:e,matrix:this.matrixList[e]});return t}}class za{constructor(t){this.structure=t,this.currentModelindex=null,this.currentChainid=null,this.currentResname=null,this.currentResno=null,this.currentInscode=void 0,this.currentHetero=null,this.previousResname="",this.previousHetero=null,this.ai=-1,this.ri=-1,this.ci=-1,this.mi=-1}addResidueType(t){const e=this.structure.atomStore,i=this.structure.residueStore,r=this.structure.residueMap,s=i.atomCount[t],n=i.atomOffset[t],o=new Array(s);for(let t=0;t<s;++t)o[t]=e.atomTypeId[n+t];i.residueTypeId[t]=r.add(this.previousResname,o,this.previousHetero)}addAtom(t,e,i,r,s,n,o,a){const c=this.structure.atomStore,l=this.structure.residueStore,h=this.structure.chainStore,d=this.structure.modelStore;let u=!1,m=!1,p=!1;this.currentModelindex!==t?(u=!0,m=!0,p=!0,this.mi+=1,this.ci+=1,this.ri+=1):this.currentChainid!==i?(m=!0,p=!0,this.ci+=1,this.ri+=1):this.currentResno===s&&this.currentResname===r&&this.currentInscode===a||(p=!0,this.ri+=1),this.ai+=1,u&&(d.growIfFull(),d.chainOffset[this.mi]=this.ci,d.chainCount[this.mi]=0,d.count+=1,h.modelIndex[this.ci]=this.mi),m&&(h.growIfFull(),h.setChainname(this.ci,e),h.setChainid(this.ci,i),h.residueOffset[this.ci]=this.ri,h.residueCount[this.ci]=0,h.count+=1,h.modelIndex[this.ci]=this.mi,d.chainCount[this.mi]+=1,l.chainIndex[this.ri]=this.ci),p&&(this.previousResname=this.currentResname,this.previousHetero=this.currentHetero,this.ri>0&&this.addResidueType(this.ri-1),l.growIfFull(),l.resno[this.ri]=s,void 0!==o&&(l.sstruc[this.ri]=o.charCodeAt(0)),void 0!==a&&(l.inscode[this.ri]=a.charCodeAt(0)),l.atomOffset[this.ri]=this.ai,l.atomCount[this.ri]=0,l.count+=1,l.chainIndex[this.ri]=this.ci,h.residueCount[this.ci]+=1),c.count+=1,c.residueIndex[this.ai]=this.ri,l.atomCount[this.ri]+=1,this.currentModelindex=t,this.currentChainid=i,this.currentResname=r,this.currentResno=s,this.currentInscode=a,this.currentHetero=n}finalize(){this.previousResname=this.currentResname,this.previousHetero=this.currentHetero,this.ri>-1&&this.addResidueType(this.ri)}}function Va(t,e){if(!e)return;De&&Me.time("assignSecondaryStructure");const i=[];t.eachModel((function(t){t.eachChain((function(t){i.push(t.chainname)}))}));const r=i.slice().sort(),s=[];r.forEach((function(t){s.push(i.indexOf(t))}));const n=e.helices.filter((function(t){return pt(r,t[0])>=0}));n.sort((function(t,e){const i=t[0],n=e[0],o=t[1],a=e[1];if(i===n)return o===a?0:o<a?-1:1;{const t=pt(r,i),e=pt(r,n);return s[t]<s[e]?-1:1}}));const o=t.residueStore;t.eachModel((function(t){let e=0;const i=n.length;if(0===i)return;let r=n[e],s=!1,a=!1;t.eachChain((function(t){let c=!1;if(t.chainname===r[0]){const l=t.residueCount,h=t.residueOffset,d=h+l;for(let l=h;l<d;++l)if(o.resno[l]===r[1]&&o.getInscode(l)===r[2]&&(s=!0),s&&(o.sstruc[l]=r[6],o.resno[l]===r[4]&&o.getInscode(l)===r[5]&&(s=!1,e+=1,e<i?(l=h-1,r=n[e],c=t.chainname!==r[0]):a=!0)),c||a)return}}))}));const a=e.sheets.filter((function(t){return pt(r,t[0])>=0}));a.sort((function(t,e){const i=t[0],n=e[0];if(i===n)return 0;const o=pt(r,i),a=pt(r,n);return s[o]<s[a]?-1:1}));const c="e".charCodeAt(0);t.eachModel((function(t){let e=0;const i=a.length;if(0===i)return;let r=a[e],s=!1,n=!1;t.eachChain((function(t){let l=!1;if(t.chainname===r[0]){const h=t.residueCount,d=t.residueOffset,u=d+h;for(let h=d;h<u;++h)if(o.resno[h]===r[1]&&o.getInscode(h)===r[2]&&(s=!0),s&&(o.sstruc[h]=c,o.resno[h]===r[4]&&o.getInscode(h)===r[5]&&(s=!1,e+=1,e<i?(h=d-1,r=a[e],l=t.chainname!==r[0]):n=!0)),l||n)return}}))})),De&&Me.timeEnd("assignSecondaryStructure")}const Ga=function(){const t=function(t,e,i,r){const s=t.structure,n=t.residueIndexStart,o=s.getResidueProxy(),a=s.getResidueProxy(),c=s.getAtomProxy(),l=s.getAtomProxy();for(let s=Math.max(0,e-2);s<=e;++s)for(let e=2;e<5;++e){if(s+e>=t.residueCount)continue;o.index=n+s,a.index=n+s+e,c.index=o.traceAtomIndex,l.index=a.traceAtomIndex;const h=c.distanceTo(l);if(Math.abs(h-i[e-2])>r)return!1}return!0},i=function(e,i){return t(e,i,[5.45,5.18,6.37],2.1)},r=function(e,i){return t(e,i,[6.1,10.4,13],1.42)};return function(t){De&&Me.time("calculateSecondaryStructure"),t.eachPolymer((function(t){if(t.residueCount<4)return;if(t.isCg())!function(t){const i=t.residueStore,r=t.residueIndexStart,s=new Pa(t).position,n=new e,o=new e;for(let e=0,a=t.residueCount;e<a;++e){n.fromArray(s.center,3*e),o.fromArray(s.center,3*e+3);const t=n.distanceTo(o);t<2&&t>1&&s.bending[e]<20&&(i.sstruc[r+e]="h".charCodeAt(0),i.sstruc[r+e+1]="h".charCodeAt(0))}}(t);else{if(!t.isProtein())return;!function(t){const e=t.residueStore,s=t.residueIndexStart;for(let n=0,o=t.residueCount;n<o;++n){let o="c";i(t,n)?o="h":r(t,n)&&(o="e"),e.sstruc[s+n]=o.charCodeAt(0)}}(t)}let s,n=0;t.eachResidue((function(t){t.sstruc===s?n+=1:(1===n&&(t.index-=1,t.sstruc="c"),n=1,s=t.sstruc)}))})),De&&Me.timeEnd("calculateSecondaryStructure")}}(),Ua="ABCDEFGHIJKLMNOPQRSTUVWXYZ";function ja(t){const e=Ua.length;let i=t,r=0,s=Ua[i%e];for(;i>=e;)i=Math.floor(i/e),s+=Ua[i%e],r+=1;return r>=5&&Me.warn("chainname overflow"),s}function Ha(t,e=!1){De&&Me.time("calculateChainnames");let i=!0;if(t.eachChain((function(t){t.chainname&&(i=!1)})),i){const i=t.modelStore,r=t.chainStore,s=t.residueStore,n=function(t,e,n,o){const a=r.count;for(let t=0;t<o;++t)s.chainIndex[n+t]=a;r.growIfFull(),r.modelIndex[a]=t,r.setChainname(a,e),r.setChainid(a,e),r.residueOffset[a]=n,r.residueCount[a]=o,r.count+=1,i.chainCount[t]+=1},o=t.getAtomProxy(),a=t.getAtomProxy();let c=0,l=0,h=0,d=0;const u=[];1===s.count?u.push({mIndex:0,chainname:"A",rStart:0,rCount:1}):t.eachResidueN(2,(function(t,i){let r=!1;const n=t.backboneType,m=i.backboneType,p=Ns;d=t.index,t.modelIndex!==i.modelIndex||t.moleculeType!==i.moleculeType?r=!0:n!==p&&n===m&&(o.index=t.backboneEndAtomIndex,a.index=i.backboneStartAtomIndex,r=e?!o.hasBondTo(a):!o.connectedTo(a)),r||i.index!==s.count-1||(r=!0,d=i.index),r&&(u.push({mIndex:l,chainname:ja(c),rStart:h,rCount:d-h+1}),c+=1,t.modelIndex!==i.modelIndex&&(c=0,l+=1),i.index===s.count-1&&d!==i.index&&u.push({mIndex:l,chainname:ja(c),rStart:s.count-1,rCount:1}),h=i.index,d=i.index)})),r.count=0,i.chainCount.fill(0,0,i.count),i.chainOffset.fill(0,0,i.count),u.forEach((function(t){n(t.mIndex,t.chainname,t.rStart,t.rCount)}));let m=0;t.eachModel((function(t){i.chainOffset[t.index]=m,m+=i.chainCount[t.index]}))}De&&Me.timeEnd("calculateChainnames")}function Wa(t,e="all"){"none"!==e&&(De&&Me.time("calculateBonds"),Ya(t,!1,e),Ka(t),De&&Me.timeEnd("calculateBonds"))}const qa={"HIS|CD2|CG":2,"HIS|CE1|ND1":2,"ARG|CZ|NH2":2,"PHE|CE1|CZ":2,"PHE|CD2|CE2":2,"PHE|CD1|CG":2,"TRP|CD1|CG":2,"TRP|CD2|CE2":2,"TRP|CE3|CZ3":2,"TRP|CH2|CZ2":2,"ASN|CG|OD1":2,"GLN|CD|OE1":2,"TYR|CD1|CG":2,"TYR|CD2|CE2":2,"TYR|CE1|CZ":2,"ASP|CG|OD1":2,"GLU|CD|OE1":2,"G|C8|N7":2,"G|C4|C5":2,"G|C2|N3":2,"G|C6|O6":2,"C|C4|N3":2,"C|C5|C6":2,"C|C2|O2":2,"A|C2|N3":2,"A|C6|N1":2,"A|C4|C5":2,"A|C8|N7":2,"U|C5|C6":2,"U|C2|O2":2,"U|C4|O4":2,"DG|C8|N7":2,"DG|C4|C5":2,"DG|C2|N3":2,"DG|C6|O6":2,"DC|C4|N3":2,"DC|C5|C6":2,"DC|C2|O2":2,"DA|C2|N3":2,"DA|C6|N1":2,"DA|C4|C5":2,"DA|C8|N7":2,"DT|C5|C6":2,"DT|C2|O2":2,"DT|C4|O4":2};function Xa(t,e,i){return[e,i]=e<i?[e,i]:[i,e],rn.includes(t)&&"C"===e&&"O"===i||an.includes(t)&&"OP1"===e&&"P"===i?2:qa[`${t}|${e}|${i}`]||1}function Ya(t,e=!1,i="all"){De&&Me.time("calculateBondsWithin");const r=t.bondStore,s=t.rungBondStore,n=t.getAtomSet(!1),o=t.getAtomProxy(),a=t.getAtomProxy(),c=t.getBondProxy(),l=e?null:function(t){De&&Me.time("calculateAtomBondMap");var e=[];return t.eachBond((function(t){var i=t.atomIndex1,r=t.atomIndex2;void 0===e[i]&&(e[i]=[]),e[i][r]=t.index})),De&&Me.timeEnd("calculateAtomBondMap"),e}(t);let h;e||"auto"!==i||(h=new Set,l.forEach(((t,e)=>{h.add(e),t.forEach((t=>{h.add(t)}))}))),t.eachResidue((function(t){if(!e&&l){const e=t.atomCount,s=t.atomOffset;if(e>500)return void Me.warn("more than 500 atoms, skip residue for auto-bonding",t.qualifiedName());if("auto"===i&&t.hetero)for(let e=t.atomOffset;e<t.atomEnd;e++)if(h.has(e))return;const n=t.getBonds(),d=n.atomIndices1,u=n.atomIndices2,m=n.bondOrders,p=d.length;for(let e=0;e<p;++e){const i=d[e],n=u[e],h=i+s,p=n+s,f=l[h];if(void 0!==f&&void 0!==f[p]){c.index=f[p];m[t.residueType.getBondIndex(i,n)]=c.bondOrder}else o.index=h,a.index=p,r.addBond(o,a,m[e])}}const d=t.residueType.traceAtomIndex,u=t.residueType.rungEndAtomIndex;-1!==d&&-1!==u&&(o.index=t.traceAtomIndex,a.index=t.rungEndAtomIndex,s.addBond(o,a),n.set(o.index),n.set(a.index))})),t.atomSetDict.rung=n,De&&Me.timeEnd("calculateBondsWithin")}function Ka(t,e=!1,i=!1){De&&Me.time("calculateBondsBetween");const r=t.bondStore,s=t.backboneBondStore,n=t.getAtomSet(!1),o=t.getAtomProxy(),a=t.getAtomProxy();function c(t,c){const l=t.backboneType,h=c.backboneType;if(l!==Ns&&l===h){o.index=t.backboneEndAtomIndex,a.index=c.backboneStartAtomIndex;let l=!1,h=!1;i&&o.hasBondTo(a)?(l=!1,h=!0):o.connectedTo(a)&&(l=!e,h=!0),l&&r.addBond(o,a,1),h&&(o.index=t.traceAtomIndex,a.index=c.traceAtomIndex,s.addBond(o,a),n.set(o.index),n.set(a.index))}}0===s.count&&s.resize(t.residueStore.count),t.eachResidueN(2,c);const l=t.getResidueProxy(),h=t.getResidueProxy();if(t.eachChain((function(t){0!==t.residueCount&&(l.index=t.residueOffset,h.index=t.residueOffset+t.residueCount-1,c(h,l))})),t.atomSetDict.backbone=n,!e){De&&Me.time("calculateBondsBetween inter");const e=t.spatialHash;t.eachResidue((function(t){t.backboneType!==Ns||t.isWater()||t.eachAtom((function(t){t.isMetal()||e.eachWithin(t.x,t.y,t.z,4,(function(e){a.index=e,t.modelIndex!==a.modelIndex||t.residueIndex===a.residueIndex||a.isMetal()||r.addBondIfConnected(t,a,1)}))}))})),De&&Me.timeEnd("calculateBondsBetween inter")}De&&Me.timeEnd("calculateBondsBetween")}function Za(t){if(!t.unitcell)return;De&&Me.time("buildUnitcellAssembly");const r=t.unitcell,s=t.center.clone().applyMatrix4(r.cartToFrac),n=s.clone().floor(),o=function(t){const e=Ra[t],r={};if(void 0===e)return console.warn(`spacegroup '${t}' not found in symop library`),r;const s=[];for(let t=0,i=e.length;t<i;t+=3){const i=[];for(let r=0;r<3;++r)i.push(Oa[e[t+r]]);s.push(i)}return s.forEach((function(t){let e=0;const s=(new i).set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1),n=s.elements;r[t.toString()]=s,t.forEach((function(t){let i=!1,r=!1;for(let s=0,o=t.length;s<o;++s){const o=t[s];if("-"===o)i=!0;else if("+"===o)i=!1;else if("/"===o)r=!0;else if("X"===o)n[0+e]=i?-1:1;else if("Y"===o)n[4+e]=i?-1:1;else if("Z"===o)n[8+e]=i?-1:1;else if(Ea.test(o)){const t=parseInt(o);r?n[12+e]/=t:n[12+e]=t}else Me.warn(`getSymmetryOperations: unknown token '${o}'`)}e+=1}))})),r}(r.spacegroup),a=new e,c=new e;function l(t){const e=[];return Object.keys(o).forEach((function(i){const l=o[i].clone();a.copy(s).applyMatrix4(l).floor(),c.setFromMatrixPosition(l),c.sub(a),c.add(n),t&&c.add(t),l.setPosition(c),l.multiplyMatrices(r.fracToCart,l),l.multiply(r.cartToFrac),e.push(l)})),e}const h=new La("UNITCELL"),d=l(),u=[];if(t.biomolDict.NCS){u.push(new i,...t.biomolDict.NCS.partList[0].matrixList);const e=[];d.forEach((t=>{u.forEach((i=>{e.push(t.clone().multiply(i))}))})),h.addPart(e)}else h.addPart(d);const m=new e,p=new La("SUPERCELL"),f=Array.prototype.concat.call(l(m.set(1,0,0)),l(m.set(0,1,0)),l(m.set(0,0,1)),l(m.set(-1,0,0)),l(m.set(0,-1,0)),l(m.set(0,0,-1)),l(m.set(1,1,0)),l(m.set(1,0,1)),l(m.set(0,1,1)),l(m.set(-1,-1,0)),l(m.set(-1,0,-1)),l(m.set(0,-1,-1)),l(m.set(1,-1,-1)),l(m.set(1,1,-1)),l(m.set(1,-1,1)),l(m.set(-1,1,1)),l(m.set(-1,-1,1)),l(m.set(-1,1,-1)),l(m.set(0,1,-1)),l(m.set(0,-1,1)),l(m.set(1,0,-1)),l(m.set(-1,0,1)),l(m.set(1,-1,0)),l(m.set(-1,1,0)),l(),l(m.set(1,1,1)),l(m.set(-1,-1,-1)));if(t.biomolDict.NCS){const t=[];f.forEach((function(e){u.forEach((function(i){t.push(e.clone().multiply(i))}))})),p.addPart(t)}else p.addPart(f);t.biomolDict.UNITCELL=h,t.biomolDict.SUPERCELL=p,De&&Me.timeEnd("buildUnitcellAssembly")}const Qa=["H","C","O","N","S","P"],Ja=["NA","CL","FE"];function tc(t){let e=t.toUpperCase(),i=0,r=0;for(let t=0;t<e.length;t++)if(e.charCodeAt(t)<65){if(r>0)break;++i}else r=t+1;(i>0||r<e.length)&&(e=e.substring(i,r));const s=e.length;if(0===s)return"";if(1===s)return e;if(2===s){if(-1!==Ja.indexOf(e))return e;if(-1!==Qa.indexOf(e[0]))return e[0];if(e in Xs)return e}return s>=3&&-1!==Qa.indexOf(e[0])?e[0]:""}function ec(t){const e=t.bondHash,i=e.countArray,r=e.offsetArray,s=e.indexArray,n=t.getBondProxy();t.eachResidue((function(t){const e=t.residueType;if(void 0!==e.bonds)return;var o=t.atomOffset,a=[],c=[],l=[],h={};const d=o+t.atomCount;t.eachAtom((function(t){const e=t.index,u=r[e];for(let t=0,r=i[e];t<r;++t){n.index=s[u+t];let e=n.atomIndex1;if(e<o||e>=d)continue;let i=n.atomIndex2;if(i<o||i>=d)continue;if(e>i){const t=i;i=e,e=t}const r=e+"|"+i;void 0===h[r]&&(h[r]=!0,a.push(e-o),c.push(i-o),l.push(n.bondOrder))}})),e.bonds={atomIndices1:a,atomIndices2:c,bondOrders:l}}))}function ic(t,...e){De&&Me.time("concatStructures");const i=new Cc(t,""),r=new za(i),s=i.atomStore,n=i.atomMap;s.addField("formalCharge",1,"int8"),s.addField("partialCharge",1,"float32");const o={};let a=0,c=0,l=0;e.forEach((t=>{t.eachAtom((t=>{s.growIfFull(),s.atomTypeId[a]=n.add(t.atomname,t.element),s.x[a]=t.x,s.y[a]=t.y,s.z[a]=t.z,s.serial[a]=t.serial,s.formalCharge[a]=t.formalCharge,s.partialCharge[a]=t.partialCharge,s.altloc[a]=t.altloc,s.occupancy[a]=t.occupancy,s.bfactor[a]=t.bfactor,r.addAtom(t.modelIndex+l,t.chainname,t.chainid,t.resname,t.resno,1===t.hetero,t.sstruc,t.inscode),o[t.index+c]=a,a+=1})),c+=t.atomStore.count,l+=t.modelStore.count}));const h=i.bondStore,d=i.getAtomProxy(),u=i.getAtomProxy();return c=0,e.forEach((t=>{t.eachBond((t=>{d.index=o[t.atomIndex1+c],u.index=o[t.atomIndex2+c],h.addBond(d,u,t.bondOrder)})),c+=t.atomStore.count})),r.finalize(),Ka(i,!0),Ya(i,!0),i.finalizeAtoms(),i.finalizeBonds(),ec(i),De&&Me.timeEnd("concatStructures"),i}const rc=[3,11,19,37,55,87],sc=[4,12,20,38,56,88],nc=[6,15,16,34],oc=[1,7,8,9,17,35,53],ac=[2,10,18,36,54,86],cc=[13,30,31,48,49,50,80,81,82,83,84,85,112],lc=[5,14,32,33,51,52,85],hc=[9,17,35,53,85];class dc{constructor(t,e,i){this.structure=t,this.atomname=e,i=i||tc(e),this.element=i,this.number=Xs[i]||0,this.vdw=Ys[this.number]||2,this.covalent=Ks[this.number]||1.6}getDefaultValence(){const t=Zs[this.number];return t?t[0]:-1}getValenceList(){return Zs[this.number]||[]}getOuterShellElectronCount(){return Qs[this.number]||2}isMetal(){return this.isAlkaliMetal()||this.isAlkalineEarthMetal()||this.isLanthanide()||this.isActinide()||this.isTransitionMetal()||this.isPostTransitionMetal()}isNonmetal(){return this.isDiatomicNonmetal()||this.isPolyatomicNonmetal()||this.isNobleGas()}isMetalloid(){return lc.includes(this.number)}isHalogen(){return hc.includes(this.number)}isDiatomicNonmetal(){return oc.includes(this.number)}isPolyatomicNonmetal(){return nc.includes(this.number)}isAlkaliMetal(){return rc.includes(this.number)}isAlkalineEarthMetal(){return sc.includes(this.number)}isNobleGas(){return ac.includes(this.number)}isTransitionMetal(){const t=this.number;return t>=21&&t<=29||t>=39&&t<=47||t>=72&&t<=79||t>=104&&t<=108}isPostTransitionMetal(){return cc.includes(this.number)}isLanthanide(){return this.number>=57&&this.number<=71}isActinide(){return this.number>=89&&this.number<=103}}class uc{constructor(t){this.structure=t,this.dict={},this.list=[],this.structure=t}add(t,e){const i=function(t,e){return t+"|"+e}(t=t.toUpperCase(),e=e?e.toUpperCase():tc(t));let r=this.dict[i];if(void 0===r){const s=new dc(this.structure,t,e);r=this.list.length,this.dict[i]=r,this.list.push(s)}return r}get(t){return this.list[t]}}class mc{constructor(t,e,i,r,s,n){this.structure=t,this.bondReferenceAtomIndices=[],this.resname=e,this.atomTypeIdList=i,this.hetero=r?1:0,this.chemCompType=s,this.bonds=n,this.atomCount=i.length,this.moleculeType=this.getMoleculeType(),this.backboneType=this.getBackboneType(0),this.backboneEndType=this.getBackboneType(-1),this.backboneStartType=this.getBackboneType(1),this.backboneIndexList=this.getBackboneIndexList();const o=mn[this.backboneType],a=mn[this.backboneStartType],c=mn[this.backboneEndType],l=this.getAtomIndexByName(o.trace);this.traceAtomIndex=st(l,-1);const h=this.getAtomIndexByName(o.direction1);this.direction1AtomIndex=st(h,-1);const d=this.getAtomIndexByName(o.direction2);this.direction2AtomIndex=st(d,-1);const u=this.getAtomIndexByName(a.backboneStart);this.backboneStartAtomIndex=st(u,-1);const m=this.getAtomIndexByName(c.backboneEnd);let p;this.backboneEndAtomIndex=st(m,-1),p=on.includes(e)?this.getAtomIndexByName("N1"):this.getAtomIndexByName("N3"),this.rungEndAtomIndex=st(p,-1)}getBackboneIndexList(){const t=[];let e;switch(this.moleculeType){case 3:e=dn;break;case 4:case 5:e=un;break;default:return t}const i=this.structure.atomMap,r=this.atomTypeIdList;for(let s=0,n=this.atomCount;s<n;++s){const n=i.get(r[s]);e.includes(n.atomname)&&t.push(s)}return t}getMoleculeType(){return this.isProtein()?3:this.isRna()?4:this.isDna()?5:this.isWater()?1:this.isIon()?2:this.isSaccharide()?6:0}getBackboneType(t){return this.hasProteinBackbone(t)?1:this.hasRnaBackbone(t)?2:this.hasDnaBackbone(t)?3:this.hasCgProteinBackbone(t)?4:this.hasCgRnaBackbone(t)?5:this.hasCgDnaBackbone(t)?6:Ns}isProtein(){return this.chemCompType?zs.includes(this.chemCompType):this.hasAtomWithName("CA","C","N")||rn.includes(this.resname)}isCg(){const t=this.backboneType;return 4===t||5===t||6===t}isNucleic(){return this.isRna()||this.isDna()}isRna(){return this.chemCompType?Vs.includes(this.chemCompType):1!==this.hetero&&(this.hasAtomWithName(["P","O3'","O3*"],["C4'","C4*"],["O2'","O2*","F2'","F2*"])||sn.includes(this.resname)&&this.hasAtomWithName(["O2'","O2*","F2'","F2*"]))}isDna(){return this.chemCompType?Gs.includes(this.chemCompType):1!==this.hetero&&(this.hasAtomWithName(["P","O3'","O3*"],["C3'","C3*"])&&!this.hasAtomWithName(["O2'","O2*","F2'","F2*"])||nn.includes(this.resname))}isHetero(){return 1===this.hetero}isIon(){return ln.includes(this.resname)}isWater(){return cn.includes(this.resname)}isSaccharide(){return this.chemCompType?Us.includes(this.chemCompType):hn.includes(this.resname)}isStandardAminoacid(){return rn.includes(this.resname)}isStandardBase(){return an.includes(this.resname)}hasBackboneAtoms(t,e){const i=mn[e];return-1===t?this.hasAtomWithName(i.trace,i.backboneEnd,i.direction1,i.direction2):0===t?this.hasAtomWithName(i.trace,i.direction1,i.direction2):1===t?this.hasAtomWithName(i.trace,i.backboneStart,i.direction1,i.direction2):this.hasAtomWithName(i.trace,i.backboneStart,i.backboneEnd,i.direction1,i.direction2)}hasProteinBackbone(t){return this.isProtein()&&this.hasBackboneAtoms(t,1)}hasRnaBackbone(t){return this.isRna()&&this.hasBackboneAtoms(t,2)}hasDnaBackbone(t){return this.isDna()&&this.hasBackboneAtoms(t,3)}hasCgProteinBackbone(t){return this.atomCount<7&&this.isProtein()&&this.hasBackboneAtoms(t,4)}hasCgRnaBackbone(t){return this.atomCount<11&&this.isRna()&&this.hasBackboneAtoms(t,5)}hasCgDnaBackbone(t){return this.atomCount<11&&this.isDna()&&this.hasBackboneAtoms(t,6)}hasBackbone(t){return this.hasProteinBackbone(t)||this.hasRnaBackbone(t)||this.hasDnaBackbone(t)||this.hasCgProteinBackbone(t)||this.hasCgRnaBackbone(t)||this.hasCgDnaBackbone(t)}getAtomIndexByName(t){const e=this.atomCount,i=this.structure.atomMap,r=this.atomTypeIdList;if(Array.isArray(t))for(let s=0;s<e;++s){const e=r[s];if(t.includes(i.get(e).atomname))return s}else for(let s=0;s<e;++s){const e=r[s];if(t===i.get(e).atomname)return s}}hasAtomWithName(...t){const e=t.length;for(let i=0;i<e;++i)if(void 0!==t[i]&&void 0===this.getAtomIndexByName(t[i]))return!1;return!0}getBonds(t){return void 0===this.bonds&&(this.bonds=function(t){const e=t.structure,i=e.getAtomProxy(),r=e.getAtomProxy(),s=t.atomCount,n=t.atomOffset,o=n+s-1,a=[],c=[],l=[];if(s>500)De&&Me.warn("more than 500 atoms, skip residue for auto-bonding",t.qualifiedName());else if(s>50){const e=new $a(t,!0),s=t.isCg()?1.2:2.3;for(let t=n;t<o;++t){i.index=t;const o=i.covalent+s+.3,h=e.nearest(i,1/0,o*o),d=h.length;for(let t=0;t<d;++t)r.index=h[t].index,i.index<r.index&&i.connectedTo(r)&&(a.push(i.index-n),c.push(r.index-n),l.push(Xa(i.resname,i.atomname,r.atomname)))}}else for(let t=n;t<o;++t){i.index=t;for(let e=t+1;e<=o;++e)r.index=e,i.connectedTo(r)&&(a.push(t-n),c.push(e-n),l.push(Xa(i.resname,i.atomname,r.atomname)))}return{atomIndices1:a,atomIndices2:c,bondOrders:l}}(t)),this.bonds}getRings(){return void 0===this.rings&&this.calculateRings(),this.rings}getBondGraph(){return void 0===this.bondGraph&&this.calculateBondGraph(),this.bondGraph}getAromatic(t){return void 0===this.aromaticAtoms&&this.calculateAromatic(this.structure.getResidueProxy(t.residueIndex)),this.aromaticAtoms}getAromaticRings(t){return void 0===this.aromaticRings&&this.calculateAromatic(t),this.aromaticRings}calculateBondGraph(){const t=this.bondGraph={},e=this.getBonds(),i=e.atomIndices1.length,r=e.atomIndices1,s=e.atomIndices2;for(let e=0;e<i;++e){const i=r[e],n=s[e];(t[i]=t[i]||[]).push(n);(t[n]=t[n]||[]).push(i)}}calculateRings(){const t=function(t,e){const i={count:e,visited:new Int32Array(e),queue:new Int32Array(e),pred:new Int32Array(e),left:new Int32Array(bc),right:new Int32Array(bc),color:new Int32Array(e),currentColor:0,rings:[],atomRings:[],bonds:t};for(let t=0;t<e;t++)i.visited[t]=-1,i.pred[t]=-1;return i}(this.getBondGraph(),this.atomCount);for(let e=0;e<t.count;e++)t.visited[e]>=0||yc(t,e);this.rings={atomRings:t.atomRings,rings:t.rings}}isAromatic(t){return this.aromaticAtoms=this.getAromatic(t),1===this.aromaticAtoms[t.index-t.residueAtomOffset]}calculateAromatic(t){const e=this.aromaticAtoms=new Uint8Array(this.atomCount),i=this.getRings().rings,r=i.map((e=>function(t){if(t.some((t=>!pc.includes(t.number))))return!1;let e=0;const i=new ho(3,t.length),r=i.data;t.forEach((t=>{r[e+0]=t.x,r[e+1]=t.y,r[e+2]=t.z,e+=3}));return new ya(i).vecC.length()<fc}(e.map((e=>this.structure.getAtomProxy(e+t.atomOffset)))))),s=this.aromaticRings=[];i.forEach(((t,i)=>{r[i]&&(s.push(t),t.forEach((t=>e[t]=1)))}))}assignBondReferenceAtomIndices(){const t=this.getBondGraph(),e=this.getRings(),i=e.atomRings,r=e.rings,s=this.bonds,n=s.atomIndices1,o=s.atomIndices2,a=s.bondOrders,c=this.bondReferenceAtomIndices,l=s.atomIndices1.length;c.length=0;for(let e=0;e<l;++e){if(a[e]<=1)continue;let s;const l=n[e],h=o[e],d=i[l],u=i[h];if(d&&u)for(let t=0;t<d.length;t++)if(-1!==u.indexOf(d[t])){s=r[d[t]];break}if(t[l].length>1)for(let i=0;i<t[l].length;++i){const r=t[l][i];if(r!==h&&(void 0===s||-1!==s.indexOf(r))){c[e]=r;break}}else if(t[h].length>1)for(let i=0;i<t[h].length;++i){const r=t[h][i];if(r!==l&&(void 0===s||-1!==s.indexOf(r))){c[e]=r;break}}}}getBondIndex(t,e){const i=this.bonds,r=i.atomIndices1,s=i.atomIndices2;let n=r.indexOf(t),o=s.indexOf(e);const a=o;for(;-1!==n;){for(;-1!==o;){if(n===o)return n;o=s.indexOf(e,o+1)}n=r.indexOf(t,n+1),o=a}}getBondReferenceAtomIndex(t,e){const i=this.getBondIndex(t,e);if(void 0!==i)return 0===this.bondReferenceAtomIndices.length&&this.assignBondReferenceAtomIndices(),this.bondReferenceAtomIndices[i]}}const pc=[5,6,7,8,14,15,16,32,33,50,51,83],fc=.05;function gc(t,e,i){if(i<e)return;const{pred:r,color:s,left:n,right:o}=t,a=++t.currentColor;let c=e;for(let t=0;t<bc&&(s[c]=a,c=r[c],!(c<0));t++);let l=0,h=0,d=!1,u=0;c=i;for(let t=0;t<bc;t++){if(s[c]===a){u=c,d=!0;break}if(o[h++]=c,c=r[c],c<0)break}if(!d)return;c=e;for(let t=0;t<bc&&(n[l++]=c,u!==c)&&(c=r[c],!(c<0));t++);const m=l+h,p=new Array(m);let f=0;for(let t=0;t<l;t++)p[f++]=n[t];for(let t=h-1;t>=0;t--)p[f++]=o[t];const g=t.rings.length;for(let e=0;e<m;++e){const i=p[e];t.atomRings[i]?t.atomRings[i].push(g):t.atomRings[i]=[g]}t.rings.push(p)}function yc(t,e){const{bonds:i,visited:r,queue:s,pred:n}=t;r[e]=1,s[0]=e;let o=0,a=1;for(;o<a;){const e=s[o++],c=0;if(void 0===i[e])continue;const l=i[e].length;for(let o=c;o<l;o++){const c=i[e][o];r[c]>0?n[c]!==e&&n[e]!==c&&gc(t,e,c):(r[c]=1,s[a++]=c,n[c]=e)}}}const bc=4;class xc{constructor(t){this.structure=t,this.dict={},this.list=[]}add(t,e,i,r="",s){const n=function(t,e,i,r=""){return t+"|"+e.join(",")+"|"+(i?1:0)+"|"+r}(t=t.toUpperCase(),e,i,r);let o=this.dict[n];if(void 0===o){const a=new mc(this.structure,t,e,i,r,s);o=this.list.length,this.dict[n]=o,this.list.push(a)}return o}get(t){return this.list[t]}}class vc{constructor(t,i=0){this.structure=t,this.index=i,this.bondStore=t.bondStore,this._v12=new e,this._v13=new e,this._ap1=this.structure.getAtomProxy(),this._ap2=this.structure.getAtomProxy(),this._ap3=this.structure.getAtomProxy()}get atom1(){return this.structure.getAtomProxy(this.atomIndex1)}get atom2(){return this.structure.getAtomProxy(this.atomIndex2)}get atomIndex1(){return this.bondStore.atomIndex1[this.index]}set atomIndex1(t){this.bondStore.atomIndex1[this.index]=t}get atomIndex2(){return this.bondStore.atomIndex2[this.index]}set atomIndex2(t){this.bondStore.atomIndex2[this.index]=t}get bondOrder(){return this.bondStore.bondOrder[this.index]}set bondOrder(t){this.bondStore.bondOrder[this.index]=t}getOtherAtomIndex(t){return t===this.atomIndex1?this.atomIndex2:this.atomIndex1}getOtherAtom(t){return this.structure.getAtomProxy(this.getOtherAtomIndex(t.index))}getReferenceAtomIndex(){const t=this._ap1,e=this._ap2;if(t.index=this.atomIndex1,e.index=this.atomIndex2,t.residueIndex!==e.residueIndex)return;const i=t.index-t.residueAtomOffset,r=e.index-e.residueAtomOffset,s=t.residueType.getBondReferenceAtomIndex(i,r);if(void 0!==s)return s+t.residueAtomOffset;console.warn("No reference atom found",t.index,e.index)}calculateShiftDir(t=new e){const i=this._ap1,r=this._ap2,s=this._ap3,n=this._v12,o=this._v13;i.index=this.atomIndex1,r.index=this.atomIndex2;const a=this.getReferenceAtomIndex();n.subVectors(i,r).normalize(),void 0!==a?(s.index=a,o.subVectors(i,s)):o.copy(i),o.normalize();let c=n.dot(o);return 1-Math.abs(c)<1e-5&&(o.set(1,0,0),c=n.dot(o),1-Math.abs(c)<1e-5&&(o.set(0,1,0),c=n.dot(o))),t.copy(o.sub(n.multiplyScalar(c))).normalize()}qualifiedName(){return this.atomIndex1+"="+this.atomIndex2}clone(){return new vc(this.structure,this.index)}toObject(){return{atomIndex1:this.atomIndex1,atomIndex2:this.atomIndex2,bondOrder:this.bondOrder}}}class wc{constructor(t,e=0){this.structure=t,this.index=e,this.chainStore=t.chainStore,this.residueStore=t.residueStore,this.atomStore=t.atomStore,this.residueMap=t.residueMap,this.atomMap=t.atomMap}get entity(){return this.structure.entityList[this.entityIndex]}get entityIndex(){return this.chainStore.entityIndex[this.chainIndex]}get chain(){return this.structure.getChainProxy(this.chainIndex)}get chainIndex(){return this.residueStore.chainIndex[this.index]}set chainIndex(t){this.residueStore.chainIndex[this.index]=t}get atomOffset(){return this.residueStore.atomOffset[this.index]}set atomOffset(t){this.residueStore.atomOffset[this.index]=t}get atomCount(){return this.residueStore.atomCount[this.index]}set atomCount(t){this.residueStore.atomCount[this.index]=t}get atomEnd(){return this.atomOffset+this.atomCount-1}get modelIndex(){return this.chainStore.modelIndex[this.chainIndex]}get chainname(){return this.chainStore.getChainname(this.chainIndex)}get chainid(){return this.chainStore.getChainid(this.chainIndex)}get resno(){return this.residueStore.resno[this.index]}set resno(t){this.residueStore.resno[this.index]=t}get sstruc(){return this.residueStore.getSstruc(this.index)}set sstruc(t){this.residueStore.setSstruc(this.index,t)}get inscode(){return this.residueStore.getInscode(this.index)}set inscode(t){this.residueStore.setInscode(this.index,t)}get residueType(){return this.residueMap.get(this.residueStore.residueTypeId[this.index])}get resname(){return this.residueType.resname}get hetero(){return this.residueType.hetero}get moleculeType(){return this.residueType.moleculeType}get backboneType(){return this.residueType.backboneType}get backboneStartType(){return this.residueType.backboneStartType}get backboneEndType(){return this.residueType.backboneEndType}get traceAtomIndex(){return this.residueType.traceAtomIndex+this.atomOffset}get direction1AtomIndex(){return this.residueType.direction1AtomIndex+this.atomOffset}get direction2AtomIndex(){return this.residueType.direction2AtomIndex+this.atomOffset}get backboneStartAtomIndex(){return this.residueType.backboneStartAtomIndex+this.atomOffset}get backboneEndAtomIndex(){return this.residueType.backboneEndAtomIndex+this.atomOffset}get rungEndAtomIndex(){return this.residueType.rungEndAtomIndex+this.atomOffset}get x(){let t=0;for(let e=this.atomOffset;e<=this.atomEnd;++e)t+=this.atomStore.x[e];return t/this.atomCount}get y(){let t=0;for(let e=this.atomOffset;e<=this.atomEnd;++e)t+=this.atomStore.y[e];return t/this.atomCount}get z(){let t=0;for(let e=this.atomOffset;e<=this.atomEnd;++e)t+=this.atomStore.z[e];return t/this.atomCount}eachAtom(t,e){const i=this.atomCount,r=this.atomOffset,s=this.structure._ap,n=r+i;if(e&&e.atomOnlyTest){const i=e.atomOnlyTest;for(let e=r;e<n;++e)s.index=e,i(s)&&t(s)}else for(let e=r;e<n;++e)s.index=e,t(s)}positionToArray(t=[],e=0){return t[e+0]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}isProtein(){return 3===this.residueType.moleculeType}isNucleic(){const t=this.residueType.moleculeType;return 4===t||5===t}isRna(){return 4===this.residueType.moleculeType}isDna(){return 5===this.residueType.moleculeType}isCg(){const t=this.residueType.backboneType;return 4===t||5===t||6===t}isPolymer(){if(this.structure.entityList.length>0)return this.entity.isPolymer();{const t=this.residueType.moleculeType;return 3===t||4===t||5===t}}isHetero(){return 1===this.residueType.hetero}isWater(){return 1===this.residueType.moleculeType}isIon(){return 2===this.residueType.moleculeType}isSaccharide(){return 6===this.residueType.moleculeType}isStandardAminoacid(){return this.residueType.isStandardAminoacid()}isStandardBase(){return this.residueType.isStandardBase()}isHelix(){return Hs.includes(this.sstruc)}isSheet(){return Ws.includes(this.sstruc)}isTurn(){return qs.includes(this.sstruc)&&this.isProtein()}getAtomType(t){return this.atomMap.get(this.atomStore.atomTypeId[t])}getResname1(){return en[this.resname.toUpperCase()]||"X"}getBackboneType(t){switch(t){case-1:return this.residueType.backboneStartType;case 1:return this.residueType.backboneEndType;default:return this.residueType.backboneType}}getAtomIndexByName(t){let e=this.residueType.getAtomIndexByName(t);return void 0!==e&&(e+=this.atomOffset),e}hasAtomWithName(t){return this.residueType.hasAtomWithName(t)}getAtomnameList(){console.warn("getAtomnameList - might be expensive");const t=this.atomCount,e=this.atomOffset,i=new Array(t);for(let r=0;r<t;++r)i[r]=this.getAtomType(e+r).atomname;return i}connectedTo(t){const e=this.structure.getAtomProxy(this.backboneEndAtomIndex),i=this.structure.getAtomProxy(t.backboneStartAtomIndex);return!(!e||!i)&&e.connectedTo(i)}getNextConnectedResidue(){const t=this.chainStore.residueOffset[this.chainIndex],e=this.chainStore.residueCount[this.chainIndex],i=this.index+1;if(i<t+e){const t=this.structure.getResidueProxy(i);if(this.connectedTo(t))return t}else if(i===t+e){const e=this.structure.getResidueProxy(t);if(this.connectedTo(e))return e}}getPreviousConnectedResidue(t){const e=this.chainStore.residueOffset[this.chainIndex],i=this.index-1;if(i>=e){const e=st(t,this.structure.getResidueProxy());if(e.index=i,e.connectedTo(this))return e}else if(i===e-1){const i=this.chainStore.residueCount[this.chainIndex],r=st(t,this.structure.getResidueProxy());if(r.index=e+i-1,r.connectedTo(this))return r}}getBonds(){return this.residueType.getBonds(this)}getRings(){return this.residueType.getRings()}getAromaticRings(){return this.residueType.getAromaticRings(this)}qualifiedName(t=!1){let e="";return this.resname&&!t&&(e+="["+this.resname+"]"),void 0!==this.resno&&(e+=this.resno),this.inscode&&(e+="^"+this.inscode),this.chain&&(e+=":"+this.chainname),e+="/"+this.modelIndex,e}clone(){return new wc(this.structure,this.index)}toObject(){return{index:this.index,chainIndex:this.chainIndex,atomOffset:this.atomOffset,atomCount:this.atomCount,resno:this.resno,resname:this.resname,sstruc:this.sstruc}}}class Ac{constructor(t,e,i){this.structure=t,this.residueIndexStart=e,this.residueIndexEnd=i,this.chainStore=t.chainStore,this.residueStore=t.residueStore,this.atomStore=t.atomStore,this.residueCount=i-e+1;const r=this.structure.getResidueProxy(this.residueIndexStart),s=this.structure.getResidueProxy(this.residueIndexEnd);this.isPrevConnected=void 0!==r.getPreviousConnectedResidue();const n=s.getNextConnectedResidue();this.isNextConnected=void 0!==n,this.isNextNextConnected=void 0!==n&&void 0!==n.getNextConnectedResidue(),this.isCyclic=s.connectedTo(r),this.__residueProxy=this.structure.getResidueProxy()}get chainIndex(){return this.residueStore.chainIndex[this.residueIndexStart]}get modelIndex(){return this.chainStore.modelIndex[this.chainIndex]}get chainname(){return this.chainStore.getChainname(this.chainIndex)}isProtein(){return this.__residueProxy.index=this.residueIndexStart,this.__residueProxy.isProtein()}isCg(){return this.__residueProxy.index=this.residueIndexStart,this.__residueProxy.isCg()}isNucleic(){return this.__residueProxy.index=this.residueIndexStart,this.__residueProxy.isNucleic()}getMoleculeType(){return this.__residueProxy.index=this.residueIndexStart,this.__residueProxy.moleculeType}getBackboneType(t){return this.__residueProxy.index=this.residueIndexStart,this.__residueProxy.getBackboneType(t)}getAtomIndexByType(t,e){this.isCyclic?-1===t?t=this.residueCount-1:t===this.residueCount&&(t=0):(-1!==t||this.isPrevConnected||(t+=1),t!==this.residueCount||this.isNextNextConnected||(t-=1));const i=this.__residueProxy;let r;switch(i.index=this.residueIndexStart+t,e){case"trace":r=i.traceAtomIndex;break;case"direction1":r=i.direction1AtomIndex;break;case"direction2":r=i.direction2AtomIndex;break;default:r=i.getAtomIndexByName(e)}return r}eachAtom(t,e){this.eachResidue((function(i){i.eachAtom(t,e)}))}eachAtomN(t,e,i){const r=this.residueCount,s=new Array(t);for(let e=0;e<t;++e)s[e]=this.structure.getAtomProxy(this.getAtomIndexByType(e,i));e.apply(this,s);for(var n=t;n<r;++n){for(let e=1;e<t;++e)s[e-1].index=s[e].index;s[t-1].index=this.getAtomIndexByType(n,i),e.apply(this,s)}}eachResidue(t){const e=this.structure.getResidueProxy(),i=this.residueCount,r=this.residueIndexStart;for(let s=0;s<i;++s)e.index=r+s,t(e)}qualifiedName(){const t=this.structure.getResidueProxy(this.residueIndexStart),e=this.structure.getResidueProxy(this.residueIndexEnd);return t.qualifiedName()+" - "+e.qualifiedName()}}class _c{constructor(t,e=0){this.structure=t,this.index=e,this.chainStore=t.chainStore,this.residueStore=t.residueStore}get entity(){return this.structure.entityList[this.entityIndex]}get model(){return this.structure.getModelProxy(this.modelIndex)}get entityIndex(){return this.chainStore.entityIndex[this.index]}set entityIndex(t){this.chainStore.entityIndex[this.index]=t}get modelIndex(){return this.chainStore.modelIndex[this.index]}set modelIndex(t){this.chainStore.modelIndex[this.index]=t}get residueOffset(){return this.chainStore.residueOffset[this.index]}set residueOffset(t){this.chainStore.residueOffset[this.index]=t}get residueCount(){return this.chainStore.residueCount[this.index]}set residueCount(t){this.chainStore.residueCount[this.index]=t}get residueEnd(){return this.residueOffset+this.residueCount-1}get atomOffset(){return this.residueStore.atomOffset[this.residueOffset]}get atomEnd(){return this.residueStore.atomOffset[this.residueEnd]+this.residueStore.atomCount[this.residueEnd]-1}get atomCount(){return 0===this.residueCount?0:this.atomEnd-this.atomOffset+1}get chainname(){return this.chainStore.getChainname(this.index)}set chainname(t){this.chainStore.setChainname(this.index,t)}get chainid(){return this.chainStore.getChainid(this.index)}set chainid(t){this.chainStore.setChainid(this.index,t)}eachAtom(t,e){this.eachResidue((function(i){i.eachAtom(t,e)}),e)}eachResidue(t,e){const i=this.residueCount,r=this.residueOffset,s=this.structure._rp,n=r+i;if(e&&e.test){const i=e.residueOnlyTest;if(i)for(let e=r;e<n;++e)s.index=e,i(s)&&t(s);else for(let e=r;e<n;++e)s.index=e,t(s)}else for(let e=r;e<n;++e)s.index=e,t(s)}eachResidueN(t,e){const i=this.residueCount,r=this.residueOffset,s=r+i;if(i<t)return;const n=new Array(t);for(let e=0;e<t;++e)n[e]=this.structure.getResidueProxy(r+e);e.apply(this,n);for(let i=r+t;i<s;++i){for(let e=0;e<t;++e)n[e].index+=1;e.apply(this,n)}}eachPolymer(t,e){let i=0,r=0;const s=e?e.residueOnlyTest:void 0,n=this.model.structure,o=this.residueCount,a=this.residueOffset,c=a+o,l=this.structure.getResidueProxy(),h=this.structure.getResidueProxy(a),d=this.structure.getAtomProxy(),u=this.structure.getAtomProxy();let m=!0;for(let e=a+1;e<c;++e){l.index=h.index,h.index=e;const o=m?l.backboneEndType:l.backboneType,a=h.backboneType;m&&(i=l.index,m=!1),r=h.index,o!==Ns&&o===a?(d.index=l.backboneEndAtomIndex,u.index=h.backboneStartAtomIndex,d&&u&&d.connectedTo(u)&&(!s||s(l)&&s(h))||(l.index-i>1&&t(new Ac(n,i,l.index)),i=r)):(o!==Ns&&l.index-i>1&&t(new Ac(n,i,l.index)),i=r)}r-i>1&&this.structure.getResidueProxy(i).backboneEndType&&t(new Ac(n,i,r))}qualifiedName(){return":"+this.chainname+"/"+this.modelIndex}clone(){return new _c(this.structure,this.index)}toObject(){return{index:this.index,residueOffset:this.residueOffset,residueCount:this.residueCount,chainname:this.chainname}}}class Sc{constructor(t,e=0){this.structure=t,this.index=e,this.modelStore=t.modelStore,this.chainStore=t.chainStore,this.residueStore=t.residueStore}get chainOffset(){return this.modelStore.chainOffset[this.index]}set chainOffset(t){this.modelStore.chainOffset[this.index]=t}get chainCount(){return this.modelStore.chainCount[this.index]}set chainCount(t){this.modelStore.chainCount[this.index]=t}get residueOffset(){return this.chainStore.residueOffset[this.chainOffset]}get atomOffset(){return this.residueStore.atomOffset[this.residueOffset]}get chainEnd(){return this.chainOffset+this.chainCount-1}get residueEnd(){return this.chainStore.residueOffset[this.chainEnd]+this.chainStore.residueCount[this.chainEnd]-1}get atomEnd(){return this.residueStore.atomOffset[this.residueEnd]+this.residueStore.atomCount[this.residueEnd]-1}get residueCount(){return 0===this.chainCount?0:this.residueEnd-this.residueOffset+1}get atomCount(){return 0===this.residueCount?0:this.atomEnd-this.atomOffset+1}eachAtom(t,e){this.eachChain((function(i){i.eachAtom(t,e)}),e)}eachResidue(t,e){this.eachChain((function(i){i.eachResidue(t,e)}),e)}eachPolymer(t,e){if(e&&e.chainOnlyTest){const i=e.chainOnlyTest;this.eachChain((function(r){i(r)&&r.eachPolymer(t,e)}))}else this.eachChain((function(i){i.eachPolymer(t,e)}))}eachChain(t,e){const i=this.chainCount,r=this.chainOffset,s=this.structure._cp,n=r+i;if(e&&e.test){const i=e.chainOnlyTest;if(i)for(let e=r;e<n;++e)s.index=e,i(s)&&t(s);else for(let e=r;e<n;++e)s.index=e,t(s)}else for(let e=r;e<n;++e)s.index=e,t(s)}qualifiedName(){return"/"+this.index}clone(){return new Sc(this.structure,this.index)}toObject(){return{index:this.index,chainOffset:this.chainOffset,chainCount:this.chainCount}}}class Cc{constructor(t="",e=""){this.signals={refreshed:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.init(t,e)}init(t,i){this.name=t,this.path=i,this.title="",this.id="",this.data={structure:this,"@spatialLookup":void 0,"@valenceModel":void 0},this.header={},this.extraData={},this.atomSetCache={},this.atomSetDict={},this.biomolDict={},this.entityList=[],this.unitcell=void 0,this.frames=[],this.boxes=[],this.validation=void 0,this.bondStore=new va(0),this.backboneBondStore=new va(0),this.rungBondStore=new va(0),this.atomStore=new wa(0),this.residueStore=new Aa(0),this.chainStore=new _a(0),this.modelStore=new Sa(0),this.atomMap=new uc(this),this.residueMap=new xc(this),this.bondHash=void 0,this.spatialHash=void 0,this.atomSet=void 0,this.bondSet=void 0,this.center=new e,this.boundingBox=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],this._bp=this.getBondProxy(),this._ap=this.getAtomProxy(),this._rp=this.getResidueProxy(),this._cp=this.getChainProxy()}get type(){return"Structure"}finalizeAtoms(){this.atomSet=this.getAtomSet(),this.atomCount=this.atomStore.count,this.boundingBox=this.getBoundingBox(void 0,this.boundingBox),this.center=this.boundingBox.getCenter(new e),this.spatialHash=new Ts(this.atomStore,this.boundingBox)}finalizeBonds(){this.bondSet=this.getBondSet(),this.bondCount=this.bondStore.count,this.bondHash=new xa(this.bondStore,this.atomStore.count),this.atomSetCache={},this.atomSetDict.rung||(this.atomSetDict.rung=this.getAtomSet(!1));for(let t in this.atomSetDict)this.atomSetCache["__"+t]=this.atomSetDict[t].clone()}getBondProxy(t){return new vc(this,t)}getAtomProxy(t){return new Ma(this,t)}getResidueProxy(t){return new wc(this,t)}getChainProxy(t){return new _c(this,t)}getModelProxy(t){return new Sc(this,t)}getBondSet(){const t=this.bondStore.count,e=new Os(t),i=this.atomSet;if(i)if(i.isAllSet())e.setAll();else if(i.isAllClear())e.clearAll();else{const r=this.getBondProxy();for(let s=0;s<t;++s)r.index=s,i.isSet(r.atomIndex1,r.atomIndex2)&&e.set(r.index)}else e.setAll();return e}getBackboneBondSet(){const t=this.backboneBondStore.count,e=new Os(t),i=this.atomSetCache.__backbone;if(i){const r=this.getBondProxy();r.bondStore=this.backboneBondStore;for(let s=0;s<t;++s)r.index=s,i.isSet(r.atomIndex1,r.atomIndex2)&&e.set(r.index)}else e.setAll();return e}getRungBondSet(){const t=this.rungBondStore.count,e=new Os(t),i=this.atomSetCache.__rung;if(i){const r=this.getBondProxy();r.bondStore=this.rungBondStore;for(let s=0;s<t;++s)r.index=s,i.isSet(r.atomIndex1,r.atomIndex2)&&e.set(r.index)}else e.setAll();return e}getAtomSet(t){const e=this.atomStore.count;if(void 0===t)return new Os(e,!0);if(t instanceof Os)return t;if(!0===t)return new Os(e,!0);if(t&&t.test){const i=t.string;if(i in this.atomSetCache)return this.atomSetCache[i];if(""===i)return new Os(e,!0);{const r=new Os(e);return this.eachAtom((function(t){r.set(t.index)}),t),this.atomSetCache[i]=r,r}}return!1===t?new Os(e):new Os(e,!0)}getAtomSetWithinSelection(t,e){const i=this.spatialHash,r=this.getAtomSet(!1),s=this.getAtomProxy();return i?(this.getAtomSet(t).forEach((function(t){s.index=t,i.within(s.x,s.y,s.z,e).forEach((function(t){r.set(t)}))})),r):r}getAtomSetWithinPoint(t,e){const i=t,r=this.getAtomSet(!1);return this.spatialHash?(this.spatialHash.within(i.x,i.y,i.z,e).forEach((function(t){r.set(t)})),r):r}getAtomSetWithinVolume(t,e,i,r,s){const n=new ba(t,i,r,s),o=n.getDataPosition(),a=o.length,c=n.matrix.getMaxScaleOnAxis(),l=this.getAtomSet(!1);if(!this.spatialHash)return l;for(let t=0;t<a;t+=3)this.spatialHash.within(o[t],o[t+1],o[t+2],c).forEach((function(t){l.set(t)}));return l}getAtomSetWithinGroup(t){const e=this.atomStore.residueIndex,i=this.getAtomSet(!1),r=this.getResidueProxy();return this.getAtomSet(t).forEach((function(t){r.index=e[t];for(let t=r.atomOffset;t<=r.atomEnd;++t)i.set(t)})),i}getSelection(){}getStructure(){return this}eachEntity(t,e){this.entityList.forEach((function(i){void 0!==e&&i.getEntityType()!==e||t(i)}))}eachBond(t,e){const i=this.getBondProxy();let r;if(e&&e.test&&(r=this.getBondSet(),this.bondSet&&r.intersection(this.bondSet)),r)r.forEach((function(e){i.index=e,t(i)}));else{const e=this.bondStore.count;for(let r=0;r<e;++r)i.index=r,t(i)}}eachAtom(t,e){if(e&&e.test)this.eachModel((function(i){i.eachAtom(t,e)}),e);else{const e=this.atomStore.count,i=this.getAtomProxy();for(let r=0;r<e;++r)i.index=r,t(i)}}eachResidue(t,e){if(e&&e.test){const i=this.modelStore.count,r=this.getModelProxy(),s=e.modelOnlyTest;if(s)for(let n=0;n<i;++n)r.index=n,s(r)&&r.eachResidue(t,e);else for(let s=0;s<i;++s)r.index=s,r.eachResidue(t,e)}else{const e=this.residueStore.count,i=this.getResidueProxy();for(let r=0;r<e;++r)i.index=r,t(i)}}eachResidueN(t,e){const i=this.residueStore.count;if(i<t)return;const r=new Array(t);for(let e=0;e<t;++e)r[e]=this.getResidueProxy(e);e.apply(this,r);for(let s=t;s<i;++s){for(let e=0;e<t;++e)r[e].index+=1;e.apply(this,r)}}eachPolymer(t,e){if(e&&e.modelOnlyTest){const i=e.modelOnlyTest;this.eachModel((function(r){i(r)&&r.eachPolymer(t,e)}))}else this.eachModel((function(i){i.eachPolymer(t,e)}))}eachChain(t,e){if(e&&e.test)this.eachModel((function(i){i.eachChain(t,e)}));else{const e=this.chainStore.count,i=this.getChainProxy();for(let r=0;r<e;++r)i.index=r,t(i)}}eachModel(t,e){const i=this.modelStore.count,r=this.getModelProxy();if(e&&e.test){const s=e.modelOnlyTest;if(s)for(let e=0;e<i;++e)r.index=e,s(r)&&t(r);else for(let e=0;e<i;++e)r.index=e,t(r)}else for(let e=0;e<i;++e)r.index=e,t(r)}getAtomData(t){const e=Object.assign({},t);e.colorParams&&(e.colorParams.structure=this.getStructure());const i=e.what,r=st(e.atomSet,this.atomSet);let s,n;const o={},a=this.getAtomProxy(),c=r.getSize();i&&!i.position||(o.position=new Float32Array(3*c)),i&&!i.color||!e.colorParams||(o.color=new Float32Array(3*c),n=Fe.getScheme(e.colorParams)),i&&!i.picking||(o.picking=new Yn(new Float32Array(c),this.getStructure())),i&&!i.radius||(o.radius=new Float32Array(c),s=new pa(e.radiusParams)),i&&!i.index||(o.index=new Uint32Array(c));const{position:l,color:h,picking:d,radius:u,index:m}=o;return r.forEach(((t,e)=>{const i=3*e;a.index=t,l&&a.positionToArray(l,i),h&&n.atomColorToArray(a,h,i),d&&(d.array[e]=t),u&&(u[e]=s.atomRadius(a)),m&&(m[e]=t)})),o}getBondData(t){const i=Object.assign({},t);i.colorParams&&(i.colorParams.structure=this.getStructure());const r=i.what,s=st(i.bondSet,this.bondSet),n=st(i.multipleBond,"off"),o="off"!==n,a="offset"===n,c=st(i.bondScale,.4),l=st(i.bondSpacing,1);let h,d;const u={},m=this.getBondProxy();i.bondStore&&(m.bondStore=i.bondStore);const p=this.getAtomProxy(),f=this.getAtomProxy();let g;if(o){const t=m.bondStore.bondOrder;g=0,s.forEach((function(e){g+=t[e]}))}else g=s.getSize();r&&!r.position||(u.position1=new Float32Array(3*g),u.position2=new Float32Array(3*g)),r&&!r.color||!i.colorParams||(u.color=new Float32Array(3*g),u.color2=new Float32Array(3*g),d=Fe.getScheme(i.colorParams)),r&&!r.picking||(u.picking=new Zn(new Float32Array(g),this.getStructure(),i.bondStore)),(!r||r.radius||o&&r.position)&&(h=new pa(i.radiusParams)),r&&!r.radius||(u.radius=new Float32Array(g),i.radius2&&(u.radius2=new Float32Array(g)));const{position1:y,position2:b,color:x,color2:v,picking:w,radius:A,radius2:_}=u;let S,C,P,I,k,M,T=0;const B=new e,D=new e,$=new e;return s.forEach((t=>{if(C=3*T,m.index=t,p.index=m.atomIndex1,f.index=m.atomIndex2,I=m.bondOrder,y)if(o&&I>1){const t=h.atomRadius(p);M=t*c/(.5*I),m.calculateShiftDir($),a?(k=2*l*t,$.multiplyScalar(k),$.negate(),D.subVectors(f,p).multiplyScalar(Math.max(.1,k/1.88)),p.positionToArray(y,C),f.positionToArray(b,C),I>=2&&(B.addVectors(p,$).add(D).toArray(y,C+3),B.addVectors(f,$).sub(D).toArray(b,C+3),I>=3&&(B.subVectors(p,$).add(D).toArray(y,C+6),B.subVectors(f,$).sub(D).toArray(b,C+6)))):(k=(l-c)*t,$.multiplyScalar(k),2===I?(B.addVectors(p,$).toArray(y,C),B.subVectors(p,$).toArray(y,C+3),B.addVectors(f,$).toArray(b,C),B.subVectors(f,$).toArray(b,C+3)):3===I?(p.positionToArray(y,C),B.addVectors(p,$).toArray(y,C+3),B.subVectors(p,$).toArray(y,C+6),f.positionToArray(b,C),B.addVectors(f,$).toArray(b,C+3),B.subVectors(f,$).toArray(b,C+6)):(p.positionToArray(y,C),f.positionToArray(b,C)))}else p.positionToArray(y,C),f.positionToArray(b,C);if(x&&v&&(d.bondColorToArray(m,1,x,C),d.bondColorToArray(m,0,v,C),o&&I>1))for(S=1;S<I;++S)P=3*S+C,Ti(x,C,P,3),Ti(v,C,P,3);if(w&&w.array&&(w.array[T]=t,o&&I>1))for(S=1;S<I;++S)w.array[T+S]=t;if(A&&(A[T]=h.atomRadius(p),o&&I>1))for(M=A[T]*c/(a?1:.5*I),S=a?1:0;S<I;++S)A[T+S]=M;if(_&&(_[T]=h.atomRadius(f),o&&I>1))for(M=_[T]*c/(a?1:.5*I),S=a?1:0;S<I;++S)_[T+S]=M;T+=o?I:1})),u}getBackboneAtomData(t){return t=Object.assign({atomSet:this.atomSetCache.__backbone},t),this.getAtomData(t)}getBackboneBondData(t){return t=Object.assign({bondSet:this.getBackboneBondSet(),bondStore:this.backboneBondStore},t),this.getBondData(t)}getRungAtomData(t){return t=Object.assign({atomSet:this.atomSetCache.__rung},t),this.getAtomData(t)}getRungBondData(t){return t=Object.assign({bondSet:this.getRungBondSet(),bondStore:this.rungBondStore},t),this.getBondData(t)}getBoundingBox(t,e){De&&Me.time("getBoundingBox"),e=e||new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */];let i=1/0,r=1/0,s=1/0,n=-1/0,o=-1/0,c=-1/0;return this.eachAtom((t=>{const e=t.x,a=t.y,l=t.z;e<i&&(i=e),a<r&&(r=a),l<s&&(s=l),e>n&&(n=e),a>o&&(o=a),l>c&&(c=l)}),t),e.min.set(i,r,s),e.max.set(n,o,c),De&&Me.timeEnd("getBoundingBox"),e}getPrincipalAxes(t){De&&Me.time("getPrincipalAxes");let e=0;const i=new ho(3,this.atomCount),r=i.data;return this.eachAtom((t=>{r[e+0]=t.x,r[e+1]=t.y,r[e+2]=t.z,e+=3}),t),De&&Me.timeEnd("getPrincipalAxes"),new ya(i)}atomCenter(t){return t?this.getBoundingBox(t).getCenter(new e):this.center.clone()}hasCoords(){if(void 0===this._hasCoords){const t=this.atomStore;this._hasCoords=0!==Di(t.x)||0!==Bi(t.x)||0!==Di(t.y)||0!==Bi(t.y)||0!==Di(t.z)||0!==Bi(t.z)||t.count/this.modelStore.count==1}return this._hasCoords}getSequence(t){const e=[],i=this.getResidueProxy();return this.eachAtom((function(t){i.index=t.residueIndex,t.index===i.traceAtomIndex&&e.push(i.getResname1())}),t),e}getAtomIndices(t){if(t&&t.string){const e=[];return this.eachAtom((function(t){e.push(t.index)}),t),new Uint32Array(e)}{const t={what:{index:!0}};return this.getAtomData(t).index}}getChainnameCount(t){const e=new Set;return this.eachChain((function(t){t.residueCount&&e.add(t.chainname)}),t),e.size}updatePosition(t,e=!0){let i=0;this.eachAtom((function(e){e.positionFromArray(t,i),i+=3}),void 0),this._hasCoords=void 0,e&&this.refreshPosition()}refreshPosition(){this.getBoundingBox(void 0,this.boundingBox),this.boundingBox.getCenter(this.center),this.spatialHash=new Ts(this.atomStore,this.boundingBox),this.signals.refreshed.dispatch(this)}dispose(){this.frames&&(this.frames.length=0),this.boxes&&(this.boxes.length=0),this.bondStore.dispose(),this.backboneBondStore.dispose(),this.rungBondStore.dispose(),this.atomStore.dispose(),this.residueStore.dispose(),this.chainStore.dispose(),this.modelStore.dispose(),delete this.bondSet,delete this.atomSet}}const Pc=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],Ic=[_s,xs,Ss,As,Cs,vs,bs,ws,Is,Ps,ks,Ms],kc={aspectRatio:1.5,sphereDetail:2,radialSegments:50,disableImpostor:!1,openEnded:!1,dashedCylinder:!1,labelParams:{},pointSize:2,sizeAttenuation:!1,useTexture:!0,linewidth:2};class Mc{constructor(t="shape",e={}){this.boundingBox=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],this.bufferList=[],this.meshCount=0,this._primitiveData={},this.name=t,this.parameters=nt(e,kc),Ic.forEach((t=>{Object.keys(t.fields).forEach((e=>{this._primitiveData[t.getShapeKey(e)]=[]})),this._primitiveData[t.getShapeKey("name")]=[]}))}addBuffer(t){this.bufferList.push(t);const e=t.geometry;return e.boundingBox||e.computeBoundingBox(),this.boundingBox.union(e.boundingBox),this}addMesh(t,e,i,r,s){let n;t=Ct(t),e=Ct(e),Array.isArray(i)&&(i=xt(i,t.length)),r&&(r=Ct(r)),n=void 0===r||0==r.length?{position:t,color:e,index:i}:{position:t,color:e,index:i,normal:r};const o=new io(this,Object.assign({serial:this.meshCount,name:s},n)),a=new Uo(Object.assign({picking:o},n));return this.bufferList.push(a),Pc.setFromArray(t),this.boundingBox.union(Pc),this.meshCount+=1,this}addSphere(t,e,i,r){return bs.objectToShape(this,{position:t,color:e,radius:i,name:r}),this}addEllipsoid(t,e,i,r,s,n){return Cs.objectToShape(this,{position:t,color:e,radius:i,majorAxis:r,minorAxis:s,name:n}),this}addTorus(t,e,i,r,s,n){return Ps.objectToShape(this,{position:t,color:e,radius:i,majorAxis:r,minorAxis:s,name:n}),this}addCylinder(t,e,i,r,s){return As.objectToShape(this,{position1:t,position2:e,color:i,radius:r,name:s}),this}addCone(t,e,i,r,s){return Ss.objectToShape(this,{position1:t,position2:e,color:i,radius:r,name:s}),this}addArrow(t,e,i,r,s){return _s.objectToShape(this,{position1:t,position2:e,color:i,radius:r,name:s}),this}addBox(t,e,i,r,s,n){return xs.objectToShape(this,{position:t,color:e,size:i,heightAxis:r,depthAxis:s,name:n}),this}addOctahedron(t,e,i,r,s,n){return vs.objectToShape(this,{position:t,color:e,size:i,heightAxis:r,depthAxis:s,name:n}),this}addTetrahedron(t,e,i,r,s,n){return ws.objectToShape(this,{position:t,color:e,size:i,heightAxis:r,depthAxis:s,name:n}),this}addText(t,e,i,r){return Is.objectToShape(this,{position:t,color:e,size:i,text:r}),this}addPoint(t,e,i){return ks.objectToShape(this,{position:t,color:e,name:i}),this}addWideline(t,e,i,r,s){return this.parameters.linewidth=r,Ms.objectToShape(this,{position1:t,position2:e,color:i,name:s}),this}addLabel(t,e,i,r){return console.warn("Shape.addLabel is deprecated, use .addText instead"),this.addText(t,e,i,r)}getBufferList(){const t=[];return Ic.forEach((e=>{this._primitiveData[e.getShapeKey("color")].length&&t.push(e.bufferFromShape(this,this.parameters))})),this.bufferList.concat(t)}dispose(){this.bufferList.forEach((function(t){t.dispose()})),this.bufferList.length=0,Ic.forEach((t=>{Object.keys(t.fields).forEach((e=>{this._primitiveData[t.getShapeKey(e)].length=0})),this._primitiveData[t.getShapeKey("name")].length=0}))}get center(){return this._center||(this._center=this.boundingBox.getCenter(new e)),this._center}get type(){return"Shape"}}class Tc extends zr{constructor(t,e,i){Array.isArray(t)||(t=[t]),super(t,e,i),this.type="buffer",this.parameters=Object.assign({},this.parameters,{colorScheme:null,colorScale:null,colorValue:null,colorDomain:null,colorMode:null}),this.buffer=t,this.init(i)}init(t){super.init(t),this.build()}create(){this.bufferList.push.apply(this.bufferList,this.buffer)}attach(t){this.bufferList.forEach((t=>{this.viewer.add(t),t.setParameters(this.getBufferParams())})),this.setVisibility(this.visible),t()}}const Bc=new i,Dc=new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix3 */];class $c extends Uo{constructor(t,e={},i){super(function(t,e){const i=e.attributes.position.array,r=e.index?e.index.array:void 0,s=t.position.length/3,n=i.length/3,o=s*n,a=new Float32Array(3*o),c=new Float32Array(3*o),l=new Float32Array(3*o);let h;return r&&(h=xt(s*r.length,o)),{position:a,color:l,index:h,normal:c,primitiveId:t.primitiveId||Ii(s,n),picking:t.picking}}(t,i),e),this.updateNormals=!1;const r=i.attributes.position.array,s=i.attributes.normal.array,n=i.index?i.index.array:void 0;this.geoPosition=r,this.geoNormal=s,this.geoIndex=n,this.positionCount=t.position.length/3,this.geoPositionCount=r.length/3,this.transformedGeoPosition=new Float32Array(3*this.geoPositionCount),this.transformedGeoNormal=new Float32Array(3*this.geoPositionCount);const o=this.geometry.attributes;if(this.meshPosition=o.position.array,this.meshColor=o.color.array,this.meshNormal=o.normal.array,this.setAttributes(t),n){const t=this.geometry.getIndex();if(!t)return void Me.error("Index is null");this.meshIndex=t.array,this.makeIndex()}}setAttributes(t={},e=!1){const i=this.geometry.attributes;let r,s,n,o,a,c,l,h,d;const u=this.updateNormals;t.position&&(r=t.position,n=this.geoPosition,l=this.meshPosition,a=this.transformedGeoPosition,i.position.needsUpdate=!0,(u||e)&&(o=this.geoNormal,d=this.meshNormal,c=this.transformedGeoNormal,i.normal.needsUpdate=!0)),t.color&&(s=t.color,h=this.meshColor,i.color.needsUpdate=!0);const m=this.positionCount,p=this.geoPositionCount;for(let t=0;t<m;++t){let i,m;const f=t*p*3,g=3*t;if(r&&a&&l&&d&&n&&o&&(a.set(n),Bc.makeTranslation(r[g],r[g+1],r[g+2]),this.applyPositionTransform(Bc,t,g),Wr(Bc.elements,a),l.set(a,f),u&&c?(c.set(o),Dc.getNormalMatrix(Bc),qr(Dc.elements,c),d.set(c,f)):e&&d.set(o,f)),s&&h)for(i=0;i<p;++i)m=f+3*i,h[m]=s[g],h[m+1]=s[g+1],h[m+2]=s[g+2]}}makeIndex(){const t=this.geoIndex,e=this.meshIndex;if(!t)return;const i=this.positionCount,r=this.geoPositionCount,s=3*(t.length/3);for(let n=0;n<i;++n){const i=n*s,o=i+s;e.set(t,i);for(let t=i;t<o;++t)e[t]+=n*r}}}const Oc=new e,Rc=Object.assign({sphereDetail:1},zo);class Ec extends $c{constructor(t,e={}){super(t,e,new __WEBPACK_IMPORTED_MODULE_0_three__["u" /* IcosahedronBufferGeometry */](1,st(e.sphereDetail,1))),this.setAttributes(t,!0)}get defaultParameters(){return Rc}applyPositionTransform(t,e){const i=this._radius[e];Oc.set(i,i,i),t.scale(Oc)}setAttributes(t={},e){t.radius&&(this._radius=t.radius),super.setAttributes(t,e)}}Ve.add("shader/SphereImpostor.vert","uniform mat4 projectionMatrixInverse;\nuniform float clipNear;\nvarying float vRadius;\nvarying float vRadiusSq;\nvarying vec3 vPoint;\nvarying vec3 vPointViewPosition;\nattribute vec2 mapping;\nattribute float radius;\n#ifdef PICKING\n#include unpack_color\nattribute float primitiveId;\nvarying vec3 vPickingColor;\n#else\n#include color_pars_vertex\n#endif\n#include matrix_scale\nconst mat4 D = mat4(\n1.0, 0.0, 0.0, 0.0,\n0.0, 1.0, 0.0, 0.0,\n0.0, 0.0, 1.0, 0.0,\n0.0, 0.0, 0.0, -1.0\n);\nmat4 transposeM( in mat4 inMatrix ) {\nvec4 i0 = inMatrix[0];\nvec4 i1 = inMatrix[1];\nvec4 i2 = inMatrix[2];\nvec4 i3 = inMatrix[3];\nmat4 outMatrix = mat4(\nvec4(i0.x, i1.x, i2.x, i3.x),\nvec4(i0.y, i1.y, i2.y, i3.y),\nvec4(i0.z, i1.z, i2.z, i3.z),\nvec4(i0.w, i1.w, i2.w, i3.w)\n);\nreturn outMatrix;\n}\nvoid ComputePointSizeAndPositionInClipCoordSphere(){\nvec2 xbc;\nvec2 ybc;\nmat4 T = mat4(\nradius, 0.0, 0.0, 0.0,\n0.0, radius, 0.0, 0.0,\n0.0, 0.0, radius, 0.0,\nposition.x, position.y, position.z, 1.0\n);\nmat4 R = transposeM( projectionMatrix * modelViewMatrix * T );\nfloat A = dot( R[ 3 ], D * R[ 3 ] );\nfloat B = -2.0 * dot( R[ 0 ], D * R[ 3 ] );\nfloat C = dot( R[ 0 ], D * R[ 0 ] );\nxbc[ 0 ] = ( -B - sqrt( B * B - 4.0 * A * C ) ) / ( 2.0 * A );\nxbc[ 1 ] = ( -B + sqrt( B * B - 4.0 * A * C ) ) / ( 2.0 * A );\nfloat sx = abs( xbc[ 0 ] - xbc[ 1 ] ) * 0.5;\nA = dot( R[ 3 ], D * R[ 3 ] );\nB = -2.0 * dot( R[ 1 ], D * R[ 3 ] );\nC = dot( R[ 1 ], D * R[ 1 ] );\nybc[ 0 ] = ( -B - sqrt( B * B - 4.0 * A * C ) ) / ( 2.0 * A );\nybc[ 1 ] = ( -B + sqrt( B * B - 4.0 * A * C ) ) / ( 2.0 * A );\nfloat sy = abs( ybc[ 0 ] - ybc[ 1 ] ) * 0.5;\ngl_Position.xy = vec2( 0.5 * ( xbc.x + xbc.y ), 0.5 * ( ybc.x + ybc.y ) );\ngl_Position.xy -= mapping * vec2( sx, sy );\ngl_Position.xy *= gl_Position.w;\n}\nvoid main(void){\n#ifdef PICKING\nvPickingColor = unpackColor( primitiveId );\n#else\n#include color_vertex\n#endif\nvRadius = radius * matrixScale( modelViewMatrix );\nvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\nmvPosition.z -= vRadius;\ngl_Position = projectionMatrix * vec4( mvPosition.xyz, 1.0 );\nComputePointSizeAndPositionInClipCoordSphere();\nvRadiusSq = vRadius * vRadius;\nvec4 vPoint4 = projectionMatrixInverse * gl_Position;\nvPoint = vPoint4.xyz / vPoint4.w;\nvPointViewPosition = -mvPosition.xyz / mvPosition.w;\n}"),Ve.add("shader/SphereImpostor.frag","#define STANDARD\n#define IMPOSTOR\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 interiorColor;\nuniform float interiorDarkening;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\nuniform float clipNear;\nuniform mat4 projectionMatrix;\nuniform float ortho;\nvarying float vRadius;\nvarying float vRadiusSq;\nvarying vec3 vPoint;\nvarying vec3 vPointViewPosition;\n#ifdef PICKING\nuniform float objectId;\nvarying vec3 vPickingColor;\n#else\n#include common\n#include color_pars_fragment\n#include fog_pars_fragment\n#include bsdfs\n#include lights_pars_begin\n#include lights_physical_pars_fragment\n#endif\nbool flag2 = false;\nbool interior = false;\nvec3 cameraPos;\nvec3 cameraNormal;\nfloat calcDepth( in vec3 cameraPos ){\nvec2 clipZW = cameraPos.z * projectionMatrix[2].zw + projectionMatrix[3].zw;\nreturn 0.5 + 0.5 * clipZW.x / clipZW.y;\n}\nfloat calcClip( vec3 cameraPos ){\nreturn dot( vec4( cameraPos, 1.0 ), vec4( 0.0, 0.0, 1.0, clipNear - 0.5 ) );\n}\nbool Impostor( out vec3 cameraPos, out vec3 cameraNormal ){\nvec3 cameraSpherePos = -vPointViewPosition;\ncameraSpherePos.z += vRadius;\nvec3 rayOrigin = mix( vec3( 0.0, 0.0, 0.0 ), vPoint, ortho );\nvec3 rayDirection = mix( normalize( vPoint ), vec3( 0.0, 0.0, 1.0 ), ortho );\nvec3 cameraSphereDir = mix( cameraSpherePos, rayOrigin - cameraSpherePos, ortho );\nfloat B = dot( rayDirection, cameraSphereDir );\nfloat det = B * B + vRadiusSq - dot( cameraSphereDir, cameraSphereDir );\nif( det < 0.0 ){\ndiscard;\nreturn false;\n}\nfloat sqrtDet = sqrt( det );\nfloat posT = mix( B + sqrtDet, B + sqrtDet, ortho );\nfloat negT = mix( B - sqrtDet, sqrtDet - B, ortho );\ncameraPos = rayDirection * negT + rayOrigin;\n#ifdef NEAR_CLIP\nif( calcDepth( cameraPos ) <= 0.0 ){\ncameraPos = rayDirection * posT + rayOrigin;\ninterior = true;\n}else if( calcClip( cameraPos ) > 0.0 ){\ncameraPos = rayDirection * posT + rayOrigin;\ninterior = true;\nflag2 = true;\n}\n#else\nif( calcDepth( cameraPos ) <= 0.0 ){\ncameraPos = rayDirection * posT + rayOrigin;\ninterior = true;\n}\n#endif\ncameraNormal = normalize( cameraPos - cameraSpherePos );\ncameraNormal *= float(!interior) * 2.0 - 1.0;\nreturn !interior;\n}\nvoid main(void){\nbool flag = Impostor( cameraPos, cameraNormal );\n#ifdef NEAR_CLIP\nif( calcClip( cameraPos ) > 0.0 )\ndiscard;\n#endif\ngl_FragDepthEXT = calcDepth( cameraPos );\nif( !flag ){\n#ifdef NEAR_CLIP\nif( flag2 ){\ngl_FragDepthEXT = max( 0.0, calcDepth( vec3( - ( clipNear - 0.5 ) ) ) + ( 0.0000001 / vRadius ) );\n}else if( gl_FragDepthEXT >= 0.0 ){\ngl_FragDepthEXT = 0.0 + ( 0.0000001 / vRadius );\n}\n#else\nif( gl_FragDepthEXT >= 0.0 ){\ngl_FragDepthEXT = 0.0 + ( 0.0000001 / vRadius );\n}\n#endif\n}\nif (gl_FragDepthEXT < 0.0)\ndiscard;\nif (gl_FragDepthEXT > 1.0)\ndiscard;\n#ifdef PICKING\nif( opacity < 0.3 )\ndiscard;\ngl_FragColor = vec4( vPickingColor, objectId );\n#else\nvec3 vNormal = cameraNormal;\nvec3 vViewPosition = -cameraPos;\nvec4 diffuseColor = vec4( diffuse, opacity );\nReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\nvec3 totalEmissiveLight = emissive;\n#include color_fragment\n#include roughnessmap_fragment\n#include metalnessmap_fragment\n#include normal_fragment_begin\n#include lights_physical_fragment\n#include lights_fragment_begin\n#include lights_fragment_end\nvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;\nif( interior ){\n#ifdef USE_INTERIOR_COLOR\noutgoingLight.xyz = interiorColor;\n#else\n#ifdef DIFFUSE_INTERIOR\noutgoingLight.xyz = vColor;\n#endif\n#endif\noutgoingLight.xyz *= 1.0 - interiorDarkening;\n}\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );\n#include premultiplied_alpha_fragment\n#include tonemapping_fragment\n#include encodings_fragment\n#include fog_fragment\n#endif\n}");class Fc extends Go{constructor(t,e,i={}){super(e,i),this.index=xt(this.indexSize,this.attributeSize),this.makeIndex(),this.initIndex(this.index),this.addAttributes({mapping:{type:t,value:null}}),this.setAttributes({primitiveId:Pi(this.size)})}get attributeSize(){return this.size*this.mappingSize}get indexSize(){return this.size*this.mappingIndicesSize}addAttributes(t){const e={};for(const i in t){const r=t[i];e[i]={type:r.type,value:null}}super.addAttributes(e)}getAttributeIndex(t){return 3*t*this.mappingSize}setAttributes(t){t&&!t.position&&t.position1&&t.position2&&(t.position=Ai(t.position1,t.position2));const e=this.size,i=this.mappingSize,r=this.geometry.attributes;let s,n,o,a,c,l,h;for(const d in t)if("index"!==d&&"picking"!==d){n=t[d],s=r[d],o=s.itemSize,a=s.array;for(let t=0;t<e;++t){c=t*o,l=c*i;for(let t=0;t<i;++t){h=l+o*t;for(let t=0;t<o;++t)a[h+t]=n[c+t]}}s.needsUpdate=!0}}makeMapping(){const t=this.size,e=this.mapping,i=this.mappingSize,r=this.mappingItemSize,s=this.geometry.attributes.mapping.array;for(let n=0;n<t;n++)s.set(e,n*r*i)}makeIndex(){const t=this.size,e=this.mappingSize,i=this.mappingIndices,r=this.mappingIndicesSize,s=this.index;for(let n=0;n<t;n++){const t=n*r,o=n*e;s.set(i,t);for(let e=0;e<r;++e)s[t+e]+=o}}}const Lc=new Float32Array([-1,1,-1,-1,1,1,1,-1]),Nc=new Uint16Array([0,1,2,1,3,2]);class zc extends Fc{constructor(t,e={}){super("v2",t,e)}get mapping(){return Lc}get mappingIndices(){return Nc}get mappingIndicesSize(){return 6}get mappingSize(){return 4}get mappingItemSize(){return 2}}class Vc extends zc{constructor(t,e={}){super(t,e),this.isImpostor=!0,this.vertexShader="SphereImpostor.vert",this.fragmentShader="SphereImpostor.frag",this.addUniforms({projectionMatrixInverse:{value:new i},ortho:{value:0}}),this.addAttributes({radius:{type:"f",value:null}}),this.setAttributes(t),this.makeMapping()}}Object.assign({disableImpostor:!1},Rc);const Gc=class{constructor(t,e){return!Ie||e&&e.disableImpostor?new Ec(t,e):new Vc(t,e)}};function Uc(t,e,i,r){const s=i-t,n=r-e;return Math.sqrt(s*s+n*n)}je.add("sphere",Gc),Ve.add("shader/Point.vert","uniform float clipNear;\nuniform float clipRadius;\nuniform vec3 clipCenter;\nuniform float size;\nuniform float canvasHeight;\nuniform float pixelRatio;\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#if defined( PICKING )\n#include unpack_color\nattribute float primitiveId;\nvarying vec3 vPickingColor;\n#else\n#include color_pars_vertex\nvarying vec3 vViewPosition;\n#endif\n#include common\nvoid main(){\n#if defined( PICKING )\nvPickingColor = unpackColor( primitiveId );\n#else\n#include color_vertex\n#endif\n#include begin_vertex\n#include project_vertex\n#ifdef USE_SIZEATTENUATION\ngl_PointSize = size * pixelRatio * ( ( canvasHeight / 2.0 ) / -mvPosition.z );\n#else\ngl_PointSize = size * pixelRatio;\n#endif\n#ifndef PICKING\nvViewPosition = -mvPosition.xyz;\n#endif\n#if defined( RADIUS_CLIP )\nvClipCenter = -( modelViewMatrix * vec4( clipCenter, 1.0 ) ).xyz;\n#endif\n#include nearclip_vertex\n#include radiusclip_vertex\n}"),Ve.add("shader/Point.frag","uniform vec3 diffuse;\nuniform float opacity;\nuniform float clipNear;\nuniform float clipRadius;\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#ifdef USE_MAP\nuniform sampler2D map;\n#endif\n#if defined( PICKING )\nuniform float objectId;\nvarying vec3 vPickingColor;\n#else\n#include common\n#include color_pars_fragment\n#include fog_pars_fragment\nvarying vec3 vViewPosition;\n#endif\nvoid main(){\n#include nearclip_fragment\n#include radiusclip_fragment\n#if defined( PICKING )\n#ifdef USE_MAP\nif( texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) ).a < 0.5 )\ndiscard;\n#endif\nif( opacity < 0.3 )\ndiscard;\ngl_FragColor = vec4( vPickingColor, objectId );\n#else\nvec3 outgoingLight = vec3( 0.0 );\nvec4 diffuseColor = vec4( diffuse, 1.0 );\n#ifdef USE_MAP\ndiffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );\n#endif\n#include color_fragment\n#include alphatest_fragment\noutgoingLight = diffuseColor.rgb;\ngl_FragColor = vec4( outgoingLight, diffuseColor.a * opacity );\n#include premultiplied_alpha_fragment\n#include tonemapping_fragment\n#include encodings_fragment\n#include fog_fragment\n#endif\n}");const jc=Object.assign({pointSize:1,sizeAttenuation:!0,sortParticles:!1,alphaTest:.5,useTexture:!1,forceTransparent:!1,edgeBleach:0},zo),Hc=Object.assign({pointSize:{uniform:"size"},sizeAttenuation:{updateShader:!0},sortParticles:{},alphaTest:{updateShader:!0},useTexture:{updateShader:!0},forceTransparent:{},edgeBleach:{uniform:!0}},Vo);class Wc extends Go{constructor(t,e={}){super(t,e),this.parameterTypes=Hc,this.vertexShader="Point.vert",this.fragmentShader="Point.frag",this.isPoint=!0,this.addUniforms({size:{value:this.parameters.pointSize},canvasHeight:{value:1},pixelRatio:{value:1},map:{value:null}})}get defaultParameters(){return jc}makeMaterial(){super.makeMaterial(),this.makeTexture();const t=this.material,e=this.wireframeMaterial,i=this.pickingMaterial;t.uniforms.map.value=this.tex,t.needsUpdate=!0,e.uniforms.map.value=this.tex,e.needsUpdate=!0,i.uniforms.map.value=this.tex,i.needsUpdate=!0}makeTexture(){this.tex&&this.tex.dispose(),this.tex=function(t){const e=t||{},i=st(e.width,256),r=st(e.height,256),s=[i/2,r/2],n=Math.min(i/2,r/2),o=st(e.delta,1/(n+1))*n;let a=0,c=0;const l=new Uint8Array(i*r*4);for(let t=0,e=l.length;t<e;t+=4){const e=1-Rt(n-o,n,Uc(a,c,s[0],s[1]));l[t]=255*e,l[t+1]=255*e,l[t+2]=255*e,l[t+3]=255*e,++a===i&&(a=0,c++)}const h=new __WEBPACK_IMPORTED_MODULE_0_three__["l" /* DataTexture */](l,i,r);return h.needsUpdate=!0,h}({delta:this.parameters.edgeBleach})}getDefines(t){const e=super.getDefines(t);return this.parameters.sizeAttenuation&&(e.USE_SIZEATTENUATION=1),this.parameters.useTexture&&(e.USE_MAP=1),this.parameters.alphaTest>0&&this.parameters.alphaTest<=1&&(e.ALPHATEST=this.parameters.alphaTest.toPrecision(2)),e}setUniforms(t){t&&void 0!==t.edgeBleach&&(this.makeTexture(),t.map=this.tex),super.setUniforms(t)}dispose(){super.dispose(),this.tex&&this.tex.dispose()}}je.add("point",Wc);class qc extends zr{constructor(t,e,i){super(t,e,i),this.type="dot",this.parameters=Object.assign({thresholdType:{type:"select",rebuild:!0,options:{value:"value",sigma:"sigma"}},thresholdMin:{type:"number",precision:3,max:1/0,min:-1/0,rebuild:!0},thresholdMax:{type:"number",precision:3,max:1/0,min:-1/0,rebuild:!0},thresholdOut:{type:"boolean",rebuild:!0},dotType:{type:"select",rebuild:!0,options:{"":"",sphere:"sphere",point:"point"}},radiusType:{type:"select",options:{"":"",value:"value","abs-value":"abs-value","value-min":"value-min",deviation:"deviation",size:"size"}},radius:{type:"number",precision:3,max:10,min:.001,property:"size"},scale:{type:"number",precision:3,max:10,min:.001},sphereDetail:!0,disableImpostor:!0,pointSize:{type:"number",precision:1,max:100,min:0,buffer:!0},sizeAttenuation:{type:"boolean",buffer:!0},sortParticles:{type:"boolean",rebuild:!0},useTexture:{type:"boolean",buffer:!0},alphaTest:{type:"range",step:.001,max:1,min:0,buffer:!0},forceTransparent:{type:"boolean",buffer:!0},edgeBleach:{type:"range",step:.001,max:1,min:0,buffer:!0}},this.parameters,{colorScheme:{type:"select",update:"color",options:{"":"",value:"value",uniform:"uniform",random:"random"}}}),t instanceof Eo?(this.surface=void 0,this.volume=new ba(t)):(this.surface=t,this.volume=void 0),this.init(i)}init(t){var e=t||{};e.colorScheme=st(e.colorScheme,"uniform"),e.colorValue=st(e.colorValue,14540253),this.thresholdType=st(e.thresholdType,"sigma"),this.thresholdMin=st(e.thresholdMin,2),this.thresholdMax=st(e.thresholdMax,1/0),this.thresholdOut=st(e.thresholdOut,!1),this.dotType=st(e.dotType,"point"),this.radius=st(e.radius,.1),this.scale=st(e.scale,1),this.pointSize=st(e.pointSize,1),this.sizeAttenuation=st(e.sizeAttenuation,!0),this.sortParticles=st(e.sortParticles,!1),this.useTexture=st(e.useTexture,!1),this.alphaTest=st(e.alphaTest,.5),this.forceTransparent=st(e.forceTransparent,!1),this.edgeBleach=st(e.edgeBleach,0),super.init(e),this.build()}attach(t){this.bufferList.forEach((t=>{this.viewer.add(t)})),this.setVisibility(this.visible),t()}create(){var t={};if(this.volume){var e,i,r=this.volume;"sigma"===this.thresholdType?(e=r.getValueForSigma(this.thresholdMin),i=r.getValueForSigma(this.thresholdMax)):(e=this.thresholdMin,i=this.thresholdMax),r.setFilter(e,i,this.thresholdOut),Object.assign(t,{position:r.getDataPosition(),color:r.getDataColor(this.getColorParams())}),"sphere"===this.dotType&&Object.assign(t,{radius:r.getDataSize(this.radius,this.scale),picking:r.getDataPicking()})}else{var s=this.surface;Object.assign(t,{position:s.getPosition(),color:s.getColor(this.getColorParams())}),"sphere"===this.dotType&&Object.assign(t,{radius:s.getSize(this.radius,this.scale),picking:s.getPicking()})}"sphere"===this.dotType?this.dotBuffer=new Gc(t,this.getBufferParams({sphereDetail:this.sphereDetail,disableImpostor:this.disableImpostor,dullInterior:!1})):this.dotBuffer=new Wc(t,this.getBufferParams({pointSize:this.pointSize,sizeAttenuation:this.sizeAttenuation,sortParticles:this.sortParticles,useTexture:this.useTexture,alphaTest:this.alphaTest,forceTransparent:this.forceTransparent,edgeBleach:this.edgeBleach})),this.bufferList.push(this.dotBuffer)}update(t={}){if(0===this.bufferList.length)return;const e={};t.color&&(this.volume?Object.assign(e,{color:this.volume.getDataColor(this.getColorParams())}):Object.assign(e,{color:this.surface.getColor(this.getColorParams())})),"sphere"===this.dotType&&(t.radius||t.scale)&&(this.volume?Object.assign(e,{radius:this.volume.getDataSize(this.radius,this.scale)}):Object.assign(e,{radius:this.surface.getSize(this.radius,this.scale)})),this.dotBuffer.setAttributes(e)}setParameters(t,e={},i){return t&&void 0!==t.thresholdType&&this.volume instanceof Eo&&("value"===this.thresholdType&&"sigma"===t.thresholdType?(this.thresholdMin=this.volume.getSigmaForValue(this.thresholdMin),this.thresholdMax=this.volume.getSigmaForValue(this.thresholdMax)):"sigma"===this.thresholdType&&"value"===t.thresholdType&&(this.thresholdMin=this.volume.getValueForSigma(this.thresholdMin),this.thresholdMax=this.volume.getValueForSigma(this.thresholdMax)),this.thresholdType=t.thresholdType),t&&void 0!==t.radiusType&&("radius"===t.radiusType?this.radius=.1:this.radius=parseFloat(t.radiusType),e.radius=!0,"sphere"!==this.dotType||Ie&&!this.disableImpostor||(i=!0)),t&&void 0!==t.radius&&(e.radius=!0,"sphere"!==this.dotType||Ie&&!this.disableImpostor||(i=!0)),t&&void 0!==t.scale&&(e.scale=!0,"sphere"!==this.dotType||Ie&&!this.disableImpostor||(i=!0)),super.setParameters(t,e,i),this}}Ve.add("shader/Image.vert","uniform float clipRadius;\nuniform vec3 clipCenter;\nvarying vec2 vUv;\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || !defined( PICKING )\nvarying vec3 vViewPosition;\n#endif\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\nvoid main() {\n#include begin_vertex\n#include project_vertex\nvUv = uv;\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || !defined( PICKING )\nvViewPosition = -mvPosition.xyz;\n#endif\n#if defined( RADIUS_CLIP )\nvClipCenter = -( modelViewMatrix * vec4( clipCenter, 1.0 ) ).xyz;\n#endif\n}"),Ve.add("shader/Image.frag","uniform sampler2D map;\nuniform float opacity;\nuniform vec2 mapSize;\nuniform float clipNear;\nuniform float clipRadius;\nvarying vec2 vUv;\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || !defined( PICKING )\nvarying vec3 vViewPosition;\n#endif\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#if defined( PICKING )\nuniform sampler2D pickingMap;\nuniform float objectId;\n#else\n#include fog_pars_fragment\n#endif\n#if defined( CUBIC_INTERPOLATION )\n#if defined( CATMULROM_FILTER ) || defined( MITCHELL_FILTER )\n#if defined( CATMULROM_FILTER )\nconst float B = 0.0;\nconst float C = 0.5;\n#elif defined( MITCHELL_FILTER )\nconst float B = 0.333;\nconst float C = 0.333;\n#endif\nfloat filter( float x ){\nfloat f = x;\nif( f < 0.0 ){\nf = -f;\n}\nif( f < 1.0 ){\nreturn ( ( 12.0 - 9.0 * B - 6.0 * C ) * ( f * f * f ) +\n( -18.0 + 12.0 * B + 6.0 *C ) * ( f * f ) +\n( 6.0 - 2.0 * B ) ) / 6.0;\n}else if( f >= 1.0 && f < 2.0 ){\nreturn ( ( -B - 6.0 * C ) * ( f * f * f )\n+ ( 6.0 * B + 30.0 * C ) * ( f *f ) +\n( - ( 12.0 * B ) - 48.0 * C ) * f +\n8.0 * B + 24.0 * C ) / 6.0;\n}else{\nreturn 0.0;\n}\n}\n#elif defined( BSPLINE_FILTER )\nfloat filter( float x ){\nfloat f = x;\nif( f < 0.0 ){\nf = -f;\n}\nif( f >= 0.0 && f <= 1.0 ){\nreturn ( 2.0 / 3.0 ) + ( 0.5 ) * ( f * f * f ) - ( f * f );\n}else if( f > 1.0 && f <= 2.0 ){\nreturn 1.0 / 6.0 * pow( ( 2.0 - f ), 3.0 );\n}\nreturn 1.0;\n}\n#else\nfloat filter( float x ){\nreturn 1.0;\n}\n#endif\nvec4 biCubic( sampler2D tex, vec2 texCoord ){\nvec2 texelSize = 1.0 / mapSize;\ntexCoord -= texelSize / 2.0;\nvec4 nSum = vec4( 0.0 );\nfloat nDenom = 0.0;\nvec2 cell = fract( texCoord * mapSize );\nfor( float m = -1.0; m <= 2.0; ++m ){\nfor( float n = -1.0; n <= 2.0; ++n ){\nvec4 vecData = texture2D(\ntex, texCoord + texelSize * vec2( m, n )\n);\nfloat c = filter( m - cell.x ) * filter( -n + cell.y );\nnSum += vecData * c;\nnDenom += c;\n}\n}\nreturn nSum / nDenom;\n}\n#endif\nvoid main(){\n#include nearclip_fragment\n#include radiusclip_fragment\n#if defined( CUBIC_INTERPOLATION )\ngl_FragColor = biCubic( map, vUv );\n#else\ngl_FragColor = texture2D( map, vUv );\n#endif\n#if defined( PICKING )\nif( gl_FragColor.a < 0.3 )\ndiscard;\ngl_FragColor = vec4( texture2D( pickingMap, vUv ).xyz, objectId );\n#else\nif( gl_FragColor.a < 0.01 )\ndiscard;\ngl_FragColor.a *= opacity;\n#include fog_fragment\n#endif\n}");const Xc=new Uint16Array([0,1,2,1,3,2]),Yc=new Float32Array([0,1,0,0,1,1,1,0]),Kc=Object.assign({filter:"nearest",forceTransparent:!0},zo),Zc=Object.assign({filter:{updateShader:!0,uniform:!0}},Vo);class Qc extends Go{constructor(e,i){super({position:e.position,index:Xc,picking:e.picking},i),this.parameterTypes=Zc,this.alwaysTransparent=!0,this.hasWireframe=!1,this.vertexShader="Image.vert",this.fragmentShader="Image.frag";const{imageData:r,width:s,height:n}=e,o=new __WEBPACK_IMPORTED_MODULE_0_three__["l" /* DataTexture */](r,s,n);o.flipY=!0,this.tex=o;const a=r.length,c=new Uint8Array(a);for(let t=0;t<a;t+=4){const e=t/4;c[t]=e>>16&255,c[t+1]=e>>8&255,c[t+2]=255&e}const l=new __WEBPACK_IMPORTED_MODULE_0_three__["l" /* DataTexture */](c,s,n);l.flipY=!0,l.minFilter=__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */],l.magFilter=__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */],this.pickingTex=l,this.addUniforms({map:{value:o},pickingMap:{value:l},mapSize:{value:new t(s,n)}}),this.geometry.setAttribute("uv",new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](Yc,2))}get defaultParameters(){return Kc}getDefines(t){const e=super.getDefines(t),i=this.parameters.filter;return i.startsWith("cubic")&&(e.CUBIC_INTERPOLATION=1,i.endsWith("bspline")?e.BSPLINE_FILTER=1:i.endsWith("catmulrom")?e.CATMULROM_FILTER=1:i.endsWith("mitchell")&&(e.MITCHELL_FILTER=1)),e}updateTexture(){const t=this.tex,e=this.parameters.filter;e.startsWith("cubic")?(t.minFilter=__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */],t.magFilter=__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */]):"linear"===e?(t.minFilter=__WEBPACK_IMPORTED_MODULE_0_three__["x" /* LinearFilter */],t.magFilter=__WEBPACK_IMPORTED_MODULE_0_three__["x" /* LinearFilter */]):(t.minFilter=__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */],t.magFilter=__WEBPACK_IMPORTED_MODULE_0_three__["B" /* NearestFilter */]),t.needsUpdate=!0,this.pickingTex.needsUpdate=!0}makeMaterial(){super.makeMaterial(),this.updateTexture();const t=this.material;t.uniforms.map.value=this.tex,t.blending=__WEBPACK_IMPORTED_MODULE_0_three__["D" /* NormalBlending */],t.needsUpdate=!0;const e=this.wireframeMaterial;e.uniforms.map.value=this.tex,e.blending=__WEBPACK_IMPORTED_MODULE_0_three__["D" /* NormalBlending */],e.needsUpdate=!0;const i=this.pickingMaterial;i.uniforms.map.value=this.tex,i.uniforms.pickingMap.value=this.pickingTex,i.blending=__WEBPACK_IMPORTED_MODULE_0_three__["D" /* NormalBlending */],i.needsUpdate=!0}setUniforms(t){t&&void 0!==t.filter&&(this.updateTexture(),t.map=this.tex),super.setUniforms(t)}}class Jc{constructor(t,e){const i=e||{};this.dimension=st(i.dimension,"x"),this.positionType=st(i.positionType,"percent"),this.position=st(i.position,30),this.thresholdType=st(i.thresholdType,"sigma"),this.thresholdMin=st(i.thresholdMin,-1/0),this.thresholdMax=st(i.thresholdMax,1/0),this.normalize=st(i.normalize,!1),this.volume=t}getPositionFromCoordinate(t){const i=this.dimension,r=this.volume,s=r.matrix,n=(new e).setFromMatrixPosition(s)[i],o=(new e).setFromMatrixScale(s)[i];let a;return a="x"===i?r.nx:"y"===i?r.ny:r.nz,Math.round(((t-n)/(a/100)+1)/o)}getData(t){t=t||{};const i=this.volume,r=i.data,s=i.matrix;let n;function o(t){return Math.round(t/100*(n-1))}function a(t,e,r,s){return 3*(r*i.ny*i.nx+e*i.nx+t)+s}n="coordinate"===this.positionType?this.getPositionFromCoordinate(this.position):this.position;const c=new Float32Array(12),l=new e;let h,d,u,m,p,f=0,g=0,y=0,b=i.nx,x=i.ny,v=i.nz;function w(t,e,i,r){l.set(t,e,i).applyMatrix4(s).toArray(c,r)}"x"===this.dimension?(u=o(i.nx),m=i.ny-1,p=i.nz-1,h=i.nz,d=i.ny,f=u,b=f+1,w(u,0,0,0),w(u,m,0,3),w(u,0,p,6),w(u,m,p,9)):"y"===this.dimension?(u=i.nx-1,m=o(i.ny),p=i.nz-1,h=i.nz,d=i.nx,g=m,x=g+1,w(0,m,0,0),w(u,m,0,3),w(0,m,p,6),w(u,m,p,9)):"z"===this.dimension&&(u=i.nx-1,m=i.ny-1,p=o(i.nz),h=i.nx,d=i.ny,y=p,v=y+1,w(0,0,p,0),w(0,m,p,3),w(u,0,p,6),w(u,m,p,9));let A=0,_=0;const S=new Uint8Array(h*d*4),C=new Float32Array(h*d);let P,I;"sigma"===this.thresholdType?(P=i.getValueForSigma(this.thresholdMin),I=i.getValueForSigma(this.thresholdMax)):(P=this.thresholdMin,I=this.thresholdMax);const k=Object.assign({},t.colorParams,{volume:i});this.normalize&&(k.domain=[0,1]);const M=Fe.getScheme(k),T=new Float32Array(3),B=M.getScale();let D,$=0,O=0;if(this.normalize){$=1/0,D=-1/0;for(let t=g;t<x;++t)for(let e=f;e<b;++e)for(let i=y;i<v;++i){const s=r[a(e,t,i,0)/3];s<$&&($=s),s>D&&(D=s)}O=D-$}for(let t=g;t<x;++t)for(let e=f;e<b;++e)for(let i=y;i<v;++i){const s=a(e,t,i,0)/3;let n=r[s];this.normalize&&(n=(n-$)/O),M.colorToArray(B(n),T),S[A]=Math.round(255*T[0]),S[A+1]=Math.round(255*T[1]),S[A+2]=Math.round(255*T[2]),S[A+3]=n>P&&n<I?255:0,C[_]=s,++_,A+=4}const R=new oo(C,i);return{position:c,imageData:S,width:h,height:d,picking:R}}}class tl extends zr{constructor(t,e,i){super(t,e,i),this.type="slice",this.parameters=Object.assign({filter:{type:"select",buffer:!0,options:{nearest:"nearest",linear:"linear","cubic-bspline":"cubic-bspline","cubic-catmulrom":"cubic-catmulrom","cubic-mitchell":"cubic-mitchell"}},positionType:{type:"select",rebuild:!0,options:{percent:"percent",coordinate:"coordinate"}},position:{type:"range",step:.1,max:100,min:1,rebuild:!0},dimension:{type:"select",rebuild:!0,options:{x:"x",y:"y",z:"z"}},thresholdType:{type:"select",rebuild:!0,options:{value:"value",sigma:"sigma"}},thresholdMin:{type:"number",precision:3,max:1/0,min:-1/0,rebuild:!0},thresholdMax:{type:"number",precision:3,max:1/0,min:-1/0,rebuild:!0},normalize:{type:"boolean",rebuild:!0}},this.parameters,{flatShaded:null,side:null,wireframe:null,linewidth:null,colorScheme:null,roughness:null,metalness:null,diffuse:null}),this.volume=t,this.init(i)}init(t){const e=this.volume,i=t||{};i.colorDomain=st(i.colorDomain,[e.min,e.max]),i.colorScheme=st(i.colorScheme,"value"),i.colorScale=st(i.colorScale,"Spectral"),this.colorScheme="value",this.dimension=st(i.dimension,"x"),this.filter=st(i.filter,"cubic-bspline"),this.positionType=st(i.positionType,"percent"),this.position=st(i.position,30),this.thresholdType=st(i.thresholdType,"sigma"),this.thresholdMin=st(i.thresholdMin,-1/0),this.thresholdMax=st(i.thresholdMax,1/0),this.normalize=st(i.normalize,!1),super.init(i),this.build()}attach(t){this.bufferList.forEach((t=>{this.viewer.add(t)})),this.setVisibility(this.visible),t()}create(){const t=new Jc(this.volume,{positionType:this.positionType,position:this.position,dimension:this.dimension,thresholdType:this.thresholdType,thresholdMin:this.thresholdMin,thresholdMax:this.thresholdMax,normalize:this.normalize}),e=new Qc(t.getData({colorParams:this.getColorParams()}),this.getBufferParams({filter:this.filter}));this.bufferList.push(e)}}function el(t){Me.error(`makeRepresentation: representation type ${t} unknown`)}const il={name:"some element",status:""};class rl{constructor(t,e={}){this.stage=t,this.signals={statusChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],nameChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],disposed:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.parameters=nt(e,this.defaultParameters),this.uuid=Bt()}get defaultParameters(){return il}get name(){return this.parameters.name}setStatus(t){return this.parameters.status=t,this.signals.statusChanged.dispatch(t),this}setName(t){return this.parameters.name=t,this.signals.nameChanged.dispatch(t),this}dispose(){this.signals.disposed.dispatch()}}const sl=Object.assign({visible:!0},il);class nl extends rl{constructor(t,e,i={},r){super(t,Object.assign({name:e.type},i)),this.parent=r,this.signals=Object.assign({visibilityChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],parametersChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.signals),this.setRepresentation(e)}get defaultParameters(){return sl}get visible(){return this.parameters.visible}get type(){return"representation"}getType(){return this.repr.type}setRepresentation(t){this._disposeRepresentation(),this.repr=t,this.stage.tasks.listen(this.repr.tasks),this.updateVisibility()}_disposeRepresentation(){this.repr&&(this.stage.tasks.unlisten(this.repr.tasks),this.repr.dispose())}dispose(){this.parent&&this.parent.hasRepresentation(this)?this.parent.removeRepresentation(this):(this._disposeRepresentation(),this.signals.disposed.dispatch())}setVisibility(t){return this.parameters.visible=t,this.updateVisibility(),this.signals.visibilityChanged.dispatch(this.parameters.visible),this}getVisibility(){return this.parent?this.parent.parameters.visible&&this.parameters.visible:this.parameters.visible}toggleVisibility(){return this.setVisibility(!this.parameters.visible)}updateVisibility(){this.repr.setVisibility(this.getVisibility())}update(t){return this.repr.update(t),this}build(t){return this.repr.build(t),this}setSelection(t){const e=this.repr;return e.setSelection&&e.setSelection(t),this}setParameters(t){return this.repr.setParameters(t),this.signals.parametersChanged.dispatch(this.repr.getParameters()),this}getParameters(){return this.repr.getParameters()}setColor(t){return this.repr.setColor(t),this}}const ol=new i,al=new e,cl={name:"",status:"",visible:!0};class ll{constructor(t,s,n={}){this.stage=t,this.object=s,this.signals={representationAdded:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],representationRemoved:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],visibilityChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],matrixChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],statusChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],nameChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],disposed:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.reprList=[],this.annotationList=[],this.matrix=new i,this.position=new e,this.quaternion=new r,this.scale=new e(1,1,1),this.transform=new i,this.parameters=nt(n,this.defaultParameters),this.uuid=Bt(),this.viewer=t.viewer,this.controls=new ua(this)}get defaultParameters(){return cl}get name(){return this.parameters.name}get status(){return this.parameters.status}get visible(){return this.parameters.visible}setPosition(t){return Array.isArray(t)?this.position.fromArray(t):this.position.copy(t),this.updateMatrix(),this}setRotation(t){if(Array.isArray(t))if(3===t.length){const e=(new __WEBPACK_IMPORTED_MODULE_0_three__["n" /* Euler */]).fromArray(t);this.quaternion.setFromEuler(e)}else this.quaternion.fromArray(t);else t instanceof __WEBPACK_IMPORTED_MODULE_0_three__["n" /* Euler */]?this.quaternion.setFromEuler(t):this.quaternion.copy(t);return this.updateMatrix(),this}setScale(t){return this.scale.set(t,t,t),this.updateMatrix(),this}setTransform(t){return this.transform.copy(t),this.updateMatrix(),this}updateMatrix(){const t=this.getCenterUntransformed(al);this.matrix.makeTranslation(-t.x,-t.y,-t.z),ol.makeRotationFromQuaternion(this.quaternion),this.matrix.premultiply(ol),ol.makeScale(this.scale.x,this.scale.y,this.scale.z),this.matrix.premultiply(ol);const e=this.position;ol.makeTranslation(e.x+t.x,e.y+t.y,e.z+t.z),this.matrix.premultiply(ol),this.matrix.premultiply(this.transform),this.updateRepresentationMatrices(),this.stage.viewer.updateBoundingBox(),this.signals.matrixChanged.dispatch(this.matrix)}updateRepresentationMatrices(){this.reprList.forEach((t=>{t.setParameters({matrix:this.matrix})}))}addAnnotation(t,e,i){const r=new ca(this,t,e,i);return this.annotationList.push(r),r}eachAnnotation(t){this.annotationList.slice().forEach(t)}removeAnnotation(t){const e=this.annotationList.indexOf(t);-1!==e&&(this.annotationList.splice(e,1),t.dispose())}removeAllAnnotations(){this.eachAnnotation((t=>t.dispose())),this.annotationList.length=0}_addRepresentation(t,e,i,r=!1){const s=i||{},n=this.stage.getParameters();s.matrix=this.matrix.clone(),s.quality=s.quality||n.quality,s.disableImpostor=st(s.disableImpostor,!n.impostor),s.useWorker=st(s.useWorker,n.workerDefault),s.visible=st(s.visible,!0);const o=Object.assign({},s,{visible:this.parameters.visible&&s.visible}),a=function(t,e,i,r){var s;if(De&&Me.time("makeRepresentation "+t),e instanceof Cc){if(!(s=Ne.get(t)))return void el(t)}else if(e instanceof Oo)if("surface"===t)s=Yo;else{if("dot"!==t)return void el(t);s=qc}else if(e instanceof Eo)if("surface"===t)s=Yo;else if("dot"===t)s=qc;else{if("slice"!==t)return void el(t);s=tl}else if(e instanceof Mc)s=Tc,e=e.getBufferList();else{if("buffer"!==t)return void Me.error("makeRepresentation: object "+e+" unknown");s=Tc}const n=new s(e,i,r);return De&&Me.timeEnd("makeRepresentation "+t),n}(t,e,this.viewer,o),c=new nl(this.stage,a,s,this);return r||(this.reprList.push(c),this.signals.representationAdded.dispatch(c)),c}addBufferRepresentation(t,e){return this._addRepresentation.call(this,"buffer",t,e)}hasRepresentation(t){return-1!==this.reprList.indexOf(t)}eachRepresentation(t){this.reprList.slice().forEach(t)}removeRepresentation(t){const e=this.reprList.indexOf(t);-1!==e&&(this.reprList.splice(e,1),t.dispose(),this.signals.representationRemoved.dispatch(t))}updateRepresentations(t){this.reprList.forEach((e=>e.update(t))),this.stage.viewer.requestRender()}removeAllRepresentations(){this.eachRepresentation((t=>t.dispose()))}dispose(){this.removeAllAnnotations(),this.removeAllRepresentations(),this.reprList.length=0,this.signals.disposed.dispatch()}setVisibility(t){return this.parameters.visible=t,this.eachRepresentation((t=>t.updateVisibility())),this.eachAnnotation((t=>t.updateVisibility())),this.signals.visibilityChanged.dispatch(t),this}setStatus(t){return this.parameters.status=t,this.signals.statusChanged.dispatch(t),this}setName(t){return this.parameters.name=t,this.signals.nameChanged.dispatch(t),this}getBox(...t){return this.getBoxUntransformed(...t).clone().applyMatrix4(this.matrix)}getCenter(...t){return this.getCenterUntransformed(...t).clone().applyMatrix4(this.matrix)}getZoom(...t){return this.stage.getZoomForBox(this.getBox(...t))}getBoxUntransformed(...t){return new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]}getCenterUntransformed(...t){return this.getBoxUntransformed().getCenter(new e)}autoView(t){this.stage.animationControls.zoomMove(this.getCenter(),this.getZoom(),st(t,0))}}class hl{constructor(t=[]){this.list=t;const e=t.length;for(let i=0;i<e;++i){t[i].signals.disposed.add(this._remove,this)}}_remove(t){const e=this.list.indexOf(t);-1!==e&&this.list.splice(e,1)}get first(){return this.list.length>0?this.list[0]:void 0}forEach(t){return this.list.forEach(t),this}dispose(){return this.forEach((t=>t.dispose()))}}class dl extends hl{setParameters(t){return this.forEach((e=>e.setParameters(t)))}setVisibility(t){return this.forEach((e=>e.setVisibility(t)))}setSelection(t){return this.forEach((e=>e.setSelection(t)))}setColor(t){return this.forEach((e=>e.setColor(t)))}update(t){return this.forEach((e=>e.update(t)))}build(t){return this.forEach((e=>e.build(t)))}dispose(t){return this.forEach((t=>t.dispose()))}}const ul=Object.assign({defaultStep:1,defaultTimeout:50,defaultInterpolateType:"",defaultInterpolateStep:5,defaultMode:"loop",defaultDirection:"forward",initialFrame:0},il);class ml extends rl{constructor(t,e,i={}){super(t,Object.assign({name:e.name},i)),this.trajectory=e,this.signals=Object.assign(this.signals,{frameChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],playerChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],countChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],parametersChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]}),e.signals.frameChanged.add((t=>{this.signals.frameChanged.dispatch(t)})),e.signals.playerChanged.add((t=>{this.signals.playerChanged.dispatch(t)})),e.signals.countChanged.add((t=>{this.signals.countChanged.dispatch(t)})),void 0!==i.initialFrame&&this.setFrame(i.initialFrame)}get defaultParameters(){return ul}get type(){return"trajectory"}setFrame(t){this.trajectory.setFrame(t)}setParameters(t={}){this.trajectory.setParameters(t),this.signals.parametersChanged.dispatch(t)}dispose(){this.trajectory.dispose(),super.dispose()}}class pl{constructor(t,e){this.name=t,this.path=e,this.coordinates=[],this.boxes=[],this.times=[],this.timeOffset=0,this.deltaTime=1}get type(){return"Frames"}}class fl{constructor(t,e){let r,s;if(this.A=new ho(3,3),this.W=new ho(1,3),this.U=new ho(3,3),this.V=new ho(3,3),this.VH=new ho(3,3),this.R=new ho(3,3),this.tmp=new ho(3,3),this.c=new ho(3,3),t instanceof Cc)r=t.atomCount;else{if(!(t instanceof Float32Array))return;r=t.length/3}if(e instanceof Cc)s=e.atomCount;else{if(!(e instanceof Float32Array))return;s=e.length/3}const n=Math.min(r,s),o=new ho(3,n),a=new ho(3,n);this.coords1t=new ho(n,3),this.coords2t=new ho(n,3),this.transformationMatrix=new i,this.c.data.set([1,0,0,0,1,0,0,0,-1]),this.prepCoords(t,o,n,!1),this.prepCoords(e,a,n,!1),this._superpose(o,a)}_superpose(t,e){this.mean1=fo(t),this.mean2=fo(e),go(t,this.mean1),go(e,this.mean2),uo(this.coords1t,t),uo(this.coords2t,e),mo(this.A,this.coords2t,this.coords1t),wo(this.A,this.W,this.U,this.V),function(t,e){const i=t.data,r=e.data,s=i[4],n=i[8],o=i[5],a=i[7],c=i[0],l=c*s,h=c*o,d=i[3],u=i[1],m=d*u,p=i[2],f=d*p,g=i[6],y=g*u,b=g*p,x=1/(l*n-h*a-m*n+f*a+y*o-b*s);r[0]=(s*n-o*a)*x,r[1]=-(u*n-p*a)*x,r[2]=-(-u*o+p*s)*x,r[3]=-(d*n-o*g)*x,r[4]=(c*n-b)*x,r[5]=-(h-f)*x,r[6]=-(-d*a+s*g)*x,r[7]=-(c*a-y)*x,r[8]=(l-m)*x}(this.V,this.VH),po(this.R,this.U,this.VH),function(t){const e=t.data;return e[0]*e[4]*e[8]-e[0]*e[5]*e[7]-e[3]*e[1]*e[8]+e[3]*e[2]*e[7]+e[6]*e[1]*e[5]-e[6]*e[2]*e[4]}(this.R)<0&&(De&&Me.log("R not a right handed system"),po(this.tmp,this.c,this.VH),po(this.R,this.U,this.tmp));const i=new ho(4,4),r=new ho(4,4),s=new ho(4,4),n=new ho(4,4),o=new ho(4,4),a=new ho(4,4),c=this.R.data,l=this.mean1,h=this.mean2;n.data.set([1,0,0,-l[0],0,1,0,-l[1],0,0,1,-l[2],0,0,0,1]),o.data.set([c[0],c[1],c[2],0,c[3],c[4],c[5],0,c[6],c[7],c[8],0,0,0,0,1]),a.data.set([1,0,0,h[0],0,1,0,h[1],0,0,1,h[2],0,0,0,1]),uo(r,n),mo(i,o,r),uo(s,i),mo(r,a,s),uo(i,r),this.transformationMatrix.elements=i.data}prepCoords(t,e,i,r){let s=0;const n=e.data;let o=3,a=3*i;if(r&&(a=4*i,o=4),t instanceof Cc)t.eachAtom((function(t){s<a&&(n[s+0]=t.x,n[s+1]=t.y,n[s+2]=t.z,r&&(n[s+3]=1),s+=o)}));else if(t instanceof Float32Array)for(;s<a;s+=o)s<a&&(n[s]=t[s],n[s+1]=t[s+1],n[s+2]=t[s+2],r&&(n[s+3]=1));else Me.warn("prepCoords: input type unknown")}transform(t){let e;if(t instanceof Cc)e=t.atomCount;else{if(!(t instanceof Float32Array))return;e=t.length/3}const r=new ho(4,e),s=new ho(e,4);this.prepCoords(t,r,e,!0);const n=this.transformationMatrix,o=n.determinant();if(!o)return o;const a=new ho(4,4);a.data=n.elements,function(t,e,i){let r=0,s=0,n=0,o=0,a=0,c=0,l=0,h=0;const d=e.cols,u=e.rows,m=i.cols,p=e.data,f=i.data,g=t.data;let y=0;for(;r<u;o+=d,r++)for(l=0,s=0;s<m;h++,l++,s++){for(c=l,a=o,y=0,n=0;n<d;a++,c+=m,n++)y+=p[a]*f[c];g[h]=y}}(s,r,a);let c=0;const l=s.data;if(t instanceof Cc){t.eachAtom((function(t){t.x=l[c],t.y=l[c+1],t.z=l[c+2],c+=4}));const e=new i;e.getInverse(n);const r=t.biomolDict;for(let t in r)if(r.hasOwnProperty(t)){r[t].partList.forEach((function(t){t.matrixList.forEach((function(t){t.premultiply(n),t.multiply(e)}))}))}}else if(t instanceof Float32Array){const i=4*e;for(;c<i;c+=4)t[c]=l[c],t[c+1]=l[c+1],t[c+2]=l[c+2]}else Me.warn("transform: input type unknown");return this.transformationMatrix}}const gl={step:1,timeout:50,start:0,end:0,interpolateType:"",interpolateStep:5,mode:"loop",direction:"forward"};class yl{constructor(t,e={}){this.signals={startedRunning:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],haltedRunning:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this._run=!1,this._previousTime=0,this._currentTime=0,this._currentStep=1,t.signals.playerChanged.add((t=>{t!==this&&this.pause()}),this);const i=st(t.frameCount,1);this.traj=t,this.parameters=nt(e,gl),this.parameters.end=Math.min(st(e.end,i-1),i-1),this.parameters.step=st(e.step,Math.ceil((i+1)/100)),this._currentFrame=this.parameters.start,this._direction="bounce"===this.parameters.direction?"forward":this.parameters.direction,t.signals.countChanged.add((t=>{this.parameters.end=Math.min(st(this.parameters.end,t-1),t-1)}),this),this._animate=this._animate.bind(this)}get isRunning(){return this._run}setParameters(t={}){ot(this.parameters,t),void 0!==t.direction&&"bounce"!==this.parameters.direction&&(this._direction=this.parameters.direction)}_animate(){if(!this._run)return;this._currentTime=window.performance.now();const t=this._currentTime-this._previousTime,e=this.parameters.interpolateType?this.parameters.interpolateStep:1,i=this.parameters.timeout/e,r=this.traj;if(r&&r.frameCount&&!r.inProgress&&t>=i)if(this.parameters.interpolateType)if(this._currentStep>this.parameters.interpolateStep&&(this._currentStep=1),1===this._currentStep&&(this._currentFrame=this._nextInterpolated()),r.hasFrame(this._currentFrame)){this._currentStep+=1;const t=this._currentStep/(this.parameters.interpolateStep+1),[e,i,s,n]=this._currentFrame;r.setFrameInterpolated(e,i,s,n,t,this.parameters.interpolateType),this._previousTime=this._currentTime}else r.loadFrame(this._currentFrame);else{const t=this._next();r.hasFrame(t)?(r.setFrame(t),this._previousTime=this._currentTime):r.loadFrame(t)}window.requestAnimationFrame(this._animate)}_next(){const t=this.parameters;let e;return e="forward"===this._direction?this.traj.currentFrame+t.step:this.traj.currentFrame-t.step,(e>t.end||e<t.start)&&("bounce"===t.direction&&("forward"===this._direction?this._direction="backward":this._direction="forward"),"once"===t.mode?(this.pause(),e="forward"===t.direction?t.end:"backward"===t.direction||"forward"===this._direction?t.start:t.end):"forward"===this._direction?(e=t.start,t.interpolateType&&(e=Math.min(t.end,e+t.step))):(e=t.end,t.interpolateType&&(e=Math.max(t.start,e-t.step)))),e}_nextInterpolated(){const t=this.parameters,e=this._next();let i,r,s;return"forward"===this._direction?(i=Math.max(t.start,e-t.step),r=Math.max(t.start,e-2*t.step),s=Math.max(t.start,e-3*t.step)):(i=Math.min(t.end,e+t.step),r=Math.min(t.end,e+2*t.step),s=Math.min(t.end,e+3*t.step)),[e,i,r,s]}toggle(){this._run?this.pause():this.play()}play(){if(!this._run){this.traj.player!==this&&this.traj.setPlayer(this),this._currentStep=1;const t=this.parameters,e=this.traj.currentFrame;let i=Math.ceil(e/t.step)*t.step;"forward"===t.direction&&e>=t.end?i=t.start:"backward"===t.direction&&e<=t.start&&(i=t.end),this.traj.setFrame(i),this._run=!0,this._animate(),this.signals.startedRunning.dispatch()}}pause(){this._run=!1,this.signals.haltedRunning.dispatch()}stop(){this.pause(),this.traj.setFrame(this.parameters.start)}}class bl{constructor(t,e,i={}){this.signals={countChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],frameChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],playerChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.frameCache={},this.loadQueue={},this.boxCache={},this.pathCache={},this.frameCacheSize=0,this._frameCount=0,this._currentFrame=-1,this._disposed=!1,this.deltaTime=st(i.deltaTime,0),this.timeOffset=st(i.timeOffset,0),this.centerPbc=st(i.centerPbc,!1),this.removePbc=st(i.removePbc,!1),this.removePeriodicity=st(i.removePeriodicity,!1),this.superpose=st(i.superpose,!1),this.name=t.replace(/^.*[\\/]/,""),this.trajPath=t,this.selection=new pe(st(i.sele,"backbone and not hydrogen")),this.selection.signals.stringChanged.add((()=>{this.selectionIndices=this.structure.getAtomIndices(this.selection),this._resetCache(),this._saveInitialCoords(),this.setFrame(this._currentFrame)}))}get frameCount(){return this._frameCount}get currentFrame(){return this._currentFrame}_init(t){this.setStructure(t),this._loadFrameCount(),this.setPlayer(new yl(this))}_loadFrameCount(){}setStructure(t){this.structure=t,this.atomCount=t.atomCount,this.backboneIndices=this._getIndices(new pe("backbone and not hydrogen")),this._makeAtomIndices(),this._saveStructureCoords(),this.selectionIndices=this._getIndices(this.selection),this._resetCache(),this._saveInitialCoords(),this.setFrame(this._currentFrame)}_saveInitialCoords(){this.structure.hasCoords()?(this.initialCoords=new Float32Array(this.structureCoords),this._makeSuperposeCoords()):this.frameCache[0]?(this.initialCoords=new Float32Array(this.frameCache[0]),this._makeSuperposeCoords()):this.loadFrame(0,(()=>this._saveInitialCoords()))}_saveStructureCoords(){this.structureCoords=this.structure.getAtomData({what:{position:!0}}).position}setSelection(t){return this.selection.setString(t),this}_getIndices(t){let e=0;const i=t.test,r=[];return i&&this.structure.eachAtom((t=>{i(t)&&r.push(e),e+=1})),r}_makeSuperposeCoords(){const t=3*this.selectionIndices.length;this.coords1=new Float32Array(t),this.coords2=new Float32Array(t);const e=this.initialCoords,i=this.coords2;for(let r=0;r<t;r+=3){const t=3*this.selectionIndices[r/3];i[r+0]=e[t+0],i[r+1]=e[t+1],i[r+2]=e[t+2]}}_makeAtomIndices(){Me.error("Trajectory._makeAtomIndices not implemented")}_resetCache(){this.frameCache={},this.loadQueue={},this.boxCache={},this.pathCache={},this.frameCacheSize=0,this.initialCoords=new Float32Array(0)}setParameters(t={}){let e=!1;void 0!==t.centerPbc&&t.centerPbc!==this.centerPbc&&(this.centerPbc=t.centerPbc,e=!0),void 0!==t.removePeriodicity&&t.removePeriodicity!==this.removePeriodicity&&(this.removePeriodicity=t.removePeriodicity,e=!0),void 0!==t.removePbc&&t.removePbc!==this.removePbc&&(this.removePbc=t.removePbc,e=!0),void 0!==t.superpose&&t.superpose!==this.superpose&&(this.superpose=t.superpose,e=!0),this.deltaTime=st(t.deltaTime,this.deltaTime),this.timeOffset=st(t.timeOffset,this.timeOffset),e&&(this._resetCache(),this.setFrame(this._currentFrame))}hasFrame(t){return Array.isArray(t)?t.every((t=>!!this.frameCache[t])):!!this.frameCache[t]}setFrame(t,e){return void 0===t||(this.inProgress=!0,-1===t||this.frameCache[t]?(this._updateStructure(t),e&&e()):this.loadFrame(t,(()=>{this._updateStructure(t),e&&e()}))),this}_interpolate(t,e,i,r,s,n){const o=this.frameCache;let a;a="spline"===n?function(t,e,i,r,s){const n=t.length,o=new Float32Array(n);for(let a=0;a<n;a+=3){const n=a+1,c=a+2;o[a]=Ot(r[a],i[a],e[a],t[a],s,1),o[n]=Ot(r[n],i[n],e[n],t[n],s,1),o[c]=Ot(r[c],i[c],e[c],t[c],s,1)}return o}(o[t],o[e],o[i],o[r],s):function(t,e,i){const r=t.length,s=new Float32Array(r);for(let n=0;n<r;n+=3){const r=n+1,o=n+2;s[n]=$t(e[n],t[n],i),s[r]=$t(e[r],t[r],i),s[o]=$t(e[o],t[o],i)}return s}(o[t],o[e],s),this.structure.updatePosition(a),this._currentFrame=t,this.signals.frameChanged.dispatch(t)}setFrameInterpolated(t,e,i,r,s,n,o){if(void 0===t)return this;const a=this.frameCache,c=[];return a[r]||c.push(r),a[i]||c.push(i),a[e]||c.push(e),a[t]||c.push(t),c.length?this.loadFrame(c,(()=>{this._interpolate(t,e,i,r,s,n),o&&o()})):(this._interpolate(t,e,i,r,s,n),o&&o()),this}loadFrame(t,e){Array.isArray(t)?t.forEach((t=>{this.loadQueue[t]||this.frameCache[t]||(this.loadQueue[t]=!0,this._loadFrame(t,(()=>{delete this.loadQueue[t]})))})):this.loadQueue[t]||this.frameCache[t]||(this.loadQueue[t]=!0,this._loadFrame(t,(()=>{delete this.loadQueue[t],e&&e()})))}_loadFrame(t,e){Me.error("Trajectory._loadFrame not implemented",t,e)}_updateStructure(t){this._disposed?console.error("updateStructure: traj disposed"):(-1===t?this.structureCoords&&this.structure.updatePosition(this.structureCoords):this.structure.updatePosition(this.frameCache[t]),this.structure.trajectory={name:this.trajPath,frame:t},this._currentFrame=t,this.inProgress=!1,this.signals.frameChanged.dispatch(t))}_doSuperpose(t){const e=3*this.selectionIndices.length,i=this.coords1,r=this.coords2;for(let r=0;r<e;r+=3){const e=3*this.selectionIndices[r/3];i[r+0]=t[e+0],i[r+1]=t[e+1],i[r+2]=t[e+2]}new fl(i,r).transform(t)}_process(t,e,i,r){if(this._setFrameCount(r),e){if(this.backboneIndices.length>0&&this.centerPbc){const t=[e[0],e[4],e[8]],r=function(t,e,i){return[wi(e,i[0],3,0,t),wi(e,i[1],3,1,t),wi(e,i[2],3,2,t)]}(this.backboneIndices,i,t);!function(t,e,i){if(0===i[0]||0===i[8]||0===i[4])return;const r=t.length,s=i[0],n=i[1],o=i[2],a=-e[0]+s+s/2,c=-e[1]+n+n/2,l=-e[2]+o+o/2;for(let e=0;e<r;e+=3)t[e+0]=(t[e+0]+a)%s,t[e+1]=(t[e+1]+c)%n,t[e+2]=(t[e+2]+l)%o}(i,r,t)}if(this.removePeriodicity){const t=function(t){return[Oi(t,3,0),Oi(t,3,1),Oi(t,3,2)]}(i);!function(t,e,i){if(0===e[0]||0===e[8]||0===e[4])return;const r=t.length;for(let s=3;s<r;s+=3)for(let r=0;r<3;++r){const n=(t[s+r]-i[r])/e[3*r+r];Math.abs(n)>.5&&(t[s+r]-=e[3*r+r]*Math.round(n))}}(i,e,t)}this.removePbc&&function(t,e){if(0===e[0]||0===e[8]||0===e[4])return;const i=t.length;for(let r=3;r<i;r+=3)for(let i=0;i<3;++i){const s=t[r+i]-t[r-3+i];if(Math.abs(s)>.9*e[3*i+i])if(s>0)for(let s=0;s<3;++s)t[r+s]-=e[3*i+s];else for(let s=0;s<3;++s)t[r+s]+=e[3*i+s]}}(i,e)}this.selectionIndices.length>0&&this.coords1&&this.superpose&&this._doSuperpose(i),this.frameCache[t]=i,this.boxCache[t]=e,this.frameCacheSize+=1}_setFrameCount(t){t!==this._frameCount&&(this._frameCount=t,this.signals.countChanged.dispatch(t))}dispose(){this._resetCache(),this._disposed=!0,this.player&&this.player.stop()}setPlayer(t){this.player=t,this.signals.playerChanged.dispatch(t)}getFrameTime(t){return this.timeOffset+t*this.deltaTime}}class xl extends bl{constructor(t,e,i){const r=i||{};r.timeOffset=st(r.timeOffset,t.timeOffset),r.deltaTime=st(r.deltaTime,t.deltaTime),super("",e,r),this.name=t.name,this.path=t.path,this.frames=t.coordinates,this.boxes=t.boxes,this._init(e)}get type(){return"frames"}_makeAtomIndices(){"StructureView"===this.structure.type?this.atomIndices=this.structure.getAtomIndices():this.atomIndices=void 0}_loadFrame(t,e){let i;const r=this.frames[t];if(this.atomIndices){const t=this.atomIndices,e=t.length;i=new Float32Array(3*e);for(let s=0;s<e;++s){const e=3*s,n=3*t[s];i[e+0]=r[n+0],i[e+1]=r[n+1],i[e+2]=r[n+2]}}else i=new Float32Array(r);const s=this.boxes[t],n=this.frames.length;this._process(t,s,i,n),"function"==typeof e&&e()}_loadFrameCount(){this.frames&&this._setFrameCount(this.frames.length)}}class vl extends bl{constructor(t,e,i){super("",e,i),this._init(e)}get type(){return"structure"}_makeAtomIndices(){this.structure.atomSet&&this.structure.atomSet.getSize()<this.structure.atomStore.count?this.atomIndices=this.structure.getAtomIndices():this.atomIndices=void 0}_loadFrame(t,e){let i;const r=this.structure,s=r.frames[t];if(this.atomIndices){const t=this.atomIndices,e=t.length;i=new Float32Array(3*e);for(let r=0;r<e;++r){const e=3*r,n=3*t[r];i[e+0]=s[n+0],i[e+1]=s[n+1],i[e+2]=s[n+2]}}else i=new Float32Array(s);const n=r.boxes[t],o=r.frames.length;this._process(t,n,i,o),"function"==typeof e&&e()}_loadFrameCount(){this._setFrameCount(this.structure.frames.length)}}class wl extends bl{constructor(t,e,i){super(t,e,i),this._init(e)}get type(){return"remote"}_makeAtomIndices(){const t=[];if("StructureView"===this.structure.type){const e=this.structure.getAtomIndices(),i=e.length;let r=e[0],s=e[0];for(let n=1;n<i;++n){const i=e[n];s+1<i&&(t.push([r,s+1]),r=i),s=i}t.push([r,s+1])}else t.push([0,this.atomCount]);this.atomIndices=t}_loadFrame(t,e){const i=new XMLHttpRequest,r=qe.getFrameUrl(this.trajPath,t),s=qe.getFrameParams(this.trajPath,this.atomIndices);i.open("POST",r,!0),i.responseType="arraybuffer",i.setRequestHeader("Content-type","application/x-www-form-urlencoded"),i.addEventListener("load",(()=>{const s=i.response;if(!s)return void Me.error(`empty arrayBuffer for '${r}'`);const n=new Int32Array(s,0,1)[0],o=new Float32Array(s,8,9),a=new Float32Array(s,44);this._process(t,o,a,n),"function"==typeof e&&e()}),!1),i.send(s)}_loadFrameCount(){const t=new XMLHttpRequest,e=qe.getCountUrl(this.trajPath);t.open("GET",e,!0),t.addEventListener("load",(()=>{this._setFrameCount(parseInt(t.response))}),!1),t.send()}}class Al extends bl{constructor(t,e,i){super("",e,i),this.requestCallback=t,this._init(e)}get type(){return"callback"}_makeAtomIndices(){const t=[];if("StructureView"===this.structure.type){const e=this.structure.getAtomIndices(),i=e.length;let r=e[0],s=e[0];for(let n=1;n<i;++n){const i=e[n];s+1<i&&(t.push([r,s+1]),r=i),s=i}t.push([r,s+1])}else t.push([0,this.atomCount]);this.atomIndices=t}_loadFrame(t,e){this.requestCallback(((t,i,r,s)=>{this._process(t,i,r,s),"function"==typeof e&&e()}),t,this.atomIndices)}_loadFrameCount(){this.requestCallback((t=>this._setFrameCount(t)))}}Cc.prototype.getView=function(t){return new _l(this,t)};class _l extends Cc{constructor(t,i){super(),this.structure=t,this.selection=i,this.center=new e,this.boundingBox=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],this._bp=this.getBondProxy(),this._ap=this.getAtomProxy(),this._rp=this.getResidueProxy(),this._cp=this.getChainProxy(),this.selection&&this.selection.signals.stringChanged.add(this.refresh,this),this.structure.signals.refreshed.add(this.refresh,this),this.refresh()}init(){}get type(){return"StructureView"}get name(){return this.structure.name}get path(){return this.structure.path}get title(){return this.structure.title}get id(){return this.structure.id}get data(){return this.structure.data}get atomSetDict(){return this.structure.atomSetDict}get biomolDict(){return this.structure.biomolDict}get entityList(){return this.structure.entityList}get unitcell(){return this.structure.unitcell}get frames(){return this.structure.frames}get boxes(){return this.structure.boxes}get validation(){return this.structure.validation}get bondStore(){return this.structure.bondStore}get backboneBondStore(){return this.structure.backboneBondStore}get rungBondStore(){return this.structure.rungBondStore}get atomStore(){return this.structure.atomStore}get residueStore(){return this.structure.residueStore}get chainStore(){return this.structure.chainStore}get modelStore(){return this.structure.modelStore}get atomMap(){return this.structure.atomMap}get residueMap(){return this.structure.residueMap}get bondHash(){return this.structure.bondHash}get spatialHash(){return this.structure.spatialHash}get _hasCoords(){return this.structure._hasCoords}set _hasCoords(t){this.structure._hasCoords=t}refresh(){De&&Me.time("StructureView.refresh"),this.atomSetCache={};const t=this.structure;if(this.selection.isAllSelection()&&t!==this&&t.atomSet&&t.bondSet){this.atomSet=t.atomSet.clone(),this.bondSet=t.bondSet.clone();for(let t in this.atomSetDict){const e=this.atomSetDict[t];this.atomSetCache["__"+t]=e.clone()}this.atomCount=t.atomCount,this.bondCount=t.bondCount,this.boundingBox.copy(t.boundingBox),this.center.copy(t.center)}else if(this.selection.isNoneSelection()&&t!==this&&t.atomSet&&t.bondSet){this.atomSet=new Os(t.atomCount),this.bondSet=new Os(t.bondCount);for(let e in this.atomSetDict)this.atomSetCache["__"+e]=new Os(t.atomCount);this.atomCount=0,this.bondCount=0,this.boundingBox.makeEmpty(),this.center.set(0,0,0)}else{this.atomSet=this.getAtomSet(this.selection,!0),t.atomSet&&(this.atomSet=this.atomSet.intersection(t.atomSet)),this.bondSet=this.getBondSet();for(let t in this.atomSetDict){const e=this.atomSetDict[t];this.atomSetCache["__"+t]=e.makeIntersection(this.atomSet)}this.atomCount=this.atomSet.getSize(),this.bondCount=this.bondSet.getSize(),this.boundingBox=this.getBoundingBox(),this.center=this.boundingBox.getCenter(new e)}De&&Me.timeEnd("StructureView.refresh"),this.signals.refreshed.dispatch()}setSelection(t){this.selection=t,this.refresh()}getSelection(t){const e=[];t&&t.string&&e.push(t.string);const i=this.structure.getSelection();i&&i.string&&e.push(i.string),this.selection&&this.selection.string&&e.push(this.selection.string);let r="";return e.length>0&&(r=`( ${e.join(" ) AND ( ")} )`),new pe(r)}getStructure(){return this.structure.getStructure()}eachBond(t,e){this.structure.eachBond(t,this.getSelection(e))}eachAtom(t,e){const i=this.getAtomProxy(),r=this.getAtomSet(e),s=this.atomStore.count;if(r.getSize()<s)r.forEach((function(e){i.index=e,t(i)}));else for(let e=0;e<s;++e)i.index=e,t(i)}eachResidue(t,e){this.structure.eachResidue(t,this.getSelection(e))}eachResidueN(t,e){console.error("StructureView.eachResidueN() not implemented")}eachChain(t,e){this.structure.eachChain(t,this.getSelection(e))}eachModel(t,e){this.structure.eachModel(t,this.getSelection(e))}getAtomSet(t,e=!1){let i=this.structure.getAtomSet(t);return!e&&this.atomSet&&(i=i.makeIntersection(this.atomSet)),i}getAtomIndices(t){return this.structure.getAtomIndices(this.getSelection(t))}refreshPosition(){return this.structure.refreshPosition()}dispose(){this.selection&&this.selection.signals.stringChanged.remove(this.refresh,this),this.structure.signals.refreshed.remove(this.refresh,this),this.structure=new Cc,delete this.atomSet,delete this.bondSet}}const Sl=[[4,0,-2,-1,-2,0,-2,-1,-1,-1,-1,-2,-1,-1,-1,1,0,0,-3,-2],[0,9,-3,-4,-2,-3,-3,-1,-3,-1,-1,-3,-3,-3,-3,-1,-1,-1,-2,-2],[-2,-3,6,2,-3,-1,-1,-3,-1,-4,-3,1,-1,0,-2,0,-1,-3,-4,-3],[-1,-4,2,5,-3,-2,0,-3,1,-3,-2,0,-1,2,0,0,-1,-2,-3,-2],[-2,-2,-3,-3,6,-3,-1,0,-3,0,0,-3,-4,-3,-3,-2,-2,-1,1,3],[0,-3,-1,-2,-3,6,-2,-4,-2,-4,-3,0,-2,-2,-2,0,-2,-3,-2,-3],[-2,-3,-1,0,-1,-2,8,-3,-1,-3,-2,1,-2,0,0,-1,-2,-3,-2,2],[-1,-1,-3,-3,0,-4,-3,4,-3,2,1,-3,-3,-3,-3,-2,-1,3,-3,-1],[-1,-3,-1,1,-3,-2,-1,-3,5,-2,-1,0,-1,1,2,0,-1,-2,-3,-2],[-1,-1,-4,-3,0,-4,-3,2,-2,4,2,-3,-3,-2,-2,-2,-1,1,-2,-1],[-1,-1,-3,-2,0,-3,-2,1,-1,2,5,-2,-2,0,-1,-1,-1,1,-1,-1],[-2,-3,1,0,-3,0,1,-3,0,-3,-2,6,-2,0,0,1,0,-3,-4,-2],[-1,-3,-1,-1,-4,-2,-2,-3,-1,-3,-2,-2,7,-1,-2,-1,-1,-2,-4,-3],[-1,-3,0,2,-3,-2,0,-3,1,-2,0,0,-1,5,1,0,-1,-2,-2,-1],[-1,-3,-2,0,-3,-2,0,-3,2,-2,-1,0,-2,1,5,-1,-1,-3,-3,-2],[1,-1,0,0,-2,0,-1,-2,0,-2,-1,1,-1,0,-1,4,1,-2,-3,-2],[0,-1,-1,-1,-2,-2,-2,-1,-1,-1,-1,0,-1,-1,-1,1,5,0,-2,-2],[0,-1,-3,-2,-1,-3,-3,3,-2,1,1,-3,-2,-2,-3,-2,0,4,-3,-1],[-3,-2,-4,-3,1,-2,-2,-3,-3,-2,-1,-4,-4,-2,-3,-3,-2,-3,11,2],[-2,-2,-3,-2,3,-3,2,-1,-2,-1,-1,-2,-3,-1,-2,-2,-2,-1,2,7]];function Cl(t,e){let i,r=0;const s={};return e.forEach((function(e){i=0;const n={};e.forEach((function(e){n[t[i++]]=e})),s[t[r++]]=n})),s}const Pl={blosum62:Cl("ARNDCQEGHILKMFPSTWYVBZ?",[[4,-1,-2,-2,0,-1,-1,0,-2,-1,-1,-1,-1,-2,-1,1,0,-3,-2,0,-2,-1,0],[-1,5,0,-2,-3,1,0,-2,0,-3,-2,2,-1,-3,-2,-1,-1,-3,-2,-3,-1,0,-1],[-2,0,6,1,-3,0,0,0,1,-3,-3,0,-2,-3,-2,1,0,-4,-2,-3,3,0,-1],[-2,-2,1,6,-3,0,2,-1,-1,-3,-4,-1,-3,-3,-1,0,-1,-4,-3,-3,4,1,-1],[0,-3,-3,-3,9,-3,-4,-3,-3,-1,-1,-3,-1,-2,-3,-1,-1,-2,-2,-1,-3,-3,-2],[-1,1,0,0,-3,5,2,-2,0,-3,-2,1,0,-3,-1,0,-1,-2,-1,-2,0,3,-1],[-1,0,0,2,-4,2,5,-2,0,-3,-3,1,-2,-3,-1,0,-1,-3,-2,-2,1,4,-1],[0,-2,0,-1,-3,-2,-2,6,-2,-4,-4,-2,-3,-3,-2,0,-2,-2,-3,-3,-1,-2,-1],[-2,0,1,-1,-3,0,0,-2,8,-3,-3,-1,-2,-1,-2,-1,-2,-2,2,-3,0,0,-1],[-1,-3,-3,-3,-1,-3,-3,-4,-3,4,2,-3,1,0,-3,-2,-1,-3,-1,3,-3,-3,-1],[-1,-2,-3,-4,-1,-2,-3,-4,-3,2,4,-2,2,0,-3,-2,-1,-2,-1,1,-4,-3,-1],[-1,2,0,-1,-3,1,1,-2,-1,-3,-2,5,-1,-3,-1,0,-1,-3,-2,-2,0,1,-1],[-1,-1,-2,-3,-1,0,-2,-3,-2,1,2,-1,5,0,-2,-1,-1,-1,-1,1,-3,-1,-1],[-2,-3,-3,-3,-2,-3,-3,-3,-1,0,0,-3,0,6,-4,-2,-2,1,3,-1,-3,-3,-1],[-1,-2,-2,-1,-3,-1,-1,-2,-2,-3,-3,-1,-2,-4,7,-1,-1,-4,-3,-2,-2,-1,-2],[1,-1,1,0,-1,0,0,0,-1,-2,-2,0,-1,-2,-1,4,1,-3,-2,-2,0,0,0],[0,-1,0,-1,-1,-1,-1,-2,-2,-1,-1,-1,-1,-2,-1,1,5,-2,-2,0,-1,-1,0],[-3,-3,-4,-4,-2,-2,-3,-2,-2,-3,-2,-3,-1,1,-4,-3,-2,11,2,-3,-4,-3,-2],[-2,-2,-2,-3,-2,-1,-2,-3,2,-1,-1,-2,-1,3,-3,-2,-2,2,7,-1,-3,-2,-1],[0,-3,-3,-3,-1,-2,-2,-3,-3,3,1,-2,1,-1,-2,-2,0,-3,-1,4,-3,-2,-1],[-2,-1,3,4,-3,0,1,-1,0,-3,-4,0,-3,-3,-2,0,-1,-4,-3,-3,4,1,-1],[-1,0,0,1,-3,3,4,-2,0,-3,-3,1,-1,-3,-1,0,-1,-3,-2,-2,1,4,-1],[0,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-2,0,0,-2,-1,-1,-1,-1,-1]]),blosum62x:Cl("ACDEFGHIKLMNPQRSTVWY",Sl)};class Il{constructor(t,e,i=-10,r=-1,s="blosum62"){this.seq1=t,this.seq2=e,this.gapPenalty=i,this.gapExtensionPenalty=r,s&&(this.substMatrix=Pl[s])}initMatrices(){this.n=this.seq1.length,this.m=this.seq2.length,this.score=void 0,this.ali="",this.S=[],this.V=[],this.H=[];for(let t=0;t<=this.n;++t){this.S[t]=[],this.V[t]=[],this.H[t]=[];for(let e=0;e<=this.m;++e)this.S[t][e]=0,this.V[t][e]=0,this.H[t][e]=0}for(let t=0;t<=this.n;++t)this.S[t][0]=this.gap(0),this.H[t][0]=-1/0;for(let t=0;t<=this.m;++t)this.S[0][t]=this.gap(0),this.V[0][t]=-1/0;this.S[0][0]=0}gap(t){return this.gapPenalty+t*this.gapExtensionPenalty}makeScoreFn(){const t=this.seq1,e=this.seq2,i=this.substMatrix;return i?function(r,s){const n=t[r],o=e[s];try{return i[n][o]}catch(t){return-4}}:(Me.warn("Alignment: no subst matrix"),function(i,r){return t[i]===e[r]?5:-3})}calc(){De&&Me.time("Alignment.calc"),this.initMatrices();const t=this.gap(0),e=this.makeScoreFn(),i=this.gapExtensionPenalty,r=this.V,s=this.H,n=this.S,o=this.n,a=this.m;let c,l,h,d,u;for(let m=1;m<=o;++m){l=n[m-1],c=r[m-1],h=r[m],d=s[m],u=n[m];for(let r=1;r<=a;++r)h[r]=Math.max(l[r]+t,c[r]+i),d[r]=Math.max(u[r-1]+t,d[r-1]+i),u[r]=Math.max(l[r-1]+e(m-1,r-1),h[r],d[r])}De&&Me.timeEnd("Alignment.calc"),De&&Me.log(this.S,this.V,this.H)}trace(){De&&Me.time("Alignment.trace"),this.ali1="",this.ali2="";const t=this.makeScoreFn();let e,i=this.n,r=this.m;for(this.S[i][r]>=this.V[i][r]?(e="S",this.score=this.S[i][r]):this.V[i][r]>=this.H[i][r]?(e="V",this.score=this.V[i][r]):(e="H",this.score=this.H[i][r]),De&&Me.log("Alignment: SCORE",this.score),De&&Me.log("Alignment: S, V, H",this.S[i][r],this.V[i][r],this.H[i][r]);i>0&&r>0;)"S"===e?this.S[i][r]===this.S[i-1][r-1]+t(i-1,r-1)?(this.ali1=this.seq1[i-1]+this.ali1,this.ali2=this.seq2[r-1]+this.ali2,--i,--r,e="S"):this.S[i][r]===this.V[i][r]?e="V":this.S[i][r]===this.H[i][r]?e="H":(--i,--r):"V"===e?this.V[i][r]===this.V[i-1][r]+this.gapExtensionPenalty?(this.ali1=this.seq1[i-1]+this.ali1,this.ali2="-"+this.ali2,--i,e="V"):this.V[i][r]===this.S[i-1][r]+this.gap(0)?(this.ali1=this.seq1[i-1]+this.ali1,this.ali2="-"+this.ali2,--i,e="S"):--i:"H"===e?this.H[i][r]===this.H[i][r-1]+this.gapExtensionPenalty?(this.ali1="-"+this.ali1,this.ali2=this.seq2[r-1]+this.ali2,--r,e="H"):this.H[i][r]===this.S[i][r-1]+this.gap(0)?(this.ali1="-"+this.ali1,this.ali2=this.seq2[r-1]+this.ali2,--r,e="S"):--r:Me.error("Alignment: no matrix");for(;i>0;)this.ali1=this.seq1[i-1]+this.ali1,this.ali2="-"+this.ali2,--i;for(;r>0;)this.ali1="-"+this.ali1,this.ali2=this.seq2[r-1]+this.ali2,--r;De&&Me.timeEnd("Alignment.trace"),De&&Me.log([this.ali1,this.ali2])}}function kl(t,e,i=!1,r="",s=""){let n,o,a,c,l;if(i){let i=t,h=e;r&&s&&(i=t.getView(new pe(r)),h=e.getView(new pe(s)));const d=i.getSequence(),u=h.getSequence(),m=new Il(d.join(""),u.join(""));let p,f;m.calc(),m.trace(),n=0,o=0,a=m.ali1.length;const g=[],y=[];for(let t=0;t<a;++t){const e=m.ali1[t],i=m.ali2[t];p=0,f=0,"-"===e?y[o]=!1:(y[o]=!0,p=1),"-"===i?g[n]=!1:(g[n]=!0,f=1),n+=p,o+=f}const b=[],x=[],v=i.getAtomProxy(),w=h.getAtomProxy();n=0,i.eachResidue((function(t){void 0!==t.traceAtomIndex&&t.traceAtomIndex===t.getAtomIndexByName("CA")&&(g[n]&&(v.index=t.getAtomIndexByName("CA"),b.push(v.x,v.y,v.z)),n+=1)})),n=0,h.eachResidue((function(t){void 0!==t.traceAtomIndex&&t.traceAtomIndex===t.getAtomIndexByName("CA")&&(y[n]&&(w.index=t.getAtomIndexByName("CA"),x.push(w.x,w.y,w.z)),n+=1)})),c=new Float32Array(b),l=new Float32Array(x)}else{c=t.getView(new pe(`${r} and .CA`)),l=e.getView(new pe(`${s} and .CA`))}const h=new fl(c,l).transform(t);return t.refreshPosition(),h}const Ml=Object.assign({sele:"",defaultAssembly:""},cl);class Tl extends ll{constructor(t,e,i={}){super(t,e,Object.assign({name:e.name},i)),this.structure=e,this.trajList=[],this.signals=Object.assign(this.signals,{trajectoryAdded:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],trajectoryRemoved:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],defaultAssemblyChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]}),this.initSelection(this.parameters.sele),this.pickBuffer=function(t){let e=0,i=0;const r=[];return{has:function(t){return-1!==r.indexOf(t)},get:function(t){return r[t]},push:function(s){r[e]=s,e=(t+e+1)%t,++i},get count(){return i},get data(){return r.slice(0,Math.min(i,t))},clear:function(){i=0,e=0,r.length=0}}}(4),this.pickDict=function(){const t={};return{has:function(e){return void 0!==t[JSON.stringify(e)]},add:function(e,i){t[JSON.stringify(e)]=i},del:function(e){delete t[JSON.stringify(e)]},get values(){return Object.keys(t).map((e=>t[e]))}}}(),this.spacefillRepresentation=this.addRepresentation("spacefill",{sele:"none",opacity:Te.opacity,color:Te.color,disablePicking:!0,radiusType:"data"},!0),this.distanceRepresentation=this.addRepresentation("distance",Te,!0),this.angleRepresentation=this.addRepresentation("angle",Te,!0),this.dihedralRepresentation=this.addRepresentation("dihedral",Te,!0),this.measureRepresentations=new dl([this.spacefillRepresentation,this.distanceRepresentation,this.angleRepresentation,this.dihedralRepresentation]),this.setDefaultAssembly(this.parameters.defaultAssembly),this.structure.signals.refreshed.add((()=>{this.updateRepresentations({position:!0})}))}get defaultParameters(){return Ml}get type(){return"structure"}initSelection(t){this.selection=new pe(t),this.structureView=new _l(this.structure,this.selection),this.selection.signals.stringChanged.add((()=>{this.structureView.setSelection(this.selection),this.rebuildRepresentations(),this.rebuildTrajectories()}))}setSelection(t){return this.parameters.sele=t,this.selection.setString(t),this}setDefaultAssembly(t){if(void 0===this.structure.biomolDict[t]&&(t=""),this.parameters.defaultAssembly!==t){const e={defaultAssembly:t};this.reprList.forEach((t=>t.setParameters(e))),this.measureRepresentations.setParameters(e),this.parameters.defaultAssembly=t,this.signals.defaultAssemblyChanged.dispatch(t)}return this}rebuildRepresentations(){this.reprList.forEach((t=>{t.build()})),this.measureRepresentations.build()}rebuildTrajectories(){this.trajList.forEach((t=>{t.trajectory.setStructure(this.structureView)}))}updateRepresentations(t){super.updateRepresentations(t),this.measureRepresentations.update(t)}updateRepresentationMatrices(){super.updateRepresentationMatrices(),this.measureRepresentations.setParameters({matrix:this.matrix})}addRepresentation(t,e={},i=!1){e.defaultAssembly=this.parameters.defaultAssembly;const r=this._addRepresentation(t,this.structureView,e,i);return i||r.signals.parametersChanged.add((()=>this.measureUpdate())),r}addTrajectory(t="",e={}){const i=function(t,e,i){let r;return r=t&&t instanceof pl?new xl(t,e,i):!t&&e.frames?new vl(t,e,i):t&&"function"==typeof t?new Al(t,e,i):new wl(t,e,i),r}(t,this.structureView,e),r=new ml(this.stage,i,e);return this.trajList.push(r),this.signals.trajectoryAdded.dispatch(r),r}removeTrajectory(t){const e=this.trajList.indexOf(t);-1!==e&&this.trajList.splice(e,1),t.dispose(),this.signals.trajectoryRemoved.dispatch(t)}dispose(){this.trajList.slice().forEach((t=>t.dispose())),this.trajList.length=0,this.structure.dispose(),this.measureRepresentations.dispose(),super.dispose()}autoView(t,e){"number"==typeof t&&(e=t,t=""),this.stage.animationControls.zoomMove(this.getCenter(t),this.getZoom(t),st(e,0))}getBoxUntransformed(t){let e;return e=t?this.structureView.getBoundingBox(new pe(t)):this.structureView.boundingBox,e}getCenterUntransformed(t){return t&&"string"==typeof t?this.structure.atomCenter(new pe(t)):this.structure.center}superpose(t,e,i,r){return kl(this.structureView,t.structureView,e,i,r),this.updateRepresentations({position:!0}),this}getMaxRepresentationRadius(t){let e=0;const i=this.structure.getAtomProxy(t);return this.eachRepresentation((t=>{if(t.getVisibility()){const r=t.repr;e=Math.max(r.getAtomRadius(i),e)}})),e}measurePick(t){const e=this.pickBuffer.count;if(this.lastPick===t.index&&e>=1){if(e>1){const t=this.pickBuffer.data,i=this.pickBuffer.data.sort();this.pickDict.has(i)?this.pickDict.del(i):this.pickDict.add(i,t),2===e?this.distanceRepresentation.setParameters({atomPair:this.pickDict.values.filter((t=>2===t.length))}):3===e?this.angleRepresentation.setParameters({atomTriple:this.pickDict.values.filter((t=>3===t.length))}):4===e&&this.dihedralRepresentation.setParameters({atomQuad:this.pickDict.values.filter((t=>4===t.length))})}this.pickBuffer.clear(),this.lastPick=void 0}else this.pickBuffer.has(t.index)||this.pickBuffer.push(t.index),this.lastPick=t.index;this.measureUpdate()}measureClear(){this.pickBuffer.clear(),this.lastPick=void 0,this.spacefillRepresentation.setSelection("none")}measureBuild(){const t=this.measureData();this.distanceRepresentation.setParameters({atomPair:t.distance}),this.angleRepresentation.setParameters({atomTriple:t.angle}),this.dihedralRepresentation.setParameters({atomQuad:t.dihedral})}measureUpdate(){const t=this.pickBuffer.data,e={};t.forEach((t=>{const i=Math.max(.1,this.getMaxRepresentationRadius(t));e[t]=i*(2.3-Rt(.1,2,i))})),this.spacefillRepresentation.setSelection(t.length?"@"+t.join(","):"none"),t.length&&this.spacefillRepresentation.setParameters({radiusData:e})}measureData(){const t=this.pickDict.values;return{distance:t.filter((t=>2===t.length)),angle:t.filter((t=>3===t.length)),dihedral:t.filter((t=>4===t.length))}}removeAllMeasurements(t){const e=this.pickDict,i=e.values,r=function(t){i.filter((e=>e.length===t)).forEach((t=>e.del(t.slice().sort())))};(!t||1&t)&&r(2),(!t||2&t)&&r(3),(!t||4&t)&&r(4),this.measureBuild()}removeMeasurement(t){this.pickDict.del(t.slice().sort()),this.measureBuild()}addMeasurement(t){if(t.length<2||t.length>4)return;const e=t.slice().sort();this.pickDict.has(e)||this.pickDict.add(e,t),this.measureBuild()}}Ue.add("structure",Tl),Ue.add("structureview",Tl);class Bl extends ll{constructor(t,e,i={}){super(t,e,Object.assign({name:e.name},i)),this.surface=e}get type(){return"surface"}addRepresentation(t,e={}){return this._addRepresentation(t,this.surface,e)}getBoxUntransformed(){return this.surface.boundingBox}getCenterUntransformed(){return this.surface.center}dispose(){this.surface.dispose(),super.dispose()}}Ue.add("surface",Bl);class Dl extends ll{constructor(t,e,i={}){super(t,e,Object.assign({name:e.name},i)),this.volume=e}get type(){return"volume"}addRepresentation(t,e={}){return this._addRepresentation(t,this.volume,e)}getBoxUntransformed(){return this.volume.boundingBox}getCenterUntransformed(){return this.volume.center}dispose(){this.volume.dispose(),super.dispose()}}Ue.add("volume",Dl);class $l extends hl{addRepresentation(t,e){return this.forEach((i=>i.addRepresentation(t,e)))}autoView(t){return this.forEach((e=>e.autoView(t)))}}function Ol(t,e){return t instanceof RegExp?null!==e.name.match(t):e.name===t}const Rl=new e,El={impostor:!0,quality:"medium",workerDefault:!0,sampleLevel:0,backgroundColor:"black",rotateSpeed:2,zoomSpeed:1.2,panSpeed:1,clipNear:0,clipFar:100,clipDist:10,clipMode:"scene",clipScale:"relative",fogNear:50,fogFar:100,cameraFov:40,cameraEyeSep:.3,cameraType:"perspective",lightColor:14540253,lightIntensity:1,ambientColor:14540253,ambientIntensity:.2,hoverTimeout:0,tooltip:!0,mousePreset:"default"};class Fl{constructor(t,e={}){this.signals={parametersChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],fullscreenChanged:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],componentAdded:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],componentRemoved:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],clicked:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"],hovered:new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]},this.tasks=new ui,this.compList=[],this.defaultFileParams={},this.logList=[],this.viewer=new Ji(t),this.viewer.renderer&&(this.tooltip=document.createElement("div"),Object.assign(this.tooltip.style,{display:"none",position:"fixed",zIndex:"1000000",pointerEvents:"none",backgroundColor:"rgba( 0, 0, 0, 0.6 )",color:"lightgrey",padding:"8px",fontFamily:"sans-serif"}),this.viewer.container.appendChild(this.tooltip),this.mouseObserver=new sr(this.viewer.renderer.domElement),this.viewerControls=new kr(this),this.trackballControls=new gr(this),this.pickingControls=new xr(this),this.animationControls=new Lr(this),this.mouseControls=new Jo(this),this.keyControls=new ia(this),this.pickingBehavior=new ra(this),this.mouseBehavior=new sa(this),this.animationBehavior=new na(this),this.keyBehavior=new aa(this),this.spinAnimation=this.animationControls.spin([0,1,0],.005),this.spinAnimation.pause(!0),this.rockAnimation=this.animationControls.rock([0,1,0],.005),this.rockAnimation.pause(!0),this.parameters=nt(e,El),this.setParameters(this.parameters),this.viewer.animate())}setParameters(t={}){ot(this.parameters,t);const e=t,i=this.parameters,r=this.viewer,s=this.trackballControls;return void 0!==e.quality&&this.setQuality(i.quality),void 0!==e.impostor&&this.setImpostor(i.impostor),void 0!==e.rotateSpeed&&(s.rotateSpeed=i.rotateSpeed),void 0!==e.zoomSpeed&&(s.zoomSpeed=i.zoomSpeed),void 0!==e.panSpeed&&(s.panSpeed=i.panSpeed),void 0!==e.mousePreset&&this.mouseControls.preset(i.mousePreset),this.mouseObserver.setParameters({hoverTimeout:i.hoverTimeout}),r.setClip(i.clipNear,i.clipFar,i.clipDist,i.clipMode,i.clipScale),r.setFog(void 0,i.fogNear,i.fogFar),r.setCamera(i.cameraType,i.cameraFov,i.cameraEyeSep),r.setSampling(i.sampleLevel),r.setBackground(i.backgroundColor),r.setLight(i.lightColor,i.lightIntensity,i.ambientColor,i.ambientIntensity),this.signals.parametersChanged.dispatch(this.getParameters()),this}log(t){console.log("STAGE LOG",t),this.logList.push(t)}getParameters(){return Object.assign({},this.parameters)}defaultFileRepresentation(t){if(t instanceof Tl){let e,i,r;t.setSelection("/0");const s=t.structure;if(s.biomolDict.BU1){const n=s.biomolDict.BU1;e=n.getAtomCount(s),i=n.getResidueCount(s),r=n.getInstanceCount(),t.setDefaultAssembly("BU1")}else e=s.getModelProxy(0).atomCount,i=s.getModelProxy(0).residueCount,r=1;let n=e;Se&&(n*=4);const o=s.atomStore.count/s.residueStore.count<2;o&&(n*=10);let a="chainname",c="RdYlBu",l=!1;if(1===s.getChainnameCount(new pe("polymer and /0"))&&(a="residueindex",c="Spectral",l=!0),De&&console.log(n,e,r,o),i/r<4)t.addRepresentation("ball+stick",{colorScheme:"element",radiusScale:2,aspectRatio:1.5,bondScale:.3,bondSpacing:.75,quality:"auto"});else if(r>5&&n>15e3||n>7e5){let e=Math.min(2,Math.max(.1,6e3/(n/r)));o&&(e=Math.min(e,.5)),t.addRepresentation("surface",{colorScheme:a,colorScale:c,colorReverse:l,sele:"polymer",surfaceType:"av",probeRadius:1.4,scaleFactor:e,useWorker:!1})}else n>25e4?t.addRepresentation("backbone",{colorScheme:a,colorScale:c,colorReverse:l,lineOnly:!0}):n>1e5?t.addRepresentation("backbone",{colorScheme:a,colorScale:c,colorReverse:l,quality:"low",disableImpostor:!0,radiusScale:2}):n>8e4?t.addRepresentation("backbone",{colorScheme:a,colorScale:c,colorReverse:l,radiusScale:2}):(t.addRepresentation("cartoon",{colorScheme:a,colorScale:c,colorReverse:l,radiusScale:.7,aspectRatio:5,quality:"auto"}),n<5e4&&t.addRepresentation("base",{colorScheme:a,colorScale:c,colorReverse:l,quality:"auto"}),t.addRepresentation("ball+stick",{sele:"ligand",colorScheme:"element",radiusScale:2,aspectRatio:1.5,bondScale:.3,bondSpacing:.75,quality:"auto"}));t.structure.frames.length&&t.addTrajectory()}else(t instanceof Bl||t instanceof Dl)&&t.addRepresentation("surface");this.tasks.onZeroOnce(this.autoView,this)}loadFile(t,e={}){const i=Object.assign({},this.defaultFileParams,e),r=ri(t).name;this.tasks.increment(),this.log(`loading file '${r}'`);const s=st(i.ext,ri(t).ext);let n;return n=ze.isTrajectory(s)?Promise.reject(new Error(`loadFile: ext '${s}' is a trajectory and must be loaded into a structure component`)):ni(t,i),n.then((t=>{this.log(`loaded '${r}'`);const e=this.addComponentFromObject(t,i);return i.defaultRepresentation&&this.defaultFileRepresentation(e),this.tasks.decrement(),e}),(t=>{this.tasks.decrement();const e=`error loading file: '${t}'`;throw this.log(e),e}))}loadScript(t){const e=ri(t).name;return this.log(`loading script '${e}'`),ni(t).then((t=>{this.tasks.increment(),this.log(`running script '${e}'`),t.run(this).then((()=>{this.tasks.decrement(),this.log(`finished script '${e}'`)})),this.log(`called script '${e}'`)}),(t=>{this.tasks.decrement();const i=`errored script '${e}' "${t}"`;throw this.log(i),i}))}addComponent(t){t?(this.compList.push(t),this.signals.componentAdded.dispatch(t)):Me.warn("Stage.addComponent: no component given")}addComponentFromObject(t,e={}){const i=Ue.get(t.type);if(i){const r=new i(this,t,e);return this.addComponent(r),r}Me.warn("no component for object type",t.type)}removeComponent(t){const e=this.compList.indexOf(t);-1!==e&&(this.compList.splice(e,1),t.dispose(),this.signals.componentRemoved.dispatch(t))}removeAllComponents(){this.compList.slice().forEach((t=>this.removeComponent(t)))}handleResize(){this.viewer.handleResize()}setSize(t,e){const i=this.viewer.container;i!==document.body&&(void 0!==t&&(i.style.width=t),void 0!==e&&(i.style.height=e),this.handleResize())}toggleFullscreen(t){if(!(document.fullscreenEnabled||document.mozFullScreenEnabled||document.webkitFullscreenEnabled||document.msFullscreenEnabled))return void Me.log("fullscreen mode (currently) not possible");const e=this;function i(){return document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement}function r(){if(!i()&&e.lastFullscreenElement){const t=e.lastFullscreenElement;t.style.width=t.dataset.normalWidth||"",t.style.height=t.dataset.normalHeight||"",document.removeEventListener("fullscreenchange",r),document.removeEventListener("mozfullscreenchange",r),document.removeEventListener("webkitfullscreenchange",r),document.removeEventListener("MSFullscreenChange",r),e.handleResize(),e.signals.fullscreenChanged.dispatch(!1)}}t=t||this.viewer.container,this.lastFullscreenElement=t,i()?document.exitFullscreen?document.exitFullscreen():document.msExitFullscreen?document.msExitFullscreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.webkitExitFullscreen&&document.webkitExitFullscreen():(t.dataset.normalWidth=t.style.width||"",t.dataset.normalHeight=t.style.height||"",t.style.width=window.screen.width+"px",t.style.height=window.screen.height+"px",t.requestFullscreen?t.requestFullscreen():t.msRequestFullscreen?t.msRequestFullscreen():t.mozRequestFullScreen?t.mozRequestFullScreen():t.webkitRequestFullscreen&&t.webkitRequestFullscreen(),document.addEventListener("fullscreenchange",r),document.addEventListener("mozfullscreenchange",r),document.addEventListener("webkitfullscreenchange",r),document.addEventListener("MSFullscreenChange",r),this.handleResize(),this.signals.fullscreenChanged.dispatch(!0),setTimeout((function(){e.handleResize()}),100))}setSpin(t){t?(this.spinAnimation.resume(!0),this.rockAnimation.pause(!0)):this.spinAnimation.pause(!0)}setRock(t){t?(this.rockAnimation.resume(!0),this.spinAnimation.pause(!0)):this.rockAnimation.pause(!0)}toggleSpin(){this.setSpin(this.spinAnimation.paused)}toggleRock(){this.setRock(this.rockAnimation.paused)}getFocus(){const t=this.parameters;if("scene"!==t.clipMode)return 0;let e=t.clipNear;return"absolute"===t.clipScale&&(e=this.viewer.absoluteToRelative(e)),2*e}setFocus(t){if("scene"!==this.parameters.clipMode)return;let e,i,r,s;"relative"===this.parameters.clipScale?(e=Dt(t/2,0,49.9),i=100-e,r=50,s=function(t){return Dt(t,0,100)}(2*i-50)):(e=this.viewer.relativeToAbsolute(t/2),i=e,r=0,s=2*i),this.setParameters({clipNear:e,clipFar:i,fogNear:r,fogFar:s})}getZoomForBox(t){const e=t.getSize(Rl),i=Math.max(e.x,e.y,e.z),r=Math.min(e.x,e.y,e.z);let s=i+Math.sqrt(r);const n=kt(this.viewer.perspectiveCamera.fov),o=this.viewer.width,a=this.viewer.height,c=a<o?1:o/a;return s=Math.abs(.5*s/c/Math.sin(n/2)),s+=this.parameters.clipDist,-s}getBox(){return this.viewer.boundingBox}getZoom(){return this.getZoomForBox(this.getBox())}getCenter(t){return this.getBox().getCenter(t||new e)}autoView(t){this.animationControls.zoomMove(this.getCenter(),this.getZoom(),st(t,0))}makeImage(t={}){return new Promise(((e,i)=>{this.tasks.onZeroOnce((()=>{this.tasks.increment(),this.viewer.makeImage(t).then((t=>{this.tasks.decrement(),e(t)})).catch((t=>{this.tasks.decrement(),i(t)}))}))}))}setImpostor(t){this.parameters.impostor=t;const e=["spacefill","ball+stick","licorice","hyperball","backbone","rocket","helixorient","contact","distance","dot"];this.eachRepresentation((function(i){if(!e.includes(i.getType()))return;const r=i.getParameters();r.disableImpostor=!t,i.build(r)}))}setQuality(t){this.parameters.quality=t;const e=["tube","cartoon","ribbon","trace","rope"],i=["spacefill","ball+stick","licorice","hyperball","backbone","rocket","helixorient","contact","distance","dot"];this.eachRepresentation((function(r){const s=r.getParameters();if(!e.includes(r.getType())){if(!i.includes(r.getType()))return;if(!s.disableImpostor)return void(r.repr.quality=t)}s.quality=t,r.build(s)}))}eachComponent(t,e){this.compList.slice().forEach((i=>{void 0!==e&&e!==i.type||t(i)}))}eachRepresentation(t,e){this.eachComponent((i=>{i.reprList.slice().forEach((r=>{void 0!==e&&e!==r.getType()||t(r,i)}))}))}getComponentsByName(t){const e=[];return this.eachComponent((i=>{(void 0===t||Ol(t,i))&&e.push(i)})),new $l(e)}getComponentsByObject(t){const e=[];return this.eachComponent((i=>{i.object===t&&e.push(i)})),new $l(e)}getRepresentationsByName(t){const e=[];return this.eachRepresentation(((i,r)=>{(void 0===t||Ol(t,i))&&e.push(i)})),new dl(e)}measureClear(){this.eachComponent((t=>t.measureClear()),"structure")}measureUpdate(){this.eachComponent((t=>t.measureUpdate()),"structure")}dispose(){this.tasks.dispose(),this.viewer.dispose(),this.mouseObserver.dispose()}}class Ll extends ll{constructor(t,e,i={}){super(t,e,Object.assign({name:e.name},i)),this.shape=e}get type(){return"shape"}addRepresentation(t,e={}){return this._addRepresentation(t,this.shape,e)}getBoxUntransformed(){return this.shape.boundingBox}getCenterUntransformed(){return this.shape.center}dispose(){this.shape.dispose(),super.dispose()}}function Nl(t,e,i,r){var s,n=arguments.length,o=n<3?e:null===r?r=Object.getOwnPropertyDescriptor(e,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(t,e,i,r);else for(var a=t.length-1;a>=0;a--)(s=t[a])&&(o=(n<3?s(o):n>3?s(e,i,o):s(e,i))||o);return n>3&&o&&Object.defineProperty(e,i,o),o}Ue.add("shape",Ll);class zl extends zt{constructor(t){super(t),t.scale||(this.parameters.scale="rainbow",this.parameters.reverse=st(t.reverse,!0)),this.scalePerModel={},t.structure.eachModel((t=>{this.parameters.domain=[t.atomOffset,t.atomEnd],this.scalePerModel[t.index]=this.getScale()}))}atomColor(t){return this.scalePerModel[t.modelIndex](t.index)}}Nl([Nt],zl.prototype,"atomColor",null),Fe.add("atomindex",zl);class Vl extends zt{constructor(t){if(super(t),t.scale||(this.parameters.scale="OrRd"),!t.domain){let e,i=1/0,r=-1/0;t.sele&&(e=new pe(t.sele)),t.structure.eachAtom((function(t){const e=t.bfactor;i=Math.min(i,e),r=Math.max(r,e)}),e),this.parameters.domain=[i,r]}this.bfactorScale=this.getScale()}atomColor(t){return this.bfactorScale(t.bfactor)}}Nl([Nt],Vl.prototype,"atomColor",null),Fe.add("bfactor",Vl);class Gl extends zt{constructor(t){super(t),this.chainidDictPerModel={},this.scalePerModel={},t.scale||(this.parameters.scale="Spectral"),t.structure.eachModel((t=>{let e=0;const i={};t.eachChain((function(t){void 0===i[t.chainid]&&(i[t.chainid]=e,e+=1)})),this.parameters.domain=[0,e-1],this.chainidDictPerModel[t.index]=i,this.scalePerModel[t.index]=this.getScale()}))}atomColor(t){const e=this.chainidDictPerModel[t.modelIndex];return this.scalePerModel[t.modelIndex](e[t.chainid])}}Nl([Nt],Gl.prototype,"atomColor",null),Fe.add("chainid",Gl);class Ul extends zt{constructor(t){super(t),this.scalePerModel={},t.scale||(this.parameters.scale="Spectral"),t.structure.eachModel((t=>{this.parameters.domain=[t.chainOffset,t.chainEnd],this.scalePerModel[t.index]=this.getScale()}))}atomColor(t){return this.scalePerModel[t.modelIndex](t.chainIndex)}}Nl([Nt],Ul.prototype,"atomColor",null),Fe.add("chainindex",Ul);class jl extends zt{constructor(t){super(t),this.chainnameDictPerModel={},this.scalePerModel={},t.scale||(this.parameters.scale="Spectral"),t.structure.eachModel((t=>{let e=0;const i={};t.eachChain((function(t){void 0===i[t.chainname]&&(i[t.chainname]=e,e+=1)})),this.parameters.domain=[0,e-1],this.chainnameDictPerModel[t.index]=i,this.scalePerModel[t.index]=this.getScale()}))}atomColor(t){const e=this.chainnameDictPerModel[t.modelIndex];return this.scalePerModel[t.modelIndex](e[t.chainname])}}Nl([Nt],jl.prototype,"atomColor",null),Fe.add("chainname",jl);class Hl extends zt{constructor(t){super(t),this.rsrzDict={},this.rsccDict={},t.scale||(this.parameters.scale="RdYlBu"),this.rsrzScale=this.getScale({domain:[2,0]}),this.rsccScale=this.getScale({domain:[.678,1]});const e=t.structure.validation;e&&(this.rsrzDict=e.rsrzDict,this.rsccDict=e.rsccDict)}atomColor(t){let e=t.resno+"";t.inscode&&(e+="^"+t.inscode),t.chainname&&(e+=":"+t.chainname),e+="/"+t.modelIndex;const i=this.rsrzDict[e];if(void 0!==i)return this.rsrzScale(i);const r=this.rsccDict[e];return void 0!==r?this.rsccScale(r):9474192}}Nl([Nt],Hl.prototype,"atomColor",null),Fe.add("densityfit",Hl);const Wl={ARG:{CD:.1,CZ:.5,NE:-.1},ASN:{CG:.55,OD1:-.55},ASP:{CB:-.16,CG:.36,OD1:-.6,OD2:-.6},CYS:{CB:.19,SG:-.19},GLN:{CD:.55,OE1:-.55},GLU:{CD:.36,CG:-.16,OE1:-.6,OE2:-.6},HIS:{CB:.1,CD2:.2,CE1:.45,CG:.15,ND1:.05,NE2:.05},LYS:{CE:.25,NZ:.75},MET:{CE:.06,CG:.06,SD:-.12},PTR:{C:.55,CA:.1,CZ:.25,N:-.35,O:-.55,O1P:-.85,O2P:-.85,O3P:-.85,OG1:-1.1,P:1.4},SEP:{C:.55,CA:.1,CB:.25,N:-.35,O:-.55,O1P:-.85,O2P:-.85,O3P:-.85,OG1:-1.1,P:1.4},SER:{CB:.25,OG:-.25},THR:{CB:.25,OG1:-.25},TPO:{C:.55,CA:.1,CB:.25,N:-.35,O:-.55,OG1:-1.1,O1P:-.85,O2P:-.85,O3P:-.85,P:1.4},TRP:{CD1:.06,CD2:.1,CE2:-.04,CE3:-.03,CG:-.03,NE1:-.06},TYR:{CZ:.25,OH:-.25},backbone:{C:.55,O:-.55,N:-.35,CA:.1}};class ql extends zt{constructor(t){super(t),this.delta=new e,this.hCharges=[],t.scale||(this.parameters.scale="rwb"),t.domain||(this.parameters.domain=[-50,50]),this.scale=this.getScale(),this.charges=new Float32Array(t.structure.atomCount);const i=[];t.structure.eachAtom((t=>{var r;if(this.charges[t.index]=(null!==(r=t).partialCharge?r.partialCharge:r.isProtein()&&(Wl[r.resname]&&Wl[r.resname][r.atomname]||Wl.backbone[r.atomname])||0)*t.occupancy,"N"===t.atomname){if(t.bondCount>=3)return;if(t.bondToElementCount(1))return;const r=function(t,i=new e){let r=!1,s=!1,n=!1;return i.set(2*t.x,2*t.y,2*t.z),t.eachBondedAtom((function(t){if(!r)return"H"===t.atomname?(i.set(t.x,t.y,t.z),void(r=!0)):void(s||"CA"!==t.atomname?n||"C"!==t.atomname||(n=!0,i.sub(t)):(i.sub(t),s=!0))})),r?i:s&&n?(i.normalize(),i.multiplyScalar(1.04),i.add(t),i):void 0}(t);void 0!==r&&(i.push(r),this.hCharges.push(.25*t.occupancy))}}));const r=t.structure.getBoundingBox();r.expandByScalar(1.04),this.hStore=function(t){const e=t.length,i=new Float32Array(e),r=new Float32Array(e),s=new Float32Array(e);for(let e=0;e<t.length;e++){const n=t[e];i[e]=n.x,r[e]=n.y,s[e]=n.z}return{x:i,y:r,z:s,count:e}}(i),this.hHash=new Ts(this.hStore,r),this.hash=new Ts(t.structure.atomStore,r)}positionColor(t){const e=this.charges,i=this.hCharges;let r=0;return this.hash.eachWithin(t.x,t.y,t.z,12,((t,i)=>{const s=e[t];0!==s&&(r+=s/i)})),this.hHash.eachWithin(t.x,t.y,t.z,12,((t,e)=>{const s=i[t];0!==s&&(r+=s/e)})),this.scale(332*r)}}Nl([Nt],ql.prototype,"positionColor",null),Fe.add("electrostatic",ql);const Xl={H:16777215,HE:14286847,LI:13402367,BE:12779264,B:16758197,C:9474192,N:3166456,O:16715021,F:9494608,NE:11789301,NA:11230450,MG:9109248,AL:12560038,SI:1578e4,P:16744448,S:16777008,CL:2093087,AR:8442339,K:9388244,CA:4062976,SC:15132390,TI:12567239,V:10921643,CR:9083335,MN:10255047,FE:14706227,CO:15765664,NI:5296208,CU:13140019,ZN:8224944,GA:12750735,GE:6721423,AS:12419299,SE:16752896,BR:10889513,KR:6076625,RB:7351984,SR:65280,Y:9764863,ZR:9756896,NB:7586505,MO:5551541,TC:3907230,RU:2396047,RH:687500,PD:27013,AG:12632256,CD:16767375,IN:10909043,SN:6717568,SB:10380213,TE:13924864,I:9699476,XE:9699476,CS:5707663,BA:51456,LA:7394559,CE:16777159,PR:14286791,ND:13107143,PM:10747847,SM:9437127,EU:6422471,GD:4587463,TB:3211207,DY:2097095,HO:65436,ER:58997,TM:54354,YB:48952,LU:43812,HF:5096191,TA:5089023,W:2200790,RE:2522539,OS:2516630,IR:1528967,PT:13684960,AU:16765219,HG:12105936,TL:10900557,PB:5724513,BI:10375093,PO:11230208,AT:7688005,RN:4358806,FR:4325478,RA:32e3,AC:7384058,TH:47871,PA:41471,U:36863,NP:33023,PU:27647,AM:5528818,CM:7888099,BK:9064419,CF:10565332,ES:11739092,FM:11739066,MD:11734438,NO:12389767,LR:13041766,RF:13369433,DB:13697103,SG:14221381,BH:14680120,HS:15073326,MT:15400998,DS:16777215,RG:16777215,CN:16777215,UUT:16777215,FL:16777215,UUP:16777215,LV:16777215,UUH:16777215,D:16777152,T:16777120};class Yl extends zt{constructor(t){t.value=st(t.value,Xl.C),super(t)}atomColor(t){const e=t.element;return"C"===e?this.parameters.value:Xl[e]||16777215}}Nl([Nt],Yl.prototype,"atomColor",null),Fe.add("element",Yl);class Kl extends zt{constructor(t){super(t),t.scale||(this.parameters.scale="Spectral"),t.domain||(this.parameters.domain=[0,t.structure.entityList.length-1]),this.entityindexScale=this.getScale()}atomColor(t){return this.entityindexScale(t.entityIndex)}}Nl([Nt],Kl.prototype,"atomColor",null),Fe.add("entityindex",Kl);class Zl extends zt{atomColor(t){const e=t.entity;switch(e?e.entityType:void 0){case 1:return 8374655;case 2:return 16629894;case 3:return 12496596;case 4:return 3697840;default:return 16777113}}}Nl([Nt],Zl.prototype,"atomColor",null),Fe.add("entitytype",Zl);class Ql extends zt{constructor(t){super(t),this.geoAtomDict={},this.geoDict={};const e=t.structure.validation;e&&(this.geoAtomDict=e.geoAtomDict,this.geoDict=e.geoDict)}atomColor(t){let e,i=t.resno+"";t.inscode&&(i+="^"+t.inscode),t.chainname&&(i+=":"+t.chainname),i+="/"+t.modelIndex;const r=this.geoAtomDict[i];if(void 0!==r){const i=r[t.atomname]||0;s=i,e=16843009*((s=(858993459&(s-=s>>1&1431655765))+(s>>2&858993459))+(s>>4)&252645135)>>24}else e=this.geoDict[i]||0;var s;return 0===e?2188972:1===e?16703627:2===e?16018755:e>=3?10813478:9474192}}Nl([Nt],Ql.prototype,"atomColor",null),Fe.add("geoquality",Ql);class Jl extends zt{constructor(t){super(t),this.resHF={},t.scale||(this.parameters.scale="RdYlGn");for(const t in Js)this.resHF[t]=Js[t][0];if(this.defaultResidueHydrophobicity=tn[0],!t.domain){let t=1/0,e=-1/0;for(const i in this.resHF){const r=this.resHF[i];t=Math.min(t,r),e=Math.max(e,r)}this.parameters.domain=[t,0,e]}this.hfScale=this.getScale()}atomColor(t){return this.hfScale(this.resHF[t.resname]||this.defaultResidueHydrophobicity)}}Nl([Nt],Jl.prototype,"atomColor",null),Fe.add("hydrophobicity",Jl);class th extends zt{constructor(t){super(t),t.scale||(this.parameters.scale="rainbow"),t.domain||(this.parameters.domain=[0,t.structure.modelStore.count]),this.modelindexScale=this.getScale()}atomColor(t){return this.modelindexScale(t.modelIndex)}}Nl([Nt],th.prototype,"atomColor",null),Fe.add("modelindex",th);class eh extends zt{atomColor(t){switch(t.residueType.moleculeType){case 1:return 3697840;case 2:return 15729279;case 3:return 12496596;case 4:return 16629894;case 5:return 12540695;case 6:return 8374655;default:return 16777113}}}Nl([Nt],eh.prototype,"atomColor",null),Fe.add("moleculetype",eh);class ih extends zt{constructor(t){super(t),t.scale||(this.parameters.scale="PuBu"),t.domain||(this.parameters.domain=[0,1]),this.occupancyScale=this.getScale()}atomColor(t){return this.occupancyScale(t.occupancy)}}Nl([Nt],ih.prototype,"atomColor",null),Fe.add("occupancy",ih);class rh extends zt{constructor(t){super(t),t.scale||(this.parameters.scale="rwb"),t.domain||(this.parameters.domain=[-1,1]),this.partialchargeScale=this.getScale()}atomColor(t){return this.partialchargeScale(t.partialCharge||0)}}function sh(){return 16777215*Math.random()}Nl([Nt],rh.prototype,"atomColor",null),Fe.add("partialcharge",rh);class nh extends zt{atomColor(){return sh()}volumeColor(){return sh()}positionColor(){return sh()}}Nl([Nt],nh.prototype,"atomColor",null),Nl([Nt],nh.prototype,"volumeColor",null),Nl([Nt],nh.prototype,"positionColor",null),Fe.add("random",nh);class oh extends zt{constructor(t){super(t),this.rciDict={},t.scale||(this.parameters.scale="RdYlBu"),this.rciScale=this.getScale({domain:[.6,0]});const e=t.structure.validation;e&&(this.rciDict=e.rciDict)}atomColor(t){let e=`[${t.resname}]${t.resno}`;t.chainname&&(e+=":"+t.chainname);const i=this.rciDict[e];return void 0!==i?this.rciScale(i):9474192}}Nl([Nt],oh.prototype,"atomColor",null),Fe.add("randomcoilindex",oh);class ah extends zt{constructor(t){super(t),this.scalePerChain={},t.scale||(this.parameters.scale="rainbow",this.parameters.reverse=st(t.reverse,!0)),t.structure.eachChain((t=>{this.parameters.domain=[t.residueOffset,t.residueEnd],this.scalePerChain[t.index]=this.getScale()}))}atomColor(t){return this.scalePerChain[t.chainIndex](t.residueIndex)}}Nl([Nt],ah.prototype,"atomColor",null),Fe.add("residueindex",ah);const ch={ALA:9240460,ARG:124,ASN:16743536,ASP:10485826,CYS:16777072,GLN:16731212,GLU:6684672,GLY:16777215,HIS:7368959,ILE:19456,LEU:4546117,LYS:4671416,MET:12099650,PHE:5459026,PRO:5395026,SER:16740418,THR:12078080,TRP:5195264,TYR:9203788,VAL:16747775,ASX:16711935,GLX:16711935,ASH:16711935,GLH:16711935,A:14423100,G:3329330,I:10145074,X:8190976,C:16766720,T:4286945,U:4251856,D:35723,DA:14423100,DG:3329330,DI:10145074,DX:8190976,DC:16766720,DT:4286945,DU:4251856,DD:35723};class lh extends zt{atomColor(t){return ch[t.resname]||16711935}}Nl([Nt],lh.prototype,"atomColor",null),Fe.add("resname",lh);const hh=16711808,dh=10485888,uh=6291584,mh=16762880,ph=6324479,fh=16777215,gh=11403518,yh=16580962,bh=10921722;class xh extends zt{constructor(t){super(t),this.residueProxy=t.structure.getResidueProxy()}atomColor(t){const e=t.sstruc,i=this.residueProxy;return"h"===e?hh:"g"===e?dh:"i"===e?uh:"e"===e||"b"===e?mh:"t"===e?ph:(i.index=t.residueIndex,i.isDna()?gh:i.isRna()?yh:i.isSaccharide()?bh:i.isProtein()||"s"===e||"l"===e?fh:8421504)}}Nl([Nt],xh.prototype,"atomColor",null),Fe.add("sstruc",xh);class vh extends zt{constructor(t){var e,i;super(t),t.scale||(this.parameters.scale="rwb"),this.atomData=null===(e=this.parameters.data)||void 0===e?void 0:e.atomData,this.bondData=null===(i=this.parameters.data)||void 0===i?void 0:i.bondData,this.scale=this.getScale(this.parameters)}atomColor(t){var e;const i=null===(e=this.atomData)||void 0===e?void 0:e[t.index];return void 0!==i?this.scale(i):this.parameters.value}bondColor(t,e){var i;const r=null===(i=this.bondData)||void 0===i?void 0:i[t.index];return void 0!==r?this.scale(r):this.atomProxy?(this.atomProxy.index=e?t.atomIndex1:t.atomIndex2,this.atomColor(this.atomProxy)):this.parameters.value}}Nl([Nt],vh.prototype,"atomColor",null),Nl([Nt],vh.prototype,"bondColor",null),Fe.add("structuredata",vh);class wh extends zt{atomColor(){return this.parameters.value}bondColor(){return this.parameters.value}valueColor(){return this.parameters.value}volumeColor(){return this.parameters.value}}Nl([Nt],wh.prototype,"atomColor",null),Nl([Nt],wh.prototype,"bondColor",null),Nl([Nt],wh.prototype,"valueColor",null),Nl([Nt],wh.prototype,"volumeColor",null),Fe.add("uniform",wh);class Ah extends zt{constructor(t){super(t),this.valueScale=this.getScale()}volumeColor(t){return this.valueScale(this.parameters.volume.data[t])}}Nl([Nt],Ah.prototype,"volumeColor",null),Fe.add("value",Ah);class _h extends zt{constructor(t){super(t),this.vec=new e,this.valueScale=this.getScale()}positionColor(t){const e=this.parameters.volume;if(!e||!e.inverseMatrix)return this.parameters.value;const i=this.vec,r=e.data,s=e.nx,n=e.ny,o=s*n;i.copy(t),i.applyMatrix4(e.inverseMatrix);const a=Math.floor(i.x),c=Math.floor(i.y),l=Math.floor(i.z),h=(l*n+c)*s+a,d=h+1,u=h+s,m=h+o,p=u+1,f=m+1,g=u+o,y=g+1,b=r[h],x=r[d],v=r[u],w=r[m],A=r[p],_=r[f],S=r[g],C=r[y],P=i.x-a,I=i.y-c,k=i.z-l,M=$t(b,x,P),T=$t(w,_,P),B=$t(v,A,P),D=$t(S,C,P),$=$t(M,B,I),O=$t(T,D,I),R=$t($,O,k);return this.valueScale(R)}}Nl([Nt],_h.prototype,"positionColor",null),Fe.add("volume",_h);class Sh extends zr{constructor(t,e,i){const r=i||{};if(super(t,e,r),this.type="structure",this.parameters=Object.assign({radiusType:{type:"select",options:pa.types},radiusData:{type:"hidden"},radiusSize:{type:"number",precision:3,max:10,min:.001},radiusScale:{type:"number",precision:3,max:10,min:.001},assembly:null,defaultAssembly:{type:"hidden"}},this.parameters),this.selection=new pe(r.sele),this.dataList=[],this.structure=t,this.structureView=this.structure.getView(this.selection),t.biomolDict){const e={default:"default","":t.unitcell?"AU":"FULL"};Object.keys(t.biomolDict).forEach((function(t){e[t]=t})),this.parameters.assembly={type:"select",options:e,rebuild:!0}}else this.parameters.assembly=null}get defaultScale(){return{vdw:1,covalent:1,bfactor:.01,sstruc:1}}init(t){const e=t||{};e.colorScheme=st(e.colorScheme,"element"),this.setRadius(e.radius,e),this.radiusType=st(e.radiusType,"vdw"),this.radiusData=st(e.radiusData,{}),this.radiusSize=st(e.radiusSize,1),this.radiusScale=st(e.radiusScale,1),this.assembly=st(e.assembly,"default"),this.defaultAssembly=st(e.defaultAssembly,""),"auto"===e.quality&&(e.quality=this.getQuality()),super.init(e),this.selection.signals.stringChanged.add((()=>{this.build()})),this.build()}setRadius(t,e){const i=Object.keys(ma);return"string"==typeof t&&i.includes(t.toLowerCase())?e.radiusType=t:void 0!==t&&(e.radiusType="size",e.radiusSize=t),this}getAssembly(){const t="default"===this.assembly?this.defaultAssembly:this.assembly;return this.structure.biomolDict[t]}getQuality(){let t;const e=this.structureView,i=this.getAssembly();t=i?i.getAtomCount(e):e.atomCount,Se&&(t*=4);return e.atomStore.count/e.residueStore.count<2&&(t*=10),t<15e3?"high":t<8e4?"medium":"low"}create(){if(0===this.structureView.atomCount)return;if(!this.structureView.hasCoords())return void(this.needsBuild=!0);this.needsBuild=!1;const t=this.getAssembly();if(t)t.partList.forEach(((t,e)=>{const i=t.getView(this.structureView);if(0===i.atomCount)return;const r=this.createData(i,e);r&&(r.sview=i,r.instanceList=t.getInstanceList(),this.dataList.push(r))}));else{const t=this.createData(this.structureView,0);t&&(t.sview=this.structureView,this.dataList.push(t))}}update(t){!this.lazy||this.visible?this.needsBuild?this.build():this.dataList.forEach((e=>{e.bufferList.length>0&&this.updateData(t,e)}),this):Object.assign(this.lazyProps.what,t)}updateData(t,e){this.build()}getColorParams(){return Object.assign(Object.assign({},super.getColorParams()),{structure:this.structure})}getRadiusParams(t){return{type:this.radiusType,scale:this.radiusScale,size:this.radiusSize,data:this.radiusData}}getAtomParams(t,e){return Object.assign({what:t,colorParams:this.getColorParams(),radiusParams:this.getRadiusParams()},e)}getBondParams(t,e){return Object.assign({what:t,colorParams:this.getColorParams(),radiusParams:this.getRadiusParams()},e)}getAtomRadius(t){if(this.structureView.atomSet.isSet(t.index)){return new pa(this.getRadiusParams()).atomRadius(t)}return 0}setSelection(t,e){return this.selection.setString(t,e),this}setParameters(t,e={},i=!1){const r=t||{};return this.setRadius(r.radius,r),void 0===r.radiusType&&void 0===r.radiusData&&void 0===r.radiusSize&&void 0===r.radiusScale||(e.radius=!0,Ie&&!this.disableImpostor||(i=!0)),void 0!==r.defaultAssembly&&r.defaultAssembly!==this.defaultAssembly&&("default"===this.assembly&&void 0===r.assembly||"default"===r.assembly)&&(i=!0),super.setParameters(r,e,i),this}getParameters(){return Object.assign(super.getParameters(),{sele:this.selection?this.selection.string:void 0,defaultAssembly:this.defaultAssembly})}attach(t){const e=this.viewer,i=this.bufferList;this.dataList.forEach((function(t){t.bufferList.forEach((function(r){i.push(r),e.add(r,t.instanceList)}))})),this.setVisibility(this.visible),t()}clear(){this.dataList.length=0,super.clear()}dispose(){this.structureView.dispose(),super.dispose()}}class Ch extends Sh{constructor(t,e,i){super(t,e,i),this.n=0,this.parameters=Object.assign({labelVisible:{type:"boolean"},labelSize:{type:"number",precision:3,max:10,min:.001},labelColor:{type:"color"},labelFontFamily:{type:"select",options:{"sans-serif":"sans-serif",monospace:"monospace",serif:"serif"},buffer:"fontFamily"},labelFontStyle:{type:"select",options:{normal:"normal",italic:"italic"},buffer:"fontStyle"},labelFontWeight:{type:"select",options:{normal:"normal",bold:"bold"},buffer:"fontWeight"},labelsdf:{type:"boolean",buffer:"sdf"},labelXOffset:{type:"number",precision:1,max:20,min:-20,buffer:"xOffset"},labelYOffset:{type:"number",precision:1,max:20,min:-20,buffer:"yOffset"},labelZOffset:{type:"number",precision:1,max:20,min:-20,buffer:"zOffset"},labelAttachment:{type:"select",options:{"bottom-left":"bottom-left","bottom-center":"bottom-center","bottom-right":"bottom-right","middle-left":"middle-left","middle-center":"middle-center","middle-right":"middle-right","top-left":"top-left","top-center":"top-center","top-right":"top-right"},rebuild:!0},labelBorder:{type:"boolean",buffer:"showBorder"},labelBorderColor:{type:"color",buffer:"borderColor"},labelBorderWidth:{type:"number",precision:2,max:.3,min:0,buffer:"borderWidth"},labelBackground:{type:"boolean",rebuild:!0},labelBackgroundColor:{type:"color",buffer:"backgroundColor"},labelBackgroundMargin:{type:"number",precision:2,max:2,min:0,rebuild:!0},labelBackgroundOpacity:{type:"range",step:.01,max:1,min:0,buffer:"backgroundOpacity"},labelFixedSize:{type:"boolean",buffer:"fixedSize"},lineOpacity:{type:"range",min:0,max:1,step:.01},linewidth:{type:"integer",max:50,min:1,buffer:!0}},this.parameters,{flatShaded:null})}init(t){const e=t||{};this.labelVisible=st(e.labelVisible,!0),this.labelSize=st(e.labelSize,2),this.labelColor=st(e.labelColor,16777215),this.labelFontFamily=st(e.labelFontFamily,"sans-serif"),this.labelFontStyle=st(e.labelFontstyle,"normal"),this.labelFontWeight=st(e.labelFontWeight,"bold"),this.labelsdf=st(e.labelsdf,"Chrome"===Ae),this.labelXOffset=st(e.labelXOffset,0),this.labelYOffset=st(e.labelYOffset,0),this.labelZOffset=st(e.labelZOffset,.5),this.labelAttachment=st(e.labelAttachment,"bottom-left"),this.labelBorder=st(e.labelBorder,!1),this.labelBorderColor=st(e.labelBorderColor,"lightgrey"),this.labelBorderWidth=st(e.labelBorderWidth,.15),this.labelBackground=st(e.labelBackground,!1),this.labelBackgroundColor=st(e.labelBackgroundColor,"lightgrey"),this.labelBackgroundMargin=st(e.labelBackgroundMargin,.5),this.labelBackgroundOpacity=st(e.labelBackgroundOpacity,1),this.labelFixedSize=st(e.labelFixedSize,!1),this.lineOpacity=st(e.lineOpacity,1),this.linewidth=st(e.linewidth,2),super.init(e)}update(t){t.position?this.build():super.update(t)}updateData(t,e){const i={};if(t&&!t.labelSize||Object.assign(i,{size:Si(this.n,this.labelSize)}),!t||t.labelColor){const t=new s(this.labelColor);Object.assign(i,{color:Ci(this.n,t.r,t.g,t.b)})}this.textBuffer.setAttributes(i)}setParameters(t,e={},i=!1){return t&&t.labelSize&&(e.labelSize=!0),t&&(t.labelColor||0===t.labelColor)&&(e.labelColor=!0,i=!0),super.setParameters(t,e,i),t&&void 0!==t.opacity&&this.textBuffer.setParameters({opacity:1}),t&&void 0!==t.labelVisible&&this.setVisibility(this.visible),this}setVisibility(t,e){return super.setVisibility(t,!0),this.textBuffer&&this.textBuffer.setVisibility(this.labelVisible&&this.visible),e||this.viewer.requestRender(),this}getLabelBufferParams(t={}){return super.getBufferParams(Object.assign({fontFamily:this.labelFontFamily,fontStyle:this.labelFontStyle,fontWeight:this.labelFontWeight,sdf:this.labelsdf,xOffset:this.labelXOffset,yOffset:this.labelYOffset,zOffset:this.labelZOffset,attachment:this.labelAttachment,showBorder:this.labelBorder,borderColor:this.labelBorderColor,borderWidth:this.labelBorderWidth,showBackground:this.labelBackground,backgroundColor:this.labelBackgroundColor,backgroundMargin:this.labelBackgroundMargin,backgroundOpacity:this.labelBackgroundOpacity,fixedSize:this.labelFixedSize,disablePicking:!0,visible:this.labelVisible},t,{opacity:1}))}getAtomRadius(){return 0}}function Ph(t,e){const i=t.getAtomProxy(),r=new pe,s=e.length;if(0===s)return new Float32Array(0);const n=e[0].length,o=t.getAtomSet(),a=new Float32Array(s*n*3);let c=0;return e.forEach((function(e){let s=!1;for(let l=0;l<n;l++){const n=e[l];if("number"==typeof n&&Number.isInteger(n)){if(!o.get(n)){s=!0;break}i.index=n}else{r.setString(n);const e=t.getAtomIndices(r);if(!e.length){s=!0;break}i.index=e[0]}let h=c+3*l;a[h++]=i.x,a[h++]=i.y,a[h++]=i.z}s||(c+=3*n)})),a.subarray(0,c)}function Ih(t,e,i,r,s){const n=Math.cos(s),o=Math.sin(s);t[0]=e[0]+i[0]*n+r[0]*o,t[1]=e[1]+i[1]*n+r[1]*o,t[2]=e[2]+i[2]*n+r[2]*o}function kh(t,e,i,r,s,n,o){for(let a=0;a<e;a++){for(let s=0;s<i;s++)r[s]=t[s*e+a];Mh(r,s,n,o,i);for(let r=0;r<i;r++)t[r*e+a]=s[r]}for(let a=0;a<i;a++){for(let i=0;i<e;i++)r[i]=t[a*e+i];Mh(r,s,n,o,e);for(let i=0;i<e;i++)t[a*e+i]=Math.sqrt(s[i])}}function Mh(t,e,i,r,s){i[0]=0,r[0]=Number.MIN_SAFE_INTEGER,r[1]=Number.MAX_SAFE_INTEGER;for(let e=1,n=0;e<s;e++){let s=(t[e]+e*e-(t[i[n]]+i[n]*i[n]))/(2*e-2*i[n]);for(;s<=r[n];)n--,s=(t[e]+e*e-(t[i[n]]+i[n]*i[n]))/(2*e-2*i[n]);n++,i[n]=e,r[n]=s,r[n+1]=Number.MAX_SAFE_INTEGER}for(let n=0,o=0;n<s;n++){for(;r[o+1]<n;)o++;e[n]=(n-i[o])*(n-i[o])+t[i[o]]}}Ve.add("shader/SDFFont.vert","uniform float clipNear;\nuniform float clipRadius;\nuniform vec3 clipCenter;\nuniform float xOffset;\nuniform float yOffset;\nuniform float zOffset;\nuniform bool ortho;\nuniform float canvasHeight;\nuniform float pixelRatio;\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || ( !defined( PICKING ) && !defined( NOLIGHT ) )\nvarying vec3 vViewPosition;\n#endif\nvarying vec2 texCoord;\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#if defined( PICKING )\n#include unpack_color\nattribute float primitiveId;\nvarying vec3 vPickingColor;\n#else\n#include color_pars_vertex\n#endif\nattribute vec2 mapping;\nattribute vec2 inputTexCoord;\nattribute float inputSize;\n#include matrix_scale\n#include common\nvoid main(void){\n#if defined( PICKING )\nvPickingColor = unpackColor( primitiveId );\n#else\n#include color_vertex\n#endif\ntexCoord = inputTexCoord;\nfloat scale = matrixScale( modelViewMatrix );\nfloat _xOffset = xOffset * scale;\nfloat _yOffset = yOffset * scale;\nfloat _zOffset = zOffset * scale;\nif( texCoord.x == 10.0 ){\n_zOffset -= 0.001;\n}\nvec4 cameraPos = modelViewMatrix * vec4( position, 1.0 );\n#ifdef FIXED_SIZE\nif ( ortho ) {\nscale /= pixelRatio * (( canvasHeight / 2.0 ) / -cameraPosition.z) * 0.1;\n} else {\nscale /= pixelRatio * (( canvasHeight / 2.0 ) / -cameraPos.z) * 0.1;\n}\n#endif\nvec4 cameraCornerPos = vec4( cameraPos.xyz, 1.0 );\ncameraCornerPos.xy += mapping * inputSize * 0.01 * scale;\ncameraCornerPos.x += _xOffset;\ncameraCornerPos.y += _yOffset;\nif( ortho ){\ncameraCornerPos.xyz += normalize( -cameraPosition ) * _zOffset;\n} else {\ncameraCornerPos.xyz += normalize( -cameraCornerPos.xyz ) * _zOffset;\n}\ngl_Position = projectionMatrix * cameraCornerPos;\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || ( !defined( PICKING ) && !defined( NOLIGHT ) )\nvViewPosition = -cameraCornerPos.xyz;\n#endif\n#if defined( RADIUS_CLIP )\nvClipCenter = -( modelViewMatrix * vec4( clipCenter, 1.0 ) ).xyz;\n#endif\n#include nearclip_vertex\n#include radiusclip_vertex\n}"),Ve.add("shader/SDFFont.frag","uniform sampler2D fontTexture;\nuniform float opacity;\nuniform bool showBorder;\nuniform vec3 borderColor;\nuniform float borderWidth;\nuniform vec3 backgroundColor;\nuniform float backgroundOpacity;\nuniform float clipNear;\nuniform float clipRadius;\nvarying vec3 vViewPosition;\nvarying vec2 texCoord;\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#if defined( PICKING )\nuniform float objectId;\nvarying vec3 vPickingColor;\nconst vec3 vColor = vec3( 0.0 );\n#else\n#include common\n#include color_pars_fragment\n#include fog_pars_fragment\n#endif\nconst float gamma = 2.2 * 1.4142 / 128.0;\nconst float padding = 0.75;\nvoid main(){\n#include nearclip_fragment\n#include radiusclip_fragment\nif( texCoord.x > 1.0 ){\ngl_FragColor = vec4( backgroundColor, backgroundOpacity );\n}else{\nfloat sdf = texture2D( fontTexture, texCoord ).a;\nif( showBorder ) sdf += borderWidth;\nfloat a = smoothstep(padding - gamma, padding + gamma, sdf);\nif( a < 0.2 ) discard;\na *= opacity;\nvec3 outgoingLight = vColor;\nif( showBorder && sdf < ( padding + borderWidth ) ){\noutgoingLight = borderColor;\n}\ngl_FragColor = vec4( outgoingLight, a );\n}\n#if defined( PICKING )\nif( opacity < 0.3 )\ndiscard;\ngl_FragColor = vec4( vPickingColor, objectId );\n#else\n#include premultiplied_alpha_fragment\n#include tonemapping_fragment\n#include encodings_fragment\n#include fog_fragment\n#endif\n}");const Th={};const Bh={font:"sans-serif",size:36,style:"normal",variant:"normal",weight:"normal",outline:3,width:1024,height:1024};class Dh{constructor(t={}){this.gamma=1,this.mapped={},this.scratchW=0,this.scratchH=0,this.currentX=0,this.currentY=0,this.cutoff=.25,this.parameters=nt(t,Bh);const e=this.parameters;this.radius=e.size/8,this.padding=e.size/3;const i=this.lineHeight=e.size+2*e.outline+Math.round(e.size/4),r=this.maxWidth=e.width/4,s=this.canvas=document.createElement("canvas");s.width=r,s.height=i;const n=this.context=this.canvas.getContext("2d");n.font=`${e.style} ${e.variant} ${e.weight} ${e.size}px ${e.font}`,n.fillStyle="black",n.textAlign="left",n.textBaseline="bottom",n.lineJoin="round",this.gridOuter=new Float64Array(i*r),this.gridInner=new Float64Array(i*r),this.f=new Float64Array(Math.max(i,r)),this.d=new Float64Array(Math.max(i,r)),this.z=new Float64Array(Math.max(i,r)+1),this.v=new Int16Array(Math.max(i,r)),this.data=new Uint8Array(e.width*e.height*4),this.canvas2=document.createElement("canvas"),this.canvas2.width=e.width,this.canvas2.height=e.height,this.context2=this.canvas2.getContext("2d"),this.placeholder=this.map(String.fromCharCode(65533));for(let t=32;t<=126;++t)this.map(String.fromCharCode(t));this.map(String.fromCharCode(176)),this.map(String.fromCharCode(8491)),this.texture=new __WEBPACK_IMPORTED_MODULE_0_three__["h" /* CanvasTexture */](this.canvas2),this.texture.flipY=!1,this.texture.needsUpdate=!0}map(t){const e=this.parameters;return void 0===this.mapped[t]&&(this.draw(t),this.currentX+this.scratchW>e.width&&(this.currentX=0,this.currentY+=this.scratchH),this.currentY+this.scratchH>e.height&&console.warn("canvas to small"),this.mapped[t]={x:this.currentX,y:this.currentY,w:this.scratchW,h:this.scratchH},this.context2.drawImage(this.canvas,0,0,this.scratchW,this.scratchH,this.currentX,this.currentY,this.scratchW,this.scratchH),this.currentX+=this.scratchW),this.mapped[t]}get(t){return this.mapped[t]||this.placeholder}draw(t){const e=this.parameters,i=this.lineHeight,r=e.outline,s=this.context,n=this.maxWidth,o=r,a=i-e.outline,c=s.measureText(t),l=Math.min(n,Math.ceil(c.width+2*o+1)),h=l*i;s.clearRect(0,0,l,i),s.fillText(t,o,a);const d=s.getImageData(0,0,l,i),u=d.data;for(let t=0;t<h;t++){const e=d.data[4*t+3]/255;this.gridOuter[t]=1===e?0:0===e?Number.MAX_SAFE_INTEGER:Math.pow(Math.max(0,.5-e),2),this.gridInner[t]=1===e?Number.MAX_SAFE_INTEGER:0===e?0:Math.pow(Math.max(0,e-.5),2)}kh(this.gridOuter,l,i,this.f,this.d,this.v,this.z),kh(this.gridInner,l,i,this.f,this.d,this.v,this.z);for(let t=0;t<h;t++){const e=this.gridOuter[t]-this.gridInner[t];u[4*t+3]=Math.max(0,Math.min(255,Math.round(255-255*(e/this.radius+this.cutoff))))}s.putImageData(d,0,0),this.scratchW=l,this.scratchH=i}}const $h=Object.assign({fontFamily:"sans-serif",fontStyle:"normal",fontWeight:"bold",fontSize:36,xOffset:0,yOffset:0,zOffset:.5,attachment:"bottom-left",showBorder:!1,borderColor:"lightgrey",borderWidth:.15,showBackground:!1,backgroundColor:"lightgrey",backgroundMargin:.5,backgroundOpacity:1,forceTransparent:!0,fixedSize:!1},zo),Oh=Object.assign({fontFamily:{uniform:!0},fontStyle:{uniform:!0},fontWeight:{uniform:!0},fontSize:{uniform:!0},xOffset:{uniform:!0},yOffset:{uniform:!0},zOffset:{uniform:!0},showBorder:{uniform:!0},borderColor:{uniform:!0},borderWidth:{uniform:!0},backgroundColor:{uniform:!0},backgroundOpacity:{uniform:!0},fixedSize:{updateShader:!0}},Vo);function Rh(t,e){const i=t.position.length/3;let r=0;for(let e=0;e<i;++e)r+=t.text[e].length;return e.showBackground&&(r+=i),r}class Eh extends zc{constructor(t,e={}){super({position:new Float32Array(3*Rh(t,e)),color:new Float32Array(3*Rh(t,e)),picking:new eo},e),this.parameterTypes=Oh,this.alwaysTransparent=!0,this.hasWireframe=!1,this.isText=!0,this.vertexShader="SDFFont.vert",this.fragmentShader="SDFFont.frag",this.text=t.text,this.positionCount=t.position.length/3,this.addUniforms({fontTexture:{value:null},xOffset:{value:this.parameters.xOffset},yOffset:{value:this.parameters.yOffset},zOffset:{value:this.parameters.zOffset},ortho:{value:!1},showBorder:{value:this.parameters.showBorder},borderColor:{value:new s(this.parameters.borderColor)},borderWidth:{value:this.parameters.borderWidth},backgroundColor:{value:new s(this.parameters.backgroundColor)},backgroundOpacity:{value:this.parameters.backgroundOpacity},canvasHeight:{value:1},pixelRatio:{value:1}}),this.addAttributes({inputTexCoord:{type:"v2",value:null},inputSize:{type:"f",value:null}}),this.setAttributes(t),this.makeTexture(),this.makeMapping()}get defaultParameters(){return $h}makeMaterial(){super.makeMaterial();const t=this.texture,e=this.material;e.transparent=!0,e.extensions.derivatives=!0,e.lights=!1,e.uniforms.fontTexture.value=t,e.needsUpdate=!0;const i=this.wireframeMaterial;i.transparent=!0,i.extensions.derivatives=!0,i.lights=!1,i.uniforms.fontTexture.value=t,i.needsUpdate=!0;const r=this.pickingMaterial;r.extensions.derivatives=!0,r.lights=!1,r.uniforms.fontTexture.value=t,r.needsUpdate=!0}setAttributes(t={}){let e,i,r,s,n,o;const a=this.text,c=this.geometry.attributes;t.position&&(e=t.position,s=c.position.array,c.position.needsUpdate=!0),t.size&&(i=t.size,n=c.inputSize.array,c.inputSize.needsUpdate=!0),t.color&&(r=t.color,o=c.color.array,c.color.needsUpdate=!0);const l=this.positionCount;let h,d,u,m,p,f=0;for(let t=0;t<l;++t)for(d=3*t,u=a[t],p=u.length,this.parameters.showBackground&&(p+=1),m=0;m<p;++m,++f)for(let a=0;a<4;a++)h=4*f*3+3*a,e&&(s[h]=e[d],s[h+1]=e[d+1],s[h+2]=e[d+2]),i&&(n[4*f+a]=i[t]),r&&(o[h]=r[d],o[h+1]=r[d+1],o[h+2]=r[d+2])}makeTexture(){this.textAtlas=function(t){const e=JSON.stringify(t);return void 0===Th[e]&&(Th[e]=new Dh(t)),Th[e]}({font:this.parameters.fontFamily,style:this.parameters.fontStyle,weight:this.parameters.fontWeight,size:this.parameters.fontSize}),this.texture=this.textAtlas.texture}makeMapping(){const t=this.textAtlas,e=this.text,i=this.parameters.attachment,r=t.lineHeight*this.parameters.backgroundMargin*.1-10,s=this.geometry.attributes,n=s.inputTexCoord.array,o=s.mapping.array,a=this.positionCount;let c,l,h,d,u,m,p,f,g=0;for(let s=0;s<a;++s){for(h=e[s],d=0,m=h.length,u=0;u<m;++u)c=t.get(h[u]),d+=c.w-2*t.parameters.outline;for(f=i.startsWith("top")?t.lineHeight/1.25:i.startsWith("middle")?t.lineHeight/2.5:0,p=i.endsWith("right")?d:i.endsWith("center")?d/2:0,p+=t.parameters.outline,f+=t.parameters.outline,this.parameters.showBackground&&(l=2*g*4,o[l+0]=-t.lineHeight/6-p-r,o[l+1]=t.lineHeight-f+r,o[l+2]=-t.lineHeight/6-p-r,o[l+3]=0-f-r,o[l+4]=d+t.lineHeight/6-p+2*t.parameters.outline+r,o[l+5]=t.lineHeight-f+r,o[l+6]=d+t.lineHeight/6-p+2*t.parameters.outline+r,o[l+7]=0-f-r,n[l+0]=10,n[l+2]=10,n[l+4]=10,n[l+6]=10,g+=1),d=0,u=0;u<m;++u,++g){c=t.get(h[u]),l=2*g*4,o[l+0]=d-p,o[l+1]=c.h-f,o[l+2]=d-p,o[l+3]=0-f,o[l+4]=d+c.w-p,o[l+5]=c.h-f,o[l+6]=d+c.w-p,o[l+7]=0-f;const e=t.parameters.width,i=t.parameters.height,r=[c.x/e,c.y/i,c.x/e,(c.y+c.h)/i,(c.x+c.w)/e,c.y/i,(c.x+c.w)/e,(c.y+c.h)/i];n.set(r,l),d+=c.w-2*t.parameters.outline}}s.inputTexCoord.needsUpdate=!0,s.mapping.needsUpdate=!0}getDefines(t){const e=super.getDefines(t);return this.parameters.fixedSize&&(e.FIXED_SIZE=1),e}setUniforms(t){!t||void 0===t.fontFamily&&void 0===t.fontStyle&&void 0===t.fontWeight&&void 0===t.fontSize||(this.makeTexture(),this.makeMapping(),this.texture.needsUpdate=!0,t.fontTexture=this.texture),super.setUniforms(t)}}je.add("text",Eh),Ve.add("shader/WideLine.vert","\nuniform float clipNear;\nuniform vec3 clipCenter;\nuniform float linewidth;\nuniform vec2 resolution;\nuniform mat4 projectionMatrixInverse;\nattribute vec2 mapping;\nattribute vec3 position1;\nattribute vec3 position2;\n#ifdef PICKING\n#include unpack_color\nattribute float primitiveId;\nvarying vec3 vPickingColor;\n#else\nattribute vec3 color2;\nvarying vec3 vColor;\nvarying vec3 vColor2;\nvarying float flag;\nvarying vec3 vViewPosition;\n#endif\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\nvoid trimSegment( const in vec4 start, inout vec4 end ) {\nfloat a = projectionMatrix[ 2 ][ 2 ]; float b = projectionMatrix[ 3 ][ 2 ]; float nearEstimate = - 0.5 * b / a;\nfloat alpha = ( nearEstimate - start.z ) / ( end.z - start.z );\nend.xyz = mix( start.xyz, end.xyz, alpha );\n}\nvoid main() {\nfloat aspect = resolution.x / resolution.y;\n#ifdef PICKING\nvPickingColor = unpackColor( primitiveId );\n#else\nflag = mapping.y;\nvColor = color;\nvColor2 = color2;\n#endif\nvec4 start = modelViewMatrix * vec4( position1, 1.0 );\nvec4 end = modelViewMatrix * vec4( position2, 1.0 );\nbool perspective = ( projectionMatrix[ 2 ][ 3 ] == -1.0 ); if ( perspective ) {\nif ( start.z < 0.0 && end.z >= 0.0 ) {\ntrimSegment( start, end );\n} else if ( end.z < 0.0 && start.z >= 0.0 ) {\ntrimSegment( end, start );\n}\n}\nvec4 clipStart = projectionMatrix * start;\nvec4 clipEnd = projectionMatrix * end;\nvec2 ndcStart = clipStart.xy / clipStart.w;\nvec2 ndcEnd = clipEnd.xy / clipEnd.w;\nvec2 dir = ndcEnd - ndcStart;\ndir.x *= aspect;\ndir = normalize( dir );\nvec2 offset = vec2( dir.y, - dir.x );\ndir.x /= aspect;\noffset.x /= aspect;\nif ( mapping.x < 0.0 ) offset *= - 1.0;\noffset *= linewidth;\noffset /= resolution.y;\nvec4 clip = ( mapping.y < 0.5 ) ? clipStart : clipEnd;\noffset *= clip.w;\nclip.xy += offset;\ngl_Position = clip;\n#ifndef PICKING\nvViewPosition = ( projectionMatrixInverse * clip ).xyz;\n#endif\n#if defined( RADIUS_CLIP )\nvClipCenter = -( modelViewMatrix * vec4( clipCenter, 1.0 ) ).xyz;\n#endif\n#include nearclip_vertex\n}"),Ve.add("shader/WideLine.frag","uniform vec3 diffuse;\nuniform float opacity;\nuniform float clipNear;\nuniform float clipRadius;\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\n#ifdef PICKING\nuniform float objectId;\nvarying vec3 vPickingColor;\n#else\n#include common\n#include fog_pars_fragment\nvarying vec3 vViewPosition;\nvarying vec3 vColor;\nvarying vec3 vColor2;\nvarying float flag;\n#endif\nvoid main() {\n#include nearclip_fragment\n#include radiusclip_fragment\n#if defined( PICKING )\nif( opacity < 0.3 )\ndiscard;\ngl_FragColor = vec4( vPickingColor, objectId );\n#else\nvec3 outgoingLight = vec3( 0.0 );\nvec4 diffuseColor = vec4( diffuse, 1.0 );\nif ( flag < 0.0 ) {\ndiffuseColor.rgb *= vColor;\n} else {\ndiffuseColor.rgb *= vColor2;\n}\n#include alphatest_fragment\noutgoingLight = diffuseColor.rgb;\ngl_FragColor = vec4( outgoingLight, diffuseColor.a * opacity );\n#include premultiplied_alpha_fragment\n#include tonemapping_fragment\n#include encodings_fragment\n#include fog_fragment\n#endif\n}");const Fh=Object.assign({linewidth:2},zo),Lh=Object.assign({linewidth:{uniform:!0}},Vo);class Nh extends zc{constructor(e,r={}){super(e,r),this.parameterTypes=Lh,this.vertexShader="WideLine.vert",this.fragmentShader="WideLine.frag",!e.color2&&e.color&&(e.color2=e.color),this.addUniforms({linewidth:{value:this.parameters.linewidth},resolution:{value:new t},projectionMatrixInverse:{value:new i}}),this.addAttributes({position1:{type:"v3",value:null},position2:{type:"v3",value:null},color2:{type:"c",value:null}}),this.setAttributes(e),this.makeMapping()}get defaultParameters(){return Fh}setParameters(t){super.setParameters(t)}}je.add("wideline",Nh);class zh extends Ch{constructor(t,e,i){super(t,e,i),this.type="angle",this.parameters=Object.assign({atomTriple:{type:"hidden",rebuild:!0},vectorVisible:{type:"boolean",default:!0},arcVisible:{type:"boolean",default:!0},sectorVisible:{type:"boolean",default:!0}},this.parameters),this.init(i)}init(t){const e=t||{};e.side=st(e.side,"double"),e.opacity=st(e.opacity,.5),this.atomTriple=st(e.atomTriple,[]),this.arcVisible=st(e.arcVisible,!0),this.sectorVisible=st(e.sectorVisible,!0),this.vectorVisible=st(e.vectorVisible,!0),super.init(e)}createData(t){if(!t.atomCount||!this.atomTriple.length)return;const e=function(t,e){return function(t){const e=[],i=t.length/9;for(let r=0;r<i;r++){let i=!0;for(let e=r;e<r+3;e+=3)t[e]===t[e+3]&&t[e+1]===t[e+4]&&t[e+2]===t[e+5]&&(i=!1);i&&e.push(r)}const r=new Float32Array(9*e.length);let s=0;return e.forEach((function(e){Mi(t,r,9*e,9*s,9),s++})),r}(Ph(t,e))}(t,this.atomTriple),i=function(t,e={}){const i=st(e.angleStep,Math.PI/90),r=t.length/9,s=new Float32Array(r),n=new Float32Array(3*r),o=new Array(r),a=new Float32Array(6*r),c=new Float32Array(6*r),l=new Array(r),h=new Array(r),d=new Array(r);let u=0;const m=Yr(),p=Yr(),f=Yr(),g=Yr(),y=Yr(),b=Yr(),x=Yr(),v=Yr(),w=Yr();for(var A=0;A<r;A++){let e=9*A;ts(m,t,e),ts(p,t,e+3),ts(f,t,e+6);let r=6*A;es(m,a,r),es(p,c,r),es(p,a,r+3),es(f,c,r+3),Qr(g,m,p),Qr(y,f,p),os(g,g),os(y,y),Kr(b,g,y);const _=rs(b),S=Zr(g,y),C=s[A]=Math.atan2(_,S);o[A]=(vi*C).toFixed(1)+String.fromCharCode(176),0===rs(b)&&(b[0]=1,b[1]=0,b[2]=0),Kr(x,b,g),os(x,x),Ih(v,p,g,x,C/2),es(v,n,3*A);const P=Math.ceil(C/i),I=new Float32Array(9*P);d[A]=I;const k=new Float32Array(3*P),M=new Float32Array(3*P);l[A]=k,h[A]=M,Jr(w,p,g);const T=function(t,e){const i=9*e,r=3*e;es(p,I,i),es(w,I,i+3),es(w,k,r),Ih(w,p,g,x,t),es(w,I,i+6),es(w,M,r)};let B=0;for(let t=i;t<C;t+=i)T(t,B),B++;T(C,B),u+=P}const _=3*u,S=9*u,C=new Float32Array(_),P=new Float32Array(_),I=new Float32Array(S);let k=0,M=0;for(let t=0;t<r;t++){const e=l[t],i=h[t];Mi(e,C,0,M,e.length),Mi(i,P,0,M,i.length),M+=e.length;const r=d[t];Mi(r,I,0,k,r.length),k+=r.length}return{labelPosition:n,labelText:o,vectorPosition1:a,vectorPosition2:c,arcPosition1:C,arcPosition2:P,sectorPosition:I}}(e),r=this.n=i.labelPosition.length/3,n=new s(this.labelColor);this.textBuffer=new Eh({position:i.labelPosition,size:Si(r,this.labelSize),color:Ci(r,n.r,n.g,n.b),text:i.labelText},this.getLabelBufferParams());const o=new s(this.colorValue);return this.vectorBuffer=new Nh(fs({position1:i.vectorPosition1,position2:i.vectorPosition2,color:Ci(2*r,o.r,o.g,o.b),color2:Ci(2*r,o.r,o.g,o.b)}),this.getBufferParams({linewidth:this.linewidth,visible:this.vectorVisible,opacity:this.lineOpacity})),this.arcLength=i.arcPosition1.length/3,this.arcBuffer=new Nh(fs({position1:i.arcPosition1,position2:i.arcPosition2,color:Ci(this.arcLength,o.r,o.g,o.b),color2:Ci(this.arcLength,o.r,o.g,o.b)}),this.getBufferParams({linewidth:this.linewidth,visible:this.arcVisible,opacity:this.lineOpacity})),this.sectorLength=i.sectorPosition.length/3,this.sectorBuffer=new Uo({position:i.sectorPosition,color:Ci(this.sectorLength,o.r,o.g,o.b)},this.getBufferParams({visible:this.sectorVisible})),{bufferList:[this.textBuffer,this.vectorBuffer,this.arcBuffer,this.sectorBuffer]}}updateData(t,e){super.updateData(t,e);const i={},r={},n={};if(t.color){const t=new s(this.colorValue);Object.assign(i,{color:Ci(2*this.n,t.r,t.g,t.b),color2:Ci(2*this.n,t.r,t.g,t.b)}),Object.assign(r,{color:Ci(this.arcLength,t.r,t.g,t.b),color2:Ci(this.arcLength,t.r,t.g,t.b)}),Object.assign(n,{color:Ci(this.sectorLength,t.r,t.g,t.b)})}this.vectorBuffer.setAttributes(i),this.arcBuffer.setAttributes(r),this.sectorBuffer.setAttributes(n)}setParameters(t){return super.setParameters(t,{},!1),!t||void 0===t.vectorVisible&&void 0===t.arcVisible&&void 0===t.sectorVisible||this.setVisibility(this.visible),t&&t.lineOpacity&&(this.vectorBuffer.setParameters({opacity:t.lineOpacity}),this.arcBuffer.setParameters({opacity:t.lineOpacity})),t&&void 0!==t.opacity&&(this.vectorBuffer.setParameters({opacity:this.lineOpacity}),this.arcBuffer.setParameters({opacity:this.lineOpacity})),t&&t.linewidth&&(this.vectorBuffer.setParameters({linewidth:t.linewidth}),this.arcBuffer.setParameters({linewidth:t.linewidth})),this}setVisibility(t,e){return super.setVisibility(t,!0),this.vectorBuffer&&this.vectorBuffer.setVisibility(this.vectorVisible&&this.visible),this.arcBuffer&&this.arcBuffer.setVisibility(this.arcVisible&&this.visible),this.sectorBuffer&&this.sectorBuffer.setVisibility(this.sectorVisible&&this.visible),e||this.viewer.requestRender(),this}}Ne.add("angle",zh);const Vh=new e,Gh=new e,Uh=new e,jh=new e(0,1,0),Hh=Object.assign({radialSegments:1,openEnded:!0},zo);function Wh(t={}){const e=st(t.radialSegments,10),r=st(t.openEnded,!0),s=(new i).makeRotationX(Math.PI/2),n=new __WEBPACK_IMPORTED_MODULE_0_three__["k" /* CylinderBufferGeometry */](1,1,1,e,1,r);return n.applyMatrix4(s),n}class qh extends $c{constructor(t,e={}){super(function(t,e={}){const i=Wh(e),r=t.position1.length,s=i.attributes.position.array.length/3,n=r/3,o=new Float32Array(2*n*s);return Ii(n,s,0,o),Ii(n,s,n*s,o),{position:new Float32Array(2*r),color:new Float32Array(2*r),primitiveId:o,picking:t.picking}}(t,e),e,Wh(e)),this.updateNormals=!0;const i=t.position1.length,r=t.radius.length;this.__center=new Float32Array(i),this._position=new Float32Array(2*i),this._color=new Float32Array(2*i),this._from=new Float32Array(2*i),this._to=new Float32Array(2*i),this._radius=new Float32Array(2*r),this.setAttributes(t,!0)}get defaultParameters(){return Hh}applyPositionTransform(t,e,i){Gh.fromArray(this._from,i),Uh.fromArray(this._to,i),t.lookAt(Gh,Uh,jh);const r=this._radius[e];Vh.set(r,r,Gh.distanceTo(Uh)),t.scale(Vh)}setAttributes(t={},e){const i={};t.position1&&t.position2&&(Ai(t.position1,t.position2,this.__center),Ai(t.position1,this.__center,this._position),Ai(this.__center,t.position2,this._position,t.position1.length),this._from.set(t.position1),this._from.set(this.__center,t.position1.length),this._to.set(this.__center),this._to.set(t.position2,this.__center.length),i.position=this._position),t.color&&t.color2&&(this._color.set(t.color),this._color.set(t.color2,t.color.length),i.color=this._color),t.radius&&(this._radius.set(t.radius),this._radius.set(t.radius,t.radius.length),i.radius=this._radius),super.setAttributes(i,e)}}Ve.add("shader/CylinderImpostor.vert","\nattribute vec3 mapping;\nattribute vec3 position1;\nattribute vec3 position2;\nattribute float radius;\nvarying vec3 axis;varying vec4 base_radius;varying vec4 end_b;varying vec3 U;varying vec3 V;\nvarying vec4 w;\n#ifdef PICKING\n#include unpack_color\nattribute float primitiveId;\nvarying vec3 vPickingColor;\n#else\nattribute vec3 color2;\nvarying vec3 vColor1;\nvarying vec3 vColor2;\n#endif\nuniform mat4 modelViewMatrixInverse;\nuniform float ortho;\n#include matrix_scale\nvoid main(){\n#ifdef PICKING\nvPickingColor = unpackColor( primitiveId );\n#else\nvColor1 = color;\nvColor2 = color2;\n#endif\nbase_radius.w = radius * matrixScale( modelViewMatrix );\nvec3 center = position;\nvec3 dir = normalize( position2 - position1 );\nfloat ext = length( position2 - position1 ) / 2.0;\nvec3 cam_dir;\nif( ortho == 0.0 ){\ncam_dir = ( modelViewMatrixInverse * vec4( 0, 0, 0, 1 ) ).xyz - center;\n}else{\ncam_dir = ( modelViewMatrixInverse * vec4( 0, 0, 1, 0 ) ).xyz;\n}\ncam_dir = normalize( cam_dir );\nvec3 ldir;\nfloat b = dot( cam_dir, dir );\nend_b.w = b;\nif( b < 0.0 )\nldir = -ext * dir;\nelse\nldir = ext * dir;\nvec3 left = radius * normalize( cross( cam_dir, ldir ) );\nvec3 up = radius * normalize( cross( left, ldir ) );\naxis = normalize( normalMatrix * ldir );\nU = normalize( normalMatrix * up );\nV = normalize( normalMatrix * left );\nvec4 base4 = modelViewMatrix * vec4( center - ldir, 1.0 );\nbase_radius.xyz = base4.xyz / base4.w;\nvec4 end4 = modelViewMatrix * vec4( center + ldir, 1.0 );\nend_b.xyz = end4.xyz / end4.w;\nw = modelViewMatrix * vec4(\ncenter + mapping.x*ldir + mapping.y*left + mapping.z*up, 1.0\n);\ngl_Position = projectionMatrix * w;\ngl_Position.z = 0.99;\n}"),Ve.add("shader/CylinderImpostor.frag","#define STANDARD\n#define IMPOSTOR\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 interiorColor;\nuniform float interiorDarkening;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\nuniform float clipNear;\nuniform mat4 projectionMatrix;\nuniform float ortho;\nvarying vec3 axis;\nvarying vec4 base_radius;\nvarying vec4 end_b;\nvarying vec3 U;\nvarying vec3 V;\nvarying vec4 w;\n#ifdef PICKING\nuniform float objectId;\nvarying vec3 vPickingColor;\n#else\nvarying vec3 vColor1;\nvarying vec3 vColor2;\n#include common\n#include fog_pars_fragment\n#include bsdfs\n#include lights_pars_begin\n#include lights_physical_pars_fragment\n#endif\nbool interior = false;\nfloat distSq3( vec3 v3a, vec3 v3b ){\nreturn (\n( v3a.x - v3b.x ) * ( v3a.x - v3b.x ) +\n( v3a.y - v3b.y ) * ( v3a.y - v3b.y ) +\n( v3a.z - v3b.z ) * ( v3a.z - v3b.z )\n);\n}\nfloat calcDepth( in vec3 cameraPos ){\nvec2 clipZW = cameraPos.z * projectionMatrix[2].zw + projectionMatrix[3].zw;\nreturn 0.5 + 0.5 * clipZW.x / clipZW.y;\n}\nfloat calcClip( vec3 cameraPos ){\nreturn dot( vec4( cameraPos, 1.0 ), vec4( 0.0, 0.0, 1.0, clipNear - 0.5 ) );\n}\nvoid main(){\nvec3 ray_target = w.xyz / w.w;\nvec3 base = base_radius.xyz; float vRadius = base_radius.w; vec3 end = end_b.xyz; float b = end_b.w;\nvec3 ray_origin = vec3(0.0); vec3 ortho_ray_direction = vec3(0.0, 0.0, 1.0); vec3 persp_ray_direction = normalize(ray_origin - ray_target);\nvec3 ray_direction = mix(persp_ray_direction, ortho_ray_direction, ortho);\n\nmat3 basis = mat3( U, V, axis );\nvec3 diff = ray_target - 0.5 * (base + end);\n\nvec3 P = diff * basis;\nfloat dz = dot( axis, ray_direction );\nfloat radius2 = vRadius*vRadius;\nvec3 D = vec3(dot(U, ray_direction),\ndot(V, ray_direction),\ndz);\nfloat a0 = P.x*P.x + P.y*P.y - radius2;\nfloat a1 = P.x*D.x + P.y*D.y;\nfloat a2 = D.x*D.x + D.y*D.y;\nfloat d = a1*a1 - a0*a2;\nif (d < 0.0) {\ndiscard;\n}\nfloat dist = (-a1 + sqrt(d)) / a2;\nvec3 surface_point = ray_target + dist * ray_direction;\nvec3 base_to_surface = surface_point - base;\nvec3 _normal = normalize( base_to_surface - axis * dot(base_to_surface, axis) );\nfloat base_cap_test = dot( base_to_surface, axis );\nfloat end_cap_test = dot((surface_point - end), axis);\n#ifndef CAP\nvec3 new_point2 = ray_target + ( (-a1 - sqrt(d)) / a2 ) * ray_direction;\nvec3 tmp_point2 = new_point2 - base;\n#endif\nif (base_cap_test < 0.0) {\nfloat dNV;\nfloat near;\nvec3 front_point;\nif ( ortho == 1.0 ) {\nfront_point = ray_target;\n} else {\ndNV = dot(-axis, ray_direction);\nnear = dot(-axis, (base)) / dNV;\nfront_point = ray_direction * near + ray_origin;\n}\nif (dot(front_point - base, front_point-base) > radius2) {\ndiscard;\n}\n#ifdef CAP\nsurface_point = front_point;\n_normal = axis;\n#else\nsurface_point = ray_target + ( (-a1 - sqrt(d)) / a2 ) * ray_direction;\ndNV = dot(-axis, ray_direction);\nnear = dot(axis, end) / dNV;\nnew_point2 = ray_direction * near + ray_origin;\nif (dot(new_point2 - end, new_point2-base) < radius2) {\ndiscard;\n}\ninterior = true;\n#endif\n}\nif( end_cap_test > 0.0 )\n{\nfloat dNV;\nfloat near;\nvec3 end_point;\nif ( ortho == 1.0 ) {\nend_point = ray_target;\n} else {\ndNV = dot(axis, ray_direction);\nif (dNV < 0.0) {\ndiscard;\n}\nnear = dot(axis, end) / dNV;\nend_point = ray_direction * near + ray_origin;\n}\n\nif( dot(end_point - end, end_point-base) > radius2 ) {\ndiscard;\n}\n#ifdef CAP\nsurface_point = end_point;\n_normal = axis;\n#else\nsurface_point = ray_target + ( (-a1 - sqrt(d)) / a2 ) * ray_direction;\ndNV = dot(-axis, ray_direction);\nnear = dot(-axis, (base)) / dNV;\nnew_point2 = ray_direction * near + ray_origin;\nif (dot(new_point2 - base, new_point2-base) < radius2) {\ndiscard;\n}\ninterior = true;\n#endif\n}\ngl_FragDepthEXT = calcDepth( surface_point );\n\n#ifdef NEAR_CLIP\nif( calcClip( surface_point ) > 0.0 ){\ndist = (-a1 - sqrt(d)) / a2;\nsurface_point = ray_target + dist * ray_direction;\nif( calcClip( surface_point ) > 0.0 ) {\ndiscard;\n}\ninterior = true;\ngl_FragDepthEXT = calcDepth( surface_point );\nif( gl_FragDepthEXT >= 0.0 ){\ngl_FragDepthEXT = max( 0.0, calcDepth( vec3( - ( clipNear - 0.5 ) ) ) + ( 0.0000001 / vRadius ) );\n}\n}else if( gl_FragDepthEXT <= 0.0 ){\ndist = (-a1 - sqrt(d)) / a2;\nsurface_point = ray_target + dist * ray_direction;\ninterior = true;\ngl_FragDepthEXT = calcDepth( surface_point );\nif( gl_FragDepthEXT >= 0.0 ){\ngl_FragDepthEXT = 0.0 + ( 0.0000001 / vRadius );\n}\n}\n#else\nif( gl_FragDepthEXT <= 0.0 ){\ndist = (-a1 - sqrt(d)) / a2;\nsurface_point = ray_target + dist * ray_direction;\ninterior = true;\ngl_FragDepthEXT = calcDepth( surface_point );\nif( gl_FragDepthEXT >= 0.0 ){\ngl_FragDepthEXT = 0.0 + ( 0.0000001 / vRadius );\n}\n}\n#endif\nif (gl_FragDepthEXT < 0.0) {\ndiscard;\n}\nif (gl_FragDepthEXT > 1.0) {\ndiscard;\n}\n#ifdef PICKING\nif( opacity < 0.3 )\ndiscard;\ngl_FragColor = vec4( vPickingColor, objectId );\n#else\nvec3 vViewPosition = -surface_point;\nvec3 vNormal = _normal;\nvec3 vColor;\nif( distSq3( surface_point, end ) < distSq3( surface_point, base ) ){\nif( b < 0.0 ){\nvColor = vColor1;\n}else{\nvColor = vColor2;\n}\n}else{\nif( b > 0.0 ){\nvColor = vColor1;\n}else{\nvColor = vColor2;\n}\n}\nvec4 diffuseColor = vec4( diffuse, opacity );\nReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\nvec3 totalEmissiveLight = emissive;\n#include color_fragment\n#include roughnessmap_fragment\n#include metalnessmap_fragment\nvec3 normal = normalize( vNormal );\nvec3 geometryNormal = normal;\n#include lights_physical_fragment\n#include lights_fragment_begin\n#include lights_fragment_end\nvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;\nif( interior ){\n#ifdef USE_INTERIOR_COLOR\noutgoingLight.xyz = interiorColor;\n#else\n#ifdef DIFFUSE_INTERIOR\noutgoingLight.xyz = vColor;\n#endif\n#endif\noutgoingLight.xyz *= 1.0 - interiorDarkening;\n}\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );\n#include premultiplied_alpha_fragment\n#include tonemapping_fragment\n#include encodings_fragment\n#include fog_fragment\n#endif\n}");const Xh=new Float32Array([-1,1,-1,-1,-1,-1,1,1,-1,1,1,1,1,-1,-1,1,-1,1]),Yh=new Uint16Array([0,1,2,1,4,2,2,4,3,4,5,3]);class Kh extends Fc{constructor(t,e={}){super("v3",t,e)}get mapping(){return Xh}get mappingIndices(){return Yh}get mappingIndicesSize(){return 12}get mappingSize(){return 6}get mappingItemSize(){return 3}}const Zh=Object.assign({openEnded:!1},zo),Qh=Object.assign({openEnded:{updateShader:!0}},Vo);class Jh extends Kh{constructor(t,e={}){super(t,e),this.parameterTypes=Qh,this.isImpostor=!0,this.vertexShader="CylinderImpostor.vert",this.fragmentShader="CylinderImpostor.frag",this.addUniforms({modelViewMatrixInverse:{value:new i},ortho:{value:0}}),this.addAttributes({position1:{type:"v3",value:null},position2:{type:"v3",value:null},color2:{type:"c",value:null},radius:{type:"f",value:null}}),this.setAttributes(t),this.makeMapping()}get defaultParameters(){return Zh}getDefines(t){const e=Kh.prototype.getDefines.call(this,t);return this.parameters.openEnded||(e.CAP=1),e}}Object.assign({disableImpostor:!1},Hh,Zh);const td=class{constructor(t,e={}){return!t.color2&&t.color&&(t.color2=t.color),!Ie||e&&e.disableImpostor?new qh(t,e):new Jh(t,e)}};je.add("cylinder",td);class ed extends Sh{constructor(t,e,i){super(t,e,i),this.type="axes",this.parameters=Object.assign({radiusSize:{type:"number",precision:3,max:10,min:.001},sphereDetail:!0,radialSegments:!0,disableImpostor:!0,showAxes:{type:"boolean",rebuild:!0},showBox:{type:"boolean",rebuild:!0}},this.parameters,{assembly:null}),this.init(i)}init(t){const e=t||{};e.radiusSize=st(e.radiusSize,.5),e.colorValue=st(e.colorValue,"lightgreen"),e.useInteriorColor=st(e.useInteriorColor,!0),this.showAxes=st(e.showAxes,!0),this.showBox=st(e.showBox,!1),super.init(e)}getPrincipalAxes(){let t;const e=this.getAssembly();return e&&(t=e.partList[0].getSelection()),this.structureView.getPrincipalAxes(t)}getAxesData(t){const i=this.getPrincipalAxes(),r=new s(this.colorValue);let n=0,o=0;this.showAxes&&(n+=6,o+=3),this.showBox&&(n+=8,o+=12);const a=new Float32Array(3*n),c=Ci(n,r.r,r.g,r.b),l=Si(n,this.radiusSize),h=new Float32Array(3*o),d=new Float32Array(3*o),u=Ci(o,r.r,r.g,r.b),m=Si(o,this.radiusSize);let p=0;if(this.showAxes){const t=function(t,e){t.toArray(a,2*p),e.toArray(a,2*p+3),t.toArray(h,p),e.toArray(d,p),p+=3};t(i.begA,i.endA),t(i.begB,i.endB),t(i.begC,i.endC)}if(this.showBox){const r=new e,{d1a:s,d2a:n,d3a:o,d1b:c,d2b:l,d3b:u}=i.getProjectedScaleForAtoms(t);let m=2*p;const f=function(t,e,s){r.copy(i.center).addScaledVector(i.normVecA,t).addScaledVector(i.normVecB,e).addScaledVector(i.normVecC,s),r.toArray(a,m),m+=3};f(s,n,o),f(s,n,u),f(s,l,u),f(s,l,o),f(c,l,u),f(c,l,o),f(c,n,o),f(c,n,u);let g=p;const y=function(t,e){r.fromArray(a,2*p+3*t).toArray(h,g),r.fromArray(a,2*p+3*e).toArray(d,g),g+=3};y(0,1),y(0,3),y(0,6),y(1,2),y(1,7),y(2,3),y(2,4),y(3,5),y(4,5),y(4,7),y(5,6),y(6,7)}const f=new Kn(i);return{vertex:{position:a,color:c,radius:l,picking:f},edge:{position1:h,position2:d,color:u,color2:u,radius:m,picking:f}}}create(){const t=this.getAxesData(this.structureView);this.sphereBuffer=new Gc(t.vertex,this.getBufferParams({sphereDetail:this.sphereDetail,disableImpostor:this.disableImpostor,dullInterior:!0})),this.cylinderBuffer=new td(t.edge,this.getBufferParams({openEnded:!0,radialSegments:this.radialSegments,disableImpostor:this.disableImpostor,dullInterior:!0})),this.dataList.push({sview:this.structureView,bufferList:[this.sphereBuffer,this.cylinderBuffer]})}createData(t){}updateData(t,e){const i=this.getAxesData(e.sview),r={},s={};t&&!t.position||(Object.assign(r,{position:i.vertex.position}),Object.assign(s,{position1:i.edge.position1,position2:i.edge.position2})),t&&!t.color||(Object.assign(r,{color:i.vertex.color}),Object.assign(s,{color:i.edge.color,color2:i.edge.color})),t&&!t.radius||(Object.assign(r,{radius:i.vertex.radius}),Object.assign(s,{radius:i.edge.radius})),this.sphereBuffer.setAttributes(r),this.cylinderBuffer.setAttributes(s)}}Ne.add("axes",ed);class id extends Sh{constructor(t,e,i){super(t,e,i),this.type="ball+stick",this.parameters=Object.assign({sphereDetail:!0,radialSegments:!0,openEnded:!0,disableImpostor:!0,aspectRatio:{type:"number",precision:1,max:10,min:1},lineOnly:{type:"boolean",rebuild:!0},cylinderOnly:{type:"boolean",rebuild:!0},multipleBond:{type:"select",rebuild:!0,options:{off:"off",symmetric:"symmetric",offset:"offset"}},bondScale:{type:"number",precision:2,max:1,min:.01},bondSpacing:{type:"number",precision:2,max:2,min:.5},linewidth:{type:"integer",max:50,min:1,buffer:!0}},this.parameters),this.init(i)}init(t){var e=t||{};e.radiusType=st(e.radiusType,"size"),e.radiusSize=st(e.radiusSize,.15),e.useInteriorColor=st(e.useInteriorColor,!0),this.aspectRatio=st(e.aspectRatio,2),this.lineOnly=st(e.lineOnly,!1),this.cylinderOnly=st(e.cylinderOnly,!1),this.multipleBond=st(e.multipleBond,"off"),this.bondSpacing=st(e.bondSpacing,1),this.bondScale=st(e.bondScale,.4),this.linewidth=st(e.linewidth,2),super.init(e)}getAtomRadius(t){return this.aspectRatio*super.getAtomRadius(t)}getAtomParams(t,e){var i=super.getAtomParams(t,e);return i.radiusParams.scale*=this.aspectRatio,i}getAtomData(t,e,i){return t.getAtomData(this.getAtomParams(e,i))}getBondParams(t,e){return e=Object.assign({multipleBond:this.multipleBond,bondSpacing:this.bondSpacing,bondScale:this.bondScale},e),super.getBondParams(t,e)}getBondData(t,e,i){return t.getBondData(this.getBondParams(e,i))}createData(t){const e=[];if(this.lineOnly)this.lineBuffer=new Nh(this.getBondData(t,{position:!0,color:!0,picking:!0}),this.getBufferParams({linewidth:this.linewidth})),e.push(this.lineBuffer);else{const i=new td(this.getBondData(t),this.getBufferParams({openEnded:this.openEnded,radialSegments:this.radialSegments,disableImpostor:this.disableImpostor,dullInterior:!0}));if(e.push(i),!this.cylinderOnly){const i=new Gc(this.getAtomData(t),this.getBufferParams({sphereDetail:this.sphereDetail,disableImpostor:this.disableImpostor,dullInterior:!0}));e.push(i)}}return{bufferList:e}}updateData(t,e){"off"!==this.multipleBond&&t&&t.radius&&(t.position=!0);const i=this.getBondData(e.sview,t);if(this.lineOnly){const r={};t&&!t.position||Object.assign(r,{position1:i.position1,position2:i.position2}),t&&!t.color||Object.assign(r,{color:i.color,color2:i.color2}),e.bufferList[0].setAttributes(r)}else{var r={};if(t&&!t.position||Object.assign(r,{position1:i.position1,position2:i.position2}),t&&!t.color||Object.assign(r,{color:i.color,color2:i.color2}),t&&!t.radius||Object.assign(r,{radius:i.radius}),e.bufferList[0].setAttributes(r),!this.cylinderOnly){var s=this.getAtomData(e.sview,t),n={};t&&!t.position||Object.assign(n,{position:s.position}),t&&!t.color||Object.assign(n,{color:s.color}),t&&!t.radius||Object.assign(n,{radius:s.radius}),e.bufferList[1].setAttributes(n)}}}setParameters(t={}){let e=!1;const i={};return(t.aspectRatio||t.bondSpacing||t.bondScale)&&(Object.assign(i,{radius:!0}),Ie&&!this.disableImpostor||(e=!0)),super.setParameters(t,i,e),this}}Ne.add("ball+stick",id);class rd extends id{constructor(t,e,i){super(t,e,i),this.type="backbone",this.parameters=Object.assign({},this.parameters,{multipleBond:null,bondSpacing:null}),this.init(i)}init(t){var e=t||{};e.aspectRatio=st(e.aspectRatio,1),e.radiusSize=st(e.radiusSize,.25),super.init(e)}getAtomRadius(t){return t.isTrace()?super.getAtomRadius(t):0}getAtomData(t,e,i){return t.getBackboneAtomData(this.getAtomParams(e,i))}getBondData(t,e,i){return t.getBackboneBondData(this.getBondParams(e,i))}}Ne.add("backbone",rd);class sd extends id{constructor(t,e,i){super(t,e,i),this.type="base",this.parameters=Object.assign({},this.parameters,{multipleBond:null,bondSpacing:null})}init(t){let e=t||{};e.aspectRatio=st(e.aspectRatio,1),e.radiusSize=st(e.radiusSize,.3),super.init(e)}getAtomData(t,e,i){return t.getRungAtomData(this.getAtomParams(e,i))}getBondData(t,e,i){let r=this.getBondParams(e,i);return Object.assign(r.colorParams,{rung:!0}),t.getRungBondData(r)}}Ne.add("base",sd);class nd{constructor(t,i){this.m=t,this.tension=i,this.dt=1/this.m,this.delta=1e-4,this.vec1=new e,this.vec2=new e,this.vDir=new e,this.vTan=new e,this.vNorm=new e,this.vBin=new e,this.m2=Math.ceil(this.m/2)}interpolateToArr(t,e,i,r,s,n,o){n[o+0]=Ot(t.x,e.x,i.x,r.x,s,this.tension),n[o+1]=Ot(t.y,e.y,i.y,r.y,s,this.tension),n[o+2]=Ot(t.z,e.z,i.z,r.z,s,this.tension)}interpolateToVec(t,e,i,r,s,n){n.x=Ot(t.x,e.x,i.x,r.x,s,this.tension),n.y=Ot(t.y,e.y,i.y,r.y,s,this.tension),n.z=Ot(t.z,e.z,i.z,r.z,s,this.tension)}interpolatePosition(t,e,i,r,s,n){for(var o=0;o<this.m;++o){var a=n+3*o,c=this.dt*o;this.interpolateToArr(t,e,i,r,c,s,a)}}interpolateTangent(t,e,i,r,s,n){for(var o=0;o<this.m;++o){var a=this.dt*o,c=a-this.delta,l=a+this.delta,h=n+3*o;c<0&&(c=0),l>1&&(l=1),this.interpolateToVec(t,e,i,r,c,this.vec1),this.interpolateToVec(t,e,i,r,l,this.vec2),this.vec2.sub(this.vec1).normalize(),this.vec2.toArray(s,h)}}vectorSubdivide(t,e,i,r,s){let n,o=e.next(),a=e.next(),c=e.next();const l=e.size,h=l-1;let d=r||0;for(let r=0;r<h;++r)n=o,o=a,a=c,c=e.next(),t.apply(this,[n,o,a,c,i,d]),d+=3*this.m;s&&(n=e.get(l-2),o=e.get(l-1),a=e.get(0),c=e.get(1),t.apply(this,[n,o,a,c,i,d]),d+=3*this.m)}getPosition(t,e,i,r){t.reset(),this.vectorSubdivide(this.interpolatePosition,t,e,i,r);var s=t.size-1,n=s*this.m*3;r&&(n+=3*this.m);var o=t.get(r?0:s);e[n]=o.x,e[n+1]=o.y,e[n+2]=o.z}getTangent(t,e,i,r){t.reset(),this.vectorSubdivide(this.interpolateTangent,t,e,i,r);let s=(t.size-1)*this.m*3;r&&(s+=3*this.m),Mi(e,e,s-3,s,3)}interpolateNormalDir(t,e,i,r,s,n,o,a,c,l,h,d,u){for(let m=0;m<this.m;++m){let p=d+3*m;u&&(p+=3*this.m2);const f=this.dt*m;this.interpolateToVec(t,e,i,r,f,this.vec1),this.interpolateToVec(s,n,o,a,f,this.vec2),this.vDir.subVectors(this.vec2,this.vec1).normalize(),this.vTan.fromArray(c,p),this.vBin.crossVectors(this.vDir,this.vTan).normalize(),this.vBin.toArray(h,p),this.vNorm.crossVectors(this.vTan,this.vBin).normalize(),this.vNorm.toArray(l,p)}}interpolateNormal(t,e,i,r,s){for(var n=0;n<this.m;++n){var o=s+3*n;t.copy(this.vNorm),this.vTan.fromArray(e,o),this.vBin.crossVectors(t,this.vTan).normalize(),this.vBin.toArray(r,o),this.vNorm.crossVectors(this.vTan,this.vBin).normalize(),this.vNorm.toArray(i,o)}}getNormal(t,e,i,r,s,n){this.vNorm.set(0,0,1);const o=t-1;let a=s||0;for(var c=0;c<o;++c)this.interpolateNormal(this.vDir,e,i,r,a),a+=3*this.m;n&&(this.interpolateNormal(this.vDir,e,i,r,a),a+=3*this.m),this.vBin.toArray(r,a),this.vNorm.toArray(i,a)}getNormalDir(t,i,r,s,n,o,a,c){t.reset(),i.reset();const l=new e,h=new e,d=new e,u=new e,m=new e,p=(new e).copy(t.next()),f=(new e).copy(t.next()),g=(new e).copy(t.next()),y=new e,b=(new e).copy(i.next()),x=(new e).copy(i.next()),v=(new e).copy(i.next());this.vNorm.set(0,0,1);let w=t.size,A=w-1,_=o||0;for(var S=0;S<A;++S)m.copy(p),p.copy(f),f.copy(g),g.copy(t.next()),y.copy(b),b.copy(x),x.copy(v),v.copy(i.next()),0===S?(l.subVectors(y,m),h.subVectors(b,p),l.dot(h)<0&&(h.multiplyScalar(-1),b.addVectors(p,h)),d.subVectors(x,f),h.dot(d)<0&&(d.multiplyScalar(-1),x.addVectors(f,d))):d.copy(u),u.subVectors(v,g),d.dot(u)<0&&(u.multiplyScalar(-1),v.addVectors(g,u)),this.interpolateNormalDir(m,p,f,g,y,b,x,v,r,s,n,_,c),_+=3*this.m;if(a&&(m.copy(t.get(w-2)),p.copy(t.get(w-1)),f.copy(t.get(0)),g.copy(t.get(1)),y.copy(i.get(w-2)),b.copy(i.get(w-1)),x.copy(i.get(0)),v.copy(i.get(1)),d.copy(u),u.subVectors(v,g),d.dot(u)<0&&(u.multiplyScalar(-1),v.addVectors(g,u)),this.interpolateNormalDir(m,p,f,g,y,b,x,v,r,s,n,_,c),_+=3*this.m),c){this.vBin.fromArray(n,3*this.m2),this.vNorm.fromArray(s,3*this.m2);for(var C=0;C<this.m2;++C)this.vBin.toArray(n,3*C),this.vNorm.toArray(s,3*C)}else this.vBin.toArray(n,_),this.vNorm.toArray(s,_)}interpolateColor(t,e,i,r,s){var n,o;for(n=0;n<this.m2;++n)o=s+3*n,i.apply(this,[t,r,o]);for(n=this.m2;n<this.m;++n)o=s+3*n,i.apply(this,[e,r,o])}getColor(t,e,i,r,s){let n;t.reset(),t.next();let o=t.next();for(var a=t.size,c=a-1,l=r||0,h=0;h<c;++h)n=o,o=t.next(),this.interpolateColor(n,o,e,i,l),l+=3*this.m;s&&(n=t.get(a-1),o=t.get(0),this.interpolateColor(n,o,e,i,l),l+=3*this.m),i[l]=i[l-3],i[l+1]=i[l-2],i[l+2]=i[l-1]}interpolatePicking(t,e,i,r,s){var n;for(n=0;n<this.m2;++n)r[s+n]=i.apply(this,[t]);for(n=this.m2;n<this.m;++n)r[s+n]=i.apply(this,[e])}getPicking(t,e,i,r,s){let n;t.reset(),t.next();let o=t.next();const a=t.size,c=a-1;let l=r||0;for(var h=0;h<c;++h)n=o,o=t.next(),this.interpolatePicking(n,o,e,i,l),l+=this.m;s&&(n=t.get(a-1),o=t.get(0),this.interpolatePicking(n,o,e,i,l),l+=this.m),i[l]=i[l-1]}interpolateSize(t,e,i,r,s){const n=i.apply(this,[t]),o=i.apply(this,[e]);for(let t=0;t<this.m;++t){let e=t/this.m;r[s+t]=(1-e)*n+e*o}}getSize(t,e,i,r,s){let n;t.reset(),t.next();let o=t.next();const a=t.size,c=a-1;let l=r||0;for(var h=0;h<c;++h)n=o,o=t.next(),this.interpolateSize(n,o,e,i,l),l+=this.m;s&&(n=t.get(a-1),o=t.get(0),this.interpolateSize(n,o,e,i,l),l+=this.m),i[l]=i[l-1]}}class od{constructor(t,e){this.polymer=t,this.size=t.residueCount;var i=e||{};this.directional=i.directional||!1,this.positionIterator=i.positionIterator||!1,this.subdiv=i.subdiv||1,this.smoothSheet=i.smoothSheet||!1,i.tension?this.tension=i.tension:this.tension=this.polymer.isNucleic()?.5:.9,this.interpolator=new nd(this.subdiv,this.tension)}getAtomIterator(t,i){const r=this.polymer,s=r.structure,n=r.residueCount;let o=0,a=-1;const c=[s.getAtomProxy(),s.getAtomProxy(),s.getAtomProxy(),s.getAtomProxy()],l=[new e,new e,new e,new e];var h=s.getAtomProxy(),d=s.getAtomProxy();function u(e){var s=c[o%4];if(s.index=r.getAtomIndexByType(e,t),i&&e>0&&e<n&&"e"===s.sstruc){var a=l[o%4];return h.index=r.getAtomIndexByType(e+1,t),d.index=r.getAtomIndexByType(e-1,t),a.addVectors(h,d).add(s).add(s).multiplyScalar(.25),o+=1,a}return o+=1,s}return{size:n,next:function(){var t=u(a);return a+=1,t},get:u,reset:function(){o=0,a=-1}}}getSubdividedColor(t){var e=this.subdiv,i=this.polymer,r=(i.residueCount-1)*e*3+3;i.isCyclic&&(r+=3*e);var s=new Float32Array(r),n=this.getAtomIterator("trace"),o=t||{};o.structure=i.structure;var a=Fe.getScheme(o);return this.interpolator.getColor(n,(function(t,e,i){a.atomColorToArray(t,e,i)}),s,0,i.isCyclic),{color:s}}getSubdividedPicking(){var t=this.subdiv,e=this.polymer,i=(e.residueCount-1)*t+1;e.isCyclic&&(i+=t);var r=e.structure,s=this.getAtomIterator("trace"),n=new Float32Array(i);return this.interpolator.getPicking(s,(function(t){return t.index}),n,0,e.isCyclic),{picking:new Yn(n,r)}}getSubdividedPosition(){return{position:this.getPosition()}}getSubdividedOrientation(){const t=this.getTangent(),e=this.getNormals(t);return{tangent:t,normal:e.normal,binormal:e.binormal}}getSubdividedSize(t){var e=this.subdiv,i=this.polymer,r=(i.residueCount-1)*e+1;i.isCyclic&&(r+=e);var s=new Float32Array(r),n=this.getAtomIterator("trace"),o=new pa(t);return this.interpolator.getSize(n,(function(t){return o.atomRadius(t)}),s,0,i.isCyclic),{size:s}}getPosition(){const t=this.subdiv,e=this.polymer;let i=(e.residueCount-1)*t*3+3;e.isCyclic&&(i+=3*t);const r=new Float32Array(i),s=this.positionIterator||this.getAtomIterator("trace",this.smoothSheet);return this.interpolator.getPosition(s,r,0,e.isCyclic),r}getTangent(){const t=this.subdiv,e=this.polymer;let i=(this.size-1)*t*3+3;e.isCyclic&&(i+=3*t);const r=new Float32Array(i),s=this.positionIterator||this.getAtomIterator("trace",this.smoothSheet);return this.interpolator.getTangent(s,r,0,e.isCyclic),r}getNormals(t){const e=this.subdiv,i=this.polymer,r=i.isProtein(),s=this.size;let n=(s-1)*e*3+3;i.isCyclic&&(n+=3*e);const o=new Float32Array(n),a=new Float32Array(n);if(this.directional&&!this.polymer.isCg()){const e=this.getAtomIterator("direction1"),s=this.getAtomIterator("direction2");this.interpolator.getNormalDir(e,s,t,o,a,0,i.isCyclic,r)}else this.interpolator.getNormal(s,t,o,a,0,i.isCyclic);return{normal:o,binormal:a}}}const ad=new e,cd=new e,ld=Object.assign({radialSegments:4,capped:!1,aspectRatio:1},zo);class hd extends Uo{constructor(t,e={}){super(function(t,e={}){const i=st(e.radialSegments,4),r=st(e.capped,!1),s=r?i:0,n=r?i-2:0,o=t.position.length/3,a=o*i*3+2*s*3,c=2*(o-1)*i*3+2*n*3;return{position:new Float32Array(a),color:new Float32Array(a),index:xt(c,a/3),normal:new Float32Array(a),picking:t.picking}}(t,e),e),this.capVertices=this.parameters.capped?this.parameters.radialSegments:0,this.capTriangles=this.parameters.capped?this.parameters.radialSegments-2:0,this.size2=t.position.length/3,t.primitiveId=Pi(this.size2),this.setAttributes(t),this.makeIndex()}get defaultParameters(){return ld}setAttributes(t={}){const e=this.parameters.aspectRatio,i=this.size2,r=i-1,s=this.parameters.radialSegments,n=this.geometry.attributes;let o,a,c,l,h,d,u,m,p,f,g,y,b;t.position&&(o=t.position,a=t.normal,c=t.binormal,l=t.tangent,d=t.size,m=n.position.array,f=n.normal.array,n.position.needsUpdate=!0,n.normal.needsUpdate=!0),t.color&&(h=t.color,p=n.color.array,n.color.needsUpdate=!0),t.primitiveId&&(u=t.primitiveId,g=n.primitiveId.array,n.primitiveId.needsUpdate=!0);let x=0,v=0,w=0,A=0,_=0,S=0,C=0,P=0,I=0,k=0;const M=[],T=[],B=[],D=[],$=[],O=[];if(o)for(let t=0;t<s;++t){const i=t/s*2*Math.PI;M[t]=e*Math.cos(i),T[t]=Math.sin(i),B[t]=e*Math.cos(i-.01),D[t]=Math.sin(i-.01),$[t]=e*Math.cos(i+.01),O[t]=Math.sin(i+.01)}for(let t=0;t<i;++t){y=3*t,b=y*s,o&&l&&a&&c&&d&&(ad.set(l[y],l[y+1],l[y+2]),v=a[y],w=a[y+1],A=a[y+2],_=c[y],S=c[y+1],C=c[y+2],P=o[y],I=o[y+1],k=o[y+2],x=d[t]);for(let e=0;e<s;++e){const i=b+3*e;if(o){const t=-x*M[e],r=x*T[e],s=-x*B[e],n=x*D[e],o=-x*$[e],a=x*O[e];m[i]=P+t*v+r*_,m[i+1]=I+t*w+r*S,m[i+2]=k+t*A+r*C,cd.set(o*v+a*_-(s*v+n*_),o*w+a*S-(s*w+n*S),o*A+a*C-(s*A+n*C)).cross(ad),f[i]=cd.x,f[i+1]=cd.y,f[i+2]=cd.z}h&&(p[i]=h[y],p[i+1]=h[y+1],p[i+2]=h[y+2]),u&&(g[t*s+e]=u[t])}}y=0,b=3*i*s;for(let t=0;t<s;++t){const e=y+3*t,r=b+3*t;o&&l&&(m[r]=m[e],m[r+1]=m[e+1],m[r+2]=m[e+2],f[r]=l[y],f[r+1]=l[y+1],f[r+2]=l[y+2]),h&&(p[r]=p[e],p[r+1]=p[e+1],p[r+2]=p[e+2]),u&&(g[i*s+t]=g[0+t])}y=3*(i-1)*s,b=3*(i+1)*s;for(let t=0;t<s;++t){const e=y+3*t,n=b+3*t;o&&l&&(m[n]=m[e],m[n+1]=m[e+1],m[n+2]=m[e+2],f[n]=l[3*r],f[n+1]=l[3*r+1],f[n+2]=l[3*r+2]),h&&(p[n]=p[e],p[n+1]=p[e+1],p[n+2]=p[e+2]),u&&(g[(i+1)*s+t]=g[(i-1)*s+t])}}makeIndex(){const t=this.geometry.getIndex();if(!t)return void Me.error("Index is null");const e=t.array,i=this.size2,r=i-1,s=this.capTriangles,n=this.parameters.radialSegments,o=this.parameters.radialSegments+1;let a,c;for(let t=0;t<r;++t){const i=t*n*3*2,r=t*n,s=(t+1)*n;for(let t=0;t<n;++t)c=i+3*t*2,e[c]=r+t,e[c+1]=r+(t+1)%n,e[c+2]=s+t,e[c+3]=s+t,e[c+4]=r+(t+1)%n,e[c+5]=s+(t+1)%n}const l=[0];for(let t=1;t<o/2;++t)l.push(t),n-t!==t&&l.push(n-t);c=r*n*3*2,a=i*n;for(let t=0;t<l.length-2;++t)t%2==0?(e[c+3*t+0]=a+l[t+0],e[c+3*t+1]=a+l[t+1],e[c+3*t+2]=a+l[t+2]):(e[c+3*t+0]=a+l[t+2],e[c+3*t+1]=a+l[t+1],e[c+3*t+2]=a+l[t+0]);c=r*n*3*2+3*s,a=i*n+n;for(let t=0;t<l.length-2;++t)t%2==0?(e[c+3*t+0]=a+l[t+0],e[c+3*t+1]=a+l[t+1],e[c+3*t+2]=a+l[t+2]):(e[c+3*t+0]=a+l[t+2],e[c+3*t+1]=a+l[t+1],e[c+3*t+2]=a+l[t+0])}}class dd extends Sh{constructor(t,e,i){super(t,e,i),this.type="cartoon",this.parameters=Object.assign({aspectRatio:{type:"number",precision:1,max:10,min:1,rebuild:!0},subdiv:{type:"integer",max:50,min:1,rebuild:!0},radialSegments:{type:"integer",max:50,min:1,rebuild:!0},tension:{type:"number",precision:1,max:1,min:.1},capped:{type:"boolean",rebuild:!0},smoothSheet:{type:"boolean",rebuild:!0}},this.parameters),this.init(i)}init(t){var e=t||{};e.colorScheme=st(e.colorScheme,"chainname"),e.colorScale=st(e.colorScale,"RdYlBu"),e.radiusType=st(e.radiusType,"sstruc"),e.radiusScale=st(e.radiusScale,.7),e.useInteriorColor=st(e.useInteriorColor,!0),this.aspectRatio=st(e.aspectRatio,5),this.tension=st(e.tension,NaN),this.capped=st(e.capped,!0),this.smoothSheet=st(e.smoothSheet,!1),"low"===e.quality?(this.subdiv=3,this.radialSegments=6):"medium"===e.quality?this.subdiv=6:"high"===e.quality?this.subdiv=12:this.subdiv=st(e.subdiv,6),super.init(e)}getSplineParams(t){return Object.assign({subdiv:this.subdiv,tension:this.tension,directional:1!==this.aspectRatio,smoothSheet:this.smoothSheet},t)}getSpline(t){return new od(t,this.getSplineParams())}getAspectRatio(t){return t.isCg()?1:this.aspectRatio}getAtomRadius(t){return t.isTrace()?super.getAtomRadius(t):0}createData(t){let e=[],i=[];return this.structure.eachPolymer((t=>{if(t.residueCount<4)return;i.push(t);const r=this.getSpline(t),s=this.getAspectRatio(t),n=r.getSubdividedPosition(),o=r.getSubdividedOrientation(),a=r.getSubdividedColor(this.getColorParams()),c=r.getSubdividedPicking(),l=r.getSubdividedSize(this.getRadiusParams());e.push(new hd(Object.assign({},n,o,a,c,l),this.getBufferParams({radialSegments:this.radialSegments,aspectRatio:s,capped:this.capped})))}),t.getSelection()),{bufferList:e,polymerList:i}}updateData(t,e){De&&Me.time(this.type+" repr update"),t=t||{};for(var i=0,r=e.polymerList.length;i<r;++i){var s={},n=e.polymerList[i],o=this.getSpline(n),a=this.getAspectRatio(n);if(Object.assign(e.bufferList[i],{aspectRatio:a}),t.position||t.radius){var c=o.getSubdividedPosition(),l=o.getSubdividedOrientation(),h=o.getSubdividedSize(this.getRadiusParams(a));s.position=c.position,s.normal=l.normal,s.binormal=l.binormal,s.tangent=l.tangent,s.size=h.size}if(t.color){var d=o.getSubdividedColor(this.getColorParams());s.color=d.color}if(t.picking){var u=o.getSubdividedPicking();s.picking=u.picking}e.bufferList[i].setAttributes(s)}De&&Me.timeEnd(this.type+" repr update")}setParameters(t){var e={};return t&&t.aspectRatio&&(e.radius=!0),t&&t.tension&&(e.position=!0),super.setParameters(t,e,!1),this}}Ne.add("cartoon",dd);class ud extends Sh{constructor(t,e,i){super(t,e,i),this.type="contact",this.parameters=Object.assign({hydrogenBond:{type:"boolean",rebuild:!0},weakHydrogenBond:{type:"boolean",rebuild:!0},waterHydrogenBond:{type:"boolean",rebuild:!0},backboneHydrogenBond:{type:"boolean",rebuild:!0},hydrophobic:{type:"boolean",rebuild:!0},halogenBond:{type:"boolean",rebuild:!0},ionicInteraction:{type:"boolean",rebuild:!0},metalCoordination:{type:"boolean",rebuild:!0},cationPi:{type:"boolean",rebuild:!0},piStacking:{type:"boolean",rebuild:!0},filterSele:{type:"text",rebuild:!0},labelVisible:{type:"boolean",rebuild:!0},labelFixedSize:{type:"boolean",buffer:"fixedSize"},labelSize:{type:"number",precision:3,max:10,min:.001,rebuild:!0},labelUnit:{type:"select",rebuild:!0,options:{"":"",angstrom:"angstrom",nm:"nm"}},maxHydrophobicDist:{type:"number",precision:1,max:10,min:.1,rebuild:!0},maxHbondDist:{type:"number",precision:1,max:10,min:.1,rebuild:!0},maxHbondSulfurDist:{type:"number",precision:1,max:10,min:.1,rebuild:!0},maxHbondAccAngle:{type:"integer",max:180,min:0,rebuild:!0},maxHbondDonAngle:{type:"integer",max:180,min:0,rebuild:!0},maxHbondAccPlaneAngle:{type:"integer",max:90,min:0,rebuild:!0},maxHbondDonPlaneAngle:{type:"integer",max:90,min:0,rebuild:!0},maxPiStackingDist:{type:"number",precision:1,max:10,min:.1,rebuild:!0},maxPiStackingOffset:{type:"number",precision:1,max:10,min:.1,rebuild:!0},maxPiStackingAngle:{type:"integer",max:180,min:0,rebuild:!0},maxCationPiDist:{type:"number",precision:1,max:10,min:.1,rebuild:!0},maxCationPiOffset:{type:"number",precision:1,max:10,min:.1,rebuild:!0},maxIonicDist:{type:"number",precision:1,max:10,min:.1,rebuild:!0},maxHalogenBondDist:{type:"number",precision:1,max:10,min:.1,rebuild:!0},maxHalogenBondAngle:{type:"integer",max:180,min:0,rebuild:!0},maxMetalDist:{type:"number",precision:1,max:10,min:.1,rebuild:!0},refineSaltBridges:{type:"boolean",rebuild:!0},masterModelIndex:{type:"integer",max:1e3,min:-1,rebuild:!0},lineOfSightDistFactor:{type:"number",precision:1,max:10,min:0,rebuild:!0},radialSegments:!0,disableImpostor:!0},this.parameters),this.init(i)}init(t){var e=t||{};e.radiusSize=st(e.radiusSize,.05),e.useInteriorColor=st(e.useInteriorColor,!0),this.hydrogenBond=st(e.hydrogenBond,!0),this.weakHydrogenBond=st(e.weakHydrogenBond,!1),this.waterHydrogenBond=st(e.waterHydrogenBond,!1),this.backboneHydrogenBond=st(e.backboneHydrogenBond,!1),this.hydrophobic=st(e.hydrophobic,!1),this.halogenBond=st(e.halogenBond,!0),this.ionicInteraction=st(e.ionicInteraction,!0),this.metalCoordination=st(e.metalCoordination,!0),this.cationPi=st(e.cationPi,!0),this.piStacking=st(e.piStacking,!0),this.filterSele=st(e.filterSele,""),this.labelVisible=st(e.labelVisible,!1),this.labelFixedSize=st(e.labelFixedSize,!1),this.labelSize=st(e.labelSize,2),this.labelUnit=st(e.labelUnit,""),this.maxHydrophobicDist=st(e.maxHydrophobicDist,4),this.maxHbondDist=st(e.maxHbondDist,3.5),this.maxHbondSulfurDist=st(e.maxHbondSulfurDist,4.1),this.maxHbondAccAngle=st(e.maxHbondAccAngle,45),this.maxHbondDonAngle=st(e.maxHbondDonAngle,45),this.maxHbondAccPlaneAngle=st(e.maxHbondAccPlaneAngle,90),this.maxHbondDonPlaneAngle=st(e.maxHbondDonPlaneAngle,30),this.maxPiStackingDist=st(e.maxPiStackingDist,5.5),this.maxPiStackingOffset=st(e.maxPiStackingOffset,2),this.maxPiStackingAngle=st(e.maxPiStackingAngle,30),this.maxCationPiDist=st(e.maxCationPiDist,6),this.maxCationPiOffset=st(e.maxCationPiOffset,2),this.maxIonicDist=st(e.maxIonicDist,5),this.maxHalogenBondDist=st(e.maxHalogenBondDist,3.5),this.maxHalogenBondAngle=st(e.maxHalogenBondAngle,30),this.maxMetalDist=st(e.maxMetalDist,3),this.refineSaltBridges=st(e.refineSaltBridges,!0),this.masterModelIndex=st(e.masterModelIndex,-1),this.lineOfSightDistFactor=st(e.lineOfSightDistFactor,1),super.init(e)}getAtomRadius(){return 0}getContactData(t){const e={maxHydrophobicDist:this.maxHydrophobicDist,maxHbondDist:this.maxHbondDist,maxHbondSulfurDist:this.maxHbondSulfurDist,maxHbondAccAngle:this.maxHbondAccAngle,maxHbondDonAngle:this.maxHbondDonAngle,maxHbondAccPlaneAngle:this.maxHbondAccPlaneAngle,maxHbondDonPlaneAngle:this.maxHbondDonPlaneAngle,maxPiStackingDist:this.maxPiStackingDist,maxPiStackingOffset:this.maxPiStackingOffset,maxPiStackingAngle:this.maxPiStackingAngle,maxCationPiDist:this.maxCationPiDist,maxCationPiOffset:this.maxCationPiOffset,maxIonicDist:this.maxIonicDist,maxHalogenBondDist:this.maxHalogenBondDist,maxHalogenBondAngle:this.maxHalogenBondAngle,maxMetalDist:this.maxMetalDist,refineSaltBridges:this.refineSaltBridges,masterModelIndex:this.masterModelIndex,lineOfSightDistFactor:this.lineOfSightDistFactor},i={hydrogenBond:this.hydrogenBond,weakHydrogenBond:this.weakHydrogenBond,waterHydrogenBond:this.waterHydrogenBond,backboneHydrogenBond:this.backboneHydrogenBond,hydrophobic:this.hydrophobic,halogenBond:this.halogenBond,ionicInteraction:this.ionicInteraction,metalCoordination:this.metalCoordination,cationPi:this.cationPi,piStacking:this.piStacking,radius:this.radiusSize*this.radiusScale,filterSele:this.filterSele};return Wn(Gn(t,e),t,i)}createData(t){const e=this.getContactData(t),i=[new td(ms(e),this.getBufferParams({sphereDetail:1,dullInterior:!0,disableImpostor:this.disableImpostor}))];if(this.labelVisible){const t={size:this.labelSize,unit:this.labelUnit};i.push(new Eh(function(t,e){const i=Ai(t.position1,t.position2),r=[],s=_i(t.position1,t.position2),n=s.length/3;for(let t=0;t<n;t++){const i=3*t,n=Math.sqrt(Math.pow(s[i],2)+Math.pow(s[i+1],2)+Math.pow(s[i+2],2));switch(e.unit){case"angstrom":r[t]=n.toFixed(2)+" "+String.fromCharCode(8491);break;case"nm":r[t]=(n/10).toFixed(2)+" nm";break;default:r[t]=n.toFixed(2)}}return{position:i,size:Si(i.length/3,e.size),color:t.color,text:r}}(e,t),this.getBufferParams({fixedSize:this.labelFixedSize})))}return{bufferList:i}}}Ne.add("contact",ud);class md extends Ch{constructor(t,e,i){super(t,e,i),this.type="dihedral",this.parameters=Object.assign({atomQuad:{type:"hidden",rebuild:!0},extendLine:{type:"boolean",rebuild:!0,default:!0},lineVisible:{type:"boolean",default:!0},planeVisible:{type:"boolean",default:!0},sectorVisible:{type:"boolean",default:!0}},this.parameters),this.init(i)}init(t){const e=t||{};e.side=st(e.side,"double"),e.opacity=st(e.opacity,.5),this.atomQuad=st(e.atomQuad,[]),this.extendLine=st(e.extendLine,!0),this.lineVisible=st(e.lineVisible,!0),this.planeVisible=st(e.planeVisible,!0),this.sectorVisible=st(e.sectorVisible,!0),super.init(e)}createData(t){if(!t.atomCount||!this.atomQuad.length)return;const e=function(t,e={}){const i=st(e.angleStep,Math.PI/90),r=t.length,s=t.length/12,n=new Float32Array(s),o=new Float32Array(3*s),a=new Array(s),c=new Array(s),l=new Array(s),h=new Array(s),d=new Array(s);let u=0,m=0,p=0;const f=Yr(),g=Yr(),y=Yr(),b=Yr(),x=Yr(),v=Yr(),w=Yr(),A=Yr(),_=Yr(),S=Yr(),C=Yr(),P=Yr(),I=Yr(),k=Yr(),M=Yr();let T=0;for(var B=0;B<r;B+=12){if(ts(f,t,B),ts(g,t,B+3),ts(y,t,B+6),ts(b,t,B+9),Qr(x,f,g),Qr(v,y,g),0===rs(v))continue;Qr(w,b,y),ns(A,v,.5),Jr(_,g,A),os(x,x),os(v,v),os(w,w),Qr(A,f,_);const r=Zr(A,v)>0;Qr(A,b,_);const s=Zr(A,v)<0;if(ns(A,v,Zr(v,x)),Qr(S,x,A),ns(A,v,Zr(v,w)),Qr(C,w,A),0===rs(S)||0===rs(C))continue;os(S,S),os(C,C);const D=n[T]=us(S,C);a[T]=(vi*D).toFixed(1)+String.fromCharCode(176),Kr(k,S,v),os(k,k),Zr(k,C)<0&&ds(k,k),Ih(A,_,S,k,D/2),es(A,o,3*T);const $=Math.ceil(D/i),O=$+(e.extendLine?4:2),R=e.extendLine?36:0,E=new Float32Array(3*O),F=new Float32Array(3*O),L=new Float32Array(9*$),N=new Float32Array(R);c[T]=E,l[T]=F,h[T]=L,d[T]=N,e.extendLine&&(r?(Qr(A,f,y),os(A,A),ns(P,A,1/Zr(S,A)),Jr(P,P,y)):(ns(P,x,1/Zr(S,x)),Jr(P,P,g)),s?(Qr(A,b,g),os(A,A),ns(I,A,1/Zr(C,A)),Jr(I,I,g)):(ns(I,w,1/Zr(C,w)),Jr(I,I,y))),Jr(M,_,S);let z=0;e.extendLine?(es(f,E,z),es(P,F,z),z+=3,es(P,E,z),es(M,F,z),z+=3,es(P,N,0),es(M,N,3),es(r?y:g,N,6),es(r?y:g,N,9),es(M,N,12),es(_,N,15)):(es(_,E,z),es(M,F,z),z+=3);const V=function(t,e){const i=9*e;es(_,L,i),es(M,L,i+3),es(M,E,z),Ih(M,_,S,k,t),es(M,L,i+6),es(M,F,z),z+=3};let G=0;for(let t=i;t<D;t+=i)V(t,G++);V(D,G++),e.extendLine?(es(M,E,3*(O-2)),es(I,F,3*(O-2)),es(I,E,3*(O-1)),es(b,F,3*(O-1)),es(I,N,18),es(M,N,21),es(s?g:y,N,24),es(s?g:y,N,27),es(M,N,30),es(_,N,33)):(es(M,E,z),es(_,F,z),z+=3),u+=3*O,m+=9*$,p+=R,T+=1}const D=T,$=new Float32Array(u),O=new Float32Array(u),R=new Float32Array(m),E=new Float32Array(p);let F=0,L=0,N=0;for(let t=0;t<D;t++){const e=c[t],i=l[t],r=h[t],s=d[t];Mi(e,$,0,F,e.length),Mi(i,O,0,F,i.length),Mi(r,R,0,L,r.length),Mi(s,E,0,N,s.length),F+=e.length,L+=r.length,N+=s.length}return{labelPosition:o.subarray(0,3*D),labelText:a.slice(0,D),linePosition1:$,linePosition2:O,planePosition:E,sectorPosition:R}}(Ph(t,this.atomQuad),{extendLine:this.extendLine}),i=this.n=e.labelText.length,r=new s(this.labelColor);this.textBuffer=new Eh({position:e.labelPosition,size:Si(i,this.labelSize),color:Ci(i,r.r,r.g,r.b),text:e.labelText},this.getLabelBufferParams());const n=new s(this.colorValue);this.lineLength=e.linePosition1.length/3;const o=Ci(this.lineLength,n.r,n.g,n.b);return this.lineBuffer=new Nh(fs({position1:e.linePosition1,position2:e.linePosition2,color:o,color2:o}),this.getBufferParams({linewidth:this.linewidth,visible:this.lineVisible,opacity:this.lineOpacity})),this.planeLength=e.planePosition.length/3,this.planeBuffer=new Uo({position:e.planePosition,color:Ci(this.planeLength,n.r,n.g,n.b)},this.getBufferParams({visible:this.planeVisible})),this.sectorLength=e.sectorPosition.length/3,this.sectorBuffer=new Uo({position:e.sectorPosition,color:Ci(this.sectorLength,n.r,n.g,n.b)},this.getBufferParams({visible:this.sectorVisible})),{bufferList:[this.textBuffer,this.lineBuffer,this.planeBuffer,this.sectorBuffer]}}updateData(t,e){super.updateData(t,e);const i={},r={},n={};if(t.color){const t=new s(this.colorValue);Object.assign(i,{color:Ci(this.lineLength,t.r,t.g,t.b),color2:Ci(this.lineLength,t.r,t.g,t.b)}),Object.assign(r,{color:Ci(this.planeLength,t.r,t.g,t.b)}),Object.assign(n,{color:Ci(this.sectorLength,t.r,t.g,t.b)})}this.lineBuffer.setAttributes(i),this.planeBuffer.setAttributes(r),this.sectorBuffer.setAttributes(n)}setParameters(t){return super.setParameters(t,{},!1),!t||void 0===t.lineVisible&&void 0===t.sectorVisible&&void 0===t.planeVisible||this.setVisibility(this.visible),t&&t.lineOpacity&&this.lineBuffer.setParameters({opacity:t.lineOpacity}),t&&void 0!==t.opacity&&this.lineBuffer.setParameters({opacity:this.lineOpacity}),t&&t.linewidth&&this.lineBuffer.setParameters({linewidth:t.linewidth}),this}setVisibility(t,e){return super.setVisibility(t,!0),this.lineBuffer&&this.lineBuffer.setVisibility(this.lineVisible&&this.visible),this.planeBuffer&&this.planeBuffer.setVisibility(this.planeVisible&&this.visible),this.sectorBuffer&&this.sectorBuffer.setVisibility(this.sectorVisible&&this.visible),e||this.viewer.requestRender(),this}}Ne.add("dihedral",md);function pd(t,e){function i(t,e){return e in t}const r=Object.assign({},t);for(const t in r)i(r,t)&&i(e,t)&&(r[t]=st(e[t],r[t]));return r}function fd(t,e){const i=new s(t),r=new Float32Array(3*e);return Ci(e,i.r,i.g,i.b,r),r}class gd extends Sh{constructor(t,e,i){super(t,e,i),this.type="dihedral-histogram",this.parameters=Object.assign({histogramsData:{type:"hidden",rebuild:!0},histogramBinBorderVisible:{type:"boolean",default:!0},scaleBinToSectorArea:{type:"boolean",rebuild:!0,default:!1}},this.parameters),this.init(i)}init(t){const e=t||{},i=pd({histogramBinBorderColor:"grey",adjacentBondArrowColor:"black",distantBondArrowColor:"magenta",frontHistogramColor:"green",backHistogramColor:"blue",opaqueMiddleDiscColor:"white"},e);Object.assign(this,i);const r=pd({histogramsData:[],histogramOpacity:1,opaqueMiddleDiscVisible:!0,opaqueMiddleDiscOpacity:1,histogramBinBorderVisible:!0,histogramBinBorderWidth:1,histogramBinBorderOpacity:.5,bondArrowVisible:!0,bondArrowWidth:2,bondArrowOpacity:1,scaleBinToSectorArea:!1},e);Object.assign(this,r),this.histogramsData.forEach((t=>{const e=pd(i,t);Object.assign(t,e)})),e.side=st(e.side,"double"),e.opacity=st(e.opacity,.5),e.radiusType=st(e.radiusType,"size"),e.radiusSize=st(e.radiusSize,.15),super.init(e)}getHistogramBinBorderBufferParameters(){return this.getBufferParams({linewidth:this.histogramBinBorderWidth,visible:this.histogramBinBorderVisible,opacity:this.histogramBinBorderOpacity})}getBondArrowsBufferParameters(){return this.getBufferParams({linewidth:this.bondArrowWidth,visible:this.bondArrowVisible,opacity:this.bondArrowOpacity})}getOpaqueMiddleDiscBufferParameters(){return this.getBufferParams({visible:this.opaqueMiddleDiscVisible,opacity:this.opaqueMiddleDiscOpacity})}getHistogramBufferParameters(){return this.getBufferParams({visible:!0,opacity:this.histogramOpacity,side:"double"})}createData(t){if(!t.atomCount||!this.histogramsData.length)return;this.histogramsData.forEach((e=>e.atomPositions=Ph(t,[e.atomQuad])));const e=this.scaleBinToSectorArea?function(t){return Math.sqrt(t)}:function(t){return t};function i(t){const e=t.map((t=>t.length)),i=new Float32Array($i(e));let r=0;for(let e=0;e<t.length;e++)i.set(t[e],r),r+=t[e].length;return i}function r(t,e){return new Nh({position1:i(t.map((t=>t.startPoints))),position2:i(t.map((t=>t.endPoints))),color:i(t.map((t=>t.startColors))),color2:i(t.map((t=>t.endColors)))},e)}function s(t,e){return new Uo({position:i(t.map((t=>t.triangles))),color:i(t.map((t=>t.triangleColors)))},e)}this.histogramsData.forEach((t=>t.histogram360Scaled=t.histogram360.map(e)));const n=[];for(let t=0;t<this.histogramsData.length;t++){let e,i=this.histogramsData[t];i.histogram360.length>=3&&(e=yd(i)),void 0!==e&&n.push(e)}return this.frontHistogramBinBordersBuffer=r(n.map((t=>t.frontHistogramBinBorders)),this.getHistogramBinBorderBufferParameters()),this.backHistogramBinBordersBuffer=r(n.map((t=>t.backHistogramBinBorders)),this.getHistogramBinBorderBufferParameters()),this.adjacentBondArrowsBuffer=r(n.map((t=>t.adjacentBondArrows)),this.getBondArrowsBufferParameters()),this.distantBondArrowsBuffer=r(n.map((t=>t.distantBondArrows)),this.getBondArrowsBufferParameters()),this.opaqueMiddleDiscBuffer=s(n.map((t=>t.opaqueMiddleDisc)),this.getOpaqueMiddleDiscBufferParameters()),this.frontHistogramBuffer=s(n.map((t=>t.frontHistogram)),this.getHistogramBufferParameters()),this.backHistogramBuffer=s(n.map((t=>t.backHistogram)),this.getHistogramBufferParameters()),{bufferList:[].concat(this.frontHistogramBinBordersBuffer,this.backHistogramBinBordersBuffer,this.adjacentBondArrowsBuffer,this.distantBondArrowsBuffer,this.opaqueMiddleDiscBuffer,this.frontHistogramBuffer,this.backHistogramBuffer)}}setParameters(t){return super.setParameters(t,{},!1),t&&void 0!==t.histogramBinBorderVisible&&this.setVisibility(this.visible),this}setVisibility(t,e){return super.setVisibility(t,!0),this.frontHistogramBinBordersBuffer&&this.frontHistogramBinBordersBuffer.setVisibility(this.histogramBinBorderVisible),this.backHistogramBinBordersBuffer&&this.backHistogramBinBordersBuffer.setVisibility(this.histogramBinBorderVisible),e||this.viewer.requestRender(),this}}function yd(t){const e=t.atomPositions,i=t.histogram360Scaled,r=i.length<=180?360:2*i.length,s={triangles:new Float32Array(3*r*3),triangleColors:fd(t.opaqueMiddleDiscColor,3*r)},n={triangles:new Float32Array(3*i.length*3),triangleColors:fd(t.frontHistogramColor,3*i.length)},o={triangles:new Float32Array(3*i.length*3),triangleColors:fd(t.backHistogramColor,3*i.length)},a={startPoints:new Float32Array(3*i.length),endPoints:new Float32Array(3*i.length),startColors:fd(t.histogramBinBorderColor,i.length),endColors:fd(t.histogramBinBorderColor,i.length)},c={startPoints:new Float32Array(3*i.length),endPoints:new Float32Array(3*i.length),startColors:fd(t.histogramBinBorderColor,i.length),endColors:fd(t.histogramBinBorderColor,i.length)},l={startPoints:new Float32Array(6),endPoints:new Float32Array(6),startColors:fd(t.adjacentBondArrowColor,i.length),endColors:fd(t.adjacentBondArrowColor,i.length)},h={startPoints:new Float32Array(6),endPoints:new Float32Array(6),startColors:fd(t.distantBondArrowColor,i.length),endColors:fd(t.distantBondArrowColor,i.length)},d=Yr(),u=Yr(),m=Yr(),p=Yr(),f=Yr(),g=Yr(),y=Yr(),b=Yr(),x=Yr(),v=Yr(),w=Yr(),A=Yr(),_=Yr(),S=Yr(),C=Yr(),P=Yr(),I=[d,u,m,p];for(let t=0;t<I.length;t++)ts(I[t],e,3*t);if(Qr(f,d,u),Qr(g,m,u),Qr(b,p,m),0===rs(g))return;if(ns(C,g,.5),Jr(x,u,C),os(f,f),os(g,g),os(b,b),ds(y,g),ns(C,y,Zr(y,f)),Qr(v,f,C),ns(C,g,Zr(g,b)),Qr(w,b,C),0===rs(v)||0===rs(w))return;os(v,v),os(w,w);const k=Math.acos(Zr(v,w));Kr(A,y,v),Kr(_,g,w),os(A,A),os(_,_);let M=k;Zr(A,w)<0&&(M=-k),Jr(S,x,v);const T=Math.max.apply(null,i),B=2*Math.PI/i.length;function D(t,e,r,s,n){const o=3*e*3;es(x,t,o);const a=Number(i[e])/T;ns(C,r,a),ns(P,s,a),Ih(S,x,C,P,e*n),es(S,t,o+3),Ih(S,x,C,P,(e+1)*n),es(S,t,o+6)}function $(t,e,r,s,n){Mi(x,l.startPoints,0,3*r,x.length),Ih(C,x,s,n,0+0*B),Mi(C,l.endPoints,0,3*r,x.length),Mi(x,h.startPoints,0,3*r,x.length),Ih(C,x,s,n,M),Mi(C,h.endPoints,0,3*r,x.length);for(let t=0;t<i.length;t++)Mi(x,e.startPoints,0,3*t,x.length),Ih(C,x,s,n,0+B*t),Mi(C,e.endPoints,0,3*t,C.length);for(let e=0;e<i.length;e++)D(t.triangles,e,s,n,B)}const O=2*Math.PI/r;for(let t=0;t<r;t++){const e=3*t*3;es(x,s.triangles,e),Ih(S,x,v,A,t*O),es(S,s.triangles,e+3),Ih(S,x,v,A,(t+1)*O),es(S,s.triangles,e+6)}return ns(C,g,-.01),Jr(x,x,C),$(n,a,0,v,A),ns(C,g,.02),Jr(x,x,C),$(o,c,1,w,_),{opaqueMiddleDisc:s,frontHistogram:n,backHistogram:o,frontHistogramBinBorders:a,backHistogramBinBorders:c,adjacentBondArrows:l,distantBondArrows:h}}Ne.add("dihedral-histogram",gd);class bd extends Ch{constructor(t,e,i){super(t,e,i),this.type="distance",this.parameters=Object.assign({radialSegments:!0,openEnded:!0,disableImpostor:!0,labelUnit:{type:"select",rebuild:!0,options:{"":"",angstrom:"angstrom",nm:"nm"}},useCylinder:{type:"boolean",rebuild:!0},atomPair:{type:"hidden",rebuild:!0}},this.parameters),this.init(i)}init(t){const e=t||{};e.linewidth=st(e.linewidth,5),e.radiusType=st(e.radiusType,"size"),e.radiusSize=st(e.radiusSize,.2),this.labelUnit=st(e.labelUnit,""),this.useCylinder=st(e.useCylinder,!1),this.atomPair=st(e.atomPair,[]),super.init(e)}getDistanceData(t,e){let i=e.length;const r=new Array(i);let s=new Float32Array(3*i);const n=new pe,o=new pe,a=new va,c=t.getAtomProxy(),l=t.getAtomProxy();let h=0;const d=t.getAtomSet();e.forEach(((e,i)=>{let u=e[0],m=e[1];if("number"==typeof u&&Number.isInteger(u)&&"number"==typeof m&&Number.isInteger(m)){if(!d.get(u)||!d.get(m))return void(h+=1);c.index=u,l.index=m}else{n.setString(u),o.setString(m);var p=t.getAtomIndices(n),f=t.getAtomIndices(o);if(!p.length||!f.length)return void(h+=1);c.index=p[0],l.index=f[0]}a.addBond(c,l,1),i-=h;var g=c.distanceTo(l);switch(this.labelUnit){case"angstrom":r[i]=g.toFixed(2)+" "+String.fromCharCode(8491);break;case"nm":r[i]=(g/10).toFixed(2)+" nm";break;default:r[i]=g.toFixed(2)}var y=3*i;s[y+0]=(c.x+l.x)/2,s[y+1]=(c.y+l.y)/2,s[y+2]=(c.z+l.z)/2})),h>0&&(i-=h,s=s.subarray(0,3*i));var u=new Os(a.count,!0);return{text:r,position:s,bondSet:u,bondStore:a}}getBondData(t,e,i){const r=t.getBondData(this.getBondParams(e,i));return r.picking&&(r.picking=new to(r.picking.array,r.picking.structure,i.bondStore)),r}createData(t){if(!t.atomCount||!this.atomPair.length)return;const e=this.atomPair.length,i=new s(this.labelColor),r=this.getDistanceData(t,this.atomPair);this.textBuffer=new Eh({position:r.position,size:Si(e,this.labelSize),color:Ci(e,i.r,i.g,i.b),text:r.text},this.getLabelBufferParams());const n={bondSet:r.bondSet,bondStore:r.bondStore},o=this.getBondData(t,{position:!0,color:!0,picking:!0,radius:this.useCylinder},n);return this.useCylinder?this.distanceBuffer=new td(o,this.getBufferParams({openEnded:this.openEnded,radialSegments:this.radialSegments,disableImpostor:this.disableImpostor,dullInterior:!0})):this.distanceBuffer=new Nh(ps(o),this.getBufferParams({linewidth:this.linewidth,visible:this.lineVisible,opacity:this.lineOpacity})),{bondSet:r.bondSet,bondStore:r.bondStore,position:r.position,bufferList:[this.textBuffer,this.distanceBuffer]}}updateData(t,e){super.updateData(t,e);const i={bondSet:e.bondSet,bondStore:e.bondStore},r=this.getBondData(e.sview,t,i),s={};t&&!t.color||Object.assign(s,{color:r.color,color2:r.color2}),t&&!t.radius||Object.assign(s,{radius:r.radius}),this.distanceBuffer.setAttributes(s)}setParameters(t){return super.setParameters(t,{},!1),this.useCylinder||(t&&t.lineOpacity&&this.distanceBuffer.setParameters({opacity:t.lineOpacity}),t&&void 0!==t.opacity&&this.distanceBuffer.setParameters({opacity:this.lineOpacity}),t&&t.linewidth&&this.distanceBuffer.setParameters({linewidth:t.linewidth})),this}}function xd(t){return 2*(t.position.length/3)*3}Ne.add("distance",bd);const vd=Object.assign({scale:1,color:"grey"},zo);class wd extends Go{constructor(t,e={}){super({position:new Float32Array(xd(t)),color:new Float32Array(xd(t))},e),this.isLine=!0,this.vertexShader="Line.vert",this.fragmentShader="Line.frag";const i=new s(this.parameters.color),r=this.geometry.attributes;Ci(xd(t)/3,i.r,i.g,i.b,r.color.array),this.setAttributes(t)}get defaultParameters(){return vd}setAttributes(t={}){const e=this.geometry.attributes;let i,r,s;t.position&&t.vector&&(i=t.position,r=t.vector,s=e.position.array,e.position.needsUpdate=!0);const n=this.size/2,o=this.parameters.scale;if(i&&r)for(let t=0;t<n;t++){const e=2*t*3,n=3*t;s[e+0]=i[n+0],s[e+1]=i[n+1],s[e+2]=i[n+2],s[e+3]=i[n+0]+r[n+0]*o,s[e+4]=i[n+1]+r[n+1]*o,s[e+5]=i[n+2]+r[n+2]*o}}}class Ad extends Sh{constructor(t,e,i){super(t,e,i),this.type="helixorient",this.parameters=Object.assign({sphereDetail:!0,disableImpostor:!0},this.parameters),this.init(i)}init(t){const e=t||{};e.colorScheme=st(e.colorScheme,"sstruc"),e.radiusType=st(e.radiusType,"size"),e.radiusSize=st(e.radiusSize,.15),e.radiusScale=st(e.radiusScale,1),e.useInteriorColor=st(e.useInteriorColor,!0),super.init(e)}createData(t){const e=[],i=[];return this.structure.eachPolymer((t=>{if(t.residueCount<4)return;i.push(t);const r=new Ca(t),s=r.getPosition(),n=r.getColor(this.getColorParams()),o=r.getSize(this.getRadiusParams()),a=r.getPicking();e.push(new Gc({position:s.center,color:n.color,radius:o.size,picking:a.picking},this.getBufferParams({sphereDetail:this.sphereDetail,disableImpostor:this.disableImpostor,dullInterior:!0})),new wd({position:s.center,vector:s.axis},this.getBufferParams({color:"skyblue",scale:1})),new wd({position:s.center,vector:s.resdir},this.getBufferParams({color:"lightgreen",scale:1})))}),t.getSelection()),{bufferList:e,polymerList:i}}updateData(t,e){De&&Me.time(this.type+" repr update"),t=t||{};for(let i=0,r=e.polymerList.length;i<r;++i){const r=3*i,s={},n=e.polymerList[i],o=new Ca(n);if(t.position){const t=o.getPosition();Object.assign(s,{position:t.center}),e.bufferList[r+1].setAttributes({position:t.center,vector:t.axis}),e.bufferList[r+2].setAttributes({position:t.center,vector:t.resdir})}e.bufferList[r].setAttributes(s)}De&&Me.timeEnd(this.type+" repr update")}}Ne.add("helixorient",Ad);class _d extends id{constructor(t,e,i){super(t,e,i),this.type="licorice",this.parameters=Object.assign({},this.parameters,{aspectRatio:null})}init(t){var e=t||{};e.aspectRatio=1,super.init(e)}}Ne.add("licorice",_d),Ve.add("shader/HyperballStickImpostor.vert","\nattribute vec3 mapping;\nattribute float radius;\nattribute float radius2;\nattribute vec3 position1;\nattribute vec3 position2;\nvarying mat4 matrix_near;\nvarying vec4 prime1;\nvarying vec4 prime2;\nvarying float vRadius;\nvarying float vRadius2;\n#ifdef PICKING\n#include unpack_color\nattribute float primitiveId;\nvarying vec3 vPickingColor;\n#else\nattribute vec3 color2;\nvarying vec3 vColor1;\nvarying vec3 vColor2;\n#endif\nuniform float shrink;\nuniform mat4 modelViewProjectionMatrix;\nuniform mat4 modelViewProjectionMatrixInverse;\nvoid main(){\nvRadius = radius;\nvRadius2 = radius2;\nvec4 spaceposition;\nvec3 position_atom1;\nvec3 position_atom2;\nvec4 vertex_position;\n#ifdef PICKING\nvPickingColor = unpackColor( primitiveId );\n#else\nvColor1 = color;\nvColor2 = color2;\n#endif\nfloat radius1 = radius;\nposition_atom1 = position1;\nposition_atom2 = position2;\nfloat distance = distance( position_atom1, position_atom2 );\nspaceposition.z = mapping.z * distance;\nif (radius1 > radius2) {\nspaceposition.y = mapping.y * 1.5 * radius1;\nspaceposition.x = mapping.x * 1.5 * radius1;\n} else {\nspaceposition.y = mapping.y * 1.5 * radius2;\nspaceposition.x = mapping.x * 1.5 * radius2;\n}\nspaceposition.w = 1.0;\nvec4 e3 = vec4( 1.0 );\nvec3 e1, e1_temp, e2, e2_temp;\ne3.xyz = normalize(position_atom1-position_atom2);\nif (e3.z == 0.0) { e3.z = 0.0000000000001;}\nif ( (position_atom1.x - position_atom2.x) == 0.0) { position_atom1.x += 0.001;}\nif ( (position_atom1.y - position_atom2.y) == 0.0) { position_atom1.y += 0.001;}\nif ( (position_atom1.z - position_atom2.z) == 0.0) { position_atom1.z += 0.001;}\nvec4 focus = vec4( 1.0 );\nfocus.x = ( position_atom1.x*position_atom1.x - position_atom2.x*position_atom2.x +\n( radius2*radius2 - radius1*radius1 )*e3.x*e3.x/shrink )/(2.0*(position_atom1.x - position_atom2.x));\nfocus.y = ( position_atom1.y*position_atom1.y - position_atom2.y*position_atom2.y +\n( radius2*radius2 - radius1*radius1 )*e3.y*e3.y/shrink )/(2.0*(position_atom1.y - position_atom2.y));\nfocus.z = ( position_atom1.z*position_atom1.z - position_atom2.z*position_atom2.z +\n( radius2*radius2 - radius1*radius1 )*e3.z*e3.z/shrink )/(2.0*(position_atom1.z - position_atom2.z));\ne1.x = 1.0;\ne1.y = 1.0;\ne1.z = ( (e3.x*focus.x + e3.y*focus.y + e3.z*focus.z) - e1.x*e3.x - e1.y*e3.y)/e3.z;\ne1_temp = e1 - focus.xyz;\ne1 = normalize(e1_temp);\ne2_temp = e1.yzx * e3.zxy - e1.zxy * e3.yzx;\ne2 = normalize(e2_temp);\nmat3 R= mat3( e1.xyz, e2.xyz, e3.xyz );\nvertex_position.xyz = R * spaceposition.xyz;\nvertex_position.w = 1.0;\nvertex_position.x += (position_atom1.x+position_atom2.x) / 2.0;\nvertex_position.y += (position_atom1.y+position_atom2.y) / 2.0;\nvertex_position.z += (position_atom1.z+position_atom2.z) / 2.0;\ngl_Position = modelViewProjectionMatrix * vertex_position;\nvec4 i_near, i_far;\nvec4 near = gl_Position;\nnear.z = 0.0 ;\nnear = modelViewProjectionMatrixInverse * near;\ni_near = near;\nvec4 far = gl_Position;\nfar.z = far.w ;\ni_far = modelViewProjectionMatrixInverse * far;\nprime1 = vec4( position_atom1 - (position_atom1 - focus.xyz)*shrink, 1.0 );\nprime2 = vec4( position_atom2 - (position_atom2 - focus.xyz)*shrink, 1.0 );\nfloat Rsquare = (radius1*radius1/shrink) - (\n(position_atom1.x - focus.x)*(position_atom1.x - focus.x) +\n(position_atom1.y - focus.y)*(position_atom1.y - focus.y) +\n(position_atom1.z - focus.z)*(position_atom1.z - focus.z)\n);\nfocus.w = Rsquare;\nmatrix_near = mat4( i_near, i_far, focus, e3 );\ngl_Position.z = 1.0;\n}"),Ve.add("shader/HyperballStickImpostor.frag","#define STANDARD\n#define IMPOSTOR\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 interiorColor;\nuniform float interiorDarkening;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\nuniform float clipNear;\nuniform float shrink;\nuniform mat4 modelViewMatrix;\nuniform mat4 modelViewProjectionMatrix;\nuniform mat4 modelViewMatrixInverseTranspose;\nuniform mat4 projectionMatrix;\nvarying mat4 matrix_near;\nvarying vec4 prime1;\nvarying vec4 prime2;\nvarying float vRadius;\nvarying float vRadius2;\n#ifdef PICKING\nuniform float objectId;\nvarying vec3 vPickingColor;\n#else\nvarying vec3 vColor1;\nvarying vec3 vColor2;\n#include common\n#include fog_pars_fragment\n#include bsdfs\n#include lights_pars_begin\n#include lights_physical_pars_fragment\n#endif\nbool interior = false;\nfloat calcClip( vec4 cameraPos ){\nreturn dot( cameraPos, vec4( 0.0, 0.0, 1.0, clipNear - 0.5 ) );\n}\nfloat calcClip( vec3 cameraPos ){\nreturn calcClip( vec4( cameraPos, 1.0 ) );\n}\nfloat calcDepth( in vec3 cameraPos ){\nvec2 clipZW = cameraPos.z * projectionMatrix[2].zw + projectionMatrix[3].zw;\nreturn 0.5 + 0.5 * clipZW.x / clipZW.y;\n}\nstruct Ray {\nvec3 origin ;\nvec3 direction ;\n};\nbool cutoff_plane (vec3 M, vec3 cutoff, vec3 x3){\nfloat a = x3.x;\nfloat b = x3.y;\nfloat c = x3.z;\nfloat d = -x3.x*cutoff.x-x3.y*cutoff.y-x3.z*cutoff.z;\nfloat l = a*M.x+b*M.y+c*M.z+d;\nif (l<0.0) {return true;}\nelse{return false;}\n}\nvec3 isect_surf(Ray r, mat4 matrix_coef){\nvec4 direction = vec4(r.direction, 0.0);\nvec4 origin = vec4(r.origin, 1.0);\nfloat a = dot(direction,(matrix_coef*direction));\nfloat b = dot(origin,(matrix_coef*direction));\nfloat c = dot(origin,(matrix_coef*origin));\nfloat delta =b*b-a*c;\ngl_FragColor.a = 1.0;\nif (delta<0.0){\ndiscard;\n}\nfloat t1 =(-b-sqrt(delta))/a;\nreturn r.origin+t1*r.direction;\n}\nvec3 isect_surf2(Ray r, mat4 matrix_coef){\nvec4 direction = vec4(r.direction, 0.0);\nvec4 origin = vec4(r.origin, 1.0);\nfloat a = dot(direction,(matrix_coef*direction));\nfloat b = dot(origin,(matrix_coef*direction));\nfloat c = dot(origin,(matrix_coef*origin));\nfloat delta =b*b-a*c;\ngl_FragColor.a = 1.0;\nif (delta<0.0){\ndiscard;\n}\nfloat t2 =(-b+sqrt(delta))/a;\nreturn r.origin+t2*r.direction;\n}\nRay primary_ray(vec4 near1, vec4 far1){\nvec3 near=near1.xyz/near1.w;\nvec3 far=far1.xyz/far1.w;\nreturn Ray(near,far-near);\n}\nfloat update_z_buffer(vec3 M, mat4 ModelViewP){\nfloat depth1;\nvec4 Ms=(ModelViewP*vec4(M,1.0));\nreturn depth1=(1.0+Ms.z/Ms.w)/2.0;\n}\nvoid main(){\nfloat radius = max( vRadius, vRadius2 );\nvec4 i_near, i_far, focus;\nvec3 e3, e1, e1_temp, e2;\ni_near = vec4(matrix_near[0][0],matrix_near[0][1],matrix_near[0][2],matrix_near[0][3]);\ni_far = vec4(matrix_near[1][0],matrix_near[1][1],matrix_near[1][2],matrix_near[1][3]);\nfocus = vec4(matrix_near[2][0],matrix_near[2][1],matrix_near[2][2],matrix_near[2][3]);\ne3 = vec3(matrix_near[3][0],matrix_near[3][1],matrix_near[3][2]);\ne1.x = 1.0;\ne1.y = 1.0;\ne1.z = ( (e3.x*focus.x + e3.y*focus.y + e3.z*focus.z) - e1.x*e3.x - e1.y*e3.y)/e3.z;\ne1_temp = e1 - focus.xyz;\ne1 = normalize(e1_temp);\ne2 = normalize(cross(e1,e3));\nvec4 equation = focus;\nfloat shrinkfactor = shrink;\nfloat t1 = -1.0/(1.0-shrinkfactor);\nfloat t2 = 1.0/(shrinkfactor);\nvec4 colonne1, colonne2, colonne3, colonne4;\nmat4 mat;\nvec3 equation1 = vec3(t2,t2,t1);\nfloat A1 = - e1.x*equation.x - e1.y*equation.y - e1.z*equation.z;\nfloat A2 = - e2.x*equation.x - e2.y*equation.y - e2.z*equation.z;\nfloat A3 = - e3.x*equation.x - e3.y*equation.y - e3.z*equation.z;\nfloat A11 = equation1.x*e1.x*e1.x + equation1.y*e2.x*e2.x + equation1.z*e3.x*e3.x;\nfloat A21 = equation1.x*e1.x*e1.y + equation1.y*e2.x*e2.y + equation1.z*e3.x*e3.y;\nfloat A31 = equation1.x*e1.x*e1.z + equation1.y*e2.x*e2.z + equation1.z*e3.x*e3.z;\nfloat A41 = equation1.x*e1.x*A1 + equation1.y*e2.x*A2 + equation1.z*e3.x*A3;\nfloat A22 = equation1.x*e1.y*e1.y + equation1.y*e2.y*e2.y + equation1.z*e3.y*e3.y;\nfloat A32 = equation1.x*e1.y*e1.z + equation1.y*e2.y*e2.z + equation1.z*e3.y*e3.z;\nfloat A42 = equation1.x*e1.y*A1 + equation1.y*e2.y*A2 + equation1.z*e3.y*A3;\nfloat A33 = equation1.x*e1.z*e1.z + equation1.y*e2.z*e2.z + equation1.z*e3.z*e3.z;\nfloat A43 = equation1.x*e1.z*A1 + equation1.y*e2.z*A2 + equation1.z*e3.z*A3;\nfloat A44 = equation1.x*A1*A1 + equation1.y*A2*A2 + equation1.z*A3*A3 - equation.w;\ncolonne1 = vec4(A11,A21,A31,A41);\ncolonne2 = vec4(A21,A22,A32,A42);\ncolonne3 = vec4(A31,A32,A33,A43);\ncolonne4 = vec4(A41,A42,A43,A44);\nmat = mat4(colonne1,colonne2,colonne3,colonne4);\nRay ray = primary_ray(i_near,i_far) ;\nvec3 M;\nM = isect_surf(ray, mat);\nif (cutoff_plane(M, prime1.xyz, -e3) || cutoff_plane(M, prime2.xyz, e3)){ discard; }\nvec4 M1 = vec4(M,1.0);\nvec4 M2 = mat*M1;\nvec3 _normal = ( modelViewMatrixInverseTranspose * M2 ).xyz;\ngl_FragDepthEXT = update_z_buffer(M, modelViewProjectionMatrix) ;\n#ifdef NEAR_CLIP\nif( calcClip( modelViewMatrix * vec4( M, 1.0 ) ) > 0.0 ){\nM = isect_surf2(ray, mat);\nif( calcClip( modelViewMatrix * vec4( M, 1.0 ) ) > 0.0 )\ndiscard;\ninterior = true;\ngl_FragDepthEXT = update_z_buffer(M, modelViewProjectionMatrix) ;\nif( gl_FragDepthEXT >= 0.0 ){\ngl_FragDepthEXT = max( 0.0, calcDepth( vec3( - ( clipNear - 0.5 ) ) ) + ( 0.0000001 / radius ) );\n}\n}else if( gl_FragDepthEXT <= 0.0 ){\nM = isect_surf2(ray, mat);\ninterior = true;\ngl_FragDepthEXT = update_z_buffer(M, modelViewProjectionMatrix);\nif( gl_FragDepthEXT >= 0.0 ){\ngl_FragDepthEXT = 0.0 + ( 0.0000001 / radius );\n}\n}\n#else\nif( gl_FragDepthEXT <= 0.0 ){\nM = isect_surf2(ray, mat);\ninterior = true;\ngl_FragDepthEXT = update_z_buffer(M, modelViewProjectionMatrix) ;\nif( gl_FragDepthEXT >= 0.0 ){\ngl_FragDepthEXT = 0.0 + ( 0.0000001 / radius );\n}\n}\n#endif\nif (cutoff_plane(M, prime1.xyz, -e3) || cutoff_plane(M, prime2.xyz, e3)){ discard; }\nif (gl_FragDepthEXT < 0.0)\ndiscard;\nif (gl_FragDepthEXT > 1.0)\ndiscard;\nfloat distance_ratio = ((M.x-prime2.x)*e3.x + (M.y-prime2.y)*e3.y +(M.z-prime2.z)*e3.z) /\ndistance(prime2.xyz,prime1.xyz);\n#ifdef PICKING\nif( opacity < 0.3 )\ndiscard;\ngl_FragColor = vec4( vPickingColor, objectId );\n#else\nvec3 vViewPosition = -( modelViewMatrix * vec4( M, 1.0 ) ).xyz;\nvec3 vNormal = _normal;\nvec3 vColor;\nif( distance_ratio>0.5 ){\nvColor = vColor1;\n}else{\nvColor = vColor2;\n}\nvec4 diffuseColor = vec4( diffuse, opacity );\nReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\nvec3 totalEmissiveLight = emissive;\n#include color_fragment\n#include roughnessmap_fragment\n#include metalnessmap_fragment\nvec3 normal = normalize( vNormal );\nvec3 geometryNormal = normal;\n#include lights_physical_fragment\n#include lights_fragment_begin\n#include lights_fragment_end\nvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveLight;\nif( interior ){\n#ifdef USE_INTERIOR_COLOR\noutgoingLight.xyz = interiorColor;\n#else\n#ifdef DIFFUSE_INTERIOR\noutgoingLight.xyz = vColor;\n#endif\n#endif\noutgoingLight.xyz *= 1.0 - interiorDarkening;\n}\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );\n#include premultiplied_alpha_fragment\n#include tonemapping_fragment\n#include encodings_fragment\n#include fog_fragment\n#endif\n}");const Sd=new Float32Array([-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,-1,1,-1,1,1,-1,1,1,1,-1,1,1]),Cd=new Uint16Array([0,1,2,0,2,3,1,5,6,1,6,2,4,6,5,4,7,6,0,7,4,0,3,7,0,5,1,0,4,5,3,2,6,3,6,7]);class Pd extends Fc{constructor(t,e={}){super("v3",t,e)}get mapping(){return Sd}get mappingIndices(){return Cd}get mappingIndicesSize(){return 36}get mappingSize(){return 8}get mappingItemSize(){return 3}}const Id=Object.assign({shrink:.14},zo),kd=Object.assign({shrink:{uniform:!0}},Vo);class Md extends Pd{constructor(t,e={}){super(t,e),this.parameterTypes=kd,this.isImpostor=!0,this.vertexShader="HyperballStickImpostor.vert",this.fragmentShader="HyperballStickImpostor.frag",this.addUniforms({modelViewProjectionMatrix:{value:new i},modelViewProjectionMatrixInverse:{value:new i},modelViewMatrixInverseTranspose:{value:new i},shrink:{value:this.parameters.shrink}}),this.addAttributes({position1:{type:"v3",value:null},position2:{type:"v3",value:null},color2:{type:"c",value:null},radius:{type:"f",value:null},radius2:{type:"f",value:null}}),this.setAttributes(t),this.makeMapping()}get defaultParameters(){return Id}}Object.assign({disableImpostor:!1},Hh,Id);const Td=class{constructor(t,e={}){return!Ie||e&&e.disableImpostor?(t.radius=function(t,e){const i=t.length,r=new Float32Array(i);for(let s=0;s<i;s++)r[s]=Math.min(t[s],e[s]);return r}(t.radius,t.radius2),new qh(t,e)):new Md(t,e)}};class Bd extends _d{constructor(t,e,i){super(t,e,i),this.type="hyperball",this.parameters=Object.assign({shrink:{type:"number",precision:3,max:1,min:.001,buffer:!0}},this.parameters,{multipleBond:null,bondSpacing:null})}init(t){var e=t||{};e.radiusScale=st(e.radiusScale,.2),e.radiusType=st(e.radiusType,"vdw"),e.useInteriorColor=st(e.useInteriorColor,!0),this.shrink=st(e.shrink,.12),super.init(e)}getBondParams(t,e){return t&&!t.radius||(e=Object.assign({radius2:!0},e)),super.getBondParams(t,e)}createData(t){var e=new Gc(t.getAtomData(this.getAtomParams()),this.getBufferParams({sphereDetail:this.sphereDetail,disableImpostor:this.disableImpostor,dullInterior:!0}));return this.__center=new Float32Array(3*t.bondCount),{bufferList:[e,new Td(t.getBondData(this.getBondParams()),this.getBufferParams({shrink:this.shrink,radialSegments:this.radialSegments,disableImpostor:this.disableImpostor,dullInterior:!0}))]}}updateData(t,e){var i=e.sview.getAtomData(this.getAtomParams()),r=e.sview.getBondData(this.getBondParams()),s={},n={};if(!t||t.position){Object.assign(s,{position:i.position});var o=r.position1,a=r.position2;Object.assign(n,{position:Ai(o,a,this.__center),position1:o,position2:a})}t&&!t.color||(Object.assign(s,{color:i.color}),Object.assign(n,{color:r.color,color2:r.color2})),t&&!t.radius||(Object.assign(s,{radius:i.radius}),Object.assign(n,{radius:r.radius,radius2:r.radius2})),e.bufferList[0].setAttributes(s),e.bufferList[1].setAttributes(n)}}Ne.add("hyperball",Bd);class Dd{constructor(t,e={},i=""){this.type=t,this.text=e,this.format=i,this.errorLogged=!1}atomLabel(t){let e;switch(this.type){case"atomname":e=t.atomname;break;case"atomindex":e=`${t.index}`;break;case"occupancy":e=t.occupancy.toFixed(2);break;case"bfactor":e=t.bfactor.toFixed(2);break;case"serial":e=`${t.serial}`;break;case"element":e=t.element;break;case"atom":e=`${t.atomname}|${t.index}`;break;case"resname":e=t.resname;break;case"resno":e=`${t.resno}`;break;case"res":e=`${en[t.resname.toUpperCase()]||t.resname}${t.resno}`;break;case"residue":const i=en[t.resname.toUpperCase()];e=i&&!t.inscode?`${i}${t.resno}`:`[${t.resname}]${t.resno}${t.inscode}`;break;case"text":e=this.text[t.index];break;case"format":try{e=Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])(this.format,t)}catch(t){this.errorLogged||(this.errorLogged=!0,console.log(t.message))}break;default:e=t.qualifiedName()}return void 0===e?"":e}}Dd.types={"":"",atomname:"atom name",atomindex:"atom index",occupancy:"occupancy",bfactor:"b-factor",serial:"serial",element:"element",atom:"atom name + index",resname:"residue name",resno:"residue no",res:"one letter code + no",residue:"[residue name] + no + inscode",text:"text",format:"format",qualified:"qualified name"};class $d extends Sh{constructor(t,e,i){super(t,e,i),this.type="label",this.parameters=Object.assign({labelType:{type:"select",options:Dd.types,rebuild:!0},labelText:{type:"hidden",rebuild:!0},labelFormat:{type:"text",rebuild:!0},labelGrouping:{type:"select",options:{atom:"atom",residue:"residue"},rebuild:!0},fontFamily:{type:"select",options:{"sans-serif":"sans-serif",monospace:"monospace",serif:"serif"},buffer:!0},fontStyle:{type:"select",options:{normal:"normal",italic:"italic"},buffer:!0},fontWeight:{type:"select",options:{normal:"normal",bold:"bold"},buffer:!0},xOffset:{type:"number",precision:1,max:20,min:-20,buffer:!0},yOffset:{type:"number",precision:1,max:20,min:-20,buffer:!0},zOffset:{type:"number",precision:1,max:20,min:-20,buffer:!0},attachment:{type:"select",options:{"bottom-left":"bottom-left","bottom-center":"bottom-center","bottom-right":"bottom-right","middle-left":"middle-left","middle-center":"middle-center","middle-right":"middle-right","top-left":"top-left","top-center":"top-center","top-right":"top-right"},rebuild:!0},showBorder:{type:"boolean",buffer:!0},borderColor:{type:"color",buffer:!0},borderWidth:{type:"number",precision:2,max:.3,min:0,buffer:!0},showBackground:{type:"boolean",rebuild:!0},backgroundColor:{type:"color",buffer:!0},backgroundMargin:{type:"number",precision:2,max:2,min:0,rebuild:!0},backgroundOpacity:{type:"range",step:.01,max:1,min:0,buffer:!0},fixedSize:{type:"boolean",buffer:!0}},this.parameters,{side:null,flatShaded:null,wireframe:null,linewidth:null,roughness:null,metalness:null,diffuse:null}),this.init(i)}init(t){const e=t||{};this.labelType=st(e.labelType,"res"),this.labelText=st(e.labelText,{}),this.labelFormat=st(e.labelFormat,""),this.labelGrouping=st(e.labelGrouping,"atom"),this.fontFamily=st(e.fontFamily,"sans-serif"),this.fontStyle=st(e.fontStyle,"normal"),this.fontWeight=st(e.fontWeight,"bold"),this.xOffset=st(e.xOffset,0),this.yOffset=st(e.yOffset,0),this.zOffset=st(e.zOffset,.5),this.attachment=st(e.attachment,"bottom-left"),this.showBorder=st(e.showBorder,!1),this.borderColor=st(e.borderColor,"lightgrey"),this.borderWidth=st(e.borderWidth,.15),this.showBackground=st(e.showBackground,!1),this.backgroundColor=st(e.backgroundColor,"lightgrey"),this.backgroundMargin=st(e.backgroundMargin,.5),this.backgroundOpacity=st(e.backgroundOpacity,1),this.fixedSize=st(e.fixedSize,!1),super.init(e)}getTextData(t,e){const i=this.getAtomParams(e),r=new Dd(this.labelType,this.labelText,this.labelFormat);let s,n,o,a,c,l,h;if("atom"===this.labelGrouping){const c=t.getAtomData(i);s=c.position,n=c.radius,o=c.color,e&&!e.text||(a=[],t.eachAtom((t=>a.push(r.atomLabel(t)))))}else if("residue"===this.labelGrouping){e&&!e.position||(c=[]),e&&!e.color||(h=[]),e&&!e.radius||(l=[]),e&&!e.text||(a=[]),i.colorParams&&(i.colorParams.structure=t.getStructure());const d=Fe.getScheme(i.colorParams),u=new pa(i.radiusParams),m=t.getAtomProxy();let p=0;t.eachResidue((t=>{const i=3*p;t.isProtein()||t.isNucleic()?(m.index=t.traceAtomIndex,e&&!e.position||m.positionToArray(c,i)):(m.index=t.atomOffset,e&&!e.position||t.positionToArray(c,i)),e&&!e.color||d.atomColorToArray(m,h,i),e&&!e.radius||(l[p]=u.atomRadius(m)),e&&!e.text||a.push(r.atomLabel(m)),++p})),e&&!e.position||(s=new Float32Array(c)),e&&!e.color||(o=new Float32Array(h)),e&&!e.radius||(n=new Float32Array(l))}return{position:s,size:n,color:o,text:a}}createData(t){return{bufferList:[new Eh(this.getTextData(t,{position:!0,color:!0,radius:!0,text:!0}),this.getBufferParams({fontFamily:this.fontFamily,fontStyle:this.fontStyle,fontWeight:this.fontWeight,xOffset:this.xOffset,yOffset:this.yOffset,zOffset:this.zOffset,attachment:this.attachment,showBorder:this.showBorder,borderColor:this.borderColor,borderWidth:this.borderWidth,showBackground:this.showBackground,backgroundColor:this.backgroundColor,backgroundMargin:this.backgroundMargin,backgroundOpacity:this.backgroundOpacity,fixedSize:this.fixedSize}))]}}updateData(t,e){e.bufferList[0].setAttributes(this.getTextData(e.sview,t))}getAtomRadius(){return 0}}function Od(t){const e=t.getAtomSet(),i=t.getBondSet(),r=t.getBondProxy();return i.forEach((function(t){r.index=t,e.clear(r.atomIndex1),e.clear(r.atomIndex2)})),e}Ne.add("label",$d);class Rd extends Sh{constructor(t,e,i){super(t,e,i),this.type="line",this.parameters=Object.assign({multipleBond:{type:"select",rebuild:!0,options:{off:"off",symmetric:"symmetric",offset:"offset"}},bondSpacing:{type:"number",precision:2,max:2,min:.5},linewidth:{type:"integer",max:50,min:1,buffer:!0},lines:{type:"boolean",rebuild:!0},crosses:{type:"select",rebuild:!0,options:{off:"off",lone:"lone",all:"all"}},crossSize:{type:"number",precision:2,max:2,min:.1}},this.parameters,{flatShaded:null,side:null,wireframe:null,roughness:null,metalness:null}),this.init(i)}init(t){var e=t||{};this.multipleBond=st(e.multipleBond,"off"),this.bondSpacing=st(e.bondSpacing,1),this.linewidth=st(e.linewidth,2),this.lines=st(e.lines,!0),this.crosses=st(e.crosses,"lone"),this.crossSize=st(e.crossSize,.4),super.init(e)}getAtomRadius(t){return.1}getBondParams(t,e){return e=Object.assign({multipleBond:this.multipleBond,bondSpacing:this.bondSpacing,radiusParams:{type:"size",size:.1,scale:1}},e),super.getBondParams(t,e)}_crossData(t,e){if(t&&!t.position&&!t.color)return;const i={};"lone"===this.crosses&&Object.assign(i,{atomSet:Od(e)});const r=e.getAtomData(this.getAtomParams(t,i)),s={},n=r.position,o=r.color,a=r.picking,c=(n||o).length,l=3*c;let h=new Float32Array(0),d=new Float32Array(0),u=new Float32Array(0),m=new Float32Array(0),p=0,f=new Float32Array(0);t&&!t.position||(h=s.position1=new Float32Array(l),d=s.position2=new Float32Array(l),p=this.crossSize/2),t&&!t.color||(u=s.color=new Float32Array(l),m=s.color2=new Float32Array(l)),t&&!t.picking||(f=new Float32Array(3*r.picking.array.length));for(let e=0;e<c;e++){const i=3*e,r=3*i;if(!t||t.position){const t=n[i],e=n[i+1],s=n[i+2];h[r]=t-p,h[r+1]=e,h[r+2]=s,d[r]=t+p,d[r+1]=e,d[r+2]=s,h[r+3]=t,h[r+4]=e-p,h[r+5]=s,d[r+3]=t,d[r+4]=e+p,d[r+5]=s,h[r+6]=t,h[r+7]=e,h[r+8]=s-p,d[r+6]=t,d[r+7]=e,d[r+8]=s+p}if(!t||t.color){const t=r+9;for(let e=r;e<t;e+=3)u[e]=m[e]=o[i],u[e+1]=m[e+1]=o[i+1],u[e+2]=m[e+2]=o[i+2]}t&&!t.picking||(f[i]=f[i+1]=f[i+2]=a.array[e])}return t&&!t.picking||(s.picking=new Yn(f,a.structure)),s}createData(t){const e={position:!0,color:!0,picking:!0},i=[];if(this.lines){const r=t.getBondData(this.getBondParams(e)),s=new Nh(r,this.getBufferParams({linewidth:this.linewidth}));i.push(s)}if("off"!==this.crosses){const r=new Nh(this._crossData(e,t),this.getBufferParams({linewidth:this.linewidth}));i.push(r)}return{bufferList:i}}updateData(t,e){let i=0;if(this.lines){const r=e.sview.getBondData(this.getBondParams(t)),s={};t&&!t.position||Object.assign(s,{position1:r.position1,position2:r.position2}),t&&!t.color||Object.assign(s,{color:r.color,color2:r.color2}),e.bufferList[i++].setAttributes(s)}if("off"!==this.crosses){const r=this._crossData(t,e.sview),s={};t&&!t.position||Object.assign(s,{position1:r.position1,position2:r.position2}),t&&!t.color||Object.assign(s,{color:r.color,color2:r.color2}),e.bufferList[i++].setAttributes(s)}}setParameters(t){var e={};return t&&(t.bondSpacing||t.crossSize)&&Object.assign(e,{position:!0}),super.setParameters(t,e,!1),this}}function Ed(t,e,i,r,s){const n=new(r=r||Int32Array)(t*e*i*(s=s||1));function o(t,r,n){return((t*e+r)*i+n)*s}return{data:n,index:o,set:function(t,e,i,...r){const a=o(t,e,i);for(let t=0;t<s;++t)n[a+t]=r[t]},toArray:function(t,e,i,r=[],a=0){const c=o(t,e,i);for(let t=0;t<s;++t)r[a+t]=n[c+t]},fromArray:function(t,e,i,r,a=0){const c=o(t,e,i);for(let t=0;t<s;++t)n[c+t]=r[a+t]},copy:function(t){n.set(t.data)}}}function Fd(t,e,i){var r=Do(e),s=Hr(t);0===t.length&&(s[0].set([0,0,0]),s[1].set([0,0,0]));var n,o,a,c,l,h,d,u,m,p,f,g,y,b,x,v=s[0],w=s[1];function A(t,e,i,s,A){n=e||1.4,o=i||2,g=A||!0;var _=0;for(var S in r)_=Math.max(_,S);var C=$o(v,w,_,o,t?n:0);c=C.dim[0],l=C.dim[1],h=C.dim[2],d=C.matrix,u=C.tran,o=C.scaleFactor,m={},p={},I(t),f=n*o,a=s||n/o,y=new Uint8Array(c*l*h),t&&(b=new Float64Array(c*l*h)),g&&(x=new Int32Array(c*l*h))}var _=1,S=2,C=4,P=[new Int32Array([1,0,0]),new Int32Array([-1,0,0]),new Int32Array([0,1,0]),new Int32Array([0,-1,0]),new Int32Array([0,0,1]),new Int32Array([0,0,-1]),new Int32Array([1,1,0]),new Int32Array([1,-1,0]),new Int32Array([-1,1,0]),new Int32Array([-1,-1,0]),new Int32Array([1,0,1]),new Int32Array([1,0,-1]),new Int32Array([-1,0,1]),new Int32Array([-1,0,-1]),new Int32Array([0,1,1]),new Int32Array([0,1,-1]),new Int32Array([0,-1,1]),new Int32Array([0,-1,-1]),new Int32Array([1,1,1]),new Int32Array([1,1,-1]),new Int32Array([1,-1,1]),new Int32Array([-1,1,1]),new Int32Array([1,-1,-1]),new Int32Array([-1,-1,1]),new Int32Array([-1,1,-1]),new Int32Array([-1,-1,-1])];function I(t){var e,i,s,a,c,l,h,d,u,f;for(var g in r)if(e=parseFloat(g),!m[g]){for(l=(h=t?(e+n)*o+.5:e*o+.5)*h,d=Math.floor(h)+1,u=new Int32Array(d*d),f=0,i=0;i<d;++i)for(s=0;s<d;++s)(a=i*i+s*s)>l?u[f]=-1:(c=Math.sqrt(l-a),u[f]=Math.floor(c)),++f;p[g]=d,m[g]=u}}function k(i){var r,s,n,a,d,f,b,v,w,A,S,C,P,I,k,M,T,B,D=3*i,$=i;r=Math.floor(.5+o*(t[D]+u[0])),s=Math.floor(.5+o*(t[D+1]+u[1])),n=Math.floor(.5+o*(t[D+2]+u[2]));var O,R=e[$],E=m[R],F=0,L=l*h,N=p[R];for(A=0;A<N;++A)for(S=0;S<N;++S){if(-1!==(O=E[F]))for(M=-1;M<2;++M)for(T=-1;T<2;++T)for(B=-1;B<2;++B)if(0!==M&&0!==T&&0!==B)for(b=M*A,w=B*S,C=0;C<=O;++C)if(I=s+(v=C*T),k=n+w,!((P=r+b)<0||I<0||k<0||P>=c||I>=l||k>=h)){var z=P*L+I*h+k;if(g)if(y[z]&_){if(y[z]&_){var V=x[z];V!==D&&b*b+v*v+w*w<(a=r+b-Math.floor(.5+o*(t[V]+u[0])))*a+(d=s+v-Math.floor(.5+o*(t[V+1]+u[1])))*d+(f=n+w-Math.floor(.5+o*(t[V+2]+u[2])))*f&&(x[z]=i)}}else y[z]|=_,x[z]=i;else y[z]|=_}F++}}function M(e){var i,r;for(console.time("EDTSurface fillvoxels"),i=0,r=y.length;i<r;++i)y[i]=0,e&&(b[i]=-1),g&&(x[i]=-1);for(i=0,r=t.length/3;i<r;++i)k(i);for(i=0,r=y.length;i<r;++i)y[i]&_&&(y[i]|=S);console.timeEnd("EDTSurface fillvoxels")}function T(i){var r,s,n,a,d,f,b,v,w,A,_,C,P,I,k,M,T,B,D,$=3*i,O=i,R=0;r=Math.floor(.5+o*(t[$]+u[0])),s=Math.floor(.5+o*(t[$+1]+u[1])),n=Math.floor(.5+o*(t[$+2]+u[2]));var E=e[O],F=l*h;for(P=0,D=p[E];P<D;++P)for(I=0;I<D;++I){if(-1!==m[E][R])for(M=-1;M<2;++M)for(T=-1;T<2;++T)for(B=-1;B<2;++B)if(0!==M&&0!==T&&0!==B)for(b=M*P,w=B*I,k=0;k<=m[E][R];++k)if(_=s+(v=k*T),C=n+w,!((A=r+b)<0||_<0||C<0||A>=c||_>=l||C>=h)){var L=A*F+_*h+C;if(y[L]&S){if(g){var N=x[L];b*b+v*v+w*w<(a=Math.floor(.5+o*(t[N]+u[0])))*a+(d=Math.floor(.5+o*(t[N+1]+u[1])))*d+(f=Math.floor(.5+o*(t[N+2]+u[2])))*f&&(x[L]=i)}}else y[L]|=S,g&&(x[L]=i)}R++}}function B(){var t,e,i,r;console.time("EDTSurface fastdistancemap");var s,n=Ed(c,l,h,Uint16Array,3),o=l*h,d=f*f,u=0;for(t=0;t<c;++t)for(e=0;e<l;++e)for(i=0;i<h;++i)y[s=t*o+e*h+i]&=~S,y[s]&_&&y[s]&C&&(n.set(t,e,i,t,e,i),b[s]=0,y[s]|=S,u+=1);var m=new Int32Array(3*u),p=0,v=new Int32Array(3*u),w=0;for(t=0;t<c;++t)for(e=0;e<l;++e)for(i=0;i<h;++i)y[s=t*o+e*h+i]&C&&(m[p]=t,m[p+1]=e,m[p+2]=i,p+=3,y[s]&=~C);do{for(w=D(m,n,p,v),p=0,t=0,r=w;t<r;t+=3)s=o*v[t]+h*v[t+1]+v[t+2],y[s]&=~C,b[s]<=1.0404*d&&(m[p]=v[t],m[p+1]=v[t+1],m[p+2]=v[t+2],p+=3)}while(p>0);var A,P=a*a,I=new Uint16Array(3);for(t=0;t<c;++t)for(e=0;e<l;++e)for(i=0;i<h;++i)y[s=t*o+e*h+i]&=~C,y[s]&_&&(y[s]&S&&!(y[s]&S&&b[s]>=P)||(y[s]|=C,g&&y[s]&S&&(n.toArray(t,e,i,I),A=I[0]*o+I[1]*h+I[2],x[s]=x[A])));console.timeEnd("EDTSurface fastdistancemap")}function D(t,e,i,r){var s,n,o,a,d,u,m,p,f,g,x,v,w=new Uint16Array(3),A=0;if(0===i)return A;var I=-1,k=-1,M=-1,T=l*h;for(m=0,f=i;m<f;m+=3)for(s=t[m],n=t[m+1],o=t[m+2],e.toArray(s,n,o,w),p=0;p<6;++p)I=s+(v=P[p])[0],k=n+v[1],M=o+v[2],I<c&&I>-1&&k<l&&k>-1&&M<h&&M>-1&&(y[x=I*T+h*k+M]&_&&!(y[x]&S)?(e.fromArray(I,k,M,w),g=(a=I-w[0])*a+(d=k-w[1])*d+(u=M-w[2])*u,b[x]=g,y[x]|=S,y[x]|=C,r[A]=I,r[A+1]=k,r[A+2]=M,A+=3):y[x]&_&&y[x]&S&&(g=(a=I-w[0])*a+(d=k-w[1])*d+(u=M-w[2])*u)<b[x]&&(e.fromArray(I,k,M,w),b[x]=g,y[x]&C||(y[x]|=C,r[A]=I,r[A+1]=k,r[A+2]=M,A+=3)));for(m=0,f=i;m<f;m+=3)for(s=t[m],n=t[m+1],o=t[m+2],e.toArray(s,n,o,w),p=6;p<18;p++)I=s+(v=P[p])[0],k=n+v[1],M=o+v[2],I<c&&I>-1&&k<l&&k>-1&&M<h&&M>-1&&(y[x=I*T+h*k+M]&_&&!(y[x]&S)?(e.fromArray(I,k,M,w),g=(a=I-w[0])*a+(d=k-w[1])*d+(u=M-w[2])*u,b[x]=g,y[x]|=S,y[x]|=C,r[A]=I,r[A+1]=k,r[A+2]=M,A+=3):y[x]&_&&y[x]&S&&(g=(a=I-w[0])*a+(d=k-w[1])*d+(u=M-w[2])*u)<b[x]&&(e.fromArray(I,k,M,w),b[x]=g,y[x]&C||(y[x]|=C,r[A]=I,r[A+1]=k,r[A+2]=M,A+=3)));for(m=0,f=i;m<f;m+=3)for(s=t[m],n=t[m+1],o=t[m+2],e.toArray(s,n,o,w),p=18;p<26;p++)I=s+(v=P[p])[0],k=n+v[1],M=o+v[2],I<c&&I>-1&&k<l&&k>-1&&M<h&&M>-1&&(y[x=I*T+h*k+M]&_&&!(y[x]&S)?(e.fromArray(I,k,M,w),g=(a=I-w[0])*a+(d=k-w[1])*d+(u=M-w[2])*u,b[x]=g,y[x]|=S,y[x]|=C,r[A]=I,r[A+1]=k,r[A+2]=M,A+=3):y[x]&_&&y[x]&S&&(g=(a=I-w[0])*a+(d=k-w[1])*d+(u=M-w[2])*u)<b[x]&&(e.fromArray(I,k,M,w),b[x]=g,y[x]&C||(y[x]|=C,r[A]=I,r[A+1]=k,r[A+2]=M,A+=3)));return A}this.getVolume=function(e,r,s,n,o){console.time("EDTSurface.getVolume");var a="vws"!==e;A(a,r,s,n,o),M(a),function(){var t,e,i,r=l*h;for(t=0;t<c;++t)for(e=0;e<h;++e)for(i=0;i<l;++i){var s=t*r+i*h+e;if(y[s]&_)for(var n=0;n<26;){var o=t+P[n][0],a=e+P[n][2],d=i+P[n][1];if(o>-1&&o<c&&d>-1&&d<l&&a>-1&&a<h&&!(y[o*r+d*h+a]&_)){y[s]|=C;break}n++}}}(),"ms"!==e&&"ses"!==e||B(),"ses"===e&&(I(!1),function(){var e,i;for(e=0,i=y.length;e<i;++e)y[e]&=~S;for(e=0,i=t.length/3;e<i;++e)T(e)}()),function(t){var e,i=y.length;if("vws"===t)for(e=0;e<i;++e)y[e]&=~C,y[e]=y[e]&S?1:0;else if("ms"===t)for(e=0;e<i;++e)y[e]&=~S,y[e]&C&&(y[e]|=S),y[e]&=~C,y[e]=y[e]&S?1:0;else if("ses"===t)for(e=0;e<i;++e)y[e]&C&&y[e]&S?y[e]&=~C:y[e]&C&&!(y[e]&S)&&(y[e]|=S),y[e]=y[e]&S?1:0;else if("sas"===t)for(e=0;e<i;++e)y[e]&=~C,y[e]=y[e]&S?1:0}(e);for(var d=0,u=x.length;d<u;++d)x[d]=i[x[d]];return console.timeEnd("EDTSurface.getVolume"),{data:y,nx:h,ny:l,nz:c,atomindex:x}},this.getSurface=function(t,e,i,r,s,n,o){var a=this.getVolume(t,e,i,r,s);return new Ro(a.data,a.nx,a.ny,a.nz,a.atomindex).getSurface(1,n,void 0,d,o)}}function Ld(t,e,i,r,s,n,o){o=Math.max(.1,o);var a=t.length,c=s[0],l=s[1],h=s[2],d=n[0],u=n[1],m=n[2];function p(t,e){return Math.floor((t-e)/o)}for(var f,g,y,b=p(d,c)+1,x=p(u,l)+1,v=p(m,h)+1,w=b*x*v,A=x*v,_=[],S=0;S<a;S++){var C=(f=t[S],g=e[S],y=i[S],(p(f,c)*x+p(g,l))*v+p(y,h));void 0===_[C]?_[C]=[S]:_[C].push(S)}var P=new Uint32Array(w),I=new Uint16Array(w),k=new Uint32Array(a),M=0,T=0;for(S=0;S<w;S++){var B=P[S]=M,D=_[S];if(void 0!==D)for(var $=0;$<D.length;$++)k[M]=D[$],M++;var O=M-B;I[S]=O,O>T&&(T=O)}return{neighbourListLength:27*T+1,withinRadii:function(s,n,o,a,d){for(var u=0,m=p(s,c),f=p(n,l),g=p(o,h),y=Math.max(0,m-1),w=Math.max(0,f-1),_=Math.max(0,g-1),S=Math.min(b,m+2),C=Math.min(x,f+2),M=Math.min(v,g+2),T=y;T<S;++T)for(var B=T*A,D=w;D<C;++D)for(var $=D*v,O=_;O<M;++O)for(var R=B+$+O,E=P[R],F=E+I[R],L=E;L<F;L++){var N=k[L],z=t[N]-s,V=e[N]-n,G=i[N]-o,U=r[N]+a;z*z+V*V+G*G<=U*U&&(d[u++]=k[L])}d[u]=-1}}}function Nd(t,e,i){const r=e.length,s=new Float32Array(r),n=new Float32Array(r),o=new Float32Array(r);for(let e=0;e<r;e++){const i=3*e;s[e]=t[i],n[e]=t[i+1],o[e]=t[i+2]}let a=Hr(t);0===t.length&&(a[0].set([0,0,0]),a[1].set([0,0,0]));const c=a[0],l=a[1];let h,d,u,m,p,f,g,y,b,x,v,w,A,_,S,C,P,I,k=-1;const M=new Float32Array([0,0,0]),T=new Float32Array([0,0,0]),B=new Float32Array([0,0,0]),D=new Float32Array([0,0,0]);let $;function O(t,i,a,M){m=st(t,1.4),p=st(i,2),f=st(a,!0),g=st(M,30),h=new Float32Array(r),d=new Float32Array(r);for(let t=0;t<h.length;++t){var T=e[t]+m;h[t]=T,d[t]=T*T}u=0;for(let t=0;t<h.length;++t)h[t]>u&&(u=h[t]);!function(){const t=$o(c,l,u,p,0);p=t.scaleFactor,y=t.dim,b=t.matrix,$=Math.max(5,2+Math.floor(m*p)),x=Si(y[0]*y[1]*y[2],-1001),v=new Int32Array(x.length),w=new Float32Array(y[0]),A=new Float32Array(y[1]),_=new Float32Array(y[2]),R(w,c[0],1/p),R(A,c[1],1/p),R(_,c[2],1/p)}(),function(){var t=0,e=2*Math.PI/g;C=new Float32Array(g),S=new Float32Array(g);for(var i=0;i<g;i++)C[i]=Math.cos(t),S[i]=Math.sin(t),t+=e}(),P=Ld(s,n,o,h,c,l,2.01*u),I=new Int32Array(P.neighbourListLength),k=-1}function R(t,e,i){for(let r=0;r<t.length;r++)t[r]=e+i*r}function E(t,e,i,r,s){let n;if(-1!==k){if(n=k,n!==r&&n!==s&&F(n,t,e,i))return n;k=-1}var o=0;for(n=I[o];n>=0;){if(n!==r&&n!==s&&F(n,t,e,i))return k=n,n;n=I[++o]}return k=-1,-1}function F(e,i,r,s){var n=3*e,o=d[e],a=t[n]-i,c=t[n+1]-r,l=t[n+2]-s;return a*a+c*c+l*l<o}function L(){for(var t=0;t<r;t++){var e=s[t],i=n[t],a=o[t],l=h[t],u=d[t];P.withinRadii(e,i,a,l,I);for(var m=Math.ceil(l*p),g=Math.floor(p*(e-c[0])),b=Math.floor(p*(i-c[1])),S=Math.floor(p*(a-c[2])),C=Math.max(0,g-m),k=Math.max(0,b-m),M=Math.max(0,S-m),T=Math.min(y[0],g+m+2),B=Math.min(y[1],b+m+2),D=Math.min(y[2],S+m+2),$=C;$<T;$++)for(var O=w[$]-e,R=y[1]*y[2]*$,F=k;F<B;F++)for(var L=A[F]-i,N=O*O+L*L,z=R+y[2]*F,V=M;V<D;V++){var G=_[V]-a,U=N+G*G;if(U<u){var j=V+z;x[j]<0&&(x[j]=-x[j]);var H=Math.sqrt(U),W=l/H,q=O*W,X=L*W,Y=G*W;if(-1===E(q+=e,X+=i,Y+=a,t,-1)){var K=l-H;K<x[j]&&(x[j]=K,f&&(v[j]=t))}}}}}function N(t,e){var i=h[t],r=h[e],a=M[0]=s[e]-s[t],l=M[1]=n[e]-n[t],d=M[2]=o[e]-o[t],u=a*a+l*l+d*d,m=Math.sqrt(u),b=i*((i*i+m*m-r*r)/(2*i*m));os(M,M),function(t,e){t[0]=t[1]=t[2]=1,0!==e[0]?t[0]=(e[1]+e[2])/-e[0]:0!==e[1]?t[1]=(e[0]+e[2])/-e[1]:0!==e[2]&&(t[2]=(e[0]+e[1])/-e[2])}(B,M),os(B,B),Kr(D,M,B),os(D,D);var P=Math.sqrt(i*i-b*b);ns(B,B,P),ns(D,D,P),ns(M,M,b),T[0]=M[0]+s[t],T[1]=M[1]+n[t],T[2]=M[2]+o[t],k=-1;for(var I=$,O=0;O<g;O++){var R=C[O],F=S[O],L=T[0]+R*B[0]+F*D[0],N=T[1]+R*B[1]+F*D[1],z=T[2]+R*B[2]+F*D[2];if(-1===E(L,N,z,t,e))for(var V=Math.floor(p*(L-c[0])),G=Math.floor(p*(N-c[1])),U=Math.floor(p*(z-c[2])),j=Math.max(0,V-I),H=Math.max(0,G-I),W=Math.max(0,U-I),q=Math.min(y[0],V+I+2),X=Math.min(y[1],G+I+2),Y=Math.min(y[2],U+I+2),K=j;K<q;K++){a=L-w[K];for(var Z=y[1]*y[2]*K,Q=H;Q<X;Q++)for(var J=a*a+(l=N-A[Q])*l,tt=Z+y[2]*Q,et=W;et<Y;et++){u=J+(d=z-_[et])*d;var it=et+tt,rt=x[it];if(rt>0&&u<rt*rt&&(x[it]=Math.sqrt(u),f)){const i=a*M[0]+l*M[1]+d*M[2];v[it]=i<0?e:t}}}}}function z(t,e,a){console.time("AVSurface.getVolume"),console.time("AVSurface.init"),O(t,e,a),console.timeEnd("AVSurface.init"),console.time("AVSurface.projectPoints"),L(),console.timeEnd("AVSurface.projectPoints"),console.time("AVSurface.projectTorii"),function(){for(var t=0;t<r;t++){P.withinRadii(s[t],n[t],o[t],h[t],I);for(var e=0,i=I[e];i>=0;)t<i&&N(t,i),i=I[++e]}}(),console.timeEnd("AVSurface.projectTorii"),function(){for(var t=0;t<x.length;t++)x[t]<0&&(x[t]=0)}(),function(){for(var t=0;t<v.length;t++)v[t]=i[v[t]]}(),console.timeEnd("AVSurface.getVolume")}this.getSurface=function(t,e,i,r,s,n,o){return z(e,i,s),new Ro(x,y[2],y[1],y[0],v).getSurface(e,!1,void 0,b,o)}}Ne.add("line",Rd),Object.assign(Fd,{__deps:[$o,Do,Ro,Hr,Ed]}),Object.assign(Nd,{__deps:[$o,Ro,Si,Hr,ns,Kr,os,Ld,st]}),Ee.add("molsurf",(function(t,e){const i=t.data.args,r=t.data.params;if(i&&r){const t=new("av"===r.type?Nd:Fd)(i.coordList,i.radiusList,i.indexList).getSurface(r.type,r.probeRadius,r.scaleFactor,r.cutoff,!0,r.smooth,r.contour),s=[t.position.buffer,t.index.buffer];t.normal&&s.push(t.normal.buffer),t.atomindex&&s.push(t.atomindex.buffer);e({sd:t,p:r},s)}}),[Fd,Nd]);class zd{constructor(t){this.structure=t}_getAtomData(t){return this.structure.getAtomData({what:{position:!0,radius:!0,index:!0},radiusParams:st(t.radiusParams,{type:"vdw",scale:1})})}_makeSurface(t,e){var i=new Oo(e.name,"",t);return i.info.type=e.type,i.info.probeRadius=e.probeRadius,i.info.scaleFactor=e.scaleFactor,i.info.smooth=e.smooth,i.info.cutoff=e.cutoff,i}getSurface(t){const e=t||{},i=this._getAtomData(t),r=i.position,s=i.radius,n=i.index,o=new("av"===e.type?Nd:Fd)(r,s,n).getSurface(e.type,e.probeRadius,e.scaleFactor,e.cutoff,!0,e.smooth,e.contour);return this._makeSurface(o,e)}getSurfaceWorker(t,e){const i=Object.assign({},t);if(window.hasOwnProperty("Worker")){void 0===this.worker&&(this.worker=new Vr("molsurf"));const r=this._getAtomData(t),s=r.position,n=r.radius,o=r.index,a={args:{coordList:s,radiusList:n,indexList:o},params:i},c=[s.buffer,n.buffer,o.buffer];this.worker.post(a,c,(t=>{e(this._makeSurface(t.data.sd,i))}),(t=>{console.warn("MolecularSurface.getSurfaceWorker error - trying without worker",t),this.worker.terminate(),this.worker=void 0;const r=this.getSurface(i);e(r)}))}else{const t=this.getSurface(i);e(t)}}dispose(){this.worker&&this.worker.terminate()}}class Vd extends Sh{constructor(t,e,i){super(t,e,i),this.type="surface",this.parameters=Object.assign({surfaceType:{type:"select",rebuild:!0,options:{vws:"vws",sas:"sas",ms:"ms",ses:"ses",av:"av"}},probeRadius:{type:"number",precision:1,max:20,min:0,rebuild:!0},smooth:{type:"integer",precision:1,max:10,min:0,rebuild:!0},scaleFactor:{type:"number",precision:1,max:5,min:0,rebuild:!0},cutoff:{type:"number",precision:2,max:50,min:0,rebuild:!0},contour:{type:"boolean",rebuild:!0},background:{type:"boolean",rebuild:!0},opaqueBack:{type:"boolean",buffer:!0},filterSele:{type:"text",rebuild:!0},colorVolume:{type:"hidden"},useWorker:{type:"boolean",rebuild:!0}},this.parameters,{radius:null,scale:null}),this.__infoList=[],this.structure.signals.refreshed.add((()=>{this.__forceNewMolsurf=!0})),this.toBePrepared=!0,this.init(i)}init(t){const e=t||{};e.colorScheme=st(e.colorScheme,"uniform"),e.colorValue=st(e.colorValue,14540253),e.disablePicking=st(e.disablePicking,!0),this.surfaceType=st(e.surfaceType,"ms"),this.probeRadius=st(e.probeRadius,1.4),this.smooth=st(e.smooth,2),this.scaleFactor=st(e.scaleFactor,2),this.cutoff=st(e.cutoff,0),this.contour=st(e.contour,!1),this.background=st(e.background,!1),this.opaqueBack=st(e.opaqueBack,!0),this.filterSele=st(e.filterSele,""),this.colorVolume=st(e.colorVolume,void 0),this.useWorker=st(e.useWorker,!0),super.init(t)}prepareData(t,i,r){let s=this.__infoList[i];if(s||(s={},this.__infoList[i]=s),s.molsurf&&s.sele===t.selection.string)r(i);else{if(this.filterSele){const s=t.structure.getView(new pe(this.filterSele)),n=s.boundingBox.getSize(new e),o=Math.max(n.x,n.y,n.z),a=t.getAtomSetWithinPoint(s.center,o/2+6);if(0===(t=t.getView(new pe(t.getAtomSetWithinSelection(a,3).toSeleString()))).atomCount)return void r(i)}s.sele=t.selection.string,s.molsurf=new zd(t);const n=this.getSurfaceParams(),o=t=>{s.surface=t,r(i)};this.useWorker?s.molsurf.getSurfaceWorker(n,o):o(s.molsurf.getSurface(n))}}prepare(t){if((this.__forceNewMolsurf||this.__sele!==this.selection.string||this.__surfaceParams!==JSON.stringify(this.getSurfaceParams()))&&(this.__infoList.forEach((t=>{t&&t.molsurf&&t.molsurf.dispose()})),this.__infoList.length=0),0===this.structureView.atomCount)return void t();const e=()=>{this.__sele=this.selection.string,this.__surfaceParams=JSON.stringify(this.getSurfaceParams()),this.__forceNewMolsurf=!1,t()},i="default"===this.assembly?this.defaultAssembly:this.assembly,r=this.structure.biomolDict[i];r?r.partList.forEach(((t,i)=>{const s=t.getView(this.structureView);this.prepareData(s,i,(t=>{t===r.partList.length-1&&e()}))})):this.prepareData(this.structureView,0,e)}createData(t,e){const i=this.__infoList[e],r=i.surface;if(!r)return;const s={position:r.getPosition(),color:r.getColor(this.getColorParams()),index:r.getFilteredIndex(this.filterSele,t)},n=[];if(r.contour){const t=new Xo(s,this.getBufferParams({wireframe:!1}));n.push(t)}else{Object.assign(s,{normal:r.getNormal(),picking:r.getPicking(t.getStructure())});const e=new jo(s,this.getBufferParams({background:this.background,opaqueBack:this.opaqueBack,dullInterior:!1}));if("double"==this.getBufferParams().side){const t=new qo(e);n.push(t)}else n.push(e)}return{bufferList:n,info:i}}updateData(t,e){const i={};if(t.position||t.radius)return this.__forceNewMolsurf=!0,void this.build();t.color&&(i.color=e.info.surface.getColor(this.getColorParams())),t.index&&(i.index=e.info.surface.getFilteredIndex(this.filterSele,e.sview)),e.bufferList[0].setAttributes(i)}setParameters(t,e={},i){return t&&t.filterSele&&(e.index=!0),t&&void 0!==t.colorVolume&&(e.color=!0),t&&t.wireframe&&(t.contour||void 0===t.contour&&this.contour)&&(t.wireframe=!1),super.setParameters(t,e,i),this}getSurfaceParams(t={}){return Object.assign({type:this.surfaceType,probeRadius:this.probeRadius,scaleFactor:this.scaleFactor,smooth:this.smooth&&!this.contour,cutoff:this.cutoff,contour:this.contour,useWorker:this.useWorker,radiusParams:this.getRadiusParams()},t)}getColorParams(){const t=super.getColorParams();return t.volume=this.colorVolume,t}getAtomRadius(){return 0}clear(){super.clear()}dispose(){this.__infoList.forEach((t=>{t&&t.molsurf&&t.molsurf.dispose()})),this.__infoList.length=0,super.dispose()}}Ne.add("surface",Vd);class Gd extends Sh{constructor(t,e,i){super(t,e,i),this.type="point",this.parameters=Object.assign({pointSize:{type:"number",precision:1,max:100,min:0,buffer:!0},sizeAttenuation:{type:"boolean",buffer:!0},sortParticles:{type:"boolean",rebuild:!0},useTexture:{type:"boolean",buffer:!0},alphaTest:{type:"range",step:.001,max:1,min:0,buffer:!0},forceTransparent:{type:"boolean",buffer:!0},edgeBleach:{type:"range",step:.001,max:1,min:0,buffer:!0}},this.parameters,{flatShaded:null,wireframe:null,linewidth:null,side:null,roughness:null,metalness:null}),this.init(i)}init(t){var e=t||{};this.pointSize=st(e.pointSize,1),this.sizeAttenuation=st(e.sizeAttenuation,!0),this.sortParticles=st(e.sortParticles,!1),this.useTexture=st(e.useTexture,!1),this.alphaTest=st(e.alphaTest,.5),this.forceTransparent=st(e.forceTransparent,!1),this.edgeBleach=st(e.edgeBleach,0),super.init(e)}createData(t){var e=t.getAtomData(this.getAtomParams({position:!0,color:!0,picking:!0}));return{bufferList:[new Wc(e,this.getBufferParams({pointSize:this.pointSize,sizeAttenuation:this.sizeAttenuation,sortParticles:this.sortParticles,useTexture:this.useTexture,alphaTest:this.alphaTest,forceTransparent:this.forceTransparent,edgeBleach:this.edgeBleach}))]}}updateData(t,e){var i=e.sview.getAtomData(this.getAtomParams(t)),r={};t&&!t.position||Object.assign(r,{position:i.position}),t&&!t.color||Object.assign(r,{color:i.color}),e.bufferList[0].setAttributes(r)}getAtomRadius(){return.1}}Ne.add("point",Gd),Ve.add("shader/Ribbon.vert","#define STANDARD\nuniform float clipNear;\nuniform vec3 clipCenter;\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || !defined( PICKING )\nvarying vec3 vViewPosition;\n#endif\n#if defined( RADIUS_CLIP )\nvarying vec3 vClipCenter;\n#endif\nattribute vec3 dir;\nattribute float size;\n#ifdef PICKING\n#include unpack_color\nattribute float primitiveId;\nvarying vec3 vPickingColor;\n#else\n#include color_pars_vertex\n#ifndef FLAT_SHADED\nvarying vec3 vNormal;\n#endif\n#endif\n#include common\nvoid main(void){\n#ifdef PICKING\nvPickingColor = unpackColor( primitiveId );\n#else\n#include color_vertex\n#include beginnormal_vertex\n#include defaultnormal_vertex\n#ifndef FLAT_SHADED\nvNormal = normalize( transformedNormal );\n#endif\n#endif\n#include begin_vertex\ntransformed += normalize( dir ) * size;\n#include project_vertex\n#if defined( NEAR_CLIP ) || defined( RADIUS_CLIP ) || !defined( PICKING )\nvViewPosition = -mvPosition.xyz;\n#endif\n#if defined( RADIUS_CLIP )\nvClipCenter = -( modelViewMatrix * vec4( clipCenter, 1.0 ) ).xyz;\n#endif\n#include nearclip_vertex\n}");const Ud=new Uint16Array([0,1,2,1,3,2]);function jd(t){return 3*(4*(t.position.length/3-1))}class Hd extends Uo{constructor(t,e={}){super({position:new Float32Array(jd(t)),color:new Float32Array(jd(t)),index:xt(jd(t),jd(t)/3),normal:new Float32Array(jd(t)),picking:t.picking},e),this.vertexShader="Ribbon.vert";const i=t.position.length/3-1,r=4*i,s=3*r;this.addAttributes({dir:{type:"v3",value:new Float32Array(s)}}),this.addAttributes({size:{type:"f",value:new Float32Array(r)}}),t.primitiveId=Pi(i),this.setAttributes(t),this.makeIndex()}setAttributes(t={}){const e=this.size/4,i=this.geometry.attributes;let r,s,n,o,a,c,l,h,d,u,m,p,f,g,y,b,x,v,w;t.position&&(r=t.position,l=i.position.array,i.position.needsUpdate=!0),t.normal&&(s=t.normal,h=i.normal.array,i.normal.needsUpdate=!0),t.size&&(n=t.size,d=i.size.array,i.size.needsUpdate=!0),t.dir&&(o=t.dir,u=i.dir.array,i.dir.needsUpdate=!0),t.color&&(a=t.color,m=i.color.array,i.color.needsUpdate=!0),t.primitiveId&&(c=t.primitiveId,p=i.primitiveId.array,i.primitiveId.needsUpdate=!0);let A=n?n[0]:null;for(f=0;f<e;++f){for(v=3*f,y=3*f*4,x=4*f,r&&(l[y]=l[y+3]=r[v],l[y+1]=l[y+4]=r[v+1],l[y+2]=l[y+5]=r[v+2],l[y+6]=l[y+9]=r[v+3],l[y+7]=l[y+10]=r[v+4],l[y+8]=l[y+11]=r[v+5]),s&&(h[y]=h[y+3]=-s[v],h[y+1]=h[y+4]=-s[v+1],h[y+2]=h[y+5]=-s[v+2],h[y+6]=h[y+9]=-s[v+3],h[y+7]=h[y+10]=-s[v+4],h[y+8]=h[y+11]=-s[v+5]),g=0;g<4;++g)b=y+3*g,a&&(m[b]=a[v],m[b+1]=a[v+1],m[b+2]=a[v+2]),c&&(p[x+g]=c[f]);n&&(w=n[f],A!==n[f]?(d[x]=A,d[x+1]=A,d[x+2]=w,d[x+3]=w):(d[x]=w,d[x+1]=w,d[x+2]=w,d[x+3]=w),A=w),o&&(u[y]=o[v],u[y+1]=o[v+1],u[y+2]=o[v+2],u[y+3]=-o[v],u[y+4]=-o[v+1],u[y+5]=-o[v+2],u[y+6]=o[v+3],u[y+7]=o[v+4],u[y+8]=o[v+5],u[y+9]=-o[v+3],u[y+10]=-o[v+4],u[y+11]=-o[v+5])}}makeIndex(){const t=this.geometry.getIndex();if(!t)return void Me.error("Index is null");const e=t.array,i=e.length/4/3;for(let t=0;t<i;++t){const i=6*t,r=4*t;e.set(Ud,i);for(let t=0;t<6;++t)e[i+t]+=r}}}class Wd extends Sh{constructor(t,e,i){super(t,e,i),this.type="ribbon",this.parameters=Object.assign({subdiv:{type:"integer",max:50,min:1,rebuild:!0},tension:{type:"number",precision:1,max:1,min:.1},smoothSheet:{type:"boolean",rebuild:!0}},this.parameters,{side:null,wireframe:null,linewidth:null}),this.init(i)}init(t){var e=t||{};e.colorScheme=st(e.colorScheme,"chainname"),e.colorScale=st(e.colorScale,"RdYlBu"),e.radiusType=st(e.radiusType,"sstruc"),e.radiusScale=st(e.radiusScale,4),"low"===e.quality?this.subdiv=3:"medium"===e.quality?this.subdiv=6:"high"===e.quality?this.subdiv=12:this.subdiv=st(e.subdiv,6),this.tension=st(e.tension,NaN),this.smoothSheet=st(e.smoothSheet,!1),super.init(e)}getSplineParams(t){return Object.assign({subdiv:this.subdiv,tension:this.tension,directional:!0,smoothSheet:this.smoothSheet},t)}getAtomRadius(t){return t.isTrace()?super.getAtomRadius(t):0}createData(t){var e=[],i=[];return this.structure.eachPolymer((t=>{if(!(t.residueCount<4)){i.push(t);var r=new od(t,this.getSplineParams()),s=r.getSubdividedPosition(),n=r.getSubdividedOrientation(),o=r.getSubdividedColor(this.getColorParams()),a=r.getSubdividedPicking(),c=r.getSubdividedSize(this.getRadiusParams());e.push(new Hd({position:s.position,normal:n.binormal,dir:n.normal,color:o.color,size:c.size,picking:a.picking},this.getBufferParams()))}}),t.getSelection()),{bufferList:e,polymerList:i}}updateData(t,e){t=t||{};var i=0,r=e.polymerList.length;for(i=0;i<r;++i){var s={},n=new od(e.polymerList[i],this.getSplineParams());if(t.position){var o=n.getSubdividedPosition(),a=n.getSubdividedOrientation();Object.assign(s,{position:o.position,normal:a.binormal,dir:a.normal})}if(t.radius||t.scale){var c=n.getSubdividedSize(this.getRadiusParams());Object.assign(s,{size:c.size})}if(t.color){var l=n.getSubdividedColor(this.getColorParams());Object.assign(s,{color:l.color})}e.bufferList[i].setAttributes(s)}}setParameters(t){var e={};return t&&t.tension&&Object.assign(e,{position:!0}),super.setParameters(t,e,!1),this}}Ne.add("ribbon",Wd);class qd extends Sh{constructor(t,e,i){super(t,e,i),this.type="rocket",this.parameters=Object.assign({localAngle:{type:"integer",max:180,min:0,rebuild:!0},centerDist:{type:"number",precision:1,max:10,min:0,rebuild:!0},ssBorder:{type:"boolean",rebuild:!0},radialSegments:!0,openEnded:!0,disableImpostor:!0},this.parameters),this.init(i)}init(t){let e=t||{};e.colorScheme=st(e.colorScheme,"sstruc"),e.radiusSize=st(e.radiusSize,1.5),e.radiusScale=st(e.radiusScale,1),e.openEnded=st(e.openEnded,!1),e.useInteriorColor=st(e.useInteriorColor,!0),this.localAngle=st(e.localAngle,30),this.centerDist=st(e.centerDist,2.5),this.ssBorder=st(e.ssBorder,!1),super.init(e)}createData(t){let e=0;const i=[],r=[];this.structure.eachPolymer((t=>{if(t.residueCount<4||t.isNucleic())return;const s=new Pa(t),n=s.getAxis(this.localAngle,this.centerDist,this.ssBorder,this.getColorParams(),this.getRadiusParams());e+=n.size.length,i.push(n),r.push(s)}),t.getSelection());const s={begin:new Float32Array(3*e),end:new Float32Array(3*e),size:new Float32Array(e),color:new Float32Array(3*e),picking:{}};let n=new Float32Array(e),o=0;i.forEach((function(t){s.begin.set(t.begin,3*o),s.end.set(t.end,3*o),s.size.set(t.size,o),s.color.set(t.color,3*o),n.set(t.picking.array,o),o+=t.size.length})),e&&(s.picking=new Yn(n,t.getStructure()));return{bufferList:[new td({position1:s.begin,position2:s.end,color:s.color,color2:s.color,radius:s.size,picking:s.picking},this.getBufferParams({openEnded:this.openEnded,radialSegments:this.radialSegments,disableImpostor:this.disableImpostor,dullInterior:!0}))],axisList:i,helixbundleList:r,axisData:s}}updateData(t,e){if((t=t||{}).position)this.build();else{var i={};if(t.color||t.radius){var r=0;e.helixbundleList.forEach((i=>{var s=i.getAxis(this.localAngle,this.centerDist,this.ssBorder,this.getColorParams(),this.getRadiusParams());t.color&&e.axisData.color.set(s.color,3*r),(t.radius||t.scale)&&e.axisData.size.set(s.size,r),r+=s.size.length})),t.color&&Object.assign(i,{color:e.axisData.color,color2:e.axisData.color}),(t.radius||t.scale)&&Object.assign(i,{radius:e.axisData.size})}e.bufferList[0].setAttributes(i)}}}Ne.add("rocket",qd);class Xd extends dd{constructor(t,e,i){super(t,e,i),this.type="rope",this.parameters=Object.assign({smooth:{type:"integer",max:15,min:0,rebuild:!0}},this.parameters,{aspectRatio:null,smoothSheet:null})}init(t){var e=t||{};e.aspectRatio=1,e.tension=st(e.tension,.5),e.radiusScale=st(e.radiusScale,5),e.smoothSheet=!1,this.smooth=st(e.smooth,2),super.init(e)}getSpline(t){var e=new Ca(t);return new od(t,this.getSplineParams({directional:!1,positionIterator:e.getCenterIterator(this.smooth)}))}}Ne.add("rope",Xd);class Yd extends Sh{constructor(t,e,i){super(t,e,i),this.type="spacefill",this.parameters=Object.assign({sphereDetail:!0,disableImpostor:!0},this.parameters),this.init(i)}init(t){var e=t||{};e.useInteriorColor=st(e.useInteriorColor,!0),super.init(e)}createData(t){return{bufferList:[new Gc(t.getAtomData(this.getAtomParams()),this.getBufferParams({sphereDetail:this.sphereDetail,dullInterior:!0,disableImpostor:this.disableImpostor}))]}}updateData(t,e){var i=e.sview.getAtomData(this.getAtomParams(t)),r={};t&&!t.position||Object.assign(r,{position:i.position}),t&&!t.color||Object.assign(r,{color:i.color}),t&&!t.radius||Object.assign(r,{radius:i.radius}),e.bufferList[0].setAttributes(r)}}function Kd(t){return 3*(t.position.length/3-1)*2}Ne.add("spacefill",Yd);class Zd extends Go{constructor(t,e={}){super({position:new Float32Array(Kd(t)),color:new Float32Array(Kd(t))},e),this.isLine=!0,this.vertexShader="Line.vert",this.fragmentShader="Line.frag",this.setAttributes(t)}setAttributes(t){let e,i,r,s;const n=this.geometry.attributes;if(t.position&&(e=t.position,r=n.position.array,n.position.needsUpdate=!0),t.color&&(i=t.color,s=n.color.array,n.color.needsUpdate=!0),!e&&!i)return void Me.warn("TraceBuffer.prototype.setAttributes no data");let o,a;const c=this.size-1;for(let t=0;t<c;++t)o=3*t,a=3*t*2,e&&(r[a]=e[o],r[a+1]=e[o+1],r[a+2]=e[o+2],r[a+3]=e[o+3],r[a+4]=e[o+4],r[a+5]=e[o+5]),i&&(s[a]=i[o],s[a+1]=i[o+1],s[a+2]=i[o+2],s[a+3]=i[o+3],s[a+4]=i[o+4],s[a+5]=i[o+5])}}class Qd extends Sh{constructor(t,e,i){super(t,e,i),this.type="trace",this.parameters=Object.assign({subdiv:{type:"integer",max:50,min:1,rebuild:!0},tension:{type:"number",precision:1,max:1,min:.1},smoothSheet:{type:"boolean",rebuild:!0}},this.parameters,{flatShaded:null,side:null,wireframe:null}),this.init(i)}init(t){var e=t||{};e.colorScheme=st(e.colorScheme,"chainname"),e.colorScale=st(e.colorScale,"RdYlBu"),"low"===e.quality?this.subdiv=3:"medium"===e.quality?this.subdiv=6:"high"===e.quality?this.subdiv=12:this.subdiv=st(e.subdiv,6),this.tension=st(e.tension,NaN),this.smoothSheet=st(e.smoothSheet,!1),super.init(e)}getSplineParams(t){return Object.assign({subdiv:this.subdiv,tension:this.tension,directional:!1,smoothSheet:this.smoothSheet},t)}getAtomRadius(t){return t.isTrace()?.1:0}createData(t){var e=[],i=[];return this.structure.eachPolymer((t=>{if(!(t.residueCount<4)){i.push(t);var r=new od(t,this.getSplineParams()),s=r.getSubdividedPosition(),n=r.getSubdividedColor(this.getColorParams());e.push(new Zd(Object.assign({},s,n),this.getBufferParams()))}}),t.getSelection()),{bufferList:e,polymerList:i}}updateData(t,e){t=t||{};var i=0,r=e.polymerList.length;for(i=0;i<r;++i){var s={},n=new od(e.polymerList[i],this.getSplineParams());if(t.position){var o=n.getSubdividedPosition();Object.assign(s,{position:o.position})}if(t.color){var a=n.getSubdividedColor(this.getColorParams());Object.assign(s,{color:a.color})}e.bufferList[i].setAttributes(s)}}setParameters(t){var e={};return t&&t.tension&&Object.assign(e,{position:!0}),super.setParameters(t,e,!1),this}}Ne.add("trace",Qd);class Jd extends dd{constructor(t,e,i){super(t,e,i),this.type="tube",this.parameters=Object.assign({},this.parameters,{aspectRatio:null})}init(t){var e=t||{};e.aspectRatio=1,e.radiusScale=st(e.radiusScale,2),"low"===e.quality&&(this.radialSegments=5),super.init(e)}getSplineParams(){return super.getSplineParams({directional:!1})}}Ne.add("tube",Jd);class tu extends Sh{constructor(t,e,i){super(t,e,i),this.type="unitcell",this.parameters=Object.assign({radiusSize:{type:"number",precision:3,max:10,min:.001},sphereDetail:!0,radialSegments:!0,disableImpostor:!0},this.parameters,{assembly:null}),this.init(i)}init(t){const e=t||{};let i=.5;this.structure.unitcell&&(i=Math.cbrt(this.structure.unitcell.volume)/200),e.radiusSize=st(e.radiusSize,i),e.colorValue=st(e.colorValue,"orange"),e.useInteriorColor=st(e.useInteriorColor,!0),super.init(e)}getUnitcellData(t){return t.unitcell.getData(t)}create(){const t=this.structureView.getStructure();if(!t.unitcell)return;const e=this.getUnitcellData(t);this.sphereBuffer=new Gc(e.vertex,this.getBufferParams({sphereDetail:this.sphereDetail,disableImpostor:this.disableImpostor,dullInterior:!0})),this.cylinderBuffer=new td(e.edge,this.getBufferParams({openEnded:!0,radialSegments:this.radialSegments,disableImpostor:this.disableImpostor,dullInterior:!0})),this.dataList.push({sview:this.structureView,bufferList:[this.sphereBuffer,this.cylinderBuffer]})}createData(t){}updateData(t,e){const i=e.sview.getStructure();if(!i.unitcell)return;const r=this.getUnitcellData(i),s={},n={};t&&!t.position||(Object.assign(s,{position:r.vertex.position}),Object.assign(n,{position1:r.edge.position1,position2:r.edge.position2})),t&&!t.color||(Object.assign(s,{color:r.vertex.color}),Object.assign(n,{color:r.edge.color,color2:r.edge.color2})),t&&!t.radius||(Object.assign(s,{radius:r.vertex.radius}),Object.assign(n,{radius:r.edge.radius})),this.sphereBuffer.setAttributes(s),this.cylinderBuffer.setAttributes(n)}}Ne.add("unitcell",tu);class eu extends Sh{constructor(t,e,i){super(t,e,i),this.type="validation",this.parameters=Object.assign({},this.parameters,{radiusType:null,radiusSize:null,radiusScale:null}),this.init(i)}init(t){const e=t||{};e.colorValue=st(e.colorValue,"#f0027f"),e.useInteriorColor=st(e.useInteriorColor,!0),super.init(e)}createData(t){if(!t.validation)return;const e=t.validation.getClashData({structure:t,color:this.colorValue});return{bufferList:[new td(e,this.getBufferParams({openEnded:!1}))]}}}Ne.add("validation",eu);const iu=new e,ru=new e,su=new e,nu=new e(0,1,0);const ou=Object.assign({radialSegments:60,openEnded:!1},zo);class au extends $c{constructor(t,e={}){super({position:new Float32Array(t.position1.length),color:t.color,picking:t.picking},e,function(t={}){const e=new __WEBPACK_IMPORTED_MODULE_0_three__["j" /* ConeBufferGeometry */](1,1,st(t.radialSegments,60),1,st(t.openEnded,!1));return e.applyMatrix4((new i).makeRotationX(-Math.PI/2)),e}(e)),this.updateNormals=!0,this._position=new Float32Array(t.position1.length),this.setAttributes(t,!0)}get defaultParameters(){return ou}applyPositionTransform(t,e,i){ru.fromArray(this._position1,i),su.fromArray(this._position2,i),t.lookAt(ru,su,nu);const r=this._radius[e];iu.set(r,r,ru.distanceTo(su)),t.scale(iu)}setAttributes(t={},e){t.position1&&t.position2&&(Ai(t.position1,t.position2,this._position),this._position1=t.position1,this._position2=t.position2,t.position=this._position),t.radius&&(this._radius=t.radius),super.setAttributes(t,e)}}je.add("cone",au);class cu{constructor(t=[]){this.geometryList=t}computeBoundingBox(){this.boundingBox?this.boundingBox.empty():this.boundingBox=new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */],this.geometryList.forEach((t=>{t.boundingBox||t.computeBoundingBox(),this.boundingBox.union(t.boundingBox)}))}}const lu=Object.assign({aspectRatio:1.5,radialSegments:50,openEnded:!1,disableImpostor:!1},zo);class hu{constructor(t,e={}){this.group=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.wireframeGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.pickingGroup=new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */],this.visible=!0,this.parameters=nt(e,this.defaultParameters),this.splitPosition=new Float32Array(t.position1.length),this.cylinderRadius=new Float32Array(t.radius.length);const r=this.makeAttributes(t),s={radialSegments:this.parameters.radialSegments,openEnded:this.parameters.openEnded,disableImpostor:this.parameters.disableImpostor};this.cylinderBuffer=new td(r.cylinder,s),this.coneBuffer=new au(r.cone,s),this.geometry=new cu([this.cylinderBuffer.geometry,this.coneBuffer.geometry]),this.matrix=st(e.matrix,new i),this.picking=t.picking}get defaultParameters(){return lu}set matrix(t){Go.prototype.setMatrix.call(this,t)}get matrix(){return this.group.matrix.clone()}get pickable(){return!!this.picking}makeAttributes(t={}){const i=this.splitPosition,r=this.cylinderRadius,s=this.parameters.aspectRatio;let n,o;const a={},c={};if(t.radius){for(n=0,o=r.length;n<o;++n)r[n]=t.radius[n]/s;a.radius=r,c.radius=t.radius}if(t.position1&&t.position2){const l=new e,h=new e,d=new e,u=new e;for(n=0,o=i.length;n<o;n+=3){l.fromArray(t.position1,n),h.fromArray(t.position2,n),d.subVectors(l,h);const e=d.length(),o=r[n/3]*s*2,a=Math.min(e,o);d.setLength(a),u.copy(h).add(d),u.toArray(i,n)}a.position1=t.position1,a.position2=i,c.position1=i,c.position2=t.position2}return t.color&&(a.color=t.color,a.color2=t.color,c.color=t.color),{cylinder:a,cone:c}}getMesh(){return(new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]).add(this.cylinderBuffer.getMesh(),this.coneBuffer.getMesh())}getWireframeMesh(){return(new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]).add(this.cylinderBuffer.getWireframeMesh(),this.coneBuffer.getWireframeMesh())}getPickingMesh(){return(new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]).add(this.cylinderBuffer.getPickingMesh(),this.coneBuffer.getPickingMesh())}setAttributes(t={}){const e=this.makeAttributes(t);this.cylinderBuffer.setAttributes(e.cylinder),this.coneBuffer.setAttributes(e.cone)}setParameters(t={}){(t=Object.assign({},t))&&void 0!==t.matrix&&(this.matrix=t.matrix),delete t.matrix,t&&void 0!==t.wireframe&&(this.parameters.wireframe=t.wireframe,this.setVisibility(this.visible)),this.cylinderBuffer.setParameters(t),this.coneBuffer.setParameters(t)}setVisibility(t){Go.prototype.setVisibility.call(this,t)}dispose(){this.cylinderBuffer.dispose(),this.coneBuffer.dispose()}}je.add("arrow",hu);const du=new e,uu=new e,mu=new e,pu=new e(0,0,0);class fu extends $c{constructor(t,e={}){super(t,e,new __WEBPACK_IMPORTED_MODULE_0_three__["e" /* BoxBufferGeometry */](1,1,1)),this.updateNormals=!0,this.setAttributes(t,!0)}applyPositionTransform(t,e,i){uu.fromArray(this._heightAxis,i),mu.fromArray(this._depthAxis,i),t.lookAt(pu,uu,mu),du.set(this._size[e],mu.length(),uu.length()),t.scale(du)}setAttributes(t={},e){t.size&&(this._size=t.size),t.heightAxis&&(this._heightAxis=t.heightAxis),t.depthAxis&&(this._depthAxis=t.depthAxis),super.setAttributes(t,e)}}je.add("box",fu);const gu=new e,yu=new e,bu=new e,xu=new e(0,0,0),vu=Object.assign({sphereDetail:2},zo);class wu extends $c{constructor(t,e={}){super(t,e,new __WEBPACK_IMPORTED_MODULE_0_three__["u" /* IcosahedronBufferGeometry */](1,st(e.sphereDetail,2))),this.updateNormals=!0,this.setAttributes(t,!0)}get defaultParameters(){return vu}applyPositionTransform(t,e,i){yu.fromArray(this._majorAxis,i),bu.fromArray(this._minorAxis,i),t.lookAt(xu,yu,bu),gu.set(this._radius[e],bu.length(),yu.length()),t.scale(gu)}setAttributes(t={},e){t.radius&&(this._radius=t.radius),t.majorAxis&&(this._majorAxis=t.majorAxis),t.minorAxis&&(this._minorAxis=t.minorAxis),super.setAttributes(t,e)}}je.add("ellipsoid",wu);const Au=new e,_u=new e,Su=new e,Cu=new e(0,0,0);class Pu extends $c{constructor(t,e={}){super(t,e,new __WEBPACK_IMPORTED_MODULE_0_three__["E" /* OctahedronBufferGeometry */](1,0)),this.updateNormals=!0,this.setAttributes(t,!0)}applyPositionTransform(t,e,i){_u.fromArray(this._heightAxis,i),Su.fromArray(this._depthAxis,i),t.lookAt(Cu,_u,Su),Au.set(this._size[e],Su.length(),_u.length()),t.scale(Au)}setAttributes(t={},e){t.size&&(this._size=t.size),t.heightAxis&&(this._heightAxis=t.heightAxis),t.depthAxis&&(this._depthAxis=t.depthAxis),super.setAttributes(t,e)}}je.add("octahedron",Pu);const Iu=new e,ku=new e,Mu=new e,Tu=new e(0,0,0);class Bu extends $c{constructor(t,e={}){super(t,e,new __WEBPACK_IMPORTED_MODULE_0_three__["R" /* TetrahedronBufferGeometry */](1,0)),this.updateNormals=!0,this.setAttributes(t,!0)}applyPositionTransform(t,e,i){ku.fromArray(this._heightAxis,i),Mu.fromArray(this._depthAxis,i),t.lookAt(Tu,ku,Mu),Iu.set(this._size[e],Mu.length(),ku.length()),t.scale(Iu)}setAttributes(t={},e){t.size&&(this._size=t.size),t.heightAxis&&(this._heightAxis=t.heightAxis),t.depthAxis&&(this._depthAxis=t.depthAxis),super.setAttributes(t,e)}}je.add("tetrahedron",Bu);const Du=new e,$u=new e,Ou=new e,Ru=new e(0,0,0),Eu=Object.assign({radiusRatio:.2,radialSegments:16,tubularSegments:32},zo);class Fu extends $c{constructor(t,e={}){super(t,e,new __WEBPACK_IMPORTED_MODULE_0_three__["S" /* TorusBufferGeometry */](1,st(e.radiusRatio,.2),st(e.radialSegments,16),st(e.tubularSegments,32))),this.updateNormals=!0,this.setAttributes(t,!0)}get defaultParameters(){return Eu}applyPositionTransform(t,e,i){$u.fromArray(this._majorAxis,i),Ou.fromArray(this._minorAxis,i),t.lookAt(Ru,$u,Ou);const r=this._radius[e];Du.set(r,r,r),t.scale(Du)}setAttributes(t={},e){t.radius&&(this._radius=t.radius),t.majorAxis&&(this._majorAxis=t.majorAxis),t.minorAxis&&(this._minorAxis=t.minorAxis),super.setAttributes(t,e)}}je.add("torus",Fu);class Lu{constructor(t,e){var i=e||{};this.streamer=t,this.name=st(i.name,""),this.path=st(i.path,"")}get type(){return""}get __objName(){return""}get isBinary(){return!1}get isJson(){return!1}get isXml(){return!1}parse(){return this.streamer.read().then((()=>(this._beforeParse(),this._parse(),this._afterParse(),this[this.__objName])))}_parse(){}_beforeParse(){}_afterParse(){De&&Me.log(this[this.__objName])}}class Nu extends Lu{constructor(t,e){var i=e||{};super(t,i),this.firstModelOnly=st(i.firstModelOnly,!1),this.asTrajectory=st(i.asTrajectory,!1),this.cAlphaOnly=st(i.cAlphaOnly,!1),this.structure=new Cc(this.name,this.path),this.structureBuilder=new za(this.structure)}get type(){return"structure"}get __objName(){return"structure"}}class zu{constructor(t,e,i="",r,s=[]){this.structure=t,this.index=e,this.description=i,this.entityType=function(t){switch(t=t.toLowerCase()){case"polymer":return 1;case"non-polymer":return 2;case"macrolide":return 3;case"water":return 4;default:return 0}}(r||""),this.chainIndexList=s,s.forEach((function(i){t.chainStore.entityIndex[i]=e}))}get type(){return function(t){switch(t){case 1:return"polymer";case 2:return"non-polymer";case 3:return"macrolide";case 4:return"water";default:return}}(this.entityType)}getEntityType(){return this.entityType}isPolymer(){return 1===this.entityType}isNonPolymer(){return 2===this.entityType}isMacrolide(){return 3===this.entityType}isWater(){return 4===this.entityType}eachChain(t){const e=this.structure.getChainProxy();this.chainIndexList.forEach((function(i){e.index=i,t(e)}))}}const Vu={a:1,b:1,c:1,alpha:90,beta:90,gamma:90,spacegroup:"P 1"};class Gu{constructor(t=Vu){this.cartToFrac=new i,this.fracToCart=new i,this.a=t.a,this.b=t.b,this.c=t.c,this.alpha=t.alpha,this.beta=t.beta,this.gamma=t.gamma,this.spacegroup=t.spacegroup;const e=kt(this.alpha),r=kt(this.beta),s=kt(this.gamma),n=Math.cos(e),o=Math.cos(r),a=Math.cos(s),c=Math.sin(r),l=Math.sin(s);if(this.volume=this.a*this.b*this.c*Math.sqrt(1-n*n-o*o-a*a+2*n*o*a),void 0===t.cartToFrac){const t=this.a*this.b*l/this.volume,e=(o*a-n)/(c*l);this.fracToCart.set(this.a,0,0,0,this.b*a,this.b*l,0,0,this.c*o,-this.c*c*e,1/t,0,0,0,0,1).transpose(),this.cartToFrac.getInverse(this.fracToCart)}else this.cartToFrac.copy(t.cartToFrac),this.fracToCart.getInverse(this.cartToFrac)}getPosition(t){const i=new Float32Array(24);if(t.unitcell){const r=t.unitcell,s=t.center.clone().applyMatrix4(r.cartToFrac).floor(),n=new e;let o=0;const a=function(t,e,a){n.set(t,e,a).add(s).applyMatrix4(r.fracToCart).toArray(i,o),o+=3};a(0,0,0),a(1,0,0),a(0,1,0),a(0,0,1),a(1,1,0),a(1,0,1),a(0,1,1),a(1,1,1)}return i}getCenter(t){return function(t,i=new e){const r=t.length;for(let e=0;e<r;e+=3)i.x+=t[e],i.y+=t[e+1],i.z+=t[e+2];return i.divideScalar(r/3),i}(this.getPosition(t))}getData(t,i={}){const r=st(i.colorValue,"orange"),n=st(i.radius,Math.cbrt(this.volume)/200),o=new s(r),a=new e,c=this.getPosition(t),l=Ci(8,o.r,o.g,o.b),h=Si(8,n),d=new Float32Array(36),u=new Float32Array(36),m=Ci(12,o.r,o.g,o.b),p=Si(12,n);let f=0;function g(t,e){a.fromArray(c,3*t).toArray(d,f),a.fromArray(c,3*e).toArray(u,f),f+=3}g(0,1),g(0,2),g(0,3),g(1,4),g(1,5),g(2,6),g(3,5),g(4,7),g(5,7),g(2,4),g(7,6),g(3,6);const y=new so(this,t);return{vertex:{position:c,color:l,radius:h,picking:y},edge:{position1:d,position2:u,color:m,color2:m,radius:p,picking:y}}}}const Uu={1:"h",2:"h",3:"i",4:"h",5:"g",6:"h",7:"h",8:"h",9:"h",10:"h",0:"h"},ju=["DAL","DAR","DSG","DAS","DCY","DGL","DGN","DHI","DIL","DLE","DLY","MED","DPN","DPR","DSN","DTH","DTR","DTY","DVA","DNE"],Hu=["MOL_ID","MOLECULE","CHAIN","FRAGMENT","SYNONYM","EC","ENGINEERED","MUTATION","OTHER_DETAILS"],Wu=/\s+/;function qu(t,e,i){let r=`${t}`;return e&&(r+=`:${e}`),i&&(r+=`^${i}`),r}class Xu extends Nu{constructor(t,e){const i=e||{};super(t,i),this.hex=st(i.hex,!1),this.inferBonds=st(i.inferBonds,"all")}get type(){return"pdb"}_parse(){De&&Me.time("PdbParser._parse "+this.name);let t=!1;const e=this.streamer.peekLines(1)[0],r=e.substr(62,4),s=e.substr(72,4);r===s&&s.trim()&&(t=!0);const n="pqr"===this.type,o="pdbqt"===this.type,a=this.structure,c=this.structureBuilder,l=this.hex;let h=10,d=10;const u=this.firstModelOnly,m=this.asTrajectory,p=this.cAlphaOnly,f=a.frames,g=a.boxes;let y,b,x=!1;const v=a.biomolDict;let w,A,_,S,C,P,I,k,M,T,B,D,$,O,R,E,F,L,N,z,V,G,U={};const j={},H={},W=[];let q,X;const Y={},K={},Z={};let Q,J,tt,et,it,rt,st;const nt={};let ot;const at={helices:[],sheets:[]},ct=at.helices,lt=at.sheets,ht=a.atomMap,dt=a.atomStore;dt.resize(Math.round(this.streamer.data.length/80)),(n||o)&&dt.addField("partialCharge",1,"float32"),n&&dt.addField("radius",1,"float32");const ut=a.getAtomProxy(),mt=a.getAtomProxy();let pt=0,ft=0,gt=!0;this.streamer.eachChunkOfLines((function(e){!function(e,r,s){for(let at=e;at<r;++at)if(S=s[at],C=S.substr(0,6),"ATOM  "===C||"HETATM"===C){if(gt&&(m?(x?(y=new Float32Array(3*dt.count),f.push(y)):y=[],b=0):u||(U={}),Q=1,J=Q.toString(),tt=!0,gt=!1),u&&ft>0)continue;let e,i,r,s,a,g=0;if(n){if(s=S.split(Wu),g=10===s.length?1:0,D=s[2],p&&"CA"!==D)continue;e=parseFloat(s[6-g]),i=parseFloat(s[7-g]),r=parseFloat(s[8-g])}else{if(D=S.substr(12,4).trim(),p&&"CA"!==D)continue;e=parseFloat(S.substr(30,8)),i=parseFloat(S.substr(38,8)),r=parseFloat(S.substr(46,8))}if(m){const t=3*b;if(y[t+0]=e,y[t+1]=i,y[t+2]=r,b+=1,x)continue}n?(P=parseInt(s[1]),a="",$="H"===S[0],I=g?"":s[4],k=parseInt(s[5-g]),B="",M=s[3],R="",T=1):(P=parseInt(S.substr(6,5),h),l&&99999===P&&(h=16),$="H"===S[0],I=S[21].trim(),k=parseInt(S.substr(22,4),d),l&&9999===k&&(d=16),B=S[26].trim(),M=S.substr(17,4).trim()||"MOL",O=parseFloat(S.substr(60,6)),R=S[16].trim(),T=parseFloat(S.substr(54,6)),t||(o?(a=S.substr(76,3).trim(),a in pn&&(a=pn[a])):(a=S.substr(76,2).trim(),I||(I=S.substr(72,4).trim())),E=parseInt((S.substr(79,1)+S.substr(78,1)).trim()))),dt.growIfFull(),dt.atomTypeId[pt]=ht.add(D,a),dt.x[pt]=e,dt.y[pt]=i,dt.z[pt]=r,dt.serial[pt]=P,dt.altloc[pt]=R.charCodeAt(0),dt.occupancy[pt]=isNaN(T)?0:T,n?(dt.partialCharge[pt]=parseFloat(s[9-g]),dt.radius[pt]=parseFloat(s[10-g])):(dt.bfactor[pt]=isNaN(O)?0:O,o&&(dt.partialCharge[pt]=parseFloat(S.substr(70,6))),isFinite(E)&&(dt.formalCharge||dt.addField("formalCharge",1,"int8"),dt.formalCharge[pt]=E));const v=qu(k,I,B);!$||K[v]||ju.includes(M)?tt||et===I||(Q+=1,J=Q.toString()):et===I&&rt===M&&(cn.includes(M)||it===k&&st===B)||(Q+=1,J=Q.toString(),it=k,rt=M,st=B),c.addAtom(ft,I,J,M,k,$,void 0,B),U[P]=pt,pt+=1,tt=!1,et=I}else if("CONECT"===C){const t=U[parseInt(S.substr(6,5))],e=[11,16,21,26],i={};if(void 0===t)continue;for(let r=0;r<4;++r){let s=parseInt(S.substr(e[r],5));if(!Number.isNaN(s)&&(s=U[s],void 0!==s))if(t<s?(ut.index=t,mt.index=s):(ut.index=s,mt.index=t),void 0!==i[s])a.bondStore.bondOrder[i[s]]+=1;else{const t=ut.index+"|"+mt.index;void 0===H[t]&&(H[t]=!0,i[s]=a.bondStore.count,a.bondStore.addBond(ut,mt,1))}}}else if("HELIX "===C){F=S[19].trim(),L=parseInt(S.substr(21,4)),N=S[25].trim(),z=S[31].trim(),V=parseInt(S.substr(33,4)),G=S[37].trim();let t=parseInt(S.substr(39,1));t=(Uu[t]||Uu[0]).charCodeAt(0),ct.push([F,L,N,z,V,G,t])}else if("SHEET "===C)F=S[21].trim(),L=parseInt(S.substr(22,4)),N=S[26].trim(),z=S[32].trim(),V=parseInt(S.substr(33,4)),G=S[37].trim(),lt.push([F,L,N,z,V,G]);else if("HETNAM"===C)Y[S.substr(11,3)]=S.substr(15).trim();else if("SEQRES"===C){const t=S[11].trim();t!==ot&&(nt[t]=[],ot=t),nt[t].push(...S.substr(19).trim().split(Wu))}else if("MODRES"===C){const t=S.substr(12,3).trim(),e=S[16].trim(),i=S[22].trim(),r=parseInt(S.substr(18,4).trim()),s=qu(r,e,i);K[s]={resname:t,chainname:e,inscode:i,resno:r}}else if("COMPND"===C){const t=S.substr(10,70).trim(),e=t.indexOf(":"),i=t.substring(0,e);let r;Hu.includes(i)?(X=i,r=t.substring(e+2)):r=t,r=r.replace(/;$/,""),"MOL_ID"===X?(q={chainList:[],name:""},W.push(q)):"MOLECULE"===X?(q.name&&(q.name+=" "),q.name+=r):"CHAIN"===X&&Array.prototype.push.apply(q.chainList,r.split(/\s*,\s*/))}else if(S.startsWith("TER")){const t=a.getChainProxy(a.chainStore.count-1);Z[t.chainname]=t.index,Q+=1,J=Q.toString(),tt=!0}else if("REMARK"===C&&"350"===S.substr(7,3)){if("BIOMOLECULE:"===S.substr(11,12)){let t=S.substr(23).trim();/^(0|[1-9][0-9]*)$/.test(t)&&(t="BU"+t),w=new La(t),v[t]=w}else if("BIOMT"===S.substr(13,5)){const t=S.split(/\s+/),e=parseInt(S[18])-1;0===e&&(_=new i,A.matrixList.push(_));const r=_.elements;r[0+e]=parseFloat(t[4]),r[4+e]=parseFloat(t[5]),r[8+e]=parseFloat(t[6]),r[12+e]=parseFloat(t[7])}else if("APPLY THE FOLLOWING TO CHAINS:"===S.substr(11,30)||"                   AND CHAINS:"===S.substr(11,30)){"APPLY"===S.substr(11,5)&&(A=w.addPart());const t=S.substr(41,30).split(",");for(let e=0,i=t.length;e<i;++e){const i=t[e].trim();i&&A.chainList.push(i)}}}else if("HEADER"===C)a.id=S.substr(62,4);else if("TITLE "===C)a.title+=(a.title?" ":"")+S.substr(10,70).trim();else if("MODEL "===C)gt=!0;else if("ENDMDL"===C||"END"===S.trim()){if(gt)continue;m&&!x&&(f.push(new Float32Array(y)),x=!0),ft+=1,gt=!0}else if("MTRIX"===S.substr(0,5)){if("1"===S[59])continue;if(!w||"NCS"!==w.name){const t="NCS";w=new La(t),v[t]=w,A=w.addPart()}const t=S.split(/\s+/),e=parseInt(S[5])-1;0===e&&(_=new i,A.matrixList.push(_));const r=_.elements;r[0+e]=parseFloat(t[2]),r[4+e]=parseFloat(t[3]),r[8+e]=parseFloat(t[4]),r[12+e]=parseFloat(t[5])}else if("ORIGX"===S.substr(0,5)){j.origx||(j.origx=new i);const t=S.split(/\s+/),e=parseInt(S[5])-1,r=j.origx.elements;r[0+e]=parseFloat(t[1]),r[4+e]=parseFloat(t[2]),r[8+e]=parseFloat(t[3]),r[12+e]=parseFloat(t[4])}else if("SCALE"===S.substr(0,5)){j.scale||(j.scale=new i);const t=S.split(/\s+/),e=parseInt(S[5])-1,r=j.scale.elements;r[0+e]=parseFloat(t[1]),r[4+e]=parseFloat(t[2]),r[8+e]=parseFloat(t[3]),r[12+e]=parseFloat(t[4])}else if("CRYST1"===C){const t=parseFloat(S.substr(6,9)),e=parseFloat(S.substr(15,9)),i=parseFloat(S.substr(24,9)),r=parseFloat(S.substr(33,7)),s=parseFloat(S.substr(40,7)),n=parseFloat(S.substr(47,7)),o=S.substr(55,11).trim(),a=new Float32Array(9);a[0]=t,a[4]=e,a[8]=i,g.push(a),0===ft&&(j.a=t,j.b=e,j.c=i,j.alpha=r,j.beta=s,j.gamma=n,j.spacegroup=o)}}(0,e.length,e)})),c.finalize();const yt=W.length;if(yt){a.eachChain((function(t){t.entityIndex=yt})),W.forEach((function(t,e){const i=t.chainList.map((function(t){return Z[t]}));a.entityList.push(new zu(a,e,t.name,"polymer",i))}));let t=W.length;const e=a.getResidueProxy(),i={};a.eachChain((function(t){t.entityIndex===yt&&(e.index=t.residueOffset,i[e.resname]||(i[e.resname]=[]),i[e.resname].push(t.index))})),Object.keys(i).forEach((function(e){const r=i[e];let s="non-polymer",n=Y[e]||e;cn.includes(e)&&(n="water",s="water"),a.entityList.push(new zu(a,t,n,s,r)),t+=1}))}void 0!==j.a?a.unitcell=new Gu(j):a.unitcell=void 0,(ct.length||lt.length)&&Va(a,at),a.finalizeAtoms(),t||Ha(a),Wa(a,this.inferBonds),a.finalizeBonds(),ct.length||lt.length||Ga(a),Za(a),De&&Me.timeEnd("PdbParser._parse "+this.name)}}ze.add("pdb",Xu),ze.add("pdb1",Xu),ze.add("ent",Xu);const Yu=/\s+/,Ku=/'((?:(?!'\s).)*)'|"((?:(?!"\s).)*)"|(\S+)/g,Zu=/"/g,Qu=/^['"]+|['"]+$/g,Ju=/^\D{1,2}/;function tm(t){return!t||t[0]!==t[t.length-1]||"'"!==t[0]&&'"'!==t[0]?t:t.substring(1,t.length-1)}function em(t,e){Array.isArray(t[e])||Object.keys(t).forEach((function(e){t[e]=[t[e]]}))}function im(t){return"?"!==t}function rm(t,e){return im(t)?t:e}function sm(t){switch(t.toLowerCase()){case"?":case"sing":return 1;case"doub":return 2;case"trip":return 3;case"quad":return 4}return 0}class nm extends Nu{get type(){return"cif"}_parse(){Me.time("CifParser._parse "+this.name);var t,r,s,n,o,a,c,l,h,d,u,m,p,f,g,y,b,x,v,w,A,_,S=this.structure,C=this.structureBuilder,P=this.firstModelOnly,I=this.asTrajectory,k=this.cAlphaOnly,M=S.frames,T={},B={},D={},$=!1,O=null,R=!1,E=!1,F=!1,L=[],N=null,z=null,V=null,G=null,U=[],j=S.atomMap,H=S.atomStore;H.resize(this.streamer.data.length/100);var W,q=0,X=0;if(this.streamer.eachChunkOfLines((function(e){!function(e,i,Y){for(var K=e;K<i;++K)if(s=Y[K],((n=s.trim())||$||E)&&"#"!==n[0])if("data_"===n.substring(0,5))T.data=n.substring(5).trim();else if(";"===n[0])$?(E?(N===L.length&&(N=0),L[N].push(O),N+=1):!1===V?T[z]=O:T[z][V]=O,$=!1,O=null):($=!0,O=n.substring(1));else if("loop_"===n)E=!0,F=!0,L.length=0,U.length=0,N=0;else if("_"===n[0]){var Z,Q,J;if(E&&!F&&(E=!1),E)Q=(Z=n.split("."))[0].substring(1),J=Z[1],1===Z.length?(J=!1,T[Q]||(T[Q]=[]),L.push(T[Q])):(T[Q]||(T[Q]={}),T[Q][J]?De&&Me.warn(Q,J,"already exists"):(T[Q][J]=[],L.push(T[Q][J]),U.push(J))),z=Q,V=J,G=!0;else{var tt=n.match(Ku),et=tt[0],it=tt[1];Q=(Z=et.split("."))[0].substring(1),J=Z[1],1===Z.length?(J=!1,T[Q]=it):(T[Q]||(T[Q]={}),T[Q][J]?De&&Me.warn(Q,J,"already exists"):T[Q][J]=it),it||(R=!0),z=Q,V=J}}else if($)O+=s;else if(E){if(!n)continue;if("atom_site"===z){const e=n.split(Yu);G&&(o=U.indexOf("auth_asym_id"),a=U.indexOf("auth_seq_id"),c=U.indexOf("label_seq_id"),l=U.indexOf("label_atom_id"),h=U.indexOf("label_comp_id"),d=U.indexOf("label_asym_id"),u=U.indexOf("label_entity_id"),m=U.indexOf("label_alt_id"),x=U.indexOf("Cartn_x"),v=U.indexOf("Cartn_y"),w=U.indexOf("Cartn_z"),f=U.indexOf("id"),g=U.indexOf("type_symbol"),p=U.indexOf("group_PDB"),A=U.indexOf("B_iso_or_equiv"),y=U.indexOf("pdbx_PDB_model_num"),b=U.indexOf("pdbx_PDB_ins_code"),_=U.indexOf("occupancy"),G=!1,W=parseInt(e[y]),I&&(t=[],r=0));const i=parseInt(e[y]);if(W!==i&&(I&&(0===X&&M.push(new Float32Array(t)),t=new Float32Array(3*H.count),M.push(t),r=0),X+=1),W=i,P&&X>0)continue;const s=e[l].replace(Zu,"");if(k&&"CA"!==s)continue;const T=parseFloat(e[x]),$=parseFloat(e[v]),O=parseFloat(e[w]);if(I){const e=3*r;if(t[e+0]=T,t[e+1]=$,t[e+2]=O,r+=1,X>0)continue}const R=e[h],E=parseInt(e[-1!==a?a:c]);let F=e[b];F="?"===F?"":F;const L=e[o],N=e[d],z="H"===e[p][0],V=e[g],Y=parseFloat(e[A]),K=parseFloat(e[_]);let Z=e[m];if(Z="."===Z?"":Z,H.growIfFull(),H.atomTypeId[q]=j.add(s,V),H.x[q]=T,H.y[q]=$,H.z[q]=O,H.serial[q]=parseInt(e[f]),H.bfactor[q]=isNaN(Y)?0:Y,H.occupancy[q]=isNaN(K)?0:K,H.altloc[q]=Z.charCodeAt(0),C.addAtom(X,L,N,R,E,z,void 0,F),De){const t=B[N];void 0!==t&&t!==L&&De&&Me.warn(t,L)}B[N]=L;const Q=e[u];D[Q]||(D[Q]=new Set),D[Q].add(S.chainStore.count-1),q+=1}else{const t=n.match(Ku),e=t.length;N===L.length&&(N=0);for(let i=0;i<e;++i)L[N+i].push(t[i]);N+=e}F=!1}else if("'"===n[0]&&"'"===n[n.length-1]){const t=n.substring(1,n.length-1);!1===V?T[z]=t:T[z][V]=t}else R?!1===V?T[z]=n:T[z][V]=n:De&&Me.log("CifParser._parse: unknown state",n);else $=!1,E=!1,R=!1,L.length=0,N=null,z=null,V=null,G=null,U.length=0}(0,e.length,e)})),T.chem_comp&&T.chem_comp_atom&&!T.struct)!function(t,e,i){const r=e.atomStore,s=e.atomMap;let n,o;const a=t.chem_comp,c=t.chem_comp_atom,l=t.chem_comp_bond;a&&(a.name&&(e.title=a.name.trim().replace(Qu,"")),a.id&&(e.id=a.id.trim().replace(Qu,"")));var h={};if(c){var d,u,m,p;for(em(c,"comp_id"),o=c.comp_id.length,n=0;n<o;++n)r.growIfFull(),d=c.atom_id[n].replace(Zu,""),u=c.type_symbol[n],h[d]=n,r.atomTypeId[n]=s.add(d,u),r.x[n]=c.model_Cartn_x[n],r.y[n]=c.model_Cartn_y[n],r.z[n]=c.model_Cartn_z[n],r.serial[n]=n,m=c.pdbx_component_comp_id[n],p=c.pdbx_residue_numbering?c.pdbx_residue_numbering[n]:1,i.addAtom(0,"","",m,p,!0);for(n=0;n<o;++n){var f=n+o;r.growIfFull(),d=c.atom_id[n].replace(Zu,""),u=c.type_symbol[n],r.atomTypeId[f]=s.add(d,u),r.x[f]=c.pdbx_model_Cartn_x_ideal[n],r.y[f]=c.pdbx_model_Cartn_y_ideal[n],r.z[f]=c.pdbx_model_Cartn_z_ideal[n],r.serial[f]=f,m=c.pdbx_component_comp_id[n],p=c.pdbx_residue_numbering?c.pdbx_residue_numbering[n]:1,i.addAtom(1,"","",m,p,!0)}}if(c&&l){var g,y,b;em(l,"comp_id"),o=l.comp_id.length;var x=c.comp_id.length,v=e.getAtomProxy(),w=e.getAtomProxy();for(n=0;n<o;++n)g=l.atom_id_1[n].replace(Zu,""),y=l.atom_id_2[n].replace(Zu,""),b=sm(l.value_order[n]),v.index=h[g],w.index=h[y],e.bondStore.growIfFull(),e.bondStore.addBond(v,w,b),v.index+=x,w.index+=x,e.bondStore.growIfFull(),e.bondStore.addBond(v,w,b)}}(T,S,C),C.finalize(),S.finalizeAtoms(),S.finalizeBonds(),ec(S);else if(T.atom_site_type_symbol&&T.atom_site_label&&T.atom_site_fract_x)!function(t,r,s){var n,o=r.atomStore,a=r.atomMap;t.data&&(r.id=t.data,r.name=t.data),r.unitcell=new Gu({a:parseFloat(t.cell_length_a),b:parseFloat(t.cell_length_b),c:parseFloat(t.cell_length_c),alpha:parseFloat(t.cell_angle_alpha),beta:parseFloat(t.cell_angle_beta),gamma:parseFloat(t.cell_angle_gamma),spacegroup:tm(t["symmetry_space_group_name_H-M"])});const c=new e,l=new e,h=t.atom_site_type_symbol.length,d={};for(let e=0;e<h;++e){o.growIfFull();const i=t.atom_site_label[e],h=t.atom_site_type_symbol[e];let u=d[h];if(!u){const t=h.match(Ju);d[h]=u=null!==(n=null==t?void 0:t[0])&&void 0!==n?n:h}o.atomTypeId[e]=a.add(i,u),c.set(t.atom_site_fract_x[e],t.atom_site_fract_y[e],t.atom_site_fract_z[e]),c.applyMatrix4(r.unitcell.fracToCart),l.add(c),o.x[e]=c.x,o.y[e]=c.y,o.z[e]=c.z,t.atom_site_occupancy&&(o.occupancy[e]=parseFloat(t.atom_site_occupancy[e])),o.serial[e]=e,s.addAtom(0,"","","HET",1,!0)}l.divideScalar(h),r.center=l,Za(r);const u=new e,m=new e,p=r.biomolDict.SUPERCELL.partList[0].matrixList;let f=h;function g(t){return a.get(o.atomTypeId[t]).covalent}const y=new i;for(let t=0;t<h;++t){const e=g(t);c.set(o.x[t],o.y[t],o.z[t]),p.forEach((function(i){if(!y.equals(i)){u.copy(c),u.applyMatrix4(i);for(let i=0;i<h;++i){m.set(o.x[i],o.y[i],o.z[i]);const r=u.distanceToSquared(m),n=g(i)+e,a=n+.3,c=n-.5;if(r<a*a&&r>c*c)return o.growIfFull(),o.atomTypeId[f]=o.atomTypeId[t],o.x[f]=u.x,o.y[f]=u.y,o.z[f]=u.z,o.occupancy[f]=o.occupancy[t],o.serial[f]=f,o.altloc[f]="A".charCodeAt(0),s.addAtom(0,"","","HET",1,!0),void(f+=1)}}}))}}(T,S,C),C.finalize(),S.finalizeAtoms(),Wa(S),S.finalizeBonds();else{var Y=function(t,e,i){var r,s,n,o,a=[],c=[],l=t.struct_conf;if(null==l?void 0:l.pdbx_PDB_helix_class)for(em(l,"id"),r=0,s=l.beg_auth_seq_id.length;r<s;++r){var h=parseInt(l.pdbx_PDB_helix_class[r]);Number.isNaN(h)||(n=l.pdbx_beg_PDB_ins_code[r],o=l.pdbx_end_PDB_ins_code[r],a.push([i[l.beg_label_asym_id[r]],parseInt(l.beg_auth_seq_id[r]),rm(n,""),i[l.end_label_asym_id[r]],parseInt(l.end_auth_seq_id[r]),rm(o,""),(Uu[h]||Uu[0]).charCodeAt(0)]))}var d=t.struct_sheet_range;if(d)for(em(d,"id"),r=0,s=d.beg_auth_seq_id.length;r<s;++r)n=d.pdbx_beg_PDB_ins_code[r],o=d.pdbx_end_PDB_ins_code[r],c.push([i[d.beg_label_asym_id[r]],parseInt(d.beg_auth_seq_id[r]),rm(n,""),i[d.end_label_asym_id[r]],parseInt(d.end_auth_seq_id[r]),rm(o,"")]);return!(!l&&!d)&&{helices:a,sheets:c}}(T,0,B);if(function(t,e,r){var s={},n=e.biomolDict;if(t.pdbx_struct_oper_list){var o=t.pdbx_struct_oper_list;em(o,"id"),o.id.forEach((function(t,e){var r=new i,n=r.elements;n[0]=parseFloat(o["matrix[1][1]"][e]),n[1]=parseFloat(o["matrix[1][2]"][e]),n[2]=parseFloat(o["matrix[1][3]"][e]),n[4]=parseFloat(o["matrix[2][1]"][e]),n[5]=parseFloat(o["matrix[2][2]"][e]),n[6]=parseFloat(o["matrix[2][3]"][e]),n[8]=parseFloat(o["matrix[3][1]"][e]),n[9]=parseFloat(o["matrix[3][2]"][e]),n[10]=parseFloat(o["matrix[3][3]"][e]),n[3]=parseFloat(o["vector[1]"][e]),n[7]=parseFloat(o["vector[2]"][e]),n[11]=parseFloat(o["vector[3]"][e]),r.transpose(),s[t]=r}))}if(t.pdbx_struct_assembly_gen){var a=t.pdbx_struct_assembly_gen;em(a,"assembly_id");var c=function(t){var e={};return t.replace(/[()']/g,"").split(",").forEach((function(t){if(t.includes("-"))for(var i=t.split("-"),r=parseInt(i[0]),n=parseInt(i[1]);r<=n;++r)e[r]=s[r];else e[t]=s[t]})),e};a.assembly_id.forEach((function(t,e){var s={},o=a.oper_expression[e].replace(/['"]\(|['"]/g,"");if(o.includes(")(")||o.indexOf("(")>0){o=o.split("(");var l=c(o[0]),h=c(o[1]);Object.keys(l).forEach((function(t){Object.keys(h).forEach((function(e){var r=new i;r.multiplyMatrices(l[t],h[e]),s[t+"x"+e]=r}))}))}else s=c(o);var d=[];for(var u in s)d.push(s[u]);var m=t;/^(0|[1-9][0-9]*)$/.test(m)&&(m="BU"+m);for(var p=a.asym_id_list[e].split(","),f=0,g=p.length;f<g;++f)p[f]=r[p[f]];void 0===n[m]&&(n[m]=new La(m)),n[m].addPart(d,p)}))}if(t.struct_ncs_oper){var l=t.struct_ncs_oper;em(l,"id");var h="NCS";n[h]=new La(h);var d=n[h].addPart();l.id.forEach((function(t,e){if("given"!==l.code[e]){var r=new i,s=r.elements;s[0]=parseFloat(l["matrix[1][1]"][e]),s[1]=parseFloat(l["matrix[1][2]"][e]),s[2]=parseFloat(l["matrix[1][3]"][e]),s[4]=parseFloat(l["matrix[2][1]"][e]),s[5]=parseFloat(l["matrix[2][2]"][e]),s[6]=parseFloat(l["matrix[2][3]"][e]),s[8]=parseFloat(l["matrix[3][1]"][e]),s[9]=parseFloat(l["matrix[3][2]"][e]),s[10]=parseFloat(l["matrix[3][3]"][e]),s[3]=parseFloat(l["vector[1]"][e]),s[7]=parseFloat(l["vector[2]"][e]),s[11]=parseFloat(l["vector[3]"][e]),r.transpose(),d.matrixList.push(r)}})),0===d.matrixList.length&&delete n[h]}const u={};if(t.cell){const i=t.cell,r=parseFloat(i.length_a),s=parseFloat(i.length_b),n=parseFloat(i.length_c),o=new Float32Array(9);o[0]=r,o[4]=s,o[8]=n,e.boxes.push(o),u.a=r,u.b=s,u.c=n,u.alpha=parseFloat(i.angle_alpha),u.beta=parseFloat(i.angle_beta),u.gamma=parseFloat(i.angle_gamma)}t.symmetry&&(u.spacegroup=tm(t.symmetry["space_group_name_H-M"]));var m=new i;if(t.database_PDB_matrix){var p=t.database_PDB_matrix,f=m.elements;f[0]=parseFloat(p["origx[1][1]"]),f[1]=parseFloat(p["origx[1][2]"]),f[2]=parseFloat(p["origx[1][3]"]),f[4]=parseFloat(p["origx[2][1]"]),f[5]=parseFloat(p["origx[2][2]"]),f[6]=parseFloat(p["origx[2][3]"]),f[8]=parseFloat(p["origx[3][1]"]),f[9]=parseFloat(p["origx[3][2]"]),f[10]=parseFloat(p["origx[3][3]"]),f[3]=parseFloat(p["origx_vector[1]"]),f[7]=parseFloat(p["origx_vector[2]"]),f[11]=parseFloat(p["origx_vector[3]"]),m.transpose(),u.origx=m}var g=new i;if(t.atom_sites){var y=t.atom_sites,b=g.elements;b[0]=parseFloat(y["fract_transf_matrix[1][1]"]),b[1]=parseFloat(y["fract_transf_matrix[1][2]"]),b[2]=parseFloat(y["fract_transf_matrix[1][3]"]),b[4]=parseFloat(y["fract_transf_matrix[2][1]"]),b[5]=parseFloat(y["fract_transf_matrix[2][2]"]),b[6]=parseFloat(y["fract_transf_matrix[2][3]"]),b[8]=parseFloat(y["fract_transf_matrix[3][1]"]),b[9]=parseFloat(y["fract_transf_matrix[3][2]"]),b[10]=parseFloat(y["fract_transf_matrix[3][3]"]),b[3]=parseFloat(y["fract_transf_vector[1]"]),b[7]=parseFloat(y["fract_transf_vector[2]"]),b[11]=parseFloat(y["fract_transf_vector[3]"]),g.transpose(),u.scale=g}void 0!==u.a?e.unitcell=new Gu(u):e.unitcell=void 0}(T,S,B),function(t,e,i){var r=t.struct_conn;if(r){em(r,"id");for(var s=/"/g,n=e.getAtomProxy(),o=e.getAtomProxy(),a={},c=0,l=r.id.length;c<l;++c){var h=r.conn_type_id[c];if("hydrog"!==h&&"mismat"!==h&&"saltbr"!==h&&"1_555"===r.ptnr1_symmetry[c]&&"1_555"===r.ptnr2_symmetry[c]){var d=r.pdbx_ptnr1_PDB_ins_code[c],u=r.pdbx_ptnr1_label_alt_id[c],m=r.ptnr1_auth_seq_id[c]+(im(d)?"^"+d:"")+":"+i[r.ptnr1_label_asym_id[c]]+"."+r.ptnr1_label_atom_id[c].replace(s,"")+(im(u)?"%"+u:""),p=a[m];if(!p){var f=new pe(m);if(f.selection.error){De&&Me.warn("invalid selection for connection",m);continue}p=e.getAtomIndices(f),a[m]=p}var g=r.pdbx_ptnr2_PDB_ins_code[c],y=r.pdbx_ptnr2_label_alt_id[c],b=r.ptnr2_auth_seq_id[c]+(im(g)?"^"+g:"")+":"+i[r.ptnr2_label_asym_id[c]]+"."+r.ptnr2_label_atom_id[c].replace(s,"")+(im(y)?"%"+y:""),x=a[b];if(!x){var v=new pe(b);if(v.selection.error){De&&Me.warn("invalid selection for connection",b);continue}x=e.getAtomIndices(v),a[b]=x}var w=p.length,A=x.length;if(w>A){var _=w;w=A,A=_;var S=p;p=x,x=S}if(0!==w&&0!==A)for(var C=0;C<A;++C)n.index=p[C%w],o.index=x[C],n&&o?e.bondStore.addBond(n,o,sm(r.pdbx_value_order[c])):Me.log("atoms for connection not found");else De&&Me.warn("no atoms found for",m,b)}}}}(T,S,B),function(t,e,i){if(t.entity){em(t.entity,"id");for(var r=t.entity,s=r.id.length,n=0;n<s;++n){var o=r.pdbx_description[n],a=r.type[n],c=Array.from(i[r.id[n]]);e.entityList[n]=new zu(e,n,o,a,c)}}}(T,S,D),T.struct&&T.struct.title&&(S.title=T.struct.title.trim().replace(Qu,"")),T.entry&&T.entry.id&&(S.id=T.entry.id.trim().replace(Qu,"")),T.pdbx_audit_revision_history){if(T.pdbx_audit_revision_history.revision_date){em(T.pdbx_audit_revision_history,"revision_date");const t=T.pdbx_audit_revision_history.revision_date.filter(im);t.length&&(S.header.releaseDate=t[0])}if(T.pdbx_database_status.recvd_initial_deposition_date){em(T.pdbx_database_status,"recvd_initial_deposition_date");const t=T.pdbx_database_status.recvd_initial_deposition_date.filter(im);t.length&&(S.header.depositionDate=t[0])}}else if(T.database_PDB_rev){if(T.database_PDB_rev.date){em(T.database_PDB_rev,"date");const t=T.database_PDB_rev.date.filter(im);t.length&&(S.header.releaseDate=t[0])}if(T.database_PDB_rev.date_original){em(T.database_PDB_rev,"date_original");const t=T.database_PDB_rev.date_original.filter(im);t.length&&(S.header.depositionDate=t[0])}}T.reflns&&T.reflns.d_resolution_high?im(T.reflns.d_resolution_high)&&(S.header.resolution=parseFloat(T.reflns.d_resolution_high)):T.refine&&T.refine.ls_d_res_high&&im(T.refine.ls_d_res_high)&&(S.header.resolution=parseFloat(T.refine.ls_d_res_high)),T.refine&&T.refine.ls_R_factor_R_free&&im(T.refine.ls_R_factor_R_free)&&(S.header.rFree=parseFloat(T.refine.ls_R_factor_R_free)),T.refine&&T.refine.ls_R_factor_R_work&&im(T.refine.ls_R_factor_R_work)&&(S.header.rWork=parseFloat(T.refine.ls_R_factor_R_work)),T.exptl&&T.exptl.method&&(em(T.exptl,"method"),S.header.experimentalMethods=T.exptl.method.map((function(t){return t.replace(Qu,"")}))),C.finalize(),S.finalizeAtoms(),Wa(S),S.finalizeBonds(),Y?Va(S,Y):Ga(S),Za(S),S.extraData.cif=T}De&&Me.timeEnd("CifParser._parse "+this.name)}}ze.add("cif",nm),ze.add("mcif",nm),ze.add("mmcif",nm);ze.add("gro",class extends Nu{get type(){return"gro"}_parse(){De&&Me.time("GroParser._parse "+this.name);var t,e,i=this.structure,r=this.structureBuilder,s=this.firstModelOnly,n=this.asTrajectory,o=this.cAlphaOnly,a=i.frames,c=i.boxes,l=this.streamer.peekLines(3);i.title=l[0].trim();var h,d,u,m,p=5+(l[2].length-l[2].lastIndexOf(".")-1),f=20+p,g=20+2*p,y=parseInt(l[1]),b=y+3,x=i.atomMap,v=i.atomStore;v.resize(y);var w=0,A=0,_=0;this.streamer.eachChunkOfLines((function(i){!function(i,l,S){for(var C=i;C<l;++C){var P=++_-1,I=S[C];if(I)if(P%b==0)n&&(t=new Float32Array(3*y),a.push(t),e=0);else if(P%b==1);else if(P%b==b-1){var k=I.trim().split(/\s+/),M=new Float32Array(9);if(M[0]=10*parseFloat(k[0]),M[4]=10*parseFloat(k[1]),M[8]=10*parseFloat(k[2]),c.push(M),s)return!0;A+=1}else{if(h=I.substr(10,5).trim(),o&&"CA"!==h)continue;var T=10*parseFloat(I.substr(20,p)),B=10*parseFloat(I.substr(f,p)),D=10*parseFloat(I.substr(g,p));if(n){var $=3*e;if(t[$+0]=T,t[$+1]=B,t[$+2]=D,e+=1,P>b)continue}d=I.substr(5,5).trim(),u=parseInt(I.substr(0,5)),m=parseInt(I.substr(15,5)),v.growIfFull(),v.atomTypeId[w]=x.add(h),v.x[w]=T,v.y[w]=B,v.z[w]=D,v.serial[w]=m,r.addAtom(A,"","",d,u,!1,"l"),w+=1}}}(0,i.length,i)})),r.finalize(),i.finalizeAtoms(),Ha(i),Wa(i),i.finalizeBonds(),Ga(i),De&&Me.timeEnd("GroParser._parse "+this.name)}});var om=["mmtfVersion","mmtfProducer","unitCell","spaceGroup","structureId","title","depositionDate","releaseDate","experimentalMethods","resolution","rFree","rWork","bioAssemblyList","ncsOperatorList","entityList","groupList","numBonds","numAtoms","numGroups","numChains","numModels","groupsPerChain","chainsPerModel"].concat(["xCoordList","yCoordList","zCoordList","groupIdList","groupTypeList","chainIdList","bFactorList","atomIdList","altLocList","occupancyList","secStructList","insCodeList","sequenceIndexList","chainNameList","bondAtomList","bondOrderList"]);function am(t,e,i){return e?new t(e.buffer,e.byteOffset,e.byteLength/(i||1)):void 0}function cm(t){return am(DataView,t)}function lm(t){return am(Int8Array,t)}function hm(t){return am(Int32Array,t,4)}function dm(t,e){var i=t.length/2;e||(e=new Int16Array(i));for(var r=0,s=0;r<i;++r,s+=2)e[r]=t[s]<<8^t[s+1]<<0;return e}function um(t,e){var i=t.length/4;e||(e=new Int32Array(i));for(var r=0,s=0;r<i;++r,s+=4)e[r]=t[s]<<24^t[s+1]<<16^t[s+2]<<8^t[s+3]<<0;return e}function mm(t,e,i){var r=t.length,s=1/e;i||(i=new Float32Array(r));for(var n=0;n<r;++n)i[n]=t[n]*s;return i}function pm(t,e){var i,r;if(!e){var s=0;for(i=0,r=t.length;i<r;i+=2)s+=t[i+1];e=new t.constructor(s)}var n=0;for(i=0,r=t.length;i<r;i+=2)for(var o=t[i],a=t[i+1],c=0;c<a;++c)e[n]=o,++n;return e}function fm(t,e){var i=t.length;e||(e=new t.constructor(i)),i&&(e[0]=t[0]);for(var r=1;r<i;++r)e[r]=t[r]+e[r-1];return e}function gm(t,e){var i,r,s=t instanceof Int8Array?127:32767,n=-s-1,o=t.length;if(!e){var a=0;for(i=0;i<o;++i)t[i]<s&&t[i]>n&&++a;e=new Int32Array(a)}for(i=0,r=0;i<o;){for(var c=0;t[i]===s||t[i]===n;)c+=t[i],++i;c+=t[i],++i,e[r]=c,++r}return e}function ym(t,e,i){return mm(gm(t,hm(i)),e,i)}function bm(t,e,i){var r=gm(t,hm(i));return function(t,e,i){return mm(fm(t,hm(i)),e,i)}(r,e,am(Float32Array,r,4))}function xm(t){var e=0,i=new DataView(t.buffer);function r(t){for(var e={},i=0;i<t;i++){e[a()]=a()}return e}function s(i){var r=t.subarray(e,e+i);return e+=i,r}function n(i){var r=t.subarray(e,e+i);e+=i;var s=65535;if(i>s){for(var n=[],o=0;o<r.length;o+=s)n.push(String.fromCharCode.apply(null,r.subarray(o,o+s)));return n.join("")}return String.fromCharCode.apply(null,r)}function o(t){for(var e=new Array(t),i=0;i<t;i++)e[i]=a();return e}function a(){var a,c,l=t[e];if(0==(128&l))return e++,l;if(128==(240&l))return e++,r(c=15&l);if(144==(240&l))return e++,o(c=15&l);if(160==(224&l))return e++,n(c=31&l);if(224==(224&l))return a=i.getInt8(e),e++,a;switch(l){case 192:return e++,null;case 194:return e++,!1;case 195:return e++,!0;case 196:return c=i.getUint8(e+1),e+=2,s(c);case 197:return c=i.getUint16(e+1),e+=3,s(c);case 198:return c=i.getUint32(e+1),e+=5,s(c);case 202:return a=i.getFloat32(e+1),e+=5,a;case 203:return a=i.getFloat64(e+1),e+=9,a;case 204:return a=t[e+1],e+=2,a;case 205:return a=i.getUint16(e+1),e+=3,a;case 206:return a=i.getUint32(e+1),e+=5,a;case 208:return a=i.getInt8(e+1),e+=2,a;case 209:return a=i.getInt16(e+1),e+=3,a;case 210:return a=i.getInt32(e+1),e+=5,a;case 217:return c=i.getUint8(e+1),e+=2,n(c);case 218:return c=i.getUint16(e+1),e+=3,n(c);case 219:return c=i.getUint32(e+1),e+=5,n(c);case 220:return c=i.getUint16(e+1),e+=3,o(c);case 221:return c=i.getUint32(e+1),e+=5,o(c);case 222:return c=i.getUint16(e+1),e+=3,r(c);case 223:return c=i.getUint32(e+1),e+=5,r(c)}throw new Error("Unknown type 0x"+l.toString(16))}return a()}function vm(t,e,i,r){switch(t){case 1:return function(t,e){var i=t.length;e||(e=new Float32Array(i/4));for(var r=cm(e),s=cm(t),n=0,o=0,a=i/4;n<a;++n,o+=4)r.setFloat32(o,s.getFloat32(o),!0);return e}(e);case 2:return lm(e);case 3:return dm(e);case 4:return um(e);case 5:return am(Uint8Array,e);case 6:return pm(um(e),new Uint8Array(i));case 7:return pm(um(e));case 8:return fm(pm(um(e)),s);case 9:return function(t,e,i){return mm(pm(t,hm(i)),e,i)}(um(e),um(r)[0]);case 10:return bm(dm(e),um(r)[0]);case 11:return mm(dm(e),um(r)[0]);case 12:return ym(dm(e),um(r)[0]);case 13:return ym(lm(e),um(r)[0]);case 14:return gm(dm(e));case 15:return gm(lm(e))}var s}function wm(t,e){var i=(e=e||{}).ignoreFields,r={};return om.forEach((function(e){var s,n,o,a,c,l=!!i&&-1!==i.indexOf(e),h=t[e];l||void 0===h||(h instanceof Uint8Array?r[e]=vm.apply(null,(n=cm(s=h),o=n.getInt32(0),a=n.getInt32(4),c=s.subarray(8,12),[o,s=s.subarray(12),a,c])):r[e]=h)})),r}const Am={0:"i".charCodeAt(0),1:"s".charCodeAt(0),2:"h".charCodeAt(0),3:"e".charCodeAt(0),4:"g".charCodeAt(0),5:"b".charCodeAt(0),6:"t".charCodeAt(0),7:"l".charCodeAt(0),"-1":"".charCodeAt(0)};ze.add("mmtf",class extends Nu{get type(){return"mmtf"}get isBinary(){return!0}_parse(){let t,e,r,s,n;De&&Me.time("MmtfParser._parse "+this.name);const o=this.structure,a=wm(xm(this.streamer.data));let c,l,h,d,u,m;if(["depositionDate","releaseDate","resolution","rFree","rWork","experimentalMethods"].forEach((function(t){void 0!==a[t]&&(o.header[t]=a[t])})),o.id=a.structureId,o.title=a.title,o.atomStore.addField("formalCharge",1,"int8"),this.firstModelOnly||this.asTrajectory){for(u=1,d=a.chainsPerModel[0],h=0,t=0,e=d;t<e;++t)h+=a.groupsPerChain[t];for(l=0,t=0,e=h;t<e;++t)n=a.groupList[a.groupTypeList[t]],l+=n.atomNameList.length;c=a.numBonds,m=[d]}else c=a.numBonds,l=a.numAtoms,h=a.numGroups,d=a.numChains,u=a.numModels,m=a.chainsPerModel;if(c+=h,this.asTrajectory)for(t=0,e=a.numModels;t<e;++t){const e=new Float32Array(3*l),i=l*t;for(r=0;r<l;++r){const t=3*r,s=r+i;e[t]=a.xCoordList[s],e[t+1]=a.yCoordList[s],e[t+2]=a.zCoordList[s]}o.frames.push(e)}const p=new Uint32Array(c),f=new Uint32Array(c),g=new Uint8Array(c),y=new Uint32Array(l),b=new Int8Array(l),x=new Uint32Array(h),v=new Uint32Array(h),w=new Uint16Array(h),A=new Uint16Array(d),_=new Uint32Array(d),S=new Uint32Array(d),C=new Uint32Array(u),P=new Uint32Array(u);let I=0;for(t=0,e=u;t<e;++t){const e=m[t];for(C[t]=I,P[t]=e,r=0;r<e;++r)A[r+I]=t;I+=e}const k=a.groupsPerChain;let M=0;for(t=0,e=d;t<e;++t){const e=k[t];for(_[t]=M,S[t]=e,r=0;r<e;++r)x[r+M]=t;M+=e}let T=0,B=0;for(t=0,e=h;t<e;++t){n=a.groupList[a.groupTypeList[t]];const e=n.atomNameList.length,i=n.formalChargeList,o=n.bondAtomList,c=n.bondOrderList;for(r=0,s=c.length;r<s;++r)p[B]=T+o[2*r],f[B]=T+o[2*r+1],g[B]=c[r],B+=1;for(v[t]=T,w[t]=e,r=0;r<e;++r)y[T]=t,b[T]=i[r],T+=1}const D=a.bondAtomList;if(D)for(a.bondOrderList&&g.set(a.bondOrderList,B),t=0,e=D.length;t<e;t+=2){const e=D[t],i=D[t+1];e<l&&i<l&&(p[B]=e,f[B]=i,B+=1)}o.bondStore.length=g.length,o.bondStore.count=B,o.bondStore.atomIndex1=p,o.bondStore.atomIndex2=f,o.bondStore.bondOrder=g,o.atomStore.length=l,o.atomStore.count=l,o.atomStore.residueIndex=y,o.atomStore.atomTypeId=new Uint16Array(l),o.atomStore.x=a.xCoordList.subarray(0,l),o.atomStore.y=a.yCoordList.subarray(0,l),o.atomStore.z=a.zCoordList.subarray(0,l),o.atomStore.serial=a.atomIdList.subarray(0,l),o.atomStore.bfactor=a.bFactorList.subarray(0,l),o.atomStore.altloc=a.altLocList.subarray(0,l),o.atomStore.occupancy=a.occupancyList.subarray(0,l),o.atomStore.formalCharge=b,o.residueStore.length=h,o.residueStore.count=h,o.residueStore.chainIndex=x,o.residueStore.residueTypeId=a.groupTypeList,o.residueStore.atomOffset=v,o.residueStore.atomCount=w,o.residueStore.resno=a.groupIdList.subarray(0,h),o.residueStore.sstruc=a.secStructList.subarray(0,h),o.residueStore.inscode=a.insCodeList.subarray(0,h),o.chainStore.length=d,o.chainStore.count=d,o.chainStore.entityIndex=new Uint16Array(d),o.chainStore.modelIndex=A,o.chainStore.residueOffset=_,o.chainStore.residueCount=S,o.chainStore.chainname=a.chainNameList.subarray(0,4*d),o.chainStore.chainid=a.chainIdList.subarray(0,4*d),o.modelStore.length=u,o.modelStore.count=u,o.modelStore.chainOffset=C,o.modelStore.chainCount=P;let $={};for(t=0,e=a.groupList.length;t<e;++t){const e=a.groupList[t],i=[];for(r=0,s=e.atomNameList.length;r<s;++r){const t=e.elementList[r].toUpperCase(),s=e.atomNameList[r];i.push(o.atomMap.add(s,t))}const n=e.chemCompType.toUpperCase(),c=js.includes(n),l=e.bondOrderList.length,h=new Array(l),d=new Array(l);for(r=0;r<l;++r)h[r]=e.bondAtomList[2*r],d[r]=e.bondAtomList[2*r+1];const u={atomIndices1:h,atomIndices2:d,bondOrders:e.bondOrderList};$[t]=o.residueMap.add(e.groupName,i,c,n,u)}for(t=0,e=h;t<e;++t)o.residueStore.residueTypeId[t]=$[o.residueStore.residueTypeId[t]];for(t=0,e=o.atomStore.count;t<e;++t){const e=o.atomStore.residueIndex[t],i=o.residueMap.list[o.residueStore.residueTypeId[e]],r=o.residueStore.atomOffset[e];o.atomStore.atomTypeId[t]=i.atomTypeIdList[t-r]}if(a.secStructList){const i=a.secStructList.length;for(t=0,e=o.residueStore.count;t<e;++t){const e=Am[o.residueStore.sstruc[t%i]];void 0!==e&&(o.residueStore.sstruc[t]=e)}}if(a.entityList&&a.entityList.forEach((function(t,e){o.entityList[e]=new zu(o,e,t.description,t.type,t.chainIndexList)})),a.bioAssemblyList&&a.bioAssemblyList.forEach((function(t,e){const r=e+1,s=new La(""+r);o.biomolDict["BU"+r]=s;let n={};t.transformList.forEach((function(t){const e=(new i).fromArray(t.matrix).transpose(),r=t.chainIndexList.map((function(t){let e="";for(let i=0;i<4;++i){const r=a.chainNameList[4*t+i];if(!r)break;e+=String.fromCharCode(r)}return e})),o=n[r.toString()];o?o.matrixList.push(e):n[r.toString()]=s.addPart([e],r)}))})),a.ncsOperatorList){const t="NCS",e=new La(t),r=e.addPart();a.ncsOperatorList.forEach((function(t){const e=(new i).fromArray(t).transpose();r.matrixList.push(e)})),r.matrixList.length>0&&(o.biomolDict[t]=e)}const O=a.unitCell;O&&Array.isArray(O)&&O[0]?o.unitcell=new Gu({a:O[0],b:O[1],c:O[2],alpha:O[3],beta:O[4],gamma:O[5],spacegroup:a.spaceGroup}):o.unitcell=void 0,Ka(o,!0),Ya(o,!0),o.finalizeAtoms(),o.finalizeBonds(),Za(o),De&&Me.timeEnd("MmtfParser._parse "+this.name)}});const _m=/\s+/,Sm={1:1,2:2,3:3,am:1,ar:1,du:1,un:1,nc:0};ze.add("mol2",class extends Nu{get type(){return"mol2"}_parse(){De&&Me.time("Mol2Parser._parse "+this.name);const t=this.structure,e=this.structureBuilder,i=this.firstModelOnly,r=this.asTrajectory,s=t.frames;let n,o,a=!1;const c=t.atomMap,l=t.atomStore;l.resize(Math.round(this.streamer.data.length/60)),l.addField("partialCharge",1,"float32");let h=0,d=0,u=0,m=-1,p=0,f=0;const g=t.getAtomProxy(),y=t.getAtomProxy();this.streamer.eachChunkOfLines((function(b){!function(b,x,v){for(let w=b;w<x;++w){const b=v[w].trim();if(""!==b&&"#"!==b[0])if("@"===b[0])"@<TRIPOS>MOLECULE"===b?(f=1,d=0,++m):"@<TRIPOS>ATOM"===b?(f=2,u=l.count,r&&(o=0,n=new Float32Array(3*p),s.push(n),m>0&&(a=!0))):f="@<TRIPOS>BOND"===b?3:0;else if(1===f){if(0===d)t.title=b,t.id=b;else if(1===d){const t=b.split(_m);p=parseInt(t[0])}++d}else if(2===f){const t=b.split(_m);if(i&&m>0)continue;const s=parseFloat(t[2]),d=parseFloat(t[3]),u=parseFloat(t[4]);if(r){const t=3*o;if(n[t+0]=s,n[t+1]=d,n[t+2]=u,o+=1,a)continue}const p=t[0],f=t[1],g=t[5].split(".")[0],y=t[6]?parseInt(t[6]):1,x=t[7]?t[7]:"",v=t[8]?parseFloat(t[8]):0;l.growIfFull(),l.atomTypeId[h]=c.add(f,g),l.x[h]=s,l.y[h]=d,l.z[h]=u,l.serial[h]=p,l.partialCharge[h]=v,e.addAtom(m,"","",x,y,!0),h+=1}else if(3===f){if(i&&m>0)continue;if(r&&m>0)continue;const e=b.split(_m);g.index=parseInt(e[1])-1+u,y.index=parseInt(e[2])-1+u;const s=Sm[e[3]];t.bondStore.addBond(g,y,s)}}}(0,b.length,b)})),e.finalize(),t.finalizeAtoms(),Ha(t),Ya(t,!0),Ka(t,!0),t.finalizeBonds(),ec(t),Ga(t),De&&Me.timeEnd("Mol2Parser._parse "+this.name)}});ze.add("pdbqt",class extends Xu{get type(){return"pdbqt"}});ze.add("pqr",class extends Xu{get type(){return"pqr"}});const Cm=/> +<(.+)>/;class Pm extends Nu{get type(){return"sdf"}_parse(){De&&Me.time("SdfParser._parse "+this.name);const t=this.structure,e=this.structureBuilder,i=this.firstModelOnly,r=this.asTrajectory,s=this.streamer.peekLines(2);t.id=s[0].trim(),t.title=s[1].trim();const n=t.frames;let o,a,c=!1;const l=t.atomMap,h=t.atomStore;h.resize(Math.round(this.streamer.data.length/50)),h.addField("formalCharge",1,"int8");const d=t.getAtomProxy(),u=t.getAtomProxy();let m=0,p=0,f=0,g=0;const y=[];let b,x,v,w,A,_,S,C,P,I,k,M,T,B,D=!1,$={};t.extraData.sdf=y;let O=!1,R=!1,E=!1,F=[],L=[];const N=new Map;this.streamer.eachChunkOfLines((function(s){!function(s,z,V){for(let G=s;G<z;++G){const s=V[G];if(O&&s&&(F=s.substring(7).split(" "),L.length&&(F=[...L,...F],L=[]),"-"===F[F.length-1]))F.pop(),L=F;else{if("$$$$"===s.substr(0,4))p=-1,++f,g=h.count,y.push($),$={},D=!1,O=!1;else if(3===p)O=s.indexOf(" V3000")>-1,O?N.clear():(x=parseInt(s.substr(0,3)),v=parseInt(s.substr(3,3)),w=4,A=w+x,_=A,S=_+v,r&&(a=0,o=new Float32Array(3*x),n.push(o),f>0&&(c=!0)));else if(O&&"COUNTS"===F[0])x=parseInt(F[1]),r&&(a=0,o=new Float32Array(3*x),n.push(o),f>0&&(c=!0));else if(O&&2==F.length)"ATOM"===F[1]?"BEGIN"===F[0]?R=!0:"END"===F[0]&&(R=!1):"BOND"===F[1]&&("BEGIN"===F[0]?E=!0:"END"===F[0]&&(E=!1));else if(R||!O&&p>=w&&p<A){if(i&&f>0)continue;let t=0;if(O){if(C=parseFloat(F[2]),P=parseFloat(F[3]),I=parseFloat(F[4]),M=F[1],T=parseInt(F[0]),N.set(T,m),k=M+T,F.length>6){let e=F.slice(6).find((t=>0===t.indexOf("CHG=")));e&&(t=parseInt(e.substring(4)))}}else C=parseFloat(s.substr(0,10)),P=parseFloat(s.substr(10,10)),I=parseFloat(s.substr(20,10)),M=s.substr(31,3).trim(),k=M+(m-g+1);if(r){const t=3*a;if(o[t+0]=C,o[t+1]=P,o[t+2]=I,a+=1,c)continue}h.growIfFull(),h.atomTypeId[m]=l.add(k,M),h.x[m]=C,h.y[m]=P,h.z[m]=I,h.serial[m]=O?T:m,h.formalCharge[m]=t,e.addAtom(f,"","","HET",1,!0),m+=1}else if(E||!O&&p>=_&&p<S){if(i&&f>0)continue;if(r&&f>0)continue;O?(d.index=N.get(parseInt(F[2])),u.index=N.get(parseInt(F[3])),B=parseInt(F[1])):(d.index=parseInt(s.substr(0,3))-1+g,u.index=parseInt(s.substr(3,3))-1+g,B=parseInt(s.substr(6,3))),t.bondStore.addBond(d,u,B)}else if("M  CHG"===s.substr(0,6)){const t=parseInt(s.substr(6,3));for(let e=0,i=10;e<t;++e,i+=8){const t=parseInt(s.substr(i,3))-1+g,e=parseInt(s.substr(i+4,3));h.formalCharge[t]=e}}else">"===s.charAt(0)&&(b=s.match(Cm))?(D=b[1],$[D]=[]):!1!==D&&s&&$[D].push(s);++p}}}(0,s.length,s)})),e.finalize(),t.finalizeAtoms(),t.finalizeBonds(),ec(t),De&&Me.timeEnd("SdfParser._parse "+this.name)}_postProcess(){ec(this.structure)}}ze.add("sdf",Pm),ze.add("sd",Pm),ze.add("mol",Pm);function Im(t,e,i){return parseInt(t.substr(e,i).trim())}class km extends Nu{get type(){return"prmtop"}_parse(){De&&Me.time("PrmtopParser._parse "+this.name);const t=this.structure,e=this.structureBuilder,i=t.atomMap,r=t.atomStore;r.addField("partialCharge",1,"float32"),r.addField("radius",1,"float32");const s=[],n={},o=["NATOM","NTYPES","NBONH","MBONA","NTHETH","MTHETA","NPHIH","MPHIA","NHPARM","NPARM","NNB","NRES","NBONA","NTHETA","NPHIA","NUMBND","NUMANG","NPTRA","NATYP","NPHB","IFPERT","NBPER","NGPER","NDPER","MBPER","MGPER","MDPER","IFBOX","NMXRS","IFCAP","NUMEXTRA","NCOPY"];let a,c,l,h,d;o.forEach((t=>{n[t]=0}));let u,m,p,f,g,y=new Uint8Array(0);this.streamer.eachChunkOfLines((function(t){!function(t,e,i){for(let b=t;b<e;++b){const t=i[b],e=t.trim();if(e)if(t.startsWith("%FORMAT"));else if(t.startsWith("%FLAG")){const e=t.substr(5).trim();f=0,"TITLE"===e?p=0:"POINTERS"===e?p=1:"ATOM_NAME"===e?p=2:"CHARGE"===e?p=3:"MASS"===e?p=4:"RESIDUE_LABEL"===e?p=5:"RESIDUE_POINTER"===e?p=6:"BONDS_INC_HYDROGEN"===e?(g=0,p=7):"BONDS_WITHOUT_HYDROGEN"===e?(g=n.NBONH,p=8):p="RADII"===e?9:void 0}else if(0===p)s.push(e);else if(1===p){const e=Math.min(f+10,32);for(let i=0;f<e;++i,++f)n[o[f]]=parseInt(t.substr(8*i,8).trim());a=new Array(n.NATOM),c=new Float32Array(n.NATOM),l=new Float32Array(n.NATOM),r.resize(n.NATOM);const i=n.NBONH+n.MBONA;h=new Uint32Array(i),d=new Uint32Array(i),y=new Uint8Array(i),u=new Array(n.NRES),m=new Uint32Array(n.NRES)}else if(2===p){const e=Math.min(f+20,n.NATOM);for(let i=0;f<e;++i,++f)a[f]=t.substr(4*i,4).trim()}else if(3===p){const e=Math.min(f+5,n.NATOM);for(let i=0;f<e;++i,++f)c[f]=parseFloat(t.substr(16*i,16))/18.2223}else if(4===p);else if(5===p){const e=Math.min(f+20,n.NRES);for(let i=0;f<e;++i,++f)u[f]=t.substr(4*i,4).trim()}else if(6===p){const e=Math.min(f+10,n.NRES);for(let i=0;f<e;++i,++f)m[f]=Im(t,8*i,8)}else if(7===p){const e=Math.min(f+10,3*n.NBONH);for(let i=0;f<e;++i,++f){const e=f%3;0===e&&(h[g]=Im(t,8*i,8)/3),1===e&&(d[g]=Im(t,8*i,8)/3,y[g]=1,++g)}}else if(8===p){const e=Math.min(f+10,3*n.MBONA);for(let i=0;f<e;++i,++f){const e=f%3;0===e&&(h[g]=Im(t,8*i,8)/3),1===e&&(d[g]=Im(t,8*i,8)/3,y[g]=1,++g)}}else if(9===p){const e=Math.min(f+5,n.NATOM);for(let i=0;f<e;++i,++f)l[f]=parseFloat(t.substr(16*i,16))}}}(0,t.length,t)})),t.title=s.join(" ");const b=n.NATOM;let x=0,v=u[0],w=1;for(let t=0;t<b;++t)t+1===m[x+1]&&(++x,v=u[x],w=x+1),r.atomTypeId[t]=i.add(a[t]),r.serial[t]=t+1,e.addAtom(0,"","",v,w,!1);r.partialCharge.set(c),r.radius.set(l),t.bondStore.length=y.length,t.bondStore.count=y.length,t.bondStore.atomIndex1=h,t.bondStore.atomIndex2=d,t.bondStore.bondOrder=y,e.finalize(),t.finalizeAtoms(),t.finalizeBonds(),Ya(t,!0),Ka(t,!0,!0),Ha(t,!0),ec(t),De&&Me.timeEnd("PrmtopParser._parse "+this.name)}}ze.add("prmtop",km),ze.add("parm7",km);const Mm=/\s+/,Tm=/(^\*|REMARK)*/;ze.add("psf",class extends Nu{get type(){return"psf"}_parse(){De&&Me.time("PsfParser._parse "+this.name);const t=this.structure,e=this.structureBuilder,i=t.atomMap,r=t.atomStore;r.addField("partialCharge",1,"float32");const s=[];let n,o,a,c,l,h,d=0,u=0,m=0;this.streamer.eachChunkOfLines((function(t){!function(t,p,f){for(let g=t;g<p;++g){const t=f[g].trim();if(t)if(2===n){const s=t.split(Mm),n=parseInt(s[0]),c=s[1],l=parseInt(s[2]),h=s[3],m=s[4],p=parseFloat(s[6]);c!==a&&(o=ja(u),++u),r.growIfFull(),r.atomTypeId[d]=i.add(m),r.serial[d]=n,r.partialCharge[d]=p,e.addAtom(0,o,o,h,l,!1),d+=1,a=c}else if(3===n){const e=t.split(Mm);for(let t=0,i=e.length;t<i;t+=2)c[m]=parseInt(e[t])-1,l[m]=parseInt(e[t+1])-1,h[m]=1,m+=1}else if(1===n)s.push(t.replace(Tm,"").trim());else if(4===n);else if(5===n);else if(6===n);else if(t.includes("!NATOM")){n=2;const e=parseInt(t.split(Mm)[0]);r.resize(e)}else if(t.includes("!NBOND")){n=3;const e=parseInt(t.split(Mm)[0]);c=new Uint32Array(e),l=new Uint32Array(e),h=new Uint8Array(e)}else t.includes("!NTITLE")?n=1:t.includes("!NTHETA")?n=4:t.includes("!NPHI")?n=5:t.includes("!NIMPHI")&&(n=6);else n=void 0}}(0,t.length,t)})),t.title=s.join(" "),t.bondStore.length=h.length,t.bondStore.count=m,t.bondStore.atomIndex1=c,t.bondStore.atomIndex2=l,t.bondStore.bondOrder=h,e.finalize(),t.finalizeAtoms(),t.finalizeBonds(),Ya(t,!0),Ka(t,!0,!0),ec(t),De&&Me.timeEnd("PsfParser._parse "+this.name)}});const Bm=/\[ (.+) \]/,Dm=/\s+/;ze.add("top",class extends Nu{get type(){return"top"}_parse(){De&&Me.time("TopParser._parse "+this.name);const t=this.structure,e=this.structureBuilder,i=t.atomMap,r=t.bondStore,s=t.atomStore;s.addField("partialCharge",1,"float32");const n=[],o={};let a,c;this.streamer.eachChunkOfLines((function(e){!function(e,i,r){for(let s=e;s<i;++s){const e=r[s];let i=e.trim();if(!i||"*"===i[0]||";"===i[0])continue;if(i.startsWith("#include"))throw new Error("TopParser: #include statements not allowed");const l=e.match(Bm);if(null!==l){const t=l[1];"moleculetype"===t?(c=2,a={atoms:[],bonds:[]}):c="atoms"===t?3:"bonds"===t?4:"system"===t?0:"molecules"===t?1:void 0;continue}const h=i.indexOf(";");if(-1!==h&&(i=i.substring(0,h).trim()),2===c){const t=i.split(Dm)[0];o[t]=a}else if(3===c){const t=i.split(Dm);a.atoms.push([parseInt(t[2]),t[3],t[4],parseFloat(t[6])])}else if(4===c){const t=i.split(Dm);a.bonds.push([parseInt(t[0]),parseInt(t[1])])}else if(0===c)t.title=i;else if(1===c){const t=i.split(Dm);n.push([t[0],parseInt(t[1])])}}}(0,e.length,e)}));let l=0,h=0;n.forEach((function(t){const[e,i]=t,r=o[e];l+=i*r.atoms.length,h+=i*r.bonds.length})),s.resize(l),r.resize(h);let d,u=0,m=0,p=0,f=0,g=0,y=0;n.forEach((function(t){const[n,a]=t,c=o[n],l=ja(f);for(let t=0;t<a;++t){d=-1;const t=cn.includes(n)?l:ja(p);c.atoms.forEach((function(r){const[n,o,a,c]=r;n!==d&&++m,s.atomTypeId[u]=i.add(a),s.serial[u]=u+1,s.partialCharge[u]=c,e.addAtom(0,l,t,o,m+1,!1),++u,d=n})),c.bonds.forEach((function(t){r.atomIndex1[g]=y+t[0]-1,r.atomIndex2[g]=y+t[1]-1,++g})),++p,y+=c.atoms.length}++f})),r.count=h,e.finalize(),t.finalizeAtoms(),t.finalizeBonds(),Ya(t,!0),Ka(t,!0,!0),ec(t),De&&Me.timeEnd("TopParser._parse "+this.name)}});class $m extends Lu{constructor(t,e){super(t,e),this.frames=new pl(this.name,this.path)}get type(){return"trajectory"}get __objName(){return"frames"}}function Om(t,e){if(t)throw new TypeError("Not a valid NetCDF v3.x file: "+e)}function Rm(t){t.offset%4!=0&&t.skip(4-t.offset%4)}function Em(t){const e=t.readUint32(),i=t.readChars(e);return Rm(t),i}ze.add("dcd",class extends $m{get type(){return"dcd"}get isBinary(){return!0}_parse(){De&&Me.time("DcdParser._parse "+this.name);const t=vt(this.streamer.data),e=new DataView(t),i=this.frames,r=i.coordinates,s=i.boxes,n={};let o=0;const a=new Int32Array(t,0,23),c=a[0]!==e.getInt32(0);if(84!==a[0]){const i=t.byteLength;for(let t=0;t<i;t+=4)e.setFloat32(t,e.getFloat32(t),!0)}84!==a[0]&&Me.error("dcd bad format, header block start");"CORD"!==String.fromCharCode(e.getUint8(4),e.getUint8(5),e.getUint8(6),e.getUint8(7))&&Me.error("dcd bad format, format string");let l=!1,h=!1,d=!1;0!==a[22]&&(l=!0,0!==a[12]&&(h=!0),1===a[13]&&(d=!0)),n.NSET=a[2],n.ISTART=a[3],n.NSAVC=a[4],n.NAMNF=a[10],n.DELTA=l?e.getFloat32(44,c):e.getFloat64(44,c),84!==a[22]&&Me.error("dcd bad format, header block end"),o=o+84+8;const u=e.getInt32(o,c),m=o+1;if((u-4)%80!=0&&Me.error("dcd bad format, title block start"),n.TITLE=yt(new Uint8Array(t,m,u)),e.getInt32(m+u+4-1,c)!==u&&Me.error("dcd bad format, title block end"),o=o+u+8,4!==e.getInt32(o,c)&&Me.error("dcd bad format, natom block start"),n.NATOM=e.getInt32(o+4,c),4!==e.getInt32(o+8,c)&&Me.error("dcd bad format, natom block end"),o=o+4+8,n.NAMNF>0)return void Me.error("dcd format with fixed atoms unsupported, aborting");const p=n.NATOM,f=4*p;for(let i=0,a=n.NSET;i<a;++i){if(h){o+=4;const t=new Float32Array(9);t[0]=e.getFloat64(o,c),t[4]=e.getFloat64(o+16,c),t[8]=e.getFloat64(o+40,c),s.push(t),o+=48,o+=4}const n=new Float32Array(3*p);for(let r=0;r<3;++r){e.getInt32(o,c)!==f&&Me.error("dcd bad format, coord block start",i,r),o+=4;const s=new Float32Array(t,o,p);for(let t=0;t<p;++t)n[3*t+r]=s[t];o+=f,e.getInt32(o,c)!==f&&Me.error("dcd bad format, coord block end",i,r),o+=4}if(r.push(n),d){o+=4+e.getInt32(o,c)+4}}n.DELTA&&(i.deltaTime=20.45482949774598*n.DELTA),n.ISTART>=1&&(i.timeOffset=(n.ISTART-1)*i.deltaTime),De&&Me.timeEnd("DcdParser._parse "+this.name)}});const Fm={BYTE:1,CHAR:2,SHORT:3,INT:4,FLOAT:5,DOUBLE:6};function Lm(t){switch(Number(t)){case Fm.BYTE:return"byte";case Fm.CHAR:return"char";case Fm.SHORT:return"short";case Fm.INT:return"int";case Fm.FLOAT:return"float";case Fm.DOUBLE:return"double";default:return"undefined"}}function Nm(t){switch(Number(t)){case Fm.BYTE:case Fm.CHAR:return 1;case Fm.SHORT:return 2;case Fm.INT:case Fm.FLOAT:return 4;case Fm.DOUBLE:return 8;default:return-1}}function zm(t){switch(String(t)){case"byte":return Fm.BYTE;case"char":return Fm.CHAR;case"short":return Fm.SHORT;case"int":return Fm.INT;case"float":return Fm.FLOAT;case"double":return Fm.DOUBLE;default:return-1}}function Vm(t,e){if(1!==t){const i=new Array(t);for(let r=0;r<t;r++)i[r]=e();return i}return e()}function Gm(t,e,i){switch(e){case Fm.BYTE:return t.readBytes(i);case Fm.CHAR:return function(t){if(0===t.charCodeAt(t.length-1))return t.substring(0,t.length-1);return t}(t.readChars(i));case Fm.SHORT:return Vm(i,t.readInt16.bind(t));case Fm.INT:return Vm(i,t.readInt32.bind(t));case Fm.FLOAT:return Vm(i,t.readFloat32.bind(t));case Fm.DOUBLE:return Vm(i,t.readFloat64.bind(t));default:return void Om(!0,"non valid type "+e)}}const Um=0,jm=10,Hm=11,Wm=12;function qm(t,e){const i={recordDimension:{length:t.readUint32()}};i.version=e;const r=function(t){let e,i,r;const s=t.readUint32();if(s===Um)return Om(t.readUint32()!==Um,"wrong empty tag for list of dimensions"),[];{Om(s!==jm,"wrong tag for list of dimensions");const n=t.readUint32();e=new Array(n);for(let s=0;s<n;s++){const n=Em(t),o=t.readUint32();0===o&&(i=s,r=n),e[s]={name:n,size:o}}return{dimensions:e,recordId:i,recordName:r}}}(t);i.recordDimension.id=r.recordId,i.recordDimension.name=r.recordName,i.dimensions=r.dimensions,i.globalAttributes=Xm(t);const s=function(t,e,i){const r=t.readUint32();let s,n=0;if(r===Um)return Om(t.readUint32()!==Um,"wrong empty tag for list of variables"),[];{Om(r!==Hm,"wrong tag for list of variables");const o=t.readUint32();s=new Array(o);for(let r=0;r<o;r++){const o=Em(t),a=t.readUint32(),c=new Array(a);for(let e=0;e<a;e++)c[e]=t.readUint32();const l=Xm(t),h=t.readUint32();Om(h<1&&h>6,"non valid type "+h);const d=t.readUint32();let u=t.readUint32();2===i&&(Om(u>0,"offsets larger than 4GB not supported"),u=t.readUint32()),c[0]===e&&(n+=d),s[r]={name:o,dimensions:c,attributes:l,type:Lm(h),size:d,offset:u,record:c[0]===e}}}return{variables:s,recordStep:n}}(t,r.recordId,e);return i.variables=s.variables,i.recordDimension.recordStep=s.recordStep,i}function Xm(t){let e;const i=t.readUint32();if(i===Um)return Om(t.readUint32()!==Um,"wrong empty tag for list of attributes"),[];{Om(i!==Wm,"wrong tag for list of attributes");const r=t.readUint32();e=new Array(r);for(let i=0;i<r;i++){const r=Em(t),s=t.readUint32();Om(s<1||s>6,"non valid type "+s);const n=t.readUint32(),o=Gm(t,s,n);Rm(t),e[i]={name:r,type:Lm(s),value:o}}}return e}class Ym{constructor(t){const e=new hi(t);e.setBigEndian(),Om("CDF"!==e.readChars(3),"should start with CDF");const i=e.readByte();Om(i>2,"unknown version"),this.header=qm(e,i),this.buffer=e}get version(){return 1===this.header.version?"classic format":"64-bit offset format"}get recordDimension(){return this.header.recordDimension}get dimensions(){return this.header.dimensions}get globalAttributes(){return this.header.globalAttributes}get variables(){return this.header.variables}hasDataVariable(t){return-1!==this.header.variables.findIndex((function(e){return e.name===t}))}getDataVariable(t){let e;return e="string"==typeof t?this.header.variables.find((function(e){return e.name===t})):t,Om(void 0===e,"variable not found"),this.buffer.seek(e.offset),e.record?function(t,e,i){const r=zm(e.type),s=e.size?e.size/Nm(r):1,n=i.length,o=new Array(n),a=i.recordStep;for(let e=0;e<n;e++){const i=t.offset;o[e]=Gm(t,r,s),t.seek(i+a)}return o}(this.buffer,e,this.header.recordDimension):function(t,e){const i=zm(e.type),r=e.size/Nm(i),s=new Array(r);for(let e=0;e<r;e++)s[e]=Gm(t,i,1);return s}(this.buffer,e)}}class Km extends $m{get type(){return"nctraj"}get isBinary(){return!0}_parse(){De&&Me.time("NctrajParser._parse "+this.name);const t=new Ym(this.streamer.data),e=this.frames,i=e.coordinates,r=e.boxes,s=e.times;t.getDataVariable("coordinates").forEach((function(t){i.push(new Float32Array(t))})),t.hasDataVariable("cell_lengths")&&t.getDataVariable("cell_lengths").forEach((function(t){r.push(new Float32Array(t))})),t.hasDataVariable("time")&&t.getDataVariable("time").forEach((function(t){s.push(t)})),s.length>=1&&(e.timeOffset=s[0]),s.length>=2&&(e.deltaTime=s[1]-s[0]),De&&Me.timeEnd("NctrajParser._parse "+this.name)}}ze.add("nctraj",Km),ze.add("ncdf",Km),ze.add("nc",Km);ze.add("trr",class extends $m{get type(){return"trr"}get isBinary(){return!0}_parse(){De&&Me.time("TrrParser._parse "+this.name);const t=vt(this.streamer.data),e=new DataView(t),i=this.frames,r=i.coordinates,s=i.boxes,n=i.times;let o=0;for(;;){o+=8;const i=e.getInt32(o);o+=4,o+=i;const a=e.getInt32(o+8),c=e.getInt32(o+12),l=e.getInt32(o+16),h=e.getInt32(o+28),d=e.getInt32(o+32),u=e.getInt32(o+36),m=e.getInt32(o+40);o+=52;const p=a/9,f=3*m;if(8===p?n.push(e.getFloat64(o)):n.push(e.getFloat32(o)),o+=2*p,a){const t=new Float32Array(9);if(8===p)for(let i=0;i<9;++i)t[i]=10*e.getFloat64(o),o+=8;else for(let i=0;i<9;++i)t[i]=10*e.getFloat32(o),o+=4;s.push(t)}if(o+=c,o+=l,h){let i;if(8===p){i=new Float32Array(f);for(let t=0;t<f;++t)i[t]=10*e.getFloat64(o),o+=8}else{const e=new Uint32Array(t,o,f);for(let t=0;t<f;++t){const i=e[t];e[t]=(255&i)<<24|(65280&i)<<8|i>>8&65280|i>>24&255}i=new Float32Array(t,o,f);for(let t=0;t<f;++t)i[t]*=10,o+=4}r.push(i)}if(o+=d,o+=u,o>=t.byteLength)break}n.length>=1&&(i.timeOffset=n[0]),n.length>=2&&(i.deltaTime=n[1]-n[0]),De&&Me.timeEnd("TrrParser._parse "+this.name)}});const Zm=new Uint32Array([0,0,0,0,0,0,0,0,0,8,10,12,16,20,25,32,40,50,64,80,101,128,161,203,256,322,406,512,645,812,1024,1290,1625,2048,2580,3250,4096,5060,6501,8192,10321,13003,16384,20642,26007,32768,41285,52015,65536,82570,104031,131072,165140,208063,262144,330280,416127,524287,660561,832255,1048576,1321122,1664510,2097152,2642245,3329021,4194304,5284491,6658042,8388607,10568983,13316085,16777216]);function Qm(t){let e=1,i=0;for(;t>=e&&i<32;)i++,e<<=1;return i}const Jm=new Uint8Array(32);function tp(t,e){let i=1,r=0;Jm[0]=1;for(let r=0;r<t;r++){let t,s=0;for(t=0;t<i;t++)s+=Jm[t]*e[r],Jm[t]=255&s,s>>=8;for(;0!==s;)Jm[t++]=255&s,s>>=8;i=t}let s=1;for(i--;Jm[i]>=s;)r++,s*=2;return r+8*i}function ep(t,e,i,r){const s=(1<<i)-1;let n=r[1],o=r[2],a=t[0],c=0;for(;i>=8;)o=o<<8|e[a++],c|=o>>n<<i-8,i-=8;return i>0&&(n<i&&(n+=8,o=o<<8|e[a++]),n-=i,c|=o>>n&(1<<i)-1),c&=s,t[0]=a,t[1]=n,t[2]=o,c}const ip=new Int32Array(32);function rp(t,e,i,r,s,n,o){let a=0;for(ip[1]=0,ip[2]=0,ip[3]=0;r>8;)ip[a++]=ep(t,e,8,o),r-=8;r>0&&(ip[a++]=ep(t,e,r,o));for(let t=i-1;t>0;t--){let e=0;for(let i=a-1;i>=0;i--){e=e<<8|ip[i];const r=e/s[t]|0;ip[i]=r,e-=r*s[t]}n[t]=e}n[0]=ip[0]|ip[1]<<8|ip[2]<<16|ip[3]<<24}ze.add("xtc",class extends $m{get type(){return"xtc"}get isBinary(){return!0}_parse(){De&&Me.time("XtcParser._parse "+this.name);const t=vt(this.streamer.data),e=new DataView(t),i=this.frames,r=i.coordinates,s=i.boxes,n=i.times,o=new Int32Array(6),a=new Int32Array(3),c=new Int32Array(3),l=new Uint32Array(3),h=new Float32Array(3),d=new Float32Array(3);let u=0;const m=new Int32Array(3),p=new Uint32Array(m.buffer);for(;;){let i;const f=e.getInt32(u+4);u+=12;const g=3*f;n.push(e.getFloat32(u)),u+=4;const y=new Float32Array(9);for(let t=0;t<9;++t)y[t]=10*e.getFloat32(u),u+=4;if(s.push(y),f<=9){i=new Float32Array(f);for(let t=0;t<f;++t)i[t]=e.getFloat32(u),u+=4}else{m[0]=m[1]=m[2]=0,a[0]=a[1]=a[2]=0,l[0]=l[1]=l[2]=0,c[0]=c[1]=c[2]=0,h[0]=h[1]=h[2]=0,d[0]=d[1]=d[2]=0,i=new Float32Array(g);let r=0;const s=e.getInt32(u);u+=4;const n=e.getFloat32(u);let f;u+=4,o[0]=e.getInt32(u),o[1]=e.getInt32(u+4),o[2]=e.getInt32(u+8),o[3]=e.getInt32(u+12),o[4]=e.getInt32(u+16),o[5]=e.getInt32(u+20),a[0]=o[3]-o[0]+1,a[1]=o[4]-o[1]+1,a[2]=o[5]-o[2]+1,u+=24,(a[0]|a[1]|a[2])>16777215?(c[0]=Qm(a[0]),c[1]=Qm(a[1]),c[2]=Qm(a[2]),f=0):f=tp(3,a);let y=e.getInt32(u);u+=4;let b=y-1;b=9>b?9:b;let x=Zm[b]/2|0,v=Zm[y]/2|0;l[0]=l[1]=l[2]=Zm[y];let w=4*Math.ceil(e.getInt32(u)/4);u+=4;const A=1/n;let _=0,S=0;const C=new Uint8Array(t,u);for(h[0]=h[1]=h[2]=0;S<s;){0===f?(h[0]=ep(m,C,c[0],p),h[1]=ep(m,C,c[1],p),h[2]=ep(m,C,c[2],p)):rp(m,C,3,f,a,h,p),S++,h[0]+=o[0],h[1]+=o[1],h[2]+=o[2],d[0]=h[0],d[1]=h[1],d[2]=h[2];let t=0;if(1===ep(m,C,1,p)&&(_=ep(m,C,5,p),t=_%3,_-=t,t--),_>0){h[0]=h[1]=h[2]=0;for(let t=0;t<_;t+=3){if(rp(m,C,3,y,l,h,p),S++,h[0]+=d[0]-v,h[1]+=d[1]-v,h[2]+=d[2]-v,0===t){let t=h[0];h[0]=d[0],d[0]=t,t=h[1],h[1]=d[1],d[1]=t,t=h[2],h[2]=d[2],d[2]=t,i[r++]=d[0]*A,i[r++]=d[1]*A,i[r++]=d[2]*A}else d[0]=h[0],d[1]=h[1],d[2]=h[2];i[r++]=h[0]*A,i[r++]=h[1]*A,i[r++]=h[2]*A}}else i[r++]=h[0]*A,i[r++]=h[1]*A,i[r++]=h[2]*A;if(y+=t,t<0?(v=x,x=y>9?Zm[y-1]/2|0:0):t>0&&(x=v,v=Zm[y]/2|0),l[0]=l[1]=l[2]=Zm[y],0===l[0]||0===l[1]||0===l[2])return void console.error("(xdrfile error) Undefined error.")}u+=w}for(let t=0;t<g;t++)i[t]*=10;if(r.push(i),u>=t.byteLength)break}n.length>=1&&(i.timeOffset=n[0]),n.length>=2&&(i.deltaTime=n[1]-n[0]),De&&Me.timeEnd("XtcParser._parse "+this.name)}});class sp extends Lu{constructor(t,e){const i=e||{};super(t,i),this.volume=new Eo(this.name,this.path),this.voxelSize=st(i.voxelSize,1)}get type(){return"volume"}get __objName(){return"volume"}_afterParse(){this.volume.setMatrix(this.getMatrix()),super._afterParse()}getMatrix(){return new i}}const np=/\s+/,op=/-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/g,ap=.529177210859;class cp extends sp{get type(){return"cube"}_parse(){De&&Me.time("CubeParser._parse "+this.name);const t=this.volume,i=this.streamer.peekLines(6),r={},s=ap*this.voxelSize;function n(t,e){var r=i[t].trim().split(np)[e];return parseFloat(r)}r.atomCount=Math.abs(n(2,0)),r.originX=n(2,1)*ap,r.originY=n(2,2)*ap,r.originZ=n(2,3)*ap,r.NVX=n(3,0),r.NVY=n(4,0),r.NVZ=n(5,0),r.basisX=new e(n(3,1),n(3,2),n(3,3)).multiplyScalar(s),r.basisY=new e(n(4,1),n(4,2),n(4,3)).multiplyScalar(s),r.basisZ=new e(n(5,1),n(5,2),n(5,3)).multiplyScalar(s);const o=new Float32Array(r.NVX*r.NVY*r.NVZ);let a=0,c=0;const l=n(2,0)>0?0:1;this.streamer.eachChunkOfLines((function(t){!function(t,e,i){for(let s=t;s<e;++s){const t=i[s].trim();if(""!==t&&c>=r.atomCount+6+l){const e=t.match(op);for(let t=0,i=e.length;t<i;++t)o[a]=parseFloat(e[t]),++a}++c}}(0,t.length,t)})),t.header=r,t.setData(o,r.NVZ,r.NVY,r.NVX),De&&Me.timeEnd("CubeParser._parse "+this.name)}getMatrix(){const t=this.volume.header,e=new i;return e.multiply((new i).makeTranslation(t.originX,t.originY,t.originZ)),e.multiply((new i).makeBasis(t.basisZ,t.basisY,t.basisX)),e}}ze.add("cub",cp),ze.add("cube",cp);class lp extends sp{get type(){return"dsn6"}get isBinary(){return!0}_parse(){De&&Me.time("Dsn6Parser._parse "+this.name);const t=this.volume,e={};let i,r;const s=vt(this.streamer.data),n=new Int16Array(s),o=new Uint8Array(s),a=String.fromCharCode.apply(null,o.subarray(0,512));if(a.startsWith(":-)"))e.xStart=parseInt(a.substr(10,5)),e.yStart=parseInt(a.substr(15,5)),e.zStart=parseInt(a.substr(20,5)),e.xExtent=parseInt(a.substr(32,5)),e.yExtent=parseInt(a.substr(38,5)),e.zExtent=parseInt(a.substr(42,5)),e.xRate=parseInt(a.substr(52,5)),e.yRate=parseInt(a.substr(58,5)),e.zRate=parseInt(a.substr(62,5)),e.xlen=parseFloat(a.substr(73,10))*this.voxelSize,e.ylen=parseFloat(a.substr(83,10))*this.voxelSize,e.zlen=parseFloat(a.substr(93,10))*this.voxelSize,e.alpha=parseFloat(a.substr(103,10)),e.beta=parseFloat(a.substr(113,10)),e.gamma=parseFloat(a.substr(123,10)),i=parseFloat(a.substr(138,12))/100,r=parseInt(a.substr(155,8)),e.sigma=100*parseFloat(a.substr(170,12));else{if(100!==n[18])for(let t=0,e=n.length;t<e;++t){const e=n[t];n[t]=(255&e)<<8|e>>8&255}e.xStart=n[0],e.yStart=n[1],e.zStart=n[2],e.xExtent=n[3],e.yExtent=n[4],e.zExtent=n[5],e.xRate=n[6],e.yRate=n[7],e.zRate=n[8];const t=1/n[17],s=t*this.voxelSize;e.xlen=n[9]*s,e.ylen=n[10]*s,e.zlen=n[11]*s,e.alpha=n[12]*t,e.beta=n[13]*t,e.gamma=n[14]*t,i=n[15]/100,r=n[16],e.gamma=n[14]*t}t.header=e,De&&Me.log(e,i,r);const c=new Float32Array(e.xExtent*e.yExtent*e.zExtent);let l=512;const h=Math.ceil(e.xExtent/8),d=Math.ceil(e.yExtent/8),u=Math.ceil(e.zExtent/8);for(var m=0;m<u;++m)for(var p=0;p<d;++p)for(var f=0;f<h;++f)for(var g=0;g<8;++g)for(var y=8*m+g,b=0;b<8;++b)for(var x=8*p+b,v=0;v<8;++v){var w=8*f+v;if(!(w<e.xExtent&&x<e.yExtent&&y<e.zExtent)){l+=8-v;break}c[(w*e.yExtent+x)*e.zExtent+y]=(o[l]-r)/i,++l}t.setData(c,e.zExtent,e.yExtent,e.xExtent),e.sigma&&t.setStats(void 0,void 0,void 0,e.sigma),De&&Me.timeEnd("Dsn6Parser._parse "+this.name)}getMatrix(){const t=this.volume.header,e=[t.xlen,0,0],r=[t.ylen*Math.cos(Math.PI/180*t.gamma),t.ylen*Math.sin(Math.PI/180*t.gamma),0],s=[t.zlen*Math.cos(Math.PI/180*t.beta),t.zlen*(Math.cos(Math.PI/180*t.alpha)-Math.cos(Math.PI/180*t.gamma)*Math.cos(Math.PI/180*t.beta))/Math.sin(Math.PI/180*t.gamma),0];s[2]=Math.sqrt(t.zlen*t.zlen*Math.sin(Math.PI/180*t.beta)*Math.sin(Math.PI/180*t.beta)-s[1]*s[1]);const n=[[],e,r,s],o=[0,t.xRate,t.yRate,t.zRate],a=[0,1,2,3],c=new i;return c.set(n[a[1]][0]/o[a[1]],n[a[2]][0]/o[a[2]],n[a[3]][0]/o[a[3]],0,n[a[1]][1]/o[a[1]],n[a[2]][1]/o[a[2]],n[a[3]][1]/o[a[3]],0,n[a[1]][2]/o[a[1]],n[a[2]][2]/o[a[2]],n[a[3]][2]/o[a[3]],0,0,0,0,1),c.multiply((new i).makeRotationY(kt(90))),c.multiply((new i).makeTranslation(-t.zStart,t.yStart,t.xStart)),c.multiply((new i).makeScale(-1,1,1)),c}}ze.add("dsn6",lp),ze.add("brix",lp);const hp=/\s+/;class dp extends sp{get type(){return"dx"}_parse(){De&&Me.time("DxParser._parse "+this.name);const t=this.volume,e=this.streamer.peekLines(30),i=this.parseHeaderLines(e),r=this.volume.header,s=i.dataLineStart,n=r.nx*r.ny*r.nz,o=new Float32Array(n);let a=0,c=0;this.streamer.eachChunkOfLines((function(t){!function(t,e,i){for(let r=t;r<e;++r){if(a<n&&c>s){const t=i[r].trim();if(""!==t){const e=t.split(hp);for(let t=0,i=e.length;t<i;++t)o[a]=parseFloat(e[t]),++a}}++c}}(0,t.length,t)})),t.setData(o,r.nz,r.ny,r.nx),De&&Me.timeEnd("DxParser._parse "+this.name)}parseHeaderLines(t){const e={},i=t.length;let r=0,s=0,n=0;for(let o=0;o<i;++o){let i;const a=t[o];if(a.startsWith("object 1"))i=a.split(hp),e.nx=parseInt(i[5]),e.ny=parseInt(i[6]),e.nz=parseInt(i[7]);else if(a.startsWith("origin"))i=a.split(hp),e.xmin=parseFloat(i[1]),e.ymin=parseFloat(i[2]),e.zmin=parseFloat(i[3]);else if(a.startsWith("delta"))i=a.split(hp),0===n?e.hx=parseFloat(i[1])*this.voxelSize:1===n?e.hy=parseFloat(i[2])*this.voxelSize:2===n&&(e.hz=parseFloat(i[3])*this.voxelSize),n+=1;else if(a.startsWith("object 3")){r=o,s+=a.length+1;break}s+=a.length+1}return this.volume.header=e,{dataLineStart:r,headerByteCount:s}}getMatrix(){const t=this.volume.header,e=new i;return e.multiply((new i).makeRotationY(kt(90))),e.multiply((new i).makeTranslation(-t.zmin,t.ymin,t.xmin)),e.multiply((new i).makeScale(-t.hz,t.hy,t.hx)),e}}ze.add("dx",dp);ze.add("dxbin",class extends dp{get type(){return"dxbin"}get isBinary(){return!0}_parse(){De&&Me.time("DxbinParser._parse "+this.name);const t=vt(this.streamer.data),e=function(t,e=10485760,i="\n"){let r="",s=[];for(let n=0;n<t.length;n+=e){const o=yt(t.subarray(n,n+e)),a=o.lastIndexOf(i);if(-1===a)r+=o;else{const t=r+o.substr(0,a);s=s.concat(t.split(i)),r=a===o.length-i.length?"":o.substr(a+i.length)}}return""!==r&&s.push(r),s}(new Uint8Array(t,0,1e3)),i=this.parseHeaderLines(e),r=this.volume.header,s=i.headerByteCount,n=r.nx*r.ny*r.nz,o=new DataView(t),a=new Float32Array(n);for(let t=0;t<n;++t)a[t]=o.getFloat64(8*t+s,!0);this.volume.setData(a,r.nz,r.ny,r.nx),De&&Me.timeEnd("DxbinParser._parse "+this.name)}});class up extends sp{get type(){return"mrc"}get isBinary(){return!0}_parse(){De&&Me.time("MrcParser._parse "+this.name);const t=this.volume,e={},i=vt(this.streamer.data),r=new Int32Array(i,0,56),s=new Float32Array(i,0,56),n=new DataView(i);if(e.MAP=String.fromCharCode(n.getUint8(208),n.getUint8(209),n.getUint8(210),n.getUint8(211)),e.MACHST=[n.getUint8(212),n.getUint8(213)],17===e.MACHST[0]&&17===e.MACHST[1]){const t=i.byteLength;for(let e=0;e<t;e+=4)n.setFloat32(e,n.getFloat32(e),!0)}let o;if(e.NX=r[0],e.NY=r[1],e.NZ=r[2],e.MODE=r[3],e.NXSTART=r[4],e.NYSTART=r[5],e.NZSTART=r[6],e.MX=r[7],e.MY=r[8],e.MZ=r[9],e.xlen=s[10]*this.voxelSize,e.ylen=s[11]*this.voxelSize,e.zlen=s[12]*this.voxelSize,e.alpha=s[13],e.beta=s[14],e.gamma=s[15],e.MAPC=r[16],e.MAPR=r[17],e.MAPS=r[18],e.DMIN=s[19],e.DMAX=s[20],e.DMEAN=s[21],e.ISPG=r[22],e.NSYMBT=r[23],e.LSKFLG=r[24],e.originX=s[49],e.originY=s[50],e.originZ=s[51],e.ARMS=s[54],t.header=e,2===e.MODE)o=new Float32Array(i,1024+e.NSYMBT,e.NX*e.NY*e.NZ);else if(0===e.MODE){if(o=new Float32Array(new Int8Array(i,1024+e.NSYMBT,e.NX*e.NY*e.NZ)),-128===r[39]&&127===r[40]){const t=(e.DMAX-e.DMIN)/255,i=.5*(e.DMIN+e.DMAX+t);for(let e=0,r=o.length;e<r;++e)o[e]=t*o[e]+i}}else Me.error("MrcParser unknown mode",e.MODE);t.setData(o,e.NX,e.NY,e.NZ),0!==e.ARMS&&t.setStats(e.DMIN,e.DMAX,e.DMEAN,e.ARMS),De&&Me.timeEnd("MrcParser._parse "+this.name)}getMatrix(){const t=this.volume.header,r=[t.xlen,0,0],s=[t.ylen*Math.cos(Math.PI/180*t.gamma),t.ylen*Math.sin(Math.PI/180*t.gamma),0],n=[t.zlen*Math.cos(Math.PI/180*t.beta),t.zlen*(Math.cos(Math.PI/180*t.alpha)-Math.cos(Math.PI/180*t.gamma)*Math.cos(Math.PI/180*t.beta))/Math.sin(Math.PI/180*t.gamma),0];n[2]=Math.sqrt(t.zlen*t.zlen*Math.sin(Math.PI/180*t.beta)*Math.sin(Math.PI/180*t.beta)-n[1]*n[1]);const o=[[],r,s,n],a=[0,t.MX,t.MY,t.MZ],c=[0,t.MAPC,t.MAPR,t.MAPS],l=new i;return l.set(o[c[1]][0]/a[c[1]],o[c[2]][0]/a[c[2]],o[c[3]][0]/a[c[3]],0,o[c[1]][1]/a[c[1]],o[c[2]][1]/a[c[2]],o[c[3]][1]/a[c[3]],0,o[c[1]][2]/a[c[1]],o[c[2]][2]/a[c[2]],o[c[3]][2]/a[c[3]],0,0,0,0,1),l.setPosition(new e(t.originX,t.originY,t.originZ)),l.multiply((new i).makeTranslation(t.NXSTART,t.NYSTART,t.NZSTART)),l}}ze.add("mrc",up),ze.add("ccp4",up),ze.add("map",up);const mp=/\s+/;function pp(t){return t.trim().split(mp).map(parseFloat)}class fp extends sp{get type(){return"xplor"}_parse(){De&&Me.time("XplorParser._parse "+this.name);const t=this.volume,e=this.streamer.peekLines(8),i={};let r;r=e[2].startsWith("REMARKS")?parseInt(e[1].substring(0,8))+2:5;const s=r+3,n=pp(e[r]);i.NA=n[0],i.AMIN=n[1],i.AMAX=n[2],i.NB=n[3],i.BMIN=n[4],i.BMAX=n[5],i.NC=n[6],i.CMIN=n[7],i.CMAX=n[8];const o=pp(e[r+1]);i.a=o[0]*this.voxelSize,i.b=o[1]*this.voxelSize,i.c=o[2]*this.voxelSize,i.alpha=o[3],i.beta=o[4],i.gamma=o[5];const a=i.AMAX-i.AMIN+1,c=i.BMAX-i.BMIN+1,l=i.CMAX-i.CMIN+1,h=a*c*l,d=new Float32Array(h),u=Math.ceil(1+a*c/6);let m=0,p=0;this.streamer.eachChunkOfLines((function(t){!function(t,e,r){for(let n=t;n<e;++n){const t=r[n];if(p>=s&&(p-s)%u!=0&&m<h)for(let e=0,i=6;e<i;++e){const i=parseFloat(t.substr(12*e,12));if(isNaN(i))break;d[m++]=i}else if(m===h){const e=t.trim();if(e&&"-9999"!==e){const e=pp(t);i.RAVE=e[0],i.RSIGMA=e[1]}}++p}}(0,t.length,t)})),t.header=i,t.setData(d,a,c,l),0!==i.RAVE&&1!==i.RSIGMA&&t.setStats(void 0,void 0,i.RAVE,i.RSIGMA),De&&Me.timeEnd("XplorParser._parse "+this.name)}getMatrix(){const t=this.volume.header,e=[t.a,0,0],r=[t.b*Math.cos(Math.PI/180*t.gamma),t.b*Math.sin(Math.PI/180*t.gamma),0],s=[t.c*Math.cos(Math.PI/180*t.beta),t.c*(Math.cos(Math.PI/180*t.alpha)-Math.cos(Math.PI/180*t.gamma)*Math.cos(Math.PI/180*t.beta))/Math.sin(Math.PI/180*t.gamma),0];s[2]=Math.sqrt(t.c*t.c*Math.sin(Math.PI/180*t.beta)*Math.sin(Math.PI/180*t.beta)-s[1]*s[1]);const n=[[],e,r,s],o=[0,t.NA,t.NB,t.NC],a=[0,1,2,3],c=new i;return c.set(n[a[1]][0]/o[a[1]],n[a[2]][0]/o[a[2]],n[a[3]][0]/o[a[3]],0,n[a[1]][1]/o[a[1]],n[a[2]][1]/o[a[2]],n[a[3]][1]/o[a[3]],0,n[a[1]][2]/o[a[1]],n[a[2]][2]/o[a[2]],n[a[3]][2]/o[a[3]],0,0,0,0,1),c.multiply((new i).makeTranslation(t.AMIN,t.BMIN,t.CMIN)),c}}function gp(t,e,i){let r,s,n;t/=360,e/=100,i/=100;const o=Math.floor(6*t),a=6*t-o,c=i*(1-e),l=i*(1-a*e),h=i*(1-(1-a)*e);switch(o%6){case 0:r=i,s=h,n=c;break;case 1:r=l,s=i,n=c;break;case 2:r=c,s=i,n=h;break;case 3:r=c,s=l,n=i;break;case 4:r=h,s=c,n=i;break;case 5:r=i,s=c,n=l}return[r,s,n]}ze.add("xplor",fp),ze.add("cns",fp);const yp={red:gp(0,100,100),orange:gp(20,100,100),gold:gp(40,100,100),yellow:gp(60,100,100),lime:gp(80,100,100),green:gp(120,80,100),sea:gp(150,100,100),cyan:gp(180,100,85),sky:gp(210,75,95),blue:gp(240,70,100),purple:gp(275,75,100),magenta:gp(300,95,100),hotpink:gp(335,100,100),pink:gp(350,55,100),peach:gp(25,75,100),lilac:gp(275,55,100),pinktint:gp(340,30,100),peachtint:gp(25,50,100),yellowtint:gp(60,50,100),greentint:gp(135,40,100),bluetint:gp(220,40,100),lilactint:gp(275,35,100),white:gp(0,0,100),gray:gp(0,0,50),brown:gp(20,45,75),deadwhite:[1,1,1],deadblack:[0,0,0],invisible:[0,0,0]},bp=/[\s,]+/,xp=/[^{}\s]*{[^{}]+}|[^{}\s]+/g,vp=/^{+|}+$/g,wp=/^['"]+|['"]+$/g,Ap=/\s*=\s*/g;function _p(t){let e,i,r,s=[];const n=(t=t.replace(Ap,"=")).match(xp);for(let t=1;t<n.length;++t){const o=n[t];if("{"===o[0])e=o.substring(1,o.length-1);else{const t=o.split("=");2===t.length&&("color"===t[0]?i=yp[t[1]]:"width"===t[0]?r=parseInt(t[1]):"master"===t[0]&&s.push(t[1].replace(vp,"")))}}return{listName:e,listColor:i,listMasters:s,listWidth:r}}function Sp(t){const e=(t=t.trim()).indexOf("{"),i=t.indexOf("}"),r=t.substr(i+1).split(bp),s=t.substr(e+1,i-1),n=[parseFloat(r[r.length-3]),parseFloat(r[r.length-2]),parseFloat(r[r.length-1])];let o,a,c,l=!1,h=!1;for(let t=4;t<=r.length;t++){const e=r[r.length-t];e in yp&&(o=yp[r[r.length-t]]),e.startsWith("width")&&(a=parseInt(e.substring(5))),e.startsWith("r=")&&(c=parseFloat(e.split("=")[1])),e.startsWith("P")&&(l=!0),e.startsWith("X")&&(h=!0)}return{label:s,position:n,color:o,radius:c,width:a,isLineBreak:l,isTriangleBreak:h}}function Cp(t){const e=t.indexOf("{"),i=t.indexOf("}");return t.substring(-1!==e?e+1:0,-1!==i?i:void 0).trim()}function Pp(t){const e=t.indexOf("}");return-1===e?void 0:t.substr(e+1).trim()}function Ip(t){let e="",i=[],r={};const s=(t=t.replace(Ap,"=")).match(xp);for(let t=1;t<s.length;++t){const n=s[t];if("{"===n[0])e=n.substring(1,n.length-1);else{const t=n.split("=");2===t.length?"master"===t[0]?i.push(t[1].replace(vp,"")):r[t[0]]=t[1].replace(vp,""):r[t[0]]=!0}}return{groupName:e,groupFlags:r,groupMasters:i}}ze.add("kin",class extends Lu{get type(){return"kin"}get __objName(){return"kinemage"}_parse(){De&&Me.time(`KinParser._parse ${this.name}`);const t={kinemage:void 0,onewidth:void 0,"1viewid":void 0,pdbfile:void 0,texts:[],text:"",captions:[],caption:"",groupDict:{},subgroupDict:{},masterDict:{},pointmasterDict:{},dotLists:[],vectorLists:[],ballLists:[],ribbonLists:[]};let i,r;this.kinemage=t;let s,n,o,a,c,l,h,d,u,m,p,f,g,y,b,x,v,w,A,_,S,C,P=!1,I="",k=!1,M="",T=null,B=null,D=!1,$="",O=!1,R="",E=!1,F=!1;if(this.streamer.eachChunkOfLines((function(e){!function(e,L,N){for(let V=e;V<L;++V){const e=N[V];if("@"===e[0]&&(P=!1,k=!1,D=!1,O=!1,E=!1,F=!1),e)if(e.startsWith("@dotlist")){let{listColor:c,listName:l,listMasters:h}=_p(e);P=!0,I="",n=[],o=[],a=[],s=c,i&&(h=h.concat(i)),r&&(h=h.concat(r)),t.dotLists.push({name:l,masterArray:h,labelArray:n,positionArray:o,colorArray:a})}else if(e.startsWith("@vectorlist")){let{listMasters:s,listName:n,listWidth:o,listColor:a}=_p(e);s&&s.forEach((function(e){t.masterDict[e]||(t.masterDict[e]={indent:!1,visible:!1})})),k=!0,M="",T=null,B=null,h=[],d=[],u=[],m=[],p=[],f=[],c=a,l=[],o&&l.push(o),i&&(s=s.concat(i)),r&&(s=s.concat(r)),t.vectorLists.push({name:n,masterArray:s,label1Array:h,label2Array:d,position1Array:u,position2Array:m,color1Array:p,color2Array:f,width:l})}else if(e.startsWith("@balllist")){let{listName:s,listColor:n,listMasters:o}=_p(e);o&&o.forEach((function(e){t.masterDict[e]||(t.masterDict[e]={indent:!1,visible:!1})})),D=!0,$="",b=[],g=[],x=[],v=[],y=n,i&&(o=o.concat(i)),r&&(o=o.concat(r)),t.ballLists.push({name:s,masterArray:o,labelArray:b,radiusArray:g,positionArray:x,colorArray:v})}else if(e.startsWith("@ribbonlist")||e.startsWith("@trianglelist")){let{listMasters:s,listName:n,listColor:o}=_p(e);s&&s.forEach((function(e){t.masterDict[e]||(t.masterDict[e]={indent:!1,visible:!1})})),O=!0,R="",A=[],_=[],S=[],C=[],w=o,i&&(s=s.concat(i)),r&&(s=s.concat(r)),t.ribbonLists.push({name:n,masterArray:s,labelArray:A,positionArray:_,breakArray:S,colorArray:C})}else if(e.startsWith("@text"))E=!0,t.texts.push(e.substr(5));else if(e.startsWith("@caption"))F=!0,t.captions.push(e.substr(8));else if(P){let{label:t,color:i,position:r}=Sp(e);'"'===t?t=I:I=t,void 0===i&&(i=s),n.push(t),o.push(...r),a.push(...i)}else if(k){let t=e.replace(/(?!^){/g,"\n{").split(/\n/);for(var z=0;z<t.length;z++){let e=t[z],{label:i,color:r,width:s,position:n,isLineBreak:o}=Sp(e);'"'===i?i=M:M=i,void 0===r&&(r=c),o||null!==T&&(s&&l.push(s),h.push(M),u.push(...T),p.push(...B),d.push(i),m.push(...n),f.push(...r)),M=i,T=n,B=r}}else if(D){let{label:t,radius:i,color:r,position:s}=Sp(e);'"'===t?t=$:$=t,void 0===i&&(i=1),void 0===r&&(r=y),b.push(t),g.push(i),x.push(...s),v.push(...r)}else if(O){let{label:t,color:i,position:r,isTriangleBreak:s}=Sp(e);'"'===t?t=R:R=t,void 0===i&&(i=w),A.push(t),_.push(...r),S.push(s),C.push(...i)}else if(E)t.texts.push(e);else if(F)t.captions.push(e);else if(e.startsWith("@kinemage"))t.kinemage=parseInt(e.substr(9).trim());else if(e.startsWith("@onewidth"))t.onewidth=!0;else if(e.startsWith("@1viewid"))t["1viewid"]=Cp(e);else if(e.startsWith("@pdbfile"))t.pdbfile=Cp(e);else if(e.startsWith("@group")){let{groupName:r,groupFlags:s,groupMasters:n}=Ip(e);t.groupDict[r]||(t.groupDict[r]={dominant:!1,animate:!1},i=n),i&&i.forEach((function(e){t.masterDict[e]||(t.masterDict[e]={indent:!1,visible:!1})}));for(let e in s)t.groupDict[r][e]=s[e]}else if(e.startsWith("@subgroup")){const{groupName:i,groupFlags:s,groupMasters:n}=Ip(e);t.subgroupDict[i]||(t.subgroupDict[i]={dominant:!1,animate:!1},r=n),r&&r.forEach((function(e){t.masterDict[e]||(t.masterDict[e]={indent:!1,visible:!1})}));for(let e in s)t.subgroupDict[i][e]=s[e]}else if(e.startsWith("@master")){const i=Cp(e),r=Pp(e);t.masterDict[i]||(t.masterDict[i]={indent:!1,visible:!1}),"on"===r?t.masterDict[i].visible=!0:"off"===r?t.masterDict[i].visible=!1:"indent"===r&&(t.masterDict[i].indent=!0)}else if(e.startsWith("@pointmaster")){const{groupName:i,groupFlags:r}=Ip(e);t.pointmasterDict[i]={id:Object.keys(r)[0].replace(wp,"")}}else console.log(e);else P=!1,k=!1,D=!1,O=!1}}(0,e.length,e)})),t.text=t.texts.join("\n").trim(),t.caption=t.captions.join("\n").trim(),t.ribbonLists){let i=[];t.ribbonLists.forEach((function(t){i.push(function(t){let{labelArray:e,positionArray:i,colorArray:r,breakArray:s}=t,n=[],o=[],a=[],c=[];for(let t=0;t<s.length/3;t++){let l=3*t,h=9*t;s[l+1]||s[l+2]||(n.push(e[l]),n.push(e[l+1]),n.push(e[l+2]),c.push(s[l]),c.push(s[l+1]),c.push(s[l+2]),o.push(i[h]),o.push(i[h+1]),o.push(i[h+2]),o.push(i[h+3]),o.push(i[h+4]),o.push(i[h+5]),o.push(i[h+6]),o.push(i[h+7]),o.push(i[h+8]),a.push(r[h]),a.push(r[h+1]),a.push(r[h+2]),a.push(r[h+3]),a.push(r[h+4]),a.push(r[h+5]),a.push(r[h+6]),a.push(r[h+7]),a.push(r[h+8]))}return{name:t.name,masterArray:t.masterArray,labelArray:n,positionArray:o,breakArray:c,colorArray:a}}(function(t){let{labelArray:i,positionArray:r,colorArray:s,breakArray:n}=t,o=[];for(let t=0;t<3*(i.length-2);++t)o[t]=i[t-2*Math.floor(t/3)];let a=[];for(let t=0;t<3*(n.length-2);++t)a[t]=n[t-2*Math.floor(t/3)];let c=[];for(let t=0;t<9*(r.length/3-2);++t)c[t]=r[t-6*Math.floor(t/9)];let l=[];for(let t=0;t<9*(s.length/3-2);++t)l[t]=s[t-6*Math.floor(t/9)];let h=[];for(let t=0;t<c.length/3;++t)h.push(new e(c[3*t],c[3*t]+1,c[3*t]+2));return{name:t.name,masterArray:t.masterArray,labelArray:o,positionArray:c,breakArray:a,colorArray:l}}(t)))})),t.ribbonLists=i}De&&Me.timeEnd(`KinParser._parse ${this.name}`)}});class kp extends Lu{constructor(t,e){super(t,e),this.loader=this.getLoader(),this.surface=new Oo(this.name,this.path)}get type(){return"surface"}get __objName(){return"surface"}_parse(){var t=this.loader.parse(this.streamer.asText());this.surface.fromGeometry(t)}}const Mp=function(){this.regexp={vertex_pattern:/^v\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)/,normal_pattern:/^vn\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)/,uv_pattern:/^vt\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)/,face_vertex:/^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,face_vertex_uv:/^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,face_vertex_uv_normal:/^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,face_vertex_normal:/^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,object_pattern:/^[og]\s*(.+)?/,smoothing_pattern:/^s\s+(\d+|on|off)/,material_library_pattern:/^mtllib /,material_use_pattern:/^usemtl /}};Mp.prototype={constructor:Mp,setPath:function(t){this.path=t},_createParserState:function(){var t={objects:[],object:{},vertices:[],normals:[],startObject:function(t,e){if(this.object&&!1===this.object.fromDeclaration)return this.object.name=t,void(this.object.fromDeclaration=!1!==e);this.object={name:t||"",geometry:{vertices:[],normals:[]},fromDeclaration:!1!==e},this.objects.push(this.object)},parseVertexIndex:function(t,e){var i=parseInt(t,10);return 3*(i>=0?i-1:i+e/3)},parseNormalIndex:function(t,e){var i=parseInt(t,10);return 3*(i>=0?i-1:i+e/3)},addVertex:function(t,e,i){var r=this.vertices,s=this.object.geometry.vertices;s.push(r[t+0]),s.push(r[t+1]),s.push(r[t+2]),s.push(r[e+0]),s.push(r[e+1]),s.push(r[e+2]),s.push(r[i+0]),s.push(r[i+1]),s.push(r[i+2])},addVertexLine:function(t){var e=this.vertices,i=this.object.geometry.vertices;i.push(e[t+0]),i.push(e[t+1]),i.push(e[t+2])},addNormal:function(t,e,i){var r=this.normals,s=this.object.geometry.normals;s.push(r[t+0]),s.push(r[t+1]),s.push(r[t+2]),s.push(r[e+0]),s.push(r[e+1]),s.push(r[e+2]),s.push(r[i+0]),s.push(r[i+1]),s.push(r[i+2])},addFace:function(t,e,i,r,s,n,o,a){var c,l=this.vertices.length,h=this.parseVertexIndex(t,l),d=this.parseVertexIndex(e,l),u=this.parseVertexIndex(i,l);if(void 0===r?this.addVertex(h,d,u):(c=this.parseVertexIndex(r,l),this.addVertex(h,d,c),this.addVertex(d,u,c)),void 0!==s){var m=this.normals.length;h=this.parseNormalIndex(s,m),d=s===n?h:this.parseNormalIndex(n,m),u=s===o?h:this.parseNormalIndex(o,m),void 0===r?this.addNormal(h,d,u):(c=this.parseNormalIndex(a,m),this.addNormal(h,d,c),this.addNormal(d,u,c))}},addLineGeometry:function(t){this.object.geometry.type="Line";for(var e=this.vertices.length,i=0,r=t.length;i<r;i++)this.addVertexLine(this.parseVertexIndex(t[i],e))}};return t.startObject("",!1),t},parse:function(t){var e,i,r=this._createParserState();-1!==t.indexOf("\r\n")&&(t=t.replace(/\r\n/g,"\n")),-1!==t.indexOf("\\\n")&&(t=t.replace(/\\\n/g,""));var s=t.split("\n"),n="",o="",a="",c=[],l="function"==typeof"".trimLeft;for(e=0,i=s.length;e<i;e++)if(n=s[e],0!==(n=l?n.trimLeft():n.trim()).length&&"#"!==(o=n.charAt(0)))if("v"===o){if(" "===(a=n.charAt(1))&&null!==(c=this.regexp.vertex_pattern.exec(n)))r.vertices.push(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3]));else if("n"===a&&null!==(c=this.regexp.normal_pattern.exec(n)))r.normals.push(parseFloat(c[1]),parseFloat(c[2]),parseFloat(c[3]));else if("t"!==a||null===this.regexp.uv_pattern.exec(n))throw new Error("Unexpected vertex/normal/uv line: '"+n+"'")}else if("f"===o)if(null!==(c=this.regexp.face_vertex_uv_normal.exec(n)))r.addFace(c[1],c[4],c[7],c[10],c[3],c[6],c[9],c[12]);else if(null!==this.regexp.face_vertex_uv.exec(n));else if(null!==(c=this.regexp.face_vertex_normal.exec(n)))r.addFace(c[1],c[3],c[5],c[7],c[2],c[4],c[6],c[8]);else{if(null===(c=this.regexp.face_vertex.exec(n)))throw new Error("Unexpected face line: '"+n+"'");r.addFace(c[1],c[2],c[3],c[4])}else if("l"===o){var h=n.substring(1).trim().split(" "),d=[],u=[];if(-1===n.indexOf("/"))d=h;else for(var m=0,p=h.length;m<p;m++){var f=h[m].split("/");""!==f[0]&&d.push(f[0]),""!==f[1]&&u.push(f[1])}r.addLineGeometry(d,u)}else if(null!==(c=this.regexp.object_pattern.exec(n))){var g=c[0].substr(1).trim();r.startObject(g)}else if(this.regexp.material_use_pattern.test(n));else if(this.regexp.material_library_pattern.test(n));else if(null===this.regexp.smoothing_pattern.exec(n)){if("\0"===n)continue;throw new Error("Unexpected line: '"+n+"'")}var y=[];for(e=0,i=r.objects.length;e<i;e++){var b=r.objects[e].geometry;if(0!==b.vertices.length){var x=new __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */];x.setAttribute("position",new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](new Float32Array(b.vertices),3)),b.normals.length>0?x.setAttribute("normal",new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](new Float32Array(b.normals),3)):x.computeVertexNormals(),y.push(x)}}return y}};ze.add("obj",class extends kp{get type(){return"obj"}getLoader(){return new Mp}});const Tp=function(){this.propertyNameMapping={}};Tp.prototype={constructor:Tp,setPropertyNameMapping:function(t){this.propertyNameMapping=t},bin2str:function(t){for(var e=new Uint8Array(t),i="",r=0;r<t.byteLength;r++)i+=String.fromCharCode(e[r]);return i},isASCII:function(t){return"ascii"===this.parseHeader(this.bin2str(t)).format},parse:function(t){return t instanceof ArrayBuffer?this.isASCII(t)?this.parseASCII(this.bin2str(t)):this.parseBinary(t):this.parseASCII(t)},parseHeader:function(t){var e="",i=0,r=/ply([\s\S]*)end_header\s/.exec(t);null!==r&&(e=r[1],i=r[0].length);var s,n,o,a,c,l,h={comments:[],elements:[],headerLength:i},d=e.split("\n");for(var u=0;u<d.length;u++){var m=d[u];if(""!==(m=m.trim()))switch(n=(o=m.split(/\s+/)).shift(),m=o.join(" "),n){case"format":h.format=o[0],h.version=o[1];break;case"comment":h.comments.push(m);break;case"element":void 0!==s&&h.elements.push(s),(s={}).name=o[0],s.count=parseInt(o[1]),s.properties=[];break;case"property":s.properties.push((a=o,c=this.propertyNameMapping,l=void 0,"list"===(l={type:a[0]}).type?(l.name=a[3],l.countType=a[1],l.itemType=a[2]):l.name=a[1],l.name in c&&(l.name=c[l.name]),l));break;default:console.log("unhandled",n,o)}}return void 0!==s&&h.elements.push(s),h},parseASCIINumber:function(t,e){switch(e){case"char":case"uchar":case"short":case"ushort":case"int":case"uint":case"int8":case"uint8":case"int16":case"uint16":case"int32":case"uint32":return parseInt(t);case"float":case"double":case"float32":case"float64":return parseFloat(t)}},parseASCIIElement:function(t,e){for(var i=e.split(/\s+/),r={},s=0;s<t.length;s++)if("list"===t[s].type){for(var n=[],o=this.parseASCIINumber(i.shift(),t[s].countType),a=0;a<o;a++)n.push(this.parseASCIINumber(i.shift(),t[s].itemType));r[t[s].name]=n}else r[t[s].name]=this.parseASCIINumber(i.shift(),t[s].type);return r},parseASCII:function(t){var e,i=new __WEBPACK_IMPORTED_MODULE_0_three__["s" /* Geometry */],r=this.parseHeader(t),s="";null!==(e=/end_header\s([\s\S]*)$/.exec(t))&&(s=e[1]);var n=s.split("\n"),o=0,a=0;i.useColor=!1;for(var c=0;c<n.length;c++){var l=n[c];if(""!==(l=l.trim())){a>=r.elements[o].count&&(o++,a=0);var h=this.parseASCIIElement(r.elements[o].properties,l);this.handleElement(i,r.elements[o].name,h),a++}}return this.postProcess(i)},postProcess:function(t){if(t.useColor){for(var e=0;e<t.faces.length;e++)t.faces[e].vertexColors=[t.colors[t.faces[e].a],t.colors[t.faces[e].b],t.colors[t.faces[e].c]];t.elementsNeedUpdate=!0}return t.computeBoundingSphere(),t},handleElement:function(t,i,r){if("vertex"===i){if(t.vertices.push(new e(r.x,r.y,r.z)),"red"in r&&"green"in r&&"blue"in r){t.useColor=!0;var n=new s;n.setRGB(r.red/255,r.green/255,r.blue/255),t.colors.push(n)}}else if("face"===i){var o=r.vertex_indices;3===o.length?t.faces.push(new __WEBPACK_IMPORTED_MODULE_0_three__["o" /* Face3 */](o[0],o[1],o[2])):4===o.length&&t.faces.push(new __WEBPACK_IMPORTED_MODULE_0_three__["o" /* Face3 */](o[0],o[1],o[3]),new __WEBPACK_IMPORTED_MODULE_0_three__["o" /* Face3 */](o[1],o[2],o[3]))}},binaryRead:function(t,e,i,r){switch(i){case"int8":case"char":return[t.getInt8(e),1];case"uint8":case"uchar":return[t.getUint8(e),1];case"int16":case"short":return[t.getInt16(e,r),2];case"uint16":case"ushort":return[t.getUint16(e,r),2];case"int32":case"int":return[t.getInt32(e,r),4];case"uint32":case"uint":return[t.getUint32(e,r),4];case"float32":case"float":return[t.getFloat32(e,r),4];case"float64":case"double":return[t.getFloat64(e,r),8]}},binaryReadElement:function(t,e,i,r){for(var s,n={},o=0,a=0;a<i.length;a++)if("list"===i[a].type){var c=[],l=(s=this.binaryRead(t,e+o,i[a].countType,r))[0];o+=s[1];for(var h=0;h<l;h++)s=this.binaryRead(t,e+o,i[a].itemType,r),c.push(s[0]),o+=s[1];n[i[a].name]=c}else s=this.binaryRead(t,e+o,i[a].type,r),n[i[a].name]=s[0],o+=s[1];return[n,o]},parseBinary:function(t){for(var e,i=new __WEBPACK_IMPORTED_MODULE_0_three__["s" /* Geometry */],r=this.parseHeader(this.bin2str(t)),s="binary_little_endian"===r.format,n=new DataView(t,r.headerLength),o=0,a=0;a<r.elements.length;a++)for(var c=0;c<r.elements[a].count;c++){o+=(e=this.binaryReadElement(n,o,r.elements[a].properties,s))[1];var l=e[0];this.handleElement(i,r.elements[a].name,l)}return this.postProcess(i)}};ze.add("ply",class extends kp{get type(){return"ply"}getLoader(){return new Tp}});ze.add("csv",class extends Lu{constructor(t,e){const i=e||{};super(t,i),this.delimiter=st(i.delimiter,","),this.comment=st(i.comment,"#"),this.columnNames=st(i.columnNames,!1),this.table={name:this.name,path:this.path,columnNames:[],data:[]}}get type(){return"csv"}get __objName(){return"table"}_parse(){const t=this.table.data,e=new RegExp("\\s*"+this.delimiter+"\\s*");let i=0;this.streamer.eachChunkOfLines((r=>{const s=r.length;for(let n=0;n<s;++n){const s=r[n].trim();if(s.startsWith(this.comment))continue;const o=s.split(e);0===i?this.table.columnNames=o:s&&t.push(o),++i}}))}});ze.add("json",class extends Lu{constructor(t,e){const i=e||{};super(t,i),this.string=st(i.string,!1),this.json={name:this.name,path:this.path,data:{}}}get type(){return"json"}get __objName(){return"json"}get isJson(){return!0}_parse(){this.streamer.isBinary()||this.string?this.json.data=JSON.parse(this.streamer.asText()):this.json.data=this.streamer.data}});ze.add("msgpack",class extends Lu{constructor(t,e){super(t,e||{}),this.msgpack={name:this.name,path:this.path,data:void 0}}get type(){return"msgpack"}get __objName(){return"msgpack"}get isBinary(){return!0}_parse(){De&&Me.time("MsgpackParser._parse "+this.name),this.msgpack.data=xm(this.streamer.data),De&&Me.timeEnd("MsgpackParser._parse "+this.name)}});ze.add("netcdf",class extends Lu{constructor(t,e){super(t,e||{}),this.netcdf={name:this.name,path:this.path,data:void 0}}get type(){return"netcdf"}get __objName(){return"netcdf"}get isBinary(){return!0}_parse(){De&&Me.time("NetcdfParser._parse "+this.name),this.netcdf.data=new Ym(this.streamer.data),De&&Me.timeEnd("NetcdfParser._parse "+this.name)}});class Bp extends Lu{constructor(t,e){super(t,e),this.text={name:this.name,path:this.path,data:""}}get type(){return"text"}get __objName(){return"text"}_parse(){this.text.data=this.streamer.asText()}}ze.add("txt",Bp),ze.add("text",Bp);const Dp=/^['"]|['"]$/g,$p=/^<([\w-:.]+)\s*/,Op=/^([^<]*)/,Rp=/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/;function Ep(t){return t=t.trim().replace(/<!--[\s\S]*?-->/g,""),{declaration:e(),root:i()};function e(){if(!s(/^<\?xml\s*/))return;const t={attributes:{}};for(;!n()&&!o("?>");){const e=r();if(!e)return t;t.attributes[e.name]=e.value}return s(/\?>\s*/),t}function i(){const t=s($p);if(!t)return;const e={name:t[1],attributes:{},children:[]};for(;!(n()||o(">")||o("?>")||o("/>"));){const t=r();if(!t)return e;e.attributes[t.name]=t.value}if(s(/^\s*\/>\s*/))return e;let a;for(s(/\??>\s*/),e.content=function(){const t=s(Op);return t?t[1]:""}();a=i();)e.children.push(a);return s(/^<\/[\w-:.]+>\s*/),e}function r(){const t=s(Rp);var e;if(t)return{name:t[1],value:(e=t[2],e.replace(Dp,""))}}function s(e){const i=t.match(e);if(i)return t=t.slice(i[0].length),i}function n(){return 0===t.length}function o(e){return 0===t.indexOf(e)}}class Fp extends Lu{constructor(t,e){const i=e||{};super(t,i),this.useDomParser=st(i.useDomParser,!1),this.xml={name:this.name,path:this.path,data:{}}}get type(){return"xml"}get __objName(){return"xml"}get isXml(){return!0}__xmlParser(t){return Ep(t)}__domParser(t){return(new window.DOMParser).parseFromString(t,"text/xml")}_parse(){De&&Me.time("XmlParser._parse "+this.name),this.useDomParser?this.streamer.data instanceof Document?this.xml.data=this.streamer.data:this.xml.data=this.__domParser(this.streamer.asText()):this.xml.data=this.__xmlParser(this.streamer.asText()),De&&Me.timeEnd("XmlParser._parse "+this.name)}}function Lp(t,e){const i=t.getNamedItem(e);return null!==i?i.value:""}function Np(t,e,i=!1){const r=Lp(t,"icode").trim(),s=Lp(t,"chain").trim(),n=Lp(t,"altcode");let o=Lp(t,"resnum");return r&&(o+="^"+r),s&&(o+=":"+s),e&&(o+="."+e),i&&n.trim()&&(o+="%"+n),o+="/"+(parseInt(Lp(t,"model"))-1),o}function zp(t){const e=Lp(t,"chain").trim();let i=`[${Lp(t,"rescode")}]${Lp(t,"resnum")}`;return e&&(i+=`:${e}`),i}function Vp(t,e,i){void 0===t[e]?t[e]=i:t[e]|=i}function Gp(t,e){return null!==t&&t.value===e}function Up(t,e,i){let r=0;const s=e.getElementsByTagName("clash");for(let e=0,i=s.length;e<i;++e)if(t[Lp(s[e].attributes,"cid")]){r+=1;break}e.getElementsByTagName("angle-outlier").length>0&&(r+=1);e.getElementsByTagName("bond-outlier").length>0&&(r+=1);return e.getElementsByTagName("plane-outlier").length>0&&(r+=1),Gp(i.getNamedItem("rota"),"OUTLIER")&&(r+=1),Gp(i.getNamedItem("rama"),"OUTLIER")&&(r+=1),Gp(i.getNamedItem("RNApucker"),"outlier")&&(r+=1),r}ze.add("xml",Fp);class jp{constructor(t,e){this.name=t,this.path=e,this.rsrzDict={},this.rsccDict={},this.rciDict={},this.clashDict={},this.clashArray=[],this.geoDict={},this.geoAtomDict={},this.atomDict={},this.clashSele="NONE"}get type(){return"validation"}fromXml(t){De&&Me.time("Validation.fromXml");const e=this.rsrzDict,i=this.rsccDict,r=this.rciDict,s=this.clashDict,n=this.clashArray,o=this.geoDict,a=this.geoAtomDict,c=this.atomDict,l=t.getElementsByTagName("Entry");if(1===l.length){const t=l[0].getElementsByTagName("chemical_shift_list");if(1===t.length){const e=t[0].getElementsByTagName("random_coil_index");for(let t=0,i=e.length;t<i;++t){const i=e[t].attributes;r[zp(i)]=parseFloat(Lp(i,"value"))}}}const h=t.getElementsByTagName("ModelledSubgroup"),d={},u=[];De&&Me.time("Validation.fromXml#clashDict");for(let r=0,o=h.length;r<o;++r){const o=h[r],a=o.attributes,l=Np(a);null!==a.getNamedItem("rsrz")&&(e[l]=parseFloat(Lp(a,"rsrz"))),null!==a.getNamedItem("rscc")&&(i[l]=parseFloat(Lp(a,"rscc")));const m=t.createAttribute("sele");m.value=l,a.setNamedItem(m);const p=o.getElementsByTagName("clash");for(let t=0,e=p.length;t<e;++t){const e=p[t].attributes,i=Lp(e,"atom");if("H"!==tc(i)){const t=Lp(e,"cid"),r=Np(a,i,!0);if(c[r]=!0,void 0===d[t])d[t]={sele1:r,res1:l};else{const e=d[t];e.res1!==l&&(e.sele2=r,e.res2=l,u.push(e.res1,l),s[t]=e,n.push(e))}}}}De&&Me.timeEnd("Validation.fromXml#clashDict");for(let t=0,e=h.length;t<e;++t){const e=h[t],i=e.attributes,r=Lp(i,"sele");if("."!==Lp(i,"seq")){const t=Up(s,e,i);t>0&&(o[r]=t)}else{const t=e.getElementsByTagName("clash"),i=e.getElementsByTagName("mog-bond-outlier"),n=e.getElementsByTagName("mog-angle-outlier");if(i.length>0||n.length>0||t.length>0){const e={};a[r]=e;for(let i=0,r=t.length;i<r;++i){const r=t[i].attributes;s[Lp(r,"cid")]&&Vp(e,Lp(r,"atom"),1)}for(let t=0,r=i.length;t<r;++t){Lp(i[t].attributes,"atoms").split(",").forEach((function(t){Vp(e,t,2)}))}for(let t=0,i=n.length;t<i;++t){Lp(n[t].attributes,"atoms").split(",").forEach((function(t){Vp(e,t,4)}))}}}}this.clashSele=u.length?u.join(" OR "):"NONE",De&&Me.timeEnd("Validation.fromXml")}getClashData(t){De&&Me.time("Validation.getClashData");const i=t||{},r=i.structure,n=r.atomSet,o=new s(st(i.color,"#f0027f")),a=r.getAtomProxy(),c=r.getAtomProxy(),l=new e,h=new e,d=new e,u=this.clashArray,m=u.length,p=new Float32Array(3*m),f=new Float32Array(3*m),g=Ci(m,o.r,o.g,o.b),y=new Float32Array(m),b=new Float32Array(m);De&&Me.time("Validation.getClashData#atomDict");const x=this.atomDict;r.eachAtom((function(t){const e=function(t){const e=t.inscode,i=t.chainname,r=t.atomname,s=t.altloc;let n=t.resno+"";return e&&(n+="^"+e),i&&(n+=":"+i),r&&(n+="."+r),s&&(n+="%"+s),n+="/"+t.modelIndex,n}(t);!0===x[e]&&(x[e]=t.index)})),De&&Me.timeEnd("Validation.getClashData#atomDict");let v=0;return u.forEach((function(t,e){if(a.index=x[t.sele1],c.index=x[t.sele2],void 0===a.index||void 0===c.index||!n.isSet(a.index,c.index))return;l.subVectors(c,a).setLength(a.vdw),h.copy(a).add(l),l.subVectors(a,c).setLength(c.vdw),d.copy(c).add(l);const i=a.distanceTo(c)/2,r=Math.sqrt(a.vdw*a.vdw-i*i),s=Math.sqrt(c.vdw*c.vdw-i*i);h.toArray(p,3*v),d.toArray(f,3*v),y[v]=(r+s)/2,b[v]=e,++v})),De&&Me.timeEnd("Validation.getClashData"),{position1:p.subarray(0,3*v),position2:f.subarray(0,3*v),color:g.subarray(0,3*v),color2:g.subarray(0,3*v),radius:y.subarray(0,v),picking:new Jn(b.subarray(0,v),this,r)}}}function Hp(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)}function Wp(t,e,i,r,s){if(e.subarray&&t.subarray)t.set(e.subarray(i,i+r),s);else for(var n=0;n<r;n++)t[s+n]=e[i+n]}function qp(t,e,i,r){for(var s=65535&t|0,n=t>>>16&65535|0,o=0;0!==i;){i-=o=i>2e3?2e3:i;do{n=n+(s=s+e[r++]|0)|0}while(--o);s%=65521,n%=65521}return s|n<<16|0}ze.add("validation",class extends Fp{constructor(t,e){super(t,e||{}),this.useDomParser=!0,this.validation=new jp(this.name,this.path)}get __objName(){return"validation"}get isXml(){return!0}_parse(){super._parse(),De&&Me.time("ValidationParser._parse "+this.name),this.validation.fromXml(this.xml.data),De&&Me.timeEnd("ValidationParser._parse "+this.name)}});var Xp=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var r=0;r<8;r++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();function Yp(t,e,i,r){var s=Xp,n=r+i;t^=-1;for(var o=r;o<n;o++)t=t>>>8^s[255&(t^e[o])];return-1^t}var Kp=30,Zp=12;function Qp(t,e){var i,r,s,n,o,a,c,l,h,d,u,m,p,f,g,y,b,x,v,w,A,_,S,C,P;i=t.state,r=t.next_in,C=t.input,s=r+(t.avail_in-5),n=t.next_out,P=t.output,o=n-(e-t.avail_out),a=n+(t.avail_out-257),c=i.dmax,l=i.wsize,h=i.whave,d=i.wnext,u=i.window,m=i.hold,p=i.bits,f=i.lencode,g=i.distcode,y=(1<<i.lenbits)-1,b=(1<<i.distbits)-1;t:do{p<15&&(m+=C[r++]<<p,p+=8,m+=C[r++]<<p,p+=8),x=f[m&y];e:for(;;){if(m>>>=v=x>>>24,p-=v,0===(v=x>>>16&255))P[n++]=65535&x;else{if(!(16&v)){if(0==(64&v)){x=f[(65535&x)+(m&(1<<v)-1)];continue e}if(32&v){i.mode=Zp;break t}t.msg="invalid literal/length code",i.mode=Kp;break t}w=65535&x,(v&=15)&&(p<v&&(m+=C[r++]<<p,p+=8),w+=m&(1<<v)-1,m>>>=v,p-=v),p<15&&(m+=C[r++]<<p,p+=8,m+=C[r++]<<p,p+=8),x=g[m&b];i:for(;;){if(m>>>=v=x>>>24,p-=v,!(16&(v=x>>>16&255))){if(0==(64&v)){x=g[(65535&x)+(m&(1<<v)-1)];continue i}t.msg="invalid distance code",i.mode=Kp;break t}if(A=65535&x,p<(v&=15)&&(m+=C[r++]<<p,(p+=8)<v&&(m+=C[r++]<<p,p+=8)),(A+=m&(1<<v)-1)>c){t.msg="invalid distance too far back",i.mode=Kp;break t}if(m>>>=v,p-=v,A>(v=n-o)){if((v=A-v)>h&&i.sane){t.msg="invalid distance too far back",i.mode=Kp;break t}if(_=0,S=u,0===d){if(_+=l-v,v<w){w-=v;do{P[n++]=u[_++]}while(--v);_=n-A,S=P}}else if(d<v){if(_+=l+d-v,(v-=d)<w){w-=v;do{P[n++]=u[_++]}while(--v);if(_=0,d<w){w-=v=d;do{P[n++]=u[_++]}while(--v);_=n-A,S=P}}}else if(_+=d-v,v<w){w-=v;do{P[n++]=u[_++]}while(--v);_=n-A,S=P}for(;w>2;)P[n++]=S[_++],P[n++]=S[_++],P[n++]=S[_++],w-=3;w&&(P[n++]=S[_++],w>1&&(P[n++]=S[_++]))}else{_=n-A;do{P[n++]=P[_++],P[n++]=P[_++],P[n++]=P[_++],w-=3}while(w>2);w&&(P[n++]=P[_++],w>1&&(P[n++]=P[_++]))}break}}break}}while(r<s&&n<a);r-=w=p>>3,m&=(1<<(p-=w<<3))-1,t.next_in=r,t.next_out=n,t.avail_in=r<s?s-r+5:5-(r-s),t.avail_out=n<a?a-n+257:257-(n-a),i.hold=m,i.bits=p}var Jp=15,tf=852,ef=592,rf=0,sf=1,nf=2,of=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],af=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],cf=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],lf=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];function hf(t,e,i,r,s,n,o,a){var c,l,h,d,u,m,p,f,g,y=a.bits,b=0,x=0,v=0,w=0,A=0,_=0,S=0,C=0,P=0,I=0,k=null,M=0,T=new Uint16Array(Jp+1),B=new Uint16Array(Jp+1),D=null,$=0;for(b=0;b<=Jp;b++)T[b]=0;for(x=0;x<r;x++)T[e[i+x]]++;for(A=y,w=Jp;w>=1&&0===T[w];w--);if(A>w&&(A=w),0===w)return s[n++]=20971520,s[n++]=20971520,a.bits=1,0;for(v=1;v<w&&0===T[v];v++);for(A<v&&(A=v),C=1,b=1;b<=Jp;b++)if(C<<=1,(C-=T[b])<0)return-1;if(C>0&&(t===rf||1!==w))return-1;for(B[1]=0,b=1;b<Jp;b++)B[b+1]=B[b]+T[b];for(x=0;x<r;x++)0!==e[i+x]&&(o[B[e[i+x]]++]=x);if(t===rf?(k=D=o,m=19):t===sf?(k=of,M-=257,D=af,$-=257,m=256):(k=cf,D=lf,m=-1),I=0,x=0,b=v,u=n,_=A,S=0,h=-1,d=(P=1<<A)-1,t===sf&&P>tf||t===nf&&P>ef)return 1;for(;;){p=b-S,o[x]<m?(f=0,g=o[x]):o[x]>m?(f=D[$+o[x]],g=k[M+o[x]]):(f=96,g=0),c=1<<b-S,v=l=1<<_;do{s[u+(I>>S)+(l-=c)]=p<<24|f<<16|g|0}while(0!==l);for(c=1<<b-1;I&c;)c>>=1;if(0!==c?(I&=c-1,I+=c):I=0,x++,0==--T[b]){if(b===w)break;b=e[i+o[x]]}if(b>A&&(I&d)!==h){for(0===S&&(S=A),u+=v,C=1<<(_=b-S);_+S<w&&!((C-=T[_+S])<=0);)_++,C<<=1;if(P+=1<<_,t===sf&&P>tf||t===nf&&P>ef)return 1;s[h=I&d]=A<<24|_<<16|u-n|0}}return 0!==I&&(s[u+I]=b-S<<24|64<<16|0),a.bits=A,0}var df=1,uf=2,mf=0,pf=-2,ff=1,gf=12,yf=30,bf=852,xf=592;function vf(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function wf(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Af(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,function(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=ff,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(bf),e.distcode=e.distdyn=new Int32Array(xf),e.sane=1,e.back=-1,mf):pf}(t)):pf}function _f(t,e){var i,r;return t?(r=new wf,t.state=r,r.window=null,i=function(t,e){var i,r;return t&&t.state?(r=t.state,e<0?(i=0,e=-e):(i=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?pf:(null!==r.window&&r.wbits!==e&&(r.window=null),r.wrap=i,r.wbits=e,Af(t))):pf}(t,e),i!==mf&&(t.state=null),i):pf}var Sf,Cf,Pf=!0;function If(t){if(Pf){var e;for(Sf=new Int32Array(512),Cf=new Int32Array(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(hf(df,t.lens,0,288,Sf,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;hf(uf,t.lens,0,32,Cf,0,t.work,{bits:5}),Pf=!1}t.lencode=Sf,t.lenbits=9,t.distcode=Cf,t.distbits=5}function kf(t,e,i,r){var s,n=t.state;return null===n.window&&(n.wsize=1<<n.wbits,n.wnext=0,n.whave=0,n.window=new Uint8Array(n.wsize)),r>=n.wsize?(Wp(n.window,e,i-n.wsize,n.wsize,0),n.wnext=0,n.whave=n.wsize):((s=n.wsize-n.wnext)>r&&(s=r),Wp(n.window,e,i-r,s,n.wnext),(r-=s)?(Wp(n.window,e,i-r,r,0),n.wnext=r,n.whave=n.wsize):(n.wnext+=s,n.wnext===n.wsize&&(n.wnext=0),n.whave<n.wsize&&(n.whave+=s))),0}function Mf(t,e){var i,r,s,n,o,a,c,l,h,d,u,m,p,f,g,y,b,x,v,w,A,_,S,C,P=0,I=new Uint8Array(4),k=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return pf;(i=t.state).mode===gf&&(i.mode=13),o=t.next_out,s=t.output,c=t.avail_out,n=t.next_in,r=t.input,a=t.avail_in,l=i.hold,h=i.bits,d=a,u=c,_=mf;t:for(;;)switch(i.mode){case ff:if(0===i.wrap){i.mode=13;break}for(;h<16;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if(2&i.wrap&&35615===l){i.check=0,I[0]=255&l,I[1]=l>>>8&255,i.check=Yp(i.check,I,2,0),l=0,h=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&l)<<8)+(l>>8))%31){t.msg="incorrect header check",i.mode=yf;break}if(8!=(15&l)){t.msg="unknown compression method",i.mode=yf;break}if(h-=4,A=8+(15&(l>>>=4)),0===i.wbits)i.wbits=A;else if(A>i.wbits){t.msg="invalid window size",i.mode=yf;break}i.dmax=1<<A,t.adler=i.check=1,i.mode=512&l?10:gf,l=0,h=0;break;case 2:for(;h<16;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if(i.flags=l,8!=(255&i.flags)){t.msg="unknown compression method",i.mode=yf;break}if(57344&i.flags){t.msg="unknown header flags set",i.mode=yf;break}i.head&&(i.head.text=l>>8&1),512&i.flags&&(I[0]=255&l,I[1]=l>>>8&255,i.check=Yp(i.check,I,2,0)),l=0,h=0,i.mode=3;case 3:for(;h<32;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}i.head&&(i.head.time=l),512&i.flags&&(I[0]=255&l,I[1]=l>>>8&255,I[2]=l>>>16&255,I[3]=l>>>24&255,i.check=Yp(i.check,I,4,0)),l=0,h=0,i.mode=4;case 4:for(;h<16;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}i.head&&(i.head.xflags=255&l,i.head.os=l>>8),512&i.flags&&(I[0]=255&l,I[1]=l>>>8&255,i.check=Yp(i.check,I,2,0)),l=0,h=0,i.mode=5;case 5:if(1024&i.flags){for(;h<16;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}i.length=l,i.head&&(i.head.extra_len=l),512&i.flags&&(I[0]=255&l,I[1]=l>>>8&255,i.check=Yp(i.check,I,2,0)),l=0,h=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&((m=i.length)>a&&(m=a),m&&(i.head&&(A=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),Wp(i.head.extra,r,n,m,A)),512&i.flags&&(i.check=Yp(i.check,r,m,n)),a-=m,n+=m,i.length-=m),i.length))break t;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===a)break t;m=0;do{A=r[n+m++],i.head&&A&&i.length<65536&&(i.head.name+=String.fromCharCode(A))}while(A&&m<a);if(512&i.flags&&(i.check=Yp(i.check,r,m,n)),a-=m,n+=m,A)break t}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===a)break t;m=0;do{A=r[n+m++],i.head&&A&&i.length<65536&&(i.head.comment+=String.fromCharCode(A))}while(A&&m<a);if(512&i.flags&&(i.check=Yp(i.check,r,m,n)),a-=m,n+=m,A)break t}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;h<16;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if(l!==(65535&i.check)){t.msg="header crc mismatch",i.mode=yf;break}l=0,h=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),t.adler=i.check=0,i.mode=gf;break;case 10:for(;h<32;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}t.adler=i.check=vf(l),l=0,h=0,i.mode=11;case 11:if(0===i.havedict)return t.next_out=o,t.avail_out=c,t.next_in=n,t.avail_in=a,i.hold=l,i.bits=h,2;t.adler=i.check=1,i.mode=gf;case gf:if(5===e||6===e)break t;case 13:if(i.last){l>>>=7&h,h-=7&h,i.mode=27;break}for(;h<3;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}switch(i.last=1&l,h-=1,3&(l>>>=1)){case 0:i.mode=14;break;case 1:if(If(i),i.mode=20,6===e){l>>>=2,h-=2;break t}break;case 2:i.mode=17;break;case 3:t.msg="invalid block type",i.mode=yf}l>>>=2,h-=2;break;case 14:for(l>>>=7&h,h-=7&h;h<32;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if((65535&l)!=(l>>>16^65535)){t.msg="invalid stored block lengths",i.mode=yf;break}if(i.length=65535&l,l=0,h=0,i.mode=15,6===e)break t;case 15:i.mode=16;case 16:if(m=i.length){if(m>a&&(m=a),m>c&&(m=c),0===m)break t;Wp(s,r,n,m,o),a-=m,n+=m,c-=m,o+=m,i.length-=m;break}i.mode=gf;break;case 17:for(;h<14;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if(i.nlen=257+(31&l),l>>>=5,h-=5,i.ndist=1+(31&l),l>>>=5,h-=5,i.ncode=4+(15&l),l>>>=4,h-=4,i.nlen>286||i.ndist>30){t.msg="too many length or distance symbols",i.mode=yf;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;h<3;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}i.lens[k[i.have++]]=7&l,l>>>=3,h-=3}for(;i.have<19;)i.lens[k[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,S={bits:i.lenbits},_=hf(0,i.lens,0,19,i.lencode,0,i.work,S),i.lenbits=S.bits,_){t.msg="invalid code lengths set",i.mode=yf;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;y=(P=i.lencode[l&(1<<i.lenbits)-1])>>>16&255,b=65535&P,!((g=P>>>24)<=h);){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if(b<16)l>>>=g,h-=g,i.lens[i.have++]=b;else{if(16===b){for(C=g+2;h<C;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if(l>>>=g,h-=g,0===i.have){t.msg="invalid bit length repeat",i.mode=yf;break}A=i.lens[i.have-1],m=3+(3&l),l>>>=2,h-=2}else if(17===b){for(C=g+3;h<C;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}h-=g,A=0,m=3+(7&(l>>>=g)),l>>>=3,h-=3}else{for(C=g+7;h<C;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}h-=g,A=0,m=11+(127&(l>>>=g)),l>>>=7,h-=7}if(i.have+m>i.nlen+i.ndist){t.msg="invalid bit length repeat",i.mode=yf;break}for(;m--;)i.lens[i.have++]=A}}if(i.mode===yf)break;if(0===i.lens[256]){t.msg="invalid code -- missing end-of-block",i.mode=yf;break}if(i.lenbits=9,S={bits:i.lenbits},_=hf(df,i.lens,0,i.nlen,i.lencode,0,i.work,S),i.lenbits=S.bits,_){t.msg="invalid literal/lengths set",i.mode=yf;break}if(i.distbits=6,i.distcode=i.distdyn,S={bits:i.distbits},_=hf(uf,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,S),i.distbits=S.bits,_){t.msg="invalid distances set",i.mode=yf;break}if(i.mode=20,6===e)break t;case 20:i.mode=21;case 21:if(a>=6&&c>=258){t.next_out=o,t.avail_out=c,t.next_in=n,t.avail_in=a,i.hold=l,i.bits=h,Qp(t,u),o=t.next_out,s=t.output,c=t.avail_out,n=t.next_in,r=t.input,a=t.avail_in,l=i.hold,h=i.bits,i.mode===gf&&(i.back=-1);break}for(i.back=0;y=(P=i.lencode[l&(1<<i.lenbits)-1])>>>16&255,b=65535&P,!((g=P>>>24)<=h);){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if(y&&0==(240&y)){for(x=g,v=y,w=b;y=(P=i.lencode[w+((l&(1<<x+v)-1)>>x)])>>>16&255,b=65535&P,!(x+(g=P>>>24)<=h);){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}l>>>=x,h-=x,i.back+=x}if(l>>>=g,h-=g,i.back+=g,i.length=b,0===y){i.mode=26;break}if(32&y){i.back=-1,i.mode=gf;break}if(64&y){t.msg="invalid literal/length code",i.mode=yf;break}i.extra=15&y,i.mode=22;case 22:if(i.extra){for(C=i.extra;h<C;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}i.length+=l&(1<<i.extra)-1,l>>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;y=(P=i.distcode[l&(1<<i.distbits)-1])>>>16&255,b=65535&P,!((g=P>>>24)<=h);){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if(0==(240&y)){for(x=g,v=y,w=b;y=(P=i.distcode[w+((l&(1<<x+v)-1)>>x)])>>>16&255,b=65535&P,!(x+(g=P>>>24)<=h);){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}l>>>=x,h-=x,i.back+=x}if(l>>>=g,h-=g,i.back+=g,64&y){t.msg="invalid distance code",i.mode=yf;break}i.offset=b,i.extra=15&y,i.mode=24;case 24:if(i.extra){for(C=i.extra;h<C;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}i.offset+=l&(1<<i.extra)-1,l>>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){t.msg="invalid distance too far back",i.mode=yf;break}i.mode=25;case 25:if(0===c)break t;if(m=u-c,i.offset>m){if((m=i.offset-m)>i.whave&&i.sane){t.msg="invalid distance too far back",i.mode=yf;break}m>i.wnext?(m-=i.wnext,p=i.wsize-m):p=i.wnext-m,m>i.length&&(m=i.length),f=i.window}else f=s,p=o-i.offset,m=i.length;m>c&&(m=c),c-=m,i.length-=m;do{s[o++]=f[p++]}while(--m);0===i.length&&(i.mode=21);break;case 26:if(0===c)break t;s[o++]=i.length,c--,i.mode=21;break;case 27:if(i.wrap){for(;h<32;){if(0===a)break t;a--,l|=r[n++]<<h,h+=8}if(u-=c,t.total_out+=u,i.total+=u,u&&(t.adler=i.check=i.flags?Yp(i.check,s,u,o-u):qp(i.check,s,u,o-u)),u=c,(i.flags?l:vf(l))!==i.check){t.msg="incorrect data check",i.mode=yf;break}l=0,h=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;h<32;){if(0===a)break t;a--,l+=r[n++]<<h,h+=8}if(l!==(4294967295&i.total)){t.msg="incorrect length check",i.mode=yf;break}l=0,h=0}i.mode=29;case 29:_=1;break t;case yf:_=-3;break t;case 31:return-4;default:return pf}return t.next_out=o,t.avail_out=c,t.next_in=n,t.avail_in=a,i.hold=l,i.bits=h,(i.wsize||u!==t.avail_out&&i.mode<yf&&(i.mode<27||4!==e))&&kf(t,t.output,t.next_out,u-t.avail_out),d-=t.avail_in,u-=t.avail_out,t.total_in+=d,t.total_out+=u,i.total+=u,i.wrap&&u&&(t.adler=i.check=i.flags?Yp(i.check,s,u,t.next_out-u):qp(i.check,s,u,t.next_out-u)),t.data_type=i.bits+(i.last?64:0)+(i.mode===gf?128:0)+(20===i.mode||15===i.mode?256:0),(0===d&&0===u||4===e)&&_===mf&&(_=-5),_}function Tf(t,e){var i,r=e.length;return t&&t.state?0!==(i=t.state).wrap&&11!==i.mode?pf:11===i.mode&&qp(1,e,r,0)!==i.check?-3:kf(t,e,r,r)?(i.mode=31,-4):(i.havedict=1,mf):pf}var Bf=!0,Df=!0;try{String.fromCharCode.apply(null,[0])}catch(t){Bf=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Df=!1}for(var $f=new Uint8Array(256),Of=0;Of<256;Of++)$f[Of]=Of>=252?6:Of>=248?5:Of>=240?4:Of>=224?3:Of>=192?2:1;function Rf(t){var e,i,r,s,n,o=t.length,a=0;for(s=0;s<o;s++)55296==(64512&(i=t.charCodeAt(s)))&&s+1<o&&56320==(64512&(r=t.charCodeAt(s+1)))&&(i=65536+(i-55296<<10)+(r-56320),s++),a+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(a),n=0,s=0;n<a;s++)55296==(64512&(i=t.charCodeAt(s)))&&s+1<o&&56320==(64512&(r=t.charCodeAt(s+1)))&&(i=65536+(i-55296<<10)+(r-56320),s++),i<128?e[n++]=i:i<2048?(e[n++]=192|i>>>6,e[n++]=128|63&i):i<65536?(e[n++]=224|i>>>12,e[n++]=128|i>>>6&63,e[n++]=128|63&i):(e[n++]=240|i>>>18,e[n++]=128|i>>>12&63,e[n++]=128|i>>>6&63,e[n++]=128|63&i);return e}function Ef(t,e){var i,r,s,n,o=e||t.length,a=new Array(2*o);for(r=0,i=0;i<o;)if((s=t[i++])<128)a[r++]=s;else if((n=$f[s])>4)a[r++]=65533,i+=n-1;else{for(s&=2===n?31:3===n?15:7;n>1&&i<o;)s=s<<6|63&t[i++],n--;n>1?a[r++]=65533:s<65536?a[r++]=s:(s-=65536,a[r++]=55296|s>>10&1023,a[r++]=56320|1023&s)}return function(t,e){if(e<65537&&(t.subarray&&Df||!t.subarray&&Bf))return String.fromCharCode.apply(null,Hp(t,e));for(var i="",r=0;r<e;r++)i+=String.fromCharCode(t[r]);return i}(a,r)}function Ff(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;i>=0&&128==(192&t[i]);)i--;return i<0||0===i?e:i+$f[t[i]]>e?i:e}$f[254]=$f[254]=1;var Lf=0,Nf={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};function zf(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}function Vf(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var Gf=Object.prototype.toString;function Uf(t){if(!(this instanceof Uf))return new Uf(t);this.options=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var r in i)i.hasOwnProperty(r)&&(t[r]=i[r])}}return t}({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new zf,this.strm.avail_out=0;var i,r,s,n=_f(this.strm,e.windowBits);if(n!==Lf)throw new Error(Nf[n]);this.header=new Vf,i=this.strm,r=this.header,i&&i.state&&(0==(2&(s=i.state).wrap)||(s.head=r,r.done=!1))}Uf.prototype.push=function(t,e){var i,r,s,n,o,a,c=this.strm,l=this.options.chunkSize,h=this.options.dictionary,d=!1;if(this.ended)return!1;r=e===~~e?e:!0===e?4:0,"string"==typeof t?c.input=function(t){for(var e=new Uint8Array(t.length),i=0,r=e.length;i<r;i++)e[i]=t.charCodeAt(i);return e}(t):"[object ArrayBuffer]"===Gf.call(t)?c.input=new Uint8Array(t):c.input=t,c.next_in=0,c.avail_in=c.input.length;do{if(0===c.avail_out&&(c.output=new Uint8Array(l),c.next_out=0,c.avail_out=l),2===(i=Mf(c,0))&&h&&(a="string"==typeof h?Rf(h):"[object ArrayBuffer]"===Gf.call(h)?new Uint8Array(h):h,i=Tf(this.strm,a)),-5===i&&!0===d&&(i=Lf,d=!1),1!==i&&i!==Lf)return this.onEnd(i),this.ended=!0,!1;c.next_out&&(0!==c.avail_out&&1!==i&&(0!==c.avail_in||4!==r&&2!==r)||("string"===this.options.to?(s=Ff(c.output,c.next_out),n=c.next_out-s,o=Ef(c.output,s),c.next_out=n,c.avail_out=l-n,n&&Wp(c.output,c.output,s,n,0),this.onData(o)):this.onData(Hp(c.output,c.next_out)))),0===c.avail_in&&0===c.avail_out&&(d=!0)}while((c.avail_in>0||0===c.avail_out)&&1!==i);return 1===i&&(r=4),4===r?(i=function(t){if(!t||!t.state)return pf;var e=t.state;return e.window&&(e.window=null),t.state=null,mf}(this.strm),this.onEnd(i),this.ended=!0,i===Lf):2!==r||(this.onEnd(Lf),c.avail_out=0,!0)},Uf.prototype.onData=function(t){this.chunks.push(t)},Uf.prototype.onEnd=function(t){t===Lf&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=function(t){var e,i,r,s,n,o;for(r=0,e=0,i=t.length;e<i;e++)r+=t[e].length;for(o=new Uint8Array(r),s=0,e=0,i=t.length;e<i;e++)n=t[e],o.set(n,s),s+=n.length;return o}(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},Ge.add("gz",(function(t){let e;t instanceof ArrayBuffer&&(t=new Uint8Array(t));try{e=function(t,e){var i=new Uf(e);if(i.push(t,!0),i.err)throw i.msg;return i.result}(t)}catch(i){e=t}return e}));class jf{}const Hf="//mmtf.rcsb.org/v1.0/",Wf=Hf+"full/",qf=Hf+"reduced/";Le.add("rcsb",new class extends jf{getUrl(t){const e=ri(t),i=e.name.substr(0,4);let r;return!["pdb","cif"].includes(e.ext)||!1!==e.compressed&&"gz"!==e.compressed?"mmtf"===e.ext?r=e.base.endsWith(".bb")?qf+i:Wf+i:e.ext?(Me.warn("unsupported ext",e.ext),r=Wf+i):r=Wf+i:r="//files.rcsb.org/download/"+e.path,ct()+r}getExt(t){const e=ri(t).ext;return e||"mmtf"}});const Xf="//pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/",Yf="/SDF?record_type=3d";Le.add("pubchem",new class extends jf{getUrl(t){const e=ri(t),i=e.name;let r;return e.ext&&"sdf"!==e.ext?(Me.warn("unsupported ext",e.ext),r=Xf+i+Yf):r=Xf+i+Yf,ct()+r}getExt(t){const e=ri(t).ext;return e||"sdf"}});class Kf extends jf{getUrl(t){return t}getExt(t){return ri(t).ext}}Le.add("ftp",new Kf),Le.add("http",new Kf),Le.add("https",new Kf);const Zf="//alphafold.ebi.ac.uk/files/AF-",Qf="-F1-model_v2.pdb";Le.add("alphafold",new class extends jf{getUrl(t){const e=ri(t),i=e.name;let r;return e.ext&&"pdb"!==e.ext?(Me.warn("unsupported AF ext",e.ext),r=Zf+i+Qf):r=Zf+i+Qf,ct()+r}getExt(t){const e=ri(t).ext;return e||"pdb"}});const Jf=/^((http|https|ftp):)*\/\//;class tg extends jf{constructor(t=""){super(),this.baseUrl=t}getUrl(t){const e=ri(t);let i=this.baseUrl+e.path;return Jf.test(this.baseUrl)||(i=function(t){const e=window.location,i=e.pathname,r=i.substring(0,i.lastIndexOf("/")+1);return e.origin+r+t}(i)),i}getExt(t){return ri(t).ext}}class eg extends jf{constructor(t=""){super(),this.baseUrl=t}getListing(t=""){let e=`${this.baseUrl}dir/${t}`;return"/"!==e[e.length-1]&&(e+="/"),ni(e,{ext:"json"}).then((e=>({path:t,data:e.data})))}getUrl(t){const e=ri(t);return`${this.baseUrl}file/${e.path}${e.query}`}getCountUrl(t){const e=ri(t);return`${this.baseUrl}traj/numframes/${e.path}${e.query}`}getFrameUrl(t,e){const i=ri(t);return`${this.baseUrl}traj/frame/${e}/${i.path}${i.query}`}getFrameParams(t,e){return`atomIndices=${e.join(";")}`}getPathUrl(t,e){const i=ri(t);return`${this.baseUrl}traj/path/${e}/${i.path}${i.query}`}getExt(t){return ri(t).ext}}function ig(t,e){return{type:"integer",max:t,min:e}}function rg(t,e,i){return{type:"number",precision:t,max:e,min:i}}function sg(t,e,i){return{type:"range",step:t,max:e,min:i}}function ng(...t){return{type:"select",options:t.reduce(((t,e)=>Object.assign(Object.assign({},t),{[e]:e})),{})}}const og={backgroundColor:{type:"color"},quality:ng("auto","low","medium","high"),sampleLevel:sg(1,5,-1),impostor:{type:"boolean"},workerDefault:{type:"boolean"},rotateSpeed:rg(1,10,0),zoomSpeed:rg(1,10,0),panSpeed:rg(1,10,0),clipNear:sg(1,100,0),clipFar:sg(1,100,0),clipDist:ig(200,0),clipMode:ng("scene","camera"),clipScale:ng("relative","absolute"),fogNear:sg(1,100,0),fogFar:sg(1,100,0),cameraType:ng("perspective","orthographic","stereo"),cameraEyeSep:rg(3,1,.01),cameraFov:sg(1,120,15),lightColor:{type:"color"},lightIntensity:rg(2,10,0),ambientColor:{type:"color"},ambientIntensity:rg(2,10,0),hoverTimeout:ig(1e4,-1),tooltip:{type:"boolean"},mousePreset:ng(...Object.keys(Zo))};const ag="2.2.2";
//# sourceMappingURL=ngl.esm.js.map


/***/ }),
/* 19 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = values;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(4);


// Retrieve the values of an object's properties.
function values(obj) {
  var _keys = Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(obj);
  var length = _keys.length;
  var values = Array(length);
  for (var i = 0; i < length; i++) {
    values[i] = obj[_keys[i]];
  }
  return values;
}


/***/ }),
/* 20 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = flatten;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isArray_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isArguments_js__ = __webpack_require__(38);





// Internal implementation of a recursive `flatten` function.
function flatten(input, depth, strict, output) {
  output = output || [];
  if (!depth && depth !== 0) {
    depth = Infinity;
  } else if (depth <= 0) {
    return output.concat(input);
  }
  var idx = output.length;
  for (var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(input); i < length; i++) {
    var value = input[i];
    if (Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(value) && (Object(__WEBPACK_IMPORTED_MODULE_2__isArray_js__["a" /* default */])(value) || Object(__WEBPACK_IMPORTED_MODULE_3__isArguments_js__["a" /* default */])(value))) {
      // Flatten current level of array or arguments object.
      if (depth > 1) {
        flatten(value, depth - 1, strict, output);
        idx = output.length;
      } else {
        var j = 0, len = value.length;
        while (j < len) output[idx++] = value[j++];
      }
    } else if (!strict) {
      output[idx++] = value;
    }
  }
  return output;
}


/***/ }),
/* 21 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = map;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__keys_js__ = __webpack_require__(4);




// Return the results of applying the iteratee to each element.
function map(obj, iteratee, context) {
  iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context);
  var _keys = !Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_2__keys_js__["a" /* default */])(obj),
      length = (_keys || obj).length,
      results = Array(length);
  for (var index = 0; index < length; index++) {
    var currentKey = _keys ? _keys[index] : index;
    results[index] = iteratee(obj[currentKey], currentKey, obj);
  }
  return results;
}


/***/ }),
/* 22 */
/***/ (function(module, exports) {

module.exports = __WEBPACK_EXTERNAL_MODULE_22__;

/***/ }),
/* 23 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return hasStringTagBug; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isIE11; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__hasObjectTag_js__ = __webpack_require__(121);



// In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
// In IE 11, the most common among them, this problem also applies to
// `Map`, `WeakMap` and `Set`.
var hasStringTagBug = (
      __WEBPACK_IMPORTED_MODULE_0__setup_js__["s" /* supportsDataView */] && Object(__WEBPACK_IMPORTED_MODULE_1__hasObjectTag_js__["a" /* default */])(new DataView(new ArrayBuffer(8)))
    ),
    isIE11 = (typeof Map !== 'undefined' && Object(__WEBPACK_IMPORTED_MODULE_1__hasObjectTag_js__["a" /* default */])(new Map));


/***/ }),
/* 24 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = allKeys;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isObject_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__collectNonEnumProps_js__ = __webpack_require__(63);




// Retrieve all the enumerable property names of an object.
function allKeys(obj) {
  if (!Object(__WEBPACK_IMPORTED_MODULE_0__isObject_js__["a" /* default */])(obj)) return [];
  var keys = [];
  for (var key in obj) keys.push(key);
  // Ahem, IE < 9.
  if (__WEBPACK_IMPORTED_MODULE_1__setup_js__["h" /* hasEnumBug */]) Object(__WEBPACK_IMPORTED_MODULE_2__collectNonEnumProps_js__["a" /* default */])(obj, keys);
  return keys;
}


/***/ }),
/* 25 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = toPath;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__toPath_js__ = __webpack_require__(71);



// Internal wrapper for `_.toPath` to enable minification.
// Similar to `cb` for `_.iteratee`.
function toPath(path) {
  return __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].toPath(path);
}


/***/ }),
/* 26 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = optimizeCb;
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
function optimizeCb(func, context, argCount) {
  if (context === void 0) return func;
  switch (argCount == null ? 3 : argCount) {
    case 1: return function(value) {
      return func.call(context, value);
    };
    // The 2-argument case is omitted because we’re not using it.
    case 3: return function(value, index, collection) {
      return func.call(context, value, index, collection);
    };
    case 4: return function(accumulator, value, index, collection) {
      return func.call(context, accumulator, value, index, collection);
    };
  }
  return function() {
    return func.apply(context, arguments);
  };
}


/***/ }),
/* 27 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = filter;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__each_js__ = __webpack_require__(16);



// Return all the elements that pass a truth test.
function filter(obj, predicate, context) {
  var results = [];
  predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
  Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(obj, function(value, index, list) {
    if (predicate(value, index, list)) results.push(value);
  });
  return results;
}


/***/ }),
/* 28 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = contains;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__values_js__ = __webpack_require__(19);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__indexOf_js__ = __webpack_require__(87);




// Determine if the array or object contains a given item (using `===`).
function contains(obj, item, fromIndex, guard) {
  if (!Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj)) obj = Object(__WEBPACK_IMPORTED_MODULE_1__values_js__["a" /* default */])(obj);
  if (typeof fromIndex != 'number' || guard) fromIndex = 0;
  return Object(__WEBPACK_IMPORTED_MODULE_2__indexOf_js__["a" /* default */])(obj, item, fromIndex) >= 0;
}


/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseView = void 0;
const widgets = __webpack_require__(22);
var NGL = __webpack_require__(18); // not sure why I can not import it
class BaseView extends widgets.DOMWidgetView {
    render() {
        if (this.isEmbeded()) {
            // embed mode: let NGLView call the handleEmbed directly
            return;
        }
        this.handleMessage();
        this.displayed.then(() => {
            this.model.set("_ready", true);
            this.touch();
        });
    }
    executeCode(code) {
        eval(code);
    }
    handleMessage() {
        this.model.on("msg:custom", function (msg) {
            this.on_msg(msg);
        }.bind(this));
    }
    on_msg(msg) {
        if (msg.type == 'callMethod') {
            console.log("from BaseView", msg);
            this[msg.methodName].apply(this, msg.args, msg.kwargs);
        }
    }
    isEmbeded() {
        return (this.model.comm == undefined);
    }
}
exports.BaseView = BaseView;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYmFzZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9iYXNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLGlEQUFnRDtBQUNoRCxJQUFJLEdBQUcsR0FBRyxPQUFPLENBQUMsS0FBSyxDQUFDLENBQUEsQ0FBQyxtQ0FBbUM7QUFHNUQsTUFDTSxRQUFTLFNBQVEsT0FBTyxDQUFDLGFBQWE7SUFFeEMsTUFBTTtRQUNOLElBQUksSUFBSSxDQUFDLFNBQVMsRUFBRSxFQUFDO1lBQ2Isd0RBQXdEO1lBQ3hELE9BQU07U0FDVDtRQUNELElBQUksQ0FBQyxhQUFhLEVBQUUsQ0FBQztRQUNyQixJQUFJLENBQUMsU0FBUyxDQUFDLElBQUksQ0FBQyxHQUFHLEVBQUU7WUFDckIsSUFBSSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsUUFBUSxFQUFFLElBQUksQ0FBQyxDQUFBO1lBQzlCLElBQUksQ0FBQyxLQUFLLEVBQUUsQ0FBQTtRQUNoQixDQUFDLENBQUMsQ0FBQTtJQUNOLENBQUM7SUFFRCxXQUFXLENBQUMsSUFBSTtRQUNaLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUNmLENBQUM7SUFFRCxhQUFhO1FBQ1QsSUFBSSxDQUFDLEtBQUssQ0FBQyxFQUFFLENBQUMsWUFBWSxFQUFFLFVBQVMsR0FBRztZQUNwQyxJQUFJLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFBO1FBQ3BCLENBQUMsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQTtJQUNqQixDQUFDO0lBRUQsTUFBTSxDQUFDLEdBQUc7UUFDTixJQUFJLEdBQUcsQ0FBQyxJQUFJLElBQUksWUFBWSxFQUFDO1lBQ3pCLE9BQU8sQ0FBQyxHQUFHLENBQUMsZUFBZSxFQUFFLEdBQUcsQ0FBQyxDQUFBO1lBQ2pDLElBQUksQ0FBQyxHQUFHLENBQUMsVUFBVSxDQUFDLENBQUMsS0FBSyxDQUFDLElBQUksRUFBRSxHQUFHLENBQUMsSUFBSSxFQUFFLEdBQUcsQ0FBQyxNQUFNLENBQUMsQ0FBQTtTQUN6RDtJQUNMLENBQUM7SUFFRCxTQUFTO1FBQ0wsT0FBTyxDQUFDLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxJQUFJLFNBQVMsQ0FBQyxDQUFBO0lBQ3pDLENBQUM7Q0FDSjtBQW5DRCw0QkFtQ0MifQ==

/***/ }),
/* 30 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = matcher;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__extendOwn_js__ = __webpack_require__(42);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isMatch_js__ = __webpack_require__(64);



// Returns a predicate for checking whether an object has a given set of
// `key:value` pairs.
function matcher(attrs) {
  attrs = Object(__WEBPACK_IMPORTED_MODULE_0__extendOwn_js__["a" /* default */])({}, attrs);
  return function(obj) {
    return Object(__WEBPACK_IMPORTED_MODULE_1__isMatch_js__["a" /* default */])(obj, attrs);
  };
}


/***/ }),
/* 31 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__executeBound_js__ = __webpack_require__(79);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__underscore_js__ = __webpack_require__(8);




// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. `_` acts
// as a placeholder by default, allowing any combination of arguments to be
// pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
var partial = Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(func, boundArgs) {
  var placeholder = partial.placeholder;
  var bound = function() {
    var position = 0, length = boundArgs.length;
    var args = Array(length);
    for (var i = 0; i < length; i++) {
      args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
    }
    while (position < arguments.length) args.push(arguments[position++]);
    return Object(__WEBPACK_IMPORTED_MODULE_1__executeBound_js__["a" /* default */])(func, bound, this, this, args);
  };
  return bound;
});

partial.placeholder = __WEBPACK_IMPORTED_MODULE_2__underscore_js__["a" /* default */];
/* harmony default export */ __webpack_exports__["a"] = (partial);


/***/ }),
/* 32 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = group;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__each_js__ = __webpack_require__(16);



// An internal function used for aggregate "group by" operations.
function group(behavior, partition) {
  return function(obj, iteratee, context) {
    var result = partition ? [[], []] : {};
    iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context);
    Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(obj, function(value, index) {
      var key = iteratee(value, index, obj);
      behavior(result, value, key);
    });
    return result;
  };
}


/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_RESULT__;/*jslint onevar:true, undef:true, newcap:true, regexp:true, bitwise:true, maxerr:50, indent:4, white:false, nomen:false, plusplus:false */
/*global define:false, require:false, exports:false, module:false, signals:false */

/** @license
 * JS Signals <http://millermedeiros.github.com/js-signals/>
 * Released under the MIT license
 * Author: Miller Medeiros
 * Version: 1.0.0 - Build: 268 (2012/11/29 05:48 PM)
 */

(function(global){

    // SignalBinding -------------------------------------------------
    //================================================================

    /**
     * Object that represents a binding between a Signal and a listener function.
     * <br />- <strong>This is an internal constructor and shouldn't be called by regular users.</strong>
     * <br />- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
     * @author Miller Medeiros
     * @constructor
     * @internal
     * @name SignalBinding
     * @param {Signal} signal Reference to Signal object that listener is currently bound to.
     * @param {Function} listener Handler function bound to the signal.
     * @param {boolean} isOnce If binding should be executed just once.
     * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
     * @param {Number} [priority] The priority level of the event listener. (default = 0).
     */
    function SignalBinding(signal, listener, isOnce, listenerContext, priority) {

        /**
         * Handler function bound to the signal.
         * @type Function
         * @private
         */
        this._listener = listener;

        /**
         * If binding should be executed just once.
         * @type boolean
         * @private
         */
        this._isOnce = isOnce;

        /**
         * Context on which listener will be executed (object that should represent the `this` variable inside listener function).
         * @memberOf SignalBinding.prototype
         * @name context
         * @type Object|undefined|null
         */
        this.context = listenerContext;

        /**
         * Reference to Signal object that listener is currently bound to.
         * @type Signal
         * @private
         */
        this._signal = signal;

        /**
         * Listener priority
         * @type Number
         * @private
         */
        this._priority = priority || 0;
    }

    SignalBinding.prototype = {

        /**
         * If binding is active and should be executed.
         * @type boolean
         */
        active : true,

        /**
         * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute`. (curried parameters)
         * @type Array|null
         */
        params : null,

        /**
         * Call listener passing arbitrary parameters.
         * <p>If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.</p>
         * @param {Array} [paramsArr] Array of parameters that should be passed to the listener
         * @return {*} Value returned by the listener.
         */
        execute : function (paramsArr) {
            var handlerReturn, params;
            if (this.active && !!this._listener) {
                params = this.params? this.params.concat(paramsArr) : paramsArr;
                handlerReturn = this._listener.apply(this.context, params);
                if (this._isOnce) {
                    this.detach();
                }
            }
            return handlerReturn;
        },

        /**
         * Detach binding from signal.
         * - alias to: mySignal.remove(myBinding.getListener());
         * @return {Function|null} Handler function bound to the signal or `null` if binding was previously detached.
         */
        detach : function () {
            return this.isBound()? this._signal.remove(this._listener, this.context) : null;
        },

        /**
         * @return {Boolean} `true` if binding is still bound to the signal and have a listener.
         */
        isBound : function () {
            return (!!this._signal && !!this._listener);
        },

        /**
         * @return {boolean} If SignalBinding will only be executed once.
         */
        isOnce : function () {
            return this._isOnce;
        },

        /**
         * @return {Function} Handler function bound to the signal.
         */
        getListener : function () {
            return this._listener;
        },

        /**
         * @return {Signal} Signal that listener is currently bound to.
         */
        getSignal : function () {
            return this._signal;
        },

        /**
         * Delete instance properties
         * @private
         */
        _destroy : function () {
            delete this._signal;
            delete this._listener;
            delete this.context;
        },

        /**
         * @return {string} String representation of the object.
         */
        toString : function () {
            return '[SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
        }

    };


/*global SignalBinding:false*/

    // Signal --------------------------------------------------------
    //================================================================

    function validateListener(listener, fnName) {
        if (typeof listener !== 'function') {
            throw new Error( 'listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName) );
        }
    }

    /**
     * Custom event broadcaster
     * <br />- inspired by Robert Penner's AS3 Signals.
     * @name Signal
     * @author Miller Medeiros
     * @constructor
     */
    function Signal() {
        /**
         * @type Array.<SignalBinding>
         * @private
         */
        this._bindings = [];
        this._prevParams = null;

        // enforce dispatch to aways work on same context (#47)
        var self = this;
        this.dispatch = function(){
            Signal.prototype.dispatch.apply(self, arguments);
        };
    }

    Signal.prototype = {

        /**
         * Signals Version Number
         * @type String
         * @const
         */
        VERSION : '1.0.0',

        /**
         * If Signal should keep record of previously dispatched parameters and
         * automatically execute listener during `add()`/`addOnce()` if Signal was
         * already dispatched before.
         * @type boolean
         */
        memorize : false,

        /**
         * @type boolean
         * @private
         */
        _shouldPropagate : true,

        /**
         * If Signal is active and should broadcast events.
         * <p><strong>IMPORTANT:</strong> Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.</p>
         * @type boolean
         */
        active : true,

        /**
         * @param {Function} listener
         * @param {boolean} isOnce
         * @param {Object} [listenerContext]
         * @param {Number} [priority]
         * @return {SignalBinding}
         * @private
         */
        _registerListener : function (listener, isOnce, listenerContext, priority) {

            var prevIndex = this._indexOfListener(listener, listenerContext),
                binding;

            if (prevIndex !== -1) {
                binding = this._bindings[prevIndex];
                if (binding.isOnce() !== isOnce) {
                    throw new Error('You cannot add'+ (isOnce? '' : 'Once') +'() then add'+ (!isOnce? '' : 'Once') +'() the same listener without removing the relationship first.');
                }
            } else {
                binding = new SignalBinding(this, listener, isOnce, listenerContext, priority);
                this._addBinding(binding);
            }

            if(this.memorize && this._prevParams){
                binding.execute(this._prevParams);
            }

            return binding;
        },

        /**
         * @param {SignalBinding} binding
         * @private
         */
        _addBinding : function (binding) {
            //simplified insertion sort
            var n = this._bindings.length;
            do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
            this._bindings.splice(n + 1, 0, binding);
        },

        /**
         * @param {Function} listener
         * @return {number}
         * @private
         */
        _indexOfListener : function (listener, context) {
            var n = this._bindings.length,
                cur;
            while (n--) {
                cur = this._bindings[n];
                if (cur._listener === listener && cur.context === context) {
                    return n;
                }
            }
            return -1;
        },

        /**
         * Check if listener was attached to Signal.
         * @param {Function} listener
         * @param {Object} [context]
         * @return {boolean} if Signal has the specified listener.
         */
        has : function (listener, context) {
            return this._indexOfListener(listener, context) !== -1;
        },

        /**
         * Add a listener to the signal.
         * @param {Function} listener Signal handler function.
         * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
         * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
         * @return {SignalBinding} An Object representing the binding between the Signal and listener.
         */
        add : function (listener, listenerContext, priority) {
            validateListener(listener, 'add');
            return this._registerListener(listener, false, listenerContext, priority);
        },

        /**
         * Add listener to the signal that should be removed after first execution (will be executed only once).
         * @param {Function} listener Signal handler function.
         * @param {Object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function).
         * @param {Number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0)
         * @return {SignalBinding} An Object representing the binding between the Signal and listener.
         */
        addOnce : function (listener, listenerContext, priority) {
            validateListener(listener, 'addOnce');
            return this._registerListener(listener, true, listenerContext, priority);
        },

        /**
         * Remove a single listener from the dispatch queue.
         * @param {Function} listener Handler function that should be removed.
         * @param {Object} [context] Execution context (since you can add the same handler multiple times if executing in a different context).
         * @return {Function} Listener handler function.
         */
        remove : function (listener, context) {
            validateListener(listener, 'remove');

            var i = this._indexOfListener(listener, context);
            if (i !== -1) {
                this._bindings[i]._destroy(); //no reason to a SignalBinding exist if it isn't attached to a signal
                this._bindings.splice(i, 1);
            }
            return listener;
        },

        /**
         * Remove all listeners from the Signal.
         */
        removeAll : function () {
            var n = this._bindings.length;
            while (n--) {
                this._bindings[n]._destroy();
            }
            this._bindings.length = 0;
        },

        /**
         * @return {number} Number of listeners attached to the Signal.
         */
        getNumListeners : function () {
            return this._bindings.length;
        },

        /**
         * Stop propagation of the event, blocking the dispatch to next listeners on the queue.
         * <p><strong>IMPORTANT:</strong> should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.</p>
         * @see Signal.prototype.disable
         */
        halt : function () {
            this._shouldPropagate = false;
        },

        /**
         * Dispatch/Broadcast Signal to all listeners added to the queue.
         * @param {...*} [params] Parameters that should be passed to each handler.
         */
        dispatch : function (params) {
            if (! this.active) {
                return;
            }

            var paramsArr = Array.prototype.slice.call(arguments),
                n = this._bindings.length,
                bindings;

            if (this.memorize) {
                this._prevParams = paramsArr;
            }

            if (! n) {
                //should come after memorize
                return;
            }

            bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
            this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.

            //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
            //reverse loop since listeners with higher priority will be added at the end of the list
            do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
        },

        /**
         * Forget memorized arguments.
         * @see Signal.memorize
         */
        forget : function(){
            this._prevParams = null;
        },

        /**
         * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object).
         * <p><strong>IMPORTANT:</strong> calling any method on the signal instance after calling dispose will throw errors.</p>
         */
        dispose : function () {
            this.removeAll();
            delete this._bindings;
            delete this._prevParams;
        },

        /**
         * @return {string} String representation of the object.
         */
        toString : function () {
            return '[Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
        }

    };


    // Namespace -----------------------------------------------------
    //================================================================

    /**
     * Signals namespace
     * @namespace
     * @name signals
     */
    var signals = Signal;

    /**
     * Custom event broadcaster
     * @see Signal
     */
    // alias for backwards compatibility (see #gh-44)
    signals.Signal = Signal;



    //exports to multiple environments
    if(true){ //AMD
        !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return signals; }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
    } else if (typeof module !== 'undefined' && module.exports){ //node
        module.exports = signals;
    } else { //browser
        //use string because of Google closure compiler ADVANCED_MODE
        /*jslint sub:true */
        global['signals'] = signals;
    }

}(this));


/***/ }),
/* 34 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__index_default_js__ = __webpack_require__(114);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return __WEBPACK_IMPORTED_MODULE_0__index_default_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__index_js__ = __webpack_require__(35);
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["VERSION"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "restArguments", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["restArguments"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isObject"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isNull", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isNull"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isUndefined", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isUndefined"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isBoolean", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isBoolean"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isElement", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isElement"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isString"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isNumber", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isNumber"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isDate", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isDate"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isRegExp", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isRegExp"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isError", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isError"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isSymbol", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isSymbol"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isArrayBuffer", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isArrayBuffer"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isDataView", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isDataView"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isArray", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isArray"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isFunction", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isFunction"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isArguments", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isArguments"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isFinite", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isFinite"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isNaN", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isNaN"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isTypedArray", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isTypedArray"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isEmpty"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isMatch", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isMatch"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isEqual", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isEqual"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isMap", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isMap"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isWeakMap", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isWeakMap"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isSet", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isSet"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "isWeakSet", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["isWeakSet"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "keys", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["keys"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "allKeys", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["allKeys"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "values", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["values"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["pairs"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "invert", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["invert"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "functions", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["functions"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "methods", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["methods"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "extend", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["extend"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "extendOwn", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["extendOwn"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "assign", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["assign"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["defaults"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "create", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["create"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "clone", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["clone"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["tap"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "get", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["get"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "has", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["has"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "mapObject", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["mapObject"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["identity"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "constant", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["constant"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["noop"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "toPath", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["toPath"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "property", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["property"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "propertyOf", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["propertyOf"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "matcher", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["matcher"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "matches", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["matches"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "times", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["times"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "random", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["random"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "now", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["now"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "escape", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["escape"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "unescape", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["unescape"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "templateSettings", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["templateSettings"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "template", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["template"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "result", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["result"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "uniqueId", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["uniqueId"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "chain", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["chain"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "iteratee", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["iteratee"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "partial", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["partial"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "bind", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["bind"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "bindAll", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["bindAll"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "memoize", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["memoize"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["delay"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["defer"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["throttle"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["debounce"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "wrap", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["wrap"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "negate", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["negate"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "compose", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["compose"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "after", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["after"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "before", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["before"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "once", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["once"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "findKey", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["findKey"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["findIndex"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "findLastIndex", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["findLastIndex"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "sortedIndex", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["sortedIndex"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "indexOf", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["indexOf"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "lastIndexOf", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["lastIndexOf"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "find", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["find"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "detect", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["detect"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "findWhere", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["findWhere"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "each", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["each"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "forEach", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["forEach"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "map", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["map"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "collect", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["collect"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["reduce"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "foldl", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["foldl"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "inject", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["inject"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "reduceRight", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["reduceRight"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "foldr", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["foldr"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["filter"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "select", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["select"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "reject", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["reject"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "every", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["every"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "all", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["all"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "some", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["some"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "any", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["any"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["contains"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "includes", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["includes"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "include", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["include"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "invoke", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["invoke"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["pluck"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "where", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["where"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "max", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["max"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "min", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["min"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "shuffle", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["shuffle"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["sample"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "sortBy", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["sortBy"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["groupBy"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "indexBy", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["indexBy"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "countBy", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["countBy"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["partition"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["toArray"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "size", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["size"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "pick", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["pick"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "omit", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["omit"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "first", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["first"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "head", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["head"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "take", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["take"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "initial", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["initial"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "last", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["last"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "rest", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["rest"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "tail", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["tail"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "drop", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["drop"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "compact", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["compact"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "flatten", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["flatten"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "without", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["without"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "uniq", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["uniq"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "unique", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["unique"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "union", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["union"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "intersection", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["intersection"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "difference", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["difference"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "unzip", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["unzip"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "transpose", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["transpose"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["zip"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "object", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["object"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "range", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["range"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "chunk", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["chunk"]; });
/* harmony namespace reexport (by provided) */ __webpack_require__.d(__webpack_exports__, "mixin", function() { return __WEBPACK_IMPORTED_MODULE_1__index_js__["mixin"]; });
// ESM Exports
// ===========
// This module is the package entry point for ES module users. In other words,
// it is the module they are interfacing with when they import from the whole
// package instead of from a submodule, like this:
//
// ```js
// import { map } from 'underscore';
// ```
//
// The difference with `./index-default`, which is the package entry point for
// CommonJS, AMD and UMD users, is purely technical. In ES modules, named and
// default exports are considered to be siblings, so when you have a default
// export, its properties are not automatically available as named exports. For
// this reason, we re-export the named exports in addition to providing the same
// default export as in `./index-default`.




/***/ }),
/* 35 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "VERSION", function() { return __WEBPACK_IMPORTED_MODULE_0__setup_js__["e"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__restArguments_js__ = __webpack_require__(7);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "restArguments", function() { return __WEBPACK_IMPORTED_MODULE_1__restArguments_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isObject_js__ = __webpack_require__(14);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return __WEBPACK_IMPORTED_MODULE_2__isObject_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isNull_js__ = __webpack_require__(116);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isNull", function() { return __WEBPACK_IMPORTED_MODULE_3__isNull_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__isUndefined_js__ = __webpack_require__(53);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isUndefined", function() { return __WEBPACK_IMPORTED_MODULE_4__isUndefined_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__isBoolean_js__ = __webpack_require__(54);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isBoolean", function() { return __WEBPACK_IMPORTED_MODULE_5__isBoolean_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__isElement_js__ = __webpack_require__(117);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isElement", function() { return __WEBPACK_IMPORTED_MODULE_6__isElement_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__isString_js__ = __webpack_require__(36);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return __WEBPACK_IMPORTED_MODULE_7__isString_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__isNumber_js__ = __webpack_require__(55);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isNumber", function() { return __WEBPACK_IMPORTED_MODULE_8__isNumber_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__isDate_js__ = __webpack_require__(118);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isDate", function() { return __WEBPACK_IMPORTED_MODULE_9__isDate_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__isRegExp_js__ = __webpack_require__(119);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isRegExp", function() { return __WEBPACK_IMPORTED_MODULE_10__isRegExp_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__isError_js__ = __webpack_require__(120);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isError", function() { return __WEBPACK_IMPORTED_MODULE_11__isError_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__isSymbol_js__ = __webpack_require__(56);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isSymbol", function() { return __WEBPACK_IMPORTED_MODULE_12__isSymbol_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__isArrayBuffer_js__ = __webpack_require__(57);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isArrayBuffer", function() { return __WEBPACK_IMPORTED_MODULE_13__isArrayBuffer_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__isDataView_js__ = __webpack_require__(37);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isDataView", function() { return __WEBPACK_IMPORTED_MODULE_14__isDataView_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__isArray_js__ = __webpack_require__(15);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isArray", function() { return __WEBPACK_IMPORTED_MODULE_15__isArray_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__isFunction_js__ = __webpack_require__(10);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isFunction", function() { return __WEBPACK_IMPORTED_MODULE_16__isFunction_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__isArguments_js__ = __webpack_require__(38);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isArguments", function() { return __WEBPACK_IMPORTED_MODULE_17__isArguments_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__isFinite_js__ = __webpack_require__(122);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isFinite", function() { return __WEBPACK_IMPORTED_MODULE_18__isFinite_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__isNaN_js__ = __webpack_require__(58);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isNaN", function() { return __WEBPACK_IMPORTED_MODULE_19__isNaN_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__isTypedArray_js__ = __webpack_require__(59);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isTypedArray", function() { return __WEBPACK_IMPORTED_MODULE_20__isTypedArray_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__isEmpty_js__ = __webpack_require__(124);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isEmpty", function() { return __WEBPACK_IMPORTED_MODULE_21__isEmpty_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__isMatch_js__ = __webpack_require__(64);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isMatch", function() { return __WEBPACK_IMPORTED_MODULE_22__isMatch_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__isEqual_js__ = __webpack_require__(125);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isEqual", function() { return __WEBPACK_IMPORTED_MODULE_23__isEqual_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__isMap_js__ = __webpack_require__(127);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isMap", function() { return __WEBPACK_IMPORTED_MODULE_24__isMap_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__isWeakMap_js__ = __webpack_require__(128);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isWeakMap", function() { return __WEBPACK_IMPORTED_MODULE_25__isWeakMap_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_26__isSet_js__ = __webpack_require__(129);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isSet", function() { return __WEBPACK_IMPORTED_MODULE_26__isSet_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_27__isWeakSet_js__ = __webpack_require__(130);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "isWeakSet", function() { return __WEBPACK_IMPORTED_MODULE_27__isWeakSet_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_28__keys_js__ = __webpack_require__(4);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "keys", function() { return __WEBPACK_IMPORTED_MODULE_28__keys_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_29__allKeys_js__ = __webpack_require__(24);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "allKeys", function() { return __WEBPACK_IMPORTED_MODULE_29__allKeys_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_30__values_js__ = __webpack_require__(19);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "values", function() { return __WEBPACK_IMPORTED_MODULE_30__values_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_31__pairs_js__ = __webpack_require__(131);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "pairs", function() { return __WEBPACK_IMPORTED_MODULE_31__pairs_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_32__invert_js__ = __webpack_require__(65);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "invert", function() { return __WEBPACK_IMPORTED_MODULE_32__invert_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_33__functions_js__ = __webpack_require__(66);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "functions", function() { return __WEBPACK_IMPORTED_MODULE_33__functions_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "methods", function() { return __WEBPACK_IMPORTED_MODULE_33__functions_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_34__extend_js__ = __webpack_require__(67);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "extend", function() { return __WEBPACK_IMPORTED_MODULE_34__extend_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_35__extendOwn_js__ = __webpack_require__(42);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "extendOwn", function() { return __WEBPACK_IMPORTED_MODULE_35__extendOwn_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "assign", function() { return __WEBPACK_IMPORTED_MODULE_35__extendOwn_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_36__defaults_js__ = __webpack_require__(68);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "defaults", function() { return __WEBPACK_IMPORTED_MODULE_36__defaults_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_37__create_js__ = __webpack_require__(132);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "create", function() { return __WEBPACK_IMPORTED_MODULE_37__create_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_38__clone_js__ = __webpack_require__(133);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "clone", function() { return __WEBPACK_IMPORTED_MODULE_38__clone_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_39__tap_js__ = __webpack_require__(134);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "tap", function() { return __WEBPACK_IMPORTED_MODULE_39__tap_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_40__get_js__ = __webpack_require__(70);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "get", function() { return __WEBPACK_IMPORTED_MODULE_40__get_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_41__has_js__ = __webpack_require__(135);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "has", function() { return __WEBPACK_IMPORTED_MODULE_41__has_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_42__mapObject_js__ = __webpack_require__(136);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "mapObject", function() { return __WEBPACK_IMPORTED_MODULE_42__mapObject_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_43__identity_js__ = __webpack_require__(44);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "identity", function() { return __WEBPACK_IMPORTED_MODULE_43__identity_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_44__constant_js__ = __webpack_require__(60);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "constant", function() { return __WEBPACK_IMPORTED_MODULE_44__constant_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_45__noop_js__ = __webpack_require__(74);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "noop", function() { return __WEBPACK_IMPORTED_MODULE_45__noop_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_46__toPath_js__ = __webpack_require__(71);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "toPath", function() { return __WEBPACK_IMPORTED_MODULE_46__toPath_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_47__property_js__ = __webpack_require__(45);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "property", function() { return __WEBPACK_IMPORTED_MODULE_47__property_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_48__propertyOf_js__ = __webpack_require__(137);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "propertyOf", function() { return __WEBPACK_IMPORTED_MODULE_48__propertyOf_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_49__matcher_js__ = __webpack_require__(30);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "matcher", function() { return __WEBPACK_IMPORTED_MODULE_49__matcher_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "matches", function() { return __WEBPACK_IMPORTED_MODULE_49__matcher_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_50__times_js__ = __webpack_require__(138);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "times", function() { return __WEBPACK_IMPORTED_MODULE_50__times_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_51__random_js__ = __webpack_require__(75);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "random", function() { return __WEBPACK_IMPORTED_MODULE_51__random_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_52__now_js__ = __webpack_require__(46);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "now", function() { return __WEBPACK_IMPORTED_MODULE_52__now_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_53__escape_js__ = __webpack_require__(139);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "escape", function() { return __WEBPACK_IMPORTED_MODULE_53__escape_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_54__unescape_js__ = __webpack_require__(140);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "unescape", function() { return __WEBPACK_IMPORTED_MODULE_54__unescape_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_55__templateSettings_js__ = __webpack_require__(78);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "templateSettings", function() { return __WEBPACK_IMPORTED_MODULE_55__templateSettings_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_56__template_js__ = __webpack_require__(142);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "template", function() { return __WEBPACK_IMPORTED_MODULE_56__template_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_57__result_js__ = __webpack_require__(143);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "result", function() { return __WEBPACK_IMPORTED_MODULE_57__result_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_58__uniqueId_js__ = __webpack_require__(144);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "uniqueId", function() { return __WEBPACK_IMPORTED_MODULE_58__uniqueId_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_59__chain_js__ = __webpack_require__(145);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "chain", function() { return __WEBPACK_IMPORTED_MODULE_59__chain_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_60__iteratee_js__ = __webpack_require__(73);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "iteratee", function() { return __WEBPACK_IMPORTED_MODULE_60__iteratee_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_61__partial_js__ = __webpack_require__(31);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "partial", function() { return __WEBPACK_IMPORTED_MODULE_61__partial_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_62__bind_js__ = __webpack_require__(80);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "bind", function() { return __WEBPACK_IMPORTED_MODULE_62__bind_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_63__bindAll_js__ = __webpack_require__(146);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "bindAll", function() { return __WEBPACK_IMPORTED_MODULE_63__bindAll_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_64__memoize_js__ = __webpack_require__(147);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "memoize", function() { return __WEBPACK_IMPORTED_MODULE_64__memoize_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_65__delay_js__ = __webpack_require__(81);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "delay", function() { return __WEBPACK_IMPORTED_MODULE_65__delay_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_66__defer_js__ = __webpack_require__(148);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "defer", function() { return __WEBPACK_IMPORTED_MODULE_66__defer_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_67__throttle_js__ = __webpack_require__(149);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return __WEBPACK_IMPORTED_MODULE_67__throttle_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_68__debounce_js__ = __webpack_require__(150);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return __WEBPACK_IMPORTED_MODULE_68__debounce_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_69__wrap_js__ = __webpack_require__(151);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "wrap", function() { return __WEBPACK_IMPORTED_MODULE_69__wrap_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_70__negate_js__ = __webpack_require__(47);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "negate", function() { return __WEBPACK_IMPORTED_MODULE_70__negate_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_71__compose_js__ = __webpack_require__(152);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "compose", function() { return __WEBPACK_IMPORTED_MODULE_71__compose_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_72__after_js__ = __webpack_require__(153);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "after", function() { return __WEBPACK_IMPORTED_MODULE_72__after_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_73__before_js__ = __webpack_require__(82);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "before", function() { return __WEBPACK_IMPORTED_MODULE_73__before_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_74__once_js__ = __webpack_require__(154);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "once", function() { return __WEBPACK_IMPORTED_MODULE_74__once_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_75__findKey_js__ = __webpack_require__(83);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "findKey", function() { return __WEBPACK_IMPORTED_MODULE_75__findKey_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_76__findIndex_js__ = __webpack_require__(48);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "findIndex", function() { return __WEBPACK_IMPORTED_MODULE_76__findIndex_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_77__findLastIndex_js__ = __webpack_require__(85);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "findLastIndex", function() { return __WEBPACK_IMPORTED_MODULE_77__findLastIndex_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_78__sortedIndex_js__ = __webpack_require__(86);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "sortedIndex", function() { return __WEBPACK_IMPORTED_MODULE_78__sortedIndex_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_79__indexOf_js__ = __webpack_require__(87);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "indexOf", function() { return __WEBPACK_IMPORTED_MODULE_79__indexOf_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_80__lastIndexOf_js__ = __webpack_require__(155);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "lastIndexOf", function() { return __WEBPACK_IMPORTED_MODULE_80__lastIndexOf_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_81__find_js__ = __webpack_require__(89);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "find", function() { return __WEBPACK_IMPORTED_MODULE_81__find_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "detect", function() { return __WEBPACK_IMPORTED_MODULE_81__find_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_82__findWhere_js__ = __webpack_require__(156);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "findWhere", function() { return __WEBPACK_IMPORTED_MODULE_82__findWhere_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_83__each_js__ = __webpack_require__(16);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "each", function() { return __WEBPACK_IMPORTED_MODULE_83__each_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "forEach", function() { return __WEBPACK_IMPORTED_MODULE_83__each_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_84__map_js__ = __webpack_require__(21);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "map", function() { return __WEBPACK_IMPORTED_MODULE_84__map_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "collect", function() { return __WEBPACK_IMPORTED_MODULE_84__map_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_85__reduce_js__ = __webpack_require__(157);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "reduce", function() { return __WEBPACK_IMPORTED_MODULE_85__reduce_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "foldl", function() { return __WEBPACK_IMPORTED_MODULE_85__reduce_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "inject", function() { return __WEBPACK_IMPORTED_MODULE_85__reduce_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_86__reduceRight_js__ = __webpack_require__(158);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "reduceRight", function() { return __WEBPACK_IMPORTED_MODULE_86__reduceRight_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "foldr", function() { return __WEBPACK_IMPORTED_MODULE_86__reduceRight_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_87__filter_js__ = __webpack_require__(27);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "filter", function() { return __WEBPACK_IMPORTED_MODULE_87__filter_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "select", function() { return __WEBPACK_IMPORTED_MODULE_87__filter_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_88__reject_js__ = __webpack_require__(159);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "reject", function() { return __WEBPACK_IMPORTED_MODULE_88__reject_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_89__every_js__ = __webpack_require__(160);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "every", function() { return __WEBPACK_IMPORTED_MODULE_89__every_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "all", function() { return __WEBPACK_IMPORTED_MODULE_89__every_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_90__some_js__ = __webpack_require__(161);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "some", function() { return __WEBPACK_IMPORTED_MODULE_90__some_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "any", function() { return __WEBPACK_IMPORTED_MODULE_90__some_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_91__contains_js__ = __webpack_require__(28);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "contains", function() { return __WEBPACK_IMPORTED_MODULE_91__contains_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "includes", function() { return __WEBPACK_IMPORTED_MODULE_91__contains_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "include", function() { return __WEBPACK_IMPORTED_MODULE_91__contains_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_92__invoke_js__ = __webpack_require__(162);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "invoke", function() { return __WEBPACK_IMPORTED_MODULE_92__invoke_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_93__pluck_js__ = __webpack_require__(49);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "pluck", function() { return __WEBPACK_IMPORTED_MODULE_93__pluck_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_94__where_js__ = __webpack_require__(163);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "where", function() { return __WEBPACK_IMPORTED_MODULE_94__where_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_95__max_js__ = __webpack_require__(91);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "max", function() { return __WEBPACK_IMPORTED_MODULE_95__max_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_96__min_js__ = __webpack_require__(164);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "min", function() { return __WEBPACK_IMPORTED_MODULE_96__min_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_97__shuffle_js__ = __webpack_require__(165);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "shuffle", function() { return __WEBPACK_IMPORTED_MODULE_97__shuffle_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_98__sample_js__ = __webpack_require__(92);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "sample", function() { return __WEBPACK_IMPORTED_MODULE_98__sample_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_99__sortBy_js__ = __webpack_require__(166);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "sortBy", function() { return __WEBPACK_IMPORTED_MODULE_99__sortBy_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_100__groupBy_js__ = __webpack_require__(167);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "groupBy", function() { return __WEBPACK_IMPORTED_MODULE_100__groupBy_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_101__indexBy_js__ = __webpack_require__(168);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "indexBy", function() { return __WEBPACK_IMPORTED_MODULE_101__indexBy_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_102__countBy_js__ = __webpack_require__(169);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "countBy", function() { return __WEBPACK_IMPORTED_MODULE_102__countBy_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_103__partition_js__ = __webpack_require__(170);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "partition", function() { return __WEBPACK_IMPORTED_MODULE_103__partition_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_104__toArray_js__ = __webpack_require__(93);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "toArray", function() { return __WEBPACK_IMPORTED_MODULE_104__toArray_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_105__size_js__ = __webpack_require__(171);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "size", function() { return __WEBPACK_IMPORTED_MODULE_105__size_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_106__pick_js__ = __webpack_require__(94);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "pick", function() { return __WEBPACK_IMPORTED_MODULE_106__pick_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_107__omit_js__ = __webpack_require__(173);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "omit", function() { return __WEBPACK_IMPORTED_MODULE_107__omit_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_108__first_js__ = __webpack_require__(174);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "first", function() { return __WEBPACK_IMPORTED_MODULE_108__first_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "head", function() { return __WEBPACK_IMPORTED_MODULE_108__first_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "take", function() { return __WEBPACK_IMPORTED_MODULE_108__first_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_109__initial_js__ = __webpack_require__(95);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "initial", function() { return __WEBPACK_IMPORTED_MODULE_109__initial_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_110__last_js__ = __webpack_require__(175);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "last", function() { return __WEBPACK_IMPORTED_MODULE_110__last_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_111__rest_js__ = __webpack_require__(96);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "rest", function() { return __WEBPACK_IMPORTED_MODULE_111__rest_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "tail", function() { return __WEBPACK_IMPORTED_MODULE_111__rest_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "drop", function() { return __WEBPACK_IMPORTED_MODULE_111__rest_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_112__compact_js__ = __webpack_require__(176);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "compact", function() { return __WEBPACK_IMPORTED_MODULE_112__compact_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_113__flatten_js__ = __webpack_require__(177);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "flatten", function() { return __WEBPACK_IMPORTED_MODULE_113__flatten_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_114__without_js__ = __webpack_require__(178);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "without", function() { return __WEBPACK_IMPORTED_MODULE_114__without_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_115__uniq_js__ = __webpack_require__(98);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "uniq", function() { return __WEBPACK_IMPORTED_MODULE_115__uniq_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "unique", function() { return __WEBPACK_IMPORTED_MODULE_115__uniq_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_116__union_js__ = __webpack_require__(179);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "union", function() { return __WEBPACK_IMPORTED_MODULE_116__union_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_117__intersection_js__ = __webpack_require__(180);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "intersection", function() { return __WEBPACK_IMPORTED_MODULE_117__intersection_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_118__difference_js__ = __webpack_require__(97);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "difference", function() { return __WEBPACK_IMPORTED_MODULE_118__difference_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_119__unzip_js__ = __webpack_require__(99);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "unzip", function() { return __WEBPACK_IMPORTED_MODULE_119__unzip_js__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "transpose", function() { return __WEBPACK_IMPORTED_MODULE_119__unzip_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_120__zip_js__ = __webpack_require__(181);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "zip", function() { return __WEBPACK_IMPORTED_MODULE_120__zip_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_121__object_js__ = __webpack_require__(182);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "object", function() { return __WEBPACK_IMPORTED_MODULE_121__object_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_122__range_js__ = __webpack_require__(183);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "range", function() { return __WEBPACK_IMPORTED_MODULE_122__range_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_123__chunk_js__ = __webpack_require__(184);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "chunk", function() { return __WEBPACK_IMPORTED_MODULE_123__chunk_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_124__mixin_js__ = __webpack_require__(185);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "mixin", function() { return __WEBPACK_IMPORTED_MODULE_124__mixin_js__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_125__underscore_array_methods_js__ = __webpack_require__(186);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return __WEBPACK_IMPORTED_MODULE_125__underscore_array_methods_js__["a"]; });
// Named Exports
// =============

//     Underscore.js 1.13.6
//     https://underscorejs.org
//     (c) 2009-2022 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.

// Baseline setup.



// Object Functions
// ----------------
// Our most fundamental functions operate on any JavaScript object.
// Most functions in Underscore depend on at least one function in this section.

// A group of functions that check the types of core JavaScript values.
// These are often informally referred to as the "isType" functions.



























// Functions that treat an object as a dictionary of key-value pairs.
















// Utility Functions
// -----------------
// A bit of a grab bag: Predicate-generating functions for use with filters and
// loops, string escaping and templating, create random numbers and unique ids,
// and functions that facilitate Underscore's chaining and iteration conventions.



















// Function (ahem) Functions
// -------------------------
// These functions take a function as an argument and return a new function
// as the result. Also known as higher-order functions.















// Finders
// -------
// Functions that extract (the position of) a single element from an object
// or array based on some criterion.









// Collection Functions
// --------------------
// Functions that work on any collection of elements: either an array, or
// an object of key-value pairs.
























// `_.pick` and `_.omit` are actually object functions, but we put
// them here in order to create a more natural reading order in the
// monolithic build as they depend on `_.contains`.



// Array Functions
// ---------------
// Functions that operate on arrays (and array-likes) only, because they’re
// expressed in terms of operations on an ordered list of values.

















// OOP
// ---
// These modules support the "object-oriented" calling style. See also
// `underscore.js` and `index-default.js`.




/***/ }),
/* 36 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);


/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('String'));


/***/ }),
/* 37 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isArrayBuffer_js__ = __webpack_require__(57);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__stringTagBug_js__ = __webpack_require__(23);





var isDataView = Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('DataView');

// In IE 10 - Edge 13, we need a different heuristic
// to determine whether an object is a `DataView`.
function ie10IsDataView(obj) {
  return obj != null && Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(obj.getInt8) && Object(__WEBPACK_IMPORTED_MODULE_2__isArrayBuffer_js__["a" /* default */])(obj.buffer);
}

/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_3__stringTagBug_js__["a" /* hasStringTagBug */] ? ie10IsDataView : isDataView);


/***/ }),
/* 38 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__has_js__ = __webpack_require__(13);



var isArguments = Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Arguments');

// Define a fallback version of the method in browsers (ahem, IE < 9), where
// there isn't any inspectable "Arguments" type.
(function() {
  if (!isArguments(arguments)) {
    isArguments = function(obj) {
      return Object(__WEBPACK_IMPORTED_MODULE_1__has_js__["a" /* default */])(obj, 'callee');
    };
  }
}());

/* harmony default export */ __webpack_exports__["a"] = (isArguments);


/***/ }),
/* 39 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__shallowProperty_js__ = __webpack_require__(62);


// Internal helper to obtain the `byteLength` property of an object.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__shallowProperty_js__["a" /* default */])('byteLength'));


/***/ }),
/* 40 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = ie11fingerprint;
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return mapMethods; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return weakMapMethods; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return setMethods; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__allKeys_js__ = __webpack_require__(24);




// Since the regular `Object.prototype.toString` type tests don't work for
// some types in IE 11, we use a fingerprinting heuristic instead, based
// on the methods. It's not great, but it's the best we got.
// The fingerprint method lists are defined below.
function ie11fingerprint(methods) {
  var length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(methods);
  return function(obj) {
    if (obj == null) return false;
    // `Map`, `WeakMap` and `Set` have no enumerable keys.
    var keys = Object(__WEBPACK_IMPORTED_MODULE_2__allKeys_js__["a" /* default */])(obj);
    if (Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(keys)) return false;
    for (var i = 0; i < length; i++) {
      if (!Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(obj[methods[i]])) return false;
    }
    // If we are testing against `WeakMap`, we need to ensure that
    // `obj` doesn't have a `forEach` method in order to distinguish
    // it from a regular `Map`.
    return methods !== weakMapMethods || !Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(obj[forEachName]);
  };
}

// In the interest of compact minification, we write
// each string in the fingerprints only once.
var forEachName = 'forEach',
    hasName = 'has',
    commonInit = ['clear', 'delete'],
    mapTail = ['get', hasName, 'set'];

// `Map`, `WeakMap` and `Set` each have slightly different
// combinations of the above sublists.
var mapMethods = commonInit.concat(forEachName, mapTail),
    weakMapMethods = commonInit.concat(mapTail),
    setMethods = ['add'].concat(commonInit, forEachName, hasName);


/***/ }),
/* 41 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = createAssigner;
// An internal function for creating assigner functions.
function createAssigner(keysFunc, defaults) {
  return function(obj) {
    var length = arguments.length;
    if (defaults) obj = Object(obj);
    if (length < 2 || obj == null) return obj;
    for (var index = 1; index < length; index++) {
      var source = arguments[index],
          keys = keysFunc(source),
          l = keys.length;
      for (var i = 0; i < l; i++) {
        var key = keys[i];
        if (!defaults || obj[key] === void 0) obj[key] = source[key];
      }
    }
    return obj;
  };
}


/***/ }),
/* 42 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createAssigner_js__ = __webpack_require__(41);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(4);



// Assigns a given object with all the own properties in the passed-in
// object(s).
// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createAssigner_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */]));


/***/ }),
/* 43 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = deepGet;
// Internal function to obtain a nested property in `obj` along `path`.
function deepGet(obj, path) {
  var length = path.length;
  for (var i = 0; i < length; i++) {
    if (obj == null) return void 0;
    obj = obj[path[i]];
  }
  return length ? obj : void 0;
}


/***/ }),
/* 44 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = identity;
// Keep the identity function around for default iteratees.
function identity(value) {
  return value;
}


/***/ }),
/* 45 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = property;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__deepGet_js__ = __webpack_require__(43);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__toPath_js__ = __webpack_require__(25);



// Creates a function that, when passed an object, will traverse that object’s
// properties down the given `path`, specified as an array of keys or indices.
function property(path) {
  path = Object(__WEBPACK_IMPORTED_MODULE_1__toPath_js__["a" /* default */])(path);
  return function(obj) {
    return Object(__WEBPACK_IMPORTED_MODULE_0__deepGet_js__["a" /* default */])(obj, path);
  };
}


/***/ }),
/* 46 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// A (possibly faster) way to get the current timestamp as an integer.
/* harmony default export */ __webpack_exports__["a"] = (Date.now || function() {
  return new Date().getTime();
});


/***/ }),
/* 47 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = negate;
// Returns a negated version of the passed-in predicate.
function negate(predicate) {
  return function() {
    return !predicate.apply(this, arguments);
  };
}


/***/ }),
/* 48 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createPredicateIndexFinder_js__ = __webpack_require__(84);


// Returns the first index on an array-like that passes a truth test.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createPredicateIndexFinder_js__["a" /* default */])(1));


/***/ }),
/* 49 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = pluck;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__map_js__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__property_js__ = __webpack_require__(45);



// Convenience version of a common use case of `_.map`: fetching a property.
function pluck(obj, key) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__map_js__["a" /* default */])(obj, Object(__WEBPACK_IMPORTED_MODULE_1__property_js__["a" /* default */])(key));
}


/***/ }),
/* 50 */
/***/ (function(module, exports) {

/**
 * @author mrdoob / http://mrdoob.com/
 * The MIT License, Copyright &copy; 2010-2016 three.js authors
 */
// TODO changes by Alexander S. Rose
// - more events and properties
// - ctrlKey modifier for Number and Integer
// - UI.Element.prototype.getBox()
// - UI.Element.prototype.dispose()
// - UI.Element.prototype.setTitle()
// - UI.Element.prototype.getStyle()
var UI = {};
UI.Element = function () { };
UI.Element.prototype = {
    setId: function (id) {
        this.dom.id = id;
        return this;
    },
    setTitle: function (title) {
        this.dom.title = title;
        return this;
    },
    setClass: function (name) {
        this.dom.className = name;
        return this;
    },
    setStyle: function (style, array) {
        for (var i = 0; i < array.length; i++) {
            this.dom.style[style] = array[i];
        }
    },
    getStyle: function (style) {
        return this.dom.style[style];
    },
    getBox: function () {
        return this.dom.getBoundingClientRect();
    },
    setDisabled: function (value) {
        this.dom.disabled = value;
        return this;
    },
    setTextContent: function (value) {
        this.dom.textContent = value;
        return this;
    },
    dispose: function () {
        this.dom.parentNode.removeChild(this.dom);
    }
};
// properties
var properties = [
    'position', 'left', 'top', 'right', 'bottom', 'width', 'height', 'border',
    'borderLeft', 'borderTop', 'borderRight', 'borderBottom', 'borderColor',
    'display', 'overflow', 'overflowX', 'overflowY', 'margin', 'marginLeft',
    'marginTop', 'marginRight',
    'marginBottom', 'padding', 'paddingLeft', 'paddingTop', 'paddingRight',
    'paddingBottom', 'color', 'backgroundColor', 'opacity', 'fontSize',
    'fontWeight', 'fontStyle', 'fontFamily', 'textTransform', 'cursor',
    'verticalAlign', 'clear', 'float', 'zIndex', 'minHeight', 'maxHeight',
    'minWidth', 'maxWidth', 'wordBreak', 'wordWrap', 'spellcheck',
    'lineHeight', 'whiteSpace', 'textOverflow', 'textAlign', 'pointerEvents'
];
properties.forEach(function (property) {
    var methodSuffix = property.substr(0, 1).toUpperCase() +
        property.substr(1, property.length);
    UI.Element.prototype['set' + methodSuffix] = function () {
        this.setStyle(property, arguments);
        return this;
    };
    UI.Element.prototype['get' + methodSuffix] = function () {
        return this.getStyle(property);
    };
});
// events
var events = [
    'KeyUp', 'KeyDown', 'KeyPress',
    'MouseOver', 'MouseOut', 'MouseDown', 'MouseUp', 'MouseMove',
    'Click', 'Change', 'Input', 'Scroll'
];
events.forEach(function (event) {
    var method = 'on' + event;
    UI.Element.prototype[method] = function (callback) {
        this.dom.addEventListener(event.toLowerCase(), callback.bind(this), false);
        return this;
    };
});
// Panel
UI.Panel = function () {
    UI.Element.call(this);
    var dom = document.createElement('div');
    dom.className = 'Panel';
    this.dom = dom;
    this.children = [];
    return this;
};
UI.Panel.prototype = Object.create(UI.Element.prototype);
UI.Panel.prototype.add = function () {
    for (var i = 0; i < arguments.length; i++) {
        this.dom.appendChild(arguments[i].dom);
        this.children.push(arguments[i]);
    }
    return this;
};
UI.Panel.prototype.remove = function () {
    for (var i = 0; i < arguments.length; i++) {
        this.dom.removeChild(arguments[i].dom);
        var idx = this.children.indexOf(arguments[i]);
        if (idx !== -1)
            this.children.splice(idx, 1);
    }
    return this;
};
UI.Panel.prototype.clear = function () {
    while (this.dom.children.length) {
        this.dom.removeChild(this.dom.lastChild);
    }
    this.children.length = 0;
    return this;
};
// Collapsible Panel
UI.CollapsiblePanel = function () {
    UI.Panel.call(this);
    this.dom.className = 'Panel CollapsiblePanel';
    this.button = document.createElement('div');
    this.button.className = 'CollapsiblePanelButton';
    this.dom.appendChild(this.button);
    var scope = this;
    this.button.addEventListener('click', function (event) {
        scope.toggle();
    }, false);
    this.content = document.createElement('div');
    this.content.className = 'CollapsibleContent';
    this.dom.appendChild(this.content);
    this.isCollapsed = false;
    return this;
};
UI.CollapsiblePanel.prototype = Object.create(UI.Panel.prototype);
UI.CollapsiblePanel.prototype.addStatic = function () {
    for (var i = 0; i < arguments.length; i++) {
        this.dom.insertBefore(arguments[i].dom, this.content);
    }
    return this;
};
UI.CollapsiblePanel.prototype.removeStatic = UI.Panel.prototype.remove;
UI.CollapsiblePanel.prototype.clearStatic = function () {
    this.dom.childNodes.forEach(function (child) {
        if (child !== this.content) {
            this.dom.removeChild(child);
        }
    });
};
UI.CollapsiblePanel.prototype.add = function () {
    for (var i = 0; i < arguments.length; i++) {
        this.content.appendChild(arguments[i].dom);
    }
    return this;
};
UI.CollapsiblePanel.prototype.remove = function () {
    for (var i = 0; i < arguments.length; i++) {
        this.content.removeChild(arguments[i].dom);
    }
    return this;
};
UI.CollapsiblePanel.prototype.clear = function () {
    while (this.content.children.length) {
        this.content.removeChild(this.content.lastChild);
    }
};
UI.CollapsiblePanel.prototype.toggle = function () {
    this.setCollapsed(!this.isCollapsed);
};
UI.CollapsiblePanel.prototype.collapse = function () {
    this.setCollapsed(true);
};
UI.CollapsiblePanel.prototype.expand = function () {
    this.setCollapsed(false);
};
UI.CollapsiblePanel.prototype.setCollapsed = function (setCollapsed) {
    if (setCollapsed) {
        this.dom.classList.add('collapsed');
    }
    else {
        this.dom.classList.remove('collapsed');
    }
    this.isCollapsed = setCollapsed;
};
// Text
UI.Text = function (text) {
    UI.Element.call(this);
    var dom = document.createElement('span');
    dom.className = 'Text';
    dom.style.display = 'inline-block';
    dom.style.verticalAlign = 'middle';
    this.dom = dom;
    this.setValue(text);
    return this;
};
UI.Text.prototype = Object.create(UI.Element.prototype);
UI.Text.prototype.setValue = function (value) {
    if (value !== undefined) {
        this.dom.textContent = value;
    }
    return this;
};
UI.Text.prototype.setName = function (value) {
    this.dom.name = value;
    return this;
};
// Input
UI.Input = function (value) {
    UI.Element.call(this);
    var scope = this;
    var dom = document.createElement('input');
    dom.className = 'Input';
    dom.style.padding = '2px';
    dom.style.border = '1px solid #ccc';
    dom.addEventListener('keydown', function (event) {
        event.stopPropagation();
    }, false);
    this.dom = dom;
    this.setValue(value || '');
    return this;
};
UI.Input.prototype = Object.create(UI.Element.prototype);
UI.Input.prototype.getValue = function () {
    return this.dom.value;
};
UI.Input.prototype.setValue = function (value) {
    this.dom.value = value;
    return this;
};
UI.Input.prototype.setName = function (value) {
    this.dom.name = value;
    return this;
};
// TextArea
UI.TextArea = function () {
    UI.Element.call(this);
    var scope = this;
    var dom = document.createElement('textarea');
    dom.className = 'TextArea';
    dom.style.padding = '2px';
    dom.style.border = '1px solid #ccc';
    dom.addEventListener('keydown', function (event) {
        event.stopPropagation();
    }, false);
    this.dom = dom;
    return this;
};
UI.TextArea.prototype = Object.create(UI.Element.prototype);
UI.TextArea.prototype.getValue = function () {
    return this.dom.value;
};
UI.TextArea.prototype.setValue = function (value) {
    this.dom.value = value;
    return this;
};
// Select
UI.Select = function () {
    UI.Element.call(this);
    var scope = this;
    var dom = document.createElement('select');
    dom.className = 'Select';
    dom.style.width = '64px';
    dom.style.height = '16px';
    dom.style.border = '0px';
    dom.style.padding = '0px';
    this.dom = dom;
    return this;
};
UI.Select.prototype = Object.create(UI.Element.prototype);
UI.Select.prototype.setMultiple = function (boolean) {
    this.dom.multiple = boolean;
    return this;
};
UI.Select.prototype.setOptions = function (options) {
    var selected = this.dom.value;
    while (this.dom.children.length > 0) {
        this.dom.removeChild(this.dom.firstChild);
    }
    for (var key in options) {
        var option = document.createElement('option');
        option.value = key;
        option.innerHTML = options[key];
        this.dom.appendChild(option);
    }
    this.dom.value = selected;
    return this;
};
UI.Select.prototype.getValue = function () {
    return this.dom.value;
};
UI.Select.prototype.setValue = function (value) {
    this.dom.value = value;
    return this;
};
UI.Select.prototype.setName = function (value) {
    this.dom.name = value;
    return this;
};
// FancySelect
UI.FancySelect = function () {
    UI.Element.call(this);
    var scope = this;
    var dom = document.createElement('div');
    dom.className = 'FancySelect';
    dom.tabIndex = 0; // keyup event is ignored without setting tabIndex
    // Broadcast for object selection after arrow navigation
    var changeEvent = document.createEvent('HTMLEvents');
    changeEvent.initEvent('change', true, true);
    // Prevent native scroll behavior
    dom.addEventListener('keydown', function (event) {
        switch (event.keyCode) {
            case 38: // up
            case 40: // down
                event.preventDefault();
                event.stopPropagation();
                break;
        }
    }, false);
    // Keybindings to support arrow navigation
    dom.addEventListener('keyup', function (event) {
        switch (event.keyCode) {
            case 38: // up
            case 40: // down
                scope.selectedIndex += (event.keyCode == 38) ? -1 : 1;
                if (scope.selectedIndex >= 0 && scope.selectedIndex < scope.options.length) {
                    // Highlight selected dom elem and scroll parent if needed
                    scope.setValue(scope.options[scope.selectedIndex].value);
                    scope.dom.dispatchEvent(changeEvent);
                }
                break;
        }
    }, false);
    this.dom = dom;
    this.options = [];
    this.selectedIndex = -1;
    this.selectedValue = null;
    return this;
};
UI.FancySelect.prototype = Object.create(UI.Element.prototype);
UI.FancySelect.prototype.setOptions = function (options) {
    var scope = this;
    var changeEvent = document.createEvent('HTMLEvents');
    changeEvent.initEvent('change', true, true);
    while (scope.dom.children.length > 0) {
        scope.dom.removeChild(scope.dom.firstChild);
    }
    scope.options = [];
    for (var i = 0; i < options.length; i++) {
        var option = options[i];
        var div = document.createElement('div');
        div.className = 'option';
        div.innerHTML = option.html;
        div.value = option.value;
        scope.dom.appendChild(div);
        scope.options.push(div);
        div.addEventListener('click', function (event) {
            scope.setValue(this.value);
            scope.dom.dispatchEvent(changeEvent);
        }, false);
    }
    return scope;
};
UI.FancySelect.prototype.getValue = function () {
    return this.selectedValue;
};
UI.FancySelect.prototype.setValue = function (value) {
    for (var i = 0; i < this.options.length; i++) {
        var element = this.options[i];
        if (element.value === value) {
            element.classList.add('active');
            // scroll into view
            var y = element.offsetTop - this.dom.offsetTop;
            var bottomY = y + element.offsetHeight;
            var minScroll = bottomY - this.dom.offsetHeight;
            if (this.dom.scrollTop > y) {
                this.dom.scrollTop = y;
            }
            else if (this.dom.scrollTop < minScroll) {
                this.dom.scrollTop = minScroll;
            }
            this.selectedIndex = i;
        }
        else {
            element.classList.remove('active');
        }
    }
    this.selectedValue = value;
    return this;
};
// Checkbox
UI.Checkbox = function (boolean) {
    UI.Element.call(this);
    var scope = this;
    var dom = document.createElement('input');
    dom.className = 'Checkbox';
    dom.type = 'checkbox';
    this.dom = dom;
    this.setValue(boolean);
    return this;
};
UI.Checkbox.prototype = Object.create(UI.Element.prototype);
UI.Checkbox.prototype.getValue = function () {
    return this.dom.checked;
};
UI.Checkbox.prototype.setValue = function (value) {
    if (value !== undefined) {
        this.dom.checked = value;
    }
    return this;
};
UI.Checkbox.prototype.setName = function (value) {
    this.dom.name = value;
    return this;
};
// Color
UI.Color = function () {
    UI.Element.call(this);
    var scope = this;
    var dom = document.createElement('input');
    dom.className = 'Color';
    dom.style.width = '64px';
    dom.style.height = '16px';
    dom.style.border = '0px';
    dom.style.padding = '0px';
    dom.style.backgroundColor = 'transparent';
    try {
        dom.type = 'color';
        dom.value = '#ffffff';
    }
    catch (exception) { }
    this.dom = dom;
    return this;
};
UI.Color.prototype = Object.create(UI.Element.prototype);
UI.Color.prototype.getValue = function () {
    return this.dom.value;
};
UI.Color.prototype.getHexValue = function () {
    return parseInt(this.dom.value.substr(1), 16);
};
UI.Color.prototype.setValue = function (value) {
    this.dom.value = value;
    return this;
};
UI.Color.prototype.setHexValue = function (hex) {
    this.dom.value = '#' + ('000000' + hex.toString(16)).slice(-6);
    return this;
};
// Number
UI.Number = function (number) {
    UI.Element.call(this);
    var scope = this;
    var dom = document.createElement('input');
    dom.className = 'Number';
    dom.value = '0.00';
    dom.addEventListener('keydown', function (event) {
        event.stopPropagation();
        if (event.keyCode === 13)
            dom.blur();
    }, false);
    this.min = -Infinity;
    this.max = Infinity;
    this.precision = 2;
    this.step = 1;
    this.dom = dom;
    this.setValue(number);
    var changeEvent = document.createEvent('HTMLEvents');
    changeEvent.initEvent('change', true, true);
    var distance = 0;
    var onMouseDownValue = 0;
    var pointer = [0, 0];
    var prevPointer = [0, 0];
    var onMouseDown = function (event) {
        event.preventDefault();
        distance = 0;
        onMouseDownValue = parseFloat(dom.value);
        prevPointer = [event.clientX, event.clientY];
        document.addEventListener('mousemove', onMouseMove, false);
        document.addEventListener('mouseup', onMouseUp, false);
    };
    var onMouseMove = function (event) {
        var currentValue = dom.value;
        pointer = [event.clientX, event.clientY];
        distance += (pointer[0] - prevPointer[0]) - (pointer[1] - prevPointer[1]);
        var modifier = 50;
        if (event.shiftKey)
            modifier = 5;
        if (event.ctrlKey)
            modifier = 500;
        var number = onMouseDownValue + (distance / modifier) * scope.step;
        dom.value = Math.min(scope.max, Math.max(scope.min, number)).toFixed(scope.precision);
        if (currentValue !== dom.value)
            dom.dispatchEvent(changeEvent);
        prevPointer = [event.clientX, event.clientY];
    };
    var onMouseUp = function (event) {
        document.removeEventListener('mousemove', onMouseMove, false);
        document.removeEventListener('mouseup', onMouseUp, false);
        if (Math.abs(distance) < 2) {
            dom.focus();
            dom.select();
        }
    };
    var onChange = function (event) {
        var number = parseFloat(dom.value);
        dom.value = isNaN(number) === false ? number : 0;
    };
    var onFocus = function (event) {
        dom.style.backgroundColor = '';
        dom.style.borderColor = '#ccc';
        dom.style.cursor = '';
    };
    var onBlur = function (event) {
        dom.style.backgroundColor = 'transparent';
        dom.style.borderColor = 'transparent';
        dom.style.cursor = 'col-resize';
    };
    dom.addEventListener('mousedown', onMouseDown, false);
    dom.addEventListener('change', onChange, false);
    dom.addEventListener('focus', onFocus, false);
    dom.addEventListener('blur', onBlur, false);
    return this;
};
UI.Number.prototype = Object.create(UI.Element.prototype);
UI.Number.prototype.getValue = function () {
    return parseFloat(this.dom.value);
};
UI.Number.prototype.setValue = function (value) {
    if (isNaN(value)) {
        this.dom.value = NaN;
    }
    else if (value !== undefined) {
        this.dom.value = value.toFixed(this.precision);
    }
    return this;
};
UI.Number.prototype.setRange = function (min, max) {
    this.min = min;
    this.max = max;
    return this;
};
UI.Number.prototype.setPrecision = function (precision) {
    this.precision = precision;
    this.setValue(parseFloat(this.dom.value));
    return this;
};
UI.Number.prototype.setName = function (value) {
    this.dom.name = value;
    return this;
};
// Integer
UI.Integer = function (number) {
    UI.Element.call(this);
    var scope = this;
    var dom = document.createElement('input');
    dom.className = 'Number';
    dom.value = '0.00';
    dom.addEventListener('keydown', function (event) {
        event.stopPropagation();
    }, false);
    this.min = -Infinity;
    this.max = Infinity;
    this.step = 1;
    this.dom = dom;
    this.setValue(number);
    var changeEvent = document.createEvent('HTMLEvents');
    changeEvent.initEvent('change', true, true);
    var distance = 0;
    var onMouseDownValue = 0;
    var pointer = [0, 0];
    var prevPointer = [0, 0];
    var onMouseDown = function (event) {
        event.preventDefault();
        distance = 0;
        onMouseDownValue = parseFloat(dom.value);
        prevPointer = [event.clientX, event.clientY];
        document.addEventListener('mousemove', onMouseMove, false);
        document.addEventListener('mouseup', onMouseUp, false);
    };
    var onMouseMove = function (event) {
        var currentValue = dom.value;
        pointer = [event.clientX, event.clientY];
        distance += (pointer[0] - prevPointer[0]) - (pointer[1] - prevPointer[1]);
        var modifier = 50;
        if (event.shiftKey)
            modifier = 5;
        if (event.ctrlKey)
            modifier = 500;
        var number = onMouseDownValue + (distance / modifier) * scope.step;
        dom.value = Math.min(scope.max, Math.max(scope.min, number)) | 0;
        if (currentValue !== dom.value)
            dom.dispatchEvent(changeEvent);
        prevPointer = [event.clientX, event.clientY];
    };
    var onMouseUp = function (event) {
        document.removeEventListener('mousemove', onMouseMove, false);
        document.removeEventListener('mouseup', onMouseUp, false);
        if (Math.abs(distance) < 2) {
            dom.focus();
            dom.select();
        }
    };
    var onChange = function (event) {
        var number = parseInt(dom.value);
        if (isNaN(number) === false) {
            dom.value = number;
        }
    };
    var onFocus = function (event) {
        dom.style.backgroundColor = '';
        dom.style.borderColor = '#ccc';
        dom.style.cursor = '';
    };
    var onBlur = function (event) {
        dom.style.backgroundColor = 'transparent';
        dom.style.borderColor = 'transparent';
        dom.style.cursor = 'col-resize';
    };
    dom.addEventListener('mousedown', onMouseDown, false);
    dom.addEventListener('change', onChange, false);
    dom.addEventListener('focus', onFocus, false);
    dom.addEventListener('blur', onBlur, false);
    return this;
};
UI.Integer.prototype = Object.create(UI.Element.prototype);
UI.Integer.prototype.getValue = function () {
    return parseInt(this.dom.value);
};
UI.Integer.prototype.setValue = function (value) {
    if (value !== undefined) {
        this.dom.value = value | 0;
    }
    return this;
};
UI.Integer.prototype.setRange = function (min, max) {
    this.min = min;
    this.max = max;
    return this;
};
UI.Integer.prototype.setName = function (value) {
    this.dom.name = value;
    return this;
};
UI.Integer.prototype.setStep = function (step) {
    this.step = step;
    return this;
};
// Break
UI.Break = function () {
    UI.Element.call(this);
    var dom = document.createElement('br');
    dom.className = 'Break';
    this.dom = dom;
    return this;
};
UI.Break.prototype = Object.create(UI.Element.prototype);
// HorizontalRule
UI.HorizontalRule = function () {
    UI.Element.call(this);
    var dom = document.createElement('hr');
    dom.className = 'HorizontalRule';
    this.dom = dom;
    return this;
};
UI.HorizontalRule.prototype = Object.create(UI.Element.prototype);
// Button
UI.Button = function (value) {
    UI.Element.call(this);
    var scope = this;
    var dom = document.createElement('button');
    dom.className = 'Button';
    this.dom = dom;
    this.dom.textContent = value;
    return this;
};
UI.Button.prototype = Object.create(UI.Element.prototype);
UI.Button.prototype.setLabel = function (value) {
    this.dom.textContent = value;
    return this;
};
// Helper
UI.MenubarHelper = {
    createMenuContainer: function (name, optionsPanel) {
        var container = new UI.Panel();
        var title = new UI.Panel();
        title.setClass('title');
        title.setTextContent(name);
        title.setMargin('0px');
        title.setPadding('8px');
        container.setClass('menu');
        container.add(title);
        container.add(optionsPanel);
        return container;
    },
    createOption: function (name, callbackHandler, icon) {
        var option = new UI.Panel();
        option.setClass('option');
        if (icon) {
            option.add(new UI.Icon(icon).setWidth('20px'));
            option.add(new UI.Text(name));
        }
        else {
            option.setTextContent(name);
        }
        option.onClick(callbackHandler);
        return option;
    },
    createOptionsPanel: function (menuConfig) {
        var options = new UI.Panel();
        options.setClass('options');
        menuConfig.forEach(function (option) {
            options.add(option);
        });
        return options;
    },
    createInput: function (name, callbackHandler) {
        var panel = new UI.Panel()
            .setClass('option');
        var text = new UI.Text()
            .setWidth('70px')
            .setValue(name);
        var input = new UI.Input()
            .setWidth('40px')
            .onKeyDown(callbackHandler);
        panel.add(text);
        panel.add(input);
        return panel;
    },
    createCheckbox: function (name, value, callbackHandler) {
        var panel = new UI.Panel()
            .setClass('option');
        var text = new UI.Text()
            .setWidth('70px')
            .setValue(name);
        var checkbox = new UI.Checkbox()
            .setValue(value)
            .onClick(callbackHandler);
        panel.add(checkbox);
        panel.add(text);
        return panel;
    },
    createDivider: function () {
        return new UI.HorizontalRule();
    }
};
module.exports = {
    "UI": UI
};
//# sourceMappingURL=data:application/json;base64, 

/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Mouse 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
			__webpack_require__(0),
			__webpack_require__(197),
			__webpack_require__(3),
			__webpack_require__(17)
		], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

var mouseHandled = false;
$( document ).on( "mouseup", function() {
	mouseHandled = false;
} );

return $.widget( "ui.mouse", {
	version: "1.13.2",
	options: {
		cancel: "input, textarea, button, select, option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.on( "mousedown." + this.widgetName, function( event ) {
				return that._mouseDown( event );
			} )
			.on( "click." + this.widgetName, function( event ) {
				if ( true === $.data( event.target, that.widgetName + ".preventClickEvent" ) ) {
					$.removeData( event.target, that.widgetName + ".preventClickEvent" );
					event.stopImmediatePropagation();
					return false;
				}
			} );

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.off( "." + this.widgetName );
		if ( this._mouseMoveDelegate ) {
			this.document
				.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
				.off( "mouseup." + this.widgetName, this._mouseUpDelegate );
		}
	},

	_mouseDown: function( event ) {

		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// We may have missed mouseup (out of window)
		if ( this._mouseStarted ) {
			this._mouseUp( event );
		}

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = ( event.which === 1 ),

			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = ( typeof this.options.cancel === "string" && event.target.nodeName ?
				$( event.target ).closest( this.options.cancel ).length : false );
		if ( !btnIsLeft || elIsCancel || !this._mouseCapture( event ) ) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if ( !this.mouseDelayMet ) {
			this._mouseDelayTimer = setTimeout( function() {
				that.mouseDelayMet = true;
			}, this.options.delay );
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted = ( this._mouseStart( event ) !== false );
			if ( !this._mouseStarted ) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if ( true === $.data( event.target, this.widgetName + ".preventClickEvent" ) ) {
			$.removeData( event.target, this.widgetName + ".preventClickEvent" );
		}

		// These delegates are required to keep context
		this._mouseMoveDelegate = function( event ) {
			return that._mouseMove( event );
		};
		this._mouseUpDelegate = function( event ) {
			return that._mouseUp( event );
		};

		this.document
			.on( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.on( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function( event ) {

		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {

			// IE mouseup check - mouseup happened when mouse was out of window
			if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) &&
					!event.button ) {
				return this._mouseUp( event );

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {

				// Support: Safari <=8 - 9
				// Safari sets which to 0 if you press any of the following keys
				// during a drag (#14461)
				if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
						event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
					this.ignoreMissingWhich = true;
				} else if ( !this.ignoreMissingWhich ) {
					return this._mouseUp( event );
				}
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if ( this._mouseStarted ) {
			this._mouseDrag( event );
			return event.preventDefault();
		}

		if ( this._mouseDistanceMet( event ) && this._mouseDelayMet( event ) ) {
			this._mouseStarted =
				( this._mouseStart( this._mouseDownEvent, event ) !== false );
			if ( this._mouseStarted ) {
				this._mouseDrag( event );
			} else {
				this._mouseUp( event );
			}
		}

		return !this._mouseStarted;
	},

	_mouseUp: function( event ) {
		this.document
			.off( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.off( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if ( this._mouseStarted ) {
			this._mouseStarted = false;

			if ( event.target === this._mouseDownEvent.target ) {
				$.data( event.target, this.widgetName + ".preventClickEvent", true );
			}

			this._mouseStop( event );
		}

		if ( this._mouseDelayTimer ) {
			clearTimeout( this._mouseDelayTimer );
			delete this._mouseDelayTimer;
		}

		this.ignoreMissingWhich = false;
		mouseHandled = false;
		event.preventDefault();
	},

	_mouseDistanceMet: function( event ) {
		return ( Math.max(
				Math.abs( this._mouseDownEvent.pageX - event.pageX ),
				Math.abs( this._mouseDownEvent.pageY - event.pageY )
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function( /* event */ ) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function( /* event */ ) {},
	_mouseDrag: function( /* event */ ) {},
	_mouseStop: function( /* event */ ) {},
	_mouseCapture: function( /* event */ ) {
		return true;
	}
} );

} );


/***/ }),
/* 52 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export ACESFilmicToneMapping */
/* unused harmony export AddEquation */
/* unused harmony export AddOperation */
/* unused harmony export AdditiveAnimationBlendMode */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AdditiveBlending; });
/* unused harmony export AlphaFormat */
/* unused harmony export AlwaysDepth */
/* unused harmony export AlwaysStencilFunc */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return AmbientLight; });
/* unused harmony export AmbientLightProbe */
/* unused harmony export AnimationClip */
/* unused harmony export AnimationLoader */
/* unused harmony export AnimationMixer */
/* unused harmony export AnimationObjectGroup */
/* unused harmony export AnimationUtils */
/* unused harmony export ArcCurve */
/* unused harmony export ArrayCamera */
/* unused harmony export ArrowHelper */
/* unused harmony export Audio */
/* unused harmony export AudioAnalyser */
/* unused harmony export AudioContext */
/* unused harmony export AudioListener */
/* unused harmony export AudioLoader */
/* unused harmony export AxesHelper */
/* unused harmony export AxisHelper */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return BackSide; });
/* unused harmony export BasicDepthPacking */
/* unused harmony export BasicShadowMap */
/* unused harmony export BinaryTextureLoader */
/* unused harmony export Bone */
/* unused harmony export BooleanKeyframeTrack */
/* unused harmony export BoundingBoxHelper */
/* unused harmony export Box2 */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return Box3; });
/* unused harmony export Box3Helper */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return BoxBufferGeometry; });
/* unused harmony export BoxGeometry */
/* unused harmony export BoxHelper */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return BufferAttribute; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return BufferGeometry; });
/* unused harmony export BufferGeometryLoader */
/* unused harmony export ByteType */
/* unused harmony export Cache */
/* unused harmony export Camera */
/* unused harmony export CameraHelper */
/* unused harmony export CanvasRenderer */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return CanvasTexture; });
/* unused harmony export CatmullRomCurve3 */
/* unused harmony export CineonToneMapping */
/* unused harmony export CircleBufferGeometry */
/* unused harmony export CircleGeometry */
/* unused harmony export ClampToEdgeWrapping */
/* unused harmony export Clock */
/* unused harmony export ClosedSplineCurve3 */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return Color; });
/* unused harmony export ColorKeyframeTrack */
/* unused harmony export CompressedTexture */
/* unused harmony export CompressedTextureLoader */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return ConeBufferGeometry; });
/* unused harmony export ConeGeometry */
/* unused harmony export CubeCamera */
/* unused harmony export CubeGeometry */
/* unused harmony export CubeReflectionMapping */
/* unused harmony export CubeRefractionMapping */
/* unused harmony export CubeTexture */
/* unused harmony export CubeTextureLoader */
/* unused harmony export CubeUVReflectionMapping */
/* unused harmony export CubeUVRefractionMapping */
/* unused harmony export CubicBezierCurve */
/* unused harmony export CubicBezierCurve3 */
/* unused harmony export CubicInterpolant */
/* unused harmony export CullFaceBack */
/* unused harmony export CullFaceFront */
/* unused harmony export CullFaceFrontBack */
/* unused harmony export CullFaceNone */
/* unused harmony export Curve */
/* unused harmony export CurvePath */
/* unused harmony export CustomBlending */
/* unused harmony export CustomToneMapping */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return CylinderBufferGeometry; });
/* unused harmony export CylinderGeometry */
/* unused harmony export Cylindrical */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return DataTexture; });
/* unused harmony export DataTexture2DArray */
/* unused harmony export DataTexture3D */
/* unused harmony export DataTextureLoader */
/* unused harmony export DecrementStencilOp */
/* unused harmony export DecrementWrapStencilOp */
/* unused harmony export DefaultLoadingManager */
/* unused harmony export DepthFormat */
/* unused harmony export DepthStencilFormat */
/* unused harmony export DepthTexture */
/* unused harmony export DirectionalLight */
/* unused harmony export DirectionalLightHelper */
/* unused harmony export DirectionalLightShadow */
/* unused harmony export DiscreteInterpolant */
/* unused harmony export DodecahedronBufferGeometry */
/* unused harmony export DodecahedronGeometry */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return DoubleSide; });
/* unused harmony export DstAlphaFactor */
/* unused harmony export DstColorFactor */
/* unused harmony export DynamicBufferAttribute */
/* unused harmony export DynamicCopyUsage */
/* unused harmony export DynamicDrawUsage */
/* unused harmony export DynamicReadUsage */
/* unused harmony export EdgesGeometry */
/* unused harmony export EdgesHelper */
/* unused harmony export EllipseCurve */
/* unused harmony export EqualDepth */
/* unused harmony export EqualStencilFunc */
/* unused harmony export EquirectangularReflectionMapping */
/* unused harmony export EquirectangularRefractionMapping */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return Euler; });
/* unused harmony export EventDispatcher */
/* unused harmony export ExtrudeBufferGeometry */
/* unused harmony export ExtrudeGeometry */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return Face3; });
/* unused harmony export Face4 */
/* unused harmony export FaceColors */
/* unused harmony export FileLoader */
/* unused harmony export FlatShading */
/* unused harmony export Float32Attribute */
/* unused harmony export Float32BufferAttribute */
/* unused harmony export Float64Attribute */
/* unused harmony export Float64BufferAttribute */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return FloatType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return Fog; });
/* unused harmony export FogExp2 */
/* unused harmony export Font */
/* unused harmony export FontLoader */
/* unused harmony export FrontFaceDirectionCCW */
/* unused harmony export FrontFaceDirectionCW */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return FrontSide; });
/* unused harmony export Frustum */
/* unused harmony export GammaEncoding */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return Geometry; });
/* unused harmony export GeometryUtils */
/* unused harmony export GreaterDepth */
/* unused harmony export GreaterEqualDepth */
/* unused harmony export GreaterEqualStencilFunc */
/* unused harmony export GreaterStencilFunc */
/* unused harmony export GridHelper */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return Group; });
/* unused harmony export HalfFloatType */
/* unused harmony export HemisphereLight */
/* unused harmony export HemisphereLightHelper */
/* unused harmony export HemisphereLightProbe */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "u", function() { return IcosahedronBufferGeometry; });
/* unused harmony export IcosahedronGeometry */
/* unused harmony export ImageBitmapLoader */
/* unused harmony export ImageLoader */
/* unused harmony export ImageUtils */
/* unused harmony export ImmediateRenderObject */
/* unused harmony export IncrementStencilOp */
/* unused harmony export IncrementWrapStencilOp */
/* unused harmony export InstancedBufferAttribute */
/* unused harmony export InstancedBufferGeometry */
/* unused harmony export InstancedInterleavedBuffer */
/* unused harmony export InstancedMesh */
/* unused harmony export Int16Attribute */
/* unused harmony export Int16BufferAttribute */
/* unused harmony export Int32Attribute */
/* unused harmony export Int32BufferAttribute */
/* unused harmony export Int8Attribute */
/* unused harmony export Int8BufferAttribute */
/* unused harmony export IntType */
/* unused harmony export InterleavedBuffer */
/* unused harmony export InterleavedBufferAttribute */
/* unused harmony export Interpolant */
/* unused harmony export InterpolateDiscrete */
/* unused harmony export InterpolateLinear */
/* unused harmony export InterpolateSmooth */
/* unused harmony export InvertStencilOp */
/* unused harmony export JSONLoader */
/* unused harmony export KeepStencilOp */
/* unused harmony export KeyframeTrack */
/* unused harmony export LOD */
/* unused harmony export LatheBufferGeometry */
/* unused harmony export LatheGeometry */
/* unused harmony export Layers */
/* unused harmony export LensFlare */
/* unused harmony export LessDepth */
/* unused harmony export LessEqualDepth */
/* unused harmony export LessEqualStencilFunc */
/* unused harmony export LessStencilFunc */
/* unused harmony export Light */
/* unused harmony export LightProbe */
/* unused harmony export LightShadow */
/* unused harmony export Line */
/* unused harmony export Line3 */
/* unused harmony export LineBasicMaterial */
/* unused harmony export LineCurve */
/* unused harmony export LineCurve3 */
/* unused harmony export LineDashedMaterial */
/* unused harmony export LineLoop */
/* unused harmony export LinePieces */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v", function() { return LineSegments; });
/* unused harmony export LineStrip */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", function() { return LinearEncoding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "x", function() { return LinearFilter; });
/* unused harmony export LinearInterpolant */
/* unused harmony export LinearMipMapLinearFilter */
/* unused harmony export LinearMipMapNearestFilter */
/* unused harmony export LinearMipmapLinearFilter */
/* unused harmony export LinearMipmapNearestFilter */
/* unused harmony export LinearToneMapping */
/* unused harmony export Loader */
/* unused harmony export LoaderUtils */
/* unused harmony export LoadingManager */
/* unused harmony export LogLuvEncoding */
/* unused harmony export LoopOnce */
/* unused harmony export LoopPingPong */
/* unused harmony export LoopRepeat */
/* unused harmony export LuminanceAlphaFormat */
/* unused harmony export LuminanceFormat */
/* unused harmony export MOUSE */
/* unused harmony export Material */
/* unused harmony export MaterialLoader */
/* unused harmony export Math */
/* unused harmony export MathUtils */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "y", function() { return Matrix3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "z", function() { return Matrix4; });
/* unused harmony export MaxEquation */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "A", function() { return Mesh; });
/* unused harmony export MeshBasicMaterial */
/* unused harmony export MeshDepthMaterial */
/* unused harmony export MeshDistanceMaterial */
/* unused harmony export MeshFaceMaterial */
/* unused harmony export MeshLambertMaterial */
/* unused harmony export MeshMatcapMaterial */
/* unused harmony export MeshNormalMaterial */
/* unused harmony export MeshPhongMaterial */
/* unused harmony export MeshPhysicalMaterial */
/* unused harmony export MeshStandardMaterial */
/* unused harmony export MeshToonMaterial */
/* unused harmony export MinEquation */
/* unused harmony export MirroredRepeatWrapping */
/* unused harmony export MixOperation */
/* unused harmony export MultiMaterial */
/* unused harmony export MultiplyBlending */
/* unused harmony export MultiplyOperation */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "B", function() { return NearestFilter; });
/* unused harmony export NearestMipMapLinearFilter */
/* unused harmony export NearestMipMapNearestFilter */
/* unused harmony export NearestMipmapLinearFilter */
/* unused harmony export NearestMipmapNearestFilter */
/* unused harmony export NeverDepth */
/* unused harmony export NeverStencilFunc */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return NoBlending; });
/* unused harmony export NoColors */
/* unused harmony export NoToneMapping */
/* unused harmony export NormalAnimationBlendMode */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "D", function() { return NormalBlending; });
/* unused harmony export NotEqualDepth */
/* unused harmony export NotEqualStencilFunc */
/* unused harmony export NumberKeyframeTrack */
/* unused harmony export Object3D */
/* unused harmony export ObjectLoader */
/* unused harmony export ObjectSpaceNormalMap */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "E", function() { return OctahedronBufferGeometry; });
/* unused harmony export OctahedronGeometry */
/* unused harmony export OneFactor */
/* unused harmony export OneMinusDstAlphaFactor */
/* unused harmony export OneMinusDstColorFactor */
/* unused harmony export OneMinusSrcAlphaFactor */
/* unused harmony export OneMinusSrcColorFactor */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "F", function() { return OrthographicCamera; });
/* unused harmony export PCFShadowMap */
/* unused harmony export PCFSoftShadowMap */
/* unused harmony export PMREMGenerator */
/* unused harmony export ParametricBufferGeometry */
/* unused harmony export ParametricGeometry */
/* unused harmony export Particle */
/* unused harmony export ParticleBasicMaterial */
/* unused harmony export ParticleSystem */
/* unused harmony export ParticleSystemMaterial */
/* unused harmony export Path */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "G", function() { return PerspectiveCamera; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "H", function() { return Plane; });
/* unused harmony export PlaneBufferGeometry */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "I", function() { return PlaneGeometry; });
/* unused harmony export PlaneHelper */
/* unused harmony export PointCloud */
/* unused harmony export PointCloudMaterial */
/* unused harmony export PointLight */
/* unused harmony export PointLightHelper */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "J", function() { return Points; });
/* unused harmony export PointsMaterial */
/* unused harmony export PolarGridHelper */
/* unused harmony export PolyhedronBufferGeometry */
/* unused harmony export PolyhedronGeometry */
/* unused harmony export PositionalAudio */
/* unused harmony export PropertyBinding */
/* unused harmony export PropertyMixer */
/* unused harmony export QuadraticBezierCurve */
/* unused harmony export QuadraticBezierCurve3 */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "K", function() { return Quaternion; });
/* unused harmony export QuaternionKeyframeTrack */
/* unused harmony export QuaternionLinearInterpolant */
/* unused harmony export REVISION */
/* unused harmony export RGBADepthPacking */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "L", function() { return RGBAFormat; });
/* unused harmony export RGBAIntegerFormat */
/* unused harmony export RGBA_ASTC_10x10_Format */
/* unused harmony export RGBA_ASTC_10x5_Format */
/* unused harmony export RGBA_ASTC_10x6_Format */
/* unused harmony export RGBA_ASTC_10x8_Format */
/* unused harmony export RGBA_ASTC_12x10_Format */
/* unused harmony export RGBA_ASTC_12x12_Format */
/* unused harmony export RGBA_ASTC_4x4_Format */
/* unused harmony export RGBA_ASTC_5x4_Format */
/* unused harmony export RGBA_ASTC_5x5_Format */
/* unused harmony export RGBA_ASTC_6x5_Format */
/* unused harmony export RGBA_ASTC_6x6_Format */
/* unused harmony export RGBA_ASTC_8x5_Format */
/* unused harmony export RGBA_ASTC_8x6_Format */
/* unused harmony export RGBA_ASTC_8x8_Format */
/* unused harmony export RGBA_BPTC_Format */
/* unused harmony export RGBA_ETC2_EAC_Format */
/* unused harmony export RGBA_PVRTC_2BPPV1_Format */
/* unused harmony export RGBA_PVRTC_4BPPV1_Format */
/* unused harmony export RGBA_S3TC_DXT1_Format */
/* unused harmony export RGBA_S3TC_DXT3_Format */
/* unused harmony export RGBA_S3TC_DXT5_Format */
/* unused harmony export RGBDEncoding */
/* unused harmony export RGBEEncoding */
/* unused harmony export RGBEFormat */
/* unused harmony export RGBFormat */
/* unused harmony export RGBIntegerFormat */
/* unused harmony export RGBM16Encoding */
/* unused harmony export RGBM7Encoding */
/* unused harmony export RGB_ETC1_Format */
/* unused harmony export RGB_ETC2_Format */
/* unused harmony export RGB_PVRTC_2BPPV1_Format */
/* unused harmony export RGB_PVRTC_4BPPV1_Format */
/* unused harmony export RGB_S3TC_DXT1_Format */
/* unused harmony export RGFormat */
/* unused harmony export RGIntegerFormat */
/* unused harmony export RawShaderMaterial */
/* unused harmony export Ray */
/* unused harmony export Raycaster */
/* unused harmony export RectAreaLight */
/* unused harmony export RedFormat */
/* unused harmony export RedIntegerFormat */
/* unused harmony export ReinhardToneMapping */
/* unused harmony export RepeatWrapping */
/* unused harmony export ReplaceStencilOp */
/* unused harmony export ReverseSubtractEquation */
/* unused harmony export RingBufferGeometry */
/* unused harmony export RingGeometry */
/* unused harmony export SRGB8_ALPHA8_ASTC_10x10_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_10x5_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_10x6_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_10x8_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_12x10_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_12x12_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_4x4_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_5x4_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_5x5_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_6x5_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_6x6_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_8x5_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_8x6_Format */
/* unused harmony export SRGB8_ALPHA8_ASTC_8x8_Format */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "M", function() { return Scene; });
/* unused harmony export SceneUtils */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "N", function() { return ShaderChunk; });
/* unused harmony export ShaderLib */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "O", function() { return ShaderMaterial; });
/* unused harmony export ShadowMaterial */
/* unused harmony export Shape */
/* unused harmony export ShapeBufferGeometry */
/* unused harmony export ShapeGeometry */
/* unused harmony export ShapePath */
/* unused harmony export ShapeUtils */
/* unused harmony export ShortType */
/* unused harmony export Skeleton */
/* unused harmony export SkeletonHelper */
/* unused harmony export SkinnedMesh */
/* unused harmony export SmoothShading */
/* unused harmony export Sphere */
/* unused harmony export SphereBufferGeometry */
/* unused harmony export SphereGeometry */
/* unused harmony export Spherical */
/* unused harmony export SphericalHarmonics3 */
/* unused harmony export Spline */
/* unused harmony export SplineCurve */
/* unused harmony export SplineCurve3 */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "P", function() { return SpotLight; });
/* unused harmony export SpotLightHelper */
/* unused harmony export SpotLightShadow */
/* unused harmony export Sprite */
/* unused harmony export SpriteMaterial */
/* unused harmony export SrcAlphaFactor */
/* unused harmony export SrcAlphaSaturateFactor */
/* unused harmony export SrcColorFactor */
/* unused harmony export StaticCopyUsage */
/* unused harmony export StaticDrawUsage */
/* unused harmony export StaticReadUsage */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Q", function() { return StereoCamera; });
/* unused harmony export StreamCopyUsage */
/* unused harmony export StreamDrawUsage */
/* unused harmony export StreamReadUsage */
/* unused harmony export StringKeyframeTrack */
/* unused harmony export SubtractEquation */
/* unused harmony export SubtractiveBlending */
/* unused harmony export TOUCH */
/* unused harmony export TangentSpaceNormalMap */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "R", function() { return TetrahedronBufferGeometry; });
/* unused harmony export TetrahedronGeometry */
/* unused harmony export TextBufferGeometry */
/* unused harmony export TextGeometry */
/* unused harmony export Texture */
/* unused harmony export TextureLoader */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "S", function() { return TorusBufferGeometry; });
/* unused harmony export TorusGeometry */
/* unused harmony export TorusKnotBufferGeometry */
/* unused harmony export TorusKnotGeometry */
/* unused harmony export Triangle */
/* unused harmony export TriangleFanDrawMode */
/* unused harmony export TriangleStripDrawMode */
/* unused harmony export TrianglesDrawMode */
/* unused harmony export TubeBufferGeometry */
/* unused harmony export TubeGeometry */
/* unused harmony export UVMapping */
/* unused harmony export Uint16Attribute */
/* unused harmony export Uint16BufferAttribute */
/* unused harmony export Uint32Attribute */
/* unused harmony export Uint32BufferAttribute */
/* unused harmony export Uint8Attribute */
/* unused harmony export Uint8BufferAttribute */
/* unused harmony export Uint8ClampedAttribute */
/* unused harmony export Uint8ClampedBufferAttribute */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "T", function() { return Uniform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "U", function() { return UniformsLib; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "V", function() { return UniformsUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "W", function() { return UnsignedByteType; });
/* unused harmony export UnsignedInt248Type */
/* unused harmony export UnsignedIntType */
/* unused harmony export UnsignedShort4444Type */
/* unused harmony export UnsignedShort5551Type */
/* unused harmony export UnsignedShort565Type */
/* unused harmony export UnsignedShortType */
/* unused harmony export VSMShadowMap */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "X", function() { return Vector2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Y", function() { return Vector3; });
/* unused harmony export Vector4 */
/* unused harmony export VectorKeyframeTrack */
/* unused harmony export Vertex */
/* unused harmony export VertexColors */
/* unused harmony export VideoTexture */
/* unused harmony export WebGL1Renderer */
/* unused harmony export WebGLCubeRenderTarget */
/* unused harmony export WebGLMultisampleRenderTarget */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Z", function() { return WebGLRenderTarget; });
/* unused harmony export WebGLRenderTargetCube */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_0", function() { return WebGLRenderer; });
/* unused harmony export WebGLUtils */
/* unused harmony export WireframeGeometry */
/* unused harmony export WireframeHelper */
/* unused harmony export WrapAroundEnding */
/* unused harmony export XHRLoader */
/* unused harmony export ZeroCurvatureEnding */
/* unused harmony export ZeroFactor */
/* unused harmony export ZeroSlopeEnding */
/* unused harmony export ZeroStencilOp */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_1", function() { return sRGBEncoding; });
// Polyfills

if ( Number.EPSILON === undefined ) {

	Number.EPSILON = Math.pow( 2, - 52 );

}

if ( Number.isInteger === undefined ) {

	// Missing in IE
	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

	Number.isInteger = function ( value ) {

		return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;

	};

}

//

if ( Math.sign === undefined ) {

	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

	Math.sign = function ( x ) {

		return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;

	};

}

if ( 'name' in Function.prototype === false ) {

	// Missing in IE
	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

	Object.defineProperty( Function.prototype, 'name', {

		get: function () {

			return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];

		}

	} );

}

if ( Object.assign === undefined ) {

	// Missing in IE
	// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

	Object.assign = function ( target ) {

		if ( target === undefined || target === null ) {

			throw new TypeError( 'Cannot convert undefined or null to object' );

		}

		const output = Object( target );

		for ( let index = 1; index < arguments.length; index ++ ) {

			const source = arguments[ index ];

			if ( source !== undefined && source !== null ) {

				for ( const nextKey in source ) {

					if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {

						output[ nextKey ] = source[ nextKey ];

					}

				}

			}

		}

		return output;

	};

}

const REVISION = '118';
const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
const CullFaceNone = 0;
const CullFaceBack = 1;
const CullFaceFront = 2;
const CullFaceFrontBack = 3;
const FrontFaceDirectionCW = 0;
const FrontFaceDirectionCCW = 1;
const BasicShadowMap = 0;
const PCFShadowMap = 1;
const PCFSoftShadowMap = 2;
const VSMShadowMap = 3;
const FrontSide = 0;
const BackSide = 1;
const DoubleSide = 2;
const FlatShading = 1;
const SmoothShading = 2;
const NoBlending = 0;
const NormalBlending = 1;
const AdditiveBlending = 2;
const SubtractiveBlending = 3;
const MultiplyBlending = 4;
const CustomBlending = 5;
const AddEquation = 100;
const SubtractEquation = 101;
const ReverseSubtractEquation = 102;
const MinEquation = 103;
const MaxEquation = 104;
const ZeroFactor = 200;
const OneFactor = 201;
const SrcColorFactor = 202;
const OneMinusSrcColorFactor = 203;
const SrcAlphaFactor = 204;
const OneMinusSrcAlphaFactor = 205;
const DstAlphaFactor = 206;
const OneMinusDstAlphaFactor = 207;
const DstColorFactor = 208;
const OneMinusDstColorFactor = 209;
const SrcAlphaSaturateFactor = 210;
const NeverDepth = 0;
const AlwaysDepth = 1;
const LessDepth = 2;
const LessEqualDepth = 3;
const EqualDepth = 4;
const GreaterEqualDepth = 5;
const GreaterDepth = 6;
const NotEqualDepth = 7;
const MultiplyOperation = 0;
const MixOperation = 1;
const AddOperation = 2;
const NoToneMapping = 0;
const LinearToneMapping = 1;
const ReinhardToneMapping = 2;
const CineonToneMapping = 3;
const ACESFilmicToneMapping = 4;
const CustomToneMapping = 5;

const UVMapping = 300;
const CubeReflectionMapping = 301;
const CubeRefractionMapping = 302;
const EquirectangularReflectionMapping = 303;
const EquirectangularRefractionMapping = 304;
const CubeUVReflectionMapping = 306;
const CubeUVRefractionMapping = 307;
const RepeatWrapping = 1000;
const ClampToEdgeWrapping = 1001;
const MirroredRepeatWrapping = 1002;
const NearestFilter = 1003;
const NearestMipmapNearestFilter = 1004;
const NearestMipMapNearestFilter = 1004;
const NearestMipmapLinearFilter = 1005;
const NearestMipMapLinearFilter = 1005;
const LinearFilter = 1006;
const LinearMipmapNearestFilter = 1007;
const LinearMipMapNearestFilter = 1007;
const LinearMipmapLinearFilter = 1008;
const LinearMipMapLinearFilter = 1008;
const UnsignedByteType = 1009;
const ByteType = 1010;
const ShortType = 1011;
const UnsignedShortType = 1012;
const IntType = 1013;
const UnsignedIntType = 1014;
const FloatType = 1015;
const HalfFloatType = 1016;
const UnsignedShort4444Type = 1017;
const UnsignedShort5551Type = 1018;
const UnsignedShort565Type = 1019;
const UnsignedInt248Type = 1020;
const AlphaFormat = 1021;
const RGBFormat = 1022;
const RGBAFormat = 1023;
const LuminanceFormat = 1024;
const LuminanceAlphaFormat = 1025;
const RGBEFormat = RGBAFormat;
const DepthFormat = 1026;
const DepthStencilFormat = 1027;
const RedFormat = 1028;
const RedIntegerFormat = 1029;
const RGFormat = 1030;
const RGIntegerFormat = 1031;
const RGBIntegerFormat = 1032;
const RGBAIntegerFormat = 1033;

const RGB_S3TC_DXT1_Format = 33776;
const RGBA_S3TC_DXT1_Format = 33777;
const RGBA_S3TC_DXT3_Format = 33778;
const RGBA_S3TC_DXT5_Format = 33779;
const RGB_PVRTC_4BPPV1_Format = 35840;
const RGB_PVRTC_2BPPV1_Format = 35841;
const RGBA_PVRTC_4BPPV1_Format = 35842;
const RGBA_PVRTC_2BPPV1_Format = 35843;
const RGB_ETC1_Format = 36196;
const RGB_ETC2_Format = 37492;
const RGBA_ETC2_EAC_Format = 37496;
const RGBA_ASTC_4x4_Format = 37808;
const RGBA_ASTC_5x4_Format = 37809;
const RGBA_ASTC_5x5_Format = 37810;
const RGBA_ASTC_6x5_Format = 37811;
const RGBA_ASTC_6x6_Format = 37812;
const RGBA_ASTC_8x5_Format = 37813;
const RGBA_ASTC_8x6_Format = 37814;
const RGBA_ASTC_8x8_Format = 37815;
const RGBA_ASTC_10x5_Format = 37816;
const RGBA_ASTC_10x6_Format = 37817;
const RGBA_ASTC_10x8_Format = 37818;
const RGBA_ASTC_10x10_Format = 37819;
const RGBA_ASTC_12x10_Format = 37820;
const RGBA_ASTC_12x12_Format = 37821;
const RGBA_BPTC_Format = 36492;
const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
const LoopOnce = 2200;
const LoopRepeat = 2201;
const LoopPingPong = 2202;
const InterpolateDiscrete = 2300;
const InterpolateLinear = 2301;
const InterpolateSmooth = 2302;
const ZeroCurvatureEnding = 2400;
const ZeroSlopeEnding = 2401;
const WrapAroundEnding = 2402;
const NormalAnimationBlendMode = 2500;
const AdditiveAnimationBlendMode = 2501;
const TrianglesDrawMode = 0;
const TriangleStripDrawMode = 1;
const TriangleFanDrawMode = 2;
const LinearEncoding = 3000;
const sRGBEncoding = 3001;
const GammaEncoding = 3007;
const RGBEEncoding = 3002;
const LogLuvEncoding = 3003;
const RGBM7Encoding = 3004;
const RGBM16Encoding = 3005;
const RGBDEncoding = 3006;
const BasicDepthPacking = 3200;
const RGBADepthPacking = 3201;
const TangentSpaceNormalMap = 0;
const ObjectSpaceNormalMap = 1;

const ZeroStencilOp = 0;
const KeepStencilOp = 7680;
const ReplaceStencilOp = 7681;
const IncrementStencilOp = 7682;
const DecrementStencilOp = 7683;
const IncrementWrapStencilOp = 34055;
const DecrementWrapStencilOp = 34056;
const InvertStencilOp = 5386;

const NeverStencilFunc = 512;
const LessStencilFunc = 513;
const EqualStencilFunc = 514;
const LessEqualStencilFunc = 515;
const GreaterStencilFunc = 516;
const NotEqualStencilFunc = 517;
const GreaterEqualStencilFunc = 518;
const AlwaysStencilFunc = 519;

const StaticDrawUsage = 35044;
const DynamicDrawUsage = 35048;
const StreamDrawUsage = 35040;
const StaticReadUsage = 35045;
const DynamicReadUsage = 35049;
const StreamReadUsage = 35041;
const StaticCopyUsage = 35046;
const DynamicCopyUsage = 35050;
const StreamCopyUsage = 35042;

/**
 * https://github.com/mrdoob/eventdispatcher.js/
 */

function EventDispatcher() {}

Object.assign( EventDispatcher.prototype, {

	addEventListener: function ( type, listener ) {

		if ( this._listeners === undefined ) this._listeners = {};

		const listeners = this._listeners;

		if ( listeners[ type ] === undefined ) {

			listeners[ type ] = [];

		}

		if ( listeners[ type ].indexOf( listener ) === - 1 ) {

			listeners[ type ].push( listener );

		}

	},

	hasEventListener: function ( type, listener ) {

		if ( this._listeners === undefined ) return false;

		const listeners = this._listeners;

		return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;

	},

	removeEventListener: function ( type, listener ) {

		if ( this._listeners === undefined ) return;

		const listeners = this._listeners;
		const listenerArray = listeners[ type ];

		if ( listenerArray !== undefined ) {

			const index = listenerArray.indexOf( listener );

			if ( index !== - 1 ) {

				listenerArray.splice( index, 1 );

			}

		}

	},

	dispatchEvent: function ( event ) {

		if ( this._listeners === undefined ) return;

		const listeners = this._listeners;
		const listenerArray = listeners[ event.type ];

		if ( listenerArray !== undefined ) {

			event.target = this;

			// Make a copy, in case listeners are removed while iterating.
			const array = listenerArray.slice( 0 );

			for ( let i = 0, l = array.length; i < l; i ++ ) {

				array[ i ].call( this, event );

			}

		}

	}

} );

/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author thezwap
 */

const _lut = [];

for ( let i = 0; i < 256; i ++ ) {

	_lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );

}

const MathUtils = {

	DEG2RAD: Math.PI / 180,
	RAD2DEG: 180 / Math.PI,

	generateUUID: function () {

		// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136

		const d0 = Math.random() * 0xffffffff | 0;
		const d1 = Math.random() * 0xffffffff | 0;
		const d2 = Math.random() * 0xffffffff | 0;
		const d3 = Math.random() * 0xffffffff | 0;
		const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
			_lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
			_lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
			_lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];

		// .toUpperCase() here flattens concatenated strings to save heap memory space.
		return uuid.toUpperCase();

	},

	clamp: function ( value, min, max ) {

		return Math.max( min, Math.min( max, value ) );

	},

	// compute euclidian modulo of m % n
	// https://en.wikipedia.org/wiki/Modulo_operation

	euclideanModulo: function ( n, m ) {

		return ( ( n % m ) + m ) % m;

	},

	// Linear mapping from range <a1, a2> to range <b1, b2>

	mapLinear: function ( x, a1, a2, b1, b2 ) {

		return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );

	},

	// https://en.wikipedia.org/wiki/Linear_interpolation

	lerp: function ( x, y, t ) {

		return ( 1 - t ) * x + t * y;

	},

	// http://en.wikipedia.org/wiki/Smoothstep

	smoothstep: function ( x, min, max ) {

		if ( x <= min ) return 0;
		if ( x >= max ) return 1;

		x = ( x - min ) / ( max - min );

		return x * x * ( 3 - 2 * x );

	},

	smootherstep: function ( x, min, max ) {

		if ( x <= min ) return 0;
		if ( x >= max ) return 1;

		x = ( x - min ) / ( max - min );

		return x * x * x * ( x * ( x * 6 - 15 ) + 10 );

	},

	// Random integer from <low, high> interval

	randInt: function ( low, high ) {

		return low + Math.floor( Math.random() * ( high - low + 1 ) );

	},

	// Random float from <low, high> interval

	randFloat: function ( low, high ) {

		return low + Math.random() * ( high - low );

	},

	// Random float from <-range/2, range/2> interval

	randFloatSpread: function ( range ) {

		return range * ( 0.5 - Math.random() );

	},

	degToRad: function ( degrees ) {

		return degrees * MathUtils.DEG2RAD;

	},

	radToDeg: function ( radians ) {

		return radians * MathUtils.RAD2DEG;

	},

	isPowerOfTwo: function ( value ) {

		return ( value & ( value - 1 ) ) === 0 && value !== 0;

	},

	ceilPowerOfTwo: function ( value ) {

		return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );

	},

	floorPowerOfTwo: function ( value ) {

		return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );

	},

	setQuaternionFromProperEuler: function ( q, a, b, c, order ) {

		// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles

		// rotations are applied to the axes in the order specified by 'order'
		// rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
		// angles are in radians

		const cos = Math.cos;
		const sin = Math.sin;

		const c2 = cos( b / 2 );
		const s2 = sin( b / 2 );

		const c13 = cos( ( a + c ) / 2 );
		const s13 = sin( ( a + c ) / 2 );

		const c1_3 = cos( ( a - c ) / 2 );
		const s1_3 = sin( ( a - c ) / 2 );

		const c3_1 = cos( ( c - a ) / 2 );
		const s3_1 = sin( ( c - a ) / 2 );

		switch ( order ) {

			case 'XYX':
				q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
				break;

			case 'YZY':
				q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
				break;

			case 'ZXZ':
				q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
				break;

			case 'XZX':
				q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
				break;

			case 'YXY':
				q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
				break;

			case 'ZYZ':
				q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
				break;

			default:
				console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );

		}

	}

};

/**
 * @author mrdoob / http://mrdoob.com/
 * @author philogb / http://blog.thejit.org/
 * @author egraether / http://egraether.com/
 * @author zz85 / http://www.lab4games.net/zz85/blog
 */

function Vector2( x = 0, y = 0 ) {

	this.x = x;
	this.y = y;

}

Object.defineProperties( Vector2.prototype, {

	"width": {

		get: function () {

			return this.x;

		},

		set: function ( value ) {

			this.x = value;

		}

	},

	"height": {

		get: function () {

			return this.y;

		},

		set: function ( value ) {

			this.y = value;

		}

	}

} );

Object.assign( Vector2.prototype, {

	isVector2: true,

	set: function ( x, y ) {

		this.x = x;
		this.y = y;

		return this;

	},

	setScalar: function ( scalar ) {

		this.x = scalar;
		this.y = scalar;

		return this;

	},

	setX: function ( x ) {

		this.x = x;

		return this;

	},

	setY: function ( y ) {

		this.y = y;

		return this;

	},

	setComponent: function ( index, value ) {

		switch ( index ) {

			case 0: this.x = value; break;
			case 1: this.y = value; break;
			default: throw new Error( 'index is out of range: ' + index );

		}

		return this;

	},

	getComponent: function ( index ) {

		switch ( index ) {

			case 0: return this.x;
			case 1: return this.y;
			default: throw new Error( 'index is out of range: ' + index );

		}

	},

	clone: function () {

		return new this.constructor( this.x, this.y );

	},

	copy: function ( v ) {

		this.x = v.x;
		this.y = v.y;

		return this;

	},

	add: function ( v, w ) {

		if ( w !== undefined ) {

			console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
			return this.addVectors( v, w );

		}

		this.x += v.x;
		this.y += v.y;

		return this;

	},

	addScalar: function ( s ) {

		this.x += s;
		this.y += s;

		return this;

	},

	addVectors: function ( a, b ) {

		this.x = a.x + b.x;
		this.y = a.y + b.y;

		return this;

	},

	addScaledVector: function ( v, s ) {

		this.x += v.x * s;
		this.y += v.y * s;

		return this;

	},

	sub: function ( v, w ) {

		if ( w !== undefined ) {

			console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
			return this.subVectors( v, w );

		}

		this.x -= v.x;
		this.y -= v.y;

		return this;

	},

	subScalar: function ( s ) {

		this.x -= s;
		this.y -= s;

		return this;

	},

	subVectors: function ( a, b ) {

		this.x = a.x - b.x;
		this.y = a.y - b.y;

		return this;

	},

	multiply: function ( v ) {

		this.x *= v.x;
		this.y *= v.y;

		return this;

	},

	multiplyScalar: function ( scalar ) {

		this.x *= scalar;
		this.y *= scalar;

		return this;

	},

	divide: function ( v ) {

		this.x /= v.x;
		this.y /= v.y;

		return this;

	},

	divideScalar: function ( scalar ) {

		return this.multiplyScalar( 1 / scalar );

	},

	applyMatrix3: function ( m ) {

		const x = this.x, y = this.y;
		const e = m.elements;

		this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
		this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];

		return this;

	},

	min: function ( v ) {

		this.x = Math.min( this.x, v.x );
		this.y = Math.min( this.y, v.y );

		return this;

	},

	max: function ( v ) {

		this.x = Math.max( this.x, v.x );
		this.y = Math.max( this.y, v.y );

		return this;

	},

	clamp: function ( min, max ) {

		// assumes min < max, componentwise

		this.x = Math.max( min.x, Math.min( max.x, this.x ) );
		this.y = Math.max( min.y, Math.min( max.y, this.y ) );

		return this;

	},

	clampScalar: function ( minVal, maxVal ) {

		this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
		this.y = Math.max( minVal, Math.min( maxVal, this.y ) );

		return this;

	},

	clampLength: function ( min, max ) {

		const length = this.length();

		return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );

	},

	floor: function () {

		this.x = Math.floor( this.x );
		this.y = Math.floor( this.y );

		return this;

	},

	ceil: function () {

		this.x = Math.ceil( this.x );
		this.y = Math.ceil( this.y );

		return this;

	},

	round: function () {

		this.x = Math.round( this.x );
		this.y = Math.round( this.y );

		return this;

	},

	roundToZero: function () {

		this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
		this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );

		return this;

	},

	negate: function () {

		this.x = - this.x;
		this.y = - this.y;

		return this;

	},

	dot: function ( v ) {

		return this.x * v.x + this.y * v.y;

	},

	cross: function ( v ) {

		return this.x * v.y - this.y * v.x;

	},

	lengthSq: function () {

		return this.x * this.x + this.y * this.y;

	},

	length: function () {

		return Math.sqrt( this.x * this.x + this.y * this.y );

	},

	manhattanLength: function () {

		return Math.abs( this.x ) + Math.abs( this.y );

	},

	normalize: function () {

		return this.divideScalar( this.length() || 1 );

	},

	angle: function () {

		// computes the angle in radians with respect to the positive x-axis

		const angle = Math.atan2( - this.y, - this.x ) + Math.PI;

		return angle;

	},

	distanceTo: function ( v ) {

		return Math.sqrt( this.distanceToSquared( v ) );

	},

	distanceToSquared: function ( v ) {

		const dx = this.x - v.x, dy = this.y - v.y;
		return dx * dx + dy * dy;

	},

	manhattanDistanceTo: function ( v ) {

		return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );

	},

	setLength: function ( length ) {

		return this.normalize().multiplyScalar( length );

	},

	lerp: function ( v, alpha ) {

		this.x += ( v.x - this.x ) * alpha;
		this.y += ( v.y - this.y ) * alpha;

		return this;

	},

	lerpVectors: function ( v1, v2, alpha ) {

		this.x = v1.x + ( v2.x - v1.x ) * alpha;
		this.y = v1.y + ( v2.y - v1.y ) * alpha;

		return this;

	},

	equals: function ( v ) {

		return ( ( v.x === this.x ) && ( v.y === this.y ) );

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		this.x = array[ offset ];
		this.y = array[ offset + 1 ];

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		array[ offset ] = this.x;
		array[ offset + 1 ] = this.y;

		return array;

	},

	fromBufferAttribute: function ( attribute, index, offset ) {

		if ( offset !== undefined ) {

			console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );

		}

		this.x = attribute.getX( index );
		this.y = attribute.getY( index );

		return this;

	},

	rotateAround: function ( center, angle ) {

		const c = Math.cos( angle ), s = Math.sin( angle );

		const x = this.x - center.x;
		const y = this.y - center.y;

		this.x = x * c - y * s + center.x;
		this.y = x * s + y * c + center.y;

		return this;

	},

	random: function () {

		this.x = Math.random();
		this.y = Math.random();

		return this;

	}

} );

/**
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author bhouston / http://clara.io
 * @author tschw
 */

function Matrix3() {

	this.elements = [

		1, 0, 0,
		0, 1, 0,
		0, 0, 1

	];

	if ( arguments.length > 0 ) {

		console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );

	}

}

Object.assign( Matrix3.prototype, {

	isMatrix3: true,

	set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {

		const te = this.elements;

		te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
		te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
		te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;

		return this;

	},

	identity: function () {

		this.set(

			1, 0, 0,
			0, 1, 0,
			0, 0, 1

		);

		return this;

	},

	clone: function () {

		return new this.constructor().fromArray( this.elements );

	},

	copy: function ( m ) {

		const te = this.elements;
		const me = m.elements;

		te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
		te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
		te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];

		return this;

	},

	extractBasis: function ( xAxis, yAxis, zAxis ) {

		xAxis.setFromMatrix3Column( this, 0 );
		yAxis.setFromMatrix3Column( this, 1 );
		zAxis.setFromMatrix3Column( this, 2 );

		return this;

	},

	setFromMatrix4: function ( m ) {

		const me = m.elements;

		this.set(

			me[ 0 ], me[ 4 ], me[ 8 ],
			me[ 1 ], me[ 5 ], me[ 9 ],
			me[ 2 ], me[ 6 ], me[ 10 ]

		);

		return this;

	},

	multiply: function ( m ) {

		return this.multiplyMatrices( this, m );

	},

	premultiply: function ( m ) {

		return this.multiplyMatrices( m, this );

	},

	multiplyMatrices: function ( a, b ) {

		const ae = a.elements;
		const be = b.elements;
		const te = this.elements;

		const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
		const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
		const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];

		const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
		const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
		const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];

		te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
		te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
		te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;

		te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
		te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
		te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;

		te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
		te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
		te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;

		return this;

	},

	multiplyScalar: function ( s ) {

		const te = this.elements;

		te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
		te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
		te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;

		return this;

	},

	determinant: function () {

		const te = this.elements;

		const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
			d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
			g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];

		return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;

	},

	getInverse: function ( matrix, throwOnDegenerate ) {

		if ( throwOnDegenerate !== undefined ) {

			console.warn( "THREE.Matrix3: .getInverse() can no longer be configured to throw on degenerate." );

		}

		const me = matrix.elements,
			te = this.elements,

			n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
			n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
			n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],

			t11 = n33 * n22 - n32 * n23,
			t12 = n32 * n13 - n33 * n12,
			t13 = n23 * n12 - n22 * n13,

			det = n11 * t11 + n21 * t12 + n31 * t13;

		if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );

		const detInv = 1 / det;

		te[ 0 ] = t11 * detInv;
		te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
		te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;

		te[ 3 ] = t12 * detInv;
		te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
		te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;

		te[ 6 ] = t13 * detInv;
		te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
		te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;

		return this;

	},

	transpose: function () {

		let tmp;
		const m = this.elements;

		tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
		tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
		tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;

		return this;

	},

	getNormalMatrix: function ( matrix4 ) {

		return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();

	},

	transposeIntoArray: function ( r ) {

		const m = this.elements;

		r[ 0 ] = m[ 0 ];
		r[ 1 ] = m[ 3 ];
		r[ 2 ] = m[ 6 ];
		r[ 3 ] = m[ 1 ];
		r[ 4 ] = m[ 4 ];
		r[ 5 ] = m[ 7 ];
		r[ 6 ] = m[ 2 ];
		r[ 7 ] = m[ 5 ];
		r[ 8 ] = m[ 8 ];

		return this;

	},

	setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {

		const c = Math.cos( rotation );
		const s = Math.sin( rotation );

		this.set(
			sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
			- sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
			0, 0, 1
		);

	},

	scale: function ( sx, sy ) {

		const te = this.elements;

		te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
		te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;

		return this;

	},

	rotate: function ( theta ) {

		const c = Math.cos( theta );
		const s = Math.sin( theta );

		const te = this.elements;

		const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
		const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];

		te[ 0 ] = c * a11 + s * a21;
		te[ 3 ] = c * a12 + s * a22;
		te[ 6 ] = c * a13 + s * a23;

		te[ 1 ] = - s * a11 + c * a21;
		te[ 4 ] = - s * a12 + c * a22;
		te[ 7 ] = - s * a13 + c * a23;

		return this;

	},

	translate: function ( tx, ty ) {

		const te = this.elements;

		te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
		te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];

		return this;

	},

	equals: function ( matrix ) {

		const te = this.elements;
		const me = matrix.elements;

		for ( let i = 0; i < 9; i ++ ) {

			if ( te[ i ] !== me[ i ] ) return false;

		}

		return true;

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		for ( let i = 0; i < 9; i ++ ) {

			this.elements[ i ] = array[ i + offset ];

		}

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		const te = this.elements;

		array[ offset ] = te[ 0 ];
		array[ offset + 1 ] = te[ 1 ];
		array[ offset + 2 ] = te[ 2 ];

		array[ offset + 3 ] = te[ 3 ];
		array[ offset + 4 ] = te[ 4 ];
		array[ offset + 5 ] = te[ 5 ];

		array[ offset + 6 ] = te[ 6 ];
		array[ offset + 7 ] = te[ 7 ];
		array[ offset + 8 ] = te[ 8 ];

		return array;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author szimek / https://github.com/szimek/
 */

let _canvas;

const ImageUtils = {

	getDataURL: function ( image ) {

		if ( /^data:/i.test( image.src ) ) {

			return image.src;

		}

		if ( typeof HTMLCanvasElement == 'undefined' ) {

			return image.src;

		}

		let canvas;

		if ( image instanceof HTMLCanvasElement ) {

			canvas = image;

		} else {

			if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );

			_canvas.width = image.width;
			_canvas.height = image.height;

			const context = _canvas.getContext( '2d' );

			if ( image instanceof ImageData ) {

				context.putImageData( image, 0, 0 );

			} else {

				context.drawImage( image, 0, 0, image.width, image.height );

			}

			canvas = _canvas;

		}

		if ( canvas.width > 2048 || canvas.height > 2048 ) {

			return canvas.toDataURL( 'image/jpeg', 0.6 );

		} else {

			return canvas.toDataURL( 'image/png' );

		}

	}

};

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author szimek / https://github.com/szimek/
 */

let textureId = 0;

function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {

	Object.defineProperty( this, 'id', { value: textureId ++ } );

	this.uuid = MathUtils.generateUUID();

	this.name = '';

	this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
	this.mipmaps = [];

	this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;

	this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
	this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;

	this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
	this.minFilter = minFilter !== undefined ? minFilter : LinearMipmapLinearFilter;

	this.anisotropy = anisotropy !== undefined ? anisotropy : 1;

	this.format = format !== undefined ? format : RGBAFormat;
	this.internalFormat = null;
	this.type = type !== undefined ? type : UnsignedByteType;

	this.offset = new Vector2( 0, 0 );
	this.repeat = new Vector2( 1, 1 );
	this.center = new Vector2( 0, 0 );
	this.rotation = 0;

	this.matrixAutoUpdate = true;
	this.matrix = new Matrix3();

	this.generateMipmaps = true;
	this.premultiplyAlpha = false;
	this.flipY = true;
	this.unpackAlignment = 4;	// valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)

	// Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
	//
	// Also changing the encoding after already used by a Material will not automatically make the Material
	// update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
	this.encoding = encoding !== undefined ? encoding : LinearEncoding;

	this.version = 0;
	this.onUpdate = null;

}

Texture.DEFAULT_IMAGE = undefined;
Texture.DEFAULT_MAPPING = UVMapping;

Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

	constructor: Texture,

	isTexture: true,

	updateMatrix: function () {

		this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( source ) {

		this.name = source.name;

		this.image = source.image;
		this.mipmaps = source.mipmaps.slice( 0 );

		this.mapping = source.mapping;

		this.wrapS = source.wrapS;
		this.wrapT = source.wrapT;

		this.magFilter = source.magFilter;
		this.minFilter = source.minFilter;

		this.anisotropy = source.anisotropy;

		this.format = source.format;
		this.internalFormat = source.internalFormat;
		this.type = source.type;

		this.offset.copy( source.offset );
		this.repeat.copy( source.repeat );
		this.center.copy( source.center );
		this.rotation = source.rotation;

		this.matrixAutoUpdate = source.matrixAutoUpdate;
		this.matrix.copy( source.matrix );

		this.generateMipmaps = source.generateMipmaps;
		this.premultiplyAlpha = source.premultiplyAlpha;
		this.flipY = source.flipY;
		this.unpackAlignment = source.unpackAlignment;
		this.encoding = source.encoding;

		return this;

	},

	toJSON: function ( meta ) {

		const isRootObject = ( meta === undefined || typeof meta === 'string' );

		if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {

			return meta.textures[ this.uuid ];

		}

		const output = {

			metadata: {
				version: 4.5,
				type: 'Texture',
				generator: 'Texture.toJSON'
			},

			uuid: this.uuid,
			name: this.name,

			mapping: this.mapping,

			repeat: [ this.repeat.x, this.repeat.y ],
			offset: [ this.offset.x, this.offset.y ],
			center: [ this.center.x, this.center.y ],
			rotation: this.rotation,

			wrap: [ this.wrapS, this.wrapT ],

			format: this.format,
			type: this.type,
			encoding: this.encoding,

			minFilter: this.minFilter,
			magFilter: this.magFilter,
			anisotropy: this.anisotropy,

			flipY: this.flipY,

			premultiplyAlpha: this.premultiplyAlpha,
			unpackAlignment: this.unpackAlignment

		};

		if ( this.image !== undefined ) {

			// TODO: Move to THREE.Image

			const image = this.image;

			if ( image.uuid === undefined ) {

				image.uuid = MathUtils.generateUUID(); // UGH

			}

			if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {

				let url;

				if ( Array.isArray( image ) ) {

					// process array of images e.g. CubeTexture

					url = [];

					for ( let i = 0, l = image.length; i < l; i ++ ) {

						url.push( ImageUtils.getDataURL( image[ i ] ) );

					}

				} else {

					// process single image

					url = ImageUtils.getDataURL( image );

				}

				meta.images[ image.uuid ] = {
					uuid: image.uuid,
					url: url
				};

			}

			output.image = image.uuid;

		}

		if ( ! isRootObject ) {

			meta.textures[ this.uuid ] = output;

		}

		return output;

	},

	dispose: function () {

		this.dispatchEvent( { type: 'dispose' } );

	},

	transformUv: function ( uv ) {

		if ( this.mapping !== UVMapping ) return uv;

		uv.applyMatrix3( this.matrix );

		if ( uv.x < 0 || uv.x > 1 ) {

			switch ( this.wrapS ) {

				case RepeatWrapping:

					uv.x = uv.x - Math.floor( uv.x );
					break;

				case ClampToEdgeWrapping:

					uv.x = uv.x < 0 ? 0 : 1;
					break;

				case MirroredRepeatWrapping:

					if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {

						uv.x = Math.ceil( uv.x ) - uv.x;

					} else {

						uv.x = uv.x - Math.floor( uv.x );

					}

					break;

			}

		}

		if ( uv.y < 0 || uv.y > 1 ) {

			switch ( this.wrapT ) {

				case RepeatWrapping:

					uv.y = uv.y - Math.floor( uv.y );
					break;

				case ClampToEdgeWrapping:

					uv.y = uv.y < 0 ? 0 : 1;
					break;

				case MirroredRepeatWrapping:

					if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {

						uv.y = Math.ceil( uv.y ) - uv.y;

					} else {

						uv.y = uv.y - Math.floor( uv.y );

					}

					break;

			}

		}

		if ( this.flipY ) {

			uv.y = 1 - uv.y;

		}

		return uv;

	}

} );

Object.defineProperty( Texture.prototype, "needsUpdate", {

	set: function ( value ) {

		if ( value === true ) this.version ++;

	}

} );

/**
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author philogb / http://blog.thejit.org/
 * @author mikael emtinger / http://gomo.se/
 * @author egraether / http://egraether.com/
 * @author WestLangley / http://github.com/WestLangley
 */

function Vector4( x = 0, y = 0, z = 0, w = 1 ) {

	this.x = x;
	this.y = y;
	this.z = z;
	this.w = w;

}

Object.defineProperties( Vector4.prototype, {

	"width": {

		get: function () {

			return this.z;

		},

		set: function ( value ) {

			this.z = value;

		}

	},

	"height": {

		get: function () {

			return this.w;

		},

		set: function ( value ) {

			this.w = value;

		}

	}

} );

Object.assign( Vector4.prototype, {

	isVector4: true,

	set: function ( x, y, z, w ) {

		this.x = x;
		this.y = y;
		this.z = z;
		this.w = w;

		return this;

	},

	setScalar: function ( scalar ) {

		this.x = scalar;
		this.y = scalar;
		this.z = scalar;
		this.w = scalar;

		return this;

	},

	setX: function ( x ) {

		this.x = x;

		return this;

	},

	setY: function ( y ) {

		this.y = y;

		return this;

	},

	setZ: function ( z ) {

		this.z = z;

		return this;

	},

	setW: function ( w ) {

		this.w = w;

		return this;

	},

	setComponent: function ( index, value ) {

		switch ( index ) {

			case 0: this.x = value; break;
			case 1: this.y = value; break;
			case 2: this.z = value; break;
			case 3: this.w = value; break;
			default: throw new Error( 'index is out of range: ' + index );

		}

		return this;

	},

	getComponent: function ( index ) {

		switch ( index ) {

			case 0: return this.x;
			case 1: return this.y;
			case 2: return this.z;
			case 3: return this.w;
			default: throw new Error( 'index is out of range: ' + index );

		}

	},

	clone: function () {

		return new this.constructor( this.x, this.y, this.z, this.w );

	},

	copy: function ( v ) {

		this.x = v.x;
		this.y = v.y;
		this.z = v.z;
		this.w = ( v.w !== undefined ) ? v.w : 1;

		return this;

	},

	add: function ( v, w ) {

		if ( w !== undefined ) {

			console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
			return this.addVectors( v, w );

		}

		this.x += v.x;
		this.y += v.y;
		this.z += v.z;
		this.w += v.w;

		return this;

	},

	addScalar: function ( s ) {

		this.x += s;
		this.y += s;
		this.z += s;
		this.w += s;

		return this;

	},

	addVectors: function ( a, b ) {

		this.x = a.x + b.x;
		this.y = a.y + b.y;
		this.z = a.z + b.z;
		this.w = a.w + b.w;

		return this;

	},

	addScaledVector: function ( v, s ) {

		this.x += v.x * s;
		this.y += v.y * s;
		this.z += v.z * s;
		this.w += v.w * s;

		return this;

	},

	sub: function ( v, w ) {

		if ( w !== undefined ) {

			console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
			return this.subVectors( v, w );

		}

		this.x -= v.x;
		this.y -= v.y;
		this.z -= v.z;
		this.w -= v.w;

		return this;

	},

	subScalar: function ( s ) {

		this.x -= s;
		this.y -= s;
		this.z -= s;
		this.w -= s;

		return this;

	},

	subVectors: function ( a, b ) {

		this.x = a.x - b.x;
		this.y = a.y - b.y;
		this.z = a.z - b.z;
		this.w = a.w - b.w;

		return this;

	},

	multiplyScalar: function ( scalar ) {

		this.x *= scalar;
		this.y *= scalar;
		this.z *= scalar;
		this.w *= scalar;

		return this;

	},

	applyMatrix4: function ( m ) {

		const x = this.x, y = this.y, z = this.z, w = this.w;
		const e = m.elements;

		this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
		this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
		this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
		this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;

		return this;

	},

	divideScalar: function ( scalar ) {

		return this.multiplyScalar( 1 / scalar );

	},

	setAxisAngleFromQuaternion: function ( q ) {

		// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm

		// q is assumed to be normalized

		this.w = 2 * Math.acos( q.w );

		const s = Math.sqrt( 1 - q.w * q.w );

		if ( s < 0.0001 ) {

			this.x = 1;
			this.y = 0;
			this.z = 0;

		} else {

			this.x = q.x / s;
			this.y = q.y / s;
			this.z = q.z / s;

		}

		return this;

	},

	setAxisAngleFromRotationMatrix: function ( m ) {

		// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm

		// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

		let angle, x, y, z; // variables for result
		const epsilon = 0.01,		// margin to allow for rounding errors
			epsilon2 = 0.1,		// margin to distinguish between 0 and 180 degrees

			te = m.elements,

			m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
			m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
			m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];

		if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
		     ( Math.abs( m13 - m31 ) < epsilon ) &&
		     ( Math.abs( m23 - m32 ) < epsilon ) ) {

			// singularity found
			// first check for identity matrix which must have +1 for all terms
			// in leading diagonal and zero in other terms

			if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
			     ( Math.abs( m13 + m31 ) < epsilon2 ) &&
			     ( Math.abs( m23 + m32 ) < epsilon2 ) &&
			     ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {

				// this singularity is identity matrix so angle = 0

				this.set( 1, 0, 0, 0 );

				return this; // zero angle, arbitrary axis

			}

			// otherwise this singularity is angle = 180

			angle = Math.PI;

			const xx = ( m11 + 1 ) / 2;
			const yy = ( m22 + 1 ) / 2;
			const zz = ( m33 + 1 ) / 2;
			const xy = ( m12 + m21 ) / 4;
			const xz = ( m13 + m31 ) / 4;
			const yz = ( m23 + m32 ) / 4;

			if ( ( xx > yy ) && ( xx > zz ) ) {

				// m11 is the largest diagonal term

				if ( xx < epsilon ) {

					x = 0;
					y = 0.707106781;
					z = 0.707106781;

				} else {

					x = Math.sqrt( xx );
					y = xy / x;
					z = xz / x;

				}

			} else if ( yy > zz ) {

				// m22 is the largest diagonal term

				if ( yy < epsilon ) {

					x = 0.707106781;
					y = 0;
					z = 0.707106781;

				} else {

					y = Math.sqrt( yy );
					x = xy / y;
					z = yz / y;

				}

			} else {

				// m33 is the largest diagonal term so base result on this

				if ( zz < epsilon ) {

					x = 0.707106781;
					y = 0.707106781;
					z = 0;

				} else {

					z = Math.sqrt( zz );
					x = xz / z;
					y = yz / z;

				}

			}

			this.set( x, y, z, angle );

			return this; // return 180 deg rotation

		}

		// as we have reached here there are no singularities so we can handle normally

		let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
			( m13 - m31 ) * ( m13 - m31 ) +
			( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize

		if ( Math.abs( s ) < 0.001 ) s = 1;

		// prevent divide by zero, should not happen if matrix is orthogonal and should be
		// caught by singularity test above, but I've left it in just in case

		this.x = ( m32 - m23 ) / s;
		this.y = ( m13 - m31 ) / s;
		this.z = ( m21 - m12 ) / s;
		this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );

		return this;

	},

	min: function ( v ) {

		this.x = Math.min( this.x, v.x );
		this.y = Math.min( this.y, v.y );
		this.z = Math.min( this.z, v.z );
		this.w = Math.min( this.w, v.w );

		return this;

	},

	max: function ( v ) {

		this.x = Math.max( this.x, v.x );
		this.y = Math.max( this.y, v.y );
		this.z = Math.max( this.z, v.z );
		this.w = Math.max( this.w, v.w );

		return this;

	},

	clamp: function ( min, max ) {

		// assumes min < max, componentwise

		this.x = Math.max( min.x, Math.min( max.x, this.x ) );
		this.y = Math.max( min.y, Math.min( max.y, this.y ) );
		this.z = Math.max( min.z, Math.min( max.z, this.z ) );
		this.w = Math.max( min.w, Math.min( max.w, this.w ) );

		return this;

	},

	clampScalar: function ( minVal, maxVal ) {

		this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
		this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
		this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
		this.w = Math.max( minVal, Math.min( maxVal, this.w ) );

		return this;

	},

	clampLength: function ( min, max ) {

		const length = this.length();

		return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );

	},

	floor: function () {

		this.x = Math.floor( this.x );
		this.y = Math.floor( this.y );
		this.z = Math.floor( this.z );
		this.w = Math.floor( this.w );

		return this;

	},

	ceil: function () {

		this.x = Math.ceil( this.x );
		this.y = Math.ceil( this.y );
		this.z = Math.ceil( this.z );
		this.w = Math.ceil( this.w );

		return this;

	},

	round: function () {

		this.x = Math.round( this.x );
		this.y = Math.round( this.y );
		this.z = Math.round( this.z );
		this.w = Math.round( this.w );

		return this;

	},

	roundToZero: function () {

		this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
		this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
		this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
		this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );

		return this;

	},

	negate: function () {

		this.x = - this.x;
		this.y = - this.y;
		this.z = - this.z;
		this.w = - this.w;

		return this;

	},

	dot: function ( v ) {

		return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;

	},

	lengthSq: function () {

		return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;

	},

	length: function () {

		return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );

	},

	manhattanLength: function () {

		return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );

	},

	normalize: function () {

		return this.divideScalar( this.length() || 1 );

	},

	setLength: function ( length ) {

		return this.normalize().multiplyScalar( length );

	},

	lerp: function ( v, alpha ) {

		this.x += ( v.x - this.x ) * alpha;
		this.y += ( v.y - this.y ) * alpha;
		this.z += ( v.z - this.z ) * alpha;
		this.w += ( v.w - this.w ) * alpha;

		return this;

	},

	lerpVectors: function ( v1, v2, alpha ) {

		this.x = v1.x + ( v2.x - v1.x ) * alpha;
		this.y = v1.y + ( v2.y - v1.y ) * alpha;
		this.z = v1.z + ( v2.z - v1.z ) * alpha;
		this.w = v1.w + ( v2.w - v1.w ) * alpha;

		return this;

	},

	equals: function ( v ) {

		return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		this.x = array[ offset ];
		this.y = array[ offset + 1 ];
		this.z = array[ offset + 2 ];
		this.w = array[ offset + 3 ];

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		array[ offset ] = this.x;
		array[ offset + 1 ] = this.y;
		array[ offset + 2 ] = this.z;
		array[ offset + 3 ] = this.w;

		return array;

	},

	fromBufferAttribute: function ( attribute, index, offset ) {

		if ( offset !== undefined ) {

			console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );

		}

		this.x = attribute.getX( index );
		this.y = attribute.getY( index );
		this.z = attribute.getZ( index );
		this.w = attribute.getW( index );

		return this;

	},

	random: function () {

		this.x = Math.random();
		this.y = Math.random();
		this.z = Math.random();
		this.w = Math.random();

		return this;

	}

} );

/**
 * @author szimek / https://github.com/szimek/
 * @author alteredq / http://alteredqualia.com/
 * @author Marius Kintel / https://github.com/kintel
 */

/*
 In options, we can specify:
 * Texture parameters for an auto-generated target texture
 * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
*/
function WebGLRenderTarget( width, height, options ) {

	this.width = width;
	this.height = height;

	this.scissor = new Vector4( 0, 0, width, height );
	this.scissorTest = false;

	this.viewport = new Vector4( 0, 0, width, height );

	options = options || {};

	this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );

	this.texture.image = {};
	this.texture.image.width = width;
	this.texture.image.height = height;

	this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
	this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;

	this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
	this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
	this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;

}

WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

	constructor: WebGLRenderTarget,

	isWebGLRenderTarget: true,

	setSize: function ( width, height ) {

		if ( this.width !== width || this.height !== height ) {

			this.width = width;
			this.height = height;

			this.texture.image.width = width;
			this.texture.image.height = height;

			this.dispose();

		}

		this.viewport.set( 0, 0, width, height );
		this.scissor.set( 0, 0, width, height );

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( source ) {

		this.width = source.width;
		this.height = source.height;

		this.viewport.copy( source.viewport );

		this.texture = source.texture.clone();

		this.depthBuffer = source.depthBuffer;
		this.stencilBuffer = source.stencilBuffer;
		this.depthTexture = source.depthTexture;

		return this;

	},

	dispose: function () {

		this.dispatchEvent( { type: 'dispose' } );

	}

} );

/**
 * @author Mugen87 / https://github.com/Mugen87
 * @author Matt DesLauriers / @mattdesl
 */

function WebGLMultisampleRenderTarget( width, height, options ) {

	WebGLRenderTarget.call( this, width, height, options );

	this.samples = 4;

}

WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {

	constructor: WebGLMultisampleRenderTarget,

	isWebGLMultisampleRenderTarget: true,

	copy: function ( source ) {

		WebGLRenderTarget.prototype.copy.call( this, source );

		this.samples = source.samples;

		return this;

	}

} );

/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author bhouston / http://clara.io
 */

function Quaternion( x = 0, y = 0, z = 0, w = 1 ) {

	this._x = x;
	this._y = y;
	this._z = z;
	this._w = w;

}

Object.assign( Quaternion, {

	slerp: function ( qa, qb, qm, t ) {

		return qm.copy( qa ).slerp( qb, t );

	},

	slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {

		// fuzz-free, array-based Quaternion SLERP operation

		let x0 = src0[ srcOffset0 + 0 ],
			y0 = src0[ srcOffset0 + 1 ],
			z0 = src0[ srcOffset0 + 2 ],
			w0 = src0[ srcOffset0 + 3 ];

		const x1 = src1[ srcOffset1 + 0 ],
			y1 = src1[ srcOffset1 + 1 ],
			z1 = src1[ srcOffset1 + 2 ],
			w1 = src1[ srcOffset1 + 3 ];

		if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {

			let s = 1 - t,

				cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,

				dir = ( cos >= 0 ? 1 : - 1 ),
				sqrSin = 1 - cos * cos;

			// Skip the Slerp for tiny steps to avoid numeric problems:
			if ( sqrSin > Number.EPSILON ) {

				const sin = Math.sqrt( sqrSin ),
					len = Math.atan2( sin, cos * dir );

				s = Math.sin( s * len ) / sin;
				t = Math.sin( t * len ) / sin;

			}

			const tDir = t * dir;

			x0 = x0 * s + x1 * tDir;
			y0 = y0 * s + y1 * tDir;
			z0 = z0 * s + z1 * tDir;
			w0 = w0 * s + w1 * tDir;

			// Normalize in case we just did a lerp:
			if ( s === 1 - t ) {

				const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );

				x0 *= f;
				y0 *= f;
				z0 *= f;
				w0 *= f;

			}

		}

		dst[ dstOffset ] = x0;
		dst[ dstOffset + 1 ] = y0;
		dst[ dstOffset + 2 ] = z0;
		dst[ dstOffset + 3 ] = w0;

	},

	multiplyQuaternionsFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {

		const x0 = src0[ srcOffset0 ];
		const y0 = src0[ srcOffset0 + 1 ];
		const z0 = src0[ srcOffset0 + 2 ];
		const w0 = src0[ srcOffset0 + 3 ];

		const x1 = src1[ srcOffset1 ];
		const y1 = src1[ srcOffset1 + 1 ];
		const z1 = src1[ srcOffset1 + 2 ];
		const w1 = src1[ srcOffset1 + 3 ];

		dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
		dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
		dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
		dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;

		return dst;

	}

} );

Object.defineProperties( Quaternion.prototype, {

	x: {

		get: function () {

			return this._x;

		},

		set: function ( value ) {

			this._x = value;
			this._onChangeCallback();

		}

	},

	y: {

		get: function () {

			return this._y;

		},

		set: function ( value ) {

			this._y = value;
			this._onChangeCallback();

		}

	},

	z: {

		get: function () {

			return this._z;

		},

		set: function ( value ) {

			this._z = value;
			this._onChangeCallback();

		}

	},

	w: {

		get: function () {

			return this._w;

		},

		set: function ( value ) {

			this._w = value;
			this._onChangeCallback();

		}

	}

} );

Object.assign( Quaternion.prototype, {

	isQuaternion: true,

	set: function ( x, y, z, w ) {

		this._x = x;
		this._y = y;
		this._z = z;
		this._w = w;

		this._onChangeCallback();

		return this;

	},

	clone: function () {

		return new this.constructor( this._x, this._y, this._z, this._w );

	},

	copy: function ( quaternion ) {

		this._x = quaternion.x;
		this._y = quaternion.y;
		this._z = quaternion.z;
		this._w = quaternion.w;

		this._onChangeCallback();

		return this;

	},

	setFromEuler: function ( euler, update ) {

		if ( ! ( euler && euler.isEuler ) ) {

			throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );

		}

		const x = euler._x, y = euler._y, z = euler._z, order = euler.order;

		// http://www.mathworks.com/matlabcentral/fileexchange/
		// 	20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
		//	content/SpinCalc.m

		const cos = Math.cos;
		const sin = Math.sin;

		const c1 = cos( x / 2 );
		const c2 = cos( y / 2 );
		const c3 = cos( z / 2 );

		const s1 = sin( x / 2 );
		const s2 = sin( y / 2 );
		const s3 = sin( z / 2 );

		switch ( order ) {

			case 'XYZ':
				this._x = s1 * c2 * c3 + c1 * s2 * s3;
				this._y = c1 * s2 * c3 - s1 * c2 * s3;
				this._z = c1 * c2 * s3 + s1 * s2 * c3;
				this._w = c1 * c2 * c3 - s1 * s2 * s3;
				break;

			case 'YXZ':
				this._x = s1 * c2 * c3 + c1 * s2 * s3;
				this._y = c1 * s2 * c3 - s1 * c2 * s3;
				this._z = c1 * c2 * s3 - s1 * s2 * c3;
				this._w = c1 * c2 * c3 + s1 * s2 * s3;
				break;

			case 'ZXY':
				this._x = s1 * c2 * c3 - c1 * s2 * s3;
				this._y = c1 * s2 * c3 + s1 * c2 * s3;
				this._z = c1 * c2 * s3 + s1 * s2 * c3;
				this._w = c1 * c2 * c3 - s1 * s2 * s3;
				break;

			case 'ZYX':
				this._x = s1 * c2 * c3 - c1 * s2 * s3;
				this._y = c1 * s2 * c3 + s1 * c2 * s3;
				this._z = c1 * c2 * s3 - s1 * s2 * c3;
				this._w = c1 * c2 * c3 + s1 * s2 * s3;
				break;

			case 'YZX':
				this._x = s1 * c2 * c3 + c1 * s2 * s3;
				this._y = c1 * s2 * c3 + s1 * c2 * s3;
				this._z = c1 * c2 * s3 - s1 * s2 * c3;
				this._w = c1 * c2 * c3 - s1 * s2 * s3;
				break;

			case 'XZY':
				this._x = s1 * c2 * c3 - c1 * s2 * s3;
				this._y = c1 * s2 * c3 - s1 * c2 * s3;
				this._z = c1 * c2 * s3 + s1 * s2 * c3;
				this._w = c1 * c2 * c3 + s1 * s2 * s3;
				break;

			default:
				console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );

		}

		if ( update !== false ) this._onChangeCallback();

		return this;

	},

	setFromAxisAngle: function ( axis, angle ) {

		// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm

		// assumes axis is normalized

		const halfAngle = angle / 2, s = Math.sin( halfAngle );

		this._x = axis.x * s;
		this._y = axis.y * s;
		this._z = axis.z * s;
		this._w = Math.cos( halfAngle );

		this._onChangeCallback();

		return this;

	},

	setFromRotationMatrix: function ( m ) {

		// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm

		// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

		const te = m.elements,

			m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
			m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
			m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],

			trace = m11 + m22 + m33;

		if ( trace > 0 ) {

			const s = 0.5 / Math.sqrt( trace + 1.0 );

			this._w = 0.25 / s;
			this._x = ( m32 - m23 ) * s;
			this._y = ( m13 - m31 ) * s;
			this._z = ( m21 - m12 ) * s;

		} else if ( m11 > m22 && m11 > m33 ) {

			const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );

			this._w = ( m32 - m23 ) / s;
			this._x = 0.25 * s;
			this._y = ( m12 + m21 ) / s;
			this._z = ( m13 + m31 ) / s;

		} else if ( m22 > m33 ) {

			const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );

			this._w = ( m13 - m31 ) / s;
			this._x = ( m12 + m21 ) / s;
			this._y = 0.25 * s;
			this._z = ( m23 + m32 ) / s;

		} else {

			const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );

			this._w = ( m21 - m12 ) / s;
			this._x = ( m13 + m31 ) / s;
			this._y = ( m23 + m32 ) / s;
			this._z = 0.25 * s;

		}

		this._onChangeCallback();

		return this;

	},

	setFromUnitVectors: function ( vFrom, vTo ) {

		// assumes direction vectors vFrom and vTo are normalized

		const EPS = 0.000001;

		let r = vFrom.dot( vTo ) + 1;

		if ( r < EPS ) {

			r = 0;

			if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {

				this._x = - vFrom.y;
				this._y = vFrom.x;
				this._z = 0;
				this._w = r;

			} else {

				this._x = 0;
				this._y = - vFrom.z;
				this._z = vFrom.y;
				this._w = r;

			}

		} else {

			// crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3

			this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
			this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
			this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
			this._w = r;

		}

		return this.normalize();

	},

	angleTo: function ( q ) {

		return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );

	},

	rotateTowards: function ( q, step ) {

		const angle = this.angleTo( q );

		if ( angle === 0 ) return this;

		const t = Math.min( 1, step / angle );

		this.slerp( q, t );

		return this;

	},

	inverse: function () {

		// quaternion is assumed to have unit length

		return this.conjugate();

	},

	conjugate: function () {

		this._x *= - 1;
		this._y *= - 1;
		this._z *= - 1;

		this._onChangeCallback();

		return this;

	},

	dot: function ( v ) {

		return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;

	},

	lengthSq: function () {

		return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;

	},

	length: function () {

		return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );

	},

	normalize: function () {

		let l = this.length();

		if ( l === 0 ) {

			this._x = 0;
			this._y = 0;
			this._z = 0;
			this._w = 1;

		} else {

			l = 1 / l;

			this._x = this._x * l;
			this._y = this._y * l;
			this._z = this._z * l;
			this._w = this._w * l;

		}

		this._onChangeCallback();

		return this;

	},

	multiply: function ( q, p ) {

		if ( p !== undefined ) {

			console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
			return this.multiplyQuaternions( q, p );

		}

		return this.multiplyQuaternions( this, q );

	},

	premultiply: function ( q ) {

		return this.multiplyQuaternions( q, this );

	},

	multiplyQuaternions: function ( a, b ) {

		// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm

		const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
		const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;

		this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
		this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
		this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
		this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;

		this._onChangeCallback();

		return this;

	},

	slerp: function ( qb, t ) {

		if ( t === 0 ) return this;
		if ( t === 1 ) return this.copy( qb );

		const x = this._x, y = this._y, z = this._z, w = this._w;

		// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/

		let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;

		if ( cosHalfTheta < 0 ) {

			this._w = - qb._w;
			this._x = - qb._x;
			this._y = - qb._y;
			this._z = - qb._z;

			cosHalfTheta = - cosHalfTheta;

		} else {

			this.copy( qb );

		}

		if ( cosHalfTheta >= 1.0 ) {

			this._w = w;
			this._x = x;
			this._y = y;
			this._z = z;

			return this;

		}

		const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;

		if ( sqrSinHalfTheta <= Number.EPSILON ) {

			const s = 1 - t;
			this._w = s * w + t * this._w;
			this._x = s * x + t * this._x;
			this._y = s * y + t * this._y;
			this._z = s * z + t * this._z;

			this.normalize();
			this._onChangeCallback();

			return this;

		}

		const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
		const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
		const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
			ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;

		this._w = ( w * ratioA + this._w * ratioB );
		this._x = ( x * ratioA + this._x * ratioB );
		this._y = ( y * ratioA + this._y * ratioB );
		this._z = ( z * ratioA + this._z * ratioB );

		this._onChangeCallback();

		return this;

	},

	equals: function ( quaternion ) {

		return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		this._x = array[ offset ];
		this._y = array[ offset + 1 ];
		this._z = array[ offset + 2 ];
		this._w = array[ offset + 3 ];

		this._onChangeCallback();

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		array[ offset ] = this._x;
		array[ offset + 1 ] = this._y;
		array[ offset + 2 ] = this._z;
		array[ offset + 3 ] = this._w;

		return array;

	},

	fromBufferAttribute: function ( attribute, index ) {

		this._x = attribute.getX( index );
		this._y = attribute.getY( index );
		this._z = attribute.getZ( index );
		this._w = attribute.getW( index );

		return this;

	},

	_onChange: function ( callback ) {

		this._onChangeCallback = callback;

		return this;

	},

	_onChangeCallback: function () {}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author kile / http://kile.stravaganza.org/
 * @author philogb / http://blog.thejit.org/
 * @author mikael emtinger / http://gomo.se/
 * @author egraether / http://egraether.com/
 * @author WestLangley / http://github.com/WestLangley
 */

const _vector = new Vector3();
const _quaternion = new Quaternion();

function Vector3( x = 0, y = 0, z = 0 ) {

	this.x = x;
	this.y = y;
	this.z = z;

}

Object.assign( Vector3.prototype, {

	isVector3: true,

	set: function ( x, y, z ) {

		this.x = x;
		this.y = y;
		this.z = z;

		return this;

	},

	setScalar: function ( scalar ) {

		this.x = scalar;
		this.y = scalar;
		this.z = scalar;

		return this;

	},

	setX: function ( x ) {

		this.x = x;

		return this;

	},

	setY: function ( y ) {

		this.y = y;

		return this;

	},

	setZ: function ( z ) {

		this.z = z;

		return this;

	},

	setComponent: function ( index, value ) {

		switch ( index ) {

			case 0: this.x = value; break;
			case 1: this.y = value; break;
			case 2: this.z = value; break;
			default: throw new Error( 'index is out of range: ' + index );

		}

		return this;

	},

	getComponent: function ( index ) {

		switch ( index ) {

			case 0: return this.x;
			case 1: return this.y;
			case 2: return this.z;
			default: throw new Error( 'index is out of range: ' + index );

		}

	},

	clone: function () {

		return new this.constructor( this.x, this.y, this.z );

	},

	copy: function ( v ) {

		this.x = v.x;
		this.y = v.y;
		this.z = v.z;

		return this;

	},

	add: function ( v, w ) {

		if ( w !== undefined ) {

			console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
			return this.addVectors( v, w );

		}

		this.x += v.x;
		this.y += v.y;
		this.z += v.z;

		return this;

	},

	addScalar: function ( s ) {

		this.x += s;
		this.y += s;
		this.z += s;

		return this;

	},

	addVectors: function ( a, b ) {

		this.x = a.x + b.x;
		this.y = a.y + b.y;
		this.z = a.z + b.z;

		return this;

	},

	addScaledVector: function ( v, s ) {

		this.x += v.x * s;
		this.y += v.y * s;
		this.z += v.z * s;

		return this;

	},

	sub: function ( v, w ) {

		if ( w !== undefined ) {

			console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
			return this.subVectors( v, w );

		}

		this.x -= v.x;
		this.y -= v.y;
		this.z -= v.z;

		return this;

	},

	subScalar: function ( s ) {

		this.x -= s;
		this.y -= s;
		this.z -= s;

		return this;

	},

	subVectors: function ( a, b ) {

		this.x = a.x - b.x;
		this.y = a.y - b.y;
		this.z = a.z - b.z;

		return this;

	},

	multiply: function ( v, w ) {

		if ( w !== undefined ) {

			console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
			return this.multiplyVectors( v, w );

		}

		this.x *= v.x;
		this.y *= v.y;
		this.z *= v.z;

		return this;

	},

	multiplyScalar: function ( scalar ) {

		this.x *= scalar;
		this.y *= scalar;
		this.z *= scalar;

		return this;

	},

	multiplyVectors: function ( a, b ) {

		this.x = a.x * b.x;
		this.y = a.y * b.y;
		this.z = a.z * b.z;

		return this;

	},

	applyEuler: function ( euler ) {

		if ( ! ( euler && euler.isEuler ) ) {

			console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );

		}

		return this.applyQuaternion( _quaternion.setFromEuler( euler ) );

	},

	applyAxisAngle: function ( axis, angle ) {

		return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );

	},

	applyMatrix3: function ( m ) {

		const x = this.x, y = this.y, z = this.z;
		const e = m.elements;

		this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
		this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
		this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;

		return this;

	},

	applyNormalMatrix: function ( m ) {

		return this.applyMatrix3( m ).normalize();

	},

	applyMatrix4: function ( m ) {

		const x = this.x, y = this.y, z = this.z;
		const e = m.elements;

		const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );

		this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
		this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
		this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;

		return this;

	},

	applyQuaternion: function ( q ) {

		const x = this.x, y = this.y, z = this.z;
		const qx = q.x, qy = q.y, qz = q.z, qw = q.w;

		// calculate quat * vector

		const ix = qw * x + qy * z - qz * y;
		const iy = qw * y + qz * x - qx * z;
		const iz = qw * z + qx * y - qy * x;
		const iw = - qx * x - qy * y - qz * z;

		// calculate result * inverse quat

		this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
		this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
		this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;

		return this;

	},

	project: function ( camera ) {

		return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );

	},

	unproject: function ( camera ) {

		return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );

	},

	transformDirection: function ( m ) {

		// input: THREE.Matrix4 affine matrix
		// vector interpreted as a direction

		const x = this.x, y = this.y, z = this.z;
		const e = m.elements;

		this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
		this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
		this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;

		return this.normalize();

	},

	divide: function ( v ) {

		this.x /= v.x;
		this.y /= v.y;
		this.z /= v.z;

		return this;

	},

	divideScalar: function ( scalar ) {

		return this.multiplyScalar( 1 / scalar );

	},

	min: function ( v ) {

		this.x = Math.min( this.x, v.x );
		this.y = Math.min( this.y, v.y );
		this.z = Math.min( this.z, v.z );

		return this;

	},

	max: function ( v ) {

		this.x = Math.max( this.x, v.x );
		this.y = Math.max( this.y, v.y );
		this.z = Math.max( this.z, v.z );

		return this;

	},

	clamp: function ( min, max ) {

		// assumes min < max, componentwise

		this.x = Math.max( min.x, Math.min( max.x, this.x ) );
		this.y = Math.max( min.y, Math.min( max.y, this.y ) );
		this.z = Math.max( min.z, Math.min( max.z, this.z ) );

		return this;

	},

	clampScalar: function ( minVal, maxVal ) {

		this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
		this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
		this.z = Math.max( minVal, Math.min( maxVal, this.z ) );

		return this;

	},

	clampLength: function ( min, max ) {

		const length = this.length();

		return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );

	},

	floor: function () {

		this.x = Math.floor( this.x );
		this.y = Math.floor( this.y );
		this.z = Math.floor( this.z );

		return this;

	},

	ceil: function () {

		this.x = Math.ceil( this.x );
		this.y = Math.ceil( this.y );
		this.z = Math.ceil( this.z );

		return this;

	},

	round: function () {

		this.x = Math.round( this.x );
		this.y = Math.round( this.y );
		this.z = Math.round( this.z );

		return this;

	},

	roundToZero: function () {

		this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
		this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
		this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );

		return this;

	},

	negate: function () {

		this.x = - this.x;
		this.y = - this.y;
		this.z = - this.z;

		return this;

	},

	dot: function ( v ) {

		return this.x * v.x + this.y * v.y + this.z * v.z;

	},

	// TODO lengthSquared?

	lengthSq: function () {

		return this.x * this.x + this.y * this.y + this.z * this.z;

	},

	length: function () {

		return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );

	},

	manhattanLength: function () {

		return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );

	},

	normalize: function () {

		return this.divideScalar( this.length() || 1 );

	},

	setLength: function ( length ) {

		return this.normalize().multiplyScalar( length );

	},

	lerp: function ( v, alpha ) {

		this.x += ( v.x - this.x ) * alpha;
		this.y += ( v.y - this.y ) * alpha;
		this.z += ( v.z - this.z ) * alpha;

		return this;

	},

	lerpVectors: function ( v1, v2, alpha ) {

		this.x = v1.x + ( v2.x - v1.x ) * alpha;
		this.y = v1.y + ( v2.y - v1.y ) * alpha;
		this.z = v1.z + ( v2.z - v1.z ) * alpha;

		return this;

	},

	cross: function ( v, w ) {

		if ( w !== undefined ) {

			console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
			return this.crossVectors( v, w );

		}

		return this.crossVectors( this, v );

	},

	crossVectors: function ( a, b ) {

		const ax = a.x, ay = a.y, az = a.z;
		const bx = b.x, by = b.y, bz = b.z;

		this.x = ay * bz - az * by;
		this.y = az * bx - ax * bz;
		this.z = ax * by - ay * bx;

		return this;

	},

	projectOnVector: function ( v ) {

		const denominator = v.lengthSq();

		if ( denominator === 0 ) return this.set( 0, 0, 0 );

		const scalar = v.dot( this ) / denominator;

		return this.copy( v ).multiplyScalar( scalar );

	},

	projectOnPlane: function ( planeNormal ) {

		_vector.copy( this ).projectOnVector( planeNormal );

		return this.sub( _vector );

	},

	reflect: function ( normal ) {

		// reflect incident vector off plane orthogonal to normal
		// normal is assumed to have unit length

		return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );

	},

	angleTo: function ( v ) {

		const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );

		if ( denominator === 0 ) return Math.PI / 2;

		const theta = this.dot( v ) / denominator;

		// clamp, to handle numerical problems

		return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );

	},

	distanceTo: function ( v ) {

		return Math.sqrt( this.distanceToSquared( v ) );

	},

	distanceToSquared: function ( v ) {

		const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;

		return dx * dx + dy * dy + dz * dz;

	},

	manhattanDistanceTo: function ( v ) {

		return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );

	},

	setFromSpherical: function ( s ) {

		return this.setFromSphericalCoords( s.radius, s.phi, s.theta );

	},

	setFromSphericalCoords: function ( radius, phi, theta ) {

		const sinPhiRadius = Math.sin( phi ) * radius;

		this.x = sinPhiRadius * Math.sin( theta );
		this.y = Math.cos( phi ) * radius;
		this.z = sinPhiRadius * Math.cos( theta );

		return this;

	},

	setFromCylindrical: function ( c ) {

		return this.setFromCylindricalCoords( c.radius, c.theta, c.y );

	},

	setFromCylindricalCoords: function ( radius, theta, y ) {

		this.x = radius * Math.sin( theta );
		this.y = y;
		this.z = radius * Math.cos( theta );

		return this;

	},

	setFromMatrixPosition: function ( m ) {

		const e = m.elements;

		this.x = e[ 12 ];
		this.y = e[ 13 ];
		this.z = e[ 14 ];

		return this;

	},

	setFromMatrixScale: function ( m ) {

		const sx = this.setFromMatrixColumn( m, 0 ).length();
		const sy = this.setFromMatrixColumn( m, 1 ).length();
		const sz = this.setFromMatrixColumn( m, 2 ).length();

		this.x = sx;
		this.y = sy;
		this.z = sz;

		return this;

	},

	setFromMatrixColumn: function ( m, index ) {

		return this.fromArray( m.elements, index * 4 );

	},

	setFromMatrix3Column: function ( m, index ) {

		return this.fromArray( m.elements, index * 3 );

	},

	equals: function ( v ) {

		return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		this.x = array[ offset ];
		this.y = array[ offset + 1 ];
		this.z = array[ offset + 2 ];

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		array[ offset ] = this.x;
		array[ offset + 1 ] = this.y;
		array[ offset + 2 ] = this.z;

		return array;

	},

	fromBufferAttribute: function ( attribute, index, offset ) {

		if ( offset !== undefined ) {

			console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );

		}

		this.x = attribute.getX( index );
		this.y = attribute.getY( index );
		this.z = attribute.getZ( index );

		return this;

	},

	random: function () {

		this.x = Math.random();
		this.y = Math.random();
		this.z = Math.random();

		return this;

	}

} );

const _v1 = new Vector3();
const _m1 = new Matrix4();
const _zero = new Vector3( 0, 0, 0 );
const _one = new Vector3( 1, 1, 1 );
const _x = new Vector3();
const _y = new Vector3();
const _z = new Vector3();

/**
 * @author mrdoob / http://mrdoob.com/
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author philogb / http://blog.thejit.org/
 * @author jordi_ros / http://plattsoft.com
 * @author D1plo1d / http://github.com/D1plo1d
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 * @author timknip / http://www.floorplanner.com/
 * @author bhouston / http://clara.io
 * @author WestLangley / http://github.com/WestLangley
 */

function Matrix4() {

	this.elements = [

		1, 0, 0, 0,
		0, 1, 0, 0,
		0, 0, 1, 0,
		0, 0, 0, 1

	];

	if ( arguments.length > 0 ) {

		console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );

	}

}

Object.assign( Matrix4.prototype, {

	isMatrix4: true,

	set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {

		const te = this.elements;

		te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
		te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
		te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
		te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;

		return this;

	},

	identity: function () {

		this.set(

			1, 0, 0, 0,
			0, 1, 0, 0,
			0, 0, 1, 0,
			0, 0, 0, 1

		);

		return this;

	},

	clone: function () {

		return new Matrix4().fromArray( this.elements );

	},

	copy: function ( m ) {

		const te = this.elements;
		const me = m.elements;

		te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
		te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
		te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
		te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];

		return this;

	},

	copyPosition: function ( m ) {

		const te = this.elements, me = m.elements;

		te[ 12 ] = me[ 12 ];
		te[ 13 ] = me[ 13 ];
		te[ 14 ] = me[ 14 ];

		return this;

	},

	extractBasis: function ( xAxis, yAxis, zAxis ) {

		xAxis.setFromMatrixColumn( this, 0 );
		yAxis.setFromMatrixColumn( this, 1 );
		zAxis.setFromMatrixColumn( this, 2 );

		return this;

	},

	makeBasis: function ( xAxis, yAxis, zAxis ) {

		this.set(
			xAxis.x, yAxis.x, zAxis.x, 0,
			xAxis.y, yAxis.y, zAxis.y, 0,
			xAxis.z, yAxis.z, zAxis.z, 0,
			0, 0, 0, 1
		);

		return this;

	},

	extractRotation: function ( m ) {

		// this method does not support reflection matrices

		const te = this.elements;
		const me = m.elements;

		const scaleX = 1 / _v1.setFromMatrixColumn( m, 0 ).length();
		const scaleY = 1 / _v1.setFromMatrixColumn( m, 1 ).length();
		const scaleZ = 1 / _v1.setFromMatrixColumn( m, 2 ).length();

		te[ 0 ] = me[ 0 ] * scaleX;
		te[ 1 ] = me[ 1 ] * scaleX;
		te[ 2 ] = me[ 2 ] * scaleX;
		te[ 3 ] = 0;

		te[ 4 ] = me[ 4 ] * scaleY;
		te[ 5 ] = me[ 5 ] * scaleY;
		te[ 6 ] = me[ 6 ] * scaleY;
		te[ 7 ] = 0;

		te[ 8 ] = me[ 8 ] * scaleZ;
		te[ 9 ] = me[ 9 ] * scaleZ;
		te[ 10 ] = me[ 10 ] * scaleZ;
		te[ 11 ] = 0;

		te[ 12 ] = 0;
		te[ 13 ] = 0;
		te[ 14 ] = 0;
		te[ 15 ] = 1;

		return this;

	},

	makeRotationFromEuler: function ( euler ) {

		if ( ! ( euler && euler.isEuler ) ) {

			console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );

		}

		const te = this.elements;

		const x = euler.x, y = euler.y, z = euler.z;
		const a = Math.cos( x ), b = Math.sin( x );
		const c = Math.cos( y ), d = Math.sin( y );
		const e = Math.cos( z ), f = Math.sin( z );

		if ( euler.order === 'XYZ' ) {

			const ae = a * e, af = a * f, be = b * e, bf = b * f;

			te[ 0 ] = c * e;
			te[ 4 ] = - c * f;
			te[ 8 ] = d;

			te[ 1 ] = af + be * d;
			te[ 5 ] = ae - bf * d;
			te[ 9 ] = - b * c;

			te[ 2 ] = bf - ae * d;
			te[ 6 ] = be + af * d;
			te[ 10 ] = a * c;

		} else if ( euler.order === 'YXZ' ) {

			const ce = c * e, cf = c * f, de = d * e, df = d * f;

			te[ 0 ] = ce + df * b;
			te[ 4 ] = de * b - cf;
			te[ 8 ] = a * d;

			te[ 1 ] = a * f;
			te[ 5 ] = a * e;
			te[ 9 ] = - b;

			te[ 2 ] = cf * b - de;
			te[ 6 ] = df + ce * b;
			te[ 10 ] = a * c;

		} else if ( euler.order === 'ZXY' ) {

			const ce = c * e, cf = c * f, de = d * e, df = d * f;

			te[ 0 ] = ce - df * b;
			te[ 4 ] = - a * f;
			te[ 8 ] = de + cf * b;

			te[ 1 ] = cf + de * b;
			te[ 5 ] = a * e;
			te[ 9 ] = df - ce * b;

			te[ 2 ] = - a * d;
			te[ 6 ] = b;
			te[ 10 ] = a * c;

		} else if ( euler.order === 'ZYX' ) {

			const ae = a * e, af = a * f, be = b * e, bf = b * f;

			te[ 0 ] = c * e;
			te[ 4 ] = be * d - af;
			te[ 8 ] = ae * d + bf;

			te[ 1 ] = c * f;
			te[ 5 ] = bf * d + ae;
			te[ 9 ] = af * d - be;

			te[ 2 ] = - d;
			te[ 6 ] = b * c;
			te[ 10 ] = a * c;

		} else if ( euler.order === 'YZX' ) {

			const ac = a * c, ad = a * d, bc = b * c, bd = b * d;

			te[ 0 ] = c * e;
			te[ 4 ] = bd - ac * f;
			te[ 8 ] = bc * f + ad;

			te[ 1 ] = f;
			te[ 5 ] = a * e;
			te[ 9 ] = - b * e;

			te[ 2 ] = - d * e;
			te[ 6 ] = ad * f + bc;
			te[ 10 ] = ac - bd * f;

		} else if ( euler.order === 'XZY' ) {

			const ac = a * c, ad = a * d, bc = b * c, bd = b * d;

			te[ 0 ] = c * e;
			te[ 4 ] = - f;
			te[ 8 ] = d * e;

			te[ 1 ] = ac * f + bd;
			te[ 5 ] = a * e;
			te[ 9 ] = ad * f - bc;

			te[ 2 ] = bc * f - ad;
			te[ 6 ] = b * e;
			te[ 10 ] = bd * f + ac;

		}

		// bottom row
		te[ 3 ] = 0;
		te[ 7 ] = 0;
		te[ 11 ] = 0;

		// last column
		te[ 12 ] = 0;
		te[ 13 ] = 0;
		te[ 14 ] = 0;
		te[ 15 ] = 1;

		return this;

	},

	makeRotationFromQuaternion: function ( q ) {

		return this.compose( _zero, q, _one );

	},

	lookAt: function ( eye, target, up ) {

		const te = this.elements;

		_z.subVectors( eye, target );

		if ( _z.lengthSq() === 0 ) {

			// eye and target are in the same position

			_z.z = 1;

		}

		_z.normalize();
		_x.crossVectors( up, _z );

		if ( _x.lengthSq() === 0 ) {

			// up and z are parallel

			if ( Math.abs( up.z ) === 1 ) {

				_z.x += 0.0001;

			} else {

				_z.z += 0.0001;

			}

			_z.normalize();
			_x.crossVectors( up, _z );

		}

		_x.normalize();
		_y.crossVectors( _z, _x );

		te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
		te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
		te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;

		return this;

	},

	multiply: function ( m, n ) {

		if ( n !== undefined ) {

			console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
			return this.multiplyMatrices( m, n );

		}

		return this.multiplyMatrices( this, m );

	},

	premultiply: function ( m ) {

		return this.multiplyMatrices( m, this );

	},

	multiplyMatrices: function ( a, b ) {

		const ae = a.elements;
		const be = b.elements;
		const te = this.elements;

		const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
		const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
		const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
		const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];

		const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
		const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
		const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
		const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];

		te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
		te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
		te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
		te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;

		te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
		te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
		te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
		te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;

		te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
		te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
		te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
		te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;

		te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
		te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
		te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
		te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;

		return this;

	},

	multiplyScalar: function ( s ) {

		const te = this.elements;

		te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
		te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
		te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
		te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;

		return this;

	},

	determinant: function () {

		const te = this.elements;

		const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
		const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
		const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
		const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];

		//TODO: make this more efficient
		//( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )

		return (
			n41 * (
				+ n14 * n23 * n32
				 - n13 * n24 * n32
				 - n14 * n22 * n33
				 + n12 * n24 * n33
				 + n13 * n22 * n34
				 - n12 * n23 * n34
			) +
			n42 * (
				+ n11 * n23 * n34
				 - n11 * n24 * n33
				 + n14 * n21 * n33
				 - n13 * n21 * n34
				 + n13 * n24 * n31
				 - n14 * n23 * n31
			) +
			n43 * (
				+ n11 * n24 * n32
				 - n11 * n22 * n34
				 - n14 * n21 * n32
				 + n12 * n21 * n34
				 + n14 * n22 * n31
				 - n12 * n24 * n31
			) +
			n44 * (
				- n13 * n22 * n31
				 - n11 * n23 * n32
				 + n11 * n22 * n33
				 + n13 * n21 * n32
				 - n12 * n21 * n33
				 + n12 * n23 * n31
			)

		);

	},

	transpose: function () {

		const te = this.elements;
		let tmp;

		tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
		tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
		tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;

		tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
		tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
		tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;

		return this;

	},

	setPosition: function ( x, y, z ) {

		const te = this.elements;

		if ( x.isVector3 ) {

			te[ 12 ] = x.x;
			te[ 13 ] = x.y;
			te[ 14 ] = x.z;

		} else {

			te[ 12 ] = x;
			te[ 13 ] = y;
			te[ 14 ] = z;

		}

		return this;

	},

	getInverse: function ( m, throwOnDegenerate ) {

		if ( throwOnDegenerate !== undefined ) {

			console.warn( "THREE.Matrix4: .getInverse() can no longer be configured to throw on degenerate." );

		}

		// based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
		const te = this.elements,
			me = m.elements,

			n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
			n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
			n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
			n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],

			t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
			t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
			t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
			t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;

		const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;

		if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );

		const detInv = 1 / det;

		te[ 0 ] = t11 * detInv;
		te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
		te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
		te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;

		te[ 4 ] = t12 * detInv;
		te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
		te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
		te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;

		te[ 8 ] = t13 * detInv;
		te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
		te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
		te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;

		te[ 12 ] = t14 * detInv;
		te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
		te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
		te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;

		return this;

	},

	scale: function ( v ) {

		const te = this.elements;
		const x = v.x, y = v.y, z = v.z;

		te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
		te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
		te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
		te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;

		return this;

	},

	getMaxScaleOnAxis: function () {

		const te = this.elements;

		const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
		const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
		const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];

		return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );

	},

	makeTranslation: function ( x, y, z ) {

		this.set(

			1, 0, 0, x,
			0, 1, 0, y,
			0, 0, 1, z,
			0, 0, 0, 1

		);

		return this;

	},

	makeRotationX: function ( theta ) {

		const c = Math.cos( theta ), s = Math.sin( theta );

		this.set(

			1, 0, 0, 0,
			0, c, - s, 0,
			0, s, c, 0,
			0, 0, 0, 1

		);

		return this;

	},

	makeRotationY: function ( theta ) {

		const c = Math.cos( theta ), s = Math.sin( theta );

		this.set(

			 c, 0, s, 0,
			 0, 1, 0, 0,
			- s, 0, c, 0,
			 0, 0, 0, 1

		);

		return this;

	},

	makeRotationZ: function ( theta ) {

		const c = Math.cos( theta ), s = Math.sin( theta );

		this.set(

			c, - s, 0, 0,
			s, c, 0, 0,
			0, 0, 1, 0,
			0, 0, 0, 1

		);

		return this;

	},

	makeRotationAxis: function ( axis, angle ) {

		// Based on http://www.gamedev.net/reference/articles/article1199.asp

		const c = Math.cos( angle );
		const s = Math.sin( angle );
		const t = 1 - c;
		const x = axis.x, y = axis.y, z = axis.z;
		const tx = t * x, ty = t * y;

		this.set(

			tx * x + c, tx * y - s * z, tx * z + s * y, 0,
			tx * y + s * z, ty * y + c, ty * z - s * x, 0,
			tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
			0, 0, 0, 1

		);

		 return this;

	},

	makeScale: function ( x, y, z ) {

		this.set(

			x, 0, 0, 0,
			0, y, 0, 0,
			0, 0, z, 0,
			0, 0, 0, 1

		);

		return this;

	},

	makeShear: function ( x, y, z ) {

		this.set(

			1, y, z, 0,
			x, 1, z, 0,
			x, y, 1, 0,
			0, 0, 0, 1

		);

		return this;

	},

	compose: function ( position, quaternion, scale ) {

		const te = this.elements;

		const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
		const x2 = x + x,	y2 = y + y, z2 = z + z;
		const xx = x * x2, xy = x * y2, xz = x * z2;
		const yy = y * y2, yz = y * z2, zz = z * z2;
		const wx = w * x2, wy = w * y2, wz = w * z2;

		const sx = scale.x, sy = scale.y, sz = scale.z;

		te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
		te[ 1 ] = ( xy + wz ) * sx;
		te[ 2 ] = ( xz - wy ) * sx;
		te[ 3 ] = 0;

		te[ 4 ] = ( xy - wz ) * sy;
		te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
		te[ 6 ] = ( yz + wx ) * sy;
		te[ 7 ] = 0;

		te[ 8 ] = ( xz + wy ) * sz;
		te[ 9 ] = ( yz - wx ) * sz;
		te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
		te[ 11 ] = 0;

		te[ 12 ] = position.x;
		te[ 13 ] = position.y;
		te[ 14 ] = position.z;
		te[ 15 ] = 1;

		return this;

	},

	decompose: function ( position, quaternion, scale ) {

		const te = this.elements;

		let sx = _v1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
		let sy = _v1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
		let sz = _v1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();

		// if determine is negative, we need to invert one scale
		const det = this.determinant();
		if ( det < 0 ) sx = - sx;

		position.x = te[ 12 ];
		position.y = te[ 13 ];
		position.z = te[ 14 ];

		// scale the rotation part
		_m1.copy( this );

		const invSX = 1 / sx;
		const invSY = 1 / sy;
		const invSZ = 1 / sz;

		_m1.elements[ 0 ] *= invSX;
		_m1.elements[ 1 ] *= invSX;
		_m1.elements[ 2 ] *= invSX;

		_m1.elements[ 4 ] *= invSY;
		_m1.elements[ 5 ] *= invSY;
		_m1.elements[ 6 ] *= invSY;

		_m1.elements[ 8 ] *= invSZ;
		_m1.elements[ 9 ] *= invSZ;
		_m1.elements[ 10 ] *= invSZ;

		quaternion.setFromRotationMatrix( _m1 );

		scale.x = sx;
		scale.y = sy;
		scale.z = sz;

		return this;

	},

	makePerspective: function ( left, right, top, bottom, near, far ) {

		if ( far === undefined ) {

			console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );

		}

		const te = this.elements;
		const x = 2 * near / ( right - left );
		const y = 2 * near / ( top - bottom );

		const a = ( right + left ) / ( right - left );
		const b = ( top + bottom ) / ( top - bottom );
		const c = - ( far + near ) / ( far - near );
		const d = - 2 * far * near / ( far - near );

		te[ 0 ] = x;	te[ 4 ] = 0;	te[ 8 ] = a;	te[ 12 ] = 0;
		te[ 1 ] = 0;	te[ 5 ] = y;	te[ 9 ] = b;	te[ 13 ] = 0;
		te[ 2 ] = 0;	te[ 6 ] = 0;	te[ 10 ] = c;	te[ 14 ] = d;
		te[ 3 ] = 0;	te[ 7 ] = 0;	te[ 11 ] = - 1;	te[ 15 ] = 0;

		return this;

	},

	makeOrthographic: function ( left, right, top, bottom, near, far ) {

		const te = this.elements;
		const w = 1.0 / ( right - left );
		const h = 1.0 / ( top - bottom );
		const p = 1.0 / ( far - near );

		const x = ( right + left ) * w;
		const y = ( top + bottom ) * h;
		const z = ( far + near ) * p;

		te[ 0 ] = 2 * w;	te[ 4 ] = 0;	te[ 8 ] = 0;	te[ 12 ] = - x;
		te[ 1 ] = 0;	te[ 5 ] = 2 * h;	te[ 9 ] = 0;	te[ 13 ] = - y;
		te[ 2 ] = 0;	te[ 6 ] = 0;	te[ 10 ] = - 2 * p;	te[ 14 ] = - z;
		te[ 3 ] = 0;	te[ 7 ] = 0;	te[ 11 ] = 0;	te[ 15 ] = 1;

		return this;

	},

	equals: function ( matrix ) {

		const te = this.elements;
		const me = matrix.elements;

		for ( let i = 0; i < 16; i ++ ) {

			if ( te[ i ] !== me[ i ] ) return false;

		}

		return true;

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		for ( let i = 0; i < 16; i ++ ) {

			this.elements[ i ] = array[ i + offset ];

		}

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		const te = this.elements;

		array[ offset ] = te[ 0 ];
		array[ offset + 1 ] = te[ 1 ];
		array[ offset + 2 ] = te[ 2 ];
		array[ offset + 3 ] = te[ 3 ];

		array[ offset + 4 ] = te[ 4 ];
		array[ offset + 5 ] = te[ 5 ];
		array[ offset + 6 ] = te[ 6 ];
		array[ offset + 7 ] = te[ 7 ];

		array[ offset + 8 ] = te[ 8 ];
		array[ offset + 9 ] = te[ 9 ];
		array[ offset + 10 ] = te[ 10 ];
		array[ offset + 11 ] = te[ 11 ];

		array[ offset + 12 ] = te[ 12 ];
		array[ offset + 13 ] = te[ 13 ];
		array[ offset + 14 ] = te[ 14 ];
		array[ offset + 15 ] = te[ 15 ];

		return array;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author bhouston / http://clara.io
 */

const _matrix = new Matrix4();
const _quaternion$1 = new Quaternion();

function Euler( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {

	this._x = x;
	this._y = y;
	this._z = z;
	this._order = order;

}

Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];

Euler.DefaultOrder = 'XYZ';

Object.defineProperties( Euler.prototype, {

	x: {

		get: function () {

			return this._x;

		},

		set: function ( value ) {

			this._x = value;
			this._onChangeCallback();

		}

	},

	y: {

		get: function () {

			return this._y;

		},

		set: function ( value ) {

			this._y = value;
			this._onChangeCallback();

		}

	},

	z: {

		get: function () {

			return this._z;

		},

		set: function ( value ) {

			this._z = value;
			this._onChangeCallback();

		}

	},

	order: {

		get: function () {

			return this._order;

		},

		set: function ( value ) {

			this._order = value;
			this._onChangeCallback();

		}

	}

} );

Object.assign( Euler.prototype, {

	isEuler: true,

	set: function ( x, y, z, order ) {

		this._x = x;
		this._y = y;
		this._z = z;
		this._order = order || this._order;

		this._onChangeCallback();

		return this;

	},

	clone: function () {

		return new this.constructor( this._x, this._y, this._z, this._order );

	},

	copy: function ( euler ) {

		this._x = euler._x;
		this._y = euler._y;
		this._z = euler._z;
		this._order = euler._order;

		this._onChangeCallback();

		return this;

	},

	setFromRotationMatrix: function ( m, order, update ) {

		const clamp = MathUtils.clamp;

		// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

		const te = m.elements;
		const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
		const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
		const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];

		order = order || this._order;

		switch ( order ) {

			case 'XYZ':

				this._y = Math.asin( clamp( m13, - 1, 1 ) );

				if ( Math.abs( m13 ) < 0.9999999 ) {

					this._x = Math.atan2( - m23, m33 );
					this._z = Math.atan2( - m12, m11 );

				} else {

					this._x = Math.atan2( m32, m22 );
					this._z = 0;

				}

				break;

			case 'YXZ':

				this._x = Math.asin( - clamp( m23, - 1, 1 ) );

				if ( Math.abs( m23 ) < 0.9999999 ) {

					this._y = Math.atan2( m13, m33 );
					this._z = Math.atan2( m21, m22 );

				} else {

					this._y = Math.atan2( - m31, m11 );
					this._z = 0;

				}

				break;

			case 'ZXY':

				this._x = Math.asin( clamp( m32, - 1, 1 ) );

				if ( Math.abs( m32 ) < 0.9999999 ) {

					this._y = Math.atan2( - m31, m33 );
					this._z = Math.atan2( - m12, m22 );

				} else {

					this._y = 0;
					this._z = Math.atan2( m21, m11 );

				}

				break;

			case 'ZYX':

				this._y = Math.asin( - clamp( m31, - 1, 1 ) );

				if ( Math.abs( m31 ) < 0.9999999 ) {

					this._x = Math.atan2( m32, m33 );
					this._z = Math.atan2( m21, m11 );

				} else {

					this._x = 0;
					this._z = Math.atan2( - m12, m22 );

				}

				break;

			case 'YZX':

				this._z = Math.asin( clamp( m21, - 1, 1 ) );

				if ( Math.abs( m21 ) < 0.9999999 ) {

					this._x = Math.atan2( - m23, m22 );
					this._y = Math.atan2( - m31, m11 );

				} else {

					this._x = 0;
					this._y = Math.atan2( m13, m33 );

				}

				break;

			case 'XZY':

				this._z = Math.asin( - clamp( m12, - 1, 1 ) );

				if ( Math.abs( m12 ) < 0.9999999 ) {

					this._x = Math.atan2( m32, m22 );
					this._y = Math.atan2( m13, m11 );

				} else {

					this._x = Math.atan2( - m23, m33 );
					this._y = 0;

				}

				break;

			default:

				console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );

		}

		this._order = order;

		if ( update !== false ) this._onChangeCallback();

		return this;

	},

	setFromQuaternion: function ( q, order, update ) {

		_matrix.makeRotationFromQuaternion( q );

		return this.setFromRotationMatrix( _matrix, order, update );

	},

	setFromVector3: function ( v, order ) {

		return this.set( v.x, v.y, v.z, order || this._order );

	},

	reorder: function ( newOrder ) {

		// WARNING: this discards revolution information -bhouston

		_quaternion$1.setFromEuler( this );

		return this.setFromQuaternion( _quaternion$1, newOrder );

	},

	equals: function ( euler ) {

		return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );

	},

	fromArray: function ( array ) {

		this._x = array[ 0 ];
		this._y = array[ 1 ];
		this._z = array[ 2 ];
		if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];

		this._onChangeCallback();

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		array[ offset ] = this._x;
		array[ offset + 1 ] = this._y;
		array[ offset + 2 ] = this._z;
		array[ offset + 3 ] = this._order;

		return array;

	},

	toVector3: function ( optionalResult ) {

		if ( optionalResult ) {

			return optionalResult.set( this._x, this._y, this._z );

		} else {

			return new Vector3( this._x, this._y, this._z );

		}

	},

	_onChange: function ( callback ) {

		this._onChangeCallback = callback;

		return this;

	},

	_onChangeCallback: function () {}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function Layers() {

	this.mask = 1 | 0;

}

Object.assign( Layers.prototype, {

	set: function ( channel ) {

		this.mask = 1 << channel | 0;

	},

	enable: function ( channel ) {

		this.mask |= 1 << channel | 0;

	},

	enableAll: function () {

		this.mask = 0xffffffff | 0;

	},

	toggle: function ( channel ) {

		this.mask ^= 1 << channel | 0;

	},

	disable: function ( channel ) {

		this.mask &= ~ ( 1 << channel | 0 );

	},

	disableAll: function () {

		this.mask = 0;

	},

	test: function ( layers ) {

		return ( this.mask & layers.mask ) !== 0;

	}

} );

let _object3DId = 0;

const _v1$1 = new Vector3();
const _q1 = new Quaternion();
const _m1$1 = new Matrix4();
const _target = new Vector3();

const _position = new Vector3();
const _scale = new Vector3();
const _quaternion$2 = new Quaternion();

const _xAxis = new Vector3( 1, 0, 0 );
const _yAxis = new Vector3( 0, 1, 0 );
const _zAxis = new Vector3( 0, 0, 1 );

const _addedEvent = { type: 'added' };
const _removedEvent = { type: 'removed' };

/**
 * @author mrdoob / http://mrdoob.com/
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 * @author elephantatwork / www.elephantatwork.ch
 */

function Object3D() {

	Object.defineProperty( this, 'id', { value: _object3DId ++ } );

	this.uuid = MathUtils.generateUUID();

	this.name = '';
	this.type = 'Object3D';

	this.parent = null;
	this.children = [];

	this.up = Object3D.DefaultUp.clone();

	const position = new Vector3();
	const rotation = new Euler();
	const quaternion = new Quaternion();
	const scale = new Vector3( 1, 1, 1 );

	function onRotationChange() {

		quaternion.setFromEuler( rotation, false );

	}

	function onQuaternionChange() {

		rotation.setFromQuaternion( quaternion, undefined, false );

	}

	rotation._onChange( onRotationChange );
	quaternion._onChange( onQuaternionChange );

	Object.defineProperties( this, {
		position: {
			configurable: true,
			enumerable: true,
			value: position
		},
		rotation: {
			configurable: true,
			enumerable: true,
			value: rotation
		},
		quaternion: {
			configurable: true,
			enumerable: true,
			value: quaternion
		},
		scale: {
			configurable: true,
			enumerable: true,
			value: scale
		},
		modelViewMatrix: {
			value: new Matrix4()
		},
		normalMatrix: {
			value: new Matrix3()
		}
	} );

	this.matrix = new Matrix4();
	this.matrixWorld = new Matrix4();

	this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
	this.matrixWorldNeedsUpdate = false;

	this.layers = new Layers();
	this.visible = true;

	this.castShadow = false;
	this.receiveShadow = false;

	this.frustumCulled = true;
	this.renderOrder = 0;

	this.userData = {};

}

Object3D.DefaultUp = new Vector3( 0, 1, 0 );
Object3D.DefaultMatrixAutoUpdate = true;

Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

	constructor: Object3D,

	isObject3D: true,

	onBeforeRender: function () {},
	onAfterRender: function () {},

	applyMatrix4: function ( matrix ) {

		if ( this.matrixAutoUpdate ) this.updateMatrix();

		this.matrix.premultiply( matrix );

		this.matrix.decompose( this.position, this.quaternion, this.scale );

	},

	applyQuaternion: function ( q ) {

		this.quaternion.premultiply( q );

		return this;

	},

	setRotationFromAxisAngle: function ( axis, angle ) {

		// assumes axis is normalized

		this.quaternion.setFromAxisAngle( axis, angle );

	},

	setRotationFromEuler: function ( euler ) {

		this.quaternion.setFromEuler( euler, true );

	},

	setRotationFromMatrix: function ( m ) {

		// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

		this.quaternion.setFromRotationMatrix( m );

	},

	setRotationFromQuaternion: function ( q ) {

		// assumes q is normalized

		this.quaternion.copy( q );

	},

	rotateOnAxis: function ( axis, angle ) {

		// rotate object on axis in object space
		// axis is assumed to be normalized

		_q1.setFromAxisAngle( axis, angle );

		this.quaternion.multiply( _q1 );

		return this;

	},

	rotateOnWorldAxis: function ( axis, angle ) {

		// rotate object on axis in world space
		// axis is assumed to be normalized
		// method assumes no rotated parent

		_q1.setFromAxisAngle( axis, angle );

		this.quaternion.premultiply( _q1 );

		return this;

	},

	rotateX: function ( angle ) {

		return this.rotateOnAxis( _xAxis, angle );

	},

	rotateY: function ( angle ) {

		return this.rotateOnAxis( _yAxis, angle );

	},

	rotateZ: function ( angle ) {

		return this.rotateOnAxis( _zAxis, angle );

	},

	translateOnAxis: function ( axis, distance ) {

		// translate object by distance along axis in object space
		// axis is assumed to be normalized

		_v1$1.copy( axis ).applyQuaternion( this.quaternion );

		this.position.add( _v1$1.multiplyScalar( distance ) );

		return this;

	},

	translateX: function ( distance ) {

		return this.translateOnAxis( _xAxis, distance );

	},

	translateY: function ( distance ) {

		return this.translateOnAxis( _yAxis, distance );

	},

	translateZ: function ( distance ) {

		return this.translateOnAxis( _zAxis, distance );

	},

	localToWorld: function ( vector ) {

		return vector.applyMatrix4( this.matrixWorld );

	},

	worldToLocal: function ( vector ) {

		return vector.applyMatrix4( _m1$1.getInverse( this.matrixWorld ) );

	},

	lookAt: function ( x, y, z ) {

		// This method does not support objects having non-uniformly-scaled parent(s)

		if ( x.isVector3 ) {

			_target.copy( x );

		} else {

			_target.set( x, y, z );

		}

		const parent = this.parent;

		this.updateWorldMatrix( true, false );

		_position.setFromMatrixPosition( this.matrixWorld );

		if ( this.isCamera || this.isLight ) {

			_m1$1.lookAt( _position, _target, this.up );

		} else {

			_m1$1.lookAt( _target, _position, this.up );

		}

		this.quaternion.setFromRotationMatrix( _m1$1 );

		if ( parent ) {

			_m1$1.extractRotation( parent.matrixWorld );
			_q1.setFromRotationMatrix( _m1$1 );
			this.quaternion.premultiply( _q1.inverse() );

		}

	},

	add: function ( object ) {

		if ( arguments.length > 1 ) {

			for ( let i = 0; i < arguments.length; i ++ ) {

				this.add( arguments[ i ] );

			}

			return this;

		}

		if ( object === this ) {

			console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
			return this;

		}

		if ( ( object && object.isObject3D ) ) {

			if ( object.parent !== null ) {

				object.parent.remove( object );

			}

			object.parent = this;
			this.children.push( object );

			object.dispatchEvent( _addedEvent );

		} else {

			console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );

		}

		return this;

	},

	remove: function ( object ) {

		if ( arguments.length > 1 ) {

			for ( let i = 0; i < arguments.length; i ++ ) {

				this.remove( arguments[ i ] );

			}

			return this;

		}

		const index = this.children.indexOf( object );

		if ( index !== - 1 ) {

			object.parent = null;
			this.children.splice( index, 1 );

			object.dispatchEvent( _removedEvent );

		}

		return this;

	},

	attach: function ( object ) {

		// adds object as a child of this, while maintaining the object's world transform

		this.updateWorldMatrix( true, false );

		_m1$1.getInverse( this.matrixWorld );

		if ( object.parent !== null ) {

			object.parent.updateWorldMatrix( true, false );

			_m1$1.multiply( object.parent.matrixWorld );

		}

		object.applyMatrix4( _m1$1 );

		object.updateWorldMatrix( false, false );

		this.add( object );

		return this;

	},

	getObjectById: function ( id ) {

		return this.getObjectByProperty( 'id', id );

	},

	getObjectByName: function ( name ) {

		return this.getObjectByProperty( 'name', name );

	},

	getObjectByProperty: function ( name, value ) {

		if ( this[ name ] === value ) return this;

		for ( let i = 0, l = this.children.length; i < l; i ++ ) {

			const child = this.children[ i ];
			const object = child.getObjectByProperty( name, value );

			if ( object !== undefined ) {

				return object;

			}

		}

		return undefined;

	},

	getWorldPosition: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
			target = new Vector3();

		}

		this.updateMatrixWorld( true );

		return target.setFromMatrixPosition( this.matrixWorld );

	},

	getWorldQuaternion: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
			target = new Quaternion();

		}

		this.updateMatrixWorld( true );

		this.matrixWorld.decompose( _position, target, _scale );

		return target;

	},

	getWorldScale: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
			target = new Vector3();

		}

		this.updateMatrixWorld( true );

		this.matrixWorld.decompose( _position, _quaternion$2, target );

		return target;

	},

	getWorldDirection: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
			target = new Vector3();

		}

		this.updateMatrixWorld( true );

		const e = this.matrixWorld.elements;

		return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();

	},

	raycast: function () {},

	traverse: function ( callback ) {

		callback( this );

		const children = this.children;

		for ( let i = 0, l = children.length; i < l; i ++ ) {

			children[ i ].traverse( callback );

		}

	},

	traverseVisible: function ( callback ) {

		if ( this.visible === false ) return;

		callback( this );

		const children = this.children;

		for ( let i = 0, l = children.length; i < l; i ++ ) {

			children[ i ].traverseVisible( callback );

		}

	},

	traverseAncestors: function ( callback ) {

		const parent = this.parent;

		if ( parent !== null ) {

			callback( parent );

			parent.traverseAncestors( callback );

		}

	},

	updateMatrix: function () {

		this.matrix.compose( this.position, this.quaternion, this.scale );

		this.matrixWorldNeedsUpdate = true;

	},

	updateMatrixWorld: function ( force ) {

		if ( this.matrixAutoUpdate ) this.updateMatrix();

		if ( this.matrixWorldNeedsUpdate || force ) {

			if ( this.parent === null ) {

				this.matrixWorld.copy( this.matrix );

			} else {

				this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );

			}

			this.matrixWorldNeedsUpdate = false;

			force = true;

		}

		// update children

		const children = this.children;

		for ( let i = 0, l = children.length; i < l; i ++ ) {

			children[ i ].updateMatrixWorld( force );

		}

	},

	updateWorldMatrix: function ( updateParents, updateChildren ) {

		const parent = this.parent;

		if ( updateParents === true && parent !== null ) {

			parent.updateWorldMatrix( true, false );

		}

		if ( this.matrixAutoUpdate ) this.updateMatrix();

		if ( this.parent === null ) {

			this.matrixWorld.copy( this.matrix );

		} else {

			this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );

		}

		// update children

		if ( updateChildren === true ) {

			const children = this.children;

			for ( let i = 0, l = children.length; i < l; i ++ ) {

				children[ i ].updateWorldMatrix( false, true );

			}

		}

	},

	toJSON: function ( meta ) {

		// meta is a string when called from JSON.stringify
		const isRootObject = ( meta === undefined || typeof meta === 'string' );

		const output = {};

		// meta is a hash used to collect geometries, materials.
		// not providing it implies that this is the root object
		// being serialized.
		if ( isRootObject ) {

			// initialize meta obj
			meta = {
				geometries: {},
				materials: {},
				textures: {},
				images: {},
				shapes: {}
			};

			output.metadata = {
				version: 4.5,
				type: 'Object',
				generator: 'Object3D.toJSON'
			};

		}

		// standard Object3D serialization

		const object = {};

		object.uuid = this.uuid;
		object.type = this.type;

		if ( this.name !== '' ) object.name = this.name;
		if ( this.castShadow === true ) object.castShadow = true;
		if ( this.receiveShadow === true ) object.receiveShadow = true;
		if ( this.visible === false ) object.visible = false;
		if ( this.frustumCulled === false ) object.frustumCulled = false;
		if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
		if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;

		object.layers = this.layers.mask;
		object.matrix = this.matrix.toArray();

		if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;

		// object specific properties

		if ( this.isInstancedMesh ) {

			object.type = 'InstancedMesh';
			object.count = this.count;
			object.instanceMatrix = this.instanceMatrix.toJSON();

		}

		//

		function serialize( library, element ) {

			if ( library[ element.uuid ] === undefined ) {

				library[ element.uuid ] = element.toJSON( meta );

			}

			return element.uuid;

		}

		if ( this.isMesh || this.isLine || this.isPoints ) {

			object.geometry = serialize( meta.geometries, this.geometry );

			const parameters = this.geometry.parameters;

			if ( parameters !== undefined && parameters.shapes !== undefined ) {

				const shapes = parameters.shapes;

				if ( Array.isArray( shapes ) ) {

					for ( let i = 0, l = shapes.length; i < l; i ++ ) {

						const shape = shapes[ i ];

						serialize( meta.shapes, shape );

					}

				} else {

					serialize( meta.shapes, shapes );

				}

			}

		}

		if ( this.material !== undefined ) {

			if ( Array.isArray( this.material ) ) {

				const uuids = [];

				for ( let i = 0, l = this.material.length; i < l; i ++ ) {

					uuids.push( serialize( meta.materials, this.material[ i ] ) );

				}

				object.material = uuids;

			} else {

				object.material = serialize( meta.materials, this.material );

			}

		}

		//

		if ( this.children.length > 0 ) {

			object.children = [];

			for ( let i = 0; i < this.children.length; i ++ ) {

				object.children.push( this.children[ i ].toJSON( meta ).object );

			}

		}

		if ( isRootObject ) {

			const geometries = extractFromCache( meta.geometries );
			const materials = extractFromCache( meta.materials );
			const textures = extractFromCache( meta.textures );
			const images = extractFromCache( meta.images );
			const shapes = extractFromCache( meta.shapes );

			if ( geometries.length > 0 ) output.geometries = geometries;
			if ( materials.length > 0 ) output.materials = materials;
			if ( textures.length > 0 ) output.textures = textures;
			if ( images.length > 0 ) output.images = images;
			if ( shapes.length > 0 ) output.shapes = shapes;

		}

		output.object = object;

		return output;

		// extract data from the cache hash
		// remove metadata on each item
		// and return as array
		function extractFromCache( cache ) {

			const values = [];
			for ( const key in cache ) {

				const data = cache[ key ];
				delete data.metadata;
				values.push( data );

			}

			return values;

		}

	},

	clone: function ( recursive ) {

		return new this.constructor().copy( this, recursive );

	},

	copy: function ( source, recursive ) {

		if ( recursive === undefined ) recursive = true;

		this.name = source.name;

		this.up.copy( source.up );

		this.position.copy( source.position );
		this.quaternion.copy( source.quaternion );
		this.scale.copy( source.scale );

		this.matrix.copy( source.matrix );
		this.matrixWorld.copy( source.matrixWorld );

		this.matrixAutoUpdate = source.matrixAutoUpdate;
		this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;

		this.layers.mask = source.layers.mask;
		this.visible = source.visible;

		this.castShadow = source.castShadow;
		this.receiveShadow = source.receiveShadow;

		this.frustumCulled = source.frustumCulled;
		this.renderOrder = source.renderOrder;

		this.userData = JSON.parse( JSON.stringify( source.userData ) );

		if ( recursive === true ) {

			for ( let i = 0; i < source.children.length; i ++ ) {

				const child = source.children[ i ];
				this.add( child.clone() );

			}

		}

		return this;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function Scene() {

	Object3D.call( this );

	this.type = 'Scene';

	this.background = null;
	this.environment = null;
	this.fog = null;

	this.overrideMaterial = null;

	this.autoUpdate = true; // checked by the renderer

	if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {

		__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef

	}

}

Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Scene,

	isScene: true,

	copy: function ( source, recursive ) {

		Object3D.prototype.copy.call( this, source, recursive );

		if ( source.background !== null ) this.background = source.background.clone();
		if ( source.environment !== null ) this.environment = source.environment.clone();
		if ( source.fog !== null ) this.fog = source.fog.clone();

		if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();

		this.autoUpdate = source.autoUpdate;
		this.matrixAutoUpdate = source.matrixAutoUpdate;

		return this;

	},

	toJSON: function ( meta ) {

		const data = Object3D.prototype.toJSON.call( this, meta );

		if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
		if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta );
		if ( this.fog !== null ) data.object.fog = this.fog.toJSON();

		return data;

	},

	dispose: function () {

		this.dispatchEvent( { type: 'dispose' } );

	}

} );

const _points = [
	new Vector3(),
	new Vector3(),
	new Vector3(),
	new Vector3(),
	new Vector3(),
	new Vector3(),
	new Vector3(),
	new Vector3()
];

const _vector$1 = new Vector3();

const _box = new Box3();

// triangle centered vertices

const _v0 = new Vector3();
const _v1$2 = new Vector3();
const _v2 = new Vector3();

// triangle edge vectors

const _f0 = new Vector3();
const _f1 = new Vector3();
const _f2 = new Vector3();

const _center = new Vector3();
const _extents = new Vector3();
const _triangleNormal = new Vector3();
const _testAxis = new Vector3();

/**
 * @author bhouston / http://clara.io
 * @author WestLangley / http://github.com/WestLangley
 */

function Box3( min, max ) {

	this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
	this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );

}


Object.assign( Box3.prototype, {

	isBox3: true,

	set: function ( min, max ) {

		this.min.copy( min );
		this.max.copy( max );

		return this;

	},

	setFromArray: function ( array ) {

		let minX = + Infinity;
		let minY = + Infinity;
		let minZ = + Infinity;

		let maxX = - Infinity;
		let maxY = - Infinity;
		let maxZ = - Infinity;

		for ( let i = 0, l = array.length; i < l; i += 3 ) {

			const x = array[ i ];
			const y = array[ i + 1 ];
			const z = array[ i + 2 ];

			if ( x < minX ) minX = x;
			if ( y < minY ) minY = y;
			if ( z < minZ ) minZ = z;

			if ( x > maxX ) maxX = x;
			if ( y > maxY ) maxY = y;
			if ( z > maxZ ) maxZ = z;

		}

		this.min.set( minX, minY, minZ );
		this.max.set( maxX, maxY, maxZ );

		return this;

	},

	setFromBufferAttribute: function ( attribute ) {

		let minX = + Infinity;
		let minY = + Infinity;
		let minZ = + Infinity;

		let maxX = - Infinity;
		let maxY = - Infinity;
		let maxZ = - Infinity;

		for ( let i = 0, l = attribute.count; i < l; i ++ ) {

			const x = attribute.getX( i );
			const y = attribute.getY( i );
			const z = attribute.getZ( i );

			if ( x < minX ) minX = x;
			if ( y < minY ) minY = y;
			if ( z < minZ ) minZ = z;

			if ( x > maxX ) maxX = x;
			if ( y > maxY ) maxY = y;
			if ( z > maxZ ) maxZ = z;

		}

		this.min.set( minX, minY, minZ );
		this.max.set( maxX, maxY, maxZ );

		return this;

	},

	setFromPoints: function ( points ) {

		this.makeEmpty();

		for ( let i = 0, il = points.length; i < il; i ++ ) {

			this.expandByPoint( points[ i ] );

		}

		return this;

	},

	setFromCenterAndSize: function ( center, size ) {

		const halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );

		this.min.copy( center ).sub( halfSize );
		this.max.copy( center ).add( halfSize );

		return this;

	},

	setFromObject: function ( object ) {

		this.makeEmpty();

		return this.expandByObject( object );

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( box ) {

		this.min.copy( box.min );
		this.max.copy( box.max );

		return this;

	},

	makeEmpty: function () {

		this.min.x = this.min.y = this.min.z = + Infinity;
		this.max.x = this.max.y = this.max.z = - Infinity;

		return this;

	},

	isEmpty: function () {

		// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes

		return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );

	},

	getCenter: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Box3: .getCenter() target is now required' );
			target = new Vector3();

		}

		return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );

	},

	getSize: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Box3: .getSize() target is now required' );
			target = new Vector3();

		}

		return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );

	},

	expandByPoint: function ( point ) {

		this.min.min( point );
		this.max.max( point );

		return this;

	},

	expandByVector: function ( vector ) {

		this.min.sub( vector );
		this.max.add( vector );

		return this;

	},

	expandByScalar: function ( scalar ) {

		this.min.addScalar( - scalar );
		this.max.addScalar( scalar );

		return this;

	},

	expandByObject: function ( object ) {

		// Computes the world-axis-aligned bounding box of an object (including its children),
		// accounting for both the object's, and children's, world transforms

		object.updateWorldMatrix( false, false );

		const geometry = object.geometry;

		if ( geometry !== undefined ) {

			if ( geometry.boundingBox === null ) {

				geometry.computeBoundingBox();

			}

			_box.copy( geometry.boundingBox );
			_box.applyMatrix4( object.matrixWorld );

			this.union( _box );

		}

		const children = object.children;

		for ( let i = 0, l = children.length; i < l; i ++ ) {

			this.expandByObject( children[ i ] );

		}

		return this;

	},

	containsPoint: function ( point ) {

		return point.x < this.min.x || point.x > this.max.x ||
			point.y < this.min.y || point.y > this.max.y ||
			point.z < this.min.z || point.z > this.max.z ? false : true;

	},

	containsBox: function ( box ) {

		return this.min.x <= box.min.x && box.max.x <= this.max.x &&
			this.min.y <= box.min.y && box.max.y <= this.max.y &&
			this.min.z <= box.min.z && box.max.z <= this.max.z;

	},

	getParameter: function ( point, target ) {

		// This can potentially have a divide by zero if the box
		// has a size dimension of 0.

		if ( target === undefined ) {

			console.warn( 'THREE.Box3: .getParameter() target is now required' );
			target = new Vector3();

		}

		return target.set(
			( point.x - this.min.x ) / ( this.max.x - this.min.x ),
			( point.y - this.min.y ) / ( this.max.y - this.min.y ),
			( point.z - this.min.z ) / ( this.max.z - this.min.z )
		);

	},

	intersectsBox: function ( box ) {

		// using 6 splitting planes to rule out intersections.
		return box.max.x < this.min.x || box.min.x > this.max.x ||
			box.max.y < this.min.y || box.min.y > this.max.y ||
			box.max.z < this.min.z || box.min.z > this.max.z ? false : true;

	},

	intersectsSphere: function ( sphere ) {

		// Find the point on the AABB closest to the sphere center.
		this.clampPoint( sphere.center, _vector$1 );

		// If that point is inside the sphere, the AABB and sphere intersect.
		return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );

	},

	intersectsPlane: function ( plane ) {

		// We compute the minimum and maximum dot product values. If those values
		// are on the same side (back or front) of the plane, then there is no intersection.

		let min, max;

		if ( plane.normal.x > 0 ) {

			min = plane.normal.x * this.min.x;
			max = plane.normal.x * this.max.x;

		} else {

			min = plane.normal.x * this.max.x;
			max = plane.normal.x * this.min.x;

		}

		if ( plane.normal.y > 0 ) {

			min += plane.normal.y * this.min.y;
			max += plane.normal.y * this.max.y;

		} else {

			min += plane.normal.y * this.max.y;
			max += plane.normal.y * this.min.y;

		}

		if ( plane.normal.z > 0 ) {

			min += plane.normal.z * this.min.z;
			max += plane.normal.z * this.max.z;

		} else {

			min += plane.normal.z * this.max.z;
			max += plane.normal.z * this.min.z;

		}

		return ( min <= - plane.constant && max >= - plane.constant );

	},

	intersectsTriangle: function ( triangle ) {

		if ( this.isEmpty() ) {

			return false;

		}

		// compute box center and extents
		this.getCenter( _center );
		_extents.subVectors( this.max, _center );

		// translate triangle to aabb origin
		_v0.subVectors( triangle.a, _center );
		_v1$2.subVectors( triangle.b, _center );
		_v2.subVectors( triangle.c, _center );

		// compute edge vectors for triangle
		_f0.subVectors( _v1$2, _v0 );
		_f1.subVectors( _v2, _v1$2 );
		_f2.subVectors( _v0, _v2 );

		// test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
		// make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
		// axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
		let axes = [
			0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
			_f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
			- _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
		];
		if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {

			return false;

		}

		// test 3 face normals from the aabb
		axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
		if ( ! satForAxes( axes, _v0, _v1$2, _v2, _extents ) ) {

			return false;

		}

		// finally testing the face normal of the triangle
		// use already existing triangle edge vectors here
		_triangleNormal.crossVectors( _f0, _f1 );
		axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];

		return satForAxes( axes, _v0, _v1$2, _v2, _extents );

	},

	clampPoint: function ( point, target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Box3: .clampPoint() target is now required' );
			target = new Vector3();

		}

		return target.copy( point ).clamp( this.min, this.max );

	},

	distanceToPoint: function ( point ) {

		const clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );

		return clampedPoint.sub( point ).length();

	},

	getBoundingSphere: function ( target ) {

		if ( target === undefined ) {

			console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
			//target = new Sphere(); // removed to avoid cyclic dependency

		}

		this.getCenter( target.center );

		target.radius = this.getSize( _vector$1 ).length() * 0.5;

		return target;

	},

	intersect: function ( box ) {

		this.min.max( box.min );
		this.max.min( box.max );

		// ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
		if ( this.isEmpty() ) this.makeEmpty();

		return this;

	},

	union: function ( box ) {

		this.min.min( box.min );
		this.max.max( box.max );

		return this;

	},

	applyMatrix4: function ( matrix ) {

		// transform of empty box is an empty box.
		if ( this.isEmpty() ) return this;

		// NOTE: I am using a binary pattern to specify all 2^3 combinations below
		_points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
		_points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
		_points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
		_points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
		_points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
		_points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
		_points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
		_points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111

		this.setFromPoints( _points );

		return this;

	},

	translate: function ( offset ) {

		this.min.add( offset );
		this.max.add( offset );

		return this;

	},

	equals: function ( box ) {

		return box.min.equals( this.min ) && box.max.equals( this.max );

	}

} );

function satForAxes( axes, v0, v1, v2, extents ) {

	for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {

		_testAxis.fromArray( axes, i );
		// project the aabb onto the seperating axis
		const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
		// project all 3 vertices of the triangle onto the seperating axis
		const p0 = v0.dot( _testAxis );
		const p1 = v1.dot( _testAxis );
		const p2 = v2.dot( _testAxis );
		// actual test, basically see if either of the most extreme of the triangle points intersects r
		if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {

			// points of the projected triangle are outside the projected half-length of the aabb
			// the axis is seperating and we can exit
			return false;

		}

	}

	return true;

}

const _box$1 = new Box3();

/**
 * @author bhouston / http://clara.io
 * @author mrdoob / http://mrdoob.com/
 */

function Sphere( center, radius ) {

	this.center = ( center !== undefined ) ? center : new Vector3();
	this.radius = ( radius !== undefined ) ? radius : - 1;

}

Object.assign( Sphere.prototype, {

	set: function ( center, radius ) {

		this.center.copy( center );
		this.radius = radius;

		return this;

	},

	setFromPoints: function ( points, optionalCenter ) {

		const center = this.center;

		if ( optionalCenter !== undefined ) {

			center.copy( optionalCenter );

		} else {

			_box$1.setFromPoints( points ).getCenter( center );

		}

		let maxRadiusSq = 0;

		for ( let i = 0, il = points.length; i < il; i ++ ) {

			maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );

		}

		this.radius = Math.sqrt( maxRadiusSq );

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( sphere ) {

		this.center.copy( sphere.center );
		this.radius = sphere.radius;

		return this;

	},

	isEmpty: function () {

		return ( this.radius < 0 );

	},

	makeEmpty: function () {

		this.center.set( 0, 0, 0 );
		this.radius = - 1;

		return this;

	},

	containsPoint: function ( point ) {

		return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );

	},

	distanceToPoint: function ( point ) {

		return ( point.distanceTo( this.center ) - this.radius );

	},

	intersectsSphere: function ( sphere ) {

		const radiusSum = this.radius + sphere.radius;

		return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );

	},

	intersectsBox: function ( box ) {

		return box.intersectsSphere( this );

	},

	intersectsPlane: function ( plane ) {

		return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;

	},

	clampPoint: function ( point, target ) {

		const deltaLengthSq = this.center.distanceToSquared( point );

		if ( target === undefined ) {

			console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
			target = new Vector3();

		}

		target.copy( point );

		if ( deltaLengthSq > ( this.radius * this.radius ) ) {

			target.sub( this.center ).normalize();
			target.multiplyScalar( this.radius ).add( this.center );

		}

		return target;

	},

	getBoundingBox: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
			target = new Box3();

		}

		if ( this.isEmpty() ) {

			// Empty sphere produces empty bounding box
			target.makeEmpty();
			return target;

		}

		target.set( this.center, this.center );
		target.expandByScalar( this.radius );

		return target;

	},

	applyMatrix4: function ( matrix ) {

		this.center.applyMatrix4( matrix );
		this.radius = this.radius * matrix.getMaxScaleOnAxis();

		return this;

	},

	translate: function ( offset ) {

		this.center.add( offset );

		return this;

	},

	equals: function ( sphere ) {

		return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );

	}

} );

const _vector$2 = new Vector3();
const _segCenter = new Vector3();
const _segDir = new Vector3();
const _diff = new Vector3();

const _edge1 = new Vector3();
const _edge2 = new Vector3();
const _normal = new Vector3();

/**
 * @author bhouston / http://clara.io
 */

function Ray( origin, direction ) {

	this.origin = ( origin !== undefined ) ? origin : new Vector3();
	this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );

}

Object.assign( Ray.prototype, {

	set: function ( origin, direction ) {

		this.origin.copy( origin );
		this.direction.copy( direction );

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( ray ) {

		this.origin.copy( ray.origin );
		this.direction.copy( ray.direction );

		return this;

	},

	at: function ( t, target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Ray: .at() target is now required' );
			target = new Vector3();

		}

		return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );

	},

	lookAt: function ( v ) {

		this.direction.copy( v ).sub( this.origin ).normalize();

		return this;

	},

	recast: function ( t ) {

		this.origin.copy( this.at( t, _vector$2 ) );

		return this;

	},

	closestPointToPoint: function ( point, target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
			target = new Vector3();

		}

		target.subVectors( point, this.origin );

		const directionDistance = target.dot( this.direction );

		if ( directionDistance < 0 ) {

			return target.copy( this.origin );

		}

		return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );

	},

	distanceToPoint: function ( point ) {

		return Math.sqrt( this.distanceSqToPoint( point ) );

	},

	distanceSqToPoint: function ( point ) {

		const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );

		// point behind the ray

		if ( directionDistance < 0 ) {

			return this.origin.distanceToSquared( point );

		}

		_vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );

		return _vector$2.distanceToSquared( point );

	},

	distanceSqToSegment: function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {

		// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
		// It returns the min distance between the ray and the segment
		// defined by v0 and v1
		// It can also set two optional targets :
		// - The closest point on the ray
		// - The closest point on the segment

		_segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
		_segDir.copy( v1 ).sub( v0 ).normalize();
		_diff.copy( this.origin ).sub( _segCenter );

		const segExtent = v0.distanceTo( v1 ) * 0.5;
		const a01 = - this.direction.dot( _segDir );
		const b0 = _diff.dot( this.direction );
		const b1 = - _diff.dot( _segDir );
		const c = _diff.lengthSq();
		const det = Math.abs( 1 - a01 * a01 );
		let s0, s1, sqrDist, extDet;

		if ( det > 0 ) {

			// The ray and segment are not parallel.

			s0 = a01 * b1 - b0;
			s1 = a01 * b0 - b1;
			extDet = segExtent * det;

			if ( s0 >= 0 ) {

				if ( s1 >= - extDet ) {

					if ( s1 <= extDet ) {

						// region 0
						// Minimum at interior points of ray and segment.

						const invDet = 1 / det;
						s0 *= invDet;
						s1 *= invDet;
						sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;

					} else {

						// region 1

						s1 = segExtent;
						s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
						sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

					}

				} else {

					// region 5

					s1 = - segExtent;
					s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
					sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

				}

			} else {

				if ( s1 <= - extDet ) {

					// region 4

					s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
					s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
					sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

				} else if ( s1 <= extDet ) {

					// region 3

					s0 = 0;
					s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
					sqrDist = s1 * ( s1 + 2 * b1 ) + c;

				} else {

					// region 2

					s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
					s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
					sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

				}

			}

		} else {

			// Ray and segment are parallel.

			s1 = ( a01 > 0 ) ? - segExtent : segExtent;
			s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
			sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;

		}

		if ( optionalPointOnRay ) {

			optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );

		}

		if ( optionalPointOnSegment ) {

			optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );

		}

		return sqrDist;

	},

	intersectSphere: function ( sphere, target ) {

		_vector$2.subVectors( sphere.center, this.origin );
		const tca = _vector$2.dot( this.direction );
		const d2 = _vector$2.dot( _vector$2 ) - tca * tca;
		const radius2 = sphere.radius * sphere.radius;

		if ( d2 > radius2 ) return null;

		const thc = Math.sqrt( radius2 - d2 );

		// t0 = first intersect point - entrance on front of sphere
		const t0 = tca - thc;

		// t1 = second intersect point - exit point on back of sphere
		const t1 = tca + thc;

		// test to see if both t0 and t1 are behind the ray - if so, return null
		if ( t0 < 0 && t1 < 0 ) return null;

		// test to see if t0 is behind the ray:
		// if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
		// in order to always return an intersect point that is in front of the ray.
		if ( t0 < 0 ) return this.at( t1, target );

		// else t0 is in front of the ray, so return the first collision point scaled by t0
		return this.at( t0, target );

	},

	intersectsSphere: function ( sphere ) {

		return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );

	},

	distanceToPlane: function ( plane ) {

		const denominator = plane.normal.dot( this.direction );

		if ( denominator === 0 ) {

			// line is coplanar, return origin
			if ( plane.distanceToPoint( this.origin ) === 0 ) {

				return 0;

			}

			// Null is preferable to undefined since undefined means.... it is undefined

			return null;

		}

		const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;

		// Return if the ray never intersects the plane

		return t >= 0 ? t : null;

	},

	intersectPlane: function ( plane, target ) {

		const t = this.distanceToPlane( plane );

		if ( t === null ) {

			return null;

		}

		return this.at( t, target );

	},

	intersectsPlane: function ( plane ) {

		// check if the ray lies on the plane first

		const distToPoint = plane.distanceToPoint( this.origin );

		if ( distToPoint === 0 ) {

			return true;

		}

		const denominator = plane.normal.dot( this.direction );

		if ( denominator * distToPoint < 0 ) {

			return true;

		}

		// ray origin is behind the plane (and is pointing behind it)

		return false;

	},

	intersectBox: function ( box, target ) {

		let tmin, tmax, tymin, tymax, tzmin, tzmax;

		const invdirx = 1 / this.direction.x,
			invdiry = 1 / this.direction.y,
			invdirz = 1 / this.direction.z;

		const origin = this.origin;

		if ( invdirx >= 0 ) {

			tmin = ( box.min.x - origin.x ) * invdirx;
			tmax = ( box.max.x - origin.x ) * invdirx;

		} else {

			tmin = ( box.max.x - origin.x ) * invdirx;
			tmax = ( box.min.x - origin.x ) * invdirx;

		}

		if ( invdiry >= 0 ) {

			tymin = ( box.min.y - origin.y ) * invdiry;
			tymax = ( box.max.y - origin.y ) * invdiry;

		} else {

			tymin = ( box.max.y - origin.y ) * invdiry;
			tymax = ( box.min.y - origin.y ) * invdiry;

		}

		if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;

		// These lines also handle the case where tmin or tmax is NaN
		// (result of 0 * Infinity). x !== x returns true if x is NaN

		if ( tymin > tmin || tmin !== tmin ) tmin = tymin;

		if ( tymax < tmax || tmax !== tmax ) tmax = tymax;

		if ( invdirz >= 0 ) {

			tzmin = ( box.min.z - origin.z ) * invdirz;
			tzmax = ( box.max.z - origin.z ) * invdirz;

		} else {

			tzmin = ( box.max.z - origin.z ) * invdirz;
			tzmax = ( box.min.z - origin.z ) * invdirz;

		}

		if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;

		if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;

		if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;

		//return point closest to the ray (positive side)

		if ( tmax < 0 ) return null;

		return this.at( tmin >= 0 ? tmin : tmax, target );

	},

	intersectsBox: function ( box ) {

		return this.intersectBox( box, _vector$2 ) !== null;

	},

	intersectTriangle: function ( a, b, c, backfaceCulling, target ) {

		// Compute the offset origin, edges, and normal.

		// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h

		_edge1.subVectors( b, a );
		_edge2.subVectors( c, a );
		_normal.crossVectors( _edge1, _edge2 );

		// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
		// E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
		//   |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
		//   |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
		//   |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
		let DdN = this.direction.dot( _normal );
		let sign;

		if ( DdN > 0 ) {

			if ( backfaceCulling ) return null;
			sign = 1;

		} else if ( DdN < 0 ) {

			sign = - 1;
			DdN = - DdN;

		} else {

			return null;

		}

		_diff.subVectors( this.origin, a );
		const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );

		// b1 < 0, no intersection
		if ( DdQxE2 < 0 ) {

			return null;

		}

		const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );

		// b2 < 0, no intersection
		if ( DdE1xQ < 0 ) {

			return null;

		}

		// b1+b2 > 1, no intersection
		if ( DdQxE2 + DdE1xQ > DdN ) {

			return null;

		}

		// Line intersects triangle, check if ray does.
		const QdN = - sign * _diff.dot( _normal );

		// t < 0, no intersection
		if ( QdN < 0 ) {

			return null;

		}

		// Ray intersects triangle.
		return this.at( QdN / DdN, target );

	},

	applyMatrix4: function ( matrix4 ) {

		this.origin.applyMatrix4( matrix4 );
		this.direction.transformDirection( matrix4 );

		return this;

	},

	equals: function ( ray ) {

		return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );

	}

} );

/**
 * @author bhouston / http://clara.io
 */

const _vector1 = new Vector3();
const _vector2 = new Vector3();
const _normalMatrix = new Matrix3();

function Plane( normal, constant ) {

	// normal is assumed to be normalized

	this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
	this.constant = ( constant !== undefined ) ? constant : 0;

}

Object.assign( Plane.prototype, {

	isPlane: true,

	set: function ( normal, constant ) {

		this.normal.copy( normal );
		this.constant = constant;

		return this;

	},

	setComponents: function ( x, y, z, w ) {

		this.normal.set( x, y, z );
		this.constant = w;

		return this;

	},

	setFromNormalAndCoplanarPoint: function ( normal, point ) {

		this.normal.copy( normal );
		this.constant = - point.dot( this.normal );

		return this;

	},

	setFromCoplanarPoints: function ( a, b, c ) {

		const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();

		// Q: should an error be thrown if normal is zero (e.g. degenerate plane)?

		this.setFromNormalAndCoplanarPoint( normal, a );

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( plane ) {

		this.normal.copy( plane.normal );
		this.constant = plane.constant;

		return this;

	},

	normalize: function () {

		// Note: will lead to a divide by zero if the plane is invalid.

		const inverseNormalLength = 1.0 / this.normal.length();
		this.normal.multiplyScalar( inverseNormalLength );
		this.constant *= inverseNormalLength;

		return this;

	},

	negate: function () {

		this.constant *= - 1;
		this.normal.negate();

		return this;

	},

	distanceToPoint: function ( point ) {

		return this.normal.dot( point ) + this.constant;

	},

	distanceToSphere: function ( sphere ) {

		return this.distanceToPoint( sphere.center ) - sphere.radius;

	},

	projectPoint: function ( point, target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Plane: .projectPoint() target is now required' );
			target = new Vector3();

		}

		return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );

	},

	intersectLine: function ( line, target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Plane: .intersectLine() target is now required' );
			target = new Vector3();

		}

		const direction = line.delta( _vector1 );

		const denominator = this.normal.dot( direction );

		if ( denominator === 0 ) {

			// line is coplanar, return origin
			if ( this.distanceToPoint( line.start ) === 0 ) {

				return target.copy( line.start );

			}

			// Unsure if this is the correct method to handle this case.
			return undefined;

		}

		const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;

		if ( t < 0 || t > 1 ) {

			return undefined;

		}

		return target.copy( direction ).multiplyScalar( t ).add( line.start );

	},

	intersectsLine: function ( line ) {

		// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.

		const startSign = this.distanceToPoint( line.start );
		const endSign = this.distanceToPoint( line.end );

		return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );

	},

	intersectsBox: function ( box ) {

		return box.intersectsPlane( this );

	},

	intersectsSphere: function ( sphere ) {

		return sphere.intersectsPlane( this );

	},

	coplanarPoint: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
			target = new Vector3();

		}

		return target.copy( this.normal ).multiplyScalar( - this.constant );

	},

	applyMatrix4: function ( matrix, optionalNormalMatrix ) {

		const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );

		const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );

		const normal = this.normal.applyMatrix3( normalMatrix ).normalize();

		this.constant = - referencePoint.dot( normal );

		return this;

	},

	translate: function ( offset ) {

		this.constant -= offset.dot( this.normal );

		return this;

	},

	equals: function ( plane ) {

		return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );

	}

} );

/**
 * @author bhouston / http://clara.io
 * @author mrdoob / http://mrdoob.com/
 */

const _v0$1 = new Vector3();
const _v1$3 = new Vector3();
const _v2$1 = new Vector3();
const _v3 = new Vector3();

const _vab = new Vector3();
const _vac = new Vector3();
const _vbc = new Vector3();
const _vap = new Vector3();
const _vbp = new Vector3();
const _vcp = new Vector3();

function Triangle( a, b, c ) {

	this.a = ( a !== undefined ) ? a : new Vector3();
	this.b = ( b !== undefined ) ? b : new Vector3();
	this.c = ( c !== undefined ) ? c : new Vector3();

}

Object.assign( Triangle, {

	getNormal: function ( a, b, c, target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Triangle: .getNormal() target is now required' );
			target = new Vector3();

		}

		target.subVectors( c, b );
		_v0$1.subVectors( a, b );
		target.cross( _v0$1 );

		const targetLengthSq = target.lengthSq();
		if ( targetLengthSq > 0 ) {

			return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );

		}

		return target.set( 0, 0, 0 );

	},

	// static/instance method to calculate barycentric coordinates
	// based on: http://www.blackpawn.com/texts/pointinpoly/default.html
	getBarycoord: function ( point, a, b, c, target ) {

		_v0$1.subVectors( c, a );
		_v1$3.subVectors( b, a );
		_v2$1.subVectors( point, a );

		const dot00 = _v0$1.dot( _v0$1 );
		const dot01 = _v0$1.dot( _v1$3 );
		const dot02 = _v0$1.dot( _v2$1 );
		const dot11 = _v1$3.dot( _v1$3 );
		const dot12 = _v1$3.dot( _v2$1 );

		const denom = ( dot00 * dot11 - dot01 * dot01 );

		if ( target === undefined ) {

			console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
			target = new Vector3();

		}

		// collinear or singular triangle
		if ( denom === 0 ) {

			// arbitrary location outside of triangle?
			// not sure if this is the best idea, maybe should be returning undefined
			return target.set( - 2, - 1, - 1 );

		}

		const invDenom = 1 / denom;
		const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
		const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;

		// barycentric coordinates must always sum to 1
		return target.set( 1 - u - v, v, u );

	},

	containsPoint: function ( point, a, b, c ) {

		Triangle.getBarycoord( point, a, b, c, _v3 );

		return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );

	},

	getUV: function ( point, p1, p2, p3, uv1, uv2, uv3, target ) {

		this.getBarycoord( point, p1, p2, p3, _v3 );

		target.set( 0, 0 );
		target.addScaledVector( uv1, _v3.x );
		target.addScaledVector( uv2, _v3.y );
		target.addScaledVector( uv3, _v3.z );

		return target;

	},

	isFrontFacing: function ( a, b, c, direction ) {

		_v0$1.subVectors( c, b );
		_v1$3.subVectors( a, b );

		// strictly front facing
		return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;

	}

} );

Object.assign( Triangle.prototype, {

	set: function ( a, b, c ) {

		this.a.copy( a );
		this.b.copy( b );
		this.c.copy( c );

		return this;

	},

	setFromPointsAndIndices: function ( points, i0, i1, i2 ) {

		this.a.copy( points[ i0 ] );
		this.b.copy( points[ i1 ] );
		this.c.copy( points[ i2 ] );

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( triangle ) {

		this.a.copy( triangle.a );
		this.b.copy( triangle.b );
		this.c.copy( triangle.c );

		return this;

	},

	getArea: function () {

		_v0$1.subVectors( this.c, this.b );
		_v1$3.subVectors( this.a, this.b );

		return _v0$1.cross( _v1$3 ).length() * 0.5;

	},

	getMidpoint: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
			target = new Vector3();

		}

		return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );

	},

	getNormal: function ( target ) {

		return Triangle.getNormal( this.a, this.b, this.c, target );

	},

	getPlane: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Triangle: .getPlane() target is now required' );
			target = new Plane();

		}

		return target.setFromCoplanarPoints( this.a, this.b, this.c );

	},

	getBarycoord: function ( point, target ) {

		return Triangle.getBarycoord( point, this.a, this.b, this.c, target );

	},

	getUV: function ( point, uv1, uv2, uv3, target ) {

		return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );

	},

	containsPoint: function ( point ) {

		return Triangle.containsPoint( point, this.a, this.b, this.c );

	},

	isFrontFacing: function ( direction ) {

		return Triangle.isFrontFacing( this.a, this.b, this.c, direction );

	},

	intersectsBox: function ( box ) {

		return box.intersectsTriangle( this );

	},

	closestPointToPoint: function ( p, target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
			target = new Vector3();

		}

		const a = this.a, b = this.b, c = this.c;
		let v, w;

		// algorithm thanks to Real-Time Collision Detection by Christer Ericson,
		// published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
		// under the accompanying license; see chapter 5.1.5 for detailed explanation.
		// basically, we're distinguishing which of the voronoi regions of the triangle
		// the point lies in with the minimum amount of redundant computation.

		_vab.subVectors( b, a );
		_vac.subVectors( c, a );
		_vap.subVectors( p, a );
		const d1 = _vab.dot( _vap );
		const d2 = _vac.dot( _vap );
		if ( d1 <= 0 && d2 <= 0 ) {

			// vertex region of A; barycentric coords (1, 0, 0)
			return target.copy( a );

		}

		_vbp.subVectors( p, b );
		const d3 = _vab.dot( _vbp );
		const d4 = _vac.dot( _vbp );
		if ( d3 >= 0 && d4 <= d3 ) {

			// vertex region of B; barycentric coords (0, 1, 0)
			return target.copy( b );

		}

		const vc = d1 * d4 - d3 * d2;
		if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {

			v = d1 / ( d1 - d3 );
			// edge region of AB; barycentric coords (1-v, v, 0)
			return target.copy( a ).addScaledVector( _vab, v );

		}

		_vcp.subVectors( p, c );
		const d5 = _vab.dot( _vcp );
		const d6 = _vac.dot( _vcp );
		if ( d6 >= 0 && d5 <= d6 ) {

			// vertex region of C; barycentric coords (0, 0, 1)
			return target.copy( c );

		}

		const vb = d5 * d2 - d1 * d6;
		if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {

			w = d2 / ( d2 - d6 );
			// edge region of AC; barycentric coords (1-w, 0, w)
			return target.copy( a ).addScaledVector( _vac, w );

		}

		const va = d3 * d6 - d5 * d4;
		if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {

			_vbc.subVectors( c, b );
			w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
			// edge region of BC; barycentric coords (0, 1-w, w)
			return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC

		}

		// face region
		const denom = 1 / ( va + vb + vc );
		// u = va * denom
		v = vb * denom;
		w = vc * denom;

		return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );

	},

	equals: function ( triangle ) {

		return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
	'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
	'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
	'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
	'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
	'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
	'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
	'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
	'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
	'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
	'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
	'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
	'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
	'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
	'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
	'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
	'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
	'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
	'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
	'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
	'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
	'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
	'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
	'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };

const _hslA = { h: 0, s: 0, l: 0 };
const _hslB = { h: 0, s: 0, l: 0 };

function Color( r, g, b ) {

	if ( g === undefined && b === undefined ) {

		// r is THREE.Color, hex or string
		return this.set( r );

	}

	return this.setRGB( r, g, b );

}

function hue2rgb( p, q, t ) {

	if ( t < 0 ) t += 1;
	if ( t > 1 ) t -= 1;
	if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
	if ( t < 1 / 2 ) return q;
	if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
	return p;

}

function SRGBToLinear( c ) {

	return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );

}

function LinearToSRGB( c ) {

	return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;

}

Object.assign( Color.prototype, {

	isColor: true,

	r: 1, g: 1, b: 1,

	set: function ( value ) {

		if ( value && value.isColor ) {

			this.copy( value );

		} else if ( typeof value === 'number' ) {

			this.setHex( value );

		} else if ( typeof value === 'string' ) {

			this.setStyle( value );

		}

		return this;

	},

	setScalar: function ( scalar ) {

		this.r = scalar;
		this.g = scalar;
		this.b = scalar;

		return this;

	},

	setHex: function ( hex ) {

		hex = Math.floor( hex );

		this.r = ( hex >> 16 & 255 ) / 255;
		this.g = ( hex >> 8 & 255 ) / 255;
		this.b = ( hex & 255 ) / 255;

		return this;

	},

	setRGB: function ( r, g, b ) {

		this.r = r;
		this.g = g;
		this.b = b;

		return this;

	},

	setHSL: function ( h, s, l ) {

		// h,s,l ranges are in 0.0 - 1.0
		h = MathUtils.euclideanModulo( h, 1 );
		s = MathUtils.clamp( s, 0, 1 );
		l = MathUtils.clamp( l, 0, 1 );

		if ( s === 0 ) {

			this.r = this.g = this.b = l;

		} else {

			const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
			const q = ( 2 * l ) - p;

			this.r = hue2rgb( q, p, h + 1 / 3 );
			this.g = hue2rgb( q, p, h );
			this.b = hue2rgb( q, p, h - 1 / 3 );

		}

		return this;

	},

	setStyle: function ( style ) {

		function handleAlpha( string ) {

			if ( string === undefined ) return;

			if ( parseFloat( string ) < 1 ) {

				console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );

			}

		}


		let m;

		if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {

			// rgb / hsl

			let color;
			const name = m[ 1 ];
			const components = m[ 2 ];

			switch ( name ) {

				case 'rgb':
				case 'rgba':

					if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {

						// rgb(255,0,0) rgba(255,0,0,0.5)
						this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
						this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
						this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;

						handleAlpha( color[ 5 ] );

						return this;

					}

					if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {

						// rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
						this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
						this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
						this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;

						handleAlpha( color[ 5 ] );

						return this;

					}

					break;

				case 'hsl':
				case 'hsla':

					if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {

						// hsl(120,50%,50%) hsla(120,50%,50%,0.5)
						const h = parseFloat( color[ 1 ] ) / 360;
						const s = parseInt( color[ 2 ], 10 ) / 100;
						const l = parseInt( color[ 3 ], 10 ) / 100;

						handleAlpha( color[ 5 ] );

						return this.setHSL( h, s, l );

					}

					break;

			}

		} else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {

			// hex color

			const hex = m[ 1 ];
			const size = hex.length;

			if ( size === 3 ) {

				// #ff0
				this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
				this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
				this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;

				return this;

			} else if ( size === 6 ) {

				// #ff0000
				this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
				this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
				this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;

				return this;

			}

		}

		if ( style && style.length > 0 ) {

			return this.setColorName( style );

		}

		return this;

	},

	setColorName: function ( style ) {

		// color keywords
		const hex = _colorKeywords[ style ];

		if ( hex !== undefined ) {

			// red
			this.setHex( hex );

		} else {

			// unknown color
			console.warn( 'THREE.Color: Unknown color ' + style );

		}

		return this;

	},

	clone: function () {

		return new this.constructor( this.r, this.g, this.b );

	},

	copy: function ( color ) {

		this.r = color.r;
		this.g = color.g;
		this.b = color.b;

		return this;

	},

	copyGammaToLinear: function ( color, gammaFactor ) {

		if ( gammaFactor === undefined ) gammaFactor = 2.0;

		this.r = Math.pow( color.r, gammaFactor );
		this.g = Math.pow( color.g, gammaFactor );
		this.b = Math.pow( color.b, gammaFactor );

		return this;

	},

	copyLinearToGamma: function ( color, gammaFactor ) {

		if ( gammaFactor === undefined ) gammaFactor = 2.0;

		const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;

		this.r = Math.pow( color.r, safeInverse );
		this.g = Math.pow( color.g, safeInverse );
		this.b = Math.pow( color.b, safeInverse );

		return this;

	},

	convertGammaToLinear: function ( gammaFactor ) {

		this.copyGammaToLinear( this, gammaFactor );

		return this;

	},

	convertLinearToGamma: function ( gammaFactor ) {

		this.copyLinearToGamma( this, gammaFactor );

		return this;

	},

	copySRGBToLinear: function ( color ) {

		this.r = SRGBToLinear( color.r );
		this.g = SRGBToLinear( color.g );
		this.b = SRGBToLinear( color.b );

		return this;

	},

	copyLinearToSRGB: function ( color ) {

		this.r = LinearToSRGB( color.r );
		this.g = LinearToSRGB( color.g );
		this.b = LinearToSRGB( color.b );

		return this;

	},

	convertSRGBToLinear: function () {

		this.copySRGBToLinear( this );

		return this;

	},

	convertLinearToSRGB: function () {

		this.copyLinearToSRGB( this );

		return this;

	},

	getHex: function () {

		return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;

	},

	getHexString: function () {

		return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );

	},

	getHSL: function ( target ) {

		// h,s,l ranges are in 0.0 - 1.0

		if ( target === undefined ) {

			console.warn( 'THREE.Color: .getHSL() target is now required' );
			target = { h: 0, s: 0, l: 0 };

		}

		const r = this.r, g = this.g, b = this.b;

		const max = Math.max( r, g, b );
		const min = Math.min( r, g, b );

		let hue, saturation;
		const lightness = ( min + max ) / 2.0;

		if ( min === max ) {

			hue = 0;
			saturation = 0;

		} else {

			const delta = max - min;

			saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );

			switch ( max ) {

				case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
				case g: hue = ( b - r ) / delta + 2; break;
				case b: hue = ( r - g ) / delta + 4; break;

			}

			hue /= 6;

		}

		target.h = hue;
		target.s = saturation;
		target.l = lightness;

		return target;

	},

	getStyle: function () {

		return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';

	},

	offsetHSL: function ( h, s, l ) {

		this.getHSL( _hslA );

		_hslA.h += h; _hslA.s += s; _hslA.l += l;

		this.setHSL( _hslA.h, _hslA.s, _hslA.l );

		return this;

	},

	add: function ( color ) {

		this.r += color.r;
		this.g += color.g;
		this.b += color.b;

		return this;

	},

	addColors: function ( color1, color2 ) {

		this.r = color1.r + color2.r;
		this.g = color1.g + color2.g;
		this.b = color1.b + color2.b;

		return this;

	},

	addScalar: function ( s ) {

		this.r += s;
		this.g += s;
		this.b += s;

		return this;

	},

	sub: function ( color ) {

		this.r = Math.max( 0, this.r - color.r );
		this.g = Math.max( 0, this.g - color.g );
		this.b = Math.max( 0, this.b - color.b );

		return this;

	},

	multiply: function ( color ) {

		this.r *= color.r;
		this.g *= color.g;
		this.b *= color.b;

		return this;

	},

	multiplyScalar: function ( s ) {

		this.r *= s;
		this.g *= s;
		this.b *= s;

		return this;

	},

	lerp: function ( color, alpha ) {

		this.r += ( color.r - this.r ) * alpha;
		this.g += ( color.g - this.g ) * alpha;
		this.b += ( color.b - this.b ) * alpha;

		return this;

	},

	lerpHSL: function ( color, alpha ) {

		this.getHSL( _hslA );
		color.getHSL( _hslB );

		const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
		const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
		const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );

		this.setHSL( h, s, l );

		return this;

	},

	equals: function ( c ) {

		return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		this.r = array[ offset ];
		this.g = array[ offset + 1 ];
		this.b = array[ offset + 2 ];

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		array[ offset ] = this.r;
		array[ offset + 1 ] = this.g;
		array[ offset + 2 ] = this.b;

		return array;

	},

	fromBufferAttribute: function ( attribute, index ) {

		this.r = attribute.getX( index );
		this.g = attribute.getY( index );
		this.b = attribute.getZ( index );

		if ( attribute.normalized === true ) {

			// assuming Uint8Array

			this.r /= 255;
			this.g /= 255;
			this.b /= 255;

		}

		return this;

	},

	toJSON: function () {

		return this.getHex();

	}

} );

Color.NAMES = _colorKeywords;

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

function Face3( a, b, c, normal, color, materialIndex ) {

	this.a = a;
	this.b = b;
	this.c = c;

	this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
	this.vertexNormals = Array.isArray( normal ) ? normal : [];

	this.color = ( color && color.isColor ) ? color : new Color();
	this.vertexColors = Array.isArray( color ) ? color : [];

	this.materialIndex = materialIndex !== undefined ? materialIndex : 0;

}

Object.assign( Face3.prototype, {

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( source ) {

		this.a = source.a;
		this.b = source.b;
		this.c = source.c;

		this.normal.copy( source.normal );
		this.color.copy( source.color );

		this.materialIndex = source.materialIndex;

		for ( let i = 0, il = source.vertexNormals.length; i < il; i ++ ) {

			this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();

		}

		for ( let i = 0, il = source.vertexColors.length; i < il; i ++ ) {

			this.vertexColors[ i ] = source.vertexColors[ i ].clone();

		}

		return this;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

let materialId = 0;

function Material() {

	Object.defineProperty( this, 'id', { value: materialId ++ } );

	this.uuid = MathUtils.generateUUID();

	this.name = '';
	this.type = 'Material';

	this.fog = true;

	this.blending = NormalBlending;
	this.side = FrontSide;
	this.flatShading = false;
	this.vertexColors = false;

	this.opacity = 1;
	this.transparent = false;

	this.blendSrc = SrcAlphaFactor;
	this.blendDst = OneMinusSrcAlphaFactor;
	this.blendEquation = AddEquation;
	this.blendSrcAlpha = null;
	this.blendDstAlpha = null;
	this.blendEquationAlpha = null;

	this.depthFunc = LessEqualDepth;
	this.depthTest = true;
	this.depthWrite = true;

	this.stencilWriteMask = 0xff;
	this.stencilFunc = AlwaysStencilFunc;
	this.stencilRef = 0;
	this.stencilFuncMask = 0xff;
	this.stencilFail = KeepStencilOp;
	this.stencilZFail = KeepStencilOp;
	this.stencilZPass = KeepStencilOp;
	this.stencilWrite = false;

	this.clippingPlanes = null;
	this.clipIntersection = false;
	this.clipShadows = false;

	this.shadowSide = null;

	this.colorWrite = true;

	this.precision = null; // override the renderer's default precision for this material

	this.polygonOffset = false;
	this.polygonOffsetFactor = 0;
	this.polygonOffsetUnits = 0;

	this.dithering = false;

	this.alphaTest = 0;
	this.premultipliedAlpha = false;

	this.visible = true;

	this.toneMapped = true;

	this.userData = {};

	this.version = 0;

}

Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

	constructor: Material,

	isMaterial: true,

	onBeforeCompile: function ( /* shaderobject, renderer */ ) {},

	customProgramCacheKey: function () {

		return this.onBeforeCompile.toString();

	},

	setValues: function ( values ) {

		if ( values === undefined ) return;

		for ( const key in values ) {

			const newValue = values[ key ];

			if ( newValue === undefined ) {

				console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
				continue;

			}

			// for backward compatability if shading is set in the constructor
			if ( key === 'shading' ) {

				console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
				this.flatShading = ( newValue === FlatShading ) ? true : false;
				continue;

			}

			const currentValue = this[ key ];

			if ( currentValue === undefined ) {

				console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
				continue;

			}

			if ( currentValue && currentValue.isColor ) {

				currentValue.set( newValue );

			} else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {

				currentValue.copy( newValue );

			} else {

				this[ key ] = newValue;

			}

		}

	},

	toJSON: function ( meta ) {

		const isRoot = ( meta === undefined || typeof meta === 'string' );

		if ( isRoot ) {

			meta = {
				textures: {},
				images: {}
			};

		}

		const data = {
			metadata: {
				version: 4.5,
				type: 'Material',
				generator: 'Material.toJSON'
			}
		};

		// standard Material serialization
		data.uuid = this.uuid;
		data.type = this.type;

		if ( this.name !== '' ) data.name = this.name;

		if ( this.color && this.color.isColor ) data.color = this.color.getHex();

		if ( this.roughness !== undefined ) data.roughness = this.roughness;
		if ( this.metalness !== undefined ) data.metalness = this.metalness;

		if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
		if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
		if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;

		if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
		if ( this.shininess !== undefined ) data.shininess = this.shininess;
		if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
		if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;

		if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {

			data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;

		}

		if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {

			data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;

		}

		if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {

			data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
			data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();

		}

		if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
		if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
		if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
		if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;

		if ( this.aoMap && this.aoMap.isTexture ) {

			data.aoMap = this.aoMap.toJSON( meta ).uuid;
			data.aoMapIntensity = this.aoMapIntensity;

		}

		if ( this.bumpMap && this.bumpMap.isTexture ) {

			data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
			data.bumpScale = this.bumpScale;

		}

		if ( this.normalMap && this.normalMap.isTexture ) {

			data.normalMap = this.normalMap.toJSON( meta ).uuid;
			data.normalMapType = this.normalMapType;
			data.normalScale = this.normalScale.toArray();

		}

		if ( this.displacementMap && this.displacementMap.isTexture ) {

			data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
			data.displacementScale = this.displacementScale;
			data.displacementBias = this.displacementBias;

		}

		if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
		if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;

		if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
		if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;

		if ( this.envMap && this.envMap.isTexture ) {

			data.envMap = this.envMap.toJSON( meta ).uuid;
			data.reflectivity = this.reflectivity; // Scale behind envMap
			data.refractionRatio = this.refractionRatio;

			if ( this.combine !== undefined ) data.combine = this.combine;
			if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;

		}

		if ( this.gradientMap && this.gradientMap.isTexture ) {

			data.gradientMap = this.gradientMap.toJSON( meta ).uuid;

		}

		if ( this.size !== undefined ) data.size = this.size;
		if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;

		if ( this.blending !== NormalBlending ) data.blending = this.blending;
		if ( this.flatShading === true ) data.flatShading = this.flatShading;
		if ( this.side !== FrontSide ) data.side = this.side;
		if ( this.vertexColors ) data.vertexColors = true;

		if ( this.opacity < 1 ) data.opacity = this.opacity;
		if ( this.transparent === true ) data.transparent = this.transparent;

		data.depthFunc = this.depthFunc;
		data.depthTest = this.depthTest;
		data.depthWrite = this.depthWrite;

		data.stencilWrite = this.stencilWrite;
		data.stencilWriteMask = this.stencilWriteMask;
		data.stencilFunc = this.stencilFunc;
		data.stencilRef = this.stencilRef;
		data.stencilFuncMask = this.stencilFuncMask;
		data.stencilFail = this.stencilFail;
		data.stencilZFail = this.stencilZFail;
		data.stencilZPass = this.stencilZPass;

		// rotation (SpriteMaterial)
		if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;

		if ( this.polygonOffset === true ) data.polygonOffset = true;
		if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
		if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;

		if ( this.linewidth && this.linewidth !== 1 ) data.linewidth = this.linewidth;
		if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
		if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
		if ( this.scale !== undefined ) data.scale = this.scale;

		if ( this.dithering === true ) data.dithering = true;

		if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
		if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;

		if ( this.wireframe === true ) data.wireframe = this.wireframe;
		if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
		if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
		if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;

		if ( this.morphTargets === true ) data.morphTargets = true;
		if ( this.morphNormals === true ) data.morphNormals = true;
		if ( this.skinning === true ) data.skinning = true;

		if ( this.visible === false ) data.visible = false;

		if ( this.toneMapped === false ) data.toneMapped = false;

		if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;

		// TODO: Copied from Object3D.toJSON

		function extractFromCache( cache ) {

			const values = [];

			for ( const key in cache ) {

				const data = cache[ key ];
				delete data.metadata;
				values.push( data );

			}

			return values;

		}

		if ( isRoot ) {

			const textures = extractFromCache( meta.textures );
			const images = extractFromCache( meta.images );

			if ( textures.length > 0 ) data.textures = textures;
			if ( images.length > 0 ) data.images = images;

		}

		return data;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( source ) {

		this.name = source.name;

		this.fog = source.fog;

		this.blending = source.blending;
		this.side = source.side;
		this.flatShading = source.flatShading;
		this.vertexColors = source.vertexColors;

		this.opacity = source.opacity;
		this.transparent = source.transparent;

		this.blendSrc = source.blendSrc;
		this.blendDst = source.blendDst;
		this.blendEquation = source.blendEquation;
		this.blendSrcAlpha = source.blendSrcAlpha;
		this.blendDstAlpha = source.blendDstAlpha;
		this.blendEquationAlpha = source.blendEquationAlpha;

		this.depthFunc = source.depthFunc;
		this.depthTest = source.depthTest;
		this.depthWrite = source.depthWrite;

		this.stencilWriteMask = source.stencilWriteMask;
		this.stencilFunc = source.stencilFunc;
		this.stencilRef = source.stencilRef;
		this.stencilFuncMask = source.stencilFuncMask;
		this.stencilFail = source.stencilFail;
		this.stencilZFail = source.stencilZFail;
		this.stencilZPass = source.stencilZPass;
		this.stencilWrite = source.stencilWrite;

		const srcPlanes = source.clippingPlanes;
		let dstPlanes = null;

		if ( srcPlanes !== null ) {

			const n = srcPlanes.length;
			dstPlanes = new Array( n );

			for ( let i = 0; i !== n; ++ i ) {

				dstPlanes[ i ] = srcPlanes[ i ].clone();

			}

		}

		this.clippingPlanes = dstPlanes;
		this.clipIntersection = source.clipIntersection;
		this.clipShadows = source.clipShadows;

		this.shadowSide = source.shadowSide;

		this.colorWrite = source.colorWrite;

		this.precision = source.precision;

		this.polygonOffset = source.polygonOffset;
		this.polygonOffsetFactor = source.polygonOffsetFactor;
		this.polygonOffsetUnits = source.polygonOffsetUnits;

		this.dithering = source.dithering;

		this.alphaTest = source.alphaTest;
		this.premultipliedAlpha = source.premultipliedAlpha;

		this.visible = source.visible;

		this.toneMapped = source.toneMapped;

		this.userData = JSON.parse( JSON.stringify( source.userData ) );

		return this;

	},

	dispose: function () {

		this.dispatchEvent( { type: 'dispose' } );

	}

} );

Object.defineProperty( Material.prototype, 'needsUpdate', {

	set: function ( value ) {

		if ( value === true ) this.version ++;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  opacity: <float>,
 *  map: new THREE.Texture( <Image> ),
 *
 *  lightMap: new THREE.Texture( <Image> ),
 *  lightMapIntensity: <float>
 *
 *  aoMap: new THREE.Texture( <Image> ),
 *  aoMapIntensity: <float>
 *
 *  specularMap: new THREE.Texture( <Image> ),
 *
 *  alphaMap: new THREE.Texture( <Image> ),
 *
 *  envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
 *  combine: THREE.Multiply,
 *  reflectivity: <float>,
 *  refractionRatio: <float>,
 *
 *  depthTest: <bool>,
 *  depthWrite: <bool>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>
 * }
 */

function MeshBasicMaterial( parameters ) {

	Material.call( this );

	this.type = 'MeshBasicMaterial';

	this.color = new Color( 0xffffff ); // emissive

	this.map = null;

	this.lightMap = null;
	this.lightMapIntensity = 1.0;

	this.aoMap = null;
	this.aoMapIntensity = 1.0;

	this.specularMap = null;

	this.alphaMap = null;

	this.envMap = null;
	this.combine = MultiplyOperation;
	this.reflectivity = 1;
	this.refractionRatio = 0.98;

	this.wireframe = false;
	this.wireframeLinewidth = 1;
	this.wireframeLinecap = 'round';
	this.wireframeLinejoin = 'round';

	this.skinning = false;
	this.morphTargets = false;

	this.setValues( parameters );

}

MeshBasicMaterial.prototype = Object.create( Material.prototype );
MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;

MeshBasicMaterial.prototype.isMeshBasicMaterial = true;

MeshBasicMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.color.copy( source.color );

	this.map = source.map;

	this.lightMap = source.lightMap;
	this.lightMapIntensity = source.lightMapIntensity;

	this.aoMap = source.aoMap;
	this.aoMapIntensity = source.aoMapIntensity;

	this.specularMap = source.specularMap;

	this.alphaMap = source.alphaMap;

	this.envMap = source.envMap;
	this.combine = source.combine;
	this.reflectivity = source.reflectivity;
	this.refractionRatio = source.refractionRatio;

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;
	this.wireframeLinecap = source.wireframeLinecap;
	this.wireframeLinejoin = source.wireframeLinejoin;

	this.skinning = source.skinning;
	this.morphTargets = source.morphTargets;

	return this;

};

/**
 * @author mrdoob / http://mrdoob.com/
 */

const _vector$3 = new Vector3();
const _vector2$1 = new Vector2();

function BufferAttribute( array, itemSize, normalized ) {

	if ( Array.isArray( array ) ) {

		throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );

	}

	this.name = '';

	this.array = array;
	this.itemSize = itemSize;
	this.count = array !== undefined ? array.length / itemSize : 0;
	this.normalized = normalized === true;

	this.usage = StaticDrawUsage;
	this.updateRange = { offset: 0, count: - 1 };

	this.version = 0;

}

Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {

	set: function ( value ) {

		if ( value === true ) this.version ++;

	}

} );

Object.assign( BufferAttribute.prototype, {

	isBufferAttribute: true,

	onUploadCallback: function () {},

	setUsage: function ( value ) {

		this.usage = value;

		return this;

	},

	copy: function ( source ) {

		this.name = source.name;
		this.array = new source.array.constructor( source.array );
		this.itemSize = source.itemSize;
		this.count = source.count;
		this.normalized = source.normalized;

		this.usage = source.usage;

		return this;

	},

	copyAt: function ( index1, attribute, index2 ) {

		index1 *= this.itemSize;
		index2 *= attribute.itemSize;

		for ( let i = 0, l = this.itemSize; i < l; i ++ ) {

			this.array[ index1 + i ] = attribute.array[ index2 + i ];

		}

		return this;

	},

	copyArray: function ( array ) {

		this.array.set( array );

		return this;

	},

	copyColorsArray: function ( colors ) {

		const array = this.array;
		let offset = 0;

		for ( let i = 0, l = colors.length; i < l; i ++ ) {

			let color = colors[ i ];

			if ( color === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
				color = new Color();

			}

			array[ offset ++ ] = color.r;
			array[ offset ++ ] = color.g;
			array[ offset ++ ] = color.b;

		}

		return this;

	},

	copyVector2sArray: function ( vectors ) {

		const array = this.array;
		let offset = 0;

		for ( let i = 0, l = vectors.length; i < l; i ++ ) {

			let vector = vectors[ i ];

			if ( vector === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
				vector = new Vector2();

			}

			array[ offset ++ ] = vector.x;
			array[ offset ++ ] = vector.y;

		}

		return this;

	},

	copyVector3sArray: function ( vectors ) {

		const array = this.array;
		let offset = 0;

		for ( let i = 0, l = vectors.length; i < l; i ++ ) {

			let vector = vectors[ i ];

			if ( vector === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
				vector = new Vector3();

			}

			array[ offset ++ ] = vector.x;
			array[ offset ++ ] = vector.y;
			array[ offset ++ ] = vector.z;

		}

		return this;

	},

	copyVector4sArray: function ( vectors ) {

		const array = this.array;
		let offset = 0;

		for ( let i = 0, l = vectors.length; i < l; i ++ ) {

			let vector = vectors[ i ];

			if ( vector === undefined ) {

				console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
				vector = new Vector4();

			}

			array[ offset ++ ] = vector.x;
			array[ offset ++ ] = vector.y;
			array[ offset ++ ] = vector.z;
			array[ offset ++ ] = vector.w;

		}

		return this;

	},

	applyMatrix3: function ( m ) {

		if ( this.itemSize === 2 ) {

			for ( let i = 0, l = this.count; i < l; i ++ ) {

				_vector2$1.fromBufferAttribute( this, i );
				_vector2$1.applyMatrix3( m );

				this.setXY( i, _vector2$1.x, _vector2$1.y, );

			}

		} else if ( this.itemSize === 3 ) {

			for ( let i = 0, l = this.count; i < l; i ++ ) {

				_vector$3.fromBufferAttribute( this, i );
				_vector$3.applyMatrix3( m );

				this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );

			}

		}

		return this;

	},

	applyMatrix4: function ( m ) {

		for ( let i = 0, l = this.count; i < l; i ++ ) {

			_vector$3.x = this.getX( i );
			_vector$3.y = this.getY( i );
			_vector$3.z = this.getZ( i );

			_vector$3.applyMatrix4( m );

			this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );

		}

		return this;

	},

	applyNormalMatrix: function ( m ) {

		for ( let i = 0, l = this.count; i < l; i ++ ) {

			_vector$3.x = this.getX( i );
			_vector$3.y = this.getY( i );
			_vector$3.z = this.getZ( i );

			_vector$3.applyNormalMatrix( m );

			this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );

		}

		return this;

	},

	transformDirection: function ( m ) {

		for ( let i = 0, l = this.count; i < l; i ++ ) {

			_vector$3.x = this.getX( i );
			_vector$3.y = this.getY( i );
			_vector$3.z = this.getZ( i );

			_vector$3.transformDirection( m );

			this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );

		}

		return this;

	},

	set: function ( value, offset ) {

		if ( offset === undefined ) offset = 0;

		this.array.set( value, offset );

		return this;

	},

	getX: function ( index ) {

		return this.array[ index * this.itemSize ];

	},

	setX: function ( index, x ) {

		this.array[ index * this.itemSize ] = x;

		return this;

	},

	getY: function ( index ) {

		return this.array[ index * this.itemSize + 1 ];

	},

	setY: function ( index, y ) {

		this.array[ index * this.itemSize + 1 ] = y;

		return this;

	},

	getZ: function ( index ) {

		return this.array[ index * this.itemSize + 2 ];

	},

	setZ: function ( index, z ) {

		this.array[ index * this.itemSize + 2 ] = z;

		return this;

	},

	getW: function ( index ) {

		return this.array[ index * this.itemSize + 3 ];

	},

	setW: function ( index, w ) {

		this.array[ index * this.itemSize + 3 ] = w;

		return this;

	},

	setXY: function ( index, x, y ) {

		index *= this.itemSize;

		this.array[ index + 0 ] = x;
		this.array[ index + 1 ] = y;

		return this;

	},

	setXYZ: function ( index, x, y, z ) {

		index *= this.itemSize;

		this.array[ index + 0 ] = x;
		this.array[ index + 1 ] = y;
		this.array[ index + 2 ] = z;

		return this;

	},

	setXYZW: function ( index, x, y, z, w ) {

		index *= this.itemSize;

		this.array[ index + 0 ] = x;
		this.array[ index + 1 ] = y;
		this.array[ index + 2 ] = z;
		this.array[ index + 3 ] = w;

		return this;

	},

	onUpload: function ( callback ) {

		this.onUploadCallback = callback;

		return this;

	},

	clone: function () {

		return new this.constructor( this.array, this.itemSize ).copy( this );

	},

	toJSON: function () {

		return {
			itemSize: this.itemSize,
			type: this.array.constructor.name,
			array: Array.prototype.slice.call( this.array ),
			normalized: this.normalized
		};

	}

} );

//

function Int8BufferAttribute( array, itemSize, normalized ) {

	BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );

}

Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;


function Uint8BufferAttribute( array, itemSize, normalized ) {

	BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );

}

Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;


function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {

	BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );

}

Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;


function Int16BufferAttribute( array, itemSize, normalized ) {

	BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );

}

Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;


function Uint16BufferAttribute( array, itemSize, normalized ) {

	BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );

}

Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;


function Int32BufferAttribute( array, itemSize, normalized ) {

	BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );

}

Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;


function Uint32BufferAttribute( array, itemSize, normalized ) {

	BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );

}

Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;


function Float32BufferAttribute( array, itemSize, normalized ) {

	BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );

}

Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;


function Float64BufferAttribute( array, itemSize, normalized ) {

	BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );

}

Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;

/**
 * @author mrdoob / http://mrdoob.com/
 */

function DirectGeometry() {

	this.vertices = [];
	this.normals = [];
	this.colors = [];
	this.uvs = [];
	this.uvs2 = [];

	this.groups = [];

	this.morphTargets = {};

	this.skinWeights = [];
	this.skinIndices = [];

	// this.lineDistances = [];

	this.boundingBox = null;
	this.boundingSphere = null;

	// update flags

	this.verticesNeedUpdate = false;
	this.normalsNeedUpdate = false;
	this.colorsNeedUpdate = false;
	this.uvsNeedUpdate = false;
	this.groupsNeedUpdate = false;

}

Object.assign( DirectGeometry.prototype, {

	computeGroups: function ( geometry ) {

		const groups = [];

		let group, i;
		let materialIndex = undefined;

		const faces = geometry.faces;

		for ( i = 0; i < faces.length; i ++ ) {

			const face = faces[ i ];

			// materials

			if ( face.materialIndex !== materialIndex ) {

				materialIndex = face.materialIndex;

				if ( group !== undefined ) {

					group.count = ( i * 3 ) - group.start;
					groups.push( group );

				}

				group = {
					start: i * 3,
					materialIndex: materialIndex
				};

			}

		}

		if ( group !== undefined ) {

			group.count = ( i * 3 ) - group.start;
			groups.push( group );

		}

		this.groups = groups;

	},

	fromGeometry: function ( geometry ) {

		const faces = geometry.faces;
		const vertices = geometry.vertices;
		const faceVertexUvs = geometry.faceVertexUvs;

		const hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
		const hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;

		// morphs

		const morphTargets = geometry.morphTargets;
		const morphTargetsLength = morphTargets.length;

		let morphTargetsPosition;

		if ( morphTargetsLength > 0 ) {

			morphTargetsPosition = [];

			for ( let i = 0; i < morphTargetsLength; i ++ ) {

				morphTargetsPosition[ i ] = {
					name: morphTargets[ i ].name,
				 	data: []
				};

			}

			this.morphTargets.position = morphTargetsPosition;

		}

		const morphNormals = geometry.morphNormals;
		const morphNormalsLength = morphNormals.length;

		let morphTargetsNormal;

		if ( morphNormalsLength > 0 ) {

			morphTargetsNormal = [];

			for ( let i = 0; i < morphNormalsLength; i ++ ) {

				morphTargetsNormal[ i ] = {
					name: morphNormals[ i ].name,
				 	data: []
				};

			}

			this.morphTargets.normal = morphTargetsNormal;

		}

		// skins

		const skinIndices = geometry.skinIndices;
		const skinWeights = geometry.skinWeights;

		const hasSkinIndices = skinIndices.length === vertices.length;
		const hasSkinWeights = skinWeights.length === vertices.length;

		//

		if ( vertices.length > 0 && faces.length === 0 ) {

			console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );

		}

		for ( let i = 0; i < faces.length; i ++ ) {

			const face = faces[ i ];

			this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );

			const vertexNormals = face.vertexNormals;

			if ( vertexNormals.length === 3 ) {

				this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );

			} else {

				const normal = face.normal;

				this.normals.push( normal, normal, normal );

			}

			const vertexColors = face.vertexColors;

			if ( vertexColors.length === 3 ) {

				this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );

			} else {

				const color = face.color;

				this.colors.push( color, color, color );

			}

			if ( hasFaceVertexUv === true ) {

				const vertexUvs = faceVertexUvs[ 0 ][ i ];

				if ( vertexUvs !== undefined ) {

					this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );

				} else {

					console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );

					this.uvs.push( new Vector2(), new Vector2(), new Vector2() );

				}

			}

			if ( hasFaceVertexUv2 === true ) {

				const vertexUvs = faceVertexUvs[ 1 ][ i ];

				if ( vertexUvs !== undefined ) {

					this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );

				} else {

					console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );

					this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );

				}

			}

			// morphs

			for ( let j = 0; j < morphTargetsLength; j ++ ) {

				const morphTarget = morphTargets[ j ].vertices;

				morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );

			}

			for ( let j = 0; j < morphNormalsLength; j ++ ) {

				const morphNormal = morphNormals[ j ].vertexNormals[ i ];

				morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );

			}

			// skins

			if ( hasSkinIndices ) {

				this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );

			}

			if ( hasSkinWeights ) {

				this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );

			}

		}

		this.computeGroups( geometry );

		this.verticesNeedUpdate = geometry.verticesNeedUpdate;
		this.normalsNeedUpdate = geometry.normalsNeedUpdate;
		this.colorsNeedUpdate = geometry.colorsNeedUpdate;
		this.uvsNeedUpdate = geometry.uvsNeedUpdate;
		this.groupsNeedUpdate = geometry.groupsNeedUpdate;

		if ( geometry.boundingSphere !== null ) {

			this.boundingSphere = geometry.boundingSphere.clone();

		}

		if ( geometry.boundingBox !== null ) {

			this.boundingBox = geometry.boundingBox.clone();

		}

		return this;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function arrayMax( array ) {

	if ( array.length === 0 ) return - Infinity;

	let max = array[ 0 ];

	for ( let i = 1, l = array.length; i < l; ++ i ) {

		if ( array[ i ] > max ) max = array[ i ];

	}

	return max;

}

/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 */

let _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id

const _m1$2 = new Matrix4();
const _obj = new Object3D();
const _offset = new Vector3();
const _box$2 = new Box3();
const _boxMorphTargets = new Box3();
const _vector$4 = new Vector3();

function BufferGeometry() {

	Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );

	this.uuid = MathUtils.generateUUID();

	this.name = '';
	this.type = 'BufferGeometry';

	this.index = null;
	this.attributes = {};

	this.morphAttributes = {};
	this.morphTargetsRelative = false;

	this.groups = [];

	this.boundingBox = null;
	this.boundingSphere = null;

	this.drawRange = { start: 0, count: Infinity };

	this.userData = {};

}

BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

	constructor: BufferGeometry,

	isBufferGeometry: true,

	getIndex: function () {

		return this.index;

	},

	setIndex: function ( index ) {

		if ( Array.isArray( index ) ) {

			this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );

		} else {

			this.index = index;

		}

	},

	getAttribute: function ( name ) {

		return this.attributes[ name ];

	},

	setAttribute: function ( name, attribute ) {

		this.attributes[ name ] = attribute;

		return this;

	},

	deleteAttribute: function ( name ) {

		delete this.attributes[ name ];

		return this;

	},

	addGroup: function ( start, count, materialIndex ) {

		this.groups.push( {

			start: start,
			count: count,
			materialIndex: materialIndex !== undefined ? materialIndex : 0

		} );

	},

	clearGroups: function () {

		this.groups = [];

	},

	setDrawRange: function ( start, count ) {

		this.drawRange.start = start;
		this.drawRange.count = count;

	},

	applyMatrix4: function ( matrix ) {

		const position = this.attributes.position;

		if ( position !== undefined ) {

			position.applyMatrix4( matrix );

			position.needsUpdate = true;

		}

		const normal = this.attributes.normal;

		if ( normal !== undefined ) {

			const normalMatrix = new Matrix3().getNormalMatrix( matrix );

			normal.applyNormalMatrix( normalMatrix );

			normal.needsUpdate = true;

		}

		const tangent = this.attributes.tangent;

		if ( tangent !== undefined ) {

			tangent.transformDirection( matrix );

			tangent.needsUpdate = true;

		}

		if ( this.boundingBox !== null ) {

			this.computeBoundingBox();

		}

		if ( this.boundingSphere !== null ) {

			this.computeBoundingSphere();

		}

		return this;

	},

	rotateX: function ( angle ) {

		// rotate geometry around world x-axis

		_m1$2.makeRotationX( angle );

		this.applyMatrix4( _m1$2 );

		return this;

	},

	rotateY: function ( angle ) {

		// rotate geometry around world y-axis

		_m1$2.makeRotationY( angle );

		this.applyMatrix4( _m1$2 );

		return this;

	},

	rotateZ: function ( angle ) {

		// rotate geometry around world z-axis

		_m1$2.makeRotationZ( angle );

		this.applyMatrix4( _m1$2 );

		return this;

	},

	translate: function ( x, y, z ) {

		// translate geometry

		_m1$2.makeTranslation( x, y, z );

		this.applyMatrix4( _m1$2 );

		return this;

	},

	scale: function ( x, y, z ) {

		// scale geometry

		_m1$2.makeScale( x, y, z );

		this.applyMatrix4( _m1$2 );

		return this;

	},

	lookAt: function ( vector ) {

		_obj.lookAt( vector );

		_obj.updateMatrix();

		this.applyMatrix4( _obj.matrix );

		return this;

	},

	center: function () {

		this.computeBoundingBox();

		this.boundingBox.getCenter( _offset ).negate();

		this.translate( _offset.x, _offset.y, _offset.z );

		return this;

	},

	setFromObject: function ( object ) {

		// console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );

		const geometry = object.geometry;

		if ( object.isPoints || object.isLine ) {

			const positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
			const colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );

			this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
			this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );

			if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {

				const lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );

				this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );

			}

			if ( geometry.boundingSphere !== null ) {

				this.boundingSphere = geometry.boundingSphere.clone();

			}

			if ( geometry.boundingBox !== null ) {

				this.boundingBox = geometry.boundingBox.clone();

			}

		} else if ( object.isMesh ) {

			if ( geometry && geometry.isGeometry ) {

				this.fromGeometry( geometry );

			}

		}

		return this;

	},

	setFromPoints: function ( points ) {

		const position = [];

		for ( let i = 0, l = points.length; i < l; i ++ ) {

			const point = points[ i ];
			position.push( point.x, point.y, point.z || 0 );

		}

		this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );

		return this;

	},

	updateFromObject: function ( object ) {

		let geometry = object.geometry;

		if ( object.isMesh ) {

			let direct = geometry.__directGeometry;

			if ( geometry.elementsNeedUpdate === true ) {

				direct = undefined;
				geometry.elementsNeedUpdate = false;

			}

			if ( direct === undefined ) {

				return this.fromGeometry( geometry );

			}

			direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
			direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
			direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
			direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
			direct.groupsNeedUpdate = geometry.groupsNeedUpdate;

			geometry.verticesNeedUpdate = false;
			geometry.normalsNeedUpdate = false;
			geometry.colorsNeedUpdate = false;
			geometry.uvsNeedUpdate = false;
			geometry.groupsNeedUpdate = false;

			geometry = direct;

		}

		if ( geometry.verticesNeedUpdate === true ) {

			const attribute = this.attributes.position;

			if ( attribute !== undefined ) {

				attribute.copyVector3sArray( geometry.vertices );
				attribute.needsUpdate = true;

			}

			geometry.verticesNeedUpdate = false;

		}

		if ( geometry.normalsNeedUpdate === true ) {

			const attribute = this.attributes.normal;

			if ( attribute !== undefined ) {

				attribute.copyVector3sArray( geometry.normals );
				attribute.needsUpdate = true;

			}

			geometry.normalsNeedUpdate = false;

		}

		if ( geometry.colorsNeedUpdate === true ) {

			const attribute = this.attributes.color;

			if ( attribute !== undefined ) {

				attribute.copyColorsArray( geometry.colors );
				attribute.needsUpdate = true;

			}

			geometry.colorsNeedUpdate = false;

		}

		if ( geometry.uvsNeedUpdate ) {

			const attribute = this.attributes.uv;

			if ( attribute !== undefined ) {

				attribute.copyVector2sArray( geometry.uvs );
				attribute.needsUpdate = true;

			}

			geometry.uvsNeedUpdate = false;

		}

		if ( geometry.lineDistancesNeedUpdate ) {

			const attribute = this.attributes.lineDistance;

			if ( attribute !== undefined ) {

				attribute.copyArray( geometry.lineDistances );
				attribute.needsUpdate = true;

			}

			geometry.lineDistancesNeedUpdate = false;

		}

		if ( geometry.groupsNeedUpdate ) {

			geometry.computeGroups( object.geometry );
			this.groups = geometry.groups;

			geometry.groupsNeedUpdate = false;

		}

		return this;

	},

	fromGeometry: function ( geometry ) {

		geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );

		return this.fromDirectGeometry( geometry.__directGeometry );

	},

	fromDirectGeometry: function ( geometry ) {

		const positions = new Float32Array( geometry.vertices.length * 3 );
		this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );

		if ( geometry.normals.length > 0 ) {

			const normals = new Float32Array( geometry.normals.length * 3 );
			this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );

		}

		if ( geometry.colors.length > 0 ) {

			const colors = new Float32Array( geometry.colors.length * 3 );
			this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );

		}

		if ( geometry.uvs.length > 0 ) {

			const uvs = new Float32Array( geometry.uvs.length * 2 );
			this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );

		}

		if ( geometry.uvs2.length > 0 ) {

			const uvs2 = new Float32Array( geometry.uvs2.length * 2 );
			this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );

		}

		// groups

		this.groups = geometry.groups;

		// morphs

		for ( const name in geometry.morphTargets ) {

			const array = [];
			const morphTargets = geometry.morphTargets[ name ];

			for ( let i = 0, l = morphTargets.length; i < l; i ++ ) {

				const morphTarget = morphTargets[ i ];

				const attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
				attribute.name = morphTarget.name;

				array.push( attribute.copyVector3sArray( morphTarget.data ) );

			}

			this.morphAttributes[ name ] = array;

		}

		// skinning

		if ( geometry.skinIndices.length > 0 ) {

			const skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
			this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );

		}

		if ( geometry.skinWeights.length > 0 ) {

			const skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
			this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );

		}

		//

		if ( geometry.boundingSphere !== null ) {

			this.boundingSphere = geometry.boundingSphere.clone();

		}

		if ( geometry.boundingBox !== null ) {

			this.boundingBox = geometry.boundingBox.clone();

		}

		return this;

	},

	computeBoundingBox: function () {

		if ( this.boundingBox === null ) {

			this.boundingBox = new Box3();

		}

		const position = this.attributes.position;
		const morphAttributesPosition = this.morphAttributes.position;

		if ( position !== undefined ) {

			this.boundingBox.setFromBufferAttribute( position );

			// process morph attributes if present

			if ( morphAttributesPosition ) {

				for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {

					const morphAttribute = morphAttributesPosition[ i ];
					_box$2.setFromBufferAttribute( morphAttribute );

					if ( this.morphTargetsRelative ) {

						_vector$4.addVectors( this.boundingBox.min, _box$2.min );
						this.boundingBox.expandByPoint( _vector$4 );

						_vector$4.addVectors( this.boundingBox.max, _box$2.max );
						this.boundingBox.expandByPoint( _vector$4 );

					} else {

						this.boundingBox.expandByPoint( _box$2.min );
						this.boundingBox.expandByPoint( _box$2.max );

					}

				}

			}

		} else {

			this.boundingBox.makeEmpty();

		}

		if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {

			console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );

		}

	},

	computeBoundingSphere: function () {

		if ( this.boundingSphere === null ) {

			this.boundingSphere = new Sphere();

		}

		const position = this.attributes.position;
		const morphAttributesPosition = this.morphAttributes.position;

		if ( position ) {

			// first, find the center of the bounding sphere

			const center = this.boundingSphere.center;

			_box$2.setFromBufferAttribute( position );

			// process morph attributes if present

			if ( morphAttributesPosition ) {

				for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {

					const morphAttribute = morphAttributesPosition[ i ];
					_boxMorphTargets.setFromBufferAttribute( morphAttribute );

					if ( this.morphTargetsRelative ) {

						_vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
						_box$2.expandByPoint( _vector$4 );

						_vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
						_box$2.expandByPoint( _vector$4 );

					} else {

						_box$2.expandByPoint( _boxMorphTargets.min );
						_box$2.expandByPoint( _boxMorphTargets.max );

					}

				}

			}

			_box$2.getCenter( center );

			// second, try to find a boundingSphere with a radius smaller than the
			// boundingSphere of the boundingBox: sqrt(3) smaller in the best case

			let maxRadiusSq = 0;

			for ( let i = 0, il = position.count; i < il; i ++ ) {

				_vector$4.fromBufferAttribute( position, i );

				maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );

			}

			// process morph attributes if present

			if ( morphAttributesPosition ) {

				for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {

					const morphAttribute = morphAttributesPosition[ i ];
					const morphTargetsRelative = this.morphTargetsRelative;

					for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {

						_vector$4.fromBufferAttribute( morphAttribute, j );

						if ( morphTargetsRelative ) {

							_offset.fromBufferAttribute( position, j );
							_vector$4.add( _offset );

						}

						maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );

					}

				}

			}

			this.boundingSphere.radius = Math.sqrt( maxRadiusSq );

			if ( isNaN( this.boundingSphere.radius ) ) {

				console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );

			}

		}

	},

	computeFaceNormals: function () {

		// backwards compatibility

	},

	computeVertexNormals: function () {

		const index = this.index;
		const positionAttribute = this.getAttribute( 'position' );

		if ( positionAttribute !== undefined ) {

			let normalAttribute = this.getAttribute( 'normal' );

			if ( normalAttribute === undefined ) {

				normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
				this.setAttribute( 'normal', normalAttribute );

			} else {

				// reset existing normals to zero

				for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {

					normalAttribute.setXYZ( i, 0, 0, 0 );

				}

			}

			const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
			const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
			const cb = new Vector3(), ab = new Vector3();

			// indexed elements

			if ( index ) {

				for ( let i = 0, il = index.count; i < il; i += 3 ) {

					const vA = index.getX( i + 0 );
					const vB = index.getX( i + 1 );
					const vC = index.getX( i + 2 );

					pA.fromBufferAttribute( positionAttribute, vA );
					pB.fromBufferAttribute( positionAttribute, vB );
					pC.fromBufferAttribute( positionAttribute, vC );

					cb.subVectors( pC, pB );
					ab.subVectors( pA, pB );
					cb.cross( ab );

					nA.fromBufferAttribute( normalAttribute, vA );
					nB.fromBufferAttribute( normalAttribute, vB );
					nC.fromBufferAttribute( normalAttribute, vC );

					nA.add( cb );
					nB.add( cb );
					nC.add( cb );

					normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
					normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
					normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );

				}

			} else {

				// non-indexed elements (unconnected triangle soup)

				for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {

					pA.fromBufferAttribute( positionAttribute, i + 0 );
					pB.fromBufferAttribute( positionAttribute, i + 1 );
					pC.fromBufferAttribute( positionAttribute, i + 2 );

					cb.subVectors( pC, pB );
					ab.subVectors( pA, pB );
					cb.cross( ab );

					normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
					normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
					normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );

				}

			}

			this.normalizeNormals();

			normalAttribute.needsUpdate = true;

		}

	},

	merge: function ( geometry, offset ) {

		if ( ! ( geometry && geometry.isBufferGeometry ) ) {

			console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
			return;

		}

		if ( offset === undefined ) {

			offset = 0;

			console.warn(
				'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
				+ 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
			);

		}

		const attributes = this.attributes;

		for ( const key in attributes ) {

			if ( geometry.attributes[ key ] === undefined ) continue;

			const attribute1 = attributes[ key ];
			const attributeArray1 = attribute1.array;

			const attribute2 = geometry.attributes[ key ];
			const attributeArray2 = attribute2.array;

			const attributeOffset = attribute2.itemSize * offset;
			const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );

			for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {

				attributeArray1[ j ] = attributeArray2[ i ];

			}

		}

		return this;

	},

	normalizeNormals: function () {

		const normals = this.attributes.normal;

		for ( let i = 0, il = normals.count; i < il; i ++ ) {

			_vector$4.fromBufferAttribute( normals, i );

			_vector$4.normalize();

			normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );

		}

	},

	toNonIndexed: function () {

		function convertBufferAttribute( attribute, indices ) {

			const array = attribute.array;
			const itemSize = attribute.itemSize;
			const normalized = attribute.normalized;

			const array2 = new array.constructor( indices.length * itemSize );

			let index = 0, index2 = 0;

			for ( let i = 0, l = indices.length; i < l; i ++ ) {

				index = indices[ i ] * itemSize;

				for ( let j = 0; j < itemSize; j ++ ) {

					array2[ index2 ++ ] = array[ index ++ ];

				}

			}

			return new BufferAttribute( array2, itemSize, normalized );

		}

		//

		if ( this.index === null ) {

			console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
			return this;

		}

		const geometry2 = new BufferGeometry();

		const indices = this.index.array;
		const attributes = this.attributes;

		// attributes

		for ( const name in attributes ) {

			const attribute = attributes[ name ];

			const newAttribute = convertBufferAttribute( attribute, indices );

			geometry2.setAttribute( name, newAttribute );

		}

		// morph attributes

		const morphAttributes = this.morphAttributes;

		for ( const name in morphAttributes ) {

			const morphArray = [];
			const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes

			for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {

				const attribute = morphAttribute[ i ];

				const newAttribute = convertBufferAttribute( attribute, indices );

				morphArray.push( newAttribute );

			}

			geometry2.morphAttributes[ name ] = morphArray;

		}

		geometry2.morphTargetsRelative = this.morphTargetsRelative;

		// groups

		const groups = this.groups;

		for ( let i = 0, l = groups.length; i < l; i ++ ) {

			const group = groups[ i ];
			geometry2.addGroup( group.start, group.count, group.materialIndex );

		}

		return geometry2;

	},

	toJSON: function () {

		const data = {
			metadata: {
				version: 4.5,
				type: 'BufferGeometry',
				generator: 'BufferGeometry.toJSON'
			}
		};

		// standard BufferGeometry serialization

		data.uuid = this.uuid;
		data.type = this.type;
		if ( this.name !== '' ) data.name = this.name;
		if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;

		if ( this.parameters !== undefined ) {

			const parameters = this.parameters;

			for ( const key in parameters ) {

				if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];

			}

			return data;

		}

		data.data = { attributes: {} };

		const index = this.index;

		if ( index !== null ) {

			data.data.index = {
				type: index.array.constructor.name,
				array: Array.prototype.slice.call( index.array )
			};

		}

		const attributes = this.attributes;

		for ( const key in attributes ) {

			const attribute = attributes[ key ];

			const attributeData = attribute.toJSON( data.data );

			if ( attribute.name !== '' ) attributeData.name = attribute.name;

			data.data.attributes[ key ] = attributeData;

		}

		const morphAttributes = {};
		let hasMorphAttributes = false;

		for ( const key in this.morphAttributes ) {

			const attributeArray = this.morphAttributes[ key ];

			const array = [];

			for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {

				const attribute = attributeArray[ i ];

				const attributeData = attribute.toJSON( data.data );

				if ( attribute.name !== '' ) attributeData.name = attribute.name;

				array.push( attributeData );

			}

			if ( array.length > 0 ) {

				morphAttributes[ key ] = array;

				hasMorphAttributes = true;

			}

		}

		if ( hasMorphAttributes ) {

			data.data.morphAttributes = morphAttributes;
			data.data.morphTargetsRelative = this.morphTargetsRelative;

		}

		const groups = this.groups;

		if ( groups.length > 0 ) {

			data.data.groups = JSON.parse( JSON.stringify( groups ) );

		}

		const boundingSphere = this.boundingSphere;

		if ( boundingSphere !== null ) {

			data.data.boundingSphere = {
				center: boundingSphere.center.toArray(),
				radius: boundingSphere.radius
			};

		}

		return data;

	},

	clone: function () {

		/*
		 // Handle primitives

		 const parameters = this.parameters;

		 if ( parameters !== undefined ) {

		 const values = [];

		 for ( const key in parameters ) {

		 values.push( parameters[ key ] );

		 }

		 const geometry = Object.create( this.constructor.prototype );
		 this.constructor.apply( geometry, values );
		 return geometry;

		 }

		 return new this.constructor().copy( this );
		 */

		return new BufferGeometry().copy( this );

	},

	copy: function ( source ) {

		// reset

		this.index = null;
		this.attributes = {};
		this.morphAttributes = {};
		this.groups = [];
		this.boundingBox = null;
		this.boundingSphere = null;

		// used for storing cloned, shared data

		const data = {};

		// name

		this.name = source.name;

		// index

		const index = source.index;

		if ( index !== null ) {

			this.setIndex( index.clone( data ) );

		}

		// attributes

		const attributes = source.attributes;

		for ( const name in attributes ) {

			const attribute = attributes[ name ];
			this.setAttribute( name, attribute.clone( data ) );

		}

		// morph attributes

		const morphAttributes = source.morphAttributes;

		for ( const name in morphAttributes ) {

			const array = [];
			const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes

			for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {

				array.push( morphAttribute[ i ].clone( data ) );

			}

			this.morphAttributes[ name ] = array;

		}

		this.morphTargetsRelative = source.morphTargetsRelative;

		// groups

		const groups = source.groups;

		for ( let i = 0, l = groups.length; i < l; i ++ ) {

			const group = groups[ i ];
			this.addGroup( group.start, group.count, group.materialIndex );

		}

		// bounding box

		const boundingBox = source.boundingBox;

		if ( boundingBox !== null ) {

			this.boundingBox = boundingBox.clone();

		}

		// bounding sphere

		const boundingSphere = source.boundingSphere;

		if ( boundingSphere !== null ) {

			this.boundingSphere = boundingSphere.clone();

		}

		// draw range

		this.drawRange.start = source.drawRange.start;
		this.drawRange.count = source.drawRange.count;

		// user data

		this.userData = source.userData;

		return this;

	},

	dispose: function () {

		this.dispatchEvent( { type: 'dispose' } );

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 * @author jonobr1 / http://jonobr1.com/
 */

const _inverseMatrix = new Matrix4();
const _ray = new Ray();
const _sphere = new Sphere();

const _vA = new Vector3();
const _vB = new Vector3();
const _vC = new Vector3();

const _tempA = new Vector3();
const _tempB = new Vector3();
const _tempC = new Vector3();

const _morphA = new Vector3();
const _morphB = new Vector3();
const _morphC = new Vector3();

const _uvA = new Vector2();
const _uvB = new Vector2();
const _uvC = new Vector2();

const _intersectionPoint = new Vector3();
const _intersectionPointWorld = new Vector3();

function Mesh( geometry, material ) {

	Object3D.call( this );

	this.type = 'Mesh';

	this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
	this.material = material !== undefined ? material : new MeshBasicMaterial();

	this.updateMorphTargets();

}

Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Mesh,

	isMesh: true,

	copy: function ( source ) {

		Object3D.prototype.copy.call( this, source );

		if ( source.morphTargetInfluences !== undefined ) {

			this.morphTargetInfluences = source.morphTargetInfluences.slice();

		}

		if ( source.morphTargetDictionary !== undefined ) {

			this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );

		}

		this.material = source.material;
		this.geometry = source.geometry;

		return this;

	},

	updateMorphTargets: function () {

		const geometry = this.geometry;

		if ( geometry.isBufferGeometry ) {

			const morphAttributes = geometry.morphAttributes;
			const keys = Object.keys( morphAttributes );

			if ( keys.length > 0 ) {

				const morphAttribute = morphAttributes[ keys[ 0 ] ];

				if ( morphAttribute !== undefined ) {

					this.morphTargetInfluences = [];
					this.morphTargetDictionary = {};

					for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {

						const name = morphAttribute[ m ].name || String( m );

						this.morphTargetInfluences.push( 0 );
						this.morphTargetDictionary[ name ] = m;

					}

				}

			}

		} else {

			const morphTargets = geometry.morphTargets;

			if ( morphTargets !== undefined && morphTargets.length > 0 ) {

				console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );

			}

		}

	},

	raycast: function ( raycaster, intersects ) {

		const geometry = this.geometry;
		const material = this.material;
		const matrixWorld = this.matrixWorld;

		if ( material === undefined ) return;

		// Checking boundingSphere distance to ray

		if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

		_sphere.copy( geometry.boundingSphere );
		_sphere.applyMatrix4( matrixWorld );

		if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;

		//

		_inverseMatrix.getInverse( matrixWorld );
		_ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );

		// Check boundingBox before continuing

		if ( geometry.boundingBox !== null ) {

			if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return;

		}

		let intersection;

		if ( geometry.isBufferGeometry ) {

			const index = geometry.index;
			const position = geometry.attributes.position;
			const morphPosition = geometry.morphAttributes.position;
			const morphTargetsRelative = geometry.morphTargetsRelative;
			const uv = geometry.attributes.uv;
			const uv2 = geometry.attributes.uv2;
			const groups = geometry.groups;
			const drawRange = geometry.drawRange;

			if ( index !== null ) {

				// indexed buffer geometry

				if ( Array.isArray( material ) ) {

					for ( let i = 0, il = groups.length; i < il; i ++ ) {

						const group = groups[ i ];
						const groupMaterial = material[ group.materialIndex ];

						const start = Math.max( group.start, drawRange.start );
						const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );

						for ( let j = start, jl = end; j < jl; j += 3 ) {

							const a = index.getX( j );
							const b = index.getX( j + 1 );
							const c = index.getX( j + 2 );

							intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );

							if ( intersection ) {

								intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
								intersection.face.materialIndex = group.materialIndex;
								intersects.push( intersection );

							}

						}

					}

				} else {

					const start = Math.max( 0, drawRange.start );
					const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );

					for ( let i = start, il = end; i < il; i += 3 ) {

						const a = index.getX( i );
						const b = index.getX( i + 1 );
						const c = index.getX( i + 2 );

						intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );

						if ( intersection ) {

							intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
							intersects.push( intersection );

						}

					}

				}

			} else if ( position !== undefined ) {

				// non-indexed buffer geometry

				if ( Array.isArray( material ) ) {

					for ( let i = 0, il = groups.length; i < il; i ++ ) {

						const group = groups[ i ];
						const groupMaterial = material[ group.materialIndex ];

						const start = Math.max( group.start, drawRange.start );
						const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );

						for ( let j = start, jl = end; j < jl; j += 3 ) {

							const a = j;
							const b = j + 1;
							const c = j + 2;

							intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );

							if ( intersection ) {

								intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
								intersection.face.materialIndex = group.materialIndex;
								intersects.push( intersection );

							}

						}

					}

				} else {

					const start = Math.max( 0, drawRange.start );
					const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );

					for ( let i = start, il = end; i < il; i += 3 ) {

						const a = i;
						const b = i + 1;
						const c = i + 2;

						intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );

						if ( intersection ) {

							intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
							intersects.push( intersection );

						}

					}

				}

			}

		} else if ( geometry.isGeometry ) {

			const isMultiMaterial = Array.isArray( material );

			const vertices = geometry.vertices;
			const faces = geometry.faces;
			let uvs;

			const faceVertexUvs = geometry.faceVertexUvs[ 0 ];
			if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;

			for ( let f = 0, fl = faces.length; f < fl; f ++ ) {

				const face = faces[ f ];
				const faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;

				if ( faceMaterial === undefined ) continue;

				const fvA = vertices[ face.a ];
				const fvB = vertices[ face.b ];
				const fvC = vertices[ face.c ];

				intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );

				if ( intersection ) {

					if ( uvs && uvs[ f ] ) {

						const uvs_f = uvs[ f ];
						_uvA.copy( uvs_f[ 0 ] );
						_uvB.copy( uvs_f[ 1 ] );
						_uvC.copy( uvs_f[ 2 ] );

						intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2() );

					}

					intersection.face = face;
					intersection.faceIndex = f;
					intersects.push( intersection );

				}

			}

		}

	}

} );

function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {

	let intersect;

	if ( material.side === BackSide ) {

		intersect = ray.intersectTriangle( pC, pB, pA, true, point );

	} else {

		intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );

	}

	if ( intersect === null ) return null;

	_intersectionPointWorld.copy( point );
	_intersectionPointWorld.applyMatrix4( object.matrixWorld );

	const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );

	if ( distance < raycaster.near || distance > raycaster.far ) return null;

	return {
		distance: distance,
		point: _intersectionPointWorld.clone(),
		object: object
	};

}

function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {

	_vA.fromBufferAttribute( position, a );
	_vB.fromBufferAttribute( position, b );
	_vC.fromBufferAttribute( position, c );

	const morphInfluences = object.morphTargetInfluences;

	if ( material.morphTargets && morphPosition && morphInfluences ) {

		_morphA.set( 0, 0, 0 );
		_morphB.set( 0, 0, 0 );
		_morphC.set( 0, 0, 0 );

		for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {

			const influence = morphInfluences[ i ];
			const morphAttribute = morphPosition[ i ];

			if ( influence === 0 ) continue;

			_tempA.fromBufferAttribute( morphAttribute, a );
			_tempB.fromBufferAttribute( morphAttribute, b );
			_tempC.fromBufferAttribute( morphAttribute, c );

			if ( morphTargetsRelative ) {

				_morphA.addScaledVector( _tempA, influence );
				_morphB.addScaledVector( _tempB, influence );
				_morphC.addScaledVector( _tempC, influence );

			} else {

				_morphA.addScaledVector( _tempA.sub( _vA ), influence );
				_morphB.addScaledVector( _tempB.sub( _vB ), influence );
				_morphC.addScaledVector( _tempC.sub( _vC ), influence );

			}

		}

		_vA.add( _morphA );
		_vB.add( _morphB );
		_vC.add( _morphC );

	}

	if ( object.isSkinnedMesh ) {

		object.boneTransform( a, _vA );
		object.boneTransform( b, _vB );
		object.boneTransform( c, _vC );

	}

	const intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );

	if ( intersection ) {

		if ( uv ) {

			_uvA.fromBufferAttribute( uv, a );
			_uvB.fromBufferAttribute( uv, b );
			_uvC.fromBufferAttribute( uv, c );

			intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );

		}

		if ( uv2 ) {

			_uvA.fromBufferAttribute( uv2, a );
			_uvB.fromBufferAttribute( uv2, b );
			_uvC.fromBufferAttribute( uv2, c );

			intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() );

		}

		const face = new Face3( a, b, c );
		Triangle.getNormal( _vA, _vB, _vC, face.normal );

		intersection.face = face;

	}

	return intersection;

}

/**
 * @author mrdoob / http://mrdoob.com/
 * @author kile / http://kile.stravaganza.org/
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * @author bhouston / http://clara.io
 */

let _geometryId = 0; // Geometry uses even numbers as Id
const _m1$3 = new Matrix4();
const _obj$1 = new Object3D();
const _offset$1 = new Vector3();

function Geometry() {

	Object.defineProperty( this, 'id', { value: _geometryId += 2 } );

	this.uuid = MathUtils.generateUUID();

	this.name = '';
	this.type = 'Geometry';

	this.vertices = [];
	this.colors = [];
	this.faces = [];
	this.faceVertexUvs = [[]];

	this.morphTargets = [];
	this.morphNormals = [];

	this.skinWeights = [];
	this.skinIndices = [];

	this.lineDistances = [];

	this.boundingBox = null;
	this.boundingSphere = null;

	// update flags

	this.elementsNeedUpdate = false;
	this.verticesNeedUpdate = false;
	this.uvsNeedUpdate = false;
	this.normalsNeedUpdate = false;
	this.colorsNeedUpdate = false;
	this.lineDistancesNeedUpdate = false;
	this.groupsNeedUpdate = false;

}

Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

	constructor: Geometry,

	isGeometry: true,

	applyMatrix4: function ( matrix ) {

		const normalMatrix = new Matrix3().getNormalMatrix( matrix );

		for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {

			const vertex = this.vertices[ i ];
			vertex.applyMatrix4( matrix );

		}

		for ( let i = 0, il = this.faces.length; i < il; i ++ ) {

			const face = this.faces[ i ];
			face.normal.applyMatrix3( normalMatrix ).normalize();

			for ( let j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {

				face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();

			}

		}

		if ( this.boundingBox !== null ) {

			this.computeBoundingBox();

		}

		if ( this.boundingSphere !== null ) {

			this.computeBoundingSphere();

		}

		this.verticesNeedUpdate = true;
		this.normalsNeedUpdate = true;

		return this;

	},

	rotateX: function ( angle ) {

		// rotate geometry around world x-axis

		_m1$3.makeRotationX( angle );

		this.applyMatrix4( _m1$3 );

		return this;

	},

	rotateY: function ( angle ) {

		// rotate geometry around world y-axis

		_m1$3.makeRotationY( angle );

		this.applyMatrix4( _m1$3 );

		return this;

	},

	rotateZ: function ( angle ) {

		// rotate geometry around world z-axis

		_m1$3.makeRotationZ( angle );

		this.applyMatrix4( _m1$3 );

		return this;

	},

	translate: function ( x, y, z ) {

		// translate geometry

		_m1$3.makeTranslation( x, y, z );

		this.applyMatrix4( _m1$3 );

		return this;

	},

	scale: function ( x, y, z ) {

		// scale geometry

		_m1$3.makeScale( x, y, z );

		this.applyMatrix4( _m1$3 );

		return this;

	},

	lookAt: function ( vector ) {

		_obj$1.lookAt( vector );

		_obj$1.updateMatrix();

		this.applyMatrix4( _obj$1.matrix );

		return this;

	},

	fromBufferGeometry: function ( geometry ) {

		const scope = this;

		const index = geometry.index !== null ? geometry.index : undefined;
		const attributes = geometry.attributes;

		if ( attributes.position === undefined ) {

			console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
			return this;

		}

		const position = attributes.position;
		const normal = attributes.normal;
		const color = attributes.color;
		const uv = attributes.uv;
		const uv2 = attributes.uv2;

		if ( uv2 !== undefined ) this.faceVertexUvs[ 1 ] = [];

		for ( let i = 0; i < position.count; i ++ ) {

			scope.vertices.push( new Vector3().fromBufferAttribute( position, i ) );

			if ( color !== undefined ) {

				scope.colors.push( new Color().fromBufferAttribute( color, i ) );

			}

		}

		function addFace( a, b, c, materialIndex ) {

			const vertexColors = ( color === undefined ) ? [] : [
				scope.colors[ a ].clone(),
				scope.colors[ b ].clone(),
				scope.colors[ c ].clone()
			];

			const vertexNormals = ( normal === undefined ) ? [] : [
				new Vector3().fromBufferAttribute( normal, a ),
				new Vector3().fromBufferAttribute( normal, b ),
				new Vector3().fromBufferAttribute( normal, c )
			];

			const face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );

			scope.faces.push( face );

			if ( uv !== undefined ) {

				scope.faceVertexUvs[ 0 ].push( [
					new Vector2().fromBufferAttribute( uv, a ),
					new Vector2().fromBufferAttribute( uv, b ),
					new Vector2().fromBufferAttribute( uv, c )
				] );

			}

			if ( uv2 !== undefined ) {

				scope.faceVertexUvs[ 1 ].push( [
					new Vector2().fromBufferAttribute( uv2, a ),
					new Vector2().fromBufferAttribute( uv2, b ),
					new Vector2().fromBufferAttribute( uv2, c )
				] );

			}

		}

		const groups = geometry.groups;

		if ( groups.length > 0 ) {

			for ( let i = 0; i < groups.length; i ++ ) {

				const group = groups[ i ];

				const start = group.start;
				const count = group.count;

				for ( let j = start, jl = start + count; j < jl; j += 3 ) {

					if ( index !== undefined ) {

						addFace( index.getX( j ), index.getX( j + 1 ), index.getX( j + 2 ), group.materialIndex );

					} else {

						addFace( j, j + 1, j + 2, group.materialIndex );

					}

				}

			}

		} else {

			if ( index !== undefined ) {

				for ( let i = 0; i < index.count; i += 3 ) {

					addFace( index.getX( i ), index.getX( i + 1 ), index.getX( i + 2 ) );

				}

			} else {

				for ( let i = 0; i < position.count; i += 3 ) {

					addFace( i, i + 1, i + 2 );

				}

			}

		}

		this.computeFaceNormals();

		if ( geometry.boundingBox !== null ) {

			this.boundingBox = geometry.boundingBox.clone();

		}

		if ( geometry.boundingSphere !== null ) {

			this.boundingSphere = geometry.boundingSphere.clone();

		}

		return this;

	},

	center: function () {

		this.computeBoundingBox();

		this.boundingBox.getCenter( _offset$1 ).negate();

		this.translate( _offset$1.x, _offset$1.y, _offset$1.z );

		return this;

	},

	normalize: function () {

		this.computeBoundingSphere();

		const center = this.boundingSphere.center;
		const radius = this.boundingSphere.radius;

		const s = radius === 0 ? 1 : 1.0 / radius;

		const matrix = new Matrix4();
		matrix.set(
			s, 0, 0, - s * center.x,
			0, s, 0, - s * center.y,
			0, 0, s, - s * center.z,
			0, 0, 0, 1
		);

		this.applyMatrix4( matrix );

		return this;

	},

	computeFaceNormals: function () {

		const cb = new Vector3(), ab = new Vector3();

		for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {

			const face = this.faces[ f ];

			const vA = this.vertices[ face.a ];
			const vB = this.vertices[ face.b ];
			const vC = this.vertices[ face.c ];

			cb.subVectors( vC, vB );
			ab.subVectors( vA, vB );
			cb.cross( ab );

			cb.normalize();

			face.normal.copy( cb );

		}

	},

	computeVertexNormals: function ( areaWeighted ) {

		if ( areaWeighted === undefined ) areaWeighted = true;

		const vertices = new Array( this.vertices.length );

		for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {

			vertices[ v ] = new Vector3();

		}

		if ( areaWeighted ) {

			// vertex normals weighted by triangle areas
			// http://www.iquilezles.org/www/articles/normals/normals.htm

			const cb = new Vector3(), ab = new Vector3();

			for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {

				const face = this.faces[ f ];

				const vA = this.vertices[ face.a ];
				const vB = this.vertices[ face.b ];
				const vC = this.vertices[ face.c ];

				cb.subVectors( vC, vB );
				ab.subVectors( vA, vB );
				cb.cross( ab );

				vertices[ face.a ].add( cb );
				vertices[ face.b ].add( cb );
				vertices[ face.c ].add( cb );

			}

		} else {

			this.computeFaceNormals();

			for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {

				const face = this.faces[ f ];

				vertices[ face.a ].add( face.normal );
				vertices[ face.b ].add( face.normal );
				vertices[ face.c ].add( face.normal );

			}

		}

		for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {

			vertices[ v ].normalize();

		}

		for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {

			const face = this.faces[ f ];

			const vertexNormals = face.vertexNormals;

			if ( vertexNormals.length === 3 ) {

				vertexNormals[ 0 ].copy( vertices[ face.a ] );
				vertexNormals[ 1 ].copy( vertices[ face.b ] );
				vertexNormals[ 2 ].copy( vertices[ face.c ] );

			} else {

				vertexNormals[ 0 ] = vertices[ face.a ].clone();
				vertexNormals[ 1 ] = vertices[ face.b ].clone();
				vertexNormals[ 2 ] = vertices[ face.c ].clone();

			}

		}

		if ( this.faces.length > 0 ) {

			this.normalsNeedUpdate = true;

		}

	},

	computeFlatVertexNormals: function () {

		this.computeFaceNormals();

		for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {

			const face = this.faces[ f ];

			const vertexNormals = face.vertexNormals;

			if ( vertexNormals.length === 3 ) {

				vertexNormals[ 0 ].copy( face.normal );
				vertexNormals[ 1 ].copy( face.normal );
				vertexNormals[ 2 ].copy( face.normal );

			} else {

				vertexNormals[ 0 ] = face.normal.clone();
				vertexNormals[ 1 ] = face.normal.clone();
				vertexNormals[ 2 ] = face.normal.clone();

			}

		}

		if ( this.faces.length > 0 ) {

			this.normalsNeedUpdate = true;

		}

	},

	computeMorphNormals: function () {

		// save original normals
		// - create temp variables on first access
		//   otherwise just copy (for faster repeated calls)

		for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {

			const face = this.faces[ f ];

			if ( ! face.__originalFaceNormal ) {

				face.__originalFaceNormal = face.normal.clone();

			} else {

				face.__originalFaceNormal.copy( face.normal );

			}

			if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];

			for ( let i = 0, il = face.vertexNormals.length; i < il; i ++ ) {

				if ( ! face.__originalVertexNormals[ i ] ) {

					face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();

				} else {

					face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );

				}

			}

		}

		// use temp geometry to compute face and vertex normals for each morph

		const tmpGeo = new Geometry();
		tmpGeo.faces = this.faces;

		for ( let i = 0, il = this.morphTargets.length; i < il; i ++ ) {

			// create on first access

			if ( ! this.morphNormals[ i ] ) {

				this.morphNormals[ i ] = {};
				this.morphNormals[ i ].faceNormals = [];
				this.morphNormals[ i ].vertexNormals = [];

				const dstNormalsFace = this.morphNormals[ i ].faceNormals;
				const dstNormalsVertex = this.morphNormals[ i ].vertexNormals;

				for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {

					const faceNormal = new Vector3();
					const vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };

					dstNormalsFace.push( faceNormal );
					dstNormalsVertex.push( vertexNormals );

				}

			}

			const morphNormals = this.morphNormals[ i ];

			// set vertices to morph target

			tmpGeo.vertices = this.morphTargets[ i ].vertices;

			// compute morph normals

			tmpGeo.computeFaceNormals();
			tmpGeo.computeVertexNormals();

			// store morph normals

			for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {

				const face = this.faces[ f ];

				const faceNormal = morphNormals.faceNormals[ f ];
				const vertexNormals = morphNormals.vertexNormals[ f ];

				faceNormal.copy( face.normal );

				vertexNormals.a.copy( face.vertexNormals[ 0 ] );
				vertexNormals.b.copy( face.vertexNormals[ 1 ] );
				vertexNormals.c.copy( face.vertexNormals[ 2 ] );

			}

		}

		// restore original normals

		for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {

			const face = this.faces[ f ];

			face.normal = face.__originalFaceNormal;
			face.vertexNormals = face.__originalVertexNormals;

		}

	},

	computeBoundingBox: function () {

		if ( this.boundingBox === null ) {

			this.boundingBox = new Box3();

		}

		this.boundingBox.setFromPoints( this.vertices );

	},

	computeBoundingSphere: function () {

		if ( this.boundingSphere === null ) {

			this.boundingSphere = new Sphere();

		}

		this.boundingSphere.setFromPoints( this.vertices );

	},

	merge: function ( geometry, matrix, materialIndexOffset ) {

		if ( ! ( geometry && geometry.isGeometry ) ) {

			console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
			return;

		}

		let normalMatrix,
			vertexOffset = this.vertices.length,
			vertices1 = this.vertices,
			vertices2 = geometry.vertices,
			faces1 = this.faces,
			faces2 = geometry.faces,
			colors1 = this.colors,
			colors2 = geometry.colors;

		if ( materialIndexOffset === undefined ) materialIndexOffset = 0;

		if ( matrix !== undefined ) {

			normalMatrix = new Matrix3().getNormalMatrix( matrix );

		}

		// vertices

		for ( let i = 0, il = vertices2.length; i < il; i ++ ) {

			const vertex = vertices2[ i ];

			const vertexCopy = vertex.clone();

			if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );

			vertices1.push( vertexCopy );

		}

		// colors

		for ( let i = 0, il = colors2.length; i < il; i ++ ) {

			colors1.push( colors2[ i ].clone() );

		}

		// faces

		for ( let i = 0, il = faces2.length; i < il; i ++ ) {

			let face = faces2[ i ], faceCopy, normal, color,
				faceVertexNormals = face.vertexNormals,
				faceVertexColors = face.vertexColors;

			faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
			faceCopy.normal.copy( face.normal );

			if ( normalMatrix !== undefined ) {

				faceCopy.normal.applyMatrix3( normalMatrix ).normalize();

			}

			for ( let j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {

				normal = faceVertexNormals[ j ].clone();

				if ( normalMatrix !== undefined ) {

					normal.applyMatrix3( normalMatrix ).normalize();

				}

				faceCopy.vertexNormals.push( normal );

			}

			faceCopy.color.copy( face.color );

			for ( let j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {

				color = faceVertexColors[ j ];
				faceCopy.vertexColors.push( color.clone() );

			}

			faceCopy.materialIndex = face.materialIndex + materialIndexOffset;

			faces1.push( faceCopy );

		}

		// uvs

		for ( let i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {

			const faceVertexUvs2 = geometry.faceVertexUvs[ i ];

			if ( this.faceVertexUvs[ i ] === undefined ) this.faceVertexUvs[ i ] = [];

			for ( let j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {

				const uvs2 = faceVertexUvs2[ j ], uvsCopy = [];

				for ( let k = 0, kl = uvs2.length; k < kl; k ++ ) {

					uvsCopy.push( uvs2[ k ].clone() );

				}

				this.faceVertexUvs[ i ].push( uvsCopy );

			}

		}

	},

	mergeMesh: function ( mesh ) {

		if ( ! ( mesh && mesh.isMesh ) ) {

			console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
			return;

		}

		if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();

		this.merge( mesh.geometry, mesh.matrix );

	},

	/*
	 * Checks for duplicate vertices with hashmap.
	 * Duplicated vertices are removed
	 * and faces' vertices are updated.
	 */

	mergeVertices: function () {

		const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
		const unique = [], changes = [];

		const precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
		const precision = Math.pow( 10, precisionPoints );

		for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {

			const v = this.vertices[ i ];
			const key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );

			if ( verticesMap[ key ] === undefined ) {

				verticesMap[ key ] = i;
				unique.push( this.vertices[ i ] );
				changes[ i ] = unique.length - 1;

			} else {

				//console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
				changes[ i ] = changes[ verticesMap[ key ] ];

			}

		}


		// if faces are completely degenerate after merging vertices, we
		// have to remove them from the geometry.
		const faceIndicesToRemove = [];

		for ( let i = 0, il = this.faces.length; i < il; i ++ ) {

			const face = this.faces[ i ];

			face.a = changes[ face.a ];
			face.b = changes[ face.b ];
			face.c = changes[ face.c ];

			const indices = [ face.a, face.b, face.c ];

			// if any duplicate vertices are found in a Face3
			// we have to remove the face as nothing can be saved
			for ( let n = 0; n < 3; n ++ ) {

				if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {

					faceIndicesToRemove.push( i );
					break;

				}

			}

		}

		for ( let i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {

			const idx = faceIndicesToRemove[ i ];

			this.faces.splice( idx, 1 );

			for ( let j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {

				this.faceVertexUvs[ j ].splice( idx, 1 );

			}

		}

		// Use unique set of vertices

		const diff = this.vertices.length - unique.length;
		this.vertices = unique;
		return diff;

	},

	setFromPoints: function ( points ) {

		this.vertices = [];

		for ( let i = 0, l = points.length; i < l; i ++ ) {

			const point = points[ i ];
			this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );

		}

		return this;

	},

	sortFacesByMaterialIndex: function () {

		const faces = this.faces;
		const length = faces.length;

		// tag faces

		for ( let i = 0; i < length; i ++ ) {

			faces[ i ]._id = i;

		}

		// sort faces

		function materialIndexSort( a, b ) {

			return a.materialIndex - b.materialIndex;

		}

		faces.sort( materialIndexSort );

		// sort uvs

		const uvs1 = this.faceVertexUvs[ 0 ];
		const uvs2 = this.faceVertexUvs[ 1 ];

		let newUvs1, newUvs2;

		if ( uvs1 && uvs1.length === length ) newUvs1 = [];
		if ( uvs2 && uvs2.length === length ) newUvs2 = [];

		for ( let i = 0; i < length; i ++ ) {

			const id = faces[ i ]._id;

			if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
			if ( newUvs2 ) newUvs2.push( uvs2[ id ] );

		}

		if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
		if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;

	},

	toJSON: function () {

		const data = {
			metadata: {
				version: 4.5,
				type: 'Geometry',
				generator: 'Geometry.toJSON'
			}
		};

		// standard Geometry serialization

		data.uuid = this.uuid;
		data.type = this.type;
		if ( this.name !== '' ) data.name = this.name;

		if ( this.parameters !== undefined ) {

			const parameters = this.parameters;

			for ( const key in parameters ) {

				if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];

			}

			return data;

		}

		const vertices = [];

		for ( let i = 0; i < this.vertices.length; i ++ ) {

			const vertex = this.vertices[ i ];
			vertices.push( vertex.x, vertex.y, vertex.z );

		}

		const faces = [];
		const normals = [];
		const normalsHash = {};
		const colors = [];
		const colorsHash = {};
		const uvs = [];
		const uvsHash = {};

		for ( let i = 0; i < this.faces.length; i ++ ) {

			const face = this.faces[ i ];

			const hasMaterial = true;
			const hasFaceUv = false; // deprecated
			const hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
			const hasFaceNormal = face.normal.length() > 0;
			const hasFaceVertexNormal = face.vertexNormals.length > 0;
			const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
			const hasFaceVertexColor = face.vertexColors.length > 0;

			let faceType = 0;

			faceType = setBit( faceType, 0, 0 ); // isQuad
			faceType = setBit( faceType, 1, hasMaterial );
			faceType = setBit( faceType, 2, hasFaceUv );
			faceType = setBit( faceType, 3, hasFaceVertexUv );
			faceType = setBit( faceType, 4, hasFaceNormal );
			faceType = setBit( faceType, 5, hasFaceVertexNormal );
			faceType = setBit( faceType, 6, hasFaceColor );
			faceType = setBit( faceType, 7, hasFaceVertexColor );

			faces.push( faceType );
			faces.push( face.a, face.b, face.c );
			faces.push( face.materialIndex );

			if ( hasFaceVertexUv ) {

				const faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];

				faces.push(
					getUvIndex( faceVertexUvs[ 0 ] ),
					getUvIndex( faceVertexUvs[ 1 ] ),
					getUvIndex( faceVertexUvs[ 2 ] )
				);

			}

			if ( hasFaceNormal ) {

				faces.push( getNormalIndex( face.normal ) );

			}

			if ( hasFaceVertexNormal ) {

				const vertexNormals = face.vertexNormals;

				faces.push(
					getNormalIndex( vertexNormals[ 0 ] ),
					getNormalIndex( vertexNormals[ 1 ] ),
					getNormalIndex( vertexNormals[ 2 ] )
				);

			}

			if ( hasFaceColor ) {

				faces.push( getColorIndex( face.color ) );

			}

			if ( hasFaceVertexColor ) {

				const vertexColors = face.vertexColors;

				faces.push(
					getColorIndex( vertexColors[ 0 ] ),
					getColorIndex( vertexColors[ 1 ] ),
					getColorIndex( vertexColors[ 2 ] )
				);

			}

		}

		function setBit( value, position, enabled ) {

			return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );

		}

		function getNormalIndex( normal ) {

			const hash = normal.x.toString() + normal.y.toString() + normal.z.toString();

			if ( normalsHash[ hash ] !== undefined ) {

				return normalsHash[ hash ];

			}

			normalsHash[ hash ] = normals.length / 3;
			normals.push( normal.x, normal.y, normal.z );

			return normalsHash[ hash ];

		}

		function getColorIndex( color ) {

			const hash = color.r.toString() + color.g.toString() + color.b.toString();

			if ( colorsHash[ hash ] !== undefined ) {

				return colorsHash[ hash ];

			}

			colorsHash[ hash ] = colors.length;
			colors.push( color.getHex() );

			return colorsHash[ hash ];

		}

		function getUvIndex( uv ) {

			const hash = uv.x.toString() + uv.y.toString();

			if ( uvsHash[ hash ] !== undefined ) {

				return uvsHash[ hash ];

			}

			uvsHash[ hash ] = uvs.length / 2;
			uvs.push( uv.x, uv.y );

			return uvsHash[ hash ];

		}

		data.data = {};

		data.data.vertices = vertices;
		data.data.normals = normals;
		if ( colors.length > 0 ) data.data.colors = colors;
		if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
		data.data.faces = faces;

		return data;

	},

	clone: function () {

		/*
		 // Handle primitives

		 const parameters = this.parameters;

		 if ( parameters !== undefined ) {

		 const values = [];

		 for ( const key in parameters ) {

		 values.push( parameters[ key ] );

		 }

		 const geometry = Object.create( this.constructor.prototype );
		 this.constructor.apply( geometry, values );
		 return geometry;

		 }

		 return new this.constructor().copy( this );
		 */

		return new Geometry().copy( this );

	},

	copy: function ( source ) {

		// reset

		this.vertices = [];
		this.colors = [];
		this.faces = [];
		this.faceVertexUvs = [[]];
		this.morphTargets = [];
		this.morphNormals = [];
		this.skinWeights = [];
		this.skinIndices = [];
		this.lineDistances = [];
		this.boundingBox = null;
		this.boundingSphere = null;

		// name

		this.name = source.name;

		// vertices

		const vertices = source.vertices;

		for ( let i = 0, il = vertices.length; i < il; i ++ ) {

			this.vertices.push( vertices[ i ].clone() );

		}

		// colors

		const colors = source.colors;

		for ( let i = 0, il = colors.length; i < il; i ++ ) {

			this.colors.push( colors[ i ].clone() );

		}

		// faces

		const faces = source.faces;

		for ( let i = 0, il = faces.length; i < il; i ++ ) {

			this.faces.push( faces[ i ].clone() );

		}

		// face vertex uvs

		for ( let i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {

			const faceVertexUvs = source.faceVertexUvs[ i ];

			if ( this.faceVertexUvs[ i ] === undefined ) {

				this.faceVertexUvs[ i ] = [];

			}

			for ( let j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {

				const uvs = faceVertexUvs[ j ], uvsCopy = [];

				for ( let k = 0, kl = uvs.length; k < kl; k ++ ) {

					const uv = uvs[ k ];

					uvsCopy.push( uv.clone() );

				}

				this.faceVertexUvs[ i ].push( uvsCopy );

			}

		}

		// morph targets

		const morphTargets = source.morphTargets;

		for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {

			const morphTarget = {};
			morphTarget.name = morphTargets[ i ].name;

			// vertices

			if ( morphTargets[ i ].vertices !== undefined ) {

				morphTarget.vertices = [];

				for ( let j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {

					morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );

				}

			}

			// normals

			if ( morphTargets[ i ].normals !== undefined ) {

				morphTarget.normals = [];

				for ( let j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {

					morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );

				}

			}

			this.morphTargets.push( morphTarget );

		}

		// morph normals

		const morphNormals = source.morphNormals;

		for ( let i = 0, il = morphNormals.length; i < il; i ++ ) {

			const morphNormal = {};

			// vertex normals

			if ( morphNormals[ i ].vertexNormals !== undefined ) {

				morphNormal.vertexNormals = [];

				for ( let j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {

					const srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
					const destVertexNormal = {};

					destVertexNormal.a = srcVertexNormal.a.clone();
					destVertexNormal.b = srcVertexNormal.b.clone();
					destVertexNormal.c = srcVertexNormal.c.clone();

					morphNormal.vertexNormals.push( destVertexNormal );

				}

			}

			// face normals

			if ( morphNormals[ i ].faceNormals !== undefined ) {

				morphNormal.faceNormals = [];

				for ( let j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {

					morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );

				}

			}

			this.morphNormals.push( morphNormal );

		}

		// skin weights

		const skinWeights = source.skinWeights;

		for ( let i = 0, il = skinWeights.length; i < il; i ++ ) {

			this.skinWeights.push( skinWeights[ i ].clone() );

		}

		// skin indices

		const skinIndices = source.skinIndices;

		for ( let i = 0, il = skinIndices.length; i < il; i ++ ) {

			this.skinIndices.push( skinIndices[ i ].clone() );

		}

		// line distances

		const lineDistances = source.lineDistances;

		for ( let i = 0, il = lineDistances.length; i < il; i ++ ) {

			this.lineDistances.push( lineDistances[ i ] );

		}

		// bounding box

		const boundingBox = source.boundingBox;

		if ( boundingBox !== null ) {

			this.boundingBox = boundingBox.clone();

		}

		// bounding sphere

		const boundingSphere = source.boundingSphere;

		if ( boundingSphere !== null ) {

			this.boundingSphere = boundingSphere.clone();

		}

		// update flags

		this.elementsNeedUpdate = source.elementsNeedUpdate;
		this.verticesNeedUpdate = source.verticesNeedUpdate;
		this.uvsNeedUpdate = source.uvsNeedUpdate;
		this.normalsNeedUpdate = source.normalsNeedUpdate;
		this.colorsNeedUpdate = source.colorsNeedUpdate;
		this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
		this.groupsNeedUpdate = source.groupsNeedUpdate;

		return this;

	},

	dispose: function () {

		this.dispatchEvent( { type: 'dispose' } );

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / https://github.com/Mugen87
 */

// BoxGeometry

class BoxGeometry extends Geometry {

	constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {

		super();

		this.type = 'BoxGeometry';

		this.parameters = {
			width: width,
			height: height,
			depth: depth,
			widthSegments: widthSegments,
			heightSegments: heightSegments,
			depthSegments: depthSegments
		};

		this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
		this.mergeVertices();

	}

}

// BoxBufferGeometry

class BoxBufferGeometry extends BufferGeometry {

	constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {

		super();

		this.type = 'BoxBufferGeometry';

		this.parameters = {
			width: width,
			height: height,
			depth: depth,
			widthSegments: widthSegments,
			heightSegments: heightSegments,
			depthSegments: depthSegments
		};

		const scope = this;

		width = width || 1;
		height = height || 1;
		depth = depth || 1;

		// segments

		widthSegments = Math.floor( widthSegments ) || 1;
		heightSegments = Math.floor( heightSegments ) || 1;
		depthSegments = Math.floor( depthSegments ) || 1;

		// buffers

		const indices = [];
		const vertices = [];
		const normals = [];
		const uvs = [];

		// helper variables

		let numberOfVertices = 0;
		let groupStart = 0;

		// build each side of the box geometry

		buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
		buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
		buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
		buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
		buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
		buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz

		// build geometry

		this.setIndex( indices );
		this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
		this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
		this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

		function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {

			const segmentWidth = width / gridX;
			const segmentHeight = height / gridY;

			const widthHalf = width / 2;
			const heightHalf = height / 2;
			const depthHalf = depth / 2;

			const gridX1 = gridX + 1;
			const gridY1 = gridY + 1;

			let vertexCounter = 0;
			let groupCount = 0;

			const vector = new Vector3();

			// generate vertices, normals and uvs

			for ( let iy = 0; iy < gridY1; iy ++ ) {

				const y = iy * segmentHeight - heightHalf;

				for ( let ix = 0; ix < gridX1; ix ++ ) {

					const x = ix * segmentWidth - widthHalf;

					// set values to correct vector component

					vector[ u ] = x * udir;
					vector[ v ] = y * vdir;
					vector[ w ] = depthHalf;

					// now apply vector to vertex buffer

					vertices.push( vector.x, vector.y, vector.z );

					// set values to correct vector component

					vector[ u ] = 0;
					vector[ v ] = 0;
					vector[ w ] = depth > 0 ? 1 : - 1;

					// now apply vector to normal buffer

					normals.push( vector.x, vector.y, vector.z );

					// uvs

					uvs.push( ix / gridX );
					uvs.push( 1 - ( iy / gridY ) );

					// counters

					vertexCounter += 1;

				}

			}

			// indices

			// 1. you need three indices to draw a single face
			// 2. a single segment consists of two faces
			// 3. so we need to generate six (2*3) indices per segment

			for ( let iy = 0; iy < gridY; iy ++ ) {

				for ( let ix = 0; ix < gridX; ix ++ ) {

					const a = numberOfVertices + ix + gridX1 * iy;
					const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
					const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
					const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;

					// faces

					indices.push( a, b, d );
					indices.push( b, c, d );

					// increase counter

					groupCount += 6;

				}

			}

			// add a group to the geometry. this will ensure multi material support

			scope.addGroup( groupStart, groupCount, materialIndex );

			// calculate new start value for groups

			groupStart += groupCount;

			// update total number of vertices

			numberOfVertices += vertexCounter;

		}

	}

}

/**
 * Uniform Utilities
 */

function cloneUniforms( src ) {

	const dst = {};

	for ( const u in src ) {

		dst[ u ] = {};

		for ( const p in src[ u ] ) {

			const property = src[ u ][ p ];

			if ( property && ( property.isColor ||
				property.isMatrix3 || property.isMatrix4 ||
				property.isVector2 || property.isVector3 || property.isVector4 ||
				property.isTexture ) ) {

				dst[ u ][ p ] = property.clone();

			} else if ( Array.isArray( property ) ) {

				dst[ u ][ p ] = property.slice();

			} else {

				dst[ u ][ p ] = property;

			}

		}

	}

	return dst;

}

function mergeUniforms( uniforms ) {

	const merged = {};

	for ( let u = 0; u < uniforms.length; u ++ ) {

		const tmp = cloneUniforms( uniforms[ u ] );

		for ( const p in tmp ) {

			merged[ p ] = tmp[ p ];

		}

	}

	return merged;

}

// Legacy

const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };

var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";

var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";

/**
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  defines: { "label" : "value" },
 *  uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
 *
 *  fragmentShader: <string>,
 *  vertexShader: <string>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  lights: <bool>,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>
 * }
 */

function ShaderMaterial( parameters ) {

	Material.call( this );

	this.type = 'ShaderMaterial';

	this.defines = {};
	this.uniforms = {};

	this.vertexShader = default_vertex;
	this.fragmentShader = default_fragment;

	this.linewidth = 1;

	this.wireframe = false;
	this.wireframeLinewidth = 1;

	this.fog = false; // set to use scene fog
	this.lights = false; // set to use scene lights
	this.clipping = false; // set to use user-defined clipping planes

	this.skinning = false; // set to use skinning attribute streams
	this.morphTargets = false; // set to use morph targets
	this.morphNormals = false; // set to use morph normals

	this.extensions = {
		derivatives: false, // set to use derivatives
		fragDepth: false, // set to use fragment depth values
		drawBuffers: false, // set to use draw buffers
		shaderTextureLOD: false // set to use shader texture LOD
	};

	// When rendered geometry doesn't include these attributes but the material does,
	// use these default values in WebGL. This avoids errors when buffer data is missing.
	this.defaultAttributeValues = {
		'color': [ 1, 1, 1 ],
		'uv': [ 0, 0 ],
		'uv2': [ 0, 0 ]
	};

	this.index0AttributeName = undefined;
	this.uniformsNeedUpdate = false;

	if ( parameters !== undefined ) {

		if ( parameters.attributes !== undefined ) {

			console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );

		}

		this.setValues( parameters );

	}

}

ShaderMaterial.prototype = Object.create( Material.prototype );
ShaderMaterial.prototype.constructor = ShaderMaterial;

ShaderMaterial.prototype.isShaderMaterial = true;

ShaderMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.fragmentShader = source.fragmentShader;
	this.vertexShader = source.vertexShader;

	this.uniforms = cloneUniforms( source.uniforms );

	this.defines = Object.assign( {}, source.defines );

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;

	this.lights = source.lights;
	this.clipping = source.clipping;

	this.skinning = source.skinning;

	this.morphTargets = source.morphTargets;
	this.morphNormals = source.morphNormals;

	this.extensions = Object.assign( {}, source.extensions );

	return this;

};

ShaderMaterial.prototype.toJSON = function ( meta ) {

	const data = Material.prototype.toJSON.call( this, meta );

	data.uniforms = {};

	for ( const name in this.uniforms ) {

		const uniform = this.uniforms[ name ];
		const value = uniform.value;

		if ( value && value.isTexture ) {

			data.uniforms[ name ] = {
				type: 't',
				value: value.toJSON( meta ).uuid
			};

		} else if ( value && value.isColor ) {

			data.uniforms[ name ] = {
				type: 'c',
				value: value.getHex()
			};

		} else if ( value && value.isVector2 ) {

			data.uniforms[ name ] = {
				type: 'v2',
				value: value.toArray()
			};

		} else if ( value && value.isVector3 ) {

			data.uniforms[ name ] = {
				type: 'v3',
				value: value.toArray()
			};

		} else if ( value && value.isVector4 ) {

			data.uniforms[ name ] = {
				type: 'v4',
				value: value.toArray()
			};

		} else if ( value && value.isMatrix3 ) {

			data.uniforms[ name ] = {
				type: 'm3',
				value: value.toArray()
			};

		} else if ( value && value.isMatrix4 ) {

			data.uniforms[ name ] = {
				type: 'm4',
				value: value.toArray()
			};

		} else {

			data.uniforms[ name ] = {
				value: value
			};

			// note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far

		}

	}

	if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;

	data.vertexShader = this.vertexShader;
	data.fragmentShader = this.fragmentShader;

	const extensions = {};

	for ( const key in this.extensions ) {

		if ( this.extensions[ key ] === true ) extensions[ key ] = true;

	}

	if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;

	return data;

};

/**
 * @author mrdoob / http://mrdoob.com/
 * @author mikael emtinger / http://gomo.se/
 * @author WestLangley / http://github.com/WestLangley
*/

function Camera() {

	Object3D.call( this );

	this.type = 'Camera';

	this.matrixWorldInverse = new Matrix4();

	this.projectionMatrix = new Matrix4();
	this.projectionMatrixInverse = new Matrix4();

}

Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Camera,

	isCamera: true,

	copy: function ( source, recursive ) {

		Object3D.prototype.copy.call( this, source, recursive );

		this.matrixWorldInverse.copy( source.matrixWorldInverse );

		this.projectionMatrix.copy( source.projectionMatrix );
		this.projectionMatrixInverse.copy( source.projectionMatrixInverse );

		return this;

	},

	getWorldDirection: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
			target = new Vector3();

		}

		this.updateMatrixWorld( true );

		const e = this.matrixWorld.elements;

		return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();

	},

	updateMatrixWorld: function ( force ) {

		Object3D.prototype.updateMatrixWorld.call( this, force );

		this.matrixWorldInverse.getInverse( this.matrixWorld );

	},

	updateWorldMatrix: function ( updateParents, updateChildren ) {

		Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );

		this.matrixWorldInverse.getInverse( this.matrixWorld );

	},

	clone: function () {

		return new this.constructor().copy( this );

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author greggman / http://games.greggman.com/
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * @author tschw
 */

function PerspectiveCamera( fov, aspect, near, far ) {

	Camera.call( this );

	this.type = 'PerspectiveCamera';

	this.fov = fov !== undefined ? fov : 50;
	this.zoom = 1;

	this.near = near !== undefined ? near : 0.1;
	this.far = far !== undefined ? far : 2000;
	this.focus = 10;

	this.aspect = aspect !== undefined ? aspect : 1;
	this.view = null;

	this.filmGauge = 35;	// width of the film (default in millimeters)
	this.filmOffset = 0;	// horizontal film offset (same unit as gauge)

	this.updateProjectionMatrix();

}

PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {

	constructor: PerspectiveCamera,

	isPerspectiveCamera: true,

	copy: function ( source, recursive ) {

		Camera.prototype.copy.call( this, source, recursive );

		this.fov = source.fov;
		this.zoom = source.zoom;

		this.near = source.near;
		this.far = source.far;
		this.focus = source.focus;

		this.aspect = source.aspect;
		this.view = source.view === null ? null : Object.assign( {}, source.view );

		this.filmGauge = source.filmGauge;
		this.filmOffset = source.filmOffset;

		return this;

	},

	/**
	 * Sets the FOV by focal length in respect to the current .filmGauge.
	 *
	 * The default film gauge is 35, so that the focal length can be specified for
	 * a 35mm (full frame) camera.
	 *
	 * Values for focal length and film gauge must have the same unit.
	 */
	setFocalLength: function ( focalLength ) {

		// see http://www.bobatkins.com/photography/technical/field_of_view.html
		const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;

		this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
		this.updateProjectionMatrix();

	},

	/**
	 * Calculates the focal length from the current .fov and .filmGauge.
	 */
	getFocalLength: function () {

		const vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );

		return 0.5 * this.getFilmHeight() / vExtentSlope;

	},

	getEffectiveFOV: function () {

		return MathUtils.RAD2DEG * 2 * Math.atan(
			Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );

	},

	getFilmWidth: function () {

		// film not completely covered in portrait format (aspect < 1)
		return this.filmGauge * Math.min( this.aspect, 1 );

	},

	getFilmHeight: function () {

		// film not completely covered in landscape format (aspect > 1)
		return this.filmGauge / Math.max( this.aspect, 1 );

	},

	/**
	 * Sets an offset in a larger frustum. This is useful for multi-window or
	 * multi-monitor/multi-machine setups.
	 *
	 * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
	 * the monitors are in grid like this
	 *
	 *   +---+---+---+
	 *   | A | B | C |
	 *   +---+---+---+
	 *   | D | E | F |
	 *   +---+---+---+
	 *
	 * then for each monitor you would call it like this
	 *
	 *   const w = 1920;
	 *   const h = 1080;
	 *   const fullWidth = w * 3;
	 *   const fullHeight = h * 2;
	 *
	 *   --A--
	 *   camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
	 *   --B--
	 *   camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
	 *   --C--
	 *   camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
	 *   --D--
	 *   camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
	 *   --E--
	 *   camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
	 *   --F--
	 *   camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
	 *
	 *   Note there is no reason monitors have to be the same size or in a grid.
	 */
	setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {

		this.aspect = fullWidth / fullHeight;

		if ( this.view === null ) {

			this.view = {
				enabled: true,
				fullWidth: 1,
				fullHeight: 1,
				offsetX: 0,
				offsetY: 0,
				width: 1,
				height: 1
			};

		}

		this.view.enabled = true;
		this.view.fullWidth = fullWidth;
		this.view.fullHeight = fullHeight;
		this.view.offsetX = x;
		this.view.offsetY = y;
		this.view.width = width;
		this.view.height = height;

		this.updateProjectionMatrix();

	},

	clearViewOffset: function () {

		if ( this.view !== null ) {

			this.view.enabled = false;

		}

		this.updateProjectionMatrix();

	},

	updateProjectionMatrix: function () {

		let near = this.near,
			top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom,
			height = 2 * top,
			width = this.aspect * height,
			left = - 0.5 * width,
			view = this.view;

		if ( this.view !== null && this.view.enabled ) {

			const fullWidth = view.fullWidth,
				fullHeight = view.fullHeight;

			left += view.offsetX * width / fullWidth;
			top -= view.offsetY * height / fullHeight;
			width *= view.width / fullWidth;
			height *= view.height / fullHeight;

		}

		const skew = this.filmOffset;
		if ( skew !== 0 ) left += near * skew / this.getFilmWidth();

		this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );

		this.projectionMatrixInverse.getInverse( this.projectionMatrix );

	},

	toJSON: function ( meta ) {

		const data = Object3D.prototype.toJSON.call( this, meta );

		data.object.fov = this.fov;
		data.object.zoom = this.zoom;

		data.object.near = this.near;
		data.object.far = this.far;
		data.object.focus = this.focus;

		data.object.aspect = this.aspect;

		if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );

		data.object.filmGauge = this.filmGauge;
		data.object.filmOffset = this.filmOffset;

		return data;

	}

} );

/**
 * Camera for rendering cube maps
 *	- renders scene into axis-aligned cube
 *
 * @author alteredq / http://alteredqualia.com/
 */

const fov = 90, aspect = 1;

function CubeCamera( near, far, renderTarget ) {

	Object3D.call( this );

	this.type = 'CubeCamera';

	if ( renderTarget.isWebGLCubeRenderTarget !== true ) {

		console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
		return;

	}

	this.renderTarget = renderTarget;

	const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
	cameraPX.layers = this.layers;
	cameraPX.up.set( 0, - 1, 0 );
	cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
	this.add( cameraPX );

	const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
	cameraNX.layers = this.layers;
	cameraNX.up.set( 0, - 1, 0 );
	cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
	this.add( cameraNX );

	const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
	cameraPY.layers = this.layers;
	cameraPY.up.set( 0, 0, 1 );
	cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
	this.add( cameraPY );

	const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
	cameraNY.layers = this.layers;
	cameraNY.up.set( 0, 0, - 1 );
	cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
	this.add( cameraNY );

	const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
	cameraPZ.layers = this.layers;
	cameraPZ.up.set( 0, - 1, 0 );
	cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
	this.add( cameraPZ );

	const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
	cameraNZ.layers = this.layers;
	cameraNZ.up.set( 0, - 1, 0 );
	cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
	this.add( cameraNZ );

	this.update = function ( renderer, scene ) {

		if ( this.parent === null ) this.updateMatrixWorld();

		const currentXrEnabled = renderer.xr.enabled;
		const currentRenderTarget = renderer.getRenderTarget();

		renderer.xr.enabled = false;

		const generateMipmaps = renderTarget.texture.generateMipmaps;

		renderTarget.texture.generateMipmaps = false;

		renderer.setRenderTarget( renderTarget, 0 );
		renderer.render( scene, cameraPX );

		renderer.setRenderTarget( renderTarget, 1 );
		renderer.render( scene, cameraNX );

		renderer.setRenderTarget( renderTarget, 2 );
		renderer.render( scene, cameraPY );

		renderer.setRenderTarget( renderTarget, 3 );
		renderer.render( scene, cameraNY );

		renderer.setRenderTarget( renderTarget, 4 );
		renderer.render( scene, cameraPZ );

		renderTarget.texture.generateMipmaps = generateMipmaps;

		renderer.setRenderTarget( renderTarget, 5 );
		renderer.render( scene, cameraNZ );

		renderer.setRenderTarget( currentRenderTarget );

		renderer.xr.enabled = currentXrEnabled;

	};

	this.clear = function ( renderer, color, depth, stencil ) {

		const currentRenderTarget = renderer.getRenderTarget();

		for ( let i = 0; i < 6; i ++ ) {

			renderer.setRenderTarget( renderTarget, i );

			renderer.clear( color, depth, stencil );

		}

		renderer.setRenderTarget( currentRenderTarget );

	};

}

CubeCamera.prototype = Object.create( Object3D.prototype );
CubeCamera.prototype.constructor = CubeCamera;

/**
 * @author alteredq / http://alteredqualia.com
 * @author WestLangley / http://github.com/WestLangley
 */

function WebGLCubeRenderTarget( size, options, dummy ) {

	if ( Number.isInteger( options ) ) {

		console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );

		options = dummy;

	}

	WebGLRenderTarget.call( this, size, size, options );

}

WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;

WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;

WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {

	this.texture.type = texture.type;
	this.texture.format = texture.format;
	this.texture.encoding = texture.encoding;

	const scene = new Scene();

	const shader = {

		uniforms: {
			tEquirect: { value: null },
		},

		vertexShader: [

			"varying vec3 vWorldDirection;",

			"vec3 transformDirection( in vec3 dir, in mat4 matrix ) {",

			"	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );",

			"}",

			"void main() {",

			"	vWorldDirection = transformDirection( position, modelMatrix );",

			"	#include <begin_vertex>",
			"	#include <project_vertex>",

			"}"

		].join( '\n' ),

		fragmentShader: [

			"uniform sampler2D tEquirect;",

			"varying vec3 vWorldDirection;",

			"#include <common>",

			"void main() {",

			"	vec3 direction = normalize( vWorldDirection );",

			"	vec2 sampleUV = equirectUv( direction );",

			"	gl_FragColor = texture2D( tEquirect, sampleUV );",

			"}"

		].join( '\n' ),
	};

	const material = new ShaderMaterial( {

		name: 'CubemapFromEquirect',

		uniforms: cloneUniforms( shader.uniforms ),
		vertexShader: shader.vertexShader,
		fragmentShader: shader.fragmentShader,
		side: BackSide,
		blending: NoBlending

	} );

	material.uniforms.tEquirect.value = texture;

	const mesh = new Mesh( new BoxBufferGeometry( 5, 5, 5 ), material );

	scene.add( mesh );

	const camera = new CubeCamera( 1, 10, this );
	camera.update( renderer, scene );

	mesh.geometry.dispose();
	mesh.material.dispose();

	return this;

};

/**
 * @author alteredq / http://alteredqualia.com/
 */

function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {

	Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );

	this.image = { data: data || null, width: width || 1, height: height || 1 };

	this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
	this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;

	this.generateMipmaps = false;
	this.flipY = false;
	this.unpackAlignment = 1;

	this.needsUpdate = true;

}

DataTexture.prototype = Object.create( Texture.prototype );
DataTexture.prototype.constructor = DataTexture;

DataTexture.prototype.isDataTexture = true;

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author bhouston / http://clara.io
 */

const _sphere$1 = new Sphere();
const _vector$5 = new Vector3();

function Frustum( p0, p1, p2, p3, p4, p5 ) {

	this.planes = [

		( p0 !== undefined ) ? p0 : new Plane(),
		( p1 !== undefined ) ? p1 : new Plane(),
		( p2 !== undefined ) ? p2 : new Plane(),
		( p3 !== undefined ) ? p3 : new Plane(),
		( p4 !== undefined ) ? p4 : new Plane(),
		( p5 !== undefined ) ? p5 : new Plane()

	];

}

Object.assign( Frustum.prototype, {

	set: function ( p0, p1, p2, p3, p4, p5 ) {

		const planes = this.planes;

		planes[ 0 ].copy( p0 );
		planes[ 1 ].copy( p1 );
		planes[ 2 ].copy( p2 );
		planes[ 3 ].copy( p3 );
		planes[ 4 ].copy( p4 );
		planes[ 5 ].copy( p5 );

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( frustum ) {

		const planes = this.planes;

		for ( let i = 0; i < 6; i ++ ) {

			planes[ i ].copy( frustum.planes[ i ] );

		}

		return this;

	},

	setFromProjectionMatrix: function ( m ) {

		const planes = this.planes;
		const me = m.elements;
		const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
		const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
		const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
		const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];

		planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
		planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
		planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
		planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
		planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
		planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();

		return this;

	},

	intersectsObject: function ( object ) {

		const geometry = object.geometry;

		if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

		_sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );

		return this.intersectsSphere( _sphere$1 );

	},

	intersectsSprite: function ( sprite ) {

		_sphere$1.center.set( 0, 0, 0 );
		_sphere$1.radius = 0.7071067811865476;
		_sphere$1.applyMatrix4( sprite.matrixWorld );

		return this.intersectsSphere( _sphere$1 );

	},

	intersectsSphere: function ( sphere ) {

		const planes = this.planes;
		const center = sphere.center;
		const negRadius = - sphere.radius;

		for ( let i = 0; i < 6; i ++ ) {

			const distance = planes[ i ].distanceToPoint( center );

			if ( distance < negRadius ) {

				return false;

			}

		}

		return true;

	},

	intersectsBox: function ( box ) {

		const planes = this.planes;

		for ( let i = 0; i < 6; i ++ ) {

			const plane = planes[ i ];

			// corner at max distance

			_vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
			_vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
			_vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;

			if ( plane.distanceToPoint( _vector$5 ) < 0 ) {

				return false;

			}

		}

		return true;

	},

	containsPoint: function ( point ) {

		const planes = this.planes;

		for ( let i = 0; i < 6; i ++ ) {

			if ( planes[ i ].distanceToPoint( point ) < 0 ) {

				return false;

			}

		}

		return true;

	}

} );

/**
 * Uniforms library for shared webgl shaders
 */

const UniformsLib = {

	common: {

		diffuse: { value: new Color( 0xeeeeee ) },
		opacity: { value: 1.0 },

		map: { value: null },
		uvTransform: { value: new Matrix3() },
		uv2Transform: { value: new Matrix3() },

		alphaMap: { value: null },

	},

	specularmap: {

		specularMap: { value: null },

	},

	envmap: {

		envMap: { value: null },
		flipEnvMap: { value: - 1 },
		reflectivity: { value: 1.0 },
		refractionRatio: { value: 0.98 },
		maxMipLevel: { value: 0 }

	},

	aomap: {

		aoMap: { value: null },
		aoMapIntensity: { value: 1 }

	},

	lightmap: {

		lightMap: { value: null },
		lightMapIntensity: { value: 1 }

	},

	emissivemap: {

		emissiveMap: { value: null }

	},

	bumpmap: {

		bumpMap: { value: null },
		bumpScale: { value: 1 }

	},

	normalmap: {

		normalMap: { value: null },
		normalScale: { value: new Vector2( 1, 1 ) }

	},

	displacementmap: {

		displacementMap: { value: null },
		displacementScale: { value: 1 },
		displacementBias: { value: 0 }

	},

	roughnessmap: {

		roughnessMap: { value: null }

	},

	metalnessmap: {

		metalnessMap: { value: null }

	},

	gradientmap: {

		gradientMap: { value: null }

	},

	fog: {

		fogDensity: { value: 0.00025 },
		fogNear: { value: 1 },
		fogFar: { value: 2000 },
		fogColor: { value: new Color( 0xffffff ) }

	},

	lights: {

		ambientLightColor: { value: [] },

		lightProbe: { value: [] },

		directionalLights: { value: [], properties: {
			direction: {},
			color: {}
		} },

		directionalLightShadows: { value: [], properties: {
			shadowBias: {},
			shadowNormalBias: {},
			shadowRadius: {},
			shadowMapSize: {}
		} },

		directionalShadowMap: { value: [] },
		directionalShadowMatrix: { value: [] },

		spotLights: { value: [], properties: {
			color: {},
			position: {},
			direction: {},
			distance: {},
			coneCos: {},
			penumbraCos: {},
			decay: {}
		} },

		spotLightShadows: { value: [], properties: {
			shadowBias: {},
			shadowNormalBias: {},
			shadowRadius: {},
			shadowMapSize: {}
		} },

		spotShadowMap: { value: [] },
		spotShadowMatrix: { value: [] },

		pointLights: { value: [], properties: {
			color: {},
			position: {},
			decay: {},
			distance: {}
		} },

		pointLightShadows: { value: [], properties: {
			shadowBias: {},
			shadowNormalBias: {},
			shadowRadius: {},
			shadowMapSize: {},
			shadowCameraNear: {},
			shadowCameraFar: {}
		} },

		pointShadowMap: { value: [] },
		pointShadowMatrix: { value: [] },

		hemisphereLights: { value: [], properties: {
			direction: {},
			skyColor: {},
			groundColor: {}
		} },

		// TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
		rectAreaLights: { value: [], properties: {
			color: {},
			position: {},
			width: {},
			height: {}
		} }

	},

	points: {

		diffuse: { value: new Color( 0xeeeeee ) },
		opacity: { value: 1.0 },
		size: { value: 1.0 },
		scale: { value: 1.0 },
		map: { value: null },
		alphaMap: { value: null },
		uvTransform: { value: new Matrix3() }

	},

	sprite: {

		diffuse: { value: new Color( 0xeeeeee ) },
		opacity: { value: 1.0 },
		center: { value: new Vector2( 0.5, 0.5 ) },
		rotation: { value: 0.0 },
		map: { value: null },
		alphaMap: { value: null },
		uvTransform: { value: new Matrix3() }

	}

};

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLAnimation() {

	let context = null;
	let isAnimating = false;
	let animationLoop = null;
	let requestId = null;

	function onAnimationFrame( time, frame ) {

		animationLoop( time, frame );

		requestId = context.requestAnimationFrame( onAnimationFrame );

	}

	return {

		start: function () {

			if ( isAnimating === true ) return;
			if ( animationLoop === null ) return;

			requestId = context.requestAnimationFrame( onAnimationFrame );

			isAnimating = true;

		},

		stop: function () {

			context.cancelAnimationFrame( requestId );

			isAnimating = false;

		},

		setAnimationLoop: function ( callback ) {

			animationLoop = callback;

		},

		setContext: function ( value ) {

			context = value;

		}

	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLAttributes( gl, capabilities ) {

	const isWebGL2 = capabilities.isWebGL2;

	const buffers = new WeakMap();

	function createBuffer( attribute, bufferType ) {

		const array = attribute.array;
		const usage = attribute.usage;

		const buffer = gl.createBuffer();

		gl.bindBuffer( bufferType, buffer );
		gl.bufferData( bufferType, array, usage );

		attribute.onUploadCallback();

		let type = 5126;

		if ( array instanceof Float32Array ) {

			type = 5126;

		} else if ( array instanceof Float64Array ) {

			console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );

		} else if ( array instanceof Uint16Array ) {

			type = 5123;

		} else if ( array instanceof Int16Array ) {

			type = 5122;

		} else if ( array instanceof Uint32Array ) {

			type = 5125;

		} else if ( array instanceof Int32Array ) {

			type = 5124;

		} else if ( array instanceof Int8Array ) {

			type = 5120;

		} else if ( array instanceof Uint8Array ) {

			type = 5121;

		}

		return {
			buffer: buffer,
			type: type,
			bytesPerElement: array.BYTES_PER_ELEMENT,
			version: attribute.version
		};

	}

	function updateBuffer( buffer, attribute, bufferType ) {

		const array = attribute.array;
		const updateRange = attribute.updateRange;

		gl.bindBuffer( bufferType, buffer );

		if ( updateRange.count === - 1 ) {

			// Not using update ranges

			gl.bufferSubData( bufferType, 0, array );

		} else {

			if ( isWebGL2 ) {

				gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
					array, updateRange.offset, updateRange.count );

			} else {

				gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
					array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );

			}

			updateRange.count = - 1; // reset range

		}

	}

	//

	function get( attribute ) {

		if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;

		return buffers.get( attribute );

	}

	function remove( attribute ) {

		if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;

		const data = buffers.get( attribute );

		if ( data ) {

			gl.deleteBuffer( data.buffer );

			buffers.delete( attribute );

		}

	}

	function update( attribute, bufferType ) {

		if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;

		const data = buffers.get( attribute );

		if ( data === undefined ) {

			buffers.set( attribute, createBuffer( attribute, bufferType ) );

		} else if ( data.version < attribute.version ) {

			updateBuffer( data.buffer, attribute, bufferType );

			data.version = attribute.version;

		}

	}

	return {

		get: get,
		remove: remove,
		update: update

	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / https://github.com/Mugen87
 */

// PlaneGeometry

function PlaneGeometry( width, height, widthSegments, heightSegments ) {

	Geometry.call( this );

	this.type = 'PlaneGeometry';

	this.parameters = {
		width: width,
		height: height,
		widthSegments: widthSegments,
		heightSegments: heightSegments
	};

	this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
	this.mergeVertices();

}

PlaneGeometry.prototype = Object.create( Geometry.prototype );
PlaneGeometry.prototype.constructor = PlaneGeometry;

// PlaneBufferGeometry

function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {

	BufferGeometry.call( this );

	this.type = 'PlaneBufferGeometry';

	this.parameters = {
		width: width,
		height: height,
		widthSegments: widthSegments,
		heightSegments: heightSegments
	};

	width = width || 1;
	height = height || 1;

	const width_half = width / 2;
	const height_half = height / 2;

	const gridX = Math.floor( widthSegments ) || 1;
	const gridY = Math.floor( heightSegments ) || 1;

	const gridX1 = gridX + 1;
	const gridY1 = gridY + 1;

	const segment_width = width / gridX;
	const segment_height = height / gridY;

	// buffers

	const indices = [];
	const vertices = [];
	const normals = [];
	const uvs = [];

	// generate vertices, normals and uvs

	for ( let iy = 0; iy < gridY1; iy ++ ) {

		const y = iy * segment_height - height_half;

		for ( let ix = 0; ix < gridX1; ix ++ ) {

			const x = ix * segment_width - width_half;

			vertices.push( x, - y, 0 );

			normals.push( 0, 0, 1 );

			uvs.push( ix / gridX );
			uvs.push( 1 - ( iy / gridY ) );

		}

	}

	// indices

	for ( let iy = 0; iy < gridY; iy ++ ) {

		for ( let ix = 0; ix < gridX; ix ++ ) {

			const a = ix + gridX1 * iy;
			const b = ix + gridX1 * ( iy + 1 );
			const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
			const d = ( ix + 1 ) + gridX1 * iy;

			// faces

			indices.push( a, b, d );
			indices.push( b, c, d );

		}

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

}

PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;

var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";

var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";

var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";

var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";

var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";

var begin_vertex = "vec3 transformed = vec3( position );";

var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";

var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE  = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS  = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha  = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";

var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";

var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";

var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";

var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";

var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";

var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";

var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";

var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";

var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";

var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n  return m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";

var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_maxMipLevel 8.0\n#define cubeUV_minMipLevel 4.0\n#define cubeUV_maxTileSize 256.0\n#define cubeUV_minTileSize 16.0\nfloat getFace(vec3 direction) {\n    vec3 absDirection = abs(direction);\n    float face = -1.0;\n    if (absDirection.x > absDirection.z) {\n      if (absDirection.x > absDirection.y)\n        face = direction.x > 0.0 ? 0.0 : 3.0;\n      else\n        face = direction.y > 0.0 ? 1.0 : 4.0;\n    } else {\n      if (absDirection.z > absDirection.y)\n        face = direction.z > 0.0 ? 2.0 : 5.0;\n      else\n        face = direction.y > 0.0 ? 1.0 : 4.0;\n    }\n    return face;\n}\nvec2 getUV(vec3 direction, float face) {\n    vec2 uv;\n    if (face == 0.0) {\n      uv = vec2(direction.z, direction.y) / abs(direction.x);    } else if (face == 1.0) {\n      uv = vec2(-direction.x, -direction.z) / abs(direction.y);    } else if (face == 2.0) {\n      uv = vec2(-direction.x, direction.y) / abs(direction.z);    } else if (face == 3.0) {\n      uv = vec2(-direction.z, direction.y) / abs(direction.x);    } else if (face == 4.0) {\n      uv = vec2(-direction.x, direction.z) / abs(direction.y);    } else {\n      uv = vec2(direction.x, direction.y) / abs(direction.z);    }\n    return 0.5 * (uv + 1.0);\n}\nvec3 bilinearCubeUV(sampler2D envMap, vec3 direction, float mipInt) {\n  float face = getFace(direction);\n  float filterInt = max(cubeUV_minMipLevel - mipInt, 0.0);\n  mipInt = max(mipInt, cubeUV_minMipLevel);\n  float faceSize = exp2(mipInt);\n  float texelSize = 1.0 / (3.0 * cubeUV_maxTileSize);\n  vec2 uv = getUV(direction, face) * (faceSize - 1.0);\n  vec2 f = fract(uv);\n  uv += 0.5 - f;\n  if (face > 2.0) {\n    uv.y += faceSize;\n    face -= 3.0;\n  }\n  uv.x += face * faceSize;\n  if(mipInt < cubeUV_maxMipLevel){\n    uv.y += 2.0 * cubeUV_maxTileSize;\n  }\n  uv.y += filterInt * 2.0 * cubeUV_minTileSize;\n  uv.x += 3.0 * max(0.0, cubeUV_maxTileSize - 2.0 * faceSize);\n  uv *= texelSize;\n  vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n  uv.x += texelSize;\n  vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n  uv.y += texelSize;\n  vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n  uv.x -= texelSize;\n  vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;\n  vec3 tm = mix(tl, tr, f.x);\n  vec3 bm = mix(bl, br, f.x);\n  return mix(tm, bm, f.y);\n}\n#define r0 1.0\n#define v0 0.339\n#define m0 -2.0\n#define r1 0.8\n#define v1 0.276\n#define m1 -1.0\n#define r4 0.4\n#define v4 0.046\n#define m4 2.0\n#define r5 0.305\n#define v5 0.016\n#define m5 3.0\n#define r6 0.21\n#define v6 0.0038\n#define m6 4.0\nfloat roughnessToMip(float roughness) {\n  float mip = 0.0;\n  if (roughness >= r1) {\n    mip = (r0 - roughness) * (m1 - m0) / (r0 - r1) + m0;\n  } else if (roughness >= r4) {\n    mip = (r1 - roughness) * (m4 - m1) / (r1 - r4) + m1;\n  } else if (roughness >= r5) {\n    mip = (r4 - roughness) * (m5 - m4) / (r4 - r5) + m4;\n  } else if (roughness >= r6) {\n    mip = (r5 - roughness) * (m6 - m5) / (r5 - r6) + m5;\n  } else {\n    mip = -2.0 * log2(1.16 * roughness);  }\n  return mip;\n}\nvec4 textureCubeUV(sampler2D envMap, vec3 sampleDir, float roughness) {\n  float mip = clamp(roughnessToMip(roughness), m0, cubeUV_maxMipLevel);\n  float mipF = fract(mip);\n  float mipInt = floor(mip);\n  vec3 color0 = bilinearCubeUV(envMap, sampleDir, mipInt);\n  if (mipF == 0.0) {\n    return vec4(color0, 1.0);\n  } else {\n    vec3 color1 = bilinearCubeUV(envMap, sampleDir, mipInt + 1.0);\n    return vec4(mix(color0, color1, mipF), 1.0);\n  }\n}\n#endif";

var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";

var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";

var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";

var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";

var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";

var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";

var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value )  {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";

var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\t\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t}  else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\treflectVec = normalize( reflectVec );\n\t\tvec2 sampleUV = equirectUv( reflectVec );\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";

var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";

var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";

var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";

var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) { \n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";

var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = -mvPosition.z;\n#endif";

var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";

var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";

var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";

var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";

var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";

var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";

var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";

var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight  ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";

var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t  vec3 reflectVec = reflect( -viewDir, normal );\n\t\t  reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t  vec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV = equirectUv( reflectVec );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";

var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";

var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3\tdiffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";

var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";

var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";

var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";

var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3(    0, 1,    0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";

var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";

var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";

var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";

var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";

var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";

var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";

var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";

var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";

var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";

var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";

var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";

var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";

var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";

var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";

var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";

var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";

var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";

var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";

var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";

var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";

var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";

var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";

var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";

var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";

var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";

var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";

var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";

var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";

var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";

var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t  f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t  f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";

var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";

var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";

var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";

var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";

var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";

var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";

var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix  = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";

var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";

var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";

var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";

var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3(  1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108,  1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605,  1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";

var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";

var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";

var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";

var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";

var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";

var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";

var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";

var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";

var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";

var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";

var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";

var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";

var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";

var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";

var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";

var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";

var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";

var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";

var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";

var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";

var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";

var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSPARENCY\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSPARENCY\n\tuniform float transparency;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSPARENCY\n\t\tdiffuseColor.a *= saturate( 1. - transparency + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";

var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";

var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";

var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";

var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";

var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";

var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";

var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";

var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";

const ShaderChunk = {
	alphamap_fragment: alphamap_fragment,
	alphamap_pars_fragment: alphamap_pars_fragment,
	alphatest_fragment: alphatest_fragment,
	aomap_fragment: aomap_fragment,
	aomap_pars_fragment: aomap_pars_fragment,
	begin_vertex: begin_vertex,
	beginnormal_vertex: beginnormal_vertex,
	bsdfs: bsdfs,
	bumpmap_pars_fragment: bumpmap_pars_fragment,
	clipping_planes_fragment: clipping_planes_fragment,
	clipping_planes_pars_fragment: clipping_planes_pars_fragment,
	clipping_planes_pars_vertex: clipping_planes_pars_vertex,
	clipping_planes_vertex: clipping_planes_vertex,
	color_fragment: color_fragment,
	color_pars_fragment: color_pars_fragment,
	color_pars_vertex: color_pars_vertex,
	color_vertex: color_vertex,
	common: common,
	cube_uv_reflection_fragment: cube_uv_reflection_fragment,
	defaultnormal_vertex: defaultnormal_vertex,
	displacementmap_pars_vertex: displacementmap_pars_vertex,
	displacementmap_vertex: displacementmap_vertex,
	emissivemap_fragment: emissivemap_fragment,
	emissivemap_pars_fragment: emissivemap_pars_fragment,
	encodings_fragment: encodings_fragment,
	encodings_pars_fragment: encodings_pars_fragment,
	envmap_fragment: envmap_fragment,
	envmap_common_pars_fragment: envmap_common_pars_fragment,
	envmap_pars_fragment: envmap_pars_fragment,
	envmap_pars_vertex: envmap_pars_vertex,
	envmap_physical_pars_fragment: envmap_physical_pars_fragment,
	envmap_vertex: envmap_vertex,
	fog_vertex: fog_vertex,
	fog_pars_vertex: fog_pars_vertex,
	fog_fragment: fog_fragment,
	fog_pars_fragment: fog_pars_fragment,
	gradientmap_pars_fragment: gradientmap_pars_fragment,
	lightmap_fragment: lightmap_fragment,
	lightmap_pars_fragment: lightmap_pars_fragment,
	lights_lambert_vertex: lights_lambert_vertex,
	lights_pars_begin: lights_pars_begin,
	lights_toon_fragment: lights_toon_fragment,
	lights_toon_pars_fragment: lights_toon_pars_fragment,
	lights_phong_fragment: lights_phong_fragment,
	lights_phong_pars_fragment: lights_phong_pars_fragment,
	lights_physical_fragment: lights_physical_fragment,
	lights_physical_pars_fragment: lights_physical_pars_fragment,
	lights_fragment_begin: lights_fragment_begin,
	lights_fragment_maps: lights_fragment_maps,
	lights_fragment_end: lights_fragment_end,
	logdepthbuf_fragment: logdepthbuf_fragment,
	logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
	logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
	logdepthbuf_vertex: logdepthbuf_vertex,
	map_fragment: map_fragment,
	map_pars_fragment: map_pars_fragment,
	map_particle_fragment: map_particle_fragment,
	map_particle_pars_fragment: map_particle_pars_fragment,
	metalnessmap_fragment: metalnessmap_fragment,
	metalnessmap_pars_fragment: metalnessmap_pars_fragment,
	morphnormal_vertex: morphnormal_vertex,
	morphtarget_pars_vertex: morphtarget_pars_vertex,
	morphtarget_vertex: morphtarget_vertex,
	normal_fragment_begin: normal_fragment_begin,
	normal_fragment_maps: normal_fragment_maps,
	normalmap_pars_fragment: normalmap_pars_fragment,
	clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
	clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
	clearcoat_pars_fragment: clearcoat_pars_fragment,
	packing: packing,
	premultiplied_alpha_fragment: premultiplied_alpha_fragment,
	project_vertex: project_vertex,
	dithering_fragment: dithering_fragment,
	dithering_pars_fragment: dithering_pars_fragment,
	roughnessmap_fragment: roughnessmap_fragment,
	roughnessmap_pars_fragment: roughnessmap_pars_fragment,
	shadowmap_pars_fragment: shadowmap_pars_fragment,
	shadowmap_pars_vertex: shadowmap_pars_vertex,
	shadowmap_vertex: shadowmap_vertex,
	shadowmask_pars_fragment: shadowmask_pars_fragment,
	skinbase_vertex: skinbase_vertex,
	skinning_pars_vertex: skinning_pars_vertex,
	skinning_vertex: skinning_vertex,
	skinnormal_vertex: skinnormal_vertex,
	specularmap_fragment: specularmap_fragment,
	specularmap_pars_fragment: specularmap_pars_fragment,
	tonemapping_fragment: tonemapping_fragment,
	tonemapping_pars_fragment: tonemapping_pars_fragment,
	uv_pars_fragment: uv_pars_fragment,
	uv_pars_vertex: uv_pars_vertex,
	uv_vertex: uv_vertex,
	uv2_pars_fragment: uv2_pars_fragment,
	uv2_pars_vertex: uv2_pars_vertex,
	uv2_vertex: uv2_vertex,
	worldpos_vertex: worldpos_vertex,

	background_frag: background_frag,
	background_vert: background_vert,
	cube_frag: cube_frag,
	cube_vert: cube_vert,
	depth_frag: depth_frag,
	depth_vert: depth_vert,
	distanceRGBA_frag: distanceRGBA_frag,
	distanceRGBA_vert: distanceRGBA_vert,
	equirect_frag: equirect_frag,
	equirect_vert: equirect_vert,
	linedashed_frag: linedashed_frag,
	linedashed_vert: linedashed_vert,
	meshbasic_frag: meshbasic_frag,
	meshbasic_vert: meshbasic_vert,
	meshlambert_frag: meshlambert_frag,
	meshlambert_vert: meshlambert_vert,
	meshmatcap_frag: meshmatcap_frag,
	meshmatcap_vert: meshmatcap_vert,
	meshtoon_frag: meshtoon_frag,
	meshtoon_vert: meshtoon_vert,
	meshphong_frag: meshphong_frag,
	meshphong_vert: meshphong_vert,
	meshphysical_frag: meshphysical_frag,
	meshphysical_vert: meshphysical_vert,
	normal_frag: normal_frag,
	normal_vert: normal_vert,
	points_frag: points_frag,
	points_vert: points_vert,
	shadow_frag: shadow_frag,
	shadow_vert: shadow_vert,
	sprite_frag: sprite_frag,
	sprite_vert: sprite_vert
};

/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 * @author mikael emtinger / http://gomo.se/
 */

const ShaderLib = {

	basic: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.specularmap,
			UniformsLib.envmap,
			UniformsLib.aomap,
			UniformsLib.lightmap,
			UniformsLib.fog
		] ),

		vertexShader: ShaderChunk.meshbasic_vert,
		fragmentShader: ShaderChunk.meshbasic_frag

	},

	lambert: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.specularmap,
			UniformsLib.envmap,
			UniformsLib.aomap,
			UniformsLib.lightmap,
			UniformsLib.emissivemap,
			UniformsLib.fog,
			UniformsLib.lights,
			{
				emissive: { value: new Color( 0x000000 ) }
			}
		] ),

		vertexShader: ShaderChunk.meshlambert_vert,
		fragmentShader: ShaderChunk.meshlambert_frag

	},

	phong: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.specularmap,
			UniformsLib.envmap,
			UniformsLib.aomap,
			UniformsLib.lightmap,
			UniformsLib.emissivemap,
			UniformsLib.bumpmap,
			UniformsLib.normalmap,
			UniformsLib.displacementmap,
			UniformsLib.fog,
			UniformsLib.lights,
			{
				emissive: { value: new Color( 0x000000 ) },
				specular: { value: new Color( 0x111111 ) },
				shininess: { value: 30 }
			}
		] ),

		vertexShader: ShaderChunk.meshphong_vert,
		fragmentShader: ShaderChunk.meshphong_frag

	},

	standard: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.envmap,
			UniformsLib.aomap,
			UniformsLib.lightmap,
			UniformsLib.emissivemap,
			UniformsLib.bumpmap,
			UniformsLib.normalmap,
			UniformsLib.displacementmap,
			UniformsLib.roughnessmap,
			UniformsLib.metalnessmap,
			UniformsLib.fog,
			UniformsLib.lights,
			{
				emissive: { value: new Color( 0x000000 ) },
				roughness: { value: 1.0 },
				metalness: { value: 0.0 },
				envMapIntensity: { value: 1 } // temporary
			}
		] ),

		vertexShader: ShaderChunk.meshphysical_vert,
		fragmentShader: ShaderChunk.meshphysical_frag

	},

	toon: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.aomap,
			UniformsLib.lightmap,
			UniformsLib.emissivemap,
			UniformsLib.bumpmap,
			UniformsLib.normalmap,
			UniformsLib.displacementmap,
			UniformsLib.gradientmap,
			UniformsLib.fog,
			UniformsLib.lights,
			{
				emissive: { value: new Color( 0x000000 ) }
			}
		] ),

		vertexShader: ShaderChunk.meshtoon_vert,
		fragmentShader: ShaderChunk.meshtoon_frag

	},

	matcap: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.bumpmap,
			UniformsLib.normalmap,
			UniformsLib.displacementmap,
			UniformsLib.fog,
			{
				matcap: { value: null }
			}
		] ),

		vertexShader: ShaderChunk.meshmatcap_vert,
		fragmentShader: ShaderChunk.meshmatcap_frag

	},

	points: {

		uniforms: mergeUniforms( [
			UniformsLib.points,
			UniformsLib.fog
		] ),

		vertexShader: ShaderChunk.points_vert,
		fragmentShader: ShaderChunk.points_frag

	},

	dashed: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.fog,
			{
				scale: { value: 1 },
				dashSize: { value: 1 },
				totalSize: { value: 2 }
			}
		] ),

		vertexShader: ShaderChunk.linedashed_vert,
		fragmentShader: ShaderChunk.linedashed_frag

	},

	depth: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.displacementmap
		] ),

		vertexShader: ShaderChunk.depth_vert,
		fragmentShader: ShaderChunk.depth_frag

	},

	normal: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.bumpmap,
			UniformsLib.normalmap,
			UniformsLib.displacementmap,
			{
				opacity: { value: 1.0 }
			}
		] ),

		vertexShader: ShaderChunk.normal_vert,
		fragmentShader: ShaderChunk.normal_frag

	},

	sprite: {

		uniforms: mergeUniforms( [
			UniformsLib.sprite,
			UniformsLib.fog
		] ),

		vertexShader: ShaderChunk.sprite_vert,
		fragmentShader: ShaderChunk.sprite_frag

	},

	background: {

		uniforms: {
			uvTransform: { value: new Matrix3() },
			t2D: { value: null },
		},

		vertexShader: ShaderChunk.background_vert,
		fragmentShader: ShaderChunk.background_frag

	},
	/* -------------------------------------------------------------------------
	//	Cube map shader
	 ------------------------------------------------------------------------- */

	cube: {

		uniforms: mergeUniforms( [
			UniformsLib.envmap,
			{
				opacity: { value: 1.0 }
			}
		] ),

		vertexShader: ShaderChunk.cube_vert,
		fragmentShader: ShaderChunk.cube_frag

	},

	equirect: {

		uniforms: {
			tEquirect: { value: null },
		},

		vertexShader: ShaderChunk.equirect_vert,
		fragmentShader: ShaderChunk.equirect_frag

	},

	distanceRGBA: {

		uniforms: mergeUniforms( [
			UniformsLib.common,
			UniformsLib.displacementmap,
			{
				referencePosition: { value: new Vector3() },
				nearDistance: { value: 1 },
				farDistance: { value: 1000 }
			}
		] ),

		vertexShader: ShaderChunk.distanceRGBA_vert,
		fragmentShader: ShaderChunk.distanceRGBA_frag

	},

	shadow: {

		uniforms: mergeUniforms( [
			UniformsLib.lights,
			UniformsLib.fog,
			{
				color: { value: new Color( 0x00000 ) },
				opacity: { value: 1.0 }
			},
		] ),

		vertexShader: ShaderChunk.shadow_vert,
		fragmentShader: ShaderChunk.shadow_frag

	}

};

ShaderLib.physical = {

	uniforms: mergeUniforms( [
		ShaderLib.standard.uniforms,
		{
			clearcoat: { value: 0 },
			clearcoatMap: { value: null },
			clearcoatRoughness: { value: 0 },
			clearcoatRoughnessMap: { value: null },
			clearcoatNormalScale: { value: new Vector2( 1, 1 ) },
			clearcoatNormalMap: { value: null },
			sheen: { value: new Color( 0x000000 ) },
			transparency: { value: 0 },
		}
	] ),

	vertexShader: ShaderChunk.meshphysical_vert,
	fragmentShader: ShaderChunk.meshphysical_frag

};

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLBackground( renderer, state, objects, premultipliedAlpha ) {

	const clearColor = new Color( 0x000000 );
	let clearAlpha = 0;

	let planeMesh;
	let boxMesh;

	let currentBackground = null;
	let currentBackgroundVersion = 0;
	let currentTonemapping = null;

	function render( renderList, scene, camera, forceClear ) {

		let background = scene.isScene === true ? scene.background : null;

		// Ignore background in AR
		// TODO: Reconsider this.

		const xr = renderer.xr;
		const session = xr.getSession && xr.getSession();

		if ( session && session.environmentBlendMode === 'additive' ) {

			background = null;

		}

		if ( background === null ) {

			setClear( clearColor, clearAlpha );

		} else if ( background && background.isColor ) {

			setClear( background, 1 );
			forceClear = true;

		}

		if ( renderer.autoClear || forceClear ) {

			renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );

		}

		if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) {

			if ( boxMesh === undefined ) {

				boxMesh = new Mesh(
					new BoxBufferGeometry( 1, 1, 1 ),
					new ShaderMaterial( {
						name: 'BackgroundCubeMaterial',
						uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
						vertexShader: ShaderLib.cube.vertexShader,
						fragmentShader: ShaderLib.cube.fragmentShader,
						side: BackSide,
						depthTest: false,
						depthWrite: false,
						fog: false
					} )
				);

				boxMesh.geometry.deleteAttribute( 'normal' );
				boxMesh.geometry.deleteAttribute( 'uv' );

				boxMesh.onBeforeRender = function ( renderer, scene, camera ) {

					this.matrixWorld.copyPosition( camera.matrixWorld );

				};

				// enable code injection for non-built-in material
				Object.defineProperty( boxMesh.material, 'envMap', {

					get: function () {

						return this.uniforms.envMap.value;

					}

				} );

				objects.update( boxMesh );

			}

			const texture = background.isWebGLCubeRenderTarget ? background.texture : background;

			boxMesh.material.uniforms.envMap.value = texture;
			boxMesh.material.uniforms.flipEnvMap.value = texture.isCubeTexture ? - 1 : 1;

			if ( currentBackground !== background ||
				currentBackgroundVersion !== texture.version ||
				currentTonemapping !== renderer.toneMapping ) {

				boxMesh.material.needsUpdate = true;

				currentBackground = background;
				currentBackgroundVersion = texture.version;
				currentTonemapping = renderer.toneMapping;

			}

			// push to the pre-sorted opaque render list
			renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );

		} else if ( background && background.isTexture ) {

			if ( planeMesh === undefined ) {

				planeMesh = new Mesh(
					new PlaneBufferGeometry( 2, 2 ),
					new ShaderMaterial( {
						name: 'BackgroundMaterial',
						uniforms: cloneUniforms( ShaderLib.background.uniforms ),
						vertexShader: ShaderLib.background.vertexShader,
						fragmentShader: ShaderLib.background.fragmentShader,
						side: FrontSide,
						depthTest: false,
						depthWrite: false,
						fog: false
					} )
				);

				planeMesh.geometry.deleteAttribute( 'normal' );

				// enable code injection for non-built-in material
				Object.defineProperty( planeMesh.material, 'map', {

					get: function () {

						return this.uniforms.t2D.value;

					}

				} );

				objects.update( planeMesh );

			}

			planeMesh.material.uniforms.t2D.value = background;

			if ( background.matrixAutoUpdate === true ) {

				background.updateMatrix();

			}

			planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );

			if ( currentBackground !== background ||
				currentBackgroundVersion !== background.version ||
				currentTonemapping !== renderer.toneMapping ) {

				planeMesh.material.needsUpdate = true;

				currentBackground = background;
				currentBackgroundVersion = background.version;
				currentTonemapping = renderer.toneMapping;

			}


			// push to the pre-sorted opaque render list
			renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );

		}

	}

	function setClear( color, alpha ) {

		state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );

	}

	return {

		getClearColor: function () {

			return clearColor;

		},
		setClearColor: function ( color, alpha ) {

			clearColor.set( color );
			clearAlpha = alpha !== undefined ? alpha : 1;
			setClear( clearColor, clearAlpha );

		},
		getClearAlpha: function () {

			return clearAlpha;

		},
		setClearAlpha: function ( alpha ) {

			clearAlpha = alpha;
			setClear( clearColor, clearAlpha );

		},
		render: render

	};

}

/**
 * @author Mugen87 / https://github.com/Mugen87
 * @author Takahiro / https://github.com/takahirox
 */

function WebGLBindingStates( gl, extensions, attributes, capabilities ) {

	const maxVertexAttributes = gl.getParameter( 34921 );

	const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
	const vaoAvailable = capabilities.isWebGL2 || extension !== null;

	const bindingStates = {};

	const defaultState = createBindingState( null );
	let currentState = defaultState;

	function setup( object, material, program, geometry, index ) {

		let updateBuffers = false;

		if ( vaoAvailable ) {

			const state = getBindingState( geometry, program, material );

			if ( currentState !== state ) {

				currentState = state;
				bindVertexArrayObject( currentState.object );

			}

			updateBuffers = needsUpdate( geometry );

			if ( updateBuffers ) saveCache( geometry );

		} else {

			const wireframe = ( material.wireframe === true );

			if ( currentState.geometry !== geometry.id ||
				currentState.program !== program.id ||
				currentState.wireframe !== wireframe ) {

				currentState.geometry = geometry.id;
				currentState.program = program.id;
				currentState.wireframe = wireframe;

				updateBuffers = true;

			}

		}

		if ( object.isInstancedMesh === true ) {

			updateBuffers = true;

		}

		if ( index !== null ) {

			attributes.update( index, 34963 );

		}

		if ( updateBuffers ) {

			setupVertexAttributes( object, material, program, geometry );

			if ( index !== null ) {

				gl.bindBuffer( 34963, attributes.get( index ).buffer );

			}

		}

	}

	function createVertexArrayObject() {

		if ( capabilities.isWebGL2 ) return gl.createVertexArray();

		return extension.createVertexArrayOES();

	}

	function bindVertexArrayObject( vao ) {

		if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );

		return extension.bindVertexArrayOES( vao );

	}

	function deleteVertexArrayObject( vao ) {

		if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );

		return extension.deleteVertexArrayOES( vao );

	}

	function getBindingState( geometry, program, material ) {

		const wireframe = ( material.wireframe === true );

		let programMap = bindingStates[ geometry.id ];

		if ( programMap === undefined ) {

			programMap = {};
			bindingStates[ geometry.id ] = programMap;

		}

		let stateMap = programMap[ program.id ];

		if ( stateMap === undefined ) {

			stateMap = {};
			programMap[ program.id ] = stateMap;

		}

		let state = stateMap[ wireframe ];

		if ( state === undefined ) {

			state = createBindingState( createVertexArrayObject() );
			stateMap[ wireframe ] = state;

		}

		return state;

	}

	function createBindingState( vao ) {

		const newAttributes = [];
		const enabledAttributes = [];
		const attributeDivisors = [];

		for ( let i = 0; i < maxVertexAttributes; i ++ ) {

			newAttributes[ i ] = 0;
			enabledAttributes[ i ] = 0;
			attributeDivisors[ i ] = 0;

		}

		return {

			// for backward compatibility on non-VAO support browser
			geometry: null,
			program: null,
			wireframe: false,

			newAttributes: newAttributes,
			enabledAttributes: enabledAttributes,
			attributeDivisors: attributeDivisors,
			object: vao,
			attributes: {}

		};

	}

	function needsUpdate( geometry ) {

		const cachedAttributes = currentState.attributes;
		const geometryAttributes = geometry.attributes;

		if ( Object.keys( cachedAttributes ).length !== Object.keys( geometryAttributes ).length ) return true;

		for ( const key in geometryAttributes ) {

			const cachedAttribute = cachedAttributes[ key ];
			const geometryAttribute = geometryAttributes[ key ];

			if ( cachedAttribute.attribute !== geometryAttribute ) return true;

			if ( cachedAttribute.data !== geometryAttribute.data ) return true;

		}

		return false;

	}

	function saveCache( geometry ) {

		const cache = {};
		const attributes = geometry.attributes;

		for ( const key in attributes ) {

			const attribute = attributes[ key ];

			const data = {};
			data.attribute = attribute;

			if ( attribute.data ) {

				data.data = attribute.data;

			}

			cache[ key ] = data;

		}

		currentState.attributes = cache;

	}

	function initAttributes() {

		const newAttributes = currentState.newAttributes;

		for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {

			newAttributes[ i ] = 0;

		}

	}

	function enableAttribute( attribute ) {

		enableAttributeAndDivisor( attribute, 0 );

	}

	function enableAttributeAndDivisor( attribute, meshPerAttribute ) {

		const newAttributes = currentState.newAttributes;
		const enabledAttributes = currentState.enabledAttributes;
		const attributeDivisors = currentState.attributeDivisors;

		newAttributes[ attribute ] = 1;

		if ( enabledAttributes[ attribute ] === 0 ) {

			gl.enableVertexAttribArray( attribute );
			enabledAttributes[ attribute ] = 1;

		}

		if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {

			const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );

			extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
			attributeDivisors[ attribute ] = meshPerAttribute;

		}

	}

	function disableUnusedAttributes() {

		const newAttributes = currentState.newAttributes;
		const enabledAttributes = currentState.enabledAttributes;

		for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {

			if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {

				gl.disableVertexAttribArray( i );
				enabledAttributes[ i ] = 0;

			}

		}

	}

	function vertexAttribPointer( index, size, type, normalized, stride, offset ) {

		if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {

			gl.vertexAttribIPointer( index, size, type, normalized, stride, offset );

		} else {

			gl.vertexAttribPointer( index, size, type, normalized, stride, offset );

		}

	}

	function setupVertexAttributes( object, material, program, geometry ) {

		if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {

			if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;

		}

		initAttributes();

		const geometryAttributes = geometry.attributes;

		const programAttributes = program.getAttributes();

		const materialDefaultAttributeValues = material.defaultAttributeValues;

		for ( const name in programAttributes ) {

			const programAttribute = programAttributes[ name ];

			if ( programAttribute >= 0 ) {

				const geometryAttribute = geometryAttributes[ name ];

				if ( geometryAttribute !== undefined ) {

					const normalized = geometryAttribute.normalized;
					const size = geometryAttribute.itemSize;

					const attribute = attributes.get( geometryAttribute );

					// TODO Attribute may not be available on context restore

					if ( attribute === undefined ) continue;

					const buffer = attribute.buffer;
					const type = attribute.type;
					const bytesPerElement = attribute.bytesPerElement;

					if ( geometryAttribute.isInterleavedBufferAttribute ) {

						const data = geometryAttribute.data;
						const stride = data.stride;
						const offset = geometryAttribute.offset;

						if ( data && data.isInstancedInterleavedBuffer ) {

							enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );

							if ( geometry._maxInstanceCount === undefined ) {

								geometry._maxInstanceCount = data.meshPerAttribute * data.count;

							}

						} else {

							enableAttribute( programAttribute );

						}

						gl.bindBuffer( 34962, buffer );
						vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );

					} else {

						if ( geometryAttribute.isInstancedBufferAttribute ) {

							enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );

							if ( geometry._maxInstanceCount === undefined ) {

								geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;

							}

						} else {

							enableAttribute( programAttribute );

						}

						gl.bindBuffer( 34962, buffer );
						vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );

					}

				} else if ( name === 'instanceMatrix' ) {

					const attribute = attributes.get( object.instanceMatrix );

					// TODO Attribute may not be available on context restore

					if ( attribute === undefined ) continue;

					const buffer = attribute.buffer;
					const type = attribute.type;

					enableAttributeAndDivisor( programAttribute + 0, 1 );
					enableAttributeAndDivisor( programAttribute + 1, 1 );
					enableAttributeAndDivisor( programAttribute + 2, 1 );
					enableAttributeAndDivisor( programAttribute + 3, 1 );

					gl.bindBuffer( 34962, buffer );

					gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
					gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
					gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
					gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );

				} else if ( materialDefaultAttributeValues !== undefined ) {

					const value = materialDefaultAttributeValues[ name ];

					if ( value !== undefined ) {

						switch ( value.length ) {

							case 2:
								gl.vertexAttrib2fv( programAttribute, value );
								break;

							case 3:
								gl.vertexAttrib3fv( programAttribute, value );
								break;

							case 4:
								gl.vertexAttrib4fv( programAttribute, value );
								break;

							default:
								gl.vertexAttrib1fv( programAttribute, value );

						}

					}

				}

			}

		}

		disableUnusedAttributes();

	}

	function dispose() {

		reset();

		for ( const geometryId in bindingStates ) {

			const programMap = bindingStates[ geometryId ];

			for ( const programId in programMap ) {

				const stateMap = programMap[ programId ];

				for ( const wireframe in stateMap ) {

					deleteVertexArrayObject( stateMap[ wireframe ].object );

					delete stateMap[ wireframe ];

				}

				delete programMap[ programId ];

			}

			delete bindingStates[ geometryId ];

		}

	}

	function releaseStatesOfGeometry( geometry ) {

		if ( bindingStates[ geometry.id ] === undefined ) return;

		const programMap = bindingStates[ geometry.id ];

		for ( const programId in programMap ) {

			const stateMap = programMap[ programId ];

			for ( const wireframe in stateMap ) {

				deleteVertexArrayObject( stateMap[ wireframe ].object );

				delete stateMap[ wireframe ];

			}

			delete programMap[ programId ];

		}

		delete bindingStates[ geometry.id ];

	}

	function releaseStatesOfProgram( program ) {

		for ( const geometryId in bindingStates ) {

			const programMap = bindingStates[ geometryId ];

			if ( programMap[ program.id ] === undefined ) continue;

			const stateMap = programMap[ program.id ];

			for ( const wireframe in stateMap ) {

				deleteVertexArrayObject( stateMap[ wireframe ].object );

				delete stateMap[ wireframe ];

			}

			delete programMap[ program.id ];

		}

	}

	function reset() {

		resetDefaultState();

		if ( currentState === defaultState ) return;

		currentState = defaultState;
		bindVertexArrayObject( currentState.object );

	}

	// for backward-compatilibity

	function resetDefaultState() {

		defaultState.geometry = null;
		defaultState.program = null;
		defaultState.wireframe = false;

	}

	return {

		setup: setup,
		reset: reset,
		resetDefaultState: resetDefaultState,
		dispose: dispose,
		releaseStatesOfGeometry: releaseStatesOfGeometry,
		releaseStatesOfProgram: releaseStatesOfProgram,

		initAttributes: initAttributes,
		enableAttribute: enableAttribute,
		disableUnusedAttributes: disableUnusedAttributes

	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLBufferRenderer( gl, extensions, info, capabilities ) {

	const isWebGL2 = capabilities.isWebGL2;

	let mode;

	function setMode( value ) {

		mode = value;

	}

	function render( start, count ) {

		gl.drawArrays( mode, start, count );

		info.update( count, mode );

	}

	function renderInstances( geometry, start, count, primcount ) {

		if ( primcount === 0 ) return;

		let extension, methodName;

		if ( isWebGL2 ) {

			extension = gl;
			methodName = 'drawArraysInstanced';

		} else {

			extension = extensions.get( 'ANGLE_instanced_arrays' );
			methodName = 'drawArraysInstancedANGLE';

			if ( extension === null ) {

				console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
				return;

			}

		}

		extension[ methodName ]( mode, start, count, primcount );

		info.update( count, mode, primcount );

	}

	//

	this.setMode = setMode;
	this.render = render;
	this.renderInstances = renderInstances;

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLCapabilities( gl, extensions, parameters ) {

	let maxAnisotropy;

	function getMaxAnisotropy() {

		if ( maxAnisotropy !== undefined ) return maxAnisotropy;

		const extension = extensions.get( 'EXT_texture_filter_anisotropic' );

		if ( extension !== null ) {

			maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );

		} else {

			maxAnisotropy = 0;

		}

		return maxAnisotropy;

	}

	function getMaxPrecision( precision ) {

		if ( precision === 'highp' ) {

			if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
				gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {

				return 'highp';

			}

			precision = 'mediump';

		}

		if ( precision === 'mediump' ) {

			if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
				gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {

				return 'mediump';

			}

		}

		return 'lowp';

	}

	/* eslint-disable no-undef */
	const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
		( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
	/* eslint-enable no-undef */

	let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
	const maxPrecision = getMaxPrecision( precision );

	if ( maxPrecision !== precision ) {

		console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
		precision = maxPrecision;

	}

	const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;

	const maxTextures = gl.getParameter( 34930 );
	const maxVertexTextures = gl.getParameter( 35660 );
	const maxTextureSize = gl.getParameter( 3379 );
	const maxCubemapSize = gl.getParameter( 34076 );

	const maxAttributes = gl.getParameter( 34921 );
	const maxVertexUniforms = gl.getParameter( 36347 );
	const maxVaryings = gl.getParameter( 36348 );
	const maxFragmentUniforms = gl.getParameter( 36349 );

	const vertexTextures = maxVertexTextures > 0;
	const floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
	const floatVertexTextures = vertexTextures && floatFragmentTextures;

	const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;

	return {

		isWebGL2: isWebGL2,

		getMaxAnisotropy: getMaxAnisotropy,
		getMaxPrecision: getMaxPrecision,

		precision: precision,
		logarithmicDepthBuffer: logarithmicDepthBuffer,

		maxTextures: maxTextures,
		maxVertexTextures: maxVertexTextures,
		maxTextureSize: maxTextureSize,
		maxCubemapSize: maxCubemapSize,

		maxAttributes: maxAttributes,
		maxVertexUniforms: maxVertexUniforms,
		maxVaryings: maxVaryings,
		maxFragmentUniforms: maxFragmentUniforms,

		vertexTextures: vertexTextures,
		floatFragmentTextures: floatFragmentTextures,
		floatVertexTextures: floatVertexTextures,

		maxSamples: maxSamples

	};

}

/**
 * @author tschw
 */

function WebGLClipping() {

	const scope = this;

	let globalState = null,
		numGlobalPlanes = 0,
		localClippingEnabled = false,
		renderingShadows = false;

	const plane = new Plane(),
		viewNormalMatrix = new Matrix3(),

		uniform = { value: null, needsUpdate: false };

	this.uniform = uniform;
	this.numPlanes = 0;
	this.numIntersection = 0;

	this.init = function ( planes, enableLocalClipping, camera ) {

		const enabled =
			planes.length !== 0 ||
			enableLocalClipping ||
			// enable state of previous frame - the clipping code has to
			// run another frame in order to reset the state:
			numGlobalPlanes !== 0 ||
			localClippingEnabled;

		localClippingEnabled = enableLocalClipping;

		globalState = projectPlanes( planes, camera, 0 );
		numGlobalPlanes = planes.length;

		return enabled;

	};

	this.beginShadows = function () {

		renderingShadows = true;
		projectPlanes( null );

	};

	this.endShadows = function () {

		renderingShadows = false;
		resetGlobalState();

	};

	this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {

		if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {

			// there's no local clipping

			if ( renderingShadows ) {

				// there's no global clipping

				projectPlanes( null );

			} else {

				resetGlobalState();

			}

		} else {

			const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
				lGlobal = nGlobal * 4;

			let dstArray = cache.clippingState || null;

			uniform.value = dstArray; // ensure unique state

			dstArray = projectPlanes( planes, camera, lGlobal, fromCache );

			for ( let i = 0; i !== lGlobal; ++ i ) {

				dstArray[ i ] = globalState[ i ];

			}

			cache.clippingState = dstArray;
			this.numIntersection = clipIntersection ? this.numPlanes : 0;
			this.numPlanes += nGlobal;

		}


	};

	function resetGlobalState() {

		if ( uniform.value !== globalState ) {

			uniform.value = globalState;
			uniform.needsUpdate = numGlobalPlanes > 0;

		}

		scope.numPlanes = numGlobalPlanes;
		scope.numIntersection = 0;

	}

	function projectPlanes( planes, camera, dstOffset, skipTransform ) {

		let nPlanes = planes !== null ? planes.length : 0,
			dstArray = null;

		if ( nPlanes !== 0 ) {

			dstArray = uniform.value;

			if ( skipTransform !== true || dstArray === null ) {

				const flatSize = dstOffset + nPlanes * 4,
					viewMatrix = camera.matrixWorldInverse;

				viewNormalMatrix.getNormalMatrix( viewMatrix );

				if ( dstArray === null || dstArray.length < flatSize ) {

					dstArray = new Float32Array( flatSize );

				}

				for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {

					plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );

					plane.normal.toArray( dstArray, i4 );
					dstArray[ i4 + 3 ] = plane.constant;

				}

			}

			uniform.value = dstArray;
			uniform.needsUpdate = true;

		}

		scope.numPlanes = nPlanes;
		scope.numIntersection = 0;

		return dstArray;

	}

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLExtensions( gl ) {

	const extensions = {};

	return {

		get: function ( name ) {

			if ( extensions[ name ] !== undefined ) {

				return extensions[ name ];

			}

			let extension;

			switch ( name ) {

				case 'WEBGL_depth_texture':
					extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
					break;

				case 'EXT_texture_filter_anisotropic':
					extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
					break;

				case 'WEBGL_compressed_texture_s3tc':
					extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
					break;

				case 'WEBGL_compressed_texture_pvrtc':
					extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
					break;

				default:
					extension = gl.getExtension( name );

			}

			if ( extension === null ) {

				console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );

			}

			extensions[ name ] = extension;

			return extension;

		}

	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLGeometries( gl, attributes, info, bindingStates ) {

	const geometries = new WeakMap();
	const wireframeAttributes = new WeakMap();

	function onGeometryDispose( event ) {

		const geometry = event.target;
		const buffergeometry = geometries.get( geometry );

		if ( buffergeometry.index !== null ) {

			attributes.remove( buffergeometry.index );

		}

		for ( const name in buffergeometry.attributes ) {

			attributes.remove( buffergeometry.attributes[ name ] );

		}

		geometry.removeEventListener( 'dispose', onGeometryDispose );

		geometries.delete( geometry );

		const attribute = wireframeAttributes.get( buffergeometry );

		if ( attribute ) {

			attributes.remove( attribute );
			wireframeAttributes.delete( buffergeometry );

		}

		bindingStates.releaseStatesOfGeometry( geometry );

		if ( geometry.isInstancedBufferGeometry === true ) {

			delete geometry._maxInstanceCount;

		}

		//

		info.memory.geometries --;

	}

	function get( object, geometry ) {

		let buffergeometry = geometries.get( geometry );

		if ( buffergeometry ) return buffergeometry;

		geometry.addEventListener( 'dispose', onGeometryDispose );

		if ( geometry.isBufferGeometry ) {

			buffergeometry = geometry;

		} else if ( geometry.isGeometry ) {

			if ( geometry._bufferGeometry === undefined ) {

				geometry._bufferGeometry = new BufferGeometry().setFromObject( object );

			}

			buffergeometry = geometry._bufferGeometry;

		}

		geometries.set( geometry, buffergeometry );

		info.memory.geometries ++;

		return buffergeometry;

	}

	function update( geometry ) {

		const geometryAttributes = geometry.attributes;

		// Updating index buffer in VAO now. See WebGLBindingStates.

		for ( const name in geometryAttributes ) {

			attributes.update( geometryAttributes[ name ], 34962 );

		}

		// morph targets

		const morphAttributes = geometry.morphAttributes;

		for ( const name in morphAttributes ) {

			const array = morphAttributes[ name ];

			for ( let i = 0, l = array.length; i < l; i ++ ) {

				attributes.update( array[ i ], 34962 );

			}

		}

	}

	function updateWireframeAttribute( geometry ) {

		const indices = [];

		const geometryIndex = geometry.index;
		const geometryPosition = geometry.attributes.position;
		let version = 0;

		if ( geometryIndex !== null ) {

			const array = geometryIndex.array;
			version = geometryIndex.version;

			for ( let i = 0, l = array.length; i < l; i += 3 ) {

				const a = array[ i + 0 ];
				const b = array[ i + 1 ];
				const c = array[ i + 2 ];

				indices.push( a, b, b, c, c, a );

			}

		} else {

			const array = geometryPosition.array;
			version = geometryPosition.version;

			for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {

				const a = i + 0;
				const b = i + 1;
				const c = i + 2;

				indices.push( a, b, b, c, c, a );

			}

		}

		const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
		attribute.version = version;

		// Updating index buffer in VAO now. See WebGLBindingStates

		//

		const previousAttribute = wireframeAttributes.get( geometry );

		if ( previousAttribute ) attributes.remove( previousAttribute );

		//

		wireframeAttributes.set( geometry, attribute );

	}

	function getWireframeAttribute( geometry ) {

		const currentAttribute = wireframeAttributes.get( geometry );

		if ( currentAttribute ) {

			const geometryIndex = geometry.index;

			if ( geometryIndex !== null ) {

				// if the attribute is obsolete, create a new one

				if ( currentAttribute.version < geometryIndex.version ) {

					updateWireframeAttribute( geometry );

				}

			}

		} else {

			updateWireframeAttribute( geometry );

		}

		return wireframeAttributes.get( geometry );

	}

	return {

		get: get,
		update: update,

		getWireframeAttribute: getWireframeAttribute

	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {

	const isWebGL2 = capabilities.isWebGL2;

	let mode;

	function setMode( value ) {

		mode = value;

	}

	let type, bytesPerElement;

	function setIndex( value ) {

		type = value.type;
		bytesPerElement = value.bytesPerElement;

	}

	function render( start, count ) {

		gl.drawElements( mode, count, type, start * bytesPerElement );

		info.update( count, mode );

	}

	function renderInstances( geometry, start, count, primcount ) {

		if ( primcount === 0 ) return;

		let extension, methodName;

		if ( isWebGL2 ) {

			extension = gl;
			methodName = 'drawElementsInstanced';

		} else {

			extension = extensions.get( 'ANGLE_instanced_arrays' );
			methodName = 'drawElementsInstancedANGLE';

			if ( extension === null ) {

				console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
				return;

			}

		}

		extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );

		info.update( count, mode, primcount );

	}

	//

	this.setMode = setMode;
	this.setIndex = setIndex;
	this.render = render;
	this.renderInstances = renderInstances;

}

/**
 * @author Mugen87 / https://github.com/Mugen87
 */

function WebGLInfo( gl ) {

	const memory = {
		geometries: 0,
		textures: 0
	};

	const render = {
		frame: 0,
		calls: 0,
		triangles: 0,
		points: 0,
		lines: 0
	};

	function update( count, mode, instanceCount ) {

		instanceCount = instanceCount || 1;

		render.calls ++;

		switch ( mode ) {

			case 4:
				render.triangles += instanceCount * ( count / 3 );
				break;

			case 1:
				render.lines += instanceCount * ( count / 2 );
				break;

			case 3:
				render.lines += instanceCount * ( count - 1 );
				break;

			case 2:
				render.lines += instanceCount * count;
				break;

			case 0:
				render.points += instanceCount * count;
				break;

			default:
				console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
				break;

		}

	}

	function reset() {

		render.frame ++;
		render.calls = 0;
		render.triangles = 0;
		render.points = 0;
		render.lines = 0;

	}

	return {
		memory: memory,
		render: render,
		programs: null,
		autoReset: true,
		reset: reset,
		update: update
	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function numericalSort( a, b ) {

	return a[ 0 ] - b[ 0 ];

}

function absNumericalSort( a, b ) {

	return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );

}

function WebGLMorphtargets( gl ) {

	const influencesList = {};
	const morphInfluences = new Float32Array( 8 );

	const workInfluences = [];

	for ( let i = 0; i < 8; i ++ ) {

		workInfluences[ i ] = [ i, 0 ];

	}

	function update( object, geometry, material, program ) {

		const objectInfluences = object.morphTargetInfluences;

		// When object doesn't have morph target influences defined, we treat it as a 0-length array
		// This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences

		const length = objectInfluences === undefined ? 0 : objectInfluences.length;

		let influences = influencesList[ geometry.id ];

		if ( influences === undefined ) {

			// initialise list

			influences = [];

			for ( let i = 0; i < length; i ++ ) {

				influences[ i ] = [ i, 0 ];

			}

			influencesList[ geometry.id ] = influences;

		}

		// Collect influences

		for ( let i = 0; i < length; i ++ ) {

			const influence = influences[ i ];

			influence[ 0 ] = i;
			influence[ 1 ] = objectInfluences[ i ];

		}

		influences.sort( absNumericalSort );

		for ( let i = 0; i < 8; i ++ ) {

			if ( i < length && influences[ i ][ 1 ] ) {

				workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
				workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];

			} else {

				workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
				workInfluences[ i ][ 1 ] = 0;

			}

		}

		workInfluences.sort( numericalSort );

		const morphTargets = material.morphTargets && geometry.morphAttributes.position;
		const morphNormals = material.morphNormals && geometry.morphAttributes.normal;

		let morphInfluencesSum = 0;

		for ( let i = 0; i < 8; i ++ ) {

			const influence = workInfluences[ i ];
			const index = influence[ 0 ];
			const value = influence[ 1 ];

			if ( index !== Number.MAX_SAFE_INTEGER && value ) {

				if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {

					geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );

				}

				if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {

					geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );

				}

				morphInfluences[ i ] = value;
				morphInfluencesSum += value;

			} else {

				if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== undefined ) {

					geometry.deleteAttribute( 'morphTarget' + i );

				}

				if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== undefined ) {

					geometry.deleteAttribute( 'morphNormal' + i );

				}

				morphInfluences[ i ] = 0;

			}

		}

		// GLSL shader uses formula baseinfluence * base + sum(target * influence)
		// This allows us to switch between absolute morphs and relative morphs without changing shader code
		// When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
		const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;

		program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
		program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );

	}

	return {

		update: update

	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLObjects( gl, geometries, attributes, info ) {

	let updateMap = new WeakMap();

	function update( object ) {

		const frame = info.render.frame;

		const geometry = object.geometry;
		const buffergeometry = geometries.get( object, geometry );

		// Update once per frame

		if ( updateMap.get( buffergeometry ) !== frame ) {

			if ( geometry.isGeometry ) {

				buffergeometry.updateFromObject( object );

			}

			geometries.update( buffergeometry );

			updateMap.set( buffergeometry, frame );

		}

		if ( object.isInstancedMesh ) {

			attributes.update( object.instanceMatrix, 34962 );

		}

		return buffergeometry;

	}

	function dispose() {

		updateMap = new WeakMap();

	}

	return {

		update: update,
		dispose: dispose

	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {

	images = images !== undefined ? images : [];
	mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
	format = format !== undefined ? format : RGBFormat;

	Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );

	this.flipY = false;

}

CubeTexture.prototype = Object.create( Texture.prototype );
CubeTexture.prototype.constructor = CubeTexture;

CubeTexture.prototype.isCubeTexture = true;

Object.defineProperty( CubeTexture.prototype, 'images', {

	get: function () {

		return this.image;

	},

	set: function ( value ) {

		this.image = value;

	}

} );

/**
 * @author Takahiro https://github.com/takahirox
 */

function DataTexture2DArray( data, width, height, depth ) {

	Texture.call( this, null );

	this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };

	this.magFilter = NearestFilter;
	this.minFilter = NearestFilter;

	this.wrapR = ClampToEdgeWrapping;

	this.generateMipmaps = false;
	this.flipY = false;

	this.needsUpdate = true;

}

DataTexture2DArray.prototype = Object.create( Texture.prototype );
DataTexture2DArray.prototype.constructor = DataTexture2DArray;
DataTexture2DArray.prototype.isDataTexture2DArray = true;

/**
 * @author Artur Trzesiok
 */

function DataTexture3D( data, width, height, depth ) {

	// We're going to add .setXXX() methods for setting properties later.
	// Users can still set in DataTexture3D directly.
	//
	//	const texture = new THREE.DataTexture3D( data, width, height, depth );
	// 	texture.anisotropy = 16;
	//
	// See #14839

	Texture.call( this, null );

	this.image = { data: data || null, width: width || 1, height: height || 1, depth: depth || 1 };

	this.magFilter = NearestFilter;
	this.minFilter = NearestFilter;

	this.wrapR = ClampToEdgeWrapping;

	this.generateMipmaps = false;
	this.flipY = false;

	this.needsUpdate = true;


}

DataTexture3D.prototype = Object.create( Texture.prototype );
DataTexture3D.prototype.constructor = DataTexture3D;
DataTexture3D.prototype.isDataTexture3D = true;

/**
 * @author tschw
 * @author Mugen87 / https://github.com/Mugen87
 * @author mrdoob / http://mrdoob.com/
 *
 * Uniforms of a program.
 * Those form a tree structure with a special top-level container for the root,
 * which you get by calling 'new WebGLUniforms( gl, program )'.
 *
 *
 * Properties of inner nodes including the top-level container:
 *
 * .seq - array of nested uniforms
 * .map - nested uniforms by name
 *
 *
 * Methods of all nodes except the top-level container:
 *
 * .setValue( gl, value, [textures] )
 *
 * 		uploads a uniform value(s)
 *  	the 'textures' parameter is needed for sampler uniforms
 *
 *
 * Static methods of the top-level container (textures factorizations):
 *
 * .upload( gl, seq, values, textures )
 *
 * 		sets uniforms in 'seq' to 'values[id].value'
 *
 * .seqWithValue( seq, values ) : filteredSeq
 *
 * 		filters 'seq' entries with corresponding entry in values
 *
 *
 * Methods of the top-level container (textures factorizations):
 *
 * .setValue( gl, name, value, textures )
 *
 * 		sets uniform with  name 'name' to 'value'
 *
 * .setOptional( gl, obj, prop )
 *
 * 		like .set for an optional property of the object
 *
 */

const emptyTexture = new Texture();
const emptyTexture2dArray = new DataTexture2DArray();
const emptyTexture3d = new DataTexture3D();
const emptyCubeTexture = new CubeTexture();

// --- Utilities ---

// Array Caches (provide typed arrays for temporary by size)

const arrayCacheF32 = [];
const arrayCacheI32 = [];

// Float32Array caches used for uploading Matrix uniforms

const mat4array = new Float32Array( 16 );
const mat3array = new Float32Array( 9 );
const mat2array = new Float32Array( 4 );

// Flattening for arrays of vectors and matrices

function flatten( array, nBlocks, blockSize ) {

	const firstElem = array[ 0 ];

	if ( firstElem <= 0 || firstElem > 0 ) return array;
	// unoptimized: ! isNaN( firstElem )
	// see http://jacksondunstan.com/articles/983

	let n = nBlocks * blockSize,
		r = arrayCacheF32[ n ];

	if ( r === undefined ) {

		r = new Float32Array( n );
		arrayCacheF32[ n ] = r;

	}

	if ( nBlocks !== 0 ) {

		firstElem.toArray( r, 0 );

		for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {

			offset += blockSize;
			array[ i ].toArray( r, offset );

		}

	}

	return r;

}

function arraysEqual( a, b ) {

	if ( a.length !== b.length ) return false;

	for ( let i = 0, l = a.length; i < l; i ++ ) {

		if ( a[ i ] !== b[ i ] ) return false;

	}

	return true;

}

function copyArray( a, b ) {

	for ( let i = 0, l = b.length; i < l; i ++ ) {

		a[ i ] = b[ i ];

	}

}

// Texture unit allocation

function allocTexUnits( textures, n ) {

	let r = arrayCacheI32[ n ];

	if ( r === undefined ) {

		r = new Int32Array( n );
		arrayCacheI32[ n ] = r;

	}

	for ( let i = 0; i !== n; ++ i ) {

		r[ i ] = textures.allocateTextureUnit();

	}

	return r;

}

// --- Setters ---

// Note: Defining these methods externally, because they come in a bunch
// and this way their names minify.

// Single scalar

function setValueV1f( gl, v ) {

	const cache = this.cache;

	if ( cache[ 0 ] === v ) return;

	gl.uniform1f( this.addr, v );

	cache[ 0 ] = v;

}

// Single float vector (from flat array or THREE.VectorN)

function setValueV2f( gl, v ) {

	const cache = this.cache;

	if ( v.x !== undefined ) {

		if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {

			gl.uniform2f( this.addr, v.x, v.y );

			cache[ 0 ] = v.x;
			cache[ 1 ] = v.y;

		}

	} else {

		if ( arraysEqual( cache, v ) ) return;

		gl.uniform2fv( this.addr, v );

		copyArray( cache, v );

	}

}

function setValueV3f( gl, v ) {

	const cache = this.cache;

	if ( v.x !== undefined ) {

		if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {

			gl.uniform3f( this.addr, v.x, v.y, v.z );

			cache[ 0 ] = v.x;
			cache[ 1 ] = v.y;
			cache[ 2 ] = v.z;

		}

	} else if ( v.r !== undefined ) {

		if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {

			gl.uniform3f( this.addr, v.r, v.g, v.b );

			cache[ 0 ] = v.r;
			cache[ 1 ] = v.g;
			cache[ 2 ] = v.b;

		}

	} else {

		if ( arraysEqual( cache, v ) ) return;

		gl.uniform3fv( this.addr, v );

		copyArray( cache, v );

	}

}

function setValueV4f( gl, v ) {

	const cache = this.cache;

	if ( v.x !== undefined ) {

		if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {

			gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );

			cache[ 0 ] = v.x;
			cache[ 1 ] = v.y;
			cache[ 2 ] = v.z;
			cache[ 3 ] = v.w;

		}

	} else {

		if ( arraysEqual( cache, v ) ) return;

		gl.uniform4fv( this.addr, v );

		copyArray( cache, v );

	}

}

// Single matrix (from flat array or MatrixN)

function setValueM2( gl, v ) {

	const cache = this.cache;
	const elements = v.elements;

	if ( elements === undefined ) {

		if ( arraysEqual( cache, v ) ) return;

		gl.uniformMatrix2fv( this.addr, false, v );

		copyArray( cache, v );

	} else {

		if ( arraysEqual( cache, elements ) ) return;

		mat2array.set( elements );

		gl.uniformMatrix2fv( this.addr, false, mat2array );

		copyArray( cache, elements );

	}

}

function setValueM3( gl, v ) {

	const cache = this.cache;
	const elements = v.elements;

	if ( elements === undefined ) {

		if ( arraysEqual( cache, v ) ) return;

		gl.uniformMatrix3fv( this.addr, false, v );

		copyArray( cache, v );

	} else {

		if ( arraysEqual( cache, elements ) ) return;

		mat3array.set( elements );

		gl.uniformMatrix3fv( this.addr, false, mat3array );

		copyArray( cache, elements );

	}

}

function setValueM4( gl, v ) {

	const cache = this.cache;
	const elements = v.elements;

	if ( elements === undefined ) {

		if ( arraysEqual( cache, v ) ) return;

		gl.uniformMatrix4fv( this.addr, false, v );

		copyArray( cache, v );

	} else {

		if ( arraysEqual( cache, elements ) ) return;

		mat4array.set( elements );

		gl.uniformMatrix4fv( this.addr, false, mat4array );

		copyArray( cache, elements );

	}

}

// Single texture (2D / Cube)

function setValueT1( gl, v, textures ) {

	const cache = this.cache;
	const unit = textures.allocateTextureUnit();

	if ( cache[ 0 ] !== unit ) {

		gl.uniform1i( this.addr, unit );
		cache[ 0 ] = unit;

	}

	textures.safeSetTexture2D( v || emptyTexture, unit );

}

function setValueT2DArray1( gl, v, textures ) {

	const cache = this.cache;
	const unit = textures.allocateTextureUnit();

	if ( cache[ 0 ] !== unit ) {

		gl.uniform1i( this.addr, unit );
		cache[ 0 ] = unit;

	}

	textures.setTexture2DArray( v || emptyTexture2dArray, unit );

}

function setValueT3D1( gl, v, textures ) {

	const cache = this.cache;
	const unit = textures.allocateTextureUnit();

	if ( cache[ 0 ] !== unit ) {

		gl.uniform1i( this.addr, unit );
		cache[ 0 ] = unit;

	}

	textures.setTexture3D( v || emptyTexture3d, unit );

}

function setValueT6( gl, v, textures ) {

	const cache = this.cache;
	const unit = textures.allocateTextureUnit();

	if ( cache[ 0 ] !== unit ) {

		gl.uniform1i( this.addr, unit );
		cache[ 0 ] = unit;

	}

	textures.safeSetTextureCube( v || emptyCubeTexture, unit );

}

// Integer / Boolean vectors or arrays thereof (always flat arrays)

function setValueV1i( gl, v ) {

	const cache = this.cache;

	if ( cache[ 0 ] === v ) return;

	gl.uniform1i( this.addr, v );

	cache[ 0 ] = v;

}

function setValueV2i( gl, v ) {

	const cache = this.cache;

	if ( arraysEqual( cache, v ) ) return;

	gl.uniform2iv( this.addr, v );

	copyArray( cache, v );

}

function setValueV3i( gl, v ) {

	const cache = this.cache;

	if ( arraysEqual( cache, v ) ) return;

	gl.uniform3iv( this.addr, v );

	copyArray( cache, v );

}

function setValueV4i( gl, v ) {

	const cache = this.cache;

	if ( arraysEqual( cache, v ) ) return;

	gl.uniform4iv( this.addr, v );

	copyArray( cache, v );

}

// uint

function setValueV1ui( gl, v ) {

	const cache = this.cache;

	if ( cache[ 0 ] === v ) return;

	gl.uniform1ui( this.addr, v );

	cache[ 0 ] = v;

}

// Helper to pick the right setter for the singular case

function getSingularSetter( type ) {

	switch ( type ) {

		case 0x1406: return setValueV1f; // FLOAT
		case 0x8b50: return setValueV2f; // _VEC2
		case 0x8b51: return setValueV3f; // _VEC3
		case 0x8b52: return setValueV4f; // _VEC4

		case 0x8b5a: return setValueM2; // _MAT2
		case 0x8b5b: return setValueM3; // _MAT3
		case 0x8b5c: return setValueM4; // _MAT4

		case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
		case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
		case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
		case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4

		case 0x1405: return setValueV1ui; // UINT

		case 0x8b5e: // SAMPLER_2D
		case 0x8d66: // SAMPLER_EXTERNAL_OES
		case 0x8dca: // INT_SAMPLER_2D
		case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
		case 0x8b62: // SAMPLER_2D_SHADOW
			return setValueT1;

		case 0x8b5f: // SAMPLER_3D
		case 0x8dcb: // INT_SAMPLER_3D
		case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
			return setValueT3D1;

		case 0x8b60: // SAMPLER_CUBE
		case 0x8dcc: // INT_SAMPLER_CUBE
		case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
		case 0x8dc5: // SAMPLER_CUBE_SHADOW
			return setValueT6;

		case 0x8dc1: // SAMPLER_2D_ARRAY
		case 0x8dcf: // INT_SAMPLER_2D_ARRAY
		case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
		case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
			return setValueT2DArray1;

	}

}

// Array of scalars
function setValueV1fArray( gl, v ) {

	gl.uniform1fv( this.addr, v );

}

// Integer / Boolean vectors or arrays thereof (always flat arrays)
function setValueV1iArray( gl, v ) {

	gl.uniform1iv( this.addr, v );

}

function setValueV2iArray( gl, v ) {

	gl.uniform2iv( this.addr, v );

}

function setValueV3iArray( gl, v ) {

	gl.uniform3iv( this.addr, v );

}

function setValueV4iArray( gl, v ) {

	gl.uniform4iv( this.addr, v );

}


// Array of vectors (flat or from THREE classes)

function setValueV2fArray( gl, v ) {

	const data = flatten( v, this.size, 2 );

	gl.uniform2fv( this.addr, data );

}

function setValueV3fArray( gl, v ) {

	const data = flatten( v, this.size, 3 );

	gl.uniform3fv( this.addr, data );

}

function setValueV4fArray( gl, v ) {

	const data = flatten( v, this.size, 4 );

	gl.uniform4fv( this.addr, data );

}

// Array of matrices (flat or from THREE clases)

function setValueM2Array( gl, v ) {

	const data = flatten( v, this.size, 4 );

	gl.uniformMatrix2fv( this.addr, false, data );

}

function setValueM3Array( gl, v ) {

	const data = flatten( v, this.size, 9 );

	gl.uniformMatrix3fv( this.addr, false, data );

}

function setValueM4Array( gl, v ) {

	const data = flatten( v, this.size, 16 );

	gl.uniformMatrix4fv( this.addr, false, data );

}

// Array of textures (2D / Cube)

function setValueT1Array( gl, v, textures ) {

	const n = v.length;

	const units = allocTexUnits( textures, n );

	gl.uniform1iv( this.addr, units );

	for ( let i = 0; i !== n; ++ i ) {

		textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );

	}

}

function setValueT6Array( gl, v, textures ) {

	const n = v.length;

	const units = allocTexUnits( textures, n );

	gl.uniform1iv( this.addr, units );

	for ( let i = 0; i !== n; ++ i ) {

		textures.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );

	}

}

// Helper to pick the right setter for a pure (bottom-level) array

function getPureArraySetter( type ) {

	switch ( type ) {

		case 0x1406: return setValueV1fArray; // FLOAT
		case 0x8b50: return setValueV2fArray; // _VEC2
		case 0x8b51: return setValueV3fArray; // _VEC3
		case 0x8b52: return setValueV4fArray; // _VEC4

		case 0x8b5a: return setValueM2Array; // _MAT2
		case 0x8b5b: return setValueM3Array; // _MAT3
		case 0x8b5c: return setValueM4Array; // _MAT4

		case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
		case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
		case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
		case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4

		case 0x8b5e: // SAMPLER_2D
		case 0x8d66: // SAMPLER_EXTERNAL_OES
		case 0x8dca: // INT_SAMPLER_2D
		case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
		case 0x8b62: // SAMPLER_2D_SHADOW
			return setValueT1Array;

		case 0x8b60: // SAMPLER_CUBE
		case 0x8dcc: // INT_SAMPLER_CUBE
		case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
		case 0x8dc5: // SAMPLER_CUBE_SHADOW
			return setValueT6Array;

	}

}

// --- Uniform Classes ---

function SingleUniform( id, activeInfo, addr ) {

	this.id = id;
	this.addr = addr;
	this.cache = [];
	this.setValue = getSingularSetter( activeInfo.type );

	// this.path = activeInfo.name; // DEBUG

}

function PureArrayUniform( id, activeInfo, addr ) {

	this.id = id;
	this.addr = addr;
	this.cache = [];
	this.size = activeInfo.size;
	this.setValue = getPureArraySetter( activeInfo.type );

	// this.path = activeInfo.name; // DEBUG

}

PureArrayUniform.prototype.updateCache = function ( data ) {

	let cache = this.cache;

	if ( data instanceof Float32Array && cache.length !== data.length ) {

		this.cache = new Float32Array( data.length );

	}

	copyArray( cache, data );

};

function StructuredUniform( id ) {

	this.id = id;

	this.seq = [];
	this.map = {};

}

StructuredUniform.prototype.setValue = function ( gl, value, textures ) {

	const seq = this.seq;

	for ( let i = 0, n = seq.length; i !== n; ++ i ) {

		const u = seq[ i ];
		u.setValue( gl, value[ u.id ], textures );

	}

};

// --- Top-level ---

// Parser - builds up the property tree from the path strings

const RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;

// extracts
// 	- the identifier (member name or array index)
//  - followed by an optional right bracket (found when array index)
//  - followed by an optional left bracket or dot (type of subscript)
//
// Note: These portions can be read in a non-overlapping fashion and
// allow straightforward parsing of the hierarchy that WebGL encodes
// in the uniform names.

function addUniform( container, uniformObject ) {

	container.seq.push( uniformObject );
	container.map[ uniformObject.id ] = uniformObject;

}

function parseUniform( activeInfo, addr, container ) {

	const path = activeInfo.name,
		pathLength = path.length;

	// reset RegExp object, because of the early exit of a previous run
	RePathPart.lastIndex = 0;

	while ( true ) {

		const match = RePathPart.exec( path ),
			matchEnd = RePathPart.lastIndex;

		let id = match[ 1 ],
			idIsIndex = match[ 2 ] === ']',
			subscript = match[ 3 ];

		if ( idIsIndex ) id = id | 0; // convert to integer

		if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {

			// bare name or "pure" bottom-level array "[0]" suffix

			addUniform( container, subscript === undefined ?
				new SingleUniform( id, activeInfo, addr ) :
				new PureArrayUniform( id, activeInfo, addr ) );

			break;

		} else {

			// step into inner node / create it in case it doesn't exist

			const map = container.map;
			let next = map[ id ];

			if ( next === undefined ) {

				next = new StructuredUniform( id );
				addUniform( container, next );

			}

			container = next;

		}

	}

}

// Root Container

function WebGLUniforms( gl, program ) {

	this.seq = [];
	this.map = {};

	const n = gl.getProgramParameter( program, 35718 );

	for ( let i = 0; i < n; ++ i ) {

		const info = gl.getActiveUniform( program, i ),
			addr = gl.getUniformLocation( program, info.name );

		parseUniform( info, addr, this );

	}

}

WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {

	const u = this.map[ name ];

	if ( u !== undefined ) u.setValue( gl, value, textures );

};

WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {

	const v = object[ name ];

	if ( v !== undefined ) this.setValue( gl, name, v );

};


// Static interface

WebGLUniforms.upload = function ( gl, seq, values, textures ) {

	for ( let i = 0, n = seq.length; i !== n; ++ i ) {

		const u = seq[ i ],
			v = values[ u.id ];

		if ( v.needsUpdate !== false ) {

			// note: always updating when .needsUpdate is undefined
			u.setValue( gl, v.value, textures );

		}

	}

};

WebGLUniforms.seqWithValue = function ( seq, values ) {

	const r = [];

	for ( let i = 0, n = seq.length; i !== n; ++ i ) {

		const u = seq[ i ];
		if ( u.id in values ) r.push( u );

	}

	return r;

};

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLShader( gl, type, string ) {

	const shader = gl.createShader( type );

	gl.shaderSource( shader, string );
	gl.compileShader( shader );

	return shader;

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

let programIdCount = 0;

function addLineNumbers( string ) {

	const lines = string.split( '\n' );

	for ( let i = 0; i < lines.length; i ++ ) {

		lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];

	}

	return lines.join( '\n' );

}

function getEncodingComponents( encoding ) {

	switch ( encoding ) {

		case LinearEncoding:
			return [ 'Linear', '( value )' ];
		case sRGBEncoding:
			return [ 'sRGB', '( value )' ];
		case RGBEEncoding:
			return [ 'RGBE', '( value )' ];
		case RGBM7Encoding:
			return [ 'RGBM', '( value, 7.0 )' ];
		case RGBM16Encoding:
			return [ 'RGBM', '( value, 16.0 )' ];
		case RGBDEncoding:
			return [ 'RGBD', '( value, 256.0 )' ];
		case GammaEncoding:
			return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
		case LogLuvEncoding:
			return [ 'LogLuv', '( value )' ];
		default:
			console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
			return [ 'Linear', '( value )' ];

	}

}

function getShaderErrors( gl, shader, type ) {

	const status = gl.getShaderParameter( shader, 35713 );
	const log = gl.getShaderInfoLog( shader ).trim();

	if ( status && log === '' ) return '';

	// --enable-privileged-webgl-extension
	// console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );

	const source = gl.getShaderSource( shader );

	return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );

}

function getTexelDecodingFunction( functionName, encoding ) {

	const components = getEncodingComponents( encoding );
	return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';

}

function getTexelEncodingFunction( functionName, encoding ) {

	const components = getEncodingComponents( encoding );
	return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';

}

function getToneMappingFunction( functionName, toneMapping ) {

	let toneMappingName;

	switch ( toneMapping ) {

		case LinearToneMapping:
			toneMappingName = 'Linear';
			break;

		case ReinhardToneMapping:
			toneMappingName = 'Reinhard';
			break;

		case CineonToneMapping:
			toneMappingName = 'OptimizedCineon';
			break;

		case ACESFilmicToneMapping:
			toneMappingName = 'ACESFilmic';
			break;

		case CustomToneMapping:
			toneMappingName = 'Custom';
			break;

		default:
			console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
			toneMappingName = 'Linear';

	}

	return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';

}

function generateExtensions( parameters ) {

	const chunks = [
		( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
		( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
		( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
		( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
	];

	return chunks.filter( filterEmptyLine ).join( '\n' );

}

function generateDefines( defines ) {

	const chunks = [];

	for ( const name in defines ) {

		const value = defines[ name ];

		if ( value === false ) continue;

		chunks.push( '#define ' + name + ' ' + value );

	}

	return chunks.join( '\n' );

}

function fetchAttributeLocations( gl, program ) {

	const attributes = {};

	const n = gl.getProgramParameter( program, 35721 );

	for ( let i = 0; i < n; i ++ ) {

		const info = gl.getActiveAttrib( program, i );
		const name = info.name;

		// console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );

		attributes[ name ] = gl.getAttribLocation( program, name );

	}

	return attributes;

}

function filterEmptyLine( string ) {

	return string !== '';

}

function replaceLightNums( string, parameters ) {

	return string
		.replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
		.replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
		.replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
		.replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
		.replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
		.replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
		.replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
		.replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );

}

function replaceClippingPlaneNums( string, parameters ) {

	return string
		.replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
		.replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );

}

// Resolve Includes

const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;

function resolveIncludes( string ) {

	return string.replace( includePattern, includeReplacer );

}

function includeReplacer( match, include ) {

	const string = ShaderChunk[ include ];

	if ( string === undefined ) {

		throw new Error( 'Can not resolve #include <' + include + '>' );

	}

	return resolveIncludes( string );

}

// Unroll Loops

const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
const unrollLoopPattern = /#pragma unroll_loop_start[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}[\s]+?#pragma unroll_loop_end/g;

function unrollLoops( string ) {

	return string
		.replace( unrollLoopPattern, loopReplacer )
		.replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );

}

function deprecatedLoopReplacer( match, start, end, snippet ) {

	console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
	return loopReplacer( match, start, end, snippet );

}

function loopReplacer( match, start, end, snippet ) {

	let string = '';

	for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {

		string += snippet
			.replace( /\[ i \]/g, '[ ' + i + ' ]' )
			.replace( /UNROLLED_LOOP_INDEX/g, i );

	}

	return string;

}

//

function generatePrecision( parameters ) {

	let precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";

	if ( parameters.precision === "highp" ) {

		precisionstring += "\n#define HIGH_PRECISION";

	} else if ( parameters.precision === "mediump" ) {

		precisionstring += "\n#define MEDIUM_PRECISION";

	} else if ( parameters.precision === "lowp" ) {

		precisionstring += "\n#define LOW_PRECISION";

	}

	return precisionstring;

}

function generateShadowMapTypeDefine( parameters ) {

	let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';

	if ( parameters.shadowMapType === PCFShadowMap ) {

		shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';

	} else if ( parameters.shadowMapType === PCFSoftShadowMap ) {

		shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';

	} else if ( parameters.shadowMapType === VSMShadowMap ) {

		shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';

	}

	return shadowMapTypeDefine;

}

function generateEnvMapTypeDefine( parameters ) {

	let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';

	if ( parameters.envMap ) {

		switch ( parameters.envMapMode ) {

			case CubeReflectionMapping:
			case CubeRefractionMapping:
				envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
				break;

			case CubeUVReflectionMapping:
			case CubeUVRefractionMapping:
				envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
				break;

			case EquirectangularReflectionMapping:
			case EquirectangularRefractionMapping:
				envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
				break;

		}

	}

	return envMapTypeDefine;

}

function generateEnvMapModeDefine( parameters ) {

	let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';

	if ( parameters.envMap ) {

		switch ( parameters.envMapMode ) {

			case CubeRefractionMapping:
			case EquirectangularRefractionMapping:
				envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
				break;

		}

	}

	return envMapModeDefine;

}

function generateEnvMapBlendingDefine( parameters ) {

	let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';

	if ( parameters.envMap ) {

		switch ( parameters.combine ) {

			case MultiplyOperation:
				envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
				break;

			case MixOperation:
				envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
				break;

			case AddOperation:
				envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
				break;

		}

	}

	return envMapBlendingDefine;

}

function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {

	const gl = renderer.getContext();

	const defines = parameters.defines;

	let vertexShader = parameters.vertexShader;
	let fragmentShader = parameters.fragmentShader;

	const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
	const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
	const envMapModeDefine = generateEnvMapModeDefine( parameters );
	const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );


	const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;

	const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );

	const customDefines = generateDefines( defines );

	const program = gl.createProgram();

	let prefixVertex, prefixFragment;

	if ( parameters.isRawShaderMaterial ) {

		prefixVertex = [

			customDefines

		].filter( filterEmptyLine ).join( '\n' );

		if ( prefixVertex.length > 0 ) {

			prefixVertex += '\n';

		}

		prefixFragment = [

			customExtensions,
			customDefines

		].filter( filterEmptyLine ).join( '\n' );

		if ( prefixFragment.length > 0 ) {

			prefixFragment += '\n';

		}

	} else {

		prefixVertex = [

			generatePrecision( parameters ),

			'#define SHADER_NAME ' + parameters.shaderName,

			customDefines,

			parameters.instancing ? '#define USE_INSTANCING' : '',
			parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',

			'#define GAMMA_FACTOR ' + gammaFactorDefine,

			'#define MAX_BONES ' + parameters.maxBones,
			( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
			( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',

			parameters.map ? '#define USE_MAP' : '',
			parameters.envMap ? '#define USE_ENVMAP' : '',
			parameters.envMap ? '#define ' + envMapModeDefine : '',
			parameters.lightMap ? '#define USE_LIGHTMAP' : '',
			parameters.aoMap ? '#define USE_AOMAP' : '',
			parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
			parameters.bumpMap ? '#define USE_BUMPMAP' : '',
			parameters.normalMap ? '#define USE_NORMALMAP' : '',
			( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
			( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',

			parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
			parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
			parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
			parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
			parameters.specularMap ? '#define USE_SPECULARMAP' : '',
			parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
			parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
			parameters.alphaMap ? '#define USE_ALPHAMAP' : '',

			parameters.vertexTangents ? '#define USE_TANGENT' : '',
			parameters.vertexColors ? '#define USE_COLOR' : '',
			parameters.vertexUvs ? '#define USE_UV' : '',
			parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',

			parameters.flatShading ? '#define FLAT_SHADED' : '',

			parameters.skinning ? '#define USE_SKINNING' : '',
			parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',

			parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
			parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
			parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
			parameters.flipSided ? '#define FLIP_SIDED' : '',

			parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
			parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',

			parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',

			parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
			( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',

			'uniform mat4 modelMatrix;',
			'uniform mat4 modelViewMatrix;',
			'uniform mat4 projectionMatrix;',
			'uniform mat4 viewMatrix;',
			'uniform mat3 normalMatrix;',
			'uniform vec3 cameraPosition;',
			'uniform bool isOrthographic;',

			'#ifdef USE_INSTANCING',

			' attribute mat4 instanceMatrix;',

			'#endif',

			'attribute vec3 position;',
			'attribute vec3 normal;',
			'attribute vec2 uv;',

			'#ifdef USE_TANGENT',

			'	attribute vec4 tangent;',

			'#endif',

			'#ifdef USE_COLOR',

			'	attribute vec3 color;',

			'#endif',

			'#ifdef USE_MORPHTARGETS',

			'	attribute vec3 morphTarget0;',
			'	attribute vec3 morphTarget1;',
			'	attribute vec3 morphTarget2;',
			'	attribute vec3 morphTarget3;',

			'	#ifdef USE_MORPHNORMALS',

			'		attribute vec3 morphNormal0;',
			'		attribute vec3 morphNormal1;',
			'		attribute vec3 morphNormal2;',
			'		attribute vec3 morphNormal3;',

			'	#else',

			'		attribute vec3 morphTarget4;',
			'		attribute vec3 morphTarget5;',
			'		attribute vec3 morphTarget6;',
			'		attribute vec3 morphTarget7;',

			'	#endif',

			'#endif',

			'#ifdef USE_SKINNING',

			'	attribute vec4 skinIndex;',
			'	attribute vec4 skinWeight;',

			'#endif',

			'\n'

		].filter( filterEmptyLine ).join( '\n' );

		prefixFragment = [

			customExtensions,

			generatePrecision( parameters ),

			'#define SHADER_NAME ' + parameters.shaderName,

			customDefines,

			parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer

			'#define GAMMA_FACTOR ' + gammaFactorDefine,

			( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
			( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',

			parameters.map ? '#define USE_MAP' : '',
			parameters.matcap ? '#define USE_MATCAP' : '',
			parameters.envMap ? '#define USE_ENVMAP' : '',
			parameters.envMap ? '#define ' + envMapTypeDefine : '',
			parameters.envMap ? '#define ' + envMapModeDefine : '',
			parameters.envMap ? '#define ' + envMapBlendingDefine : '',
			parameters.lightMap ? '#define USE_LIGHTMAP' : '',
			parameters.aoMap ? '#define USE_AOMAP' : '',
			parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
			parameters.bumpMap ? '#define USE_BUMPMAP' : '',
			parameters.normalMap ? '#define USE_NORMALMAP' : '',
			( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
			( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
			parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
			parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
			parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
			parameters.specularMap ? '#define USE_SPECULARMAP' : '',
			parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
			parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
			parameters.alphaMap ? '#define USE_ALPHAMAP' : '',

			parameters.sheen ? '#define USE_SHEEN' : '',

			parameters.vertexTangents ? '#define USE_TANGENT' : '',
			parameters.vertexColors ? '#define USE_COLOR' : '',
			parameters.vertexUvs ? '#define USE_UV' : '',
			parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',

			parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',

			parameters.flatShading ? '#define FLAT_SHADED' : '',

			parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
			parameters.flipSided ? '#define FLIP_SIDED' : '',

			parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
			parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',

			parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',

			parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',

			parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
			( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',

			( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',

			'uniform mat4 viewMatrix;',
			'uniform vec3 cameraPosition;',
			'uniform bool isOrthographic;',

			( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
			( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
			( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',

			parameters.dithering ? '#define DITHERING' : '',

			ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
			parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
			parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
			parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
			parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
			parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
			getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),

			parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',

			'\n'

		].filter( filterEmptyLine ).join( '\n' );

	}

	vertexShader = resolveIncludes( vertexShader );
	vertexShader = replaceLightNums( vertexShader, parameters );
	vertexShader = replaceClippingPlaneNums( vertexShader, parameters );

	fragmentShader = resolveIncludes( fragmentShader );
	fragmentShader = replaceLightNums( fragmentShader, parameters );
	fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );

	vertexShader = unrollLoops( vertexShader );
	fragmentShader = unrollLoops( fragmentShader );

	if ( parameters.isWebGL2 && ! parameters.isRawShaderMaterial ) {

		let isGLSL3ShaderMaterial = false;

		const versionRegex = /^\s*#version\s+300\s+es\s*\n/;

		if ( parameters.isShaderMaterial &&
			vertexShader.match( versionRegex ) !== null &&
			fragmentShader.match( versionRegex ) !== null ) {

			isGLSL3ShaderMaterial = true;

			vertexShader = vertexShader.replace( versionRegex, '' );
			fragmentShader = fragmentShader.replace( versionRegex, '' );

		}

		// GLSL 3.0 conversion

		prefixVertex = [
			'#version 300 es\n',
			'#define attribute in',
			'#define varying out',
			'#define texture2D texture'
		].join( '\n' ) + '\n' + prefixVertex;

		prefixFragment = [
			'#version 300 es\n',
			'#define varying in',
			isGLSL3ShaderMaterial ? '' : 'out highp vec4 pc_fragColor;',
			isGLSL3ShaderMaterial ? '' : '#define gl_FragColor pc_fragColor',
			'#define gl_FragDepthEXT gl_FragDepth',
			'#define texture2D texture',
			'#define textureCube texture',
			'#define texture2DProj textureProj',
			'#define texture2DLodEXT textureLod',
			'#define texture2DProjLodEXT textureProjLod',
			'#define textureCubeLodEXT textureLod',
			'#define texture2DGradEXT textureGrad',
			'#define texture2DProjGradEXT textureProjGrad',
			'#define textureCubeGradEXT textureGrad'
		].join( '\n' ) + '\n' + prefixFragment;

	}

	const vertexGlsl = prefixVertex + vertexShader;
	const fragmentGlsl = prefixFragment + fragmentShader;

	// console.log( '*VERTEX*', vertexGlsl );
	// console.log( '*FRAGMENT*', fragmentGlsl );

	const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
	const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );

	gl.attachShader( program, glVertexShader );
	gl.attachShader( program, glFragmentShader );

	// Force a particular attribute to index 0.

	if ( parameters.index0AttributeName !== undefined ) {

		gl.bindAttribLocation( program, 0, parameters.index0AttributeName );

	} else if ( parameters.morphTargets === true ) {

		// programs with morphTargets displace position out of attribute 0
		gl.bindAttribLocation( program, 0, 'position' );

	}

	gl.linkProgram( program );

	// check for link errors
	if ( renderer.debug.checkShaderErrors ) {

		const programLog = gl.getProgramInfoLog( program ).trim();
		const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
		const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();

		let runnable = true;
		let haveDiagnostics = true;

		if ( gl.getProgramParameter( program, 35714 ) === false ) {

			runnable = false;

			const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
			const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );

			console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );

		} else if ( programLog !== '' ) {

			console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );

		} else if ( vertexLog === '' || fragmentLog === '' ) {

			haveDiagnostics = false;

		}

		if ( haveDiagnostics ) {

			this.diagnostics = {

				runnable: runnable,

				programLog: programLog,

				vertexShader: {

					log: vertexLog,
					prefix: prefixVertex

				},

				fragmentShader: {

					log: fragmentLog,
					prefix: prefixFragment

				}

			};

		}

	}

	// Clean up

	// Crashes in iOS9 and iOS10. #18402
	// gl.detachShader( program, glVertexShader );
	// gl.detachShader( program, glFragmentShader );

	gl.deleteShader( glVertexShader );
	gl.deleteShader( glFragmentShader );

	// set up caching for uniform locations

	let cachedUniforms;

	this.getUniforms = function () {

		if ( cachedUniforms === undefined ) {

			cachedUniforms = new WebGLUniforms( gl, program );

		}

		return cachedUniforms;

	};

	// set up caching for attribute locations

	let cachedAttributes;

	this.getAttributes = function () {

		if ( cachedAttributes === undefined ) {

			cachedAttributes = fetchAttributeLocations( gl, program );

		}

		return cachedAttributes;

	};

	// free resource

	this.destroy = function () {

		bindingStates.releaseStatesOfProgram( this );

		gl.deleteProgram( program );
		this.program = undefined;

	};

	//

	this.name = parameters.shaderName;
	this.id = programIdCount ++;
	this.cacheKey = cacheKey;
	this.usedTimes = 1;
	this.program = program;
	this.vertexShader = glVertexShader;
	this.fragmentShader = glFragmentShader;

	return this;

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLPrograms( renderer, extensions, capabilities, bindingStates ) {

	const programs = [];

	const isWebGL2 = capabilities.isWebGL2;
	const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
	const floatVertexTextures = capabilities.floatVertexTextures;
	const maxVertexUniforms = capabilities.maxVertexUniforms;
	const vertexTextures = capabilities.vertexTextures;

	let precision = capabilities.precision;

	const shaderIDs = {
		MeshDepthMaterial: 'depth',
		MeshDistanceMaterial: 'distanceRGBA',
		MeshNormalMaterial: 'normal',
		MeshBasicMaterial: 'basic',
		MeshLambertMaterial: 'lambert',
		MeshPhongMaterial: 'phong',
		MeshToonMaterial: 'toon',
		MeshStandardMaterial: 'physical',
		MeshPhysicalMaterial: 'physical',
		MeshMatcapMaterial: 'matcap',
		LineBasicMaterial: 'basic',
		LineDashedMaterial: 'dashed',
		PointsMaterial: 'points',
		ShadowMaterial: 'shadow',
		SpriteMaterial: 'sprite'
	};

	const parameterNames = [
		"precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing",
		"map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV",
		"lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap",
		"roughnessMap", "metalnessMap", "gradientMap",
		"alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2",
		"flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
		"maxBones", "useVertexTexture", "morphTargets", "morphNormals",
		"maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
		"numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
		"numDirLightShadows", "numPointLightShadows", "numSpotLightShadows",
		"shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
		"alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering",
		"sheen"
	];

	function getShaderObject( material, shaderID ) {

		let shaderobject;

		if ( shaderID ) {

			const shader = ShaderLib[ shaderID ];

			shaderobject = {
				name: material.name || material.type,
				uniforms: UniformsUtils.clone( shader.uniforms ),
				vertexShader: shader.vertexShader,
				fragmentShader: shader.fragmentShader
			};

		} else {

			shaderobject = {
				name: material.name || material.type,
				uniforms: material.uniforms,
				vertexShader: material.vertexShader,
				fragmentShader: material.fragmentShader
			};

		}

		return shaderobject;

	}

	function allocateBones( object ) {

		const skeleton = object.skeleton;
		const bones = skeleton.bones;

		if ( floatVertexTextures ) {

			return 1024;

		} else {

			// default for when object is not specified
			// ( for example when prebuilding shader to be used with multiple objects )
			//
			//  - leave some extra space for other uniforms
			//  - limit here is ANGLE's 254 max uniform vectors
			//    (up to 54 should be safe)

			const nVertexUniforms = maxVertexUniforms;
			const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );

			const maxBones = Math.min( nVertexMatrices, bones.length );

			if ( maxBones < bones.length ) {

				console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
				return 0;

			}

			return maxBones;

		}

	}

	function getTextureEncodingFromMap( map ) {

		let encoding;

		if ( ! map ) {

			encoding = LinearEncoding;

		} else if ( map.isTexture ) {

			encoding = map.encoding;

		} else if ( map.isWebGLRenderTarget ) {

			console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
			encoding = map.texture.encoding;

		}

		return encoding;

	}

	function getParameters( material, lights, shadows, scene, nClipPlanes, nClipIntersection, object ) {

		const fog = scene.fog;
		const environment = material.isMeshStandardMaterial ? scene.environment : null;

		const envMap = material.envMap || environment;

		const shaderID = shaderIDs[ material.type ];

		// heuristics to create shader parameters according to lights in the scene
		// (not to blow over maxLights budget)

		const maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;

		if ( material.precision !== null ) {

			precision = capabilities.getMaxPrecision( material.precision );

			if ( precision !== material.precision ) {

				console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );

			}

		}

		const shaderobject = getShaderObject( material, shaderID );
		material.onBeforeCompile( shaderobject, renderer );

		const currentRenderTarget = renderer.getRenderTarget();

		const parameters = {

			isWebGL2: isWebGL2,

			shaderID: shaderID,
			shaderName: shaderobject.name,

			uniforms: shaderobject.uniforms,
			vertexShader: shaderobject.vertexShader,
			fragmentShader: shaderobject.fragmentShader,
			defines: material.defines,

			isRawShaderMaterial: material.isRawShaderMaterial,
			isShaderMaterial: material.isShaderMaterial,

			precision: precision,

			instancing: object.isInstancedMesh === true,

			supportsVertexTextures: vertexTextures,
			outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
			map: !! material.map,
			mapEncoding: getTextureEncodingFromMap( material.map ),
			matcap: !! material.matcap,
			matcapEncoding: getTextureEncodingFromMap( material.matcap ),
			envMap: !! envMap,
			envMapMode: envMap && envMap.mapping,
			envMapEncoding: getTextureEncodingFromMap( envMap ),
			envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
			lightMap: !! material.lightMap,
			lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
			aoMap: !! material.aoMap,
			emissiveMap: !! material.emissiveMap,
			emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
			bumpMap: !! material.bumpMap,
			normalMap: !! material.normalMap,
			objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
			tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
			clearcoatMap: !! material.clearcoatMap,
			clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
			clearcoatNormalMap: !! material.clearcoatNormalMap,
			displacementMap: !! material.displacementMap,
			roughnessMap: !! material.roughnessMap,
			metalnessMap: !! material.metalnessMap,
			specularMap: !! material.specularMap,
			alphaMap: !! material.alphaMap,

			gradientMap: !! material.gradientMap,

			sheen: !! material.sheen,

			combine: material.combine,

			vertexTangents: ( material.normalMap && material.vertexTangents ),
			vertexColors: material.vertexColors,
			vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.displacementMap,
			uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap ) && !! material.displacementMap,

			fog: !! fog,
			useFog: material.fog,
			fogExp2: ( fog && fog.isFogExp2 ),

			flatShading: material.flatShading,

			sizeAttenuation: material.sizeAttenuation,
			logarithmicDepthBuffer: logarithmicDepthBuffer,

			skinning: material.skinning && maxBones > 0,
			maxBones: maxBones,
			useVertexTexture: floatVertexTextures,

			morphTargets: material.morphTargets,
			morphNormals: material.morphNormals,
			maxMorphTargets: renderer.maxMorphTargets,
			maxMorphNormals: renderer.maxMorphNormals,

			numDirLights: lights.directional.length,
			numPointLights: lights.point.length,
			numSpotLights: lights.spot.length,
			numRectAreaLights: lights.rectArea.length,
			numHemiLights: lights.hemi.length,

			numDirLightShadows: lights.directionalShadowMap.length,
			numPointLightShadows: lights.pointShadowMap.length,
			numSpotLightShadows: lights.spotShadowMap.length,

			numClippingPlanes: nClipPlanes,
			numClipIntersection: nClipIntersection,

			dithering: material.dithering,

			shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
			shadowMapType: renderer.shadowMap.type,

			toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
			physicallyCorrectLights: renderer.physicallyCorrectLights,

			premultipliedAlpha: material.premultipliedAlpha,

			alphaTest: material.alphaTest,
			doubleSided: material.side === DoubleSide,
			flipSided: material.side === BackSide,

			depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,

			index0AttributeName: material.index0AttributeName,

			extensionDerivatives: material.extensions && material.extensions.derivatives,
			extensionFragDepth: material.extensions && material.extensions.fragDepth,
			extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
			extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,

			rendererExtensionFragDepth: isWebGL2 || extensions.get( 'EXT_frag_depth' ) !== null,
			rendererExtensionDrawBuffers: isWebGL2 || extensions.get( 'WEBGL_draw_buffers' ) !== null,
			rendererExtensionShaderTextureLod: isWebGL2 || extensions.get( 'EXT_shader_texture_lod' ) !== null,

			customProgramCacheKey: material.customProgramCacheKey()

		};

		return parameters;

	}

	function getProgramCacheKey( parameters ) {

		const array = [];

		if ( parameters.shaderID ) {

			array.push( parameters.shaderID );

		} else {

			array.push( parameters.fragmentShader );
			array.push( parameters.vertexShader );

		}

		if ( parameters.defines !== undefined ) {

			for ( const name in parameters.defines ) {

				array.push( name );
				array.push( parameters.defines[ name ] );

			}

		}

		if ( parameters.isRawShaderMaterial === undefined ) {

			for ( let i = 0; i < parameterNames.length; i ++ ) {

				array.push( parameters[ parameterNames[ i ] ] );

			}

			array.push( renderer.outputEncoding );
			array.push( renderer.gammaFactor );

		}

		array.push( parameters.customProgramCacheKey );

		return array.join();

	}

	function acquireProgram( parameters, cacheKey ) {

		let program;

		// Check if code has been already compiled
		for ( let p = 0, pl = programs.length; p < pl; p ++ ) {

			const preexistingProgram = programs[ p ];

			if ( preexistingProgram.cacheKey === cacheKey ) {

				program = preexistingProgram;
				++ program.usedTimes;

				break;

			}

		}

		if ( program === undefined ) {

			program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
			programs.push( program );

		}

		return program;

	}

	function releaseProgram( program ) {

		if ( -- program.usedTimes === 0 ) {

			// Remove from unordered set
			const i = programs.indexOf( program );
			programs[ i ] = programs[ programs.length - 1 ];
			programs.pop();

			// Free WebGL resources
			program.destroy();

		}

	}

	return {
		getParameters: getParameters,
		getProgramCacheKey: getProgramCacheKey,
		acquireProgram: acquireProgram,
		releaseProgram: releaseProgram,
		// Exposed for resource monitoring & error feedback via renderer.info:
		programs: programs
	};

}

/**
 * @author fordacious / fordacious.github.io
 */

function WebGLProperties() {

	let properties = new WeakMap();

	function get( object ) {

		let map = properties.get( object );

		if ( map === undefined ) {

			map = {};
			properties.set( object, map );

		}

		return map;

	}

	function remove( object ) {

		properties.delete( object );

	}

	function update( object, key, value ) {

		properties.get( object )[ key ] = value;

	}

	function dispose() {

		properties = new WeakMap();

	}

	return {
		get: get,
		remove: remove,
		update: update,
		dispose: dispose
	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function painterSortStable( a, b ) {

	if ( a.groupOrder !== b.groupOrder ) {

		return a.groupOrder - b.groupOrder;

	} else if ( a.renderOrder !== b.renderOrder ) {

		return a.renderOrder - b.renderOrder;

	} else if ( a.program !== b.program ) {

		return a.program.id - b.program.id;

	} else if ( a.material.id !== b.material.id ) {

		return a.material.id - b.material.id;

	} else if ( a.z !== b.z ) {

		return a.z - b.z;

	} else {

		return a.id - b.id;

	}

}

function reversePainterSortStable( a, b ) {

	if ( a.groupOrder !== b.groupOrder ) {

		return a.groupOrder - b.groupOrder;

	} else if ( a.renderOrder !== b.renderOrder ) {

		return a.renderOrder - b.renderOrder;

	} else if ( a.z !== b.z ) {

		return b.z - a.z;

	} else {

		return a.id - b.id;

	}

}


function WebGLRenderList() {

	const renderItems = [];
	let renderItemsIndex = 0;

	const opaque = [];
	const transparent = [];

	const defaultProgram = { id: - 1 };

	function init() {

		renderItemsIndex = 0;

		opaque.length = 0;
		transparent.length = 0;

	}

	function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {

		let renderItem = renderItems[ renderItemsIndex ];

		if ( renderItem === undefined ) {

			renderItem = {
				id: object.id,
				object: object,
				geometry: geometry,
				material: material,
				program: material.program || defaultProgram,
				groupOrder: groupOrder,
				renderOrder: object.renderOrder,
				z: z,
				group: group
			};

			renderItems[ renderItemsIndex ] = renderItem;

		} else {

			renderItem.id = object.id;
			renderItem.object = object;
			renderItem.geometry = geometry;
			renderItem.material = material;
			renderItem.program = material.program || defaultProgram;
			renderItem.groupOrder = groupOrder;
			renderItem.renderOrder = object.renderOrder;
			renderItem.z = z;
			renderItem.group = group;

		}

		renderItemsIndex ++;

		return renderItem;

	}

	function push( object, geometry, material, groupOrder, z, group ) {

		const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );

		( material.transparent === true ? transparent : opaque ).push( renderItem );

	}

	function unshift( object, geometry, material, groupOrder, z, group ) {

		const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );

		( material.transparent === true ? transparent : opaque ).unshift( renderItem );

	}

	function sort( customOpaqueSort, customTransparentSort ) {

		if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
		if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );

	}

	function finish() {

		// Clear references from inactive renderItems in the list

		for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {

			const renderItem = renderItems[ i ];

			if ( renderItem.id === null ) break;

			renderItem.id = null;
			renderItem.object = null;
			renderItem.geometry = null;
			renderItem.material = null;
			renderItem.program = null;
			renderItem.group = null;

		}

	}

	return {
		opaque: opaque,
		transparent: transparent,

		init: init,
		push: push,
		unshift: unshift,
		finish: finish,

		sort: sort
	};

}

function WebGLRenderLists() {

	let lists = new WeakMap();

	function onSceneDispose( event ) {

		const scene = event.target;

		scene.removeEventListener( 'dispose', onSceneDispose );

		lists.delete( scene );

	}

	function get( scene, camera ) {

		const cameras = lists.get( scene );
		let list;

		if ( cameras === undefined ) {

			list = new WebGLRenderList();
			lists.set( scene, new WeakMap() );
			lists.get( scene ).set( camera, list );

			scene.addEventListener( 'dispose', onSceneDispose );

		} else {

			list = cameras.get( camera );
			if ( list === undefined ) {

				list = new WebGLRenderList();
				cameras.set( camera, list );

			}

		}

		return list;

	}

	function dispose() {

		lists = new WeakMap();

	}

	return {
		get: get,
		dispose: dispose
	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function UniformsCache() {

	const lights = {};

	return {

		get: function ( light ) {

			if ( lights[ light.id ] !== undefined ) {

				return lights[ light.id ];

			}

			let uniforms;

			switch ( light.type ) {

				case 'DirectionalLight':
					uniforms = {
						direction: new Vector3(),
						color: new Color()
					};
					break;

				case 'SpotLight':
					uniforms = {
						position: new Vector3(),
						direction: new Vector3(),
						color: new Color(),
						distance: 0,
						coneCos: 0,
						penumbraCos: 0,
						decay: 0
					};
					break;

				case 'PointLight':
					uniforms = {
						position: new Vector3(),
						color: new Color(),
						distance: 0,
						decay: 0
					};
					break;

				case 'HemisphereLight':
					uniforms = {
						direction: new Vector3(),
						skyColor: new Color(),
						groundColor: new Color()
					};
					break;

				case 'RectAreaLight':
					uniforms = {
						color: new Color(),
						position: new Vector3(),
						halfWidth: new Vector3(),
						halfHeight: new Vector3()
					};
					break;

			}

			lights[ light.id ] = uniforms;

			return uniforms;

		}

	};

}

function ShadowUniformsCache() {

	const lights = {};

	return {

		get: function ( light ) {

			if ( lights[ light.id ] !== undefined ) {

				return lights[ light.id ];

			}

			let uniforms;

			switch ( light.type ) {

				case 'DirectionalLight':
					uniforms = {
						shadowBias: 0,
						shadowNormalBias: 0,
						shadowRadius: 1,
						shadowMapSize: new Vector2()
					};
					break;

				case 'SpotLight':
					uniforms = {
						shadowBias: 0,
						shadowNormalBias: 0,
						shadowRadius: 1,
						shadowMapSize: new Vector2()
					};
					break;

				case 'PointLight':
					uniforms = {
						shadowBias: 0,
						shadowNormalBias: 0,
						shadowRadius: 1,
						shadowMapSize: new Vector2(),
						shadowCameraNear: 1,
						shadowCameraFar: 1000
					};
					break;

				// TODO (abelnation): set RectAreaLight shadow uniforms

			}

			lights[ light.id ] = uniforms;

			return uniforms;

		}

	};

}



let nextVersion = 0;

function shadowCastingLightsFirst( lightA, lightB ) {

	return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );

}

function WebGLLights() {

	const cache = new UniformsCache();

	const shadowCache = ShadowUniformsCache();

	const state = {

		version: 0,

		hash: {
			directionalLength: - 1,
			pointLength: - 1,
			spotLength: - 1,
			rectAreaLength: - 1,
			hemiLength: - 1,

			numDirectionalShadows: - 1,
			numPointShadows: - 1,
			numSpotShadows: - 1
		},

		ambient: [ 0, 0, 0 ],
		probe: [],
		directional: [],
		directionalShadow: [],
		directionalShadowMap: [],
		directionalShadowMatrix: [],
		spot: [],
		spotShadow: [],
		spotShadowMap: [],
		spotShadowMatrix: [],
		rectArea: [],
		point: [],
		pointShadow: [],
		pointShadowMap: [],
		pointShadowMatrix: [],
		hemi: []

	};

	for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );

	const vector3 = new Vector3();
	const matrix4 = new Matrix4();
	const matrix42 = new Matrix4();

	function setup( lights, shadows, camera ) {

		let r = 0, g = 0, b = 0;

		for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );

		let directionalLength = 0;
		let pointLength = 0;
		let spotLength = 0;
		let rectAreaLength = 0;
		let hemiLength = 0;

		let numDirectionalShadows = 0;
		let numPointShadows = 0;
		let numSpotShadows = 0;

		const viewMatrix = camera.matrixWorldInverse;

		lights.sort( shadowCastingLightsFirst );

		for ( let i = 0, l = lights.length; i < l; i ++ ) {

			const light = lights[ i ];

			const color = light.color;
			const intensity = light.intensity;
			const distance = light.distance;

			const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;

			if ( light.isAmbientLight ) {

				r += color.r * intensity;
				g += color.g * intensity;
				b += color.b * intensity;

			} else if ( light.isLightProbe ) {

				for ( let j = 0; j < 9; j ++ ) {

					state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );

				}

			} else if ( light.isDirectionalLight ) {

				const uniforms = cache.get( light );

				uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
				vector3.setFromMatrixPosition( light.target.matrixWorld );
				uniforms.direction.sub( vector3 );
				uniforms.direction.transformDirection( viewMatrix );

				if ( light.castShadow ) {

					const shadow = light.shadow;

					const shadowUniforms = shadowCache.get( light );

					shadowUniforms.shadowBias = shadow.bias;
					shadowUniforms.shadowNormalBias = shadow.normalBias;
					shadowUniforms.shadowRadius = shadow.radius;
					shadowUniforms.shadowMapSize = shadow.mapSize;

					state.directionalShadow[ directionalLength ] = shadowUniforms;
					state.directionalShadowMap[ directionalLength ] = shadowMap;
					state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;

					numDirectionalShadows ++;

				}

				state.directional[ directionalLength ] = uniforms;

				directionalLength ++;

			} else if ( light.isSpotLight ) {

				const uniforms = cache.get( light );

				uniforms.position.setFromMatrixPosition( light.matrixWorld );
				uniforms.position.applyMatrix4( viewMatrix );

				uniforms.color.copy( color ).multiplyScalar( intensity );
				uniforms.distance = distance;

				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
				vector3.setFromMatrixPosition( light.target.matrixWorld );
				uniforms.direction.sub( vector3 );
				uniforms.direction.transformDirection( viewMatrix );

				uniforms.coneCos = Math.cos( light.angle );
				uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
				uniforms.decay = light.decay;

				if ( light.castShadow ) {

					const shadow = light.shadow;

					const shadowUniforms = shadowCache.get( light );

					shadowUniforms.shadowBias = shadow.bias;
					shadowUniforms.shadowNormalBias = shadow.normalBias;
					shadowUniforms.shadowRadius = shadow.radius;
					shadowUniforms.shadowMapSize = shadow.mapSize;

					state.spotShadow[ spotLength ] = shadowUniforms;
					state.spotShadowMap[ spotLength ] = shadowMap;
					state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;

					numSpotShadows ++;

				}

				state.spot[ spotLength ] = uniforms;

				spotLength ++;

			} else if ( light.isRectAreaLight ) {

				const uniforms = cache.get( light );

				// (a) intensity is the total visible light emitted
				//uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );

				// (b) intensity is the brightness of the light
				uniforms.color.copy( color ).multiplyScalar( intensity );

				uniforms.position.setFromMatrixPosition( light.matrixWorld );
				uniforms.position.applyMatrix4( viewMatrix );

				// extract local rotation of light to derive width/height half vectors
				matrix42.identity();
				matrix4.copy( light.matrixWorld );
				matrix4.premultiply( viewMatrix );
				matrix42.extractRotation( matrix4 );

				uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
				uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );

				uniforms.halfWidth.applyMatrix4( matrix42 );
				uniforms.halfHeight.applyMatrix4( matrix42 );

				// TODO (abelnation): RectAreaLight distance?
				// uniforms.distance = distance;

				state.rectArea[ rectAreaLength ] = uniforms;

				rectAreaLength ++;

			} else if ( light.isPointLight ) {

				const uniforms = cache.get( light );

				uniforms.position.setFromMatrixPosition( light.matrixWorld );
				uniforms.position.applyMatrix4( viewMatrix );

				uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
				uniforms.distance = light.distance;
				uniforms.decay = light.decay;

				if ( light.castShadow ) {

					const shadow = light.shadow;

					const shadowUniforms = shadowCache.get( light );

					shadowUniforms.shadowBias = shadow.bias;
					shadowUniforms.shadowNormalBias = shadow.normalBias;
					shadowUniforms.shadowRadius = shadow.radius;
					shadowUniforms.shadowMapSize = shadow.mapSize;
					shadowUniforms.shadowCameraNear = shadow.camera.near;
					shadowUniforms.shadowCameraFar = shadow.camera.far;

					state.pointShadow[ pointLength ] = shadowUniforms;
					state.pointShadowMap[ pointLength ] = shadowMap;
					state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;

					numPointShadows ++;

				}

				state.point[ pointLength ] = uniforms;

				pointLength ++;

			} else if ( light.isHemisphereLight ) {

				const uniforms = cache.get( light );

				uniforms.direction.setFromMatrixPosition( light.matrixWorld );
				uniforms.direction.transformDirection( viewMatrix );
				uniforms.direction.normalize();

				uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
				uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );

				state.hemi[ hemiLength ] = uniforms;

				hemiLength ++;

			}

		}

		state.ambient[ 0 ] = r;
		state.ambient[ 1 ] = g;
		state.ambient[ 2 ] = b;

		const hash = state.hash;

		if ( hash.directionalLength !== directionalLength ||
			hash.pointLength !== pointLength ||
			hash.spotLength !== spotLength ||
			hash.rectAreaLength !== rectAreaLength ||
			hash.hemiLength !== hemiLength ||
			hash.numDirectionalShadows !== numDirectionalShadows ||
			hash.numPointShadows !== numPointShadows ||
			hash.numSpotShadows !== numSpotShadows ) {

			state.directional.length = directionalLength;
			state.spot.length = spotLength;
			state.rectArea.length = rectAreaLength;
			state.point.length = pointLength;
			state.hemi.length = hemiLength;

			state.directionalShadow.length = numDirectionalShadows;
			state.directionalShadowMap.length = numDirectionalShadows;
			state.pointShadow.length = numPointShadows;
			state.pointShadowMap.length = numPointShadows;
			state.spotShadow.length = numSpotShadows;
			state.spotShadowMap.length = numSpotShadows;
			state.directionalShadowMatrix.length = numDirectionalShadows;
			state.pointShadowMatrix.length = numPointShadows;
			state.spotShadowMatrix.length = numSpotShadows;

			hash.directionalLength = directionalLength;
			hash.pointLength = pointLength;
			hash.spotLength = spotLength;
			hash.rectAreaLength = rectAreaLength;
			hash.hemiLength = hemiLength;

			hash.numDirectionalShadows = numDirectionalShadows;
			hash.numPointShadows = numPointShadows;
			hash.numSpotShadows = numSpotShadows;

			state.version = nextVersion ++;

		}

	}

	return {
		setup: setup,
		state: state
	};

}

/**
 * @author Mugen87 / https://github.com/Mugen87
 */

function WebGLRenderState() {

	const lights = new WebGLLights();

	const lightsArray = [];
	const shadowsArray = [];

	function init() {

		lightsArray.length = 0;
		shadowsArray.length = 0;

	}

	function pushLight( light ) {

		lightsArray.push( light );

	}

	function pushShadow( shadowLight ) {

		shadowsArray.push( shadowLight );

	}

	function setupLights( camera ) {

		lights.setup( lightsArray, shadowsArray, camera );

	}

	const state = {
		lightsArray: lightsArray,
		shadowsArray: shadowsArray,

		lights: lights
	};

	return {
		init: init,
		state: state,
		setupLights: setupLights,

		pushLight: pushLight,
		pushShadow: pushShadow
	};

}

function WebGLRenderStates() {

	let renderStates = new WeakMap();

	function onSceneDispose( event ) {

		const scene = event.target;

		scene.removeEventListener( 'dispose', onSceneDispose );

		renderStates.delete( scene );

	}

	function get( scene, camera ) {

		let renderState;

		if ( renderStates.has( scene ) === false ) {

			renderState = new WebGLRenderState();
			renderStates.set( scene, new WeakMap() );
			renderStates.get( scene ).set( camera, renderState );

			scene.addEventListener( 'dispose', onSceneDispose );

		} else {

			if ( renderStates.get( scene ).has( camera ) === false ) {

				renderState = new WebGLRenderState();
				renderStates.get( scene ).set( camera, renderState );

			} else {

				renderState = renderStates.get( scene ).get( camera );

			}

		}

		return renderState;

	}

	function dispose() {

		renderStates = new WeakMap();

	}

	return {
		get: get,
		dispose: dispose
	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author bhouston / https://clara.io
 * @author WestLangley / http://github.com/WestLangley
 *
 * parameters = {
 *
 *  opacity: <float>,
 *
 *  map: new THREE.Texture( <Image> ),
 *
 *  alphaMap: new THREE.Texture( <Image> ),
 *
 *  displacementMap: new THREE.Texture( <Image> ),
 *  displacementScale: <float>,
 *  displacementBias: <float>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>
 * }
 */

function MeshDepthMaterial( parameters ) {

	Material.call( this );

	this.type = 'MeshDepthMaterial';

	this.depthPacking = BasicDepthPacking;

	this.skinning = false;
	this.morphTargets = false;

	this.map = null;

	this.alphaMap = null;

	this.displacementMap = null;
	this.displacementScale = 1;
	this.displacementBias = 0;

	this.wireframe = false;
	this.wireframeLinewidth = 1;

	this.fog = false;

	this.setValues( parameters );

}

MeshDepthMaterial.prototype = Object.create( Material.prototype );
MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;

MeshDepthMaterial.prototype.isMeshDepthMaterial = true;

MeshDepthMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.depthPacking = source.depthPacking;

	this.skinning = source.skinning;
	this.morphTargets = source.morphTargets;

	this.map = source.map;

	this.alphaMap = source.alphaMap;

	this.displacementMap = source.displacementMap;
	this.displacementScale = source.displacementScale;
	this.displacementBias = source.displacementBias;

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;

	return this;

};

/**
 * @author WestLangley / http://github.com/WestLangley
 *
 * parameters = {
 *
 *  referencePosition: <float>,
 *  nearDistance: <float>,
 *  farDistance: <float>,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *
 *  map: new THREE.Texture( <Image> ),
 *
 *  alphaMap: new THREE.Texture( <Image> ),
 *
 *  displacementMap: new THREE.Texture( <Image> ),
 *  displacementScale: <float>,
 *  displacementBias: <float>
 *
 * }
 */

function MeshDistanceMaterial( parameters ) {

	Material.call( this );

	this.type = 'MeshDistanceMaterial';

	this.referencePosition = new Vector3();
	this.nearDistance = 1;
	this.farDistance = 1000;

	this.skinning = false;
	this.morphTargets = false;

	this.map = null;

	this.alphaMap = null;

	this.displacementMap = null;
	this.displacementScale = 1;
	this.displacementBias = 0;

	this.fog = false;

	this.setValues( parameters );

}

MeshDistanceMaterial.prototype = Object.create( Material.prototype );
MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;

MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;

MeshDistanceMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.referencePosition.copy( source.referencePosition );
	this.nearDistance = source.nearDistance;
	this.farDistance = source.farDistance;

	this.skinning = source.skinning;
	this.morphTargets = source.morphTargets;

	this.map = source.map;

	this.alphaMap = source.alphaMap;

	this.displacementMap = source.displacementMap;
	this.displacementScale = source.displacementScale;
	this.displacementBias = source.displacementBias;

	return this;

};

var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n  float mean = 0.0;\n  float squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy  ) / resolution ) );\n  for ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n    #ifdef HORIZONAL_PASS\n      vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n      mean += distribution.x;\n      squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n    #else\n      float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0,  i )  * radius ) / resolution ) );\n      mean += depth;\n      squared_mean += depth * depth;\n    #endif\n  }\n  mean = mean * HALF_SAMPLE_RATE;\n  squared_mean = squared_mean * HALF_SAMPLE_RATE;\n  float std_dev = sqrt( squared_mean - mean * mean );\n  gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";

var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";

/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {

	let _frustum = new Frustum();

	const _shadowMapSize = new Vector2(),
		_viewportSize = new Vector2(),

		_viewport = new Vector4(),

		_depthMaterials = [],
		_distanceMaterials = [],

		_materialCache = {};

	const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };

	const shadowMaterialVertical = new ShaderMaterial( {

		defines: {
			SAMPLE_RATE: 2.0 / 8.0,
			HALF_SAMPLE_RATE: 1.0 / 8.0
		},

		uniforms: {
			shadow_pass: { value: null },
			resolution: { value: new Vector2() },
			radius: { value: 4.0 }
		},

		vertexShader: vsm_vert,

		fragmentShader: vsm_frag

	} );

	const shadowMaterialHorizonal = shadowMaterialVertical.clone();
	shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;

	const fullScreenTri = new BufferGeometry();
	fullScreenTri.setAttribute(
		"position",
		new BufferAttribute(
			new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
			3
		)
	);

	const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );

	const scope = this;

	this.enabled = false;

	this.autoUpdate = true;
	this.needsUpdate = false;

	this.type = PCFShadowMap;

	this.render = function ( lights, scene, camera ) {

		if ( scope.enabled === false ) return;
		if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;

		if ( lights.length === 0 ) return;

		const currentRenderTarget = _renderer.getRenderTarget();
		const activeCubeFace = _renderer.getActiveCubeFace();
		const activeMipmapLevel = _renderer.getActiveMipmapLevel();

		const _state = _renderer.state;

		// Set GL state for depth map.
		_state.setBlending( NoBlending );
		_state.buffers.color.setClear( 1, 1, 1, 1 );
		_state.buffers.depth.setTest( true );
		_state.setScissorTest( false );

		// render depth map

		for ( let i = 0, il = lights.length; i < il; i ++ ) {

			const light = lights[ i ];
			const shadow = light.shadow;

			if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;

			if ( shadow === undefined ) {

				console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
				continue;

			}

			_shadowMapSize.copy( shadow.mapSize );

			const shadowFrameExtents = shadow.getFrameExtents();

			_shadowMapSize.multiply( shadowFrameExtents );

			_viewportSize.copy( shadow.mapSize );

			if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {

				if ( _shadowMapSize.x > maxTextureSize ) {

					_viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
					_shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
					shadow.mapSize.x = _viewportSize.x;

				}

				if ( _shadowMapSize.y > maxTextureSize ) {

					_viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
					_shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
					shadow.mapSize.y = _viewportSize.y;

				}

			}

			if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {

				const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };

				shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
				shadow.map.texture.name = light.name + ".shadowMap";

				shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );

				shadow.camera.updateProjectionMatrix();

			}

			if ( shadow.map === null ) {

				const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };

				shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
				shadow.map.texture.name = light.name + ".shadowMap";

				shadow.camera.updateProjectionMatrix();

			}

			_renderer.setRenderTarget( shadow.map );
			_renderer.clear();

			const viewportCount = shadow.getViewportCount();

			for ( let vp = 0; vp < viewportCount; vp ++ ) {

				const viewport = shadow.getViewport( vp );

				_viewport.set(
					_viewportSize.x * viewport.x,
					_viewportSize.y * viewport.y,
					_viewportSize.x * viewport.z,
					_viewportSize.y * viewport.w
				);

				_state.viewport( _viewport );

				shadow.updateMatrices( light, vp );

				_frustum = shadow.getFrustum();

				renderObject( scene, camera, shadow.camera, light, this.type );

			}

			// do blur pass for VSM

			if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {

				VSMPass( shadow, camera );

			}

			shadow.needsUpdate = false;

		}

		scope.needsUpdate = false;

		_renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );

	};

	function VSMPass( shadow, camera ) {

		const geometry = _objects.update( fullScreenMesh );

		// vertical pass

		shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
		shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
		shadowMaterialVertical.uniforms.radius.value = shadow.radius;
		_renderer.setRenderTarget( shadow.mapPass );
		_renderer.clear();
		_renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );

		// horizonal pass

		shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
		shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
		shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
		_renderer.setRenderTarget( shadow.map );
		_renderer.clear();
		_renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null );

	}

	function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {

		const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;

		let material = _depthMaterials[ index ];

		if ( material === undefined ) {

			material = new MeshDepthMaterial( {

				depthPacking: RGBADepthPacking,

				morphTargets: useMorphing,
				skinning: useSkinning

			} );

			_depthMaterials[ index ] = material;

		}

		return material;

	}

	function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {

		const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;

		let material = _distanceMaterials[ index ];

		if ( material === undefined ) {

			material = new MeshDistanceMaterial( {

				morphTargets: useMorphing,
				skinning: useSkinning

			} );

			_distanceMaterials[ index ] = material;

		}

		return material;

	}

	function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {

		let result = null;

		let getMaterialVariant = getDepthMaterialVariant;
		let customMaterial = object.customDepthMaterial;

		if ( light.isPointLight === true ) {

			getMaterialVariant = getDistanceMaterialVariant;
			customMaterial = object.customDistanceMaterial;

		}

		if ( customMaterial === undefined ) {

			let useMorphing = false;

			if ( material.morphTargets === true ) {

				useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;

			}

			let useSkinning = false;

			if ( object.isSkinnedMesh === true ) {

				if ( material.skinning === true ) {

					useSkinning = true;

				} else {

					console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );

				}

			}

			const useInstancing = object.isInstancedMesh === true;

			result = getMaterialVariant( useMorphing, useSkinning, useInstancing );

		} else {

			result = customMaterial;

		}

		if ( _renderer.localClippingEnabled &&
				material.clipShadows === true &&
				material.clippingPlanes.length !== 0 ) {

			// in this case we need a unique material instance reflecting the
			// appropriate state

			const keyA = result.uuid, keyB = material.uuid;

			let materialsForVariant = _materialCache[ keyA ];

			if ( materialsForVariant === undefined ) {

				materialsForVariant = {};
				_materialCache[ keyA ] = materialsForVariant;

			}

			let cachedMaterial = materialsForVariant[ keyB ];

			if ( cachedMaterial === undefined ) {

				cachedMaterial = result.clone();
				materialsForVariant[ keyB ] = cachedMaterial;

			}

			result = cachedMaterial;

		}

		result.visible = material.visible;
		result.wireframe = material.wireframe;

		if ( type === VSMShadowMap ) {

			result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;

		} else {

			result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];

		}

		result.clipShadows = material.clipShadows;
		result.clippingPlanes = material.clippingPlanes;
		result.clipIntersection = material.clipIntersection;

		result.wireframeLinewidth = material.wireframeLinewidth;
		result.linewidth = material.linewidth;

		if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {

			result.referencePosition.setFromMatrixPosition( light.matrixWorld );
			result.nearDistance = shadowCameraNear;
			result.farDistance = shadowCameraFar;

		}

		return result;

	}

	function renderObject( object, camera, shadowCamera, light, type ) {

		if ( object.visible === false ) return;

		const visible = object.layers.test( camera.layers );

		if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {

			if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {

				object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );

				const geometry = _objects.update( object );
				const material = object.material;

				if ( Array.isArray( material ) ) {

					const groups = geometry.groups;

					for ( let k = 0, kl = groups.length; k < kl; k ++ ) {

						const group = groups[ k ];
						const groupMaterial = material[ group.materialIndex ];

						if ( groupMaterial && groupMaterial.visible ) {

							const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );

							_renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );

						}

					}

				} else if ( material.visible ) {

					const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );

					_renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );

				}

			}

		}

		const children = object.children;

		for ( let i = 0, l = children.length; i < l; i ++ ) {

			renderObject( children[ i ], camera, shadowCamera, light, type );

		}

	}

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLState( gl, extensions, capabilities ) {

	const isWebGL2 = capabilities.isWebGL2;

	function ColorBuffer() {

		let locked = false;

		const color = new Vector4();
		let currentColorMask = null;
		const currentColorClear = new Vector4( 0, 0, 0, 0 );

		return {

			setMask: function ( colorMask ) {

				if ( currentColorMask !== colorMask && ! locked ) {

					gl.colorMask( colorMask, colorMask, colorMask, colorMask );
					currentColorMask = colorMask;

				}

			},

			setLocked: function ( lock ) {

				locked = lock;

			},

			setClear: function ( r, g, b, a, premultipliedAlpha ) {

				if ( premultipliedAlpha === true ) {

					r *= a; g *= a; b *= a;

				}

				color.set( r, g, b, a );

				if ( currentColorClear.equals( color ) === false ) {

					gl.clearColor( r, g, b, a );
					currentColorClear.copy( color );

				}

			},

			reset: function () {

				locked = false;

				currentColorMask = null;
				currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state

			}

		};

	}

	function DepthBuffer() {

		let locked = false;

		let currentDepthMask = null;
		let currentDepthFunc = null;
		let currentDepthClear = null;

		return {

			setTest: function ( depthTest ) {

				if ( depthTest ) {

					enable( 2929 );

				} else {

					disable( 2929 );

				}

			},

			setMask: function ( depthMask ) {

				if ( currentDepthMask !== depthMask && ! locked ) {

					gl.depthMask( depthMask );
					currentDepthMask = depthMask;

				}

			},

			setFunc: function ( depthFunc ) {

				if ( currentDepthFunc !== depthFunc ) {

					if ( depthFunc ) {

						switch ( depthFunc ) {

							case NeverDepth:

								gl.depthFunc( 512 );
								break;

							case AlwaysDepth:

								gl.depthFunc( 519 );
								break;

							case LessDepth:

								gl.depthFunc( 513 );
								break;

							case LessEqualDepth:

								gl.depthFunc( 515 );
								break;

							case EqualDepth:

								gl.depthFunc( 514 );
								break;

							case GreaterEqualDepth:

								gl.depthFunc( 518 );
								break;

							case GreaterDepth:

								gl.depthFunc( 516 );
								break;

							case NotEqualDepth:

								gl.depthFunc( 517 );
								break;

							default:

								gl.depthFunc( 515 );

						}

					} else {

						gl.depthFunc( 515 );

					}

					currentDepthFunc = depthFunc;

				}

			},

			setLocked: function ( lock ) {

				locked = lock;

			},

			setClear: function ( depth ) {

				if ( currentDepthClear !== depth ) {

					gl.clearDepth( depth );
					currentDepthClear = depth;

				}

			},

			reset: function () {

				locked = false;

				currentDepthMask = null;
				currentDepthFunc = null;
				currentDepthClear = null;

			}

		};

	}

	function StencilBuffer() {

		let locked = false;

		let currentStencilMask = null;
		let currentStencilFunc = null;
		let currentStencilRef = null;
		let currentStencilFuncMask = null;
		let currentStencilFail = null;
		let currentStencilZFail = null;
		let currentStencilZPass = null;
		let currentStencilClear = null;

		return {

			setTest: function ( stencilTest ) {

				if ( ! locked ) {

					if ( stencilTest ) {

						enable( 2960 );

					} else {

						disable( 2960 );

					}

				}

			},

			setMask: function ( stencilMask ) {

				if ( currentStencilMask !== stencilMask && ! locked ) {

					gl.stencilMask( stencilMask );
					currentStencilMask = stencilMask;

				}

			},

			setFunc: function ( stencilFunc, stencilRef, stencilMask ) {

				if ( currentStencilFunc !== stencilFunc ||
				     currentStencilRef 	!== stencilRef 	||
				     currentStencilFuncMask !== stencilMask ) {

					gl.stencilFunc( stencilFunc, stencilRef, stencilMask );

					currentStencilFunc = stencilFunc;
					currentStencilRef = stencilRef;
					currentStencilFuncMask = stencilMask;

				}

			},

			setOp: function ( stencilFail, stencilZFail, stencilZPass ) {

				if ( currentStencilFail	 !== stencilFail 	||
				     currentStencilZFail !== stencilZFail ||
				     currentStencilZPass !== stencilZPass ) {

					gl.stencilOp( stencilFail, stencilZFail, stencilZPass );

					currentStencilFail = stencilFail;
					currentStencilZFail = stencilZFail;
					currentStencilZPass = stencilZPass;

				}

			},

			setLocked: function ( lock ) {

				locked = lock;

			},

			setClear: function ( stencil ) {

				if ( currentStencilClear !== stencil ) {

					gl.clearStencil( stencil );
					currentStencilClear = stencil;

				}

			},

			reset: function () {

				locked = false;

				currentStencilMask = null;
				currentStencilFunc = null;
				currentStencilRef = null;
				currentStencilFuncMask = null;
				currentStencilFail = null;
				currentStencilZFail = null;
				currentStencilZPass = null;
				currentStencilClear = null;

			}

		};

	}

	//

	const colorBuffer = new ColorBuffer();
	const depthBuffer = new DepthBuffer();
	const stencilBuffer = new StencilBuffer();

	let enabledCapabilities = {};

	let currentProgram = null;

	let currentBlendingEnabled = null;
	let currentBlending = null;
	let currentBlendEquation = null;
	let currentBlendSrc = null;
	let currentBlendDst = null;
	let currentBlendEquationAlpha = null;
	let currentBlendSrcAlpha = null;
	let currentBlendDstAlpha = null;
	let currentPremultipledAlpha = false;

	let currentFlipSided = null;
	let currentCullFace = null;

	let currentLineWidth = null;

	let currentPolygonOffsetFactor = null;
	let currentPolygonOffsetUnits = null;

	const maxTextures = gl.getParameter( 35661 );

	let lineWidthAvailable = false;
	let version = 0;
	const glVersion = gl.getParameter( 7938 );

	if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {

		version = parseFloat( /^WebGL\ ([0-9])/.exec( glVersion )[ 1 ] );
		lineWidthAvailable = ( version >= 1.0 );

	} else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {

		version = parseFloat( /^OpenGL\ ES\ ([0-9])/.exec( glVersion )[ 1 ] );
		lineWidthAvailable = ( version >= 2.0 );

	}

	let currentTextureSlot = null;
	let currentBoundTextures = {};

	const currentScissor = new Vector4();
	const currentViewport = new Vector4();

	function createTexture( type, target, count ) {

		const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
		const texture = gl.createTexture();

		gl.bindTexture( type, texture );
		gl.texParameteri( type, 10241, 9728 );
		gl.texParameteri( type, 10240, 9728 );

		for ( let i = 0; i < count; i ++ ) {

			gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );

		}

		return texture;

	}

	const emptyTextures = {};
	emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
	emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );

	// init

	colorBuffer.setClear( 0, 0, 0, 1 );
	depthBuffer.setClear( 1 );
	stencilBuffer.setClear( 0 );

	enable( 2929 );
	depthBuffer.setFunc( LessEqualDepth );

	setFlipSided( false );
	setCullFace( CullFaceBack );
	enable( 2884 );

	setBlending( NoBlending );

	//

	function enable( id ) {

		if ( enabledCapabilities[ id ] !== true ) {

			gl.enable( id );
			enabledCapabilities[ id ] = true;

		}

	}

	function disable( id ) {

		if ( enabledCapabilities[ id ] !== false ) {

			gl.disable( id );
			enabledCapabilities[ id ] = false;

		}

	}

	function useProgram( program ) {

		if ( currentProgram !== program ) {

			gl.useProgram( program );

			currentProgram = program;

			return true;

		}

		return false;

	}

	const equationToGL = {
		[ AddEquation ]: 32774,
		[ SubtractEquation ]: 32778,
		[ ReverseSubtractEquation ]: 32779
	};

	if ( isWebGL2 ) {

		equationToGL[ MinEquation ] = 32775;
		equationToGL[ MaxEquation ] = 32776;

	} else {

		const extension = extensions.get( 'EXT_blend_minmax' );

		if ( extension !== null ) {

			equationToGL[ MinEquation ] = extension.MIN_EXT;
			equationToGL[ MaxEquation ] = extension.MAX_EXT;

		}

	}

	const factorToGL = {
		[ ZeroFactor ]: 0,
		[ OneFactor ]: 1,
		[ SrcColorFactor ]: 768,
		[ SrcAlphaFactor ]: 770,
		[ SrcAlphaSaturateFactor ]: 776,
		[ DstColorFactor ]: 774,
		[ DstAlphaFactor ]: 772,
		[ OneMinusSrcColorFactor ]: 769,
		[ OneMinusSrcAlphaFactor ]: 771,
		[ OneMinusDstColorFactor ]: 775,
		[ OneMinusDstAlphaFactor ]: 773
	};

	function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {

		if ( blending === NoBlending ) {

			if ( currentBlendingEnabled ) {

				disable( 3042 );
				currentBlendingEnabled = false;

			}

			return;

		}

		if ( ! currentBlendingEnabled ) {

			enable( 3042 );
			currentBlendingEnabled = true;

		}

		if ( blending !== CustomBlending ) {

			if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {

				if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {

					gl.blendEquation( 32774 );

					currentBlendEquation = AddEquation;
					currentBlendEquationAlpha = AddEquation;

				}

				if ( premultipliedAlpha ) {

					switch ( blending ) {

						case NormalBlending:
							gl.blendFuncSeparate( 1, 771, 1, 771 );
							break;

						case AdditiveBlending:
							gl.blendFunc( 1, 1 );
							break;

						case SubtractiveBlending:
							gl.blendFuncSeparate( 0, 0, 769, 771 );
							break;

						case MultiplyBlending:
							gl.blendFuncSeparate( 0, 768, 0, 770 );
							break;

						default:
							console.error( 'THREE.WebGLState: Invalid blending: ', blending );
							break;

					}

				} else {

					switch ( blending ) {

						case NormalBlending:
							gl.blendFuncSeparate( 770, 771, 1, 771 );
							break;

						case AdditiveBlending:
							gl.blendFunc( 770, 1 );
							break;

						case SubtractiveBlending:
							gl.blendFunc( 0, 769 );
							break;

						case MultiplyBlending:
							gl.blendFunc( 0, 768 );
							break;

						default:
							console.error( 'THREE.WebGLState: Invalid blending: ', blending );
							break;

					}

				}

				currentBlendSrc = null;
				currentBlendDst = null;
				currentBlendSrcAlpha = null;
				currentBlendDstAlpha = null;

				currentBlending = blending;
				currentPremultipledAlpha = premultipliedAlpha;

			}

			return;

		}

		// custom blending

		blendEquationAlpha = blendEquationAlpha || blendEquation;
		blendSrcAlpha = blendSrcAlpha || blendSrc;
		blendDstAlpha = blendDstAlpha || blendDst;

		if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {

			gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );

			currentBlendEquation = blendEquation;
			currentBlendEquationAlpha = blendEquationAlpha;

		}

		if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {

			gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );

			currentBlendSrc = blendSrc;
			currentBlendDst = blendDst;
			currentBlendSrcAlpha = blendSrcAlpha;
			currentBlendDstAlpha = blendDstAlpha;

		}

		currentBlending = blending;
		currentPremultipledAlpha = null;

	}

	function setMaterial( material, frontFaceCW ) {

		material.side === DoubleSide
			? disable( 2884 )
			: enable( 2884 );

		let flipSided = ( material.side === BackSide );
		if ( frontFaceCW ) flipSided = ! flipSided;

		setFlipSided( flipSided );

		( material.blending === NormalBlending && material.transparent === false )
			? setBlending( NoBlending )
			: setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );

		depthBuffer.setFunc( material.depthFunc );
		depthBuffer.setTest( material.depthTest );
		depthBuffer.setMask( material.depthWrite );
		colorBuffer.setMask( material.colorWrite );

		const stencilWrite = material.stencilWrite;
		stencilBuffer.setTest( stencilWrite );
		if ( stencilWrite ) {

			stencilBuffer.setMask( material.stencilWriteMask );
			stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
			stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );

		}

		setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );

	}

	//

	function setFlipSided( flipSided ) {

		if ( currentFlipSided !== flipSided ) {

			if ( flipSided ) {

				gl.frontFace( 2304 );

			} else {

				gl.frontFace( 2305 );

			}

			currentFlipSided = flipSided;

		}

	}

	function setCullFace( cullFace ) {

		if ( cullFace !== CullFaceNone ) {

			enable( 2884 );

			if ( cullFace !== currentCullFace ) {

				if ( cullFace === CullFaceBack ) {

					gl.cullFace( 1029 );

				} else if ( cullFace === CullFaceFront ) {

					gl.cullFace( 1028 );

				} else {

					gl.cullFace( 1032 );

				}

			}

		} else {

			disable( 2884 );

		}

		currentCullFace = cullFace;

	}

	function setLineWidth( width ) {

		if ( width !== currentLineWidth ) {

			if ( lineWidthAvailable ) gl.lineWidth( width );

			currentLineWidth = width;

		}

	}

	function setPolygonOffset( polygonOffset, factor, units ) {

		if ( polygonOffset ) {

			enable( 32823 );

			if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {

				gl.polygonOffset( factor, units );

				currentPolygonOffsetFactor = factor;
				currentPolygonOffsetUnits = units;

			}

		} else {

			disable( 32823 );

		}

	}

	function setScissorTest( scissorTest ) {

		if ( scissorTest ) {

			enable( 3089 );

		} else {

			disable( 3089 );

		}

	}

	// texture

	function activeTexture( webglSlot ) {

		if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;

		if ( currentTextureSlot !== webglSlot ) {

			gl.activeTexture( webglSlot );
			currentTextureSlot = webglSlot;

		}

	}

	function bindTexture( webglType, webglTexture ) {

		if ( currentTextureSlot === null ) {

			activeTexture();

		}

		let boundTexture = currentBoundTextures[ currentTextureSlot ];

		if ( boundTexture === undefined ) {

			boundTexture = { type: undefined, texture: undefined };
			currentBoundTextures[ currentTextureSlot ] = boundTexture;

		}

		if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {

			gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );

			boundTexture.type = webglType;
			boundTexture.texture = webglTexture;

		}

	}

	function unbindTexture() {

		const boundTexture = currentBoundTextures[ currentTextureSlot ];

		if ( boundTexture !== undefined && boundTexture.type !== undefined ) {

			gl.bindTexture( boundTexture.type, null );

			boundTexture.type = undefined;
			boundTexture.texture = undefined;

		}

	}

	function compressedTexImage2D() {

		try {

			gl.compressedTexImage2D.apply( gl, arguments );

		} catch ( error ) {

			console.error( 'THREE.WebGLState:', error );

		}

	}

	function texImage2D() {

		try {

			gl.texImage2D.apply( gl, arguments );

		} catch ( error ) {

			console.error( 'THREE.WebGLState:', error );

		}

	}

	function texImage3D() {

		try {

			gl.texImage3D.apply( gl, arguments );

		} catch ( error ) {

			console.error( 'THREE.WebGLState:', error );

		}

	}

	//

	function scissor( scissor ) {

		if ( currentScissor.equals( scissor ) === false ) {

			gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
			currentScissor.copy( scissor );

		}

	}

	function viewport( viewport ) {

		if ( currentViewport.equals( viewport ) === false ) {

			gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
			currentViewport.copy( viewport );

		}

	}

	//

	function reset() {

		enabledCapabilities = {};

		currentTextureSlot = null;
		currentBoundTextures = {};

		currentProgram = null;

		currentBlending = null;

		currentFlipSided = null;
		currentCullFace = null;

		colorBuffer.reset();
		depthBuffer.reset();
		stencilBuffer.reset();

	}

	return {

		buffers: {
			color: colorBuffer,
			depth: depthBuffer,
			stencil: stencilBuffer
		},

		enable: enable,
		disable: disable,

		useProgram: useProgram,

		setBlending: setBlending,
		setMaterial: setMaterial,

		setFlipSided: setFlipSided,
		setCullFace: setCullFace,

		setLineWidth: setLineWidth,
		setPolygonOffset: setPolygonOffset,

		setScissorTest: setScissorTest,

		activeTexture: activeTexture,
		bindTexture: bindTexture,
		unbindTexture: unbindTexture,
		compressedTexImage2D: compressedTexImage2D,
		texImage2D: texImage2D,
		texImage3D: texImage3D,

		scissor: scissor,
		viewport: viewport,

		reset: reset

	};

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {

	const isWebGL2 = capabilities.isWebGL2;
	const maxTextures = capabilities.maxTextures;
	const maxCubemapSize = capabilities.maxCubemapSize;
	const maxTextureSize = capabilities.maxTextureSize;
	const maxSamples = capabilities.maxSamples;

	const _videoTextures = new WeakMap();
	let _canvas;

	// cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
	// also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
	// Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).

	let useOffscreenCanvas = false;

	try {

		useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
			&& ( new OffscreenCanvas( 1, 1 ).getContext( "2d" ) ) !== null;

	} catch ( err ) {

		// Ignore any errors

	}

	function createCanvas( width, height ) {

		// Use OffscreenCanvas when available. Specially needed in web workers

		return useOffscreenCanvas ?
			new OffscreenCanvas( width, height ) :
			document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );

	}

	function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {

		let scale = 1;

		// handle case if texture exceeds max size

		if ( image.width > maxSize || image.height > maxSize ) {

			scale = maxSize / Math.max( image.width, image.height );

		}

		// only perform resize if necessary

		if ( scale < 1 || needsPowerOfTwo === true ) {

			// only perform resize for certain image types

			if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
				( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
				( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {

				const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;

				const width = floor( scale * image.width );
				const height = floor( scale * image.height );

				if ( _canvas === undefined ) _canvas = createCanvas( width, height );

				// cube textures can't reuse the same canvas

				const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;

				canvas.width = width;
				canvas.height = height;

				const context = canvas.getContext( '2d' );
				context.drawImage( image, 0, 0, width, height );

				console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );

				return canvas;

			} else {

				if ( 'data' in image ) {

					console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );

				}

				return image;

			}

		}

		return image;

	}

	function isPowerOfTwo( image ) {

		return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );

	}

	function textureNeedsPowerOfTwo( texture ) {

		if ( isWebGL2 ) return false;

		return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
			( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );

	}

	function textureNeedsGenerateMipmaps( texture, supportsMips ) {

		return texture.generateMipmaps && supportsMips &&
			texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;

	}

	function generateMipmap( target, texture, width, height ) {

		_gl.generateMipmap( target );

		const textureProperties = properties.get( texture );

		// Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
		textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;

	}

	function getInternalFormat( internalFormatName, glFormat, glType ) {

		if ( isWebGL2 === false ) return glFormat;

		if ( internalFormatName !== null ) {

			if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];

			console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );

		}

		let internalFormat = glFormat;

		if ( glFormat === 6403 ) {

			if ( glType === 5126 ) internalFormat = 33326;
			if ( glType === 5131 ) internalFormat = 33325;
			if ( glType === 5121 ) internalFormat = 33321;

		}

		if ( glFormat === 6407 ) {

			if ( glType === 5126 ) internalFormat = 34837;
			if ( glType === 5131 ) internalFormat = 34843;
			if ( glType === 5121 ) internalFormat = 32849;

		}

		if ( glFormat === 6408 ) {

			if ( glType === 5126 ) internalFormat = 34836;
			if ( glType === 5131 ) internalFormat = 34842;
			if ( glType === 5121 ) internalFormat = 32856;

		}

		if ( internalFormat === 33325 || internalFormat === 33326 ||
			internalFormat === 34842 || internalFormat === 34836 ) {

			extensions.get( 'EXT_color_buffer_float' );

		}

		return internalFormat;

	}

	// Fallback filters for non-power-of-2 textures

	function filterFallback( f ) {

		if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {

			return 9728;

		}

		return 9729;

	}

	//

	function onTextureDispose( event ) {

		const texture = event.target;

		texture.removeEventListener( 'dispose', onTextureDispose );

		deallocateTexture( texture );

		if ( texture.isVideoTexture ) {

			_videoTextures.delete( texture );

		}

		info.memory.textures --;

	}

	function onRenderTargetDispose( event ) {

		const renderTarget = event.target;

		renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );

		deallocateRenderTarget( renderTarget );

		info.memory.textures --;

	}

	//

	function deallocateTexture( texture ) {

		const textureProperties = properties.get( texture );

		if ( textureProperties.__webglInit === undefined ) return;

		_gl.deleteTexture( textureProperties.__webglTexture );

		properties.remove( texture );

	}

	function deallocateRenderTarget( renderTarget ) {

		const renderTargetProperties = properties.get( renderTarget );
		const textureProperties = properties.get( renderTarget.texture );

		if ( ! renderTarget ) return;

		if ( textureProperties.__webglTexture !== undefined ) {

			_gl.deleteTexture( textureProperties.__webglTexture );

		}

		if ( renderTarget.depthTexture ) {

			renderTarget.depthTexture.dispose();

		}

		if ( renderTarget.isWebGLCubeRenderTarget ) {

			for ( let i = 0; i < 6; i ++ ) {

				_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
				if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );

			}

		} else {

			_gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
			if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
			if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
			if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
			if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );

		}

		properties.remove( renderTarget.texture );
		properties.remove( renderTarget );

	}

	//

	let textureUnits = 0;

	function resetTextureUnits() {

		textureUnits = 0;

	}

	function allocateTextureUnit() {

		const textureUnit = textureUnits;

		if ( textureUnit >= maxTextures ) {

			console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );

		}

		textureUnits += 1;

		return textureUnit;

	}

	//

	function setTexture2D( texture, slot ) {

		const textureProperties = properties.get( texture );

		if ( texture.isVideoTexture ) updateVideoTexture( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

			const image = texture.image;

			if ( image === undefined ) {

				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );

			} else if ( image.complete === false ) {

				console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );

			} else {

				uploadTexture( textureProperties, texture, slot );
				return;

			}

		}

		state.activeTexture( 33984 + slot );
		state.bindTexture( 3553, textureProperties.__webglTexture );

	}

	function setTexture2DArray( texture, slot ) {

		const textureProperties = properties.get( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

			uploadTexture( textureProperties, texture, slot );
			return;

		}

		state.activeTexture( 33984 + slot );
		state.bindTexture( 35866, textureProperties.__webglTexture );

	}

	function setTexture3D( texture, slot ) {

		const textureProperties = properties.get( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

			uploadTexture( textureProperties, texture, slot );
			return;

		}

		state.activeTexture( 33984 + slot );
		state.bindTexture( 32879, textureProperties.__webglTexture );

	}

	function setTextureCube( texture, slot ) {

		if ( texture.image.length !== 6 ) return;

		const textureProperties = properties.get( texture );

		if ( texture.version > 0 && textureProperties.__version !== texture.version ) {

			initTexture( textureProperties, texture );

			state.activeTexture( 33984 + slot );
			state.bindTexture( 34067, textureProperties.__webglTexture );

			_gl.pixelStorei( 37440, texture.flipY );

			const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
			const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );

			const cubeImage = [];

			for ( let i = 0; i < 6; i ++ ) {

				if ( ! isCompressed && ! isDataTexture ) {

					cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );

				} else {

					cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];

				}

			}

			const image = cubeImage[ 0 ],
				supportsMips = isPowerOfTwo( image ) || isWebGL2,
				glFormat = utils.convert( texture.format ),
				glType = utils.convert( texture.type ),
				glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );

			setTextureParameters( 34067, texture, supportsMips );

			let mipmaps;

			if ( isCompressed ) {

				for ( let i = 0; i < 6; i ++ ) {

					mipmaps = cubeImage[ i ].mipmaps;

					for ( let j = 0; j < mipmaps.length; j ++ ) {

						const mipmap = mipmaps[ j ];

						if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {

							if ( glFormat !== null ) {

								state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );

							} else {

								console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );

							}

						} else {

							state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );

						}

					}

				}

				textureProperties.__maxMipLevel = mipmaps.length - 1;

			} else {

				mipmaps = texture.mipmaps;

				for ( let i = 0; i < 6; i ++ ) {

					if ( isDataTexture ) {

						state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );

						for ( let j = 0; j < mipmaps.length; j ++ ) {

							const mipmap = mipmaps[ j ];
							const mipmapImage = mipmap.image[ i ].image;

							state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );

						}

					} else {

						state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );

						for ( let j = 0; j < mipmaps.length; j ++ ) {

							const mipmap = mipmaps[ j ];

							state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );

						}

					}

				}

				textureProperties.__maxMipLevel = mipmaps.length;

			}

			if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {

				// We assume images for cube map have the same size.
				generateMipmap( 34067, texture, image.width, image.height );

			}

			textureProperties.__version = texture.version;

			if ( texture.onUpdate ) texture.onUpdate( texture );

		} else {

			state.activeTexture( 33984 + slot );
			state.bindTexture( 34067, textureProperties.__webglTexture );

		}

	}

	function setTextureCubeDynamic( texture, slot ) {

		state.activeTexture( 33984 + slot );
		state.bindTexture( 34067, properties.get( texture ).__webglTexture );

	}

	const wrappingToGL = {
		[ RepeatWrapping ]: 10497,
		[ ClampToEdgeWrapping ]: 33071,
		[ MirroredRepeatWrapping ]: 33648
	};

	const filterToGL = {
		[ NearestFilter ]: 9728,
		[ NearestMipmapNearestFilter ]: 9984,
		[ NearestMipmapLinearFilter ]: 9986,

		[ LinearFilter ]: 9729,
		[ LinearMipmapNearestFilter ]: 9985,
		[ LinearMipmapLinearFilter ]: 9987
	};

	function setTextureParameters( textureType, texture, supportsMips ) {

		if ( supportsMips ) {

			_gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
			_gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );

			if ( textureType === 32879 || textureType === 35866 ) {

				_gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );

			}

			_gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
			_gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );

		} else {

			_gl.texParameteri( textureType, 10242, 33071 );
			_gl.texParameteri( textureType, 10243, 33071 );

			if ( textureType === 32879 || textureType === 35866 ) {

				_gl.texParameteri( textureType, 32882, 33071 );

			}

			if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {

				console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );

			}

			_gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
			_gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );

			if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {

				console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );

			}

		}

		const extension = extensions.get( 'EXT_texture_filter_anisotropic' );

		if ( extension ) {

			if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
			if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;

			if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {

				_gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
				properties.get( texture ).__currentAnisotropy = texture.anisotropy;

			}

		}

	}

	function initTexture( textureProperties, texture ) {

		if ( textureProperties.__webglInit === undefined ) {

			textureProperties.__webglInit = true;

			texture.addEventListener( 'dispose', onTextureDispose );

			textureProperties.__webglTexture = _gl.createTexture();

			info.memory.textures ++;

		}

	}

	function uploadTexture( textureProperties, texture, slot ) {

		let textureType = 3553;

		if ( texture.isDataTexture2DArray ) textureType = 35866;
		if ( texture.isDataTexture3D ) textureType = 32879;

		initTexture( textureProperties, texture );

		state.activeTexture( 33984 + slot );
		state.bindTexture( textureType, textureProperties.__webglTexture );

		_gl.pixelStorei( 37440, texture.flipY );
		_gl.pixelStorei( 37441, texture.premultiplyAlpha );
		_gl.pixelStorei( 3317, texture.unpackAlignment );

		const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
		const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );

		const supportsMips = isPowerOfTwo( image ) || isWebGL2,
			glFormat = utils.convert( texture.format );

		let glType = utils.convert( texture.type ),
			glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );

		setTextureParameters( textureType, texture, supportsMips );

		let mipmap;
		const mipmaps = texture.mipmaps;

		if ( texture.isDepthTexture ) {

			// populate depth texture with dummy data

			glInternalFormat = 6402;

			if ( isWebGL2 ) {

				if ( texture.type === FloatType ) {

					glInternalFormat = 36012;

				} else if ( texture.type === UnsignedIntType ) {

					glInternalFormat = 33190;

				} else if ( texture.type === UnsignedInt248Type ) {

					glInternalFormat = 35056;

				} else {

					glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D

				}

			} else {

				if ( texture.type === FloatType ) {

					console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );

				}

			}

			// validation checks for WebGL 1

			if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {

				// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
				// DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
				// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
				if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {

					console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );

					texture.type = UnsignedShortType;
					glType = utils.convert( texture.type );

				}

			}

			if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {

				// Depth stencil textures need the DEPTH_STENCIL internal format
				// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
				glInternalFormat = 34041;

				// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
				// DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
				// (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
				if ( texture.type !== UnsignedInt248Type ) {

					console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );

					texture.type = UnsignedInt248Type;
					glType = utils.convert( texture.type );

				}

			}

			//

			state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );

		} else if ( texture.isDataTexture ) {

			// use manually created mipmaps if available
			// if there are no manual mipmaps
			// set 0 level mipmap and then use GL to generate other mipmap levels

			if ( mipmaps.length > 0 && supportsMips ) {

				for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {

					mipmap = mipmaps[ i ];
					state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );

				}

				texture.generateMipmaps = false;
				textureProperties.__maxMipLevel = mipmaps.length - 1;

			} else {

				state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
				textureProperties.__maxMipLevel = 0;

			}

		} else if ( texture.isCompressedTexture ) {

			for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {

				mipmap = mipmaps[ i ];

				if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {

					if ( glFormat !== null ) {

						state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );

					} else {

						console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );

					}

				} else {

					state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );

				}

			}

			textureProperties.__maxMipLevel = mipmaps.length - 1;

		} else if ( texture.isDataTexture2DArray ) {

			state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
			textureProperties.__maxMipLevel = 0;

		} else if ( texture.isDataTexture3D ) {

			state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
			textureProperties.__maxMipLevel = 0;

		} else {

			// regular Texture (image, video, canvas)

			// use manually created mipmaps if available
			// if there are no manual mipmaps
			// set 0 level mipmap and then use GL to generate other mipmap levels

			if ( mipmaps.length > 0 && supportsMips ) {

				for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {

					mipmap = mipmaps[ i ];
					state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );

				}

				texture.generateMipmaps = false;
				textureProperties.__maxMipLevel = mipmaps.length - 1;

			} else {

				state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
				textureProperties.__maxMipLevel = 0;

			}

		}

		if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {

			generateMipmap( textureType, texture, image.width, image.height );

		}

		textureProperties.__version = texture.version;

		if ( texture.onUpdate ) texture.onUpdate( texture );

	}

	// Render targets

	// Setup storage for target texture and bind it to correct framebuffer
	function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {

		const glFormat = utils.convert( renderTarget.texture.format );
		const glType = utils.convert( renderTarget.texture.type );
		const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
		state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
		_gl.bindFramebuffer( 36160, framebuffer );
		_gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
		_gl.bindFramebuffer( 36160, null );

	}

	// Setup storage for internal depth/stencil buffers and bind to correct framebuffer
	function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {

		_gl.bindRenderbuffer( 36161, renderbuffer );

		if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {

			let glInternalFormat = 33189;

			if ( isMultisample ) {

				const depthTexture = renderTarget.depthTexture;

				if ( depthTexture && depthTexture.isDepthTexture ) {

					if ( depthTexture.type === FloatType ) {

						glInternalFormat = 36012;

					} else if ( depthTexture.type === UnsignedIntType ) {

						glInternalFormat = 33190;

					}

				}

				const samples = getRenderTargetSamples( renderTarget );

				_gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );

			} else {

				_gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );

			}

			_gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );

		} else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {

			if ( isMultisample ) {

				const samples = getRenderTargetSamples( renderTarget );

				_gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );

			} else {

				_gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );

			}


			_gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );

		} else {

			const glFormat = utils.convert( renderTarget.texture.format );
			const glType = utils.convert( renderTarget.texture.type );
			const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );

			if ( isMultisample ) {

				const samples = getRenderTargetSamples( renderTarget );

				_gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );

			} else {

				_gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );

			}

		}

		_gl.bindRenderbuffer( 36161, null );

	}

	// Setup resources for a Depth Texture for a FBO (needs an extension)
	function setupDepthTexture( framebuffer, renderTarget ) {

		const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
		if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );

		_gl.bindFramebuffer( 36160, framebuffer );

		if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {

			throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );

		}

		// upload an empty depth texture with framebuffer size
		if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
				renderTarget.depthTexture.image.width !== renderTarget.width ||
				renderTarget.depthTexture.image.height !== renderTarget.height ) {

			renderTarget.depthTexture.image.width = renderTarget.width;
			renderTarget.depthTexture.image.height = renderTarget.height;
			renderTarget.depthTexture.needsUpdate = true;

		}

		setTexture2D( renderTarget.depthTexture, 0 );

		const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;

		if ( renderTarget.depthTexture.format === DepthFormat ) {

			_gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );

		} else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {

			_gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );

		} else {

			throw new Error( 'Unknown depthTexture format' );

		}

	}

	// Setup GL resources for a non-texture depth buffer
	function setupDepthRenderbuffer( renderTarget ) {

		const renderTargetProperties = properties.get( renderTarget );

		const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );

		if ( renderTarget.depthTexture ) {

			if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );

			setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );

		} else {

			if ( isCube ) {

				renderTargetProperties.__webglDepthbuffer = [];

				for ( let i = 0; i < 6; i ++ ) {

					_gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
					renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
					setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );

				}

			} else {

				_gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
				renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
				setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );

			}

		}

		_gl.bindFramebuffer( 36160, null );

	}

	// Set up GL resources for the render target
	function setupRenderTarget( renderTarget ) {

		const renderTargetProperties = properties.get( renderTarget );
		const textureProperties = properties.get( renderTarget.texture );

		renderTarget.addEventListener( 'dispose', onRenderTargetDispose );

		textureProperties.__webglTexture = _gl.createTexture();

		info.memory.textures ++;

		const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
		const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
		const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;

		// Handles WebGL2 RGBFormat fallback - #18858

		if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {

			renderTarget.texture.format = RGBAFormat;

			console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );

		}

		// Setup framebuffer

		if ( isCube ) {

			renderTargetProperties.__webglFramebuffer = [];

			for ( let i = 0; i < 6; i ++ ) {

				renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();

			}

		} else {

			renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();

			if ( isMultisample ) {

				if ( isWebGL2 ) {

					renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
					renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();

					_gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );

					const glFormat = utils.convert( renderTarget.texture.format );
					const glType = utils.convert( renderTarget.texture.type );
					const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
					const samples = getRenderTargetSamples( renderTarget );
					_gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );

					_gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
					_gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
					_gl.bindRenderbuffer( 36161, null );

					if ( renderTarget.depthBuffer ) {

						renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
						setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );

					}

					_gl.bindFramebuffer( 36160, null );


				} else {

					console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );

				}

			}

		}

		// Setup color buffer

		if ( isCube ) {

			state.bindTexture( 34067, textureProperties.__webglTexture );
			setTextureParameters( 34067, renderTarget.texture, supportsMips );

			for ( let i = 0; i < 6; i ++ ) {

				setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );

			}

			if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {

				generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );

			}

			state.bindTexture( 34067, null );

		} else {

			state.bindTexture( 3553, textureProperties.__webglTexture );
			setTextureParameters( 3553, renderTarget.texture, supportsMips );
			setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );

			if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {

				generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );

			}

			state.bindTexture( 3553, null );

		}

		// Setup depth and stencil buffers

		if ( renderTarget.depthBuffer ) {

			setupDepthRenderbuffer( renderTarget );

		}

	}

	function updateRenderTargetMipmap( renderTarget ) {

		const texture = renderTarget.texture;
		const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;

		if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {

			const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
			const webglTexture = properties.get( texture ).__webglTexture;

			state.bindTexture( target, webglTexture );
			generateMipmap( target, texture, renderTarget.width, renderTarget.height );
			state.bindTexture( target, null );

		}

	}

	function updateMultisampleRenderTarget( renderTarget ) {

		if ( renderTarget.isWebGLMultisampleRenderTarget ) {

			if ( isWebGL2 ) {

				const renderTargetProperties = properties.get( renderTarget );

				_gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
				_gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );

				const width = renderTarget.width;
				const height = renderTarget.height;
				let mask = 16384;

				if ( renderTarget.depthBuffer ) mask |= 256;
				if ( renderTarget.stencilBuffer ) mask |= 1024;

				_gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );

				_gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905

			} else {

				console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );

			}

		}

	}

	function getRenderTargetSamples( renderTarget ) {

		return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
			Math.min( maxSamples, renderTarget.samples ) : 0;

	}

	function updateVideoTexture( texture ) {

		const frame = info.render.frame;

		// Check the last frame we updated the VideoTexture

		if ( _videoTextures.get( texture ) !== frame ) {

			_videoTextures.set( texture, frame );
			texture.update();

		}

	}

	// backwards compatibility

	let warnedTexture2D = false;
	let warnedTextureCube = false;

	function safeSetTexture2D( texture, slot ) {

		if ( texture && texture.isWebGLRenderTarget ) {

			if ( warnedTexture2D === false ) {

				console.warn( "THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead." );
				warnedTexture2D = true;

			}

			texture = texture.texture;

		}

		setTexture2D( texture, slot );

	}

	function safeSetTextureCube( texture, slot ) {

		if ( texture && texture.isWebGLCubeRenderTarget ) {

			if ( warnedTextureCube === false ) {

				console.warn( "THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
				warnedTextureCube = true;

			}

			texture = texture.texture;

		}

		// currently relying on the fact that WebGLCubeRenderTarget.texture is a Texture and NOT a CubeTexture
		// TODO: unify these code paths
		if ( ( texture && texture.isCubeTexture ) ||
			( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {

			// CompressedTexture can have Array in image :/

			// this function alone should take care of cube textures
			setTextureCube( texture, slot );

		} else {

			// assumed: texture property of THREE.WebGLCubeRenderTarget
			setTextureCubeDynamic( texture, slot );

		}

	}

	//

	this.allocateTextureUnit = allocateTextureUnit;
	this.resetTextureUnits = resetTextureUnits;

	this.setTexture2D = setTexture2D;
	this.setTexture2DArray = setTexture2DArray;
	this.setTexture3D = setTexture3D;
	this.setTextureCube = setTextureCube;
	this.setTextureCubeDynamic = setTextureCubeDynamic;
	this.setupRenderTarget = setupRenderTarget;
	this.updateRenderTargetMipmap = updateRenderTargetMipmap;
	this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;

	this.safeSetTexture2D = safeSetTexture2D;
	this.safeSetTextureCube = safeSetTextureCube;

}

/**
 * @author thespite / http://www.twitter.com/thespite
 */

function WebGLUtils( gl, extensions, capabilities ) {

	const isWebGL2 = capabilities.isWebGL2;

	function convert( p ) {

		let extension;

		if ( p === UnsignedByteType ) return 5121;
		if ( p === UnsignedShort4444Type ) return 32819;
		if ( p === UnsignedShort5551Type ) return 32820;
		if ( p === UnsignedShort565Type ) return 33635;

		if ( p === ByteType ) return 5120;
		if ( p === ShortType ) return 5122;
		if ( p === UnsignedShortType ) return 5123;
		if ( p === IntType ) return 5124;
		if ( p === UnsignedIntType ) return 5125;
		if ( p === FloatType ) return 5126;

		if ( p === HalfFloatType ) {

			if ( isWebGL2 ) return 5131;

			extension = extensions.get( 'OES_texture_half_float' );

			if ( extension !== null ) {

				return extension.HALF_FLOAT_OES;

			} else {

				return null;

			}

		}

		if ( p === AlphaFormat ) return 6406;
		if ( p === RGBFormat ) return 6407;
		if ( p === RGBAFormat ) return 6408;
		if ( p === LuminanceFormat ) return 6409;
		if ( p === LuminanceAlphaFormat ) return 6410;
		if ( p === DepthFormat ) return 6402;
		if ( p === DepthStencilFormat ) return 34041;
		if ( p === RedFormat ) return 6403;

		// WebGL2 formats.

		if ( p === RedIntegerFormat ) return 36244;
		if ( p === RGFormat ) return 33319;
		if ( p === RGIntegerFormat ) return 33320;
		if ( p === RGBIntegerFormat ) return 36248;
		if ( p === RGBAIntegerFormat ) return 36249;

		if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
			p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {

			extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );

			if ( extension !== null ) {

				if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
				if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
				if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
				if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;

			} else {

				return null;

			}

		}

		if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
			p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {

			extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );

			if ( extension !== null ) {

				if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
				if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
				if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
				if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;

			} else {

				return null;

			}

		}

		if ( p === RGB_ETC1_Format ) {

			extension = extensions.get( 'WEBGL_compressed_texture_etc1' );

			if ( extension !== null ) {

				return extension.COMPRESSED_RGB_ETC1_WEBGL;

			} else {

				return null;

			}

		}

		if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {

			extension = extensions.get( 'WEBGL_compressed_texture_etc' );

			if ( extension !== null ) {

				if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
				if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;

			}

		}

		if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
			p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
			p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
			p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
			p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
			p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
			p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
			p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
			p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
			p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {

			extension = extensions.get( 'WEBGL_compressed_texture_astc' );

			if ( extension !== null ) {

				// TODO Complete?

				return p;

			} else {

				return null;

			}

		}

		if ( p === RGBA_BPTC_Format ) {

			extension = extensions.get( 'EXT_texture_compression_bptc' );

			if ( extension !== null ) {

				// TODO Complete?

				return p;

			} else {

				return null;

			}

		}

		if ( p === UnsignedInt248Type ) {

			if ( isWebGL2 ) return 34042;

			extension = extensions.get( 'WEBGL_depth_texture' );

			if ( extension !== null ) {

				return extension.UNSIGNED_INT_24_8_WEBGL;

			} else {

				return null;

			}

		}

	}

	return { convert: convert };

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function ArrayCamera( array ) {

	PerspectiveCamera.call( this );

	this.cameras = array || [];

}

ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {

	constructor: ArrayCamera,

	isArrayCamera: true

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function Group() {

	Object3D.call( this );

	this.type = 'Group';

}

Group.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Group,

	isGroup: true

} );

/**
 * @author Mugen87 / https://github.com/Mugen87
 */

function WebXRController() {

	this._targetRay = null;
	this._grip = null;

}

Object.assign( WebXRController.prototype, {

	constructor: WebXRController,

	getTargetRaySpace: function () {

		if ( this._targetRay === null ) {

			this._targetRay = new Group();
			this._targetRay.matrixAutoUpdate = false;
			this._targetRay.visible = false;

		}

		return this._targetRay;

	},

	getGripSpace: function () {

		if ( this._grip === null ) {

			this._grip = new Group();
			this._grip.matrixAutoUpdate = false;
			this._grip.visible = false;

		}

		return this._grip;

	},

	dispatchEvent: function ( event ) {

		if ( this._targetRay !== null ) {

			this._targetRay.dispatchEvent( event );

		}

		if ( this._grip !== null ) {

			this._grip.dispatchEvent( event );

		}

		return this;

	},

	disconnect: function ( inputSource ) {

		this.dispatchEvent( { type: 'disconnected', data: inputSource } );

		if ( this._targetRay !== null ) {

			this._targetRay.visible = false;

		}

		if ( this._grip !== null ) {

			this._grip.visible = false;

		}

		return this;

	},

	update: function ( inputSource, frame, referenceSpace ) {

		let inputPose = null;
		let gripPose = null;

		const targetRay = this._targetRay;
		const grip = this._grip;

		if ( inputSource ) {

			if ( targetRay !== null ) {

				inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );

				if ( inputPose !== null ) {

					targetRay.matrix.fromArray( inputPose.transform.matrix );
					targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );

				}

			}

			if ( grip !== null && inputSource.gripSpace ) {

				gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );

				if ( gripPose !== null ) {

					grip.matrix.fromArray( gripPose.transform.matrix );
					grip.matrix.decompose( grip.position, grip.rotation, grip.scale );

				}

			}

		}

		if ( targetRay !== null ) {

			targetRay.visible = ( inputPose !== null );

		}

		if ( grip !== null ) {

			grip.visible = ( gripPose !== null );

		}

		return this;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebXRManager( renderer, gl ) {

	const scope = this;

	let session = null;

	let framebufferScaleFactor = 1.0;

	let referenceSpace = null;
	let referenceSpaceType = 'local-floor';

	let pose = null;

	const controllers = [];
	const inputSourcesMap = new Map();

	//

	const cameraL = new PerspectiveCamera();
	cameraL.layers.enable( 1 );
	cameraL.viewport = new Vector4();

	const cameraR = new PerspectiveCamera();
	cameraR.layers.enable( 2 );
	cameraR.viewport = new Vector4();

	const cameras = [ cameraL, cameraR ];

	const cameraVR = new ArrayCamera();
	cameraVR.layers.enable( 1 );
	cameraVR.layers.enable( 2 );

	let _currentDepthNear = null;
	let _currentDepthFar = null;

	//

	this.enabled = false;

	this.isPresenting = false;

	this.getController = function ( index ) {

		let controller = controllers[ index ];

		if ( controller === undefined ) {

			controller = new WebXRController();
			controllers[ index ] = controller;

		}

		return controller.getTargetRaySpace();

	};

	this.getControllerGrip = function ( index ) {

		let controller = controllers[ index ];

		if ( controller === undefined ) {

			controller = new WebXRController();
			controllers[ index ] = controller;

		}

		return controller.getGripSpace();

	};

	//

	function onSessionEvent( event ) {

		const controller = inputSourcesMap.get( event.inputSource );

		if ( controller ) {

			controller.dispatchEvent( { type: event.type } );

		}

	}

	function onSessionEnd() {

		inputSourcesMap.forEach( function ( controller, inputSource ) {

			controller.disconnect( inputSource );

		} );

		inputSourcesMap.clear();

		//

		renderer.setFramebuffer( null );
		renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
		animation.stop();

		scope.isPresenting = false;

		scope.dispatchEvent( { type: 'sessionend' } );

	}

	function onRequestReferenceSpace( value ) {

		referenceSpace = value;

		animation.setContext( session );
		animation.start();

		scope.isPresenting = true;

		scope.dispatchEvent( { type: 'sessionstart' } );

	}

	this.setFramebufferScaleFactor = function ( value ) {

		framebufferScaleFactor = value;

		if ( scope.isPresenting === true ) {

			console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );

		}

	};

	this.setReferenceSpaceType = function ( value ) {

		referenceSpaceType = value;

		if ( scope.isPresenting === true ) {

			console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );

		}

	};

	this.getReferenceSpace = function () {

		return referenceSpace;

	};

	this.getSession = function () {

		return session;

	};

	this.setSession = function ( value ) {

		session = value;

		if ( session !== null ) {

			session.addEventListener( 'select', onSessionEvent );
			session.addEventListener( 'selectstart', onSessionEvent );
			session.addEventListener( 'selectend', onSessionEvent );
			session.addEventListener( 'squeeze', onSessionEvent );
			session.addEventListener( 'squeezestart', onSessionEvent );
			session.addEventListener( 'squeezeend', onSessionEvent );
			session.addEventListener( 'end', onSessionEnd );

			const attributes = gl.getContextAttributes();

			if ( attributes.xrCompatible !== true ) {

				gl.makeXRCompatible();

			}

			const layerInit = {
				antialias: attributes.antialias,
				alpha: attributes.alpha,
				depth: attributes.depth,
				stencil: attributes.stencil,
				framebufferScaleFactor: framebufferScaleFactor
			};

			// eslint-disable-next-line no-undef
			const baseLayer = new XRWebGLLayer( session, gl, layerInit );

			session.updateRenderState( { baseLayer: baseLayer } );

			session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );

			//

			session.addEventListener( 'inputsourceschange', updateInputSources );

		}

	};

	function updateInputSources( event ) {

		const inputSources = session.inputSources;

		// Assign inputSources to available controllers

		for ( let i = 0; i < controllers.length; i ++ ) {

			inputSourcesMap.set( inputSources[ i ], controllers[ i ] );

		}

		// Notify disconnected

		for ( let i = 0; i < event.removed.length; i ++ ) {

			const inputSource = event.removed[ i ];
			const controller = inputSourcesMap.get( inputSource );

			if ( controller ) {

				controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
				inputSourcesMap.delete( inputSource );

			}

		}

		// Notify connected

		for ( let i = 0; i < event.added.length; i ++ ) {

			const inputSource = event.added[ i ];
			const controller = inputSourcesMap.get( inputSource );

			if ( controller ) {

				controller.dispatchEvent( { type: 'connected', data: inputSource } );

			}

		}

	}

	//

	const cameraLPos = new Vector3();
	const cameraRPos = new Vector3();

	/**
	 * @author jsantell / https://www.jsantell.com/
	 *
	 * Assumes 2 cameras that are parallel and share an X-axis, and that
	 * the cameras' projection and world matrices have already been set.
	 * And that near and far planes are identical for both cameras.
	 * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
	 */
	function setProjectionFromUnion( camera, cameraL, cameraR ) {

		cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
		cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );

		const ipd = cameraLPos.distanceTo( cameraRPos );

		const projL = cameraL.projectionMatrix.elements;
		const projR = cameraR.projectionMatrix.elements;

		// VR systems will have identical far and near planes, and
		// most likely identical top and bottom frustum extents.
		// Use the left camera for these values.
		const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
		const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
		const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
		const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];

		const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
		const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
		const left = near * leftFov;
		const right = near * rightFov;

		// Calculate the new camera's position offset from the
		// left camera. xOffset should be roughly half `ipd`.
		const zOffset = ipd / ( - leftFov + rightFov );
		const xOffset = zOffset * - leftFov;

		// TODO: Better way to apply this offset?
		cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
		camera.translateX( xOffset );
		camera.translateZ( zOffset );
		camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

		// Find the union of the frustum values of the cameras and scale
		// the values so that the near plane's position does not change in world space,
		// although must now be relative to the new union camera.
		const near2 = near + zOffset;
		const far2 = far + zOffset;
		const left2 = left - xOffset;
		const right2 = right + ( ipd - xOffset );
		const top2 = topFov * far / far2 * near2;
		const bottom2 = bottomFov * far / far2 * near2;

		camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );

	}

	function updateCamera( camera, parent ) {

		if ( parent === null ) {

			camera.matrixWorld.copy( camera.matrix );

		} else {

			camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );

		}

		camera.matrixWorldInverse.getInverse( camera.matrixWorld );

	}

	this.getCamera = function ( camera ) {

		cameraVR.near = cameraR.near = cameraL.near = camera.near;
		cameraVR.far = cameraR.far = cameraL.far = camera.far;

		if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {

			// Note that the new renderState won't apply until the next frame. See #18320

			session.updateRenderState( {
				depthNear: cameraVR.near,
				depthFar: cameraVR.far
			} );

			_currentDepthNear = cameraVR.near;
			_currentDepthFar = cameraVR.far;

		}

		const parent = camera.parent;
		const cameras = cameraVR.cameras;

		updateCamera( cameraVR, parent );

		for ( let i = 0; i < cameras.length; i ++ ) {

			updateCamera( cameras[ i ], parent );

		}

		// update camera and its children

		camera.matrixWorld.copy( cameraVR.matrixWorld );

		const children = camera.children;

		for ( let i = 0, l = children.length; i < l; i ++ ) {

			children[ i ].updateMatrixWorld( true );

		}

		// update projection matrix for proper view frustum culling

		if ( cameras.length === 2 ) {

			setProjectionFromUnion( cameraVR, cameraL, cameraR );

		} else {

			// assume single camera setup (AR)

			cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );

		}

		return cameraVR;

	};

	// Animation Loop

	let onAnimationFrameCallback = null;

	function onAnimationFrame( time, frame ) {

		pose = frame.getViewerPose( referenceSpace );

		if ( pose !== null ) {

			const views = pose.views;
			const baseLayer = session.renderState.baseLayer;

			renderer.setFramebuffer( baseLayer.framebuffer );

			let cameraVRNeedsUpdate = false;

			// check if it's necessary to rebuild cameraVR's camera list

			if ( views.length !== cameraVR.cameras.length ) {

				cameraVR.cameras.length = 0;
				cameraVRNeedsUpdate = true;

			}

			for ( let i = 0; i < views.length; i ++ ) {

				const view = views[ i ];
				const viewport = baseLayer.getViewport( view );

				const camera = cameras[ i ];
				camera.matrix.fromArray( view.transform.matrix );
				camera.projectionMatrix.fromArray( view.projectionMatrix );
				camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );

				if ( i === 0 ) {

					cameraVR.matrix.copy( camera.matrix );

				}

				if ( cameraVRNeedsUpdate === true ) {

					cameraVR.cameras.push( camera );

				}

			}

		}

		//

		const inputSources = session.inputSources;

		for ( let i = 0; i < controllers.length; i ++ ) {

			const controller = controllers[ i ];
			const inputSource = inputSources[ i ];

			controller.update( inputSource, frame, referenceSpace );

		}

		if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );

	}

	const animation = new WebGLAnimation();
	animation.setAnimationLoop( onAnimationFrame );

	this.setAnimationLoop = function ( callback ) {

		onAnimationFrameCallback = callback;

	};

	this.dispose = function () {};

}

Object.assign( WebXRManager.prototype, EventDispatcher.prototype );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function WebGLMaterials( properties ) {

	function refreshFogUniforms( uniforms, fog ) {

		uniforms.fogColor.value.copy( fog.color );

		if ( fog.isFog ) {

			uniforms.fogNear.value = fog.near;
			uniforms.fogFar.value = fog.far;

		} else if ( fog.isFogExp2 ) {

			uniforms.fogDensity.value = fog.density;

		}

	}

	function refreshMaterialUniforms( uniforms, material, environment, pixelRatio, height ) {

		if ( material.isMeshBasicMaterial ) {

			refreshUniformsCommon( uniforms, material );

		} else if ( material.isMeshLambertMaterial ) {

			refreshUniformsCommon( uniforms, material );
			refreshUniformsLambert( uniforms, material );

		} else if ( material.isMeshToonMaterial ) {

			refreshUniformsCommon( uniforms, material );
			refreshUniformsToon( uniforms, material );

		} else if ( material.isMeshPhongMaterial ) {

			refreshUniformsCommon( uniforms, material );
			refreshUniformsPhong( uniforms, material );

		} else if ( material.isMeshStandardMaterial ) {

			refreshUniformsCommon( uniforms, material, environment );

			if ( material.isMeshPhysicalMaterial ) {

				refreshUniformsPhysical( uniforms, material, environment );

			} else {

				refreshUniformsStandard( uniforms, material, environment );

			}

		} else if ( material.isMeshMatcapMaterial ) {

			refreshUniformsCommon( uniforms, material );
			refreshUniformsMatcap( uniforms, material );

		} else if ( material.isMeshDepthMaterial ) {

			refreshUniformsCommon( uniforms, material );
			refreshUniformsDepth( uniforms, material );

		} else if ( material.isMeshDistanceMaterial ) {

			refreshUniformsCommon( uniforms, material );
			refreshUniformsDistance( uniforms, material );

		} else if ( material.isMeshNormalMaterial ) {

			refreshUniformsCommon( uniforms, material );
			refreshUniformsNormal( uniforms, material );

		} else if ( material.isLineBasicMaterial ) {

			refreshUniformsLine( uniforms, material );

			if ( material.isLineDashedMaterial ) {

				refreshUniformsDash( uniforms, material );

			}

		} else if ( material.isPointsMaterial ) {

			refreshUniformsPoints( uniforms, material, pixelRatio, height );

		} else if ( material.isSpriteMaterial ) {

			refreshUniformsSprites( uniforms, material );

		} else if ( material.isShadowMaterial ) {

			uniforms.color.value.copy( material.color );
			uniforms.opacity.value = material.opacity;

		} else if ( material.isShaderMaterial ) {

			material.uniformsNeedUpdate = false; // #15581

		}

	}

	function refreshUniformsCommon( uniforms, material, environment ) {

		uniforms.opacity.value = material.opacity;

		if ( material.color ) {

			uniforms.diffuse.value.copy( material.color );

		}

		if ( material.emissive ) {

			uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );

		}

		if ( material.map ) {

			uniforms.map.value = material.map;

		}

		if ( material.alphaMap ) {

			uniforms.alphaMap.value = material.alphaMap;

		}

		if ( material.specularMap ) {

			uniforms.specularMap.value = material.specularMap;

		}

		const envMap = material.envMap || environment;

		if ( envMap ) {

			uniforms.envMap.value = envMap;

			uniforms.flipEnvMap.value = envMap.isCubeTexture ? - 1 : 1;

			uniforms.reflectivity.value = material.reflectivity;
			uniforms.refractionRatio.value = material.refractionRatio;

			uniforms.maxMipLevel.value = properties.get( envMap ).__maxMipLevel;

		}

		if ( material.lightMap ) {

			uniforms.lightMap.value = material.lightMap;
			uniforms.lightMapIntensity.value = material.lightMapIntensity;

		}

		if ( material.aoMap ) {

			uniforms.aoMap.value = material.aoMap;
			uniforms.aoMapIntensity.value = material.aoMapIntensity;

		}

		// uv repeat and offset setting priorities
		// 1. color map
		// 2. specular map
		// 3. normal map
		// 4. bump map
		// 5. alpha map
		// 6. emissive map

		let uvScaleMap;

		if ( material.map ) {

			uvScaleMap = material.map;

		} else if ( material.specularMap ) {

			uvScaleMap = material.specularMap;

		} else if ( material.displacementMap ) {

			uvScaleMap = material.displacementMap;

		} else if ( material.normalMap ) {

			uvScaleMap = material.normalMap;

		} else if ( material.bumpMap ) {

			uvScaleMap = material.bumpMap;

		} else if ( material.roughnessMap ) {

			uvScaleMap = material.roughnessMap;

		} else if ( material.metalnessMap ) {

			uvScaleMap = material.metalnessMap;

		} else if ( material.alphaMap ) {

			uvScaleMap = material.alphaMap;

		} else if ( material.emissiveMap ) {

			uvScaleMap = material.emissiveMap;

		}

		if ( uvScaleMap !== undefined ) {

			// backwards compatibility
			if ( uvScaleMap.isWebGLRenderTarget ) {

				uvScaleMap = uvScaleMap.texture;

			}

			if ( uvScaleMap.matrixAutoUpdate === true ) {

				uvScaleMap.updateMatrix();

			}

			uniforms.uvTransform.value.copy( uvScaleMap.matrix );

		}

		// uv repeat and offset setting priorities for uv2
		// 1. ao map
		// 2. light map

		let uv2ScaleMap;

		if ( material.aoMap ) {

			uv2ScaleMap = material.aoMap;

		} else if ( material.lightMap ) {

			uv2ScaleMap = material.lightMap;

		}

		if ( uv2ScaleMap !== undefined ) {

			// backwards compatibility
			if ( uv2ScaleMap.isWebGLRenderTarget ) {

				uv2ScaleMap = uv2ScaleMap.texture;

			}

			if ( uv2ScaleMap.matrixAutoUpdate === true ) {

				uv2ScaleMap.updateMatrix();

			}

			uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );

		}

	}

	function refreshUniformsLine( uniforms, material ) {

		uniforms.diffuse.value.copy( material.color );
		uniforms.opacity.value = material.opacity;

	}

	function refreshUniformsDash( uniforms, material ) {

		uniforms.dashSize.value = material.dashSize;
		uniforms.totalSize.value = material.dashSize + material.gapSize;
		uniforms.scale.value = material.scale;

	}

	function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {

		uniforms.diffuse.value.copy( material.color );
		uniforms.opacity.value = material.opacity;
		uniforms.size.value = material.size * pixelRatio;
		uniforms.scale.value = height * 0.5;

		if ( material.map ) {

			uniforms.map.value = material.map;

		}

		if ( material.alphaMap ) {

			uniforms.alphaMap.value = material.alphaMap;

		}

		// uv repeat and offset setting priorities
		// 1. color map
		// 2. alpha map

		let uvScaleMap;

		if ( material.map ) {

			uvScaleMap = material.map;

		} else if ( material.alphaMap ) {

			uvScaleMap = material.alphaMap;

		}

		if ( uvScaleMap !== undefined ) {

			if ( uvScaleMap.matrixAutoUpdate === true ) {

				uvScaleMap.updateMatrix();

			}

			uniforms.uvTransform.value.copy( uvScaleMap.matrix );

		}

	}

	function refreshUniformsSprites( uniforms, material ) {

		uniforms.diffuse.value.copy( material.color );
		uniforms.opacity.value = material.opacity;
		uniforms.rotation.value = material.rotation;

		if ( material.map ) {

			uniforms.map.value = material.map;

		}

		if ( material.alphaMap ) {

			uniforms.alphaMap.value = material.alphaMap;

		}

		// uv repeat and offset setting priorities
		// 1. color map
		// 2. alpha map

		let uvScaleMap;

		if ( material.map ) {

			uvScaleMap = material.map;

		} else if ( material.alphaMap ) {

			uvScaleMap = material.alphaMap;

		}

		if ( uvScaleMap !== undefined ) {

			if ( uvScaleMap.matrixAutoUpdate === true ) {

				uvScaleMap.updateMatrix();

			}

			uniforms.uvTransform.value.copy( uvScaleMap.matrix );

		}

	}

	function refreshUniformsLambert( uniforms, material ) {

		if ( material.emissiveMap ) {

			uniforms.emissiveMap.value = material.emissiveMap;

		}

	}

	function refreshUniformsPhong( uniforms, material ) {

		uniforms.specular.value.copy( material.specular );
		uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )

		if ( material.emissiveMap ) {

			uniforms.emissiveMap.value = material.emissiveMap;

		}

		if ( material.bumpMap ) {

			uniforms.bumpMap.value = material.bumpMap;
			uniforms.bumpScale.value = material.bumpScale;
			if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;

		}

		if ( material.normalMap ) {

			uniforms.normalMap.value = material.normalMap;
			uniforms.normalScale.value.copy( material.normalScale );
			if ( material.side === BackSide ) uniforms.normalScale.value.negate();

		}

		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;

		}

	}

	function refreshUniformsToon( uniforms, material ) {

		if ( material.gradientMap ) {

			uniforms.gradientMap.value = material.gradientMap;

		}

		if ( material.emissiveMap ) {

			uniforms.emissiveMap.value = material.emissiveMap;

		}

		if ( material.bumpMap ) {

			uniforms.bumpMap.value = material.bumpMap;
			uniforms.bumpScale.value = material.bumpScale;
			if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;

		}

		if ( material.normalMap ) {

			uniforms.normalMap.value = material.normalMap;
			uniforms.normalScale.value.copy( material.normalScale );
			if ( material.side === BackSide ) uniforms.normalScale.value.negate();

		}

		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;

		}

	}

	function refreshUniformsStandard( uniforms, material, environment ) {

		uniforms.roughness.value = material.roughness;
		uniforms.metalness.value = material.metalness;

		if ( material.roughnessMap ) {

			uniforms.roughnessMap.value = material.roughnessMap;

		}

		if ( material.metalnessMap ) {

			uniforms.metalnessMap.value = material.metalnessMap;

		}

		if ( material.emissiveMap ) {

			uniforms.emissiveMap.value = material.emissiveMap;

		}

		if ( material.bumpMap ) {

			uniforms.bumpMap.value = material.bumpMap;
			uniforms.bumpScale.value = material.bumpScale;
			if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;

		}

		if ( material.normalMap ) {

			uniforms.normalMap.value = material.normalMap;
			uniforms.normalScale.value.copy( material.normalScale );
			if ( material.side === BackSide ) uniforms.normalScale.value.negate();

		}

		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;

		}

		if ( material.envMap || environment ) {

			//uniforms.envMap.value = material.envMap; // part of uniforms common
			uniforms.envMapIntensity.value = material.envMapIntensity;

		}

	}

	function refreshUniformsPhysical( uniforms, material, environment ) {

		refreshUniformsStandard( uniforms, material, environment );

		uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common

		uniforms.clearcoat.value = material.clearcoat;
		uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
		if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );

		if ( material.clearcoatMap ) {

			uniforms.clearcoatMap.value = material.clearcoatMap;

		}

		if ( material.clearcoatRoughnessMap ) {

			uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;

		}

		if ( material.clearcoatNormalMap ) {

			uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
			uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;

			if ( material.side === BackSide ) {

				uniforms.clearcoatNormalScale.value.negate();

			}

		}

		uniforms.transparency.value = material.transparency;

	}

	function refreshUniformsMatcap( uniforms, material ) {

		if ( material.matcap ) {

			uniforms.matcap.value = material.matcap;

		}

		if ( material.bumpMap ) {

			uniforms.bumpMap.value = material.bumpMap;
			uniforms.bumpScale.value = material.bumpScale;
			if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;

		}

		if ( material.normalMap ) {

			uniforms.normalMap.value = material.normalMap;
			uniforms.normalScale.value.copy( material.normalScale );
			if ( material.side === BackSide ) uniforms.normalScale.value.negate();

		}

		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;

		}

	}

	function refreshUniformsDepth( uniforms, material ) {

		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;

		}

	}

	function refreshUniformsDistance( uniforms, material ) {

		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;

		}

		uniforms.referencePosition.value.copy( material.referencePosition );
		uniforms.nearDistance.value = material.nearDistance;
		uniforms.farDistance.value = material.farDistance;

	}

	function refreshUniformsNormal( uniforms, material ) {

		if ( material.bumpMap ) {

			uniforms.bumpMap.value = material.bumpMap;
			uniforms.bumpScale.value = material.bumpScale;
			if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;

		}

		if ( material.normalMap ) {

			uniforms.normalMap.value = material.normalMap;
			uniforms.normalScale.value.copy( material.normalScale );
			if ( material.side === BackSide ) uniforms.normalScale.value.negate();

		}

		if ( material.displacementMap ) {

			uniforms.displacementMap.value = material.displacementMap;
			uniforms.displacementScale.value = material.displacementScale;
			uniforms.displacementBias.value = material.displacementBias;

		}

	}

	return {
		refreshFogUniforms: refreshFogUniforms,
		refreshMaterialUniforms: refreshMaterialUniforms
	};

}

/**
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author szimek / https://github.com/szimek/
 * @author tschw
 */

function WebGLRenderer( parameters ) {

	parameters = parameters || {};

	const _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
		_context = parameters.context !== undefined ? parameters.context : null,

		_alpha = parameters.alpha !== undefined ? parameters.alpha : false,
		_depth = parameters.depth !== undefined ? parameters.depth : true,
		_stencil = parameters.stencil !== undefined ? parameters.stencil : true,
		_antialias = parameters.antialias !== undefined ? parameters.antialias : false,
		_premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
		_preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
		_powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
		_failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;

	let currentRenderList = null;
	let currentRenderState = null;

	// public properties

	this.domElement = _canvas;

	// Debug configuration container
	this.debug = {

		/**
		 * Enables error checking and reporting when shader programs are being compiled
		 * @type {boolean}
		 */
		checkShaderErrors: true
	};

	// clearing

	this.autoClear = true;
	this.autoClearColor = true;
	this.autoClearDepth = true;
	this.autoClearStencil = true;

	// scene graph

	this.sortObjects = true;

	// user-defined clipping

	this.clippingPlanes = [];
	this.localClippingEnabled = false;

	// physically based shading

	this.gammaFactor = 2.0;	// for backwards compatibility
	this.outputEncoding = LinearEncoding;

	// physical lights

	this.physicallyCorrectLights = false;

	// tone mapping

	this.toneMapping = NoToneMapping;
	this.toneMappingExposure = 1.0;

	// morphs

	this.maxMorphTargets = 8;
	this.maxMorphNormals = 4;

	// internal properties

	const _this = this;

	let _isContextLost = false;

	// internal state cache

	let _framebuffer = null;

	let _currentActiveCubeFace = 0;
	let _currentActiveMipmapLevel = 0;
	let _currentRenderTarget = null;
	let _currentFramebuffer = null;
	let _currentMaterialId = - 1;

	let _currentCamera = null;
	let _currentArrayCamera = null;

	const _currentViewport = new Vector4();
	const _currentScissor = new Vector4();
	let _currentScissorTest = null;

	//

	let _width = _canvas.width;
	let _height = _canvas.height;

	let _pixelRatio = 1;
	let _opaqueSort = null;
	let _transparentSort = null;

	const _viewport = new Vector4( 0, 0, _width, _height );
	const _scissor = new Vector4( 0, 0, _width, _height );
	let _scissorTest = false;

	// frustum

	const _frustum = new Frustum();

	// clipping

	const _clipping = new WebGLClipping();
	let _clippingEnabled = false;
	let _localClippingEnabled = false;

	// camera matrices cache

	const _projScreenMatrix = new Matrix4();

	const _vector3 = new Vector3();

	const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };

	function getTargetPixelRatio() {

		return _currentRenderTarget === null ? _pixelRatio : 1;

	}

	// initialize

	let _gl = _context;

	function getContext( contextNames, contextAttributes ) {

		for ( let i = 0; i < contextNames.length; i ++ ) {

			const contextName = contextNames[ i ];
			const context = _canvas.getContext( contextName, contextAttributes );
			if ( context !== null ) return context;

		}

		return null;

	}

	try {

		const contextAttributes = {
			alpha: _alpha,
			depth: _depth,
			stencil: _stencil,
			antialias: _antialias,
			premultipliedAlpha: _premultipliedAlpha,
			preserveDrawingBuffer: _preserveDrawingBuffer,
			powerPreference: _powerPreference,
			failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
		};

		// event listeners must be registered before WebGL context is created, see #12753

		_canvas.addEventListener( 'webglcontextlost', onContextLost, false );
		_canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );

		if ( _gl === null ) {

			const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];

			if ( _this.isWebGL1Renderer === true ) {

				contextNames.shift();

			}

			_gl = getContext( contextNames, contextAttributes );

			if ( _gl === null ) {

				if ( getContext( contextNames ) ) {

					throw new Error( 'Error creating WebGL context with your selected attributes.' );

				} else {

					throw new Error( 'Error creating WebGL context.' );

				}

			}

		}

		// Some experimental-webgl implementations do not have getShaderPrecisionFormat

		if ( _gl.getShaderPrecisionFormat === undefined ) {

			_gl.getShaderPrecisionFormat = function () {

				return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };

			};

		}

	} catch ( error ) {

		console.error( 'THREE.WebGLRenderer: ' + error.message );
		throw error;

	}

	let extensions, capabilities, state, info;
	let properties, textures, attributes, geometries, objects;
	let programCache, materials, renderLists, renderStates;

	let background, morphtargets, bufferRenderer, indexedBufferRenderer;

	let utils, bindingStates;

	function initGLContext() {

		extensions = new WebGLExtensions( _gl );

		capabilities = new WebGLCapabilities( _gl, extensions, parameters );

		if ( capabilities.isWebGL2 === false ) {

			extensions.get( 'WEBGL_depth_texture' );
			extensions.get( 'OES_texture_float' );
			extensions.get( 'OES_texture_half_float' );
			extensions.get( 'OES_texture_half_float_linear' );
			extensions.get( 'OES_standard_derivatives' );
			extensions.get( 'OES_element_index_uint' );
			extensions.get( 'OES_vertex_array_object' );
			extensions.get( 'ANGLE_instanced_arrays' );

		}

		extensions.get( 'OES_texture_float_linear' );

		utils = new WebGLUtils( _gl, extensions, capabilities );

		state = new WebGLState( _gl, extensions, capabilities );
		state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
		state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );

		info = new WebGLInfo( _gl );
		properties = new WebGLProperties();
		textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
		attributes = new WebGLAttributes( _gl, capabilities );
		bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
		geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
		objects = new WebGLObjects( _gl, geometries, attributes, info );
		morphtargets = new WebGLMorphtargets( _gl );
		programCache = new WebGLPrograms( _this, extensions, capabilities, bindingStates );
		materials = new WebGLMaterials( properties );
		renderLists = new WebGLRenderLists();
		renderStates = new WebGLRenderStates();

		background = new WebGLBackground( _this, state, objects, _premultipliedAlpha );

		bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
		indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );

		info.programs = programCache.programs;

		_this.capabilities = capabilities;
		_this.extensions = extensions;
		_this.properties = properties;
		_this.renderLists = renderLists;
		_this.state = state;
		_this.info = info;

	}

	initGLContext();

	// xr

	const xr = new WebXRManager( _this, _gl );

	this.xr = xr;

	// shadow map

	const shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );

	this.shadowMap = shadowMap;

	// API

	this.getContext = function () {

		return _gl;

	};

	this.getContextAttributes = function () {

		return _gl.getContextAttributes();

	};

	this.forceContextLoss = function () {

		const extension = extensions.get( 'WEBGL_lose_context' );
		if ( extension ) extension.loseContext();

	};

	this.forceContextRestore = function () {

		const extension = extensions.get( 'WEBGL_lose_context' );
		if ( extension ) extension.restoreContext();

	};

	this.getPixelRatio = function () {

		return _pixelRatio;

	};

	this.setPixelRatio = function ( value ) {

		if ( value === undefined ) return;

		_pixelRatio = value;

		this.setSize( _width, _height, false );

	};

	this.getSize = function ( target ) {

		if ( target === undefined ) {

			console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );

			target = new Vector2();

		}

		return target.set( _width, _height );

	};

	this.setSize = function ( width, height, updateStyle ) {

		if ( xr.isPresenting ) {

			console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
			return;

		}

		_width = width;
		_height = height;

		_canvas.width = Math.floor( width * _pixelRatio );
		_canvas.height = Math.floor( height * _pixelRatio );

		if ( updateStyle !== false ) {

			_canvas.style.width = width + 'px';
			_canvas.style.height = height + 'px';

		}

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

	};

	this.getDrawingBufferSize = function ( target ) {

		if ( target === undefined ) {

			console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );

			target = new Vector2();

		}

		return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();

	};

	this.setDrawingBufferSize = function ( width, height, pixelRatio ) {

		_width = width;
		_height = height;

		_pixelRatio = pixelRatio;

		_canvas.width = Math.floor( width * pixelRatio );
		_canvas.height = Math.floor( height * pixelRatio );

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

	};

	this.getCurrentViewport = function ( target ) {

		if ( target === undefined ) {

			console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );

			target = new Vector4();

		}

		return target.copy( _currentViewport );

	};

	this.getViewport = function ( target ) {

		return target.copy( _viewport );

	};

	this.setViewport = function ( x, y, width, height ) {

		if ( x.isVector4 ) {

			_viewport.set( x.x, x.y, x.z, x.w );

		} else {

			_viewport.set( x, y, width, height );

		}

		state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );

	};

	this.getScissor = function ( target ) {

		return target.copy( _scissor );

	};

	this.setScissor = function ( x, y, width, height ) {

		if ( x.isVector4 ) {

			_scissor.set( x.x, x.y, x.z, x.w );

		} else {

			_scissor.set( x, y, width, height );

		}

		state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );

	};

	this.getScissorTest = function () {

		return _scissorTest;

	};

	this.setScissorTest = function ( boolean ) {

		state.setScissorTest( _scissorTest = boolean );

	};

	this.setOpaqueSort = function ( method ) {

		_opaqueSort = method;

	};

	this.setTransparentSort = function ( method ) {

		_transparentSort = method;

	};

	// Clearing

	this.getClearColor = function () {

		return background.getClearColor();

	};

	this.setClearColor = function () {

		background.setClearColor.apply( background, arguments );

	};

	this.getClearAlpha = function () {

		return background.getClearAlpha();

	};

	this.setClearAlpha = function () {

		background.setClearAlpha.apply( background, arguments );

	};

	this.clear = function ( color, depth, stencil ) {

		let bits = 0;

		if ( color === undefined || color ) bits |= 16384;
		if ( depth === undefined || depth ) bits |= 256;
		if ( stencil === undefined || stencil ) bits |= 1024;

		_gl.clear( bits );

	};

	this.clearColor = function () {

		this.clear( true, false, false );

	};

	this.clearDepth = function () {

		this.clear( false, true, false );

	};

	this.clearStencil = function () {

		this.clear( false, false, true );

	};

	//

	this.dispose = function () {

		_canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
		_canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );

		renderLists.dispose();
		renderStates.dispose();
		properties.dispose();
		objects.dispose();
		bindingStates.dispose();

		xr.dispose();

		animation.stop();

	};

	// Events

	function onContextLost( event ) {

		event.preventDefault();

		console.log( 'THREE.WebGLRenderer: Context Lost.' );

		_isContextLost = true;

	}

	function onContextRestore( /* event */ ) {

		console.log( 'THREE.WebGLRenderer: Context Restored.' );

		_isContextLost = false;

		initGLContext();

	}

	function onMaterialDispose( event ) {

		const material = event.target;

		material.removeEventListener( 'dispose', onMaterialDispose );

		deallocateMaterial( material );

	}

	// Buffer deallocation

	function deallocateMaterial( material ) {

		releaseMaterialProgramReference( material );

		properties.remove( material );

	}


	function releaseMaterialProgramReference( material ) {

		const programInfo = properties.get( material ).program;

		material.program = undefined;

		if ( programInfo !== undefined ) {

			programCache.releaseProgram( programInfo );

		}

	}

	// Buffer rendering

	function renderObjectImmediate( object, program ) {

		object.render( function ( object ) {

			_this.renderBufferImmediate( object, program );

		} );

	}

	this.renderBufferImmediate = function ( object, program ) {

		bindingStates.initAttributes();

		const buffers = properties.get( object );

		if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
		if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
		if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
		if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();

		const programAttributes = program.getAttributes();

		if ( object.hasPositions ) {

			_gl.bindBuffer( 34962, buffers.position );
			_gl.bufferData( 34962, object.positionArray, 35048 );

			bindingStates.enableAttribute( programAttributes.position );
			_gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );

		}

		if ( object.hasNormals ) {

			_gl.bindBuffer( 34962, buffers.normal );
			_gl.bufferData( 34962, object.normalArray, 35048 );

			bindingStates.enableAttribute( programAttributes.normal );
			_gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );

		}

		if ( object.hasUvs ) {

			_gl.bindBuffer( 34962, buffers.uv );
			_gl.bufferData( 34962, object.uvArray, 35048 );

			bindingStates.enableAttribute( programAttributes.uv );
			_gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );

		}

		if ( object.hasColors ) {

			_gl.bindBuffer( 34962, buffers.color );
			_gl.bufferData( 34962, object.colorArray, 35048 );

			bindingStates.enableAttribute( programAttributes.color );
			_gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );

		}

		bindingStates.disableUnusedAttributes();

		_gl.drawArrays( 4, 0, object.count );

		object.count = 0;

	};

	this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {

		if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)

		const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );

		const program = setProgram( camera, scene, material, object );

		state.setMaterial( material, frontFaceCW );

		//

		let index = geometry.index;
		const position = geometry.attributes.position;

		//

		if ( index === null ) {

			if ( position === undefined || position.count === 0 ) return;

		} else if ( index.count === 0 ) {

			return;

		}

		//

		let rangeFactor = 1;

		if ( material.wireframe === true ) {

			index = geometries.getWireframeAttribute( geometry );
			rangeFactor = 2;

		}

		if ( material.morphTargets || material.morphNormals ) {

			morphtargets.update( object, geometry, material, program );

		}

		bindingStates.setup( object, material, program, geometry, index );

		let attribute;
		let renderer = bufferRenderer;

		if ( index !== null ) {

			attribute = attributes.get( index );

			renderer = indexedBufferRenderer;
			renderer.setIndex( attribute );

		}

		//

		const dataCount = ( index !== null ) ? index.count : position.count;

		const rangeStart = geometry.drawRange.start * rangeFactor;
		const rangeCount = geometry.drawRange.count * rangeFactor;

		const groupStart = group !== null ? group.start * rangeFactor : 0;
		const groupCount = group !== null ? group.count * rangeFactor : Infinity;

		const drawStart = Math.max( rangeStart, groupStart );
		const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;

		const drawCount = Math.max( 0, drawEnd - drawStart + 1 );

		if ( drawCount === 0 ) return;

		//

		if ( object.isMesh ) {

			if ( material.wireframe === true ) {

				state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
				renderer.setMode( 1 );

			} else {

				renderer.setMode( 4 );

			}

		} else if ( object.isLine ) {

			let lineWidth = material.linewidth;

			if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material

			state.setLineWidth( lineWidth * getTargetPixelRatio() );

			if ( object.isLineSegments ) {

				renderer.setMode( 1 );

			} else if ( object.isLineLoop ) {

				renderer.setMode( 2 );

			} else {

				renderer.setMode( 3 );

			}

		} else if ( object.isPoints ) {

			renderer.setMode( 0 );

		} else if ( object.isSprite ) {

			renderer.setMode( 4 );

		}

		if ( object.isInstancedMesh ) {

			renderer.renderInstances( geometry, drawStart, drawCount, object.count );

		} else if ( geometry.isInstancedBufferGeometry ) {

			const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );

			renderer.renderInstances( geometry, drawStart, drawCount, instanceCount );

		} else {

			renderer.render( drawStart, drawCount );

		}

	};

	// Compile

	this.compile = function ( scene, camera ) {

		currentRenderState = renderStates.get( scene, camera );
		currentRenderState.init();

		scene.traverse( function ( object ) {

			if ( object.isLight ) {

				currentRenderState.pushLight( object );

				if ( object.castShadow ) {

					currentRenderState.pushShadow( object );

				}

			}

		} );

		currentRenderState.setupLights( camera );

		const compiled = new WeakMap();

		scene.traverse( function ( object ) {

			let material = object.material;

			if ( material ) {

				if ( Array.isArray( material ) ) {

					for ( let i = 0; i < material.length; i ++ ) {

						let material2 = material[ i ];

						if ( compiled.has( material2 ) === false ) {

							initMaterial( material2, scene, object );
							compiled.set( material2 );

						}

					}

				} else if ( compiled.has( material ) === false ) {

					initMaterial( material, scene, object );
					compiled.set( material );

				}

			}

		} );

	};

	// Animation Loop

	let onAnimationFrameCallback = null;

	function onAnimationFrame( time ) {

		if ( xr.isPresenting ) return;
		if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );

	}

	const animation = new WebGLAnimation();
	animation.setAnimationLoop( onAnimationFrame );

	if ( typeof window !== 'undefined' ) animation.setContext( window );

	this.setAnimationLoop = function ( callback ) {

		onAnimationFrameCallback = callback;
		xr.setAnimationLoop( callback );

		( callback === null ) ? animation.stop() : animation.start();

	};

	// Rendering

	this.render = function ( scene, camera ) {

		let renderTarget, forceClear;

		if ( arguments[ 2 ] !== undefined ) {

			console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
			renderTarget = arguments[ 2 ];

		}

		if ( arguments[ 3 ] !== undefined ) {

			console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
			forceClear = arguments[ 3 ];

		}

		if ( camera !== undefined && camera.isCamera !== true ) {

			console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
			return;

		}

		if ( _isContextLost === true ) return;

		// reset caching for this frame

		bindingStates.resetDefaultState();
		_currentMaterialId = - 1;
		_currentCamera = null;

		// update scene graph

		if ( scene.autoUpdate === true ) scene.updateMatrixWorld();

		// update camera matrices and frustum

		if ( camera.parent === null ) camera.updateMatrixWorld();

		if ( xr.enabled === true && xr.isPresenting === true ) {

			camera = xr.getCamera( camera );

		}

		//
		if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );

		currentRenderState = renderStates.get( scene, camera );
		currentRenderState.init();

		_projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
		_frustum.setFromProjectionMatrix( _projScreenMatrix );

		_localClippingEnabled = this.localClippingEnabled;
		_clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );

		currentRenderList = renderLists.get( scene, camera );
		currentRenderList.init();

		projectObject( scene, camera, 0, _this.sortObjects );

		currentRenderList.finish();

		if ( _this.sortObjects === true ) {

			currentRenderList.sort( _opaqueSort, _transparentSort );

		}

		//

		if ( _clippingEnabled === true ) _clipping.beginShadows();

		const shadowsArray = currentRenderState.state.shadowsArray;

		shadowMap.render( shadowsArray, scene, camera );

		currentRenderState.setupLights( camera );

		if ( _clippingEnabled === true ) _clipping.endShadows();

		//

		if ( this.info.autoReset === true ) this.info.reset();

		if ( renderTarget !== undefined ) {

			this.setRenderTarget( renderTarget );

		}

		//

		background.render( currentRenderList, scene, camera, forceClear );

		// render scene

		const opaqueObjects = currentRenderList.opaque;
		const transparentObjects = currentRenderList.transparent;

		if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
		if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );

		//

		if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );

		//

		if ( _currentRenderTarget !== null ) {

			// Generate mipmap if we're using any kind of mipmap filtering

			textures.updateRenderTargetMipmap( _currentRenderTarget );

			// resolve multisample renderbuffers to a single-sample texture if necessary

			textures.updateMultisampleRenderTarget( _currentRenderTarget );

		}

		// Ensure depth buffer writing is enabled so it can be cleared on next render

		state.buffers.depth.setTest( true );
		state.buffers.depth.setMask( true );
		state.buffers.color.setMask( true );

		state.setPolygonOffset( false );

		// _gl.finish();

		currentRenderList = null;
		currentRenderState = null;

	};

	function projectObject( object, camera, groupOrder, sortObjects ) {

		if ( object.visible === false ) return;

		const visible = object.layers.test( camera.layers );

		if ( visible ) {

			if ( object.isGroup ) {

				groupOrder = object.renderOrder;

			} else if ( object.isLOD ) {

				if ( object.autoUpdate === true ) object.update( camera );

			} else if ( object.isLight ) {

				currentRenderState.pushLight( object );

				if ( object.castShadow ) {

					currentRenderState.pushShadow( object );

				}

			} else if ( object.isSprite ) {

				if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {

					if ( sortObjects ) {

						_vector3.setFromMatrixPosition( object.matrixWorld )
							.applyMatrix4( _projScreenMatrix );

					}

					const geometry = objects.update( object );
					const material = object.material;

					if ( material.visible ) {

						currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );

					}

				}

			} else if ( object.isImmediateRenderObject ) {

				if ( sortObjects ) {

					_vector3.setFromMatrixPosition( object.matrixWorld )
						.applyMatrix4( _projScreenMatrix );

				}

				currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );

			} else if ( object.isMesh || object.isLine || object.isPoints ) {

				if ( object.isSkinnedMesh ) {

					// update skeleton only once in a frame

					if ( object.skeleton.frame !== info.render.frame ) {

						object.skeleton.update();
						object.skeleton.frame = info.render.frame;

					}

				}

				if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {

					if ( sortObjects ) {

						_vector3.setFromMatrixPosition( object.matrixWorld )
							.applyMatrix4( _projScreenMatrix );

					}

					const geometry = objects.update( object );
					const material = object.material;

					if ( Array.isArray( material ) ) {

						const groups = geometry.groups;

						for ( let i = 0, l = groups.length; i < l; i ++ ) {

							const group = groups[ i ];
							const groupMaterial = material[ group.materialIndex ];

							if ( groupMaterial && groupMaterial.visible ) {

								currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );

							}

						}

					} else if ( material.visible ) {

						currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );

					}

				}

			}

		}

		const children = object.children;

		for ( let i = 0, l = children.length; i < l; i ++ ) {

			projectObject( children[ i ], camera, groupOrder, sortObjects );

		}

	}

	function renderObjects( renderList, scene, camera ) {

		const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;

		for ( let i = 0, l = renderList.length; i < l; i ++ ) {

			const renderItem = renderList[ i ];

			const object = renderItem.object;
			const geometry = renderItem.geometry;
			const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
			const group = renderItem.group;

			if ( camera.isArrayCamera ) {

				_currentArrayCamera = camera;

				const cameras = camera.cameras;

				for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {

					const camera2 = cameras[ j ];

					if ( object.layers.test( camera2.layers ) ) {

						state.viewport( _currentViewport.copy( camera2.viewport ) );

						currentRenderState.setupLights( camera2 );

						renderObject( object, scene, camera2, geometry, material, group );

					}

				}

			} else {

				_currentArrayCamera = null;

				renderObject( object, scene, camera, geometry, material, group );

			}

		}

	}

	function renderObject( object, scene, camera, geometry, material, group ) {

		object.onBeforeRender( _this, scene, camera, geometry, material, group );
		currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );

		object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
		object.normalMatrix.getNormalMatrix( object.modelViewMatrix );

		if ( object.isImmediateRenderObject ) {

			const program = setProgram( camera, scene, material, object );

			state.setMaterial( material );

			bindingStates.reset();

			renderObjectImmediate( object, program );

		} else {

			_this.renderBufferDirect( camera, scene, geometry, material, object, group );

		}

		object.onAfterRender( _this, scene, camera, geometry, material, group );
		currentRenderState = renderStates.get( scene, _currentArrayCamera || camera );

	}

	function initMaterial( material, scene, object ) {

		if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...

		const materialProperties = properties.get( material );

		const lights = currentRenderState.state.lights;
		const shadowsArray = currentRenderState.state.shadowsArray;

		const lightsStateVersion = lights.state.version;

		const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, _clipping.numPlanes, _clipping.numIntersection, object );
		const programCacheKey = programCache.getProgramCacheKey( parameters );

		let program = materialProperties.program;
		let programChange = true;

		if ( program === undefined ) {

			// new material
			material.addEventListener( 'dispose', onMaterialDispose );

		} else if ( program.cacheKey !== programCacheKey ) {

			// changed glsl or parameters
			releaseMaterialProgramReference( material );

		} else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {

			materialProperties.lightsStateVersion = lightsStateVersion;

			programChange = false;

		} else if ( parameters.shaderID !== undefined ) {

			// same glsl and uniform list
			return;

		} else {

			// only rebuild uniform list
			programChange = false;

		}

		if ( programChange ) {

			program = programCache.acquireProgram( parameters, programCacheKey );

			materialProperties.program = program;
			materialProperties.uniforms = parameters.uniforms;
			materialProperties.outputEncoding = parameters.outputEncoding;
			material.program = program;

		}

		const programAttributes = program.getAttributes();

		if ( material.morphTargets ) {

			material.numSupportedMorphTargets = 0;

			for ( let i = 0; i < _this.maxMorphTargets; i ++ ) {

				if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {

					material.numSupportedMorphTargets ++;

				}

			}

		}

		if ( material.morphNormals ) {

			material.numSupportedMorphNormals = 0;

			for ( let i = 0; i < _this.maxMorphNormals; i ++ ) {

				if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {

					material.numSupportedMorphNormals ++;

				}

			}

		}

		const uniforms = materialProperties.uniforms;

		if ( ! material.isShaderMaterial &&
			! material.isRawShaderMaterial ||
			material.clipping === true ) {

			materialProperties.numClippingPlanes = _clipping.numPlanes;
			materialProperties.numIntersection = _clipping.numIntersection;
			uniforms.clippingPlanes = _clipping.uniform;

		}

		materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
		materialProperties.fog = scene.fog;

		// store the light setup it was created for

		materialProperties.needsLights = materialNeedsLights( material );
		materialProperties.lightsStateVersion = lightsStateVersion;

		if ( materialProperties.needsLights ) {

			// wire up the material to this renderer's lighting state

			uniforms.ambientLightColor.value = lights.state.ambient;
			uniforms.lightProbe.value = lights.state.probe;
			uniforms.directionalLights.value = lights.state.directional;
			uniforms.directionalLightShadows.value = lights.state.directionalShadow;
			uniforms.spotLights.value = lights.state.spot;
			uniforms.spotLightShadows.value = lights.state.spotShadow;
			uniforms.rectAreaLights.value = lights.state.rectArea;
			uniforms.pointLights.value = lights.state.point;
			uniforms.pointLightShadows.value = lights.state.pointShadow;
			uniforms.hemisphereLights.value = lights.state.hemi;

			uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
			uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
			uniforms.spotShadowMap.value = lights.state.spotShadowMap;
			uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
			uniforms.pointShadowMap.value = lights.state.pointShadowMap;
			uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
			// TODO (abelnation): add area lights shadow info to uniforms

		}

		const progUniforms = materialProperties.program.getUniforms(),
			uniformsList =
				WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );

		materialProperties.uniformsList = uniformsList;

	}

	function setProgram( camera, scene, material, object ) {

		if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...

		textures.resetTextureUnits();

		const fog = scene.fog;
		const environment = material.isMeshStandardMaterial ? scene.environment : null;
		const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;

		const materialProperties = properties.get( material );
		const lights = currentRenderState.state.lights;

		if ( _clippingEnabled === true ) {

			if ( _localClippingEnabled === true || camera !== _currentCamera ) {

				const useCache =
					camera === _currentCamera &&
					material.id === _currentMaterialId;

				// we might want to call this function with some ClippingGroup
				// object instead of the material, once it becomes feasible
				// (#8465, #8379)
				_clipping.setState(
					material.clippingPlanes, material.clipIntersection, material.clipShadows,
					camera, materialProperties, useCache );

			}

		}

		if ( material.version === materialProperties.__version ) {

			if ( materialProperties.program === undefined ) {

				initMaterial( material, scene, object );

			} else if ( material.fog && materialProperties.fog !== fog ) {

				initMaterial( material, scene, object );

			} else if ( materialProperties.environment !== environment ) {

				initMaterial( material, scene, object );

			} else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {

				initMaterial( material, scene, object );

			} else if ( materialProperties.numClippingPlanes !== undefined &&
				( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
				materialProperties.numIntersection !== _clipping.numIntersection ) ) {

				initMaterial( material, scene, object );

			} else if ( materialProperties.outputEncoding !== encoding ) {

				initMaterial( material, scene, object );

			}

		} else {

			initMaterial( material, scene, object );
			materialProperties.__version = material.version;

		}

		let refreshProgram = false;
		let refreshMaterial = false;
		let refreshLights = false;

		const program = materialProperties.program,
			p_uniforms = program.getUniforms(),
			m_uniforms = materialProperties.uniforms;

		if ( state.useProgram( program.program ) ) {

			refreshProgram = true;
			refreshMaterial = true;
			refreshLights = true;

		}

		if ( material.id !== _currentMaterialId ) {

			_currentMaterialId = material.id;

			refreshMaterial = true;

		}

		if ( refreshProgram || _currentCamera !== camera ) {

			p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );

			if ( capabilities.logarithmicDepthBuffer ) {

				p_uniforms.setValue( _gl, 'logDepthBufFC',
					2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );

			}

			if ( _currentCamera !== camera ) {

				_currentCamera = camera;

				// lighting uniforms depend on the camera so enforce an update
				// now, in case this material supports lights - or later, when
				// the next material that does gets activated:

				refreshMaterial = true;		// set to true on material change
				refreshLights = true;		// remains set until update done

			}

			// load material specific uniforms
			// (shader material also gets them for the sake of genericity)

			if ( material.isShaderMaterial ||
				material.isMeshPhongMaterial ||
				material.isMeshToonMaterial ||
				material.isMeshStandardMaterial ||
				material.envMap ) {

				const uCamPos = p_uniforms.map.cameraPosition;

				if ( uCamPos !== undefined ) {

					uCamPos.setValue( _gl,
						_vector3.setFromMatrixPosition( camera.matrixWorld ) );

				}

			}

			if ( material.isMeshPhongMaterial ||
				material.isMeshToonMaterial ||
				material.isMeshLambertMaterial ||
				material.isMeshBasicMaterial ||
				material.isMeshStandardMaterial ||
				material.isShaderMaterial ) {

				p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );

			}

			if ( material.isMeshPhongMaterial ||
				material.isMeshToonMaterial ||
				material.isMeshLambertMaterial ||
				material.isMeshBasicMaterial ||
				material.isMeshStandardMaterial ||
				material.isShaderMaterial ||
				material.isShadowMaterial ||
				material.skinning ) {

				p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );

			}

		}

		// skinning uniforms must be set even if material didn't change
		// auto-setting of texture unit for bone texture must go before other textures
		// otherwise textures used for skinning can take over texture units reserved for other material textures

		if ( material.skinning ) {

			p_uniforms.setOptional( _gl, object, 'bindMatrix' );
			p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );

			const skeleton = object.skeleton;

			if ( skeleton ) {

				const bones = skeleton.bones;

				if ( capabilities.floatVertexTextures ) {

					if ( skeleton.boneTexture === undefined ) {

						// layout (1 matrix = 4 pixels)
						//      RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
						//  with  8x8  pixel texture max   16 bones * 4 pixels =  (8 * 8)
						//       16x16 pixel texture max   64 bones * 4 pixels = (16 * 16)
						//       32x32 pixel texture max  256 bones * 4 pixels = (32 * 32)
						//       64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)


						let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
						size = MathUtils.ceilPowerOfTwo( size );
						size = Math.max( size, 4 );

						const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
						boneMatrices.set( skeleton.boneMatrices ); // copy current values

						const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );

						skeleton.boneMatrices = boneMatrices;
						skeleton.boneTexture = boneTexture;
						skeleton.boneTextureSize = size;

					}

					p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
					p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );

				} else {

					p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );

				}

			}

		}

		if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {

			materialProperties.receiveShadow = object.receiveShadow;
			p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );

		}

		if ( refreshMaterial ) {

			p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );

			if ( materialProperties.needsLights ) {

				// the current material requires lighting info

				// note: all lighting uniforms are always set correctly
				// they simply reference the renderer's state for their
				// values
				//
				// use the current material's .needsUpdate flags to set
				// the GL state when required

				markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );

			}

			// refresh uniforms common to several materials

			if ( fog && material.fog ) {

				materials.refreshFogUniforms( m_uniforms, fog );

			}

			materials.refreshMaterialUniforms( m_uniforms, material, environment, _pixelRatio, _height );

			// RectAreaLight Texture
			// TODO (mrdoob): Find a nicer implementation

			if ( m_uniforms.ltc_1 !== undefined ) m_uniforms.ltc_1.value = UniformsLib.LTC_1;
			if ( m_uniforms.ltc_2 !== undefined ) m_uniforms.ltc_2.value = UniformsLib.LTC_2;

			WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );

		}

		if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {

			WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
			material.uniformsNeedUpdate = false;

		}

		if ( material.isSpriteMaterial ) {

			p_uniforms.setValue( _gl, 'center', object.center );

		}

		// common matrices

		p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
		p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
		p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );

		return program;

	}

	// If uniforms are marked as clean, they don't need to be loaded to the GPU.

	function markUniformsLightsNeedsUpdate( uniforms, value ) {

		uniforms.ambientLightColor.needsUpdate = value;
		uniforms.lightProbe.needsUpdate = value;

		uniforms.directionalLights.needsUpdate = value;
		uniforms.directionalLightShadows.needsUpdate = value;
		uniforms.pointLights.needsUpdate = value;
		uniforms.pointLightShadows.needsUpdate = value;
		uniforms.spotLights.needsUpdate = value;
		uniforms.spotLightShadows.needsUpdate = value;
		uniforms.rectAreaLights.needsUpdate = value;
		uniforms.hemisphereLights.needsUpdate = value;

	}

	function materialNeedsLights( material ) {

		return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
			material.isMeshStandardMaterial || material.isShadowMaterial ||
			( material.isShaderMaterial && material.lights === true );

	}

	//
	this.setFramebuffer = function ( value ) {

		if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value );

		_framebuffer = value;

	};

	this.getActiveCubeFace = function () {

		return _currentActiveCubeFace;

	};

	this.getActiveMipmapLevel = function () {

		return _currentActiveMipmapLevel;

	};

	this.getRenderTarget = function () {

		return _currentRenderTarget;

	};

	this.setRenderTarget = function ( renderTarget, activeCubeFace, activeMipmapLevel ) {

		_currentRenderTarget = renderTarget;
		_currentActiveCubeFace = activeCubeFace;
		_currentActiveMipmapLevel = activeMipmapLevel;

		if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {

			textures.setupRenderTarget( renderTarget );

		}

		let framebuffer = _framebuffer;
		let isCube = false;

		if ( renderTarget ) {

			const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;

			if ( renderTarget.isWebGLCubeRenderTarget ) {

				framebuffer = __webglFramebuffer[ activeCubeFace || 0 ];
				isCube = true;

			} else if ( renderTarget.isWebGLMultisampleRenderTarget ) {

				framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;

			} else {

				framebuffer = __webglFramebuffer;

			}

			_currentViewport.copy( renderTarget.viewport );
			_currentScissor.copy( renderTarget.scissor );
			_currentScissorTest = renderTarget.scissorTest;

		} else {

			_currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
			_currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
			_currentScissorTest = _scissorTest;

		}

		if ( _currentFramebuffer !== framebuffer ) {

			_gl.bindFramebuffer( 36160, framebuffer );
			_currentFramebuffer = framebuffer;

		}

		state.viewport( _currentViewport );
		state.scissor( _currentScissor );
		state.setScissorTest( _currentScissorTest );

		if ( isCube ) {

			const textureProperties = properties.get( renderTarget.texture );
			_gl.framebufferTexture2D( 36160, 36064, 34069 + ( activeCubeFace || 0 ), textureProperties.__webglTexture, activeMipmapLevel || 0 );

		}

	};

	this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {

		if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {

			console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
			return;

		}

		let framebuffer = properties.get( renderTarget ).__webglFramebuffer;

		if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {

			framebuffer = framebuffer[ activeCubeFaceIndex ];

		}

		if ( framebuffer ) {

			let restore = false;

			if ( framebuffer !== _currentFramebuffer ) {

				_gl.bindFramebuffer( 36160, framebuffer );

				restore = true;

			}

			try {

				const texture = renderTarget.texture;
				const textureFormat = texture.format;
				const textureType = texture.type;

				if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {

					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
					return;

				}

				if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
					! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
					! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {

					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
					return;

				}

				if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {

					// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)

					if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {

						_gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );

					}

				} else {

					console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );

				}

			} finally {

				if ( restore ) {

					_gl.bindFramebuffer( 36160, _currentFramebuffer );

				}

			}

		}

	};

	this.copyFramebufferToTexture = function ( position, texture, level ) {

		if ( level === undefined ) level = 0;

		const levelScale = Math.pow( 2, - level );
		const width = Math.floor( texture.image.width * levelScale );
		const height = Math.floor( texture.image.height * levelScale );
		const glFormat = utils.convert( texture.format );

		textures.setTexture2D( texture, 0 );

		_gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );

		state.unbindTexture();

	};

	this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level ) {

		if ( level === undefined ) level = 0;

		const width = srcTexture.image.width;
		const height = srcTexture.image.height;
		const glFormat = utils.convert( dstTexture.format );
		const glType = utils.convert( dstTexture.type );

		textures.setTexture2D( dstTexture, 0 );

		// As another texture upload may have changed pixelStorei
		// parameters, make sure they are correct for the dstTexture
		_gl.pixelStorei( 37440, dstTexture.flipY );
		_gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
		_gl.pixelStorei( 3317, dstTexture.unpackAlignment );

		if ( srcTexture.isDataTexture ) {

			_gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );

		} else {

			if ( srcTexture.isCompressedTexture ) {

				_gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );

			} else {

				_gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );

			}

		}

		// Generate mipmaps only when copying level 0
		if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );

		state.unbindTexture();

	};

	this.initTexture = function ( texture ) {

		textures.setTexture2D( texture, 0 );

		state.unbindTexture();

	};

	if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {

		__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef

	}

}

/**
 * @author Mugen87 / https://github.com/Mugen87
 */

function WebGL1Renderer( parameters ) {

	WebGLRenderer.call( this, parameters );

}

WebGL1Renderer.prototype = Object.assign( Object.create( WebGLRenderer.prototype ), {

	constructor: WebGL1Renderer,

	isWebGL1Renderer: true

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

function FogExp2( color, density ) {

	this.name = '';

	this.color = new Color( color );
	this.density = ( density !== undefined ) ? density : 0.00025;

}

Object.assign( FogExp2.prototype, {

	isFogExp2: true,

	clone: function () {

		return new FogExp2( this.color, this.density );

	},

	toJSON: function ( /* meta */ ) {

		return {
			type: 'FogExp2',
			color: this.color.getHex(),
			density: this.density
		};

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

function Fog( color, near, far ) {

	this.name = '';

	this.color = new Color( color );

	this.near = ( near !== undefined ) ? near : 1;
	this.far = ( far !== undefined ) ? far : 1000;

}

Object.assign( Fog.prototype, {

	isFog: true,

	clone: function () {

		return new Fog( this.color, this.near, this.far );

	},

	toJSON: function ( /* meta */ ) {

		return {
			type: 'Fog',
			color: this.color.getHex(),
			near: this.near,
			far: this.far
		};

	}

} );

/**
 * @author benaadams / https://twitter.com/ben_a_adams
 */

function InterleavedBuffer( array, stride ) {

	this.array = array;
	this.stride = stride;
	this.count = array !== undefined ? array.length / stride : 0;

	this.usage = StaticDrawUsage;
	this.updateRange = { offset: 0, count: - 1 };

	this.version = 0;

	this.uuid = MathUtils.generateUUID();

}

Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {

	set: function ( value ) {

		if ( value === true ) this.version ++;

	}

} );

Object.assign( InterleavedBuffer.prototype, {

	isInterleavedBuffer: true,

	onUploadCallback: function () {},

	setUsage: function ( value ) {

		this.usage = value;

		return this;

	},

	copy: function ( source ) {

		this.array = new source.array.constructor( source.array );
		this.count = source.count;
		this.stride = source.stride;
		this.usage = source.usage;

		return this;

	},

	copyAt: function ( index1, attribute, index2 ) {

		index1 *= this.stride;
		index2 *= attribute.stride;

		for ( let i = 0, l = this.stride; i < l; i ++ ) {

			this.array[ index1 + i ] = attribute.array[ index2 + i ];

		}

		return this;

	},

	set: function ( value, offset ) {

		if ( offset === undefined ) offset = 0;

		this.array.set( value, offset );

		return this;

	},

	clone: function ( data ) {

		if ( data.arrayBuffers === undefined ) {

			data.arrayBuffers = {};

		}

		if ( this.array.buffer._uuid === undefined ) {

			this.array.buffer._uuid = MathUtils.generateUUID();

		}

		if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {

			data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;

		}

		const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );

		const ib = new InterleavedBuffer( array, this.stride );
		ib.setUsage( this.usage );

		return ib;

	},

	onUpload: function ( callback ) {

		this.onUploadCallback = callback;

		return this;

	},

	toJSON: function ( data ) {

		if ( data.arrayBuffers === undefined ) {

			data.arrayBuffers = {};

		}

		// generate UUID for array buffer if necessary

		if ( this.array.buffer._uuid === undefined ) {

			this.array.buffer._uuid = MathUtils.generateUUID();

		}

		if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {

			data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );

		}

		//

		return {
			uuid: this.uuid,
			buffer: this.array.buffer._uuid,
			type: this.array.constructor.name,
			stride: this.stride
		};

	}

} );

/**
 * @author benaadams / https://twitter.com/ben_a_adams
 */

const _vector$6 = new Vector3();

function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {

	this.name = '';

	this.data = interleavedBuffer;
	this.itemSize = itemSize;
	this.offset = offset;

	this.normalized = normalized === true;

}

Object.defineProperties( InterleavedBufferAttribute.prototype, {

	count: {

		get: function () {

			return this.data.count;

		}

	},

	array: {

		get: function () {

			return this.data.array;

		}

	}

} );

Object.assign( InterleavedBufferAttribute.prototype, {

	isInterleavedBufferAttribute: true,

	applyMatrix4: function ( m ) {

		for ( let i = 0, l = this.data.count; i < l; i ++ ) {

			_vector$6.x = this.getX( i );
			_vector$6.y = this.getY( i );
			_vector$6.z = this.getZ( i );

			_vector$6.applyMatrix4( m );

			this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );

		}

		return this;

	},

	setX: function ( index, x ) {

		this.data.array[ index * this.data.stride + this.offset ] = x;

		return this;

	},

	setY: function ( index, y ) {

		this.data.array[ index * this.data.stride + this.offset + 1 ] = y;

		return this;

	},

	setZ: function ( index, z ) {

		this.data.array[ index * this.data.stride + this.offset + 2 ] = z;

		return this;

	},

	setW: function ( index, w ) {

		this.data.array[ index * this.data.stride + this.offset + 3 ] = w;

		return this;

	},

	getX: function ( index ) {

		return this.data.array[ index * this.data.stride + this.offset ];

	},

	getY: function ( index ) {

		return this.data.array[ index * this.data.stride + this.offset + 1 ];

	},

	getZ: function ( index ) {

		return this.data.array[ index * this.data.stride + this.offset + 2 ];

	},

	getW: function ( index ) {

		return this.data.array[ index * this.data.stride + this.offset + 3 ];

	},

	setXY: function ( index, x, y ) {

		index = index * this.data.stride + this.offset;

		this.data.array[ index + 0 ] = x;
		this.data.array[ index + 1 ] = y;

		return this;

	},

	setXYZ: function ( index, x, y, z ) {

		index = index * this.data.stride + this.offset;

		this.data.array[ index + 0 ] = x;
		this.data.array[ index + 1 ] = y;
		this.data.array[ index + 2 ] = z;

		return this;

	},

	setXYZW: function ( index, x, y, z, w ) {

		index = index * this.data.stride + this.offset;

		this.data.array[ index + 0 ] = x;
		this.data.array[ index + 1 ] = y;
		this.data.array[ index + 2 ] = z;
		this.data.array[ index + 3 ] = w;

		return this;

	},

	clone: function ( data ) {

		if ( data === undefined ) {

			console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );

			const array = [];

			for ( let i = 0; i < this.count; i ++ ) {

				const index = i * this.data.stride + this.offset;

				for ( let j = 0; j < this.itemSize; j ++ ) {

					array.push( this.data.array[ index + j ] );

				}

			}

			return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );

		} else {

			if ( data.interleavedBuffers === undefined ) {

				data.interleavedBuffers = {};

			}

			if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {

				data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );

			}

			return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );

		}

	},

	toJSON: function ( data ) {

		if ( data === undefined ) {

			console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );

			const array = [];

			for ( let i = 0; i < this.count; i ++ ) {

				const index = i * this.data.stride + this.offset;

				for ( let j = 0; j < this.itemSize; j ++ ) {

					array.push( this.data.array[ index + j ] );

				}

			}

			// deinterleave data and save it as an ordinary buffer attribute for now

			return {
				itemSize: this.itemSize,
				type: this.array.constructor.name,
				array: array,
				normalized: this.normalized
			};

		} else {

			// save as true interlaved attribtue

			if ( data.interleavedBuffers === undefined ) {

				data.interleavedBuffers = {};

			}

			if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {

				data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );

			}

			return {
				isInterleavedBufferAttribute: true,
				itemSize: this.itemSize,
				data: this.data.uuid,
				offset: this.offset,
				normalized: this.normalized
			};

		}

	}

} );

/**
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  map: new THREE.Texture( <Image> ),
 *  alphaMap: new THREE.Texture( <Image> ),
 *  rotation: <float>,
 *  sizeAttenuation: <bool>
 * }
 */

function SpriteMaterial( parameters ) {

	Material.call( this );

	this.type = 'SpriteMaterial';

	this.color = new Color( 0xffffff );

	this.map = null;

	this.alphaMap = null;

	this.rotation = 0;

	this.sizeAttenuation = true;

	this.transparent = true;

	this.setValues( parameters );

}

SpriteMaterial.prototype = Object.create( Material.prototype );
SpriteMaterial.prototype.constructor = SpriteMaterial;
SpriteMaterial.prototype.isSpriteMaterial = true;

SpriteMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.color.copy( source.color );

	this.map = source.map;

	this.alphaMap = source.alphaMap;

	this.rotation = source.rotation;

	this.sizeAttenuation = source.sizeAttenuation;

	return this;

};

/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 */

let _geometry;

const _intersectPoint = new Vector3();
const _worldScale = new Vector3();
const _mvPosition = new Vector3();

const _alignedPosition = new Vector2();
const _rotatedPosition = new Vector2();
const _viewWorldMatrix = new Matrix4();

const _vA$1 = new Vector3();
const _vB$1 = new Vector3();
const _vC$1 = new Vector3();

const _uvA$1 = new Vector2();
const _uvB$1 = new Vector2();
const _uvC$1 = new Vector2();

function Sprite( material ) {

	Object3D.call( this );

	this.type = 'Sprite';

	if ( _geometry === undefined ) {

		_geometry = new BufferGeometry();

		const float32Array = new Float32Array( [
			- 0.5, - 0.5, 0, 0, 0,
			0.5, - 0.5, 0, 1, 0,
			0.5, 0.5, 0, 1, 1,
			- 0.5, 0.5, 0, 0, 1
		] );

		const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );

		_geometry.setIndex( [ 0, 1, 2,	0, 2, 3 ] );
		_geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
		_geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );

	}

	this.geometry = _geometry;
	this.material = ( material !== undefined ) ? material : new SpriteMaterial();

	this.center = new Vector2( 0.5, 0.5 );

}

Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Sprite,

	isSprite: true,

	raycast: function ( raycaster, intersects ) {

		if ( raycaster.camera === null ) {

			console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );

		}

		_worldScale.setFromMatrixScale( this.matrixWorld );

		_viewWorldMatrix.copy( raycaster.camera.matrixWorld );
		this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );

		_mvPosition.setFromMatrixPosition( this.modelViewMatrix );

		if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {

			_worldScale.multiplyScalar( - _mvPosition.z );

		}

		const rotation = this.material.rotation;
		let sin, cos;

		if ( rotation !== 0 ) {

			cos = Math.cos( rotation );
			sin = Math.sin( rotation );

		}

		const center = this.center;

		transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
		transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
		transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );

		_uvA$1.set( 0, 0 );
		_uvB$1.set( 1, 0 );
		_uvC$1.set( 1, 1 );

		// check first triangle
		let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );

		if ( intersect === null ) {

			// check second triangle
			transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
			_uvB$1.set( 0, 1 );

			intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
			if ( intersect === null ) {

				return;

			}

		}

		const distance = raycaster.ray.origin.distanceTo( _intersectPoint );

		if ( distance < raycaster.near || distance > raycaster.far ) return;

		intersects.push( {

			distance: distance,
			point: _intersectPoint.clone(),
			uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() ),
			face: null,
			object: this

		} );

	},

	copy: function ( source ) {

		Object3D.prototype.copy.call( this, source );

		if ( source.center !== undefined ) this.center.copy( source.center );

		this.material = source.material;

		return this;

	}

} );

function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {

	// compute position in camera space
	_alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );

	// to check if rotation is not zero
	if ( sin !== undefined ) {

		_rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
		_rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );

	} else {

		_rotatedPosition.copy( _alignedPosition );

	}


	vertexPosition.copy( mvPosition );
	vertexPosition.x += _rotatedPosition.x;
	vertexPosition.y += _rotatedPosition.y;

	// transform to world space
	vertexPosition.applyMatrix4( _viewWorldMatrix );

}

/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 */

const _v1$4 = new Vector3();
const _v2$2 = new Vector3();

function LOD() {

	Object3D.call( this );

	this._currentLevel = 0;

	this.type = 'LOD';

	Object.defineProperties( this, {
		levels: {
			enumerable: true,
			value: []
		}
	} );

	this.autoUpdate = true;

}

LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: LOD,

	isLOD: true,

	copy: function ( source ) {

		Object3D.prototype.copy.call( this, source, false );

		const levels = source.levels;

		for ( let i = 0, l = levels.length; i < l; i ++ ) {

			const level = levels[ i ];

			this.addLevel( level.object.clone(), level.distance );

		}

		this.autoUpdate = source.autoUpdate;

		return this;

	},

	addLevel: function ( object, distance ) {

		if ( distance === undefined ) distance = 0;

		distance = Math.abs( distance );

		const levels = this.levels;

		let l;

		for ( l = 0; l < levels.length; l ++ ) {

			if ( distance < levels[ l ].distance ) {

				break;

			}

		}

		levels.splice( l, 0, { distance: distance, object: object } );

		this.add( object );

		return this;

	},

	getCurrentLevel: function () {

		return this._currentLevel;

	},

	getObjectForDistance: function ( distance ) {

		const levels = this.levels;

		if ( levels.length > 0 ) {

			let i, l;

			for ( i = 1, l = levels.length; i < l; i ++ ) {

				if ( distance < levels[ i ].distance ) {

					break;

				}

			}

			return levels[ i - 1 ].object;

		}

		return null;

	},

	raycast: function ( raycaster, intersects ) {

		const levels = this.levels;

		if ( levels.length > 0 ) {

			_v1$4.setFromMatrixPosition( this.matrixWorld );

			const distance = raycaster.ray.origin.distanceTo( _v1$4 );

			this.getObjectForDistance( distance ).raycast( raycaster, intersects );

		}

	},

	update: function ( camera ) {

		const levels = this.levels;

		if ( levels.length > 1 ) {

			_v1$4.setFromMatrixPosition( camera.matrixWorld );
			_v2$2.setFromMatrixPosition( this.matrixWorld );

			const distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;

			levels[ 0 ].object.visible = true;

			let i, l;

			for ( i = 1, l = levels.length; i < l; i ++ ) {

				if ( distance >= levels[ i ].distance ) {

					levels[ i - 1 ].object.visible = false;
					levels[ i ].object.visible = true;

				} else {

					break;

				}

			}

			this._currentLevel = i - 1;

			for ( ; i < l; i ++ ) {

				levels[ i ].object.visible = false;

			}

		}

	},

	toJSON: function ( meta ) {

		const data = Object3D.prototype.toJSON.call( this, meta );

		if ( this.autoUpdate === false ) data.object.autoUpdate = false;

		data.object.levels = [];

		const levels = this.levels;

		for ( let i = 0, l = levels.length; i < l; i ++ ) {

			const level = levels[ i ];

			data.object.levels.push( {
				object: level.object.uuid,
				distance: level.distance
			} );

		}

		return data;

	}

} );

/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author ikerr / http://verold.com
 */

function SkinnedMesh( geometry, material ) {

	if ( geometry && geometry.isGeometry ) {

		console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );

	}

	Mesh.call( this, geometry, material );

	this.type = 'SkinnedMesh';

	this.bindMode = 'attached';
	this.bindMatrix = new Matrix4();
	this.bindMatrixInverse = new Matrix4();

}

SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {

	constructor: SkinnedMesh,

	isSkinnedMesh: true,

	copy: function ( source ) {

		Mesh.prototype.copy.call( this, source );

		this.bindMode = source.bindMode;
		this.bindMatrix.copy( source.bindMatrix );
		this.bindMatrixInverse.copy( source.bindMatrixInverse );

		this.skeleton = source.skeleton;

		return this;

	},

	bind: function ( skeleton, bindMatrix ) {

		this.skeleton = skeleton;

		if ( bindMatrix === undefined ) {

			this.updateMatrixWorld( true );

			this.skeleton.calculateInverses();

			bindMatrix = this.matrixWorld;

		}

		this.bindMatrix.copy( bindMatrix );
		this.bindMatrixInverse.getInverse( bindMatrix );

	},

	pose: function () {

		this.skeleton.pose();

	},

	normalizeSkinWeights: function () {

		const vector = new Vector4();

		const skinWeight = this.geometry.attributes.skinWeight;

		for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {

			vector.x = skinWeight.getX( i );
			vector.y = skinWeight.getY( i );
			vector.z = skinWeight.getZ( i );
			vector.w = skinWeight.getW( i );

			const scale = 1.0 / vector.manhattanLength();

			if ( scale !== Infinity ) {

				vector.multiplyScalar( scale );

			} else {

				vector.set( 1, 0, 0, 0 ); // do something reasonable

			}

			skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );

		}

	},

	updateMatrixWorld: function ( force ) {

		Mesh.prototype.updateMatrixWorld.call( this, force );

		if ( this.bindMode === 'attached' ) {

			this.bindMatrixInverse.getInverse( this.matrixWorld );

		} else if ( this.bindMode === 'detached' ) {

			this.bindMatrixInverse.getInverse( this.bindMatrix );

		} else {

			console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );

		}

	},

	boneTransform: ( function () {

		const basePosition = new Vector3();

		const skinIndex = new Vector4();
		const skinWeight = new Vector4();

		const vector = new Vector3();
		const matrix = new Matrix4();

		return function ( index, target ) {

			const skeleton = this.skeleton;
			const geometry = this.geometry;

			skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
			skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );

			basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );

			target.set( 0, 0, 0 );

			for ( let i = 0; i < 4; i ++ ) {

				const weight = skinWeight.getComponent( i );

				if ( weight !== 0 ) {

					const boneIndex = skinIndex.getComponent( i );

					matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );

					target.addScaledVector( vector.copy( basePosition ).applyMatrix4( matrix ), weight );

				}

			}

			return target.applyMatrix4( this.bindMatrixInverse );

		};

	}() )

} );

/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author michael guerrero / http://realitymeltdown.com
 * @author ikerr / http://verold.com
 */

const _offsetMatrix = new Matrix4();
const _identityMatrix = new Matrix4();

function Skeleton( bones, boneInverses ) {

	// copy the bone array

	bones = bones || [];

	this.bones = bones.slice( 0 );
	this.boneMatrices = new Float32Array( this.bones.length * 16 );

	this.frame = - 1;

	// use the supplied bone inverses or calculate the inverses

	if ( boneInverses === undefined ) {

		this.calculateInverses();

	} else {

		if ( this.bones.length === boneInverses.length ) {

			this.boneInverses = boneInverses.slice( 0 );

		} else {

			console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );

			this.boneInverses = [];

			for ( let i = 0, il = this.bones.length; i < il; i ++ ) {

				this.boneInverses.push( new Matrix4() );

			}

		}

	}

}

Object.assign( Skeleton.prototype, {

	calculateInverses: function () {

		this.boneInverses = [];

		for ( let i = 0, il = this.bones.length; i < il; i ++ ) {

			const inverse = new Matrix4();

			if ( this.bones[ i ] ) {

				inverse.getInverse( this.bones[ i ].matrixWorld );

			}

			this.boneInverses.push( inverse );

		}

	},

	pose: function () {

		// recover the bind-time world matrices

		for ( let i = 0, il = this.bones.length; i < il; i ++ ) {

			const bone = this.bones[ i ];

			if ( bone ) {

				bone.matrixWorld.getInverse( this.boneInverses[ i ] );

			}

		}

		// compute the local matrices, positions, rotations and scales

		for ( let i = 0, il = this.bones.length; i < il; i ++ ) {

			const bone = this.bones[ i ];

			if ( bone ) {

				if ( bone.parent && bone.parent.isBone ) {

					bone.matrix.getInverse( bone.parent.matrixWorld );
					bone.matrix.multiply( bone.matrixWorld );

				} else {

					bone.matrix.copy( bone.matrixWorld );

				}

				bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );

			}

		}

	},

	update: function () {

		const bones = this.bones;
		const boneInverses = this.boneInverses;
		const boneMatrices = this.boneMatrices;
		const boneTexture = this.boneTexture;

		// flatten bone matrices to array

		for ( let i = 0, il = bones.length; i < il; i ++ ) {

			// compute the offset between the current and the original transform

			const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;

			_offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
			_offsetMatrix.toArray( boneMatrices, i * 16 );

		}

		if ( boneTexture !== undefined ) {

			boneTexture.needsUpdate = true;

		}

	},

	clone: function () {

		return new Skeleton( this.bones, this.boneInverses );

	},

	getBoneByName: function ( name ) {

		for ( let i = 0, il = this.bones.length; i < il; i ++ ) {

			const bone = this.bones[ i ];

			if ( bone.name === name ) {

				return bone;

			}

		}

		return undefined;

	},

	dispose: function ( ) {

		if ( this.boneTexture ) {

			this.boneTexture.dispose();

			this.boneTexture = undefined;

		}

	}

} );

/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author ikerr / http://verold.com
 */

function Bone() {

	Object3D.call( this );

	this.type = 'Bone';

}

Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Bone,

	isBone: true

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

const _instanceLocalMatrix = new Matrix4();
const _instanceWorldMatrix = new Matrix4();

const _instanceIntersects = [];

const _mesh = new Mesh();

function InstancedMesh( geometry, material, count ) {

	Mesh.call( this, geometry, material );

	this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );

	this.count = count;

	this.frustumCulled = false;

}

InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {

	constructor: InstancedMesh,

	isInstancedMesh: true,

	copy: function ( source ) {

		Mesh.prototype.copy.call( this, source );

		this.instanceMatrix.copy( source.instanceMatrix );
		this.count = source.count;

		return this;

	},

	getMatrixAt: function ( index, matrix ) {

		matrix.fromArray( this.instanceMatrix.array, index * 16 );

	},

	raycast: function ( raycaster, intersects ) {

		const matrixWorld = this.matrixWorld;
		const raycastTimes = this.count;

		_mesh.geometry = this.geometry;
		_mesh.material = this.material;

		if ( _mesh.material === undefined ) return;

		for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {

			// calculate the world matrix for each instance

			this.getMatrixAt( instanceId, _instanceLocalMatrix );

			_instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );

			// the mesh represents this single instance

			_mesh.matrixWorld = _instanceWorldMatrix;

			_mesh.raycast( raycaster, _instanceIntersects );

			// process the result of raycast

			for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {

				const intersect = _instanceIntersects[ i ];
				intersect.instanceId = instanceId;
				intersect.object = this;
				intersects.push( intersect );

			}

			_instanceIntersects.length = 0;

		}

	},

	setMatrixAt: function ( index, matrix ) {

		matrix.toArray( this.instanceMatrix.array, index * 16 );

	},

	updateMorphTargets: function () {

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  opacity: <float>,
 *
 *  linewidth: <float>,
 *  linecap: "round",
 *  linejoin: "round"
 * }
 */

function LineBasicMaterial( parameters ) {

	Material.call( this );

	this.type = 'LineBasicMaterial';

	this.color = new Color( 0xffffff );

	this.linewidth = 1;
	this.linecap = 'round';
	this.linejoin = 'round';

	this.morphTargets = false;

	this.setValues( parameters );

}

LineBasicMaterial.prototype = Object.create( Material.prototype );
LineBasicMaterial.prototype.constructor = LineBasicMaterial;

LineBasicMaterial.prototype.isLineBasicMaterial = true;

LineBasicMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.color.copy( source.color );

	this.linewidth = source.linewidth;
	this.linecap = source.linecap;
	this.linejoin = source.linejoin;

	this.morphTargets = source.morphTargets;

	return this;

};

/**
 * @author mrdoob / http://mrdoob.com/
 */

const _start = new Vector3();
const _end = new Vector3();
const _inverseMatrix$1 = new Matrix4();
const _ray$1 = new Ray();
const _sphere$2 = new Sphere();

function Line( geometry, material, mode ) {

	if ( mode === 1 ) {

		console.error( 'THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.' );

	}

	Object3D.call( this );

	this.type = 'Line';

	this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
	this.material = material !== undefined ? material : new LineBasicMaterial();

	this.updateMorphTargets();

}

Line.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Line,

	isLine: true,

	copy: function ( source ) {

		Object3D.prototype.copy.call( this, source );

		this.material = source.material;
		this.geometry = source.geometry;

		return this;

	},

	computeLineDistances: function () {

		const geometry = this.geometry;

		if ( geometry.isBufferGeometry ) {

			// we assume non-indexed geometry

			if ( geometry.index === null ) {

				const positionAttribute = geometry.attributes.position;
				const lineDistances = [ 0 ];

				for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {

					_start.fromBufferAttribute( positionAttribute, i - 1 );
					_end.fromBufferAttribute( positionAttribute, i );

					lineDistances[ i ] = lineDistances[ i - 1 ];
					lineDistances[ i ] += _start.distanceTo( _end );

				}

				geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );

			} else {

				console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );

			}

		} else if ( geometry.isGeometry ) {

			const vertices = geometry.vertices;
			const lineDistances = geometry.lineDistances;

			lineDistances[ 0 ] = 0;

			for ( let i = 1, l = vertices.length; i < l; i ++ ) {

				lineDistances[ i ] = lineDistances[ i - 1 ];
				lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );

			}

		}

		return this;

	},

	raycast: function ( raycaster, intersects ) {

		const geometry = this.geometry;
		const matrixWorld = this.matrixWorld;
		const threshold = raycaster.params.Line.threshold;

		// Checking boundingSphere distance to ray

		if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

		_sphere$2.copy( geometry.boundingSphere );
		_sphere$2.applyMatrix4( matrixWorld );
		_sphere$2.radius += threshold;

		if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;

		//

		_inverseMatrix$1.getInverse( matrixWorld );
		_ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );

		const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
		const localThresholdSq = localThreshold * localThreshold;

		const vStart = new Vector3();
		const vEnd = new Vector3();
		const interSegment = new Vector3();
		const interRay = new Vector3();
		const step = ( this && this.isLineSegments ) ? 2 : 1;

		if ( geometry.isBufferGeometry ) {

			const index = geometry.index;
			const attributes = geometry.attributes;
			const positions = attributes.position.array;

			if ( index !== null ) {

				const indices = index.array;

				for ( let i = 0, l = indices.length - 1; i < l; i += step ) {

					const a = indices[ i ];
					const b = indices[ i + 1 ];

					vStart.fromArray( positions, a * 3 );
					vEnd.fromArray( positions, b * 3 );

					const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );

					if ( distSq > localThresholdSq ) continue;

					interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

					const distance = raycaster.ray.origin.distanceTo( interRay );

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						// What do we want? intersection point on the ray or on the segment??
						// point: raycaster.ray.at( distance ),
						point: interSegment.clone().applyMatrix4( this.matrixWorld ),
						index: i,
						face: null,
						faceIndex: null,
						object: this

					} );

				}

			} else {

				for ( let i = 0, l = positions.length / 3 - 1; i < l; i += step ) {

					vStart.fromArray( positions, 3 * i );
					vEnd.fromArray( positions, 3 * i + 3 );

					const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );

					if ( distSq > localThresholdSq ) continue;

					interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

					const distance = raycaster.ray.origin.distanceTo( interRay );

					if ( distance < raycaster.near || distance > raycaster.far ) continue;

					intersects.push( {

						distance: distance,
						// What do we want? intersection point on the ray or on the segment??
						// point: raycaster.ray.at( distance ),
						point: interSegment.clone().applyMatrix4( this.matrixWorld ),
						index: i,
						face: null,
						faceIndex: null,
						object: this

					} );

				}

			}

		} else if ( geometry.isGeometry ) {

			const vertices = geometry.vertices;
			const nbVertices = vertices.length;

			for ( let i = 0; i < nbVertices - 1; i += step ) {

				const distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );

				if ( distSq > localThresholdSq ) continue;

				interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation

				const distance = raycaster.ray.origin.distanceTo( interRay );

				if ( distance < raycaster.near || distance > raycaster.far ) continue;

				intersects.push( {

					distance: distance,
					// What do we want? intersection point on the ray or on the segment??
					// point: raycaster.ray.at( distance ),
					point: interSegment.clone().applyMatrix4( this.matrixWorld ),
					index: i,
					face: null,
					faceIndex: null,
					object: this

				} );

			}

		}

	},

	updateMorphTargets: function () {

		const geometry = this.geometry;

		if ( geometry.isBufferGeometry ) {

			const morphAttributes = geometry.morphAttributes;
			const keys = Object.keys( morphAttributes );

			if ( keys.length > 0 ) {

				const morphAttribute = morphAttributes[ keys[ 0 ] ];

				if ( morphAttribute !== undefined ) {

					this.morphTargetInfluences = [];
					this.morphTargetDictionary = {};

					for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {

						const name = morphAttribute[ m ].name || String( m );

						this.morphTargetInfluences.push( 0 );
						this.morphTargetDictionary[ name ] = m;

					}

				}

			}

		} else {

			const morphTargets = geometry.morphTargets;

			if ( morphTargets !== undefined && morphTargets.length > 0 ) {

				console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );

			}

		}

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

const _start$1 = new Vector3();
const _end$1 = new Vector3();

function LineSegments( geometry, material ) {

	Line.call( this, geometry, material );

	this.type = 'LineSegments';

}

LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {

	constructor: LineSegments,

	isLineSegments: true,

	computeLineDistances: function () {

		const geometry = this.geometry;

		if ( geometry.isBufferGeometry ) {

			// we assume non-indexed geometry

			if ( geometry.index === null ) {

				const positionAttribute = geometry.attributes.position;
				const lineDistances = [];

				for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {

					_start$1.fromBufferAttribute( positionAttribute, i );
					_end$1.fromBufferAttribute( positionAttribute, i + 1 );

					lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
					lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );

				}

				geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );

			} else {

				console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );

			}

		} else if ( geometry.isGeometry ) {

			const vertices = geometry.vertices;
			const lineDistances = geometry.lineDistances;

			for ( let i = 0, l = vertices.length; i < l; i += 2 ) {

				_start$1.copy( vertices[ i ] );
				_end$1.copy( vertices[ i + 1 ] );

				lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
				lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );

			}

		}

		return this;

	}

} );

/**
 * @author mgreter / http://github.com/mgreter
 */

function LineLoop( geometry, material ) {

	Line.call( this, geometry, material );

	this.type = 'LineLoop';

}

LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {

	constructor: LineLoop,

	isLineLoop: true,

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  opacity: <float>,
 *  map: new THREE.Texture( <Image> ),
 *  alphaMap: new THREE.Texture( <Image> ),
 *
 *  size: <float>,
 *  sizeAttenuation: <bool>
 *
 *  morphTargets: <bool>
 * }
 */

function PointsMaterial( parameters ) {

	Material.call( this );

	this.type = 'PointsMaterial';

	this.color = new Color( 0xffffff );

	this.map = null;

	this.alphaMap = null;

	this.size = 1;
	this.sizeAttenuation = true;

	this.morphTargets = false;

	this.setValues( parameters );

}

PointsMaterial.prototype = Object.create( Material.prototype );
PointsMaterial.prototype.constructor = PointsMaterial;

PointsMaterial.prototype.isPointsMaterial = true;

PointsMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.color.copy( source.color );

	this.map = source.map;

	this.alphaMap = source.alphaMap;

	this.size = source.size;
	this.sizeAttenuation = source.sizeAttenuation;

	this.morphTargets = source.morphTargets;

	return this;

};

/**
 * @author alteredq / http://alteredqualia.com/
 */

const _inverseMatrix$2 = new Matrix4();
const _ray$2 = new Ray();
const _sphere$3 = new Sphere();
const _position$1 = new Vector3();

function Points( geometry, material ) {

	Object3D.call( this );

	this.type = 'Points';

	this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
	this.material = material !== undefined ? material : new PointsMaterial();

	this.updateMorphTargets();

}

Points.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Points,

	isPoints: true,

	copy: function ( source ) {

		Object3D.prototype.copy.call( this, source );

		this.material = source.material;
		this.geometry = source.geometry;

		return this;

	},

	raycast: function ( raycaster, intersects ) {

		const geometry = this.geometry;
		const matrixWorld = this.matrixWorld;
		const threshold = raycaster.params.Points.threshold;

		// Checking boundingSphere distance to ray

		if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();

		_sphere$3.copy( geometry.boundingSphere );
		_sphere$3.applyMatrix4( matrixWorld );
		_sphere$3.radius += threshold;

		if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;

		//

		_inverseMatrix$2.getInverse( matrixWorld );
		_ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );

		const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
		const localThresholdSq = localThreshold * localThreshold;

		if ( geometry.isBufferGeometry ) {

			const index = geometry.index;
			const attributes = geometry.attributes;
			const positions = attributes.position.array;

			if ( index !== null ) {

				const indices = index.array;

				for ( let i = 0, il = indices.length; i < il; i ++ ) {

					const a = indices[ i ];

					_position$1.fromArray( positions, a * 3 );

					testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );

				}

			} else {

				for ( let i = 0, l = positions.length / 3; i < l; i ++ ) {

					_position$1.fromArray( positions, i * 3 );

					testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );

				}

			}

		} else {

			const vertices = geometry.vertices;

			for ( let i = 0, l = vertices.length; i < l; i ++ ) {

				testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );

			}

		}

	},

	updateMorphTargets: function () {

		const geometry = this.geometry;

		if ( geometry.isBufferGeometry ) {

			const morphAttributes = geometry.morphAttributes;
			const keys = Object.keys( morphAttributes );

			if ( keys.length > 0 ) {

				const morphAttribute = morphAttributes[ keys[ 0 ] ];

				if ( morphAttribute !== undefined ) {

					this.morphTargetInfluences = [];
					this.morphTargetDictionary = {};

					for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {

						const name = morphAttribute[ m ].name || String( m );

						this.morphTargetInfluences.push( 0 );
						this.morphTargetDictionary[ name ] = m;

					}

				}

			}

		} else {

			const morphTargets = geometry.morphTargets;

			if ( morphTargets !== undefined && morphTargets.length > 0 ) {

				console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );

			}

		}

	}

} );

function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {

	const rayPointDistanceSq = _ray$2.distanceSqToPoint( point );

	if ( rayPointDistanceSq < localThresholdSq ) {

		const intersectPoint = new Vector3();

		_ray$2.closestPointToPoint( point, intersectPoint );
		intersectPoint.applyMatrix4( matrixWorld );

		const distance = raycaster.ray.origin.distanceTo( intersectPoint );

		if ( distance < raycaster.near || distance > raycaster.far ) return;

		intersects.push( {

			distance: distance,
			distanceToRay: Math.sqrt( rayPointDistanceSq ),
			point: intersectPoint,
			index: index,
			face: null,
			object: object

		} );

	}

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {

	Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );

	this.format = format !== undefined ? format : RGBFormat;

	this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
	this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;

	this.generateMipmaps = false;

}

VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {

	constructor: VideoTexture,

	isVideoTexture: true,

	update: function () {

		const video = this.image;

		if ( video.readyState >= video.HAVE_CURRENT_DATA ) {

			this.needsUpdate = true;

		}

	}

} );

/**
 * @author alteredq / http://alteredqualia.com/
 */

function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {

	Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );

	this.image = { width: width, height: height };
	this.mipmaps = mipmaps;

	// no flipping for cube textures
	// (also flipping doesn't work for compressed textures )

	this.flipY = false;

	// can't generate mipmaps for compressed textures
	// mips must be embedded in DDS files

	this.generateMipmaps = false;

}

CompressedTexture.prototype = Object.create( Texture.prototype );
CompressedTexture.prototype.constructor = CompressedTexture;

CompressedTexture.prototype.isCompressedTexture = true;

/**
 * @author mrdoob / http://mrdoob.com/
 */

function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {

	Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );

	this.needsUpdate = true;

}

CanvasTexture.prototype = Object.create( Texture.prototype );
CanvasTexture.prototype.constructor = CanvasTexture;
CanvasTexture.prototype.isCanvasTexture = true;

/**
 * @author Matt DesLauriers / @mattdesl
 * @author atix / arthursilber.de
 */

function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {

	format = format !== undefined ? format : DepthFormat;

	if ( format !== DepthFormat && format !== DepthStencilFormat ) {

		throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );

	}

	if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
	if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;

	Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );

	this.image = { width: width, height: height };

	this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
	this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;

	this.flipY = false;
	this.generateMipmaps	= false;

}

DepthTexture.prototype = Object.create( Texture.prototype );
DepthTexture.prototype.constructor = DepthTexture;
DepthTexture.prototype.isDepthTexture = true;

/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / https://github.com/Mugen87
 */

function WireframeGeometry( geometry ) {

	BufferGeometry.call( this );

	this.type = 'WireframeGeometry';

	// buffer

	const vertices = [];

	// helper variables

	const edge = [ 0, 0 ], edges = {};
	const keys = [ 'a', 'b', 'c' ];

	// different logic for Geometry and BufferGeometry

	if ( geometry && geometry.isGeometry ) {

		// create a data structure that contains all edges without duplicates

		const faces = geometry.faces;

		for ( let i = 0, l = faces.length; i < l; i ++ ) {

			const face = faces[ i ];

			for ( let j = 0; j < 3; j ++ ) {

				const edge1 = face[ keys[ j ] ];
				const edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
				edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
				edge[ 1 ] = Math.max( edge1, edge2 );

				const key = edge[ 0 ] + ',' + edge[ 1 ];

				if ( edges[ key ] === undefined ) {

					edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };

				}

			}

		}

		// generate vertices

		for ( const key in edges ) {

			const e = edges[ key ];

			let vertex = geometry.vertices[ e.index1 ];
			vertices.push( vertex.x, vertex.y, vertex.z );

			vertex = geometry.vertices[ e.index2 ];
			vertices.push( vertex.x, vertex.y, vertex.z );

		}

	} else if ( geometry && geometry.isBufferGeometry ) {

		let vertex = new Vector3();

		if ( geometry.index !== null ) {

			// indexed BufferGeometry

			const position = geometry.attributes.position;
			const indices = geometry.index;
			let groups = geometry.groups;

			if ( groups.length === 0 ) {

				groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];

			}

			// create a data structure that contains all eges without duplicates

			for ( let o = 0, ol = groups.length; o < ol; ++ o ) {

				const group = groups[ o ];

				const start = group.start;
				const count = group.count;

				for ( let i = start, l = ( start + count ); i < l; i += 3 ) {

					for ( let j = 0; j < 3; j ++ ) {

						const edge1 = indices.getX( i + j );
						const edge2 = indices.getX( i + ( j + 1 ) % 3 );
						edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
						edge[ 1 ] = Math.max( edge1, edge2 );

						const key = edge[ 0 ] + ',' + edge[ 1 ];

						if ( edges[ key ] === undefined ) {

							edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };

						}

					}

				}

			}

			// generate vertices

			for ( const key in edges ) {

				const e = edges[ key ];

				vertex.fromBufferAttribute( position, e.index1 );
				vertices.push( vertex.x, vertex.y, vertex.z );

				vertex.fromBufferAttribute( position, e.index2 );
				vertices.push( vertex.x, vertex.y, vertex.z );

			}

		} else {

			// non-indexed BufferGeometry

			const position = geometry.attributes.position;

			for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {

				for ( let j = 0; j < 3; j ++ ) {

					// three edges per triangle, an edge is represented as (index1, index2)
					// e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)

					const index1 = 3 * i + j;
					vertex.fromBufferAttribute( position, index1 );
					vertices.push( vertex.x, vertex.y, vertex.z );

					const index2 = 3 * i + ( ( j + 1 ) % 3 );
					vertex.fromBufferAttribute( position, index2 );
					vertices.push( vertex.x, vertex.y, vertex.z );

				}

			}

		}

	}

	// build geometry

	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );

}

WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
WireframeGeometry.prototype.constructor = WireframeGeometry;

/**
 * @author zz85 / https://github.com/zz85
 * @author Mugen87 / https://github.com/Mugen87
 *
 * Parametric Surfaces Geometry
 * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
 */

// ParametricGeometry

function ParametricGeometry( func, slices, stacks ) {

	Geometry.call( this );

	this.type = 'ParametricGeometry';

	this.parameters = {
		func: func,
		slices: slices,
		stacks: stacks
	};

	this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
	this.mergeVertices();

}

ParametricGeometry.prototype = Object.create( Geometry.prototype );
ParametricGeometry.prototype.constructor = ParametricGeometry;

// ParametricBufferGeometry

function ParametricBufferGeometry( func, slices, stacks ) {

	BufferGeometry.call( this );

	this.type = 'ParametricBufferGeometry';

	this.parameters = {
		func: func,
		slices: slices,
		stacks: stacks
	};

	// buffers

	const indices = [];
	const vertices = [];
	const normals = [];
	const uvs = [];

	const EPS = 0.00001;

	const normal = new Vector3();

	const p0 = new Vector3(), p1 = new Vector3();
	const pu = new Vector3(), pv = new Vector3();

	if ( func.length < 3 ) {

		console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );

	}

	// generate vertices, normals and uvs

	const sliceCount = slices + 1;

	for ( let i = 0; i <= stacks; i ++ ) {

		const v = i / stacks;

		for ( let j = 0; j <= slices; j ++ ) {

			const u = j / slices;

			// vertex

			func( u, v, p0 );
			vertices.push( p0.x, p0.y, p0.z );

			// normal

			// approximate tangent vectors via finite differences

			if ( u - EPS >= 0 ) {

				func( u - EPS, v, p1 );
				pu.subVectors( p0, p1 );

			} else {

				func( u + EPS, v, p1 );
				pu.subVectors( p1, p0 );

			}

			if ( v - EPS >= 0 ) {

				func( u, v - EPS, p1 );
				pv.subVectors( p0, p1 );

			} else {

				func( u, v + EPS, p1 );
				pv.subVectors( p1, p0 );

			}

			// cross product of tangent vectors returns surface normal

			normal.crossVectors( pu, pv ).normalize();
			normals.push( normal.x, normal.y, normal.z );

			// uv

			uvs.push( u, v );

		}

	}

	// generate indices

	for ( let i = 0; i < stacks; i ++ ) {

		for ( let j = 0; j < slices; j ++ ) {

			const a = i * sliceCount + j;
			const b = i * sliceCount + j + 1;
			const c = ( i + 1 ) * sliceCount + j + 1;
			const d = ( i + 1 ) * sliceCount + j;

			// faces one and two

			indices.push( a, b, d );
			indices.push( b, c, d );

		}

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

}

ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;

/**
 * @author clockworkgeek / https://github.com/clockworkgeek
 * @author timothypratley / https://github.com/timothypratley
 * @author WestLangley / http://github.com/WestLangley
 * @author Mugen87 / https://github.com/Mugen87
 */

// PolyhedronGeometry

function PolyhedronGeometry( vertices, indices, radius, detail ) {

	Geometry.call( this );

	this.type = 'PolyhedronGeometry';

	this.parameters = {
		vertices: vertices,
		indices: indices,
		radius: radius,
		detail: detail
	};

	this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
	this.mergeVertices();

}

PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;

// PolyhedronBufferGeometry

function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {

	BufferGeometry.call( this );

	this.type = 'PolyhedronBufferGeometry';

	this.parameters = {
		vertices: vertices,
		indices: indices,
		radius: radius,
		detail: detail
	};

	radius = radius || 1;
	detail = detail || 0;

	// default buffer data

	const vertexBuffer = [];
	const uvBuffer = [];

	// the subdivision creates the vertex buffer data

	subdivide( detail );

	// all vertices should lie on a conceptual sphere with a given radius

	applyRadius( radius );

	// finally, create the uv data

	generateUVs();

	// build non-indexed geometry

	this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );

	if ( detail === 0 ) {

		this.computeVertexNormals(); // flat normals

	} else {

		this.normalizeNormals(); // smooth normals

	}

	// helper functions

	function subdivide( detail ) {

		const a = new Vector3();
		const b = new Vector3();
		const c = new Vector3();

		// iterate over all faces and apply a subdivison with the given detail value

		for ( let i = 0; i < indices.length; i += 3 ) {

			// get the vertices of the face

			getVertexByIndex( indices[ i + 0 ], a );
			getVertexByIndex( indices[ i + 1 ], b );
			getVertexByIndex( indices[ i + 2 ], c );

			// perform subdivision

			subdivideFace( a, b, c, detail );

		}

	}

	function subdivideFace( a, b, c, detail ) {

		const cols = Math.pow( 2, detail );

		// we use this multidimensional array as a data structure for creating the subdivision

		const v = [];

		// construct all of the vertices for this subdivision

		for ( let i = 0; i <= cols; i ++ ) {

			v[ i ] = [];

			const aj = a.clone().lerp( c, i / cols );
			const bj = b.clone().lerp( c, i / cols );

			const rows = cols - i;

			for ( let j = 0; j <= rows; j ++ ) {

				if ( j === 0 && i === cols ) {

					v[ i ][ j ] = aj;

				} else {

					v[ i ][ j ] = aj.clone().lerp( bj, j / rows );

				}

			}

		}

		// construct all of the faces

		for ( let i = 0; i < cols; i ++ ) {

			for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {

				const k = Math.floor( j / 2 );

				if ( j % 2 === 0 ) {

					pushVertex( v[ i ][ k + 1 ] );
					pushVertex( v[ i + 1 ][ k ] );
					pushVertex( v[ i ][ k ] );

				} else {

					pushVertex( v[ i ][ k + 1 ] );
					pushVertex( v[ i + 1 ][ k + 1 ] );
					pushVertex( v[ i + 1 ][ k ] );

				}

			}

		}

	}

	function applyRadius( radius ) {

		const vertex = new Vector3();

		// iterate over the entire buffer and apply the radius to each vertex

		for ( let i = 0; i < vertexBuffer.length; i += 3 ) {

			vertex.x = vertexBuffer[ i + 0 ];
			vertex.y = vertexBuffer[ i + 1 ];
			vertex.z = vertexBuffer[ i + 2 ];

			vertex.normalize().multiplyScalar( radius );

			vertexBuffer[ i + 0 ] = vertex.x;
			vertexBuffer[ i + 1 ] = vertex.y;
			vertexBuffer[ i + 2 ] = vertex.z;

		}

	}

	function generateUVs() {

		const vertex = new Vector3();

		for ( let i = 0; i < vertexBuffer.length; i += 3 ) {

			vertex.x = vertexBuffer[ i + 0 ];
			vertex.y = vertexBuffer[ i + 1 ];
			vertex.z = vertexBuffer[ i + 2 ];

			const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
			const v = inclination( vertex ) / Math.PI + 0.5;
			uvBuffer.push( u, 1 - v );

		}

		correctUVs();

		correctSeam();

	}

	function correctSeam() {

		// handle case when face straddles the seam, see #3269

		for ( let i = 0; i < uvBuffer.length; i += 6 ) {

			// uv data of a single face

			const x0 = uvBuffer[ i + 0 ];
			const x1 = uvBuffer[ i + 2 ];
			const x2 = uvBuffer[ i + 4 ];

			const max = Math.max( x0, x1, x2 );
			const min = Math.min( x0, x1, x2 );

			// 0.9 is somewhat arbitrary

			if ( max > 0.9 && min < 0.1 ) {

				if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
				if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
				if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;

			}

		}

	}

	function pushVertex( vertex ) {

		vertexBuffer.push( vertex.x, vertex.y, vertex.z );

	}

	function getVertexByIndex( index, vertex ) {

		const stride = index * 3;

		vertex.x = vertices[ stride + 0 ];
		vertex.y = vertices[ stride + 1 ];
		vertex.z = vertices[ stride + 2 ];

	}

	function correctUVs() {

		const a = new Vector3();
		const b = new Vector3();
		const c = new Vector3();

		const centroid = new Vector3();

		const uvA = new Vector2();
		const uvB = new Vector2();
		const uvC = new Vector2();

		for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {

			a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
			b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
			c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );

			uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
			uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
			uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );

			centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );

			const azi = azimuth( centroid );

			correctUV( uvA, j + 0, a, azi );
			correctUV( uvB, j + 2, b, azi );
			correctUV( uvC, j + 4, c, azi );

		}

	}

	function correctUV( uv, stride, vector, azimuth ) {

		if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {

			uvBuffer[ stride ] = uv.x - 1;

		}

		if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {

			uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;

		}

	}

	// Angle around the Y axis, counter-clockwise when looking from above.

	function azimuth( vector ) {

		return Math.atan2( vector.z, - vector.x );

	}


	// Angle above the XZ plane.

	function inclination( vector ) {

		return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );

	}

}

PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;

/**
 * @author timothypratley / https://github.com/timothypratley
 * @author Mugen87 / https://github.com/Mugen87
 */

// TetrahedronGeometry

function TetrahedronGeometry( radius, detail ) {

	Geometry.call( this );

	this.type = 'TetrahedronGeometry';

	this.parameters = {
		radius: radius,
		detail: detail
	};

	this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
	this.mergeVertices();

}

TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;

// TetrahedronBufferGeometry

function TetrahedronBufferGeometry( radius, detail ) {

	const vertices = [
		1, 1, 1, 	- 1, - 1, 1, 	- 1, 1, - 1, 	1, - 1, - 1
	];

	const indices = [
		2, 1, 0, 	0, 3, 2,	1, 3, 0,	2, 3, 1
	];

	PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );

	this.type = 'TetrahedronBufferGeometry';

	this.parameters = {
		radius: radius,
		detail: detail
	};

}

TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;

/**
 * @author timothypratley / https://github.com/timothypratley
 * @author Mugen87 / https://github.com/Mugen87
 */

// OctahedronGeometry

function OctahedronGeometry( radius, detail ) {

	Geometry.call( this );

	this.type = 'OctahedronGeometry';

	this.parameters = {
		radius: radius,
		detail: detail
	};

	this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
	this.mergeVertices();

}

OctahedronGeometry.prototype = Object.create( Geometry.prototype );
OctahedronGeometry.prototype.constructor = OctahedronGeometry;

// OctahedronBufferGeometry

function OctahedronBufferGeometry( radius, detail ) {

	const vertices = [
		1, 0, 0, 	- 1, 0, 0,	0, 1, 0,
		0, - 1, 0, 	0, 0, 1,	0, 0, - 1
	];

	const indices = [
		0, 2, 4,	0, 4, 3,	0, 3, 5,
		0, 5, 2,	1, 2, 5,	1, 5, 3,
		1, 3, 4,	1, 4, 2
	];

	PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );

	this.type = 'OctahedronBufferGeometry';

	this.parameters = {
		radius: radius,
		detail: detail
	};

}

OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;

/**
 * @author timothypratley / https://github.com/timothypratley
 * @author Mugen87 / https://github.com/Mugen87
 */

// IcosahedronGeometry

function IcosahedronGeometry( radius, detail ) {

	Geometry.call( this );

	this.type = 'IcosahedronGeometry';

	this.parameters = {
		radius: radius,
		detail: detail
	};

	this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
	this.mergeVertices();

}

IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;

// IcosahedronBufferGeometry

function IcosahedronBufferGeometry( radius, detail ) {

	const t = ( 1 + Math.sqrt( 5 ) ) / 2;

	const vertices = [
		- 1, t, 0, 	1, t, 0, 	- 1, - t, 0, 	1, - t, 0,
		 0, - 1, t, 	0, 1, t,	0, - 1, - t, 	0, 1, - t,
		 t, 0, - 1, 	t, 0, 1, 	- t, 0, - 1, 	- t, 0, 1
	];

	const indices = [
		 0, 11, 5, 	0, 5, 1, 	0, 1, 7, 	0, 7, 10, 	0, 10, 11,
		 1, 5, 9, 	5, 11, 4,	11, 10, 2,	10, 7, 6,	7, 1, 8,
		 3, 9, 4, 	3, 4, 2,	3, 2, 6,	3, 6, 8,	3, 8, 9,
		 4, 9, 5, 	2, 4, 11,	6, 2, 10,	8, 6, 7,	9, 8, 1
	];

	PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );

	this.type = 'IcosahedronBufferGeometry';

	this.parameters = {
		radius: radius,
		detail: detail
	};

}

IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;

/**
 * @author Abe Pazos / https://hamoid.com
 * @author Mugen87 / https://github.com/Mugen87
 */

// DodecahedronGeometry

function DodecahedronGeometry( radius, detail ) {

	Geometry.call( this );

	this.type = 'DodecahedronGeometry';

	this.parameters = {
		radius: radius,
		detail: detail
	};

	this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
	this.mergeVertices();

}

DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;

// DodecahedronBufferGeometry

function DodecahedronBufferGeometry( radius, detail ) {

	const t = ( 1 + Math.sqrt( 5 ) ) / 2;
	const r = 1 / t;

	const vertices = [

		// (±1, ±1, ±1)
		- 1, - 1, - 1,	- 1, - 1, 1,
		- 1, 1, - 1, - 1, 1, 1,
		1, - 1, - 1, 1, - 1, 1,
		1, 1, - 1, 1, 1, 1,

		// (0, ±1/φ, ±φ)
		 0, - r, - t, 0, - r, t,
		 0, r, - t, 0, r, t,

		// (±1/φ, ±φ, 0)
		- r, - t, 0, - r, t, 0,
		 r, - t, 0, r, t, 0,

		// (±φ, 0, ±1/φ)
		- t, 0, - r, t, 0, - r,
		- t, 0, r, t, 0, r
	];

	const indices = [
		3, 11, 7, 	3, 7, 15, 	3, 15, 13,
		7, 19, 17, 	7, 17, 6, 	7, 6, 15,
		17, 4, 8, 	17, 8, 10, 	17, 10, 6,
		8, 0, 16, 	8, 16, 2, 	8, 2, 10,
		0, 12, 1, 	0, 1, 18, 	0, 18, 16,
		6, 10, 2, 	6, 2, 13, 	6, 13, 15,
		2, 16, 18, 	2, 18, 3, 	2, 3, 13,
		18, 1, 9, 	18, 9, 11, 	18, 11, 3,
		4, 14, 12, 	4, 12, 0, 	4, 0, 8,
		11, 9, 5, 	11, 5, 19, 	11, 19, 7,
		19, 5, 14, 	19, 14, 4, 	19, 4, 17,
		1, 12, 14, 	1, 14, 5, 	1, 5, 9
	];

	PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );

	this.type = 'DodecahedronBufferGeometry';

	this.parameters = {
		radius: radius,
		detail: detail
	};

}

DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;

/**
 * @author oosmoxiecode / https://github.com/oosmoxiecode
 * @author WestLangley / https://github.com/WestLangley
 * @author zz85 / https://github.com/zz85
 * @author miningold / https://github.com/miningold
 * @author jonobr1 / https://github.com/jonobr1
 * @author Mugen87 / https://github.com/Mugen87
 *
 */

// TubeGeometry

function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {

	Geometry.call( this );

	this.type = 'TubeGeometry';

	this.parameters = {
		path: path,
		tubularSegments: tubularSegments,
		radius: radius,
		radialSegments: radialSegments,
		closed: closed
	};

	if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );

	const bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );

	// expose internals

	this.tangents = bufferGeometry.tangents;
	this.normals = bufferGeometry.normals;
	this.binormals = bufferGeometry.binormals;

	// create geometry

	this.fromBufferGeometry( bufferGeometry );
	this.mergeVertices();

}

TubeGeometry.prototype = Object.create( Geometry.prototype );
TubeGeometry.prototype.constructor = TubeGeometry;

// TubeBufferGeometry

function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {

	BufferGeometry.call( this );

	this.type = 'TubeBufferGeometry';

	this.parameters = {
		path: path,
		tubularSegments: tubularSegments,
		radius: radius,
		radialSegments: radialSegments,
		closed: closed
	};

	tubularSegments = tubularSegments || 64;
	radius = radius || 1;
	radialSegments = radialSegments || 8;
	closed = closed || false;

	const frames = path.computeFrenetFrames( tubularSegments, closed );

	// expose internals

	this.tangents = frames.tangents;
	this.normals = frames.normals;
	this.binormals = frames.binormals;

	// helper variables

	const vertex = new Vector3();
	const normal = new Vector3();
	const uv = new Vector2();
	let P = new Vector3();

	// buffer

	const vertices = [];
	const normals = [];
	const uvs = [];
	const indices = [];

	// create buffer data

	generateBufferData();

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	// functions

	function generateBufferData() {

		for ( let i = 0; i < tubularSegments; i ++ ) {

			generateSegment( i );

		}

		// if the geometry is not closed, generate the last row of vertices and normals
		// at the regular position on the given path
		//
		// if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)

		generateSegment( ( closed === false ) ? tubularSegments : 0 );

		// uvs are generated in a separate function.
		// this makes it easy compute correct values for closed geometries

		generateUVs();

		// finally create faces

		generateIndices();

	}

	function generateSegment( i ) {

		// we use getPointAt to sample evenly distributed points from the given path

		P = path.getPointAt( i / tubularSegments, P );

		// retrieve corresponding normal and binormal

		const N = frames.normals[ i ];
		const B = frames.binormals[ i ];

		// generate normals and vertices for the current segment

		for ( let j = 0; j <= radialSegments; j ++ ) {

			const v = j / radialSegments * Math.PI * 2;

			const sin = Math.sin( v );
			const cos = - Math.cos( v );

			// normal

			normal.x = ( cos * N.x + sin * B.x );
			normal.y = ( cos * N.y + sin * B.y );
			normal.z = ( cos * N.z + sin * B.z );
			normal.normalize();

			normals.push( normal.x, normal.y, normal.z );

			// vertex

			vertex.x = P.x + radius * normal.x;
			vertex.y = P.y + radius * normal.y;
			vertex.z = P.z + radius * normal.z;

			vertices.push( vertex.x, vertex.y, vertex.z );

		}

	}

	function generateIndices() {

		for ( let j = 1; j <= tubularSegments; j ++ ) {

			for ( let i = 1; i <= radialSegments; i ++ ) {

				const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
				const b = ( radialSegments + 1 ) * j + ( i - 1 );
				const c = ( radialSegments + 1 ) * j + i;
				const d = ( radialSegments + 1 ) * ( j - 1 ) + i;

				// faces

				indices.push( a, b, d );
				indices.push( b, c, d );

			}

		}

	}

	function generateUVs() {

		for ( let i = 0; i <= tubularSegments; i ++ ) {

			for ( let j = 0; j <= radialSegments; j ++ ) {

				uv.x = i / tubularSegments;
				uv.y = j / radialSegments;

				uvs.push( uv.x, uv.y );

			}

		}

	}

}

TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;

TubeBufferGeometry.prototype.toJSON = function () {

	const data = BufferGeometry.prototype.toJSON.call( this );

	data.path = this.parameters.path.toJSON();

	return data;

};

/**
 * @author oosmoxiecode
 * @author Mugen87 / https://github.com/Mugen87
 *
 * based on http://www.blackpawn.com/texts/pqtorus/
 */

// TorusKnotGeometry

function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {

	Geometry.call( this );

	this.type = 'TorusKnotGeometry';

	this.parameters = {
		radius: radius,
		tube: tube,
		tubularSegments: tubularSegments,
		radialSegments: radialSegments,
		p: p,
		q: q
	};

	if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );

	this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
	this.mergeVertices();

}

TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;

// TorusKnotBufferGeometry

function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {

	BufferGeometry.call( this );

	this.type = 'TorusKnotBufferGeometry';

	this.parameters = {
		radius: radius,
		tube: tube,
		tubularSegments: tubularSegments,
		radialSegments: radialSegments,
		p: p,
		q: q
	};

	radius = radius || 1;
	tube = tube || 0.4;
	tubularSegments = Math.floor( tubularSegments ) || 64;
	radialSegments = Math.floor( radialSegments ) || 8;
	p = p || 2;
	q = q || 3;

	// buffers

	const indices = [];
	const vertices = [];
	const normals = [];
	const uvs = [];

	// helper variables

	const vertex = new Vector3();
	const normal = new Vector3();

	const P1 = new Vector3();
	const P2 = new Vector3();

	const B = new Vector3();
	const T = new Vector3();
	const N = new Vector3();

	// generate vertices, normals and uvs

	for ( let i = 0; i <= tubularSegments; ++ i ) {

		// the radian "u" is used to calculate the position on the torus curve of the current tubular segement

		const u = i / tubularSegments * p * Math.PI * 2;

		// now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
		// these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions

		calculatePositionOnCurve( u, p, q, radius, P1 );
		calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );

		// calculate orthonormal basis

		T.subVectors( P2, P1 );
		N.addVectors( P2, P1 );
		B.crossVectors( T, N );
		N.crossVectors( B, T );

		// normalize B, N. T can be ignored, we don't use it

		B.normalize();
		N.normalize();

		for ( let j = 0; j <= radialSegments; ++ j ) {

			// now calculate the vertices. they are nothing more than an extrusion of the torus curve.
			// because we extrude a shape in the xy-plane, there is no need to calculate a z-value.

			const v = j / radialSegments * Math.PI * 2;
			const cx = - tube * Math.cos( v );
			const cy = tube * Math.sin( v );

			// now calculate the final vertex position.
			// first we orient the extrusion with our basis vectos, then we add it to the current position on the curve

			vertex.x = P1.x + ( cx * N.x + cy * B.x );
			vertex.y = P1.y + ( cx * N.y + cy * B.y );
			vertex.z = P1.z + ( cx * N.z + cy * B.z );

			vertices.push( vertex.x, vertex.y, vertex.z );

			// normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)

			normal.subVectors( vertex, P1 ).normalize();

			normals.push( normal.x, normal.y, normal.z );

			// uv

			uvs.push( i / tubularSegments );
			uvs.push( j / radialSegments );

		}

	}

	// generate indices

	for ( let j = 1; j <= tubularSegments; j ++ ) {

		for ( let i = 1; i <= radialSegments; i ++ ) {

			// indices

			const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
			const b = ( radialSegments + 1 ) * j + ( i - 1 );
			const c = ( radialSegments + 1 ) * j + i;
			const d = ( radialSegments + 1 ) * ( j - 1 ) + i;

			// faces

			indices.push( a, b, d );
			indices.push( b, c, d );

		}

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	// this function calculates the current position on the torus curve

	function calculatePositionOnCurve( u, p, q, radius, position ) {

		const cu = Math.cos( u );
		const su = Math.sin( u );
		const quOverP = q / p * u;
		const cs = Math.cos( quOverP );

		position.x = radius * ( 2 + cs ) * 0.5 * cu;
		position.y = radius * ( 2 + cs ) * su * 0.5;
		position.z = radius * Math.sin( quOverP ) * 0.5;

	}

}

TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;

/**
 * @author oosmoxiecode
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / https://github.com/Mugen87
 */

// TorusGeometry

function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {

	Geometry.call( this );

	this.type = 'TorusGeometry';

	this.parameters = {
		radius: radius,
		tube: tube,
		radialSegments: radialSegments,
		tubularSegments: tubularSegments,
		arc: arc
	};

	this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
	this.mergeVertices();

}

TorusGeometry.prototype = Object.create( Geometry.prototype );
TorusGeometry.prototype.constructor = TorusGeometry;

// TorusBufferGeometry

function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {

	BufferGeometry.call( this );

	this.type = 'TorusBufferGeometry';

	this.parameters = {
		radius: radius,
		tube: tube,
		radialSegments: radialSegments,
		tubularSegments: tubularSegments,
		arc: arc
	};

	radius = radius || 1;
	tube = tube || 0.4;
	radialSegments = Math.floor( radialSegments ) || 8;
	tubularSegments = Math.floor( tubularSegments ) || 6;
	arc = arc || Math.PI * 2;

	// buffers

	const indices = [];
	const vertices = [];
	const normals = [];
	const uvs = [];

	// helper variables

	const center = new Vector3();
	const vertex = new Vector3();
	const normal = new Vector3();

	// generate vertices, normals and uvs

	for ( let j = 0; j <= radialSegments; j ++ ) {

		for ( let i = 0; i <= tubularSegments; i ++ ) {

			const u = i / tubularSegments * arc;
			const v = j / radialSegments * Math.PI * 2;

			// vertex

			vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
			vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
			vertex.z = tube * Math.sin( v );

			vertices.push( vertex.x, vertex.y, vertex.z );

			// normal

			center.x = radius * Math.cos( u );
			center.y = radius * Math.sin( u );
			normal.subVectors( vertex, center ).normalize();

			normals.push( normal.x, normal.y, normal.z );

			// uv

			uvs.push( i / tubularSegments );
			uvs.push( j / radialSegments );

		}

	}

	// generate indices

	for ( let j = 1; j <= radialSegments; j ++ ) {

		for ( let i = 1; i <= tubularSegments; i ++ ) {

			// indices

			const a = ( tubularSegments + 1 ) * j + i - 1;
			const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
			const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
			const d = ( tubularSegments + 1 ) * j + i;

			// faces

			indices.push( a, b, d );
			indices.push( b, c, d );

		}

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

}

TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;

/**
 * @author Mugen87 / https://github.com/Mugen87
 * Port from https://github.com/mapbox/earcut (v2.2.2)
 */

const Earcut = {

	triangulate: function ( data, holeIndices, dim ) {

		dim = dim || 2;

		let hasHoles = holeIndices && holeIndices.length,
			outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
			outerNode = linkedList( data, 0, outerLen, dim, true ),
			triangles = [];

		if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;

		let minX, minY, maxX, maxY, x, y, invSize;

		if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );

		// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
		if ( data.length > 80 * dim ) {

			minX = maxX = data[ 0 ];
			minY = maxY = data[ 1 ];

			for ( let i = dim; i < outerLen; i += dim ) {

				x = data[ i ];
				y = data[ i + 1 ];
				if ( x < minX ) minX = x;
				if ( y < minY ) minY = y;
				if ( x > maxX ) maxX = x;
				if ( y > maxY ) maxY = y;

			}

			// minX, minY and invSize are later used to transform coords into integers for z-order calculation
			invSize = Math.max( maxX - minX, maxY - minY );
			invSize = invSize !== 0 ? 1 / invSize : 0;

		}

		earcutLinked( outerNode, triangles, dim, minX, minY, invSize );

		return triangles;

	}

};

// create a circular doubly linked list from polygon points in the specified winding order
function linkedList( data, start, end, dim, clockwise ) {

	let i, last;

	if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {

		for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );

	} else {

		for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );

	}

	if ( last && equals( last, last.next ) ) {

		removeNode( last );
		last = last.next;

	}

	return last;

}

// eliminate colinear or duplicate points
function filterPoints( start, end ) {

	if ( ! start ) return start;
	if ( ! end ) end = start;

	let p = start,
		again;
	do {

		again = false;

		if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {

			removeNode( p );
			p = end = p.prev;
			if ( p === p.next ) break;
			again = true;

		} else {

			p = p.next;

		}

	} while ( again || p !== end );

	return end;

}

// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {

	if ( ! ear ) return;

	// interlink polygon nodes in z-order
	if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );

	let stop = ear,
		prev, next;

	// iterate through ears, slicing them one by one
	while ( ear.prev !== ear.next ) {

		prev = ear.prev;
		next = ear.next;

		if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {

			// cut off the triangle
			triangles.push( prev.i / dim );
			triangles.push( ear.i / dim );
			triangles.push( next.i / dim );

			removeNode( ear );

			// skipping the next vertex leads to less sliver triangles
			ear = next.next;
			stop = next.next;

			continue;

		}

		ear = next;

		// if we looped through the whole remaining polygon and can't find any more ears
		if ( ear === stop ) {

			// try filtering points and slicing again
			if ( ! pass ) {

				earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );

				// if this didn't work, try curing all small self-intersections locally

			} else if ( pass === 1 ) {

				ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
				earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );

				// as a last resort, try splitting the remaining polygon into two

			} else if ( pass === 2 ) {

				splitEarcut( ear, triangles, dim, minX, minY, invSize );

			}

			break;

		}

	}

}

// check whether a polygon node forms a valid ear with adjacent nodes
function isEar( ear ) {

	let a = ear.prev,
		b = ear,
		c = ear.next;

	if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear

	// now make sure we don't have other points inside the potential ear
	let p = ear.next.next;

	while ( p !== ear.prev ) {

		if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
			area( p.prev, p, p.next ) >= 0 ) return false;
		p = p.next;

	}

	return true;

}

function isEarHashed( ear, minX, minY, invSize ) {

	let a = ear.prev,
		b = ear,
		c = ear.next;

	if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear

	// triangle bbox; min & max are calculated like this for speed
	let minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
		minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
		maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
		maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );

	// z-order range for the current triangle bbox;
	let minZ = zOrder( minTX, minTY, minX, minY, invSize ),
		maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );

	let p = ear.prevZ,
		n = ear.nextZ;

	// look for points inside the triangle in both directions
	while ( p && p.z >= minZ && n && n.z <= maxZ ) {

		if ( p !== ear.prev && p !== ear.next &&
			pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
			area( p.prev, p, p.next ) >= 0 ) return false;
		p = p.prevZ;

		if ( n !== ear.prev && n !== ear.next &&
			pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
			area( n.prev, n, n.next ) >= 0 ) return false;
		n = n.nextZ;

	}

	// look for remaining points in decreasing z-order
	while ( p && p.z >= minZ ) {

		if ( p !== ear.prev && p !== ear.next &&
			pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
			area( p.prev, p, p.next ) >= 0 ) return false;
		p = p.prevZ;

	}

	// look for remaining points in increasing z-order
	while ( n && n.z <= maxZ ) {

		if ( n !== ear.prev && n !== ear.next &&
			pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
			area( n.prev, n, n.next ) >= 0 ) return false;
		n = n.nextZ;

	}

	return true;

}

// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections( start, triangles, dim ) {

	let p = start;
	do {

		let a = p.prev,
			b = p.next.next;

		if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {

			triangles.push( a.i / dim );
			triangles.push( p.i / dim );
			triangles.push( b.i / dim );

			// remove two nodes involved
			removeNode( p );
			removeNode( p.next );

			p = start = b;

		}

		p = p.next;

	} while ( p !== start );

	return filterPoints( p );

}

// try splitting polygon into two and triangulate them independently
function splitEarcut( start, triangles, dim, minX, minY, invSize ) {

	// look for a valid diagonal that divides the polygon into two
	let a = start;
	do {

		let b = a.next.next;
		while ( b !== a.prev ) {

			if ( a.i !== b.i && isValidDiagonal( a, b ) ) {

				// split the polygon in two by the diagonal
				let c = splitPolygon( a, b );

				// filter colinear points around the cuts
				a = filterPoints( a, a.next );
				c = filterPoints( c, c.next );

				// run earcut on each half
				earcutLinked( a, triangles, dim, minX, minY, invSize );
				earcutLinked( c, triangles, dim, minX, minY, invSize );
				return;

			}

			b = b.next;

		}

		a = a.next;

	} while ( a !== start );

}

// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles( data, holeIndices, outerNode, dim ) {

	let queue = [],
		i, len, start, end, list;

	for ( i = 0, len = holeIndices.length; i < len; i ++ ) {

		start = holeIndices[ i ] * dim;
		end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
		list = linkedList( data, start, end, dim, false );
		if ( list === list.next ) list.steiner = true;
		queue.push( getLeftmost( list ) );

	}

	queue.sort( compareX );

	// process holes from left to right
	for ( i = 0; i < queue.length; i ++ ) {

		eliminateHole( queue[ i ], outerNode );
		outerNode = filterPoints( outerNode, outerNode.next );

	}

	return outerNode;

}

function compareX( a, b ) {

	return a.x - b.x;

}

// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole( hole, outerNode ) {

	outerNode = findHoleBridge( hole, outerNode );
	if ( outerNode ) {

		const b = splitPolygon( outerNode, hole );

		// filter collinear points around the cuts
		filterPoints( outerNode, outerNode.next );
		filterPoints( b, b.next );

	}

}

// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge( hole, outerNode ) {

	let p = outerNode,
		hx = hole.x,
		hy = hole.y,
		qx = - Infinity,
		m;

	// find a segment intersected by a ray from the hole's leftmost point to the left;
	// segment's endpoint with lesser x will be potential connection point
	do {

		if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {

			let x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
			if ( x <= hx && x > qx ) {

				qx = x;
				if ( x === hx ) {

					if ( hy === p.y ) return p;
					if ( hy === p.next.y ) return p.next;

				}

				m = p.x < p.next.x ? p : p.next;

			}

		}

		p = p.next;

	} while ( p !== outerNode );

	if ( ! m ) return null;

	if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint

	// look for points inside the triangle of hole point, segment intersection and endpoint;
	// if there are no points found, we have a valid connection;
	// otherwise choose the point of the minimum angle with the ray as connection point

	let stop = m,
		mx = m.x,
		my = m.y,
		tanMin = Infinity,
		tan;

	p = m;

	do {

		if ( hx >= p.x && p.x >= mx && hx !== p.x &&
				pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {

			tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential

			if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {

				m = p;
				tanMin = tan;

			}

		}

		p = p.next;

	} while ( p !== stop );

	return m;

}

// whether sector in vertex m contains sector in vertex p in the same coordinates
function sectorContainsSector( m, p ) {

	return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;

}

// interlink polygon nodes in z-order
function indexCurve( start, minX, minY, invSize ) {

	let p = start;
	do {

		if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
		p.prevZ = p.prev;
		p.nextZ = p.next;
		p = p.next;

	} while ( p !== start );

	p.prevZ.nextZ = null;
	p.prevZ = null;

	sortLinked( p );

}

// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked( list ) {

	let i, p, q, e, tail, numMerges, pSize, qSize,
		inSize = 1;

	do {

		p = list;
		list = null;
		tail = null;
		numMerges = 0;

		while ( p ) {

			numMerges ++;
			q = p;
			pSize = 0;
			for ( i = 0; i < inSize; i ++ ) {

				pSize ++;
				q = q.nextZ;
				if ( ! q ) break;

			}

			qSize = inSize;

			while ( pSize > 0 || ( qSize > 0 && q ) ) {

				if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {

					e = p;
					p = p.nextZ;
					pSize --;

				} else {

					e = q;
					q = q.nextZ;
					qSize --;

				}

				if ( tail ) tail.nextZ = e;
				else list = e;

				e.prevZ = tail;
				tail = e;

			}

			p = q;

		}

		tail.nextZ = null;
		inSize *= 2;

	} while ( numMerges > 1 );

	return list;

}

// z-order of a point given coords and inverse of the longer side of data bbox
function zOrder( x, y, minX, minY, invSize ) {

	// coords are transformed into non-negative 15-bit integer range
	x = 32767 * ( x - minX ) * invSize;
	y = 32767 * ( y - minY ) * invSize;

	x = ( x | ( x << 8 ) ) & 0x00FF00FF;
	x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
	x = ( x | ( x << 2 ) ) & 0x33333333;
	x = ( x | ( x << 1 ) ) & 0x55555555;

	y = ( y | ( y << 8 ) ) & 0x00FF00FF;
	y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
	y = ( y | ( y << 2 ) ) & 0x33333333;
	y = ( y | ( y << 1 ) ) & 0x55555555;

	return x | ( y << 1 );

}

// find the leftmost node of a polygon ring
function getLeftmost( start ) {

	let p = start,
		leftmost = start;
	do {

		if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
		p = p.next;

	} while ( p !== start );

	return leftmost;

}

// check if a point lies within a convex triangle
function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {

	return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
			( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
			( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;

}

// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal( a, b ) {

	return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
		( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
		( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
		equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case

}

// signed area of a triangle
function area( p, q, r ) {

	return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );

}

// check if two points are equal
function equals( p1, p2 ) {

	return p1.x === p2.x && p1.y === p2.y;

}

// check if two segments intersect
function intersects( p1, q1, p2, q2 ) {

	const o1 = sign( area( p1, q1, p2 ) );
	const o2 = sign( area( p1, q1, q2 ) );
	const o3 = sign( area( p2, q2, p1 ) );
	const o4 = sign( area( p2, q2, q1 ) );

	if ( o1 !== o2 && o3 !== o4 ) return true; // general case

	if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
	if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
	if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
	if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2

	return false;

}

// for collinear points p, q, r, check if point q lies on segment pr
function onSegment( p, q, r ) {

	return q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );

}

function sign( num ) {

	return num > 0 ? 1 : num < 0 ? - 1 : 0;

}

// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon( a, b ) {

	let p = a;
	do {

		if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
				intersects( p, p.next, a, b ) ) return true;
		p = p.next;

	} while ( p !== a );

	return false;

}

// check if a polygon diagonal is locally inside the polygon
function locallyInside( a, b ) {

	return area( a.prev, a, a.next ) < 0 ?
		area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
		area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;

}

// check if the middle point of a polygon diagonal is inside the polygon
function middleInside( a, b ) {

	let p = a,
		inside = false,
		px = ( a.x + b.x ) / 2,
		py = ( a.y + b.y ) / 2;
	do {

		if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
				( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
			inside = ! inside;
		p = p.next;

	} while ( p !== a );

	return inside;

}

// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon( a, b ) {

	let a2 = new Node( a.i, a.x, a.y ),
		b2 = new Node( b.i, b.x, b.y ),
		an = a.next,
		bp = b.prev;

	a.next = b;
	b.prev = a;

	a2.next = an;
	an.prev = a2;

	b2.next = a2;
	a2.prev = b2;

	bp.next = b2;
	b2.prev = bp;

	return b2;

}

// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode( i, x, y, last ) {

	const p = new Node( i, x, y );

	if ( ! last ) {

		p.prev = p;
		p.next = p;

	} else {

		p.next = last.next;
		p.prev = last;
		last.next.prev = p;
		last.next = p;

	}

	return p;

}

function removeNode( p ) {

	p.next.prev = p.prev;
	p.prev.next = p.next;

	if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
	if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;

}

function Node( i, x, y ) {

	// vertex index in coordinates array
	this.i = i;

	// vertex coordinates
	this.x = x;
	this.y = y;

	// previous and next vertex nodes in a polygon ring
	this.prev = null;
	this.next = null;

	// z-order curve value
	this.z = null;

	// previous and next nodes in z-order
	this.prevZ = null;
	this.nextZ = null;

	// indicates whether this is a steiner point
	this.steiner = false;

}

function signedArea( data, start, end, dim ) {

	let sum = 0;
	for ( let i = start, j = end - dim; i < end; i += dim ) {

		sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
		j = i;

	}

	return sum;

}

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 */

const ShapeUtils = {

	// calculate area of the contour polygon

	area: function ( contour ) {

		const n = contour.length;
		let a = 0.0;

		for ( let p = n - 1, q = 0; q < n; p = q ++ ) {

			a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;

		}

		return a * 0.5;

	},

	isClockWise: function ( pts ) {

		return ShapeUtils.area( pts ) < 0;

	},

	triangulateShape: function ( contour, holes ) {

		const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
		const holeIndices = []; // array of hole indices
		const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]

		removeDupEndPts( contour );
		addContour( vertices, contour );

		//

		let holeIndex = contour.length;

		holes.forEach( removeDupEndPts );

		for ( let i = 0; i < holes.length; i ++ ) {

			holeIndices.push( holeIndex );
			holeIndex += holes[ i ].length;
			addContour( vertices, holes[ i ] );

		}

		//

		const triangles = Earcut.triangulate( vertices, holeIndices );

		//

		for ( let i = 0; i < triangles.length; i += 3 ) {

			faces.push( triangles.slice( i, i + 3 ) );

		}

		return faces;

	}

};

function removeDupEndPts( points ) {

	const l = points.length;

	if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {

		points.pop();

	}

}

function addContour( vertices, contour ) {

	for ( let i = 0; i < contour.length; i ++ ) {

		vertices.push( contour[ i ].x );
		vertices.push( contour[ i ].y );

	}

}

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 *
 * Creates extruded geometry from a path shape.
 *
 * parameters = {
 *
 *  curveSegments: <int>, // number of points on the curves
 *  steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
 *  depth: <float>, // Depth to extrude the shape
 *
 *  bevelEnabled: <bool>, // turn on bevel
 *  bevelThickness: <float>, // how deep into the original shape bevel goes
 *  bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
 *  bevelOffset: <float>, // how far from shape outline does bevel start
 *  bevelSegments: <int>, // number of bevel layers
 *
 *  extrudePath: <THREE.Curve> // curve to extrude shape along
 *
 *  UVGenerator: <Object> // object that provides UV generator functions
 *
 * }
 */

// ExtrudeGeometry

function ExtrudeGeometry( shapes, options ) {

	Geometry.call( this );

	this.type = 'ExtrudeGeometry';

	this.parameters = {
		shapes: shapes,
		options: options
	};

	this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
	this.mergeVertices();

}

ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;

ExtrudeGeometry.prototype.toJSON = function () {

	const data = Geometry.prototype.toJSON.call( this );

	const shapes = this.parameters.shapes;
	const options = this.parameters.options;

	return toJSON( shapes, options, data );

};

// ExtrudeBufferGeometry

function ExtrudeBufferGeometry( shapes, options ) {

	BufferGeometry.call( this );

	this.type = 'ExtrudeBufferGeometry';

	this.parameters = {
		shapes: shapes,
		options: options
	};

	shapes = Array.isArray( shapes ) ? shapes : [ shapes ];

	const scope = this;

	const verticesArray = [];
	const uvArray = [];

	for ( let i = 0, l = shapes.length; i < l; i ++ ) {

		const shape = shapes[ i ];
		addShape( shape );

	}

	// build geometry

	this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );

	this.computeVertexNormals();

	// functions

	function addShape( shape ) {

		const placeholder = [];

		// options

		const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
		const steps = options.steps !== undefined ? options.steps : 1;
		let depth = options.depth !== undefined ? options.depth : 100;

		let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
		let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
		let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
		let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
		let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;

		const extrudePath = options.extrudePath;

		const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;

		// deprecated options

		if ( options.amount !== undefined ) {

			console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
			depth = options.amount;

		}

		//

		let extrudePts, extrudeByPath = false;
		let splineTube, binormal, normal, position2;

		if ( extrudePath ) {

			extrudePts = extrudePath.getSpacedPoints( steps );

			extrudeByPath = true;
			bevelEnabled = false; // bevels not supported for path extrusion

			// SETUP TNB variables

			// TODO1 - have a .isClosed in spline?

			splineTube = extrudePath.computeFrenetFrames( steps, false );

			// console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);

			binormal = new Vector3();
			normal = new Vector3();
			position2 = new Vector3();

		}

		// Safeguards if bevels are not enabled

		if ( ! bevelEnabled ) {

			bevelSegments = 0;
			bevelThickness = 0;
			bevelSize = 0;
			bevelOffset = 0;

		}

		// Variables initialization

		const shapePoints = shape.extractPoints( curveSegments );

		let vertices = shapePoints.shape;
		const holes = shapePoints.holes;

		const reverse = ! ShapeUtils.isClockWise( vertices );

		if ( reverse ) {

			vertices = vertices.reverse();

			// Maybe we should also check if holes are in the opposite direction, just to be safe ...

			for ( let h = 0, hl = holes.length; h < hl; h ++ ) {

				const ahole = holes[ h ];

				if ( ShapeUtils.isClockWise( ahole ) ) {

					holes[ h ] = ahole.reverse();

				}

			}

		}


		const faces = ShapeUtils.triangulateShape( vertices, holes );

		/* Vertices */

		const contour = vertices; // vertices has all points but contour has only points of circumference

		for ( let h = 0, hl = holes.length; h < hl; h ++ ) {

			const ahole = holes[ h ];

			vertices = vertices.concat( ahole );

		}


		function scalePt2( pt, vec, size ) {

			if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );

			return vec.clone().multiplyScalar( size ).add( pt );

		}

		const vlen = vertices.length, flen = faces.length;


		// Find directions for point movement


		function getBevelVec( inPt, inPrev, inNext ) {

			// computes for inPt the corresponding point inPt' on a new contour
			//   shifted by 1 unit (length of normalized vector) to the left
			// if we walk along contour clockwise, this new contour is outside the old one
			//
			// inPt' is the intersection of the two lines parallel to the two
			//  adjacent edges of inPt at a distance of 1 unit on the left side.

			let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt

			// good reading for geometry algorithms (here: line-line intersection)
			// http://geomalgorithms.com/a05-_intersect-1.html

			const v_prev_x = inPt.x - inPrev.x,
				v_prev_y = inPt.y - inPrev.y;
			const v_next_x = inNext.x - inPt.x,
				v_next_y = inNext.y - inPt.y;

			const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );

			// check for collinear edges
			const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );

			if ( Math.abs( collinear0 ) > Number.EPSILON ) {

				// not collinear

				// length of vectors for normalizing

				const v_prev_len = Math.sqrt( v_prev_lensq );
				const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );

				// shift adjacent points by unit vectors to the left

				const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
				const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );

				const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
				const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );

				// scaling factor for v_prev to intersection point

				const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
						( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
					( v_prev_x * v_next_y - v_prev_y * v_next_x );

				// vector from inPt to intersection point

				v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
				v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );

				// Don't normalize!, otherwise sharp corners become ugly
				//  but prevent crazy spikes
				const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
				if ( v_trans_lensq <= 2 ) {

					return new Vector2( v_trans_x, v_trans_y );

				} else {

					shrink_by = Math.sqrt( v_trans_lensq / 2 );

				}

			} else {

				// handle special case of collinear edges

				let direction_eq = false; // assumes: opposite

				if ( v_prev_x > Number.EPSILON ) {

					if ( v_next_x > Number.EPSILON ) {

						direction_eq = true;

					}

				} else {

					if ( v_prev_x < - Number.EPSILON ) {

						if ( v_next_x < - Number.EPSILON ) {

							direction_eq = true;

						}

					} else {

						if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {

							direction_eq = true;

						}

					}

				}

				if ( direction_eq ) {

					// console.log("Warning: lines are a straight sequence");
					v_trans_x = - v_prev_y;
					v_trans_y = v_prev_x;
					shrink_by = Math.sqrt( v_prev_lensq );

				} else {

					// console.log("Warning: lines are a straight spike");
					v_trans_x = v_prev_x;
					v_trans_y = v_prev_y;
					shrink_by = Math.sqrt( v_prev_lensq / 2 );

				}

			}

			return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );

		}


		const contourMovements = [];

		for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {

			if ( j === il ) j = 0;
			if ( k === il ) k = 0;

			//  (j)---(i)---(k)
			// console.log('i,j,k', i, j , k)

			contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );

		}

		const holesMovements = [];
		let oneHoleMovements, verticesMovements = contourMovements.concat();

		for ( let h = 0, hl = holes.length; h < hl; h ++ ) {

			const ahole = holes[ h ];

			oneHoleMovements = [];

			for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {

				if ( j === il ) j = 0;
				if ( k === il ) k = 0;

				//  (j)---(i)---(k)
				oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );

			}

			holesMovements.push( oneHoleMovements );
			verticesMovements = verticesMovements.concat( oneHoleMovements );

		}


		// Loop bevelSegments, 1 for the front, 1 for the back

		for ( let b = 0; b < bevelSegments; b ++ ) {

			//for ( b = bevelSegments; b > 0; b -- ) {

			const t = b / bevelSegments;
			const z = bevelThickness * Math.cos( t * Math.PI / 2 );
			const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;

			// contract shape

			for ( let i = 0, il = contour.length; i < il; i ++ ) {

				const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );

				v( vert.x, vert.y, - z );

			}

			// expand holes

			for ( let h = 0, hl = holes.length; h < hl; h ++ ) {

				const ahole = holes[ h ];
				oneHoleMovements = holesMovements[ h ];

				for ( let i = 0, il = ahole.length; i < il; i ++ ) {

					const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );

					v( vert.x, vert.y, - z );

				}

			}

		}

		const bs = bevelSize + bevelOffset;

		// Back facing vertices

		for ( let i = 0; i < vlen; i ++ ) {

			const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];

			if ( ! extrudeByPath ) {

				v( vert.x, vert.y, 0 );

			} else {

				// v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );

				normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
				binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );

				position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );

				v( position2.x, position2.y, position2.z );

			}

		}

		// Add stepped vertices...
		// Including front facing vertices

		for ( let s = 1; s <= steps; s ++ ) {

			for ( let i = 0; i < vlen; i ++ ) {

				const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];

				if ( ! extrudeByPath ) {

					v( vert.x, vert.y, depth / steps * s );

				} else {

					// v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );

					normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
					binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );

					position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );

					v( position2.x, position2.y, position2.z );

				}

			}

		}


		// Add bevel segments planes

		//for ( b = 1; b <= bevelSegments; b ++ ) {
		for ( let b = bevelSegments - 1; b >= 0; b -- ) {

			const t = b / bevelSegments;
			const z = bevelThickness * Math.cos( t * Math.PI / 2 );
			const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;

			// contract shape

			for ( let i = 0, il = contour.length; i < il; i ++ ) {

				const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
				v( vert.x, vert.y, depth + z );

			}

			// expand holes

			for ( let h = 0, hl = holes.length; h < hl; h ++ ) {

				const ahole = holes[ h ];
				oneHoleMovements = holesMovements[ h ];

				for ( let i = 0, il = ahole.length; i < il; i ++ ) {

					const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );

					if ( ! extrudeByPath ) {

						v( vert.x, vert.y, depth + z );

					} else {

						v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );

					}

				}

			}

		}

		/* Faces */

		// Top and bottom faces

		buildLidFaces();

		// Sides faces

		buildSideFaces();


		/////  Internal functions

		function buildLidFaces() {

			const start = verticesArray.length / 3;

			if ( bevelEnabled ) {

				let layer = 0; // steps + 1
				let offset = vlen * layer;

				// Bottom faces

				for ( let i = 0; i < flen; i ++ ) {

					const face = faces[ i ];
					f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );

				}

				layer = steps + bevelSegments * 2;
				offset = vlen * layer;

				// Top faces

				for ( let i = 0; i < flen; i ++ ) {

					const face = faces[ i ];
					f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );

				}

			} else {

				// Bottom faces

				for ( let i = 0; i < flen; i ++ ) {

					const face = faces[ i ];
					f3( face[ 2 ], face[ 1 ], face[ 0 ] );

				}

				// Top faces

				for ( let i = 0; i < flen; i ++ ) {

					const face = faces[ i ];
					f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );

				}

			}

			scope.addGroup( start, verticesArray.length / 3 - start, 0 );

		}

		// Create faces for the z-sides of the shape

		function buildSideFaces() {

			const start = verticesArray.length / 3;
			let layeroffset = 0;
			sidewalls( contour, layeroffset );
			layeroffset += contour.length;

			for ( let h = 0, hl = holes.length; h < hl; h ++ ) {

				const ahole = holes[ h ];
				sidewalls( ahole, layeroffset );

				//, true
				layeroffset += ahole.length;

			}


			scope.addGroup( start, verticesArray.length / 3 - start, 1 );


		}

		function sidewalls( contour, layeroffset ) {

			let i = contour.length;

			while ( -- i >= 0 ) {

				const j = i;
				let k = i - 1;
				if ( k < 0 ) k = contour.length - 1;

				//console.log('b', i,j, i-1, k,vertices.length);

				for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {

					const slen1 = vlen * s;
					const slen2 = vlen * ( s + 1 );

					const a = layeroffset + j + slen1,
						b = layeroffset + k + slen1,
						c = layeroffset + k + slen2,
						d = layeroffset + j + slen2;

					f4( a, b, c, d );

				}

			}

		}

		function v( x, y, z ) {

			placeholder.push( x );
			placeholder.push( y );
			placeholder.push( z );

		}


		function f3( a, b, c ) {

			addVertex( a );
			addVertex( b );
			addVertex( c );

			const nextIndex = verticesArray.length / 3;
			const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );

			addUV( uvs[ 0 ] );
			addUV( uvs[ 1 ] );
			addUV( uvs[ 2 ] );

		}

		function f4( a, b, c, d ) {

			addVertex( a );
			addVertex( b );
			addVertex( d );

			addVertex( b );
			addVertex( c );
			addVertex( d );


			const nextIndex = verticesArray.length / 3;
			const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );

			addUV( uvs[ 0 ] );
			addUV( uvs[ 1 ] );
			addUV( uvs[ 3 ] );

			addUV( uvs[ 1 ] );
			addUV( uvs[ 2 ] );
			addUV( uvs[ 3 ] );

		}

		function addVertex( index ) {

			verticesArray.push( placeholder[ index * 3 + 0 ] );
			verticesArray.push( placeholder[ index * 3 + 1 ] );
			verticesArray.push( placeholder[ index * 3 + 2 ] );

		}


		function addUV( vector2 ) {

			uvArray.push( vector2.x );
			uvArray.push( vector2.y );

		}

	}

}

ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;

ExtrudeBufferGeometry.prototype.toJSON = function () {

	const data = BufferGeometry.prototype.toJSON.call( this );

	const shapes = this.parameters.shapes;
	const options = this.parameters.options;

	return toJSON( shapes, options, data );

};

//

const WorldUVGenerator = {

	generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {

		const a_x = vertices[ indexA * 3 ];
		const a_y = vertices[ indexA * 3 + 1 ];
		const b_x = vertices[ indexB * 3 ];
		const b_y = vertices[ indexB * 3 + 1 ];
		const c_x = vertices[ indexC * 3 ];
		const c_y = vertices[ indexC * 3 + 1 ];

		return [
			new Vector2( a_x, a_y ),
			new Vector2( b_x, b_y ),
			new Vector2( c_x, c_y )
		];

	},

	generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {

		const a_x = vertices[ indexA * 3 ];
		const a_y = vertices[ indexA * 3 + 1 ];
		const a_z = vertices[ indexA * 3 + 2 ];
		const b_x = vertices[ indexB * 3 ];
		const b_y = vertices[ indexB * 3 + 1 ];
		const b_z = vertices[ indexB * 3 + 2 ];
		const c_x = vertices[ indexC * 3 ];
		const c_y = vertices[ indexC * 3 + 1 ];
		const c_z = vertices[ indexC * 3 + 2 ];
		const d_x = vertices[ indexD * 3 ];
		const d_y = vertices[ indexD * 3 + 1 ];
		const d_z = vertices[ indexD * 3 + 2 ];

		if ( Math.abs( a_y - b_y ) < 0.01 ) {

			return [
				new Vector2( a_x, 1 - a_z ),
				new Vector2( b_x, 1 - b_z ),
				new Vector2( c_x, 1 - c_z ),
				new Vector2( d_x, 1 - d_z )
			];

		} else {

			return [
				new Vector2( a_y, 1 - a_z ),
				new Vector2( b_y, 1 - b_z ),
				new Vector2( c_y, 1 - c_z ),
				new Vector2( d_y, 1 - d_z )
			];

		}

	}
};

function toJSON( shapes, options, data ) {

	//

	data.shapes = [];

	if ( Array.isArray( shapes ) ) {

		for ( let i = 0, l = shapes.length; i < l; i ++ ) {

			const shape = shapes[ i ];

			data.shapes.push( shape.uuid );

		}

	} else {

		data.shapes.push( shapes.uuid );

	}

	//

	if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();

	return data;

}

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * @author alteredq / http://alteredqualia.com/
 *
 * Text = 3D Text
 *
 * parameters = {
 *  font: <THREE.Font>, // font
 *
 *  size: <float>, // size of the text
 *  height: <float>, // thickness to extrude text
 *  curveSegments: <int>, // number of points on the curves
 *
 *  bevelEnabled: <bool>, // turn on bevel
 *  bevelThickness: <float>, // how deep into text bevel goes
 *  bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
 *  bevelOffset: <float> // how far from text outline does bevel start
 * }
 */

// TextGeometry

function TextGeometry( text, parameters ) {

	Geometry.call( this );

	this.type = 'TextGeometry';

	this.parameters = {
		text: text,
		parameters: parameters
	};

	this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
	this.mergeVertices();

}

TextGeometry.prototype = Object.create( Geometry.prototype );
TextGeometry.prototype.constructor = TextGeometry;

// TextBufferGeometry

function TextBufferGeometry( text, parameters ) {

	parameters = parameters || {};

	const font = parameters.font;

	if ( ! ( font && font.isFont ) ) {

		console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
		return new Geometry();

	}

	const shapes = font.generateShapes( text, parameters.size );

	// translate parameters to ExtrudeGeometry API

	parameters.depth = parameters.height !== undefined ? parameters.height : 50;

	// defaults

	if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
	if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
	if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;

	ExtrudeBufferGeometry.call( this, shapes, parameters );

	this.type = 'TextBufferGeometry';

}

TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
TextBufferGeometry.prototype.constructor = TextBufferGeometry;

/**
 * @author mrdoob / http://mrdoob.com/
 * @author benaadams / https://twitter.com/ben_a_adams
 * @author Mugen87 / https://github.com/Mugen87
 */

// SphereGeometry

function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {

	Geometry.call( this );

	this.type = 'SphereGeometry';

	this.parameters = {
		radius: radius,
		widthSegments: widthSegments,
		heightSegments: heightSegments,
		phiStart: phiStart,
		phiLength: phiLength,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
	this.mergeVertices();

}

SphereGeometry.prototype = Object.create( Geometry.prototype );
SphereGeometry.prototype.constructor = SphereGeometry;

// SphereBufferGeometry

function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {

	BufferGeometry.call( this );

	this.type = 'SphereBufferGeometry';

	this.parameters = {
		radius: radius,
		widthSegments: widthSegments,
		heightSegments: heightSegments,
		phiStart: phiStart,
		phiLength: phiLength,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	radius = radius || 1;

	widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
	heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );

	phiStart = phiStart !== undefined ? phiStart : 0;
	phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;

	thetaStart = thetaStart !== undefined ? thetaStart : 0;
	thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;

	const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );

	let index = 0;
	const grid = [];

	const vertex = new Vector3();
	const normal = new Vector3();

	// buffers

	const indices = [];
	const vertices = [];
	const normals = [];
	const uvs = [];

	// generate vertices, normals and uvs

	for ( let iy = 0; iy <= heightSegments; iy ++ ) {

		const verticesRow = [];

		const v = iy / heightSegments;

		// special case for the poles

		let uOffset = 0;

		if ( iy == 0 && thetaStart == 0 ) {

			uOffset = 0.5 / widthSegments;

		} else if ( iy == heightSegments && thetaEnd == Math.PI ) {

			uOffset = - 0.5 / widthSegments;

		}

		for ( let ix = 0; ix <= widthSegments; ix ++ ) {

			const u = ix / widthSegments;

			// vertex

			vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
			vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
			vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );

			vertices.push( vertex.x, vertex.y, vertex.z );

			// normal

			normal.copy( vertex ).normalize();
			normals.push( normal.x, normal.y, normal.z );

			// uv

			uvs.push( u + uOffset, 1 - v );

			verticesRow.push( index ++ );

		}

		grid.push( verticesRow );

	}

	// indices

	for ( let iy = 0; iy < heightSegments; iy ++ ) {

		for ( let ix = 0; ix < widthSegments; ix ++ ) {

			const a = grid[ iy ][ ix + 1 ];
			const b = grid[ iy ][ ix ];
			const c = grid[ iy + 1 ][ ix ];
			const d = grid[ iy + 1 ][ ix + 1 ];

			if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
			if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );

		}

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

}

SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;

/**
 * @author Kaleb Murphy
 * @author Mugen87 / https://github.com/Mugen87
 */

// RingGeometry

function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {

	Geometry.call( this );

	this.type = 'RingGeometry';

	this.parameters = {
		innerRadius: innerRadius,
		outerRadius: outerRadius,
		thetaSegments: thetaSegments,
		phiSegments: phiSegments,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
	this.mergeVertices();

}

RingGeometry.prototype = Object.create( Geometry.prototype );
RingGeometry.prototype.constructor = RingGeometry;

// RingBufferGeometry

function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {

	BufferGeometry.call( this );

	this.type = 'RingBufferGeometry';

	this.parameters = {
		innerRadius: innerRadius,
		outerRadius: outerRadius,
		thetaSegments: thetaSegments,
		phiSegments: phiSegments,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	innerRadius = innerRadius || 0.5;
	outerRadius = outerRadius || 1;

	thetaStart = thetaStart !== undefined ? thetaStart : 0;
	thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;

	thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
	phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;

	// buffers

	const indices = [];
	const vertices = [];
	const normals = [];
	const uvs = [];

	// some helper variables

	let radius = innerRadius;
	const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
	const vertex = new Vector3();
	const uv = new Vector2();

	// generate vertices, normals and uvs

	for ( let j = 0; j <= phiSegments; j ++ ) {

		for ( let i = 0; i <= thetaSegments; i ++ ) {

			// values are generate from the inside of the ring to the outside

			const segment = thetaStart + i / thetaSegments * thetaLength;

			// vertex

			vertex.x = radius * Math.cos( segment );
			vertex.y = radius * Math.sin( segment );

			vertices.push( vertex.x, vertex.y, vertex.z );

			// normal

			normals.push( 0, 0, 1 );

			// uv

			uv.x = ( vertex.x / outerRadius + 1 ) / 2;
			uv.y = ( vertex.y / outerRadius + 1 ) / 2;

			uvs.push( uv.x, uv.y );

		}

		// increase the radius for next row of vertices

		radius += radiusStep;

	}

	// indices

	for ( let j = 0; j < phiSegments; j ++ ) {

		const thetaSegmentLevel = j * ( thetaSegments + 1 );

		for ( let i = 0; i < thetaSegments; i ++ ) {

			const segment = i + thetaSegmentLevel;

			const a = segment;
			const b = segment + thetaSegments + 1;
			const c = segment + thetaSegments + 2;
			const d = segment + 1;

			// faces

			indices.push( a, b, d );
			indices.push( b, c, d );

		}

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

}

RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
RingBufferGeometry.prototype.constructor = RingBufferGeometry;

/**
 * @author zz85 / https://github.com/zz85
 * @author bhouston / http://clara.io
 * @author Mugen87 / https://github.com/Mugen87
 */

// LatheGeometry

function LatheGeometry( points, segments, phiStart, phiLength ) {

	Geometry.call( this );

	this.type = 'LatheGeometry';

	this.parameters = {
		points: points,
		segments: segments,
		phiStart: phiStart,
		phiLength: phiLength
	};

	this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
	this.mergeVertices();

}

LatheGeometry.prototype = Object.create( Geometry.prototype );
LatheGeometry.prototype.constructor = LatheGeometry;

// LatheBufferGeometry

function LatheBufferGeometry( points, segments, phiStart, phiLength ) {

	BufferGeometry.call( this );

	this.type = 'LatheBufferGeometry';

	this.parameters = {
		points: points,
		segments: segments,
		phiStart: phiStart,
		phiLength: phiLength
	};

	segments = Math.floor( segments ) || 12;
	phiStart = phiStart || 0;
	phiLength = phiLength || Math.PI * 2;

	// clamp phiLength so it's in range of [ 0, 2PI ]

	phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );


	// buffers

	const indices = [];
	const vertices = [];
	const uvs = [];

	// helper variables

	const inverseSegments = 1.0 / segments;
	const vertex = new Vector3();
	const uv = new Vector2();

	// generate vertices and uvs

	for ( let i = 0; i <= segments; i ++ ) {

		const phi = phiStart + i * inverseSegments * phiLength;

		const sin = Math.sin( phi );
		const cos = Math.cos( phi );

		for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {

			// vertex

			vertex.x = points[ j ].x * sin;
			vertex.y = points[ j ].y;
			vertex.z = points[ j ].x * cos;

			vertices.push( vertex.x, vertex.y, vertex.z );

			// uv

			uv.x = i / segments;
			uv.y = j / ( points.length - 1 );

			uvs.push( uv.x, uv.y );


		}

	}

	// indices

	for ( let i = 0; i < segments; i ++ ) {

		for ( let j = 0; j < ( points.length - 1 ); j ++ ) {

			const base = j + i * points.length;

			const a = base;
			const b = base + points.length;
			const c = base + points.length + 1;
			const d = base + 1;

			// faces

			indices.push( a, b, d );
			indices.push( b, c, d );

		}

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	// generate normals

	this.computeVertexNormals();

	// if the geometry is closed, we need to average the normals along the seam.
	// because the corresponding vertices are identical (but still have different UVs).

	if ( phiLength === Math.PI * 2 ) {

		const normals = this.attributes.normal.array;
		const n1 = new Vector3();
		const n2 = new Vector3();
		const n = new Vector3();

		// this is the buffer offset for the last line of vertices

		const base = segments * points.length * 3;

		for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {

			// select the normal of the vertex in the first line

			n1.x = normals[ j + 0 ];
			n1.y = normals[ j + 1 ];
			n1.z = normals[ j + 2 ];

			// select the normal of the vertex in the last line

			n2.x = normals[ base + j + 0 ];
			n2.y = normals[ base + j + 1 ];
			n2.z = normals[ base + j + 2 ];

			// average normals

			n.addVectors( n1, n2 ).normalize();

			// assign the new values to both normals

			normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
			normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
			normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;

		}

	}

}

LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;

/**
 * @author jonobr1 / http://jonobr1.com
 * @author Mugen87 / https://github.com/Mugen87
 */

// ShapeGeometry

function ShapeGeometry( shapes, curveSegments ) {

	Geometry.call( this );

	this.type = 'ShapeGeometry';

	if ( typeof curveSegments === 'object' ) {

		console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );

		curveSegments = curveSegments.curveSegments;

	}

	this.parameters = {
		shapes: shapes,
		curveSegments: curveSegments
	};

	this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
	this.mergeVertices();

}

ShapeGeometry.prototype = Object.create( Geometry.prototype );
ShapeGeometry.prototype.constructor = ShapeGeometry;

ShapeGeometry.prototype.toJSON = function () {

	const data = Geometry.prototype.toJSON.call( this );

	const shapes = this.parameters.shapes;

	return toJSON$1( shapes, data );

};

// ShapeBufferGeometry

function ShapeBufferGeometry( shapes, curveSegments ) {

	BufferGeometry.call( this );

	this.type = 'ShapeBufferGeometry';

	this.parameters = {
		shapes: shapes,
		curveSegments: curveSegments
	};

	curveSegments = curveSegments || 12;

	// buffers

	const indices = [];
	const vertices = [];
	const normals = [];
	const uvs = [];

	// helper variables

	let groupStart = 0;
	let groupCount = 0;

	// allow single and array values for "shapes" parameter

	if ( Array.isArray( shapes ) === false ) {

		addShape( shapes );

	} else {

		for ( let i = 0; i < shapes.length; i ++ ) {

			addShape( shapes[ i ] );

			this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support

			groupStart += groupCount;
			groupCount = 0;

		}

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );


	// helper functions

	function addShape( shape ) {

		const indexOffset = vertices.length / 3;
		const points = shape.extractPoints( curveSegments );

		let shapeVertices = points.shape;
		const shapeHoles = points.holes;

		// check direction of vertices

		if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {

			shapeVertices = shapeVertices.reverse();

		}

		for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {

			const shapeHole = shapeHoles[ i ];

			if ( ShapeUtils.isClockWise( shapeHole ) === true ) {

				shapeHoles[ i ] = shapeHole.reverse();

			}

		}

		const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );

		// join vertices of inner and outer paths to a single array

		for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {

			const shapeHole = shapeHoles[ i ];
			shapeVertices = shapeVertices.concat( shapeHole );

		}

		// vertices, normals, uvs

		for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {

			const vertex = shapeVertices[ i ];

			vertices.push( vertex.x, vertex.y, 0 );
			normals.push( 0, 0, 1 );
			uvs.push( vertex.x, vertex.y ); // world uvs

		}

		// incides

		for ( let i = 0, l = faces.length; i < l; i ++ ) {

			const face = faces[ i ];

			const a = face[ 0 ] + indexOffset;
			const b = face[ 1 ] + indexOffset;
			const c = face[ 2 ] + indexOffset;

			indices.push( a, b, c );
			groupCount += 3;

		}

	}

}

ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;

ShapeBufferGeometry.prototype.toJSON = function () {

	const data = BufferGeometry.prototype.toJSON.call( this );

	const shapes = this.parameters.shapes;

	return toJSON$1( shapes, data );

};

//

function toJSON$1( shapes, data ) {

	data.shapes = [];

	if ( Array.isArray( shapes ) ) {

		for ( let i = 0, l = shapes.length; i < l; i ++ ) {

			const shape = shapes[ i ];

			data.shapes.push( shape.uuid );

		}

	} else {

		data.shapes.push( shapes.uuid );

	}

	return data;

}

/**
 * @author WestLangley / http://github.com/WestLangley
 * @author Mugen87 / https://github.com/Mugen87
 */

function EdgesGeometry( geometry, thresholdAngle ) {

	BufferGeometry.call( this );

	this.type = 'EdgesGeometry';

	this.parameters = {
		thresholdAngle: thresholdAngle
	};

	thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;

	// buffer

	const vertices = [];

	// helper variables

	const thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
	const edge = [ 0, 0 ], edges = {};
	let edge1, edge2, key;
	const keys = [ 'a', 'b', 'c' ];

	// prepare source geometry

	let geometry2;

	if ( geometry.isBufferGeometry ) {

		geometry2 = new Geometry();
		geometry2.fromBufferGeometry( geometry );

	} else {

		geometry2 = geometry.clone();

	}

	geometry2.mergeVertices();
	geometry2.computeFaceNormals();

	const sourceVertices = geometry2.vertices;
	const faces = geometry2.faces;

	// now create a data structure where each entry represents an edge with its adjoining faces

	for ( let i = 0, l = faces.length; i < l; i ++ ) {

		const face = faces[ i ];

		for ( let j = 0; j < 3; j ++ ) {

			edge1 = face[ keys[ j ] ];
			edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
			edge[ 0 ] = Math.min( edge1, edge2 );
			edge[ 1 ] = Math.max( edge1, edge2 );

			key = edge[ 0 ] + ',' + edge[ 1 ];

			if ( edges[ key ] === undefined ) {

				edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };

			} else {

				edges[ key ].face2 = i;

			}

		}

	}

	// generate vertices

	for ( key in edges ) {

		const e = edges[ key ];

		// an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.

		if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {

			let vertex = sourceVertices[ e.index1 ];
			vertices.push( vertex.x, vertex.y, vertex.z );

			vertex = sourceVertices[ e.index2 ];
			vertices.push( vertex.x, vertex.y, vertex.z );

		}

	}

	// build geometry

	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );

}

EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
EdgesGeometry.prototype.constructor = EdgesGeometry;

/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / https://github.com/Mugen87
 */

// CylinderGeometry

function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

	Geometry.call( this );

	this.type = 'CylinderGeometry';

	this.parameters = {
		radiusTop: radiusTop,
		radiusBottom: radiusBottom,
		height: height,
		radialSegments: radialSegments,
		heightSegments: heightSegments,
		openEnded: openEnded,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
	this.mergeVertices();

}

CylinderGeometry.prototype = Object.create( Geometry.prototype );
CylinderGeometry.prototype.constructor = CylinderGeometry;

// CylinderBufferGeometry

function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

	BufferGeometry.call( this );

	this.type = 'CylinderBufferGeometry';

	this.parameters = {
		radiusTop: radiusTop,
		radiusBottom: radiusBottom,
		height: height,
		radialSegments: radialSegments,
		heightSegments: heightSegments,
		openEnded: openEnded,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	const scope = this;

	radiusTop = radiusTop !== undefined ? radiusTop : 1;
	radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
	height = height || 1;

	radialSegments = Math.floor( radialSegments ) || 8;
	heightSegments = Math.floor( heightSegments ) || 1;

	openEnded = openEnded !== undefined ? openEnded : false;
	thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
	thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;

	// buffers

	const indices = [];
	const vertices = [];
	const normals = [];
	const uvs = [];

	// helper variables

	let index = 0;
	const indexArray = [];
	const halfHeight = height / 2;
	let groupStart = 0;

	// generate geometry

	generateTorso();

	if ( openEnded === false ) {

		if ( radiusTop > 0 ) generateCap( true );
		if ( radiusBottom > 0 ) generateCap( false );

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

	function generateTorso() {

		const normal = new Vector3();
		const vertex = new Vector3();

		let groupCount = 0;

		// this will be used to calculate the normal
		const slope = ( radiusBottom - radiusTop ) / height;

		// generate vertices, normals and uvs

		for ( let y = 0; y <= heightSegments; y ++ ) {

			const indexRow = [];

			const v = y / heightSegments;

			// calculate the radius of the current row

			const radius = v * ( radiusBottom - radiusTop ) + radiusTop;

			for ( let x = 0; x <= radialSegments; x ++ ) {

				const u = x / radialSegments;

				const theta = u * thetaLength + thetaStart;

				const sinTheta = Math.sin( theta );
				const cosTheta = Math.cos( theta );

				// vertex

				vertex.x = radius * sinTheta;
				vertex.y = - v * height + halfHeight;
				vertex.z = radius * cosTheta;
				vertices.push( vertex.x, vertex.y, vertex.z );

				// normal

				normal.set( sinTheta, slope, cosTheta ).normalize();
				normals.push( normal.x, normal.y, normal.z );

				// uv

				uvs.push( u, 1 - v );

				// save index of vertex in respective row

				indexRow.push( index ++ );

			}

			// now save vertices of the row in our index array

			indexArray.push( indexRow );

		}

		// generate indices

		for ( let x = 0; x < radialSegments; x ++ ) {

			for ( let y = 0; y < heightSegments; y ++ ) {

				// we use the index array to access the correct indices

				const a = indexArray[ y ][ x ];
				const b = indexArray[ y + 1 ][ x ];
				const c = indexArray[ y + 1 ][ x + 1 ];
				const d = indexArray[ y ][ x + 1 ];

				// faces

				indices.push( a, b, d );
				indices.push( b, c, d );

				// update group counter

				groupCount += 6;

			}

		}

		// add a group to the geometry. this will ensure multi material support

		scope.addGroup( groupStart, groupCount, 0 );

		// calculate new start value for groups

		groupStart += groupCount;

	}

	function generateCap( top ) {

		let centerIndexStart, centerIndexEnd;

		const uv = new Vector2();
		const vertex = new Vector3();

		let groupCount = 0;

		const radius = ( top === true ) ? radiusTop : radiusBottom;
		const sign = ( top === true ) ? 1 : - 1;

		// save the index of the first center vertex
		centerIndexStart = index;

		// first we generate the center vertex data of the cap.
		// because the geometry needs one set of uvs per face,
		// we must generate a center vertex per face/segment

		for ( let x = 1; x <= radialSegments; x ++ ) {

			// vertex

			vertices.push( 0, halfHeight * sign, 0 );

			// normal

			normals.push( 0, sign, 0 );

			// uv

			uvs.push( 0.5, 0.5 );

			// increase index

			index ++;

		}

		// save the index of the last center vertex

		centerIndexEnd = index;

		// now we generate the surrounding vertices, normals and uvs

		for ( let x = 0; x <= radialSegments; x ++ ) {

			const u = x / radialSegments;
			const theta = u * thetaLength + thetaStart;

			const cosTheta = Math.cos( theta );
			const sinTheta = Math.sin( theta );

			// vertex

			vertex.x = radius * sinTheta;
			vertex.y = halfHeight * sign;
			vertex.z = radius * cosTheta;
			vertices.push( vertex.x, vertex.y, vertex.z );

			// normal

			normals.push( 0, sign, 0 );

			// uv

			uv.x = ( cosTheta * 0.5 ) + 0.5;
			uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
			uvs.push( uv.x, uv.y );

			// increase index

			index ++;

		}

		// generate indices

		for ( let x = 0; x < radialSegments; x ++ ) {

			const c = centerIndexStart + x;
			const i = centerIndexEnd + x;

			if ( top === true ) {

				// face top

				indices.push( i, i + 1, c );

			} else {

				// face bottom

				indices.push( i + 1, i, c );

			}

			groupCount += 3;

		}

		// add a group to the geometry. this will ensure multi material support

		scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );

		// calculate new start value for groups

		groupStart += groupCount;

	}

}

CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;

/**
 * @author abelnation / http://github.com/abelnation
 */

// ConeGeometry

function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

	CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );

	this.type = 'ConeGeometry';

	this.parameters = {
		radius: radius,
		height: height,
		radialSegments: radialSegments,
		heightSegments: heightSegments,
		openEnded: openEnded,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

}

ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
ConeGeometry.prototype.constructor = ConeGeometry;

// ConeBufferGeometry

function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {

	CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );

	this.type = 'ConeBufferGeometry';

	this.parameters = {
		radius: radius,
		height: height,
		radialSegments: radialSegments,
		heightSegments: heightSegments,
		openEnded: openEnded,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

}

ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;

/**
 * @author benaadams / https://twitter.com/ben_a_adams
 * @author Mugen87 / https://github.com/Mugen87
 * @author hughes
 */

// CircleGeometry

function CircleGeometry( radius, segments, thetaStart, thetaLength ) {

	Geometry.call( this );

	this.type = 'CircleGeometry';

	this.parameters = {
		radius: radius,
		segments: segments,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
	this.mergeVertices();

}

CircleGeometry.prototype = Object.create( Geometry.prototype );
CircleGeometry.prototype.constructor = CircleGeometry;

// CircleBufferGeometry

function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {

	BufferGeometry.call( this );

	this.type = 'CircleBufferGeometry';

	this.parameters = {
		radius: radius,
		segments: segments,
		thetaStart: thetaStart,
		thetaLength: thetaLength
	};

	radius = radius || 1;
	segments = segments !== undefined ? Math.max( 3, segments ) : 8;

	thetaStart = thetaStart !== undefined ? thetaStart : 0;
	thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;

	// buffers

	const indices = [];
	const vertices = [];
	const normals = [];
	const uvs = [];

	// helper variables

	const vertex = new Vector3();
	const uv = new Vector2();

	// center point

	vertices.push( 0, 0, 0 );
	normals.push( 0, 0, 1 );
	uvs.push( 0.5, 0.5 );

	for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {

		const segment = thetaStart + s / segments * thetaLength;

		// vertex

		vertex.x = radius * Math.cos( segment );
		vertex.y = radius * Math.sin( segment );

		vertices.push( vertex.x, vertex.y, vertex.z );

		// normal

		normals.push( 0, 0, 1 );

		// uvs

		uv.x = ( vertices[ i ] / radius + 1 ) / 2;
		uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;

		uvs.push( uv.x, uv.y );

	}

	// indices

	for ( let i = 1; i <= segments; i ++ ) {

		indices.push( i, i + 1, 0 );

	}

	// build geometry

	this.setIndex( indices );
	this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
	this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );

}

CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;

var Geometries = /*#__PURE__*/Object.freeze({
	__proto__: null,
	WireframeGeometry: WireframeGeometry,
	ParametricGeometry: ParametricGeometry,
	ParametricBufferGeometry: ParametricBufferGeometry,
	TetrahedronGeometry: TetrahedronGeometry,
	TetrahedronBufferGeometry: TetrahedronBufferGeometry,
	OctahedronGeometry: OctahedronGeometry,
	OctahedronBufferGeometry: OctahedronBufferGeometry,
	IcosahedronGeometry: IcosahedronGeometry,
	IcosahedronBufferGeometry: IcosahedronBufferGeometry,
	DodecahedronGeometry: DodecahedronGeometry,
	DodecahedronBufferGeometry: DodecahedronBufferGeometry,
	PolyhedronGeometry: PolyhedronGeometry,
	PolyhedronBufferGeometry: PolyhedronBufferGeometry,
	TubeGeometry: TubeGeometry,
	TubeBufferGeometry: TubeBufferGeometry,
	TorusKnotGeometry: TorusKnotGeometry,
	TorusKnotBufferGeometry: TorusKnotBufferGeometry,
	TorusGeometry: TorusGeometry,
	TorusBufferGeometry: TorusBufferGeometry,
	TextGeometry: TextGeometry,
	TextBufferGeometry: TextBufferGeometry,
	SphereGeometry: SphereGeometry,
	SphereBufferGeometry: SphereBufferGeometry,
	RingGeometry: RingGeometry,
	RingBufferGeometry: RingBufferGeometry,
	PlaneGeometry: PlaneGeometry,
	PlaneBufferGeometry: PlaneBufferGeometry,
	LatheGeometry: LatheGeometry,
	LatheBufferGeometry: LatheBufferGeometry,
	ShapeGeometry: ShapeGeometry,
	ShapeBufferGeometry: ShapeBufferGeometry,
	ExtrudeGeometry: ExtrudeGeometry,
	ExtrudeBufferGeometry: ExtrudeBufferGeometry,
	EdgesGeometry: EdgesGeometry,
	ConeGeometry: ConeGeometry,
	ConeBufferGeometry: ConeBufferGeometry,
	CylinderGeometry: CylinderGeometry,
	CylinderBufferGeometry: CylinderBufferGeometry,
	CircleGeometry: CircleGeometry,
	CircleBufferGeometry: CircleBufferGeometry,
	BoxGeometry: BoxGeometry,
	BoxBufferGeometry: BoxBufferGeometry
});

/**
 * @author mrdoob / http://mrdoob.com/
 *
 * parameters = {
 *  color: <THREE.Color>
 * }
 */

function ShadowMaterial( parameters ) {

	Material.call( this );

	this.type = 'ShadowMaterial';

	this.color = new Color( 0x000000 );
	this.transparent = true;

	this.setValues( parameters );

}

ShadowMaterial.prototype = Object.create( Material.prototype );
ShadowMaterial.prototype.constructor = ShadowMaterial;

ShadowMaterial.prototype.isShadowMaterial = true;

ShadowMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.color.copy( source.color );

	return this;

};

/**
 * @author mrdoob / http://mrdoob.com/
 */

function RawShaderMaterial( parameters ) {

	ShaderMaterial.call( this, parameters );

	this.type = 'RawShaderMaterial';

}

RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
RawShaderMaterial.prototype.constructor = RawShaderMaterial;

RawShaderMaterial.prototype.isRawShaderMaterial = true;

/**
 * @author WestLangley / http://github.com/WestLangley
 *
 * parameters = {
 *  color: <hex>,
 *  roughness: <float>,
 *  metalness: <float>,
 *  opacity: <float>,
 *
 *  map: new THREE.Texture( <Image> ),
 *
 *  lightMap: new THREE.Texture( <Image> ),
 *  lightMapIntensity: <float>
 *
 *  aoMap: new THREE.Texture( <Image> ),
 *  aoMapIntensity: <float>
 *
 *  emissive: <hex>,
 *  emissiveIntensity: <float>
 *  emissiveMap: new THREE.Texture( <Image> ),
 *
 *  bumpMap: new THREE.Texture( <Image> ),
 *  bumpScale: <float>,
 *
 *  normalMap: new THREE.Texture( <Image> ),
 *  normalMapType: THREE.TangentSpaceNormalMap,
 *  normalScale: <Vector2>,
 *
 *  displacementMap: new THREE.Texture( <Image> ),
 *  displacementScale: <float>,
 *  displacementBias: <float>,
 *
 *  roughnessMap: new THREE.Texture( <Image> ),
 *
 *  metalnessMap: new THREE.Texture( <Image> ),
 *
 *  alphaMap: new THREE.Texture( <Image> ),
 *
 *  envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
 *  envMapIntensity: <float>
 *
 *  refractionRatio: <float>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>
 * }
 */

function MeshStandardMaterial( parameters ) {

	Material.call( this );

	this.defines = { 'STANDARD': '' };

	this.type = 'MeshStandardMaterial';

	this.color = new Color( 0xffffff ); // diffuse
	this.roughness = 1.0;
	this.metalness = 0.0;

	this.map = null;

	this.lightMap = null;
	this.lightMapIntensity = 1.0;

	this.aoMap = null;
	this.aoMapIntensity = 1.0;

	this.emissive = new Color( 0x000000 );
	this.emissiveIntensity = 1.0;
	this.emissiveMap = null;

	this.bumpMap = null;
	this.bumpScale = 1;

	this.normalMap = null;
	this.normalMapType = TangentSpaceNormalMap;
	this.normalScale = new Vector2( 1, 1 );

	this.displacementMap = null;
	this.displacementScale = 1;
	this.displacementBias = 0;

	this.roughnessMap = null;

	this.metalnessMap = null;

	this.alphaMap = null;

	this.envMap = null;
	this.envMapIntensity = 1.0;

	this.refractionRatio = 0.98;

	this.wireframe = false;
	this.wireframeLinewidth = 1;
	this.wireframeLinecap = 'round';
	this.wireframeLinejoin = 'round';

	this.skinning = false;
	this.morphTargets = false;
	this.morphNormals = false;

	this.vertexTangents = false;

	this.setValues( parameters );

}

MeshStandardMaterial.prototype = Object.create( Material.prototype );
MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;

MeshStandardMaterial.prototype.isMeshStandardMaterial = true;

MeshStandardMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.defines = { 'STANDARD': '' };

	this.color.copy( source.color );
	this.roughness = source.roughness;
	this.metalness = source.metalness;

	this.map = source.map;

	this.lightMap = source.lightMap;
	this.lightMapIntensity = source.lightMapIntensity;

	this.aoMap = source.aoMap;
	this.aoMapIntensity = source.aoMapIntensity;

	this.emissive.copy( source.emissive );
	this.emissiveMap = source.emissiveMap;
	this.emissiveIntensity = source.emissiveIntensity;

	this.bumpMap = source.bumpMap;
	this.bumpScale = source.bumpScale;

	this.normalMap = source.normalMap;
	this.normalMapType = source.normalMapType;
	this.normalScale.copy( source.normalScale );

	this.displacementMap = source.displacementMap;
	this.displacementScale = source.displacementScale;
	this.displacementBias = source.displacementBias;

	this.roughnessMap = source.roughnessMap;

	this.metalnessMap = source.metalnessMap;

	this.alphaMap = source.alphaMap;

	this.envMap = source.envMap;
	this.envMapIntensity = source.envMapIntensity;

	this.refractionRatio = source.refractionRatio;

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;
	this.wireframeLinecap = source.wireframeLinecap;
	this.wireframeLinejoin = source.wireframeLinejoin;

	this.skinning = source.skinning;
	this.morphTargets = source.morphTargets;
	this.morphNormals = source.morphNormals;

	this.vertexTangents = source.vertexTangents;

	return this;

};

/**
 * @author WestLangley / http://github.com/WestLangley
 *
 * parameters = {
 *  clearcoat: <float>,
 *  clearcoatMap: new THREE.Texture( <Image> ),
 *  clearcoatRoughness: <float>,
 *  clearcoatRoughnessMap: new THREE.Texture( <Image> ),
 *  clearcoatNormalScale: <Vector2>,
 *  clearcoatNormalMap: new THREE.Texture( <Image> ),
 *
 *  reflectivity: <float>,
 *
 *  sheen: <Color>,
 *
 *  transparency: <float>
 * }
 */

function MeshPhysicalMaterial( parameters ) {

	MeshStandardMaterial.call( this );

	this.defines = {

		'STANDARD': '',
		'PHYSICAL': ''

	};

	this.type = 'MeshPhysicalMaterial';

	this.clearcoat = 0.0;
	this.clearcoatMap = null;
	this.clearcoatRoughness = 0.0;
	this.clearcoatRoughnessMap = null;
	this.clearcoatNormalScale = new Vector2( 1, 1 );
	this.clearcoatNormalMap = null;

	this.reflectivity = 0.5; // maps to F0 = 0.04

	this.sheen = null; // null will disable sheen bsdf

	this.transparency = 0.0;

	this.setValues( parameters );

}

MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;

MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;

MeshPhysicalMaterial.prototype.copy = function ( source ) {

	MeshStandardMaterial.prototype.copy.call( this, source );

	this.defines = {

		'STANDARD': '',
		'PHYSICAL': ''

	};

	this.clearcoat = source.clearcoat;
	this.clearcoatMap = source.clearcoatMap;
	this.clearcoatRoughness = source.clearcoatRoughness;
	this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
	this.clearcoatNormalMap = source.clearcoatNormalMap;
	this.clearcoatNormalScale.copy( source.clearcoatNormalScale );

	this.reflectivity = source.reflectivity;

	if ( source.sheen ) {

		this.sheen = ( this.sheen || new Color() ).copy( source.sheen );

	} else {

		this.sheen = null;

	}

	this.transparency = source.transparency;

	return this;

};

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  specular: <hex>,
 *  shininess: <float>,
 *  opacity: <float>,
 *
 *  map: new THREE.Texture( <Image> ),
 *
 *  lightMap: new THREE.Texture( <Image> ),
 *  lightMapIntensity: <float>
 *
 *  aoMap: new THREE.Texture( <Image> ),
 *  aoMapIntensity: <float>
 *
 *  emissive: <hex>,
 *  emissiveIntensity: <float>
 *  emissiveMap: new THREE.Texture( <Image> ),
 *
 *  bumpMap: new THREE.Texture( <Image> ),
 *  bumpScale: <float>,
 *
 *  normalMap: new THREE.Texture( <Image> ),
 *  normalMapType: THREE.TangentSpaceNormalMap,
 *  normalScale: <Vector2>,
 *
 *  displacementMap: new THREE.Texture( <Image> ),
 *  displacementScale: <float>,
 *  displacementBias: <float>,
 *
 *  specularMap: new THREE.Texture( <Image> ),
 *
 *  alphaMap: new THREE.Texture( <Image> ),
 *
 *  envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
 *  combine: THREE.MultiplyOperation,
 *  reflectivity: <float>,
 *  refractionRatio: <float>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>
 * }
 */

function MeshPhongMaterial( parameters ) {

	Material.call( this );

	this.type = 'MeshPhongMaterial';

	this.color = new Color( 0xffffff ); // diffuse
	this.specular = new Color( 0x111111 );
	this.shininess = 30;

	this.map = null;

	this.lightMap = null;
	this.lightMapIntensity = 1.0;

	this.aoMap = null;
	this.aoMapIntensity = 1.0;

	this.emissive = new Color( 0x000000 );
	this.emissiveIntensity = 1.0;
	this.emissiveMap = null;

	this.bumpMap = null;
	this.bumpScale = 1;

	this.normalMap = null;
	this.normalMapType = TangentSpaceNormalMap;
	this.normalScale = new Vector2( 1, 1 );

	this.displacementMap = null;
	this.displacementScale = 1;
	this.displacementBias = 0;

	this.specularMap = null;

	this.alphaMap = null;

	this.envMap = null;
	this.combine = MultiplyOperation;
	this.reflectivity = 1;
	this.refractionRatio = 0.98;

	this.wireframe = false;
	this.wireframeLinewidth = 1;
	this.wireframeLinecap = 'round';
	this.wireframeLinejoin = 'round';

	this.skinning = false;
	this.morphTargets = false;
	this.morphNormals = false;

	this.setValues( parameters );

}

MeshPhongMaterial.prototype = Object.create( Material.prototype );
MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;

MeshPhongMaterial.prototype.isMeshPhongMaterial = true;

MeshPhongMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.color.copy( source.color );
	this.specular.copy( source.specular );
	this.shininess = source.shininess;

	this.map = source.map;

	this.lightMap = source.lightMap;
	this.lightMapIntensity = source.lightMapIntensity;

	this.aoMap = source.aoMap;
	this.aoMapIntensity = source.aoMapIntensity;

	this.emissive.copy( source.emissive );
	this.emissiveMap = source.emissiveMap;
	this.emissiveIntensity = source.emissiveIntensity;

	this.bumpMap = source.bumpMap;
	this.bumpScale = source.bumpScale;

	this.normalMap = source.normalMap;
	this.normalMapType = source.normalMapType;
	this.normalScale.copy( source.normalScale );

	this.displacementMap = source.displacementMap;
	this.displacementScale = source.displacementScale;
	this.displacementBias = source.displacementBias;

	this.specularMap = source.specularMap;

	this.alphaMap = source.alphaMap;

	this.envMap = source.envMap;
	this.combine = source.combine;
	this.reflectivity = source.reflectivity;
	this.refractionRatio = source.refractionRatio;

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;
	this.wireframeLinecap = source.wireframeLinecap;
	this.wireframeLinejoin = source.wireframeLinejoin;

	this.skinning = source.skinning;
	this.morphTargets = source.morphTargets;
	this.morphNormals = source.morphNormals;

	return this;

};

/**
 * @author takahirox / http://github.com/takahirox
 *
 * parameters = {
 *  color: <hex>,
 *
 *  map: new THREE.Texture( <Image> ),
 *  gradientMap: new THREE.Texture( <Image> ),
 *
 *  lightMap: new THREE.Texture( <Image> ),
 *  lightMapIntensity: <float>
 *
 *  aoMap: new THREE.Texture( <Image> ),
 *  aoMapIntensity: <float>
 *
 *  emissive: <hex>,
 *  emissiveIntensity: <float>
 *  emissiveMap: new THREE.Texture( <Image> ),
 *
 *  bumpMap: new THREE.Texture( <Image> ),
 *  bumpScale: <float>,
 *
 *  normalMap: new THREE.Texture( <Image> ),
 *  normalMapType: THREE.TangentSpaceNormalMap,
 *  normalScale: <Vector2>,
 *
 *  displacementMap: new THREE.Texture( <Image> ),
 *  displacementScale: <float>,
 *  displacementBias: <float>,
 *
 *  alphaMap: new THREE.Texture( <Image> ),
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>
 * }
 */

function MeshToonMaterial( parameters ) {

	Material.call( this );

	this.defines = { 'TOON': '' };

	this.type = 'MeshToonMaterial';

	this.color = new Color( 0xffffff );

	this.map = null;
	this.gradientMap = null;

	this.lightMap = null;
	this.lightMapIntensity = 1.0;

	this.aoMap = null;
	this.aoMapIntensity = 1.0;

	this.emissive = new Color( 0x000000 );
	this.emissiveIntensity = 1.0;
	this.emissiveMap = null;

	this.bumpMap = null;
	this.bumpScale = 1;

	this.normalMap = null;
	this.normalMapType = TangentSpaceNormalMap;
	this.normalScale = new Vector2( 1, 1 );

	this.displacementMap = null;
	this.displacementScale = 1;
	this.displacementBias = 0;

	this.alphaMap = null;

	this.wireframe = false;
	this.wireframeLinewidth = 1;
	this.wireframeLinecap = 'round';
	this.wireframeLinejoin = 'round';

	this.skinning = false;
	this.morphTargets = false;
	this.morphNormals = false;

	this.setValues( parameters );

}

MeshToonMaterial.prototype = Object.create( Material.prototype );
MeshToonMaterial.prototype.constructor = MeshToonMaterial;

MeshToonMaterial.prototype.isMeshToonMaterial = true;

MeshToonMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.color.copy( source.color );

	this.map = source.map;
	this.gradientMap = source.gradientMap;

	this.lightMap = source.lightMap;
	this.lightMapIntensity = source.lightMapIntensity;

	this.aoMap = source.aoMap;
	this.aoMapIntensity = source.aoMapIntensity;

	this.emissive.copy( source.emissive );
	this.emissiveMap = source.emissiveMap;
	this.emissiveIntensity = source.emissiveIntensity;

	this.bumpMap = source.bumpMap;
	this.bumpScale = source.bumpScale;

	this.normalMap = source.normalMap;
	this.normalMapType = source.normalMapType;
	this.normalScale.copy( source.normalScale );

	this.displacementMap = source.displacementMap;
	this.displacementScale = source.displacementScale;
	this.displacementBias = source.displacementBias;

	this.alphaMap = source.alphaMap;

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;
	this.wireframeLinecap = source.wireframeLinecap;
	this.wireframeLinejoin = source.wireframeLinejoin;

	this.skinning = source.skinning;
	this.morphTargets = source.morphTargets;
	this.morphNormals = source.morphNormals;

	return this;

};

/**
 * @author mrdoob / http://mrdoob.com/
 * @author WestLangley / http://github.com/WestLangley
 *
 * parameters = {
 *  opacity: <float>,
 *
 *  bumpMap: new THREE.Texture( <Image> ),
 *  bumpScale: <float>,
 *
 *  normalMap: new THREE.Texture( <Image> ),
 *  normalMapType: THREE.TangentSpaceNormalMap,
 *  normalScale: <Vector2>,
 *
 *  displacementMap: new THREE.Texture( <Image> ),
 *  displacementScale: <float>,
 *  displacementBias: <float>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>
 * }
 */

function MeshNormalMaterial( parameters ) {

	Material.call( this );

	this.type = 'MeshNormalMaterial';

	this.bumpMap = null;
	this.bumpScale = 1;

	this.normalMap = null;
	this.normalMapType = TangentSpaceNormalMap;
	this.normalScale = new Vector2( 1, 1 );

	this.displacementMap = null;
	this.displacementScale = 1;
	this.displacementBias = 0;

	this.wireframe = false;
	this.wireframeLinewidth = 1;

	this.fog = false;

	this.skinning = false;
	this.morphTargets = false;
	this.morphNormals = false;

	this.setValues( parameters );

}

MeshNormalMaterial.prototype = Object.create( Material.prototype );
MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;

MeshNormalMaterial.prototype.isMeshNormalMaterial = true;

MeshNormalMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.bumpMap = source.bumpMap;
	this.bumpScale = source.bumpScale;

	this.normalMap = source.normalMap;
	this.normalMapType = source.normalMapType;
	this.normalScale.copy( source.normalScale );

	this.displacementMap = source.displacementMap;
	this.displacementScale = source.displacementScale;
	this.displacementBias = source.displacementBias;

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;

	this.skinning = source.skinning;
	this.morphTargets = source.morphTargets;
	this.morphNormals = source.morphNormals;

	return this;

};

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  opacity: <float>,
 *
 *  map: new THREE.Texture( <Image> ),
 *
 *  lightMap: new THREE.Texture( <Image> ),
 *  lightMapIntensity: <float>
 *
 *  aoMap: new THREE.Texture( <Image> ),
 *  aoMapIntensity: <float>
 *
 *  emissive: <hex>,
 *  emissiveIntensity: <float>
 *  emissiveMap: new THREE.Texture( <Image> ),
 *
 *  specularMap: new THREE.Texture( <Image> ),
 *
 *  alphaMap: new THREE.Texture( <Image> ),
 *
 *  envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
 *  combine: THREE.Multiply,
 *  reflectivity: <float>,
 *  refractionRatio: <float>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>
 * }
 */

function MeshLambertMaterial( parameters ) {

	Material.call( this );

	this.type = 'MeshLambertMaterial';

	this.color = new Color( 0xffffff ); // diffuse

	this.map = null;

	this.lightMap = null;
	this.lightMapIntensity = 1.0;

	this.aoMap = null;
	this.aoMapIntensity = 1.0;

	this.emissive = new Color( 0x000000 );
	this.emissiveIntensity = 1.0;
	this.emissiveMap = null;

	this.specularMap = null;

	this.alphaMap = null;

	this.envMap = null;
	this.combine = MultiplyOperation;
	this.reflectivity = 1;
	this.refractionRatio = 0.98;

	this.wireframe = false;
	this.wireframeLinewidth = 1;
	this.wireframeLinecap = 'round';
	this.wireframeLinejoin = 'round';

	this.skinning = false;
	this.morphTargets = false;
	this.morphNormals = false;

	this.setValues( parameters );

}

MeshLambertMaterial.prototype = Object.create( Material.prototype );
MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;

MeshLambertMaterial.prototype.isMeshLambertMaterial = true;

MeshLambertMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.color.copy( source.color );

	this.map = source.map;

	this.lightMap = source.lightMap;
	this.lightMapIntensity = source.lightMapIntensity;

	this.aoMap = source.aoMap;
	this.aoMapIntensity = source.aoMapIntensity;

	this.emissive.copy( source.emissive );
	this.emissiveMap = source.emissiveMap;
	this.emissiveIntensity = source.emissiveIntensity;

	this.specularMap = source.specularMap;

	this.alphaMap = source.alphaMap;

	this.envMap = source.envMap;
	this.combine = source.combine;
	this.reflectivity = source.reflectivity;
	this.refractionRatio = source.refractionRatio;

	this.wireframe = source.wireframe;
	this.wireframeLinewidth = source.wireframeLinewidth;
	this.wireframeLinecap = source.wireframeLinecap;
	this.wireframeLinejoin = source.wireframeLinejoin;

	this.skinning = source.skinning;
	this.morphTargets = source.morphTargets;
	this.morphNormals = source.morphNormals;

	return this;

};

/**
 * @author WestLangley / http://github.com/WestLangley
 *
 * parameters = {
 *  color: <hex>,
 *  opacity: <float>,
 *
 *  matcap: new THREE.Texture( <Image> ),
 *
 *  map: new THREE.Texture( <Image> ),
 *
 *  bumpMap: new THREE.Texture( <Image> ),
 *  bumpScale: <float>,
 *
 *  normalMap: new THREE.Texture( <Image> ),
 *  normalMapType: THREE.TangentSpaceNormalMap,
 *  normalScale: <Vector2>,
 *
 *  displacementMap: new THREE.Texture( <Image> ),
 *  displacementScale: <float>,
 *  displacementBias: <float>,
 *
 *  alphaMap: new THREE.Texture( <Image> ),
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>
 * }
 */

function MeshMatcapMaterial( parameters ) {

	Material.call( this );

	this.defines = { 'MATCAP': '' };

	this.type = 'MeshMatcapMaterial';

	this.color = new Color( 0xffffff ); // diffuse

	this.matcap = null;

	this.map = null;

	this.bumpMap = null;
	this.bumpScale = 1;

	this.normalMap = null;
	this.normalMapType = TangentSpaceNormalMap;
	this.normalScale = new Vector2( 1, 1 );

	this.displacementMap = null;
	this.displacementScale = 1;
	this.displacementBias = 0;

	this.alphaMap = null;

	this.skinning = false;
	this.morphTargets = false;
	this.morphNormals = false;

	this.setValues( parameters );

}

MeshMatcapMaterial.prototype = Object.create( Material.prototype );
MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;

MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;

MeshMatcapMaterial.prototype.copy = function ( source ) {

	Material.prototype.copy.call( this, source );

	this.defines = { 'MATCAP': '' };

	this.color.copy( source.color );

	this.matcap = source.matcap;

	this.map = source.map;

	this.bumpMap = source.bumpMap;
	this.bumpScale = source.bumpScale;

	this.normalMap = source.normalMap;
	this.normalMapType = source.normalMapType;
	this.normalScale.copy( source.normalScale );

	this.displacementMap = source.displacementMap;
	this.displacementScale = source.displacementScale;
	this.displacementBias = source.displacementBias;

	this.alphaMap = source.alphaMap;

	this.skinning = source.skinning;
	this.morphTargets = source.morphTargets;
	this.morphNormals = source.morphNormals;

	return this;

};

/**
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  opacity: <float>,
 *
 *  linewidth: <float>,
 *
 *  scale: <float>,
 *  dashSize: <float>,
 *  gapSize: <float>
 * }
 */

function LineDashedMaterial( parameters ) {

	LineBasicMaterial.call( this );

	this.type = 'LineDashedMaterial';

	this.scale = 1;
	this.dashSize = 3;
	this.gapSize = 1;

	this.setValues( parameters );

}

LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
LineDashedMaterial.prototype.constructor = LineDashedMaterial;

LineDashedMaterial.prototype.isLineDashedMaterial = true;

LineDashedMaterial.prototype.copy = function ( source ) {

	LineBasicMaterial.prototype.copy.call( this, source );

	this.scale = source.scale;
	this.dashSize = source.dashSize;
	this.gapSize = source.gapSize;

	return this;

};

var Materials = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ShadowMaterial: ShadowMaterial,
	SpriteMaterial: SpriteMaterial,
	RawShaderMaterial: RawShaderMaterial,
	ShaderMaterial: ShaderMaterial,
	PointsMaterial: PointsMaterial,
	MeshPhysicalMaterial: MeshPhysicalMaterial,
	MeshStandardMaterial: MeshStandardMaterial,
	MeshPhongMaterial: MeshPhongMaterial,
	MeshToonMaterial: MeshToonMaterial,
	MeshNormalMaterial: MeshNormalMaterial,
	MeshLambertMaterial: MeshLambertMaterial,
	MeshDepthMaterial: MeshDepthMaterial,
	MeshDistanceMaterial: MeshDistanceMaterial,
	MeshBasicMaterial: MeshBasicMaterial,
	MeshMatcapMaterial: MeshMatcapMaterial,
	LineDashedMaterial: LineDashedMaterial,
	LineBasicMaterial: LineBasicMaterial,
	Material: Material
});

/**
 * @author tschw
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 */

const AnimationUtils = {

	// same as Array.prototype.slice, but also works on typed arrays
	arraySlice: function ( array, from, to ) {

		if ( AnimationUtils.isTypedArray( array ) ) {

			// in ios9 array.subarray(from, undefined) will return empty array
			// but array.subarray(from) or array.subarray(from, len) is correct
			return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );

		}

		return array.slice( from, to );

	},

	// converts an array to a specific type
	convertArray: function ( array, type, forceClone ) {

		if ( ! array || // let 'undefined' and 'null' pass
			! forceClone && array.constructor === type ) return array;

		if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {

			return new type( array ); // create typed array

		}

		return Array.prototype.slice.call( array ); // create Array

	},

	isTypedArray: function ( object ) {

		return ArrayBuffer.isView( object ) &&
			! ( object instanceof DataView );

	},

	// returns an array by which times and values can be sorted
	getKeyframeOrder: function ( times ) {

		function compareTime( i, j ) {

			return times[ i ] - times[ j ];

		}

		const n = times.length;
		const result = new Array( n );
		for ( let i = 0; i !== n; ++ i ) result[ i ] = i;

		result.sort( compareTime );

		return result;

	},

	// uses the array previously returned by 'getKeyframeOrder' to sort data
	sortedArray: function ( values, stride, order ) {

		const nValues = values.length;
		const result = new values.constructor( nValues );

		for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {

			const srcOffset = order[ i ] * stride;

			for ( let j = 0; j !== stride; ++ j ) {

				result[ dstOffset ++ ] = values[ srcOffset + j ];

			}

		}

		return result;

	},

	// function for parsing AOS keyframe formats
	flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {

		let i = 1, key = jsonKeys[ 0 ];

		while ( key !== undefined && key[ valuePropertyName ] === undefined ) {

			key = jsonKeys[ i ++ ];

		}

		if ( key === undefined ) return; // no data

		let value = key[ valuePropertyName ];
		if ( value === undefined ) return; // no data

		if ( Array.isArray( value ) ) {

			do {

				value = key[ valuePropertyName ];

				if ( value !== undefined ) {

					times.push( key.time );
					values.push.apply( values, value ); // push all elements

				}

				key = jsonKeys[ i ++ ];

			} while ( key !== undefined );

		} else if ( value.toArray !== undefined ) {

			// ...assume THREE.Math-ish

			do {

				value = key[ valuePropertyName ];

				if ( value !== undefined ) {

					times.push( key.time );
					value.toArray( values, values.length );

				}

				key = jsonKeys[ i ++ ];

			} while ( key !== undefined );

		} else {

			// otherwise push as-is

			do {

				value = key[ valuePropertyName ];

				if ( value !== undefined ) {

					times.push( key.time );
					values.push( value );

				}

				key = jsonKeys[ i ++ ];

			} while ( key !== undefined );

		}

	},

	subclip: function ( sourceClip, name, startFrame, endFrame, fps ) {

		fps = fps || 30;

		const clip = sourceClip.clone();

		clip.name = name;

		const tracks = [];

		for ( let i = 0; i < clip.tracks.length; ++ i ) {

			const track = clip.tracks[ i ];
			const valueSize = track.getValueSize();

			const times = [];
			const values = [];

			for ( let j = 0; j < track.times.length; ++ j ) {

				const frame = track.times[ j ] * fps;

				if ( frame < startFrame || frame >= endFrame ) continue;

				times.push( track.times[ j ] );

				for ( let k = 0; k < valueSize; ++ k ) {

					values.push( track.values[ j * valueSize + k ] );

				}

			}

			if ( times.length === 0 ) continue;

			track.times = AnimationUtils.convertArray( times, track.times.constructor );
			track.values = AnimationUtils.convertArray( values, track.values.constructor );

			tracks.push( track );

		}

		clip.tracks = tracks;

		// find minimum .times value across all tracks in the trimmed clip

		let minStartTime = Infinity;

		for ( let i = 0; i < clip.tracks.length; ++ i ) {

			if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {

				minStartTime = clip.tracks[ i ].times[ 0 ];

			}

		}

		// shift all tracks such that clip begins at t=0

		for ( let i = 0; i < clip.tracks.length; ++ i ) {

			clip.tracks[ i ].shift( - 1 * minStartTime );

		}

		clip.resetDuration();

		return clip;

	},

	makeClipAdditive: function ( targetClip, referenceFrame, referenceClip, fps ) {

		if ( referenceFrame === undefined ) referenceFrame = 0;
		if ( referenceClip === undefined ) referenceClip = targetClip;
		if ( fps === undefined || fps <= 0 ) fps = 30;

		const numTracks = targetClip.tracks.length;
		const referenceTime = referenceFrame / fps;

		// Make each track's values relative to the values at the reference frame
		for ( let i = 0; i < numTracks; ++ i ) {

			const referenceTrack = referenceClip.tracks[ i ];
			const referenceTrackType = referenceTrack.ValueTypeName;

			// Skip this track if it's non-numeric
			if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;

			// Find the track in the target clip whose name and type matches the reference track
			const targetTrack = targetClip.tracks.find( function ( track ) {

				return track.name === referenceTrack.name
				&& track.ValueTypeName === referenceTrackType;

			} );

			if ( targetTrack === undefined ) continue;

			const valueSize = referenceTrack.getValueSize();
			const lastIndex = referenceTrack.times.length - 1;
			let referenceValue;

			// Find the value to subtract out of the track
			if ( referenceTime <= referenceTrack.times[ 0 ] ) {

				// Reference frame is earlier than the first keyframe, so just use the first keyframe
				referenceValue = AnimationUtils.arraySlice( referenceTrack.values, 0, referenceTrack.valueSize );

			} else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {

				// Reference frame is after the last keyframe, so just use the last keyframe
				const startIndex = lastIndex * valueSize;
				referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex );

			} else {

				// Interpolate to the reference value
				const interpolant = referenceTrack.createInterpolant();
				interpolant.evaluate( referenceTime );
				referenceValue = interpolant.resultBuffer;

			}

			// Conjugate the quaternion
			if ( referenceTrackType === 'quaternion' ) {

				const referenceQuat = new Quaternion(
					referenceValue[ 0 ],
					referenceValue[ 1 ],
					referenceValue[ 2 ],
					referenceValue[ 3 ]
				).normalize().conjugate();
				referenceQuat.toArray( referenceValue );

			}

			// Subtract the reference value from all of the track values

			const numTimes = targetTrack.times.length;
			for ( let j = 0; j < numTimes; ++ j ) {

				const valueStart = j * valueSize;

				if ( referenceTrackType === 'quaternion' ) {

					// Multiply the conjugate for quaternion track types
					Quaternion.multiplyQuaternionsFlat(
						targetTrack.values,
						valueStart,
						referenceValue,
						0,
						targetTrack.values,
						valueStart
					);

				} else {

					// Subtract each value for all other numeric track types
					for ( let k = 0; k < valueSize; ++ k ) {

						targetTrack.values[ valueStart + k ] -= referenceValue[ k ];

					}

				}

			}

		}

		targetClip.blendMode = AdditiveAnimationBlendMode;

		return targetClip;

	}

};

/**
 * Abstract base class of interpolants over parametric samples.
 *
 * The parameter domain is one dimensional, typically the time or a path
 * along a curve defined by the data.
 *
 * The sample values can have any dimensionality and derived classes may
 * apply special interpretations to the data.
 *
 * This class provides the interval seek in a Template Method, deferring
 * the actual interpolation to derived classes.
 *
 * Time complexity is O(1) for linear access crossing at most two points
 * and O(log N) for random access, where N is the number of positions.
 *
 * References:
 *
 * 		http://www.oodesign.com/template-method-pattern.html
 *
 * @author tschw
 */

function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

	this.parameterPositions = parameterPositions;
	this._cachedIndex = 0;

	this.resultBuffer = resultBuffer !== undefined ?
		resultBuffer : new sampleValues.constructor( sampleSize );
	this.sampleValues = sampleValues;
	this.valueSize = sampleSize;

}

Object.assign( Interpolant.prototype, {

	evaluate: function ( t ) {

		let pp = this.parameterPositions,
			i1 = this._cachedIndex,

			t1 = pp[ i1 ],
			t0 = pp[ i1 - 1 ];

		validate_interval: {

			seek: {

				let right;

				linear_scan: {

					//- See http://jsperf.com/comparison-to-undefined/3
					//- slower code:
					//-
					//- 				if ( t >= t1 || t1 === undefined ) {
					forward_scan: if ( ! ( t < t1 ) ) {

						for ( let giveUpAt = i1 + 2; ; ) {

							if ( t1 === undefined ) {

								if ( t < t0 ) break forward_scan;

								// after end

								i1 = pp.length;
								this._cachedIndex = i1;
								return this.afterEnd_( i1 - 1, t, t0 );

							}

							if ( i1 === giveUpAt ) break; // this loop

							t0 = t1;
							t1 = pp[ ++ i1 ];

							if ( t < t1 ) {

								// we have arrived at the sought interval
								break seek;

							}

						}

						// prepare binary search on the right side of the index
						right = pp.length;
						break linear_scan;

					}

					//- slower code:
					//-					if ( t < t0 || t0 === undefined ) {
					if ( ! ( t >= t0 ) ) {

						// looping?

						const t1global = pp[ 1 ];

						if ( t < t1global ) {

							i1 = 2; // + 1, using the scan for the details
							t0 = t1global;

						}

						// linear reverse scan

						for ( let giveUpAt = i1 - 2; ; ) {

							if ( t0 === undefined ) {

								// before start

								this._cachedIndex = 0;
								return this.beforeStart_( 0, t, t1 );

							}

							if ( i1 === giveUpAt ) break; // this loop

							t1 = t0;
							t0 = pp[ -- i1 - 1 ];

							if ( t >= t0 ) {

								// we have arrived at the sought interval
								break seek;

							}

						}

						// prepare binary search on the left side of the index
						right = i1;
						i1 = 0;
						break linear_scan;

					}

					// the interval is valid

					break validate_interval;

				} // linear scan

				// binary search

				while ( i1 < right ) {

					const mid = ( i1 + right ) >>> 1;

					if ( t < pp[ mid ] ) {

						right = mid;

					} else {

						i1 = mid + 1;

					}

				}

				t1 = pp[ i1 ];
				t0 = pp[ i1 - 1 ];

				// check boundary cases, again

				if ( t0 === undefined ) {

					this._cachedIndex = 0;
					return this.beforeStart_( 0, t, t1 );

				}

				if ( t1 === undefined ) {

					i1 = pp.length;
					this._cachedIndex = i1;
					return this.afterEnd_( i1 - 1, t0, t );

				}

			} // seek

			this._cachedIndex = i1;

			this.intervalChanged_( i1, t0, t1 );

		} // validate_interval

		return this.interpolate_( i1, t0, t, t1 );

	},

	settings: null, // optional, subclass-specific settings structure
	// Note: The indirection allows central control of many interpolants.

	// --- Protected interface

	DefaultSettings_: {},

	getSettings_: function () {

		return this.settings || this.DefaultSettings_;

	},

	copySampleValue_: function ( index ) {

		// copies a sample value to the result buffer

		const result = this.resultBuffer,
			values = this.sampleValues,
			stride = this.valueSize,
			offset = index * stride;

		for ( let i = 0; i !== stride; ++ i ) {

			result[ i ] = values[ offset + i ];

		}

		return result;

	},

	// Template methods for derived classes:

	interpolate_: function ( /* i1, t0, t, t1 */ ) {

		throw new Error( 'call to abstract method' );
		// implementations shall return this.resultBuffer

	},

	intervalChanged_: function ( /* i1, t0, t1 */ ) {

		// empty

	}

} );

// DECLARE ALIAS AFTER assign prototype
Object.assign( Interpolant.prototype, {

	//( 0, t, t0 ), returns this.resultBuffer
	beforeStart_: Interpolant.prototype.copySampleValue_,

	//( N-1, tN-1, t ), returns this.resultBuffer
	afterEnd_: Interpolant.prototype.copySampleValue_,

} );

/**
 * Fast and simple cubic spline interpolant.
 *
 * It was derived from a Hermitian construction setting the first derivative
 * at each sample position to the linear slope between neighboring positions
 * over their parameter interval.
 *
 * @author tschw
 */

function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

	Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );

	this._weightPrev = - 0;
	this._offsetPrev = - 0;
	this._weightNext = - 0;
	this._offsetNext = - 0;

}

CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {

	constructor: CubicInterpolant,

	DefaultSettings_: {

		endingStart: ZeroCurvatureEnding,
		endingEnd: ZeroCurvatureEnding

	},

	intervalChanged_: function ( i1, t0, t1 ) {

		let pp = this.parameterPositions,
			iPrev = i1 - 2,
			iNext = i1 + 1,

			tPrev = pp[ iPrev ],
			tNext = pp[ iNext ];

		if ( tPrev === undefined ) {

			switch ( this.getSettings_().endingStart ) {

				case ZeroSlopeEnding:

					// f'(t0) = 0
					iPrev = i1;
					tPrev = 2 * t0 - t1;

					break;

				case WrapAroundEnding:

					// use the other end of the curve
					iPrev = pp.length - 2;
					tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];

					break;

				default: // ZeroCurvatureEnding

					// f''(t0) = 0 a.k.a. Natural Spline
					iPrev = i1;
					tPrev = t1;

			}

		}

		if ( tNext === undefined ) {

			switch ( this.getSettings_().endingEnd ) {

				case ZeroSlopeEnding:

					// f'(tN) = 0
					iNext = i1;
					tNext = 2 * t1 - t0;

					break;

				case WrapAroundEnding:

					// use the other end of the curve
					iNext = 1;
					tNext = t1 + pp[ 1 ] - pp[ 0 ];

					break;

				default: // ZeroCurvatureEnding

					// f''(tN) = 0, a.k.a. Natural Spline
					iNext = i1 - 1;
					tNext = t0;

			}

		}

		const halfDt = ( t1 - t0 ) * 0.5,
			stride = this.valueSize;

		this._weightPrev = halfDt / ( t0 - tPrev );
		this._weightNext = halfDt / ( tNext - t1 );
		this._offsetPrev = iPrev * stride;
		this._offsetNext = iNext * stride;

	},

	interpolate_: function ( i1, t0, t, t1 ) {

		const result = this.resultBuffer,
			values = this.sampleValues,
			stride = this.valueSize,

			o1 = i1 * stride,		o0 = o1 - stride,
			oP = this._offsetPrev, 	oN = this._offsetNext,
			wP = this._weightPrev,	wN = this._weightNext,

			p = ( t - t0 ) / ( t1 - t0 ),
			pp = p * p,
			ppp = pp * p;

		// evaluate polynomials

		const sP = - wP * ppp + 2 * wP * pp - wP * p;
		const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
		const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
		const sN = wN * ppp - wN * pp;

		// combine data linearly

		for ( let i = 0; i !== stride; ++ i ) {

			result[ i ] =
					sP * values[ oP + i ] +
					s0 * values[ o0 + i ] +
					s1 * values[ o1 + i ] +
					sN * values[ oN + i ];

		}

		return result;

	}

} );

/**
 * @author tschw
 */

function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

	Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );

}

LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {

	constructor: LinearInterpolant,

	interpolate_: function ( i1, t0, t, t1 ) {

		const result = this.resultBuffer,
			values = this.sampleValues,
			stride = this.valueSize,

			offset1 = i1 * stride,
			offset0 = offset1 - stride,

			weight1 = ( t - t0 ) / ( t1 - t0 ),
			weight0 = 1 - weight1;

		for ( let i = 0; i !== stride; ++ i ) {

			result[ i ] =
					values[ offset0 + i ] * weight0 +
					values[ offset1 + i ] * weight1;

		}

		return result;

	}

} );

/**
 *
 * Interpolant that evaluates to the sample value at the position preceeding
 * the parameter.
 *
 * @author tschw
 */

function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

	Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );

}

DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {

	constructor: DiscreteInterpolant,

	interpolate_: function ( i1 /*, t0, t, t1 */ ) {

		return this.copySampleValue_( i1 - 1 );

	}

} );

/**
 *
 * A timed sequence of keyframes for a specific property.
 *
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

function KeyframeTrack( name, times, values, interpolation ) {

	if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
	if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );

	this.name = name;

	this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
	this.values = AnimationUtils.convertArray( values, this.ValueBufferType );

	this.setInterpolation( interpolation || this.DefaultInterpolation );

}

// Static methods

Object.assign( KeyframeTrack, {

	// Serialization (in static context, because of constructor invocation
	// and automatic invocation of .toJSON):

	toJSON: function ( track ) {

		const trackType = track.constructor;

		let json;

		// derived classes can define a static toJSON method
		if ( trackType.toJSON !== undefined ) {

			json = trackType.toJSON( track );

		} else {

			// by default, we assume the data can be serialized as-is
			json = {

				'name': track.name,
				'times': AnimationUtils.convertArray( track.times, Array ),
				'values': AnimationUtils.convertArray( track.values, Array )

			};

			const interpolation = track.getInterpolation();

			if ( interpolation !== track.DefaultInterpolation ) {

				json.interpolation = interpolation;

			}

		}

		json.type = track.ValueTypeName; // mandatory

		return json;

	}

} );

Object.assign( KeyframeTrack.prototype, {

	constructor: KeyframeTrack,

	TimeBufferType: Float32Array,

	ValueBufferType: Float32Array,

	DefaultInterpolation: InterpolateLinear,

	InterpolantFactoryMethodDiscrete: function ( result ) {

		return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );

	},

	InterpolantFactoryMethodLinear: function ( result ) {

		return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );

	},

	InterpolantFactoryMethodSmooth: function ( result ) {

		return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );

	},

	setInterpolation: function ( interpolation ) {

		let factoryMethod;

		switch ( interpolation ) {

			case InterpolateDiscrete:

				factoryMethod = this.InterpolantFactoryMethodDiscrete;

				break;

			case InterpolateLinear:

				factoryMethod = this.InterpolantFactoryMethodLinear;

				break;

			case InterpolateSmooth:

				factoryMethod = this.InterpolantFactoryMethodSmooth;

				break;

		}

		if ( factoryMethod === undefined ) {

			const message = "unsupported interpolation for " +
				this.ValueTypeName + " keyframe track named " + this.name;

			if ( this.createInterpolant === undefined ) {

				// fall back to default, unless the default itself is messed up
				if ( interpolation !== this.DefaultInterpolation ) {

					this.setInterpolation( this.DefaultInterpolation );

				} else {

					throw new Error( message ); // fatal, in this case

				}

			}

			console.warn( 'THREE.KeyframeTrack:', message );
			return this;

		}

		this.createInterpolant = factoryMethod;

		return this;

	},

	getInterpolation: function () {

		switch ( this.createInterpolant ) {

			case this.InterpolantFactoryMethodDiscrete:

				return InterpolateDiscrete;

			case this.InterpolantFactoryMethodLinear:

				return InterpolateLinear;

			case this.InterpolantFactoryMethodSmooth:

				return InterpolateSmooth;

		}

	},

	getValueSize: function () {

		return this.values.length / this.times.length;

	},

	// move all keyframes either forwards or backwards in time
	shift: function ( timeOffset ) {

		if ( timeOffset !== 0.0 ) {

			const times = this.times;

			for ( let i = 0, n = times.length; i !== n; ++ i ) {

				times[ i ] += timeOffset;

			}

		}

		return this;

	},

	// scale all keyframe times by a factor (useful for frame <-> seconds conversions)
	scale: function ( timeScale ) {

		if ( timeScale !== 1.0 ) {

			const times = this.times;

			for ( let i = 0, n = times.length; i !== n; ++ i ) {

				times[ i ] *= timeScale;

			}

		}

		return this;

	},

	// removes keyframes before and after animation without changing any values within the range [startTime, endTime].
	// IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
	trim: function ( startTime, endTime ) {

		const times = this.times,
			nKeys = times.length;

		let from = 0,
			to = nKeys - 1;

		while ( from !== nKeys && times[ from ] < startTime ) {

			++ from;

		}

		while ( to !== - 1 && times[ to ] > endTime ) {

			-- to;

		}

		++ to; // inclusive -> exclusive bound

		if ( from !== 0 || to !== nKeys ) {

			// empty tracks are forbidden, so keep at least one keyframe
			if ( from >= to ) {

				to = Math.max( to, 1 );
				from = to - 1;

			}

			const stride = this.getValueSize();
			this.times = AnimationUtils.arraySlice( times, from, to );
			this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );

		}

		return this;

	},

	// ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
	validate: function () {

		let valid = true;

		const valueSize = this.getValueSize();
		if ( valueSize - Math.floor( valueSize ) !== 0 ) {

			console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
			valid = false;

		}

		const times = this.times,
			values = this.values,

			nKeys = times.length;

		if ( nKeys === 0 ) {

			console.error( 'THREE.KeyframeTrack: Track is empty.', this );
			valid = false;

		}

		let prevTime = null;

		for ( let i = 0; i !== nKeys; i ++ ) {

			const currTime = times[ i ];

			if ( typeof currTime === 'number' && isNaN( currTime ) ) {

				console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
				valid = false;
				break;

			}

			if ( prevTime !== null && prevTime > currTime ) {

				console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
				valid = false;
				break;

			}

			prevTime = currTime;

		}

		if ( values !== undefined ) {

			if ( AnimationUtils.isTypedArray( values ) ) {

				for ( let i = 0, n = values.length; i !== n; ++ i ) {

					const value = values[ i ];

					if ( isNaN( value ) ) {

						console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
						valid = false;
						break;

					}

				}

			}

		}

		return valid;

	},

	// removes equivalent sequential keys as common in morph target sequences
	// (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
	optimize: function () {

		// times or values may be shared with other tracks, so overwriting is unsafe
		const times = AnimationUtils.arraySlice( this.times ),
			values = AnimationUtils.arraySlice( this.values ),
			stride = this.getValueSize(),

			smoothInterpolation = this.getInterpolation() === InterpolateSmooth,

			lastIndex = times.length - 1;

		let writeIndex = 1;

		for ( let i = 1; i < lastIndex; ++ i ) {

			let keep = false;

			const time = times[ i ];
			const timeNext = times[ i + 1 ];

			// remove adjacent keyframes scheduled at the same time

			if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {

				if ( ! smoothInterpolation ) {

					// remove unnecessary keyframes same as their neighbors

					const offset = i * stride,
						offsetP = offset - stride,
						offsetN = offset + stride;

					for ( let j = 0; j !== stride; ++ j ) {

						const value = values[ offset + j ];

						if ( value !== values[ offsetP + j ] ||
							value !== values[ offsetN + j ] ) {

							keep = true;
							break;

						}

					}

				} else {

					keep = true;

				}

			}

			// in-place compaction

			if ( keep ) {

				if ( i !== writeIndex ) {

					times[ writeIndex ] = times[ i ];

					const readOffset = i * stride,
						writeOffset = writeIndex * stride;

					for ( let j = 0; j !== stride; ++ j ) {

						values[ writeOffset + j ] = values[ readOffset + j ];

					}

				}

				++ writeIndex;

			}

		}

		// flush last keyframe (compaction looks ahead)

		if ( lastIndex > 0 ) {

			times[ writeIndex ] = times[ lastIndex ];

			for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {

				values[ writeOffset + j ] = values[ readOffset + j ];

			}

			++ writeIndex;

		}

		if ( writeIndex !== times.length ) {

			this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
			this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );

		} else {

			this.times = times;
			this.values = values;

		}

		return this;

	},

	clone: function () {

		const times = AnimationUtils.arraySlice( this.times, 0 );
		const values = AnimationUtils.arraySlice( this.values, 0 );

		const TypedKeyframeTrack = this.constructor;
		const track = new TypedKeyframeTrack( this.name, times, values );

		// Interpolant argument to constructor is not saved, so copy the factory method directly.
		track.createInterpolant = this.createInterpolant;

		return track;

	}

} );

/**
 *
 * A Track of Boolean keyframe values.
 *
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

function BooleanKeyframeTrack( name, times, values ) {

	KeyframeTrack.call( this, name, times, values );

}

BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

	constructor: BooleanKeyframeTrack,

	ValueTypeName: 'bool',
	ValueBufferType: Array,

	DefaultInterpolation: InterpolateDiscrete,

	InterpolantFactoryMethodLinear: undefined,
	InterpolantFactoryMethodSmooth: undefined

	// Note: Actually this track could have a optimized / compressed
	// representation of a single value and a custom interpolant that
	// computes "firstValue ^ isOdd( index )".

} );

/**
 *
 * A Track of keyframe values that represent color.
 *
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

function ColorKeyframeTrack( name, times, values, interpolation ) {

	KeyframeTrack.call( this, name, times, values, interpolation );

}

ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

	constructor: ColorKeyframeTrack,

	ValueTypeName: 'color'

	// ValueBufferType is inherited

	// DefaultInterpolation is inherited

	// Note: Very basic implementation and nothing special yet.
	// However, this is the place for color space parameterization.

} );

/**
 *
 * A Track of numeric keyframe values.
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

function NumberKeyframeTrack( name, times, values, interpolation ) {

	KeyframeTrack.call( this, name, times, values, interpolation );

}

NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

	constructor: NumberKeyframeTrack,

	ValueTypeName: 'number'

	// ValueBufferType is inherited

	// DefaultInterpolation is inherited

} );

/**
 * Spherical linear unit quaternion interpolant.
 *
 * @author tschw
 */

function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {

	Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );

}

QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {

	constructor: QuaternionLinearInterpolant,

	interpolate_: function ( i1, t0, t, t1 ) {

		const result = this.resultBuffer,
			values = this.sampleValues,
			stride = this.valueSize,

			alpha = ( t - t0 ) / ( t1 - t0 );

		let offset = i1 * stride;

		for ( let end = offset + stride; offset !== end; offset += 4 ) {

			Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );

		}

		return result;

	}

} );

/**
 *
 * A Track of quaternion keyframe values.
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

function QuaternionKeyframeTrack( name, times, values, interpolation ) {

	KeyframeTrack.call( this, name, times, values, interpolation );

}

QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

	constructor: QuaternionKeyframeTrack,

	ValueTypeName: 'quaternion',

	// ValueBufferType is inherited

	DefaultInterpolation: InterpolateLinear,

	InterpolantFactoryMethodLinear: function ( result ) {

		return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );

	},

	InterpolantFactoryMethodSmooth: undefined // not yet implemented

} );

/**
 *
 * A Track that interpolates Strings
 *
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

function StringKeyframeTrack( name, times, values, interpolation ) {

	KeyframeTrack.call( this, name, times, values, interpolation );

}

StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

	constructor: StringKeyframeTrack,

	ValueTypeName: 'string',
	ValueBufferType: Array,

	DefaultInterpolation: InterpolateDiscrete,

	InterpolantFactoryMethodLinear: undefined,

	InterpolantFactoryMethodSmooth: undefined

} );

/**
 *
 * A Track of vectored keyframe values.
 *
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

function VectorKeyframeTrack( name, times, values, interpolation ) {

	KeyframeTrack.call( this, name, times, values, interpolation );

}

VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {

	constructor: VectorKeyframeTrack,

	ValueTypeName: 'vector'

	// ValueBufferType is inherited

	// DefaultInterpolation is inherited

} );

/**
 *
 * Reusable set of Tracks that represent an animation.
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 */

function AnimationClip( name, duration, tracks, blendMode ) {

	this.name = name;
	this.tracks = tracks;
	this.duration = ( duration !== undefined ) ? duration : - 1;
	this.blendMode = ( blendMode !== undefined ) ? blendMode : NormalAnimationBlendMode;

	this.uuid = MathUtils.generateUUID();

	// this means it should figure out its duration by scanning the tracks
	if ( this.duration < 0 ) {

		this.resetDuration();

	}

}

function getTrackTypeForValueTypeName( typeName ) {

	switch ( typeName.toLowerCase() ) {

		case 'scalar':
		case 'double':
		case 'float':
		case 'number':
		case 'integer':

			return NumberKeyframeTrack;

		case 'vector':
		case 'vector2':
		case 'vector3':
		case 'vector4':

			return VectorKeyframeTrack;

		case 'color':

			return ColorKeyframeTrack;

		case 'quaternion':

			return QuaternionKeyframeTrack;

		case 'bool':
		case 'boolean':

			return BooleanKeyframeTrack;

		case 'string':

			return StringKeyframeTrack;

	}

	throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );

}

function parseKeyframeTrack( json ) {

	if ( json.type === undefined ) {

		throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );

	}

	const trackType = getTrackTypeForValueTypeName( json.type );

	if ( json.times === undefined ) {

		const times = [], values = [];

		AnimationUtils.flattenJSON( json.keys, times, values, 'value' );

		json.times = times;
		json.values = values;

	}

	// derived classes can define a static parse method
	if ( trackType.parse !== undefined ) {

		return trackType.parse( json );

	} else {

		// by default, we assume a constructor compatible with the base
		return new trackType( json.name, json.times, json.values, json.interpolation );

	}

}

Object.assign( AnimationClip, {

	parse: function ( json ) {

		const tracks = [],
			jsonTracks = json.tracks,
			frameTime = 1.0 / ( json.fps || 1.0 );

		for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {

			tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );

		}

		return new AnimationClip( json.name, json.duration, tracks, json.blendMode );

	},

	toJSON: function ( clip ) {

		const tracks = [],
			clipTracks = clip.tracks;

		const json = {

			'name': clip.name,
			'duration': clip.duration,
			'tracks': tracks,
			'uuid': clip.uuid,
			'blendMode': clip.blendMode

		};

		for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {

			tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );

		}

		return json;

	},

	CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {

		const numMorphTargets = morphTargetSequence.length;
		const tracks = [];

		for ( let i = 0; i < numMorphTargets; i ++ ) {

			let times = [];
			let values = [];

			times.push(
				( i + numMorphTargets - 1 ) % numMorphTargets,
				i,
				( i + 1 ) % numMorphTargets );

			values.push( 0, 1, 0 );

			const order = AnimationUtils.getKeyframeOrder( times );
			times = AnimationUtils.sortedArray( times, 1, order );
			values = AnimationUtils.sortedArray( values, 1, order );

			// if there is a key at the first frame, duplicate it as the
			// last frame as well for perfect loop.
			if ( ! noLoop && times[ 0 ] === 0 ) {

				times.push( numMorphTargets );
				values.push( values[ 0 ] );

			}

			tracks.push(
				new NumberKeyframeTrack(
					'.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
					times, values
				).scale( 1.0 / fps ) );

		}

		return new AnimationClip( name, - 1, tracks );

	},

	findByName: function ( objectOrClipArray, name ) {

		let clipArray = objectOrClipArray;

		if ( ! Array.isArray( objectOrClipArray ) ) {

			const o = objectOrClipArray;
			clipArray = o.geometry && o.geometry.animations || o.animations;

		}

		for ( let i = 0; i < clipArray.length; i ++ ) {

			if ( clipArray[ i ].name === name ) {

				return clipArray[ i ];

			}

		}

		return null;

	},

	CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {

		const animationToMorphTargets = {};

		// tested with https://regex101.com/ on trick sequences
		// such flamingo_flyA_003, flamingo_run1_003, crdeath0059
		const pattern = /^([\w-]*?)([\d]+)$/;

		// sort morph target names into animation groups based
		// patterns like Walk_001, Walk_002, Run_001, Run_002
		for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {

			const morphTarget = morphTargets[ i ];
			const parts = morphTarget.name.match( pattern );

			if ( parts && parts.length > 1 ) {

				const name = parts[ 1 ];

				let animationMorphTargets = animationToMorphTargets[ name ];

				if ( ! animationMorphTargets ) {

					animationToMorphTargets[ name ] = animationMorphTargets = [];

				}

				animationMorphTargets.push( morphTarget );

			}

		}

		const clips = [];

		for ( const name in animationToMorphTargets ) {

			clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );

		}

		return clips;

	},

	// parse the animation.hierarchy format
	parseAnimation: function ( animation, bones ) {

		if ( ! animation ) {

			console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
			return null;

		}

		const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {

			// only return track if there are actually keys.
			if ( animationKeys.length !== 0 ) {

				const times = [];
				const values = [];

				AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );

				// empty keys are filtered out, so check again
				if ( times.length !== 0 ) {

					destTracks.push( new trackType( trackName, times, values ) );

				}

			}

		};

		const tracks = [];

		const clipName = animation.name || 'default';
		const fps = animation.fps || 30;
		const blendMode = animation.blendMode;

		// automatic length determination in AnimationClip.
		let duration = animation.length || - 1;

		const hierarchyTracks = animation.hierarchy || [];

		for ( let h = 0; h < hierarchyTracks.length; h ++ ) {

			const animationKeys = hierarchyTracks[ h ].keys;

			// skip empty tracks
			if ( ! animationKeys || animationKeys.length === 0 ) continue;

			// process morph targets
			if ( animationKeys[ 0 ].morphTargets ) {

				// figure out all morph targets used in this track
				const morphTargetNames = {};

				let k;

				for ( k = 0; k < animationKeys.length; k ++ ) {

					if ( animationKeys[ k ].morphTargets ) {

						for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {

							morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;

						}

					}

				}

				// create a track for each morph target with all zero
				// morphTargetInfluences except for the keys in which
				// the morphTarget is named.
				for ( const morphTargetName in morphTargetNames ) {

					const times = [];
					const values = [];

					for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {

						const animationKey = animationKeys[ k ];

						times.push( animationKey.time );
						values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );

					}

					tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );

				}

				duration = morphTargetNames.length * ( fps || 1.0 );

			} else {

				// ...assume skeletal animation

				const boneName = '.bones[' + bones[ h ].name + ']';

				addNonemptyTrack(
					VectorKeyframeTrack, boneName + '.position',
					animationKeys, 'pos', tracks );

				addNonemptyTrack(
					QuaternionKeyframeTrack, boneName + '.quaternion',
					animationKeys, 'rot', tracks );

				addNonemptyTrack(
					VectorKeyframeTrack, boneName + '.scale',
					animationKeys, 'scl', tracks );

			}

		}

		if ( tracks.length === 0 ) {

			return null;

		}

		const clip = new AnimationClip( clipName, duration, tracks, blendMode );

		return clip;

	}

} );

Object.assign( AnimationClip.prototype, {

	resetDuration: function () {

		const tracks = this.tracks;
		let duration = 0;

		for ( let i = 0, n = tracks.length; i !== n; ++ i ) {

			const track = this.tracks[ i ];

			duration = Math.max( duration, track.times[ track.times.length - 1 ] );

		}

		this.duration = duration;

		return this;

	},

	trim: function () {

		for ( let i = 0; i < this.tracks.length; i ++ ) {

			this.tracks[ i ].trim( 0, this.duration );

		}

		return this;

	},

	validate: function () {

		let valid = true;

		for ( let i = 0; i < this.tracks.length; i ++ ) {

			valid = valid && this.tracks[ i ].validate();

		}

		return valid;

	},

	optimize: function () {

		for ( let i = 0; i < this.tracks.length; i ++ ) {

			this.tracks[ i ].optimize();

		}

		return this;

	},

	clone: function () {

		const tracks = [];

		for ( let i = 0; i < this.tracks.length; i ++ ) {

			tracks.push( this.tracks[ i ].clone() );

		}

		return new AnimationClip( this.name, this.duration, tracks, this.blendMode );

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

const Cache = {

	enabled: false,

	files: {},

	add: function ( key, file ) {

		if ( this.enabled === false ) return;

		// console.log( 'THREE.Cache', 'Adding key:', key );

		this.files[ key ] = file;

	},

	get: function ( key ) {

		if ( this.enabled === false ) return;

		// console.log( 'THREE.Cache', 'Checking key:', key );

		return this.files[ key ];

	},

	remove: function ( key ) {

		delete this.files[ key ];

	},

	clear: function () {

		this.files = {};

	}

};

/**
 * @author mrdoob / http://mrdoob.com/
 */

function LoadingManager( onLoad, onProgress, onError ) {

	const scope = this;

	let isLoading = false;
	let itemsLoaded = 0;
	let itemsTotal = 0;
	let urlModifier = undefined;
	const handlers = [];

	// Refer to #5689 for the reason why we don't set .onStart
	// in the constructor

	this.onStart = undefined;
	this.onLoad = onLoad;
	this.onProgress = onProgress;
	this.onError = onError;

	this.itemStart = function ( url ) {

		itemsTotal ++;

		if ( isLoading === false ) {

			if ( scope.onStart !== undefined ) {

				scope.onStart( url, itemsLoaded, itemsTotal );

			}

		}

		isLoading = true;

	};

	this.itemEnd = function ( url ) {

		itemsLoaded ++;

		if ( scope.onProgress !== undefined ) {

			scope.onProgress( url, itemsLoaded, itemsTotal );

		}

		if ( itemsLoaded === itemsTotal ) {

			isLoading = false;

			if ( scope.onLoad !== undefined ) {

				scope.onLoad();

			}

		}

	};

	this.itemError = function ( url ) {

		if ( scope.onError !== undefined ) {

			scope.onError( url );

		}

	};

	this.resolveURL = function ( url ) {

		if ( urlModifier ) {

			return urlModifier( url );

		}

		return url;

	};

	this.setURLModifier = function ( transform ) {

		urlModifier = transform;

		return this;

	};

	this.addHandler = function ( regex, loader ) {

		handlers.push( regex, loader );

		return this;

	};

	this.removeHandler = function ( regex ) {

		const index = handlers.indexOf( regex );

		if ( index !== - 1 ) {

			handlers.splice( index, 2 );

		}

		return this;

	};

	this.getHandler = function ( file ) {

		for ( let i = 0, l = handlers.length; i < l; i += 2 ) {

			const regex = handlers[ i ];
			const loader = handlers[ i + 1 ];

			if ( regex.global ) regex.lastIndex = 0; // see #17920

			if ( regex.test( file ) ) {

				return loader;

			}

		}

		return null;

	};

}

const DefaultLoadingManager = new LoadingManager();

/**
 * @author alteredq / http://alteredqualia.com/
 */

function Loader( manager ) {

	this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

	this.crossOrigin = 'anonymous';
	this.path = '';
	this.resourcePath = '';
	this.requestHeader = {};

}

Object.assign( Loader.prototype, {

	load: function ( /* url, onLoad, onProgress, onError */ ) {},

	loadAsync: function ( url, onProgress ) {

		const scope = this;

		return new Promise( function ( resolve, reject ) {

			scope.load( url, resolve, onProgress, reject );

		} );

	},

	parse: function ( /* data */ ) {},

	setCrossOrigin: function ( crossOrigin ) {

		this.crossOrigin = crossOrigin;
		return this;

	},

	setPath: function ( path ) {

		this.path = path;
		return this;

	},

	setResourcePath: function ( resourcePath ) {

		this.resourcePath = resourcePath;
		return this;

	},

	setRequestHeader: function ( requestHeader ) {

		this.requestHeader = requestHeader;
		return this;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

const loading = {};

function FileLoader( manager ) {

	Loader.call( this, manager );

}

FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: FileLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		if ( url === undefined ) url = '';

		if ( this.path !== undefined ) url = this.path + url;

		url = this.manager.resolveURL( url );

		const scope = this;

		const cached = Cache.get( url );

		if ( cached !== undefined ) {

			scope.manager.itemStart( url );

			setTimeout( function () {

				if ( onLoad ) onLoad( cached );

				scope.manager.itemEnd( url );

			}, 0 );

			return cached;

		}

		// Check if request is duplicate

		if ( loading[ url ] !== undefined ) {

			loading[ url ].push( {

				onLoad: onLoad,
				onProgress: onProgress,
				onError: onError

			} );

			return;

		}

		// Check for data: URI
		const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
		const dataUriRegexResult = url.match( dataUriRegex );
		let request;

		// Safari can not handle Data URIs through XMLHttpRequest so process manually
		if ( dataUriRegexResult ) {

			const mimeType = dataUriRegexResult[ 1 ];
			const isBase64 = !! dataUriRegexResult[ 2 ];

			let data = dataUriRegexResult[ 3 ];
			data = decodeURIComponent( data );

			if ( isBase64 ) data = atob( data );

			try {

				let response;
				const responseType = ( this.responseType || '' ).toLowerCase();

				switch ( responseType ) {

					case 'arraybuffer':
					case 'blob':

						const view = new Uint8Array( data.length );

						for ( let i = 0; i < data.length; i ++ ) {

							view[ i ] = data.charCodeAt( i );

						}

						if ( responseType === 'blob' ) {

							response = new Blob( [ view.buffer ], { type: mimeType } );

						} else {

							response = view.buffer;

						}

						break;

					case 'document':

						const parser = new DOMParser();
						response = parser.parseFromString( data, mimeType );

						break;

					case 'json':

						response = JSON.parse( data );

						break;

					default: // 'text' or other

						response = data;

						break;

				}

				// Wait for next browser tick like standard XMLHttpRequest event dispatching does
				setTimeout( function () {

					if ( onLoad ) onLoad( response );

					scope.manager.itemEnd( url );

				}, 0 );

			} catch ( error ) {

				// Wait for next browser tick like standard XMLHttpRequest event dispatching does
				setTimeout( function () {

					if ( onError ) onError( error );

					scope.manager.itemError( url );
					scope.manager.itemEnd( url );

				}, 0 );

			}

		} else {

			// Initialise array for duplicate requests

			loading[ url ] = [];

			loading[ url ].push( {

				onLoad: onLoad,
				onProgress: onProgress,
				onError: onError

			} );

			request = new XMLHttpRequest();

			request.open( 'GET', url, true );

			request.addEventListener( 'load', function ( event ) {

				const response = this.response;

				const callbacks = loading[ url ];

				delete loading[ url ];

				if ( this.status === 200 || this.status === 0 ) {

					// Some browsers return HTTP Status 0 when using non-http protocol
					// e.g. 'file://' or 'data://'. Handle as success.

					if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );

					// Add to cache only on HTTP success, so that we do not cache
					// error response bodies as proper responses to requests.
					Cache.add( url, response );

					for ( let i = 0, il = callbacks.length; i < il; i ++ ) {

						const callback = callbacks[ i ];
						if ( callback.onLoad ) callback.onLoad( response );

					}

					scope.manager.itemEnd( url );

				} else {

					for ( let i = 0, il = callbacks.length; i < il; i ++ ) {

						const callback = callbacks[ i ];
						if ( callback.onError ) callback.onError( event );

					}

					scope.manager.itemError( url );
					scope.manager.itemEnd( url );

				}

			}, false );

			request.addEventListener( 'progress', function ( event ) {

				const callbacks = loading[ url ];

				for ( let i = 0, il = callbacks.length; i < il; i ++ ) {

					const callback = callbacks[ i ];
					if ( callback.onProgress ) callback.onProgress( event );

				}

			}, false );

			request.addEventListener( 'error', function ( event ) {

				const callbacks = loading[ url ];

				delete loading[ url ];

				for ( let i = 0, il = callbacks.length; i < il; i ++ ) {

					const callback = callbacks[ i ];
					if ( callback.onError ) callback.onError( event );

				}

				scope.manager.itemError( url );
				scope.manager.itemEnd( url );

			}, false );

			request.addEventListener( 'abort', function ( event ) {

				const callbacks = loading[ url ];

				delete loading[ url ];

				for ( let i = 0, il = callbacks.length; i < il; i ++ ) {

					const callback = callbacks[ i ];
					if ( callback.onError ) callback.onError( event );

				}

				scope.manager.itemError( url );
				scope.manager.itemEnd( url );

			}, false );

			if ( this.responseType !== undefined ) request.responseType = this.responseType;
			if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;

			if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );

			for ( const header in this.requestHeader ) {

				request.setRequestHeader( header, this.requestHeader[ header ] );

			}

			request.send( null );

		}

		scope.manager.itemStart( url );

		return request;

	},

	setResponseType: function ( value ) {

		this.responseType = value;
		return this;

	},

	setWithCredentials: function ( value ) {

		this.withCredentials = value;
		return this;

	},

	setMimeType: function ( value ) {

		this.mimeType = value;
		return this;

	}

} );

/**
 * @author bhouston / http://clara.io/
 */

function AnimationLoader( manager ) {

	Loader.call( this, manager );

}

AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: AnimationLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const loader = new FileLoader( scope.manager );
		loader.setPath( scope.path );
		loader.load( url, function ( text ) {

			try {

				onLoad( scope.parse( JSON.parse( text ) ) );

			} catch ( e ) {

				if ( onError ) {

					onError( e );

				} else {

					console.error( e );

				}

				scope.manager.itemError( url );

			}

		}, onProgress, onError );

	},

	parse: function ( json ) {

		const animations = [];

		for ( let i = 0; i < json.length; i ++ ) {

			const clip = AnimationClip.parse( json[ i ] );

			animations.push( clip );

		}

		return animations;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 *
 * Abstract Base class to block based textures loader (dds, pvr, ...)
 *
 * Sub classes have to implement the parse() method which will be used in load().
 */

function CompressedTextureLoader( manager ) {

	Loader.call( this, manager );

}

CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: CompressedTextureLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const images = [];

		const texture = new CompressedTexture();
		texture.image = images;

		const loader = new FileLoader( this.manager );
		loader.setPath( this.path );
		loader.setResponseType( 'arraybuffer' );

		let loaded = 0;

		function loadTexture( i ) {

			loader.load( url[ i ], function ( buffer ) {

				const texDatas = scope.parse( buffer, true );

				images[ i ] = {
					width: texDatas.width,
					height: texDatas.height,
					format: texDatas.format,
					mipmaps: texDatas.mipmaps
				};

				loaded += 1;

				if ( loaded === 6 ) {

					if ( texDatas.mipmapCount === 1 )
						texture.minFilter = LinearFilter;

					texture.format = texDatas.format;
					texture.needsUpdate = true;

					if ( onLoad ) onLoad( texture );

				}

			}, onProgress, onError );

		}

		if ( Array.isArray( url ) ) {

			for ( let i = 0, il = url.length; i < il; ++ i ) {

				loadTexture( i );

			}

		} else {

			// compressed cubemap texture stored in a single DDS file

			loader.load( url, function ( buffer ) {

				const texDatas = scope.parse( buffer, true );

				if ( texDatas.isCubemap ) {

					const faces = texDatas.mipmaps.length / texDatas.mipmapCount;

					for ( let f = 0; f < faces; f ++ ) {

						images[ f ] = { mipmaps: [] };

						for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {

							images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
							images[ f ].format = texDatas.format;
							images[ f ].width = texDatas.width;
							images[ f ].height = texDatas.height;

						}

					}

				} else {

					texture.image.width = texDatas.width;
					texture.image.height = texDatas.height;
					texture.mipmaps = texDatas.mipmaps;

				}

				if ( texDatas.mipmapCount === 1 ) {

					texture.minFilter = LinearFilter;

				}

				texture.format = texDatas.format;
				texture.needsUpdate = true;

				if ( onLoad ) onLoad( texture );

			}, onProgress, onError );

		}

		return texture;

	}

} );

/**
 * @author Nikos M. / https://github.com/foo123/
 *
 * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
 *
 * Sub classes have to implement the parse() method which will be used in load().
 */

function DataTextureLoader( manager ) {

	Loader.call( this, manager );

}

DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: DataTextureLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const texture = new DataTexture();

		const loader = new FileLoader( this.manager );
		loader.setResponseType( 'arraybuffer' );
		loader.setPath( this.path );
		loader.load( url, function ( buffer ) {

			const texData = scope.parse( buffer );

			if ( ! texData ) return;

			if ( texData.image !== undefined ) {

				texture.image = texData.image;

			} else if ( texData.data !== undefined ) {

				texture.image.width = texData.width;
				texture.image.height = texData.height;
				texture.image.data = texData.data;

			}

			texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
			texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;

			texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
			texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;

			texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;

			if ( texData.format !== undefined ) {

				texture.format = texData.format;

			}

			if ( texData.type !== undefined ) {

				texture.type = texData.type;

			}

			if ( texData.mipmaps !== undefined ) {

				texture.mipmaps = texData.mipmaps;
				texture.minFilter = LinearMipmapLinearFilter; // presumably...

			}

			if ( texData.mipmapCount === 1 ) {

				texture.minFilter = LinearFilter;

			}

			texture.needsUpdate = true;

			if ( onLoad ) onLoad( texture, texData );

		}, onProgress, onError );


		return texture;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function ImageLoader( manager ) {

	Loader.call( this, manager );

}

ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: ImageLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		if ( this.path !== undefined ) url = this.path + url;

		url = this.manager.resolveURL( url );

		const scope = this;

		const cached = Cache.get( url );

		if ( cached !== undefined ) {

			scope.manager.itemStart( url );

			setTimeout( function () {

				if ( onLoad ) onLoad( cached );

				scope.manager.itemEnd( url );

			}, 0 );

			return cached;

		}

		const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );

		function onImageLoad() {

			image.removeEventListener( 'load', onImageLoad, false );
			image.removeEventListener( 'error', onImageError, false );

			Cache.add( url, this );

			if ( onLoad ) onLoad( this );

			scope.manager.itemEnd( url );

		}

		function onImageError( event ) {

			image.removeEventListener( 'load', onImageLoad, false );
			image.removeEventListener( 'error', onImageError, false );

			if ( onError ) onError( event );

			scope.manager.itemError( url );
			scope.manager.itemEnd( url );

		}

		image.addEventListener( 'load', onImageLoad, false );
		image.addEventListener( 'error', onImageError, false );

		if ( url.substr( 0, 5 ) !== 'data:' ) {

			if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;

		}

		scope.manager.itemStart( url );

		image.src = url;

		return image;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */


function CubeTextureLoader( manager ) {

	Loader.call( this, manager );

}

CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: CubeTextureLoader,

	load: function ( urls, onLoad, onProgress, onError ) {

		const texture = new CubeTexture();

		const loader = new ImageLoader( this.manager );
		loader.setCrossOrigin( this.crossOrigin );
		loader.setPath( this.path );

		let loaded = 0;

		function loadTexture( i ) {

			loader.load( urls[ i ], function ( image ) {

				texture.images[ i ] = image;

				loaded ++;

				if ( loaded === 6 ) {

					texture.needsUpdate = true;

					if ( onLoad ) onLoad( texture );

				}

			}, undefined, onError );

		}

		for ( let i = 0; i < urls.length; ++ i ) {

			loadTexture( i );

		}

		return texture;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function TextureLoader( manager ) {

	Loader.call( this, manager );

}

TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: TextureLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const texture = new Texture();

		const loader = new ImageLoader( this.manager );
		loader.setCrossOrigin( this.crossOrigin );
		loader.setPath( this.path );

		loader.load( url, function ( image ) {

			texture.image = image;

			// JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
			const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;

			texture.format = isJPEG ? RGBFormat : RGBAFormat;
			texture.needsUpdate = true;

			if ( onLoad !== undefined ) {

				onLoad( texture );

			}

		}, onProgress, onError );

		return texture;

	}

} );

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * Extensible curve object
 *
 * Some common of curve methods:
 * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
 * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
 * .getPoints(), .getSpacedPoints()
 * .getLength()
 * .updateArcLengths()
 *
 * This following curves inherit from THREE.Curve:
 *
 * -- 2D curves --
 * THREE.ArcCurve
 * THREE.CubicBezierCurve
 * THREE.EllipseCurve
 * THREE.LineCurve
 * THREE.QuadraticBezierCurve
 * THREE.SplineCurve
 *
 * -- 3D curves --
 * THREE.CatmullRomCurve3
 * THREE.CubicBezierCurve3
 * THREE.LineCurve3
 * THREE.QuadraticBezierCurve3
 *
 * A series of curves can be represented as a THREE.CurvePath.
 *
 **/

/**************************************************************
 *	Abstract Curve base class
 **************************************************************/

function Curve() {

	this.type = 'Curve';

	this.arcLengthDivisions = 200;

}

Object.assign( Curve.prototype, {

	// Virtual base class method to overwrite and implement in subclasses
	//	- t [0 .. 1]

	getPoint: function ( /* t, optionalTarget */ ) {

		console.warn( 'THREE.Curve: .getPoint() not implemented.' );
		return null;

	},

	// Get point at relative position in curve according to arc length
	// - u [0 .. 1]

	getPointAt: function ( u, optionalTarget ) {

		const t = this.getUtoTmapping( u );
		return this.getPoint( t, optionalTarget );

	},

	// Get sequence of points using getPoint( t )

	getPoints: function ( divisions ) {

		if ( divisions === undefined ) divisions = 5;

		const points = [];

		for ( let d = 0; d <= divisions; d ++ ) {

			points.push( this.getPoint( d / divisions ) );

		}

		return points;

	},

	// Get sequence of points using getPointAt( u )

	getSpacedPoints: function ( divisions ) {

		if ( divisions === undefined ) divisions = 5;

		const points = [];

		for ( let d = 0; d <= divisions; d ++ ) {

			points.push( this.getPointAt( d / divisions ) );

		}

		return points;

	},

	// Get total curve arc length

	getLength: function () {

		const lengths = this.getLengths();
		return lengths[ lengths.length - 1 ];

	},

	// Get list of cumulative segment lengths

	getLengths: function ( divisions ) {

		if ( divisions === undefined ) divisions = this.arcLengthDivisions;

		if ( this.cacheArcLengths &&
			( this.cacheArcLengths.length === divisions + 1 ) &&
			! this.needsUpdate ) {

			return this.cacheArcLengths;

		}

		this.needsUpdate = false;

		const cache = [];
		let current, last = this.getPoint( 0 );
		let sum = 0;

		cache.push( 0 );

		for ( let p = 1; p <= divisions; p ++ ) {

			current = this.getPoint( p / divisions );
			sum += current.distanceTo( last );
			cache.push( sum );
			last = current;

		}

		this.cacheArcLengths = cache;

		return cache; // { sums: cache, sum: sum }; Sum is in the last element.

	},

	updateArcLengths: function () {

		this.needsUpdate = true;
		this.getLengths();

	},

	// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant

	getUtoTmapping: function ( u, distance ) {

		const arcLengths = this.getLengths();

		let i = 0, il = arcLengths.length;

		let targetArcLength; // The targeted u distance value to get

		if ( distance ) {

			targetArcLength = distance;

		} else {

			targetArcLength = u * arcLengths[ il - 1 ];

		}

		// binary search for the index with largest value smaller than target u distance

		let low = 0, high = il - 1, comparison;

		while ( low <= high ) {

			i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats

			comparison = arcLengths[ i ] - targetArcLength;

			if ( comparison < 0 ) {

				low = i + 1;

			} else if ( comparison > 0 ) {

				high = i - 1;

			} else {

				high = i;
				break;

				// DONE

			}

		}

		i = high;

		if ( arcLengths[ i ] === targetArcLength ) {

			return i / ( il - 1 );

		}

		// we could get finer grain at lengths, or use simple interpolation between two points

		const lengthBefore = arcLengths[ i ];
		const lengthAfter = arcLengths[ i + 1 ];

		const segmentLength = lengthAfter - lengthBefore;

		// determine where we are between the 'before' and 'after' points

		const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;

		// add that fractional amount to t

		const t = ( i + segmentFraction ) / ( il - 1 );

		return t;

	},

	// Returns a unit vector tangent at t
	// In case any sub curve does not implement its tangent derivation,
	// 2 points a small delta apart will be used to find its gradient
	// which seems to give a reasonable approximation

	getTangent: function ( t, optionalTarget ) {

		const delta = 0.0001;
		let t1 = t - delta;
		let t2 = t + delta;

		// Capping in case of danger

		if ( t1 < 0 ) t1 = 0;
		if ( t2 > 1 ) t2 = 1;

		const pt1 = this.getPoint( t1 );
		const pt2 = this.getPoint( t2 );

		const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );

		tangent.copy( pt2 ).sub( pt1 ).normalize();

		return tangent;

	},

	getTangentAt: function ( u, optionalTarget ) {

		const t = this.getUtoTmapping( u );
		return this.getTangent( t, optionalTarget );

	},

	computeFrenetFrames: function ( segments, closed ) {

		// see http://www.cs.indiana.edu/pub/techreports/TR425.pdf

		const normal = new Vector3();

		const tangents = [];
		const normals = [];
		const binormals = [];

		const vec = new Vector3();
		const mat = new Matrix4();

		// compute the tangent vectors for each segment on the curve

		for ( let i = 0; i <= segments; i ++ ) {

			const u = i / segments;

			tangents[ i ] = this.getTangentAt( u, new Vector3() );
			tangents[ i ].normalize();

		}

		// select an initial normal vector perpendicular to the first tangent vector,
		// and in the direction of the minimum tangent xyz component

		normals[ 0 ] = new Vector3();
		binormals[ 0 ] = new Vector3();
		let min = Number.MAX_VALUE;
		const tx = Math.abs( tangents[ 0 ].x );
		const ty = Math.abs( tangents[ 0 ].y );
		const tz = Math.abs( tangents[ 0 ].z );

		if ( tx <= min ) {

			min = tx;
			normal.set( 1, 0, 0 );

		}

		if ( ty <= min ) {

			min = ty;
			normal.set( 0, 1, 0 );

		}

		if ( tz <= min ) {

			normal.set( 0, 0, 1 );

		}

		vec.crossVectors( tangents[ 0 ], normal ).normalize();

		normals[ 0 ].crossVectors( tangents[ 0 ], vec );
		binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );


		// compute the slowly-varying normal and binormal vectors for each segment on the curve

		for ( let i = 1; i <= segments; i ++ ) {

			normals[ i ] = normals[ i - 1 ].clone();

			binormals[ i ] = binormals[ i - 1 ].clone();

			vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );

			if ( vec.length() > Number.EPSILON ) {

				vec.normalize();

				const theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors

				normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );

			}

			binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );

		}

		// if the curve is closed, postprocess the vectors so the first and last normal vectors are the same

		if ( closed === true ) {

			let theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
			theta /= segments;

			if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {

				theta = - theta;

			}

			for ( let i = 1; i <= segments; i ++ ) {

				// twist a little...
				normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
				binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );

			}

		}

		return {
			tangents: tangents,
			normals: normals,
			binormals: binormals
		};

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( source ) {

		this.arcLengthDivisions = source.arcLengthDivisions;

		return this;

	},

	toJSON: function () {

		const data = {
			metadata: {
				version: 4.5,
				type: 'Curve',
				generator: 'Curve.toJSON'
			}
		};

		data.arcLengthDivisions = this.arcLengthDivisions;
		data.type = this.type;

		return data;

	},

	fromJSON: function ( json ) {

		this.arcLengthDivisions = json.arcLengthDivisions;

		return this;

	}

} );

function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {

	Curve.call( this );

	this.type = 'EllipseCurve';

	this.aX = aX || 0;
	this.aY = aY || 0;

	this.xRadius = xRadius || 1;
	this.yRadius = yRadius || 1;

	this.aStartAngle = aStartAngle || 0;
	this.aEndAngle = aEndAngle || 2 * Math.PI;

	this.aClockwise = aClockwise || false;

	this.aRotation = aRotation || 0;

}

EllipseCurve.prototype = Object.create( Curve.prototype );
EllipseCurve.prototype.constructor = EllipseCurve;

EllipseCurve.prototype.isEllipseCurve = true;

EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {

	const point = optionalTarget || new Vector2();

	const twoPi = Math.PI * 2;
	let deltaAngle = this.aEndAngle - this.aStartAngle;
	const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;

	// ensures that deltaAngle is 0 .. 2 PI
	while ( deltaAngle < 0 ) deltaAngle += twoPi;
	while ( deltaAngle > twoPi ) deltaAngle -= twoPi;

	if ( deltaAngle < Number.EPSILON ) {

		if ( samePoints ) {

			deltaAngle = 0;

		} else {

			deltaAngle = twoPi;

		}

	}

	if ( this.aClockwise === true && ! samePoints ) {

		if ( deltaAngle === twoPi ) {

			deltaAngle = - twoPi;

		} else {

			deltaAngle = deltaAngle - twoPi;

		}

	}

	const angle = this.aStartAngle + t * deltaAngle;
	let x = this.aX + this.xRadius * Math.cos( angle );
	let y = this.aY + this.yRadius * Math.sin( angle );

	if ( this.aRotation !== 0 ) {

		const cos = Math.cos( this.aRotation );
		const sin = Math.sin( this.aRotation );

		const tx = x - this.aX;
		const ty = y - this.aY;

		// Rotate the point about the center of the ellipse.
		x = tx * cos - ty * sin + this.aX;
		y = tx * sin + ty * cos + this.aY;

	}

	return point.set( x, y );

};

EllipseCurve.prototype.copy = function ( source ) {

	Curve.prototype.copy.call( this, source );

	this.aX = source.aX;
	this.aY = source.aY;

	this.xRadius = source.xRadius;
	this.yRadius = source.yRadius;

	this.aStartAngle = source.aStartAngle;
	this.aEndAngle = source.aEndAngle;

	this.aClockwise = source.aClockwise;

	this.aRotation = source.aRotation;

	return this;

};


EllipseCurve.prototype.toJSON = function () {

	const data = Curve.prototype.toJSON.call( this );

	data.aX = this.aX;
	data.aY = this.aY;

	data.xRadius = this.xRadius;
	data.yRadius = this.yRadius;

	data.aStartAngle = this.aStartAngle;
	data.aEndAngle = this.aEndAngle;

	data.aClockwise = this.aClockwise;

	data.aRotation = this.aRotation;

	return data;

};

EllipseCurve.prototype.fromJSON = function ( json ) {

	Curve.prototype.fromJSON.call( this, json );

	this.aX = json.aX;
	this.aY = json.aY;

	this.xRadius = json.xRadius;
	this.yRadius = json.yRadius;

	this.aStartAngle = json.aStartAngle;
	this.aEndAngle = json.aEndAngle;

	this.aClockwise = json.aClockwise;

	this.aRotation = json.aRotation;

	return this;

};

function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

	EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );

	this.type = 'ArcCurve';

}

ArcCurve.prototype = Object.create( EllipseCurve.prototype );
ArcCurve.prototype.constructor = ArcCurve;

ArcCurve.prototype.isArcCurve = true;

/**
 * @author zz85 https://github.com/zz85
 *
 * Centripetal CatmullRom Curve - which is useful for avoiding
 * cusps and self-intersections in non-uniform catmull rom curves.
 * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
 *
 * curve.type accepts centripetal(default), chordal and catmullrom
 * curve.tension is used for catmullrom which defaults to 0.5
 */


/*
Based on an optimized c++ solution in
 - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
 - http://ideone.com/NoEbVM

This CubicPoly class could be used for reusing some variables and calculations,
but for three.js curve use, it could be possible inlined and flatten into a single function call
which can be placed in CurveUtils.
*/

function CubicPoly() {

	let c0 = 0, c1 = 0, c2 = 0, c3 = 0;

	/*
	 * Compute coefficients for a cubic polynomial
	 *   p(s) = c0 + c1*s + c2*s^2 + c3*s^3
	 * such that
	 *   p(0) = x0, p(1) = x1
	 *  and
	 *   p'(0) = t0, p'(1) = t1.
	 */
	function init( x0, x1, t0, t1 ) {

		c0 = x0;
		c1 = t0;
		c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
		c3 = 2 * x0 - 2 * x1 + t0 + t1;

	}

	return {

		initCatmullRom: function ( x0, x1, x2, x3, tension ) {

			init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );

		},

		initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {

			// compute tangents when parameterized in [t1,t2]
			let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
			let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;

			// rescale tangents for parametrization in [0,1]
			t1 *= dt1;
			t2 *= dt1;

			init( x1, x2, t1, t2 );

		},

		calc: function ( t ) {

			const t2 = t * t;
			const t3 = t2 * t;
			return c0 + c1 * t + c2 * t2 + c3 * t3;

		}

	};

}

//

const tmp = new Vector3();
const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();

function CatmullRomCurve3( points, closed, curveType, tension ) {

	Curve.call( this );

	this.type = 'CatmullRomCurve3';

	this.points = points || [];
	this.closed = closed || false;
	this.curveType = curveType || 'centripetal';
	this.tension = tension || 0.5;

}

CatmullRomCurve3.prototype = Object.create( Curve.prototype );
CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;

CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;

CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {

	const point = optionalTarget || new Vector3();

	const points = this.points;
	const l = points.length;

	const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
	let intPoint = Math.floor( p );
	let weight = p - intPoint;

	if ( this.closed ) {

		intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;

	} else if ( weight === 0 && intPoint === l - 1 ) {

		intPoint = l - 2;
		weight = 1;

	}

	let p0, p1, p2, p3; // 4 points

	if ( this.closed || intPoint > 0 ) {

		p0 = points[ ( intPoint - 1 ) % l ];

	} else {

		// extrapolate first point
		tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
		p0 = tmp;

	}

	p1 = points[ intPoint % l ];
	p2 = points[ ( intPoint + 1 ) % l ];

	if ( this.closed || intPoint + 2 < l ) {

		p3 = points[ ( intPoint + 2 ) % l ];

	} else {

		// extrapolate last point
		tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
		p3 = tmp;

	}

	if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {

		// init Centripetal / Chordal Catmull-Rom
		const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
		let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
		let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
		let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );

		// safety check for repeated points
		if ( dt1 < 1e-4 ) dt1 = 1.0;
		if ( dt0 < 1e-4 ) dt0 = dt1;
		if ( dt2 < 1e-4 ) dt2 = dt1;

		px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
		py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
		pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );

	} else if ( this.curveType === 'catmullrom' ) {

		px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
		py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
		pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );

	}

	point.set(
		px.calc( weight ),
		py.calc( weight ),
		pz.calc( weight )
	);

	return point;

};

CatmullRomCurve3.prototype.copy = function ( source ) {

	Curve.prototype.copy.call( this, source );

	this.points = [];

	for ( let i = 0, l = source.points.length; i < l; i ++ ) {

		const point = source.points[ i ];

		this.points.push( point.clone() );

	}

	this.closed = source.closed;
	this.curveType = source.curveType;
	this.tension = source.tension;

	return this;

};

CatmullRomCurve3.prototype.toJSON = function () {

	const data = Curve.prototype.toJSON.call( this );

	data.points = [];

	for ( let i = 0, l = this.points.length; i < l; i ++ ) {

		const point = this.points[ i ];
		data.points.push( point.toArray() );

	}

	data.closed = this.closed;
	data.curveType = this.curveType;
	data.tension = this.tension;

	return data;

};

CatmullRomCurve3.prototype.fromJSON = function ( json ) {

	Curve.prototype.fromJSON.call( this, json );

	this.points = [];

	for ( let i = 0, l = json.points.length; i < l; i ++ ) {

		const point = json.points[ i ];
		this.points.push( new Vector3().fromArray( point ) );

	}

	this.closed = json.closed;
	this.curveType = json.curveType;
	this.tension = json.tension;

	return this;

};

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 *
 * Bezier Curves formulas obtained from
 * http://en.wikipedia.org/wiki/Bézier_curve
 */

function CatmullRom( t, p0, p1, p2, p3 ) {

	const v0 = ( p2 - p0 ) * 0.5;
	const v1 = ( p3 - p1 ) * 0.5;
	const t2 = t * t;
	const t3 = t * t2;
	return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;

}

//

function QuadraticBezierP0( t, p ) {

	const k = 1 - t;
	return k * k * p;

}

function QuadraticBezierP1( t, p ) {

	return 2 * ( 1 - t ) * t * p;

}

function QuadraticBezierP2( t, p ) {

	return t * t * p;

}

function QuadraticBezier( t, p0, p1, p2 ) {

	return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
		QuadraticBezierP2( t, p2 );

}

//

function CubicBezierP0( t, p ) {

	const k = 1 - t;
	return k * k * k * p;

}

function CubicBezierP1( t, p ) {

	const k = 1 - t;
	return 3 * k * k * t * p;

}

function CubicBezierP2( t, p ) {

	return 3 * ( 1 - t ) * t * t * p;

}

function CubicBezierP3( t, p ) {

	return t * t * t * p;

}

function CubicBezier( t, p0, p1, p2, p3 ) {

	return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
		CubicBezierP3( t, p3 );

}

function CubicBezierCurve( v0, v1, v2, v3 ) {

	Curve.call( this );

	this.type = 'CubicBezierCurve';

	this.v0 = v0 || new Vector2();
	this.v1 = v1 || new Vector2();
	this.v2 = v2 || new Vector2();
	this.v3 = v3 || new Vector2();

}

CubicBezierCurve.prototype = Object.create( Curve.prototype );
CubicBezierCurve.prototype.constructor = CubicBezierCurve;

CubicBezierCurve.prototype.isCubicBezierCurve = true;

CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {

	const point = optionalTarget || new Vector2();

	const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;

	point.set(
		CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
		CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
	);

	return point;

};

CubicBezierCurve.prototype.copy = function ( source ) {

	Curve.prototype.copy.call( this, source );

	this.v0.copy( source.v0 );
	this.v1.copy( source.v1 );
	this.v2.copy( source.v2 );
	this.v3.copy( source.v3 );

	return this;

};

CubicBezierCurve.prototype.toJSON = function () {

	const data = Curve.prototype.toJSON.call( this );

	data.v0 = this.v0.toArray();
	data.v1 = this.v1.toArray();
	data.v2 = this.v2.toArray();
	data.v3 = this.v3.toArray();

	return data;

};

CubicBezierCurve.prototype.fromJSON = function ( json ) {

	Curve.prototype.fromJSON.call( this, json );

	this.v0.fromArray( json.v0 );
	this.v1.fromArray( json.v1 );
	this.v2.fromArray( json.v2 );
	this.v3.fromArray( json.v3 );

	return this;

};

function CubicBezierCurve3( v0, v1, v2, v3 ) {

	Curve.call( this );

	this.type = 'CubicBezierCurve3';

	this.v0 = v0 || new Vector3();
	this.v1 = v1 || new Vector3();
	this.v2 = v2 || new Vector3();
	this.v3 = v3 || new Vector3();

}

CubicBezierCurve3.prototype = Object.create( Curve.prototype );
CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;

CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;

CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {

	const point = optionalTarget || new Vector3();

	const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;

	point.set(
		CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
		CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
		CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
	);

	return point;

};

CubicBezierCurve3.prototype.copy = function ( source ) {

	Curve.prototype.copy.call( this, source );

	this.v0.copy( source.v0 );
	this.v1.copy( source.v1 );
	this.v2.copy( source.v2 );
	this.v3.copy( source.v3 );

	return this;

};

CubicBezierCurve3.prototype.toJSON = function () {

	const data = Curve.prototype.toJSON.call( this );

	data.v0 = this.v0.toArray();
	data.v1 = this.v1.toArray();
	data.v2 = this.v2.toArray();
	data.v3 = this.v3.toArray();

	return data;

};

CubicBezierCurve3.prototype.fromJSON = function ( json ) {

	Curve.prototype.fromJSON.call( this, json );

	this.v0.fromArray( json.v0 );
	this.v1.fromArray( json.v1 );
	this.v2.fromArray( json.v2 );
	this.v3.fromArray( json.v3 );

	return this;

};

function LineCurve( v1, v2 ) {

	Curve.call( this );

	this.type = 'LineCurve';

	this.v1 = v1 || new Vector2();
	this.v2 = v2 || new Vector2();

}

LineCurve.prototype = Object.create( Curve.prototype );
LineCurve.prototype.constructor = LineCurve;

LineCurve.prototype.isLineCurve = true;

LineCurve.prototype.getPoint = function ( t, optionalTarget ) {

	const point = optionalTarget || new Vector2();

	if ( t === 1 ) {

		point.copy( this.v2 );

	} else {

		point.copy( this.v2 ).sub( this.v1 );
		point.multiplyScalar( t ).add( this.v1 );

	}

	return point;

};

// Line curve is linear, so we can overwrite default getPointAt

LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {

	return this.getPoint( u, optionalTarget );

};

LineCurve.prototype.getTangent = function ( t, optionalTarget ) {

	const tangent = optionalTarget || new Vector2();

	tangent.copy( this.v2 ).sub( this.v1 ).normalize();

	return tangent;

};

LineCurve.prototype.copy = function ( source ) {

	Curve.prototype.copy.call( this, source );

	this.v1.copy( source.v1 );
	this.v2.copy( source.v2 );

	return this;

};

LineCurve.prototype.toJSON = function () {

	const data = Curve.prototype.toJSON.call( this );

	data.v1 = this.v1.toArray();
	data.v2 = this.v2.toArray();

	return data;

};

LineCurve.prototype.fromJSON = function ( json ) {

	Curve.prototype.fromJSON.call( this, json );

	this.v1.fromArray( json.v1 );
	this.v2.fromArray( json.v2 );

	return this;

};

function LineCurve3( v1, v2 ) {

	Curve.call( this );

	this.type = 'LineCurve3';

	this.v1 = v1 || new Vector3();
	this.v2 = v2 || new Vector3();

}

LineCurve3.prototype = Object.create( Curve.prototype );
LineCurve3.prototype.constructor = LineCurve3;

LineCurve3.prototype.isLineCurve3 = true;

LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {

	const point = optionalTarget || new Vector3();

	if ( t === 1 ) {

		point.copy( this.v2 );

	} else {

		point.copy( this.v2 ).sub( this.v1 );
		point.multiplyScalar( t ).add( this.v1 );

	}

	return point;

};

// Line curve is linear, so we can overwrite default getPointAt

LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {

	return this.getPoint( u, optionalTarget );

};

LineCurve3.prototype.copy = function ( source ) {

	Curve.prototype.copy.call( this, source );

	this.v1.copy( source.v1 );
	this.v2.copy( source.v2 );

	return this;

};

LineCurve3.prototype.toJSON = function () {

	const data = Curve.prototype.toJSON.call( this );

	data.v1 = this.v1.toArray();
	data.v2 = this.v2.toArray();

	return data;

};

LineCurve3.prototype.fromJSON = function ( json ) {

	Curve.prototype.fromJSON.call( this, json );

	this.v1.fromArray( json.v1 );
	this.v2.fromArray( json.v2 );

	return this;

};

function QuadraticBezierCurve( v0, v1, v2 ) {

	Curve.call( this );

	this.type = 'QuadraticBezierCurve';

	this.v0 = v0 || new Vector2();
	this.v1 = v1 || new Vector2();
	this.v2 = v2 || new Vector2();

}

QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;

QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;

QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {

	const point = optionalTarget || new Vector2();

	const v0 = this.v0, v1 = this.v1, v2 = this.v2;

	point.set(
		QuadraticBezier( t, v0.x, v1.x, v2.x ),
		QuadraticBezier( t, v0.y, v1.y, v2.y )
	);

	return point;

};

QuadraticBezierCurve.prototype.copy = function ( source ) {

	Curve.prototype.copy.call( this, source );

	this.v0.copy( source.v0 );
	this.v1.copy( source.v1 );
	this.v2.copy( source.v2 );

	return this;

};

QuadraticBezierCurve.prototype.toJSON = function () {

	const data = Curve.prototype.toJSON.call( this );

	data.v0 = this.v0.toArray();
	data.v1 = this.v1.toArray();
	data.v2 = this.v2.toArray();

	return data;

};

QuadraticBezierCurve.prototype.fromJSON = function ( json ) {

	Curve.prototype.fromJSON.call( this, json );

	this.v0.fromArray( json.v0 );
	this.v1.fromArray( json.v1 );
	this.v2.fromArray( json.v2 );

	return this;

};

function QuadraticBezierCurve3( v0, v1, v2 ) {

	Curve.call( this );

	this.type = 'QuadraticBezierCurve3';

	this.v0 = v0 || new Vector3();
	this.v1 = v1 || new Vector3();
	this.v2 = v2 || new Vector3();

}

QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;

QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;

QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {

	const point = optionalTarget || new Vector3();

	const v0 = this.v0, v1 = this.v1, v2 = this.v2;

	point.set(
		QuadraticBezier( t, v0.x, v1.x, v2.x ),
		QuadraticBezier( t, v0.y, v1.y, v2.y ),
		QuadraticBezier( t, v0.z, v1.z, v2.z )
	);

	return point;

};

QuadraticBezierCurve3.prototype.copy = function ( source ) {

	Curve.prototype.copy.call( this, source );

	this.v0.copy( source.v0 );
	this.v1.copy( source.v1 );
	this.v2.copy( source.v2 );

	return this;

};

QuadraticBezierCurve3.prototype.toJSON = function () {

	const data = Curve.prototype.toJSON.call( this );

	data.v0 = this.v0.toArray();
	data.v1 = this.v1.toArray();
	data.v2 = this.v2.toArray();

	return data;

};

QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {

	Curve.prototype.fromJSON.call( this, json );

	this.v0.fromArray( json.v0 );
	this.v1.fromArray( json.v1 );
	this.v2.fromArray( json.v2 );

	return this;

};

function SplineCurve( points /* array of Vector2 */ ) {

	Curve.call( this );

	this.type = 'SplineCurve';

	this.points = points || [];

}

SplineCurve.prototype = Object.create( Curve.prototype );
SplineCurve.prototype.constructor = SplineCurve;

SplineCurve.prototype.isSplineCurve = true;

SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {

	const point = optionalTarget || new Vector2();

	const points = this.points;
	const p = ( points.length - 1 ) * t;

	const intPoint = Math.floor( p );
	const weight = p - intPoint;

	const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
	const p1 = points[ intPoint ];
	const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
	const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];

	point.set(
		CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
		CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
	);

	return point;

};

SplineCurve.prototype.copy = function ( source ) {

	Curve.prototype.copy.call( this, source );

	this.points = [];

	for ( let i = 0, l = source.points.length; i < l; i ++ ) {

		const point = source.points[ i ];

		this.points.push( point.clone() );

	}

	return this;

};

SplineCurve.prototype.toJSON = function () {

	const data = Curve.prototype.toJSON.call( this );

	data.points = [];

	for ( let i = 0, l = this.points.length; i < l; i ++ ) {

		const point = this.points[ i ];
		data.points.push( point.toArray() );

	}

	return data;

};

SplineCurve.prototype.fromJSON = function ( json ) {

	Curve.prototype.fromJSON.call( this, json );

	this.points = [];

	for ( let i = 0, l = json.points.length; i < l; i ++ ) {

		const point = json.points[ i ];
		this.points.push( new Vector2().fromArray( point ) );

	}

	return this;

};

var Curves = /*#__PURE__*/Object.freeze({
	__proto__: null,
	ArcCurve: ArcCurve,
	CatmullRomCurve3: CatmullRomCurve3,
	CubicBezierCurve: CubicBezierCurve,
	CubicBezierCurve3: CubicBezierCurve3,
	EllipseCurve: EllipseCurve,
	LineCurve: LineCurve,
	LineCurve3: LineCurve3,
	QuadraticBezierCurve: QuadraticBezierCurve,
	QuadraticBezierCurve3: QuadraticBezierCurve3,
	SplineCurve: SplineCurve
});

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 *
 **/

/**************************************************************
 *	Curved Path - a curve path is simply a array of connected
 *  curves, but retains the api of a curve
 **************************************************************/

function CurvePath() {

	Curve.call( this );

	this.type = 'CurvePath';

	this.curves = [];
	this.autoClose = false; // Automatically closes the path

}

CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {

	constructor: CurvePath,

	add: function ( curve ) {

		this.curves.push( curve );

	},

	closePath: function () {

		// Add a line curve if start and end of lines are not connected
		const startPoint = this.curves[ 0 ].getPoint( 0 );
		const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );

		if ( ! startPoint.equals( endPoint ) ) {

			this.curves.push( new LineCurve( endPoint, startPoint ) );

		}

	},

	// To get accurate point with reference to
	// entire path distance at time t,
	// following has to be done:

	// 1. Length of each sub path have to be known
	// 2. Locate and identify type of curve
	// 3. Get t for the curve
	// 4. Return curve.getPointAt(t')

	getPoint: function ( t ) {

		const d = t * this.getLength();
		const curveLengths = this.getCurveLengths();
		let i = 0;

		// To think about boundaries points.

		while ( i < curveLengths.length ) {

			if ( curveLengths[ i ] >= d ) {

				const diff = curveLengths[ i ] - d;
				const curve = this.curves[ i ];

				const segmentLength = curve.getLength();
				const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;

				return curve.getPointAt( u );

			}

			i ++;

		}

		return null;

		// loop where sum != 0, sum > d , sum+1 <d

	},

	// We cannot use the default THREE.Curve getPoint() with getLength() because in
	// THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
	// getPoint() depends on getLength

	getLength: function () {

		const lens = this.getCurveLengths();
		return lens[ lens.length - 1 ];

	},

	// cacheLengths must be recalculated.
	updateArcLengths: function () {

		this.needsUpdate = true;
		this.cacheLengths = null;
		this.getCurveLengths();

	},

	// Compute lengths and cache them
	// We cannot overwrite getLengths() because UtoT mapping uses it.

	getCurveLengths: function () {

		// We use cache values if curves and cache array are same length

		if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {

			return this.cacheLengths;

		}

		// Get length of sub-curve
		// Push sums into cached array

		const lengths = [];
		let sums = 0;

		for ( let i = 0, l = this.curves.length; i < l; i ++ ) {

			sums += this.curves[ i ].getLength();
			lengths.push( sums );

		}

		this.cacheLengths = lengths;

		return lengths;

	},

	getSpacedPoints: function ( divisions ) {

		if ( divisions === undefined ) divisions = 40;

		const points = [];

		for ( let i = 0; i <= divisions; i ++ ) {

			points.push( this.getPoint( i / divisions ) );

		}

		if ( this.autoClose ) {

			points.push( points[ 0 ] );

		}

		return points;

	},

	getPoints: function ( divisions ) {

		divisions = divisions || 12;

		const points = [];
		let last;

		for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {

			const curve = curves[ i ];
			const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
				: ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
					: ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
						: divisions;

			const pts = curve.getPoints( resolution );

			for ( let j = 0; j < pts.length; j ++ ) {

				const point = pts[ j ];

				if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates

				points.push( point );
				last = point;

			}

		}

		if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {

			points.push( points[ 0 ] );

		}

		return points;

	},

	copy: function ( source ) {

		Curve.prototype.copy.call( this, source );

		this.curves = [];

		for ( let i = 0, l = source.curves.length; i < l; i ++ ) {

			const curve = source.curves[ i ];

			this.curves.push( curve.clone() );

		}

		this.autoClose = source.autoClose;

		return this;

	},

	toJSON: function () {

		const data = Curve.prototype.toJSON.call( this );

		data.autoClose = this.autoClose;
		data.curves = [];

		for ( let i = 0, l = this.curves.length; i < l; i ++ ) {

			const curve = this.curves[ i ];
			data.curves.push( curve.toJSON() );

		}

		return data;

	},

	fromJSON: function ( json ) {

		Curve.prototype.fromJSON.call( this, json );

		this.autoClose = json.autoClose;
		this.curves = [];

		for ( let i = 0, l = json.curves.length; i < l; i ++ ) {

			const curve = json.curves[ i ];
			this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );

		}

		return this;

	}

} );

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * Creates free form 2d path using series of points, lines or curves.
 **/

function Path( points ) {

	CurvePath.call( this );

	this.type = 'Path';

	this.currentPoint = new Vector2();

	if ( points ) {

		this.setFromPoints( points );

	}

}

Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {

	constructor: Path,

	setFromPoints: function ( points ) {

		this.moveTo( points[ 0 ].x, points[ 0 ].y );

		for ( let i = 1, l = points.length; i < l; i ++ ) {

			this.lineTo( points[ i ].x, points[ i ].y );

		}

		return this;

	},

	moveTo: function ( x, y ) {

		this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?

		return this;

	},

	lineTo: function ( x, y ) {

		const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
		this.curves.push( curve );

		this.currentPoint.set( x, y );

		return this;

	},

	quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {

		const curve = new QuadraticBezierCurve(
			this.currentPoint.clone(),
			new Vector2( aCPx, aCPy ),
			new Vector2( aX, aY )
		);

		this.curves.push( curve );

		this.currentPoint.set( aX, aY );

		return this;

	},

	bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {

		const curve = new CubicBezierCurve(
			this.currentPoint.clone(),
			new Vector2( aCP1x, aCP1y ),
			new Vector2( aCP2x, aCP2y ),
			new Vector2( aX, aY )
		);

		this.curves.push( curve );

		this.currentPoint.set( aX, aY );

		return this;

	},

	splineThru: function ( pts /*Array of Vector*/ ) {

		const npts = [ this.currentPoint.clone() ].concat( pts );

		const curve = new SplineCurve( npts );
		this.curves.push( curve );

		this.currentPoint.copy( pts[ pts.length - 1 ] );

		return this;

	},

	arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

		const x0 = this.currentPoint.x;
		const y0 = this.currentPoint.y;

		this.absarc( aX + x0, aY + y0, aRadius,
			aStartAngle, aEndAngle, aClockwise );

		return this;

	},

	absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

		this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );

		return this;

	},

	ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {

		const x0 = this.currentPoint.x;
		const y0 = this.currentPoint.y;

		this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );

		return this;

	},

	absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {

		const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );

		if ( this.curves.length > 0 ) {

			// if a previous curve is present, attempt to join
			const firstPoint = curve.getPoint( 0 );

			if ( ! firstPoint.equals( this.currentPoint ) ) {

				this.lineTo( firstPoint.x, firstPoint.y );

			}

		}

		this.curves.push( curve );

		const lastPoint = curve.getPoint( 1 );
		this.currentPoint.copy( lastPoint );

		return this;

	},

	copy: function ( source ) {

		CurvePath.prototype.copy.call( this, source );

		this.currentPoint.copy( source.currentPoint );

		return this;

	},

	toJSON: function () {

		const data = CurvePath.prototype.toJSON.call( this );

		data.currentPoint = this.currentPoint.toArray();

		return data;

	},

	fromJSON: function ( json ) {

		CurvePath.prototype.fromJSON.call( this, json );

		this.currentPoint.fromArray( json.currentPoint );

		return this;

	}

} );

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * Defines a 2d shape plane using paths.
 **/

// STEP 1 Create a path.
// STEP 2 Turn path into shape.
// STEP 3 ExtrudeGeometry takes in Shape/Shapes
// STEP 3a - Extract points from each shape, turn to vertices
// STEP 3b - Triangulate each shape, add faces.

function Shape( points ) {

	Path.call( this, points );

	this.uuid = MathUtils.generateUUID();

	this.type = 'Shape';

	this.holes = [];

}

Shape.prototype = Object.assign( Object.create( Path.prototype ), {

	constructor: Shape,

	getPointsHoles: function ( divisions ) {

		const holesPts = [];

		for ( let i = 0, l = this.holes.length; i < l; i ++ ) {

			holesPts[ i ] = this.holes[ i ].getPoints( divisions );

		}

		return holesPts;

	},

	// get points of shape and holes (keypoints based on segments parameter)

	extractPoints: function ( divisions ) {

		return {

			shape: this.getPoints( divisions ),
			holes: this.getPointsHoles( divisions )

		};

	},

	copy: function ( source ) {

		Path.prototype.copy.call( this, source );

		this.holes = [];

		for ( let i = 0, l = source.holes.length; i < l; i ++ ) {

			const hole = source.holes[ i ];

			this.holes.push( hole.clone() );

		}

		return this;

	},

	toJSON: function () {

		const data = Path.prototype.toJSON.call( this );

		data.uuid = this.uuid;
		data.holes = [];

		for ( let i = 0, l = this.holes.length; i < l; i ++ ) {

			const hole = this.holes[ i ];
			data.holes.push( hole.toJSON() );

		}

		return data;

	},

	fromJSON: function ( json ) {

		Path.prototype.fromJSON.call( this, json );

		this.uuid = json.uuid;
		this.holes = [];

		for ( let i = 0, l = json.holes.length; i < l; i ++ ) {

			const hole = json.holes[ i ];
			this.holes.push( new Path().fromJSON( hole ) );

		}

		return this;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

function Light( color, intensity ) {

	Object3D.call( this );

	this.type = 'Light';

	this.color = new Color( color );
	this.intensity = intensity !== undefined ? intensity : 1;

	this.receiveShadow = undefined;

}

Light.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Light,

	isLight: true,

	copy: function ( source ) {

		Object3D.prototype.copy.call( this, source );

		this.color.copy( source.color );
		this.intensity = source.intensity;

		return this;

	},

	toJSON: function ( meta ) {

		const data = Object3D.prototype.toJSON.call( this, meta );

		data.object.color = this.color.getHex();
		data.object.intensity = this.intensity;

		if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();

		if ( this.distance !== undefined ) data.object.distance = this.distance;
		if ( this.angle !== undefined ) data.object.angle = this.angle;
		if ( this.decay !== undefined ) data.object.decay = this.decay;
		if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;

		if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();

		return data;

	}

} );

/**
 * @author alteredq / http://alteredqualia.com/
 */

function HemisphereLight( skyColor, groundColor, intensity ) {

	Light.call( this, skyColor, intensity );

	this.type = 'HemisphereLight';

	this.castShadow = undefined;

	this.position.copy( Object3D.DefaultUp );
	this.updateMatrix();

	this.groundColor = new Color( groundColor );

}

HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {

	constructor: HemisphereLight,

	isHemisphereLight: true,

	copy: function ( source ) {

		Light.prototype.copy.call( this, source );

		this.groundColor.copy( source.groundColor );

		return this;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function LightShadow( camera ) {

	this.camera = camera;

	this.bias = 0;
	this.normalBias = 0;
	this.radius = 1;

	this.mapSize = new Vector2( 512, 512 );

	this.map = null;
	this.mapPass = null;
	this.matrix = new Matrix4();

	this.autoUpdate = true;
	this.needsUpdate = false;

	this._frustum = new Frustum();
	this._frameExtents = new Vector2( 1, 1 );

	this._viewportCount = 1;

	this._viewports = [

		new Vector4( 0, 0, 1, 1 )

	];

}

Object.assign( LightShadow.prototype, {

	_projScreenMatrix: new Matrix4(),

	_lightPositionWorld: new Vector3(),

	_lookTarget: new Vector3(),

	getViewportCount: function () {

		return this._viewportCount;

	},

	getFrustum: function () {

		return this._frustum;

	},

	updateMatrices: function ( light ) {

		const shadowCamera = this.camera,
			shadowMatrix = this.matrix,
			projScreenMatrix = this._projScreenMatrix,
			lookTarget = this._lookTarget,
			lightPositionWorld = this._lightPositionWorld;

		lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
		shadowCamera.position.copy( lightPositionWorld );

		lookTarget.setFromMatrixPosition( light.target.matrixWorld );
		shadowCamera.lookAt( lookTarget );
		shadowCamera.updateMatrixWorld();

		projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
		this._frustum.setFromProjectionMatrix( projScreenMatrix );

		shadowMatrix.set(
			0.5, 0.0, 0.0, 0.5,
			0.0, 0.5, 0.0, 0.5,
			0.0, 0.0, 0.5, 0.5,
			0.0, 0.0, 0.0, 1.0
		);

		shadowMatrix.multiply( shadowCamera.projectionMatrix );
		shadowMatrix.multiply( shadowCamera.matrixWorldInverse );

	},

	getViewport: function ( viewportIndex ) {

		return this._viewports[ viewportIndex ];

	},

	getFrameExtents: function () {

		return this._frameExtents;

	},

	copy: function ( source ) {

		this.camera = source.camera.clone();

		this.bias = source.bias;
		this.radius = source.radius;

		this.mapSize.copy( source.mapSize );

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	toJSON: function () {

		const object = {};

		if ( this.bias !== 0 ) object.bias = this.bias;
		if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
		if ( this.radius !== 1 ) object.radius = this.radius;
		if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();

		object.camera = this.camera.toJSON( false ).object;
		delete object.camera.matrix;

		return object;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function SpotLightShadow() {

	LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );

}

SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {

	constructor: SpotLightShadow,

	isSpotLightShadow: true,

	updateMatrices: function ( light ) {

		const camera = this.camera;

		const fov = MathUtils.RAD2DEG * 2 * light.angle;
		const aspect = this.mapSize.width / this.mapSize.height;
		const far = light.distance || camera.far;

		if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {

			camera.fov = fov;
			camera.aspect = aspect;
			camera.far = far;
			camera.updateProjectionMatrix();

		}

		LightShadow.prototype.updateMatrices.call( this, light );

	}

} );

/**
 * @author alteredq / http://alteredqualia.com/
 */

function SpotLight( color, intensity, distance, angle, penumbra, decay ) {

	Light.call( this, color, intensity );

	this.type = 'SpotLight';

	this.position.copy( Object3D.DefaultUp );
	this.updateMatrix();

	this.target = new Object3D();

	Object.defineProperty( this, 'power', {
		get: function () {

			// intensity = power per solid angle.
			// ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
			return this.intensity * Math.PI;

		},
		set: function ( power ) {

			// intensity = power per solid angle.
			// ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
			this.intensity = power / Math.PI;

		}
	} );

	this.distance = ( distance !== undefined ) ? distance : 0;
	this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
	this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
	this.decay = ( decay !== undefined ) ? decay : 1;	// for physically correct lights, should be 2.

	this.shadow = new SpotLightShadow();

}

SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {

	constructor: SpotLight,

	isSpotLight: true,

	copy: function ( source ) {

		Light.prototype.copy.call( this, source );

		this.distance = source.distance;
		this.angle = source.angle;
		this.penumbra = source.penumbra;
		this.decay = source.decay;

		this.target = source.target.clone();

		this.shadow = source.shadow.clone();

		return this;

	}

} );

function PointLightShadow() {

	LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );

	this._frameExtents = new Vector2( 4, 2 );

	this._viewportCount = 6;

	this._viewports = [
		// These viewports map a cube-map onto a 2D texture with the
		// following orientation:
		//
		//  xzXZ
		//   y Y
		//
		// X - Positive x direction
		// x - Negative x direction
		// Y - Positive y direction
		// y - Negative y direction
		// Z - Positive z direction
		// z - Negative z direction

		// positive X
		new Vector4( 2, 1, 1, 1 ),
		// negative X
		new Vector4( 0, 1, 1, 1 ),
		// positive Z
		new Vector4( 3, 1, 1, 1 ),
		// negative Z
		new Vector4( 1, 1, 1, 1 ),
		// positive Y
		new Vector4( 3, 0, 1, 1 ),
		// negative Y
		new Vector4( 1, 0, 1, 1 )
	];

	this._cubeDirections = [
		new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
		new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
	];

	this._cubeUps = [
		new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
		new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ),	new Vector3( 0, 0, - 1 )
	];

}

PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {

	constructor: PointLightShadow,

	isPointLightShadow: true,

	updateMatrices: function ( light, viewportIndex ) {

		if ( viewportIndex === undefined ) viewportIndex = 0;

		const camera = this.camera,
			shadowMatrix = this.matrix,
			lightPositionWorld = this._lightPositionWorld,
			lookTarget = this._lookTarget,
			projScreenMatrix = this._projScreenMatrix;

		lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
		camera.position.copy( lightPositionWorld );

		lookTarget.copy( camera.position );
		lookTarget.add( this._cubeDirections[ viewportIndex ] );
		camera.up.copy( this._cubeUps[ viewportIndex ] );
		camera.lookAt( lookTarget );
		camera.updateMatrixWorld();

		shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );

		projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
		this._frustum.setFromProjectionMatrix( projScreenMatrix );

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */


function PointLight( color, intensity, distance, decay ) {

	Light.call( this, color, intensity );

	this.type = 'PointLight';

	Object.defineProperty( this, 'power', {
		get: function () {

			// intensity = power per solid angle.
			// ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
			return this.intensity * 4 * Math.PI;

		},
		set: function ( power ) {

			// intensity = power per solid angle.
			// ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
			this.intensity = power / ( 4 * Math.PI );

		}
	} );

	this.distance = ( distance !== undefined ) ? distance : 0;
	this.decay = ( decay !== undefined ) ? decay : 1;	// for physically correct lights, should be 2.

	this.shadow = new PointLightShadow();

}

PointLight.prototype = Object.assign( Object.create( Light.prototype ), {

	constructor: PointLight,

	isPointLight: true,

	copy: function ( source ) {

		Light.prototype.copy.call( this, source );

		this.distance = source.distance;
		this.decay = source.decay;

		this.shadow = source.shadow.clone();

		return this;

	}

} );

/**
 * @author alteredq / http://alteredqualia.com/
 * @author arose / http://github.com/arose
 */

function OrthographicCamera( left, right, top, bottom, near, far ) {

	Camera.call( this );

	this.type = 'OrthographicCamera';

	this.zoom = 1;
	this.view = null;

	this.left = ( left !== undefined ) ? left : - 1;
	this.right = ( right !== undefined ) ? right : 1;
	this.top = ( top !== undefined ) ? top : 1;
	this.bottom = ( bottom !== undefined ) ? bottom : - 1;

	this.near = ( near !== undefined ) ? near : 0.1;
	this.far = ( far !== undefined ) ? far : 2000;

	this.updateProjectionMatrix();

}

OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {

	constructor: OrthographicCamera,

	isOrthographicCamera: true,

	copy: function ( source, recursive ) {

		Camera.prototype.copy.call( this, source, recursive );

		this.left = source.left;
		this.right = source.right;
		this.top = source.top;
		this.bottom = source.bottom;
		this.near = source.near;
		this.far = source.far;

		this.zoom = source.zoom;
		this.view = source.view === null ? null : Object.assign( {}, source.view );

		return this;

	},

	setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {

		if ( this.view === null ) {

			this.view = {
				enabled: true,
				fullWidth: 1,
				fullHeight: 1,
				offsetX: 0,
				offsetY: 0,
				width: 1,
				height: 1
			};

		}

		this.view.enabled = true;
		this.view.fullWidth = fullWidth;
		this.view.fullHeight = fullHeight;
		this.view.offsetX = x;
		this.view.offsetY = y;
		this.view.width = width;
		this.view.height = height;

		this.updateProjectionMatrix();

	},

	clearViewOffset: function () {

		if ( this.view !== null ) {

			this.view.enabled = false;

		}

		this.updateProjectionMatrix();

	},

	updateProjectionMatrix: function () {

		const dx = ( this.right - this.left ) / ( 2 * this.zoom );
		const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
		const cx = ( this.right + this.left ) / 2;
		const cy = ( this.top + this.bottom ) / 2;

		let left = cx - dx;
		let right = cx + dx;
		let top = cy + dy;
		let bottom = cy - dy;

		if ( this.view !== null && this.view.enabled ) {

			const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
			const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;

			left += scaleW * this.view.offsetX;
			right = left + scaleW * this.view.width;
			top -= scaleH * this.view.offsetY;
			bottom = top - scaleH * this.view.height;

		}

		this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );

		this.projectionMatrixInverse.getInverse( this.projectionMatrix );

	},

	toJSON: function ( meta ) {

		const data = Object3D.prototype.toJSON.call( this, meta );

		data.object.zoom = this.zoom;
		data.object.left = this.left;
		data.object.right = this.right;
		data.object.top = this.top;
		data.object.bottom = this.bottom;
		data.object.near = this.near;
		data.object.far = this.far;

		if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );

		return data;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function DirectionalLightShadow() {

	LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );

}

DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {

	constructor: DirectionalLightShadow,

	isDirectionalLightShadow: true,

	updateMatrices: function ( light ) {

		LightShadow.prototype.updateMatrices.call( this, light );

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

function DirectionalLight( color, intensity ) {

	Light.call( this, color, intensity );

	this.type = 'DirectionalLight';

	this.position.copy( Object3D.DefaultUp );
	this.updateMatrix();

	this.target = new Object3D();

	this.shadow = new DirectionalLightShadow();

}

DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {

	constructor: DirectionalLight,

	isDirectionalLight: true,

	copy: function ( source ) {

		Light.prototype.copy.call( this, source );

		this.target = source.target.clone();

		this.shadow = source.shadow.clone();

		return this;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function AmbientLight( color, intensity ) {

	Light.call( this, color, intensity );

	this.type = 'AmbientLight';

	this.castShadow = undefined;

}

AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {

	constructor: AmbientLight,

	isAmbientLight: true

} );

/**
 * @author abelnation / http://github.com/abelnation
 */

function RectAreaLight( color, intensity, width, height ) {

	Light.call( this, color, intensity );

	this.type = 'RectAreaLight';

	this.width = ( width !== undefined ) ? width : 10;
	this.height = ( height !== undefined ) ? height : 10;

}

RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {

	constructor: RectAreaLight,

	isRectAreaLight: true,

	copy: function ( source ) {

		Light.prototype.copy.call( this, source );

		this.width = source.width;
		this.height = source.height;

		return this;

	},

	toJSON: function ( meta ) {

		const data = Light.prototype.toJSON.call( this, meta );

		data.object.width = this.width;
		data.object.height = this.height;

		return data;

	}

} );

/**
 * @author bhouston / http://clara.io
 * @author WestLangley / http://github.com/WestLangley
 *
 * Primary reference:
 *   https://graphics.stanford.edu/papers/envmap/envmap.pdf
 *
 * Secondary reference:
 *   https://www.ppsloan.org/publications/StupidSH36.pdf
 */

// 3-band SH defined by 9 coefficients

function SphericalHarmonics3() {

	this.coefficients = [];

	for ( let i = 0; i < 9; i ++ ) {

		this.coefficients.push( new Vector3() );

	}

}

Object.assign( SphericalHarmonics3.prototype, {

	isSphericalHarmonics3: true,

	set: function ( coefficients ) {

		for ( let i = 0; i < 9; i ++ ) {

			this.coefficients[ i ].copy( coefficients[ i ] );

		}

		return this;

	},

	zero: function () {

		for ( let i = 0; i < 9; i ++ ) {

			this.coefficients[ i ].set( 0, 0, 0 );

		}

		return this;

	},

	// get the radiance in the direction of the normal
	// target is a Vector3
	getAt: function ( normal, target ) {

		// normal is assumed to be unit length

		const x = normal.x, y = normal.y, z = normal.z;

		const coeff = this.coefficients;

		// band 0
		target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );

		// band 1
		target.addScaledVector( coeff[ 1 ], 0.488603 * y );
		target.addScaledVector( coeff[ 2 ], 0.488603 * z );
		target.addScaledVector( coeff[ 3 ], 0.488603 * x );

		// band 2
		target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
		target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
		target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
		target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
		target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );

		return target;

	},

	// get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
	// target is a Vector3
	// https://graphics.stanford.edu/papers/envmap/envmap.pdf
	getIrradianceAt: function ( normal, target ) {

		// normal is assumed to be unit length

		const x = normal.x, y = normal.y, z = normal.z;

		const coeff = this.coefficients;

		// band 0
		target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095

		// band 1
		target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
		target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
		target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );

		// band 2
		target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
		target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
		target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
		target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
		target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274

		return target;

	},

	add: function ( sh ) {

		for ( let i = 0; i < 9; i ++ ) {

			this.coefficients[ i ].add( sh.coefficients[ i ] );

		}

		return this;

	},

	addScaledSH: function ( sh, s ) {

		for ( let i = 0; i < 9; i ++ ) {

			this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );

		}

		return this;

	},

	scale: function ( s ) {

		for ( let i = 0; i < 9; i ++ ) {

			this.coefficients[ i ].multiplyScalar( s );

		}

		return this;

	},

	lerp: function ( sh, alpha ) {

		for ( let i = 0; i < 9; i ++ ) {

			this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );

		}

		return this;

	},

	equals: function ( sh ) {

		for ( let i = 0; i < 9; i ++ ) {

			if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {

				return false;

			}

		}

		return true;

	},

	copy: function ( sh ) {

		return this.set( sh.coefficients );

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	fromArray: function ( array, offset ) {

		if ( offset === undefined ) offset = 0;

		const coefficients = this.coefficients;

		for ( let i = 0; i < 9; i ++ ) {

			coefficients[ i ].fromArray( array, offset + ( i * 3 ) );

		}

		return this;

	},

	toArray: function ( array, offset ) {

		if ( array === undefined ) array = [];
		if ( offset === undefined ) offset = 0;

		const coefficients = this.coefficients;

		for ( let i = 0; i < 9; i ++ ) {

			coefficients[ i ].toArray( array, offset + ( i * 3 ) );

		}

		return array;

	}

} );

Object.assign( SphericalHarmonics3, {

	// evaluate the basis functions
	// shBasis is an Array[ 9 ]
	getBasisAt: function ( normal, shBasis ) {

		// normal is assumed to be unit length

		const x = normal.x, y = normal.y, z = normal.z;

		// band 0
		shBasis[ 0 ] = 0.282095;

		// band 1
		shBasis[ 1 ] = 0.488603 * y;
		shBasis[ 2 ] = 0.488603 * z;
		shBasis[ 3 ] = 0.488603 * x;

		// band 2
		shBasis[ 4 ] = 1.092548 * x * y;
		shBasis[ 5 ] = 1.092548 * y * z;
		shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
		shBasis[ 7 ] = 1.092548 * x * z;
		shBasis[ 8 ] = 0.546274 * ( x * x - y * y );

	}

} );

/**
 * @author WestLangley / http://github.com/WestLangley
 *
 * A LightProbe is a source of indirect-diffuse light
 */

function LightProbe( sh, intensity ) {

	Light.call( this, undefined, intensity );

	this.type = 'LightProbe';

	this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();

}

LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {

	constructor: LightProbe,

	isLightProbe: true,

	copy: function ( source ) {

		Light.prototype.copy.call( this, source );

		this.sh.copy( source.sh );

		return this;

	},

	fromJSON: function ( json ) {

		this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
		this.sh.fromArray( json.sh );

		return this;

	},

	toJSON: function ( meta ) {

		const data = Light.prototype.toJSON.call( this, meta );

		data.object.sh = this.sh.toArray();

		return data;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function MaterialLoader( manager ) {

	Loader.call( this, manager );

	this.textures = {};

}

MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: MaterialLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const loader = new FileLoader( scope.manager );
		loader.setPath( scope.path );
		loader.load( url, function ( text ) {

			try {

				onLoad( scope.parse( JSON.parse( text ) ) );

			} catch ( e ) {

				if ( onError ) {

					onError( e );

				} else {

					console.error( e );

				}

				scope.manager.itemError( url );

			}

		}, onProgress, onError );

	},

	parse: function ( json ) {

		const textures = this.textures;

		function getTexture( name ) {

			if ( textures[ name ] === undefined ) {

				console.warn( 'THREE.MaterialLoader: Undefined texture', name );

			}

			return textures[ name ];

		}

		const material = new Materials[ json.type ]();

		if ( json.uuid !== undefined ) material.uuid = json.uuid;
		if ( json.name !== undefined ) material.name = json.name;
		if ( json.color !== undefined ) material.color.setHex( json.color );
		if ( json.roughness !== undefined ) material.roughness = json.roughness;
		if ( json.metalness !== undefined ) material.metalness = json.metalness;
		if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
		if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
		if ( json.specular !== undefined ) material.specular.setHex( json.specular );
		if ( json.shininess !== undefined ) material.shininess = json.shininess;
		if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
		if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
		if ( json.fog !== undefined ) material.fog = json.fog;
		if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
		if ( json.blending !== undefined ) material.blending = json.blending;
		if ( json.combine !== undefined ) material.combine = json.combine;
		if ( json.side !== undefined ) material.side = json.side;
		if ( json.opacity !== undefined ) material.opacity = json.opacity;
		if ( json.transparent !== undefined ) material.transparent = json.transparent;
		if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
		if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
		if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
		if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;

		if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
		if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
		if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
		if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
		if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
		if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
		if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
		if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;

		if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
		if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
		if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
		if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;

		if ( json.rotation !== undefined ) material.rotation = json.rotation;

		if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
		if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
		if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
		if ( json.scale !== undefined ) material.scale = json.scale;

		if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
		if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
		if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;

		if ( json.skinning !== undefined ) material.skinning = json.skinning;
		if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
		if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
		if ( json.dithering !== undefined ) material.dithering = json.dithering;

		if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;

		if ( json.visible !== undefined ) material.visible = json.visible;

		if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;

		if ( json.userData !== undefined ) material.userData = json.userData;

		if ( json.vertexColors !== undefined ) {

			if ( typeof json.vertexColors === 'number' ) {

				material.vertexColors = ( json.vertexColors > 0 ) ? true : false;

			} else {

				material.vertexColors = json.vertexColors;

			}

		}

		// Shader Material

		if ( json.uniforms !== undefined ) {

			for ( const name in json.uniforms ) {

				const uniform = json.uniforms[ name ];

				material.uniforms[ name ] = {};

				switch ( uniform.type ) {

					case 't':
						material.uniforms[ name ].value = getTexture( uniform.value );
						break;

					case 'c':
						material.uniforms[ name ].value = new Color().setHex( uniform.value );
						break;

					case 'v2':
						material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
						break;

					case 'v3':
						material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
						break;

					case 'v4':
						material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
						break;

					case 'm3':
						material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );

					case 'm4':
						material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
						break;

					default:
						material.uniforms[ name ].value = uniform.value;

				}

			}

		}

		if ( json.defines !== undefined ) material.defines = json.defines;
		if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
		if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;

		if ( json.extensions !== undefined ) {

			for ( const key in json.extensions ) {

				material.extensions[ key ] = json.extensions[ key ];

			}

		}

		// Deprecated

		if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading

		// for PointsMaterial

		if ( json.size !== undefined ) material.size = json.size;
		if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;

		// maps

		if ( json.map !== undefined ) material.map = getTexture( json.map );
		if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );

		if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );

		if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
		if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;

		if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
		if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
		if ( json.normalScale !== undefined ) {

			let normalScale = json.normalScale;

			if ( Array.isArray( normalScale ) === false ) {

				// Blender exporter used to export a scalar. See #7459

				normalScale = [ normalScale, normalScale ];

			}

			material.normalScale = new Vector2().fromArray( normalScale );

		}

		if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
		if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
		if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;

		if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
		if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );

		if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
		if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;

		if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );

		if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
		if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;

		if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
		if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;

		if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
		if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;

		if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
		if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;

		if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );

		if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
		if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
		if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
		if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );

		return material;

	},

	setTextures: function ( value ) {

		this.textures = value;
		return this;

	}

} );

/**
 * @author Don McCurdy / https://www.donmccurdy.com
 */

const LoaderUtils = {

	decodeText: function ( array ) {

		if ( typeof TextDecoder !== 'undefined' ) {

			return new TextDecoder().decode( array );

		}

		// Avoid the String.fromCharCode.apply(null, array) shortcut, which
		// throws a "maximum call stack size exceeded" error for large arrays.

		let s = '';

		for ( let i = 0, il = array.length; i < il; i ++ ) {

			// Implicitly assumes little-endian.
			s += String.fromCharCode( array[ i ] );

		}

		try {

			// merges multi-byte utf-8 characters.

			return decodeURIComponent( escape( s ) );

		} catch ( e ) { // see #16358

			return s;

		}

	},

	extractUrlBase: function ( url ) {

		const index = url.lastIndexOf( '/' );

		if ( index === - 1 ) return './';

		return url.substr( 0, index + 1 );

	}

};

/**
 * @author benaadams / https://twitter.com/ben_a_adams
 */

function InstancedBufferGeometry() {

	BufferGeometry.call( this );

	this.type = 'InstancedBufferGeometry';
	this.instanceCount = Infinity;

}

InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {

	constructor: InstancedBufferGeometry,

	isInstancedBufferGeometry: true,

	copy: function ( source ) {

		BufferGeometry.prototype.copy.call( this, source );

		this.instanceCount = source.instanceCount;

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	toJSON: function () {

		const data = BufferGeometry.prototype.toJSON.call( this );

		data.instanceCount = this.instanceCount;

		data.isInstancedBufferGeometry = true;

		return data;

	}

} );

/**
 * @author benaadams / https://twitter.com/ben_a_adams
 */

function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {

	if ( typeof ( normalized ) === 'number' ) {

		meshPerAttribute = normalized;

		normalized = false;

		console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );

	}

	BufferAttribute.call( this, array, itemSize, normalized );

	this.meshPerAttribute = meshPerAttribute || 1;

}

InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {

	constructor: InstancedBufferAttribute,

	isInstancedBufferAttribute: true,

	copy: function ( source ) {

		BufferAttribute.prototype.copy.call( this, source );

		this.meshPerAttribute = source.meshPerAttribute;

		return this;

	},

	toJSON: function ()	{

		const data = BufferAttribute.prototype.toJSON.call( this );

		data.meshPerAttribute = this.meshPerAttribute;

		data.isInstancedBufferAttribute = true;

		return data;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function BufferGeometryLoader( manager ) {

	Loader.call( this, manager );

}

BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: BufferGeometryLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const loader = new FileLoader( scope.manager );
		loader.setPath( scope.path );
		loader.load( url, function ( text ) {

			try {

				onLoad( scope.parse( JSON.parse( text ) ) );

			} catch ( e ) {

				if ( onError ) {

					onError( e );

				} else {

					console.error( e );

				}

				scope.manager.itemError( url );

			}

		}, onProgress, onError );

	},

	parse: function ( json ) {

		const interleavedBufferMap = {};
		const arrayBufferMap = {};

		function getInterleavedBuffer( json, uuid ) {

			if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];

			const interleavedBuffers = json.interleavedBuffers;
			const interleavedBuffer = interleavedBuffers[ uuid ];

			const buffer = getArrayBuffer( json, interleavedBuffer.buffer );

			const array = new TYPED_ARRAYS[ interleavedBuffer.type ]( buffer );
			const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
			ib.uuid = interleavedBuffer.uuid;

			interleavedBufferMap[ uuid ] = ib;

			return ib;

		}

		function getArrayBuffer( json, uuid ) {

			if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];

			const arrayBuffers = json.arrayBuffers;
			const arrayBuffer = arrayBuffers[ uuid ];

			const ab = new Uint32Array( arrayBuffer ).buffer;

			arrayBufferMap[ uuid ] = ab;

			return ab;

		}

		const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();

		const index = json.data.index;

		if ( index !== undefined ) {

			const typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
			geometry.setIndex( new BufferAttribute( typedArray, 1 ) );

		}

		const attributes = json.data.attributes;

		for ( const key in attributes ) {

			const attribute = attributes[ key ];
			let bufferAttribute;

			if ( attribute.isInterleavedBufferAttribute ) {

				const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
				bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );

			} else {

				const typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
				const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
				bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );

			}

			if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
			geometry.setAttribute( key, bufferAttribute );

		}

		const morphAttributes = json.data.morphAttributes;

		if ( morphAttributes ) {

			for ( const key in morphAttributes ) {

				const attributeArray = morphAttributes[ key ];

				const array = [];

				for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {

					const attribute = attributeArray[ i ];
					let bufferAttribute;

					if ( attribute.isInterleavedBufferAttribute ) {

						const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
						bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );

					} else {

						const typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
						bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );

					}

					if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
					array.push( bufferAttribute );

				}

				geometry.morphAttributes[ key ] = array;

			}

		}

		const morphTargetsRelative = json.data.morphTargetsRelative;

		if ( morphTargetsRelative ) {

			geometry.morphTargetsRelative = true;

		}

		const groups = json.data.groups || json.data.drawcalls || json.data.offsets;

		if ( groups !== undefined ) {

			for ( let i = 0, n = groups.length; i !== n; ++ i ) {

				const group = groups[ i ];

				geometry.addGroup( group.start, group.count, group.materialIndex );

			}

		}

		const boundingSphere = json.data.boundingSphere;

		if ( boundingSphere !== undefined ) {

			const center = new Vector3();

			if ( boundingSphere.center !== undefined ) {

				center.fromArray( boundingSphere.center );

			}

			geometry.boundingSphere = new Sphere( center, boundingSphere.radius );

		}

		if ( json.name ) geometry.name = json.name;
		if ( json.userData ) geometry.userData = json.userData;

		return geometry;

	}

} );

const TYPED_ARRAYS = {
	Int8Array: Int8Array,
	Uint8Array: Uint8Array,
	// Workaround for IE11 pre KB2929437. See #11440
	Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
	Int16Array: Int16Array,
	Uint16Array: Uint16Array,
	Int32Array: Int32Array,
	Uint32Array: Uint32Array,
	Float32Array: Float32Array,
	Float64Array: Float64Array
};

/**
 * @author mrdoob / http://mrdoob.com/
 */

function ObjectLoader( manager ) {

	Loader.call( this, manager );

}

ObjectLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: ObjectLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
		this.resourcePath = this.resourcePath || path;

		const loader = new FileLoader( scope.manager );
		loader.setPath( this.path );
		loader.load( url, function ( text ) {

			let json = null;

			try {

				json = JSON.parse( text );

			} catch ( error ) {

				if ( onError !== undefined ) onError( error );

				console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );

				return;

			}

			const metadata = json.metadata;

			if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {

				console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
				return;

			}

			scope.parse( json, onLoad );

		}, onProgress, onError );

	},

	parse: function ( json, onLoad ) {

		const shapes = this.parseShape( json.shapes );
		const geometries = this.parseGeometries( json.geometries, shapes );

		const images = this.parseImages( json.images, function () {

			if ( onLoad !== undefined ) onLoad( object );

		} );

		const textures = this.parseTextures( json.textures, images );
		const materials = this.parseMaterials( json.materials, textures );

		const object = this.parseObject( json.object, geometries, materials );

		if ( json.animations ) {

			object.animations = this.parseAnimations( json.animations );

		}

		if ( json.images === undefined || json.images.length === 0 ) {

			if ( onLoad !== undefined ) onLoad( object );

		}

		return object;

	},

	parseShape: function ( json ) {

		const shapes = {};

		if ( json !== undefined ) {

			for ( let i = 0, l = json.length; i < l; i ++ ) {

				const shape = new Shape().fromJSON( json[ i ] );

				shapes[ shape.uuid ] = shape;

			}

		}

		return shapes;

	},

	parseGeometries: function ( json, shapes ) {

		const geometries = {};
		let geometryShapes;

		if ( json !== undefined ) {

			const bufferGeometryLoader = new BufferGeometryLoader();

			for ( let i = 0, l = json.length; i < l; i ++ ) {

				let geometry;
				const data = json[ i ];

				switch ( data.type ) {

					case 'PlaneGeometry':
					case 'PlaneBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.width,
							data.height,
							data.widthSegments,
							data.heightSegments
						);

						break;

					case 'BoxGeometry':
					case 'BoxBufferGeometry':
					case 'CubeGeometry': // backwards compatible

						geometry = new Geometries[ data.type ](
							data.width,
							data.height,
							data.depth,
							data.widthSegments,
							data.heightSegments,
							data.depthSegments
						);

						break;

					case 'CircleGeometry':
					case 'CircleBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.radius,
							data.segments,
							data.thetaStart,
							data.thetaLength
						);

						break;

					case 'CylinderGeometry':
					case 'CylinderBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.radiusTop,
							data.radiusBottom,
							data.height,
							data.radialSegments,
							data.heightSegments,
							data.openEnded,
							data.thetaStart,
							data.thetaLength
						);

						break;

					case 'ConeGeometry':
					case 'ConeBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.radius,
							data.height,
							data.radialSegments,
							data.heightSegments,
							data.openEnded,
							data.thetaStart,
							data.thetaLength
						);

						break;

					case 'SphereGeometry':
					case 'SphereBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.radius,
							data.widthSegments,
							data.heightSegments,
							data.phiStart,
							data.phiLength,
							data.thetaStart,
							data.thetaLength
						);

						break;

					case 'DodecahedronGeometry':
					case 'DodecahedronBufferGeometry':
					case 'IcosahedronGeometry':
					case 'IcosahedronBufferGeometry':
					case 'OctahedronGeometry':
					case 'OctahedronBufferGeometry':
					case 'TetrahedronGeometry':
					case 'TetrahedronBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.radius,
							data.detail
						);

						break;

					case 'RingGeometry':
					case 'RingBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.innerRadius,
							data.outerRadius,
							data.thetaSegments,
							data.phiSegments,
							data.thetaStart,
							data.thetaLength
						);

						break;

					case 'TorusGeometry':
					case 'TorusBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.radius,
							data.tube,
							data.radialSegments,
							data.tubularSegments,
							data.arc
						);

						break;

					case 'TorusKnotGeometry':
					case 'TorusKnotBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.radius,
							data.tube,
							data.tubularSegments,
							data.radialSegments,
							data.p,
							data.q
						);

						break;

					case 'TubeGeometry':
					case 'TubeBufferGeometry':

						// This only works for built-in curves (e.g. CatmullRomCurve3).
						// User defined curves or instances of CurvePath will not be deserialized.
						geometry = new Geometries[ data.type ](
							new Curves[ data.path.type ]().fromJSON( data.path ),
							data.tubularSegments,
							data.radius,
							data.radialSegments,
							data.closed
						);

						break;

					case 'LatheGeometry':
					case 'LatheBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.points,
							data.segments,
							data.phiStart,
							data.phiLength
						);

						break;

					case 'PolyhedronGeometry':
					case 'PolyhedronBufferGeometry':

						geometry = new Geometries[ data.type ](
							data.vertices,
							data.indices,
							data.radius,
							data.details
						);

						break;

					case 'ShapeGeometry':
					case 'ShapeBufferGeometry':

						geometryShapes = [];

						for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {

							const shape = shapes[ data.shapes[ j ] ];

							geometryShapes.push( shape );

						}

						geometry = new Geometries[ data.type ](
							geometryShapes,
							data.curveSegments
						);

						break;


					case 'ExtrudeGeometry':
					case 'ExtrudeBufferGeometry':

						geometryShapes = [];

						for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {

							const shape = shapes[ data.shapes[ j ] ];

							geometryShapes.push( shape );

						}

						const extrudePath = data.options.extrudePath;

						if ( extrudePath !== undefined ) {

							data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );

						}

						geometry = new Geometries[ data.type ](
							geometryShapes,
							data.options
						);

						break;

					case 'BufferGeometry':
					case 'InstancedBufferGeometry':

						geometry = bufferGeometryLoader.parse( data );

						break;

					case 'Geometry':

						console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );

						break;

					default:

						console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );

						continue;

				}

				geometry.uuid = data.uuid;

				if ( data.name !== undefined ) geometry.name = data.name;
				if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;

				geometries[ data.uuid ] = geometry;

			}

		}

		return geometries;

	},

	parseMaterials: function ( json, textures ) {

		const cache = {}; // MultiMaterial
		const materials = {};

		if ( json !== undefined ) {

			const loader = new MaterialLoader();
			loader.setTextures( textures );

			for ( let i = 0, l = json.length; i < l; i ++ ) {

				const data = json[ i ];

				if ( data.type === 'MultiMaterial' ) {

					// Deprecated

					const array = [];

					for ( let j = 0; j < data.materials.length; j ++ ) {

						const material = data.materials[ j ];

						if ( cache[ material.uuid ] === undefined ) {

							cache[ material.uuid ] = loader.parse( material );

						}

						array.push( cache[ material.uuid ] );

					}

					materials[ data.uuid ] = array;

				} else {

					if ( cache[ data.uuid ] === undefined ) {

						cache[ data.uuid ] = loader.parse( data );

					}

					materials[ data.uuid ] = cache[ data.uuid ];

				}

			}

		}

		return materials;

	},

	parseAnimations: function ( json ) {

		const animations = [];

		for ( let i = 0; i < json.length; i ++ ) {

			const data = json[ i ];

			const clip = AnimationClip.parse( data );

			if ( data.uuid !== undefined ) clip.uuid = data.uuid;

			animations.push( clip );

		}

		return animations;

	},

	parseImages: function ( json, onLoad ) {

		const scope = this;
		const images = {};

		let loader;

		function loadImage( url ) {

			scope.manager.itemStart( url );

			return loader.load( url, function () {

				scope.manager.itemEnd( url );

			}, undefined, function () {

				scope.manager.itemError( url );
				scope.manager.itemEnd( url );

			} );

		}

		if ( json !== undefined && json.length > 0 ) {

			const manager = new LoadingManager( onLoad );

			loader = new ImageLoader( manager );
			loader.setCrossOrigin( this.crossOrigin );

			for ( let i = 0, il = json.length; i < il; i ++ ) {

				const image = json[ i ];
				const url = image.url;

				if ( Array.isArray( url ) ) {

					// load array of images e.g CubeTexture

					images[ image.uuid ] = [];

					for ( let j = 0, jl = url.length; j < jl; j ++ ) {

						const currentUrl = url[ j ];

						const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( currentUrl ) ? currentUrl : scope.resourcePath + currentUrl;

						images[ image.uuid ].push( loadImage( path ) );

					}

				} else {

					// load single image

					const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.resourcePath + image.url;

					images[ image.uuid ] = loadImage( path );

				}

			}

		}

		return images;

	},

	parseTextures: function ( json, images ) {

		function parseConstant( value, type ) {

			if ( typeof value === 'number' ) return value;

			console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );

			return type[ value ];

		}

		const textures = {};

		if ( json !== undefined ) {

			for ( let i = 0, l = json.length; i < l; i ++ ) {

				const data = json[ i ];

				if ( data.image === undefined ) {

					console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );

				}

				if ( images[ data.image ] === undefined ) {

					console.warn( 'THREE.ObjectLoader: Undefined image', data.image );

				}

				let texture;

				if ( Array.isArray( images[ data.image ] ) ) {

					texture = new CubeTexture( images[ data.image ] );

				} else {

					texture = new Texture( images[ data.image ] );

				}

				texture.needsUpdate = true;

				texture.uuid = data.uuid;

				if ( data.name !== undefined ) texture.name = data.name;

				if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );

				if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
				if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
				if ( data.center !== undefined ) texture.center.fromArray( data.center );
				if ( data.rotation !== undefined ) texture.rotation = data.rotation;

				if ( data.wrap !== undefined ) {

					texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
					texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );

				}

				if ( data.format !== undefined ) texture.format = data.format;
				if ( data.type !== undefined ) texture.type = data.type;
				if ( data.encoding !== undefined ) texture.encoding = data.encoding;

				if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
				if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
				if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;

				if ( data.flipY !== undefined ) texture.flipY = data.flipY;

				if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
				if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;

				textures[ data.uuid ] = texture;

			}

		}

		return textures;

	},

	parseObject: function ( data, geometries, materials ) {

		let object;

		function getGeometry( name ) {

			if ( geometries[ name ] === undefined ) {

				console.warn( 'THREE.ObjectLoader: Undefined geometry', name );

			}

			return geometries[ name ];

		}

		function getMaterial( name ) {

			if ( name === undefined ) return undefined;

			if ( Array.isArray( name ) ) {

				const array = [];

				for ( let i = 0, l = name.length; i < l; i ++ ) {

					const uuid = name[ i ];

					if ( materials[ uuid ] === undefined ) {

						console.warn( 'THREE.ObjectLoader: Undefined material', uuid );

					}

					array.push( materials[ uuid ] );

				}

				return array;

			}

			if ( materials[ name ] === undefined ) {

				console.warn( 'THREE.ObjectLoader: Undefined material', name );

			}

			return materials[ name ];

		}

		let geometry, material;

		switch ( data.type ) {

			case 'Scene':

				object = new Scene();

				if ( data.background !== undefined ) {

					if ( Number.isInteger( data.background ) ) {

						object.background = new Color( data.background );

					}

				}

				if ( data.fog !== undefined ) {

					if ( data.fog.type === 'Fog' ) {

						object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );

					} else if ( data.fog.type === 'FogExp2' ) {

						object.fog = new FogExp2( data.fog.color, data.fog.density );

					}

				}

				break;

			case 'PerspectiveCamera':

				object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );

				if ( data.focus !== undefined ) object.focus = data.focus;
				if ( data.zoom !== undefined ) object.zoom = data.zoom;
				if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
				if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
				if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );

				break;

			case 'OrthographicCamera':

				object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );

				if ( data.zoom !== undefined ) object.zoom = data.zoom;
				if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );

				break;

			case 'AmbientLight':

				object = new AmbientLight( data.color, data.intensity );

				break;

			case 'DirectionalLight':

				object = new DirectionalLight( data.color, data.intensity );

				break;

			case 'PointLight':

				object = new PointLight( data.color, data.intensity, data.distance, data.decay );

				break;

			case 'RectAreaLight':

				object = new RectAreaLight( data.color, data.intensity, data.width, data.height );

				break;

			case 'SpotLight':

				object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );

				break;

			case 'HemisphereLight':

				object = new HemisphereLight( data.color, data.groundColor, data.intensity );

				break;

			case 'LightProbe':

				object = new LightProbe().fromJSON( data );

				break;

			case 'SkinnedMesh':

				console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );

			case 'Mesh':

				geometry = getGeometry( data.geometry );
				material = getMaterial( data.material );

				object = new Mesh( geometry, material );

				break;

			case 'InstancedMesh':

				geometry = getGeometry( data.geometry );
				material = getMaterial( data.material );
				const count = data.count;
				const instanceMatrix = data.instanceMatrix;

				object = new InstancedMesh( geometry, material, count );
				object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );

				break;

			case 'LOD':

				object = new LOD();

				break;

			case 'Line':

				object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );

				break;

			case 'LineLoop':

				object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );

				break;

			case 'LineSegments':

				object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );

				break;

			case 'PointCloud':
			case 'Points':

				object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );

				break;

			case 'Sprite':

				object = new Sprite( getMaterial( data.material ) );

				break;

			case 'Group':

				object = new Group();

				break;

			default:

				object = new Object3D();

		}

		object.uuid = data.uuid;

		if ( data.name !== undefined ) object.name = data.name;

		if ( data.matrix !== undefined ) {

			object.matrix.fromArray( data.matrix );

			if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
			if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );

		} else {

			if ( data.position !== undefined ) object.position.fromArray( data.position );
			if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
			if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
			if ( data.scale !== undefined ) object.scale.fromArray( data.scale );

		}

		if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
		if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;

		if ( data.shadow ) {

			if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
			if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
			if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
			if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
			if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );

		}

		if ( data.visible !== undefined ) object.visible = data.visible;
		if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
		if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
		if ( data.userData !== undefined ) object.userData = data.userData;
		if ( data.layers !== undefined ) object.layers.mask = data.layers;

		if ( data.children !== undefined ) {

			const children = data.children;

			for ( let i = 0; i < children.length; i ++ ) {

				object.add( this.parseObject( children[ i ], geometries, materials ) );

			}

		}

		if ( data.type === 'LOD' ) {

			if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;

			const levels = data.levels;

			for ( let l = 0; l < levels.length; l ++ ) {

				const level = levels[ l ];
				const child = object.getObjectByProperty( 'uuid', level.object );

				if ( child !== undefined ) {

					object.addLevel( child, level.distance );

				}

			}

		}

		return object;

	}

} );

const TEXTURE_MAPPING = {
	UVMapping: UVMapping,
	CubeReflectionMapping: CubeReflectionMapping,
	CubeRefractionMapping: CubeRefractionMapping,
	EquirectangularReflectionMapping: EquirectangularReflectionMapping,
	EquirectangularRefractionMapping: EquirectangularRefractionMapping,
	CubeUVReflectionMapping: CubeUVReflectionMapping,
	CubeUVRefractionMapping: CubeUVRefractionMapping
};

const TEXTURE_WRAPPING = {
	RepeatWrapping: RepeatWrapping,
	ClampToEdgeWrapping: ClampToEdgeWrapping,
	MirroredRepeatWrapping: MirroredRepeatWrapping
};

const TEXTURE_FILTER = {
	NearestFilter: NearestFilter,
	NearestMipmapNearestFilter: NearestMipmapNearestFilter,
	NearestMipmapLinearFilter: NearestMipmapLinearFilter,
	LinearFilter: LinearFilter,
	LinearMipmapNearestFilter: LinearMipmapNearestFilter,
	LinearMipmapLinearFilter: LinearMipmapLinearFilter
};

/**
 * @author thespite / http://clicktorelease.com/
 */


function ImageBitmapLoader( manager ) {

	if ( typeof createImageBitmap === 'undefined' ) {

		console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );

	}

	if ( typeof fetch === 'undefined' ) {

		console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );

	}

	Loader.call( this, manager );

	this.options = { premultiplyAlpha: 'none' };

}

ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: ImageBitmapLoader,

	isImageBitmapLoader: true,

	setOptions: function setOptions( options ) {

		this.options = options;

		return this;

	},

	load: function ( url, onLoad, onProgress, onError ) {

		if ( url === undefined ) url = '';

		if ( this.path !== undefined ) url = this.path + url;

		url = this.manager.resolveURL( url );

		const scope = this;

		const cached = Cache.get( url );

		if ( cached !== undefined ) {

			scope.manager.itemStart( url );

			setTimeout( function () {

				if ( onLoad ) onLoad( cached );

				scope.manager.itemEnd( url );

			}, 0 );

			return cached;

		}

		fetch( url ).then( function ( res ) {

			return res.blob();

		} ).then( function ( blob ) {

			return createImageBitmap( blob, scope.options );

		} ).then( function ( imageBitmap ) {

			Cache.add( url, imageBitmap );

			if ( onLoad ) onLoad( imageBitmap );

			scope.manager.itemEnd( url );

		} ).catch( function ( e ) {

			if ( onError ) onError( e );

			scope.manager.itemError( url );
			scope.manager.itemEnd( url );

		} );

		scope.manager.itemStart( url );

	}

} );

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
 **/

function ShapePath() {

	this.type = 'ShapePath';

	this.color = new Color();

	this.subPaths = [];
	this.currentPath = null;

}

Object.assign( ShapePath.prototype, {

	moveTo: function ( x, y ) {

		this.currentPath = new Path();
		this.subPaths.push( this.currentPath );
		this.currentPath.moveTo( x, y );

		return this;

	},

	lineTo: function ( x, y ) {

		this.currentPath.lineTo( x, y );

		return this;

	},

	quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {

		this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );

		return this;

	},

	bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {

		this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );

		return this;

	},

	splineThru: function ( pts ) {

		this.currentPath.splineThru( pts );

		return this;

	},

	toShapes: function ( isCCW, noHoles ) {

		function toShapesNoHoles( inSubpaths ) {

			const shapes = [];

			for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {

				const tmpPath = inSubpaths[ i ];

				const tmpShape = new Shape();
				tmpShape.curves = tmpPath.curves;

				shapes.push( tmpShape );

			}

			return shapes;

		}

		function isPointInsidePolygon( inPt, inPolygon ) {

			const polyLen = inPolygon.length;

			// inPt on polygon contour => immediate success    or
			// toggling of inside/outside at every single! intersection point of an edge
			//  with the horizontal line through inPt, left of inPt
			//  not counting lowerY endpoints of edges and whole edges on that line
			let inside = false;
			for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {

				let edgeLowPt = inPolygon[ p ];
				let edgeHighPt = inPolygon[ q ];

				let edgeDx = edgeHighPt.x - edgeLowPt.x;
				let edgeDy = edgeHighPt.y - edgeLowPt.y;

				if ( Math.abs( edgeDy ) > Number.EPSILON ) {

					// not parallel
					if ( edgeDy < 0 ) {

						edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
						edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;

					}

					if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) 		continue;

					if ( inPt.y === edgeLowPt.y ) {

						if ( inPt.x === edgeLowPt.x )		return	true;		// inPt is on contour ?
						// continue;				// no intersection or edgeLowPt => doesn't count !!!

					} else {

						const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
						if ( perpEdge === 0 )				return	true;		// inPt is on contour ?
						if ( perpEdge < 0 ) 				continue;
						inside = ! inside;		// true intersection left of inPt

					}

				} else {

					// parallel or collinear
					if ( inPt.y !== edgeLowPt.y ) 		continue;			// parallel
					// edge lies on the same horizontal line as inPt
					if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
						 ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) )		return	true;	// inPt: Point on contour !
					// continue;

				}

			}

			return	inside;

		}

		const isClockWise = ShapeUtils.isClockWise;

		const subPaths = this.subPaths;
		if ( subPaths.length === 0 ) return [];

		if ( noHoles === true )	return	toShapesNoHoles( subPaths );


		let solid, tmpPath, tmpShape, shapes = [];

		if ( subPaths.length === 1 ) {

			tmpPath = subPaths[ 0 ];
			tmpShape = new Shape();
			tmpShape.curves = tmpPath.curves;
			shapes.push( tmpShape );
			return shapes;

		}

		let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
		holesFirst = isCCW ? ! holesFirst : holesFirst;

		// console.log("Holes first", holesFirst);

		const betterShapeHoles = [];
		const newShapes = [];
		let newShapeHoles = [];
		let mainIdx = 0;
		let tmpPoints;

		newShapes[ mainIdx ] = undefined;
		newShapeHoles[ mainIdx ] = [];

		for ( let i = 0, l = subPaths.length; i < l; i ++ ) {

			tmpPath = subPaths[ i ];
			tmpPoints = tmpPath.getPoints();
			solid = isClockWise( tmpPoints );
			solid = isCCW ? ! solid : solid;

			if ( solid ) {

				if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) )	mainIdx ++;

				newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
				newShapes[ mainIdx ].s.curves = tmpPath.curves;

				if ( holesFirst )	mainIdx ++;
				newShapeHoles[ mainIdx ] = [];

				//console.log('cw', i);

			} else {

				newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );

				//console.log('ccw', i);

			}

		}

		// only Holes? -> probably all Shapes with wrong orientation
		if ( ! newShapes[ 0 ] )	return	toShapesNoHoles( subPaths );


		if ( newShapes.length > 1 ) {

			let ambiguous = false;
			const toChange = [];

			for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {

				betterShapeHoles[ sIdx ] = [];

			}

			for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {

				const sho = newShapeHoles[ sIdx ];

				for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {

					const ho = sho[ hIdx ];
					let hole_unassigned = true;

					for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {

						if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {

							if ( sIdx !== s2Idx )	toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
							if ( hole_unassigned ) {

								hole_unassigned = false;
								betterShapeHoles[ s2Idx ].push( ho );

							} else {

								ambiguous = true;

							}

						}

					}

					if ( hole_unassigned ) {

						betterShapeHoles[ sIdx ].push( ho );

					}

				}

			}
			// console.log("ambiguous: ", ambiguous);

			if ( toChange.length > 0 ) {

				// console.log("to change: ", toChange);
				if ( ! ambiguous )	newShapeHoles = betterShapeHoles;

			}

		}

		let tmpHoles;

		for ( let i = 0, il = newShapes.length; i < il; i ++ ) {

			tmpShape = newShapes[ i ].s;
			shapes.push( tmpShape );
			tmpHoles = newShapeHoles[ i ];

			for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {

				tmpShape.holes.push( tmpHoles[ j ].h );

			}

		}

		//console.log("shape", shapes);

		return shapes;

	}

} );

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * @author mrdoob / http://mrdoob.com/
 */


function Font( data ) {

	this.type = 'Font';

	this.data = data;

}

Object.assign( Font.prototype, {

	isFont: true,

	generateShapes: function ( text, size ) {

		if ( size === undefined ) size = 100;

		const shapes = [];
		const paths = createPaths( text, size, this.data );

		for ( let p = 0, pl = paths.length; p < pl; p ++ ) {

			Array.prototype.push.apply( shapes, paths[ p ].toShapes() );

		}

		return shapes;

	}

} );

function createPaths( text, size, data ) {

	const chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
	const scale = size / data.resolution;
	const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;

	const paths = [];

	let offsetX = 0, offsetY = 0;

	for ( let i = 0; i < chars.length; i ++ ) {

		const char = chars[ i ];

		if ( char === '\n' ) {

			offsetX = 0;
			offsetY -= line_height;

		} else {

			const ret = createPath( char, scale, offsetX, offsetY, data );
			offsetX += ret.offsetX;
			paths.push( ret.path );

		}

	}

	return paths;

}

function createPath( char, scale, offsetX, offsetY, data ) {

	const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];

	if ( ! glyph ) {

		console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );

		return;

	}

	const path = new ShapePath();

	let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;

	if ( glyph.o ) {

		const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );

		for ( let i = 0, l = outline.length; i < l; ) {

			const action = outline[ i ++ ];

			switch ( action ) {

				case 'm': // moveTo

					x = outline[ i ++ ] * scale + offsetX;
					y = outline[ i ++ ] * scale + offsetY;

					path.moveTo( x, y );

					break;

				case 'l': // lineTo

					x = outline[ i ++ ] * scale + offsetX;
					y = outline[ i ++ ] * scale + offsetY;

					path.lineTo( x, y );

					break;

				case 'q': // quadraticCurveTo

					cpx = outline[ i ++ ] * scale + offsetX;
					cpy = outline[ i ++ ] * scale + offsetY;
					cpx1 = outline[ i ++ ] * scale + offsetX;
					cpy1 = outline[ i ++ ] * scale + offsetY;

					path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );

					break;

				case 'b': // bezierCurveTo

					cpx = outline[ i ++ ] * scale + offsetX;
					cpy = outline[ i ++ ] * scale + offsetY;
					cpx1 = outline[ i ++ ] * scale + offsetX;
					cpy1 = outline[ i ++ ] * scale + offsetY;
					cpx2 = outline[ i ++ ] * scale + offsetX;
					cpy2 = outline[ i ++ ] * scale + offsetY;

					path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );

					break;

			}

		}

	}

	return { offsetX: glyph.ha * scale, path: path };

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function FontLoader( manager ) {

	Loader.call( this, manager );

}

FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: FontLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const loader = new FileLoader( this.manager );
		loader.setPath( this.path );
		loader.load( url, function ( text ) {

			let json;

			try {

				json = JSON.parse( text );

			} catch ( e ) {

				console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
				json = JSON.parse( text.substring( 65, text.length - 2 ) );

			}

			const font = scope.parse( json );

			if ( onLoad ) onLoad( font );

		}, onProgress, onError );

	},

	parse: function ( json ) {

		return new Font( json );

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

let _context;

const AudioContext = {

	getContext: function () {

		if ( _context === undefined ) {

			_context = new ( window.AudioContext || window.webkitAudioContext )();

		}

		return _context;

	},

	setContext: function ( value ) {

		_context = value;

	}

};

/**
 * @author Reece Aaron Lecrivain / http://reecenotes.com/
 */

function AudioLoader( manager ) {

	Loader.call( this, manager );

}

AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: AudioLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		const scope = this;

		const loader = new FileLoader( scope.manager );
		loader.setResponseType( 'arraybuffer' );
		loader.setPath( scope.path );
		loader.load( url, function ( buffer ) {

			try {

				// Create a copy of the buffer. The `decodeAudioData` method
				// detaches the buffer when complete, preventing reuse.
				const bufferCopy = buffer.slice( 0 );

				const context = AudioContext.getContext();
				context.decodeAudioData( bufferCopy, function ( audioBuffer ) {

					onLoad( audioBuffer );

				} );

			} catch ( e ) {

				if ( onError ) {

					onError( e );

				} else {

					console.error( e );

				}

				scope.manager.itemError( url );

			}

		}, onProgress, onError );

	}

} );

/**
 * @author WestLangley / http://github.com/WestLangley
 */

function HemisphereLightProbe( skyColor, groundColor, intensity ) {

	LightProbe.call( this, undefined, intensity );

	const color1 = new Color().set( skyColor );
	const color2 = new Color().set( groundColor );

	const sky = new Vector3( color1.r, color1.g, color1.b );
	const ground = new Vector3( color2.r, color2.g, color2.b );

	// without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
	const c0 = Math.sqrt( Math.PI );
	const c1 = c0 * Math.sqrt( 0.75 );

	this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
	this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );

}

HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {

	constructor: HemisphereLightProbe,

	isHemisphereLightProbe: true,

	copy: function ( source ) { // modifying colors not currently supported

		LightProbe.prototype.copy.call( this, source );

		return this;

	},

	toJSON: function ( meta ) {

		const data = LightProbe.prototype.toJSON.call( this, meta );

		// data.sh = this.sh.toArray(); // todo

		return data;

	}

} );

/**
 * @author WestLangley / http://github.com/WestLangley
 */

function AmbientLightProbe( color, intensity ) {

	LightProbe.call( this, undefined, intensity );

	const color1 = new Color().set( color );

	// without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
	this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );

}

AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {

	constructor: AmbientLightProbe,

	isAmbientLightProbe: true,

	copy: function ( source ) { // modifying color not currently supported

		LightProbe.prototype.copy.call( this, source );

		return this;

	},

	toJSON: function ( meta ) {

		const data = LightProbe.prototype.toJSON.call( this, meta );

		// data.sh = this.sh.toArray(); // todo

		return data;

	}

} );

const _eyeRight = new Matrix4();
const _eyeLeft = new Matrix4();

/**
 * @author mrdoob / http://mrdoob.com/
 */

function StereoCamera() {

	this.type = 'StereoCamera';

	this.aspect = 1;

	this.eyeSep = 0.064;

	this.cameraL = new PerspectiveCamera();
	this.cameraL.layers.enable( 1 );
	this.cameraL.matrixAutoUpdate = false;

	this.cameraR = new PerspectiveCamera();
	this.cameraR.layers.enable( 2 );
	this.cameraR.matrixAutoUpdate = false;

	this._cache = {
		focus: null,
		fov: null,
		aspect: null,
		near: null,
		far: null,
		zoom: null,
		eyeSep: null
	};

}

Object.assign( StereoCamera.prototype, {

	update: function ( camera ) {

		const cache = this._cache;

		const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
			cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
			cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;

		if ( needsUpdate ) {

			cache.focus = camera.focus;
			cache.fov = camera.fov;
			cache.aspect = camera.aspect * this.aspect;
			cache.near = camera.near;
			cache.far = camera.far;
			cache.zoom = camera.zoom;
			cache.eyeSep = this.eyeSep;

			// Off-axis stereoscopic effect based on
			// http://paulbourke.net/stereographics/stereorender/

			const projectionMatrix = camera.projectionMatrix.clone();
			const eyeSepHalf = cache.eyeSep / 2;
			const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
			const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
			let xmin, xmax;

			// translate xOffset

			_eyeLeft.elements[ 12 ] = - eyeSepHalf;
			_eyeRight.elements[ 12 ] = eyeSepHalf;

			// for left eye

			xmin = - ymax * cache.aspect + eyeSepOnProjection;
			xmax = ymax * cache.aspect + eyeSepOnProjection;

			projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
			projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );

			this.cameraL.projectionMatrix.copy( projectionMatrix );

			// for right eye

			xmin = - ymax * cache.aspect - eyeSepOnProjection;
			xmax = ymax * cache.aspect - eyeSepOnProjection;

			projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
			projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );

			this.cameraR.projectionMatrix.copy( projectionMatrix );

		}

		this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
		this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );

	}

} );

/**
 * @author alteredq / http://alteredqualia.com/
 */

function Clock( autoStart ) {

	this.autoStart = ( autoStart !== undefined ) ? autoStart : true;

	this.startTime = 0;
	this.oldTime = 0;
	this.elapsedTime = 0;

	this.running = false;

}

Object.assign( Clock.prototype, {

	start: function () {

		this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732

		this.oldTime = this.startTime;
		this.elapsedTime = 0;
		this.running = true;

	},

	stop: function () {

		this.getElapsedTime();
		this.running = false;
		this.autoStart = false;

	},

	getElapsedTime: function () {

		this.getDelta();
		return this.elapsedTime;

	},

	getDelta: function () {

		let diff = 0;

		if ( this.autoStart && ! this.running ) {

			this.start();
			return 0;

		}

		if ( this.running ) {

			const newTime = ( typeof performance === 'undefined' ? Date : performance ).now();

			diff = ( newTime - this.oldTime ) / 1000;
			this.oldTime = newTime;

			this.elapsedTime += diff;

		}

		return diff;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

const _position$2 = new Vector3();
const _quaternion$3 = new Quaternion();
const _scale$1 = new Vector3();
const _orientation = new Vector3();

function AudioListener() {

	Object3D.call( this );

	this.type = 'AudioListener';

	this.context = AudioContext.getContext();

	this.gain = this.context.createGain();
	this.gain.connect( this.context.destination );

	this.filter = null;

	this.timeDelta = 0;

	// private

	this._clock = new Clock();

}

AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: AudioListener,

	getInput: function () {

		return this.gain;

	},

	removeFilter: function ( ) {

		if ( this.filter !== null ) {

			this.gain.disconnect( this.filter );
			this.filter.disconnect( this.context.destination );
			this.gain.connect( this.context.destination );
			this.filter = null;

		}

		return this;

	},

	getFilter: function () {

		return this.filter;

	},

	setFilter: function ( value ) {

		if ( this.filter !== null ) {

			this.gain.disconnect( this.filter );
			this.filter.disconnect( this.context.destination );

		} else {

			this.gain.disconnect( this.context.destination );

		}

		this.filter = value;
		this.gain.connect( this.filter );
		this.filter.connect( this.context.destination );

		return this;

	},

	getMasterVolume: function () {

		return this.gain.gain.value;

	},

	setMasterVolume: function ( value ) {

		this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );

		return this;

	},

	updateMatrixWorld: function ( force ) {

		Object3D.prototype.updateMatrixWorld.call( this, force );

		const listener = this.context.listener;
		const up = this.up;

		this.timeDelta = this._clock.getDelta();

		this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );

		_orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );

		if ( listener.positionX ) {

			// code path for Chrome (see #14393)

			const endTime = this.context.currentTime + this.timeDelta;

			listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
			listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
			listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
			listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
			listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
			listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
			listener.upX.linearRampToValueAtTime( up.x, endTime );
			listener.upY.linearRampToValueAtTime( up.y, endTime );
			listener.upZ.linearRampToValueAtTime( up.z, endTime );

		} else {

			listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
			listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );

		}

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author Reece Aaron Lecrivain / http://reecenotes.com/
 */

function Audio( listener ) {

	Object3D.call( this );

	this.type = 'Audio';

	this.listener = listener;
	this.context = listener.context;

	this.gain = this.context.createGain();
	this.gain.connect( listener.getInput() );

	this.autoplay = false;

	this.buffer = null;
	this.detune = 0;
	this.loop = false;
	this.loopStart = 0;
	this.loopEnd = 0;
	this.offset = 0;
	this.duration = undefined;
	this.playbackRate = 1;
	this.isPlaying = false;
	this.hasPlaybackControl = true;
	this.sourceType = 'empty';

	this._startedAt = 0;
	this._progress = 0;

	this.filters = [];

}

Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {

	constructor: Audio,

	getOutput: function () {

		return this.gain;

	},

	setNodeSource: function ( audioNode ) {

		this.hasPlaybackControl = false;
		this.sourceType = 'audioNode';
		this.source = audioNode;
		this.connect();

		return this;

	},

	setMediaElementSource: function ( mediaElement ) {

		this.hasPlaybackControl = false;
		this.sourceType = 'mediaNode';
		this.source = this.context.createMediaElementSource( mediaElement );
		this.connect();

		return this;

	},

	setMediaStreamSource: function ( mediaStream ) {

		this.hasPlaybackControl = false;
		this.sourceType = 'mediaStreamNode';
		this.source = this.context.createMediaStreamSource( mediaStream );
		this.connect();

		return this;

	},

	setBuffer: function ( audioBuffer ) {

		this.buffer = audioBuffer;
		this.sourceType = 'buffer';

		if ( this.autoplay ) this.play();

		return this;

	},

	play: function ( delay ) {

		if ( delay === undefined ) delay = 0;

		if ( this.isPlaying === true ) {

			console.warn( 'THREE.Audio: Audio is already playing.' );
			return;

		}

		if ( this.hasPlaybackControl === false ) {

			console.warn( 'THREE.Audio: this Audio has no playback control.' );
			return;

		}

		this._startedAt = this.context.currentTime + delay;

		const source = this.context.createBufferSource();
		source.buffer = this.buffer;
		source.loop = this.loop;
		source.loopStart = this.loopStart;
		source.loopEnd = this.loopEnd;
		source.onended = this.onEnded.bind( this );
		source.start( this._startedAt, this._progress + this.offset, this.duration );

		this.isPlaying = true;

		this.source = source;

		this.setDetune( this.detune );
		this.setPlaybackRate( this.playbackRate );

		return this.connect();

	},

	pause: function () {

		if ( this.hasPlaybackControl === false ) {

			console.warn( 'THREE.Audio: this Audio has no playback control.' );
			return;

		}

		if ( this.isPlaying === true ) {

			// update current progress

			this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;

			if ( this.loop === true ) {

				// ensure _progress does not exceed duration with looped audios

				this._progress = this._progress % ( this.duration || this.buffer.duration );

			}

			this.source.stop();
			this.source.onended = null;

			this.isPlaying = false;

		}

		return this;

	},

	stop: function () {

		if ( this.hasPlaybackControl === false ) {

			console.warn( 'THREE.Audio: this Audio has no playback control.' );
			return;

		}

		this._progress = 0;

		this.source.stop();
		this.source.onended = null;
		this.isPlaying = false;

		return this;

	},

	connect: function () {

		if ( this.filters.length > 0 ) {

			this.source.connect( this.filters[ 0 ] );

			for ( let i = 1, l = this.filters.length; i < l; i ++ ) {

				this.filters[ i - 1 ].connect( this.filters[ i ] );

			}

			this.filters[ this.filters.length - 1 ].connect( this.getOutput() );

		} else {

			this.source.connect( this.getOutput() );

		}

		return this;

	},

	disconnect: function () {

		if ( this.filters.length > 0 ) {

			this.source.disconnect( this.filters[ 0 ] );

			for ( let i = 1, l = this.filters.length; i < l; i ++ ) {

				this.filters[ i - 1 ].disconnect( this.filters[ i ] );

			}

			this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );

		} else {

			this.source.disconnect( this.getOutput() );

		}

		return this;

	},

	getFilters: function () {

		return this.filters;

	},

	setFilters: function ( value ) {

		if ( ! value ) value = [];

		if ( this.isPlaying === true ) {

			this.disconnect();
			this.filters = value;
			this.connect();

		} else {

			this.filters = value;

		}

		return this;

	},

	setDetune: function ( value ) {

		this.detune = value;

		if ( this.source.detune === undefined ) return; // only set detune when available

		if ( this.isPlaying === true ) {

			this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );

		}

		return this;

	},

	getDetune: function () {

		return this.detune;

	},

	getFilter: function () {

		return this.getFilters()[ 0 ];

	},

	setFilter: function ( filter ) {

		return this.setFilters( filter ? [ filter ] : [] );

	},

	setPlaybackRate: function ( value ) {

		if ( this.hasPlaybackControl === false ) {

			console.warn( 'THREE.Audio: this Audio has no playback control.' );
			return;

		}

		this.playbackRate = value;

		if ( this.isPlaying === true ) {

			this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );

		}

		return this;

	},

	getPlaybackRate: function () {

		return this.playbackRate;

	},

	onEnded: function () {

		this.isPlaying = false;

	},

	getLoop: function () {

		if ( this.hasPlaybackControl === false ) {

			console.warn( 'THREE.Audio: this Audio has no playback control.' );
			return false;

		}

		return this.loop;

	},

	setLoop: function ( value ) {

		if ( this.hasPlaybackControl === false ) {

			console.warn( 'THREE.Audio: this Audio has no playback control.' );
			return;

		}

		this.loop = value;

		if ( this.isPlaying === true ) {

			this.source.loop = this.loop;

		}

		return this;

	},

	setLoopStart: function ( value ) {

		this.loopStart = value;

		return this;

	},

	setLoopEnd: function ( value ) {

		this.loopEnd = value;

		return this;

	},

	getVolume: function () {

		return this.gain.gain.value;

	},

	setVolume: function ( value ) {

		this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );

		return this;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

const _position$3 = new Vector3();
const _quaternion$4 = new Quaternion();
const _scale$2 = new Vector3();
const _orientation$1 = new Vector3();

function PositionalAudio( listener ) {

	Audio.call( this, listener );

	this.panner = this.context.createPanner();
	this.panner.panningModel = 'HRTF';
	this.panner.connect( this.gain );

}

PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {

	constructor: PositionalAudio,

	getOutput: function () {

		return this.panner;

	},

	getRefDistance: function () {

		return this.panner.refDistance;

	},

	setRefDistance: function ( value ) {

		this.panner.refDistance = value;

		return this;

	},

	getRolloffFactor: function () {

		return this.panner.rolloffFactor;

	},

	setRolloffFactor: function ( value ) {

		this.panner.rolloffFactor = value;

		return this;

	},

	getDistanceModel: function () {

		return this.panner.distanceModel;

	},

	setDistanceModel: function ( value ) {

		this.panner.distanceModel = value;

		return this;

	},

	getMaxDistance: function () {

		return this.panner.maxDistance;

	},

	setMaxDistance: function ( value ) {

		this.panner.maxDistance = value;

		return this;

	},

	setDirectionalCone: function ( coneInnerAngle, coneOuterAngle, coneOuterGain ) {

		this.panner.coneInnerAngle = coneInnerAngle;
		this.panner.coneOuterAngle = coneOuterAngle;
		this.panner.coneOuterGain = coneOuterGain;

		return this;

	},

	updateMatrixWorld: function ( force ) {

		Object3D.prototype.updateMatrixWorld.call( this, force );

		if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;

		this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );

		_orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );

		const panner = this.panner;

		if ( panner.positionX ) {

			// code path for Chrome and Firefox (see #14393)

			const endTime = this.context.currentTime + this.listener.timeDelta;

			panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
			panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
			panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
			panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
			panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
			panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );

		} else {

			panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
			panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );

		}

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function AudioAnalyser( audio, fftSize ) {

	this.analyser = audio.context.createAnalyser();
	this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;

	this.data = new Uint8Array( this.analyser.frequencyBinCount );

	audio.getOutput().connect( this.analyser );

}

Object.assign( AudioAnalyser.prototype, {

	getFrequencyData: function () {

		this.analyser.getByteFrequencyData( this.data );

		return this.data;

	},

	getAverageFrequency: function () {

		let value = 0;
		const data = this.getFrequencyData();

		for ( let i = 0; i < data.length; i ++ ) {

			value += data[ i ];

		}

		return value / data.length;

	}

} );

/**
 *
 * Buffered scene graph property that allows weighted accumulation.
 *
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

function PropertyMixer( binding, typeName, valueSize ) {

	this.binding = binding;
	this.valueSize = valueSize;

	let mixFunction,
		mixFunctionAdditive,
		setIdentity;

	// buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
	//
	// interpolators can use .buffer as their .result
	// the data then goes to 'incoming'
	//
	// 'accu0' and 'accu1' are used frame-interleaved for
	// the cumulative result and are compared to detect
	// changes
	//
	// 'orig' stores the original state of the property
	//
	// 'add' is used for additive cumulative results
	//
	// 'work' is optional and is only present for quaternion types. It is used
	// to store intermediate quaternion multiplication results

	switch ( typeName ) {

		case 'quaternion':
			mixFunction = this._slerp;
			mixFunctionAdditive = this._slerpAdditive;
			setIdentity = this._setAdditiveIdentityQuaternion;

			this.buffer = new Float64Array( valueSize * 6 );
			this._workIndex = 5;
			break;

		case 'string':
		case 'bool':
			mixFunction = this._select;

			// Use the regular mix function and for additive on these types,
			// additive is not relevant for non-numeric types
			mixFunctionAdditive = this._select;

			setIdentity = this._setAdditiveIdentityOther;

			this.buffer = new Array( valueSize * 5 );
			break;

		default:
			mixFunction = this._lerp;
			mixFunctionAdditive = this._lerpAdditive;
			setIdentity = this._setAdditiveIdentityNumeric;

			this.buffer = new Float64Array( valueSize * 5 );

	}

	this._mixBufferRegion = mixFunction;
	this._mixBufferRegionAdditive = mixFunctionAdditive;
	this._setIdentity = setIdentity;
	this._origIndex = 3;
	this._addIndex = 4;

	this.cumulativeWeight = 0;
	this.cumulativeWeightAdditive = 0;

	this.useCount = 0;
	this.referenceCount = 0;

}

Object.assign( PropertyMixer.prototype, {

	// accumulate data in the 'incoming' region into 'accu<i>'
	accumulate: function ( accuIndex, weight ) {

		// note: happily accumulating nothing when weight = 0, the caller knows
		// the weight and shouldn't have made the call in the first place

		const buffer = this.buffer,
			stride = this.valueSize,
			offset = accuIndex * stride + stride;

		let currentWeight = this.cumulativeWeight;

		if ( currentWeight === 0 ) {

			// accuN := incoming * weight

			for ( let i = 0; i !== stride; ++ i ) {

				buffer[ offset + i ] = buffer[ i ];

			}

			currentWeight = weight;

		} else {

			// accuN := accuN + incoming * weight

			currentWeight += weight;
			const mix = weight / currentWeight;
			this._mixBufferRegion( buffer, offset, 0, mix, stride );

		}

		this.cumulativeWeight = currentWeight;

	},

	// accumulate data in the 'incoming' region into 'add'
	accumulateAdditive: function ( weight ) {

		const buffer = this.buffer,
			stride = this.valueSize,
			offset = stride * this._addIndex;

		if ( this.cumulativeWeightAdditive === 0 ) {

			// add = identity

			this._setIdentity();

		}

		// add := add + incoming * weight

		this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
		this.cumulativeWeightAdditive += weight;

	},

	// apply the state of 'accu<i>' to the binding when accus differ
	apply: function ( accuIndex ) {

		const stride = this.valueSize,
			buffer = this.buffer,
			offset = accuIndex * stride + stride,

			weight = this.cumulativeWeight,
			weightAdditive = this.cumulativeWeightAdditive,

			binding = this.binding;

		this.cumulativeWeight = 0;
		this.cumulativeWeightAdditive = 0;

		if ( weight < 1 ) {

			// accuN := accuN + original * ( 1 - cumulativeWeight )

			const originalValueOffset = stride * this._origIndex;

			this._mixBufferRegion(
				buffer, offset, originalValueOffset, 1 - weight, stride );

		}

		if ( weightAdditive > 0 ) {

			// accuN := accuN + additive accuN

			this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );

		}

		for ( let i = stride, e = stride + stride; i !== e; ++ i ) {

			if ( buffer[ i ] !== buffer[ i + stride ] ) {

				// value has changed -> update scene graph

				binding.setValue( buffer, offset );
				break;

			}

		}

	},

	// remember the state of the bound property and copy it to both accus
	saveOriginalState: function () {

		const binding = this.binding;

		const buffer = this.buffer,
			stride = this.valueSize,

			originalValueOffset = stride * this._origIndex;

		binding.getValue( buffer, originalValueOffset );

		// accu[0..1] := orig -- initially detect changes against the original
		for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {

			buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];

		}

		// Add to identity for additive
		this._setIdentity();

		this.cumulativeWeight = 0;
		this.cumulativeWeightAdditive = 0;

	},

	// apply the state previously taken via 'saveOriginalState' to the binding
	restoreOriginalState: function () {

		const originalValueOffset = this.valueSize * 3;
		this.binding.setValue( this.buffer, originalValueOffset );

	},

	_setAdditiveIdentityNumeric: function () {

		const startIndex = this._addIndex * this.valueSize;
		const endIndex = startIndex + this.valueSize;

		for ( let i = startIndex; i < endIndex; i ++ ) {

			this.buffer[ i ] = 0;

		}

	},

	_setAdditiveIdentityQuaternion: function () {

		this._setAdditiveIdentityNumeric();
		this.buffer[ this._addIndex * 4 + 3 ] = 1;

	},

	_setAdditiveIdentityOther: function () {

		const startIndex = this._origIndex * this.valueSize;
		const targetIndex = this._addIndex * this.valueSize;

		for ( let i = 0; i < this.valueSize; i ++ ) {

			this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];

		}

	},


	// mix functions

	_select: function ( buffer, dstOffset, srcOffset, t, stride ) {

		if ( t >= 0.5 ) {

			for ( let i = 0; i !== stride; ++ i ) {

				buffer[ dstOffset + i ] = buffer[ srcOffset + i ];

			}

		}

	},

	_slerp: function ( buffer, dstOffset, srcOffset, t ) {

		Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );

	},

	_slerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {

		const workOffset = this._workIndex * stride;

		// Store result in intermediate buffer offset
		Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );

		// Slerp to the intermediate result
		Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );

	},

	_lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {

		const s = 1 - t;

		for ( let i = 0; i !== stride; ++ i ) {

			const j = dstOffset + i;

			buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;

		}

	},

	_lerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {

		for ( let i = 0; i !== stride; ++ i ) {

			const j = dstOffset + i;

			buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;

		}

	}

} );

/**
 *
 * A reference to a real property in the scene graph.
 *
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

// Characters [].:/ are reserved for track binding syntax.
const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );

// Attempts to allow node names from any language. ES5's `\w` regexp matches
// only latin characters, and the unicode \p{L} is not yet supported. So
// instead, we exclude reserved characters and match everything else.
const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';

// Parent directories, delimited by '/' or ':'. Currently unused, but must
// be matched to parse the rest of the track name.
const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );

// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );

// Object on target node, and accessor. May not contain reserved
// characters. Accessor may contain any character except closing bracket.
const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );

// Property and accessor. May not contain reserved characters. Accessor may
// contain any non-bracket characters.
const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );

const _trackRe = new RegExp( ''
	+ '^'
	+ _directoryRe
	+ _nodeRe
	+ _objectRe
	+ _propertyRe
	+ '$'
);

const _supportedObjectNames = [ 'material', 'materials', 'bones' ];

function Composite( targetGroup, path, optionalParsedPath ) {

	const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );

	this._targetGroup = targetGroup;
	this._bindings = targetGroup.subscribe_( path, parsedPath );

}

Object.assign( Composite.prototype, {

	getValue: function ( array, offset ) {

		this.bind(); // bind all binding

		const firstValidIndex = this._targetGroup.nCachedObjects_,
			binding = this._bindings[ firstValidIndex ];

		// and only call .getValue on the first
		if ( binding !== undefined ) binding.getValue( array, offset );

	},

	setValue: function ( array, offset ) {

		const bindings = this._bindings;

		for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {

			bindings[ i ].setValue( array, offset );

		}

	},

	bind: function () {

		const bindings = this._bindings;

		for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {

			bindings[ i ].bind();

		}

	},

	unbind: function () {

		const bindings = this._bindings;

		for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {

			bindings[ i ].unbind();

		}

	}

} );


function PropertyBinding( rootNode, path, parsedPath ) {

	this.path = path;
	this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );

	this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;

	this.rootNode = rootNode;

}

Object.assign( PropertyBinding, {

	Composite: Composite,

	create: function ( root, path, parsedPath ) {

		if ( ! ( root && root.isAnimationObjectGroup ) ) {

			return new PropertyBinding( root, path, parsedPath );

		} else {

			return new PropertyBinding.Composite( root, path, parsedPath );

		}

	},

	/**
	 * Replaces spaces with underscores and removes unsupported characters from
	 * node names, to ensure compatibility with parseTrackName().
	 *
	 * @param {string} name Node name to be sanitized.
	 * @return {string}
	 */
	sanitizeNodeName: function ( name ) {

		return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );

	},

	parseTrackName: function ( trackName ) {

		const matches = _trackRe.exec( trackName );

		if ( ! matches ) {

			throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );

		}

		const results = {
			// directoryName: matches[ 1 ], // (tschw) currently unused
			nodeName: matches[ 2 ],
			objectName: matches[ 3 ],
			objectIndex: matches[ 4 ],
			propertyName: matches[ 5 ], // required
			propertyIndex: matches[ 6 ]
		};

		const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );

		if ( lastDot !== undefined && lastDot !== - 1 ) {

			const objectName = results.nodeName.substring( lastDot + 1 );

			// Object names must be checked against an allowlist. Otherwise, there
			// is no way to parse 'foo.bar.baz': 'baz' must be a property, but
			// 'bar' could be the objectName, or part of a nodeName (which can
			// include '.' characters).
			if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {

				results.nodeName = results.nodeName.substring( 0, lastDot );
				results.objectName = objectName;

			}

		}

		if ( results.propertyName === null || results.propertyName.length === 0 ) {

			throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );

		}

		return results;

	},

	findNode: function ( root, nodeName ) {

		if ( ! nodeName || nodeName === "" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {

			return root;

		}

		// search into skeleton bones.
		if ( root.skeleton ) {

			const bone = root.skeleton.getBoneByName( nodeName );

			if ( bone !== undefined ) {

				return bone;

			}

		}

		// search into node subtree.
		if ( root.children ) {

			const searchNodeSubtree = function ( children ) {

				for ( let i = 0; i < children.length; i ++ ) {

					const childNode = children[ i ];

					if ( childNode.name === nodeName || childNode.uuid === nodeName ) {

						return childNode;

					}

					const result = searchNodeSubtree( childNode.children );

					if ( result ) return result;

				}

				return null;

			};

			const subTreeNode = searchNodeSubtree( root.children );

			if ( subTreeNode ) {

				return subTreeNode;

			}

		}

		return null;

	}

} );

Object.assign( PropertyBinding.prototype, { // prototype, continued

	// these are used to "bind" a nonexistent property
	_getValue_unavailable: function () {},
	_setValue_unavailable: function () {},

	BindingType: {
		Direct: 0,
		EntireArray: 1,
		ArrayElement: 2,
		HasFromToArray: 3
	},

	Versioning: {
		None: 0,
		NeedsUpdate: 1,
		MatrixWorldNeedsUpdate: 2
	},

	GetterByBindingType: [

		function getValue_direct( buffer, offset ) {

			buffer[ offset ] = this.node[ this.propertyName ];

		},

		function getValue_array( buffer, offset ) {

			const source = this.resolvedProperty;

			for ( let i = 0, n = source.length; i !== n; ++ i ) {

				buffer[ offset ++ ] = source[ i ];

			}

		},

		function getValue_arrayElement( buffer, offset ) {

			buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];

		},

		function getValue_toArray( buffer, offset ) {

			this.resolvedProperty.toArray( buffer, offset );

		}

	],

	SetterByBindingTypeAndVersioning: [

		[
			// Direct

			function setValue_direct( buffer, offset ) {

				this.targetObject[ this.propertyName ] = buffer[ offset ];

			},

			function setValue_direct_setNeedsUpdate( buffer, offset ) {

				this.targetObject[ this.propertyName ] = buffer[ offset ];
				this.targetObject.needsUpdate = true;

			},

			function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {

				this.targetObject[ this.propertyName ] = buffer[ offset ];
				this.targetObject.matrixWorldNeedsUpdate = true;

			}

		], [

			// EntireArray

			function setValue_array( buffer, offset ) {

				const dest = this.resolvedProperty;

				for ( let i = 0, n = dest.length; i !== n; ++ i ) {

					dest[ i ] = buffer[ offset ++ ];

				}

			},

			function setValue_array_setNeedsUpdate( buffer, offset ) {

				const dest = this.resolvedProperty;

				for ( let i = 0, n = dest.length; i !== n; ++ i ) {

					dest[ i ] = buffer[ offset ++ ];

				}

				this.targetObject.needsUpdate = true;

			},

			function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {

				const dest = this.resolvedProperty;

				for ( let i = 0, n = dest.length; i !== n; ++ i ) {

					dest[ i ] = buffer[ offset ++ ];

				}

				this.targetObject.matrixWorldNeedsUpdate = true;

			}

		], [

			// ArrayElement

			function setValue_arrayElement( buffer, offset ) {

				this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];

			},

			function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {

				this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
				this.targetObject.needsUpdate = true;

			},

			function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {

				this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
				this.targetObject.matrixWorldNeedsUpdate = true;

			}

		], [

			// HasToFromArray

			function setValue_fromArray( buffer, offset ) {

				this.resolvedProperty.fromArray( buffer, offset );

			},

			function setValue_fromArray_setNeedsUpdate( buffer, offset ) {

				this.resolvedProperty.fromArray( buffer, offset );
				this.targetObject.needsUpdate = true;

			},

			function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {

				this.resolvedProperty.fromArray( buffer, offset );
				this.targetObject.matrixWorldNeedsUpdate = true;

			}

		]

	],

	getValue: function getValue_unbound( targetArray, offset ) {

		this.bind();
		this.getValue( targetArray, offset );

		// Note: This class uses a State pattern on a per-method basis:
		// 'bind' sets 'this.getValue' / 'setValue' and shadows the
		// prototype version of these methods with one that represents
		// the bound state. When the property is not found, the methods
		// become no-ops.

	},

	setValue: function getValue_unbound( sourceArray, offset ) {

		this.bind();
		this.setValue( sourceArray, offset );

	},

	// create getter / setter pair for a property in the scene graph
	bind: function () {

		let targetObject = this.node,
			parsedPath = this.parsedPath,

			objectName = parsedPath.objectName,
			propertyName = parsedPath.propertyName,
			propertyIndex = parsedPath.propertyIndex;

		if ( ! targetObject ) {

			targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;

			this.node = targetObject;

		}

		// set fail state so we can just 'return' on error
		this.getValue = this._getValue_unavailable;
		this.setValue = this._setValue_unavailable;

		// ensure there is a value node
		if ( ! targetObject ) {

			console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
			return;

		}

		if ( objectName ) {

			let objectIndex = parsedPath.objectIndex;

			// special cases were we need to reach deeper into the hierarchy to get the face materials....
			switch ( objectName ) {

				case 'materials':

					if ( ! targetObject.material ) {

						console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
						return;

					}

					if ( ! targetObject.material.materials ) {

						console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
						return;

					}

					targetObject = targetObject.material.materials;

					break;

				case 'bones':

					if ( ! targetObject.skeleton ) {

						console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
						return;

					}

					// potential future optimization: skip this if propertyIndex is already an integer
					// and convert the integer string to a true integer.

					targetObject = targetObject.skeleton.bones;

					// support resolving morphTarget names into indices.
					for ( let i = 0; i < targetObject.length; i ++ ) {

						if ( targetObject[ i ].name === objectIndex ) {

							objectIndex = i;
							break;

						}

					}

					break;

				default:

					if ( targetObject[ objectName ] === undefined ) {

						console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
						return;

					}

					targetObject = targetObject[ objectName ];

			}


			if ( objectIndex !== undefined ) {

				if ( targetObject[ objectIndex ] === undefined ) {

					console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
					return;

				}

				targetObject = targetObject[ objectIndex ];

			}

		}

		// resolve property
		const nodeProperty = targetObject[ propertyName ];

		if ( nodeProperty === undefined ) {

			const nodeName = parsedPath.nodeName;

			console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
				'.' + propertyName + ' but it wasn\'t found.', targetObject );
			return;

		}

		// determine versioning scheme
		let versioning = this.Versioning.None;

		this.targetObject = targetObject;

		if ( targetObject.needsUpdate !== undefined ) { // material

			versioning = this.Versioning.NeedsUpdate;

		} else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform

			versioning = this.Versioning.MatrixWorldNeedsUpdate;

		}

		// determine how the property gets bound
		let bindingType = this.BindingType.Direct;

		if ( propertyIndex !== undefined ) {

			// access a sub element of the property array (only primitives are supported right now)

			if ( propertyName === "morphTargetInfluences" ) {

				// potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.

				// support resolving morphTarget names into indices.
				if ( ! targetObject.geometry ) {

					console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
					return;

				}

				if ( targetObject.geometry.isBufferGeometry ) {

					if ( ! targetObject.geometry.morphAttributes ) {

						console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
						return;

					}

					if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {

						propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];

					}


				} else {

					console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
					return;

				}

			}

			bindingType = this.BindingType.ArrayElement;

			this.resolvedProperty = nodeProperty;
			this.propertyIndex = propertyIndex;

		} else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {

			// must use copy for Object3D.Euler/Quaternion

			bindingType = this.BindingType.HasFromToArray;

			this.resolvedProperty = nodeProperty;

		} else if ( Array.isArray( nodeProperty ) ) {

			bindingType = this.BindingType.EntireArray;

			this.resolvedProperty = nodeProperty;

		} else {

			this.propertyName = propertyName;

		}

		// select getter / setter
		this.getValue = this.GetterByBindingType[ bindingType ];
		this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];

	},

	unbind: function () {

		this.node = null;

		// back to the prototype version of getValue / setValue
		// note: avoiding to mutate the shape of 'this' via 'delete'
		this.getValue = this._getValue_unbound;
		this.setValue = this._setValue_unbound;

	}

} );

// DECLARE ALIAS AFTER assign prototype
Object.assign( PropertyBinding.prototype, {

	// initial state of these methods that calls 'bind'
	_getValue_unbound: PropertyBinding.prototype.getValue,
	_setValue_unbound: PropertyBinding.prototype.setValue,

} );

/**
 *
 * A group of objects that receives a shared animation state.
 *
 * Usage:
 *
 *  - Add objects you would otherwise pass as 'root' to the
 *    constructor or the .clipAction method of AnimationMixer.
 *
 *  - Instead pass this object as 'root'.
 *
 *  - You can also add and remove objects later when the mixer
 *    is running.
 *
 * Note:
 *
 *    Objects of this class appear as one object to the mixer,
 *    so cache control of the individual objects must be done
 *    on the group.
 *
 * Limitation:
 *
 *  - The animated properties must be compatible among the
 *    all objects in the group.
 *
 *  - A single property can either be controlled through a
 *    target group or directly, but not both.
 *
 * @author tschw
 */

function AnimationObjectGroup() {

	this.uuid = MathUtils.generateUUID();

	// cached objects followed by the active ones
	this._objects = Array.prototype.slice.call( arguments );

	this.nCachedObjects_ = 0; // threshold
	// note: read by PropertyBinding.Composite

	const indices = {};
	this._indicesByUUID = indices; // for bookkeeping

	for ( let i = 0, n = arguments.length; i !== n; ++ i ) {

		indices[ arguments[ i ].uuid ] = i;

	}

	this._paths = []; // inside: string
	this._parsedPaths = []; // inside: { we don't care, here }
	this._bindings = []; // inside: Array< PropertyBinding >
	this._bindingsIndicesByPath = {}; // inside: indices in these arrays

	const scope = this;

	this.stats = {

		objects: {
			get total() {

				return scope._objects.length;

			},
			get inUse() {

				return this.total - scope.nCachedObjects_;

			}
		},
		get bindingsPerObject() {

			return scope._bindings.length;

		}

	};

}

Object.assign( AnimationObjectGroup.prototype, {

	isAnimationObjectGroup: true,

	add: function () {

		const objects = this._objects,
			indicesByUUID = this._indicesByUUID,
			paths = this._paths,
			parsedPaths = this._parsedPaths,
			bindings = this._bindings,
			nBindings = bindings.length;

		let knownObject = undefined,
			nObjects = objects.length,
			nCachedObjects = this.nCachedObjects_;

		for ( let i = 0, n = arguments.length; i !== n; ++ i ) {

			const object = arguments[ i ],
				uuid = object.uuid;
			let index = indicesByUUID[ uuid ];

			if ( index === undefined ) {

				// unknown object -> add it to the ACTIVE region

				index = nObjects ++;
				indicesByUUID[ uuid ] = index;
				objects.push( object );

				// accounting is done, now do the same for all bindings

				for ( let j = 0, m = nBindings; j !== m; ++ j ) {

					bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );

				}

			} else if ( index < nCachedObjects ) {

				knownObject = objects[ index ];

				// move existing object to the ACTIVE region

				const firstActiveIndex = -- nCachedObjects,
					lastCachedObject = objects[ firstActiveIndex ];

				indicesByUUID[ lastCachedObject.uuid ] = index;
				objects[ index ] = lastCachedObject;

				indicesByUUID[ uuid ] = firstActiveIndex;
				objects[ firstActiveIndex ] = object;

				// accounting is done, now do the same for all bindings

				for ( let j = 0, m = nBindings; j !== m; ++ j ) {

					const bindingsForPath = bindings[ j ],
						lastCached = bindingsForPath[ firstActiveIndex ];

					let binding = bindingsForPath[ index ];

					bindingsForPath[ index ] = lastCached;

					if ( binding === undefined ) {

						// since we do not bother to create new bindings
						// for objects that are cached, the binding may
						// or may not exist

						binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );

					}

					bindingsForPath[ firstActiveIndex ] = binding;

				}

			} else if ( objects[ index ] !== knownObject ) {

				console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
					'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );

			} // else the object is already where we want it to be

		} // for arguments

		this.nCachedObjects_ = nCachedObjects;

	},

	remove: function () {

		const objects = this._objects,
			indicesByUUID = this._indicesByUUID,
			bindings = this._bindings,
			nBindings = bindings.length;

		let nCachedObjects = this.nCachedObjects_;

		for ( let i = 0, n = arguments.length; i !== n; ++ i ) {

			const object = arguments[ i ],
				uuid = object.uuid,
				index = indicesByUUID[ uuid ];

			if ( index !== undefined && index >= nCachedObjects ) {

				// move existing object into the CACHED region

				const lastCachedIndex = nCachedObjects ++,
					firstActiveObject = objects[ lastCachedIndex ];

				indicesByUUID[ firstActiveObject.uuid ] = index;
				objects[ index ] = firstActiveObject;

				indicesByUUID[ uuid ] = lastCachedIndex;
				objects[ lastCachedIndex ] = object;

				// accounting is done, now do the same for all bindings

				for ( let j = 0, m = nBindings; j !== m; ++ j ) {

					const bindingsForPath = bindings[ j ],
						firstActive = bindingsForPath[ lastCachedIndex ],
						binding = bindingsForPath[ index ];

					bindingsForPath[ index ] = firstActive;
					bindingsForPath[ lastCachedIndex ] = binding;

				}

			}

		} // for arguments

		this.nCachedObjects_ = nCachedObjects;

	},

	// remove & forget
	uncache: function () {

		const objects = this._objects,
			indicesByUUID = this._indicesByUUID,
			bindings = this._bindings,
			nBindings = bindings.length;

		let nCachedObjects = this.nCachedObjects_,
			nObjects = objects.length;

		for ( let i = 0, n = arguments.length; i !== n; ++ i ) {

			const object = arguments[ i ],
				uuid = object.uuid,
				index = indicesByUUID[ uuid ];

			if ( index !== undefined ) {

				delete indicesByUUID[ uuid ];

				if ( index < nCachedObjects ) {

					// object is cached, shrink the CACHED region

					const firstActiveIndex = -- nCachedObjects,
						lastCachedObject = objects[ firstActiveIndex ],
						lastIndex = -- nObjects,
						lastObject = objects[ lastIndex ];

					// last cached object takes this object's place
					indicesByUUID[ lastCachedObject.uuid ] = index;
					objects[ index ] = lastCachedObject;

					// last object goes to the activated slot and pop
					indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
					objects[ firstActiveIndex ] = lastObject;
					objects.pop();

					// accounting is done, now do the same for all bindings

					for ( let j = 0, m = nBindings; j !== m; ++ j ) {

						const bindingsForPath = bindings[ j ],
							lastCached = bindingsForPath[ firstActiveIndex ],
							last = bindingsForPath[ lastIndex ];

						bindingsForPath[ index ] = lastCached;
						bindingsForPath[ firstActiveIndex ] = last;
						bindingsForPath.pop();

					}

				} else {

					// object is active, just swap with the last and pop

					const lastIndex = -- nObjects,
						lastObject = objects[ lastIndex ];

					indicesByUUID[ lastObject.uuid ] = index;
					objects[ index ] = lastObject;
					objects.pop();

					// accounting is done, now do the same for all bindings

					for ( let j = 0, m = nBindings; j !== m; ++ j ) {

						const bindingsForPath = bindings[ j ];

						bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
						bindingsForPath.pop();

					}

				} // cached or active

			} // if object is known

		} // for arguments

		this.nCachedObjects_ = nCachedObjects;

	},

	// Internal interface used by befriended PropertyBinding.Composite:

	subscribe_: function ( path, parsedPath ) {

		// returns an array of bindings for the given path that is changed
		// according to the contained objects in the group

		let indicesByPath = this._bindingsIndicesByPath,
			index = indicesByPath[ path ],
			bindings = this._bindings;

		if ( index !== undefined ) return bindings[ index ];

		const paths = this._paths,
			parsedPaths = this._parsedPaths,
			objects = this._objects,
			nObjects = objects.length,
			nCachedObjects = this.nCachedObjects_,
			bindingsForPath = new Array( nObjects );

		index = bindings.length;

		indicesByPath[ path ] = index;

		paths.push( path );
		parsedPaths.push( parsedPath );
		bindings.push( bindingsForPath );

		for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {

			const object = objects[ i ];
			bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );

		}

		return bindingsForPath;

	},

	unsubscribe_: function ( path ) {

		// tells the group to forget about a property path and no longer
		// update the array previously obtained with 'subscribe_'

		const indicesByPath = this._bindingsIndicesByPath,
			index = indicesByPath[ path ];

		if ( index !== undefined ) {

			const paths = this._paths,
				parsedPaths = this._parsedPaths,
				bindings = this._bindings,
				lastBindingsIndex = bindings.length - 1,
				lastBindings = bindings[ lastBindingsIndex ],
				lastBindingsPath = path[ lastBindingsIndex ];

			indicesByPath[ lastBindingsPath ] = index;

			bindings[ index ] = lastBindings;
			bindings.pop();

			parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
			parsedPaths.pop();

			paths[ index ] = paths[ lastBindingsIndex ];
			paths.pop();

		}

	}

} );

/**
 *
 * Action provided by AnimationMixer for scheduling clip playback on specific
 * objects.
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 *
 */

function AnimationAction( mixer, clip, localRoot, blendMode ) {

	this._mixer = mixer;
	this._clip = clip;
	this._localRoot = localRoot || null;
	this.blendMode = blendMode || clip.blendMode;

	const tracks = clip.tracks,
		nTracks = tracks.length,
		interpolants = new Array( nTracks );

	const interpolantSettings = {
		endingStart: ZeroCurvatureEnding,
		endingEnd: ZeroCurvatureEnding
	};

	for ( let i = 0; i !== nTracks; ++ i ) {

		const interpolant = tracks[ i ].createInterpolant( null );
		interpolants[ i ] = interpolant;
		interpolant.settings = interpolantSettings;

	}

	this._interpolantSettings = interpolantSettings;

	this._interpolants = interpolants; // bound by the mixer

	// inside: PropertyMixer (managed by the mixer)
	this._propertyBindings = new Array( nTracks );

	this._cacheIndex = null; // for the memory manager
	this._byClipCacheIndex = null; // for the memory manager

	this._timeScaleInterpolant = null;
	this._weightInterpolant = null;

	this.loop = LoopRepeat;
	this._loopCount = - 1;

	// global mixer time when the action is to be started
	// it's set back to 'null' upon start of the action
	this._startTime = null;

	// scaled local time of the action
	// gets clamped or wrapped to 0..clip.duration according to loop
	this.time = 0;

	this.timeScale = 1;
	this._effectiveTimeScale = 1;

	this.weight = 1;
	this._effectiveWeight = 1;

	this.repetitions = Infinity; // no. of repetitions when looping

	this.paused = false; // true -> zero effective time scale
	this.enabled = true; // false -> zero effective weight

	this.clampWhenFinished = false;// keep feeding the last frame?

	this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
	this.zeroSlopeAtEnd = true;// clips for start, loop and end

}

Object.assign( AnimationAction.prototype, {

	// State & Scheduling

	play: function () {

		this._mixer._activateAction( this );

		return this;

	},

	stop: function () {

		this._mixer._deactivateAction( this );

		return this.reset();

	},

	reset: function () {

		this.paused = false;
		this.enabled = true;

		this.time = 0; // restart clip
		this._loopCount = - 1;// forget previous loops
		this._startTime = null;// forget scheduling

		return this.stopFading().stopWarping();

	},

	isRunning: function () {

		return this.enabled && ! this.paused && this.timeScale !== 0 &&
			this._startTime === null && this._mixer._isActiveAction( this );

	},

	// return true when play has been called
	isScheduled: function () {

		return this._mixer._isActiveAction( this );

	},

	startAt: function ( time ) {

		this._startTime = time;

		return this;

	},

	setLoop: function ( mode, repetitions ) {

		this.loop = mode;
		this.repetitions = repetitions;

		return this;

	},

	// Weight

	// set the weight stopping any scheduled fading
	// although .enabled = false yields an effective weight of zero, this
	// method does *not* change .enabled, because it would be confusing
	setEffectiveWeight: function ( weight ) {

		this.weight = weight;

		// note: same logic as when updated at runtime
		this._effectiveWeight = this.enabled ? weight : 0;

		return this.stopFading();

	},

	// return the weight considering fading and .enabled
	getEffectiveWeight: function () {

		return this._effectiveWeight;

	},

	fadeIn: function ( duration ) {

		return this._scheduleFading( duration, 0, 1 );

	},

	fadeOut: function ( duration ) {

		return this._scheduleFading( duration, 1, 0 );

	},

	crossFadeFrom: function ( fadeOutAction, duration, warp ) {

		fadeOutAction.fadeOut( duration );
		this.fadeIn( duration );

		if ( warp ) {

			const fadeInDuration = this._clip.duration,
				fadeOutDuration = fadeOutAction._clip.duration,

				startEndRatio = fadeOutDuration / fadeInDuration,
				endStartRatio = fadeInDuration / fadeOutDuration;

			fadeOutAction.warp( 1.0, startEndRatio, duration );
			this.warp( endStartRatio, 1.0, duration );

		}

		return this;

	},

	crossFadeTo: function ( fadeInAction, duration, warp ) {

		return fadeInAction.crossFadeFrom( this, duration, warp );

	},

	stopFading: function () {

		let weightInterpolant = this._weightInterpolant;

		if ( weightInterpolant !== null ) {

			this._weightInterpolant = null;
			this._mixer._takeBackControlInterpolant( weightInterpolant );

		}

		return this;

	},

	// Time Scale Control

	// set the time scale stopping any scheduled warping
	// although .paused = true yields an effective time scale of zero, this
	// method does *not* change .paused, because it would be confusing
	setEffectiveTimeScale: function ( timeScale ) {

		this.timeScale = timeScale;
		this._effectiveTimeScale = this.paused ? 0 : timeScale;

		return this.stopWarping();

	},

	// return the time scale considering warping and .paused
	getEffectiveTimeScale: function () {

		return this._effectiveTimeScale;

	},

	setDuration: function ( duration ) {

		this.timeScale = this._clip.duration / duration;

		return this.stopWarping();

	},

	syncWith: function ( action ) {

		this.time = action.time;
		this.timeScale = action.timeScale;

		return this.stopWarping();

	},

	halt: function ( duration ) {

		return this.warp( this._effectiveTimeScale, 0, duration );

	},

	warp: function ( startTimeScale, endTimeScale, duration ) {

		const mixer = this._mixer,
			now = mixer.time,
			timeScale = this.timeScale;

		let interpolant = this._timeScaleInterpolant;

		if ( interpolant === null ) {

			interpolant = mixer._lendControlInterpolant();
			this._timeScaleInterpolant = interpolant;

		}

		const times = interpolant.parameterPositions,
			values = interpolant.sampleValues;

		times[ 0 ] = now;
		times[ 1 ] = now + duration;

		values[ 0 ] = startTimeScale / timeScale;
		values[ 1 ] = endTimeScale / timeScale;

		return this;

	},

	stopWarping: function () {

		let timeScaleInterpolant = this._timeScaleInterpolant;

		if ( timeScaleInterpolant !== null ) {

			this._timeScaleInterpolant = null;
			this._mixer._takeBackControlInterpolant( timeScaleInterpolant );

		}

		return this;

	},

	// Object Accessors

	getMixer: function () {

		return this._mixer;

	},

	getClip: function () {

		return this._clip;

	},

	getRoot: function () {

		return this._localRoot || this._mixer._root;

	},

	// Interna

	_update: function ( time, deltaTime, timeDirection, accuIndex ) {

		// called by the mixer

		if ( ! this.enabled ) {

			// call ._updateWeight() to update ._effectiveWeight

			this._updateWeight( time );
			return;

		}

		const startTime = this._startTime;

		if ( startTime !== null ) {

			// check for scheduled start of action

			const timeRunning = ( time - startTime ) * timeDirection;
			if ( timeRunning < 0 || timeDirection === 0 ) {

				return; // yet to come / don't decide when delta = 0

			}

			// start

			this._startTime = null; // unschedule
			deltaTime = timeDirection * timeRunning;

		}

		// apply time scale and advance time

		deltaTime *= this._updateTimeScale( time );
		const clipTime = this._updateTime( deltaTime );

		// note: _updateTime may disable the action resulting in
		// an effective weight of 0

		const weight = this._updateWeight( time );

		if ( weight > 0 ) {

			const interpolants = this._interpolants;
			const propertyMixers = this._propertyBindings;

			switch ( this.blendMode ) {

				case AdditiveAnimationBlendMode:

					for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {

						interpolants[ j ].evaluate( clipTime );
						propertyMixers[ j ].accumulateAdditive( weight );

					}

					break;

				case NormalAnimationBlendMode:
				default:

					for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {

						interpolants[ j ].evaluate( clipTime );
						propertyMixers[ j ].accumulate( accuIndex, weight );

					}

			}

		}

	},

	_updateWeight: function ( time ) {

		let weight = 0;

		if ( this.enabled ) {

			weight = this.weight;
			const interpolant = this._weightInterpolant;

			if ( interpolant !== null ) {

				const interpolantValue = interpolant.evaluate( time )[ 0 ];

				weight *= interpolantValue;

				if ( time > interpolant.parameterPositions[ 1 ] ) {

					this.stopFading();

					if ( interpolantValue === 0 ) {

						// faded out, disable
						this.enabled = false;

					}

				}

			}

		}

		this._effectiveWeight = weight;
		return weight;

	},

	_updateTimeScale: function ( time ) {

		let timeScale = 0;

		if ( ! this.paused ) {

			timeScale = this.timeScale;

			const interpolant = this._timeScaleInterpolant;

			if ( interpolant !== null ) {

				const interpolantValue = interpolant.evaluate( time )[ 0 ];

				timeScale *= interpolantValue;

				if ( time > interpolant.parameterPositions[ 1 ] ) {

					this.stopWarping();

					if ( timeScale === 0 ) {

						// motion has halted, pause
						this.paused = true;

					} else {

						// warp done - apply final time scale
						this.timeScale = timeScale;

					}

				}

			}

		}

		this._effectiveTimeScale = timeScale;
		return timeScale;

	},

	_updateTime: function ( deltaTime ) {

		const duration = this._clip.duration;
		const loop = this.loop;

		let time = this.time + deltaTime;
		let loopCount = this._loopCount;

		const pingPong = ( loop === LoopPingPong );

		if ( deltaTime === 0 ) {

			if ( loopCount === - 1 ) return time;

			return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;

		}

		if ( loop === LoopOnce ) {

			if ( loopCount === - 1 ) {

				// just started

				this._loopCount = 0;
				this._setEndings( true, true, false );

			}

			handle_stop: {

				if ( time >= duration ) {

					time = duration;

				} else if ( time < 0 ) {

					time = 0;

				} else {

					this.time = time;

					break handle_stop;

				}

				if ( this.clampWhenFinished ) this.paused = true;
				else this.enabled = false;

				this.time = time;

				this._mixer.dispatchEvent( {
					type: 'finished', action: this,
					direction: deltaTime < 0 ? - 1 : 1
				} );

			}

		} else { // repetitive Repeat or PingPong

			if ( loopCount === - 1 ) {

				// just started

				if ( deltaTime >= 0 ) {

					loopCount = 0;

					this._setEndings( true, this.repetitions === 0, pingPong );

				} else {

					// when looping in reverse direction, the initial
					// transition through zero counts as a repetition,
					// so leave loopCount at -1

					this._setEndings( this.repetitions === 0, true, pingPong );

				}

			}

			if ( time >= duration || time < 0 ) {

				// wrap around

				const loopDelta = Math.floor( time / duration ); // signed
				time -= duration * loopDelta;

				loopCount += Math.abs( loopDelta );

				const pending = this.repetitions - loopCount;

				if ( pending <= 0 ) {

					// have to stop (switch state, clamp time, fire event)

					if ( this.clampWhenFinished ) this.paused = true;
					else this.enabled = false;

					time = deltaTime > 0 ? duration : 0;

					this.time = time;

					this._mixer.dispatchEvent( {
						type: 'finished', action: this,
						direction: deltaTime > 0 ? 1 : - 1
					} );

				} else {

					// keep running

					if ( pending === 1 ) {

						// entering the last round

						const atStart = deltaTime < 0;
						this._setEndings( atStart, ! atStart, pingPong );

					} else {

						this._setEndings( false, false, pingPong );

					}

					this._loopCount = loopCount;

					this.time = time;

					this._mixer.dispatchEvent( {
						type: 'loop', action: this, loopDelta: loopDelta
					} );

				}

			} else {

				this.time = time;

			}

			if ( pingPong && ( loopCount & 1 ) === 1 ) {

				// invert time for the "pong round"

				return duration - time;

			}

		}

		return time;

	},

	_setEndings: function ( atStart, atEnd, pingPong ) {

		const settings = this._interpolantSettings;

		if ( pingPong ) {

			settings.endingStart = ZeroSlopeEnding;
			settings.endingEnd = ZeroSlopeEnding;

		} else {

			// assuming for LoopOnce atStart == atEnd == true

			if ( atStart ) {

				settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;

			} else {

				settings.endingStart = WrapAroundEnding;

			}

			if ( atEnd ) {

				settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;

			} else {

				settings.endingEnd 	 = WrapAroundEnding;

			}

		}

	},

	_scheduleFading: function ( duration, weightNow, weightThen ) {

		const mixer = this._mixer, now = mixer.time;
		let interpolant = this._weightInterpolant;

		if ( interpolant === null ) {

			interpolant = mixer._lendControlInterpolant();
			this._weightInterpolant = interpolant;

		}

		const times = interpolant.parameterPositions,
			values = interpolant.sampleValues;

		times[ 0 ] = now;
		values[ 0 ] = weightNow;
		times[ 1 ] = now + duration;
		values[ 1 ] = weightThen;

		return this;

	}

} );

/**
 *
 * Player for AnimationClips.
 *
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 * @author tschw
 */

function AnimationMixer( root ) {

	this._root = root;
	this._initMemoryManager();
	this._accuIndex = 0;

	this.time = 0;

	this.timeScale = 1.0;

}

AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {

	constructor: AnimationMixer,

	_bindAction: function ( action, prototypeAction ) {

		const root = action._localRoot || this._root,
			tracks = action._clip.tracks,
			nTracks = tracks.length,
			bindings = action._propertyBindings,
			interpolants = action._interpolants,
			rootUuid = root.uuid,
			bindingsByRoot = this._bindingsByRootAndName;

		let bindingsByName = bindingsByRoot[ rootUuid ];

		if ( bindingsByName === undefined ) {

			bindingsByName = {};
			bindingsByRoot[ rootUuid ] = bindingsByName;

		}

		for ( let i = 0; i !== nTracks; ++ i ) {

			const track = tracks[ i ],
				trackName = track.name;

			let binding = bindingsByName[ trackName ];

			if ( binding !== undefined ) {

				bindings[ i ] = binding;

			} else {

				binding = bindings[ i ];

				if ( binding !== undefined ) {

					// existing binding, make sure the cache knows

					if ( binding._cacheIndex === null ) {

						++ binding.referenceCount;
						this._addInactiveBinding( binding, rootUuid, trackName );

					}

					continue;

				}

				const path = prototypeAction && prototypeAction.
					_propertyBindings[ i ].binding.parsedPath;

				binding = new PropertyMixer(
					PropertyBinding.create( root, trackName, path ),
					track.ValueTypeName, track.getValueSize() );

				++ binding.referenceCount;
				this._addInactiveBinding( binding, rootUuid, trackName );

				bindings[ i ] = binding;

			}

			interpolants[ i ].resultBuffer = binding.buffer;

		}

	},

	_activateAction: function ( action ) {

		if ( ! this._isActiveAction( action ) ) {

			if ( action._cacheIndex === null ) {

				// this action has been forgotten by the cache, but the user
				// appears to be still using it -> rebind

				const rootUuid = ( action._localRoot || this._root ).uuid,
					clipUuid = action._clip.uuid,
					actionsForClip = this._actionsByClip[ clipUuid ];

				this._bindAction( action,
					actionsForClip && actionsForClip.knownActions[ 0 ] );

				this._addInactiveAction( action, clipUuid, rootUuid );

			}

			const bindings = action._propertyBindings;

			// increment reference counts / sort out state
			for ( let i = 0, n = bindings.length; i !== n; ++ i ) {

				const binding = bindings[ i ];

				if ( binding.useCount ++ === 0 ) {

					this._lendBinding( binding );
					binding.saveOriginalState();

				}

			}

			this._lendAction( action );

		}

	},

	_deactivateAction: function ( action ) {

		if ( this._isActiveAction( action ) ) {

			const bindings = action._propertyBindings;

			// decrement reference counts / sort out state
			for ( let i = 0, n = bindings.length; i !== n; ++ i ) {

				const binding = bindings[ i ];

				if ( -- binding.useCount === 0 ) {

					binding.restoreOriginalState();
					this._takeBackBinding( binding );

				}

			}

			this._takeBackAction( action );

		}

	},

	// Memory manager

	_initMemoryManager: function () {

		this._actions = []; // 'nActiveActions' followed by inactive ones
		this._nActiveActions = 0;

		this._actionsByClip = {};
		// inside:
		// {
		// 	knownActions: Array< AnimationAction > - used as prototypes
		// 	actionByRoot: AnimationAction - lookup
		// }


		this._bindings = []; // 'nActiveBindings' followed by inactive ones
		this._nActiveBindings = 0;

		this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >


		this._controlInterpolants = []; // same game as above
		this._nActiveControlInterpolants = 0;

		const scope = this;

		this.stats = {

			actions: {
				get total() {

					return scope._actions.length;

				},
				get inUse() {

					return scope._nActiveActions;

				}
			},
			bindings: {
				get total() {

					return scope._bindings.length;

				},
				get inUse() {

					return scope._nActiveBindings;

				}
			},
			controlInterpolants: {
				get total() {

					return scope._controlInterpolants.length;

				},
				get inUse() {

					return scope._nActiveControlInterpolants;

				}
			}

		};

	},

	// Memory management for AnimationAction objects

	_isActiveAction: function ( action ) {

		const index = action._cacheIndex;
		return index !== null && index < this._nActiveActions;

	},

	_addInactiveAction: function ( action, clipUuid, rootUuid ) {

		const actions = this._actions,
			actionsByClip = this._actionsByClip;

		let actionsForClip = actionsByClip[ clipUuid ];

		if ( actionsForClip === undefined ) {

			actionsForClip = {

				knownActions: [ action ],
				actionByRoot: {}

			};

			action._byClipCacheIndex = 0;

			actionsByClip[ clipUuid ] = actionsForClip;

		} else {

			const knownActions = actionsForClip.knownActions;

			action._byClipCacheIndex = knownActions.length;
			knownActions.push( action );

		}

		action._cacheIndex = actions.length;
		actions.push( action );

		actionsForClip.actionByRoot[ rootUuid ] = action;

	},

	_removeInactiveAction: function ( action ) {

		const actions = this._actions,
			lastInactiveAction = actions[ actions.length - 1 ],
			cacheIndex = action._cacheIndex;

		lastInactiveAction._cacheIndex = cacheIndex;
		actions[ cacheIndex ] = lastInactiveAction;
		actions.pop();

		action._cacheIndex = null;


		const clipUuid = action._clip.uuid,
			actionsByClip = this._actionsByClip,
			actionsForClip = actionsByClip[ clipUuid ],
			knownActionsForClip = actionsForClip.knownActions,

			lastKnownAction =
				knownActionsForClip[ knownActionsForClip.length - 1 ],

			byClipCacheIndex = action._byClipCacheIndex;

		lastKnownAction._byClipCacheIndex = byClipCacheIndex;
		knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
		knownActionsForClip.pop();

		action._byClipCacheIndex = null;


		const actionByRoot = actionsForClip.actionByRoot,
			rootUuid = ( action._localRoot || this._root ).uuid;

		delete actionByRoot[ rootUuid ];

		if ( knownActionsForClip.length === 0 ) {

			delete actionsByClip[ clipUuid ];

		}

		this._removeInactiveBindingsForAction( action );

	},

	_removeInactiveBindingsForAction: function ( action ) {

		const bindings = action._propertyBindings;

		for ( let i = 0, n = bindings.length; i !== n; ++ i ) {

			const binding = bindings[ i ];

			if ( -- binding.referenceCount === 0 ) {

				this._removeInactiveBinding( binding );

			}

		}

	},

	_lendAction: function ( action ) {

		// [ active actions |  inactive actions  ]
		// [  active actions >| inactive actions ]
		//                 s        a
		//                  <-swap->
		//                 a        s

		const actions = this._actions,
			prevIndex = action._cacheIndex,

			lastActiveIndex = this._nActiveActions ++,

			firstInactiveAction = actions[ lastActiveIndex ];

		action._cacheIndex = lastActiveIndex;
		actions[ lastActiveIndex ] = action;

		firstInactiveAction._cacheIndex = prevIndex;
		actions[ prevIndex ] = firstInactiveAction;

	},

	_takeBackAction: function ( action ) {

		// [  active actions  | inactive actions ]
		// [ active actions |< inactive actions  ]
		//        a        s
		//         <-swap->
		//        s        a

		const actions = this._actions,
			prevIndex = action._cacheIndex,

			firstInactiveIndex = -- this._nActiveActions,

			lastActiveAction = actions[ firstInactiveIndex ];

		action._cacheIndex = firstInactiveIndex;
		actions[ firstInactiveIndex ] = action;

		lastActiveAction._cacheIndex = prevIndex;
		actions[ prevIndex ] = lastActiveAction;

	},

	// Memory management for PropertyMixer objects

	_addInactiveBinding: function ( binding, rootUuid, trackName ) {

		const bindingsByRoot = this._bindingsByRootAndName,
			bindings = this._bindings;

		let bindingByName = bindingsByRoot[ rootUuid ];

		if ( bindingByName === undefined ) {

			bindingByName = {};
			bindingsByRoot[ rootUuid ] = bindingByName;

		}

		bindingByName[ trackName ] = binding;

		binding._cacheIndex = bindings.length;
		bindings.push( binding );

	},

	_removeInactiveBinding: function ( binding ) {

		const bindings = this._bindings,
			propBinding = binding.binding,
			rootUuid = propBinding.rootNode.uuid,
			trackName = propBinding.path,
			bindingsByRoot = this._bindingsByRootAndName,
			bindingByName = bindingsByRoot[ rootUuid ],

			lastInactiveBinding = bindings[ bindings.length - 1 ],
			cacheIndex = binding._cacheIndex;

		lastInactiveBinding._cacheIndex = cacheIndex;
		bindings[ cacheIndex ] = lastInactiveBinding;
		bindings.pop();

		delete bindingByName[ trackName ];

		if ( Object.keys( bindingByName ).length === 0 ) {

			delete bindingsByRoot[ rootUuid ];

		}

	},

	_lendBinding: function ( binding ) {

		const bindings = this._bindings,
			prevIndex = binding._cacheIndex,

			lastActiveIndex = this._nActiveBindings ++,

			firstInactiveBinding = bindings[ lastActiveIndex ];

		binding._cacheIndex = lastActiveIndex;
		bindings[ lastActiveIndex ] = binding;

		firstInactiveBinding._cacheIndex = prevIndex;
		bindings[ prevIndex ] = firstInactiveBinding;

	},

	_takeBackBinding: function ( binding ) {

		const bindings = this._bindings,
			prevIndex = binding._cacheIndex,

			firstInactiveIndex = -- this._nActiveBindings,

			lastActiveBinding = bindings[ firstInactiveIndex ];

		binding._cacheIndex = firstInactiveIndex;
		bindings[ firstInactiveIndex ] = binding;

		lastActiveBinding._cacheIndex = prevIndex;
		bindings[ prevIndex ] = lastActiveBinding;

	},


	// Memory management of Interpolants for weight and time scale

	_lendControlInterpolant: function () {

		const interpolants = this._controlInterpolants,
			lastActiveIndex = this._nActiveControlInterpolants ++;

		let interpolant = interpolants[ lastActiveIndex ];

		if ( interpolant === undefined ) {

			interpolant = new LinearInterpolant(
				new Float32Array( 2 ), new Float32Array( 2 ),
				1, this._controlInterpolantsResultBuffer );

			interpolant.__cacheIndex = lastActiveIndex;
			interpolants[ lastActiveIndex ] = interpolant;

		}

		return interpolant;

	},

	_takeBackControlInterpolant: function ( interpolant ) {

		const interpolants = this._controlInterpolants,
			prevIndex = interpolant.__cacheIndex,

			firstInactiveIndex = -- this._nActiveControlInterpolants,

			lastActiveInterpolant = interpolants[ firstInactiveIndex ];

		interpolant.__cacheIndex = firstInactiveIndex;
		interpolants[ firstInactiveIndex ] = interpolant;

		lastActiveInterpolant.__cacheIndex = prevIndex;
		interpolants[ prevIndex ] = lastActiveInterpolant;

	},

	_controlInterpolantsResultBuffer: new Float32Array( 1 ),

	// return an action for a clip optionally using a custom root target
	// object (this method allocates a lot of dynamic memory in case a
	// previously unknown clip/root combination is specified)
	clipAction: function ( clip, optionalRoot, blendMode ) {

		const root = optionalRoot || this._root,
			rootUuid = root.uuid;

		let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;

		const clipUuid = clipObject !== null ? clipObject.uuid : clip;

		let actionsForClip = this._actionsByClip[ clipUuid ],
			prototypeAction = null;

		if ( blendMode === undefined ) {

			if ( clipObject !== null ) {

				blendMode = clipObject.blendMode;

			} else {

				blendMode = NormalAnimationBlendMode;

			}

		}

		if ( actionsForClip !== undefined ) {

			const existingAction = actionsForClip.actionByRoot[ rootUuid ];

			if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {

				return existingAction;

			}

			// we know the clip, so we don't have to parse all
			// the bindings again but can just copy
			prototypeAction = actionsForClip.knownActions[ 0 ];

			// also, take the clip from the prototype action
			if ( clipObject === null )
				clipObject = prototypeAction._clip;

		}

		// clip must be known when specified via string
		if ( clipObject === null ) return null;

		// allocate all resources required to run it
		const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );

		this._bindAction( newAction, prototypeAction );

		// and make the action known to the memory manager
		this._addInactiveAction( newAction, clipUuid, rootUuid );

		return newAction;

	},

	// get an existing action
	existingAction: function ( clip, optionalRoot ) {

		const root = optionalRoot || this._root,
			rootUuid = root.uuid,

			clipObject = typeof clip === 'string' ?
				AnimationClip.findByName( root, clip ) : clip,

			clipUuid = clipObject ? clipObject.uuid : clip,

			actionsForClip = this._actionsByClip[ clipUuid ];

		if ( actionsForClip !== undefined ) {

			return actionsForClip.actionByRoot[ rootUuid ] || null;

		}

		return null;

	},

	// deactivates all previously scheduled actions
	stopAllAction: function () {

		const actions = this._actions,
			nActions = this._nActiveActions;

		for ( let i = nActions - 1; i >= 0; -- i ) {

			actions[ i ].stop();

		}

		return this;

	},

	// advance the time and update apply the animation
	update: function ( deltaTime ) {

		deltaTime *= this.timeScale;

		const actions = this._actions,
			nActions = this._nActiveActions,

			time = this.time += deltaTime,
			timeDirection = Math.sign( deltaTime ),

			accuIndex = this._accuIndex ^= 1;

		// run active actions

		for ( let i = 0; i !== nActions; ++ i ) {

			const action = actions[ i ];

			action._update( time, deltaTime, timeDirection, accuIndex );

		}

		// update scene graph

		const bindings = this._bindings,
			nBindings = this._nActiveBindings;

		for ( let i = 0; i !== nBindings; ++ i ) {

			bindings[ i ].apply( accuIndex );

		}

		return this;

	},

	// Allows you to seek to a specific time in an animation.
	setTime: function ( timeInSeconds ) {

		this.time = 0; // Zero out time attribute for AnimationMixer object;
		for ( let i = 0; i < this._actions.length; i ++ ) {

			this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.

		}

		return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.

	},

	// return this mixer's root target object
	getRoot: function () {

		return this._root;

	},

	// free all resources specific to a particular clip
	uncacheClip: function ( clip ) {

		const actions = this._actions,
			clipUuid = clip.uuid,
			actionsByClip = this._actionsByClip,
			actionsForClip = actionsByClip[ clipUuid ];

		if ( actionsForClip !== undefined ) {

			// note: just calling _removeInactiveAction would mess up the
			// iteration state and also require updating the state we can
			// just throw away

			const actionsToRemove = actionsForClip.knownActions;

			for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {

				const action = actionsToRemove[ i ];

				this._deactivateAction( action );

				const cacheIndex = action._cacheIndex,
					lastInactiveAction = actions[ actions.length - 1 ];

				action._cacheIndex = null;
				action._byClipCacheIndex = null;

				lastInactiveAction._cacheIndex = cacheIndex;
				actions[ cacheIndex ] = lastInactiveAction;
				actions.pop();

				this._removeInactiveBindingsForAction( action );

			}

			delete actionsByClip[ clipUuid ];

		}

	},

	// free all resources specific to a particular root target object
	uncacheRoot: function ( root ) {

		const rootUuid = root.uuid,
			actionsByClip = this._actionsByClip;

		for ( const clipUuid in actionsByClip ) {

			const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
				action = actionByRoot[ rootUuid ];

			if ( action !== undefined ) {

				this._deactivateAction( action );
				this._removeInactiveAction( action );

			}

		}

		const bindingsByRoot = this._bindingsByRootAndName,
			bindingByName = bindingsByRoot[ rootUuid ];

		if ( bindingByName !== undefined ) {

			for ( const trackName in bindingByName ) {

				const binding = bindingByName[ trackName ];
				binding.restoreOriginalState();
				this._removeInactiveBinding( binding );

			}

		}

	},

	// remove a targeted clip from the cache
	uncacheAction: function ( clip, optionalRoot ) {

		const action = this.existingAction( clip, optionalRoot );

		if ( action !== null ) {

			this._deactivateAction( action );
			this._removeInactiveAction( action );

		}

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 */

function Uniform( value ) {

	if ( typeof value === 'string' ) {

		console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
		value = arguments[ 1 ];

	}

	this.value = value;

}

Uniform.prototype.clone = function () {

	return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );

};

/**
 * @author benaadams / https://twitter.com/ben_a_adams
 */

function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {

	InterleavedBuffer.call( this, array, stride );

	this.meshPerAttribute = meshPerAttribute || 1;

}

InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {

	constructor: InstancedInterleavedBuffer,

	isInstancedInterleavedBuffer: true,

	copy: function ( source ) {

		InterleavedBuffer.prototype.copy.call( this, source );

		this.meshPerAttribute = source.meshPerAttribute;

		return this;

	},

	clone: function ( data ) {

		const ib = InterleavedBuffer.prototype.clone.call( this, data );

		ib.meshPerAttribute = this.meshPerAttribute;

		return ib;

	},

	toJSON: function ( data ) {

		const json = InterleavedBuffer.prototype.toJSON.call( this, data );

		json.isInstancedInterleavedBuffer = true;
		json.meshPerAttribute = this.meshPerAttribute;

		return json;

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author bhouston / http://clara.io/
 * @author stephomi / http://stephaneginier.com/
 */

function Raycaster( origin, direction, near, far ) {

	this.ray = new Ray( origin, direction );
	// direction is assumed to be normalized (for accurate distance calculations)

	this.near = near || 0;
	this.far = far || Infinity;
	this.camera = null;
	this.layers = new Layers();

	this.params = {
		Mesh: {},
		Line: { threshold: 1 },
		LOD: {},
		Points: { threshold: 1 },
		Sprite: {}
	};

	Object.defineProperties( this.params, {
		PointCloud: {
			get: function () {

				console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
				return this.Points;

			}
		}
	} );

}

function ascSort( a, b ) {

	return a.distance - b.distance;

}

function intersectObject( object, raycaster, intersects, recursive ) {

	if ( object.layers.test( raycaster.layers ) ) {

		object.raycast( raycaster, intersects );

	}

	if ( recursive === true ) {

		const children = object.children;

		for ( let i = 0, l = children.length; i < l; i ++ ) {

			intersectObject( children[ i ], raycaster, intersects, true );

		}

	}

}

Object.assign( Raycaster.prototype, {

	set: function ( origin, direction ) {

		// direction is assumed to be normalized (for accurate distance calculations)

		this.ray.set( origin, direction );

	},

	setFromCamera: function ( coords, camera ) {

		if ( ( camera && camera.isPerspectiveCamera ) ) {

			this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
			this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
			this.camera = camera;

		} else if ( ( camera && camera.isOrthographicCamera ) ) {

			this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
			this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
			this.camera = camera;

		} else {

			console.error( 'THREE.Raycaster: Unsupported camera type.' );

		}

	},

	intersectObject: function ( object, recursive, optionalTarget ) {

		const intersects = optionalTarget || [];

		intersectObject( object, this, intersects, recursive );

		intersects.sort( ascSort );

		return intersects;

	},

	intersectObjects: function ( objects, recursive, optionalTarget ) {

		const intersects = optionalTarget || [];

		if ( Array.isArray( objects ) === false ) {

			console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
			return intersects;

		}

		for ( let i = 0, l = objects.length; i < l; i ++ ) {

			intersectObject( objects[ i ], this, intersects, recursive );

		}

		intersects.sort( ascSort );

		return intersects;

	}

} );

/**
 * @author bhouston / http://clara.io
 * @author WestLangley / http://github.com/WestLangley
 *
 * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
 *
 * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
 * The azimuthal angle (theta) is measured from the positive z-axis.
 */

function Spherical( radius, phi, theta ) {

	this.radius = ( radius !== undefined ) ? radius : 1.0;
	this.phi = ( phi !== undefined ) ? phi : 0; // polar angle
	this.theta = ( theta !== undefined ) ? theta : 0; // azimuthal angle

	return this;

}

Object.assign( Spherical.prototype, {

	set: function ( radius, phi, theta ) {

		this.radius = radius;
		this.phi = phi;
		this.theta = theta;

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( other ) {

		this.radius = other.radius;
		this.phi = other.phi;
		this.theta = other.theta;

		return this;

	},

	// restrict phi to be betwee EPS and PI-EPS
	makeSafe: function () {

		const EPS = 0.000001;
		this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );

		return this;

	},

	setFromVector3: function ( v ) {

		return this.setFromCartesianCoords( v.x, v.y, v.z );

	},

	setFromCartesianCoords: function ( x, y, z ) {

		this.radius = Math.sqrt( x * x + y * y + z * z );

		if ( this.radius === 0 ) {

			this.theta = 0;
			this.phi = 0;

		} else {

			this.theta = Math.atan2( x, z );
			this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );

		}

		return this;

	}

} );

/**
 * @author Mugen87 / https://github.com/Mugen87
 *
 * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
 *
 */

function Cylindrical( radius, theta, y ) {

	this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
	this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
	this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane

	return this;

}

Object.assign( Cylindrical.prototype, {

	set: function ( radius, theta, y ) {

		this.radius = radius;
		this.theta = theta;
		this.y = y;

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( other ) {

		this.radius = other.radius;
		this.theta = other.theta;
		this.y = other.y;

		return this;

	},

	setFromVector3: function ( v ) {

		return this.setFromCartesianCoords( v.x, v.y, v.z );

	},

	setFromCartesianCoords: function ( x, y, z ) {

		this.radius = Math.sqrt( x * x + z * z );
		this.theta = Math.atan2( x, z );
		this.y = y;

		return this;

	}

} );

/**
 * @author bhouston / http://clara.io
 */

const _vector$7 = new Vector2();

function Box2( min, max ) {

	this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
	this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );

}

Object.assign( Box2.prototype, {

	set: function ( min, max ) {

		this.min.copy( min );
		this.max.copy( max );

		return this;

	},

	setFromPoints: function ( points ) {

		this.makeEmpty();

		for ( let i = 0, il = points.length; i < il; i ++ ) {

			this.expandByPoint( points[ i ] );

		}

		return this;

	},

	setFromCenterAndSize: function ( center, size ) {

		const halfSize = _vector$7.copy( size ).multiplyScalar( 0.5 );
		this.min.copy( center ).sub( halfSize );
		this.max.copy( center ).add( halfSize );

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( box ) {

		this.min.copy( box.min );
		this.max.copy( box.max );

		return this;

	},

	makeEmpty: function () {

		this.min.x = this.min.y = + Infinity;
		this.max.x = this.max.y = - Infinity;

		return this;

	},

	isEmpty: function () {

		// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes

		return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );

	},

	getCenter: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Box2: .getCenter() target is now required' );
			target = new Vector2();

		}

		return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );

	},

	getSize: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Box2: .getSize() target is now required' );
			target = new Vector2();

		}

		return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );

	},

	expandByPoint: function ( point ) {

		this.min.min( point );
		this.max.max( point );

		return this;

	},

	expandByVector: function ( vector ) {

		this.min.sub( vector );
		this.max.add( vector );

		return this;

	},

	expandByScalar: function ( scalar ) {

		this.min.addScalar( - scalar );
		this.max.addScalar( scalar );

		return this;

	},

	containsPoint: function ( point ) {

		return point.x < this.min.x || point.x > this.max.x ||
			point.y < this.min.y || point.y > this.max.y ? false : true;

	},

	containsBox: function ( box ) {

		return this.min.x <= box.min.x && box.max.x <= this.max.x &&
			this.min.y <= box.min.y && box.max.y <= this.max.y;

	},

	getParameter: function ( point, target ) {

		// This can potentially have a divide by zero if the box
		// has a size dimension of 0.

		if ( target === undefined ) {

			console.warn( 'THREE.Box2: .getParameter() target is now required' );
			target = new Vector2();

		}

		return target.set(
			( point.x - this.min.x ) / ( this.max.x - this.min.x ),
			( point.y - this.min.y ) / ( this.max.y - this.min.y )
		);

	},

	intersectsBox: function ( box ) {

		// using 4 splitting planes to rule out intersections

		return box.max.x < this.min.x || box.min.x > this.max.x ||
			box.max.y < this.min.y || box.min.y > this.max.y ? false : true;

	},

	clampPoint: function ( point, target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Box2: .clampPoint() target is now required' );
			target = new Vector2();

		}

		return target.copy( point ).clamp( this.min, this.max );

	},

	distanceToPoint: function ( point ) {

		const clampedPoint = _vector$7.copy( point ).clamp( this.min, this.max );
		return clampedPoint.sub( point ).length();

	},

	intersect: function ( box ) {

		this.min.max( box.min );
		this.max.min( box.max );

		return this;

	},

	union: function ( box ) {

		this.min.min( box.min );
		this.max.max( box.max );

		return this;

	},

	translate: function ( offset ) {

		this.min.add( offset );
		this.max.add( offset );

		return this;

	},

	equals: function ( box ) {

		return box.min.equals( this.min ) && box.max.equals( this.max );

	}

} );

/**
 * @author bhouston / http://clara.io
 */

const _startP = new Vector3();
const _startEnd = new Vector3();

function Line3( start, end ) {

	this.start = ( start !== undefined ) ? start : new Vector3();
	this.end = ( end !== undefined ) ? end : new Vector3();

}

Object.assign( Line3.prototype, {

	set: function ( start, end ) {

		this.start.copy( start );
		this.end.copy( end );

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	},

	copy: function ( line ) {

		this.start.copy( line.start );
		this.end.copy( line.end );

		return this;

	},

	getCenter: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Line3: .getCenter() target is now required' );
			target = new Vector3();

		}

		return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );

	},

	delta: function ( target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Line3: .delta() target is now required' );
			target = new Vector3();

		}

		return target.subVectors( this.end, this.start );

	},

	distanceSq: function () {

		return this.start.distanceToSquared( this.end );

	},

	distance: function () {

		return this.start.distanceTo( this.end );

	},

	at: function ( t, target ) {

		if ( target === undefined ) {

			console.warn( 'THREE.Line3: .at() target is now required' );
			target = new Vector3();

		}

		return this.delta( target ).multiplyScalar( t ).add( this.start );

	},

	closestPointToPointParameter: function ( point, clampToLine ) {

		_startP.subVectors( point, this.start );
		_startEnd.subVectors( this.end, this.start );

		const startEnd2 = _startEnd.dot( _startEnd );
		const startEnd_startP = _startEnd.dot( _startP );

		let t = startEnd_startP / startEnd2;

		if ( clampToLine ) {

			t = MathUtils.clamp( t, 0, 1 );

		}

		return t;

	},

	closestPointToPoint: function ( point, clampToLine, target ) {

		const t = this.closestPointToPointParameter( point, clampToLine );

		if ( target === undefined ) {

			console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
			target = new Vector3();

		}

		return this.delta( target ).multiplyScalar( t ).add( this.start );

	},

	applyMatrix4: function ( matrix ) {

		this.start.applyMatrix4( matrix );
		this.end.applyMatrix4( matrix );

		return this;

	},

	equals: function ( line ) {

		return line.start.equals( this.start ) && line.end.equals( this.end );

	}

} );

/**
 * @author alteredq / http://alteredqualia.com/
 */

function ImmediateRenderObject( material ) {

	Object3D.call( this );

	this.material = material;
	this.render = function ( /* renderCallback */ ) {};

	this.hasPositions = false;
	this.hasNormals = false;
	this.hasColors = false;
	this.hasUvs = false;

	this.positionArray = null;
	this.normalArray = null;
	this.colorArray = null;
	this.uvArray = null;

	this.count = 0;

}

ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;

ImmediateRenderObject.prototype.isImmediateRenderObject = true;

/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 * @author WestLangley / http://github.com/WestLangley
 */

const _vector$8 = new Vector3();

function SpotLightHelper( light, color ) {

	Object3D.call( this );

	this.light = light;
	this.light.updateMatrixWorld();

	this.matrix = light.matrixWorld;
	this.matrixAutoUpdate = false;

	this.color = color;

	const geometry = new BufferGeometry();

	const positions = [
		0, 0, 0, 	0, 0, 1,
		0, 0, 0, 	1, 0, 1,
		0, 0, 0,	- 1, 0, 1,
		0, 0, 0, 	0, 1, 1,
		0, 0, 0, 	0, - 1, 1
	];

	for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {

		const p1 = ( i / l ) * Math.PI * 2;
		const p2 = ( j / l ) * Math.PI * 2;

		positions.push(
			Math.cos( p1 ), Math.sin( p1 ), 1,
			Math.cos( p2 ), Math.sin( p2 ), 1
		);

	}

	geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );

	const material = new LineBasicMaterial( { fog: false, toneMapped: false } );

	this.cone = new LineSegments( geometry, material );
	this.add( this.cone );

	this.update();

}

SpotLightHelper.prototype = Object.create( Object3D.prototype );
SpotLightHelper.prototype.constructor = SpotLightHelper;

SpotLightHelper.prototype.dispose = function () {

	this.cone.geometry.dispose();
	this.cone.material.dispose();

};

SpotLightHelper.prototype.update = function () {

	this.light.updateMatrixWorld();

	const coneLength = this.light.distance ? this.light.distance : 1000;
	const coneWidth = coneLength * Math.tan( this.light.angle );

	this.cone.scale.set( coneWidth, coneWidth, coneLength );

	_vector$8.setFromMatrixPosition( this.light.target.matrixWorld );

	this.cone.lookAt( _vector$8 );

	if ( this.color !== undefined ) {

		this.cone.material.color.set( this.color );

	} else {

		this.cone.material.color.copy( this.light.color );

	}

};

/**
 * @author Sean Griffin / http://twitter.com/sgrif
 * @author Michael Guerrero / http://realitymeltdown.com
 * @author mrdoob / http://mrdoob.com/
 * @author ikerr / http://verold.com
 * @author Mugen87 / https://github.com/Mugen87
 */

const _vector$9 = new Vector3();
const _boneMatrix = new Matrix4();
const _matrixWorldInv = new Matrix4();

function getBoneList( object ) {

	const boneList = [];

	if ( object && object.isBone ) {

		boneList.push( object );

	}

	for ( let i = 0; i < object.children.length; i ++ ) {

		boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );

	}

	return boneList;

}

function SkeletonHelper( object ) {

	const bones = getBoneList( object );

	const geometry = new BufferGeometry();

	const vertices = [];
	const colors = [];

	const color1 = new Color( 0, 0, 1 );
	const color2 = new Color( 0, 1, 0 );

	for ( let i = 0; i < bones.length; i ++ ) {

		const bone = bones[ i ];

		if ( bone.parent && bone.parent.isBone ) {

			vertices.push( 0, 0, 0 );
			vertices.push( 0, 0, 0 );
			colors.push( color1.r, color1.g, color1.b );
			colors.push( color2.r, color2.g, color2.b );

		}

	}

	geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

	const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );

	LineSegments.call( this, geometry, material );

	this.type = 'SkeletonHelper';

	this.root = object;
	this.bones = bones;

	this.matrix = object.matrixWorld;
	this.matrixAutoUpdate = false;

}

SkeletonHelper.prototype = Object.create( LineSegments.prototype );
SkeletonHelper.prototype.constructor = SkeletonHelper;

SkeletonHelper.prototype.isSkeletonHelper = true;

SkeletonHelper.prototype.updateMatrixWorld = function ( force ) {

	const bones = this.bones;

	const geometry = this.geometry;
	const position = geometry.getAttribute( 'position' );

	_matrixWorldInv.getInverse( this.root.matrixWorld );

	for ( let i = 0, j = 0; i < bones.length; i ++ ) {

		const bone = bones[ i ];

		if ( bone.parent && bone.parent.isBone ) {

			_boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
			_vector$9.setFromMatrixPosition( _boneMatrix );
			position.setXYZ( j, _vector$9.x, _vector$9.y, _vector$9.z );

			_boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
			_vector$9.setFromMatrixPosition( _boneMatrix );
			position.setXYZ( j + 1, _vector$9.x, _vector$9.y, _vector$9.z );

			j += 2;

		}

	}

	geometry.getAttribute( 'position' ).needsUpdate = true;

	Object3D.prototype.updateMatrixWorld.call( this, force );

};

/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 */

function PointLightHelper( light, sphereSize, color ) {

	this.light = light;
	this.light.updateMatrixWorld();

	this.color = color;

	const geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
	const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );

	Mesh.call( this, geometry, material );

	this.type = 'PointLightHelper';

	this.matrix = this.light.matrixWorld;
	this.matrixAutoUpdate = false;

	this.update();


	/*
	const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
	const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );

	this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
	this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );

	const d = light.distance;

	if ( d === 0.0 ) {

		this.lightDistance.visible = false;

	} else {

		this.lightDistance.scale.set( d, d, d );

	}

	this.add( this.lightDistance );
	*/

}

PointLightHelper.prototype = Object.create( Mesh.prototype );
PointLightHelper.prototype.constructor = PointLightHelper;

PointLightHelper.prototype.dispose = function () {

	this.geometry.dispose();
	this.material.dispose();

};

PointLightHelper.prototype.update = function () {

	if ( this.color !== undefined ) {

		this.material.color.set( this.color );

	} else {

		this.material.color.copy( this.light.color );

	}

	/*
	const d = this.light.distance;

	if ( d === 0.0 ) {

		this.lightDistance.visible = false;

	} else {

		this.lightDistance.visible = true;
		this.lightDistance.scale.set( d, d, d );

	}
	*/

};

/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / https://github.com/Mugen87
 */

const _vector$a = new Vector3();
const _color1 = new Color();
const _color2 = new Color();

function HemisphereLightHelper( light, size, color ) {

	Object3D.call( this );

	this.light = light;
	this.light.updateMatrixWorld();

	this.matrix = light.matrixWorld;
	this.matrixAutoUpdate = false;

	this.color = color;

	const geometry = new OctahedronBufferGeometry( size );
	geometry.rotateY( Math.PI * 0.5 );

	this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
	if ( this.color === undefined ) this.material.vertexColors = true;

	const position = geometry.getAttribute( 'position' );
	const colors = new Float32Array( position.count * 3 );

	geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );

	this.add( new Mesh( geometry, this.material ) );

	this.update();

}

HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;

HemisphereLightHelper.prototype.dispose = function () {

	this.children[ 0 ].geometry.dispose();
	this.children[ 0 ].material.dispose();

};

HemisphereLightHelper.prototype.update = function () {

	const mesh = this.children[ 0 ];

	if ( this.color !== undefined ) {

		this.material.color.set( this.color );

	} else {

		const colors = mesh.geometry.getAttribute( 'color' );

		_color1.copy( this.light.color );
		_color2.copy( this.light.groundColor );

		for ( let i = 0, l = colors.count; i < l; i ++ ) {

			const color = ( i < ( l / 2 ) ) ? _color1 : _color2;

			colors.setXYZ( i, color.r, color.g, color.b );

		}

		colors.needsUpdate = true;

	}

	mesh.lookAt( _vector$a.setFromMatrixPosition( this.light.matrixWorld ).negate() );

};

/**
 * @author mrdoob / http://mrdoob.com/
 */

function GridHelper( size, divisions, color1, color2 ) {

	size = size || 10;
	divisions = divisions || 10;
	color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
	color2 = new Color( color2 !== undefined ? color2 : 0x888888 );

	const center = divisions / 2;
	const step = size / divisions;
	const halfSize = size / 2;

	const vertices = [], colors = [];

	for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {

		vertices.push( - halfSize, 0, k, halfSize, 0, k );
		vertices.push( k, 0, - halfSize, k, 0, halfSize );

		const color = i === center ? color1 : color2;

		color.toArray( colors, j ); j += 3;
		color.toArray( colors, j ); j += 3;
		color.toArray( colors, j ); j += 3;
		color.toArray( colors, j ); j += 3;

	}

	const geometry = new BufferGeometry();
	geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

	const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );

	LineSegments.call( this, geometry, material );

	this.type = 'GridHelper';

}

GridHelper.prototype = Object.assign( Object.create( LineSegments.prototype ), {

	constructor: GridHelper,

	copy: function ( source ) {

		LineSegments.prototype.copy.call( this, source );

		this.geometry.copy( source.geometry );
		this.material.copy( source.material );

		return this;

	},

	clone: function () {

		return new this.constructor().copy( this );

	}

} );

/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / http://github.com/Mugen87
 * @author Hectate / http://www.github.com/Hectate
 */

function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {

	radius = radius || 10;
	radials = radials || 16;
	circles = circles || 8;
	divisions = divisions || 64;
	color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
	color2 = new Color( color2 !== undefined ? color2 : 0x888888 );

	const vertices = [];
	const colors = [];

	// create the radials

	for ( let i = 0; i <= radials; i ++ ) {

		const v = ( i / radials ) * ( Math.PI * 2 );

		const x = Math.sin( v ) * radius;
		const z = Math.cos( v ) * radius;

		vertices.push( 0, 0, 0 );
		vertices.push( x, 0, z );

		const color = ( i & 1 ) ? color1 : color2;

		colors.push( color.r, color.g, color.b );
		colors.push( color.r, color.g, color.b );

	}

	// create the circles

	for ( let i = 0; i <= circles; i ++ ) {

		const color = ( i & 1 ) ? color1 : color2;

		const r = radius - ( radius / circles * i );

		for ( let j = 0; j < divisions; j ++ ) {

			// first vertex

			let v = ( j / divisions ) * ( Math.PI * 2 );

			let x = Math.sin( v ) * r;
			let z = Math.cos( v ) * r;

			vertices.push( x, 0, z );
			colors.push( color.r, color.g, color.b );

			// second vertex

			v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );

			x = Math.sin( v ) * r;
			z = Math.cos( v ) * r;

			vertices.push( x, 0, z );
			colors.push( color.r, color.g, color.b );

		}

	}

	const geometry = new BufferGeometry();
	geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

	const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );

	LineSegments.call( this, geometry, material );

	this.type = 'PolarGridHelper';

}

PolarGridHelper.prototype = Object.create( LineSegments.prototype );
PolarGridHelper.prototype.constructor = PolarGridHelper;

/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 * @author WestLangley / http://github.com/WestLangley
 */

const _v1$5 = new Vector3();
const _v2$3 = new Vector3();
const _v3$1 = new Vector3();

function DirectionalLightHelper( light, size, color ) {

	Object3D.call( this );

	this.light = light;
	this.light.updateMatrixWorld();

	this.matrix = light.matrixWorld;
	this.matrixAutoUpdate = false;

	this.color = color;

	if ( size === undefined ) size = 1;

	let geometry = new BufferGeometry();
	geometry.setAttribute( 'position', new Float32BufferAttribute( [
		- size, size, 0,
		size, size, 0,
		size, - size, 0,
		- size, - size, 0,
		- size, size, 0
	], 3 ) );

	const material = new LineBasicMaterial( { fog: false, toneMapped: false } );

	this.lightPlane = new Line( geometry, material );
	this.add( this.lightPlane );

	geometry = new BufferGeometry();
	geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );

	this.targetLine = new Line( geometry, material );
	this.add( this.targetLine );

	this.update();

}

DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;

DirectionalLightHelper.prototype.dispose = function () {

	this.lightPlane.geometry.dispose();
	this.lightPlane.material.dispose();
	this.targetLine.geometry.dispose();
	this.targetLine.material.dispose();

};

DirectionalLightHelper.prototype.update = function () {

	_v1$5.setFromMatrixPosition( this.light.matrixWorld );
	_v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
	_v3$1.subVectors( _v2$3, _v1$5 );

	this.lightPlane.lookAt( _v2$3 );

	if ( this.color !== undefined ) {

		this.lightPlane.material.color.set( this.color );
		this.targetLine.material.color.set( this.color );

	} else {

		this.lightPlane.material.color.copy( this.light.color );
		this.targetLine.material.color.copy( this.light.color );

	}

	this.targetLine.lookAt( _v2$3 );
	this.targetLine.scale.z = _v3$1.length();

};

/**
 * @author alteredq / http://alteredqualia.com/
 * @author Mugen87 / https://github.com/Mugen87
 *
 *	- shows frustum, line of sight and up of the camera
 *	- suitable for fast updates
 * 	- based on frustum visualization in lightgl.js shadowmap example
 *		http://evanw.github.com/lightgl.js/tests/shadowmap.html
 */

const _vector$b = new Vector3();
const _camera = new Camera();

function CameraHelper( camera ) {

	const geometry = new BufferGeometry();
	const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );

	const vertices = [];
	const colors = [];

	const pointMap = {};

	// colors

	const colorFrustum = new Color( 0xffaa00 );
	const colorCone = new Color( 0xff0000 );
	const colorUp = new Color( 0x00aaff );
	const colorTarget = new Color( 0xffffff );
	const colorCross = new Color( 0x333333 );

	// near

	addLine( 'n1', 'n2', colorFrustum );
	addLine( 'n2', 'n4', colorFrustum );
	addLine( 'n4', 'n3', colorFrustum );
	addLine( 'n3', 'n1', colorFrustum );

	// far

	addLine( 'f1', 'f2', colorFrustum );
	addLine( 'f2', 'f4', colorFrustum );
	addLine( 'f4', 'f3', colorFrustum );
	addLine( 'f3', 'f1', colorFrustum );

	// sides

	addLine( 'n1', 'f1', colorFrustum );
	addLine( 'n2', 'f2', colorFrustum );
	addLine( 'n3', 'f3', colorFrustum );
	addLine( 'n4', 'f4', colorFrustum );

	// cone

	addLine( 'p', 'n1', colorCone );
	addLine( 'p', 'n2', colorCone );
	addLine( 'p', 'n3', colorCone );
	addLine( 'p', 'n4', colorCone );

	// up

	addLine( 'u1', 'u2', colorUp );
	addLine( 'u2', 'u3', colorUp );
	addLine( 'u3', 'u1', colorUp );

	// target

	addLine( 'c', 't', colorTarget );
	addLine( 'p', 'c', colorCross );

	// cross

	addLine( 'cn1', 'cn2', colorCross );
	addLine( 'cn3', 'cn4', colorCross );

	addLine( 'cf1', 'cf2', colorCross );
	addLine( 'cf3', 'cf4', colorCross );

	function addLine( a, b, color ) {

		addPoint( a, color );
		addPoint( b, color );

	}

	function addPoint( id, color ) {

		vertices.push( 0, 0, 0 );
		colors.push( color.r, color.g, color.b );

		if ( pointMap[ id ] === undefined ) {

			pointMap[ id ] = [];

		}

		pointMap[ id ].push( ( vertices.length / 3 ) - 1 );

	}

	geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

	LineSegments.call( this, geometry, material );

	this.type = 'CameraHelper';

	this.camera = camera;
	if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();

	this.matrix = camera.matrixWorld;
	this.matrixAutoUpdate = false;

	this.pointMap = pointMap;

	this.update();

}

CameraHelper.prototype = Object.create( LineSegments.prototype );
CameraHelper.prototype.constructor = CameraHelper;

CameraHelper.prototype.update = function () {

	const geometry = this.geometry;
	const pointMap = this.pointMap;

	const w = 1, h = 1;

	// we need just camera projection matrix inverse
	// world matrix must be identity

	_camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );

	// center / target

	setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
	setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );

	// near

	setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
	setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
	setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
	setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );

	// far

	setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
	setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
	setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
	setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );

	// up

	setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
	setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
	setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );

	// cross

	setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
	setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
	setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
	setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );

	setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
	setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
	setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
	setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );

	geometry.getAttribute( 'position' ).needsUpdate = true;

};

function setPoint( point, pointMap, geometry, camera, x, y, z ) {

	_vector$b.set( x, y, z ).unproject( camera );

	const points = pointMap[ point ];

	if ( points !== undefined ) {

		const position = geometry.getAttribute( 'position' );

		for ( let i = 0, l = points.length; i < l; i ++ ) {

			position.setXYZ( points[ i ], _vector$b.x, _vector$b.y, _vector$b.z );

		}

	}

}

/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / http://github.com/Mugen87
 */

const _box$3 = new Box3();

function BoxHelper( object, color ) {

	this.object = object;

	if ( color === undefined ) color = 0xffff00;

	const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
	const positions = new Float32Array( 8 * 3 );

	const geometry = new BufferGeometry();
	geometry.setIndex( new BufferAttribute( indices, 1 ) );
	geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );

	LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );

	this.type = 'BoxHelper';

	this.matrixAutoUpdate = false;

	this.update();

}

BoxHelper.prototype = Object.create( LineSegments.prototype );
BoxHelper.prototype.constructor = BoxHelper;

BoxHelper.prototype.update = function ( object ) {

	if ( object !== undefined ) {

		console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );

	}

	if ( this.object !== undefined ) {

		_box$3.setFromObject( this.object );

	}

	if ( _box$3.isEmpty() ) return;

	const min = _box$3.min;
	const max = _box$3.max;

	/*
	  5____4
	1/___0/|
	| 6__|_7
	2/___3/

	0: max.x, max.y, max.z
	1: min.x, max.y, max.z
	2: min.x, min.y, max.z
	3: max.x, min.y, max.z
	4: max.x, max.y, min.z
	5: min.x, max.y, min.z
	6: min.x, min.y, min.z
	7: max.x, min.y, min.z
	*/

	const position = this.geometry.attributes.position;
	const array = position.array;

	array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
	array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
	array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
	array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
	array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
	array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
	array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
	array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;

	position.needsUpdate = true;

	this.geometry.computeBoundingSphere();


};

BoxHelper.prototype.setFromObject = function ( object ) {

	this.object = object;
	this.update();

	return this;

};

BoxHelper.prototype.copy = function ( source ) {

	LineSegments.prototype.copy.call( this, source );

	this.object = source.object;

	return this;

};

BoxHelper.prototype.clone = function () {

	return new this.constructor().copy( this );

};

/**
 * @author WestLangley / http://github.com/WestLangley
 */

function Box3Helper( box, color ) {

	this.type = 'Box3Helper';

	this.box = box;

	color = color || 0xffff00;

	const indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );

	const positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];

	const geometry = new BufferGeometry();

	geometry.setIndex( new BufferAttribute( indices, 1 ) );

	geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );

	LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );

	this.type = 'Box3Helper';

	this.geometry.computeBoundingSphere();

}

Box3Helper.prototype = Object.create( LineSegments.prototype );
Box3Helper.prototype.constructor = Box3Helper;

Box3Helper.prototype.updateMatrixWorld = function ( force ) {

	const box = this.box;

	if ( box.isEmpty() ) return;

	box.getCenter( this.position );

	box.getSize( this.scale );

	this.scale.multiplyScalar( 0.5 );

	Object3D.prototype.updateMatrixWorld.call( this, force );

};

/**
 * @author WestLangley / http://github.com/WestLangley
 */

function PlaneHelper( plane, size, hex ) {

	this.plane = plane;

	this.size = ( size === undefined ) ? 1 : size;

	const color = ( hex !== undefined ) ? hex : 0xffff00;

	const positions = [ 1, - 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0 ];

	const geometry = new BufferGeometry();
	geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
	geometry.computeBoundingSphere();

	Line.call( this, geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );

	this.type = 'PlaneHelper';

	//

	const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];

	const geometry2 = new BufferGeometry();
	geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
	geometry2.computeBoundingSphere();

	this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );

}

PlaneHelper.prototype = Object.create( Line.prototype );
PlaneHelper.prototype.constructor = PlaneHelper;

PlaneHelper.prototype.updateMatrixWorld = function ( force ) {

	let scale = - this.plane.constant;

	if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter

	this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );

	this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here

	this.lookAt( this.plane.normal );

	Object3D.prototype.updateMatrixWorld.call( this, force );

};

/**
 * @author WestLangley / http://github.com/WestLangley
 * @author zz85 / http://github.com/zz85
 * @author bhouston / http://clara.io
 *
 * Creates an arrow for visualizing directions
 *
 * Parameters:
 *  dir - Vector3
 *  origin - Vector3
 *  length - Number
 *  color - color in hex value
 *  headLength - Number
 *  headWidth - Number
 */

const _axis = new Vector3();
let _lineGeometry, _coneGeometry;

function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {

	// dir is assumed to be normalized

	Object3D.call( this );

	this.type = 'ArrowHelper';

	if ( dir === undefined ) dir = new Vector3( 0, 0, 1 );
	if ( origin === undefined ) origin = new Vector3( 0, 0, 0 );
	if ( length === undefined ) length = 1;
	if ( color === undefined ) color = 0xffff00;
	if ( headLength === undefined ) headLength = 0.2 * length;
	if ( headWidth === undefined ) headWidth = 0.2 * headLength;

	if ( _lineGeometry === undefined ) {

		_lineGeometry = new BufferGeometry();
		_lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );

		_coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
		_coneGeometry.translate( 0, - 0.5, 0 );

	}

	this.position.copy( origin );

	this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
	this.line.matrixAutoUpdate = false;
	this.add( this.line );

	this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
	this.cone.matrixAutoUpdate = false;
	this.add( this.cone );

	this.setDirection( dir );
	this.setLength( length, headLength, headWidth );

}

ArrowHelper.prototype = Object.create( Object3D.prototype );
ArrowHelper.prototype.constructor = ArrowHelper;

ArrowHelper.prototype.setDirection = function ( dir ) {

	// dir is assumed to be normalized

	if ( dir.y > 0.99999 ) {

		this.quaternion.set( 0, 0, 0, 1 );

	} else if ( dir.y < - 0.99999 ) {

		this.quaternion.set( 1, 0, 0, 0 );

	} else {

		_axis.set( dir.z, 0, - dir.x ).normalize();

		const radians = Math.acos( dir.y );

		this.quaternion.setFromAxisAngle( _axis, radians );

	}

};

ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {

	if ( headLength === undefined ) headLength = 0.2 * length;
	if ( headWidth === undefined ) headWidth = 0.2 * headLength;

	this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
	this.line.updateMatrix();

	this.cone.scale.set( headWidth, headLength, headWidth );
	this.cone.position.y = length;
	this.cone.updateMatrix();

};

ArrowHelper.prototype.setColor = function ( color ) {

	this.line.material.color.set( color );
	this.cone.material.color.set( color );

};

ArrowHelper.prototype.copy = function ( source ) {

	Object3D.prototype.copy.call( this, source, false );

	this.line.copy( source.line );
	this.cone.copy( source.cone );

	return this;

};

ArrowHelper.prototype.clone = function () {

	return new this.constructor().copy( this );

};

/**
 * @author sroucheray / http://sroucheray.org/
 * @author mrdoob / http://mrdoob.com/
 */

function AxesHelper( size ) {

	size = size || 1;

	const vertices = [
		0, 0, 0,	size, 0, 0,
		0, 0, 0,	0, size, 0,
		0, 0, 0,	0, 0, size
	];

	const colors = [
		1, 0, 0,	1, 0.6, 0,
		0, 1, 0,	0.6, 1, 0,
		0, 0, 1,	0, 0.6, 1
	];

	const geometry = new BufferGeometry();
	geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
	geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );

	const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );

	LineSegments.call( this, geometry, material );

	this.type = 'AxesHelper';

}

AxesHelper.prototype = Object.create( LineSegments.prototype );
AxesHelper.prototype.constructor = AxesHelper;

/**
 * @author Emmett Lalish / elalish
 *
 * This class generates a Prefiltered, Mipmapped Radiance Environment Map
 * (PMREM) from a cubeMap environment texture. This allows different levels of
 * blur to be quickly accessed based on material roughness. It is packed into a
 * special CubeUV format that allows us to perform custom interpolation so that
 * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
 * chain, it only goes down to the LOD_MIN level (above), and then creates extra
 * even more filtered 'mips' at the same LOD_MIN resolution, associated with
 * higher roughness levels. In this way we maintain resolution to smoothly
 * interpolate diffuse lighting while limiting sampling computation.
 */

const LOD_MIN = 4;
const LOD_MAX = 8;
const SIZE_MAX = Math.pow( 2, LOD_MAX );

// The standard deviations (radians) associated with the extra mips. These are
// chosen to approximate a Trowbridge-Reitz distribution function times the
// geometric shadowing function. These sigma values squared must match the
// variance #defines in cube_uv_reflection_fragment.glsl.js.
const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];

const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;

// The maximum length of the blur for loop. Smaller sigmas will use fewer
// samples and exit early, but not recompile the shader.
const MAX_SAMPLES = 20;

const ENCODINGS = {
	[ LinearEncoding ]: 0,
	[ sRGBEncoding ]: 1,
	[ RGBEEncoding ]: 2,
	[ RGBM7Encoding ]: 3,
	[ RGBM16Encoding ]: 4,
	[ RGBDEncoding ]: 5,
	[ GammaEncoding ]: 6
};

const _flatCamera = new OrthographicCamera();
const { _lodPlanes, _sizeLods, _sigmas } = _createPlanes();
let _oldTarget = null;

// Golden Ratio
const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
const INV_PHI = 1 / PHI;

// Vertices of a dodecahedron (except the opposites, which represent the
// same axis), used as axis directions evenly spread on a sphere.
const _axisDirections = [
	new Vector3( 1, 1, 1 ),
	new Vector3( - 1, 1, 1 ),
	new Vector3( 1, 1, - 1 ),
	new Vector3( - 1, 1, - 1 ),
	new Vector3( 0, PHI, INV_PHI ),
	new Vector3( 0, PHI, - INV_PHI ),
	new Vector3( INV_PHI, 0, PHI ),
	new Vector3( - INV_PHI, 0, PHI ),
	new Vector3( PHI, INV_PHI, 0 ),
	new Vector3( - PHI, INV_PHI, 0 ) ];

function PMREMGenerator( renderer ) {

	this._renderer = renderer;
	this._pingPongRenderTarget = null;

	this._blurMaterial = _getBlurShader( MAX_SAMPLES );
	this._equirectShader = null;
	this._cubemapShader = null;

	this._compileMaterial( this._blurMaterial );

}

PMREMGenerator.prototype = {

	constructor: PMREMGenerator,

	/**
	 * Generates a PMREM from a supplied Scene, which can be faster than using an
	 * image if networking bandwidth is low. Optional sigma specifies a blur radius
	 * in radians to be applied to the scene before PMREM generation. Optional near
	 * and far planes ensure the scene is rendered in its entirety (the cubeCamera
	 * is placed at the origin).
	 */
	fromScene: function ( scene, sigma = 0, near = 0.1, far = 100 ) {

		_oldTarget = this._renderer.getRenderTarget();
		const cubeUVRenderTarget = this._allocateTargets();

		this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
		if ( sigma > 0 ) {

			this._blur( cubeUVRenderTarget, 0, 0, sigma );

		}

		this._applyPMREM( cubeUVRenderTarget );
		this._cleanup( cubeUVRenderTarget );

		return cubeUVRenderTarget;

	},

	/**
	 * Generates a PMREM from an equirectangular texture, which can be either LDR
	 * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
	 * as this matches best with the 256 x 256 cubemap output.
	 */
	fromEquirectangular: function ( equirectangular ) {

		return this._fromTexture( equirectangular );

	},

	/**
	 * Generates a PMREM from an cubemap texture, which can be either LDR
	 * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
	 * as this matches best with the 256 x 256 cubemap output.
	 */
	fromCubemap: function ( cubemap ) {

		return this._fromTexture( cubemap );

	},

	/**
	 * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
	 * your texture's network fetch for increased concurrency.
	 */
	compileCubemapShader: function () {

		if ( this._cubemapShader === null ) {

			this._cubemapShader = _getCubemapShader();
			this._compileMaterial( this._cubemapShader );

		}

	},

	/**
	 * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
	 * your texture's network fetch for increased concurrency.
	 */
	compileEquirectangularShader: function () {

		if ( this._equirectShader === null ) {

			this._equirectShader = _getEquirectShader();
			this._compileMaterial( this._equirectShader );

		}

	},

	/**
	 * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
	 * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
	 * one of them will cause any others to also become unusable.
	 */
	dispose: function () {

		this._blurMaterial.dispose();

		if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
		if ( this._equirectShader !== null ) this._equirectShader.dispose();

		for ( let i = 0; i < _lodPlanes.length; i ++ ) {

			_lodPlanes[ i ].dispose();

		}

	},

	// private interface

	_cleanup: function ( outputTarget ) {

		this._pingPongRenderTarget.dispose();
		this._renderer.setRenderTarget( _oldTarget );
		outputTarget.scissorTest = false;
		_setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );

	},

	_fromTexture: function ( texture ) {

		_oldTarget = this._renderer.getRenderTarget();
		const cubeUVRenderTarget = this._allocateTargets( texture );
		this._textureToCubeUV( texture, cubeUVRenderTarget );
		this._applyPMREM( cubeUVRenderTarget );
		this._cleanup( cubeUVRenderTarget );

		return cubeUVRenderTarget;

	},

	_allocateTargets: function ( texture ) { // warning: null texture is valid

		const params = {
			magFilter: NearestFilter,
			minFilter: NearestFilter,
			generateMipmaps: false,
			type: UnsignedByteType,
			format: RGBEFormat,
			encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
			depthBuffer: false,
			stencilBuffer: false
		};

		const cubeUVRenderTarget = _createRenderTarget( params );
		cubeUVRenderTarget.depthBuffer = texture ? false : true;
		this._pingPongRenderTarget = _createRenderTarget( params );
		return cubeUVRenderTarget;

	},

	_compileMaterial: function ( material ) {

		const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
		this._renderer.compile( tmpMesh, _flatCamera );

	},

	_sceneToCubeUV: function ( scene, near, far, cubeUVRenderTarget ) {

		const fov = 90;
		const aspect = 1;
		const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
		const upSign = [ 1, - 1, 1, 1, 1, 1 ];
		const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
		const renderer = this._renderer;

		const outputEncoding = renderer.outputEncoding;
		const toneMapping = renderer.toneMapping;
		const clearColor = renderer.getClearColor();
		const clearAlpha = renderer.getClearAlpha();

		renderer.toneMapping = NoToneMapping;
		renderer.outputEncoding = LinearEncoding;

		let background = scene.background;
		if ( background && background.isColor ) {

			background.convertSRGBToLinear();
			// Convert linear to RGBE
			const maxComponent = Math.max( background.r, background.g, background.b );
			const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
			background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
			const alpha = ( fExp + 128.0 ) / 255.0;
			renderer.setClearColor( background, alpha );
			scene.background = null;

		}

		for ( let i = 0; i < 6; i ++ ) {

			const col = i % 3;
			if ( col == 0 ) {

				cubeCamera.up.set( 0, upSign[ i ], 0 );
				cubeCamera.lookAt( forwardSign[ i ], 0, 0 );

			} else if ( col == 1 ) {

				cubeCamera.up.set( 0, 0, upSign[ i ] );
				cubeCamera.lookAt( 0, forwardSign[ i ], 0 );

			} else {

				cubeCamera.up.set( 0, upSign[ i ], 0 );
				cubeCamera.lookAt( 0, 0, forwardSign[ i ] );

			}

			_setViewport( cubeUVRenderTarget,
				col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
			renderer.setRenderTarget( cubeUVRenderTarget );
			renderer.render( scene, cubeCamera );

		}

		renderer.toneMapping = toneMapping;
		renderer.outputEncoding = outputEncoding;
		renderer.setClearColor( clearColor, clearAlpha );

	},

	_textureToCubeUV: function ( texture, cubeUVRenderTarget ) {

		const renderer = this._renderer;

		if ( texture.isCubeTexture ) {

			if ( this._cubemapShader == null ) {

				this._cubemapShader = _getCubemapShader();

			}

		} else {

			if ( this._equirectShader == null ) {

				this._equirectShader = _getEquirectShader();

			}

		}

		const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
		const mesh = new Mesh( _lodPlanes[ 0 ], material );

		const uniforms = material.uniforms;

		uniforms[ 'envMap' ].value = texture;

		if ( ! texture.isCubeTexture ) {

			uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );

		}

		uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
		uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];

		_setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );

		renderer.setRenderTarget( cubeUVRenderTarget );
		renderer.render( mesh, _flatCamera );

	},

	_applyPMREM: function ( cubeUVRenderTarget ) {

		const renderer = this._renderer;
		const autoClear = renderer.autoClear;
		renderer.autoClear = false;

		for ( let i = 1; i < TOTAL_LODS; i ++ ) {

			const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );

			const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];

			this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );

		}

		renderer.autoClear = autoClear;

	},

	/**
	 * This is a two-pass Gaussian blur for a cubemap. Normally this is done
	 * vertically and horizontally, but this breaks down on a cube. Here we apply
	 * the blur latitudinally (around the poles), and then longitudinally (towards
	 * the poles) to approximate the orthogonally-separable blur. It is least
	 * accurate at the poles, but still does a decent job.
	 */
	_blur: function ( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {

		const pingPongRenderTarget = this._pingPongRenderTarget;

		this._halfBlur(
			cubeUVRenderTarget,
			pingPongRenderTarget,
			lodIn,
			lodOut,
			sigma,
			'latitudinal',
			poleAxis );

		this._halfBlur(
			pingPongRenderTarget,
			cubeUVRenderTarget,
			lodOut,
			lodOut,
			sigma,
			'longitudinal',
			poleAxis );

	},

	_halfBlur: function ( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {

		const renderer = this._renderer;
		const blurMaterial = this._blurMaterial;

		if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {

			console.error(
				'blur direction must be either latitudinal or longitudinal!' );

		}

		// Number of standard deviations at which to cut off the discrete approximation.
		const STANDARD_DEVIATIONS = 3;

		const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
		const blurUniforms = blurMaterial.uniforms;

		const pixels = _sizeLods[ lodIn ] - 1;
		const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
		const sigmaPixels = sigmaRadians / radiansPerPixel;
		const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;

		if ( samples > MAX_SAMPLES ) {

			console.warn( `sigmaRadians, ${
				sigmaRadians}, is too large and will clip, as it requested ${
				samples} samples when the maximum is set to ${MAX_SAMPLES}` );

		}

		const weights = [];
		let sum = 0;

		for ( let i = 0; i < MAX_SAMPLES; ++ i ) {

			const x = i / sigmaPixels;
			const weight = Math.exp( - x * x / 2 );
			weights.push( weight );

			if ( i == 0 ) {

				sum += weight;

			} else if ( i < samples ) {

				sum += 2 * weight;

			}

		}

		for ( let i = 0; i < weights.length; i ++ ) {

			weights[ i ] = weights[ i ] / sum;

		}

		blurUniforms[ 'envMap' ].value = targetIn.texture;
		blurUniforms[ 'samples' ].value = samples;
		blurUniforms[ 'weights' ].value = weights;
		blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';

		if ( poleAxis ) {

			blurUniforms[ 'poleAxis' ].value = poleAxis;

		}

		blurUniforms[ 'dTheta' ].value = radiansPerPixel;
		blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
		blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
		blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];

		const outputSize = _sizeLods[ lodOut ];
		const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
		const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );

		_setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
		renderer.setRenderTarget( targetOut );
		renderer.render( blurMesh, _flatCamera );

	}

};

function _isLDR( texture ) {

	if ( texture === undefined || texture.type !== UnsignedByteType ) return false;

	return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;

}

function _createPlanes() {

	const _lodPlanes = [];
	const _sizeLods = [];
	const _sigmas = [];

	let lod = LOD_MAX;

	for ( let i = 0; i < TOTAL_LODS; i ++ ) {

		const sizeLod = Math.pow( 2, lod );
		_sizeLods.push( sizeLod );
		let sigma = 1.0 / sizeLod;

		if ( i > LOD_MAX - LOD_MIN ) {

			sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];

		} else if ( i == 0 ) {

			sigma = 0;

		}

		_sigmas.push( sigma );

		const texelSize = 1.0 / ( sizeLod - 1 );
		const min = - texelSize / 2;
		const max = 1 + texelSize / 2;
		const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];

		const cubeFaces = 6;
		const vertices = 6;
		const positionSize = 3;
		const uvSize = 2;
		const faceIndexSize = 1;

		const position = new Float32Array( positionSize * vertices * cubeFaces );
		const uv = new Float32Array( uvSize * vertices * cubeFaces );
		const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );

		for ( let face = 0; face < cubeFaces; face ++ ) {

			const x = ( face % 3 ) * 2 / 3 - 1;
			const y = face > 2 ? 0 : - 1;
			const coordinates = [
				x, y, 0,
				x + 2 / 3, y, 0,
				x + 2 / 3, y + 1, 0,
				x, y, 0,
				x + 2 / 3, y + 1, 0,
				x, y + 1, 0
			];
			position.set( coordinates, positionSize * vertices * face );
			uv.set( uv1, uvSize * vertices * face );
			const fill = [ face, face, face, face, face, face ];
			faceIndex.set( fill, faceIndexSize * vertices * face );

		}

		const planes = new BufferGeometry();
		planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
		planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
		planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
		_lodPlanes.push( planes );

		if ( lod > LOD_MIN ) {

			lod --;

		}

	}

	return { _lodPlanes, _sizeLods, _sigmas };

}

function _createRenderTarget( params ) {

	const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
	cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
	cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
	cubeUVRenderTarget.scissorTest = true;
	return cubeUVRenderTarget;

}

function _setViewport( target, x, y, width, height ) {

	target.viewport.set( x, y, width, height );
	target.scissor.set( x, y, width, height );

}

function _getBlurShader( maxSamples ) {

	const weights = new Float32Array( maxSamples );
	const poleAxis = new Vector3( 0, 1, 0 );
	const shaderMaterial = new RawShaderMaterial( {

		name: 'SphericalGaussianBlur',

		defines: { 'n': maxSamples },

		uniforms: {
			'envMap': { value: null },
			'samples': { value: 1 },
			'weights': { value: weights },
			'latitudinal': { value: false },
			'dTheta': { value: 0 },
			'mipInt': { value: 0 },
			'poleAxis': { value: poleAxis },
			'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
			'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
		},

		vertexShader: _getCommonVertexShader(),

		fragmentShader: `
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform int samples;
uniform float weights[n];
uniform bool latitudinal;
uniform float dTheta;
uniform float mipInt;
uniform vec3 poleAxis;

${_getEncodings()}

#define ENVMAP_TYPE_CUBE_UV
#include <cube_uv_reflection_fragment>

vec3 getSample(float theta, vec3 axis) {
	float cosTheta = cos(theta);
	// Rodrigues' axis-angle rotation
	vec3 sampleDirection = vOutputDirection * cosTheta
		+ cross(axis, vOutputDirection) * sin(theta)
		+ axis * dot(axis, vOutputDirection) * (1.0 - cosTheta);
	return bilinearCubeUV(envMap, sampleDirection, mipInt);
}

void main() {
	vec3 axis = latitudinal ? poleAxis : cross(poleAxis, vOutputDirection);
	if (all(equal(axis, vec3(0.0))))
		axis = vec3(vOutputDirection.z, 0.0, - vOutputDirection.x);
	axis = normalize(axis);
	gl_FragColor = vec4(0.0);
	gl_FragColor.rgb += weights[0] * getSample(0.0, axis);
	for (int i = 1; i < n; i++) {
		if (i >= samples)
			break;
		float theta = dTheta * float(i);
		gl_FragColor.rgb += weights[i] * getSample(-1.0 * theta, axis);
		gl_FragColor.rgb += weights[i] * getSample(theta, axis);
	}
	gl_FragColor = linearToOutputTexel(gl_FragColor);
}
		`,

		blending: NoBlending,
		depthTest: false,
		depthWrite: false

	} );

	return shaderMaterial;

}

function _getEquirectShader() {

	const texelSize = new Vector2( 1, 1 );
	const shaderMaterial = new RawShaderMaterial( {

		name: 'EquirectangularToCubeUV',

		uniforms: {
			'envMap': { value: null },
			'texelSize': { value: texelSize },
			'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
			'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
		},

		vertexShader: _getCommonVertexShader(),

		fragmentShader: `
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform sampler2D envMap;
uniform vec2 texelSize;

${_getEncodings()}

#include <common>

void main() {
	gl_FragColor = vec4(0.0);
	vec3 outputDirection = normalize(vOutputDirection);
	vec2 uv = equirectUv( outputDirection );
	vec2 f = fract(uv / texelSize - 0.5);
	uv -= f * texelSize;
	vec3 tl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
	uv.x += texelSize.x;
	vec3 tr = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
	uv.y += texelSize.y;
	vec3 br = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
	uv.x -= texelSize.x;
	vec3 bl = envMapTexelToLinear(texture2D(envMap, uv)).rgb;
	vec3 tm = mix(tl, tr, f.x);
	vec3 bm = mix(bl, br, f.x);
	gl_FragColor.rgb = mix(tm, bm, f.y);
	gl_FragColor = linearToOutputTexel(gl_FragColor);
}
		`,

		blending: NoBlending,
		depthTest: false,
		depthWrite: false

	} );

	return shaderMaterial;

}

function _getCubemapShader() {

	const shaderMaterial = new RawShaderMaterial( {

		name: 'CubemapToCubeUV',

		uniforms: {
			'envMap': { value: null },
			'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
			'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
		},

		vertexShader: _getCommonVertexShader(),

		fragmentShader: `
precision mediump float;
precision mediump int;
varying vec3 vOutputDirection;
uniform samplerCube envMap;

${_getEncodings()}

void main() {
	gl_FragColor = vec4(0.0);
	gl_FragColor.rgb = envMapTexelToLinear(textureCube(envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ))).rgb;
	gl_FragColor = linearToOutputTexel(gl_FragColor);
}
		`,

		blending: NoBlending,
		depthTest: false,
		depthWrite: false

	} );

	return shaderMaterial;

}

function _getCommonVertexShader() {

	return `
precision mediump float;
precision mediump int;
attribute vec3 position;
attribute vec2 uv;
attribute float faceIndex;
varying vec3 vOutputDirection;

// RH coordinate system; PMREM face-indexing convention
vec3 getDirection(vec2 uv, float face) {
	uv = 2.0 * uv - 1.0;
	vec3 direction = vec3(uv, 1.0);
	if (face == 0.0) {
		direction = direction.zyx; // ( 1, v, u ) pos x
	} else if (face == 1.0) {
		direction = direction.xzy;
		direction.xz *= -1.0; // ( -u, 1, -v ) pos y
	} else if (face == 2.0) {
		direction.x *= -1.0; // ( -u, v, 1 ) pos z
	} else if (face == 3.0) {
		direction = direction.zyx;
		direction.xz *= -1.0; // ( -1, v, -u ) neg x
	} else if (face == 4.0) {
		direction = direction.xzy;
		direction.xy *= -1.0; // ( -u, -1, v ) neg y
	} else if (face == 5.0) {
		direction.z *= -1.0; // ( u, v, -1 ) neg z
	}
	return direction;
}

void main() {
	vOutputDirection = getDirection(uv, faceIndex);
	gl_Position = vec4( position, 1.0 );
}
	`;

}

function _getEncodings() {

	return `
uniform int inputEncoding;
uniform int outputEncoding;

#include <encodings_pars_fragment>

vec4 inputTexelToLinear(vec4 value){
	if(inputEncoding == 0){
		return value;
	}else if(inputEncoding == 1){
		return sRGBToLinear(value);
	}else if(inputEncoding == 2){
		return RGBEToLinear(value);
	}else if(inputEncoding == 3){
		return RGBMToLinear(value, 7.0);
	}else if(inputEncoding == 4){
		return RGBMToLinear(value, 16.0);
	}else if(inputEncoding == 5){
		return RGBDToLinear(value, 256.0);
	}else{
		return GammaToLinear(value, 2.2);
	}
}

vec4 linearToOutputTexel(vec4 value){
	if(outputEncoding == 0){
		return value;
	}else if(outputEncoding == 1){
		return LinearTosRGB(value);
	}else if(outputEncoding == 2){
		return LinearToRGBE(value);
	}else if(outputEncoding == 3){
		return LinearToRGBM(value, 7.0);
	}else if(outputEncoding == 4){
		return LinearToRGBM(value, 16.0);
	}else if(outputEncoding == 5){
		return LinearToRGBD(value, 256.0);
	}else{
		return LinearToGamma(value, 2.2);
	}
}

vec4 envMapTexelToLinear(vec4 color) {
	return inputTexelToLinear(color);
}
	`;

}

/**
 * @author mrdoob / http://mrdoob.com/
 */

function Face4( a, b, c, d, normal, color, materialIndex ) {

	console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
	return new Face3( a, b, c, normal, color, materialIndex );

}

const LineStrip = 0;
const LinePieces = 1;
const NoColors = 0;
const FaceColors = 1;
const VertexColors = 2;

function MeshFaceMaterial( materials ) {

	console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
	return materials;

}

function MultiMaterial( materials ) {

	if ( materials === undefined ) materials = [];

	console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
	materials.isMultiMaterial = true;
	materials.materials = materials;
	materials.clone = function () {

		return materials.slice();

	};

	return materials;

}

function PointCloud( geometry, material ) {

	console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
	return new Points( geometry, material );

}

function Particle( material ) {

	console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
	return new Sprite( material );

}

function ParticleSystem( geometry, material ) {

	console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
	return new Points( geometry, material );

}

function PointCloudMaterial( parameters ) {

	console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
	return new PointsMaterial( parameters );

}

function ParticleBasicMaterial( parameters ) {

	console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
	return new PointsMaterial( parameters );

}

function ParticleSystemMaterial( parameters ) {

	console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
	return new PointsMaterial( parameters );

}

function Vertex( x, y, z ) {

	console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
	return new Vector3( x, y, z );

}

//

function DynamicBufferAttribute( array, itemSize ) {

	console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
	return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );

}

function Int8Attribute( array, itemSize ) {

	console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
	return new Int8BufferAttribute( array, itemSize );

}

function Uint8Attribute( array, itemSize ) {

	console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
	return new Uint8BufferAttribute( array, itemSize );

}

function Uint8ClampedAttribute( array, itemSize ) {

	console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
	return new Uint8ClampedBufferAttribute( array, itemSize );

}

function Int16Attribute( array, itemSize ) {

	console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
	return new Int16BufferAttribute( array, itemSize );

}

function Uint16Attribute( array, itemSize ) {

	console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
	return new Uint16BufferAttribute( array, itemSize );

}

function Int32Attribute( array, itemSize ) {

	console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
	return new Int32BufferAttribute( array, itemSize );

}

function Uint32Attribute( array, itemSize ) {

	console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
	return new Uint32BufferAttribute( array, itemSize );

}

function Float32Attribute( array, itemSize ) {

	console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
	return new Float32BufferAttribute( array, itemSize );

}

function Float64Attribute( array, itemSize ) {

	console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
	return new Float64BufferAttribute( array, itemSize );

}

//

Curve.create = function ( construct, getPoint ) {

	console.log( 'THREE.Curve.create() has been deprecated' );

	construct.prototype = Object.create( Curve.prototype );
	construct.prototype.constructor = construct;
	construct.prototype.getPoint = getPoint;

	return construct;

};

//

Object.assign( CurvePath.prototype, {

	createPointsGeometry: function ( divisions ) {

		console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );

		// generate geometry from path points (for Line or Points objects)

		const pts = this.getPoints( divisions );
		return this.createGeometry( pts );

	},

	createSpacedPointsGeometry: function ( divisions ) {

		console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );

		// generate geometry from equidistant sampling along the path

		const pts = this.getSpacedPoints( divisions );
		return this.createGeometry( pts );

	},

	createGeometry: function ( points ) {

		console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );

		const geometry = new Geometry();

		for ( let i = 0, l = points.length; i < l; i ++ ) {

			const point = points[ i ];
			geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );

		}

		return geometry;

	}

} );

//

Object.assign( Path.prototype, {

	fromPoints: function ( points ) {

		console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
		return this.setFromPoints( points );

	}

} );

//

function ClosedSplineCurve3( points ) {

	console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );

	CatmullRomCurve3.call( this, points );
	this.type = 'catmullrom';
	this.closed = true;

}

ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );

//

function SplineCurve3( points ) {

	console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );

	CatmullRomCurve3.call( this, points );
	this.type = 'catmullrom';

}

SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );

//

function Spline( points ) {

	console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );

	CatmullRomCurve3.call( this, points );
	this.type = 'catmullrom';

}

Spline.prototype = Object.create( CatmullRomCurve3.prototype );

Object.assign( Spline.prototype, {

	initFromArray: function ( /* a */ ) {

		console.error( 'THREE.Spline: .initFromArray() has been removed.' );

	},
	getControlPointsArray: function ( /* optionalTarget */ ) {

		console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );

	},
	reparametrizeByArcLength: function ( /* samplingCoef */ ) {

		console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );

	}

} );

//

function AxisHelper( size ) {

	console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
	return new AxesHelper( size );

}

function BoundingBoxHelper( object, color ) {

	console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
	return new BoxHelper( object, color );

}

function EdgesHelper( object, hex ) {

	console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
	return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );

}

GridHelper.prototype.setColors = function () {

	console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );

};

SkeletonHelper.prototype.update = function () {

	console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );

};

function WireframeHelper( object, hex ) {

	console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
	return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );

}

//

Object.assign( Loader.prototype, {

	extractUrlBase: function ( url ) {

		console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
		return LoaderUtils.extractUrlBase( url );

	}

} );

Loader.Handlers = {

	add: function ( /* regex, loader */ ) {

		console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );

	},

	get: function ( /* file */ ) {

		console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );

	}

};

function XHRLoader( manager ) {

	console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
	return new FileLoader( manager );

}

function BinaryTextureLoader( manager ) {

	console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
	return new DataTextureLoader( manager );

}

Object.assign( ObjectLoader.prototype, {

	setTexturePath: function ( value ) {

		console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
		return this.setResourcePath( value );

	}

} );

//

Object.assign( Box2.prototype, {

	center: function ( optionalTarget ) {

		console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
		return this.getCenter( optionalTarget );

	},
	empty: function () {

		console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
		return this.isEmpty();

	},
	isIntersectionBox: function ( box ) {

		console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
		return this.intersectsBox( box );

	},
	size: function ( optionalTarget ) {

		console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
		return this.getSize( optionalTarget );

	}
} );

Object.assign( Box3.prototype, {

	center: function ( optionalTarget ) {

		console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
		return this.getCenter( optionalTarget );

	},
	empty: function () {

		console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
		return this.isEmpty();

	},
	isIntersectionBox: function ( box ) {

		console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
		return this.intersectsBox( box );

	},
	isIntersectionSphere: function ( sphere ) {

		console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
		return this.intersectsSphere( sphere );

	},
	size: function ( optionalTarget ) {

		console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
		return this.getSize( optionalTarget );

	}
} );

Object.assign( Sphere.prototype, {

	empty: function () {

		console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
		return this.isEmpty();

	},

} );

Frustum.prototype.setFromMatrix = function ( m ) {

	console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
	return this.setFromProjectionMatrix( m );

};

Line3.prototype.center = function ( optionalTarget ) {

	console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
	return this.getCenter( optionalTarget );

};

Object.assign( MathUtils, {

	random16: function () {

		console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
		return Math.random();

	},

	nearestPowerOfTwo: function ( value ) {

		console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
		return MathUtils.floorPowerOfTwo( value );

	},

	nextPowerOfTwo: function ( value ) {

		console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
		return MathUtils.ceilPowerOfTwo( value );

	}

} );

Object.assign( Matrix3.prototype, {

	flattenToArrayOffset: function ( array, offset ) {

		console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
		return this.toArray( array, offset );

	},
	multiplyVector3: function ( vector ) {

		console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
		return vector.applyMatrix3( this );

	},
	multiplyVector3Array: function ( /* a */ ) {

		console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );

	},
	applyToBufferAttribute: function ( attribute ) {

		console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
		return attribute.applyMatrix3( this );

	},
	applyToVector3Array: function ( /* array, offset, length */ ) {

		console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );

	}

} );

Object.assign( Matrix4.prototype, {

	extractPosition: function ( m ) {

		console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
		return this.copyPosition( m );

	},
	flattenToArrayOffset: function ( array, offset ) {

		console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
		return this.toArray( array, offset );

	},
	getPosition: function () {

		console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
		return new Vector3().setFromMatrixColumn( this, 3 );

	},
	setRotationFromQuaternion: function ( q ) {

		console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
		return this.makeRotationFromQuaternion( q );

	},
	multiplyToArray: function () {

		console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );

	},
	multiplyVector3: function ( vector ) {

		console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
		return vector.applyMatrix4( this );

	},
	multiplyVector4: function ( vector ) {

		console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
		return vector.applyMatrix4( this );

	},
	multiplyVector3Array: function ( /* a */ ) {

		console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );

	},
	rotateAxis: function ( v ) {

		console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
		v.transformDirection( this );

	},
	crossVector: function ( vector ) {

		console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
		return vector.applyMatrix4( this );

	},
	translate: function () {

		console.error( 'THREE.Matrix4: .translate() has been removed.' );

	},
	rotateX: function () {

		console.error( 'THREE.Matrix4: .rotateX() has been removed.' );

	},
	rotateY: function () {

		console.error( 'THREE.Matrix4: .rotateY() has been removed.' );

	},
	rotateZ: function () {

		console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );

	},
	rotateByAxis: function () {

		console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );

	},
	applyToBufferAttribute: function ( attribute ) {

		console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
		return attribute.applyMatrix4( this );

	},
	applyToVector3Array: function ( /* array, offset, length */ ) {

		console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );

	},
	makeFrustum: function ( left, right, bottom, top, near, far ) {

		console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
		return this.makePerspective( left, right, top, bottom, near, far );

	}

} );

Plane.prototype.isIntersectionLine = function ( line ) {

	console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
	return this.intersectsLine( line );

};

Quaternion.prototype.multiplyVector3 = function ( vector ) {

	console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
	return vector.applyQuaternion( this );

};

Object.assign( Ray.prototype, {

	isIntersectionBox: function ( box ) {

		console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
		return this.intersectsBox( box );

	},
	isIntersectionPlane: function ( plane ) {

		console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
		return this.intersectsPlane( plane );

	},
	isIntersectionSphere: function ( sphere ) {

		console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
		return this.intersectsSphere( sphere );

	}

} );

Object.assign( Triangle.prototype, {

	area: function () {

		console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
		return this.getArea();

	},
	barycoordFromPoint: function ( point, target ) {

		console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
		return this.getBarycoord( point, target );

	},
	midpoint: function ( target ) {

		console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
		return this.getMidpoint( target );

	},
	normal: function ( target ) {

		console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
		return this.getNormal( target );

	},
	plane: function ( target ) {

		console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
		return this.getPlane( target );

	}

} );

Object.assign( Triangle, {

	barycoordFromPoint: function ( point, a, b, c, target ) {

		console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
		return Triangle.getBarycoord( point, a, b, c, target );

	},
	normal: function ( a, b, c, target ) {

		console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
		return Triangle.getNormal( a, b, c, target );

	}

} );

Object.assign( Shape.prototype, {

	extractAllPoints: function ( divisions ) {

		console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
		return this.extractPoints( divisions );

	},
	extrude: function ( options ) {

		console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
		return new ExtrudeGeometry( this, options );

	},
	makeGeometry: function ( options ) {

		console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
		return new ShapeGeometry( this, options );

	}

} );

Object.assign( Vector2.prototype, {

	fromAttribute: function ( attribute, index, offset ) {

		console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
		return this.fromBufferAttribute( attribute, index, offset );

	},
	distanceToManhattan: function ( v ) {

		console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
		return this.manhattanDistanceTo( v );

	},
	lengthManhattan: function () {

		console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
		return this.manhattanLength();

	}

} );

Object.assign( Vector3.prototype, {

	setEulerFromRotationMatrix: function () {

		console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );

	},
	setEulerFromQuaternion: function () {

		console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );

	},
	getPositionFromMatrix: function ( m ) {

		console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
		return this.setFromMatrixPosition( m );

	},
	getScaleFromMatrix: function ( m ) {

		console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
		return this.setFromMatrixScale( m );

	},
	getColumnFromMatrix: function ( index, matrix ) {

		console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
		return this.setFromMatrixColumn( matrix, index );

	},
	applyProjection: function ( m ) {

		console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
		return this.applyMatrix4( m );

	},
	fromAttribute: function ( attribute, index, offset ) {

		console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
		return this.fromBufferAttribute( attribute, index, offset );

	},
	distanceToManhattan: function ( v ) {

		console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
		return this.manhattanDistanceTo( v );

	},
	lengthManhattan: function () {

		console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
		return this.manhattanLength();

	}

} );

Object.assign( Vector4.prototype, {

	fromAttribute: function ( attribute, index, offset ) {

		console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
		return this.fromBufferAttribute( attribute, index, offset );

	},
	lengthManhattan: function () {

		console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
		return this.manhattanLength();

	}

} );

//

Object.assign( Geometry.prototype, {

	computeTangents: function () {

		console.error( 'THREE.Geometry: .computeTangents() has been removed.' );

	},
	computeLineDistances: function () {

		console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );

	},
	applyMatrix: function ( matrix ) {

		console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
		return this.applyMatrix4( matrix );

	}

} );

Object.assign( Object3D.prototype, {

	getChildByName: function ( name ) {

		console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
		return this.getObjectByName( name );

	},
	renderDepth: function () {

		console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );

	},
	translate: function ( distance, axis ) {

		console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
		return this.translateOnAxis( axis, distance );

	},
	getWorldRotation: function () {

		console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );

	},
	applyMatrix: function ( matrix ) {

		console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
		return this.applyMatrix4( matrix );

	}

} );

Object.defineProperties( Object3D.prototype, {

	eulerOrder: {
		get: function () {

			console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
			return this.rotation.order;

		},
		set: function ( value ) {

			console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
			this.rotation.order = value;

		}
	},
	useQuaternion: {
		get: function () {

			console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );

		},
		set: function () {

			console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );

		}
	}

} );

Object.assign( Mesh.prototype, {

	setDrawMode: function () {

		console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );

	},

} );

Object.defineProperties( Mesh.prototype, {

	drawMode: {
		get: function () {

			console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
			return TrianglesDrawMode;

		},
		set: function () {

			console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );

		}
	}

} );

Object.defineProperties( LOD.prototype, {

	objects: {
		get: function () {

			console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
			return this.levels;

		}
	}

} );

Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {

	get: function () {

		console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );

	},
	set: function () {

		console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );

	}

} );

SkinnedMesh.prototype.initBones = function () {

	console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );

};

Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {

	get: function () {

		console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
		return this.arcLengthDivisions;

	},
	set: function ( value ) {

		console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
		this.arcLengthDivisions = value;

	}

} );

//

PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {

	console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
			"Use .setFocalLength and .filmGauge for a photographic setup." );

	if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
	this.setFocalLength( focalLength );

};

//

Object.defineProperties( Light.prototype, {
	onlyShadow: {
		set: function () {

			console.warn( 'THREE.Light: .onlyShadow has been removed.' );

		}
	},
	shadowCameraFov: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
			this.shadow.camera.fov = value;

		}
	},
	shadowCameraLeft: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
			this.shadow.camera.left = value;

		}
	},
	shadowCameraRight: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
			this.shadow.camera.right = value;

		}
	},
	shadowCameraTop: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
			this.shadow.camera.top = value;

		}
	},
	shadowCameraBottom: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
			this.shadow.camera.bottom = value;

		}
	},
	shadowCameraNear: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
			this.shadow.camera.near = value;

		}
	},
	shadowCameraFar: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
			this.shadow.camera.far = value;

		}
	},
	shadowCameraVisible: {
		set: function () {

			console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );

		}
	},
	shadowBias: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
			this.shadow.bias = value;

		}
	},
	shadowDarkness: {
		set: function () {

			console.warn( 'THREE.Light: .shadowDarkness has been removed.' );

		}
	},
	shadowMapWidth: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
			this.shadow.mapSize.width = value;

		}
	},
	shadowMapHeight: {
		set: function ( value ) {

			console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
			this.shadow.mapSize.height = value;

		}
	}
} );

//

Object.defineProperties( BufferAttribute.prototype, {

	length: {
		get: function () {

			console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
			return this.array.length;

		}
	},
	dynamic: {
		get: function () {

			console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
			return this.usage === DynamicDrawUsage;

		},
		set: function ( /* value */ ) {

			console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
			this.setUsage( DynamicDrawUsage );

		}
	}

} );

Object.assign( BufferAttribute.prototype, {
	setDynamic: function ( value ) {

		console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
		this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
		return this;

	},
	copyIndicesArray: function ( /* indices */ ) {

		console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );

	},
	setArray: function ( /* array */ ) {

		console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );

	}
} );

Object.assign( BufferGeometry.prototype, {

	addIndex: function ( index ) {

		console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
		this.setIndex( index );

	},
	addAttribute: function ( name, attribute ) {

		console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );

		if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {

			console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );

			return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );

		}

		if ( name === 'index' ) {

			console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
			this.setIndex( attribute );

			return this;

		}

		return this.setAttribute( name, attribute );

	},
	addDrawCall: function ( start, count, indexOffset ) {

		if ( indexOffset !== undefined ) {

			console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );

		}

		console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
		this.addGroup( start, count );

	},
	clearDrawCalls: function () {

		console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
		this.clearGroups();

	},
	computeTangents: function () {

		console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );

	},
	computeOffsets: function () {

		console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );

	},
	removeAttribute: function ( name ) {

		console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );

		return this.deleteAttribute( name );

	},
	applyMatrix: function ( matrix ) {

		console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
		return this.applyMatrix4( matrix );

	}

} );

Object.defineProperties( BufferGeometry.prototype, {

	drawcalls: {
		get: function () {

			console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
			return this.groups;

		}
	},
	offsets: {
		get: function () {

			console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
			return this.groups;

		}
	}

} );

Object.defineProperties( InstancedBufferGeometry.prototype, {

	maxInstancedCount: {
		get: function () {

			console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
			return this.instanceCount;

		},
		set: function ( value ) {

			console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
			this.instanceCount = value;

		}
	}

} );

Object.defineProperties( Raycaster.prototype, {

	linePrecision: {
		get: function () {

			console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
			return this.params.Line.threshold;

		},
		set: function ( value ) {

			console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
			this.params.Line.threshold = value;

		}
	}

} );

Object.defineProperties( InterleavedBuffer.prototype, {

	dynamic: {
		get: function () {

			console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
			return this.usage === DynamicDrawUsage;

		},
		set: function ( value ) {

			console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
			this.setUsage( value );

		}
	}

} );

Object.assign( InterleavedBuffer.prototype, {
	setDynamic: function ( value ) {

		console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
		this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
		return this;

	},
	setArray: function ( /* array */ ) {

		console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );

	}
} );

//

Object.assign( ExtrudeBufferGeometry.prototype, {

	getArrays: function () {

		console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );

	},

	addShapeList: function () {

		console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );

	},

	addShape: function () {

		console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );

	}

} );

//

Object.defineProperties( Uniform.prototype, {

	dynamic: {
		set: function () {

			console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );

		}
	},
	onUpdate: {
		value: function () {

			console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
			return this;

		}
	}

} );

//

Object.defineProperties( Material.prototype, {

	wrapAround: {
		get: function () {

			console.warn( 'THREE.Material: .wrapAround has been removed.' );

		},
		set: function () {

			console.warn( 'THREE.Material: .wrapAround has been removed.' );

		}
	},

	overdraw: {
		get: function () {

			console.warn( 'THREE.Material: .overdraw has been removed.' );

		},
		set: function () {

			console.warn( 'THREE.Material: .overdraw has been removed.' );

		}
	},

	wrapRGB: {
		get: function () {

			console.warn( 'THREE.Material: .wrapRGB has been removed.' );
			return new Color();

		}
	},

	shading: {
		get: function () {

			console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );

		},
		set: function ( value ) {

			console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
			this.flatShading = ( value === FlatShading );

		}
	},

	stencilMask: {
		get: function () {

			console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
			return this.stencilFuncMask;

		},
		set: function ( value ) {

			console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
			this.stencilFuncMask = value;

		}
	}

} );

Object.defineProperties( MeshPhongMaterial.prototype, {

	metal: {
		get: function () {

			console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
			return false;

		},
		set: function () {

			console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );

		}
	}

} );

Object.defineProperties( ShaderMaterial.prototype, {

	derivatives: {
		get: function () {

			console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
			return this.extensions.derivatives;

		},
		set: function ( value ) {

			console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
			this.extensions.derivatives = value;

		}
	}

} );

//

Object.assign( WebGLRenderer.prototype, {

	clearTarget: function ( renderTarget, color, depth, stencil ) {

		console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
		this.setRenderTarget( renderTarget );
		this.clear( color, depth, stencil );

	},
	animate: function ( callback ) {

		console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
		this.setAnimationLoop( callback );

	},
	getCurrentRenderTarget: function () {

		console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
		return this.getRenderTarget();

	},
	getMaxAnisotropy: function () {

		console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
		return this.capabilities.getMaxAnisotropy();

	},
	getPrecision: function () {

		console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
		return this.capabilities.precision;

	},
	resetGLState: function () {

		console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
		return this.state.reset();

	},
	supportsFloatTextures: function () {

		console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
		return this.extensions.get( 'OES_texture_float' );

	},
	supportsHalfFloatTextures: function () {

		console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
		return this.extensions.get( 'OES_texture_half_float' );

	},
	supportsStandardDerivatives: function () {

		console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
		return this.extensions.get( 'OES_standard_derivatives' );

	},
	supportsCompressedTextureS3TC: function () {

		console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
		return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );

	},
	supportsCompressedTexturePVRTC: function () {

		console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
		return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );

	},
	supportsBlendMinMax: function () {

		console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
		return this.extensions.get( 'EXT_blend_minmax' );

	},
	supportsVertexTextures: function () {

		console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
		return this.capabilities.vertexTextures;

	},
	supportsInstancedArrays: function () {

		console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
		return this.extensions.get( 'ANGLE_instanced_arrays' );

	},
	enableScissorTest: function ( boolean ) {

		console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
		this.setScissorTest( boolean );

	},
	initMaterial: function () {

		console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );

	},
	addPrePlugin: function () {

		console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );

	},
	addPostPlugin: function () {

		console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );

	},
	updateShadowMap: function () {

		console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );

	},
	setFaceCulling: function () {

		console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );

	},
	allocTextureUnit: function () {

		console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );

	},
	setTexture: function () {

		console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );

	},
	setTexture2D: function () {

		console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );

	},
	setTextureCube: function () {

		console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );

	},
	getActiveMipMapLevel: function () {

		console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
		return this.getActiveMipmapLevel();

	}

} );

Object.defineProperties( WebGLRenderer.prototype, {

	shadowMapEnabled: {
		get: function () {

			return this.shadowMap.enabled;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
			this.shadowMap.enabled = value;

		}
	},
	shadowMapType: {
		get: function () {

			return this.shadowMap.type;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
			this.shadowMap.type = value;

		}
	},
	shadowMapCullFace: {
		get: function () {

			console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
			return undefined;

		},
		set: function ( /* value */ ) {

			console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );

		}
	},
	context: {
		get: function () {

			console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
			return this.getContext();

		}
	},
	vr: {
		get: function () {

			console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
			return this.xr;

		}
	},
	gammaInput: {
		get: function () {

			console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
			return false;

		},
		set: function () {

			console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );

		}
	},
	gammaOutput: {
		get: function () {

			console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
			return false;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
			this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;

		}
	},
	toneMappingWhitePoint: {
		get: function () {

			console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
			return 1.0;

		},
		set: function () {

			console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );

		}
	},

} );

Object.defineProperties( WebGLShadowMap.prototype, {

	cullFace: {
		get: function () {

			console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
			return undefined;

		},
		set: function ( /* cullFace */ ) {

			console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );

		}
	},
	renderReverseSided: {
		get: function () {

			console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
			return undefined;

		},
		set: function () {

			console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );

		}
	},
	renderSingleSided: {
		get: function () {

			console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
			return undefined;

		},
		set: function () {

			console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );

		}
	}

} );

function WebGLRenderTargetCube( width, height, options ) {

	console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
	return new WebGLCubeRenderTarget( width, options );

}

//

Object.defineProperties( WebGLRenderTarget.prototype, {

	wrapS: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
			return this.texture.wrapS;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
			this.texture.wrapS = value;

		}
	},
	wrapT: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
			return this.texture.wrapT;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
			this.texture.wrapT = value;

		}
	},
	magFilter: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
			return this.texture.magFilter;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
			this.texture.magFilter = value;

		}
	},
	minFilter: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
			return this.texture.minFilter;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
			this.texture.minFilter = value;

		}
	},
	anisotropy: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
			return this.texture.anisotropy;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
			this.texture.anisotropy = value;

		}
	},
	offset: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
			return this.texture.offset;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
			this.texture.offset = value;

		}
	},
	repeat: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
			return this.texture.repeat;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
			this.texture.repeat = value;

		}
	},
	format: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
			return this.texture.format;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
			this.texture.format = value;

		}
	},
	type: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
			return this.texture.type;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
			this.texture.type = value;

		}
	},
	generateMipmaps: {
		get: function () {

			console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
			return this.texture.generateMipmaps;

		},
		set: function ( value ) {

			console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
			this.texture.generateMipmaps = value;

		}
	}

} );

//

Object.defineProperties( Audio.prototype, {

	load: {
		value: function ( file ) {

			console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
			const scope = this;
			const audioLoader = new AudioLoader();
			audioLoader.load( file, function ( buffer ) {

				scope.setBuffer( buffer );

			} );
			return this;

		}
	},
	startTime: {
		set: function () {

			console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );

		}
	}

} );

AudioAnalyser.prototype.getData = function () {

	console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
	return this.getFrequencyData();

};

//

CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {

	console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
	return this.update( renderer, scene );

};

//

const GeometryUtils = {

	merge: function ( geometry1, geometry2, materialIndexOffset ) {

		console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
		let matrix;

		if ( geometry2.isMesh ) {

			geometry2.matrixAutoUpdate && geometry2.updateMatrix();

			matrix = geometry2.matrix;
			geometry2 = geometry2.geometry;

		}

		geometry1.merge( geometry2, matrix, materialIndexOffset );

	},

	center: function ( geometry ) {

		console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
		return geometry.center();

	}

};

ImageUtils.crossOrigin = undefined;

ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {

	console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );

	const loader = new TextureLoader();
	loader.setCrossOrigin( this.crossOrigin );

	const texture = loader.load( url, onLoad, undefined, onError );

	if ( mapping ) texture.mapping = mapping;

	return texture;

};

ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {

	console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );

	const loader = new CubeTextureLoader();
	loader.setCrossOrigin( this.crossOrigin );

	const texture = loader.load( urls, onLoad, undefined, onError );

	if ( mapping ) texture.mapping = mapping;

	return texture;

};

ImageUtils.loadCompressedTexture = function () {

	console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );

};

ImageUtils.loadCompressedTextureCube = function () {

	console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );

};

//

function CanvasRenderer() {

	console.error( 'THREE.CanvasRenderer has been removed' );

}

//

function JSONLoader() {

	console.error( 'THREE.JSONLoader has been removed.' );

}

//

const SceneUtils = {

	createMultiMaterialObject: function ( /* geometry, materials */ ) {

		console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );

	},

	detach: function ( /* child, parent, scene */ ) {

		console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );

	},

	attach: function ( /* child, scene, parent */ ) {

		console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );

	}

};

//

function LensFlare() {

	console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );

}

if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {

	/* eslint-disable no-undef */
	__THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
		revision: REVISION,
	} } ) );
	/* eslint-enable no-undef */

}




/***/ }),
/* 53 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isUndefined;
// Is a given variable undefined?
function isUndefined(obj) {
  return obj === void 0;
}


/***/ }),
/* 54 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isBoolean;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);


// Is a given value a boolean?
function isBoolean(obj) {
  return obj === true || obj === false || __WEBPACK_IMPORTED_MODULE_0__setup_js__["t" /* toString */].call(obj) === '[object Boolean]';
}


/***/ }),
/* 55 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);


/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Number'));


/***/ }),
/* 56 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);


/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Symbol'));


/***/ }),
/* 57 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);


/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('ArrayBuffer'));


/***/ }),
/* 58 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isNaN;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isNumber_js__ = __webpack_require__(55);



// Is the given value `NaN`?
function isNaN(obj) {
  return Object(__WEBPACK_IMPORTED_MODULE_1__isNumber_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_0__setup_js__["g" /* _isNaN */])(obj);
}


/***/ }),
/* 59 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isDataView_js__ = __webpack_require__(37);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__constant_js__ = __webpack_require__(60);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isBufferLike_js__ = __webpack_require__(123);





// Is a given value a typed array?
var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
function isTypedArray(obj) {
  // `ArrayBuffer.isView` is the most future-proof, so use it when available.
  // Otherwise, fall back on the above regular expression.
  return __WEBPACK_IMPORTED_MODULE_0__setup_js__["l" /* nativeIsView */] ? (Object(__WEBPACK_IMPORTED_MODULE_0__setup_js__["l" /* nativeIsView */])(obj) && !Object(__WEBPACK_IMPORTED_MODULE_1__isDataView_js__["a" /* default */])(obj)) :
                Object(__WEBPACK_IMPORTED_MODULE_3__isBufferLike_js__["a" /* default */])(obj) && typedArrayPattern.test(__WEBPACK_IMPORTED_MODULE_0__setup_js__["t" /* toString */].call(obj));
}

/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_0__setup_js__["r" /* supportsArrayBuffer */] ? isTypedArray : Object(__WEBPACK_IMPORTED_MODULE_2__constant_js__["a" /* default */])(false));


/***/ }),
/* 60 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = constant;
// Predicate-generating function. Often useful outside of Underscore.
function constant(value) {
  return function() {
    return value;
  };
}


/***/ }),
/* 61 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = createSizePropertyCheck;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);


// Common internal logic for `isArrayLike` and `isBufferLike`.
function createSizePropertyCheck(getSizeProperty) {
  return function(collection) {
    var sizeProperty = getSizeProperty(collection);
    return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= __WEBPACK_IMPORTED_MODULE_0__setup_js__["b" /* MAX_ARRAY_INDEX */];
  }
}


/***/ }),
/* 62 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = shallowProperty;
// Internal helper to generate a function to obtain property `key` from `obj`.
function shallowProperty(key) {
  return function(obj) {
    return obj == null ? void 0 : obj[key];
  };
}


/***/ }),
/* 63 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = collectNonEnumProps;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__has_js__ = __webpack_require__(13);




// Internal helper to create a simple lookup structure.
// `collectNonEnumProps` used to depend on `_.contains`, but this led to
// circular imports. `emulatedSet` is a one-off solution that only works for
// arrays of strings.
function emulatedSet(keys) {
  var hash = {};
  for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
  return {
    contains: function(key) { return hash[key] === true; },
    push: function(key) {
      hash[key] = true;
      return keys.push(key);
    }
  };
}

// Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
// be iterated by `for key in ...` and thus missed. Extends `keys` in place if
// needed.
function collectNonEnumProps(obj, keys) {
  keys = emulatedSet(keys);
  var nonEnumIdx = __WEBPACK_IMPORTED_MODULE_0__setup_js__["n" /* nonEnumerableProps */].length;
  var constructor = obj.constructor;
  var proto = (Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(constructor) && constructor.prototype) || __WEBPACK_IMPORTED_MODULE_0__setup_js__["c" /* ObjProto */];

  // Constructor is a special case.
  var prop = 'constructor';
  if (Object(__WEBPACK_IMPORTED_MODULE_2__has_js__["a" /* default */])(obj, prop) && !keys.contains(prop)) keys.push(prop);

  while (nonEnumIdx--) {
    prop = __WEBPACK_IMPORTED_MODULE_0__setup_js__["n" /* nonEnumerableProps */][nonEnumIdx];
    if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
      keys.push(prop);
    }
  }
}


/***/ }),
/* 64 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isMatch;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(4);


// Returns whether an object has a given set of `key:value` pairs.
function isMatch(object, attrs) {
  var _keys = Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(attrs), length = _keys.length;
  if (object == null) return !length;
  var obj = Object(object);
  for (var i = 0; i < length; i++) {
    var key = _keys[i];
    if (attrs[key] !== obj[key] || !(key in obj)) return false;
  }
  return true;
}


/***/ }),
/* 65 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = invert;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(4);


// Invert the keys and values of an object. The values must be serializable.
function invert(obj) {
  var result = {};
  var _keys = Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(obj);
  for (var i = 0, length = _keys.length; i < length; i++) {
    result[obj[_keys[i]]] = _keys[i];
  }
  return result;
}


/***/ }),
/* 66 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = functions;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isFunction_js__ = __webpack_require__(10);


// Return a sorted list of the function names available on the object.
function functions(obj) {
  var names = [];
  for (var key in obj) {
    if (Object(__WEBPACK_IMPORTED_MODULE_0__isFunction_js__["a" /* default */])(obj[key])) names.push(key);
  }
  return names.sort();
}


/***/ }),
/* 67 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createAssigner_js__ = __webpack_require__(41);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__allKeys_js__ = __webpack_require__(24);



// Extend a given object with all the properties in passed-in object(s).
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createAssigner_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__allKeys_js__["a" /* default */]));


/***/ }),
/* 68 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createAssigner_js__ = __webpack_require__(41);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__allKeys_js__ = __webpack_require__(24);



// Fill in a given object with default properties.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createAssigner_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__allKeys_js__["a" /* default */], true));


/***/ }),
/* 69 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = baseCreate;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isObject_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(1);



// Create a naked function reference for surrogate-prototype-swapping.
function ctor() {
  return function(){};
}

// An internal function for creating a new object that inherits from another.
function baseCreate(prototype) {
  if (!Object(__WEBPACK_IMPORTED_MODULE_0__isObject_js__["a" /* default */])(prototype)) return {};
  if (__WEBPACK_IMPORTED_MODULE_1__setup_js__["j" /* nativeCreate */]) return Object(__WEBPACK_IMPORTED_MODULE_1__setup_js__["j" /* nativeCreate */])(prototype);
  var Ctor = ctor();
  Ctor.prototype = prototype;
  var result = new Ctor;
  Ctor.prototype = null;
  return result;
}


/***/ }),
/* 70 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = get;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__toPath_js__ = __webpack_require__(25);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__deepGet_js__ = __webpack_require__(43);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isUndefined_js__ = __webpack_require__(53);




// Get the value of the (deep) property on `path` from `object`.
// If any property in `path` does not exist or if the value is
// `undefined`, return `defaultValue` instead.
// The `path` is normalized through `_.toPath`.
function get(object, path, defaultValue) {
  var value = Object(__WEBPACK_IMPORTED_MODULE_1__deepGet_js__["a" /* default */])(object, Object(__WEBPACK_IMPORTED_MODULE_0__toPath_js__["a" /* default */])(path));
  return Object(__WEBPACK_IMPORTED_MODULE_2__isUndefined_js__["a" /* default */])(value) ? defaultValue : value;
}


/***/ }),
/* 71 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = toPath;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArray_js__ = __webpack_require__(15);



// Normalize a (deep) property `path` to array.
// Like `_.iteratee`, this function can be customized.
function toPath(path) {
  return Object(__WEBPACK_IMPORTED_MODULE_1__isArray_js__["a" /* default */])(path) ? path : [path];
}
__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].toPath = toPath;


/***/ }),
/* 72 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = baseIteratee;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__identity_js__ = __webpack_require__(44);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isObject_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isArray_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__matcher_js__ = __webpack_require__(30);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__property_js__ = __webpack_require__(45);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__optimizeCb_js__ = __webpack_require__(26);








// An internal function to generate callbacks that can be applied to each
// element in a collection, returning the desired result — either `_.identity`,
// an arbitrary callback, a property matcher, or a property accessor.
function baseIteratee(value, context, argCount) {
  if (value == null) return __WEBPACK_IMPORTED_MODULE_0__identity_js__["a" /* default */];
  if (Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(value)) return Object(__WEBPACK_IMPORTED_MODULE_6__optimizeCb_js__["a" /* default */])(value, context, argCount);
  if (Object(__WEBPACK_IMPORTED_MODULE_2__isObject_js__["a" /* default */])(value) && !Object(__WEBPACK_IMPORTED_MODULE_3__isArray_js__["a" /* default */])(value)) return Object(__WEBPACK_IMPORTED_MODULE_4__matcher_js__["a" /* default */])(value);
  return Object(__WEBPACK_IMPORTED_MODULE_5__property_js__["a" /* default */])(value);
}


/***/ }),
/* 73 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = iteratee;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__baseIteratee_js__ = __webpack_require__(72);



// External wrapper for our callback generator. Users may customize
// `_.iteratee` if they want additional predicate/iteratee shorthand styles.
// This abstraction hides the internal-only `argCount` argument.
function iteratee(value, context) {
  return Object(__WEBPACK_IMPORTED_MODULE_1__baseIteratee_js__["a" /* default */])(value, context, Infinity);
}
__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].iteratee = iteratee;


/***/ }),
/* 74 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = noop;
// Predicate-generating function. Often useful outside of Underscore.
function noop(){}


/***/ }),
/* 75 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = random;
// Return a random integer between `min` and `max` (inclusive).
function random(min, max) {
  if (max == null) {
    max = min;
    min = 0;
  }
  return min + Math.floor(Math.random() * (max - min + 1));
}


/***/ }),
/* 76 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = createEscaper;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(4);


// Internal helper to generate functions for escaping and unescaping strings
// to/from HTML interpolation.
function createEscaper(map) {
  var escaper = function(match) {
    return map[match];
  };
  // Regexes for identifying a key that needs to be escaped.
  var source = '(?:' + Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(map).join('|') + ')';
  var testRegexp = RegExp(source);
  var replaceRegexp = RegExp(source, 'g');
  return function(string) {
    string = string == null ? '' : '' + string;
    return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
  };
}


/***/ }),
/* 77 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// Internal list of HTML entities for escaping.
/* harmony default export */ __webpack_exports__["a"] = ({
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#x27;',
  '`': '&#x60;'
});


/***/ }),
/* 78 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);


// By default, Underscore uses ERB-style template delimiters. Change the
// following template settings to use alternative delimiters.
/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].templateSettings = {
  evaluate: /<%([\s\S]+?)%>/g,
  interpolate: /<%=([\s\S]+?)%>/g,
  escape: /<%-([\s\S]+?)%>/g
});


/***/ }),
/* 79 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = executeBound;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__baseCreate_js__ = __webpack_require__(69);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isObject_js__ = __webpack_require__(14);



// Internal function to execute `sourceFunc` bound to `context` with optional
// `args`. Determines whether to execute a function as a constructor or as a
// normal function.
function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
  if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
  var self = Object(__WEBPACK_IMPORTED_MODULE_0__baseCreate_js__["a" /* default */])(sourceFunc.prototype);
  var result = sourceFunc.apply(self, args);
  if (Object(__WEBPACK_IMPORTED_MODULE_1__isObject_js__["a" /* default */])(result)) return result;
  return self;
}


/***/ }),
/* 80 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__executeBound_js__ = __webpack_require__(79);




// Create a function bound to a given object (assigning `this`, and arguments,
// optionally).
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(func, context, args) {
  if (!Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(func)) throw new TypeError('Bind must be called on a function');
  var bound = Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(callArgs) {
    return Object(__WEBPACK_IMPORTED_MODULE_2__executeBound_js__["a" /* default */])(func, bound, context, this, args.concat(callArgs));
  });
  return bound;
}));


/***/ }),
/* 81 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);


// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(func, wait, args) {
  return setTimeout(function() {
    return func.apply(null, args);
  }, wait);
}));


/***/ }),
/* 82 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = before;
// Returns a function that will only be executed up to (but not including) the
// Nth call.
function before(times, func) {
  var memo;
  return function() {
    if (--times > 0) {
      memo = func.apply(this, arguments);
    }
    if (times <= 1) func = null;
    return memo;
  };
}


/***/ }),
/* 83 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = findKey;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(4);



// Returns the first key on an object that passes a truth test.
function findKey(obj, predicate, context) {
  predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
  var _keys = Object(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */])(obj), key;
  for (var i = 0, length = _keys.length; i < length; i++) {
    key = _keys[i];
    if (predicate(obj[key], key, obj)) return key;
  }
}


/***/ }),
/* 84 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = createPredicateIndexFinder;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getLength_js__ = __webpack_require__(11);



// Internal function to generate `_.findIndex` and `_.findLastIndex`.
function createPredicateIndexFinder(dir) {
  return function(array, predicate, context) {
    predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
    var length = Object(__WEBPACK_IMPORTED_MODULE_1__getLength_js__["a" /* default */])(array);
    var index = dir > 0 ? 0 : length - 1;
    for (; index >= 0 && index < length; index += dir) {
      if (predicate(array[index], index, array)) return index;
    }
    return -1;
  };
}


/***/ }),
/* 85 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createPredicateIndexFinder_js__ = __webpack_require__(84);


// Returns the last index on an array-like that passes a truth test.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createPredicateIndexFinder_js__["a" /* default */])(-1));


/***/ }),
/* 86 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = sortedIndex;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getLength_js__ = __webpack_require__(11);



// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
function sortedIndex(array, obj, iteratee, context) {
  iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context, 1);
  var value = iteratee(obj);
  var low = 0, high = Object(__WEBPACK_IMPORTED_MODULE_1__getLength_js__["a" /* default */])(array);
  while (low < high) {
    var mid = Math.floor((low + high) / 2);
    if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
  }
  return low;
}


/***/ }),
/* 87 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sortedIndex_js__ = __webpack_require__(86);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__findIndex_js__ = __webpack_require__(48);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__createIndexFinder_js__ = __webpack_require__(88);




// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_2__createIndexFinder_js__["a" /* default */])(1, __WEBPACK_IMPORTED_MODULE_1__findIndex_js__["a" /* default */], __WEBPACK_IMPORTED_MODULE_0__sortedIndex_js__["a" /* default */]));


/***/ }),
/* 88 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = createIndexFinder;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isNaN_js__ = __webpack_require__(58);




// Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions.
function createIndexFinder(dir, predicateFind, sortedIndex) {
  return function(array, item, idx) {
    var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(array);
    if (typeof idx == 'number') {
      if (dir > 0) {
        i = idx >= 0 ? idx : Math.max(idx + length, i);
      } else {
        length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
      }
    } else if (sortedIndex && idx && length) {
      idx = sortedIndex(array, item);
      return array[idx] === item ? idx : -1;
    }
    if (item !== item) {
      idx = predicateFind(__WEBPACK_IMPORTED_MODULE_1__setup_js__["q" /* slice */].call(array, i, length), __WEBPACK_IMPORTED_MODULE_2__isNaN_js__["a" /* default */]);
      return idx >= 0 ? idx + i : -1;
    }
    for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
      if (array[idx] === item) return idx;
    }
    return -1;
  };
}


/***/ }),
/* 89 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = find;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__findIndex_js__ = __webpack_require__(48);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__findKey_js__ = __webpack_require__(83);




// Return the first value which passes a truth test.
function find(obj, predicate, context) {
  var keyFinder = Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) ? __WEBPACK_IMPORTED_MODULE_1__findIndex_js__["a" /* default */] : __WEBPACK_IMPORTED_MODULE_2__findKey_js__["a" /* default */];
  var key = keyFinder(obj, predicate, context);
  if (key !== void 0 && key !== -1) return obj[key];
}


/***/ }),
/* 90 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = createReduce;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__optimizeCb_js__ = __webpack_require__(26);




// Internal helper to create a reducing function, iterating left or right.
function createReduce(dir) {
  // Wrap code that reassigns argument variables in a separate function than
  // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
  var reducer = function(obj, iteratee, memo, initial) {
    var _keys = !Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */])(obj),
        length = (_keys || obj).length,
        index = dir > 0 ? 0 : length - 1;
    if (!initial) {
      memo = obj[_keys ? _keys[index] : index];
      index += dir;
    }
    for (; index >= 0 && index < length; index += dir) {
      var currentKey = _keys ? _keys[index] : index;
      memo = iteratee(memo, obj[currentKey], currentKey, obj);
    }
    return memo;
  };

  return function(obj, iteratee, memo, context) {
    var initial = arguments.length >= 3;
    return reducer(obj, Object(__WEBPACK_IMPORTED_MODULE_2__optimizeCb_js__["a" /* default */])(iteratee, context, 4), memo, initial);
  };
}


/***/ }),
/* 91 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = max;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__values_js__ = __webpack_require__(19);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__each_js__ = __webpack_require__(16);





// Return the maximum element (or element-based computation).
function max(obj, iteratee, context) {
  var result = -Infinity, lastComputed = -Infinity,
      value, computed;
  if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) {
    obj = Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) ? obj : Object(__WEBPACK_IMPORTED_MODULE_1__values_js__["a" /* default */])(obj);
    for (var i = 0, length = obj.length; i < length; i++) {
      value = obj[i];
      if (value != null && value > result) {
        result = value;
      }
    }
  } else {
    iteratee = Object(__WEBPACK_IMPORTED_MODULE_2__cb_js__["a" /* default */])(iteratee, context);
    Object(__WEBPACK_IMPORTED_MODULE_3__each_js__["a" /* default */])(obj, function(v, index, list) {
      computed = iteratee(v, index, list);
      if (computed > lastComputed || (computed === -Infinity && result === -Infinity)) {
        result = v;
        lastComputed = computed;
      }
    });
  }
  return result;
}


/***/ }),
/* 92 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = sample;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__values_js__ = __webpack_require__(19);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__getLength_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__random_js__ = __webpack_require__(75);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__toArray_js__ = __webpack_require__(93);






// Sample **n** random values from a collection using the modern version of the
// [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `_.map`.
function sample(obj, n, guard) {
  if (n == null || guard) {
    if (!Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj)) obj = Object(__WEBPACK_IMPORTED_MODULE_1__values_js__["a" /* default */])(obj);
    return obj[Object(__WEBPACK_IMPORTED_MODULE_3__random_js__["a" /* default */])(obj.length - 1)];
  }
  var sample = Object(__WEBPACK_IMPORTED_MODULE_4__toArray_js__["a" /* default */])(obj);
  var length = Object(__WEBPACK_IMPORTED_MODULE_2__getLength_js__["a" /* default */])(sample);
  n = Math.max(Math.min(n, length), 0);
  var last = length - 1;
  for (var index = 0; index < n; index++) {
    var rand = Object(__WEBPACK_IMPORTED_MODULE_3__random_js__["a" /* default */])(index, last);
    var temp = sample[index];
    sample[index] = sample[rand];
    sample[rand] = temp;
  }
  return sample.slice(0, n);
}


/***/ }),
/* 93 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = toArray;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArray_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isString_js__ = __webpack_require__(36);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__map_js__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__identity_js__ = __webpack_require__(44);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__values_js__ = __webpack_require__(19);








// Safely create a real, live array from anything iterable.
var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
function toArray(obj) {
  if (!obj) return [];
  if (Object(__WEBPACK_IMPORTED_MODULE_0__isArray_js__["a" /* default */])(obj)) return __WEBPACK_IMPORTED_MODULE_1__setup_js__["q" /* slice */].call(obj);
  if (Object(__WEBPACK_IMPORTED_MODULE_2__isString_js__["a" /* default */])(obj)) {
    // Keep surrogate pair characters together.
    return obj.match(reStrSymbol);
  }
  if (Object(__WEBPACK_IMPORTED_MODULE_3__isArrayLike_js__["a" /* default */])(obj)) return Object(__WEBPACK_IMPORTED_MODULE_4__map_js__["a" /* default */])(obj, __WEBPACK_IMPORTED_MODULE_5__identity_js__["a" /* default */]);
  return Object(__WEBPACK_IMPORTED_MODULE_6__values_js__["a" /* default */])(obj);
}


/***/ }),
/* 94 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__optimizeCb_js__ = __webpack_require__(26);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__allKeys_js__ = __webpack_require__(24);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__keyInObj_js__ = __webpack_require__(172);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__flatten_js__ = __webpack_require__(20);







// Return a copy of the object only containing the allowed properties.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(obj, keys) {
  var result = {}, iteratee = keys[0];
  if (obj == null) return result;
  if (Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(iteratee)) {
    if (keys.length > 1) iteratee = Object(__WEBPACK_IMPORTED_MODULE_2__optimizeCb_js__["a" /* default */])(iteratee, keys[1]);
    keys = Object(__WEBPACK_IMPORTED_MODULE_3__allKeys_js__["a" /* default */])(obj);
  } else {
    iteratee = __WEBPACK_IMPORTED_MODULE_4__keyInObj_js__["a" /* default */];
    keys = Object(__WEBPACK_IMPORTED_MODULE_5__flatten_js__["a" /* default */])(keys, false, false);
    obj = Object(obj);
  }
  for (var i = 0, length = keys.length; i < length; i++) {
    var key = keys[i];
    var value = obj[key];
    if (iteratee(value, key, obj)) result[key] = value;
  }
  return result;
}));


/***/ }),
/* 95 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = initial;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);


// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N.
function initial(array, n, guard) {
  return __WEBPACK_IMPORTED_MODULE_0__setup_js__["q" /* slice */].call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
}


/***/ }),
/* 96 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = rest;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);


// Returns everything but the first entry of the `array`. Especially useful on
// the `arguments` object. Passing an **n** will return the rest N values in the
// `array`.
function rest(array, n, guard) {
  return __WEBPACK_IMPORTED_MODULE_0__setup_js__["q" /* slice */].call(array, n == null || guard ? 1 : n);
}


/***/ }),
/* 97 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__flatten_js__ = __webpack_require__(20);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__filter_js__ = __webpack_require__(27);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__contains_js__ = __webpack_require__(28);





// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(array, rest) {
  rest = Object(__WEBPACK_IMPORTED_MODULE_1__flatten_js__["a" /* default */])(rest, true, true);
  return Object(__WEBPACK_IMPORTED_MODULE_2__filter_js__["a" /* default */])(array, function(value){
    return !Object(__WEBPACK_IMPORTED_MODULE_3__contains_js__["a" /* default */])(rest, value);
  });
}));


/***/ }),
/* 98 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = uniq;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isBoolean_js__ = __webpack_require__(54);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__getLength_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__contains_js__ = __webpack_require__(28);





// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// The faster algorithm will not work with an iteratee if the iteratee
// is not a one-to-one function, so providing an iteratee will disable
// the faster algorithm.
function uniq(array, isSorted, iteratee, context) {
  if (!Object(__WEBPACK_IMPORTED_MODULE_0__isBoolean_js__["a" /* default */])(isSorted)) {
    context = iteratee;
    iteratee = isSorted;
    isSorted = false;
  }
  if (iteratee != null) iteratee = Object(__WEBPACK_IMPORTED_MODULE_1__cb_js__["a" /* default */])(iteratee, context);
  var result = [];
  var seen = [];
  for (var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_2__getLength_js__["a" /* default */])(array); i < length; i++) {
    var value = array[i],
        computed = iteratee ? iteratee(value, i, array) : value;
    if (isSorted && !iteratee) {
      if (!i || seen !== computed) result.push(value);
      seen = computed;
    } else if (iteratee) {
      if (!Object(__WEBPACK_IMPORTED_MODULE_3__contains_js__["a" /* default */])(seen, computed)) {
        seen.push(computed);
        result.push(value);
      }
    } else if (!Object(__WEBPACK_IMPORTED_MODULE_3__contains_js__["a" /* default */])(result, value)) {
      result.push(value);
    }
  }
  return result;
}


/***/ }),
/* 99 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = unzip;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__max_js__ = __webpack_require__(91);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getLength_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__pluck_js__ = __webpack_require__(49);




// Complement of zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices.
function unzip(array) {
  var length = (array && Object(__WEBPACK_IMPORTED_MODULE_0__max_js__["a" /* default */])(array, __WEBPACK_IMPORTED_MODULE_1__getLength_js__["a" /* default */]).length) || 0;
  var result = Array(length);

  for (var index = 0; index < length; index++) {
    result[index] = Object(__WEBPACK_IMPORTED_MODULE_2__pluck_js__["a" /* default */])(array, index);
  }
  return result;
}


/***/ }),
/* 100 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = chainResult;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);


// Helper function to continue chaining intermediate results.
function chainResult(instance, obj) {
  return instance._chain ? Object(__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */])(obj).chain() : obj;
}


/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_RESULT__;/*

 JS Signals <http://millermedeiros.github.com/js-signals/>
 Released under the MIT license
 Author: Miller Medeiros
 Version: 1.0.0 - Build: 268 (2012/11/29 05:48 PM)
*/
(function (i) {
    function h(a, b, c, d, e) { this._listener = b; this._isOnce = c; this.context = d; this._signal = a; this._priority = e || 0; }
    function g(a, b) { if (typeof a !== "function")
        throw Error("listener is a required param of {fn}() and should be a Function.".replace("{fn}", b)); }
    function e() { this._bindings = []; this._prevParams = null; var a = this; this.dispatch = function () { e.prototype.dispatch.apply(a, arguments); }; }
    h.prototype = { active: !0, params: null, execute: function (a) {
            var b;
            this.active && this._listener && (a = this.params ? this.params.concat(a) :
                a, b = this._listener.apply(this.context, a), this._isOnce && this.detach());
            return b;
        }, detach: function () { return this.isBound() ? this._signal.remove(this._listener, this.context) : null; }, isBound: function () { return !!this._signal && !!this._listener; }, isOnce: function () { return this._isOnce; }, getListener: function () { return this._listener; }, getSignal: function () { return this._signal; }, _destroy: function () { delete this._signal; delete this._listener; delete this.context; }, toString: function () {
            return "[SignalBinding isOnce:" + this._isOnce +
                ", isBound:" + this.isBound() + ", active:" + this.active + "]";
        } };
    e.prototype = { VERSION: "1.0.0", memorize: !1, _shouldPropagate: !0, active: !0, _registerListener: function (a, b, c, d) { var e = this._indexOfListener(a, c); if (e !== -1) {
            if (a = this._bindings[e], a.isOnce() !== b)
                throw Error("You cannot add" + (b ? "" : "Once") + "() then add" + (!b ? "" : "Once") + "() the same listener without removing the relationship first.");
        }
        else
            a = new h(this, a, b, c, d), this._addBinding(a); this.memorize && this._prevParams && a.execute(this._prevParams); return a; },
        _addBinding: function (a) { var b = this._bindings.length; do
            --b;
        while (this._bindings[b] && a._priority <= this._bindings[b]._priority); this._bindings.splice(b + 1, 0, a); }, _indexOfListener: function (a, b) { for (var c = this._bindings.length, d; c--;)
            if (d = this._bindings[c], d._listener === a && d.context === b)
                return c; return -1; }, has: function (a, b) { return this._indexOfListener(a, b) !== -1; }, add: function (a, b, c) { g(a, "add"); return this._registerListener(a, !1, b, c); }, addOnce: function (a, b, c) {
            g(a, "addOnce");
            return this._registerListener(a, !0, b, c);
        }, remove: function (a, b) { g(a, "remove"); var c = this._indexOfListener(a, b); c !== -1 && (this._bindings[c]._destroy(), this._bindings.splice(c, 1)); return a; }, removeAll: function () { for (var a = this._bindings.length; a--;)
            this._bindings[a]._destroy(); this._bindings.length = 0; }, getNumListeners: function () { return this._bindings.length; }, halt: function () { this._shouldPropagate = !1; }, dispatch: function (a) {
            if (this.active) {
                var b = Array.prototype.slice.call(arguments), c = this._bindings.length, d;
                if (this.memorize)
                    this._prevParams =
                        b;
                if (c) {
                    d = this._bindings.slice();
                    this._shouldPropagate = !0;
                    do
                        c--;
                    while (d[c] && this._shouldPropagate && d[c].execute(b) !== !1);
                }
            }
        }, forget: function () { this._prevParams = null; }, dispose: function () { this.removeAll(); delete this._bindings; delete this._prevParams; }, toString: function () { return "[Signal active:" + this.active + " numListeners:" + this.getNumListeners() + "]"; } };
    var f = e;
    f.Signal = e;
     true ? !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return f; }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : typeof module !== "undefined" && module.exports ? module.exports = f : i.signals =
        f;
})(this);
//# sourceMappingURL=data:application/json;base64, 

/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
// Html
var UI = __webpack_require__(50).UI;
UI.Html = function (html) {
    UI.Element.call(this);
    var dom = document.createElement('span');
    dom.className = 'Html';
    dom.style.cursor = 'default';
    dom.style.display = 'inline-block';
    dom.style.verticalAlign = 'middle';
    this.dom = dom;
    this.setValue(html);
    return this;
};
UI.Html.prototype = Object.create(UI.Element.prototype);
UI.Html.prototype.setValue = function (value) {
    if (value !== undefined) {
        this.dom.innerHTML = value;
    }
    return this;
};
// Form
UI.Form = function () {
    UI.Panel.call(this);
    var dom = document.createElement('form');
    dom.className = 'Form';
    dom.method = 'post';
    dom.action = '';
    dom.target = '_blank';
    dom.enctype = 'multipart/form-data';
    this.dom = dom;
    return this;
};
UI.Form.prototype = Object.create(UI.Panel.prototype);
UI.Form.prototype.setMethod = function (value) {
    this.dom.method = value;
    return this;
};
UI.Form.prototype.setAction = function (value) {
    this.dom.action = value;
    return this;
};
UI.Form.prototype.setTarget = function (value) {
    this.dom.target = value;
    return this;
};
UI.Form.prototype.setEnctype = function (value) {
    this.dom.enctype = value;
    return this;
};
// File
UI.File = function () {
    UI.Input.call(this);
    this.dom.className = 'File';
    this.dom.type = 'file';
    this.dom.multiple = false;
    return this;
};
UI.File.prototype = Object.create(UI.Input.prototype);
UI.File.prototype.setMultiple = function (value) {
    this.dom.multiple = value;
    return this;
};
UI.File.prototype.getFiles = function (value) {
    return this.dom.files;
};
// Hidden
UI.Hidden = function () {
    UI.Input.call(this);
    this.dom.type = 'hidden';
    return this;
};
UI.Hidden.prototype = Object.create(UI.Input.prototype);
// Toggle Button
UI.ToggleButton = function (labelA, labelB, callbackA, callbackB) {
    UI.Button.call(this, labelB);
    var flag = true;
    this.onClick(function () {
        if (flag) {
            flag = false;
            this.setLabel(labelA);
            callbackB();
        }
        else {
            flag = true;
            this.setLabel(labelB);
            callbackA();
        }
    }.bind(this));
    return this;
};
UI.ToggleButton.prototype = Object.create(UI.Button.prototype);
// Ellipsis Text
UI.EllipsisText = function (text) {
    UI.Text.call(this, text);
    this.setWhiteSpace('nowrap');
    this.setOverflow('hidden');
    this.setTextOverflow('ellipsis');
    return this;
};
UI.EllipsisText.prototype = Object.create(UI.Text.prototype);
UI.EllipsisText.prototype.setValue = function (value) {
    if (value !== undefined) {
        this.dom.textContent = value;
        this.setTitle(value);
    }
    return this;
};
// Ellipsis Multiline Text
UI.EllipsisMultilineText = function (text) {
    // http://www.mobify.com/blog/multiline-ellipsis-in-pure-css/
    UI.Element.call(this);
    var dom = document.createElement('span');
    dom.className = 'EllipsisMultilineText';
    dom.style.cursor = 'default';
    dom.style.display = 'inline-block';
    dom.style.verticalAlign = 'middle';
    var content = document.createElement('p');
    dom.appendChild(content);
    this.dom = dom;
    this.content = content;
    this.setValue(text);
    return this;
};
UI.EllipsisMultilineText.prototype = Object.create(UI.Element.prototype);
UI.EllipsisMultilineText.prototype.setValue = function (value) {
    if (value !== undefined) {
        this.content.textContent = value;
        this.setTitle(value);
    }
    return this;
};
// Overlay Panel
UI.OverlayPanel = function () {
    UI.Panel.call(this);
    this.dom.className = 'Panel OverlayPanel';
    this.dom.tabIndex = '-1';
    this.dom.style.outline = 'none';
    return this;
};
UI.OverlayPanel.prototype = Object.create(UI.Panel.prototype);
UI.OverlayPanel.prototype.attach = function (node) {
    node = node || document.body;
    node.appendChild(this.dom);
    return this;
};
// Icon (requires font awesome)
UI.Icon = function (value) {
    UI.Panel.call(this);
    var dom = document.createElement('span');
    dom.className = 'Icon fa';
    this.dom = dom;
    if (value)
        this.addClass.apply(this, arguments);
    return this;
};
UI.Icon.prototype = Object.create(UI.Panel.prototype);
UI.Icon.prototype.hasClass = function (value) {
    return this.dom.classList.contains('fa-' + value);
};
UI.Icon.prototype.addClass = function (value) {
    for (var i = 0; i < arguments.length; i++) {
        this.dom.classList.add('fa-' + arguments[i]);
    }
    return this;
};
UI.Icon.prototype.setClass = function (value) {
    this.dom.className = 'Icon fa';
    for (var i = 0; i < arguments.length; i++) {
        this.dom.classList.add('fa-' + arguments[i]);
    }
    return this;
};
UI.Icon.prototype.removeClass = function (value) {
    for (var i = 0; i < arguments.length; i++) {
        this.dom.classList.remove('fa-' + arguments[i]);
    }
    return this;
};
UI.Icon.prototype.switchClass = function (newValue, oldValue) {
    this.removeClass(oldValue, newValue);
    this.addClass(newValue);
    return this;
};
// Toggle Icon
UI.ToggleIcon = function (value, classTrue, classFalse) {
    UI.Icon.call(this, value ? classTrue : classFalse);
    this.value = value;
    this.classTrue = classTrue;
    this.classFalse = classFalse;
    return this;
};
UI.ToggleIcon.prototype = Object.create(UI.Icon.prototype);
UI.ToggleIcon.prototype.setValue = function (value) {
    this.value = value;
    if (value) {
        this.switchClass(this.classTrue, this.classFalse);
    }
    else {
        this.switchClass(this.classFalse, this.classTrue);
    }
    return this;
};
UI.ToggleIcon.prototype.getValue = function () {
    return this.value;
};
// Dispose Icon
UI.DisposeIcon = function () {
    UI.Icon.call(this, 'trash-o');
    var flag = false;
    var scope = this;
    this.setTitle('delete');
    this.setCursor('pointer');
    this.onClick(function () {
        if (flag === true) {
            if (typeof scope.disposeFunction === 'function') {
                scope.disposeFunction();
            }
        }
        else {
            scope.setColor('rgb(178, 34, 34)');
            scope.dom.classList.add('deleteInfo');
            flag = true;
            setTimeout(function () {
                scope.setColor('#888');
                scope.dom.classList.remove('deleteInfo');
                flag = false;
            }, 1500);
        }
    });
    return this;
};
UI.DisposeIcon.prototype = Object.create(UI.Icon.prototype);
UI.DisposeIcon.prototype.setDisposeFunction = function (fn) {
    this.disposeFunction = fn;
    return this;
};
// Progress
UI.Progress = function (max, value) {
    UI.Element.call(this);
    var dom = document.createElement('progress');
    dom.className = 'Progress';
    dom.max = max || 1.0;
    if (value !== undefined)
        dom.value = value;
    this.dom = dom;
    return this;
};
UI.Progress.prototype = Object.create(UI.Element.prototype);
UI.Progress.prototype.getValue = function () {
    return this.dom.value;
};
UI.Progress.prototype.setValue = function (value) {
    this.dom.value = value;
    return this;
};
UI.Progress.prototype.setMax = function (value) {
    this.dom.max = value;
    return this;
};
UI.Progress.prototype.setIndeterminate = function () {
    this.dom.removeAttribute('value');
    return this;
};
// Range
UI.Range = function (min, max, value, step) {
    UI.Element.call(this);
    var dom = document.createElement('input');
    dom.className = 'Range';
    dom.type = 'range';
    dom.min = min.toPrecision(3);
    dom.max = max.toPrecision(3);
    dom.value = value.toPrecision(3);
    dom.step = step.toPrecision(3);
    this.dom = dom;
    return this;
};
UI.Range.prototype = Object.create(UI.Element.prototype);
UI.Range.prototype.getValue = function () {
    return parseFloat(this.dom.value);
};
UI.Range.prototype.setRange = function (min, max) {
    this.dom.min = min;
    this.dom.max = max;
    return this;
};
UI.Range.prototype.setValue = function (value) {
    this.dom.value = value;
    return this;
};
UI.Range.prototype.setStep = function (value) {
    this.dom.step = value;
    return this;
};
// AdaptiveTextArea
UI.AdaptiveTextArea = function () {
    // http://www.brianchu.com/blog/2013/11/02/creating-an-auto-growing-text-input/
    UI.Element.call(this);
    var container = document.createElement('div');
    container.className = 'AdaptiveTextAreaContainer';
    var textarea = document.createElement('textarea');
    textarea.className = 'AdaptiveTextArea';
    var size = document.createElement('div');
    size.className = 'AdaptiveTextAreaSize';
    container.appendChild(textarea);
    container.appendChild(size);
    textarea.addEventListener('input', function (event) {
        size.innerHTML = textarea.value + '\n';
    }, false);
    this.textarea = textarea;
    this.size = size;
    this.dom = container;
    return this;
};
UI.AdaptiveTextArea.prototype = Object.create(UI.Element.prototype);
UI.AdaptiveTextArea.prototype.getValue = function () {
    return this.textarea.value;
};
UI.AdaptiveTextArea.prototype.setValue = function (value) {
    this.textarea.value = value;
    this.size.innerHTML = value + '\n';
    return this;
};
UI.AdaptiveTextArea.prototype.setSpellcheck = function (value) {
    this.textarea.spellcheck = value;
    return this;
};
UI.AdaptiveTextArea.prototype.setBackgroundColor = function (value) {
    this.textarea.style.backgroundColor = value;
    return this;
};
// Virtual List
UI.VirtualList = function (items, itemHeight, height, generatorFn) {
    // based on Virtual DOM List
    // https://github.com/sergi/virtual-list
    // The MIT License (MIT)
    // Copyright (C) 2013 Sergi Mansilla
    UI.Element.call(this);
    items = items || [];
    itemHeight = itemHeight || 20;
    height = height || 300;
    generatorFn = generatorFn || function () { };
    var dom = document.createElement('div');
    dom.className = 'VirtualList';
    dom.style.height = height + 'px';
    var totalRows = items.length;
    var screenItemsCount = Math.ceil(height / itemHeight);
    var cachedItemsCount = screenItemsCount * 3;
    var lastRepaintY;
    var maxBuffer = screenItemsCount * itemHeight;
    var lastScrolled = 0;
    var renderChunkCallback = function () { };
    var list = document.createElement('div');
    list.style.width = '100%';
    list.style.height = height + 'px';
    list.style['overflow-y'] = 'auto';
    list.style.position = 'relative';
    list.style.padding = 0;
    var scroller = document.createElement('div');
    scroller.style.opacity = 0;
    scroller.style.position = 'absolute';
    scroller.style.top = 0;
    scroller.style.left = 0;
    scroller.style.width = '1px';
    scroller.style.height = (itemHeight * totalRows) + 'px';
    function createRow(i) {
        var item = generatorFn(i);
        item.classList.add('VirtualListRow');
        item.style.height = itemHeight + 'px';
        item.style.top = (i * itemHeight) + 'px';
        return item;
    }
    function renderChunk(from) {
        var finalItem = Math.min(totalRows, from + cachedItemsCount);
        renderChunkCallback(from, finalItem);
        // Append all the new rows in a document fragment
        // that we will later append to the parent node
        var fragment = document.createDocumentFragment();
        for (var i = from; i < finalItem; i++) {
            fragment.appendChild(createRow(i));
        }
        // Hide and mark obsolete nodes for deletion.
        for (var j = 1, l = list.childNodes.length; j < l; j++) {
            list.childNodes[j].style.display = 'none';
            list.childNodes[j].setAttribute('data-rm', '1');
        }
        list.appendChild(fragment);
    }
    ;
    // As soon as scrolling has stopped, this interval asynchronously
    // removes all the nodes that are not used anymore
    var rmNodeInterval = setInterval(function () {
        // check if list is still attached to dom
        var element = dom;
        while (element !== document && element.parentNode) {
            element = element.parentNode;
        }
        // if list not attached to dom, clear interval
        if (element !== document) {
            clearInterval(rmNodeInterval);
        }
        // remove tagged nodes
        if (Date.now() - lastScrolled > 100) {
            var badNodes = list.querySelectorAll('[data-rm="1"]');
            for (var i = 0, l = badNodes.length; i < l; i++) {
                list.removeChild(badNodes[i]);
            }
        }
    }, 500);
    function onScroll(e) {
        var scrollTop = e.target.scrollTop; // Triggers reflow
        if (!lastRepaintY || Math.abs(scrollTop - lastRepaintY) > maxBuffer) {
            var first = Math.floor(scrollTop / itemHeight);
            renderChunk(Math.max(0, first - screenItemsCount));
            lastRepaintY = scrollTop;
        }
        lastScrolled = Date.now();
        e.preventDefault && e.preventDefault();
    }
    // API
    this.setItems = function (value) {
        items = value;
        totalRows = items.length;
        scroller.style.height = (itemHeight * totalRows) + 'px';
        renderChunk(0);
        return this;
    };
    this.setItemHeight = function (value) {
        itemHeight = value;
        screenItemsCount = Math.ceil(height / itemHeight);
        cachedItemsCount = screenItemsCount * 3;
        maxBuffer = screenItemsCount * itemHeight;
        scroller.style.height = (itemHeight * totalRows) + 'px';
        renderChunk(0);
        return this;
    };
    this.setHeight = function (value) {
        UI.Element.prototype.setHeight.call(this, value + 'px');
        height = value;
        screenItemsCount = Math.ceil(height / itemHeight);
        cachedItemsCount = screenItemsCount * 3;
        maxBuffer = screenItemsCount * itemHeight;
        list.style.height = height + 'px';
        scroller.style.height = height + 'px';
        renderChunk(0);
        return this;
    };
    this.setGeneratorFn = function (value) {
        generatorFn = value;
        renderChunk(0);
        return this;
    };
    this.setRenderChunkCallback = function (value) {
        renderChunkCallback = value;
    };
    this.redraw = function () {
        var first = Math.floor(list.scrollTop / itemHeight);
        renderChunk(Math.max(0, first - screenItemsCount));
        lastRepaintY = list.scrollTop;
        return this;
    };
    //
    list.appendChild(scroller);
    dom.appendChild(list);
    list.addEventListener('scroll', onScroll);
    renderChunk(0);
    this.dom = dom;
    return this;
};
UI.VirtualList.prototype = Object.create(UI.Element.prototype);
// Virtual Table
UI.VirtualTable = function (items, itemHeight, height, columns, params) {
    var p = params || {};
    UI.Panel.call(this);
    // this.setOverflow( "scroll" );
    var defaultWidth = p.defaultWidth !== undefined ? p.defaultWidth : 30;
    var defaultMargin = p.defaultMargin !== undefined ? p.defaultMargin : 5;
    var defaultAlign = p.defaultAlign !== undefined ? p.defaultAlign : 'left';
    var onRowSelect = p.onRowSelect;
    // header
    var header = new UI.Panel()
        .setWhiteSpace('nowrap')
        .setDisplay('inline-block')
        .setOverflow('')
        .setWidth('100%');
    var fullWidth = 0;
    var selected = [];
    var numericalSort = function (a, b) {
        return a - b;
    };
    var lexicalSort = function (a, b) {
        return a.localeCompare(b);
    };
    var sortColumn = function (idx, flag) {
        var sort;
        if (typeof items[0][idx] === 'string') {
            sort = lexicalSort;
        }
        else {
            sort = numericalSort;
        }
        items.sort(function (a, b) {
            if (flag) {
                return sort(b[idx], a[idx]);
            }
            else {
                return sort(a[idx], b[idx]);
            }
        });
        virtualList.redraw();
        return this;
    };
    var selectRow = function (event, idx) {
        selected.length = 0;
        if (onRowSelect)
            onRowSelect(event, idx);
        if (idx !== undefined) {
            selected.push(items[idx][0]);
        }
        virtualList.redraw();
        return this;
    };
    columns.forEach(function (col) {
        var width = col.width || defaultWidth;
        var margin = col.margin || defaultMargin;
        var text = new UI.EllipsisText()
            .setValue(col.name)
            .setWidth(width + 'px')
            .setTextAlign(col.align || defaultAlign)
            .setMarginLeft(margin + 'px')
            .setMarginRight(margin + 'px')
            .setCursor('pointer')
            .onClick(function (e) {
            var flag = col.__sortFlag === 'ASC';
            sortColumn(col.index, flag);
            if (flag) {
                col.__sortFlag = 'DESC';
            }
            else {
                col.__sortFlag = 'ASC';
            }
        });
        header.add(text);
        fullWidth += width + 2 * margin;
    });
    // list
    var generatorFn = function (index) {
        var panel = new UI.Panel();
        columns.forEach(function (col) {
            var value = items[index][col.index];
            if (col.format)
                value = col.format(value);
            var width = col.width || defaultWidth;
            var margin = col.margin || defaultMargin;
            var element;
            if (typeof value === 'object') {
                element = value;
            }
            else {
                element = new UI.Text()
                    .setValue(value);
            }
            element
                .setWidth(width + 'px')
                .setTextAlign(col.align || defaultAlign)
                .setMarginLeft(margin + 'px')
                .setMarginRight(margin + 'px')
                .onClick(function (event) {
                if (typeof col.onClick === 'function') {
                    col.onClick(event, index, value);
                }
            })
                .onMouseOver(function (event) {
                if (typeof col.onMouseOver === 'function') {
                    col.onMouseOver(event, index, value);
                }
            })
                .onMouseOut(function (event) {
                if (typeof col.onMouseOut === 'function') {
                    col.onMouseOut(event, index, value);
                }
            });
            panel.add(element);
        });
        panel
            .setCursor('pointer')
            .onClick(function (event) {
            selectRow(event, index);
        });
        if (selected.indexOf(items[index][0]) !== -1) {
            panel.dom.classList.add('highlight');
        }
        return panel.dom;
    };
    var virtualList = new UI.VirtualList(items, itemHeight, height, generatorFn).setWidth((fullWidth + 20) + 'px');
    //
    this.add(header, virtualList);
    // API
    this.header = header;
    this.list = virtualList;
    this.sortColumn = sortColumn;
    this.selectRow = function (idx) {
        selectRow(undefined, idx);
    };
    return this;
};
UI.VirtualTable.prototype = Object.create(UI.Panel.prototype);
UI.PopupMenu = function (iconClass, heading, constraintTo) {
    constraintTo = constraintTo || 'scrollParent';
    UI.Panel.call(this);
    var entryLabelWidth = '100px';
    var icon = new UI.Icon(iconClass || 'bars');
    var panel = new UI.OverlayPanel()
        .setDisplay('none')
        .attach(this.dom);
    var xOffset = 0;
    var yOffset = 0;
    var prevX = 0;
    var prevY = 0;
    function onMousemove(e) {
        if (prevX === 0) {
            prevX = e.clientX;
            prevY = e.clientY;
        }
        xOffset += prevX - e.clientX;
        yOffset += prevY - e.clientY;
        prevX = e.clientX;
        prevY = e.clientY;
    }
    var headingPanel = new UI.Panel()
        .setBorderBottom('1px solid #555')
        .setMarginBottom('10px')
        .setHeight('25px')
        .setCursor('move')
        .onMouseDown(function (e) {
        if (e.which === 1) {
            document.addEventListener('mousemove', onMousemove);
        }
        document.addEventListener('mouseup', function (e) {
            document.removeEventListener('mousemove', onMousemove);
        });
    });
    headingPanel
        .add(new UI.Icon('times')
        .setFloat('right')
        .setCursor('pointer')
        .onClick(function () {
        this.setMenuDisplay('none');
    }.bind(this)))
        .add(new UI.Text(heading));
    panel.add(headingPanel);
    icon.setTitle('menu');
    icon.setCursor('pointer');
    icon.onClick(function (e) {
        if (panel.getDisplay() === 'block') {
            this.setMenuDisplay('none');
            return;
        }
        panel.setMaxHeight((window.innerHeight / 1.2) + 'px');
        this.setMenuDisplay('block');
        xOffset = 5;
        yOffset = 0;
    }.bind(this));
    this.add(icon);
    this.setClass('')
        .setDisplay('inline');
    this.icon = icon;
    this.panel = panel;
    this.entryLabelWidth = entryLabelWidth;
    return this;
};
UI.PopupMenu.prototype = Object.create(UI.Panel.prototype);
UI.PopupMenu.prototype.addEntry = function (label, entry) {
    this.panel
        .add(new UI.Text(label)
        // .setWhiteSpace( "nowrap" )
        .setWidth(this.entryLabelWidth))
        .add(entry || new UI.Panel())
        .add(new UI.Break());
    return this;
};
UI.PopupMenu.prototype.setEntryLabelWidth = function (value) {
    this.entryLabelWidth = value;
    return this;
};
UI.PopupMenu.prototype.setMenuDisplay = function (value) {
    this.panel.setDisplay(value);
    if (value !== 'none')
        this.panel.dom.focus();
    return this;
};
UI.PopupMenu.prototype.setIconTitle = function (value) {
    this.icon.setTitle(value);
    return this;
};
UI.PopupMenu.prototype.dispose = function () {
    this.panel.dispose();
    UI.Element.prototype.dispose.call(this);
};
// Collapsible Icon Panel
UI.CollapsibleIconPanel = function (iconClass1, iconClass2) {
    UI.Panel.call(this);
    this.dom.className = 'Panel CollapsiblePanel';
    if (iconClass1 === undefined) {
        // iconClass1 = iconClass1 || "plus-square";
        // iconClass2 = iconClass2 || "minus-square";
        iconClass1 = iconClass1 || 'chevron-down';
        iconClass2 = iconClass2 || 'chevron-right';
    }
    this.button = new UI.Icon(iconClass1)
        .setTitle('expand/collapse')
        .setCursor('pointer')
        .setWidth('12px')
        .setMarginRight('6px');
    this.addStatic(this.button);
    var scope = this;
    this.button.dom.addEventListener('click', function (event) {
        scope.toggle();
    }, false);
    this.content = document.createElement('div');
    this.content.className = 'CollapsibleContent';
    this.dom.appendChild(this.content);
    this.isCollapsed = false;
    this.iconClass1 = iconClass1;
    this.iconClass2 = iconClass2;
    return this;
};
UI.CollapsibleIconPanel.prototype = Object.create(UI.CollapsiblePanel.prototype);
UI.CollapsibleIconPanel.prototype.setCollapsed = function (setCollapsed) {
    if (setCollapsed) {
        this.dom.classList.add('collapsed');
        if (this.iconClass2) {
            this.button.switchClass(this.iconClass2, this.iconClass1);
        }
        else {
            this.button.addClass('rotate-90');
        }
    }
    else {
        this.dom.classList.remove('collapsed');
        if (this.iconClass2) {
            this.button.switchClass(this.iconClass1, this.iconClass2);
        }
        else {
            this.button.removeClass('rotate-90');
        }
    }
    this.isCollapsed = setCollapsed;
};
// Color picker (requires FlexiColorPicker)
// https://github.com/DavidDurman/FlexiColorPicker
// https://github.com/zvin/FlexiColorPicker
UI.ColorPicker = function () {
    var scope = this;
    UI.Panel.call(this);
    // slider
    this.slideWrapper = new UI.Panel()
        .setClass('slide-wrapper');
    this.sliderIndicator = new UI.Panel()
        .setClass('slide-indicator');
    this.slider = new UI.Panel()
        .setClass('slide')
        .setWidth('25px')
        .setHeight('80px');
    this.slideWrapper.add(this.slider, this.sliderIndicator);
    // picker
    this.pickerWrapper = new UI.Panel()
        .setClass('picker-wrapper');
    this.pickerIndicator = new UI.Panel()
        .setClass('picker-indicator');
    this.picker = new UI.Panel()
        .setClass('picker')
        .setWidth('130px')
        .setHeight('80px');
    this.pickerWrapper.add(this.picker, this.pickerIndicator);
    // event
    var changeEvent = document.createEvent('Event');
    changeEvent.initEvent('change', true, true);
    // finalize
    this.add(this.pickerWrapper, this.slideWrapper);
    this.colorPicker = ColorPicker(this.slider.dom, this.picker.dom, function (hex, hsv, rgb, pickerCoordinate, sliderCoordinate) {
        if (!pickerCoordinate && sliderCoordinate && hsv.s < 0.05) {
            hsv.s = 0.5;
            hsv.v = 0.7;
            scope.colorPicker.setHsv(hsv);
            return;
        }
        ColorPicker.positionIndicators(scope.sliderIndicator.dom, scope.pickerIndicator.dom, sliderCoordinate, pickerCoordinate);
        scope.hex = hex;
        scope.hsv = hsv;
        scope.rgb = rgb;
        if (!scope._settingValue) {
            scope.dom.dispatchEvent(changeEvent);
        }
    });
    this.colorPicker.fixIndicators(this.sliderIndicator.dom, this.pickerIndicator.dom);
    return this;
};
UI.ColorPicker.prototype = Object.create(UI.Panel.prototype);
UI.ColorPicker.prototype.setValue = function (value) {
    if (value !== this.hex) {
        this._settingValue = true;
        this.colorPicker.setHex(value);
        this._settingValue = false;
    }
    return this;
};
UI.ColorPicker.prototype.getValue = function () {
    return this.hex;
};
module.exports = {
    "UI": UI
};
//# sourceMappingURL=data:application/json;base64, 

/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Keycode 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.ui.keyCode = {
	BACKSPACE: 8,
	COMMA: 188,
	DELETE: 46,
	DOWN: 40,
	END: 35,
	ENTER: 13,
	ESCAPE: 27,
	HOME: 36,
	LEFT: 37,
	PAGE_DOWN: 34,
	PAGE_UP: 33,
	PERIOD: 190,
	RIGHT: 39,
	SPACE: 32,
	TAB: 9,
	UP: 38
};

} );


/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

// $.ui.plugin is deprecated. Use $.widget() extensions instead.
return $.ui.plugin = {
	add: function( module, option, set ) {
		var i,
			proto = $.ui[ module ].prototype;
		for ( i in set ) {
			proto.plugins[ i ] = proto.plugins[ i ] || [];
			proto.plugins[ i ].push( [ option, set[ i ] ] );
		}
	},
	call: function( instance, name, args, allowDisconnected ) {
		var i,
			set = instance.plugins[ name ];

		if ( !set ) {
			return;
		}

		if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode ||
				instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
			return;
		}

		for ( i = 0; i < set.length; i++ ) {
			if ( instance.options[ set[ i ][ 0 ] ] ) {
				set[ i ][ 1 ].apply( instance.element, args );
			}
		}
	}
};

} );


/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.ui.safeActiveElement = function( document ) {
	var activeElement;

	// Support: IE 9 only
	// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
	try {
		activeElement = document.activeElement;
	} catch ( error ) {
		activeElement = document.body;
	}

	// Support: IE 9 - 11 only
	// IE may return null instead of an element
	// Interestingly, this only seems to occur when NOT in an iframe
	if ( !activeElement ) {
		activeElement = document.body;
	}

	// Support: IE 11 only
	// IE11 returns a seemingly empty object in some cases when accessing
	// document.activeElement from an <iframe>
	if ( !activeElement.nodeName ) {
		activeElement = document.body;
	}

	return activeElement;
};

} );


/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.ui.safeBlur = function( element ) {

	// Support: IE9 - 10 only
	// If the <body> is blurred, IE will switch windows, see #9420
	if ( element && element.nodeName.toLowerCase() !== "body" ) {
		$( element ).trigger( "blur" );
	}
};

} );


/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Focusable 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :focusable Selector
//>>group: Core
//>>description: Selects elements which can be focused.
//>>docs: http://api.jqueryui.com/focusable-selector/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

// Selectors
$.ui.focusable = function( element, hasTabindex ) {
	var map, mapName, img, focusableIfVisible, fieldset,
		nodeName = element.nodeName.toLowerCase();

	if ( "area" === nodeName ) {
		map = element.parentNode;
		mapName = map.name;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap='#" + mapName + "']" );
		return img.length > 0 && img.is( ":visible" );
	}

	if ( /^(input|select|textarea|button|object)$/.test( nodeName ) ) {
		focusableIfVisible = !element.disabled;

		if ( focusableIfVisible ) {

			// Form controls within a disabled fieldset are disabled.
			// However, controls within the fieldset's legend do not get disabled.
			// Since controls generally aren't placed inside legends, we skip
			// this portion of the check.
			fieldset = $( element ).closest( "fieldset" )[ 0 ];
			if ( fieldset ) {
				focusableIfVisible = !fieldset.disabled;
			}
		}
	} else if ( "a" === nodeName ) {
		focusableIfVisible = element.href || hasTabindex;
	} else {
		focusableIfVisible = hasTabindex;
	}

	return focusableIfVisible && $( element ).is( ":visible" ) && visible( $( element ) );
};

// Support: IE 8 only
// IE 8 doesn't resolve inherit to visible/hidden for computed values
function visible( element ) {
	var visibility = element.css( "visibility" );
	while ( visibility === "inherit" ) {
		element = element.parent();
		visibility = element.css( "visibility" );
	}
	return visibility === "visible";
}

$.extend( $.expr.pseudos, {
	focusable: function( element ) {
		return $.ui.focusable( element, $.attr( element, "tabindex" ) != null );
	}
} );

return $.ui.focusable;

} );


/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "f83a8b8886694eaef4505dd80af7a430.png";

/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = {};
var loadedModules = [
    __webpack_require__(110),
];
for (var i in loadedModules) {
    if (loadedModules && Object.prototype.hasOwnProperty.call(loadedModules, i)) {
        var loadedModule = loadedModules[i];
        for (var target_name in loadedModule) {
            if (loadedModule && Object.prototype.hasOwnProperty.call(loadedModule, target_name)) {
                module.exports[target_name] = loadedModule[target_name];
            }
        }
    }
}
module.exports['version'] = __webpack_require__(12).version;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsTUFBTSxDQUFDLE9BQU8sR0FBRyxFQUFFLENBQUM7QUFFcEIsSUFBSSxhQUFhLEdBQUc7SUFDaEIsT0FBTyxDQUFDLGlCQUFpQixDQUFDO0NBQzdCLENBQUE7QUFFRCxLQUFLLElBQUksQ0FBQyxJQUFJLGFBQWEsRUFBRTtJQUN6QixJQUFJLGFBQWEsSUFBSSxNQUFNLENBQUMsU0FBUyxDQUFDLGNBQWMsQ0FBQyxJQUFJLENBQUMsYUFBYSxFQUFFLENBQUMsQ0FBQyxFQUFFO1FBQ3pFLElBQUksWUFBWSxHQUFHLGFBQWEsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUNwQyxLQUFLLElBQUksV0FBVyxJQUFJLFlBQVksRUFBRTtZQUNsQyxJQUFJLFlBQVksSUFBSSxNQUFNLENBQUMsU0FBUyxDQUFDLGNBQWMsQ0FBQyxJQUFJLENBQUMsWUFBWSxFQUFFLFdBQVcsQ0FBQyxFQUFFO2dCQUNqRixNQUFNLENBQUMsT0FBTyxDQUFDLFdBQVcsQ0FBQyxHQUFHLFlBQVksQ0FBQyxXQUFXLENBQUMsQ0FBQzthQUMzRDtTQUNKO0tBQ0o7Q0FDSjtBQUVELE1BQU0sQ0FBQyxPQUFPLENBQUMsU0FBUyxDQUFDLEdBQUcsT0FBTyxDQUFDLGlCQUFpQixDQUFDLENBQUMsT0FBTyxDQUFDIn0=

/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NGLView = exports.NGLModel = void 0;
var Jupyter;
var widgets = __webpack_require__(22);
var NGL = __webpack_require__(18);
var BaseView = __webpack_require__(29).BaseView;
const $ = __webpack_require__(0);
const _ = __webpack_require__(34);
__webpack_require__(101);
__webpack_require__(187);
__webpack_require__(50);
__webpack_require__(102);
__webpack_require__(188);
__webpack_require__(189); // FIXME: remove?
__webpack_require__(205); // FIXME: remove?
const gui_1 = __webpack_require__(234);
const fullscreen_1 = __webpack_require__(235);
const color_1 = __webpack_require__(236);
const theme_1 = __webpack_require__(237);
NGL.nglview_debug = false;
// From NGL
// http://www.broofa.com/Tools/Math.uuid.htm
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
const uuid = new Array(36);
function generateUUID() {
    let rnd = 0;
    let r;
    for (let i = 0; i < 36; i++) {
        if (i === 8 || i === 13 || i === 18 || i === 23) {
            uuid[i] = '-';
        }
        else if (i === 14) {
            uuid[i] = '4';
        }
        else {
            if (rnd <= 0x02)
                rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
            r = rnd & 0xf;
            rnd = rnd >> 4;
            uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r];
        }
    }
    return uuid.join('');
}
function createView(that, trait_name) {
    return __awaiter(this, void 0, void 0, function* () {
        // Create a view for the model with given `trait_name`
        // e.g: in backend, 'view.<trait_name>`
        console.log("Creating view for model " + trait_name);
        var manager = that.model.widget_manager;
        var model_id = that.model.get(trait_name).replace("IPY_MODEL_", "");
        return yield manager.create_view(yield manager.get_model(model_id));
    });
}
class NGLModel extends widgets.DOMWidgetModel {
    defaults() {
        return _.extend(widgets.DOMWidgetModel.prototype.defaults(), {
            _model_name: 'NGLModel',
            _model_module: 'nglview-js-widgets',
            _model_module_version: __webpack_require__(12).version,
            _view_name: "NGLView",
            _view_module: "nglview-js-widgets",
            _view_module_version: __webpack_require__(12).version,
        });
    }
}
exports.NGLModel = NGLModel;
class NGLView extends widgets.DOMWidgetView {
    render() {
        this.beforeDisplay();
        this.displayed.then(function () {
            // move all below code inside 'displayed'
            // to make sure the NGLView and NGLModel are created
            this.createStage();
            this.handlePicking();
            this.handleSignals();
            this.handleMessage();
            this.finalizeDisplay();
        }.bind(this));
    }
    beforeDisplay() {
        this.model.on("change:_parameters", this.parametersChanged, this);
        this.model.on("change:gui_style", this.GUIStyleChanged, this);
        this.model.set('_ngl_version', NGL.Version);
        this._ngl_focused = 0;
        this.uuid = generateUUID();
        this.stage_widget = undefined;
        this.comp_uuids = [];
        this._synced_model_ids = this.model.get("_synced_model_ids");
        this._synced_repr_model_ids = this.model.get("_synced_repr_model_ids");
        if (this.isEmbeded()) {
            // embed mode
            this._handleEmbedBeforeStage();
        }
    }
    createStage() {
        // init NGL stage
        var stage_params = Object.assign({}, this.model.get("_ngl_full_stage_parameters"));
        if (!("backgroundColor" in stage_params)) {
            stage_params["backgroundColor"] = "white";
        }
        NGL.useWorker = false;
        var view_parent = this.options.parent;
        this.stage = new NGL.Stage(undefined);
        this.$container = $(this.stage.viewer.container);
        this.$el.append(this.$container);
        this.stage.setParameters(stage_params);
        this.$container = $(this.stage.viewer.container);
        this.handleResizable();
        this.ngl_view_id = this.uuid;
        this.touch();
        var that = this;
        var width = this.model.get("_view_width") || this.$el.parent().width() + "px";
        var height = this.model.get("_view_height") || "300px";
        this.setSize(width, height);
        this.createFullscreenBtn(); // FIXME: move up?
        this.createIPlayer(); // FIXME: move up?
        this.GUIStyleChanged(); // must be called after displaying to get correct width and height
        this.$container.resizable("option", "maxWidth", this.$el.parent().width());
        if (this.isEmbeded()) {
            console.log("Embed mode for NGLView");
            that.handleEmbed();
        }
        else {
            this.requestUpdateStageParameters();
            if (this.model.views.length == 1) {
                this.serialize_camera_orientation();
            }
            else {
                this.set_camera_orientation(that.model.get("_camera_orientation"));
            }
        }
    }
    isEmbeded() {
        return (this.model.get("_ngl_serialize") || (this.model.comm == undefined));
    }
    handleMessage() {
        this.model.on("msg:custom", function (msg) {
            this.on_msg(msg);
        }, this);
        if (this.model.comm) {
            this.model.comm.on_msg(function (msg) {
                var buffers = msg.buffers;
                var content = msg.content.data.content;
                if (buffers.length && content) {
                    content.buffers = buffers;
                }
                this.model._handle_comm_msg.call(this.model, msg);
            }.bind(this));
        }
    }
    finalizeDisplay() {
        // for callbacks from Python
        // must be after initializing NGL.Stage
        this.send({
            'type': 'request_loaded',
            'data': true
        });
        var state_params = this.stage.getParameters();
        this.model.set('_ngl_original_stage_parameters', state_params);
        this.touch();
        if (!this.isEmbeded() && this.stage.compList.length < this.model.get("n_components")) {
            // only call this in notebook to avoid calling handleEmbed twice in embeded mode.
            this.handleEmbed();
        }
        var ngl_view_ids = this.model.get("_ngl_view_id");
        ngl_view_ids.push(this.ngl_view_id);
        this.send({ "type": "updateIDs", "data": ngl_view_ids });
        // FIXME: Why below doesn't update _ngl_view_id in backend?
        // this.model.set("_ngl_view_id", ngl_view_ids)
        // this.touch()
    }
    handleSignals() {
        var container = this.stage.viewer.container;
        var that = this;
        container.addEventListener('mouseover', function (e) {
            that._ngl_focused = 1;
            e; // linter
            that.mouseOverDisplay('block');
        }, false);
        container.addEventListener('mouseout', function (e) {
            that._ngl_focused = 0;
            e; // linter
            that.mouseOverDisplay('none');
        }, false);
        container.addEventListener('contextmenu', function (e) {
            e.stopPropagation();
            e.preventDefault();
        }, true);
        this.stage.signals.componentAdded.add(function (component) {
            this.comp_uuids.push(component.uuid);
            var len = this.stage.compList.length;
            this.model.set("n_components", len);
            this.touch();
            var comp = this.stage.compList[len - 1];
            comp.signals.representationRemoved.add(function () {
                that.request_repr_dict();
            });
            comp.signals.representationAdded.add(function (repr) {
                that.request_repr_dict();
                repr.signals.parametersChanged.add(function () {
                    console.log("repr.parametersChanged");
                    that.request_repr_dict();
                });
            });
        }, this);
        this.stage.signals.componentRemoved.add(function (component) {
            return __awaiter(this, void 0, void 0, function* () {
                var that = this;
                var cindex = this.comp_uuids.indexOf(component.uuid);
                this.comp_uuids.splice(cindex, 1);
                var n_components = this.stage.compList.length;
                this.model.set("n_components", n_components);
                this.touch();
                console.log('componentRemoved', component, component.uuid);
                var pviews = [];
                for (var k in this.model.views) {
                    pviews.push(this.model.views[k]);
                }
                var views = yield Promise.all(pviews);
                console.log(views);
                var update_backend = false;
                for (var k in views) {
                    var view = views[k];
                    if ((view.uuid != that.uuid) && (view.stage.compList.length > n_components)) {
                        // remove component from NGL's GUI
                        // pass
                        view.stage.removeComponent(view.stage.compList[cindex]);
                        update_backend = true;
                    }
                }
                if (update_backend) {
                    console.log("should update backend");
                    that.send({ "type": "removeComponent", "data": cindex });
                }
            });
        }, this);
        this.stage.signals.parametersChanged.add(function () {
            this.requestUpdateStageParameters();
        }, this);
        this.stage.viewerControls.signals.changed.add(function () {
            this.serialize_camera_orientation();
            var m = this.stage.viewerControls.getOrientation();
            if (that._synced_model_ids.length > 0 && that._ngl_focused == 1) {
                that._synced_model_ids.forEach(function (mid) {
                    return __awaiter(this, void 0, void 0, function* () {
                        var model = yield that.model.widget_manager.get_model(mid);
                        for (var k in model.views) {
                            var pview = model.views[k];
                            var view = yield model.views[k];
                            if (view.uuid != that.uuid) {
                                view.stage.viewerControls.orient(m);
                            }
                        }
                    });
                });
            }
        }.bind(this));
    }
    handlePicking() {
        this.$pickingInfo = $("<div></div>")
            .css("position", "absolute")
            .css("top", "5%")
            .css("left", "3%")
            .css("background-color", "white")
            .css("padding", "2px 5px 2px 5px")
            .css("opacity", "0.7")
            .appendTo(this.$container);
        var that = this;
        this.stage.signals.clicked.add(function (pd) {
            if (pd) {
                this.model.set('picked', {}); //refresh signal
                this.touch();
                var pd2 = {};
                var pickingText = "";
                if (pd.atom) {
                    pd2.atom1 = pd.atom.toObject();
                    pd2.atom1.name = pd.atom.qualifiedName();
                    pickingText = "Atom: " + pd2.atom1.name;
                }
                else if (pd.bond) {
                    pd2.bond = pd.bond.toObject();
                    pd2.atom1 = pd.bond.atom1.toObject();
                    pd2.atom1.name = pd.bond.atom1.qualifiedName();
                    pd2.atom2 = pd.bond.atom2.toObject();
                    pd2.atom2.name = pd.bond.atom2.qualifiedName();
                    pickingText = "Bond: " + pd2.atom1.name + " - " + pd2.atom2.name;
                }
                if (pd.instance)
                    pd2.instance = pd.instance;
                var n_components = this.stage.compList.length;
                for (var i = 0; i < n_components; i++) {
                    var comp = this.stage.compList[i];
                    if (comp.uuid == pd.component.uuid) {
                        pd2.component = i;
                    }
                }
                this.model.set('picked', pd2);
                this.touch();
                this.$pickingInfo.text(pickingText);
            }
        }, this);
    }
    mouseOverDisplay(type) {
        return __awaiter(this, void 0, void 0, function* () {
            var that = this;
            if (this.btn_pview_fullscreen) {
                var btn = yield this.btn_pview_fullscreen;
                btn.el.style.display = type;
                if (that.stage_widget) {
                    // If NGL's GUI exists, use its fullscreen button.
                    btn.el.style.display = 'none';
                }
            }
            var that = this;
            if (this.player_pview) {
                var v = yield this.player_pview;
                v.el.style.display = type;
                // Need to check if max_frame is available (otherwise NaN)
                // https://github.com/jupyter-widgets/ipywidgets/issues/2485
                if (!that.model.get("max_frame") || (that.model.get("max_frame") == 0)) {
                    // always hide if there's no trajectory.
                    v.el.style.display = 'none';
                }
            }
        });
    }
    updateNGLTheme(css_content) {
        var ele = document.getElementById("nglview_style");
        if (ele != undefined) {
            document.head.removeChild(ele);
        }
        var style = document.createElement("style");
        style.id = 'nglview_style';
        style.type = 'text/css';
        style.appendChild(document.createTextNode(css_content));
        document.head.appendChild(style);
    }
    serialize_camera_orientation() {
        var m = this.stage.viewerControls.getOrientation();
        this.model.set('_camera_orientation', m.elements);
        this.touch();
    }
    set_camera_orientation(orientation) {
        if (orientation.length > 0) {
            this.stage.viewerControls.orient(orientation);
            this.serialize_camera_orientation();
        }
    }
    executeCode(code) {
        eval(code);
    }
    _handleEmbedBeforeStage() {
        // Only need to reconstruct colors in embeding mode (outside notebook)
        // FIXME: remove this function
        var that = this;
        var ngl_color_dict = that.model.get("_ngl_color_dict");
        var label;
        // Old API (_ColorScheme)
        for (label in ngl_color_dict) {
            if (!NGL.ColormakerRegistry.hasScheme(label)) {
                that.addColorScheme(ngl_color_dict[label], label);
            }
        }
    }
    handleEmbed() {
        return __awaiter(this, void 0, void 0, function* () {
            var that = this;
            var ngl_msg_archive = that.model.get("_ngl_msg_archive");
            var ngl_stage_params = that.model.get('_ngl_full_stage_parameters');
            const camera_orientation = that.model.get("_camera_orientation");
            if (Object.keys(ngl_stage_params).length === 0
                && camera_orientation.length === 0) {
                console.log("No state stored; initializing embedded widget for the first time.");
                for (const msg of ngl_msg_archive) {
                    yield that.on_msg(msg);
                }
                return;
            }
            var loadfile_list = [];
            _.each(ngl_msg_archive, function (msg) {
                if (msg.methodName == 'loadFile') {
                    if (msg.kwargs && msg.kwargs.defaultRepresentation) {
                        // no need to add default representation as all representations
                        // are serialized separately, also it unwantedly sets the orientation
                        msg.kwargs.defaultRepresentation = false;
                    }
                    loadfile_list.push(that._getLoadFilePromise(msg));
                }
            });
            var compList = yield Promise.all(loadfile_list);
            that.stage.setParameters(ngl_stage_params);
            that.set_camera_orientation(camera_orientation);
            that.touch();
            // Outside notebook
            if (that.model.comm === undefined) {
                var ngl_coordinate_resource = that.model.get("_ngl_coordinate_resource");
                var n_frames = ngl_coordinate_resource['n_frames'] || 1;
                that.model.set("max_frame", n_frames - 1); // trigger updating slider and player's max
                that.touch();
                var model = yield that.getPlayerModel();
                var pmodel = model.get("children")[0];
                that.listenTo(pmodel, "change:value", function () {
                    that.updateCoordinatesFromDict(ngl_coordinate_resource, pmodel.get("value"));
                });
            }
            // fire any msg with "fire_embed"
            for (const msg of that.model.get("_ngl_msg_archive")) {
                if (msg.fire_embed) {
                    yield that.on_msg(msg);
                }
            }
            // Must call _set_representation_from_repr_dict after "fire_embed"
            // User might add Shape (buffer component) to the view and the buffer component
            // is not created yet via loadFile
            // https://github.com/nglviewer/nglview/issues/1003
            that._set_representation_from_repr_dict(that.model.get("_ngl_repr_dict"));
            that.handleResize(); // FIXME: really need this?
        });
    }
    updateCoordinatesFromDict(cdict, frame_index) {
        // update coordinates for given "index"
        // cdict = Dict[int, List[base64]]
        var keys = Object.keys(cdict).filter(k => (k !== 'n_frames'));
        for (var i = 0; i < keys.length; i++) {
            var traj_index = keys[i];
            var coordinates = this.decode_base64(cdict[traj_index][frame_index]);
            if (coordinates && coordinates.byteLength > 0) {
                this.updateCoordinates(coordinates, traj_index);
            }
        }
    }
    requestFrame() {
        this.send({
            'type': 'request_frame',
            'data': 'frame'
        });
    }
    requestUpdateStageParameters() {
        var updated_params = this.stage.getParameters();
        this.model.set('_ngl_full_stage_parameters', updated_params);
        this.touch();
    }
    requestReprParameters(component_index, repr_index) {
        var comp = this.stage.compList[component_index];
        var repr = comp.reprList[repr_index];
        var msg = repr.repr.getParameters();
        if (msg) {
            msg['name'] = repr.name;
            this.send({
                'type': 'repr_parameters',
                'data': msg
            });
        }
    }
    request_repr_dict() {
        var repr_dict = this.getReprDictFrontEnd();
        this.send({
            // make sure we are using "request_repr_dict" name
            // in backend too.
            'type': 'request_repr_dict',
            'data': repr_dict,
        });
        var that = this;
        if (that._synced_repr_model_ids.length > 0) {
            that._synced_repr_model_ids.forEach(function (mid) {
                return __awaiter(this, void 0, void 0, function* () {
                    var model = yield that.model.widget_manager.get_model(mid);
                    for (var k in model.views) {
                        var view = yield model.views[k];
                        // not sync with itself
                        if (view.uuid != that.uuid) {
                            view._set_representation_from_repr_dict(repr_dict);
                        }
                    }
                });
            });
        }
    }
    getReprDictFrontEnd() {
        var repr_dict = {};
        var n_components = this.stage.compList.length;
        for (var i = 0; i < n_components; i++) {
            var comp = this.stage.compList[i];
            repr_dict[i] = {};
            var msgi = repr_dict[i];
            for (var j = 0; j < comp.reprList.length; j++) {
                var repr = comp.reprList[j];
                msgi[j] = {};
                msgi[j]['type'] = repr.name;
                msgi[j]['params'] = repr.repr.getParameters();
            }
        }
        return repr_dict;
    }
    syncReprForAllViews() {
        var repr_dict_backend = this.model.get("_ngl_repr_dict");
        var repr_dict_frontend = this.getReprDictFrontEnd();
        if (JSON.stringify(repr_dict_frontend) !== JSON.stringify(repr_dict_backend)) {
            this._set_representation_from_repr_dict(repr_dict_backend);
        }
    }
    syncReprWithMe() {
        return __awaiter(this, void 0, void 0, function* () {
            // Make sure views of the same model has the same representations
            // Only needed if we use Sidebar that connects to specific view.
            var that = this;
            var repr_dict = this.getReprDictFrontEnd();
            for (var k in this.model.views) {
                var v = yield this.model.views[k];
                if (v.uuid != that.uuid) {
                    v._set_representation_from_repr_dict(repr_dict);
                }
            }
            this.request_repr_dict();
        });
    }
    setSyncRepr(model_ids) {
        this._synced_repr_model_ids = model_ids;
    }
    setSyncCamera(model_ids) {
        this._synced_model_ids = model_ids;
    }
    viewXZPlane() {
        var m = new NGL.Matrix4().makeRotationX(Math.PI / 2);
        var q = new NGL.Quaternion().setFromRotationMatrix(m);
        this.stage.viewerControls.rotate(q);
    }
    set_representation_from_backend() {
        var repr_dict = this.model.get('_ngl_repr_dict');
        this._set_representation_from_repr_dict(repr_dict);
    }
    _set_representation_from_repr_dict(repr_dict) {
        var compList = this.stage.compList;
        if (compList.length > 0) {
            for (var index in repr_dict) {
                var comp = compList[index];
                comp.removeAllRepresentations();
                var reprlist = repr_dict[index];
                for (var j in reprlist) {
                    var repr = reprlist[j];
                    if (repr) {
                        comp.addRepresentation(repr.type, repr.params);
                    }
                }
            }
        }
    }
    createView(trait_name) {
        return __awaiter(this, void 0, void 0, function* () {
            // Create a view for the model with given `trait_name`
            // e.g: in backend, 'view.<trait_name>`
            console.log("Creating view for model " + trait_name);
            var manager = this.model.widget_manager;
            var model_id = this.model.get(trait_name).replace("IPY_MODEL_", "");
            return yield manager.create_view(yield manager.get_model(model_id));
        });
    }
    getPlayerModel() {
        // return a Promise
        var model_id = this.model.get("_iplayer").replace("IPY_MODEL_", "");
        return this.model.widget_manager.get_model(model_id);
    }
    createIPlayer() {
        return __awaiter(this, void 0, void 0, function* () {
            this.player_pview = this.createView("_iplayer");
            var view = yield this.player_pview;
            var that = this;
            var pe = view.el;
            pe.style.position = 'absolute';
            pe.style.zIndex = 100;
            pe.style.bottom = '5%';
            pe.style.left = '10%';
            pe.style.opacity = '0.7';
            that.stage.viewer.container.append(view.el);
            pe.style.display = 'none';
        });
    }
    createImageBtn() {
        return __awaiter(this, void 0, void 0, function* () {
            this.image_btn_pview = this.createView("_ibtn_image");
            var view = yield this.image_btn_pview;
            var pe = view.el;
            pe.style.position = 'absolute';
            pe.style.zIndex = 100;
            pe.style.top = '5%';
            pe.style.right = '10%';
            pe.style.opacity = '0.7';
            pe.style.width = '35px';
            this.stage.viewer.container.append(view.el);
        });
    }
    createFullscreenBtn() {
        return __awaiter(this, void 0, void 0, function* () {
            this.btn_pview_fullscreen = this.createView("_ibtn_fullscreen");
            var view = yield this.btn_pview_fullscreen;
            var stage = this.stage;
            var pe = view.el;
            pe.style.position = 'absolute';
            pe.style.zIndex = 100;
            pe.style.top = '5%';
            pe.style.right = '5%';
            pe.style.opacity = '0.7';
            pe.style.width = '35px';
            pe.style.background = 'white';
            pe.style.opacity = '0.3';
            pe.style.display = 'none';
            pe.onclick = function () {
                this.stage.toggleFullscreen();
            }.bind(this);
            stage.viewer.container.append(view.el);
            stage.signals.fullscreenChanged.add(function (isFullscreen) {
                if (isFullscreen) {
                    view.model.set("icon", "compress");
                }
                else {
                    view.model.set("icon", "expand");
                }
            });
        });
    }
    createGUI() {
        return __awaiter(this, void 0, void 0, function* () {
            this.pgui_view = this.createView("_igui");
            var view = yield this.pgui_view;
            var pe = view.el;
            pe.style.position = 'absolute';
            pe.style.zIndex = 100;
            pe.style.top = '5%';
            pe.style.right = '10%';
            pe.style.width = '300px';
            this.stage.viewer.container.append(view.el);
        });
    }
    createNglGUI() {
        this.stage_widget = new gui_1.StageWidget(this);
    }
    setVisibilityForRepr(component_index, repr_index, value) {
        // value = True/False
        var component = this.stage.compList[component_index];
        var repr = component.reprList[repr_index];
        if (repr) {
            repr.setVisibility(value);
        }
    }
    removeRepresentation(component_index, repr_index) {
        var component = this.stage.compList[component_index];
        var repr = component.reprList[repr_index];
        if (repr) {
            component.removeRepresentation(repr);
        }
    }
    removeRepresentationsByName(repr_name, component_index) {
        var component = this.stage.compList[component_index];
        if (component) {
            component.reprList.forEach(function (repr) {
                if (repr.name == repr_name) {
                    component.removeRepresentation(repr);
                }
            });
        }
    }
    updateRepresentationForComponent(repr_index, component_index, params) {
        var component = this.stage.compList[component_index];
        var that = this;
        var repr = component.reprList[repr_index];
        if (repr) {
            repr.setParameters(params);
        }
    }
    updateRepresentationsByName(repr_name, component_index, params) {
        var component = this.stage.compList[component_index];
        var that = this;
        if (component) {
            component.reprList.forEach(function (repr) {
                if (repr.name == repr_name) {
                    repr.setParameters(params);
                    that.request_repr_dict();
                }
            });
        }
    }
    setRepresentation(name, params, component_index, repr_index) {
        var component = this.stage.compList[component_index];
        var repr = component.reprList[repr_index];
        var that = this;
        if (repr) {
            params['useWorker'] = false;
            var new_repr = NGL.makeRepresentation(name, component.structure, this.stage.viewer, params);
            if (new_repr) {
                repr.setRepresentation(new_repr);
                repr.name = name;
                component.reprList[repr_index] = repr;
                that.request_repr_dict();
            }
        }
    }
    setColorByResidue(colors, component_index, repr_index) {
        var repr = this.stage.compList[component_index].reprList[repr_index];
        var schemeId = NGL.ColormakerRegistry.addScheme(function (params) {
            this.atomColor = function (atom) {
                var color = colors[atom.residueIndex];
                return color;
            };
            params; // to pass eslint; ack;
        });
        repr.setColor(schemeId);
    }
    addShape(name, shapes) {
        // shapes: List[Tuple[str, ...]]
        // e.g: [('sphere', ...), ('cone', ...)]
        var shape = new NGL.Shape(name);
        var shape_dict = {
            'sphere': shape.addSphere,
            'ellipsoid': shape.addEllipsoid,
            'cylinder': shape.addCylinder,
            'cone': shape.addCone,
            'mesh': shape.addMesh,
            'arrow': shape.addArrow,
            'text': shape.addText,
            'label': shape.addText,
            'tetrahedron': shape.addTetrahedron,
            'octahedron': shape.addOctahedron,
            'torus': shape.addTorus
        };
        for (var i = 0; i < shapes.length; i++) {
            var shapes_i = shapes[i];
            var shape_type = shapes_i[0];
            var params = shapes_i.slice(1, shapes_i.length);
            // e.g params = ('sphere', [ 0, 0, 9 ], [ 1, 0, 0 ], 1.5)
            var func = shape_dict[shape_type];
            func.apply(shape, params);
            // shape.func(params);
        }
        var shapeComp = this.stage.addComponentFromObject(shape);
        shapeComp.addRepresentation("buffer");
    }
    addBuffer(name, kwargs) {
        var class_dict = {
            "arrow": NGL.ArrowBuffer,
            "box": NGL.BoXbuffer,
            "cone": NGL.ConeBuffer,
            "cylinder": NGL.CylinderBuffer,
            "ellipsoid": NGL.EllipsoidBuffer,
            "octahedron": NGL.OctahedronBuffer,
            "sphere": NGL.SphereBuffer,
            "text": NGL.TextBuffer,
            "tetrahedron": NGL.TetrahedronBuffer,
            "torus": NGL.TorusBuffer
        };
        var params = {};
        for (var key in kwargs) {
            params[key] = new Float32Array(kwargs[key]);
        }
        var shape = new NGL.Shape("shape");
        var buffer_class = class_dict[name];
        var buffer = new buffer_class(params);
        shape.addBuffer(buffer);
        var shapeComp = this.stage.addComponentFromObject(shape);
        shapeComp.addRepresentation("buffer");
    }
    replaceStructure(structure) {
        return __awaiter(this, void 0, void 0, function* () {
            var blob = new Blob([structure.data], { type: "text/plain" });
            var stage = this.stage;
            var params = structure.params || {};
            params.ext = structure.ext;
            params.defaultRepresentation = false;
            var comp = this.stage.compList[0];
            var representations = comp.reprList.slice();
            var old_orientation = this.stage.viewerControls.getOrientation();
            var component = yield this.stage.loadFile(blob, params);
            stage.viewerControls.orient(old_orientation);
            representations.forEach(function (repr) {
                var repr_name = repr.name;
                var repr_params = repr.repr.getParameters();
                // Note: not using repr.repr.type, repr.repr.params
                // since seems to me that repr.repr.params won't return correct "sele"
                component.addRepresentation(repr_name, repr_params);
            });
            stage.removeComponent(comp);
            this._handleLoadFileFinished();
        });
    }
    superpose(cindex0, cindex1, align, sele0, sele1) {
        // superpose two components with given params
        var component0 = this.stage.compList[cindex0];
        var component1 = this.stage.compList[cindex1];
        component1.superpose(component0, align, sele0, sele1);
    }
    decode_base64(base64) {
        // lightly adapted from Niklas
        /*
         * base64-arraybuffer
         * https://github.com/niklasvh/base64-arraybuffer
         *
         * Copyright (c) 2012 Niklas von Hertzen
         * Licensed under the MIT license.
         */
        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
        if (base64[base64.length - 1] === "=") {
            bufferLength--;
            if (base64[base64.length - 2] === "=") {
                bufferLength--;
            }
        }
        var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
        for (i = 0; i < len; i += 4) {
            encoded1 = chars.indexOf(base64[i]);
            encoded2 = chars.indexOf(base64[i + 1]);
            encoded3 = chars.indexOf(base64[i + 2]);
            encoded4 = chars.indexOf(base64[i + 3]);
            bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
            bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
            bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
        }
        return arraybuffer;
    }
    updateCoordinates(coordinates, model) {
        // coordinates must be ArrayBuffer (use this.decode_base64)
        var component = this.stage.compList[model];
        if (coordinates && component) {
            var coords = new Float32Array(coordinates);
            component.structure.updatePosition(coords);
            component.updateRepresentations({
                "position": true
            });
        }
    }
    handleResizable() {
        this.$container.resizable({
            resize: function (event, ui) {
                this.setSize(ui.size.width + "px", ui.size.height + "px");
            }.bind(this)
        });
    }
    handleResize() {
        var width = this.$el.width();
        var height = this.$el.height() + "px";
        if (this.stage_widget) {
            width = width - $(this.stage_widget.sidebar.dom).width();
        }
        width = width + "px";
        this.setSize(width, height);
    }
    setSize(width, height) {
        this.stage.viewer.container.style.width = width;
        this.stage.viewer.container.style.height = height;
        this.stage.handleResize();
    }
    GUIStyleChanged() {
        var style = this.model.get("gui_style");
        if (style === 'ngl') {
            this.createNglGUI();
        }
        else {
            if (this.stage_widget) {
                this.stage_widget.dispose();
                this.stage_widget = undefined;
                this.$container.resizable("enable");
                var width = this.$el.parent().width() + "px";
                var height = this.$el.parent().height() + "px";
                this.setSize(width, height);
            }
        }
    }
    parametersChanged() {
        var _parameters = this.model.get("_parameters");
        this.setParameters(_parameters);
    }
    setParameters(parameters) {
        this.stage.setParameters(parameters);
        // do not set _ngl_full_stage_parameters here
        // or parameters will be never updated (not sure why)
        // use observe in python side
        var updated_params = this.stage.getParameters();
        this.send({
            'type': 'stage_parameters',
            'data': updated_params
        });
    }
    _downloadImage(filename, params) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.ngl_view_id == this.get_last_child_id()) {
                var blob = yield this.stage.makeImage(params);
                NGL.download(blob, filename);
            }
        });
    }
    _exportImage(wid, params) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.ngl_view_id == this.get_last_child_id()) {
                var blob = yield this.stage.makeImage(params);
                var reader = new FileReader();
                var arr_str;
                reader.onload = function () {
                    arr_str = reader.result.replace("data:image/png;base64,", "");
                    // this.model.set("_image_data", arr_str);
                    // this.touch();
                    this.send({
                        "data": arr_str,
                        "type": "image_data",
                        "ID": wid,
                    });
                    this.send({ 'type': 'async_message', 'data': 'ok' });
                }.bind(this);
                reader.readAsDataURL(blob);
            }
        });
    }
    handleMovieMaking(render_params) {
        return __awaiter(this, void 0, void 0, function* () {
            console.log('handleMovieMaking: render_params', render_params);
            if (this.ngl_view_id == this.get_last_child_id()) {
                var blob = yield this.stage.makeImage(render_params);
                var reader = new FileReader();
                var arr_str;
                reader.onload = function () {
                    arr_str = reader.result.replace("data:image/png;base64,", "");
                    // this.model.set("_image_data", arr_str);
                    // this.touch();
                    this.send({
                        "data": arr_str,
                        "type": "movie_image_data",
                    }); // tell backend that image render is finished,
                    // backend will send next frame's coordinates.
                    this.send({ 'type': 'async_message', 'data': 'ok' });
                }.bind(this);
                reader.readAsDataURL(blob);
            }
        });
    }
    _handleLoadFileFinished() {
        this.send({ 'type': 'async_message', 'data': 'ok' });
    }
    _getLoadFilePromise(msg) {
        // args = [{'type': ..., 'data': ...}]
        var args0 = msg.args[0];
        if (args0.type == 'blob') {
            var blob;
            if (args0.binary) {
                var decoded_data = this.decode_base64(args0.data);
                blob = new Blob([decoded_data], {
                    type: "application/octet-binary"
                });
            }
            else {
                blob = new Blob([args0.data], {
                    type: "text/plain"
                });
            }
            return this.stage.loadFile(blob, msg.kwargs);
        }
        else {
            var file = new File([""], args0.data);
            // FIXME: if not "any", typescipt complains there is no
            // "exists" method.
            var path = "";
            // FIXME: uncomment ("exists" does not exist)
            // if (args0.type == 'path' && ! file.exists){
            // hacky fix for jupyterlab
            // https://github.com/arose/nglview/issues/783
            // https://github.com/jupyterlab/jupyterlab/issues/6218
            // e.g: http://localhost:8888/files/ala3.pdb
            //    path = 'files/' + args0.data;
            // } else {
            // path = args0.data;
            //}
            path = args0.data;
            return this.stage.loadFile(path, msg.kwargs);
        }
    }
    get_last_child_id() {
        var keys = this.model.get('_ngl_view_id');
        return keys[keys.length - 1];
    }
    _handleStageLoadFile(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            // args = [{'type': ..., 'data': ...}]
            if (this.ngl_view_id != this.get_last_child_id() && msg.last_child) {
                return;
            }
            var o = yield this._getLoadFilePromise(msg);
            this._handleLoadFileFinished();
        });
    }
    addColorScheme(args, label) {
        var id = NGL.ColormakerRegistry.addSelectionScheme(args, label);
        var scheme = NGL.ColormakerRegistry.userSchemes[id];
        NGL.ColormakerRegistry.removeScheme(id);
        // hard code the scheme ID
        NGL.ColormakerRegistry.add(label, scheme);
        return label;
    }
    on_msg(msg) {
        return __awaiter(this, void 0, void 0, function* () {
            // TODO: re-organize
            if (('ngl_view_id' in msg) && (msg.ngl_view_id !== this.ngl_view_id)) {
                return;
            }
            if (msg.type == 'call_method') {
                var index, component, func, stage;
                var new_args = msg.args.slice();
                new_args.push(msg.kwargs);
                // handle color
                if (msg.methodName == 'addRepresentation' &&
                    msg.reconstruc_color_scheme) {
                    msg.kwargs.color = this.addColorScheme(msg.kwargs.color, msg.kwargs.color_label);
                }
                if ("colorVolume" in msg.kwargs) {
                    // backend only send component index
                    // so we need to convert to 'volume' data
                    index = msg.kwargs["colorVolume"];
                    msg.kwargs["colorVolume"] = this.stage.compList[index].volume;
                }
                switch (msg.target) {
                    case 'Stage':
                        var stage_func = this.stage[msg.methodName];
                        stage = this.stage;
                        if (msg.methodName == 'screenshot') {
                            NGL.screenshot(this.stage.viewer, msg.kwargs);
                        }
                        else if (msg.methodName == 'removeComponent') {
                            index = msg.args[0];
                            component = this.stage.compList[index];
                            this.stage.removeComponent(component);
                        }
                        else if (msg.methodName == 'loadFile') {
                            if (this.model.views.length > 1 && msg.kwargs &&
                                msg.kwargs.defaultRepresentation) {
                                // no need to add default representation as all representations
                                // are serialized separately, also it unwantedly sets the orientation
                                msg.kwargs.defaultRepresentation = false;
                            }
                            yield this._handleStageLoadFile(msg);
                        }
                        else {
                            stage_func.apply(stage, new_args);
                        }
                        break;
                    case 'Viewer':
                        var viewer = this.stage.viewer;
                        func = this.stage.viewer[msg.methodName];
                        func.apply(viewer, new_args);
                        break;
                    case 'viewerControls':
                        var controls = this.stage.viewerControls;
                        func = controls[msg.methodName];
                        func.apply(controls, new_args);
                        break;
                    case 'compList':
                        index = msg['component_index'];
                        component = this.stage.compList[index];
                        func = component[msg.methodName];
                        func.apply(component, new_args);
                        break;
                    case 'Widget':
                        func = this[msg.methodName];
                        if (func) {
                            func.apply(this, new_args);
                        }
                        else {
                            // send error message to Python?
                            console.log('can not create func for ' + msg.methodName);
                        }
                        break;
                    case 'Representation':
                        var component_index = msg['component_index'];
                        var repr_index = msg['repr_index'];
                        component = this.stage.compList[component_index];
                        var repr = component.reprList[repr_index];
                        func = repr[msg.methodName];
                        if (repr && func) {
                            func.apply(repr, new_args);
                        }
                        break;
                    default:
                        console.log('there is no method for ' + msg.target);
                        break;
                }
            }
            else if (msg.type == 'base64_single') {
                var coordinatesDict = msg.data;
                var keys = Object.keys(coordinatesDict);
                for (var i = 0; i < keys.length; i++) {
                    var traj_index = keys[i];
                    var coordinates = this.decode_base64(coordinatesDict[traj_index]);
                    if (coordinates && coordinates.byteLength > 0) {
                        this.updateCoordinates(coordinates, traj_index);
                    }
                }
            }
            else if (msg.type == 'binary_single') {
                var coordinateMeta = msg.data;
                keys = Object.keys(coordinateMeta);
                for (i = 0; i < keys.length; i++) {
                    traj_index = keys[i];
                    coordinates = new Float32Array(msg.buffers[i].buffer);
                    if (coordinates.byteLength > 0) {
                        this.updateCoordinates(coordinates, traj_index);
                    }
                }
                if (msg.movie_making) {
                    this.handleMovieMaking(msg.render_params);
                }
            }
            else if (msg.type == 'get') {
                if (msg.data == 'camera') {
                    this.send(JSON.stringify(this.stage.viewer.camera));
                }
                else if (msg.data == 'parameters') {
                    this.send(JSON.stringify(this.stage.parameters));
                }
                else {
                    console.log("Number of components", this.stage.compList.length);
                    console.log("ngl_view_id", this.ngl_view_id);
                }
            }
        });
    }
}
exports.NGLView = NGLView;
// export all models and views here to make embeding a bit easier
module.exports = {
    'NGLView': NGLView,
    'NGLModel': NGLModel,
    'NGL': NGL,
    'FullscreenModel': fullscreen_1.FullscreenModel,
    'FullscreenView': fullscreen_1.FullscreenView,
    'ColormakerRegistryModel': color_1.ColormakerRegistryModel,
    'ColormakerRegistryView': color_1.ColormakerRegistryView,
    'ThemeManagerModel': theme_1.ThemeManagerModel,
    'ThemeManagerView': theme_1.ThemeManagerView,
};
//# sourceMappingURL=data:application/json;base64, 

/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;
/**
 * @license
 *
 * chroma.js - JavaScript library for color conversions
 * 
 * Copyright (c) 2011-2017, Gregor Aisch
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * 3. The name Gregor Aisch may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL GREGOR AISCH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

(function() {
  var Color, DEG2RAD, LAB_CONSTANTS, PI, PITHIRD, RAD2DEG, TWOPI, _average_lrgb, _guess_formats, _guess_formats_sorted, _input, _interpolators, abs, atan2, bezier, blend, blend_f, brewer, burn, chroma, clip_rgb, cmyk2rgb, colors, cos, css2rgb, darken, dodge, each, floor, hcg2rgb, hex2rgb, hsi2rgb, hsl2css, hsl2rgb, hsv2rgb, interpolate, interpolate_hsx, interpolate_lab, interpolate_lrgb, interpolate_num, interpolate_rgb, lab2lch, lab2rgb, lab_xyz, lch2lab, lch2rgb, lighten, limit, log, luminance_x, m, max, multiply, normal, num2rgb, overlay, pow, rgb2cmyk, rgb2css, rgb2hcg, rgb2hex, rgb2hsi, rgb2hsl, rgb2hsv, rgb2lab, rgb2lch, rgb2luminance, rgb2num, rgb2temperature, rgb2xyz, rgb_xyz, rnd, root, round, screen, sin, sqrt, temperature2rgb, type, unpack, w3cx11, xyz_lab, xyz_rgb,
    slice = [].slice;

  type = (function() {

    /*
    for browser-safe type checking+
    ported from jQuery's $.type
     */
    var classToType, len, name, o, ref;
    classToType = {};
    ref = "Boolean Number String Function Array Date RegExp Undefined Null".split(" ");
    for (o = 0, len = ref.length; o < len; o++) {
      name = ref[o];
      classToType["[object " + name + "]"] = name.toLowerCase();
    }
    return function(obj) {
      var strType;
      strType = Object.prototype.toString.call(obj);
      return classToType[strType] || "object";
    };
  })();

  limit = function(x, min, max) {
    if (min == null) {
      min = 0;
    }
    if (max == null) {
      max = 1;
    }
    if (x < min) {
      x = min;
    }
    if (x > max) {
      x = max;
    }
    return x;
  };

  unpack = function(args) {
    if (args.length >= 3) {
      return Array.prototype.slice.call(args);
    } else {
      return args[0];
    }
  };

  clip_rgb = function(rgb) {
    var i, o;
    rgb._clipped = false;
    rgb._unclipped = rgb.slice(0);
    for (i = o = 0; o < 3; i = ++o) {
      if (i < 3) {
        if (rgb[i] < 0 || rgb[i] > 255) {
          rgb._clipped = true;
        }
        if (rgb[i] < 0) {
          rgb[i] = 0;
        }
        if (rgb[i] > 255) {
          rgb[i] = 255;
        }
      } else if (i === 3) {
        if (rgb[i] < 0) {
          rgb[i] = 0;
        }
        if (rgb[i] > 1) {
          rgb[i] = 1;
        }
      }
    }
    if (!rgb._clipped) {
      delete rgb._unclipped;
    }
    return rgb;
  };

  PI = Math.PI, round = Math.round, cos = Math.cos, floor = Math.floor, pow = Math.pow, log = Math.log, sin = Math.sin, sqrt = Math.sqrt, atan2 = Math.atan2, max = Math.max, abs = Math.abs;

  TWOPI = PI * 2;

  PITHIRD = PI / 3;

  DEG2RAD = PI / 180;

  RAD2DEG = 180 / PI;

  chroma = function() {
    if (arguments[0] instanceof Color) {
      return arguments[0];
    }
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, arguments, function(){});
  };

  chroma["default"] = chroma;

  _interpolators = [];

  if ((typeof module !== "undefined" && module !== null) && (module.exports != null)) {
    module.exports = chroma;
  }

  if (true) {
    !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function() {
      return chroma;
    }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  } else {
    root = typeof exports !== "undefined" && exports !== null ? exports : this;
    root.chroma = chroma;
  }

  chroma.version = '1.4.1';

  _input = {};

  _guess_formats = [];

  _guess_formats_sorted = false;

  Color = (function() {
    function Color() {
      var arg, args, chk, len, len1, me, mode, o, w;
      me = this;
      args = [];
      for (o = 0, len = arguments.length; o < len; o++) {
        arg = arguments[o];
        if (arg != null) {
          args.push(arg);
        }
      }
      if (args.length > 1) {
        mode = args[args.length - 1];
      }
      if (_input[mode] != null) {
        me._rgb = clip_rgb(_input[mode](unpack(args.slice(0, -1))));
      } else {
        if (!_guess_formats_sorted) {
          _guess_formats = _guess_formats.sort(function(a, b) {
            return b.p - a.p;
          });
          _guess_formats_sorted = true;
        }
        for (w = 0, len1 = _guess_formats.length; w < len1; w++) {
          chk = _guess_formats[w];
          mode = chk.test.apply(chk, args);
          if (mode) {
            break;
          }
        }
        if (mode) {
          me._rgb = clip_rgb(_input[mode].apply(_input, args));
        }
      }
      if (me._rgb == null) {
        console.warn('unknown format: ' + args);
      }
      if (me._rgb == null) {
        me._rgb = [0, 0, 0];
      }
      if (me._rgb.length === 3) {
        me._rgb.push(1);
      }
    }

    Color.prototype.toString = function() {
      return this.hex();
    };

    return Color;

  })();

  chroma._input = _input;


  /**
  	ColorBrewer colors for chroma.js
  
  	Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The 
  	Pennsylvania State University.
  
  	Licensed under the Apache License, Version 2.0 (the "License"); 
  	you may not use this file except in compliance with the License.
  	You may obtain a copy of the License at	
  	http://www.apache.org/licenses/LICENSE-2.0
  
  	Unless required by applicable law or agreed to in writing, software distributed
  	under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  	CONDITIONS OF ANY KIND, either express or implied. See the License for the
  	specific language governing permissions and limitations under the License.
  
      @preserve
   */

  chroma.brewer = brewer = {
    OrRd: ['#fff7ec', '#fee8c8', '#fdd49e', '#fdbb84', '#fc8d59', '#ef6548', '#d7301f', '#b30000', '#7f0000'],
    PuBu: ['#fff7fb', '#ece7f2', '#d0d1e6', '#a6bddb', '#74a9cf', '#3690c0', '#0570b0', '#045a8d', '#023858'],
    BuPu: ['#f7fcfd', '#e0ecf4', '#bfd3e6', '#9ebcda', '#8c96c6', '#8c6bb1', '#88419d', '#810f7c', '#4d004b'],
    Oranges: ['#fff5eb', '#fee6ce', '#fdd0a2', '#fdae6b', '#fd8d3c', '#f16913', '#d94801', '#a63603', '#7f2704'],
    BuGn: ['#f7fcfd', '#e5f5f9', '#ccece6', '#99d8c9', '#66c2a4', '#41ae76', '#238b45', '#006d2c', '#00441b'],
    YlOrBr: ['#ffffe5', '#fff7bc', '#fee391', '#fec44f', '#fe9929', '#ec7014', '#cc4c02', '#993404', '#662506'],
    YlGn: ['#ffffe5', '#f7fcb9', '#d9f0a3', '#addd8e', '#78c679', '#41ab5d', '#238443', '#006837', '#004529'],
    Reds: ['#fff5f0', '#fee0d2', '#fcbba1', '#fc9272', '#fb6a4a', '#ef3b2c', '#cb181d', '#a50f15', '#67000d'],
    RdPu: ['#fff7f3', '#fde0dd', '#fcc5c0', '#fa9fb5', '#f768a1', '#dd3497', '#ae017e', '#7a0177', '#49006a'],
    Greens: ['#f7fcf5', '#e5f5e0', '#c7e9c0', '#a1d99b', '#74c476', '#41ab5d', '#238b45', '#006d2c', '#00441b'],
    YlGnBu: ['#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58'],
    Purples: ['#fcfbfd', '#efedf5', '#dadaeb', '#bcbddc', '#9e9ac8', '#807dba', '#6a51a3', '#54278f', '#3f007d'],
    GnBu: ['#f7fcf0', '#e0f3db', '#ccebc5', '#a8ddb5', '#7bccc4', '#4eb3d3', '#2b8cbe', '#0868ac', '#084081'],
    Greys: ['#ffffff', '#f0f0f0', '#d9d9d9', '#bdbdbd', '#969696', '#737373', '#525252', '#252525', '#000000'],
    YlOrRd: ['#ffffcc', '#ffeda0', '#fed976', '#feb24c', '#fd8d3c', '#fc4e2a', '#e31a1c', '#bd0026', '#800026'],
    PuRd: ['#f7f4f9', '#e7e1ef', '#d4b9da', '#c994c7', '#df65b0', '#e7298a', '#ce1256', '#980043', '#67001f'],
    Blues: ['#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6', '#2171b5', '#08519c', '#08306b'],
    PuBuGn: ['#fff7fb', '#ece2f0', '#d0d1e6', '#a6bddb', '#67a9cf', '#3690c0', '#02818a', '#016c59', '#014636'],
    Viridis: ['#440154', '#482777', '#3f4a8a', '#31678e', '#26838f', '#1f9d8a', '#6cce5a', '#b6de2b', '#fee825'],
    Spectral: ['#9e0142', '#d53e4f', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#e6f598', '#abdda4', '#66c2a5', '#3288bd', '#5e4fa2'],
    RdYlGn: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee08b', '#ffffbf', '#d9ef8b', '#a6d96a', '#66bd63', '#1a9850', '#006837'],
    RdBu: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#f7f7f7', '#d1e5f0', '#92c5de', '#4393c3', '#2166ac', '#053061'],
    PiYG: ['#8e0152', '#c51b7d', '#de77ae', '#f1b6da', '#fde0ef', '#f7f7f7', '#e6f5d0', '#b8e186', '#7fbc41', '#4d9221', '#276419'],
    PRGn: ['#40004b', '#762a83', '#9970ab', '#c2a5cf', '#e7d4e8', '#f7f7f7', '#d9f0d3', '#a6dba0', '#5aae61', '#1b7837', '#00441b'],
    RdYlBu: ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#ffffbf', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695'],
    BrBG: ['#543005', '#8c510a', '#bf812d', '#dfc27d', '#f6e8c3', '#f5f5f5', '#c7eae5', '#80cdc1', '#35978f', '#01665e', '#003c30'],
    RdGy: ['#67001f', '#b2182b', '#d6604d', '#f4a582', '#fddbc7', '#ffffff', '#e0e0e0', '#bababa', '#878787', '#4d4d4d', '#1a1a1a'],
    PuOr: ['#7f3b08', '#b35806', '#e08214', '#fdb863', '#fee0b6', '#f7f7f7', '#d8daeb', '#b2abd2', '#8073ac', '#542788', '#2d004b'],
    Set2: ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854', '#ffd92f', '#e5c494', '#b3b3b3'],
    Accent: ['#7fc97f', '#beaed4', '#fdc086', '#ffff99', '#386cb0', '#f0027f', '#bf5b17', '#666666'],
    Set1: ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33', '#a65628', '#f781bf', '#999999'],
    Set3: ['#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5', '#ffed6f'],
    Dark2: ['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#a6761d', '#666666'],
    Paired: ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99', '#e31a1c', '#fdbf6f', '#ff7f00', '#cab2d6', '#6a3d9a', '#ffff99', '#b15928'],
    Pastel2: ['#b3e2cd', '#fdcdac', '#cbd5e8', '#f4cae4', '#e6f5c9', '#fff2ae', '#f1e2cc', '#cccccc'],
    Pastel1: ['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#e5d8bd', '#fddaec', '#f2f2f2']
  };

  (function() {
    var key, results;
    results = [];
    for (key in brewer) {
      results.push(brewer[key.toLowerCase()] = brewer[key]);
    }
    return results;
  })();


  /**
  	X11 color names
  
  	http://www.w3.org/TR/css3-color/#svg-color
   */

  w3cx11 = {
    aliceblue: '#f0f8ff',
    antiquewhite: '#faebd7',
    aqua: '#00ffff',
    aquamarine: '#7fffd4',
    azure: '#f0ffff',
    beige: '#f5f5dc',
    bisque: '#ffe4c4',
    black: '#000000',
    blanchedalmond: '#ffebcd',
    blue: '#0000ff',
    blueviolet: '#8a2be2',
    brown: '#a52a2a',
    burlywood: '#deb887',
    cadetblue: '#5f9ea0',
    chartreuse: '#7fff00',
    chocolate: '#d2691e',
    coral: '#ff7f50',
    cornflower: '#6495ed',
    cornflowerblue: '#6495ed',
    cornsilk: '#fff8dc',
    crimson: '#dc143c',
    cyan: '#00ffff',
    darkblue: '#00008b',
    darkcyan: '#008b8b',
    darkgoldenrod: '#b8860b',
    darkgray: '#a9a9a9',
    darkgreen: '#006400',
    darkgrey: '#a9a9a9',
    darkkhaki: '#bdb76b',
    darkmagenta: '#8b008b',
    darkolivegreen: '#556b2f',
    darkorange: '#ff8c00',
    darkorchid: '#9932cc',
    darkred: '#8b0000',
    darksalmon: '#e9967a',
    darkseagreen: '#8fbc8f',
    darkslateblue: '#483d8b',
    darkslategray: '#2f4f4f',
    darkslategrey: '#2f4f4f',
    darkturquoise: '#00ced1',
    darkviolet: '#9400d3',
    deeppink: '#ff1493',
    deepskyblue: '#00bfff',
    dimgray: '#696969',
    dimgrey: '#696969',
    dodgerblue: '#1e90ff',
    firebrick: '#b22222',
    floralwhite: '#fffaf0',
    forestgreen: '#228b22',
    fuchsia: '#ff00ff',
    gainsboro: '#dcdcdc',
    ghostwhite: '#f8f8ff',
    gold: '#ffd700',
    goldenrod: '#daa520',
    gray: '#808080',
    green: '#008000',
    greenyellow: '#adff2f',
    grey: '#808080',
    honeydew: '#f0fff0',
    hotpink: '#ff69b4',
    indianred: '#cd5c5c',
    indigo: '#4b0082',
    ivory: '#fffff0',
    khaki: '#f0e68c',
    laserlemon: '#ffff54',
    lavender: '#e6e6fa',
    lavenderblush: '#fff0f5',
    lawngreen: '#7cfc00',
    lemonchiffon: '#fffacd',
    lightblue: '#add8e6',
    lightcoral: '#f08080',
    lightcyan: '#e0ffff',
    lightgoldenrod: '#fafad2',
    lightgoldenrodyellow: '#fafad2',
    lightgray: '#d3d3d3',
    lightgreen: '#90ee90',
    lightgrey: '#d3d3d3',
    lightpink: '#ffb6c1',
    lightsalmon: '#ffa07a',
    lightseagreen: '#20b2aa',
    lightskyblue: '#87cefa',
    lightslategray: '#778899',
    lightslategrey: '#778899',
    lightsteelblue: '#b0c4de',
    lightyellow: '#ffffe0',
    lime: '#00ff00',
    limegreen: '#32cd32',
    linen: '#faf0e6',
    magenta: '#ff00ff',
    maroon: '#800000',
    maroon2: '#7f0000',
    maroon3: '#b03060',
    mediumaquamarine: '#66cdaa',
    mediumblue: '#0000cd',
    mediumorchid: '#ba55d3',
    mediumpurple: '#9370db',
    mediumseagreen: '#3cb371',
    mediumslateblue: '#7b68ee',
    mediumspringgreen: '#00fa9a',
    mediumturquoise: '#48d1cc',
    mediumvioletred: '#c71585',
    midnightblue: '#191970',
    mintcream: '#f5fffa',
    mistyrose: '#ffe4e1',
    moccasin: '#ffe4b5',
    navajowhite: '#ffdead',
    navy: '#000080',
    oldlace: '#fdf5e6',
    olive: '#808000',
    olivedrab: '#6b8e23',
    orange: '#ffa500',
    orangered: '#ff4500',
    orchid: '#da70d6',
    palegoldenrod: '#eee8aa',
    palegreen: '#98fb98',
    paleturquoise: '#afeeee',
    palevioletred: '#db7093',
    papayawhip: '#ffefd5',
    peachpuff: '#ffdab9',
    peru: '#cd853f',
    pink: '#ffc0cb',
    plum: '#dda0dd',
    powderblue: '#b0e0e6',
    purple: '#800080',
    purple2: '#7f007f',
    purple3: '#a020f0',
    rebeccapurple: '#663399',
    red: '#ff0000',
    rosybrown: '#bc8f8f',
    royalblue: '#4169e1',
    saddlebrown: '#8b4513',
    salmon: '#fa8072',
    sandybrown: '#f4a460',
    seagreen: '#2e8b57',
    seashell: '#fff5ee',
    sienna: '#a0522d',
    silver: '#c0c0c0',
    skyblue: '#87ceeb',
    slateblue: '#6a5acd',
    slategray: '#708090',
    slategrey: '#708090',
    snow: '#fffafa',
    springgreen: '#00ff7f',
    steelblue: '#4682b4',
    tan: '#d2b48c',
    teal: '#008080',
    thistle: '#d8bfd8',
    tomato: '#ff6347',
    turquoise: '#40e0d0',
    violet: '#ee82ee',
    wheat: '#f5deb3',
    white: '#ffffff',
    whitesmoke: '#f5f5f5',
    yellow: '#ffff00',
    yellowgreen: '#9acd32'
  };

  chroma.colors = colors = w3cx11;

  lab2rgb = function() {
    var a, args, b, g, l, r, x, y, z;
    args = unpack(arguments);
    l = args[0], a = args[1], b = args[2];
    y = (l + 16) / 116;
    x = isNaN(a) ? y : y + a / 500;
    z = isNaN(b) ? y : y - b / 200;
    y = LAB_CONSTANTS.Yn * lab_xyz(y);
    x = LAB_CONSTANTS.Xn * lab_xyz(x);
    z = LAB_CONSTANTS.Zn * lab_xyz(z);
    r = xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z);
    g = xyz_rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z);
    b = xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
    return [r, g, b, args.length > 3 ? args[3] : 1];
  };

  xyz_rgb = function(r) {
    return 255 * (r <= 0.00304 ? 12.92 * r : 1.055 * pow(r, 1 / 2.4) - 0.055);
  };

  lab_xyz = function(t) {
    if (t > LAB_CONSTANTS.t1) {
      return t * t * t;
    } else {
      return LAB_CONSTANTS.t2 * (t - LAB_CONSTANTS.t0);
    }
  };

  LAB_CONSTANTS = {
    Kn: 18,
    Xn: 0.950470,
    Yn: 1,
    Zn: 1.088830,
    t0: 0.137931034,
    t1: 0.206896552,
    t2: 0.12841855,
    t3: 0.008856452
  };

  rgb2lab = function() {
    var b, g, r, ref, ref1, x, y, z;
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    ref1 = rgb2xyz(r, g, b), x = ref1[0], y = ref1[1], z = ref1[2];
    return [116 * y - 16, 500 * (x - y), 200 * (y - z)];
  };

  rgb_xyz = function(r) {
    if ((r /= 255) <= 0.04045) {
      return r / 12.92;
    } else {
      return pow((r + 0.055) / 1.055, 2.4);
    }
  };

  xyz_lab = function(t) {
    if (t > LAB_CONSTANTS.t3) {
      return pow(t, 1 / 3);
    } else {
      return t / LAB_CONSTANTS.t2 + LAB_CONSTANTS.t0;
    }
  };

  rgb2xyz = function() {
    var b, g, r, ref, x, y, z;
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    r = rgb_xyz(r);
    g = rgb_xyz(g);
    b = rgb_xyz(b);
    x = xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / LAB_CONSTANTS.Xn);
    y = xyz_lab((0.2126729 * r + 0.7151522 * g + 0.0721750 * b) / LAB_CONSTANTS.Yn);
    z = xyz_lab((0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / LAB_CONSTANTS.Zn);
    return [x, y, z];
  };

  chroma.lab = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['lab']), function(){});
  };

  _input.lab = lab2rgb;

  Color.prototype.lab = function() {
    return rgb2lab(this._rgb);
  };

  bezier = function(colors) {
    var I, I0, I1, c, lab0, lab1, lab2, lab3, ref, ref1, ref2;
    colors = (function() {
      var len, o, results;
      results = [];
      for (o = 0, len = colors.length; o < len; o++) {
        c = colors[o];
        results.push(chroma(c));
      }
      return results;
    })();
    if (colors.length === 2) {
      ref = (function() {
        var len, o, results;
        results = [];
        for (o = 0, len = colors.length; o < len; o++) {
          c = colors[o];
          results.push(c.lab());
        }
        return results;
      })(), lab0 = ref[0], lab1 = ref[1];
      I = function(t) {
        var i, lab;
        lab = (function() {
          var o, results;
          results = [];
          for (i = o = 0; o <= 2; i = ++o) {
            results.push(lab0[i] + t * (lab1[i] - lab0[i]));
          }
          return results;
        })();
        return chroma.lab.apply(chroma, lab);
      };
    } else if (colors.length === 3) {
      ref1 = (function() {
        var len, o, results;
        results = [];
        for (o = 0, len = colors.length; o < len; o++) {
          c = colors[o];
          results.push(c.lab());
        }
        return results;
      })(), lab0 = ref1[0], lab1 = ref1[1], lab2 = ref1[2];
      I = function(t) {
        var i, lab;
        lab = (function() {
          var o, results;
          results = [];
          for (i = o = 0; o <= 2; i = ++o) {
            results.push((1 - t) * (1 - t) * lab0[i] + 2 * (1 - t) * t * lab1[i] + t * t * lab2[i]);
          }
          return results;
        })();
        return chroma.lab.apply(chroma, lab);
      };
    } else if (colors.length === 4) {
      ref2 = (function() {
        var len, o, results;
        results = [];
        for (o = 0, len = colors.length; o < len; o++) {
          c = colors[o];
          results.push(c.lab());
        }
        return results;
      })(), lab0 = ref2[0], lab1 = ref2[1], lab2 = ref2[2], lab3 = ref2[3];
      I = function(t) {
        var i, lab;
        lab = (function() {
          var o, results;
          results = [];
          for (i = o = 0; o <= 2; i = ++o) {
            results.push((1 - t) * (1 - t) * (1 - t) * lab0[i] + 3 * (1 - t) * (1 - t) * t * lab1[i] + 3 * (1 - t) * t * t * lab2[i] + t * t * t * lab3[i]);
          }
          return results;
        })();
        return chroma.lab.apply(chroma, lab);
      };
    } else if (colors.length === 5) {
      I0 = bezier(colors.slice(0, 3));
      I1 = bezier(colors.slice(2, 5));
      I = function(t) {
        if (t < 0.5) {
          return I0(t * 2);
        } else {
          return I1((t - 0.5) * 2);
        }
      };
    }
    return I;
  };

  chroma.bezier = function(colors) {
    var f;
    f = bezier(colors);
    f.scale = function() {
      return chroma.scale(f);
    };
    return f;
  };

  chroma.cubehelix = function(start, rotations, hue, gamma, lightness) {
    var dh, dl, f;
    if (start == null) {
      start = 300;
    }
    if (rotations == null) {
      rotations = -1.5;
    }
    if (hue == null) {
      hue = 1;
    }
    if (gamma == null) {
      gamma = 1;
    }
    if (lightness == null) {
      lightness = [0, 1];
    }
    dh = 0;
    if (type(lightness) === 'array') {
      dl = lightness[1] - lightness[0];
    } else {
      dl = 0;
      lightness = [lightness, lightness];
    }
    f = function(fract) {
      var a, amp, b, cos_a, g, h, l, r, sin_a;
      a = TWOPI * ((start + 120) / 360 + rotations * fract);
      l = pow(lightness[0] + dl * fract, gamma);
      h = dh !== 0 ? hue[0] + fract * dh : hue;
      amp = h * l * (1 - l) / 2;
      cos_a = cos(a);
      sin_a = sin(a);
      r = l + amp * (-0.14861 * cos_a + 1.78277 * sin_a);
      g = l + amp * (-0.29227 * cos_a - 0.90649 * sin_a);
      b = l + amp * (+1.97294 * cos_a);
      return chroma(clip_rgb([r * 255, g * 255, b * 255, 1]));
    };
    f.start = function(s) {
      if (s == null) {
        return start;
      }
      start = s;
      return f;
    };
    f.rotations = function(r) {
      if (r == null) {
        return rotations;
      }
      rotations = r;
      return f;
    };
    f.gamma = function(g) {
      if (g == null) {
        return gamma;
      }
      gamma = g;
      return f;
    };
    f.hue = function(h) {
      if (h == null) {
        return hue;
      }
      hue = h;
      if (type(hue) === 'array') {
        dh = hue[1] - hue[0];
        if (dh === 0) {
          hue = hue[1];
        }
      } else {
        dh = 0;
      }
      return f;
    };
    f.lightness = function(h) {
      if (h == null) {
        return lightness;
      }
      if (type(h) === 'array') {
        lightness = h;
        dl = h[1] - h[0];
      } else {
        lightness = [h, h];
        dl = 0;
      }
      return f;
    };
    f.scale = function() {
      return chroma.scale(f);
    };
    f.hue(hue);
    return f;
  };

  chroma.random = function() {
    var code, digits, i, o;
    digits = '0123456789abcdef';
    code = '#';
    for (i = o = 0; o < 6; i = ++o) {
      code += digits.charAt(floor(Math.random() * 16));
    }
    return new Color(code);
  };

  _interpolators = [];

  interpolate = function(col1, col2, f, m) {
    var interpol, len, o, res;
    if (f == null) {
      f = 0.5;
    }
    if (m == null) {
      m = 'rgb';
    }

    /*
    interpolates between colors
    f = 0 --> me
    f = 1 --> col
     */
    if (type(col1) !== 'object') {
      col1 = chroma(col1);
    }
    if (type(col2) !== 'object') {
      col2 = chroma(col2);
    }
    for (o = 0, len = _interpolators.length; o < len; o++) {
      interpol = _interpolators[o];
      if (m === interpol[0]) {
        res = interpol[1](col1, col2, f, m);
        break;
      }
    }
    if (res == null) {
      throw "color mode " + m + " is not supported";
    }
    return res.alpha(col1.alpha() + f * (col2.alpha() - col1.alpha()));
  };

  chroma.interpolate = interpolate;

  Color.prototype.interpolate = function(col2, f, m) {
    return interpolate(this, col2, f, m);
  };

  chroma.mix = interpolate;

  Color.prototype.mix = Color.prototype.interpolate;

  _input.rgb = function() {
    var k, ref, results, v;
    ref = unpack(arguments);
    results = [];
    for (k in ref) {
      v = ref[k];
      results.push(v);
    }
    return results;
  };

  chroma.rgb = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['rgb']), function(){});
  };

  Color.prototype.rgb = function(round) {
    if (round == null) {
      round = true;
    }
    if (round) {
      return this._rgb.map(Math.round).slice(0, 3);
    } else {
      return this._rgb.slice(0, 3);
    }
  };

  Color.prototype.rgba = function(round) {
    if (round == null) {
      round = true;
    }
    if (!round) {
      return this._rgb.slice(0);
    }
    return [Math.round(this._rgb[0]), Math.round(this._rgb[1]), Math.round(this._rgb[2]), this._rgb[3]];
  };

  _guess_formats.push({
    p: 3,
    test: function(n) {
      var a;
      a = unpack(arguments);
      if (type(a) === 'array' && a.length === 3) {
        return 'rgb';
      }
      if (a.length === 4 && type(a[3]) === "number" && a[3] >= 0 && a[3] <= 1) {
        return 'rgb';
      }
    }
  });

  _input.lrgb = _input.rgb;

  interpolate_lrgb = function(col1, col2, f, m) {
    var xyz0, xyz1;
    xyz0 = col1._rgb;
    xyz1 = col2._rgb;
    return new Color(sqrt(pow(xyz0[0], 2) * (1 - f) + pow(xyz1[0], 2) * f), sqrt(pow(xyz0[1], 2) * (1 - f) + pow(xyz1[1], 2) * f), sqrt(pow(xyz0[2], 2) * (1 - f) + pow(xyz1[2], 2) * f), m);
  };

  _average_lrgb = function(colors) {
    var col, f, len, o, rgb, xyz;
    f = 1 / colors.length;
    xyz = [0, 0, 0, 0];
    for (o = 0, len = colors.length; o < len; o++) {
      col = colors[o];
      rgb = col._rgb;
      xyz[0] += pow(rgb[0], 2) * f;
      xyz[1] += pow(rgb[1], 2) * f;
      xyz[2] += pow(rgb[2], 2) * f;
      xyz[3] += rgb[3] * f;
    }
    xyz[0] = sqrt(xyz[0]);
    xyz[1] = sqrt(xyz[1]);
    xyz[2] = sqrt(xyz[2]);
    if (xyz[3] > 1) {
      xyz[3] = 1;
    }
    return new Color(clip_rgb(xyz));
  };

  _interpolators.push(['lrgb', interpolate_lrgb]);

  chroma.average = function(colors, mode) {
    var A, alpha, c, cnt, dx, dy, first, i, l, len, o, xyz, xyz2;
    if (mode == null) {
      mode = 'rgb';
    }
    l = colors.length;
    colors = colors.map(function(c) {
      return chroma(c);
    });
    first = colors.splice(0, 1)[0];
    if (mode === 'lrgb') {
      return _average_lrgb(colors);
    }
    xyz = first.get(mode);
    cnt = [];
    dx = 0;
    dy = 0;
    for (i in xyz) {
      xyz[i] = xyz[i] || 0;
      cnt.push(isNaN(xyz[i]) ? 0 : 1);
      if (mode.charAt(i) === 'h' && !isNaN(xyz[i])) {
        A = xyz[i] / 180 * PI;
        dx += cos(A);
        dy += sin(A);
      }
    }
    alpha = first.alpha();
    for (o = 0, len = colors.length; o < len; o++) {
      c = colors[o];
      xyz2 = c.get(mode);
      alpha += c.alpha();
      for (i in xyz) {
        if (!isNaN(xyz2[i])) {
          cnt[i] += 1;
          if (mode.charAt(i) === 'h') {
            A = xyz2[i] / 180 * PI;
            dx += cos(A);
            dy += sin(A);
          } else {
            xyz[i] += xyz2[i];
          }
        }
      }
    }
    for (i in xyz) {
      if (mode.charAt(i) === 'h') {
        A = atan2(dy / cnt[i], dx / cnt[i]) / PI * 180;
        while (A < 0) {
          A += 360;
        }
        while (A >= 360) {
          A -= 360;
        }
        xyz[i] = A;
      } else {
        xyz[i] = xyz[i] / cnt[i];
      }
    }
    return chroma(xyz, mode).alpha(alpha / l);
  };

  hex2rgb = function(hex) {
    var a, b, g, r, rgb, u;
    if (hex.match(/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)) {
      if (hex.length === 4 || hex.length === 7) {
        hex = hex.substr(1);
      }
      if (hex.length === 3) {
        hex = hex.split("");
        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
      }
      u = parseInt(hex, 16);
      r = u >> 16;
      g = u >> 8 & 0xFF;
      b = u & 0xFF;
      return [r, g, b, 1];
    }
    if (hex.match(/^#?([A-Fa-f0-9]{8})$/)) {
      if (hex.length === 9) {
        hex = hex.substr(1);
      }
      u = parseInt(hex, 16);
      r = u >> 24 & 0xFF;
      g = u >> 16 & 0xFF;
      b = u >> 8 & 0xFF;
      a = round((u & 0xFF) / 0xFF * 100) / 100;
      return [r, g, b, a];
    }
    if ((_input.css != null) && (rgb = _input.css(hex))) {
      return rgb;
    }
    throw "unknown color: " + hex;
  };

  rgb2hex = function(channels, mode) {
    var a, b, g, hxa, r, str, u;
    if (mode == null) {
      mode = 'auto';
    }
    r = channels[0], g = channels[1], b = channels[2], a = channels[3];
    if (mode === 'auto') {
      mode = a < 1 ? 'rgba' : 'rgb';
    }
    r = Math.round(r);
    g = Math.round(g);
    b = Math.round(b);
    u = r << 16 | g << 8 | b;
    str = "000000" + u.toString(16);
    str = str.substr(str.length - 6);
    hxa = '0' + round(a * 255).toString(16);
    hxa = hxa.substr(hxa.length - 2);
    return "#" + (function() {
      switch (mode.toLowerCase()) {
        case 'rgba':
          return str + hxa;
        case 'argb':
          return hxa + str;
        default:
          return str;
      }
    })();
  };

  _input.hex = function(h) {
    return hex2rgb(h);
  };

  chroma.hex = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['hex']), function(){});
  };

  Color.prototype.hex = function(mode) {
    if (mode == null) {
      mode = 'auto';
    }
    return rgb2hex(this._rgb, mode);
  };

  _guess_formats.push({
    p: 4,
    test: function(n) {
      if (arguments.length === 1 && type(n) === "string") {
        return 'hex';
      }
    }
  });

  hsl2rgb = function() {
    var args, b, c, g, h, i, l, o, r, ref, s, t1, t2, t3;
    args = unpack(arguments);
    h = args[0], s = args[1], l = args[2];
    if (s === 0) {
      r = g = b = l * 255;
    } else {
      t3 = [0, 0, 0];
      c = [0, 0, 0];
      t2 = l < 0.5 ? l * (1 + s) : l + s - l * s;
      t1 = 2 * l - t2;
      h /= 360;
      t3[0] = h + 1 / 3;
      t3[1] = h;
      t3[2] = h - 1 / 3;
      for (i = o = 0; o <= 2; i = ++o) {
        if (t3[i] < 0) {
          t3[i] += 1;
        }
        if (t3[i] > 1) {
          t3[i] -= 1;
        }
        if (6 * t3[i] < 1) {
          c[i] = t1 + (t2 - t1) * 6 * t3[i];
        } else if (2 * t3[i] < 1) {
          c[i] = t2;
        } else if (3 * t3[i] < 2) {
          c[i] = t1 + (t2 - t1) * ((2 / 3) - t3[i]) * 6;
        } else {
          c[i] = t1;
        }
      }
      ref = [round(c[0] * 255), round(c[1] * 255), round(c[2] * 255)], r = ref[0], g = ref[1], b = ref[2];
    }
    if (args.length > 3) {
      return [r, g, b, args[3]];
    } else {
      return [r, g, b];
    }
  };

  rgb2hsl = function(r, g, b) {
    var h, l, min, ref, s;
    if (r !== void 0 && r.length >= 3) {
      ref = r, r = ref[0], g = ref[1], b = ref[2];
    }
    r /= 255;
    g /= 255;
    b /= 255;
    min = Math.min(r, g, b);
    max = Math.max(r, g, b);
    l = (max + min) / 2;
    if (max === min) {
      s = 0;
      h = Number.NaN;
    } else {
      s = l < 0.5 ? (max - min) / (max + min) : (max - min) / (2 - max - min);
    }
    if (r === max) {
      h = (g - b) / (max - min);
    } else if (g === max) {
      h = 2 + (b - r) / (max - min);
    } else if (b === max) {
      h = 4 + (r - g) / (max - min);
    }
    h *= 60;
    if (h < 0) {
      h += 360;
    }
    return [h, s, l];
  };

  chroma.hsl = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['hsl']), function(){});
  };

  _input.hsl = hsl2rgb;

  Color.prototype.hsl = function() {
    return rgb2hsl(this._rgb);
  };

  hsv2rgb = function() {
    var args, b, f, g, h, i, p, q, r, ref, ref1, ref2, ref3, ref4, ref5, s, t, v;
    args = unpack(arguments);
    h = args[0], s = args[1], v = args[2];
    v *= 255;
    if (s === 0) {
      r = g = b = v;
    } else {
      if (h === 360) {
        h = 0;
      }
      if (h > 360) {
        h -= 360;
      }
      if (h < 0) {
        h += 360;
      }
      h /= 60;
      i = floor(h);
      f = h - i;
      p = v * (1 - s);
      q = v * (1 - s * f);
      t = v * (1 - s * (1 - f));
      switch (i) {
        case 0:
          ref = [v, t, p], r = ref[0], g = ref[1], b = ref[2];
          break;
        case 1:
          ref1 = [q, v, p], r = ref1[0], g = ref1[1], b = ref1[2];
          break;
        case 2:
          ref2 = [p, v, t], r = ref2[0], g = ref2[1], b = ref2[2];
          break;
        case 3:
          ref3 = [p, q, v], r = ref3[0], g = ref3[1], b = ref3[2];
          break;
        case 4:
          ref4 = [t, p, v], r = ref4[0], g = ref4[1], b = ref4[2];
          break;
        case 5:
          ref5 = [v, p, q], r = ref5[0], g = ref5[1], b = ref5[2];
      }
    }
    return [r, g, b, args.length > 3 ? args[3] : 1];
  };

  rgb2hsv = function() {
    var b, delta, g, h, min, r, ref, s, v;
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    min = Math.min(r, g, b);
    max = Math.max(r, g, b);
    delta = max - min;
    v = max / 255.0;
    if (max === 0) {
      h = Number.NaN;
      s = 0;
    } else {
      s = delta / max;
      if (r === max) {
        h = (g - b) / delta;
      }
      if (g === max) {
        h = 2 + (b - r) / delta;
      }
      if (b === max) {
        h = 4 + (r - g) / delta;
      }
      h *= 60;
      if (h < 0) {
        h += 360;
      }
    }
    return [h, s, v];
  };

  chroma.hsv = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['hsv']), function(){});
  };

  _input.hsv = hsv2rgb;

  Color.prototype.hsv = function() {
    return rgb2hsv(this._rgb);
  };

  num2rgb = function(num) {
    var b, g, r;
    if (type(num) === "number" && num >= 0 && num <= 0xFFFFFF) {
      r = num >> 16;
      g = (num >> 8) & 0xFF;
      b = num & 0xFF;
      return [r, g, b, 1];
    }
    console.warn("unknown num color: " + num);
    return [0, 0, 0, 1];
  };

  rgb2num = function() {
    var b, g, r, ref;
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    return (r << 16) + (g << 8) + b;
  };

  chroma.num = function(num) {
    return new Color(num, 'num');
  };

  Color.prototype.num = function(mode) {
    if (mode == null) {
      mode = 'rgb';
    }
    return rgb2num(this._rgb, mode);
  };

  _input.num = num2rgb;

  _guess_formats.push({
    p: 1,
    test: function(n) {
      if (arguments.length === 1 && type(n) === "number" && n >= 0 && n <= 0xFFFFFF) {
        return 'num';
      }
    }
  });

  hcg2rgb = function() {
    var _c, _g, args, b, c, f, g, h, i, p, q, r, ref, ref1, ref2, ref3, ref4, ref5, t, v;
    args = unpack(arguments);
    h = args[0], c = args[1], _g = args[2];
    c = c / 100;
    g = g / 100 * 255;
    _c = c * 255;
    if (c === 0) {
      r = g = b = _g;
    } else {
      if (h === 360) {
        h = 0;
      }
      if (h > 360) {
        h -= 360;
      }
      if (h < 0) {
        h += 360;
      }
      h /= 60;
      i = floor(h);
      f = h - i;
      p = _g * (1 - c);
      q = p + _c * (1 - f);
      t = p + _c * f;
      v = p + _c;
      switch (i) {
        case 0:
          ref = [v, t, p], r = ref[0], g = ref[1], b = ref[2];
          break;
        case 1:
          ref1 = [q, v, p], r = ref1[0], g = ref1[1], b = ref1[2];
          break;
        case 2:
          ref2 = [p, v, t], r = ref2[0], g = ref2[1], b = ref2[2];
          break;
        case 3:
          ref3 = [p, q, v], r = ref3[0], g = ref3[1], b = ref3[2];
          break;
        case 4:
          ref4 = [t, p, v], r = ref4[0], g = ref4[1], b = ref4[2];
          break;
        case 5:
          ref5 = [v, p, q], r = ref5[0], g = ref5[1], b = ref5[2];
      }
    }
    return [r, g, b, args.length > 3 ? args[3] : 1];
  };

  rgb2hcg = function() {
    var _g, b, c, delta, g, h, min, r, ref;
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    min = Math.min(r, g, b);
    max = Math.max(r, g, b);
    delta = max - min;
    c = delta * 100 / 255;
    _g = min / (255 - delta) * 100;
    if (delta === 0) {
      h = Number.NaN;
    } else {
      if (r === max) {
        h = (g - b) / delta;
      }
      if (g === max) {
        h = 2 + (b - r) / delta;
      }
      if (b === max) {
        h = 4 + (r - g) / delta;
      }
      h *= 60;
      if (h < 0) {
        h += 360;
      }
    }
    return [h, c, _g];
  };

  chroma.hcg = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['hcg']), function(){});
  };

  _input.hcg = hcg2rgb;

  Color.prototype.hcg = function() {
    return rgb2hcg(this._rgb);
  };

  css2rgb = function(css) {
    var aa, ab, hsl, i, m, o, rgb, w;
    css = css.toLowerCase();
    if ((chroma.colors != null) && chroma.colors[css]) {
      return hex2rgb(chroma.colors[css]);
    }
    if (m = css.match(/rgb\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*\)/)) {
      rgb = m.slice(1, 4);
      for (i = o = 0; o <= 2; i = ++o) {
        rgb[i] = +rgb[i];
      }
      rgb[3] = 1;
    } else if (m = css.match(/rgba\(\s*(\-?\d+),\s*(\-?\d+)\s*,\s*(\-?\d+)\s*,\s*([01]|[01]?\.\d+)\)/)) {
      rgb = m.slice(1, 5);
      for (i = w = 0; w <= 3; i = ++w) {
        rgb[i] = +rgb[i];
      }
    } else if (m = css.match(/rgb\(\s*(\-?\d+(?:\.\d+)?)%,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*\)/)) {
      rgb = m.slice(1, 4);
      for (i = aa = 0; aa <= 2; i = ++aa) {
        rgb[i] = round(rgb[i] * 2.55);
      }
      rgb[3] = 1;
    } else if (m = css.match(/rgba\(\s*(\-?\d+(?:\.\d+)?)%,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)/)) {
      rgb = m.slice(1, 5);
      for (i = ab = 0; ab <= 2; i = ++ab) {
        rgb[i] = round(rgb[i] * 2.55);
      }
      rgb[3] = +rgb[3];
    } else if (m = css.match(/hsl\(\s*(\-?\d+(?:\.\d+)?),\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*\)/)) {
      hsl = m.slice(1, 4);
      hsl[1] *= 0.01;
      hsl[2] *= 0.01;
      rgb = hsl2rgb(hsl);
      rgb[3] = 1;
    } else if (m = css.match(/hsla\(\s*(\-?\d+(?:\.\d+)?),\s*(\-?\d+(?:\.\d+)?)%\s*,\s*(\-?\d+(?:\.\d+)?)%\s*,\s*([01]|[01]?\.\d+)\)/)) {
      hsl = m.slice(1, 4);
      hsl[1] *= 0.01;
      hsl[2] *= 0.01;
      rgb = hsl2rgb(hsl);
      rgb[3] = +m[4];
    }
    return rgb;
  };

  rgb2css = function(rgba) {
    var mode;
    mode = rgba[3] < 1 ? 'rgba' : 'rgb';
    if (mode === 'rgb') {
      return mode + '(' + rgba.slice(0, 3).map(round).join(',') + ')';
    } else if (mode === 'rgba') {
      return mode + '(' + rgba.slice(0, 3).map(round).join(',') + ',' + rgba[3] + ')';
    } else {

    }
  };

  rnd = function(a) {
    return round(a * 100) / 100;
  };

  hsl2css = function(hsl, alpha) {
    var mode;
    mode = alpha < 1 ? 'hsla' : 'hsl';
    hsl[0] = rnd(hsl[0] || 0);
    hsl[1] = rnd(hsl[1] * 100) + '%';
    hsl[2] = rnd(hsl[2] * 100) + '%';
    if (mode === 'hsla') {
      hsl[3] = alpha;
    }
    return mode + '(' + hsl.join(',') + ')';
  };

  _input.css = function(h) {
    return css2rgb(h);
  };

  chroma.css = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['css']), function(){});
  };

  Color.prototype.css = function(mode) {
    if (mode == null) {
      mode = 'rgb';
    }
    if (mode.slice(0, 3) === 'rgb') {
      return rgb2css(this._rgb);
    } else if (mode.slice(0, 3) === 'hsl') {
      return hsl2css(this.hsl(), this.alpha());
    }
  };

  _input.named = function(name) {
    return hex2rgb(w3cx11[name]);
  };

  _guess_formats.push({
    p: 5,
    test: function(n) {
      if (arguments.length === 1 && (w3cx11[n] != null)) {
        return 'named';
      }
    }
  });

  Color.prototype.name = function(n) {
    var h, k;
    if (arguments.length) {
      if (w3cx11[n]) {
        this._rgb = hex2rgb(w3cx11[n]);
      }
      this._rgb[3] = 1;
      this;
    }
    h = this.hex('rgb');
    for (k in w3cx11) {
      if (h === w3cx11[k]) {
        return k;
      }
    }
    return h;
  };

  lch2lab = function() {

    /*
    Convert from a qualitative parameter h and a quantitative parameter l to a 24-bit pixel.
    These formulas were invented by David Dalrymple to obtain maximum contrast without going
    out of gamut if the parameters are in the range 0-1.
    
    A saturation multiplier was added by Gregor Aisch
     */
    var c, h, l, ref;
    ref = unpack(arguments), l = ref[0], c = ref[1], h = ref[2];
    h = h * DEG2RAD;
    return [l, cos(h) * c, sin(h) * c];
  };

  lch2rgb = function() {
    var L, a, args, b, c, g, h, l, r, ref, ref1;
    args = unpack(arguments);
    l = args[0], c = args[1], h = args[2];
    ref = lch2lab(l, c, h), L = ref[0], a = ref[1], b = ref[2];
    ref1 = lab2rgb(L, a, b), r = ref1[0], g = ref1[1], b = ref1[2];
    return [r, g, b, args.length > 3 ? args[3] : 1];
  };

  lab2lch = function() {
    var a, b, c, h, l, ref;
    ref = unpack(arguments), l = ref[0], a = ref[1], b = ref[2];
    c = sqrt(a * a + b * b);
    h = (atan2(b, a) * RAD2DEG + 360) % 360;
    if (round(c * 10000) === 0) {
      h = Number.NaN;
    }
    return [l, c, h];
  };

  rgb2lch = function() {
    var a, b, g, l, r, ref, ref1;
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    ref1 = rgb2lab(r, g, b), l = ref1[0], a = ref1[1], b = ref1[2];
    return lab2lch(l, a, b);
  };

  chroma.lch = function() {
    var args;
    args = unpack(arguments);
    return new Color(args, 'lch');
  };

  chroma.hcl = function() {
    var args;
    args = unpack(arguments);
    return new Color(args, 'hcl');
  };

  _input.lch = lch2rgb;

  _input.hcl = function() {
    var c, h, l, ref;
    ref = unpack(arguments), h = ref[0], c = ref[1], l = ref[2];
    return lch2rgb([l, c, h]);
  };

  Color.prototype.lch = function() {
    return rgb2lch(this._rgb);
  };

  Color.prototype.hcl = function() {
    return rgb2lch(this._rgb).reverse();
  };

  rgb2cmyk = function(mode) {
    var b, c, f, g, k, m, r, ref, y;
    if (mode == null) {
      mode = 'rgb';
    }
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    r = r / 255;
    g = g / 255;
    b = b / 255;
    k = 1 - Math.max(r, Math.max(g, b));
    f = k < 1 ? 1 / (1 - k) : 0;
    c = (1 - r - k) * f;
    m = (1 - g - k) * f;
    y = (1 - b - k) * f;
    return [c, m, y, k];
  };

  cmyk2rgb = function() {
    var alpha, args, b, c, g, k, m, r, y;
    args = unpack(arguments);
    c = args[0], m = args[1], y = args[2], k = args[3];
    alpha = args.length > 4 ? args[4] : 1;
    if (k === 1) {
      return [0, 0, 0, alpha];
    }
    r = c >= 1 ? 0 : 255 * (1 - c) * (1 - k);
    g = m >= 1 ? 0 : 255 * (1 - m) * (1 - k);
    b = y >= 1 ? 0 : 255 * (1 - y) * (1 - k);
    return [r, g, b, alpha];
  };

  _input.cmyk = function() {
    return cmyk2rgb(unpack(arguments));
  };

  chroma.cmyk = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['cmyk']), function(){});
  };

  Color.prototype.cmyk = function() {
    return rgb2cmyk(this._rgb);
  };

  _input.gl = function() {
    var i, k, o, rgb, v;
    rgb = (function() {
      var ref, results;
      ref = unpack(arguments);
      results = [];
      for (k in ref) {
        v = ref[k];
        results.push(v);
      }
      return results;
    }).apply(this, arguments);
    for (i = o = 0; o <= 2; i = ++o) {
      rgb[i] *= 255;
    }
    return rgb;
  };

  chroma.gl = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['gl']), function(){});
  };

  Color.prototype.gl = function() {
    var rgb;
    rgb = this._rgb;
    return [rgb[0] / 255, rgb[1] / 255, rgb[2] / 255, rgb[3]];
  };

  rgb2luminance = function(r, g, b) {
    var ref;
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    r = luminance_x(r);
    g = luminance_x(g);
    b = luminance_x(b);
    return 0.2126 * r + 0.7152 * g + 0.0722 * b;
  };

  luminance_x = function(x) {
    x /= 255;
    if (x <= 0.03928) {
      return x / 12.92;
    } else {
      return pow((x + 0.055) / 1.055, 2.4);
    }
  };

  interpolate_rgb = function(col1, col2, f, m) {
    var xyz0, xyz1;
    xyz0 = col1._rgb;
    xyz1 = col2._rgb;
    return new Color(xyz0[0] + f * (xyz1[0] - xyz0[0]), xyz0[1] + f * (xyz1[1] - xyz0[1]), xyz0[2] + f * (xyz1[2] - xyz0[2]), m);
  };

  _interpolators.push(['rgb', interpolate_rgb]);

  Color.prototype.luminance = function(lum, mode) {
    var cur_lum, eps, max_iter, rgba, test;
    if (mode == null) {
      mode = 'rgb';
    }
    if (!arguments.length) {
      return rgb2luminance(this._rgb);
    }
    rgba = this._rgb;
    if (lum === 0) {
      rgba = [0, 0, 0, this._rgb[3]];
    } else if (lum === 1) {
      rgba = [255, 255, 255, this[3]];
    } else {
      cur_lum = rgb2luminance(this._rgb);
      eps = 1e-7;
      max_iter = 20;
      test = function(l, h) {
        var lm, m;
        m = l.interpolate(h, 0.5, mode);
        lm = m.luminance();
        if (Math.abs(lum - lm) < eps || !max_iter--) {
          return m;
        }
        if (lm > lum) {
          return test(l, m);
        }
        return test(m, h);
      };
      if (cur_lum > lum) {
        rgba = test(chroma('black'), this).rgba();
      } else {
        rgba = test(this, chroma('white')).rgba();
      }
    }
    return chroma(rgba).alpha(this.alpha());
  };

  temperature2rgb = function(kelvin) {
    var b, g, r, temp;
    temp = kelvin / 100;
    if (temp < 66) {
      r = 255;
      g = -155.25485562709179 - 0.44596950469579133 * (g = temp - 2) + 104.49216199393888 * log(g);
      b = temp < 20 ? 0 : -254.76935184120902 + 0.8274096064007395 * (b = temp - 10) + 115.67994401066147 * log(b);
    } else {
      r = 351.97690566805693 + 0.114206453784165 * (r = temp - 55) - 40.25366309332127 * log(r);
      g = 325.4494125711974 + 0.07943456536662342 * (g = temp - 50) - 28.0852963507957 * log(g);
      b = 255;
    }
    return [r, g, b];
  };

  rgb2temperature = function() {
    var b, eps, g, maxTemp, minTemp, r, ref, rgb, temp;
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    minTemp = 1000;
    maxTemp = 40000;
    eps = 0.4;
    while (maxTemp - minTemp > eps) {
      temp = (maxTemp + minTemp) * 0.5;
      rgb = temperature2rgb(temp);
      if ((rgb[2] / rgb[0]) >= (b / r)) {
        maxTemp = temp;
      } else {
        minTemp = temp;
      }
    }
    return round(temp);
  };

  chroma.temperature = chroma.kelvin = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['temperature']), function(){});
  };

  _input.temperature = _input.kelvin = _input.K = temperature2rgb;

  Color.prototype.temperature = function() {
    return rgb2temperature(this._rgb);
  };

  Color.prototype.kelvin = Color.prototype.temperature;

  chroma.contrast = function(a, b) {
    var l1, l2, ref, ref1;
    if ((ref = type(a)) === 'string' || ref === 'number') {
      a = new Color(a);
    }
    if ((ref1 = type(b)) === 'string' || ref1 === 'number') {
      b = new Color(b);
    }
    l1 = a.luminance();
    l2 = b.luminance();
    if (l1 > l2) {
      return (l1 + 0.05) / (l2 + 0.05);
    } else {
      return (l2 + 0.05) / (l1 + 0.05);
    }
  };

  chroma.distance = function(a, b, mode) {
    var d, i, l1, l2, ref, ref1, sum_sq;
    if (mode == null) {
      mode = 'lab';
    }
    if ((ref = type(a)) === 'string' || ref === 'number') {
      a = new Color(a);
    }
    if ((ref1 = type(b)) === 'string' || ref1 === 'number') {
      b = new Color(b);
    }
    l1 = a.get(mode);
    l2 = b.get(mode);
    sum_sq = 0;
    for (i in l1) {
      d = (l1[i] || 0) - (l2[i] || 0);
      sum_sq += d * d;
    }
    return Math.sqrt(sum_sq);
  };

  chroma.deltaE = function(a, b, L, C) {
    var L1, L2, a1, a2, b1, b2, c1, c2, c4, dH2, delA, delB, delC, delL, f, h1, ref, ref1, ref2, ref3, sc, sh, sl, t, v1, v2, v3;
    if (L == null) {
      L = 1;
    }
    if (C == null) {
      C = 1;
    }
    if ((ref = type(a)) === 'string' || ref === 'number') {
      a = new Color(a);
    }
    if ((ref1 = type(b)) === 'string' || ref1 === 'number') {
      b = new Color(b);
    }
    ref2 = a.lab(), L1 = ref2[0], a1 = ref2[1], b1 = ref2[2];
    ref3 = b.lab(), L2 = ref3[0], a2 = ref3[1], b2 = ref3[2];
    c1 = sqrt(a1 * a1 + b1 * b1);
    c2 = sqrt(a2 * a2 + b2 * b2);
    sl = L1 < 16.0 ? 0.511 : (0.040975 * L1) / (1.0 + 0.01765 * L1);
    sc = (0.0638 * c1) / (1.0 + 0.0131 * c1) + 0.638;
    h1 = c1 < 0.000001 ? 0.0 : (atan2(b1, a1) * 180.0) / PI;
    while (h1 < 0) {
      h1 += 360;
    }
    while (h1 >= 360) {
      h1 -= 360;
    }
    t = (h1 >= 164.0) && (h1 <= 345.0) ? 0.56 + abs(0.2 * cos((PI * (h1 + 168.0)) / 180.0)) : 0.36 + abs(0.4 * cos((PI * (h1 + 35.0)) / 180.0));
    c4 = c1 * c1 * c1 * c1;
    f = sqrt(c4 / (c4 + 1900.0));
    sh = sc * (f * t + 1.0 - f);
    delL = L1 - L2;
    delC = c1 - c2;
    delA = a1 - a2;
    delB = b1 - b2;
    dH2 = delA * delA + delB * delB - delC * delC;
    v1 = delL / (L * sl);
    v2 = delC / (C * sc);
    v3 = sh;
    return sqrt(v1 * v1 + v2 * v2 + (dH2 / (v3 * v3)));
  };

  Color.prototype.get = function(modechan) {
    var channel, i, me, mode, ref, src;
    me = this;
    ref = modechan.split('.'), mode = ref[0], channel = ref[1];
    src = me[mode]();
    if (channel) {
      i = mode.indexOf(channel);
      if (i > -1) {
        return src[i];
      } else {
        return console.warn('unknown channel ' + channel + ' in mode ' + mode);
      }
    } else {
      return src;
    }
  };

  Color.prototype.set = function(modechan, value) {
    var channel, i, me, mode, ref, src;
    me = this;
    ref = modechan.split('.'), mode = ref[0], channel = ref[1];
    if (channel) {
      src = me[mode]();
      i = mode.indexOf(channel);
      if (i > -1) {
        if (type(value) === 'string') {
          switch (value.charAt(0)) {
            case '+':
              src[i] += +value;
              break;
            case '-':
              src[i] += +value;
              break;
            case '*':
              src[i] *= +(value.substr(1));
              break;
            case '/':
              src[i] /= +(value.substr(1));
              break;
            default:
              src[i] = +value;
          }
        } else {
          src[i] = value;
        }
      } else {
        console.warn('unknown channel ' + channel + ' in mode ' + mode);
      }
    } else {
      src = value;
    }
    return chroma(src, mode).alpha(me.alpha());
  };

  Color.prototype.clipped = function() {
    return this._rgb._clipped || false;
  };

  Color.prototype.alpha = function(a) {
    if (arguments.length) {
      return chroma.rgb([this._rgb[0], this._rgb[1], this._rgb[2], a]);
    }
    return this._rgb[3];
  };

  Color.prototype.darken = function(amount) {
    var lab, me;
    if (amount == null) {
      amount = 1;
    }
    me = this;
    lab = me.lab();
    lab[0] -= LAB_CONSTANTS.Kn * amount;
    return chroma.lab(lab).alpha(me.alpha());
  };

  Color.prototype.brighten = function(amount) {
    if (amount == null) {
      amount = 1;
    }
    return this.darken(-amount);
  };

  Color.prototype.darker = Color.prototype.darken;

  Color.prototype.brighter = Color.prototype.brighten;

  Color.prototype.saturate = function(amount) {
    var lch, me;
    if (amount == null) {
      amount = 1;
    }
    me = this;
    lch = me.lch();
    lch[1] += amount * LAB_CONSTANTS.Kn;
    if (lch[1] < 0) {
      lch[1] = 0;
    }
    return chroma.lch(lch).alpha(me.alpha());
  };

  Color.prototype.desaturate = function(amount) {
    if (amount == null) {
      amount = 1;
    }
    return this.saturate(-amount);
  };

  Color.prototype.premultiply = function() {
    var a, rgb;
    rgb = this.rgb();
    a = this.alpha();
    return chroma(rgb[0] * a, rgb[1] * a, rgb[2] * a, a);
  };

  blend = function(bottom, top, mode) {
    if (!blend[mode]) {
      throw 'unknown blend mode ' + mode;
    }
    return blend[mode](bottom, top);
  };

  blend_f = function(f) {
    return function(bottom, top) {
      var c0, c1;
      c0 = chroma(top).rgb();
      c1 = chroma(bottom).rgb();
      return chroma(f(c0, c1), 'rgb');
    };
  };

  each = function(f) {
    return function(c0, c1) {
      var i, o, out;
      out = [];
      for (i = o = 0; o <= 3; i = ++o) {
        out[i] = f(c0[i], c1[i]);
      }
      return out;
    };
  };

  normal = function(a, b) {
    return a;
  };

  multiply = function(a, b) {
    return a * b / 255;
  };

  darken = function(a, b) {
    if (a > b) {
      return b;
    } else {
      return a;
    }
  };

  lighten = function(a, b) {
    if (a > b) {
      return a;
    } else {
      return b;
    }
  };

  screen = function(a, b) {
    return 255 * (1 - (1 - a / 255) * (1 - b / 255));
  };

  overlay = function(a, b) {
    if (b < 128) {
      return 2 * a * b / 255;
    } else {
      return 255 * (1 - 2 * (1 - a / 255) * (1 - b / 255));
    }
  };

  burn = function(a, b) {
    return 255 * (1 - (1 - b / 255) / (a / 255));
  };

  dodge = function(a, b) {
    if (a === 255) {
      return 255;
    }
    a = 255 * (b / 255) / (1 - a / 255);
    if (a > 255) {
      return 255;
    } else {
      return a;
    }
  };

  blend.normal = blend_f(each(normal));

  blend.multiply = blend_f(each(multiply));

  blend.screen = blend_f(each(screen));

  blend.overlay = blend_f(each(overlay));

  blend.darken = blend_f(each(darken));

  blend.lighten = blend_f(each(lighten));

  blend.dodge = blend_f(each(dodge));

  blend.burn = blend_f(each(burn));

  chroma.blend = blend;

  chroma.analyze = function(data) {
    var len, o, r, val;
    r = {
      min: Number.MAX_VALUE,
      max: Number.MAX_VALUE * -1,
      sum: 0,
      values: [],
      count: 0
    };
    for (o = 0, len = data.length; o < len; o++) {
      val = data[o];
      if ((val != null) && !isNaN(val)) {
        r.values.push(val);
        r.sum += val;
        if (val < r.min) {
          r.min = val;
        }
        if (val > r.max) {
          r.max = val;
        }
        r.count += 1;
      }
    }
    r.domain = [r.min, r.max];
    r.limits = function(mode, num) {
      return chroma.limits(r, mode, num);
    };
    return r;
  };

  chroma.scale = function(colors, positions) {
    var _classes, _colorCache, _colors, _correctLightness, _domain, _fixed, _gamma, _max, _min, _mode, _nacol, _out, _padding, _pos, _spread, _useCache, classifyValue, f, getClass, getColor, resetCache, setColors, tmap;
    _mode = 'rgb';
    _nacol = chroma('#ccc');
    _spread = 0;
    _fixed = false;
    _domain = [0, 1];
    _pos = [];
    _padding = [0, 0];
    _classes = false;
    _colors = [];
    _out = false;
    _min = 0;
    _max = 1;
    _correctLightness = false;
    _colorCache = {};
    _useCache = true;
    _gamma = 1;
    setColors = function(colors) {
      var c, col, o, ref, ref1, w;
      if (colors == null) {
        colors = ['#fff', '#000'];
      }
      if ((colors != null) && type(colors) === 'string' && (chroma.brewer != null)) {
        colors = chroma.brewer[colors] || chroma.brewer[colors.toLowerCase()] || colors;
      }
      if (type(colors) === 'array') {
        if (colors.length === 1) {
          colors = [colors[0], colors[0]];
        }
        colors = colors.slice(0);
        for (c = o = 0, ref = colors.length - 1; 0 <= ref ? o <= ref : o >= ref; c = 0 <= ref ? ++o : --o) {
          col = colors[c];
          if (type(col) === "string") {
            colors[c] = chroma(col);
          }
        }
        _pos.length = 0;
        for (c = w = 0, ref1 = colors.length - 1; 0 <= ref1 ? w <= ref1 : w >= ref1; c = 0 <= ref1 ? ++w : --w) {
          _pos.push(c / (colors.length - 1));
        }
      }
      resetCache();
      return _colors = colors;
    };
    getClass = function(value) {
      var i, n;
      if (_classes != null) {
        n = _classes.length - 1;
        i = 0;
        while (i < n && value >= _classes[i]) {
          i++;
        }
        return i - 1;
      }
      return 0;
    };
    tmap = function(t) {
      return t;
    };
    classifyValue = function(value) {
      var i, maxc, minc, n, val;
      val = value;
      if (_classes.length > 2) {
        n = _classes.length - 1;
        i = getClass(value);
        minc = _classes[0] + (_classes[1] - _classes[0]) * (0 + _spread * 0.5);
        maxc = _classes[n - 1] + (_classes[n] - _classes[n - 1]) * (1 - _spread * 0.5);
        val = _min + ((_classes[i] + (_classes[i + 1] - _classes[i]) * 0.5 - minc) / (maxc - minc)) * (_max - _min);
      }
      return val;
    };
    getColor = function(val, bypassMap) {
      var c, col, i, k, o, p, ref, t;
      if (bypassMap == null) {
        bypassMap = false;
      }
      if (isNaN(val) || val === null) {
        return _nacol;
      }
      if (!bypassMap) {
        if (_classes && _classes.length > 2) {
          c = getClass(val);
          t = c / (_classes.length - 2);
        } else if (_max !== _min) {
          t = (val - _min) / (_max - _min);
        } else {
          t = 1;
        }
      } else {
        t = val;
      }
      if (!bypassMap) {
        t = tmap(t);
      }
      if (_gamma !== 1) {
        t = pow(t, _gamma);
      }
      t = _padding[0] + (t * (1 - _padding[0] - _padding[1]));
      t = Math.min(1, Math.max(0, t));
      k = Math.floor(t * 10000);
      if (_useCache && _colorCache[k]) {
        col = _colorCache[k];
      } else {
        if (type(_colors) === 'array') {
          for (i = o = 0, ref = _pos.length - 1; 0 <= ref ? o <= ref : o >= ref; i = 0 <= ref ? ++o : --o) {
            p = _pos[i];
            if (t <= p) {
              col = _colors[i];
              break;
            }
            if (t >= p && i === _pos.length - 1) {
              col = _colors[i];
              break;
            }
            if (t > p && t < _pos[i + 1]) {
              t = (t - p) / (_pos[i + 1] - p);
              col = chroma.interpolate(_colors[i], _colors[i + 1], t, _mode);
              break;
            }
          }
        } else if (type(_colors) === 'function') {
          col = _colors(t);
        }
        if (_useCache) {
          _colorCache[k] = col;
        }
      }
      return col;
    };
    resetCache = function() {
      return _colorCache = {};
    };
    setColors(colors);
    f = function(v) {
      var c;
      c = chroma(getColor(v));
      if (_out && c[_out]) {
        return c[_out]();
      } else {
        return c;
      }
    };
    f.classes = function(classes) {
      var d;
      if (classes != null) {
        if (type(classes) === 'array') {
          _classes = classes;
          _domain = [classes[0], classes[classes.length - 1]];
        } else {
          d = chroma.analyze(_domain);
          if (classes === 0) {
            _classes = [d.min, d.max];
          } else {
            _classes = chroma.limits(d, 'e', classes);
          }
        }
        return f;
      }
      return _classes;
    };
    f.domain = function(domain) {
      var c, d, k, len, o, ref, w;
      if (!arguments.length) {
        return _domain;
      }
      _min = domain[0];
      _max = domain[domain.length - 1];
      _pos = [];
      k = _colors.length;
      if (domain.length === k && _min !== _max) {
        for (o = 0, len = domain.length; o < len; o++) {
          d = domain[o];
          _pos.push((d - _min) / (_max - _min));
        }
      } else {
        for (c = w = 0, ref = k - 1; 0 <= ref ? w <= ref : w >= ref; c = 0 <= ref ? ++w : --w) {
          _pos.push(c / (k - 1));
        }
      }
      _domain = [_min, _max];
      return f;
    };
    f.mode = function(_m) {
      if (!arguments.length) {
        return _mode;
      }
      _mode = _m;
      resetCache();
      return f;
    };
    f.range = function(colors, _pos) {
      setColors(colors, _pos);
      return f;
    };
    f.out = function(_o) {
      _out = _o;
      return f;
    };
    f.spread = function(val) {
      if (!arguments.length) {
        return _spread;
      }
      _spread = val;
      return f;
    };
    f.correctLightness = function(v) {
      if (v == null) {
        v = true;
      }
      _correctLightness = v;
      resetCache();
      if (_correctLightness) {
        tmap = function(t) {
          var L0, L1, L_actual, L_diff, L_ideal, max_iter, pol, t0, t1;
          L0 = getColor(0, true).lab()[0];
          L1 = getColor(1, true).lab()[0];
          pol = L0 > L1;
          L_actual = getColor(t, true).lab()[0];
          L_ideal = L0 + (L1 - L0) * t;
          L_diff = L_actual - L_ideal;
          t0 = 0;
          t1 = 1;
          max_iter = 20;
          while (Math.abs(L_diff) > 1e-2 && max_iter-- > 0) {
            (function() {
              if (pol) {
                L_diff *= -1;
              }
              if (L_diff < 0) {
                t0 = t;
                t += (t1 - t) * 0.5;
              } else {
                t1 = t;
                t += (t0 - t) * 0.5;
              }
              L_actual = getColor(t, true).lab()[0];
              return L_diff = L_actual - L_ideal;
            })();
          }
          return t;
        };
      } else {
        tmap = function(t) {
          return t;
        };
      }
      return f;
    };
    f.padding = function(p) {
      if (p != null) {
        if (type(p) === 'number') {
          p = [p, p];
        }
        _padding = p;
        return f;
      } else {
        return _padding;
      }
    };
    f.colors = function(numColors, out) {
      var dd, dm, i, o, ref, result, results, samples, w;
      if (arguments.length < 2) {
        out = 'hex';
      }
      result = [];
      if (arguments.length === 0) {
        result = _colors.slice(0);
      } else if (numColors === 1) {
        result = [f(0.5)];
      } else if (numColors > 1) {
        dm = _domain[0];
        dd = _domain[1] - dm;
        result = (function() {
          results = [];
          for (var o = 0; 0 <= numColors ? o < numColors : o > numColors; 0 <= numColors ? o++ : o--){ results.push(o); }
          return results;
        }).apply(this).map(function(i) {
          return f(dm + i / (numColors - 1) * dd);
        });
      } else {
        colors = [];
        samples = [];
        if (_classes && _classes.length > 2) {
          for (i = w = 1, ref = _classes.length; 1 <= ref ? w < ref : w > ref; i = 1 <= ref ? ++w : --w) {
            samples.push((_classes[i - 1] + _classes[i]) * 0.5);
          }
        } else {
          samples = _domain;
        }
        result = samples.map(function(v) {
          return f(v);
        });
      }
      if (chroma[out]) {
        result = result.map(function(c) {
          return c[out]();
        });
      }
      return result;
    };
    f.cache = function(c) {
      if (c != null) {
        _useCache = c;
        return f;
      } else {
        return _useCache;
      }
    };
    f.gamma = function(g) {
      if (g != null) {
        _gamma = g;
        return f;
      } else {
        return _gamma;
      }
    };
    f.nodata = function(d) {
      if (d != null) {
        _nacol = chroma(d);
        return f;
      } else {
        return _nacol;
      }
    };
    return f;
  };

  if (chroma.scales == null) {
    chroma.scales = {};
  }

  chroma.scales.cool = function() {
    return chroma.scale([chroma.hsl(180, 1, .9), chroma.hsl(250, .7, .4)]);
  };

  chroma.scales.hot = function() {
    return chroma.scale(['#000', '#f00', '#ff0', '#fff'], [0, .25, .75, 1]).mode('rgb');
  };

  chroma.analyze = function(data, key, filter) {
    var add, k, len, o, r, val, visit;
    r = {
      min: Number.MAX_VALUE,
      max: Number.MAX_VALUE * -1,
      sum: 0,
      values: [],
      count: 0
    };
    if (filter == null) {
      filter = function() {
        return true;
      };
    }
    add = function(val) {
      if ((val != null) && !isNaN(val)) {
        r.values.push(val);
        r.sum += val;
        if (val < r.min) {
          r.min = val;
        }
        if (val > r.max) {
          r.max = val;
        }
        r.count += 1;
      }
    };
    visit = function(val, k) {
      if (filter(val, k)) {
        if ((key != null) && type(key) === 'function') {
          return add(key(val));
        } else if ((key != null) && type(key) === 'string' || type(key) === 'number') {
          return add(val[key]);
        } else {
          return add(val);
        }
      }
    };
    if (type(data) === 'array') {
      for (o = 0, len = data.length; o < len; o++) {
        val = data[o];
        visit(val);
      }
    } else {
      for (k in data) {
        val = data[k];
        visit(val, k);
      }
    }
    r.domain = [r.min, r.max];
    r.limits = function(mode, num) {
      return chroma.limits(r, mode, num);
    };
    return r;
  };

  chroma.limits = function(data, mode, num) {
    var aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am, assignments, best, centroids, cluster, clusterSizes, dist, i, j, kClusters, limits, max_log, min, min_log, mindist, n, nb_iters, newCentroids, o, p, pb, pr, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, repeat, sum, tmpKMeansBreaks, v, value, values, w;
    if (mode == null) {
      mode = 'equal';
    }
    if (num == null) {
      num = 7;
    }
    if (type(data) === 'array') {
      data = chroma.analyze(data);
    }
    min = data.min;
    max = data.max;
    sum = data.sum;
    values = data.values.sort(function(a, b) {
      return a - b;
    });
    if (num === 1) {
      return [min, max];
    }
    limits = [];
    if (mode.substr(0, 1) === 'c') {
      limits.push(min);
      limits.push(max);
    }
    if (mode.substr(0, 1) === 'e') {
      limits.push(min);
      for (i = o = 1, ref = num - 1; 1 <= ref ? o <= ref : o >= ref; i = 1 <= ref ? ++o : --o) {
        limits.push(min + (i / num) * (max - min));
      }
      limits.push(max);
    } else if (mode.substr(0, 1) === 'l') {
      if (min <= 0) {
        throw 'Logarithmic scales are only possible for values > 0';
      }
      min_log = Math.LOG10E * log(min);
      max_log = Math.LOG10E * log(max);
      limits.push(min);
      for (i = w = 1, ref1 = num - 1; 1 <= ref1 ? w <= ref1 : w >= ref1; i = 1 <= ref1 ? ++w : --w) {
        limits.push(pow(10, min_log + (i / num) * (max_log - min_log)));
      }
      limits.push(max);
    } else if (mode.substr(0, 1) === 'q') {
      limits.push(min);
      for (i = aa = 1, ref2 = num - 1; 1 <= ref2 ? aa <= ref2 : aa >= ref2; i = 1 <= ref2 ? ++aa : --aa) {
        p = (values.length - 1) * i / num;
        pb = floor(p);
        if (pb === p) {
          limits.push(values[pb]);
        } else {
          pr = p - pb;
          limits.push(values[pb] * (1 - pr) + values[pb + 1] * pr);
        }
      }
      limits.push(max);
    } else if (mode.substr(0, 1) === 'k') {

      /*
      implementation based on
      http://code.google.com/p/figue/source/browse/trunk/figue.js#336
      simplified for 1-d input values
       */
      n = values.length;
      assignments = new Array(n);
      clusterSizes = new Array(num);
      repeat = true;
      nb_iters = 0;
      centroids = null;
      centroids = [];
      centroids.push(min);
      for (i = ab = 1, ref3 = num - 1; 1 <= ref3 ? ab <= ref3 : ab >= ref3; i = 1 <= ref3 ? ++ab : --ab) {
        centroids.push(min + (i / num) * (max - min));
      }
      centroids.push(max);
      while (repeat) {
        for (j = ac = 0, ref4 = num - 1; 0 <= ref4 ? ac <= ref4 : ac >= ref4; j = 0 <= ref4 ? ++ac : --ac) {
          clusterSizes[j] = 0;
        }
        for (i = ad = 0, ref5 = n - 1; 0 <= ref5 ? ad <= ref5 : ad >= ref5; i = 0 <= ref5 ? ++ad : --ad) {
          value = values[i];
          mindist = Number.MAX_VALUE;
          for (j = ae = 0, ref6 = num - 1; 0 <= ref6 ? ae <= ref6 : ae >= ref6; j = 0 <= ref6 ? ++ae : --ae) {
            dist = abs(centroids[j] - value);
            if (dist < mindist) {
              mindist = dist;
              best = j;
            }
          }
          clusterSizes[best]++;
          assignments[i] = best;
        }
        newCentroids = new Array(num);
        for (j = af = 0, ref7 = num - 1; 0 <= ref7 ? af <= ref7 : af >= ref7; j = 0 <= ref7 ? ++af : --af) {
          newCentroids[j] = null;
        }
        for (i = ag = 0, ref8 = n - 1; 0 <= ref8 ? ag <= ref8 : ag >= ref8; i = 0 <= ref8 ? ++ag : --ag) {
          cluster = assignments[i];
          if (newCentroids[cluster] === null) {
            newCentroids[cluster] = values[i];
          } else {
            newCentroids[cluster] += values[i];
          }
        }
        for (j = ah = 0, ref9 = num - 1; 0 <= ref9 ? ah <= ref9 : ah >= ref9; j = 0 <= ref9 ? ++ah : --ah) {
          newCentroids[j] *= 1 / clusterSizes[j];
        }
        repeat = false;
        for (j = ai = 0, ref10 = num - 1; 0 <= ref10 ? ai <= ref10 : ai >= ref10; j = 0 <= ref10 ? ++ai : --ai) {
          if (newCentroids[j] !== centroids[i]) {
            repeat = true;
            break;
          }
        }
        centroids = newCentroids;
        nb_iters++;
        if (nb_iters > 200) {
          repeat = false;
        }
      }
      kClusters = {};
      for (j = aj = 0, ref11 = num - 1; 0 <= ref11 ? aj <= ref11 : aj >= ref11; j = 0 <= ref11 ? ++aj : --aj) {
        kClusters[j] = [];
      }
      for (i = ak = 0, ref12 = n - 1; 0 <= ref12 ? ak <= ref12 : ak >= ref12; i = 0 <= ref12 ? ++ak : --ak) {
        cluster = assignments[i];
        kClusters[cluster].push(values[i]);
      }
      tmpKMeansBreaks = [];
      for (j = al = 0, ref13 = num - 1; 0 <= ref13 ? al <= ref13 : al >= ref13; j = 0 <= ref13 ? ++al : --al) {
        tmpKMeansBreaks.push(kClusters[j][0]);
        tmpKMeansBreaks.push(kClusters[j][kClusters[j].length - 1]);
      }
      tmpKMeansBreaks = tmpKMeansBreaks.sort(function(a, b) {
        return a - b;
      });
      limits.push(tmpKMeansBreaks[0]);
      for (i = am = 1, ref14 = tmpKMeansBreaks.length - 1; am <= ref14; i = am += 2) {
        v = tmpKMeansBreaks[i];
        if (!isNaN(v) && limits.indexOf(v) === -1) {
          limits.push(v);
        }
      }
    }
    return limits;
  };

  hsi2rgb = function(h, s, i) {

    /*
    borrowed from here:
    http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/hsi2rgb.cpp
     */
    var args, b, g, r;
    args = unpack(arguments);
    h = args[0], s = args[1], i = args[2];
    if (isNaN(h)) {
      h = 0;
    }
    h /= 360;
    if (h < 1 / 3) {
      b = (1 - s) / 3;
      r = (1 + s * cos(TWOPI * h) / cos(PITHIRD - TWOPI * h)) / 3;
      g = 1 - (b + r);
    } else if (h < 2 / 3) {
      h -= 1 / 3;
      r = (1 - s) / 3;
      g = (1 + s * cos(TWOPI * h) / cos(PITHIRD - TWOPI * h)) / 3;
      b = 1 - (r + g);
    } else {
      h -= 2 / 3;
      g = (1 - s) / 3;
      b = (1 + s * cos(TWOPI * h) / cos(PITHIRD - TWOPI * h)) / 3;
      r = 1 - (g + b);
    }
    r = limit(i * r * 3);
    g = limit(i * g * 3);
    b = limit(i * b * 3);
    return [r * 255, g * 255, b * 255, args.length > 3 ? args[3] : 1];
  };

  rgb2hsi = function() {

    /*
    borrowed from here:
    http://hummer.stanford.edu/museinfo/doc/examples/humdrum/keyscape2/rgb2hsi.cpp
     */
    var b, g, h, i, min, r, ref, s;
    ref = unpack(arguments), r = ref[0], g = ref[1], b = ref[2];
    TWOPI = Math.PI * 2;
    r /= 255;
    g /= 255;
    b /= 255;
    min = Math.min(r, g, b);
    i = (r + g + b) / 3;
    s = 1 - min / i;
    if (s === 0) {
      h = 0;
    } else {
      h = ((r - g) + (r - b)) / 2;
      h /= Math.sqrt((r - g) * (r - g) + (r - b) * (g - b));
      h = Math.acos(h);
      if (b > g) {
        h = TWOPI - h;
      }
      h /= TWOPI;
    }
    return [h * 360, s, i];
  };

  chroma.hsi = function() {
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Color, slice.call(arguments).concat(['hsi']), function(){});
  };

  _input.hsi = hsi2rgb;

  Color.prototype.hsi = function() {
    return rgb2hsi(this._rgb);
  };

  interpolate_hsx = function(col1, col2, f, m) {
    var dh, hue, hue0, hue1, lbv, lbv0, lbv1, res, sat, sat0, sat1, xyz0, xyz1;
    if (m === 'hsl') {
      xyz0 = col1.hsl();
      xyz1 = col2.hsl();
    } else if (m === 'hsv') {
      xyz0 = col1.hsv();
      xyz1 = col2.hsv();
    } else if (m === 'hcg') {
      xyz0 = col1.hcg();
      xyz1 = col2.hcg();
    } else if (m === 'hsi') {
      xyz0 = col1.hsi();
      xyz1 = col2.hsi();
    } else if (m === 'lch' || m === 'hcl') {
      m = 'hcl';
      xyz0 = col1.hcl();
      xyz1 = col2.hcl();
    }
    if (m.substr(0, 1) === 'h') {
      hue0 = xyz0[0], sat0 = xyz0[1], lbv0 = xyz0[2];
      hue1 = xyz1[0], sat1 = xyz1[1], lbv1 = xyz1[2];
    }
    if (!isNaN(hue0) && !isNaN(hue1)) {
      if (hue1 > hue0 && hue1 - hue0 > 180) {
        dh = hue1 - (hue0 + 360);
      } else if (hue1 < hue0 && hue0 - hue1 > 180) {
        dh = hue1 + 360 - hue0;
      } else {
        dh = hue1 - hue0;
      }
      hue = hue0 + f * dh;
    } else if (!isNaN(hue0)) {
      hue = hue0;
      if ((lbv1 === 1 || lbv1 === 0) && m !== 'hsv') {
        sat = sat0;
      }
    } else if (!isNaN(hue1)) {
      hue = hue1;
      if ((lbv0 === 1 || lbv0 === 0) && m !== 'hsv') {
        sat = sat1;
      }
    } else {
      hue = Number.NaN;
    }
    if (sat == null) {
      sat = sat0 + f * (sat1 - sat0);
    }
    lbv = lbv0 + f * (lbv1 - lbv0);
    return res = chroma[m](hue, sat, lbv);
  };

  _interpolators = _interpolators.concat((function() {
    var len, o, ref, results;
    ref = ['hsv', 'hsl', 'hsi', 'hcl', 'lch', 'hcg'];
    results = [];
    for (o = 0, len = ref.length; o < len; o++) {
      m = ref[o];
      results.push([m, interpolate_hsx]);
    }
    return results;
  })());

  interpolate_num = function(col1, col2, f, m) {
    var n1, n2;
    n1 = col1.num();
    n2 = col2.num();
    return chroma.num(n1 + (n2 - n1) * f, 'num');
  };

  _interpolators.push(['num', interpolate_num]);

  interpolate_lab = function(col1, col2, f, m) {
    var res, xyz0, xyz1;
    xyz0 = col1.lab();
    xyz1 = col2.lab();
    return res = new Color(xyz0[0] + f * (xyz1[0] - xyz0[0]), xyz0[1] + f * (xyz1[1] - xyz0[1]), xyz0[2] + f * (xyz1[2] - xyz0[2]), m);
  };

  _interpolators.push(['lab', interpolate_lab]);

}).call(this);

/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(112)(module)))

/***/ }),
/* 112 */
/***/ (function(module, exports) {

module.exports = function(module) {
	if(!module.webpackPolyfill) {
		module.deprecate = function() {};
		module.paths = [];
		// module.parent = undefined by default
		if(!module.children) module.children = [];
		Object.defineProperty(module, "loaded", {
			enumerable: true,
			get: function() {
				return module.l;
			}
		});
		Object.defineProperty(module, "id", {
			enumerable: true,
			get: function() {
				return module.i;
			}
		});
		module.webpackPolyfill = 1;
	}
	return module;
};


/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_RESULT__;/* global window, exports, define */

!function() {
    'use strict'

    var re = {
        not_string: /[^s]/,
        not_bool: /[^t]/,
        not_type: /[^T]/,
        not_primitive: /[^v]/,
        number: /[diefg]/,
        numeric_arg: /[bcdiefguxX]/,
        json: /[j]/,
        not_json: /[^j]/,
        text: /^[^\x25]+/,
        modulo: /^\x25{2}/,
        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
        key: /^([a-z_][a-z_\d]*)/i,
        key_access: /^\.([a-z_][a-z_\d]*)/i,
        index_access: /^\[(\d+)\]/,
        sign: /^[+-]/
    }

    function sprintf(key) {
        // `arguments` is not an array, but should be fine for this call
        return sprintf_format(sprintf_parse(key), arguments)
    }

    function vsprintf(fmt, argv) {
        return sprintf.apply(null, [fmt].concat(argv || []))
    }

    function sprintf_format(parse_tree, argv) {
        var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign
        for (i = 0; i < tree_length; i++) {
            if (typeof parse_tree[i] === 'string') {
                output += parse_tree[i]
            }
            else if (typeof parse_tree[i] === 'object') {
                ph = parse_tree[i] // convenience purposes only
                if (ph.keys) { // keyword argument
                    arg = argv[cursor]
                    for (k = 0; k < ph.keys.length; k++) {
                        if (arg == undefined) {
                            throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]))
                        }
                        arg = arg[ph.keys[k]]
                    }
                }
                else if (ph.param_no) { // positional argument (explicit)
                    arg = argv[ph.param_no]
                }
                else { // positional argument (implicit)
                    arg = argv[cursor++]
                }

                if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
                    arg = arg()
                }

                if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
                    throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg))
                }

                if (re.number.test(ph.type)) {
                    is_positive = arg >= 0
                }

                switch (ph.type) {
                    case 'b':
                        arg = parseInt(arg, 10).toString(2)
                        break
                    case 'c':
                        arg = String.fromCharCode(parseInt(arg, 10))
                        break
                    case 'd':
                    case 'i':
                        arg = parseInt(arg, 10)
                        break
                    case 'j':
                        arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0)
                        break
                    case 'e':
                        arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential()
                        break
                    case 'f':
                        arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg)
                        break
                    case 'g':
                        arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg)
                        break
                    case 'o':
                        arg = (parseInt(arg, 10) >>> 0).toString(8)
                        break
                    case 's':
                        arg = String(arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 't':
                        arg = String(!!arg)
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'T':
                        arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'u':
                        arg = parseInt(arg, 10) >>> 0
                        break
                    case 'v':
                        arg = arg.valueOf()
                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg)
                        break
                    case 'x':
                        arg = (parseInt(arg, 10) >>> 0).toString(16)
                        break
                    case 'X':
                        arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase()
                        break
                }
                if (re.json.test(ph.type)) {
                    output += arg
                }
                else {
                    if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
                        sign = is_positive ? '+' : '-'
                        arg = arg.toString().replace(re.sign, '')
                    }
                    else {
                        sign = ''
                    }
                    pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' '
                    pad_length = ph.width - (sign + arg).length
                    pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : ''
                    output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg)
                }
            }
        }
        return output
    }

    var sprintf_cache = Object.create(null)

    function sprintf_parse(fmt) {
        if (sprintf_cache[fmt]) {
            return sprintf_cache[fmt]
        }

        var _fmt = fmt, match, parse_tree = [], arg_names = 0
        while (_fmt) {
            if ((match = re.text.exec(_fmt)) !== null) {
                parse_tree.push(match[0])
            }
            else if ((match = re.modulo.exec(_fmt)) !== null) {
                parse_tree.push('%')
            }
            else if ((match = re.placeholder.exec(_fmt)) !== null) {
                if (match[2]) {
                    arg_names |= 1
                    var field_list = [], replacement_field = match[2], field_match = []
                    if ((field_match = re.key.exec(replacement_field)) !== null) {
                        field_list.push(field_match[1])
                        while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
                                field_list.push(field_match[1])
                            }
                            else {
                                throw new SyntaxError('[sprintf] failed to parse named argument key')
                            }
                        }
                    }
                    else {
                        throw new SyntaxError('[sprintf] failed to parse named argument key')
                    }
                    match[2] = field_list
                }
                else {
                    arg_names |= 2
                }
                if (arg_names === 3) {
                    throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported')
                }

                parse_tree.push(
                    {
                        placeholder: match[0],
                        param_no:    match[1],
                        keys:        match[2],
                        sign:        match[3],
                        pad_char:    match[4],
                        align:       match[5],
                        width:       match[6],
                        precision:   match[7],
                        type:        match[8]
                    }
                )
            }
            else {
                throw new SyntaxError('[sprintf] unexpected placeholder')
            }
            _fmt = _fmt.substring(match[0].length)
        }
        return sprintf_cache[fmt] = parse_tree
    }

    /**
     * export to either browser or node.js
     */
    /* eslint-disable quote-props */
    if (true) {
        exports['sprintf'] = sprintf
        exports['vsprintf'] = vsprintf
    }
    if (typeof window !== 'undefined') {
        window['sprintf'] = sprintf
        window['vsprintf'] = vsprintf

        if (true) {
            !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
                return {
                    'sprintf': sprintf,
                    'vsprintf': vsprintf
                }
            }).call(exports, __webpack_require__, exports, module),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))
        }
    }
    /* eslint-enable quote-props */
}(); // eslint-disable-line


/***/ }),
/* 114 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__index_js__ = __webpack_require__(35);
// Default Export
// ==============
// In this module, we mix our bundled exports into the `_` object and export
// the result. This is analogous to setting `module.exports = _` in CommonJS.
// Hence, this module is also the entry point of our UMD bundle and the package
// entry point for CommonJS and AMD users. In other words, this is (the source
// of) the module you are interfacing with when you do any of the following:
//
// ```js
// // CommonJS
// var _ = require('underscore');
//
// // AMD
// define(['underscore'], function(_) {...});
//
// // UMD in the browser
// // _ is available as a global variable
// ```



// Add all of the Underscore functions to the wrapper object.
var _ = Object(__WEBPACK_IMPORTED_MODULE_0__index_js__["mixin"])(__WEBPACK_IMPORTED_MODULE_0__index_js__);
// Legacy Node.js API.
_._ = _;
// Export the Underscore API.
/* harmony default export */ __webpack_exports__["a"] = (_);


/***/ }),
/* 115 */
/***/ (function(module, exports) {

var g;

// This works in non-strict mode
g = (function() {
	return this;
})();

try {
	// This works if eval is allowed (see CSP)
	g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
	// This works if the window reference is available
	if(typeof window === "object")
		g = window;
}

// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}

module.exports = g;


/***/ }),
/* 116 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isNull;
// Is a given value equal to null?
function isNull(obj) {
  return obj === null;
}


/***/ }),
/* 117 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isElement;
// Is a given value a DOM element?
function isElement(obj) {
  return !!(obj && obj.nodeType === 1);
}


/***/ }),
/* 118 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);


/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Date'));


/***/ }),
/* 119 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);


/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('RegExp'));


/***/ }),
/* 120 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);


/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Error'));


/***/ }),
/* 121 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);


/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Object'));


/***/ }),
/* 122 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isFinite;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isSymbol_js__ = __webpack_require__(56);



// Is a given object a finite number?
function isFinite(obj) {
  return !Object(__WEBPACK_IMPORTED_MODULE_1__isSymbol_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_0__setup_js__["f" /* _isFinite */])(obj) && !isNaN(parseFloat(obj));
}


/***/ }),
/* 123 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createSizePropertyCheck_js__ = __webpack_require__(61);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__getByteLength_js__ = __webpack_require__(39);



// Internal helper to determine whether we should spend extensive checks against
// `ArrayBuffer` et al.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createSizePropertyCheck_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__getByteLength_js__["a" /* default */]));


/***/ }),
/* 124 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isEmpty;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArray_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__isString_js__ = __webpack_require__(36);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isArguments_js__ = __webpack_require__(38);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__keys_js__ = __webpack_require__(4);






// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
function isEmpty(obj) {
  if (obj == null) return true;
  // Skip the more expensive `toString`-based type checks if `obj` has no
  // `.length`.
  var length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(obj);
  if (typeof length == 'number' && (
    Object(__WEBPACK_IMPORTED_MODULE_1__isArray_js__["a" /* default */])(obj) || Object(__WEBPACK_IMPORTED_MODULE_2__isString_js__["a" /* default */])(obj) || Object(__WEBPACK_IMPORTED_MODULE_3__isArguments_js__["a" /* default */])(obj)
  )) return length === 0;
  return Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_4__keys_js__["a" /* default */])(obj)) === 0;
}


/***/ }),
/* 125 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isEqual;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__getByteLength_js__ = __webpack_require__(39);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isTypedArray_js__ = __webpack_require__(59);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__stringTagBug_js__ = __webpack_require__(23);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__isDataView_js__ = __webpack_require__(37);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__keys_js__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__has_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__toBufferView_js__ = __webpack_require__(126);











// We use this string twice, so give it a name for minification.
var tagDataView = '[object DataView]';

// Internal recursive comparison function for `_.isEqual`.
function eq(a, b, aStack, bStack) {
  // Identical objects are equal. `0 === -0`, but they aren't identical.
  // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal).
  if (a === b) return a !== 0 || 1 / a === 1 / b;
  // `null` or `undefined` only equal to itself (strict comparison).
  if (a == null || b == null) return false;
  // `NaN`s are equivalent, but non-reflexive.
  if (a !== a) return b !== b;
  // Exhaust primitive checks
  var type = typeof a;
  if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
  return deepEq(a, b, aStack, bStack);
}

// Internal recursive comparison function for `_.isEqual`.
function deepEq(a, b, aStack, bStack) {
  // Unwrap any wrapped objects.
  if (a instanceof __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */]) a = a._wrapped;
  if (b instanceof __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */]) b = b._wrapped;
  // Compare `[[Class]]` names.
  var className = __WEBPACK_IMPORTED_MODULE_1__setup_js__["t" /* toString */].call(a);
  if (className !== __WEBPACK_IMPORTED_MODULE_1__setup_js__["t" /* toString */].call(b)) return false;
  // Work around a bug in IE 10 - Edge 13.
  if (__WEBPACK_IMPORTED_MODULE_5__stringTagBug_js__["a" /* hasStringTagBug */] && className == '[object Object]' && Object(__WEBPACK_IMPORTED_MODULE_6__isDataView_js__["a" /* default */])(a)) {
    if (!Object(__WEBPACK_IMPORTED_MODULE_6__isDataView_js__["a" /* default */])(b)) return false;
    className = tagDataView;
  }
  switch (className) {
    // These types are compared by value.
    case '[object RegExp]':
      // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
    case '[object String]':
      // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
      // equivalent to `new String("5")`.
      return '' + a === '' + b;
    case '[object Number]':
      // `NaN`s are equivalent, but non-reflexive.
      // Object(NaN) is equivalent to NaN.
      if (+a !== +a) return +b !== +b;
      // An `egal` comparison is performed for other numeric values.
      return +a === 0 ? 1 / +a === 1 / b : +a === +b;
    case '[object Date]':
    case '[object Boolean]':
      // Coerce dates and booleans to numeric primitive values. Dates are compared by their
      // millisecond representations. Note that invalid dates with millisecond representations
      // of `NaN` are not equivalent.
      return +a === +b;
    case '[object Symbol]':
      return __WEBPACK_IMPORTED_MODULE_1__setup_js__["d" /* SymbolProto */].valueOf.call(a) === __WEBPACK_IMPORTED_MODULE_1__setup_js__["d" /* SymbolProto */].valueOf.call(b);
    case '[object ArrayBuffer]':
    case tagDataView:
      // Coerce to typed array so we can fall through.
      return deepEq(Object(__WEBPACK_IMPORTED_MODULE_9__toBufferView_js__["a" /* default */])(a), Object(__WEBPACK_IMPORTED_MODULE_9__toBufferView_js__["a" /* default */])(b), aStack, bStack);
  }

  var areArrays = className === '[object Array]';
  if (!areArrays && Object(__WEBPACK_IMPORTED_MODULE_3__isTypedArray_js__["a" /* default */])(a)) {
      var byteLength = Object(__WEBPACK_IMPORTED_MODULE_2__getByteLength_js__["a" /* default */])(a);
      if (byteLength !== Object(__WEBPACK_IMPORTED_MODULE_2__getByteLength_js__["a" /* default */])(b)) return false;
      if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true;
      areArrays = true;
  }
  if (!areArrays) {
    if (typeof a != 'object' || typeof b != 'object') return false;

    // Objects with different constructors are not equivalent, but `Object`s or `Array`s
    // from different frames are.
    var aCtor = a.constructor, bCtor = b.constructor;
    if (aCtor !== bCtor && !(Object(__WEBPACK_IMPORTED_MODULE_4__isFunction_js__["a" /* default */])(aCtor) && aCtor instanceof aCtor &&
                             Object(__WEBPACK_IMPORTED_MODULE_4__isFunction_js__["a" /* default */])(bCtor) && bCtor instanceof bCtor)
                        && ('constructor' in a && 'constructor' in b)) {
      return false;
    }
  }
  // Assume equality for cyclic structures. The algorithm for detecting cyclic
  // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

  // Initializing stack of traversed objects.
  // It's done here since we only need them for objects and arrays comparison.
  aStack = aStack || [];
  bStack = bStack || [];
  var length = aStack.length;
  while (length--) {
    // Linear search. Performance is inversely proportional to the number of
    // unique nested structures.
    if (aStack[length] === a) return bStack[length] === b;
  }

  // Add the first object to the stack of traversed objects.
  aStack.push(a);
  bStack.push(b);

  // Recursively compare objects and arrays.
  if (areArrays) {
    // Compare array lengths to determine if a deep comparison is necessary.
    length = a.length;
    if (length !== b.length) return false;
    // Deep compare the contents, ignoring non-numeric properties.
    while (length--) {
      if (!eq(a[length], b[length], aStack, bStack)) return false;
    }
  } else {
    // Deep compare objects.
    var _keys = Object(__WEBPACK_IMPORTED_MODULE_7__keys_js__["a" /* default */])(a), key;
    length = _keys.length;
    // Ensure that both objects contain the same number of properties before comparing deep equality.
    if (Object(__WEBPACK_IMPORTED_MODULE_7__keys_js__["a" /* default */])(b).length !== length) return false;
    while (length--) {
      // Deep compare each member
      key = _keys[length];
      if (!(Object(__WEBPACK_IMPORTED_MODULE_8__has_js__["a" /* default */])(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
    }
  }
  // Remove the first object from the stack of traversed objects.
  aStack.pop();
  bStack.pop();
  return true;
}

// Perform a deep comparison to check if two objects are equal.
function isEqual(a, b) {
  return eq(a, b);
}


/***/ }),
/* 126 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = toBufferView;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getByteLength_js__ = __webpack_require__(39);


// Internal function to wrap or shallow-copy an ArrayBuffer,
// typed array or DataView to a new view, reusing the buffer.
function toBufferView(bufferSource) {
  return new Uint8Array(
    bufferSource.buffer || bufferSource,
    bufferSource.byteOffset || 0,
    Object(__WEBPACK_IMPORTED_MODULE_0__getByteLength_js__["a" /* default */])(bufferSource)
  );
}


/***/ }),
/* 127 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__ = __webpack_require__(23);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__ = __webpack_require__(40);




/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__["b" /* isIE11 */] ? Object(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["a" /* ie11fingerprint */])(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["b" /* mapMethods */]) : Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Map'));


/***/ }),
/* 128 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__ = __webpack_require__(23);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__ = __webpack_require__(40);




/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__["b" /* isIE11 */] ? Object(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["a" /* ie11fingerprint */])(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["d" /* weakMapMethods */]) : Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('WeakMap'));


/***/ }),
/* 129 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__ = __webpack_require__(23);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__ = __webpack_require__(40);




/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_1__stringTagBug_js__["b" /* isIE11 */] ? Object(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["a" /* ie11fingerprint */])(__WEBPACK_IMPORTED_MODULE_2__methodFingerprint_js__["c" /* setMethods */]) : Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('Set'));


/***/ }),
/* 130 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__tagTester_js__ = __webpack_require__(5);


/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__tagTester_js__["a" /* default */])('WeakSet'));


/***/ }),
/* 131 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = pairs;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__keys_js__ = __webpack_require__(4);


// Convert an object into a list of `[key, value]` pairs.
// The opposite of `_.object` with one argument.
function pairs(obj) {
  var _keys = Object(__WEBPACK_IMPORTED_MODULE_0__keys_js__["a" /* default */])(obj);
  var length = _keys.length;
  var pairs = Array(length);
  for (var i = 0; i < length; i++) {
    pairs[i] = [_keys[i], obj[_keys[i]]];
  }
  return pairs;
}


/***/ }),
/* 132 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = create;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__baseCreate_js__ = __webpack_require__(69);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__extendOwn_js__ = __webpack_require__(42);



// Creates an object that inherits from the given prototype object.
// If additional properties are provided then they will be added to the
// created object.
function create(prototype, props) {
  var result = Object(__WEBPACK_IMPORTED_MODULE_0__baseCreate_js__["a" /* default */])(prototype);
  if (props) Object(__WEBPACK_IMPORTED_MODULE_1__extendOwn_js__["a" /* default */])(result, props);
  return result;
}


/***/ }),
/* 133 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = clone;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isObject_js__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArray_js__ = __webpack_require__(15);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__extend_js__ = __webpack_require__(67);




// Create a (shallow-cloned) duplicate of an object.
function clone(obj) {
  if (!Object(__WEBPACK_IMPORTED_MODULE_0__isObject_js__["a" /* default */])(obj)) return obj;
  return Object(__WEBPACK_IMPORTED_MODULE_1__isArray_js__["a" /* default */])(obj) ? obj.slice() : Object(__WEBPACK_IMPORTED_MODULE_2__extend_js__["a" /* default */])({}, obj);
}


/***/ }),
/* 134 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = tap;
// Invokes `interceptor` with the `obj` and then returns `obj`.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
function tap(obj, interceptor) {
  interceptor(obj);
  return obj;
}


/***/ }),
/* 135 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = has;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__has_js__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__toPath_js__ = __webpack_require__(25);



// Shortcut function for checking if an object has a given property directly on
// itself (in other words, not on a prototype). Unlike the internal `has`
// function, this public version can also traverse nested properties.
function has(obj, path) {
  path = Object(__WEBPACK_IMPORTED_MODULE_1__toPath_js__["a" /* default */])(path);
  var length = path.length;
  for (var i = 0; i < length; i++) {
    var key = path[i];
    if (!Object(__WEBPACK_IMPORTED_MODULE_0__has_js__["a" /* default */])(obj, key)) return false;
    obj = obj[key];
  }
  return !!length;
}


/***/ }),
/* 136 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = mapObject;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(4);



// Returns the results of applying the `iteratee` to each element of `obj`.
// In contrast to `_.map` it returns an object.
function mapObject(obj, iteratee, context) {
  iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context);
  var _keys = Object(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */])(obj),
      length = _keys.length,
      results = {};
  for (var index = 0; index < length; index++) {
    var currentKey = _keys[index];
    results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
  }
  return results;
}


/***/ }),
/* 137 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = propertyOf;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__noop_js__ = __webpack_require__(74);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__get_js__ = __webpack_require__(70);



// Generates a function for a given object that returns a given property.
function propertyOf(obj) {
  if (obj == null) return __WEBPACK_IMPORTED_MODULE_0__noop_js__["a" /* default */];
  return function(path) {
    return Object(__WEBPACK_IMPORTED_MODULE_1__get_js__["a" /* default */])(obj, path);
  };
}


/***/ }),
/* 138 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = times;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__optimizeCb_js__ = __webpack_require__(26);


// Run a function **n** times.
function times(n, iteratee, context) {
  var accum = Array(Math.max(0, n));
  iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__optimizeCb_js__["a" /* default */])(iteratee, context, 1);
  for (var i = 0; i < n; i++) accum[i] = iteratee(i);
  return accum;
}


/***/ }),
/* 139 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createEscaper_js__ = __webpack_require__(76);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__escapeMap_js__ = __webpack_require__(77);



// Function for escaping strings to HTML interpolation.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createEscaper_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__escapeMap_js__["a" /* default */]));


/***/ }),
/* 140 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createEscaper_js__ = __webpack_require__(76);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__unescapeMap_js__ = __webpack_require__(141);



// Function for unescaping strings from HTML interpolation.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createEscaper_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__unescapeMap_js__["a" /* default */]));


/***/ }),
/* 141 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__invert_js__ = __webpack_require__(65);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__escapeMap_js__ = __webpack_require__(77);



// Internal list of HTML entities for unescaping.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__invert_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__escapeMap_js__["a" /* default */]));


/***/ }),
/* 142 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = template;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__defaults_js__ = __webpack_require__(68);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__underscore_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__templateSettings_js__ = __webpack_require__(78);




// When customizing `_.templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;

// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
  "'": "'",
  '\\': '\\',
  '\r': 'r',
  '\n': 'n',
  '\u2028': 'u2028',
  '\u2029': 'u2029'
};

var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;

function escapeChar(match) {
  return '\\' + escapes[match];
}

// In order to prevent third-party code injection through
// `_.templateSettings.variable`, we test it against the following regular
// expression. It is intentionally a bit more liberal than just matching valid
// identifiers, but still prevents possible loopholes through defaults or
// destructuring assignment.
var bareIdentifier = /^\s*(\w|\$)+\s*$/;

// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
function template(text, settings, oldSettings) {
  if (!settings && oldSettings) settings = oldSettings;
  settings = Object(__WEBPACK_IMPORTED_MODULE_0__defaults_js__["a" /* default */])({}, settings, __WEBPACK_IMPORTED_MODULE_1__underscore_js__["a" /* default */].templateSettings);

  // Combine delimiters into one regular expression via alternation.
  var matcher = RegExp([
    (settings.escape || noMatch).source,
    (settings.interpolate || noMatch).source,
    (settings.evaluate || noMatch).source
  ].join('|') + '|$', 'g');

  // Compile the template source, escaping string literals appropriately.
  var index = 0;
  var source = "__p+='";
  text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
    source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
    index = offset + match.length;

    if (escape) {
      source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
    } else if (interpolate) {
      source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
    } else if (evaluate) {
      source += "';\n" + evaluate + "\n__p+='";
    }

    // Adobe VMs need the match returned to produce the correct offset.
    return match;
  });
  source += "';\n";

  var argument = settings.variable;
  if (argument) {
    // Insure against third-party code injection. (CVE-2021-23358)
    if (!bareIdentifier.test(argument)) throw new Error(
      'variable is not a bare identifier: ' + argument
    );
  } else {
    // If a variable is not specified, place data values in local scope.
    source = 'with(obj||{}){\n' + source + '}\n';
    argument = 'obj';
  }

  source = "var __t,__p='',__j=Array.prototype.join," +
    "print=function(){__p+=__j.call(arguments,'');};\n" +
    source + 'return __p;\n';

  var render;
  try {
    render = new Function(argument, '_', source);
  } catch (e) {
    e.source = source;
    throw e;
  }

  var template = function(data) {
    return render.call(this, data, __WEBPACK_IMPORTED_MODULE_1__underscore_js__["a" /* default */]);
  };

  // Provide the compiled source as a convenience for precompilation.
  template.source = 'function(' + argument + '){\n' + source + '}';

  return template;
}


/***/ }),
/* 143 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = result;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__toPath_js__ = __webpack_require__(25);



// Traverses the children of `obj` along `path`. If a child is a function, it
// is invoked with its parent as context. Returns the value of the final
// child, or `fallback` if any child is undefined.
function result(obj, path, fallback) {
  path = Object(__WEBPACK_IMPORTED_MODULE_1__toPath_js__["a" /* default */])(path);
  var length = path.length;
  if (!length) {
    return Object(__WEBPACK_IMPORTED_MODULE_0__isFunction_js__["a" /* default */])(fallback) ? fallback.call(obj) : fallback;
  }
  for (var i = 0; i < length; i++) {
    var prop = obj == null ? void 0 : obj[path[i]];
    if (prop === void 0) {
      prop = fallback;
      i = length; // Ensure we don't continue iterating.
    }
    obj = Object(__WEBPACK_IMPORTED_MODULE_0__isFunction_js__["a" /* default */])(prop) ? prop.call(obj) : prop;
  }
  return obj;
}


/***/ }),
/* 144 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = uniqueId;
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
function uniqueId(prefix) {
  var id = ++idCounter + '';
  return prefix ? prefix + id : id;
}


/***/ }),
/* 145 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = chain;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);


// Start chaining a wrapped Underscore object.
function chain(obj) {
  var instance = Object(__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */])(obj);
  instance._chain = true;
  return instance;
}


/***/ }),
/* 146 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__flatten_js__ = __webpack_require__(20);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__bind_js__ = __webpack_require__(80);




// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(obj, keys) {
  keys = Object(__WEBPACK_IMPORTED_MODULE_1__flatten_js__["a" /* default */])(keys, false, false);
  var index = keys.length;
  if (index < 1) throw new Error('bindAll must be passed function names');
  while (index--) {
    var key = keys[index];
    obj[key] = Object(__WEBPACK_IMPORTED_MODULE_2__bind_js__["a" /* default */])(obj[key], obj);
  }
  return obj;
}));


/***/ }),
/* 147 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = memoize;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__has_js__ = __webpack_require__(13);


// Memoize an expensive function by storing its results.
function memoize(func, hasher) {
  var memoize = function(key) {
    var cache = memoize.cache;
    var address = '' + (hasher ? hasher.apply(this, arguments) : key);
    if (!Object(__WEBPACK_IMPORTED_MODULE_0__has_js__["a" /* default */])(cache, address)) cache[address] = func.apply(this, arguments);
    return cache[address];
  };
  memoize.cache = {};
  return memoize;
}


/***/ }),
/* 148 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__partial_js__ = __webpack_require__(31);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__delay_js__ = __webpack_require__(81);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__underscore_js__ = __webpack_require__(8);




// Defers a function, scheduling it to run after the current call stack has
// cleared.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__partial_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__delay_js__["a" /* default */], __WEBPACK_IMPORTED_MODULE_2__underscore_js__["a" /* default */], 1));


/***/ }),
/* 149 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = throttle;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__now_js__ = __webpack_require__(46);


// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
function throttle(func, wait, options) {
  var timeout, context, args, result;
  var previous = 0;
  if (!options) options = {};

  var later = function() {
    previous = options.leading === false ? 0 : Object(__WEBPACK_IMPORTED_MODULE_0__now_js__["a" /* default */])();
    timeout = null;
    result = func.apply(context, args);
    if (!timeout) context = args = null;
  };

  var throttled = function() {
    var _now = Object(__WEBPACK_IMPORTED_MODULE_0__now_js__["a" /* default */])();
    if (!previous && options.leading === false) previous = _now;
    var remaining = wait - (_now - previous);
    context = this;
    args = arguments;
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      previous = _now;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
    return result;
  };

  throttled.cancel = function() {
    clearTimeout(timeout);
    previous = 0;
    timeout = context = args = null;
  };

  return throttled;
}


/***/ }),
/* 150 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = debounce;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__now_js__ = __webpack_require__(46);



// When a sequence of calls of the returned function ends, the argument
// function is triggered. The end of a sequence is defined by the `wait`
// parameter. If `immediate` is passed, the argument function will be
// triggered at the beginning of the sequence instead of at the end.
function debounce(func, wait, immediate) {
  var timeout, previous, args, result, context;

  var later = function() {
    var passed = Object(__WEBPACK_IMPORTED_MODULE_1__now_js__["a" /* default */])() - previous;
    if (wait > passed) {
      timeout = setTimeout(later, wait - passed);
    } else {
      timeout = null;
      if (!immediate) result = func.apply(context, args);
      // This check is needed because `func` can recursively invoke `debounced`.
      if (!timeout) args = context = null;
    }
  };

  var debounced = Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(_args) {
    context = this;
    args = _args;
    previous = Object(__WEBPACK_IMPORTED_MODULE_1__now_js__["a" /* default */])();
    if (!timeout) {
      timeout = setTimeout(later, wait);
      if (immediate) result = func.apply(context, args);
    }
    return result;
  });

  debounced.cancel = function() {
    clearTimeout(timeout);
    timeout = args = context = null;
  };

  return debounced;
}


/***/ }),
/* 151 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = wrap;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__partial_js__ = __webpack_require__(31);


// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
function wrap(func, wrapper) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__partial_js__["a" /* default */])(wrapper, func);
}


/***/ }),
/* 152 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = compose;
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
function compose() {
  var args = arguments;
  var start = args.length - 1;
  return function() {
    var i = start;
    var result = args[start].apply(this, arguments);
    while (i--) result = args[i].call(this, result);
    return result;
  };
}


/***/ }),
/* 153 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = after;
// Returns a function that will only be executed on and after the Nth call.
function after(times, func) {
  return function() {
    if (--times < 1) {
      return func.apply(this, arguments);
    }
  };
}


/***/ }),
/* 154 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__partial_js__ = __webpack_require__(31);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__before_js__ = __webpack_require__(82);



// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__partial_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__before_js__["a" /* default */], 2));


/***/ }),
/* 155 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__findLastIndex_js__ = __webpack_require__(85);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__createIndexFinder_js__ = __webpack_require__(88);



// Return the position of the last occurrence of an item in an array,
// or -1 if the item is not included in the array.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_1__createIndexFinder_js__["a" /* default */])(-1, __WEBPACK_IMPORTED_MODULE_0__findLastIndex_js__["a" /* default */]));


/***/ }),
/* 156 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = findWhere;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__find_js__ = __webpack_require__(89);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__matcher_js__ = __webpack_require__(30);



// Convenience version of a common use case of `_.find`: getting the first
// object containing specific `key:value` pairs.
function findWhere(obj, attrs) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__find_js__["a" /* default */])(obj, Object(__WEBPACK_IMPORTED_MODULE_1__matcher_js__["a" /* default */])(attrs));
}


/***/ }),
/* 157 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createReduce_js__ = __webpack_require__(90);


// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createReduce_js__["a" /* default */])(1));


/***/ }),
/* 158 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createReduce_js__ = __webpack_require__(90);


// The right-associative version of reduce, also known as `foldr`.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__createReduce_js__["a" /* default */])(-1));


/***/ }),
/* 159 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = reject;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__filter_js__ = __webpack_require__(27);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__negate_js__ = __webpack_require__(47);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__cb_js__ = __webpack_require__(6);




// Return all the elements for which a truth test fails.
function reject(obj, predicate, context) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__filter_js__["a" /* default */])(obj, Object(__WEBPACK_IMPORTED_MODULE_1__negate_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_2__cb_js__["a" /* default */])(predicate)), context);
}


/***/ }),
/* 160 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = every;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__keys_js__ = __webpack_require__(4);




// Determine whether all of the elements pass a truth test.
function every(obj, predicate, context) {
  predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
  var _keys = !Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_2__keys_js__["a" /* default */])(obj),
      length = (_keys || obj).length;
  for (var index = 0; index < length; index++) {
    var currentKey = _keys ? _keys[index] : index;
    if (!predicate(obj[currentKey], currentKey, obj)) return false;
  }
  return true;
}


/***/ }),
/* 161 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = some;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__keys_js__ = __webpack_require__(4);




// Determine if at least one element in the object passes a truth test.
function some(obj, predicate, context) {
  predicate = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(predicate, context);
  var _keys = !Object(__WEBPACK_IMPORTED_MODULE_1__isArrayLike_js__["a" /* default */])(obj) && Object(__WEBPACK_IMPORTED_MODULE_2__keys_js__["a" /* default */])(obj),
      length = (_keys || obj).length;
  for (var index = 0; index < length; index++) {
    var currentKey = _keys ? _keys[index] : index;
    if (predicate(obj[currentKey], currentKey, obj)) return true;
  }
  return false;
}


/***/ }),
/* 162 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__map_js__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__deepGet_js__ = __webpack_require__(43);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__toPath_js__ = __webpack_require__(25);






// Invoke a method (with arguments) on every item in a collection.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(obj, path, args) {
  var contextPath, func;
  if (Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(path)) {
    func = path;
  } else {
    path = Object(__WEBPACK_IMPORTED_MODULE_4__toPath_js__["a" /* default */])(path);
    contextPath = path.slice(0, -1);
    path = path[path.length - 1];
  }
  return Object(__WEBPACK_IMPORTED_MODULE_2__map_js__["a" /* default */])(obj, function(context) {
    var method = func;
    if (!method) {
      if (contextPath && contextPath.length) {
        context = Object(__WEBPACK_IMPORTED_MODULE_3__deepGet_js__["a" /* default */])(context, contextPath);
      }
      if (context == null) return void 0;
      method = context[path];
    }
    return method == null ? method : method.apply(context, args);
  });
}));


/***/ }),
/* 163 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = where;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__filter_js__ = __webpack_require__(27);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__matcher_js__ = __webpack_require__(30);



// Convenience version of a common use case of `_.filter`: selecting only
// objects containing specific `key:value` pairs.
function where(obj, attrs) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__filter_js__["a" /* default */])(obj, Object(__WEBPACK_IMPORTED_MODULE_1__matcher_js__["a" /* default */])(attrs));
}


/***/ }),
/* 164 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = min;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__values_js__ = __webpack_require__(19);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__each_js__ = __webpack_require__(16);





// Return the minimum element (or element-based computation).
function min(obj, iteratee, context) {
  var result = Infinity, lastComputed = Infinity,
      value, computed;
  if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) {
    obj = Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) ? obj : Object(__WEBPACK_IMPORTED_MODULE_1__values_js__["a" /* default */])(obj);
    for (var i = 0, length = obj.length; i < length; i++) {
      value = obj[i];
      if (value != null && value < result) {
        result = value;
      }
    }
  } else {
    iteratee = Object(__WEBPACK_IMPORTED_MODULE_2__cb_js__["a" /* default */])(iteratee, context);
    Object(__WEBPACK_IMPORTED_MODULE_3__each_js__["a" /* default */])(obj, function(v, index, list) {
      computed = iteratee(v, index, list);
      if (computed < lastComputed || (computed === Infinity && result === Infinity)) {
        result = v;
        lastComputed = computed;
      }
    });
  }
  return result;
}


/***/ }),
/* 165 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = shuffle;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sample_js__ = __webpack_require__(92);


// Shuffle a collection.
function shuffle(obj) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__sample_js__["a" /* default */])(obj, Infinity);
}


/***/ }),
/* 166 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = sortBy;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__cb_js__ = __webpack_require__(6);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__pluck_js__ = __webpack_require__(49);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__map_js__ = __webpack_require__(21);




// Sort the object's values by a criterion produced by an iteratee.
function sortBy(obj, iteratee, context) {
  var index = 0;
  iteratee = Object(__WEBPACK_IMPORTED_MODULE_0__cb_js__["a" /* default */])(iteratee, context);
  return Object(__WEBPACK_IMPORTED_MODULE_1__pluck_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_2__map_js__["a" /* default */])(obj, function(value, key, list) {
    return {
      value: value,
      index: index++,
      criteria: iteratee(value, key, list)
    };
  }).sort(function(left, right) {
    var a = left.criteria;
    var b = right.criteria;
    if (a !== b) {
      if (a > b || a === void 0) return 1;
      if (a < b || b === void 0) return -1;
    }
    return left.index - right.index;
  }), 'value');
}


/***/ }),
/* 167 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__group_js__ = __webpack_require__(32);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__has_js__ = __webpack_require__(13);



// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__group_js__["a" /* default */])(function(result, value, key) {
  if (Object(__WEBPACK_IMPORTED_MODULE_1__has_js__["a" /* default */])(result, key)) result[key].push(value); else result[key] = [value];
}));


/***/ }),
/* 168 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__group_js__ = __webpack_require__(32);


// Indexes the object's values by a criterion, similar to `_.groupBy`, but for
// when you know that your index values will be unique.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__group_js__["a" /* default */])(function(result, value, key) {
  result[key] = value;
}));


/***/ }),
/* 169 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__group_js__ = __webpack_require__(32);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__has_js__ = __webpack_require__(13);



// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__group_js__["a" /* default */])(function(result, value, key) {
  if (Object(__WEBPACK_IMPORTED_MODULE_1__has_js__["a" /* default */])(result, key)) result[key]++; else result[key] = 1;
}));


/***/ }),
/* 170 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__group_js__ = __webpack_require__(32);


// Split a collection into two arrays: one whose elements all pass the given
// truth test, and one whose elements all do not pass the truth test.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__group_js__["a" /* default */])(function(result, value, pass) {
  result[pass ? 0 : 1].push(value);
}, true));


/***/ }),
/* 171 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = size;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__keys_js__ = __webpack_require__(4);



// Return the number of elements in a collection.
function size(obj) {
  if (obj == null) return 0;
  return Object(__WEBPACK_IMPORTED_MODULE_0__isArrayLike_js__["a" /* default */])(obj) ? obj.length : Object(__WEBPACK_IMPORTED_MODULE_1__keys_js__["a" /* default */])(obj).length;
}


/***/ }),
/* 172 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = keyInObj;
// Internal `_.pick` helper function to determine whether `key` is an enumerable
// property name of `obj`.
function keyInObj(value, key, obj) {
  return key in obj;
}


/***/ }),
/* 173 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__isFunction_js__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__negate_js__ = __webpack_require__(47);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__map_js__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__flatten_js__ = __webpack_require__(20);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__contains_js__ = __webpack_require__(28);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__pick_js__ = __webpack_require__(94);








// Return a copy of the object without the disallowed properties.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(obj, keys) {
  var iteratee = keys[0], context;
  if (Object(__WEBPACK_IMPORTED_MODULE_1__isFunction_js__["a" /* default */])(iteratee)) {
    iteratee = Object(__WEBPACK_IMPORTED_MODULE_2__negate_js__["a" /* default */])(iteratee);
    if (keys.length > 1) context = keys[1];
  } else {
    keys = Object(__WEBPACK_IMPORTED_MODULE_3__map_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_4__flatten_js__["a" /* default */])(keys, false, false), String);
    iteratee = function(value, key) {
      return !Object(__WEBPACK_IMPORTED_MODULE_5__contains_js__["a" /* default */])(keys, key);
    };
  }
  return Object(__WEBPACK_IMPORTED_MODULE_6__pick_js__["a" /* default */])(obj, iteratee, context);
}));


/***/ }),
/* 174 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = first;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__initial_js__ = __webpack_require__(95);


// Get the first element of an array. Passing **n** will return the first N
// values in the array. The **guard** check allows it to work with `_.map`.
function first(array, n, guard) {
  if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
  if (n == null || guard) return array[0];
  return Object(__WEBPACK_IMPORTED_MODULE_0__initial_js__["a" /* default */])(array, array.length - n);
}


/***/ }),
/* 175 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = last;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__rest_js__ = __webpack_require__(96);


// Get the last element of an array. Passing **n** will return the last N
// values in the array.
function last(array, n, guard) {
  if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
  if (n == null || guard) return array[array.length - 1];
  return Object(__WEBPACK_IMPORTED_MODULE_0__rest_js__["a" /* default */])(array, Math.max(0, array.length - n));
}


/***/ }),
/* 176 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = compact;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__filter_js__ = __webpack_require__(27);


// Trim out all falsy values from an array.
function compact(array) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__filter_js__["a" /* default */])(array, Boolean);
}


/***/ }),
/* 177 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = flatten;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__flatten_js__ = __webpack_require__(20);


// Flatten out an array, either recursively (by default), or up to `depth`.
// Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively.
function flatten(array, depth) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__flatten_js__["a" /* default */])(array, depth, false);
}


/***/ }),
/* 178 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__difference_js__ = __webpack_require__(97);



// Return a version of the array that does not contain the specified value(s).
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(array, otherArrays) {
  return Object(__WEBPACK_IMPORTED_MODULE_1__difference_js__["a" /* default */])(array, otherArrays);
}));


/***/ }),
/* 179 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__uniq_js__ = __webpack_require__(98);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__flatten_js__ = __webpack_require__(20);




// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(function(arrays) {
  return Object(__WEBPACK_IMPORTED_MODULE_1__uniq_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_2__flatten_js__["a" /* default */])(arrays, true, true));
}));


/***/ }),
/* 180 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = intersection;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__contains_js__ = __webpack_require__(28);



// Produce an array that contains every item shared between all the
// passed-in arrays.
function intersection(array) {
  var result = [];
  var argsLength = arguments.length;
  for (var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(array); i < length; i++) {
    var item = array[i];
    if (Object(__WEBPACK_IMPORTED_MODULE_1__contains_js__["a" /* default */])(result, item)) continue;
    var j;
    for (j = 1; j < argsLength; j++) {
      if (!Object(__WEBPACK_IMPORTED_MODULE_1__contains_js__["a" /* default */])(arguments[j], item)) break;
    }
    if (j === argsLength) result.push(item);
  }
  return result;
}


/***/ }),
/* 181 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__restArguments_js__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__unzip_js__ = __webpack_require__(99);



// Zip together multiple lists into a single array -- elements that share
// an index go together.
/* harmony default export */ __webpack_exports__["a"] = (Object(__WEBPACK_IMPORTED_MODULE_0__restArguments_js__["a" /* default */])(__WEBPACK_IMPORTED_MODULE_1__unzip_js__["a" /* default */]));


/***/ }),
/* 182 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = object;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__getLength_js__ = __webpack_require__(11);


// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values. Passing by pairs is the reverse of `_.pairs`.
function object(list, values) {
  var result = {};
  for (var i = 0, length = Object(__WEBPACK_IMPORTED_MODULE_0__getLength_js__["a" /* default */])(list); i < length; i++) {
    if (values) {
      result[list[i]] = values[i];
    } else {
      result[list[i][0]] = list[i][1];
    }
  }
  return result;
}


/***/ }),
/* 183 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = range;
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](https://docs.python.org/library/functions.html#range).
function range(start, stop, step) {
  if (stop == null) {
    stop = start || 0;
    start = 0;
  }
  if (!step) {
    step = stop < start ? -1 : 1;
  }

  var length = Math.max(Math.ceil((stop - start) / step), 0);
  var range = Array(length);

  for (var idx = 0; idx < length; idx++, start += step) {
    range[idx] = start;
  }

  return range;
}


/***/ }),
/* 184 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = chunk;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__setup_js__ = __webpack_require__(1);


// Chunk a single array into multiple arrays, each containing `count` or fewer
// items.
function chunk(array, count) {
  if (count == null || count < 1) return [];
  var result = [];
  var i = 0, length = array.length;
  while (i < length) {
    result.push(__WEBPACK_IMPORTED_MODULE_0__setup_js__["q" /* slice */].call(array, i, i += count));
  }
  return result;
}


/***/ }),
/* 185 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = mixin;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__each_js__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__functions_js__ = __webpack_require__(66);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__chainResult_js__ = __webpack_require__(100);






// Add your own custom functions to the Underscore object.
function mixin(obj) {
  Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(Object(__WEBPACK_IMPORTED_MODULE_2__functions_js__["a" /* default */])(obj), function(name) {
    var func = __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */][name] = obj[name];
    __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].prototype[name] = function() {
      var args = [this._wrapped];
      __WEBPACK_IMPORTED_MODULE_3__setup_js__["o" /* push */].apply(args, arguments);
      return Object(__WEBPACK_IMPORTED_MODULE_4__chainResult_js__["a" /* default */])(this, func.apply(__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */], args));
    };
  });
  return __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */];
}


/***/ }),
/* 186 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__underscore_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__each_js__ = __webpack_require__(16);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__chainResult_js__ = __webpack_require__(100);





// Add all mutator `Array` functions to the wrapper.
Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
  var method = __WEBPACK_IMPORTED_MODULE_2__setup_js__["a" /* ArrayProto */][name];
  __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].prototype[name] = function() {
    var obj = this._wrapped;
    if (obj != null) {
      method.apply(obj, arguments);
      if ((name === 'shift' || name === 'splice') && obj.length === 0) {
        delete obj[0];
      }
    }
    return Object(__WEBPACK_IMPORTED_MODULE_3__chainResult_js__["a" /* default */])(this, obj);
  };
});

// Add all accessor `Array` functions to the wrapper.
Object(__WEBPACK_IMPORTED_MODULE_1__each_js__["a" /* default */])(['concat', 'join', 'slice'], function(name) {
  var method = __WEBPACK_IMPORTED_MODULE_2__setup_js__["a" /* ArrayProto */][name];
  __WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */].prototype[name] = function() {
    var obj = this._wrapped;
    if (obj != null) obj = method.apply(obj, arguments);
    return Object(__WEBPACK_IMPORTED_MODULE_3__chainResult_js__["a" /* default */])(this, obj);
  };
});

/* harmony default export */ __webpack_exports__["a"] = (__WEBPACK_IMPORTED_MODULE_0__underscore_js__["a" /* default */]);


/***/ }),
/* 187 */
/***/ (function(module, exports) {

if (typeof importScripts !== 'function') {
    (function (w, l, r) {
        function s(a, c) { var d = c.getBoundingClientRect(); return { x: Math.max(Math.min(a.clientX - d.left, c.clientWidth), 0), y: Math.max(Math.min(a.clientY - d.top, c.clientHeight), 0) }; }
        function f(a, c, d) { a = l.createElementNS("http://www.w3.org/2000/svg", a); for (var b in c)
            a.setAttribute(b, c[b]); Array.isArray(d) || (d = [d]); c = 0; for (b = d[0] && d.length || 0; c < b; c++)
            a.appendChild(d[c]); return a; }
        function k(a) {
            var c, d, b, e, h = a.h % 360 / 60;
            e = a.v * a.s;
            b = e * (1 - Math.abs(h % 2 - 1));
            c = d = a = a.v - e;
            h = ~~h;
            c += [e, b, 0, 0, b, e][h];
            d += [b, e,
                e, b, 0, 0][h];
            a += [0, 0, b, e, e, b][h];
            b = Math.floor(255 * c);
            d = Math.floor(255 * d);
            a = Math.floor(255 * a);
            return { r: b, g: d, b: a, hex: "#" + (16777216 | a | d << 8 | b << 16).toString(16).slice(1) };
        }
        function m(a) { var c = a.r, d = a.g, b = a.b; if (1 < a.r || 1 < a.g || 1 < a.b)
            c /= 255, d /= 255, b /= 255; var e; a = Math.max(c, d, b); e = a - Math.min(c, d, b); c = (0 == e ? 0 : a == c ? (d - b) / e + (d < b ? 6 : 0) : a == d ? (b - c) / e + 2 : (c - d) / e + 4) % 6 * 60; return { h: c, s: 0 == e ? 0 : e / a, v: a }; }
        function x(a, c, d) {
            return function (b) {
                b = s(b, c);
                a.h = b.y / c.offsetHeight * 360;
                var e = k({ h: a.h, s: 1, v: 1 }), h = k({ h: a.h, s: a.s, v: a.v });
                d.style.backgroundColor = e.hex;
                a.callback && a.callback(h.hex, { h: a.h, s: a.s, v: a.v }, { r: h.r, g: h.g, b: h.b }, r, b);
            };
        }
        function y(a, c) { return function (d) { d = s(d, c); var b = c.offsetHeight; a.s = d.x / c.offsetWidth; a.v = (b - d.y) / b; b = k(a); a.callback && a.callback(b.hex, { h: a.h, s: a.s, v: a.v }, { r: b.r, g: b.g, b: b.b }, d); }; }
        function g(a, c, d) {
            if (!(this instanceof g))
                return new g(a, c, d);
            this.h = 0;
            this.v = this.s = 1;
            d ? (this.callback = d, this.pickerElement = c, this.slideElement = a) : (a.innerHTML = '<div class="picker-wrapper"><div class="picker"></div><div class="picker-indicator"></div></div><div class="slide-wrapper"><div class="slide"></div><div class="slide-indicator"></div></div>',
                this.slideElement = a.getElementsByClassName("slide")[0], this.pickerElement = a.getElementsByClassName("picker")[0], this.slideIndicator = a.getElementsByClassName("slide-indicator")[0], this.pickerIndicator = a.getElementsByClassName("picker-indicator")[0], g.positionIndicators(this.slideIndicator, this.pickerIndicator, { x: 0, y: 0 }, { x: 0, y: 0 }), this.callback = function (a, b, d, e, f) { g.positionIndicators(this.slideIndicator, this.pickerIndicator, f, e); c(a, b, d); });
            this.slide_listener = x(this, this.slideElement, this.pickerElement);
            this.picker_listener = y(this, this.pickerElement);
            d || this.fixIndicators(this.slideIndicator, this.pickerIndicator);
            a = t.cloneNode(!0);
            d = u.cloneNode(!0);
            var b = a.getElementsByTagName("defs")[0].firstChild, e = a.getElementsByTagName("rect")[0];
            b.id = "gradient-hsv-" + n;
            e.setAttribute("fill", "url(#" + b.id + ")");
            b = d.getElementsByTagName("defs")[0];
            b = [b.firstChild, b.lastChild];
            e = d.getElementsByTagName("rect");
            b[0].id = "gradient-black-" + n;
            b[1].id = "gradient-white-" + n;
            e[0].setAttribute("fill", "url(#" + b[1].id + ")");
            e[1].setAttribute("fill", "url(#" + b[0].id + ")");
            this.slideElement.appendChild(a);
            this.pickerElement.appendChild(d);
            n++;
            p(this.slideElement, this.slide_listener);
            p(this.pickerElement, this.picker_listener);
        }
        function p(a, c) { function d(a) { e && c(a); } function b(a) { d(a); e = !1; l.removeEventListener("mouseup", b, !1); l.removeEventListener("mousemove", d, !1); } var e = !1; a.addEventListener("mousedown", function (a) { e = !0; a.preventDefault(); l.addEventListener("mouseup", b, !0); l.addEventListener("mousemove", d, !1); }, !1); }
        function q(a, c, d, b) {
            a.h = c.h % 360;
            a.s = c.s;
            a.v = c.v;
            c = k(a);
            var e = { y: a.h * a.slideElement.offsetHeight / 360, x: 0 }, f = a.pickerElement.offsetHeight, f = { x: a.s * a.pickerElement.offsetWidth, y: f - a.v * f };
            a.pickerElement.style.backgroundColor = k({ h: a.h, s: 1, v: 1 }).hex;
            a.callback && a.callback(b || c.hex, { h: a.h, s: a.s, v: a.v }, d || { r: c.r, g: c.g, b: c.b }, f, e);
            return a;
        }
        var u, t, v = { xmlns: "http://www.w3.org/2000/svg", version: "1.1", width: "100%", height: "100%" };
        t = f("svg", v, [f("defs", {}, f("linearGradient", { id: "gradient-hsv", x1: "0%", y1: "100%", x2: "0%", y2: "0%" }, [f("stop", { offset: "0%",
                    "stop-color": "#FF0000", "stop-opacity": "1" }), f("stop", { offset: "13%", "stop-color": "#FF00FF", "stop-opacity": "1" }), f("stop", { offset: "25%", "stop-color": "#8000FF", "stop-opacity": "1" }), f("stop", { offset: "38%", "stop-color": "#0040FF", "stop-opacity": "1" }), f("stop", { offset: "50%", "stop-color": "#00FFFF", "stop-opacity": "1" }), f("stop", { offset: "63%", "stop-color": "#00FF40", "stop-opacity": "1" }), f("stop", { offset: "75%", "stop-color": "#0BED00", "stop-opacity": "1" }), f("stop", { offset: "88%", "stop-color": "#FFFF00", "stop-opacity": "1" }),
                f("stop", { offset: "100%", "stop-color": "#FF0000", "stop-opacity": "1" })])), f("rect", { x: "0", y: "0", width: "100%", height: "100%", fill: "url(#gradient-hsv)" })]);
        u = f("svg", v, [f("defs", {}, [f("linearGradient", { id: "gradient-black", x1: "0%", y1: "100%", x2: "0%", y2: "0%" }, [f("stop", { offset: "0%", "stop-color": "#000000", "stop-opacity": "1" }), f("stop", { offset: "100%", "stop-color": "#CC9A81", "stop-opacity": "0" })]), f("linearGradient", { id: "gradient-white", x1: "0%", y1: "100%", x2: "100%", y2: "100%" }, [f("stop", { offset: "0%", "stop-color": "#FFFFFF",
                        "stop-opacity": "1" }), f("stop", { offset: "100%", "stop-color": "#CC9A81", "stop-opacity": "0" })])]), f("rect", { x: "0", y: "0", width: "100%", height: "100%", fill: "url(#gradient-white)" }), f("rect", { x: "0", y: "0", width: "100%", height: "100%", fill: "url(#gradient-black)" })]);
        var n = 0;
        g.hsv2rgb = function (a) { a = k(a); delete a.hex; return a; };
        g.hsv2hex = function (a) { return k(a).hex; };
        g.rgb2hsv = m;
        g.rgb2hex = function (a) { return k(m(a)).hex; };
        g.hex2hsv = function (a) { return m(g.hex2rgb(a)); };
        g.hex2rgb = function (a) {
            return { r: parseInt(a.substr(1, 2), 16), g: parseInt(a.substr(3, 2), 16), b: parseInt(a.substr(5, 2), 16) };
        };
        g.prototype.setHsv = function (a) { return q(this, a); };
        g.prototype.setRgb = function (a) { return q(this, m(a), a); };
        g.prototype.setHex = function (a) { return q(this, g.hex2hsv(a), r, a); };
        g.positionIndicators = function (a, c, d, b) { d && (a.style.top = d.y - a.offsetHeight / 2 + "px"); b && (c.style.top = b.y - c.offsetHeight / 2 + "px", c.style.left = b.x - c.offsetWidth / 2 + "px"); };
        g.prototype.fixIndicators = function (a, c) { p(a, this.slide_listener); p(c, this.picker_listener); };
        w.ColorPicker =
            g;
    })(window, window.document);
}
//# sourceMappingURL=data:application/json;base64, 

/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * @file UI NGL
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
// Color
var NGL = __webpack_require__(18);
var UI = __webpack_require__(102).UI;
UI.ColorPopupMenu = function () {
    var scope = this;
    UI.Panel.call(this);
    this.iconText = new UI.Text('')
        .setCursor('pointer')
        .setClass('fa-stack-1x')
        .setFontFamily('Arial, sans-serif')
        .setColor('#111');
    this.iconSquare = new UI.Icon('square', 'stack-1x');
    // .setMarginTop( "0.05em" );
    this.menu = new UI.PopupMenu('stack', 'Color');
    this.menu.icon
        .setTitle('color')
        .setWidth('1em').setHeight('1em').setLineHeight('1em')
        .add(this.iconSquare)
        .add(this.iconText);
    var changeEvent = document.createEvent('Event');
    changeEvent.initEvent('change', true, true);
    this.colorInput = new UI.Input()
        .onChange(function () {
        scope.setColor(scope.colorInput.getValue());
        scope.dom.dispatchEvent(changeEvent);
    });
    this.colorPicker = new UI.ColorPicker()
        .setDisplay('inline-block')
        .onChange(function (e) {
        scope.setColor(scope.colorPicker.getValue());
        scope.dom.dispatchEvent(changeEvent);
    });
    this.menu
        .addEntry('Input', this.colorInput)
        .addEntry('Picker', this.colorPicker);
    this.add(this.menu);
    this.setClass('')
        .setDisplay('inline');
    return this;
};
UI.ColorPopupMenu.prototype = Object.create(UI.Panel.prototype);
UI.ColorPopupMenu.prototype.setColor = (function () {
    var c = new NGL.Color();
    return function (value) {
        c.set(value);
        value = '#' + c.getHexString();
        this.colorInput
            .setBackgroundColor(value)
            .setValue(value);
        this.colorPicker.setValue(value);
        this.iconSquare.setColor(value);
        // perceived brightness (http://alienryderflex.com/hsp.html)
        var brightness = Math.sqrt(c.r * 255 * c.r * 255 * 0.241 +
            c.g * 255 * c.g * 255 * 0.691 +
            c.b * 255 * c.b * 255 * 0.068);
        if (brightness > 130) {
            this.iconText.setColor('#000000');
            this.colorInput.setColor('#000000');
        }
        else {
            this.iconText.setColor('#FFFFFF');
            this.colorInput.setColor('#FFFFFF');
        }
        return this;
    };
}());
UI.ColorPopupMenu.prototype.getColor = function () {
    return this.colorInput.getValue();
};
UI.ColorPopupMenu.prototype.getValue = function () {
    return this.getColor();
};
UI.ColorPopupMenu.prototype.setValue = function (value) {
    this.setColor(value);
    return this;
};
UI.ColorPopupMenu.prototype.dispose = function () {
    this.menu.dispose();
    UI.Panel.prototype.dispose.call(this);
};
// Vector3
UI.Vector3 = function (value) {
    UI.Panel.call(this).setDisplay('inline-block');
    this.xNumber = new UI.Number(0).setWidth('40px');
    this.yNumber = new UI.Number(0).setWidth('40px');
    this.zNumber = new UI.Number(0).setWidth('40px');
    this.add(this.xNumber, this.yNumber, this.zNumber);
    this.setValue(value);
    var changeEvent = document.createEvent('Event');
    changeEvent.initEvent('change', true, true);
    this.xNumber.onChange(function () {
        this.dom.dispatchEvent(changeEvent);
    }.bind(this));
    this.yNumber.onChange(function () {
        this.dom.dispatchEvent(changeEvent);
    }.bind(this));
    this.zNumber.onChange(function () {
        this.dom.dispatchEvent(changeEvent);
    }.bind(this));
    return this;
};
UI.Vector3.prototype = Object.create(UI.Panel.prototype);
UI.Vector3.prototype.getValue = function () {
    return {
        x: this.xNumber.getValue(),
        y: this.yNumber.getValue(),
        z: this.zNumber.getValue()
    };
};
UI.Vector3.prototype.setValue = function (value) {
    if (value) {
        this.xNumber.setValue(value.x);
        this.yNumber.setValue(value.y);
        this.zNumber.setValue(value.z);
    }
    return this;
};
UI.Vector3.prototype.setPrecision = function (precision) {
    this.xNumber.setPrecision(precision);
    this.yNumber.setPrecision(precision);
    this.zNumber.setPrecision(precision);
    return this;
};
UI.Vector3.prototype.setRange = function (min, max) {
    this.xNumber.setRange(min, max);
    this.yNumber.setRange(min, max);
    this.zNumber.setRange(min, max);
    return this;
};
// Selection
UI.SelectionInput = function (selection) {
    UI.AdaptiveTextArea.call(this);
    this.setSpellcheck(false);
    if (!(selection.type === 'selection')) {
        NGL.error('UI.SelectionInput: not a selection', selection);
        return this;
    }
    this.setValue(selection.string);
    this.selection = selection;
    var scope = this;
    var signals = selection.signals;
    signals.stringChanged.add(function (string) {
        scope.setValue(string);
    });
    this.onEnter();
    return this;
};
UI.SelectionInput.prototype = Object.create(UI.AdaptiveTextArea.prototype);
UI.SelectionInput.prototype.setValue = function (value) {
    UI.AdaptiveTextArea.prototype.setValue.call(this, value);
    return this;
};
UI.SelectionInput.prototype.onEnter = function (callback) {
    // TODO more a private method
    var scope = this;
    var check = function (string) {
        var selection = new NGL.Selection(string);
        return !selection.selection['error'];
    };
    this.onKeyPress(function (e) {
        var value = scope.getValue();
        var character = String.fromCharCode(e.which);
        if (e.keyCode === 13) {
            e.preventDefault();
            if (check(value)) {
                if (typeof callback === 'function') {
                    callback(value);
                }
                else {
                    scope.selection.setString(value);
                }
                scope.setBackgroundColor('white');
            }
            else {
                scope.setBackgroundColor('tomato');
            }
        }
        else if (scope.selection.string !== value + character) {
            scope.setBackgroundColor('skyblue');
        }
        else {
            scope.setBackgroundColor('white');
        }
    });
    this.onKeyUp(function (e) {
        var value = scope.getValue();
        if (!check(value)) {
            scope.setBackgroundColor('tomato');
        }
        else if (scope.selection.string === scope.getValue()) {
            scope.setBackgroundColor('white');
        }
        else {
            scope.setBackgroundColor('skyblue');
        }
    });
    return this;
};
UI.SelectionPanel = function (selection) {
    UI.Panel.call(this);
    this.icon = new UI.Icon('filter')
        .setTitle('filter selection')
        .addClass('lg')
        .setMarginRight('10px');
    this.input = new UI.SelectionInput(selection);
    this.add(this.icon, this.input);
    return this;
};
UI.SelectionPanel.prototype = Object.create(UI.Panel.prototype);
UI.SelectionPanel.prototype.setInputWidth = function (value) {
    this.input.setWidth(value);
    return this;
};
// Component
UI.ComponentPanel = function (component) {
    UI.Panel.call(this);
    var stage = component.stage;
    var signals = component.signals;
    signals.nameChanged.add(function (value) {
        name.setValue(value);
    });
    signals.visibilityChanged.add(function (value) {
        toggle.setValue(value);
    });
    signals.disposed.add(function () {
        menu.dispose();
    });
    // Name
    var name = new UI.EllipsisText(component.name)
        .setWidth('100px');
    // Actions
    var toggle = new UI.ToggleIcon(component.visible, 'eye', 'eye-slash')
        .setTitle('hide/show')
        .setCursor('pointer')
        .setMarginLeft('25px')
        .onClick(function () {
        component.setVisibility(!component.visible);
    });
    var center = new UI.Icon('bullseye')
        .setTitle('center')
        .setCursor('pointer')
        .setMarginLeft('10px')
        .onClick(function () {
        component.autoView(1000);
    });
    var dispose = new UI.DisposeIcon()
        .setMarginLeft('10px')
        .setDisposeFunction(function () {
        stage.removeComponent(component);
    });
    // Menu
    var menu = new UI.PopupMenu('bars', component.type)
        .setMarginLeft('46px')
        .setEntryLabelWidth('110px');
    //
    this.add(name, toggle, center, dispose, menu);
    //
    this.menu = menu;
    return this;
};
UI.ComponentPanel.prototype = Object.create(UI.Panel.prototype);
UI.ComponentPanel.prototype.addMenuEntry = function (label, entry) {
    this.menu.addEntry(label, entry);
    return this;
};
UI.ComponentPanel.prototype.setMenuDisplay = function (value) {
    this.menu.setMenuDisplay(value);
    return this;
};
module.exports = {
    "UI": UI
};
//# sourceMappingURL=data:application/json;base64, 

/***/ }),
/* 189 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Dialog 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Dialog
//>>group: Widgets
//>>description: Displays customizable dialog windows.
//>>docs: http://api.jqueryui.com/dialog/
//>>demos: http://jqueryui.com/dialog/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/dialog.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
			__webpack_require__(0),
			__webpack_require__(190),
			__webpack_require__(196),
			__webpack_require__(51),
			__webpack_require__(200),
			__webpack_require__(107),
			__webpack_require__(103),
			__webpack_require__(202),
			__webpack_require__(105),
			__webpack_require__(106),
			__webpack_require__(203),
			__webpack_require__(204),
			__webpack_require__(3),
			__webpack_require__(17)
		], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.dialog", {
	version: "1.13.2",
	options: {
		appendTo: "body",
		autoOpen: true,
		buttons: [],
		classes: {
			"ui-dialog": "ui-corner-all",
			"ui-dialog-titlebar": "ui-corner-all"
		},
		closeOnEscape: true,
		closeText: "Close",
		draggable: true,
		hide: null,
		height: "auto",
		maxHeight: null,
		maxWidth: null,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: {
			my: "center",
			at: "center",
			of: window,
			collision: "fit",

			// Ensure the titlebar is always visible
			using: function( pos ) {
				var topOffset = $( this ).css( pos ).offset().top;
				if ( topOffset < 0 ) {
					$( this ).css( "top", pos.top - topOffset );
				}
			}
		},
		resizable: true,
		show: null,
		title: null,
		width: 300,

		// Callbacks
		beforeClose: null,
		close: null,
		drag: null,
		dragStart: null,
		dragStop: null,
		focus: null,
		open: null,
		resize: null,
		resizeStart: null,
		resizeStop: null
	},

	sizeRelatedOptions: {
		buttons: true,
		height: true,
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true,
		width: true
	},

	resizableRelatedOptions: {
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true
	},

	_create: function() {
		this.originalCss = {
			display: this.element[ 0 ].style.display,
			width: this.element[ 0 ].style.width,
			minHeight: this.element[ 0 ].style.minHeight,
			maxHeight: this.element[ 0 ].style.maxHeight,
			height: this.element[ 0 ].style.height
		};
		this.originalPosition = {
			parent: this.element.parent(),
			index: this.element.parent().children().index( this.element )
		};
		this.originalTitle = this.element.attr( "title" );
		if ( this.options.title == null && this.originalTitle != null ) {
			this.options.title = this.originalTitle;
		}

		// Dialogs can't be disabled
		if ( this.options.disabled ) {
			this.options.disabled = false;
		}

		this._createWrapper();

		this.element
			.show()
			.removeAttr( "title" )
			.appendTo( this.uiDialog );

		this._addClass( "ui-dialog-content", "ui-widget-content" );

		this._createTitlebar();
		this._createButtonPane();

		if ( this.options.draggable && $.fn.draggable ) {
			this._makeDraggable();
		}
		if ( this.options.resizable && $.fn.resizable ) {
			this._makeResizable();
		}

		this._isOpen = false;

		this._trackFocus();
	},

	_init: function() {
		if ( this.options.autoOpen ) {
			this.open();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;
		if ( element && ( element.jquery || element.nodeType ) ) {
			return $( element );
		}
		return this.document.find( element || "body" ).eq( 0 );
	},

	_destroy: function() {
		var next,
			originalPosition = this.originalPosition;

		this._untrackInstance();
		this._destroyOverlay();

		this.element
			.removeUniqueId()
			.css( this.originalCss )

			// Without detaching first, the following becomes really slow
			.detach();

		this.uiDialog.remove();

		if ( this.originalTitle ) {
			this.element.attr( "title", this.originalTitle );
		}

		next = originalPosition.parent.children().eq( originalPosition.index );

		// Don't try to place the dialog next to itself (#8613)
		if ( next.length && next[ 0 ] !== this.element[ 0 ] ) {
			next.before( this.element );
		} else {
			originalPosition.parent.append( this.element );
		}
	},

	widget: function() {
		return this.uiDialog;
	},

	disable: $.noop,
	enable: $.noop,

	close: function( event ) {
		var that = this;

		if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
			return;
		}

		this._isOpen = false;
		this._focusedElement = null;
		this._destroyOverlay();
		this._untrackInstance();

		if ( !this.opener.filter( ":focusable" ).trigger( "focus" ).length ) {

			// Hiding a focused element doesn't trigger blur in WebKit
			// so in case we have nothing to focus on, explicitly blur the active element
			// https://bugs.webkit.org/show_bug.cgi?id=47182
			$.ui.safeBlur( $.ui.safeActiveElement( this.document[ 0 ] ) );
		}

		this._hide( this.uiDialog, this.options.hide, function() {
			that._trigger( "close", event );
		} );
	},

	isOpen: function() {
		return this._isOpen;
	},

	moveToTop: function() {
		this._moveToTop();
	},

	_moveToTop: function( event, silent ) {
		var moved = false,
			zIndices = this.uiDialog.siblings( ".ui-front:visible" ).map( function() {
				return +$( this ).css( "z-index" );
			} ).get(),
			zIndexMax = Math.max.apply( null, zIndices );

		if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) {
			this.uiDialog.css( "z-index", zIndexMax + 1 );
			moved = true;
		}

		if ( moved && !silent ) {
			this._trigger( "focus", event );
		}
		return moved;
	},

	open: function() {
		var that = this;
		if ( this._isOpen ) {
			if ( this._moveToTop() ) {
				this._focusTabbable();
			}
			return;
		}

		this._isOpen = true;
		this.opener = $( $.ui.safeActiveElement( this.document[ 0 ] ) );

		this._size();
		this._position();
		this._createOverlay();
		this._moveToTop( null, true );

		// Ensure the overlay is moved to the top with the dialog, but only when
		// opening. The overlay shouldn't move after the dialog is open so that
		// modeless dialogs opened after the modal dialog stack properly.
		if ( this.overlay ) {
			this.overlay.css( "z-index", this.uiDialog.css( "z-index" ) - 1 );
		}

		this._show( this.uiDialog, this.options.show, function() {
			that._focusTabbable();
			that._trigger( "focus" );
		} );

		// Track the dialog immediately upon opening in case a focus event
		// somehow occurs outside of the dialog before an element inside the
		// dialog is focused (#10152)
		this._makeFocusTarget();

		this._trigger( "open" );
	},

	_focusTabbable: function() {

		// Set focus to the first match:
		// 1. An element that was focused previously
		// 2. First element inside the dialog matching [autofocus]
		// 3. Tabbable element inside the content element
		// 4. Tabbable element inside the buttonpane
		// 5. The close button
		// 6. The dialog itself
		var hasFocus = this._focusedElement;
		if ( !hasFocus ) {
			hasFocus = this.element.find( "[autofocus]" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.element.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogButtonPane.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialog;
		}
		hasFocus.eq( 0 ).trigger( "focus" );
	},

	_restoreTabbableFocus: function() {
		var activeElement = $.ui.safeActiveElement( this.document[ 0 ] ),
			isActive = this.uiDialog[ 0 ] === activeElement ||
				$.contains( this.uiDialog[ 0 ], activeElement );
		if ( !isActive ) {
			this._focusTabbable();
		}
	},

	_keepFocus: function( event ) {
		event.preventDefault();
		this._restoreTabbableFocus();

		// support: IE
		// IE <= 8 doesn't prevent moving focus even with event.preventDefault()
		// so we check again later
		this._delay( this._restoreTabbableFocus );
	},

	_createWrapper: function() {
		this.uiDialog = $( "<div>" )
			.hide()
			.attr( {

				// Setting tabIndex makes the div focusable
				tabIndex: -1,
				role: "dialog"
			} )
			.appendTo( this._appendTo() );

		this._addClass( this.uiDialog, "ui-dialog", "ui-widget ui-widget-content ui-front" );
		this._on( this.uiDialog, {
			keydown: function( event ) {
				if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
						event.keyCode === $.ui.keyCode.ESCAPE ) {
					event.preventDefault();
					this.close( event );
					return;
				}

				// Prevent tabbing out of dialogs
				if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) {
					return;
				}
				var tabbables = this.uiDialog.find( ":tabbable" ),
					first = tabbables.first(),
					last = tabbables.last();

				if ( ( event.target === last[ 0 ] || event.target === this.uiDialog[ 0 ] ) &&
						!event.shiftKey ) {
					this._delay( function() {
						first.trigger( "focus" );
					} );
					event.preventDefault();
				} else if ( ( event.target === first[ 0 ] ||
						event.target === this.uiDialog[ 0 ] ) && event.shiftKey ) {
					this._delay( function() {
						last.trigger( "focus" );
					} );
					event.preventDefault();
				}
			},
			mousedown: function( event ) {
				if ( this._moveToTop( event ) ) {
					this._focusTabbable();
				}
			}
		} );

		// We assume that any existing aria-describedby attribute means
		// that the dialog content is marked up properly
		// otherwise we brute force the content as the description
		if ( !this.element.find( "[aria-describedby]" ).length ) {
			this.uiDialog.attr( {
				"aria-describedby": this.element.uniqueId().attr( "id" )
			} );
		}
	},

	_createTitlebar: function() {
		var uiDialogTitle;

		this.uiDialogTitlebar = $( "<div>" );
		this._addClass( this.uiDialogTitlebar,
			"ui-dialog-titlebar", "ui-widget-header ui-helper-clearfix" );
		this._on( this.uiDialogTitlebar, {
			mousedown: function( event ) {

				// Don't prevent click on close button (#8838)
				// Focusing a dialog that is partially scrolled out of view
				// causes the browser to scroll it into view, preventing the click event
				if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) {

					// Dialog isn't getting focus when dragging (#8063)
					this.uiDialog.trigger( "focus" );
				}
			}
		} );

		// Support: IE
		// Use type="button" to prevent enter keypresses in textboxes from closing the
		// dialog in IE (#9312)
		this.uiDialogTitlebarClose = $( "<button type='button'></button>" )
			.button( {
				label: $( "<a>" ).text( this.options.closeText ).html(),
				icon: "ui-icon-closethick",
				showLabel: false
			} )
			.appendTo( this.uiDialogTitlebar );

		this._addClass( this.uiDialogTitlebarClose, "ui-dialog-titlebar-close" );
		this._on( this.uiDialogTitlebarClose, {
			click: function( event ) {
				event.preventDefault();
				this.close( event );
			}
		} );

		uiDialogTitle = $( "<span>" ).uniqueId().prependTo( this.uiDialogTitlebar );
		this._addClass( uiDialogTitle, "ui-dialog-title" );
		this._title( uiDialogTitle );

		this.uiDialogTitlebar.prependTo( this.uiDialog );

		this.uiDialog.attr( {
			"aria-labelledby": uiDialogTitle.attr( "id" )
		} );
	},

	_title: function( title ) {
		if ( this.options.title ) {
			title.text( this.options.title );
		} else {
			title.html( "&#160;" );
		}
	},

	_createButtonPane: function() {
		this.uiDialogButtonPane = $( "<div>" );
		this._addClass( this.uiDialogButtonPane, "ui-dialog-buttonpane",
			"ui-widget-content ui-helper-clearfix" );

		this.uiButtonSet = $( "<div>" )
			.appendTo( this.uiDialogButtonPane );
		this._addClass( this.uiButtonSet, "ui-dialog-buttonset" );

		this._createButtons();
	},

	_createButtons: function() {
		var that = this,
			buttons = this.options.buttons;

		// If we already have a button pane, remove it
		this.uiDialogButtonPane.remove();
		this.uiButtonSet.empty();

		if ( $.isEmptyObject( buttons ) || ( Array.isArray( buttons ) && !buttons.length ) ) {
			this._removeClass( this.uiDialog, "ui-dialog-buttons" );
			return;
		}

		$.each( buttons, function( name, props ) {
			var click, buttonOptions;
			props = typeof props === "function" ?
				{ click: props, text: name } :
				props;

			// Default to a non-submitting button
			props = $.extend( { type: "button" }, props );

			// Change the context for the click callback to be the main element
			click = props.click;
			buttonOptions = {
				icon: props.icon,
				iconPosition: props.iconPosition,
				showLabel: props.showLabel,

				// Deprecated options
				icons: props.icons,
				text: props.text
			};

			delete props.click;
			delete props.icon;
			delete props.iconPosition;
			delete props.showLabel;

			// Deprecated options
			delete props.icons;
			if ( typeof props.text === "boolean" ) {
				delete props.text;
			}

			$( "<button></button>", props )
				.button( buttonOptions )
				.appendTo( that.uiButtonSet )
				.on( "click", function() {
					click.apply( that.element[ 0 ], arguments );
				} );
		} );
		this._addClass( this.uiDialog, "ui-dialog-buttons" );
		this.uiDialogButtonPane.appendTo( this.uiDialog );
	},

	_makeDraggable: function() {
		var that = this,
			options = this.options;

		function filteredUi( ui ) {
			return {
				position: ui.position,
				offset: ui.offset
			};
		}

		this.uiDialog.draggable( {
			cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
			handle: ".ui-dialog-titlebar",
			containment: "document",
			start: function( event, ui ) {
				that._addClass( $( this ), "ui-dialog-dragging" );
				that._blockFrames();
				that._trigger( "dragStart", event, filteredUi( ui ) );
			},
			drag: function( event, ui ) {
				that._trigger( "drag", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var left = ui.offset.left - that.document.scrollLeft(),
					top = ui.offset.top - that.document.scrollTop();

				options.position = {
					my: "left top",
					at: "left" + ( left >= 0 ? "+" : "" ) + left + " " +
						"top" + ( top >= 0 ? "+" : "" ) + top,
					of: that.window
				};
				that._removeClass( $( this ), "ui-dialog-dragging" );
				that._unblockFrames();
				that._trigger( "dragStop", event, filteredUi( ui ) );
			}
		} );
	},

	_makeResizable: function() {
		var that = this,
			options = this.options,
			handles = options.resizable,

			// .ui-resizable has position: relative defined in the stylesheet
			// but dialogs have to use absolute or fixed positioning
			position = this.uiDialog.css( "position" ),
			resizeHandles = typeof handles === "string" ?
				handles :
				"n,e,s,w,se,sw,ne,nw";

		function filteredUi( ui ) {
			return {
				originalPosition: ui.originalPosition,
				originalSize: ui.originalSize,
				position: ui.position,
				size: ui.size
			};
		}

		this.uiDialog.resizable( {
			cancel: ".ui-dialog-content",
			containment: "document",
			alsoResize: this.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: this._minHeight(),
			handles: resizeHandles,
			start: function( event, ui ) {
				that._addClass( $( this ), "ui-dialog-resizing" );
				that._blockFrames();
				that._trigger( "resizeStart", event, filteredUi( ui ) );
			},
			resize: function( event, ui ) {
				that._trigger( "resize", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var offset = that.uiDialog.offset(),
					left = offset.left - that.document.scrollLeft(),
					top = offset.top - that.document.scrollTop();

				options.height = that.uiDialog.height();
				options.width = that.uiDialog.width();
				options.position = {
					my: "left top",
					at: "left" + ( left >= 0 ? "+" : "" ) + left + " " +
						"top" + ( top >= 0 ? "+" : "" ) + top,
					of: that.window
				};
				that._removeClass( $( this ), "ui-dialog-resizing" );
				that._unblockFrames();
				that._trigger( "resizeStop", event, filteredUi( ui ) );
			}
		} )
			.css( "position", position );
	},

	_trackFocus: function() {
		this._on( this.widget(), {
			focusin: function( event ) {
				this._makeFocusTarget();
				this._focusedElement = $( event.target );
			}
		} );
	},

	_makeFocusTarget: function() {
		this._untrackInstance();
		this._trackingInstances().unshift( this );
	},

	_untrackInstance: function() {
		var instances = this._trackingInstances(),
			exists = $.inArray( this, instances );
		if ( exists !== -1 ) {
			instances.splice( exists, 1 );
		}
	},

	_trackingInstances: function() {
		var instances = this.document.data( "ui-dialog-instances" );
		if ( !instances ) {
			instances = [];
			this.document.data( "ui-dialog-instances", instances );
		}
		return instances;
	},

	_minHeight: function() {
		var options = this.options;

		return options.height === "auto" ?
			options.minHeight :
			Math.min( options.minHeight, options.height );
	},

	_position: function() {

		// Need to show the dialog to get the actual offset in the position plugin
		var isVisible = this.uiDialog.is( ":visible" );
		if ( !isVisible ) {
			this.uiDialog.show();
		}
		this.uiDialog.position( this.options.position );
		if ( !isVisible ) {
			this.uiDialog.hide();
		}
	},

	_setOptions: function( options ) {
		var that = this,
			resize = false,
			resizableOptions = {};

		$.each( options, function( key, value ) {
			that._setOption( key, value );

			if ( key in that.sizeRelatedOptions ) {
				resize = true;
			}
			if ( key in that.resizableRelatedOptions ) {
				resizableOptions[ key ] = value;
			}
		} );

		if ( resize ) {
			this._size();
			this._position();
		}
		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", resizableOptions );
		}
	},

	_setOption: function( key, value ) {
		var isDraggable, isResizable,
			uiDialog = this.uiDialog;

		if ( key === "disabled" ) {
			return;
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.uiDialog.appendTo( this._appendTo() );
		}

		if ( key === "buttons" ) {
			this._createButtons();
		}

		if ( key === "closeText" ) {
			this.uiDialogTitlebarClose.button( {

				// Ensure that we always pass a string
				label: $( "<a>" ).text( "" + this.options.closeText ).html()
			} );
		}

		if ( key === "draggable" ) {
			isDraggable = uiDialog.is( ":data(ui-draggable)" );
			if ( isDraggable && !value ) {
				uiDialog.draggable( "destroy" );
			}

			if ( !isDraggable && value ) {
				this._makeDraggable();
			}
		}

		if ( key === "position" ) {
			this._position();
		}

		if ( key === "resizable" ) {

			// currently resizable, becoming non-resizable
			isResizable = uiDialog.is( ":data(ui-resizable)" );
			if ( isResizable && !value ) {
				uiDialog.resizable( "destroy" );
			}

			// Currently resizable, changing handles
			if ( isResizable && typeof value === "string" ) {
				uiDialog.resizable( "option", "handles", value );
			}

			// Currently non-resizable, becoming resizable
			if ( !isResizable && value !== false ) {
				this._makeResizable();
			}
		}

		if ( key === "title" ) {
			this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) );
		}
	},

	_size: function() {

		// If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
		// divs will both have width and height set, so we need to reset them
		var nonContentHeight, minContentHeight, maxContentHeight,
			options = this.options;

		// Reset content sizing
		this.element.show().css( {
			width: "auto",
			minHeight: 0,
			maxHeight: "none",
			height: 0
		} );

		if ( options.minWidth > options.width ) {
			options.width = options.minWidth;
		}

		// Reset wrapper sizing
		// determine the height of all the non-content elements
		nonContentHeight = this.uiDialog.css( {
			height: "auto",
			width: options.width
		} )
			.outerHeight();
		minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
		maxContentHeight = typeof options.maxHeight === "number" ?
			Math.max( 0, options.maxHeight - nonContentHeight ) :
			"none";

		if ( options.height === "auto" ) {
			this.element.css( {
				minHeight: minContentHeight,
				maxHeight: maxContentHeight,
				height: "auto"
			} );
		} else {
			this.element.height( Math.max( 0, options.height - nonContentHeight ) );
		}

		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
		}
	},

	_blockFrames: function() {
		this.iframeBlocks = this.document.find( "iframe" ).map( function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( {
					position: "absolute",
					width: iframe.outerWidth(),
					height: iframe.outerHeight()
				} )
				.appendTo( iframe.parent() )
				.offset( iframe.offset() )[ 0 ];
		} );
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_allowInteraction: function( event ) {
		if ( $( event.target ).closest( ".ui-dialog" ).length ) {
			return true;
		}

		// TODO: Remove hack when datepicker implements
		// the .ui-front logic (#8989)
		return !!$( event.target ).closest( ".ui-datepicker" ).length;
	},

	_createOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		var jqMinor = $.fn.jquery.substring( 0, 4 );

		// We use a delay in case the overlay is created from an
		// event that we're going to be cancelling (#2804)
		var isOpening = true;
		this._delay( function() {
			isOpening = false;
		} );

		if ( !this.document.data( "ui-dialog-overlays" ) ) {

			// Prevent use of anchors and inputs
			// This doesn't use `_on()` because it is a shared event handler
			// across all open modal dialogs.
			this.document.on( "focusin.ui-dialog", function( event ) {
				if ( isOpening ) {
					return;
				}

				var instance = this._trackingInstances()[ 0 ];
				if ( !instance._allowInteraction( event ) ) {
					event.preventDefault();
					instance._focusTabbable();

					// Support: jQuery >=3.4 <3.6 only
					// Focus re-triggering in jQuery 3.4/3.5 makes the original element
					// have its focus event propagated last, breaking the re-targeting.
					// Trigger focus in a delay in addition if needed to avoid the issue
					// See https://github.com/jquery/jquery/issues/4382
					if ( jqMinor === "3.4." || jqMinor === "3.5." ) {
						instance._delay( instance._restoreTabbableFocus );
					}
				}
			}.bind( this ) );
		}

		this.overlay = $( "<div>" )
			.appendTo( this._appendTo() );

		this._addClass( this.overlay, null, "ui-widget-overlay ui-front" );
		this._on( this.overlay, {
			mousedown: "_keepFocus"
		} );
		this.document.data( "ui-dialog-overlays",
			( this.document.data( "ui-dialog-overlays" ) || 0 ) + 1 );
	},

	_destroyOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		if ( this.overlay ) {
			var overlays = this.document.data( "ui-dialog-overlays" ) - 1;

			if ( !overlays ) {
				this.document.off( "focusin.ui-dialog" );
				this.document.removeData( "ui-dialog-overlays" );
			} else {
				this.document.data( "ui-dialog-overlays", overlays );
			}

			this.overlay.remove();
			this.overlay = null;
		}
	}
} );

// DEPRECATED
// TODO: switch return back to widget declaration at top of file when this is removed
if ( $.uiBackCompat !== false ) {

	// Backcompat for dialogClass option
	$.widget( "ui.dialog", $.ui.dialog, {
		options: {
			dialogClass: ""
		},
		_createWrapper: function() {
			this._super();
			this.uiDialog.addClass( this.options.dialogClass );
		},
		_setOption: function( key, value ) {
			if ( key === "dialogClass" ) {
				this.uiDialog
					.removeClass( this.options.dialogClass )
					.addClass( value );
			}
			this._superApply( arguments );
		}
	} );
}

return $.ui.dialog;

} );


/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Button 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Button
//>>group: Widgets
//>>description: Enhances a form with themeable buttons.
//>>docs: http://api.jqueryui.com/button/
//>>demos: http://jqueryui.com/button/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/button.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
			__webpack_require__(0),

			// These are only for backcompat
			// TODO: Remove after 1.12
			__webpack_require__(191),
			__webpack_require__(192),

			__webpack_require__(103),
			__webpack_require__(17)
		], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.button", {
	version: "1.13.2",
	defaultElement: "<button>",
	options: {
		classes: {
			"ui-button": "ui-corner-all"
		},
		disabled: null,
		icon: null,
		iconPosition: "beginning",
		label: null,
		showLabel: true
	},

	_getCreateOptions: function() {
		var disabled,

			// This is to support cases like in jQuery Mobile where the base widget does have
			// an implementation of _getCreateOptions
			options = this._super() || {};

		this.isInput = this.element.is( "input" );

		disabled = this.element[ 0 ].disabled;
		if ( disabled != null ) {
			options.disabled = disabled;
		}

		this.originalLabel = this.isInput ? this.element.val() : this.element.html();
		if ( this.originalLabel ) {
			options.label = this.originalLabel;
		}

		return options;
	},

	_create: function() {
		if ( !this.option.showLabel & !this.options.icon ) {
			this.options.showLabel = true;
		}

		// We have to check the option again here even though we did in _getCreateOptions,
		// because null may have been passed on init which would override what was set in
		// _getCreateOptions
		if ( this.options.disabled == null ) {
			this.options.disabled = this.element[ 0 ].disabled || false;
		}

		this.hasTitle = !!this.element.attr( "title" );

		// Check to see if the label needs to be set or if its already correct
		if ( this.options.label && this.options.label !== this.originalLabel ) {
			if ( this.isInput ) {
				this.element.val( this.options.label );
			} else {
				this.element.html( this.options.label );
			}
		}
		this._addClass( "ui-button", "ui-widget" );
		this._setOption( "disabled", this.options.disabled );
		this._enhance();

		if ( this.element.is( "a" ) ) {
			this._on( {
				"keyup": function( event ) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						event.preventDefault();

						// Support: PhantomJS <= 1.9, IE 8 Only
						// If a native click is available use it so we actually cause navigation
						// otherwise just trigger a click event
						if ( this.element[ 0 ].click ) {
							this.element[ 0 ].click();
						} else {
							this.element.trigger( "click" );
						}
					}
				}
			} );
		}
	},

	_enhance: function() {
		if ( !this.element.is( "button" ) ) {
			this.element.attr( "role", "button" );
		}

		if ( this.options.icon ) {
			this._updateIcon( "icon", this.options.icon );
			this._updateTooltip();
		}
	},

	_updateTooltip: function() {
		this.title = this.element.attr( "title" );

		if ( !this.options.showLabel && !this.title ) {
			this.element.attr( "title", this.options.label );
		}
	},

	_updateIcon: function( option, value ) {
		var icon = option !== "iconPosition",
			position = icon ? this.options.iconPosition : value,
			displayBlock = position === "top" || position === "bottom";

		// Create icon
		if ( !this.icon ) {
			this.icon = $( "<span>" );

			this._addClass( this.icon, "ui-button-icon", "ui-icon" );

			if ( !this.options.showLabel ) {
				this._addClass( "ui-button-icon-only" );
			}
		} else if ( icon ) {

			// If we are updating the icon remove the old icon class
			this._removeClass( this.icon, null, this.options.icon );
		}

		// If we are updating the icon add the new icon class
		if ( icon ) {
			this._addClass( this.icon, null, value );
		}

		this._attachIcon( position );

		// If the icon is on top or bottom we need to add the ui-widget-icon-block class and remove
		// the iconSpace if there is one.
		if ( displayBlock ) {
			this._addClass( this.icon, null, "ui-widget-icon-block" );
			if ( this.iconSpace ) {
				this.iconSpace.remove();
			}
		} else {

			// Position is beginning or end so remove the ui-widget-icon-block class and add the
			// space if it does not exist
			if ( !this.iconSpace ) {
				this.iconSpace = $( "<span> </span>" );
				this._addClass( this.iconSpace, "ui-button-icon-space" );
			}
			this._removeClass( this.icon, null, "ui-wiget-icon-block" );
			this._attachIconSpace( position );
		}
	},

	_destroy: function() {
		this.element.removeAttr( "role" );

		if ( this.icon ) {
			this.icon.remove();
		}
		if ( this.iconSpace ) {
			this.iconSpace.remove();
		}
		if ( !this.hasTitle ) {
			this.element.removeAttr( "title" );
		}
	},

	_attachIconSpace: function( iconPosition ) {
		this.icon[ /^(?:end|bottom)/.test( iconPosition ) ? "before" : "after" ]( this.iconSpace );
	},

	_attachIcon: function( iconPosition ) {
		this.element[ /^(?:end|bottom)/.test( iconPosition ) ? "append" : "prepend" ]( this.icon );
	},

	_setOptions: function( options ) {
		var newShowLabel = options.showLabel === undefined ?
				this.options.showLabel :
				options.showLabel,
			newIcon = options.icon === undefined ? this.options.icon : options.icon;

		if ( !newShowLabel && !newIcon ) {
			options.showLabel = true;
		}
		this._super( options );
	},

	_setOption: function( key, value ) {
		if ( key === "icon" ) {
			if ( value ) {
				this._updateIcon( key, value );
			} else if ( this.icon ) {
				this.icon.remove();
				if ( this.iconSpace ) {
					this.iconSpace.remove();
				}
			}
		}

		if ( key === "iconPosition" ) {
			this._updateIcon( key, value );
		}

		// Make sure we can't end up with a button that has neither text nor icon
		if ( key === "showLabel" ) {
				this._toggleClass( "ui-button-icon-only", null, !value );
				this._updateTooltip();
		}

		if ( key === "label" ) {
			if ( this.isInput ) {
				this.element.val( value );
			} else {

				// If there is an icon, append it, else nothing then append the value
				// this avoids removal of the icon when setting label text
				this.element.html( value );
				if ( this.icon ) {
					this._attachIcon( this.options.iconPosition );
					this._attachIconSpace( this.options.iconPosition );
				}
			}
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this._toggleClass( null, "ui-state-disabled", value );
			this.element[ 0 ].disabled = value;
			if ( value ) {
				this.element.trigger( "blur" );
			}
		}
	},

	refresh: function() {

		// Make sure to only check disabled if its an element that supports this otherwise
		// check for the disabled class to determine state
		var isDisabled = this.element.is( "input, button" ) ?
			this.element[ 0 ].disabled : this.element.hasClass( "ui-button-disabled" );

		if ( isDisabled !== this.options.disabled ) {
			this._setOptions( { disabled: isDisabled } );
		}

		this._updateTooltip();
	}
} );

// DEPRECATED
if ( $.uiBackCompat !== false ) {

	// Text and Icons options
	$.widget( "ui.button", $.ui.button, {
		options: {
			text: true,
			icons: {
				primary: null,
				secondary: null
			}
		},

		_create: function() {
			if ( this.options.showLabel && !this.options.text ) {
				this.options.showLabel = this.options.text;
			}
			if ( !this.options.showLabel && this.options.text ) {
				this.options.text = this.options.showLabel;
			}
			if ( !this.options.icon && ( this.options.icons.primary ||
					this.options.icons.secondary ) ) {
				if ( this.options.icons.primary ) {
					this.options.icon = this.options.icons.primary;
				} else {
					this.options.icon = this.options.icons.secondary;
					this.options.iconPosition = "end";
				}
			} else if ( this.options.icon ) {
				this.options.icons.primary = this.options.icon;
			}
			this._super();
		},

		_setOption: function( key, value ) {
			if ( key === "text" ) {
				this._super( "showLabel", value );
				return;
			}
			if ( key === "showLabel" ) {
				this.options.text = value;
			}
			if ( key === "icon" ) {
				this.options.icons.primary = value;
			}
			if ( key === "icons" ) {
				if ( value.primary ) {
					this._super( "icon", value.primary );
					this._super( "iconPosition", "beginning" );
				} else if ( value.secondary ) {
					this._super( "icon", value.secondary );
					this._super( "iconPosition", "end" );
				}
			}
			this._superApply( arguments );
		}
	} );

	$.fn.button = ( function( orig ) {
		return function( options ) {
			var isMethodCall = typeof options === "string";
			var args = Array.prototype.slice.call( arguments, 1 );
			var returnValue = this;

			if ( isMethodCall ) {

				// If this is an empty collection, we need to have the instance method
				// return undefined instead of the jQuery instance
				if ( !this.length && options === "instance" ) {
					returnValue = undefined;
				} else {
					this.each( function() {
						var methodValue;
						var type = $( this ).attr( "type" );
						var name = type !== "checkbox" && type !== "radio" ?
							"button" :
							"checkboxradio";
						var instance = $.data( this, "ui-" + name );

						if ( options === "instance" ) {
							returnValue = instance;
							return false;
						}

						if ( !instance ) {
							return $.error( "cannot call methods on button" +
								" prior to initialization; " +
								"attempted to call method '" + options + "'" );
						}

						if ( typeof instance[ options ] !== "function" ||
							options.charAt( 0 ) === "_" ) {
							return $.error( "no such method '" + options + "' for button" +
								" widget instance" );
						}

						methodValue = instance[ options ].apply( instance, args );

						if ( methodValue !== instance && methodValue !== undefined ) {
							returnValue = methodValue && methodValue.jquery ?
								returnValue.pushStack( methodValue.get() ) :
								methodValue;
							return false;
						}
					} );
				}
			} else {

				// Allow multiple hashes to be passed on init
				if ( args.length ) {
					options = $.widget.extend.apply( null, [ options ].concat( args ) );
				}

				this.each( function() {
					var type = $( this ).attr( "type" );
					var name = type !== "checkbox" && type !== "radio" ? "button" : "checkboxradio";
					var instance = $.data( this, "ui-" + name );

					if ( instance ) {
						instance.option( options || {} );
						if ( instance._init ) {
							instance._init();
						}
					} else {
						if ( name === "button" ) {
							orig.call( $( this ), options );
							return;
						}

						$( this ).checkboxradio( $.extend( { icon: false }, options ) );
					}
				} );
			}

			return returnValue;
		};
	} )( $.fn.button );

	$.fn.buttonset = function() {
		if ( !$.ui.controlgroup ) {
			$.error( "Controlgroup widget missing" );
		}
		if ( arguments[ 0 ] === "option" && arguments[ 1 ] === "items" && arguments[ 2 ] ) {
			return this.controlgroup.apply( this,
				[ arguments[ 0 ], "items.button", arguments[ 2 ] ] );
		}
		if ( arguments[ 0 ] === "option" && arguments[ 1 ] === "items" ) {
			return this.controlgroup.apply( this, [ arguments[ 0 ], "items.button" ] );
		}
		if ( typeof arguments[ 0 ] === "object" && arguments[ 0 ].items ) {
			arguments[ 0 ].items = {
				button: arguments[ 0 ].items
			};
		}
		return this.controlgroup.apply( this, arguments );
	};
}

return $.ui.button;

} );


/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Controlgroup 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Controlgroup
//>>group: Widgets
//>>description: Visually groups form control widgets
//>>docs: http://api.jqueryui.com/controlgroup/
//>>demos: http://jqueryui.com/controlgroup/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/controlgroup.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
			__webpack_require__(0),
			__webpack_require__(17)
		], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

var controlgroupCornerRegex = /ui-corner-([a-z]){2,6}/g;

return $.widget( "ui.controlgroup", {
	version: "1.13.2",
	defaultElement: "<div>",
	options: {
		direction: "horizontal",
		disabled: null,
		onlyVisible: true,
		items: {
			"button": "input[type=button], input[type=submit], input[type=reset], button, a",
			"controlgroupLabel": ".ui-controlgroup-label",
			"checkboxradio": "input[type='checkbox'], input[type='radio']",
			"selectmenu": "select",
			"spinner": ".ui-spinner-input"
		}
	},

	_create: function() {
		this._enhance();
	},

	// To support the enhanced option in jQuery Mobile, we isolate DOM manipulation
	_enhance: function() {
		this.element.attr( "role", "toolbar" );
		this.refresh();
	},

	_destroy: function() {
		this._callChildMethod( "destroy" );
		this.childWidgets.removeData( "ui-controlgroup-data" );
		this.element.removeAttr( "role" );
		if ( this.options.items.controlgroupLabel ) {
			this.element
				.find( this.options.items.controlgroupLabel )
				.find( ".ui-controlgroup-label-contents" )
				.contents().unwrap();
		}
	},

	_initWidgets: function() {
		var that = this,
			childWidgets = [];

		// First we iterate over each of the items options
		$.each( this.options.items, function( widget, selector ) {
			var labels;
			var options = {};

			// Make sure the widget has a selector set
			if ( !selector ) {
				return;
			}

			if ( widget === "controlgroupLabel" ) {
				labels = that.element.find( selector );
				labels.each( function() {
					var element = $( this );

					if ( element.children( ".ui-controlgroup-label-contents" ).length ) {
						return;
					}
					element.contents()
						.wrapAll( "<span class='ui-controlgroup-label-contents'></span>" );
				} );
				that._addClass( labels, null, "ui-widget ui-widget-content ui-state-default" );
				childWidgets = childWidgets.concat( labels.get() );
				return;
			}

			// Make sure the widget actually exists
			if ( !$.fn[ widget ] ) {
				return;
			}

			// We assume everything is in the middle to start because we can't determine
			// first / last elements until all enhancments are done.
			if ( that[ "_" + widget + "Options" ] ) {
				options = that[ "_" + widget + "Options" ]( "middle" );
			} else {
				options = { classes: {} };
			}

			// Find instances of this widget inside controlgroup and init them
			that.element
				.find( selector )
				.each( function() {
					var element = $( this );
					var instance = element[ widget ]( "instance" );

					// We need to clone the default options for this type of widget to avoid
					// polluting the variable options which has a wider scope than a single widget.
					var instanceOptions = $.widget.extend( {}, options );

					// If the button is the child of a spinner ignore it
					// TODO: Find a more generic solution
					if ( widget === "button" && element.parent( ".ui-spinner" ).length ) {
						return;
					}

					// Create the widget if it doesn't exist
					if ( !instance ) {
						instance = element[ widget ]()[ widget ]( "instance" );
					}
					if ( instance ) {
						instanceOptions.classes =
							that._resolveClassesValues( instanceOptions.classes, instance );
					}
					element[ widget ]( instanceOptions );

					// Store an instance of the controlgroup to be able to reference
					// from the outermost element for changing options and refresh
					var widgetElement = element[ widget ]( "widget" );
					$.data( widgetElement[ 0 ], "ui-controlgroup-data",
						instance ? instance : element[ widget ]( "instance" ) );

					childWidgets.push( widgetElement[ 0 ] );
				} );
		} );

		this.childWidgets = $( $.uniqueSort( childWidgets ) );
		this._addClass( this.childWidgets, "ui-controlgroup-item" );
	},

	_callChildMethod: function( method ) {
		this.childWidgets.each( function() {
			var element = $( this ),
				data = element.data( "ui-controlgroup-data" );
			if ( data && data[ method ] ) {
				data[ method ]();
			}
		} );
	},

	_updateCornerClass: function( element, position ) {
		var remove = "ui-corner-top ui-corner-bottom ui-corner-left ui-corner-right ui-corner-all";
		var add = this._buildSimpleOptions( position, "label" ).classes.label;

		this._removeClass( element, null, remove );
		this._addClass( element, null, add );
	},

	_buildSimpleOptions: function( position, key ) {
		var direction = this.options.direction === "vertical";
		var result = {
			classes: {}
		};
		result.classes[ key ] = {
			"middle": "",
			"first": "ui-corner-" + ( direction ? "top" : "left" ),
			"last": "ui-corner-" + ( direction ? "bottom" : "right" ),
			"only": "ui-corner-all"
		}[ position ];

		return result;
	},

	_spinnerOptions: function( position ) {
		var options = this._buildSimpleOptions( position, "ui-spinner" );

		options.classes[ "ui-spinner-up" ] = "";
		options.classes[ "ui-spinner-down" ] = "";

		return options;
	},

	_buttonOptions: function( position ) {
		return this._buildSimpleOptions( position, "ui-button" );
	},

	_checkboxradioOptions: function( position ) {
		return this._buildSimpleOptions( position, "ui-checkboxradio-label" );
	},

	_selectmenuOptions: function( position ) {
		var direction = this.options.direction === "vertical";
		return {
			width: direction ? "auto" : false,
			classes: {
				middle: {
					"ui-selectmenu-button-open": "",
					"ui-selectmenu-button-closed": ""
				},
				first: {
					"ui-selectmenu-button-open": "ui-corner-" + ( direction ? "top" : "tl" ),
					"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "top" : "left" )
				},
				last: {
					"ui-selectmenu-button-open": direction ? "" : "ui-corner-tr",
					"ui-selectmenu-button-closed": "ui-corner-" + ( direction ? "bottom" : "right" )
				},
				only: {
					"ui-selectmenu-button-open": "ui-corner-top",
					"ui-selectmenu-button-closed": "ui-corner-all"
				}

			}[ position ]
		};
	},

	_resolveClassesValues: function( classes, instance ) {
		var result = {};
		$.each( classes, function( key ) {
			var current = instance.options.classes[ key ] || "";
			current = String.prototype.trim.call( current.replace( controlgroupCornerRegex, "" ) );
			result[ key ] = ( current + " " + classes[ key ] ).replace( /\s+/g, " " );
		} );
		return result;
	},

	_setOption: function( key, value ) {
		if ( key === "direction" ) {
			this._removeClass( "ui-controlgroup-" + this.options.direction );
		}

		this._super( key, value );
		if ( key === "disabled" ) {
			this._callChildMethod( value ? "disable" : "enable" );
			return;
		}

		this.refresh();
	},

	refresh: function() {
		var children,
			that = this;

		this._addClass( "ui-controlgroup ui-controlgroup-" + this.options.direction );

		if ( this.options.direction === "horizontal" ) {
			this._addClass( null, "ui-helper-clearfix" );
		}
		this._initWidgets();

		children = this.childWidgets;

		// We filter here because we need to track all childWidgets not just the visible ones
		if ( this.options.onlyVisible ) {
			children = children.filter( ":visible" );
		}

		if ( children.length ) {

			// We do this last because we need to make sure all enhancment is done
			// before determining first and last
			$.each( [ "first", "last" ], function( index, value ) {
				var instance = children[ value ]().data( "ui-controlgroup-data" );

				if ( instance && that[ "_" + instance.widgetName + "Options" ] ) {
					var options = that[ "_" + instance.widgetName + "Options" ](
						children.length === 1 ? "only" : value
					);
					options.classes = that._resolveClassesValues( options.classes, instance );
					instance.element[ instance.widgetName ]( options );
				} else {
					that._updateCornerClass( children[ value ](), value );
				}
			} );

			// Finally call the refresh method on each of the child widgets.
			this._callChildMethod( "refresh" );
		}
	}
} );
} );


/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Checkboxradio 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Checkboxradio
//>>group: Widgets
//>>description: Enhances a form with multiple themeable checkboxes or radio buttons.
//>>docs: http://api.jqueryui.com/checkboxradio/
//>>demos: http://jqueryui.com/checkboxradio/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/button.css
//>>css.structure: ../../themes/base/checkboxradio.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
			__webpack_require__(0),
			__webpack_require__(193),
			__webpack_require__(195),
			__webpack_require__(17)
		], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.checkboxradio", [ $.ui.formResetMixin, {
	version: "1.13.2",
	options: {
		disabled: null,
		label: null,
		icon: true,
		classes: {
			"ui-checkboxradio-label": "ui-corner-all",
			"ui-checkboxradio-icon": "ui-corner-all"
		}
	},

	_getCreateOptions: function() {
		var disabled, labels, labelContents;
		var options = this._super() || {};

		// We read the type here, because it makes more sense to throw a element type error first,
		// rather then the error for lack of a label. Often if its the wrong type, it
		// won't have a label (e.g. calling on a div, btn, etc)
		this._readType();

		labels = this.element.labels();

		// If there are multiple labels, use the last one
		this.label = $( labels[ labels.length - 1 ] );
		if ( !this.label.length ) {
			$.error( "No label found for checkboxradio widget" );
		}

		this.originalLabel = "";

		// We need to get the label text but this may also need to make sure it does not contain the
		// input itself.
		// The label contents could be text, html, or a mix. We wrap all elements
		// and read the wrapper's `innerHTML` to get a string representation of
		// the label, without the input as part of it.
		labelContents = this.label.contents().not( this.element[ 0 ] );

		if ( labelContents.length ) {
			this.originalLabel += labelContents
				.clone()
				.wrapAll( "<div></div>" )
				.parent()
				.html();
		}

		// Set the label option if we found label text
		if ( this.originalLabel ) {
			options.label = this.originalLabel;
		}

		disabled = this.element[ 0 ].disabled;
		if ( disabled != null ) {
			options.disabled = disabled;
		}
		return options;
	},

	_create: function() {
		var checked = this.element[ 0 ].checked;

		this._bindFormResetHandler();

		if ( this.options.disabled == null ) {
			this.options.disabled = this.element[ 0 ].disabled;
		}

		this._setOption( "disabled", this.options.disabled );
		this._addClass( "ui-checkboxradio", "ui-helper-hidden-accessible" );
		this._addClass( this.label, "ui-checkboxradio-label", "ui-button ui-widget" );

		if ( this.type === "radio" ) {
			this._addClass( this.label, "ui-checkboxradio-radio-label" );
		}

		if ( this.options.label && this.options.label !== this.originalLabel ) {
			this._updateLabel();
		} else if ( this.originalLabel ) {
			this.options.label = this.originalLabel;
		}

		this._enhance();

		if ( checked ) {
			this._addClass( this.label, "ui-checkboxradio-checked", "ui-state-active" );
		}

		this._on( {
			change: "_toggleClasses",
			focus: function() {
				this._addClass( this.label, null, "ui-state-focus ui-visual-focus" );
			},
			blur: function() {
				this._removeClass( this.label, null, "ui-state-focus ui-visual-focus" );
			}
		} );
	},

	_readType: function() {
		var nodeName = this.element[ 0 ].nodeName.toLowerCase();
		this.type = this.element[ 0 ].type;
		if ( nodeName !== "input" || !/radio|checkbox/.test( this.type ) ) {
			$.error( "Can't create checkboxradio on element.nodeName=" + nodeName +
				" and element.type=" + this.type );
		}
	},

	// Support jQuery Mobile enhanced option
	_enhance: function() {
		this._updateIcon( this.element[ 0 ].checked );
	},

	widget: function() {
		return this.label;
	},

	_getRadioGroup: function() {
		var group;
		var name = this.element[ 0 ].name;
		var nameSelector = "input[name='" + $.escapeSelector( name ) + "']";

		if ( !name ) {
			return $( [] );
		}

		if ( this.form.length ) {
			group = $( this.form[ 0 ].elements ).filter( nameSelector );
		} else {

			// Not inside a form, check all inputs that also are not inside a form
			group = $( nameSelector ).filter( function() {
				return $( this )._form().length === 0;
			} );
		}

		return group.not( this.element );
	},

	_toggleClasses: function() {
		var checked = this.element[ 0 ].checked;
		this._toggleClass( this.label, "ui-checkboxradio-checked", "ui-state-active", checked );

		if ( this.options.icon && this.type === "checkbox" ) {
			this._toggleClass( this.icon, null, "ui-icon-check ui-state-checked", checked )
				._toggleClass( this.icon, null, "ui-icon-blank", !checked );
		}

		if ( this.type === "radio" ) {
			this._getRadioGroup()
				.each( function() {
					var instance = $( this ).checkboxradio( "instance" );

					if ( instance ) {
						instance._removeClass( instance.label,
							"ui-checkboxradio-checked", "ui-state-active" );
					}
				} );
		}
	},

	_destroy: function() {
		this._unbindFormResetHandler();

		if ( this.icon ) {
			this.icon.remove();
			this.iconSpace.remove();
		}
	},

	_setOption: function( key, value ) {

		// We don't allow the value to be set to nothing
		if ( key === "label" && !value ) {
			return;
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this._toggleClass( this.label, null, "ui-state-disabled", value );
			this.element[ 0 ].disabled = value;

			// Don't refresh when setting disabled
			return;
		}
		this.refresh();
	},

	_updateIcon: function( checked ) {
		var toAdd = "ui-icon ui-icon-background ";

		if ( this.options.icon ) {
			if ( !this.icon ) {
				this.icon = $( "<span>" );
				this.iconSpace = $( "<span> </span>" );
				this._addClass( this.iconSpace, "ui-checkboxradio-icon-space" );
			}

			if ( this.type === "checkbox" ) {
				toAdd += checked ? "ui-icon-check ui-state-checked" : "ui-icon-blank";
				this._removeClass( this.icon, null, checked ? "ui-icon-blank" : "ui-icon-check" );
			} else {
				toAdd += "ui-icon-blank";
			}
			this._addClass( this.icon, "ui-checkboxradio-icon", toAdd );
			if ( !checked ) {
				this._removeClass( this.icon, null, "ui-icon-check ui-state-checked" );
			}
			this.icon.prependTo( this.label ).after( this.iconSpace );
		} else if ( this.icon !== undefined ) {
			this.icon.remove();
			this.iconSpace.remove();
			delete this.icon;
		}
	},

	_updateLabel: function() {

		// Remove the contents of the label ( minus the icon, icon space, and input )
		var contents = this.label.contents().not( this.element[ 0 ] );
		if ( this.icon ) {
			contents = contents.not( this.icon[ 0 ] );
		}
		if ( this.iconSpace ) {
			contents = contents.not( this.iconSpace[ 0 ] );
		}
		contents.remove();

		this.label.append( this.options.label );
	},

	refresh: function() {
		var checked = this.element[ 0 ].checked,
			isDisabled = this.element[ 0 ].disabled;

		this._updateIcon( checked );
		this._toggleClass( this.label, "ui-checkboxradio-checked", "ui-state-active", checked );
		if ( this.options.label !== null ) {
			this._updateLabel();
		}

		if ( isDisabled !== this.options.disabled ) {
			this._setOptions( { "disabled": isDisabled } );
		}
	}

} ] );

return $.ui.checkboxradio;

} );


/***/ }),
/* 193 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Form Reset Mixin 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Form Reset Mixin
//>>group: Core
//>>description: Refresh input widgets when their form is reset
//>>docs: http://api.jqueryui.com/form-reset-mixin/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
			__webpack_require__(0),
			__webpack_require__(194),
			__webpack_require__(3)
		], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.ui.formResetMixin = {
	_formResetHandler: function() {
		var form = $( this );

		// Wait for the form reset to actually happen before refreshing
		setTimeout( function() {
			var instances = form.data( "ui-form-reset-instances" );
			$.each( instances, function() {
				this.refresh();
			} );
		} );
	},

	_bindFormResetHandler: function() {
		this.form = this.element._form();
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" ) || [];
		if ( !instances.length ) {

			// We don't use _on() here because we use a single event handler per form
			this.form.on( "reset.ui-form-reset", this._formResetHandler );
		}
		instances.push( this );
		this.form.data( "ui-form-reset-instances", instances );
	},

	_unbindFormResetHandler: function() {
		if ( !this.form.length ) {
			return;
		}

		var instances = this.form.data( "ui-form-reset-instances" );
		instances.splice( $.inArray( this, instances ), 1 );
		if ( instances.length ) {
			this.form.data( "ui-form-reset-instances", instances );
		} else {
			this.form
				.removeData( "ui-form-reset-instances" )
				.off( "reset.ui-form-reset" );
		}
	}
};

} );


/***/ }),
/* 194 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

// Support: IE8 Only
// IE8 does not support the form attribute and when it is supplied. It overwrites the form prop
// with a string, so we need to find the proper form.
return $.fn._form = function() {
	return typeof this[ 0 ].form === "string" ? this.closest( "form" ) : $( this[ 0 ].form );
};

} );


/***/ }),
/* 195 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Labels 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: labels
//>>group: Core
//>>description: Find all the labels associated with a given input
//>>docs: http://api.jqueryui.com/labels/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.fn.labels = function() {
	var ancestor, selector, id, labels, ancestors;

	if ( !this.length ) {
		return this.pushStack( [] );
	}

	// Check control.labels first
	if ( this[ 0 ].labels && this[ 0 ].labels.length ) {
		return this.pushStack( this[ 0 ].labels );
	}

	// Support: IE <= 11, FF <= 37, Android <= 2.3 only
	// Above browsers do not support control.labels. Everything below is to support them
	// as well as document fragments. control.labels does not work on document fragments
	labels = this.eq( 0 ).parents( "label" );

	// Look for the label based on the id
	id = this.attr( "id" );
	if ( id ) {

		// We don't search against the document in case the element
		// is disconnected from the DOM
		ancestor = this.eq( 0 ).parents().last();

		// Get a full set of top level ancestors
		ancestors = ancestor.add( ancestor.length ? ancestor.siblings() : this.siblings() );

		// Create a selector for the label based on the id
		selector = "label[for='" + $.escapeSelector( id ) + "']";

		labels = labels.add( ancestors.find( selector ).addBack( selector ) );

	}

	// Return whatever we have found for labels
	return this.pushStack( labels );
};

} );


/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Draggable 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Draggable
//>>group: Interactions
//>>description: Enables dragging functionality for any element.
//>>docs: http://api.jqueryui.com/draggable/
//>>demos: http://jqueryui.com/draggable/
//>>css.structure: ../../themes/base/draggable.css

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
			__webpack_require__(0),
			__webpack_require__(51),
			__webpack_require__(198),
			__webpack_require__(104),
			__webpack_require__(105),
			__webpack_require__(106),
			__webpack_require__(199),
			__webpack_require__(3),
			__webpack_require__(17)
		], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.draggable", $.ui.mouse, {
	version: "1.13.2",
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false,

		// Callbacks
		drag: null,
		start: null,
		stop: null
	},
	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if ( this.options.addClasses ) {
			this._addClass( "ui-draggable" );
		}
		this._setHandleClassName();

		this._mouseInit();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "handle" ) {
			this._removeHandleClassName();
			this._setHandleClassName();
		}
	},

	_destroy: function() {
		if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
			this.destroyOnClear = true;
			return;
		}
		this._removeHandleClassName();
		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var o = this.options;

		// Among others, prevent a drag on a resizable-handle
		if ( this.helper || o.disabled ||
				$( event.target ).closest( ".ui-resizable-handle" ).length > 0 ) {
			return false;
		}

		//Quit if we're not on a valid handle
		this.handle = this._getHandle( event );
		if ( !this.handle ) {
			return false;
		}

		this._blurActiveElement( event );

		this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );

		return true;

	},

	_blockFrames: function( selector ) {
		this.iframeBlocks = this.document.find( selector ).map( function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( "position", "absolute" )
				.appendTo( iframe.parent() )
				.outerWidth( iframe.outerWidth() )
				.outerHeight( iframe.outerHeight() )
				.offset( iframe.offset() )[ 0 ];
		} );
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_blurActiveElement: function( event ) {
		var activeElement = $.ui.safeActiveElement( this.document[ 0 ] ),
			target = $( event.target );

		// Don't blur if the event occurred on an element that is within
		// the currently focused element
		// See #10527, #12472
		if ( target.closest( activeElement ).length ) {
			return;
		}

		// Blur any element that currently has focus, see #4261
		$.ui.safeBlur( activeElement );
	},

	_mouseStart: function( event ) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper( event );

		this._addClass( this.helper, "ui-draggable-dragging" );

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.current = this;
		}

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css( "position" );
		this.scrollParent = this.helper.scrollParent( true );
		this.offsetParent = this.helper.offsetParent();
		this.hasFixedAncestor = this.helper.parents().filter( function() {
				return $( this ).css( "position" ) === "fixed";
			} ).length > 0;

		//The element's absolute position on the page minus margins
		this.positionAbs = this.element.offset();
		this._refreshOffsets( event );

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition( event, false );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		if ( o.cursorAt ) {
			this._adjustOffsetFromHelper( o.cursorAt );
		}

		//Set a containment if given in the options
		this._setContainment();

		//Trigger event + callbacks
		if ( this._trigger( "start", event ) === false ) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ( $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( this, event );
		}

		// Execute the drag once - this causes the helper not to be visible before getting its
		// correct position
		this._mouseDrag( event, true );

		// If the ddmanager is used for droppables, inform the manager that dragging has started
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStart( this, event );
		}

		return true;
	},

	_refreshOffsets: function( event ) {
		this.offset = {
			top: this.positionAbs.top - this.margins.top,
			left: this.positionAbs.left - this.margins.left,
			scroll: false,
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset()
		};

		this.offset.click = {
			left: event.pageX - this.offset.left,
			top: event.pageY - this.offset.top
		};
	},

	_mouseDrag: function( event, noPropagation ) {

		// reset any necessary cached properties (see #5009)
		if ( this.hasFixedAncestor ) {
			this.offset.parent = this._getParentOffset();
		}

		//Compute the helpers position
		this.position = this._generatePosition( event, true );
		this.positionAbs = this._convertPositionTo( "absolute" );

		//Call plugins and callbacks and use the resulting position if something is returned
		if ( !noPropagation ) {
			var ui = this._uiHash();
			if ( this._trigger( "drag", event, ui ) === false ) {
				this._mouseUp( new $.Event( "mouseup", event ) );
				return false;
			}
			this.position = ui.position;
		}

		this.helper[ 0 ].style.left = this.position.left + "px";
		this.helper[ 0 ].style.top = this.position.top + "px";

		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.drag( this, event );
		}

		return false;
	},

	_mouseStop: function( event ) {

		//If we are using droppables, inform the manager about the drop
		var that = this,
			dropped = false;
		if ( $.ui.ddmanager && !this.options.dropBehaviour ) {
			dropped = $.ui.ddmanager.drop( this, event );
		}

		//if a drop comes from outside (a sortable)
		if ( this.dropped ) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if ( ( this.options.revert === "invalid" && !dropped ) ||
				( this.options.revert === "valid" && dropped ) ||
				this.options.revert === true || ( typeof this.options.revert === "function" &&
				this.options.revert.call( this.element, dropped ) )
		) {
			$( this.helper ).animate(
				this.originalPosition,
				parseInt( this.options.revertDuration, 10 ),
				function() {
					if ( that._trigger( "stop", event ) !== false ) {
						that._clear();
					}
				}
			);
		} else {
			if ( this._trigger( "stop", event ) !== false ) {
				this._clear();
			}
		}

		return false;
	},

	_mouseUp: function( event ) {
		this._unblockFrames();

		// If the ddmanager is used for droppables, inform the manager that dragging has stopped
		// (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStop( this, event );
		}

		// Only need to focus if the event occurred on the draggable itself, see #10527
		if ( this.handleElement.is( event.target ) ) {

			// The interaction is over; whether or not the click resulted in a drag,
			// focus the element
			this.element.trigger( "focus" );
		}

		return $.ui.mouse.prototype._mouseUp.call( this, event );
	},

	cancel: function() {

		if ( this.helper.is( ".ui-draggable-dragging" ) ) {
			this._mouseUp( new $.Event( "mouseup", { target: this.element[ 0 ] } ) );
		} else {
			this._clear();
		}

		return this;

	},

	_getHandle: function( event ) {
		return this.options.handle ?
			!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
			true;
	},

	_setHandleClassName: function() {
		this.handleElement = this.options.handle ?
			this.element.find( this.options.handle ) : this.element;
		this._addClass( this.handleElement, "ui-draggable-handle" );
	},

	_removeHandleClassName: function() {
		this._removeClass( this.handleElement, "ui-draggable-handle" );
	},

	_createHelper: function( event ) {

		var o = this.options,
			helperIsFunction = typeof o.helper === "function",
			helper = helperIsFunction ?
				$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
				( o.helper === "clone" ?
					this.element.clone().removeAttr( "id" ) :
					this.element );

		if ( !helper.parents( "body" ).length ) {
			helper.appendTo( ( o.appendTo === "parent" ?
				this.element[ 0 ].parentNode :
				o.appendTo ) );
		}

		// Http://bugs.jqueryui.com/ticket/9446
		// a helper function can return the original element
		// which wouldn't have been set to relative in _create
		if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
			this._setPositionRelative();
		}

		if ( helper[ 0 ] !== this.element[ 0 ] &&
				!( /(fixed|absolute)/ ).test( helper.css( "position" ) ) ) {
			helper.css( "position", "absolute" );
		}

		return helper;

	},

	_setPositionRelative: function() {
		if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
			this.element[ 0 ].style.position = "relative";
		}
	},

	_adjustOffsetFromHelper: function( obj ) {
		if ( typeof obj === "string" ) {
			obj = obj.split( " " );
		}
		if ( Array.isArray( obj ) ) {
			obj = { left: +obj[ 0 ], top: +obj[ 1 ] || 0 };
		}
		if ( "left" in obj ) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ( "right" in obj ) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ( "top" in obj ) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ( "bottom" in obj ) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_isRootNode: function( element ) {
		return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		var po = this.offsetParent.offset(),
			document = this.document[ 0 ];

		// This is a special case where we need to modify a offset calculated on start, since the
		// following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the
		// next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't
		// the document, which means that the scroll is included in the initial calculation of the
		// offset of the parent, and never recalculated upon drag
		if ( this.cssPosition === "absolute" && this.scrollParent[ 0 ] !== document &&
				$.contains( this.scrollParent[ 0 ], this.offsetParent[ 0 ] ) ) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + ( parseInt( this.offsetParent.css( "borderTopWidth" ), 10 ) || 0 ),
			left: po.left + ( parseInt( this.offsetParent.css( "borderLeftWidth" ), 10 ) || 0 )
		};

	},

	_getRelativeOffset: function() {
		if ( this.cssPosition !== "relative" ) {
			return { top: 0, left: 0 };
		}

		var p = this.element.position(),
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: p.top - ( parseInt( this.helper.css( "top" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
			left: p.left - ( parseInt( this.helper.css( "left" ), 10 ) || 0 ) +
				( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
		};

	},

	_cacheMargins: function() {
		this.margins = {
			left: ( parseInt( this.element.css( "marginLeft" ), 10 ) || 0 ),
			top: ( parseInt( this.element.css( "marginTop" ), 10 ) || 0 ),
			right: ( parseInt( this.element.css( "marginRight" ), 10 ) || 0 ),
			bottom: ( parseInt( this.element.css( "marginBottom" ), 10 ) || 0 )
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var isUserScrollable, c, ce,
			o = this.options,
			document = this.document[ 0 ];

		this.relativeContainer = null;

		if ( !o.containment ) {
			this.containment = null;
			return;
		}

		if ( o.containment === "window" ) {
			this.containment = [
				$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
				$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
				$( window ).scrollLeft() + $( window ).width() -
					this.helperProportions.width - this.margins.left,
				$( window ).scrollTop() +
					( $( window ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment === "document" ) {
			this.containment = [
				0,
				0,
				$( document ).width() - this.helperProportions.width - this.margins.left,
				( $( document ).height() || document.body.parentNode.scrollHeight ) -
					this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment.constructor === Array ) {
			this.containment = o.containment;
			return;
		}

		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}

		c = $( o.containment );
		ce = c[ 0 ];

		if ( !ce ) {
			return;
		}

		isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );

		this.containment = [
			( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
			( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) +
				( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
			( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
				( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
				this.helperProportions.width -
				this.margins.left -
				this.margins.right,
			( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
				( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
				this.helperProportions.height -
				this.margins.top -
				this.margins.bottom
		];
		this.relativeContainer = c;
	},

	_convertPositionTo: function( d, pos ) {

		if ( !pos ) {
			pos = this.position;
		}

		var mod = d === "absolute" ? 1 : -1,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: (

				// The absolute mouse position
				pos.top	+

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top * mod -
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod )
			),
			left: (

				// The absolute mouse position
				pos.left +

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left * mod +

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left * mod	-
				( ( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod )
			)
		};

	},

	_generatePosition: function( event, constrainPosition ) {

		var containment, co, top, left,
			o = this.options,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
			pageX = event.pageX,
			pageY = event.pageY;

		// Cache the scroll
		if ( !scrollIsRootNode || !this.offset.scroll ) {
			this.offset.scroll = {
				top: this.scrollParent.scrollTop(),
				left: this.scrollParent.scrollLeft()
			};
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		// If we are not dragging yet, we won't check for options
		if ( constrainPosition ) {
			if ( this.containment ) {
				if ( this.relativeContainer ) {
					co = this.relativeContainer.offset();
					containment = [
						this.containment[ 0 ] + co.left,
						this.containment[ 1 ] + co.top,
						this.containment[ 2 ] + co.left,
						this.containment[ 3 ] + co.top
					];
				} else {
					containment = this.containment;
				}

				if ( event.pageX - this.offset.click.left < containment[ 0 ] ) {
					pageX = containment[ 0 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top < containment[ 1 ] ) {
					pageY = containment[ 1 ] + this.offset.click.top;
				}
				if ( event.pageX - this.offset.click.left > containment[ 2 ] ) {
					pageX = containment[ 2 ] + this.offset.click.left;
				}
				if ( event.pageY - this.offset.click.top > containment[ 3 ] ) {
					pageY = containment[ 3 ] + this.offset.click.top;
				}
			}

			if ( o.grid ) {

				//Check for grid elements set to 0 to prevent divide by 0 error causing invalid
				// argument errors in IE (see ticket #6950)
				top = o.grid[ 1 ] ? this.originalPageY + Math.round( ( pageY -
					this.originalPageY ) / o.grid[ 1 ] ) * o.grid[ 1 ] : this.originalPageY;
				pageY = containment ? ( ( top - this.offset.click.top >= containment[ 1 ] ||
					top - this.offset.click.top > containment[ 3 ] ) ?
						top :
						( ( top - this.offset.click.top >= containment[ 1 ] ) ?
							top - o.grid[ 1 ] : top + o.grid[ 1 ] ) ) : top;

				left = o.grid[ 0 ] ? this.originalPageX +
					Math.round( ( pageX - this.originalPageX ) / o.grid[ 0 ] ) * o.grid[ 0 ] :
					this.originalPageX;
				pageX = containment ? ( ( left - this.offset.click.left >= containment[ 0 ] ||
					left - this.offset.click.left > containment[ 2 ] ) ?
						left :
						( ( left - this.offset.click.left >= containment[ 0 ] ) ?
							left - o.grid[ 0 ] : left + o.grid[ 0 ] ) ) : left;
			}

			if ( o.axis === "y" ) {
				pageX = this.originalPageX;
			}

			if ( o.axis === "x" ) {
				pageY = this.originalPageY;
			}
		}

		return {
			top: (

				// The absolute mouse position
				pageY -

				// Click offset (relative to the element)
				this.offset.click.top -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.top -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.top +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.top :
					( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
			),
			left: (

				// The absolute mouse position
				pageX -

				// Click offset (relative to the element)
				this.offset.click.left -

				// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.relative.left -

				// The offsetParent's offset without borders (offset + border)
				this.offset.parent.left +
				( this.cssPosition === "fixed" ?
					-this.offset.scroll.left :
					( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
			)
		};

	},

	_clear: function() {
		this._removeClass( this.helper, "ui-draggable-dragging" );
		if ( this.helper[ 0 ] !== this.element[ 0 ] && !this.cancelHelperRemoval ) {
			this.helper.remove();
		}
		this.helper = null;
		this.cancelHelperRemoval = false;
		if ( this.destroyOnClear ) {
			this.destroy();
		}
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function( type, event, ui ) {
		ui = ui || this._uiHash();
		$.ui.plugin.call( this, type, [ event, ui, this ], true );

		// Absolute position and offset (see #6884 ) have to be recalculated after plugins
		if ( /^(drag|start|stop)/.test( type ) ) {
			this.positionAbs = this._convertPositionTo( "absolute" );
			ui.offset = this.positionAbs;
		}
		return $.Widget.prototype._trigger.call( this, type, event, ui );
	},

	plugins: {},

	_uiHash: function() {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

} );

$.ui.plugin.add( "draggable", "connectToSortable", {
	start: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.sortables = [];
		$( draggable.options.connectToSortable ).each( function() {
			var sortable = $( this ).sortable( "instance" );

			if ( sortable && !sortable.options.disabled ) {
				draggable.sortables.push( sortable );

				// RefreshPositions is called at drag start to refresh the containerCache
				// which is used in drag. This ensures it's initialized and synchronized
				// with any changes that might have happened on the page since initialization.
				sortable.refreshPositions();
				sortable._trigger( "activate", event, uiSortable );
			}
		} );
	},
	stop: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		} );

		draggable.cancelHelperRemoval = false;

		$.each( draggable.sortables, function() {
			var sortable = this;

			if ( sortable.isOver ) {
				sortable.isOver = 0;

				// Allow this sortable to handle removing the helper
				draggable.cancelHelperRemoval = true;
				sortable.cancelHelperRemoval = false;

				// Use _storedCSS To restore properties in the sortable,
				// as this also handles revert (#9675) since the draggable
				// may have modified them in unexpected ways (#8809)
				sortable._storedCSS = {
					position: sortable.placeholder.css( "position" ),
					top: sortable.placeholder.css( "top" ),
					left: sortable.placeholder.css( "left" )
				};

				sortable._mouseStop( event );

				// Once drag has ended, the sortable should return to using
				// its original helper, not the shared helper from draggable
				sortable.options.helper = sortable.options._helper;
			} else {

				// Prevent this Sortable from removing the helper.
				// However, don't set the draggable to remove the helper
				// either as another connected Sortable may yet handle the removal.
				sortable.cancelHelperRemoval = true;

				sortable._trigger( "deactivate", event, uiSortable );
			}
		} );
	},
	drag: function( event, ui, draggable ) {
		$.each( draggable.sortables, function() {
			var innermostIntersecting = false,
				sortable = this;

			// Copy over variables that sortable's _intersectsWith uses
			sortable.positionAbs = draggable.positionAbs;
			sortable.helperProportions = draggable.helperProportions;
			sortable.offset.click = draggable.offset.click;

			if ( sortable._intersectsWith( sortable.containerCache ) ) {
				innermostIntersecting = true;

				$.each( draggable.sortables, function() {

					// Copy over variables that sortable's _intersectsWith uses
					this.positionAbs = draggable.positionAbs;
					this.helperProportions = draggable.helperProportions;
					this.offset.click = draggable.offset.click;

					if ( this !== sortable &&
							this._intersectsWith( this.containerCache ) &&
							$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
						innermostIntersecting = false;
					}

					return innermostIntersecting;
				} );
			}

			if ( innermostIntersecting ) {

				// If it intersects, we use a little isOver variable and set it once,
				// so that the move-in stuff gets fired only once.
				if ( !sortable.isOver ) {
					sortable.isOver = 1;

					// Store draggable's parent in case we need to reappend to it later.
					draggable._parent = ui.helper.parent();

					sortable.currentItem = ui.helper
						.appendTo( sortable.element )
						.data( "ui-sortable-item", true );

					// Store helper option to later restore it
					sortable.options._helper = sortable.options.helper;

					sortable.options.helper = function() {
						return ui.helper[ 0 ];
					};

					// Fire the start events of the sortable with our passed browser event,
					// and our own helper (so it doesn't create a new one)
					event.target = sortable.currentItem[ 0 ];
					sortable._mouseCapture( event, true );
					sortable._mouseStart( event, true, true );

					// Because the browser event is way off the new appended portlet,
					// modify necessary variables to reflect the changes
					sortable.offset.click.top = draggable.offset.click.top;
					sortable.offset.click.left = draggable.offset.click.left;
					sortable.offset.parent.left -= draggable.offset.parent.left -
						sortable.offset.parent.left;
					sortable.offset.parent.top -= draggable.offset.parent.top -
						sortable.offset.parent.top;

					draggable._trigger( "toSortable", event );

					// Inform draggable that the helper is in a valid drop zone,
					// used solely in the revert option to handle "valid/invalid".
					draggable.dropped = sortable.element;

					// Need to refreshPositions of all sortables in the case that
					// adding to one sortable changes the location of the other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );

					// Hack so receive/update callbacks work (mostly)
					draggable.currentItem = draggable.element;
					sortable.fromOutside = draggable;
				}

				if ( sortable.currentItem ) {
					sortable._mouseDrag( event );

					// Copy the sortable's position because the draggable's can potentially reflect
					// a relative position, while sortable is always absolute, which the dragged
					// element has now become. (#8809)
					ui.position = sortable.position;
				}
			} else {

				// If it doesn't intersect with the sortable, and it intersected before,
				// we fake the drag stop of the sortable, but make sure it doesn't remove
				// the helper by using cancelHelperRemoval.
				if ( sortable.isOver ) {

					sortable.isOver = 0;
					sortable.cancelHelperRemoval = true;

					// Calling sortable's mouseStop would trigger a revert,
					// so revert must be temporarily false until after mouseStop is called.
					sortable.options._revert = sortable.options.revert;
					sortable.options.revert = false;

					sortable._trigger( "out", event, sortable._uiHash( sortable ) );
					sortable._mouseStop( event, true );

					// Restore sortable behaviors that were modfied
					// when the draggable entered the sortable area (#9481)
					sortable.options.revert = sortable.options._revert;
					sortable.options.helper = sortable.options._helper;

					if ( sortable.placeholder ) {
						sortable.placeholder.remove();
					}

					// Restore and recalculate the draggable's offset considering the sortable
					// may have modified them in unexpected ways. (#8809, #10669)
					ui.helper.appendTo( draggable._parent );
					draggable._refreshOffsets( event );
					ui.position = draggable._generatePosition( event, true );

					draggable._trigger( "fromSortable", event );

					// Inform draggable that the helper is no longer in a valid drop zone
					draggable.dropped = false;

					// Need to refreshPositions of all sortables just in case removing
					// from one sortable changes the location of other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					} );
				}
			}
		} );
	}
} );

$.ui.plugin.add( "draggable", "cursor", {
	start: function( event, ui, instance ) {
		var t = $( "body" ),
			o = instance.options;

		if ( t.css( "cursor" ) ) {
			o._cursor = t.css( "cursor" );
		}
		t.css( "cursor", o.cursor );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._cursor ) {
			$( "body" ).css( "cursor", o._cursor );
		}
	}
} );

$.ui.plugin.add( "draggable", "opacity", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;
		if ( t.css( "opacity" ) ) {
			o._opacity = t.css( "opacity" );
		}
		t.css( "opacity", o.opacity );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if ( o._opacity ) {
			$( ui.helper ).css( "opacity", o._opacity );
		}
	}
} );

$.ui.plugin.add( "draggable", "scroll", {
	start: function( event, ui, i ) {
		if ( !i.scrollParentNotHidden ) {
			i.scrollParentNotHidden = i.helper.scrollParent( false );
		}

		if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] &&
				i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
			i.overflowOffset = i.scrollParentNotHidden.offset();
		}
	},
	drag: function( event, ui, i  ) {

		var o = i.options,
			scrolled = false,
			scrollParent = i.scrollParentNotHidden[ 0 ],
			document = i.document[ 0 ];

		if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
			if ( !o.axis || o.axis !== "x" ) {
				if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY <
						o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
				} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX <
						o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
				} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
				}
			}

		} else {

			if ( !o.axis || o.axis !== "x" ) {
				if ( event.pageY - $( document ).scrollTop() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() - o.scrollSpeed );
				} else if ( $( window ).height() - ( event.pageY - $( document ).scrollTop() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollTop( $( document ).scrollTop() + o.scrollSpeed );
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( event.pageX - $( document ).scrollLeft() < o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() - o.scrollSpeed
					);
				} else if ( $( window ).width() - ( event.pageX - $( document ).scrollLeft() ) <
						o.scrollSensitivity ) {
					scrolled = $( document ).scrollLeft(
						$( document ).scrollLeft() + o.scrollSpeed
					);
				}
			}

		}

		if ( scrolled !== false && $.ui.ddmanager && !o.dropBehaviour ) {
			$.ui.ddmanager.prepareOffsets( i, event );
		}

	}
} );

$.ui.plugin.add( "draggable", "snap", {
	start: function( event, ui, i ) {

		var o = i.options;

		i.snapElements = [];

		$( o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap )
			.each( function() {
				var $t = $( this ),
					$o = $t.offset();
				if ( this !== i.element[ 0 ] ) {
					i.snapElements.push( {
						item: this,
						width: $t.outerWidth(), height: $t.outerHeight(),
						top: $o.top, left: $o.left
					} );
				}
			} );

	},
	drag: function( event, ui, inst ) {

		var ts, bs, ls, rs, l, r, t, b, i, first,
			o = inst.options,
			d = o.snapTolerance,
			x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for ( i = inst.snapElements.length - 1; i >= 0; i-- ) {

			l = inst.snapElements[ i ].left - inst.margins.left;
			r = l + inst.snapElements[ i ].width;
			t = inst.snapElements[ i ].top - inst.margins.top;
			b = t + inst.snapElements[ i ].height;

			if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d ||
					!$.contains( inst.snapElements[ i ].item.ownerDocument,
					inst.snapElements[ i ].item ) ) {
				if ( inst.snapElements[ i ].snapping ) {
					if ( inst.options.snap.release ) {
						inst.options.snap.release.call(
							inst.element,
							event,
							$.extend( inst._uiHash(), { snapItem: inst.snapElements[ i ].item } )
						);
					}
				}
				inst.snapElements[ i ].snapping = false;
				continue;
			}

			if ( o.snapMode !== "inner" ) {
				ts = Math.abs( t - y2 ) <= d;
				bs = Math.abs( b - y1 ) <= d;
				ls = Math.abs( l - x2 ) <= d;
				rs = Math.abs( r - x1 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l - inst.helperProportions.width
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r
					} ).left;
				}
			}

			first = ( ts || bs || ls || rs );

			if ( o.snapMode !== "outer" ) {
				ts = Math.abs( t - y1 ) <= d;
				bs = Math.abs( b - y2 ) <= d;
				ls = Math.abs( l - x1 ) <= d;
				rs = Math.abs( r - x2 ) <= d;
				if ( ts ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: t,
						left: 0
					} ).top;
				}
				if ( bs ) {
					ui.position.top = inst._convertPositionTo( "relative", {
						top: b - inst.helperProportions.height,
						left: 0
					} ).top;
				}
				if ( ls ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: l
					} ).left;
				}
				if ( rs ) {
					ui.position.left = inst._convertPositionTo( "relative", {
						top: 0,
						left: r - inst.helperProportions.width
					} ).left;
				}
			}

			if ( !inst.snapElements[ i ].snapping && ( ts || bs || ls || rs || first ) ) {
				if ( inst.options.snap.snap ) {
					inst.options.snap.snap.call(
						inst.element,
						event,
						$.extend( inst._uiHash(), {
							snapItem: inst.snapElements[ i ].item
						} ) );
				}
			}
			inst.snapElements[ i ].snapping = ( ts || bs || ls || rs || first );

		}

	}
} );

$.ui.plugin.add( "draggable", "stack", {
	start: function( event, ui, instance ) {
		var min,
			o = instance.options,
			group = $.makeArray( $( o.stack ) ).sort( function( a, b ) {
				return ( parseInt( $( a ).css( "zIndex" ), 10 ) || 0 ) -
					( parseInt( $( b ).css( "zIndex" ), 10 ) || 0 );
			} );

		if ( !group.length ) {
			return;
		}

		min = parseInt( $( group[ 0 ] ).css( "zIndex" ), 10 ) || 0;
		$( group ).each( function( i ) {
			$( this ).css( "zIndex", min + i );
		} );
		this.css( "zIndex", ( min + group.length ) );
	}
} );

$.ui.plugin.add( "draggable", "zIndex", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;

		if ( t.css( "zIndex" ) ) {
			o._zIndex = t.css( "zIndex" );
		}
		t.css( "zIndex", o.zIndex );
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;

		if ( o._zIndex ) {
			$( ui.helper ).css( "zIndex", o._zIndex );
		}
	}
} );

return $.ui.draggable;

} );


/***/ }),
/* 197 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

// This file is deprecated
return $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
} );


/***/ }),
/* 198 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI :data 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :data Selector
//>>group: Core
//>>description: Selects elements which have data stored under the specified key.
//>>docs: http://api.jqueryui.com/data-selector/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.extend( $.expr.pseudos, {
	data: $.expr.createPseudo ?
		$.expr.createPseudo( function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		} ) :

		// Support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		}
} );
} );


/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Scroll Parent 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: scrollParent
//>>group: Core
//>>description: Get the closest ancestor element that is scrollable.
//>>docs: http://api.jqueryui.com/scrollParent/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.fn.scrollParent = function( includeHidden ) {
	var position = this.css( "position" ),
		excludeStaticParent = position === "absolute",
		overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
		scrollParent = this.parents().filter( function() {
			var parent = $( this );
			if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
				return false;
			}
			return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) +
				parent.css( "overflow-x" ) );
		} ).eq( 0 );

	return position === "fixed" || !scrollParent.length ?
		$( this[ 0 ].ownerDocument || document ) :
		scrollParent;
};

} );


/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Resizable 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Resizable
//>>group: Interactions
//>>description: Enables resize functionality for any element.
//>>docs: http://api.jqueryui.com/resizable/
//>>demos: http://jqueryui.com/resizable/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/resizable.css
//>>css.theme: ../../themes/base/theme.css

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [
			__webpack_require__(0),
			__webpack_require__(51),
			__webpack_require__(201),
			__webpack_require__(104),
			__webpack_require__(3),
			__webpack_require__(17)
		], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

$.widget( "ui.resizable", $.ui.mouse, {
	version: "1.13.2",
	widgetEventPrefix: "resize",
	options: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		classes: {
			"ui-resizable-se": "ui-icon ui-icon-gripsmall-diagonal-se"
		},
		containment: false,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,

		// See #7960
		zIndex: 90,

		// Callbacks
		resize: null,
		start: null,
		stop: null
	},

	_num: function( value ) {
		return parseFloat( value ) || 0;
	},

	_isNumber: function( value ) {
		return !isNaN( parseFloat( value ) );
	},

	_hasScroll: function( el, a ) {

		if ( $( el ).css( "overflow" ) === "hidden" ) {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		try {
			el[ scroll ] = 1;
			has = ( el[ scroll ] > 0 );
			el[ scroll ] = 0;
		} catch ( e ) {

			// `el` might be a string, then setting `scroll` will throw
			// an error in strict mode; ignore it.
		}
		return has;
	},

	_create: function() {

		var margins,
			o = this.options,
			that = this;
		this._addClass( "ui-resizable" );

		$.extend( this, {
			_aspectRatio: !!( o.aspectRatio ),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
		} );

		// Wrap the element if it cannot hold child nodes
		if ( this.element[ 0 ].nodeName.match( /^(canvas|textarea|input|select|button|img)$/i ) ) {

			this.element.wrap(
				$( "<div class='ui-wrapper'></div>" ).css( {
					overflow: "hidden",
					position: this.element.css( "position" ),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css( "top" ),
					left: this.element.css( "left" )
				} )
			);

			this.element = this.element.parent().data(
				"ui-resizable", this.element.resizable( "instance" )
			);

			this.elementIsWrapper = true;

			margins = {
				marginTop: this.originalElement.css( "marginTop" ),
				marginRight: this.originalElement.css( "marginRight" ),
				marginBottom: this.originalElement.css( "marginBottom" ),
				marginLeft: this.originalElement.css( "marginLeft" )
			};

			this.element.css( margins );
			this.originalElement.css( "margin", 0 );

			// support: Safari
			// Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css( "resize" );
			this.originalElement.css( "resize", "none" );

			this._proportionallyResizeElements.push( this.originalElement.css( {
				position: "static",
				zoom: 1,
				display: "block"
			} ) );

			// Support: IE9
			// avoid IE jump (hard set the margin)
			this.originalElement.css( margins );

			this._proportionallyResize();
		}

		this._setupHandles();

		if ( o.autoHide ) {
			$( this.element )
				.on( "mouseenter", function() {
					if ( o.disabled ) {
						return;
					}
					that._removeClass( "ui-resizable-autohide" );
					that._handles.show();
				} )
				.on( "mouseleave", function() {
					if ( o.disabled ) {
						return;
					}
					if ( !that.resizing ) {
						that._addClass( "ui-resizable-autohide" );
						that._handles.hide();
					}
				} );
		}

		this._mouseInit();
	},

	_destroy: function() {

		this._mouseDestroy();
		this._addedHandles.remove();

		var wrapper,
			_destroy = function( exp ) {
				$( exp )
					.removeData( "resizable" )
					.removeData( "ui-resizable" )
					.off( ".resizable" );
			};

		// TODO: Unwrap at same DOM position
		if ( this.elementIsWrapper ) {
			_destroy( this.element );
			wrapper = this.element;
			this.originalElement.css( {
				position: wrapper.css( "position" ),
				width: wrapper.outerWidth(),
				height: wrapper.outerHeight(),
				top: wrapper.css( "top" ),
				left: wrapper.css( "left" )
			} ).insertAfter( wrapper );
			wrapper.remove();
		}

		this.originalElement.css( "resize", this.originalResizeStyle );
		_destroy( this.originalElement );

		return this;
	},

	_setOption: function( key, value ) {
		this._super( key, value );

		switch ( key ) {
		case "handles":
			this._removeHandles();
			this._setupHandles();
			break;
		case "aspectRatio":
			this._aspectRatio = !!value;
			break;
		default:
			break;
		}
	},

	_setupHandles: function() {
		var o = this.options, handle, i, n, hname, axis, that = this;
		this.handles = o.handles ||
			( !$( ".ui-resizable-handle", this.element ).length ?
				"e,s,se" : {
					n: ".ui-resizable-n",
					e: ".ui-resizable-e",
					s: ".ui-resizable-s",
					w: ".ui-resizable-w",
					se: ".ui-resizable-se",
					sw: ".ui-resizable-sw",
					ne: ".ui-resizable-ne",
					nw: ".ui-resizable-nw"
				} );

		this._handles = $();
		this._addedHandles = $();
		if ( this.handles.constructor === String ) {

			if ( this.handles === "all" ) {
				this.handles = "n,e,s,w,se,sw,ne,nw";
			}

			n = this.handles.split( "," );
			this.handles = {};

			for ( i = 0; i < n.length; i++ ) {

				handle = String.prototype.trim.call( n[ i ] );
				hname = "ui-resizable-" + handle;
				axis = $( "<div>" );
				this._addClass( axis, "ui-resizable-handle " + hname );

				axis.css( { zIndex: o.zIndex } );

				this.handles[ handle ] = ".ui-resizable-" + handle;
				if ( !this.element.children( this.handles[ handle ] ).length ) {
					this.element.append( axis );
					this._addedHandles = this._addedHandles.add( axis );
				}
			}

		}

		this._renderAxis = function( target ) {

			var i, axis, padPos, padWrapper;

			target = target || this.element;

			for ( i in this.handles ) {

				if ( this.handles[ i ].constructor === String ) {
					this.handles[ i ] = this.element.children( this.handles[ i ] ).first().show();
				} else if ( this.handles[ i ].jquery || this.handles[ i ].nodeType ) {
					this.handles[ i ] = $( this.handles[ i ] );
					this._on( this.handles[ i ], { "mousedown": that._mouseDown } );
				}

				if ( this.elementIsWrapper &&
						this.originalElement[ 0 ]
							.nodeName
							.match( /^(textarea|input|select|button)$/i ) ) {
					axis = $( this.handles[ i ], this.element );

					padWrapper = /sw|ne|nw|se|n|s/.test( i ) ?
						axis.outerHeight() :
						axis.outerWidth();

					padPos = [ "padding",
						/ne|nw|n/.test( i ) ? "Top" :
						/se|sw|s/.test( i ) ? "Bottom" :
						/^e$/.test( i ) ? "Right" : "Left" ].join( "" );

					target.css( padPos, padWrapper );

					this._proportionallyResize();
				}

				this._handles = this._handles.add( this.handles[ i ] );
			}
		};

		// TODO: make renderAxis a prototype function
		this._renderAxis( this.element );

		this._handles = this._handles.add( this.element.find( ".ui-resizable-handle" ) );
		this._handles.disableSelection();

		this._handles.on( "mouseover", function() {
			if ( !that.resizing ) {
				if ( this.className ) {
					axis = this.className.match( /ui-resizable-(se|sw|ne|nw|n|e|s|w)/i );
				}
				that.axis = axis && axis[ 1 ] ? axis[ 1 ] : "se";
			}
		} );

		if ( o.autoHide ) {
			this._handles.hide();
			this._addClass( "ui-resizable-autohide" );
		}
	},

	_removeHandles: function() {
		this._addedHandles.remove();
	},

	_mouseCapture: function( event ) {
		var i, handle,
			capture = false;

		for ( i in this.handles ) {
			handle = $( this.handles[ i ] )[ 0 ];
			if ( handle === event.target || $.contains( handle, event.target ) ) {
				capture = true;
			}
		}

		return !this.options.disabled && capture;
	},

	_mouseStart: function( event ) {

		var curleft, curtop, cursor,
			o = this.options,
			el = this.element;

		this.resizing = true;

		this._renderProxy();

		curleft = this._num( this.helper.css( "left" ) );
		curtop = this._num( this.helper.css( "top" ) );

		if ( o.containment ) {
			curleft += $( o.containment ).scrollLeft() || 0;
			curtop += $( o.containment ).scrollTop() || 0;
		}

		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };

		this.size = this._helper ? {
				width: this.helper.width(),
				height: this.helper.height()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.originalSize = this._helper ? {
				width: el.outerWidth(),
				height: el.outerHeight()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.sizeDiff = {
			width: el.outerWidth() - el.width(),
			height: el.outerHeight() - el.height()
		};

		this.originalPosition = { left: curleft, top: curtop };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		this.aspectRatio = ( typeof o.aspectRatio === "number" ) ?
			o.aspectRatio :
			( ( this.originalSize.width / this.originalSize.height ) || 1 );

		cursor = $( ".ui-resizable-" + this.axis ).css( "cursor" );
		$( "body" ).css( "cursor", cursor === "auto" ? this.axis + "-resize" : cursor );

		this._addClass( "ui-resizable-resizing" );
		this._propagate( "start", event );
		return true;
	},

	_mouseDrag: function( event ) {

		var data, props,
			smp = this.originalMousePosition,
			a = this.axis,
			dx = ( event.pageX - smp.left ) || 0,
			dy = ( event.pageY - smp.top ) || 0,
			trigger = this._change[ a ];

		this._updatePrevProperties();

		if ( !trigger ) {
			return false;
		}

		data = trigger.apply( this, [ event, dx, dy ] );

		this._updateVirtualBoundaries( event.shiftKey );
		if ( this._aspectRatio || event.shiftKey ) {
			data = this._updateRatio( data, event );
		}

		data = this._respectSize( data, event );

		this._updateCache( data );

		this._propagate( "resize", event );

		props = this._applyChanges();

		if ( !this._helper && this._proportionallyResizeElements.length ) {
			this._proportionallyResize();
		}

		if ( !$.isEmptyObject( props ) ) {
			this._updatePrevProperties();
			this._trigger( "resize", event, this.ui() );
			this._applyChanges();
		}

		return false;
	},

	_mouseStop: function( event ) {

		this.resizing = false;
		var pr, ista, soffseth, soffsetw, s, left, top,
			o = this.options, that = this;

		if ( this._helper ) {

			pr = this._proportionallyResizeElements;
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName );
			soffseth = ista && this._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height;
			soffsetw = ista ? 0 : that.sizeDiff.width;

			s = {
				width: ( that.helper.width()  - soffsetw ),
				height: ( that.helper.height() - soffseth )
			};
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null;
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

			if ( !o.animate ) {
				this.element.css( $.extend( s, { top: top, left: left } ) );
			}

			that.helper.height( that.size.height );
			that.helper.width( that.size.width );

			if ( this._helper && !o.animate ) {
				this._proportionallyResize();
			}
		}

		$( "body" ).css( "cursor", "auto" );

		this._removeClass( "ui-resizable-resizing" );

		this._propagate( "stop", event );

		if ( this._helper ) {
			this.helper.remove();
		}

		return false;

	},

	_updatePrevProperties: function() {
		this.prevPosition = {
			top: this.position.top,
			left: this.position.left
		};
		this.prevSize = {
			width: this.size.width,
			height: this.size.height
		};
	},

	_applyChanges: function() {
		var props = {};

		if ( this.position.top !== this.prevPosition.top ) {
			props.top = this.position.top + "px";
		}
		if ( this.position.left !== this.prevPosition.left ) {
			props.left = this.position.left + "px";
		}
		if ( this.size.width !== this.prevSize.width ) {
			props.width = this.size.width + "px";
		}
		if ( this.size.height !== this.prevSize.height ) {
			props.height = this.size.height + "px";
		}

		this.helper.css( props );

		return props;
	},

	_updateVirtualBoundaries: function( forceAspectRatio ) {
		var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
			o = this.options;

		b = {
			minWidth: this._isNumber( o.minWidth ) ? o.minWidth : 0,
			maxWidth: this._isNumber( o.maxWidth ) ? o.maxWidth : Infinity,
			minHeight: this._isNumber( o.minHeight ) ? o.minHeight : 0,
			maxHeight: this._isNumber( o.maxHeight ) ? o.maxHeight : Infinity
		};

		if ( this._aspectRatio || forceAspectRatio ) {
			pMinWidth = b.minHeight * this.aspectRatio;
			pMinHeight = b.minWidth / this.aspectRatio;
			pMaxWidth = b.maxHeight * this.aspectRatio;
			pMaxHeight = b.maxWidth / this.aspectRatio;

			if ( pMinWidth > b.minWidth ) {
				b.minWidth = pMinWidth;
			}
			if ( pMinHeight > b.minHeight ) {
				b.minHeight = pMinHeight;
			}
			if ( pMaxWidth < b.maxWidth ) {
				b.maxWidth = pMaxWidth;
			}
			if ( pMaxHeight < b.maxHeight ) {
				b.maxHeight = pMaxHeight;
			}
		}
		this._vBoundaries = b;
	},

	_updateCache: function( data ) {
		this.offset = this.helper.offset();
		if ( this._isNumber( data.left ) ) {
			this.position.left = data.left;
		}
		if ( this._isNumber( data.top ) ) {
			this.position.top = data.top;
		}
		if ( this._isNumber( data.height ) ) {
			this.size.height = data.height;
		}
		if ( this._isNumber( data.width ) ) {
			this.size.width = data.width;
		}
	},

	_updateRatio: function( data ) {

		var cpos = this.position,
			csize = this.size,
			a = this.axis;

		if ( this._isNumber( data.height ) ) {
			data.width = ( data.height * this.aspectRatio );
		} else if ( this._isNumber( data.width ) ) {
			data.height = ( data.width / this.aspectRatio );
		}

		if ( a === "sw" ) {
			data.left = cpos.left + ( csize.width - data.width );
			data.top = null;
		}
		if ( a === "nw" ) {
			data.top = cpos.top + ( csize.height - data.height );
			data.left = cpos.left + ( csize.width - data.width );
		}

		return data;
	},

	_respectSize: function( data ) {

		var o = this._vBoundaries,
			a = this.axis,
			ismaxw = this._isNumber( data.width ) && o.maxWidth && ( o.maxWidth < data.width ),
			ismaxh = this._isNumber( data.height ) && o.maxHeight && ( o.maxHeight < data.height ),
			isminw = this._isNumber( data.width ) && o.minWidth && ( o.minWidth > data.width ),
			isminh = this._isNumber( data.height ) && o.minHeight && ( o.minHeight > data.height ),
			dw = this.originalPosition.left + this.originalSize.width,
			dh = this.originalPosition.top + this.originalSize.height,
			cw = /sw|nw|w/.test( a ), ch = /nw|ne|n/.test( a );
		if ( isminw ) {
			data.width = o.minWidth;
		}
		if ( isminh ) {
			data.height = o.minHeight;
		}
		if ( ismaxw ) {
			data.width = o.maxWidth;
		}
		if ( ismaxh ) {
			data.height = o.maxHeight;
		}

		if ( isminw && cw ) {
			data.left = dw - o.minWidth;
		}
		if ( ismaxw && cw ) {
			data.left = dw - o.maxWidth;
		}
		if ( isminh && ch ) {
			data.top = dh - o.minHeight;
		}
		if ( ismaxh && ch ) {
			data.top = dh - o.maxHeight;
		}

		// Fixing jump error on top/left - bug #2330
		if ( !data.width && !data.height && !data.left && data.top ) {
			data.top = null;
		} else if ( !data.width && !data.height && !data.top && data.left ) {
			data.left = null;
		}

		return data;
	},

	_getPaddingPlusBorderDimensions: function( element ) {
		var i = 0,
			widths = [],
			borders = [
				element.css( "borderTopWidth" ),
				element.css( "borderRightWidth" ),
				element.css( "borderBottomWidth" ),
				element.css( "borderLeftWidth" )
			],
			paddings = [
				element.css( "paddingTop" ),
				element.css( "paddingRight" ),
				element.css( "paddingBottom" ),
				element.css( "paddingLeft" )
			];

		for ( ; i < 4; i++ ) {
			widths[ i ] = ( parseFloat( borders[ i ] ) || 0 );
			widths[ i ] += ( parseFloat( paddings[ i ] ) || 0 );
		}

		return {
			height: widths[ 0 ] + widths[ 2 ],
			width: widths[ 1 ] + widths[ 3 ]
		};
	},

	_proportionallyResize: function() {

		if ( !this._proportionallyResizeElements.length ) {
			return;
		}

		var prel,
			i = 0,
			element = this.helper || this.element;

		for ( ; i < this._proportionallyResizeElements.length; i++ ) {

			prel = this._proportionallyResizeElements[ i ];

			// TODO: Seems like a bug to cache this.outerDimensions
			// considering that we are in a loop.
			if ( !this.outerDimensions ) {
				this.outerDimensions = this._getPaddingPlusBorderDimensions( prel );
			}

			prel.css( {
				height: ( element.height() - this.outerDimensions.height ) || 0,
				width: ( element.width() - this.outerDimensions.width ) || 0
			} );

		}

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if ( this._helper ) {

			this.helper = this.helper || $( "<div></div>" ).css( { overflow: "hidden" } );

			this._addClass( this.helper, this._helper );
			this.helper.css( {
				width: this.element.outerWidth(),
				height: this.element.outerHeight(),
				position: "absolute",
				left: this.elementOffset.left + "px",
				top: this.elementOffset.top + "px",
				zIndex: ++o.zIndex //TODO: Don't modify option
			} );

			this.helper
				.appendTo( "body" )
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function( event, dx ) {
			return { width: this.originalSize.width + dx };
		},
		w: function( event, dx ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function( event, dx, dy ) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function( event, dx, dy ) {
			return { height: this.originalSize.height + dy };
		},
		se: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		sw: function( event, dx, dy ) {
			return $.extend( this._change.s.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		},
		ne: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.e.apply( this, [ event, dx, dy ] ) );
		},
		nw: function( event, dx, dy ) {
			return $.extend( this._change.n.apply( this, arguments ),
				this._change.w.apply( this, [ event, dx, dy ] ) );
		}
	},

	_propagate: function( n, event ) {
		$.ui.plugin.call( this, n, [ event, this.ui() ] );
		if ( n !== "resize" ) {
			this._trigger( n, event, this.ui() );
		}
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

} );

/*
 * Resizable Extensions
 */

$.ui.plugin.add( "resizable", "animate", {

	stop: function( event ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			pr = that._proportionallyResizeElements,
			ista = pr.length && ( /textarea/i ).test( pr[ 0 ].nodeName ),
			soffseth = ista && that._hasScroll( pr[ 0 ], "left" ) ? 0 : that.sizeDiff.height,
			soffsetw = ista ? 0 : that.sizeDiff.width,
			style = {
				width: ( that.size.width - soffsetw ),
				height: ( that.size.height - soffseth )
			},
			left = ( parseFloat( that.element.css( "left" ) ) +
				( that.position.left - that.originalPosition.left ) ) || null,
			top = ( parseFloat( that.element.css( "top" ) ) +
				( that.position.top - that.originalPosition.top ) ) || null;

		that.element.animate(
			$.extend( style, top && left ? { top: top, left: left } : {} ), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseFloat( that.element.css( "width" ) ),
						height: parseFloat( that.element.css( "height" ) ),
						top: parseFloat( that.element.css( "top" ) ),
						left: parseFloat( that.element.css( "left" ) )
					};

					if ( pr && pr.length ) {
						$( pr[ 0 ] ).css( { width: data.width, height: data.height } );
					}

					// Propagating resize, and updating values for each animation step
					that._updateCache( data );
					that._propagate( "resize", event );

				}
			}
		);
	}

} );

$.ui.plugin.add( "resizable", "containment", {

	start: function() {
		var element, p, co, ch, cw, width, height,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			el = that.element,
			oc = o.containment,
			ce = ( oc instanceof $ ) ?
				oc.get( 0 ) :
				( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc;

		if ( !ce ) {
			return;
		}

		that.containerElement = $( ce );

		if ( /document/.test( oc ) || oc === document ) {
			that.containerOffset = {
				left: 0,
				top: 0
			};
			that.containerPosition = {
				left: 0,
				top: 0
			};

			that.parentData = {
				element: $( document ),
				left: 0,
				top: 0,
				width: $( document ).width(),
				height: $( document ).height() || document.body.parentNode.scrollHeight
			};
		} else {
			element = $( ce );
			p = [];
			$( [ "Top", "Right", "Left", "Bottom" ] ).each( function( i, name ) {
				p[ i ] = that._num( element.css( "padding" + name ) );
			} );

			that.containerOffset = element.offset();
			that.containerPosition = element.position();
			that.containerSize = {
				height: ( element.innerHeight() - p[ 3 ] ),
				width: ( element.innerWidth() - p[ 1 ] )
			};

			co = that.containerOffset;
			ch = that.containerSize.height;
			cw = that.containerSize.width;
			width = ( that._hasScroll( ce, "left" ) ? ce.scrollWidth : cw );
			height = ( that._hasScroll( ce ) ? ce.scrollHeight : ch );

			that.parentData = {
				element: ce,
				left: co.left,
				top: co.top,
				width: width,
				height: height
			};
		}
	},

	resize: function( event ) {
		var woset, hoset, isParent, isOffsetRelative,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cp = that.position,
			pRatio = that._aspectRatio || event.shiftKey,
			cop = {
				top: 0,
				left: 0
			},
			ce = that.containerElement,
			continueResize = true;

		if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) {
			cop = co;
		}

		if ( cp.left < ( that._helper ? co.left : 0 ) ) {
			that.size.width = that.size.width +
				( that._helper ?
					( that.position.left - co.left ) :
					( that.position.left - cop.left ) );

			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
			that.position.left = o.helper ? co.left : 0;
		}

		if ( cp.top < ( that._helper ? co.top : 0 ) ) {
			that.size.height = that.size.height +
				( that._helper ?
					( that.position.top - co.top ) :
					that.position.top );

			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
			that.position.top = that._helper ? co.top : 0;
		}

		isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 );
		isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) );

		if ( isParent && isOffsetRelative ) {
			that.offset.left = that.parentData.left + that.position.left;
			that.offset.top = that.parentData.top + that.position.top;
		} else {
			that.offset.left = that.element.offset().left;
			that.offset.top = that.element.offset().top;
		}

		woset = Math.abs( that.sizeDiff.width +
			( that._helper ?
				that.offset.left - cop.left :
				( that.offset.left - co.left ) ) );

		hoset = Math.abs( that.sizeDiff.height +
			( that._helper ?
				that.offset.top - cop.top :
				( that.offset.top - co.top ) ) );

		if ( woset + that.size.width >= that.parentData.width ) {
			that.size.width = that.parentData.width - woset;
			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
		}

		if ( hoset + that.size.height >= that.parentData.height ) {
			that.size.height = that.parentData.height - hoset;
			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
		}

		if ( !continueResize ) {
			that.position.left = that.prevPosition.left;
			that.position.top = that.prevPosition.top;
			that.size.width = that.prevSize.width;
			that.size.height = that.prevSize.height;
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cop = that.containerPosition,
			ce = that.containerElement,
			helper = $( that.helper ),
			ho = helper.offset(),
			w = helper.outerWidth() - that.sizeDiff.width,
			h = helper.outerHeight() - that.sizeDiff.height;

		if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}

		if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) {
			$( this ).css( {
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			} );
		}
	}
} );

$.ui.plugin.add( "resizable", "alsoResize", {

	start: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options;

		$( o.alsoResize ).each( function() {
			var el = $( this );
			el.data( "ui-resizable-alsoresize", {
				width: parseFloat( el.width() ), height: parseFloat( el.height() ),
				left: parseFloat( el.css( "left" ) ), top: parseFloat( el.css( "top" ) )
			} );
		} );
	},

	resize: function( event, ui ) {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			os = that.originalSize,
			op = that.originalPosition,
			delta = {
				height: ( that.size.height - os.height ) || 0,
				width: ( that.size.width - os.width ) || 0,
				top: ( that.position.top - op.top ) || 0,
				left: ( that.position.left - op.left ) || 0
			};

			$( o.alsoResize ).each( function() {
				var el = $( this ), start = $( this ).data( "ui-resizable-alsoresize" ), style = {},
					css = el.parents( ui.originalElement[ 0 ] ).length ?
							[ "width", "height" ] :
							[ "width", "height", "top", "left" ];

				$.each( css, function( i, prop ) {
					var sum = ( start[ prop ] || 0 ) + ( delta[ prop ] || 0 );
					if ( sum && sum >= 0 ) {
						style[ prop ] = sum || null;
					}
				} );

				el.css( style );
			} );
	},

	stop: function() {
		$( this ).removeData( "ui-resizable-alsoresize" );
	}
} );

$.ui.plugin.add( "resizable", "ghost", {

	start: function() {

		var that = $( this ).resizable( "instance" ), cs = that.size;

		that.ghost = that.originalElement.clone();
		that.ghost.css( {
			opacity: 0.25,
			display: "block",
			position: "relative",
			height: cs.height,
			width: cs.width,
			margin: 0,
			left: 0,
			top: 0
		} );

		that._addClass( that.ghost, "ui-resizable-ghost" );

		// DEPRECATED
		// TODO: remove after 1.12
		if ( $.uiBackCompat !== false && typeof that.options.ghost === "string" ) {

			// Ghost option
			that.ghost.addClass( this.options.ghost );
		}

		that.ghost.appendTo( that.helper );

	},

	resize: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost ) {
			that.ghost.css( {
				position: "relative",
				height: that.size.height,
				width: that.size.width
			} );
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" );
		if ( that.ghost && that.helper ) {
			that.helper.get( 0 ).removeChild( that.ghost.get( 0 ) );
		}
	}

} );

$.ui.plugin.add( "resizable", "grid", {

	resize: function() {
		var outerDimensions,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			cs = that.size,
			os = that.originalSize,
			op = that.originalPosition,
			a = that.axis,
			grid = typeof o.grid === "number" ? [ o.grid, o.grid ] : o.grid,
			gridX = ( grid[ 0 ] || 1 ),
			gridY = ( grid[ 1 ] || 1 ),
			ox = Math.round( ( cs.width - os.width ) / gridX ) * gridX,
			oy = Math.round( ( cs.height - os.height ) / gridY ) * gridY,
			newWidth = os.width + ox,
			newHeight = os.height + oy,
			isMaxWidth = o.maxWidth && ( o.maxWidth < newWidth ),
			isMaxHeight = o.maxHeight && ( o.maxHeight < newHeight ),
			isMinWidth = o.minWidth && ( o.minWidth > newWidth ),
			isMinHeight = o.minHeight && ( o.minHeight > newHeight );

		o.grid = grid;

		if ( isMinWidth ) {
			newWidth += gridX;
		}
		if ( isMinHeight ) {
			newHeight += gridY;
		}
		if ( isMaxWidth ) {
			newWidth -= gridX;
		}
		if ( isMaxHeight ) {
			newHeight -= gridY;
		}

		if ( /^(se|s|e)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
		} else if ( /^(ne)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.top = op.top - oy;
		} else if ( /^(sw)$/.test( a ) ) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.left = op.left - ox;
		} else {
			if ( newHeight - gridY <= 0 || newWidth - gridX <= 0 ) {
				outerDimensions = that._getPaddingPlusBorderDimensions( this );
			}

			if ( newHeight - gridY > 0 ) {
				that.size.height = newHeight;
				that.position.top = op.top - oy;
			} else {
				newHeight = gridY - outerDimensions.height;
				that.size.height = newHeight;
				that.position.top = op.top + os.height - newHeight;
			}
			if ( newWidth - gridX > 0 ) {
				that.size.width = newWidth;
				that.position.left = op.left - ox;
			} else {
				newWidth = gridX - outerDimensions.width;
				that.size.width = newWidth;
				that.position.left = op.left + os.width - newWidth;
			}
		}
	}

} );

return $.ui.resizable;

} );


/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Disable Selection 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: disableSelection
//>>group: Core
//>>description: Disable selection of text content within the set of matched elements.
//>>docs: http://api.jqueryui.com/disableSelection/

// This file is deprecated
( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.fn.extend( {
	disableSelection: ( function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.on( eventType + ".ui-disableSelection", function( event ) {
				event.preventDefault();
			} );
		};
	} )(),

	enableSelection: function() {
		return this.off( ".ui-disableSelection" );
	}
} );

} );


/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Position 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */

//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: http://api.jqueryui.com/position/
//>>demos: http://jqueryui.com/position/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

( function() {
var cachedScrollbarWidth,
	max = Math.max,
	abs = Math.abs,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function isWindow( obj ) {
	return obj != null && obj === obj.window;
}

function getDimensions( elem ) {
	var raw = elem[ 0 ];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "<div style=" +
				"'display:block;position:absolute;width:200px;height:200px;overflow:hidden;'>" +
				"<div style='height:300px;width:auto;'></div></div>" ),
			innerDiv = div.children()[ 0 ];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[ 0 ].clientWidth;
		}

		div.remove();

		return ( cachedScrollbarWidth = w1 - w2 );
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-x" ),
			overflowY = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" && within.width < within.element[ 0 ].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < within.element[ 0 ].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isElemWindow = isWindow( withinElement[ 0 ] ),
			isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9,
			hasOffset = !isElemWindow && !isDocument;
		return {
			element: withinElement,
			isWindow: isElemWindow,
			isDocument: isDocument,
			offset: hasOffset ? $( element ).offset() : { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),
			width: withinElement.outerWidth(),
			height: withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// Make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,

		// Make sure string options are treated as CSS selectors
		target = typeof options.of === "string" ?
			$( document ).find( options.of ) :
			$( options.of ),

		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[ 0 ].preventDefault ) {

		// Force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;

	// Clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// Force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1 ) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// Calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// Reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	} );

	// Normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each( function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) +
				scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) +
				scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		collisionPosition = {
			marginLeft: marginLeft,
			marginTop: marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within,
					elem: elem
				} );
			}
		} );

		if ( options.using ) {

			// Adds feedback as second argument to using callback, if present
			using = function( props ) {
				var left = targetOffset.left - position.left,
					right = left + targetWidth - elemWidth,
					top = targetOffset.top - position.top,
					bottom = top + targetHeight - elemHeight,
					feedback = {
						target: {
							element: target,
							left: targetOffset.left,
							top: targetOffset.top,
							width: targetWidth,
							height: targetHeight
						},
						element: {
							element: elem,
							left: position.left,
							top: position.top,
							width: elemWidth,
							height: elemHeight
						},
						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
					};
				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
					feedback.important = "horizontal";
				} else {
					feedback.important = "vertical";
				}
				options.using.call( this, props, feedback );
			};
		}

		elem.offset( $.extend( position, { using: using } ) );
	} );
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
				outerWidth = within.width,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = withinOffset - collisionPosLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
				newOverRight;

			// Element is wider than within
			if ( data.collisionWidth > outerWidth ) {

				// Element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
						withinOffset;
					position.left += overLeft - newOverRight;

				// Element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;

				// Element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}

			// Too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;

			// Too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left -= overRight;

			// Adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// Element is taller than within
			if ( data.collisionHeight > outerHeight ) {

				// Element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
						withinOffset;
					position.top += overTop - newOverBottom;

				// Element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;

				// Element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}

			// Too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;

			// Too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top -= overBottom;

			// Adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

			if ( overLeft < 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth -
					outerWidth - withinOffset;
				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight > 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset +
					atOffset + offset - offsetLeft;
				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
					position.left += myOffset + atOffset + offset;
				}
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.top + within.scrollTop,
				outerHeight = within.height,
				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = collisionPosTop - offsetTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					data.at[ 1 ] === "bottom" ?
						-data.targetHeight :
						0,
				offset = -2 * data.offset[ 1 ],
				newOverTop,
				newOverBottom;
			if ( overTop < 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight -
					outerHeight - withinOffset;
				if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom > 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset +
					offset - offsetTop;
				if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
					position.top += myOffset + atOffset + offset;
				}
			}
		}
	},
	flipfit: {
		left: function() {
			$.ui.position.flip.left.apply( this, arguments );
			$.ui.position.fit.left.apply( this, arguments );
		},
		top: function() {
			$.ui.position.flip.top.apply( this, arguments );
			$.ui.position.fit.top.apply( this, arguments );
		}
	}
};

} )();

return $.ui.position;

} );


/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Tabbable 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: :tabbable Selector
//>>group: Core
//>>description: Selects elements which can be tabbed to.
//>>docs: http://api.jqueryui.com/tabbable-selector/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3), __webpack_require__(107) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.extend( $.expr.pseudos, {
	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			hasTabindex = tabIndex != null;
		return ( !hasTabindex || tabIndex >= 0 ) && $.ui.focusable( element, hasTabindex );
	}
} );

} );


/***/ }),
/* 204 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery UI Unique ID 1.13.2
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: http://api.jqueryui.com/uniqueId/

( function( factory ) {
	"use strict";

	if ( true ) {

		// AMD. Register as an anonymous module.
		!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(0), __webpack_require__(3) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
	} else {

		// Browser globals
		factory( jQuery );
	}
} )( function( $ ) {
"use strict";

return $.fn.extend( {
	uniqueId: ( function() {
		var uuid = 0;

		return function() {
			return this.each( function() {
				if ( !this.id ) {
					this.id = "ui-id-" + ( ++uuid );
				}
			} );
		};
	} )(),

	removeUniqueId: function() {
		return this.each( function() {
			if ( /^ui-id-\d+$/.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		} );
	}
} );

} );


/***/ }),
/* 205 */
/***/ (function(module, exports, __webpack_require__) {

// style-loader: Adds some css to the DOM by adding a <style> tag

// load the styles
var content = __webpack_require__(206);
if(typeof content === 'string') content = [[module.i, content, '']];
// add the styles to the DOM
var update = __webpack_require__(233)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
	// When the styles change, update the <style> tags
	if(!content.locals) {
		module.hot.accept("!!../../../css-loader/index.js!./all.css", function() {
			var newContent = require("!!../../../css-loader/index.js!./all.css");
			if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
			update(newContent);
		});
	}
	// When the module is disposed, remove the <style> tags
	module.hot.dispose(function() { update(); });
}

/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports
exports.i(__webpack_require__(207), "");
exports.i(__webpack_require__(227), "");

// module
exports.push([module.i, "/*!\n * jQuery UI CSS Framework 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/category/theming/\n */\n", ""]);

// exports


/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports
exports.i(__webpack_require__(208), "");
exports.i(__webpack_require__(209), "");
exports.i(__webpack_require__(210), "");
exports.i(__webpack_require__(211), "");
exports.i(__webpack_require__(212), "");
exports.i(__webpack_require__(213), "");
exports.i(__webpack_require__(214), "");
exports.i(__webpack_require__(215), "");
exports.i(__webpack_require__(216), "");
exports.i(__webpack_require__(217), "");
exports.i(__webpack_require__(218), "");
exports.i(__webpack_require__(219), "");
exports.i(__webpack_require__(220), "");
exports.i(__webpack_require__(221), "");
exports.i(__webpack_require__(222), "");
exports.i(__webpack_require__(223), "");
exports.i(__webpack_require__(224), "");
exports.i(__webpack_require__(225), "");
exports.i(__webpack_require__(226), "");

// module
exports.push([module.i, "/*!\n * jQuery UI CSS Framework 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/category/theming/\n */\n", ""]);

// exports


/***/ }),
/* 208 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI CSS Framework 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/category/theming/\n */\n\n/* Layout helpers\n----------------------------------*/\n.ui-helper-hidden {\n\tdisplay: none;\n}\n.ui-helper-hidden-accessible {\n\tborder: 0;\n\tclip: rect(0 0 0 0);\n\theight: 1px;\n\tmargin: -1px;\n\toverflow: hidden;\n\tpadding: 0;\n\tposition: absolute;\n\twidth: 1px;\n}\n.ui-helper-reset {\n\tmargin: 0;\n\tpadding: 0;\n\tborder: 0;\n\toutline: 0;\n\tline-height: 1.3;\n\ttext-decoration: none;\n\tfont-size: 100%;\n\tlist-style: none;\n}\n.ui-helper-clearfix:before,\n.ui-helper-clearfix:after {\n\tcontent: \"\";\n\tdisplay: table;\n\tborder-collapse: collapse;\n}\n.ui-helper-clearfix:after {\n\tclear: both;\n}\n.ui-helper-zfix {\n\twidth: 100%;\n\theight: 100%;\n\ttop: 0;\n\tleft: 0;\n\tposition: absolute;\n\topacity: 0;\n\t-ms-filter: \"alpha(opacity=0)\"; /* support: IE8 */\n}\n\n.ui-front {\n\tz-index: 100;\n}\n\n\n/* Interaction Cues\n----------------------------------*/\n.ui-state-disabled {\n\tcursor: default !important;\n\tpointer-events: none;\n}\n\n\n/* Icons\n----------------------------------*/\n.ui-icon {\n\tdisplay: inline-block;\n\tvertical-align: middle;\n\tmargin-top: -.25em;\n\tposition: relative;\n\ttext-indent: -99999px;\n\toverflow: hidden;\n\tbackground-repeat: no-repeat;\n}\n\n.ui-widget-icon-block {\n\tleft: 50%;\n\tmargin-left: -8px;\n\tdisplay: block;\n}\n\n/* Misc visuals\n----------------------------------*/\n\n/* Overlays */\n.ui-widget-overlay {\n\tposition: fixed;\n\ttop: 0;\n\tleft: 0;\n\twidth: 100%;\n\theight: 100%;\n}\n", ""]);

// exports


/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Accordion 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/accordion/#theming\n */\n.ui-accordion .ui-accordion-header {\n\tdisplay: block;\n\tcursor: pointer;\n\tposition: relative;\n\tmargin: 2px 0 0 0;\n\tpadding: .5em .5em .5em .7em;\n\tfont-size: 100%;\n}\n.ui-accordion .ui-accordion-content {\n\tpadding: 1em 2.2em;\n\tborder-top: 0;\n\toverflow: auto;\n}\n", ""]);

// exports


/***/ }),
/* 210 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Autocomplete 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/autocomplete/#theming\n */\n.ui-autocomplete {\n\tposition: absolute;\n\ttop: 0;\n\tleft: 0;\n\tcursor: default;\n}\n", ""]);

// exports


/***/ }),
/* 211 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Button 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/button/#theming\n */\n.ui-button {\n\tpadding: .4em 1em;\n\tdisplay: inline-block;\n\tposition: relative;\n\tline-height: normal;\n\tmargin-right: .1em;\n\tcursor: pointer;\n\tvertical-align: middle;\n\ttext-align: center;\n\t-webkit-user-select: none;\n\t-moz-user-select: none;\n\t-ms-user-select: none;\n\tuser-select: none;\n\n\t/* Support: IE <= 11 */\n\toverflow: visible;\n}\n\n.ui-button,\n.ui-button:link,\n.ui-button:visited,\n.ui-button:hover,\n.ui-button:active {\n\ttext-decoration: none;\n}\n\n/* to make room for the icon, a width needs to be set here */\n.ui-button-icon-only {\n\twidth: 2em;\n\tbox-sizing: border-box;\n\ttext-indent: -9999px;\n\twhite-space: nowrap;\n}\n\n/* no icon support for input elements */\ninput.ui-button.ui-button-icon-only {\n\ttext-indent: 0;\n}\n\n/* button icon element(s) */\n.ui-button-icon-only .ui-icon {\n\tposition: absolute;\n\ttop: 50%;\n\tleft: 50%;\n\tmargin-top: -8px;\n\tmargin-left: -8px;\n}\n\n.ui-button.ui-icon-notext .ui-icon {\n\tpadding: 0;\n\twidth: 2.1em;\n\theight: 2.1em;\n\ttext-indent: -9999px;\n\twhite-space: nowrap;\n\n}\n\ninput.ui-button.ui-icon-notext .ui-icon {\n\twidth: auto;\n\theight: auto;\n\ttext-indent: 0;\n\twhite-space: normal;\n\tpadding: .4em 1em;\n}\n\n/* workarounds */\n/* Support: Firefox 5 - 40 */\ninput.ui-button::-moz-focus-inner,\nbutton.ui-button::-moz-focus-inner {\n\tborder: 0;\n\tpadding: 0;\n}\n", ""]);

// exports


/***/ }),
/* 212 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Checkboxradio 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/checkboxradio/#theming\n */\n\n.ui-checkboxradio-label .ui-icon-background {\n\tbox-shadow: inset 1px 1px 1px #ccc;\n\tborder-radius: .12em;\n\tborder: none;\n}\n.ui-checkboxradio-radio-label .ui-icon-background {\n\twidth: 16px;\n\theight: 16px;\n\tborder-radius: 1em;\n\toverflow: visible;\n\tborder: none;\n}\n.ui-checkboxradio-radio-label.ui-checkboxradio-checked .ui-icon,\n.ui-checkboxradio-radio-label.ui-checkboxradio-checked:hover .ui-icon {\n\tbackground-image: none;\n\twidth: 8px;\n\theight: 8px;\n\tborder-width: 4px;\n\tborder-style: solid;\n}\n.ui-checkboxradio-disabled {\n\tpointer-events: none;\n}\n", ""]);

// exports


/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Controlgroup 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/controlgroup/#theming\n */\n\n.ui-controlgroup {\n\tvertical-align: middle;\n\tdisplay: inline-block;\n}\n.ui-controlgroup > .ui-controlgroup-item {\n\tfloat: left;\n\tmargin-left: 0;\n\tmargin-right: 0;\n}\n.ui-controlgroup > .ui-controlgroup-item:focus,\n.ui-controlgroup > .ui-controlgroup-item.ui-visual-focus {\n\tz-index: 9999;\n}\n.ui-controlgroup-vertical > .ui-controlgroup-item {\n\tdisplay: block;\n\tfloat: none;\n\twidth: 100%;\n\tmargin-top: 0;\n\tmargin-bottom: 0;\n\ttext-align: left;\n}\n.ui-controlgroup-vertical .ui-controlgroup-item {\n\tbox-sizing: border-box;\n}\n.ui-controlgroup .ui-controlgroup-label {\n\tpadding: .4em 1em;\n}\n.ui-controlgroup .ui-controlgroup-label span {\n\tfont-size: 80%;\n}\n.ui-controlgroup-horizontal .ui-controlgroup-label + .ui-controlgroup-item {\n\tborder-left: none;\n}\n.ui-controlgroup-vertical .ui-controlgroup-label + .ui-controlgroup-item {\n\tborder-top: none;\n}\n.ui-controlgroup-horizontal .ui-controlgroup-label.ui-widget-content {\n\tborder-right: none;\n}\n.ui-controlgroup-vertical .ui-controlgroup-label.ui-widget-content {\n\tborder-bottom: none;\n}\n\n/* Spinner specific style fixes */\n.ui-controlgroup-vertical .ui-spinner-input {\n\n\t/* Support: IE8 only, Android < 4.4 only */\n\twidth: 75%;\n\twidth: calc( 100% - 2.4em );\n}\n.ui-controlgroup-vertical .ui-spinner .ui-spinner-up {\n\tborder-top-style: solid;\n}\n\n", ""]);

// exports


/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Datepicker 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/datepicker/#theming\n */\n.ui-datepicker {\n\twidth: 17em;\n\tpadding: .2em .2em 0;\n\tdisplay: none;\n}\n.ui-datepicker .ui-datepicker-header {\n\tposition: relative;\n\tpadding: .2em 0;\n}\n.ui-datepicker .ui-datepicker-prev,\n.ui-datepicker .ui-datepicker-next {\n\tposition: absolute;\n\ttop: 2px;\n\twidth: 1.8em;\n\theight: 1.8em;\n}\n.ui-datepicker .ui-datepicker-prev-hover,\n.ui-datepicker .ui-datepicker-next-hover {\n\ttop: 1px;\n}\n.ui-datepicker .ui-datepicker-prev {\n\tleft: 2px;\n}\n.ui-datepicker .ui-datepicker-next {\n\tright: 2px;\n}\n.ui-datepicker .ui-datepicker-prev-hover {\n\tleft: 1px;\n}\n.ui-datepicker .ui-datepicker-next-hover {\n\tright: 1px;\n}\n.ui-datepicker .ui-datepicker-prev span,\n.ui-datepicker .ui-datepicker-next span {\n\tdisplay: block;\n\tposition: absolute;\n\tleft: 50%;\n\tmargin-left: -8px;\n\ttop: 50%;\n\tmargin-top: -8px;\n}\n.ui-datepicker .ui-datepicker-title {\n\tmargin: 0 2.3em;\n\tline-height: 1.8em;\n\ttext-align: center;\n}\n.ui-datepicker .ui-datepicker-title select {\n\tfont-size: 1em;\n\tmargin: 1px 0;\n}\n.ui-datepicker select.ui-datepicker-month,\n.ui-datepicker select.ui-datepicker-year {\n\twidth: 45%;\n}\n.ui-datepicker table {\n\twidth: 100%;\n\tfont-size: .9em;\n\tborder-collapse: collapse;\n\tmargin: 0 0 .4em;\n}\n.ui-datepicker th {\n\tpadding: .7em .3em;\n\ttext-align: center;\n\tfont-weight: bold;\n\tborder: 0;\n}\n.ui-datepicker td {\n\tborder: 0;\n\tpadding: 1px;\n}\n.ui-datepicker td span,\n.ui-datepicker td a {\n\tdisplay: block;\n\tpadding: .2em;\n\ttext-align: right;\n\ttext-decoration: none;\n}\n.ui-datepicker .ui-datepicker-buttonpane {\n\tbackground-image: none;\n\tmargin: .7em 0 0 0;\n\tpadding: 0 .2em;\n\tborder-left: 0;\n\tborder-right: 0;\n\tborder-bottom: 0;\n}\n.ui-datepicker .ui-datepicker-buttonpane button {\n\tfloat: right;\n\tmargin: .5em .2em .4em;\n\tcursor: pointer;\n\tpadding: .2em .6em .3em .6em;\n\twidth: auto;\n\toverflow: visible;\n}\n.ui-datepicker .ui-datepicker-buttonpane button.ui-datepicker-current {\n\tfloat: left;\n}\n\n/* with multiple calendars */\n.ui-datepicker.ui-datepicker-multi {\n\twidth: auto;\n}\n.ui-datepicker-multi .ui-datepicker-group {\n\tfloat: left;\n}\n.ui-datepicker-multi .ui-datepicker-group table {\n\twidth: 95%;\n\tmargin: 0 auto .4em;\n}\n.ui-datepicker-multi-2 .ui-datepicker-group {\n\twidth: 50%;\n}\n.ui-datepicker-multi-3 .ui-datepicker-group {\n\twidth: 33.3%;\n}\n.ui-datepicker-multi-4 .ui-datepicker-group {\n\twidth: 25%;\n}\n.ui-datepicker-multi .ui-datepicker-group-last .ui-datepicker-header,\n.ui-datepicker-multi .ui-datepicker-group-middle .ui-datepicker-header {\n\tborder-left-width: 0;\n}\n.ui-datepicker-multi .ui-datepicker-buttonpane {\n\tclear: left;\n}\n.ui-datepicker-row-break {\n\tclear: both;\n\twidth: 100%;\n\tfont-size: 0;\n}\n\n/* RTL support */\n.ui-datepicker-rtl {\n\tdirection: rtl;\n}\n.ui-datepicker-rtl .ui-datepicker-prev {\n\tright: 2px;\n\tleft: auto;\n}\n.ui-datepicker-rtl .ui-datepicker-next {\n\tleft: 2px;\n\tright: auto;\n}\n.ui-datepicker-rtl .ui-datepicker-prev:hover {\n\tright: 1px;\n\tleft: auto;\n}\n.ui-datepicker-rtl .ui-datepicker-next:hover {\n\tleft: 1px;\n\tright: auto;\n}\n.ui-datepicker-rtl .ui-datepicker-buttonpane {\n\tclear: right;\n}\n.ui-datepicker-rtl .ui-datepicker-buttonpane button {\n\tfloat: left;\n}\n.ui-datepicker-rtl .ui-datepicker-buttonpane button.ui-datepicker-current,\n.ui-datepicker-rtl .ui-datepicker-group {\n\tfloat: right;\n}\n.ui-datepicker-rtl .ui-datepicker-group-last .ui-datepicker-header,\n.ui-datepicker-rtl .ui-datepicker-group-middle .ui-datepicker-header {\n\tborder-right-width: 0;\n\tborder-left-width: 1px;\n}\n\n/* Icons */\n.ui-datepicker .ui-icon {\n\tdisplay: block;\n\ttext-indent: -99999px;\n\toverflow: hidden;\n\tbackground-repeat: no-repeat;\n\tleft: .5em;\n\ttop: .3em;\n}\n", ""]);

// exports


/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Dialog 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/dialog/#theming\n */\n.ui-dialog {\n\tposition: absolute;\n\ttop: 0;\n\tleft: 0;\n\tpadding: .2em;\n\toutline: 0;\n}\n.ui-dialog .ui-dialog-titlebar {\n\tpadding: .4em 1em;\n\tposition: relative;\n}\n.ui-dialog .ui-dialog-title {\n\tfloat: left;\n\tmargin: .1em 0;\n\twhite-space: nowrap;\n\twidth: 90%;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n.ui-dialog .ui-dialog-titlebar-close {\n\tposition: absolute;\n\tright: .3em;\n\ttop: 50%;\n\twidth: 20px;\n\tmargin: -10px 0 0 0;\n\tpadding: 1px;\n\theight: 20px;\n}\n.ui-dialog .ui-dialog-content {\n\tposition: relative;\n\tborder: 0;\n\tpadding: .5em 1em;\n\tbackground: none;\n\toverflow: auto;\n}\n.ui-dialog .ui-dialog-buttonpane {\n\ttext-align: left;\n\tborder-width: 1px 0 0 0;\n\tbackground-image: none;\n\tmargin-top: .5em;\n\tpadding: .3em 1em .5em .4em;\n}\n.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset {\n\tfloat: right;\n}\n.ui-dialog .ui-dialog-buttonpane button {\n\tmargin: .5em .4em .5em 0;\n\tcursor: pointer;\n}\n.ui-dialog .ui-resizable-n {\n\theight: 2px;\n\ttop: 0;\n}\n.ui-dialog .ui-resizable-e {\n\twidth: 2px;\n\tright: 0;\n}\n.ui-dialog .ui-resizable-s {\n\theight: 2px;\n\tbottom: 0;\n}\n.ui-dialog .ui-resizable-w {\n\twidth: 2px;\n\tleft: 0;\n}\n.ui-dialog .ui-resizable-se,\n.ui-dialog .ui-resizable-sw,\n.ui-dialog .ui-resizable-ne,\n.ui-dialog .ui-resizable-nw {\n\twidth: 7px;\n\theight: 7px;\n}\n.ui-dialog .ui-resizable-se {\n\tright: 0;\n\tbottom: 0;\n}\n.ui-dialog .ui-resizable-sw {\n\tleft: 0;\n\tbottom: 0;\n}\n.ui-dialog .ui-resizable-ne {\n\tright: 0;\n\ttop: 0;\n}\n.ui-dialog .ui-resizable-nw {\n\tleft: 0;\n\ttop: 0;\n}\n.ui-draggable .ui-dialog-titlebar {\n\tcursor: move;\n}\n", ""]);

// exports


/***/ }),
/* 216 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Draggable 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n */\n.ui-draggable-handle {\n\t-ms-touch-action: none;\n\ttouch-action: none;\n}\n", ""]);

// exports


/***/ }),
/* 217 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Menu 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/menu/#theming\n */\n.ui-menu {\n\tlist-style: none;\n\tpadding: 0;\n\tmargin: 0;\n\tdisplay: block;\n\toutline: 0;\n}\n.ui-menu .ui-menu {\n\tposition: absolute;\n}\n.ui-menu .ui-menu-item {\n\tmargin: 0;\n\tcursor: pointer;\n\t/* support: IE10, see #8844 */\n\tlist-style-image: url(\"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7\");\n}\n.ui-menu .ui-menu-item-wrapper {\n\tposition: relative;\n\tpadding: 3px 1em 3px .4em;\n}\n.ui-menu .ui-menu-divider {\n\tmargin: 5px 0;\n\theight: 0;\n\tfont-size: 0;\n\tline-height: 0;\n\tborder-width: 1px 0 0 0;\n}\n.ui-menu .ui-state-focus,\n.ui-menu .ui-state-active {\n\tmargin: -1px;\n}\n\n/* icon support */\n.ui-menu-icons {\n\tposition: relative;\n}\n.ui-menu-icons .ui-menu-item-wrapper {\n\tpadding-left: 2em;\n}\n\n/* left-aligned */\n.ui-menu .ui-icon {\n\tposition: absolute;\n\ttop: 0;\n\tbottom: 0;\n\tleft: .2em;\n\tmargin: auto 0;\n}\n\n/* right-aligned */\n.ui-menu .ui-menu-icon {\n\tleft: auto;\n\tright: 0;\n}\n", ""]);

// exports


/***/ }),
/* 218 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Progressbar 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/progressbar/#theming\n */\n.ui-progressbar {\n\theight: 2em;\n\ttext-align: left;\n\toverflow: hidden;\n}\n.ui-progressbar .ui-progressbar-value {\n\tmargin: -1px;\n\theight: 100%;\n}\n.ui-progressbar .ui-progressbar-overlay {\n\tbackground: url(\"data:image/gif;base64,R0lGODlhKAAoAIABAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQJAQABACwAAAAAKAAoAAACkYwNqXrdC52DS06a7MFZI+4FHBCKoDeWKXqymPqGqxvJrXZbMx7Ttc+w9XgU2FB3lOyQRWET2IFGiU9m1frDVpxZZc6bfHwv4c1YXP6k1Vdy292Fb6UkuvFtXpvWSzA+HycXJHUXiGYIiMg2R6W459gnWGfHNdjIqDWVqemH2ekpObkpOlppWUqZiqr6edqqWQAAIfkECQEAAQAsAAAAACgAKAAAApSMgZnGfaqcg1E2uuzDmmHUBR8Qil95hiPKqWn3aqtLsS18y7G1SzNeowWBENtQd+T1JktP05nzPTdJZlR6vUxNWWjV+vUWhWNkWFwxl9VpZRedYcflIOLafaa28XdsH/ynlcc1uPVDZxQIR0K25+cICCmoqCe5mGhZOfeYSUh5yJcJyrkZWWpaR8doJ2o4NYq62lAAACH5BAkBAAEALAAAAAAoACgAAAKVDI4Yy22ZnINRNqosw0Bv7i1gyHUkFj7oSaWlu3ovC8GxNso5fluz3qLVhBVeT/Lz7ZTHyxL5dDalQWPVOsQWtRnuwXaFTj9jVVh8pma9JjZ4zYSj5ZOyma7uuolffh+IR5aW97cHuBUXKGKXlKjn+DiHWMcYJah4N0lYCMlJOXipGRr5qdgoSTrqWSq6WFl2ypoaUAAAIfkECQEAAQAsAAAAACgAKAAAApaEb6HLgd/iO7FNWtcFWe+ufODGjRfoiJ2akShbueb0wtI50zm02pbvwfWEMWBQ1zKGlLIhskiEPm9R6vRXxV4ZzWT2yHOGpWMyorblKlNp8HmHEb/lCXjcW7bmtXP8Xt229OVWR1fod2eWqNfHuMjXCPkIGNileOiImVmCOEmoSfn3yXlJWmoHGhqp6ilYuWYpmTqKUgAAIfkECQEAAQAsAAAAACgAKAAAApiEH6kb58biQ3FNWtMFWW3eNVcojuFGfqnZqSebuS06w5V80/X02pKe8zFwP6EFWOT1lDFk8rGERh1TTNOocQ61Hm4Xm2VexUHpzjymViHrFbiELsefVrn6XKfnt2Q9G/+Xdie499XHd2g4h7ioOGhXGJboGAnXSBnoBwKYyfioubZJ2Hn0RuRZaflZOil56Zp6iioKSXpUAAAh+QQJAQABACwAAAAAKAAoAAACkoQRqRvnxuI7kU1a1UU5bd5tnSeOZXhmn5lWK3qNTWvRdQxP8qvaC+/yaYQzXO7BMvaUEmJRd3TsiMAgswmNYrSgZdYrTX6tSHGZO73ezuAw2uxuQ+BbeZfMxsexY35+/Qe4J1inV0g4x3WHuMhIl2jXOKT2Q+VU5fgoSUI52VfZyfkJGkha6jmY+aaYdirq+lQAACH5BAkBAAEALAAAAAAoACgAAAKWBIKpYe0L3YNKToqswUlvznigd4wiR4KhZrKt9Upqip61i9E3vMvxRdHlbEFiEXfk9YARYxOZZD6VQ2pUunBmtRXo1Lf8hMVVcNl8JafV38aM2/Fu5V16Bn63r6xt97j09+MXSFi4BniGFae3hzbH9+hYBzkpuUh5aZmHuanZOZgIuvbGiNeomCnaxxap2upaCZsq+1kAACH5BAkBAAEALAAAAAAoACgAAAKXjI8By5zf4kOxTVrXNVlv1X0d8IGZGKLnNpYtm8Lr9cqVeuOSvfOW79D9aDHizNhDJidFZhNydEahOaDH6nomtJjp1tutKoNWkvA6JqfRVLHU/QUfau9l2x7G54d1fl995xcIGAdXqMfBNadoYrhH+Mg2KBlpVpbluCiXmMnZ2Sh4GBqJ+ckIOqqJ6LmKSllZmsoq6wpQAAAh+QQJAQABACwAAAAAKAAoAAAClYx/oLvoxuJDkU1a1YUZbJ59nSd2ZXhWqbRa2/gF8Gu2DY3iqs7yrq+xBYEkYvFSM8aSSObE+ZgRl1BHFZNr7pRCavZ5BW2142hY3AN/zWtsmf12p9XxxFl2lpLn1rseztfXZjdIWIf2s5dItwjYKBgo9yg5pHgzJXTEeGlZuenpyPmpGQoKOWkYmSpaSnqKileI2FAAACH5BAkBAAEALAAAAAAoACgAAAKVjB+gu+jG4kORTVrVhRlsnn2dJ3ZleFaptFrb+CXmO9OozeL5VfP99HvAWhpiUdcwkpBH3825AwYdU8xTqlLGhtCosArKMpvfa1mMRae9VvWZfeB2XfPkeLmm18lUcBj+p5dnN8jXZ3YIGEhYuOUn45aoCDkp16hl5IjYJvjWKcnoGQpqyPlpOhr3aElaqrq56Bq7VAAAOw==\");\n\theight: 100%;\n\t-ms-filter: \"alpha(opacity=25)\"; /* support: IE8 */\n\topacity: 0.25;\n}\n.ui-progressbar-indeterminate .ui-progressbar-value {\n\tbackground-image: none;\n}\n", ""]);

// exports


/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Resizable 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n */\n.ui-resizable {\n\tposition: relative;\n}\n.ui-resizable-handle {\n\tposition: absolute;\n\tfont-size: 0.1px;\n\tdisplay: block;\n\t-ms-touch-action: none;\n\ttouch-action: none;\n}\n.ui-resizable-disabled .ui-resizable-handle,\n.ui-resizable-autohide .ui-resizable-handle {\n\tdisplay: none;\n}\n.ui-resizable-n {\n\tcursor: n-resize;\n\theight: 7px;\n\twidth: 100%;\n\ttop: -5px;\n\tleft: 0;\n}\n.ui-resizable-s {\n\tcursor: s-resize;\n\theight: 7px;\n\twidth: 100%;\n\tbottom: -5px;\n\tleft: 0;\n}\n.ui-resizable-e {\n\tcursor: e-resize;\n\twidth: 7px;\n\tright: -5px;\n\ttop: 0;\n\theight: 100%;\n}\n.ui-resizable-w {\n\tcursor: w-resize;\n\twidth: 7px;\n\tleft: -5px;\n\ttop: 0;\n\theight: 100%;\n}\n.ui-resizable-se {\n\tcursor: se-resize;\n\twidth: 12px;\n\theight: 12px;\n\tright: 1px;\n\tbottom: 1px;\n}\n.ui-resizable-sw {\n\tcursor: sw-resize;\n\twidth: 9px;\n\theight: 9px;\n\tleft: -5px;\n\tbottom: -5px;\n}\n.ui-resizable-nw {\n\tcursor: nw-resize;\n\twidth: 9px;\n\theight: 9px;\n\tleft: -5px;\n\ttop: -5px;\n}\n.ui-resizable-ne {\n\tcursor: ne-resize;\n\twidth: 9px;\n\theight: 9px;\n\tright: -5px;\n\ttop: -5px;\n}\n", ""]);

// exports


/***/ }),
/* 220 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Selectable 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n */\n.ui-selectable {\n\t-ms-touch-action: none;\n\ttouch-action: none;\n}\n.ui-selectable-helper {\n\tposition: absolute;\n\tz-index: 100;\n\tborder: 1px dotted black;\n}\n", ""]);

// exports


/***/ }),
/* 221 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Selectmenu 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/selectmenu/#theming\n */\n.ui-selectmenu-menu {\n\tpadding: 0;\n\tmargin: 0;\n\tposition: absolute;\n\ttop: 0;\n\tleft: 0;\n\tdisplay: none;\n}\n.ui-selectmenu-menu .ui-menu {\n\toverflow: auto;\n\toverflow-x: hidden;\n\tpadding-bottom: 1px;\n}\n.ui-selectmenu-menu .ui-menu .ui-selectmenu-optgroup {\n\tfont-size: 1em;\n\tfont-weight: bold;\n\tline-height: 1.5;\n\tpadding: 2px 0.4em;\n\tmargin: 0.5em 0 0 0;\n\theight: auto;\n\tborder: 0;\n}\n.ui-selectmenu-open {\n\tdisplay: block;\n}\n.ui-selectmenu-text {\n\tdisplay: block;\n\tmargin-right: 20px;\n\toverflow: hidden;\n\ttext-overflow: ellipsis;\n}\n.ui-selectmenu-button.ui-button {\n\ttext-align: left;\n\twhite-space: nowrap;\n\twidth: 14em;\n}\n.ui-selectmenu-icon.ui-icon {\n\tfloat: right;\n\tmargin-top: 0;\n}\n", ""]);

// exports


/***/ }),
/* 222 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Sortable 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n */\n.ui-sortable-handle {\n\t-ms-touch-action: none;\n\ttouch-action: none;\n}\n", ""]);

// exports


/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Slider 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/slider/#theming\n */\n.ui-slider {\n\tposition: relative;\n\ttext-align: left;\n}\n.ui-slider .ui-slider-handle {\n\tposition: absolute;\n\tz-index: 2;\n\twidth: 1.2em;\n\theight: 1.2em;\n\tcursor: pointer;\n\t-ms-touch-action: none;\n\ttouch-action: none;\n}\n.ui-slider .ui-slider-range {\n\tposition: absolute;\n\tz-index: 1;\n\tfont-size: .7em;\n\tdisplay: block;\n\tborder: 0;\n\tbackground-position: 0 0;\n}\n\n/* support: IE8 - See #6727 */\n.ui-slider.ui-state-disabled .ui-slider-handle,\n.ui-slider.ui-state-disabled .ui-slider-range {\n\tfilter: inherit;\n}\n\n.ui-slider-horizontal {\n\theight: .8em;\n}\n.ui-slider-horizontal .ui-slider-handle {\n\ttop: -.3em;\n\tmargin-left: -.6em;\n}\n.ui-slider-horizontal .ui-slider-range {\n\ttop: 0;\n\theight: 100%;\n}\n.ui-slider-horizontal .ui-slider-range-min {\n\tleft: 0;\n}\n.ui-slider-horizontal .ui-slider-range-max {\n\tright: 0;\n}\n\n.ui-slider-vertical {\n\twidth: .8em;\n\theight: 100px;\n}\n.ui-slider-vertical .ui-slider-handle {\n\tleft: -.3em;\n\tmargin-left: 0;\n\tmargin-bottom: -.6em;\n}\n.ui-slider-vertical .ui-slider-range {\n\tleft: 0;\n\twidth: 100%;\n}\n.ui-slider-vertical .ui-slider-range-min {\n\tbottom: 0;\n}\n.ui-slider-vertical .ui-slider-range-max {\n\ttop: 0;\n}\n", ""]);

// exports


/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Spinner 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/spinner/#theming\n */\n.ui-spinner {\n\tposition: relative;\n\tdisplay: inline-block;\n\toverflow: hidden;\n\tpadding: 0;\n\tvertical-align: middle;\n}\n.ui-spinner-input {\n\tborder: none;\n\tbackground: none;\n\tcolor: inherit;\n\tpadding: .222em 0;\n\tmargin: .2em 0;\n\tvertical-align: middle;\n\tmargin-left: .4em;\n\tmargin-right: 2em;\n}\n.ui-spinner-button {\n\twidth: 1.6em;\n\theight: 50%;\n\tfont-size: .5em;\n\tpadding: 0;\n\tmargin: 0;\n\ttext-align: center;\n\tposition: absolute;\n\tcursor: default;\n\tdisplay: block;\n\toverflow: hidden;\n\tright: 0;\n}\n/* more specificity required here to override default borders */\n.ui-spinner a.ui-spinner-button {\n\tborder-top-style: none;\n\tborder-bottom-style: none;\n\tborder-right-style: none;\n}\n.ui-spinner-up {\n\ttop: 0;\n}\n.ui-spinner-down {\n\tbottom: 0;\n}\n", ""]);

// exports


/***/ }),
/* 225 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Tabs 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/tabs/#theming\n */\n.ui-tabs {\n\tposition: relative;/* position: relative prevents IE scroll bug (element with position: relative inside container with overflow: auto appear as \"fixed\") */\n\tpadding: .2em;\n}\n.ui-tabs .ui-tabs-nav {\n\tmargin: 0;\n\tpadding: .2em .2em 0;\n}\n.ui-tabs .ui-tabs-nav li {\n\tlist-style: none;\n\tfloat: left;\n\tposition: relative;\n\ttop: 0;\n\tmargin: 1px .2em 0 0;\n\tborder-bottom-width: 0;\n\tpadding: 0;\n\twhite-space: nowrap;\n}\n.ui-tabs .ui-tabs-nav .ui-tabs-anchor {\n\tfloat: left;\n\tpadding: .5em 1em;\n\ttext-decoration: none;\n}\n.ui-tabs .ui-tabs-nav li.ui-tabs-active {\n\tmargin-bottom: -1px;\n\tpadding-bottom: 1px;\n}\n.ui-tabs .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor,\n.ui-tabs .ui-tabs-nav li.ui-state-disabled .ui-tabs-anchor,\n.ui-tabs .ui-tabs-nav li.ui-tabs-loading .ui-tabs-anchor {\n\tcursor: text;\n}\n.ui-tabs-collapsible .ui-tabs-nav li.ui-tabs-active .ui-tabs-anchor {\n\tcursor: pointer;\n}\n.ui-tabs .ui-tabs-panel {\n\tdisplay: block;\n\tborder-width: 0;\n\tpadding: 1em 1.4em;\n\tbackground: none;\n}\n", ""]);

// exports


/***/ }),
/* 226 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI Tooltip 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/tooltip/#theming\n */\n.ui-tooltip {\n\tpadding: 8px;\n\tposition: absolute;\n\tz-index: 9999;\n\tmax-width: 300px;\n}\nbody .ui-tooltip {\n\tborder-width: 2px;\n}\n", ""]);

// exports


/***/ }),
/* 227 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports


// module
exports.push([module.i, "/*!\n * jQuery UI CSS Framework 1.13.2\n * http://jqueryui.com\n *\n * Copyright jQuery Foundation and other contributors\n * Released under the MIT license.\n * http://jquery.org/license\n *\n * http://api.jqueryui.com/category/theming/\n *\n * To view and modify this theme, visit http://jqueryui.com/themeroller/\n */\n\n\n/* Component containers\n----------------------------------*/\n.ui-widget {\n\tfont-family: Arial,Helvetica,sans-serif/*{ffDefault}*/;\n\tfont-size: 1em/*{fsDefault}*/;\n}\n.ui-widget .ui-widget {\n\tfont-size: 1em;\n}\n.ui-widget input,\n.ui-widget select,\n.ui-widget textarea,\n.ui-widget button {\n\tfont-family: Arial,Helvetica,sans-serif/*{ffDefault}*/;\n\tfont-size: 1em;\n}\n.ui-widget.ui-widget-content {\n\tborder: 1px solid #c5c5c5/*{borderColorDefault}*/;\n}\n.ui-widget-content {\n\tborder: 1px solid #dddddd/*{borderColorContent}*/;\n\tbackground: #ffffff/*{bgColorContent}*/ /*{bgImgUrlContent}*/ /*{bgContentXPos}*/ /*{bgContentYPos}*/ /*{bgContentRepeat}*/;\n\tcolor: #333333/*{fcContent}*/;\n}\n.ui-widget-content a {\n\tcolor: #333333/*{fcContent}*/;\n}\n.ui-widget-header {\n\tborder: 1px solid #dddddd/*{borderColorHeader}*/;\n\tbackground: #e9e9e9/*{bgColorHeader}*/ /*{bgImgUrlHeader}*/ /*{bgHeaderXPos}*/ /*{bgHeaderYPos}*/ /*{bgHeaderRepeat}*/;\n\tcolor: #333333/*{fcHeader}*/;\n\tfont-weight: bold;\n}\n.ui-widget-header a {\n\tcolor: #333333/*{fcHeader}*/;\n}\n\n/* Interaction states\n----------------------------------*/\n.ui-state-default,\n.ui-widget-content .ui-state-default,\n.ui-widget-header .ui-state-default,\n.ui-button,\n\n/* We use html here because we need a greater specificity to make sure disabled\nworks properly when clicked or hovered */\nhtml .ui-button.ui-state-disabled:hover,\nhtml .ui-button.ui-state-disabled:active {\n\tborder: 1px solid #c5c5c5/*{borderColorDefault}*/;\n\tbackground: #f6f6f6/*{bgColorDefault}*/ /*{bgImgUrlDefault}*/ /*{bgDefaultXPos}*/ /*{bgDefaultYPos}*/ /*{bgDefaultRepeat}*/;\n\tfont-weight: normal/*{fwDefault}*/;\n\tcolor: #454545/*{fcDefault}*/;\n}\n.ui-state-default a,\n.ui-state-default a:link,\n.ui-state-default a:visited,\na.ui-button,\na:link.ui-button,\na:visited.ui-button,\n.ui-button {\n\tcolor: #454545/*{fcDefault}*/;\n\ttext-decoration: none;\n}\n.ui-state-hover,\n.ui-widget-content .ui-state-hover,\n.ui-widget-header .ui-state-hover,\n.ui-state-focus,\n.ui-widget-content .ui-state-focus,\n.ui-widget-header .ui-state-focus,\n.ui-button:hover,\n.ui-button:focus {\n\tborder: 1px solid #cccccc/*{borderColorHover}*/;\n\tbackground: #ededed/*{bgColorHover}*/ /*{bgImgUrlHover}*/ /*{bgHoverXPos}*/ /*{bgHoverYPos}*/ /*{bgHoverRepeat}*/;\n\tfont-weight: normal/*{fwDefault}*/;\n\tcolor: #2b2b2b/*{fcHover}*/;\n}\n.ui-state-hover a,\n.ui-state-hover a:hover,\n.ui-state-hover a:link,\n.ui-state-hover a:visited,\n.ui-state-focus a,\n.ui-state-focus a:hover,\n.ui-state-focus a:link,\n.ui-state-focus a:visited,\na.ui-button:hover,\na.ui-button:focus {\n\tcolor: #2b2b2b/*{fcHover}*/;\n\ttext-decoration: none;\n}\n\n.ui-visual-focus {\n\tbox-shadow: 0 0 3px 1px rgb(94, 158, 214);\n}\n.ui-state-active,\n.ui-widget-content .ui-state-active,\n.ui-widget-header .ui-state-active,\na.ui-button:active,\n.ui-button:active,\n.ui-button.ui-state-active:hover {\n\tborder: 1px solid #003eff/*{borderColorActive}*/;\n\tbackground: #007fff/*{bgColorActive}*/ /*{bgImgUrlActive}*/ /*{bgActiveXPos}*/ /*{bgActiveYPos}*/ /*{bgActiveRepeat}*/;\n\tfont-weight: normal/*{fwDefault}*/;\n\tcolor: #ffffff/*{fcActive}*/;\n}\n.ui-icon-background,\n.ui-state-active .ui-icon-background {\n\tborder: #003eff/*{borderColorActive}*/;\n\tbackground-color: #ffffff/*{fcActive}*/;\n}\n.ui-state-active a,\n.ui-state-active a:link,\n.ui-state-active a:visited {\n\tcolor: #ffffff/*{fcActive}*/;\n\ttext-decoration: none;\n}\n\n/* Interaction Cues\n----------------------------------*/\n.ui-state-highlight,\n.ui-widget-content .ui-state-highlight,\n.ui-widget-header .ui-state-highlight {\n\tborder: 1px solid #dad55e/*{borderColorHighlight}*/;\n\tbackground: #fffa90/*{bgColorHighlight}*/ /*{bgImgUrlHighlight}*/ /*{bgHighlightXPos}*/ /*{bgHighlightYPos}*/ /*{bgHighlightRepeat}*/;\n\tcolor: #777620/*{fcHighlight}*/;\n}\n.ui-state-checked {\n\tborder: 1px solid #dad55e/*{borderColorHighlight}*/;\n\tbackground: #fffa90/*{bgColorHighlight}*/;\n}\n.ui-state-highlight a,\n.ui-widget-content .ui-state-highlight a,\n.ui-widget-header .ui-state-highlight a {\n\tcolor: #777620/*{fcHighlight}*/;\n}\n.ui-state-error,\n.ui-widget-content .ui-state-error,\n.ui-widget-header .ui-state-error {\n\tborder: 1px solid #f1a899/*{borderColorError}*/;\n\tbackground: #fddfdf/*{bgColorError}*/ /*{bgImgUrlError}*/ /*{bgErrorXPos}*/ /*{bgErrorYPos}*/ /*{bgErrorRepeat}*/;\n\tcolor: #5f3f3f/*{fcError}*/;\n}\n.ui-state-error a,\n.ui-widget-content .ui-state-error a,\n.ui-widget-header .ui-state-error a {\n\tcolor: #5f3f3f/*{fcError}*/;\n}\n.ui-state-error-text,\n.ui-widget-content .ui-state-error-text,\n.ui-widget-header .ui-state-error-text {\n\tcolor: #5f3f3f/*{fcError}*/;\n}\n.ui-priority-primary,\n.ui-widget-content .ui-priority-primary,\n.ui-widget-header .ui-priority-primary {\n\tfont-weight: bold;\n}\n.ui-priority-secondary,\n.ui-widget-content .ui-priority-secondary,\n.ui-widget-header .ui-priority-secondary {\n\topacity: .7;\n\t-ms-filter: \"alpha(opacity=70)\"; /* support: IE8 */\n\tfont-weight: normal;\n}\n.ui-state-disabled,\n.ui-widget-content .ui-state-disabled,\n.ui-widget-header .ui-state-disabled {\n\topacity: .35;\n\t-ms-filter: \"alpha(opacity=35)\"; /* support: IE8 */\n\tbackground-image: none;\n}\n.ui-state-disabled .ui-icon {\n\t-ms-filter: \"alpha(opacity=35)\"; /* support: IE8 - See #6059 */\n}\n\n/* Icons\n----------------------------------*/\n\n/* states and images */\n.ui-icon {\n\twidth: 16px;\n\theight: 16px;\n}\n.ui-icon,\n.ui-widget-content .ui-icon {\n\tbackground-image: url(" + __webpack_require__(108) + ");\n}\n.ui-widget-header .ui-icon {\n\tbackground-image: url(" + __webpack_require__(108) + ");\n}\n.ui-state-hover .ui-icon,\n.ui-state-focus .ui-icon,\n.ui-button:hover .ui-icon,\n.ui-button:focus .ui-icon {\n\tbackground-image: url(" + __webpack_require__(228) + ");\n}\n.ui-state-active .ui-icon,\n.ui-button:active .ui-icon {\n\tbackground-image: url(" + __webpack_require__(229) + ");\n}\n.ui-state-highlight .ui-icon,\n.ui-button .ui-state-highlight.ui-icon {\n\tbackground-image: url(" + __webpack_require__(230) + ");\n}\n.ui-state-error .ui-icon,\n.ui-state-error-text .ui-icon {\n\tbackground-image: url(" + __webpack_require__(231) + ");\n}\n.ui-button .ui-icon {\n\tbackground-image: url(" + __webpack_require__(232) + ");\n}\n\n/* positioning */\n/* Three classes needed to override `.ui-button:hover .ui-icon` */\n.ui-icon-blank.ui-icon-blank.ui-icon-blank {\n\tbackground-image: none;\n}\n.ui-icon-caret-1-n { background-position: 0 0; }\n.ui-icon-caret-1-ne { background-position: -16px 0; }\n.ui-icon-caret-1-e { background-position: -32px 0; }\n.ui-icon-caret-1-se { background-position: -48px 0; }\n.ui-icon-caret-1-s { background-position: -65px 0; }\n.ui-icon-caret-1-sw { background-position: -80px 0; }\n.ui-icon-caret-1-w { background-position: -96px 0; }\n.ui-icon-caret-1-nw { background-position: -112px 0; }\n.ui-icon-caret-2-n-s { background-position: -128px 0; }\n.ui-icon-caret-2-e-w { background-position: -144px 0; }\n.ui-icon-triangle-1-n { background-position: 0 -16px; }\n.ui-icon-triangle-1-ne { background-position: -16px -16px; }\n.ui-icon-triangle-1-e { background-position: -32px -16px; }\n.ui-icon-triangle-1-se { background-position: -48px -16px; }\n.ui-icon-triangle-1-s { background-position: -65px -16px; }\n.ui-icon-triangle-1-sw { background-position: -80px -16px; }\n.ui-icon-triangle-1-w { background-position: -96px -16px; }\n.ui-icon-triangle-1-nw { background-position: -112px -16px; }\n.ui-icon-triangle-2-n-s { background-position: -128px -16px; }\n.ui-icon-triangle-2-e-w { background-position: -144px -16px; }\n.ui-icon-arrow-1-n { background-position: 0 -32px; }\n.ui-icon-arrow-1-ne { background-position: -16px -32px; }\n.ui-icon-arrow-1-e { background-position: -32px -32px; }\n.ui-icon-arrow-1-se { background-position: -48px -32px; }\n.ui-icon-arrow-1-s { background-position: -65px -32px; }\n.ui-icon-arrow-1-sw { background-position: -80px -32px; }\n.ui-icon-arrow-1-w { background-position: -96px -32px; }\n.ui-icon-arrow-1-nw { background-position: -112px -32px; }\n.ui-icon-arrow-2-n-s { background-position: -128px -32px; }\n.ui-icon-arrow-2-ne-sw { background-position: -144px -32px; }\n.ui-icon-arrow-2-e-w { background-position: -160px -32px; }\n.ui-icon-arrow-2-se-nw { background-position: -176px -32px; }\n.ui-icon-arrowstop-1-n { background-position: -192px -32px; }\n.ui-icon-arrowstop-1-e { background-position: -208px -32px; }\n.ui-icon-arrowstop-1-s { background-position: -224px -32px; }\n.ui-icon-arrowstop-1-w { background-position: -240px -32px; }\n.ui-icon-arrowthick-1-n { background-position: 1px -48px; }\n.ui-icon-arrowthick-1-ne { background-position: -16px -48px; }\n.ui-icon-arrowthick-1-e { background-position: -32px -48px; }\n.ui-icon-arrowthick-1-se { background-position: -48px -48px; }\n.ui-icon-arrowthick-1-s { background-position: -64px -48px; }\n.ui-icon-arrowthick-1-sw { background-position: -80px -48px; }\n.ui-icon-arrowthick-1-w { background-position: -96px -48px; }\n.ui-icon-arrowthick-1-nw { background-position: -112px -48px; }\n.ui-icon-arrowthick-2-n-s { background-position: -128px -48px; }\n.ui-icon-arrowthick-2-ne-sw { background-position: -144px -48px; }\n.ui-icon-arrowthick-2-e-w { background-position: -160px -48px; }\n.ui-icon-arrowthick-2-se-nw { background-position: -176px -48px; }\n.ui-icon-arrowthickstop-1-n { background-position: -192px -48px; }\n.ui-icon-arrowthickstop-1-e { background-position: -208px -48px; }\n.ui-icon-arrowthickstop-1-s { background-position: -224px -48px; }\n.ui-icon-arrowthickstop-1-w { background-position: -240px -48px; }\n.ui-icon-arrowreturnthick-1-w { background-position: 0 -64px; }\n.ui-icon-arrowreturnthick-1-n { background-position: -16px -64px; }\n.ui-icon-arrowreturnthick-1-e { background-position: -32px -64px; }\n.ui-icon-arrowreturnthick-1-s { background-position: -48px -64px; }\n.ui-icon-arrowreturn-1-w { background-position: -64px -64px; }\n.ui-icon-arrowreturn-1-n { background-position: -80px -64px; }\n.ui-icon-arrowreturn-1-e { background-position: -96px -64px; }\n.ui-icon-arrowreturn-1-s { background-position: -112px -64px; }\n.ui-icon-arrowrefresh-1-w { background-position: -128px -64px; }\n.ui-icon-arrowrefresh-1-n { background-position: -144px -64px; }\n.ui-icon-arrowrefresh-1-e { background-position: -160px -64px; }\n.ui-icon-arrowrefresh-1-s { background-position: -176px -64px; }\n.ui-icon-arrow-4 { background-position: 0 -80px; }\n.ui-icon-arrow-4-diag { background-position: -16px -80px; }\n.ui-icon-extlink { background-position: -32px -80px; }\n.ui-icon-newwin { background-position: -48px -80px; }\n.ui-icon-refresh { background-position: -64px -80px; }\n.ui-icon-shuffle { background-position: -80px -80px; }\n.ui-icon-transfer-e-w { background-position: -96px -80px; }\n.ui-icon-transferthick-e-w { background-position: -112px -80px; }\n.ui-icon-folder-collapsed { background-position: 0 -96px; }\n.ui-icon-folder-open { background-position: -16px -96px; }\n.ui-icon-document { background-position: -32px -96px; }\n.ui-icon-document-b { background-position: -48px -96px; }\n.ui-icon-note { background-position: -64px -96px; }\n.ui-icon-mail-closed { background-position: -80px -96px; }\n.ui-icon-mail-open { background-position: -96px -96px; }\n.ui-icon-suitcase { background-position: -112px -96px; }\n.ui-icon-comment { background-position: -128px -96px; }\n.ui-icon-person { background-position: -144px -96px; }\n.ui-icon-print { background-position: -160px -96px; }\n.ui-icon-trash { background-position: -176px -96px; }\n.ui-icon-locked { background-position: -192px -96px; }\n.ui-icon-unlocked { background-position: -208px -96px; }\n.ui-icon-bookmark { background-position: -224px -96px; }\n.ui-icon-tag { background-position: -240px -96px; }\n.ui-icon-home { background-position: 0 -112px; }\n.ui-icon-flag { background-position: -16px -112px; }\n.ui-icon-calendar { background-position: -32px -112px; }\n.ui-icon-cart { background-position: -48px -112px; }\n.ui-icon-pencil { background-position: -64px -112px; }\n.ui-icon-clock { background-position: -80px -112px; }\n.ui-icon-disk { background-position: -96px -112px; }\n.ui-icon-calculator { background-position: -112px -112px; }\n.ui-icon-zoomin { background-position: -128px -112px; }\n.ui-icon-zoomout { background-position: -144px -112px; }\n.ui-icon-search { background-position: -160px -112px; }\n.ui-icon-wrench { background-position: -176px -112px; }\n.ui-icon-gear { background-position: -192px -112px; }\n.ui-icon-heart { background-position: -208px -112px; }\n.ui-icon-star { background-position: -224px -112px; }\n.ui-icon-link { background-position: -240px -112px; }\n.ui-icon-cancel { background-position: 0 -128px; }\n.ui-icon-plus { background-position: -16px -128px; }\n.ui-icon-plusthick { background-position: -32px -128px; }\n.ui-icon-minus { background-position: -48px -128px; }\n.ui-icon-minusthick { background-position: -64px -128px; }\n.ui-icon-close { background-position: -80px -128px; }\n.ui-icon-closethick { background-position: -96px -128px; }\n.ui-icon-key { background-position: -112px -128px; }\n.ui-icon-lightbulb { background-position: -128px -128px; }\n.ui-icon-scissors { background-position: -144px -128px; }\n.ui-icon-clipboard { background-position: -160px -128px; }\n.ui-icon-copy { background-position: -176px -128px; }\n.ui-icon-contact { background-position: -192px -128px; }\n.ui-icon-image { background-position: -208px -128px; }\n.ui-icon-video { background-position: -224px -128px; }\n.ui-icon-script { background-position: -240px -128px; }\n.ui-icon-alert { background-position: 0 -144px; }\n.ui-icon-info { background-position: -16px -144px; }\n.ui-icon-notice { background-position: -32px -144px; }\n.ui-icon-help { background-position: -48px -144px; }\n.ui-icon-check { background-position: -64px -144px; }\n.ui-icon-bullet { background-position: -80px -144px; }\n.ui-icon-radio-on { background-position: -96px -144px; }\n.ui-icon-radio-off { background-position: -112px -144px; }\n.ui-icon-pin-w { background-position: -128px -144px; }\n.ui-icon-pin-s { background-position: -144px -144px; }\n.ui-icon-play { background-position: 0 -160px; }\n.ui-icon-pause { background-position: -16px -160px; }\n.ui-icon-seek-next { background-position: -32px -160px; }\n.ui-icon-seek-prev { background-position: -48px -160px; }\n.ui-icon-seek-end { background-position: -64px -160px; }\n.ui-icon-seek-start { background-position: -80px -160px; }\n/* ui-icon-seek-first is deprecated, use ui-icon-seek-start instead */\n.ui-icon-seek-first { background-position: -80px -160px; }\n.ui-icon-stop { background-position: -96px -160px; }\n.ui-icon-eject { background-position: -112px -160px; }\n.ui-icon-volume-off { background-position: -128px -160px; }\n.ui-icon-volume-on { background-position: -144px -160px; }\n.ui-icon-power { background-position: 0 -176px; }\n.ui-icon-signal-diag { background-position: -16px -176px; }\n.ui-icon-signal { background-position: -32px -176px; }\n.ui-icon-battery-0 { background-position: -48px -176px; }\n.ui-icon-battery-1 { background-position: -64px -176px; }\n.ui-icon-battery-2 { background-position: -80px -176px; }\n.ui-icon-battery-3 { background-position: -96px -176px; }\n.ui-icon-circle-plus { background-position: 0 -192px; }\n.ui-icon-circle-minus { background-position: -16px -192px; }\n.ui-icon-circle-close { background-position: -32px -192px; }\n.ui-icon-circle-triangle-e { background-position: -48px -192px; }\n.ui-icon-circle-triangle-s { background-position: -64px -192px; }\n.ui-icon-circle-triangle-w { background-position: -80px -192px; }\n.ui-icon-circle-triangle-n { background-position: -96px -192px; }\n.ui-icon-circle-arrow-e { background-position: -112px -192px; }\n.ui-icon-circle-arrow-s { background-position: -128px -192px; }\n.ui-icon-circle-arrow-w { background-position: -144px -192px; }\n.ui-icon-circle-arrow-n { background-position: -160px -192px; }\n.ui-icon-circle-zoomin { background-position: -176px -192px; }\n.ui-icon-circle-zoomout { background-position: -192px -192px; }\n.ui-icon-circle-check { background-position: -208px -192px; }\n.ui-icon-circlesmall-plus { background-position: 0 -208px; }\n.ui-icon-circlesmall-minus { background-position: -16px -208px; }\n.ui-icon-circlesmall-close { background-position: -32px -208px; }\n.ui-icon-squaresmall-plus { background-position: -48px -208px; }\n.ui-icon-squaresmall-minus { background-position: -64px -208px; }\n.ui-icon-squaresmall-close { background-position: -80px -208px; }\n.ui-icon-grip-dotted-vertical { background-position: 0 -224px; }\n.ui-icon-grip-dotted-horizontal { background-position: -16px -224px; }\n.ui-icon-grip-solid-vertical { background-position: -32px -224px; }\n.ui-icon-grip-solid-horizontal { background-position: -48px -224px; }\n.ui-icon-gripsmall-diagonal-se { background-position: -64px -224px; }\n.ui-icon-grip-diagonal-se { background-position: -80px -224px; }\n\n\n/* Misc visuals\n----------------------------------*/\n\n/* Corner radius */\n.ui-corner-all,\n.ui-corner-top,\n.ui-corner-left,\n.ui-corner-tl {\n\tborder-top-left-radius: 3px/*{cornerRadius}*/;\n}\n.ui-corner-all,\n.ui-corner-top,\n.ui-corner-right,\n.ui-corner-tr {\n\tborder-top-right-radius: 3px/*{cornerRadius}*/;\n}\n.ui-corner-all,\n.ui-corner-bottom,\n.ui-corner-left,\n.ui-corner-bl {\n\tborder-bottom-left-radius: 3px/*{cornerRadius}*/;\n}\n.ui-corner-all,\n.ui-corner-bottom,\n.ui-corner-right,\n.ui-corner-br {\n\tborder-bottom-right-radius: 3px/*{cornerRadius}*/;\n}\n\n/* Overlays */\n.ui-widget-overlay {\n\tbackground: #aaaaaa/*{bgColorOverlay}*/ /*{bgImgUrlOverlay}*/ /*{bgOverlayXPos}*/ /*{bgOverlayYPos}*/ /*{bgOverlayRepeat}*/;\n\topacity: .3/*{opacityOverlay}*/;\n\t-ms-filter: \"alpha(opacity=30)\"/*{opacityFilterOverlay}*/; /* support: IE8 */\n}\n.ui-widget-shadow {\n\t-webkit-box-shadow: 0/*{offsetLeftShadow}*/ 0/*{offsetTopShadow}*/ 5px/*{thicknessShadow}*/ #666666/*{bgColorShadow}*/;\n\tbox-shadow: 0/*{offsetLeftShadow}*/ 0/*{offsetTopShadow}*/ 5px/*{thicknessShadow}*/ #666666/*{bgColorShadow}*/;\n}\n", ""]);

// exports


/***/ }),
/* 228 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "91b1966e761a8e0c0b83450f676e8fe4.png";

/***/ }),
/* 229 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "47d227801c1ad6c59d033bc151848c07.png";

/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "efbf84f0f6384f5c303ea15ebb299a08.png";

/***/ }),
/* 231 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "dd8125ead27254818e47e1a08814e83a.png";

/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "5e7882c25f80ead21c4b7fa3d8e7c1a3.png";

/***/ }),
/* 233 */
/***/ (function(module, exports) {

/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var stylesInDom = {},
	memoize = function(fn) {
		var memo;
		return function () {
			if (typeof memo === "undefined") memo = fn.apply(this, arguments);
			return memo;
		};
	},
	isOldIE = memoize(function() {
		return /msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase());
	}),
	getHeadElement = memoize(function () {
		return document.head || document.getElementsByTagName("head")[0];
	}),
	singletonElement = null,
	singletonCounter = 0,
	styleElementsInsertedAtTop = [];

module.exports = function(list, options) {
	if(typeof DEBUG !== "undefined" && DEBUG) {
		if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
	}

	options = options || {};
	// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
	// tags it will allow on a page
	if (typeof options.singleton === "undefined") options.singleton = isOldIE();

	// By default, add <style> tags to the bottom of <head>.
	if (typeof options.insertAt === "undefined") options.insertAt = "bottom";

	var styles = listToStyles(list);
	addStylesToDom(styles, options);

	return function update(newList) {
		var mayRemove = [];
		for(var i = 0; i < styles.length; i++) {
			var item = styles[i];
			var domStyle = stylesInDom[item.id];
			domStyle.refs--;
			mayRemove.push(domStyle);
		}
		if(newList) {
			var newStyles = listToStyles(newList);
			addStylesToDom(newStyles, options);
		}
		for(var i = 0; i < mayRemove.length; i++) {
			var domStyle = mayRemove[i];
			if(domStyle.refs === 0) {
				for(var j = 0; j < domStyle.parts.length; j++)
					domStyle.parts[j]();
				delete stylesInDom[domStyle.id];
			}
		}
	};
}

function addStylesToDom(styles, options) {
	for(var i = 0; i < styles.length; i++) {
		var item = styles[i];
		var domStyle = stylesInDom[item.id];
		if(domStyle) {
			domStyle.refs++;
			for(var j = 0; j < domStyle.parts.length; j++) {
				domStyle.parts[j](item.parts[j]);
			}
			for(; j < item.parts.length; j++) {
				domStyle.parts.push(addStyle(item.parts[j], options));
			}
		} else {
			var parts = [];
			for(var j = 0; j < item.parts.length; j++) {
				parts.push(addStyle(item.parts[j], options));
			}
			stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
		}
	}
}

function listToStyles(list) {
	var styles = [];
	var newStyles = {};
	for(var i = 0; i < list.length; i++) {
		var item = list[i];
		var id = item[0];
		var css = item[1];
		var media = item[2];
		var sourceMap = item[3];
		var part = {css: css, media: media, sourceMap: sourceMap};
		if(!newStyles[id])
			styles.push(newStyles[id] = {id: id, parts: [part]});
		else
			newStyles[id].parts.push(part);
	}
	return styles;
}

function insertStyleElement(options, styleElement) {
	var head = getHeadElement();
	var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
	if (options.insertAt === "top") {
		if(!lastStyleElementInsertedAtTop) {
			head.insertBefore(styleElement, head.firstChild);
		} else if(lastStyleElementInsertedAtTop.nextSibling) {
			head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
		} else {
			head.appendChild(styleElement);
		}
		styleElementsInsertedAtTop.push(styleElement);
	} else if (options.insertAt === "bottom") {
		head.appendChild(styleElement);
	} else {
		throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
	}
}

function removeStyleElement(styleElement) {
	styleElement.parentNode.removeChild(styleElement);
	var idx = styleElementsInsertedAtTop.indexOf(styleElement);
	if(idx >= 0) {
		styleElementsInsertedAtTop.splice(idx, 1);
	}
}

function createStyleElement(options) {
	var styleElement = document.createElement("style");
	styleElement.type = "text/css";
	insertStyleElement(options, styleElement);
	return styleElement;
}

function createLinkElement(options) {
	var linkElement = document.createElement("link");
	linkElement.rel = "stylesheet";
	insertStyleElement(options, linkElement);
	return linkElement;
}

function addStyle(obj, options) {
	var styleElement, update, remove;

	if (options.singleton) {
		var styleIndex = singletonCounter++;
		styleElement = singletonElement || (singletonElement = createStyleElement(options));
		update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
		remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true);
	} else if(obj.sourceMap &&
		typeof URL === "function" &&
		typeof URL.createObjectURL === "function" &&
		typeof URL.revokeObjectURL === "function" &&
		typeof Blob === "function" &&
		typeof btoa === "function") {
		styleElement = createLinkElement(options);
		update = updateLink.bind(null, styleElement);
		remove = function() {
			removeStyleElement(styleElement);
			if(styleElement.href)
				URL.revokeObjectURL(styleElement.href);
		};
	} else {
		styleElement = createStyleElement(options);
		update = applyToTag.bind(null, styleElement);
		remove = function() {
			removeStyleElement(styleElement);
		};
	}

	update(obj);

	return function updateStyle(newObj) {
		if(newObj) {
			if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap)
				return;
			update(obj = newObj);
		} else {
			remove();
		}
	};
}

var replaceText = (function () {
	var textStore = [];

	return function (index, replacement) {
		textStore[index] = replacement;
		return textStore.filter(Boolean).join('\n');
	};
})();

function applyToSingletonTag(styleElement, index, remove, obj) {
	var css = remove ? "" : obj.css;

	if (styleElement.styleSheet) {
		styleElement.styleSheet.cssText = replaceText(index, css);
	} else {
		var cssNode = document.createTextNode(css);
		var childNodes = styleElement.childNodes;
		if (childNodes[index]) styleElement.removeChild(childNodes[index]);
		if (childNodes.length) {
			styleElement.insertBefore(cssNode, childNodes[index]);
		} else {
			styleElement.appendChild(cssNode);
		}
	}
}

function applyToTag(styleElement, obj) {
	var css = obj.css;
	var media = obj.media;

	if(media) {
		styleElement.setAttribute("media", media)
	}

	if(styleElement.styleSheet) {
		styleElement.styleSheet.cssText = css;
	} else {
		while(styleElement.firstChild) {
			styleElement.removeChild(styleElement.firstChild);
		}
		styleElement.appendChild(document.createTextNode(css));
	}
}

function updateLink(linkElement, obj) {
	var css = obj.css;
	var sourceMap = obj.sourceMap;

	if(sourceMap) {
		// http://stackoverflow.com/a/26603875
		css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
	}

	var blob = new Blob([css], { type: "text/css" });

	var oldSrc = linkElement.href;

	linkElement.href = URL.createObjectURL(blob);

	if(oldSrc)
		URL.revokeObjectURL(oldSrc);
}


/***/ }),
/* 234 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * @file  Gui
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var NGL = __webpack_require__(18);
var UI = __webpack_require__(50).UI;
var signals = __webpack_require__(101);
HTMLElement.prototype.getBoundingClientRect = (function () {
    // workaround for ie11 behavior with disconnected dom nodes
    var _getBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
    return function getBoundingClientRect() {
        try {
            return _getBoundingClientRect.apply(this, arguments);
        }
        catch (e) {
            return {
                top: 0,
                left: 0,
                width: this.width,
                height: this.height
            };
        }
    };
}());
NGL.Widget = function () {
};
NGL.Widget.prototype = {
    constructor: NGL.Widget
};
NGL.createParameterInput = function (p, v) {
    if (!p)
        return;
    var value = v === undefined ? p.value : v;
    var input;
    if (p.type === 'number') {
        input = new UI.Number(0)
            .setRange(p.min, p.max)
            .setPrecision(p.precision)
            .setValue(parseFloat(value));
    }
    else if (p.type === 'integer') {
        input = new UI.Integer(parseInt(value))
            .setRange(p.min, p.max);
    }
    else if (p.type === 'range') {
        input = new UI.Range(p.min, p.max, value, p.step)
            .setValue(parseFloat(value));
    }
    else if (p.type === 'boolean') {
        input = new UI.Checkbox(value);
    }
    else if (p.type === 'text') {
        input = new UI.Input(value);
    }
    else if (p.type === 'select') {
        input = new UI.Select()
            .setWidth('')
            .setOptions(p.options)
            .setValue(value);
    }
    else if (p.type === 'color') {
        input = new UI.ColorPopupMenu(p.label)
            .setValue(value);
    }
    else if (p.type === 'vector3') {
        input = new UI.Vector3(value)
            .setPrecision(p.precision);
    }
    else if (p.type === 'hidden') {
        // nothing to display
    }
    else {
        console.warn('NGL.createParameterInput: unknown parameter type ' +
            "'" + p.type + "'");
    }
    return input;
};
/// /////////////
// Preferences
NGL.Preferences = function (id, defaultParams) {
    this.signals = {
        keyChanged: new signals.Signal()
    };
    this.id = id || 'ngl-gui';
    var dp = Object.assign({}, defaultParams);
    this.storage = {
        impostor: true,
        quality: 'auto',
        sampleLevel: 0,
        theme: 'dark',
        backgroundColor: 'black',
        overview: false,
        rotateSpeed: 2.0,
        zoomSpeed: 1.2,
        panSpeed: 0.8,
        clipNear: 0,
        clipFar: 100,
        clipDist: 10,
        fogNear: 50,
        fogFar: 100,
        cameraFov: 40,
        cameraType: 'perspective',
        lightColor: 0xdddddd,
        lightIntensity: 1.0,
        ambientColor: 0xdddddd,
        ambientIntensity: 0.2,
        hoverTimeout: 0
    };
    // overwrite default values with params
    for (var key in this.storage) {
        if (dp[key] !== undefined) {
            this.storage[key] = dp[key];
        }
    }
};
NGL.Preferences.prototype = {
    constructor: NGL.Preferences,
    getKey: function (key) {
        return this.storage[key];
    },
    setKey: function (key, value) {
        this.storage[key] = value;
        this.signals.keyChanged.dispatch(key, value);
    },
};
// Stage
class StageWidget {
    constructor(view) {
        // view: NGLView of NGLModel
        var el;
        var stage = view.stage;
        var viewport = new UI.Panel();
        if (view.options.parent) {
            el = view.el.parentElement;
        }
        else {
            el = view.el;
        }
        viewport.setPosition("absolute");
        viewport.dom = stage.viewer.container;
        this.el = el;
        this.widgetList = [];
        // Turn off in Jupyter notebook so user can run the next cell.
        // ensure initial focus on viewer canvas for key-stroke listening
        // stage.viewer.renderer.domElement.focus()
        var preferences = new NGL.Preferences('ngl-stage-widget', stage.getParameters());
        var pp = {};
        for (var name in preferences.storage) {
            pp[name] = preferences.getKey(name);
        }
        stage.setParameters(pp);
        preferences.signals.keyChanged.add(function (key, value) {
            var sp = {};
            sp[key] = value;
            stage.setParameters(sp);
            // FIXME: remove?
            // if (key === 'theme') {
            //   setTheme(value)
            // }
        }, this);
        //
        var cssLinkElement = document.createElement('link');
        cssLinkElement.rel = 'stylesheet';
        cssLinkElement.id = 'theme';
        function setTheme(value) {
            var cssPath, bgColor;
            if (value === 'light') {
                cssPath = NGL.cssDirectory + 'light.css';
                bgColor = 'white';
            }
            else {
                cssPath = NGL.cssDirectory + 'dark.css';
                bgColor = 'black';
            }
            cssLinkElement.href = cssPath;
            stage.setParameters({ backgroundColor: bgColor });
        }
        // FIXME: remove?
        // setTheme(preferences.getKey('theme'))
        el.appendChild(cssLinkElement);
        var toolbar = new NGL.ToolbarWidget(stage).setId('toolbar_ngl');
        el.appendChild(toolbar.dom);
        var menubar = new NGL.MenubarWidget(stage, preferences).setId('menubar_ngl');
        el.appendChild(menubar.dom);
        var sidebar = new NGL.SidebarWidget(stage).setId('sidebar_ngl');
        el.appendChild(sidebar.dom);
        this.widgetList.push(toolbar);
        this.widgetList.push(menubar);
        this.widgetList.push(sidebar);
        //
        // el.body.style.touchAction = 'none'
        el.style.touchAction = 'none';
        //
        stage.handleResize();
        // FIXME hack for ie11
        setTimeout(function () { stage.handleResize(); }, 500);
        //
        var doResizeLeft = false;
        var movedResizeLeft = false;
        var minResizeLeft = false;
        var handleResizeInNotebook;
        var handleResizeLeft = function (clientX) {
            if (clientX >= 50 && clientX <= window.innerWidth - 10) {
                sidebar.setWidth(window.innerWidth - clientX + 'px');
                viewport.setWidth(clientX + 'px');
                toolbar.setWidth(clientX + 'px');
                stage.handleResize();
            }
            var sidebarWidth = sidebar.dom.getBoundingClientRect().width;
            if (clientX === undefined) {
                var mainWidth = window.innerWidth - sidebarWidth;
                viewport.setWidth(mainWidth + 'px');
                toolbar.setWidth(mainWidth + 'px');
                stage.handleResize();
            }
            if (sidebarWidth <= 10) {
                minResizeLeft = true;
            }
            else {
                minResizeLeft = false;
            }
            handleResizeInNotebook();
        };
        handleResizeLeft = NGL.throttle(handleResizeLeft, 50, { leading: true, trailing: true });
        var handleResizeInNotebook = function () {
            // FIXME
            var sw = sidebar.dom.getBoundingClientRect().width;
            var ew = el.getBoundingClientRect().width;
            if (ew == sw) {
                sw = ew / 4;
            }
            var w = ew - sw + 'px';
            stage.viewer.container.style.width = w;
            stage.handleResize();
        };
        var resizeLeft = new UI.Panel()
            .setClass('ResizeLeft')
            .onMouseDown(function () {
            doResizeLeft = true;
            movedResizeLeft = false;
        })
            .onClick(function () {
            if (minResizeLeft) {
                handleResizeLeft(window.innerWidth - 300);
            }
            else if (!doResizeLeft && !movedResizeLeft) {
                handleResizeLeft(window.innerWidth - 10);
            }
        });
        sidebar.add(resizeLeft);
        this.viewport = viewport;
        this.toolbar = toolbar;
        this.menubar = menubar;
        this.sidebar = sidebar;
        handleResizeInNotebook();
        stage.signals.fullscreenChanged.add(function (isFullscreen) {
            const box = stage.viewer.container.parentElement.getBoundingClientRect();
            stage.setSize(box.width + "px", isFullscreen ? box.height + 'px' : '300px');
            view.handleResize();
        });
        window.addEventListener('mousemove', function (event) {
            if (doResizeLeft) {
                document.body.style.cursor = 'col-resize';
                movedResizeLeft = true;
                handleResizeLeft(event.clientX);
            }
        }, false);
        window.addEventListener('mouseup', function (event) {
            doResizeLeft = false;
            document.body.style.cursor = '';
        }, false);
        window.addEventListener('resize', function (event) {
            handleResizeLeft();
        }, false);
        //
        document.addEventListener('dragover', function (e) {
            e.stopPropagation();
            e.preventDefault();
            e.dataTransfer.dropEffect = 'none';
        }, false);
        document.addEventListener('drop', function (e) {
            e.stopPropagation();
            e.preventDefault();
        }, false);
    }
    dispose() {
        for (var i in this.widgetList) {
            this.widgetList[i].dispose();
        }
    }
}
// Viewport
NGL.ViewportWidget = function (stage) {
    var viewer = stage.viewer;
    var renderer = viewer.renderer;
    var container = new UI.Panel();
    container.dom = viewer.container;
    container.setPosition('absolute');
    var fileTypesOpen = NGL.flatten([
        NGL.ParserRegistry.getStructureExtensions(),
        NGL.ParserRegistry.getVolumeExtensions(),
        NGL.ParserRegistry.getSurfaceExtensions(),
        NGL.DecompressorRegistry.names
    ]);
    // event handlers
    container.dom.addEventListener('dragover', function (e) {
        e.stopPropagation();
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';
    }, false);
    container.dom.addEventListener('drop', function (e) {
        e.stopPropagation();
        e.preventDefault();
        var fn = function (file, callback) {
            var ext = file.name.split('.').pop().toLowerCase();
            if (NGL.ScriptExtensions.includes(ext)) {
                stage.loadScript(file).then(callback);
            }
            else if (fileTypesOpen.includes(ext)) {
                stage.loadFile(file, { defaultRepresentation: true }).then(callback);
            }
            else {
                console.error('unknown filetype: ' + ext);
                callback();
            }
        };
        var queue = new NGL.Queue(fn, e.dataTransfer.files);
    }, false);
    return container;
};
// Toolbar
NGL.ToolbarWidget = function (stage) {
    var container = new UI.Panel();
    var messageText = new UI.Text();
    var messagePanel = new UI.Panel()
        .setDisplay('inline')
        .setFloat('left')
        .add(messageText);
    var statsText = new UI.Text();
    var statsPanel = new UI.Panel()
        .setDisplay('inline')
        .setFloat('right')
        .add(statsText);
    stage.signals.clicked.add(function (pickingProxy) {
        messageText.setValue(pickingProxy ? pickingProxy.getLabel() : 'nothing');
    });
    stage.viewer.stats.signals.updated.add(function () {
        if (NGL.Debug) {
            statsText.setValue(stage.viewer.stats.lastDuration.toFixed(2) + ' ms | ' +
                stage.viewer.stats.lastFps + ' fps');
        }
        else {
            statsText.setValue('');
        }
    });
    container.add(messagePanel, statsPanel);
    return container;
};
// Menubar
NGL.MenubarWidget = function (stage, preferences) {
    var container = new UI.Panel();
    container.add(new NGL.MenubarFileWidget(stage));
    container.add(new NGL.MenubarViewWidget(stage, preferences));
    if (NGL.examplesListUrl && NGL.examplesScriptUrl) {
        container.add(new NGL.MenubarExamplesWidget(stage));
    }
    container.add(new NGL.MenubarHelpWidget(stage, preferences));
    container.add(new UI.Panel().setClass('menu').setFloat('right').add(new UI.Text('NGL Viewer ' + NGL.Version).setClass('title')));
    return container;
};
NGL.MenubarFileWidget = function (stage) {
    var fileTypesOpen = NGL.flatten([
        NGL.ParserRegistry.getStructureExtensions(),
        NGL.ParserRegistry.getVolumeExtensions(),
        NGL.ParserRegistry.getSurfaceExtensions(),
        NGL.DecompressorRegistry.names,
        NGL.ScriptExtensions
    ]);
    function fileInputOnChange(e) {
        var fn = function (file, callback) {
            var ext = file.name.split('.').pop().toLowerCase();
            if (NGL.ScriptExtensions.includes(ext)) {
                stage.loadScript(file).then(callback);
            }
            else if (fileTypesOpen.includes(ext)) {
                stage.loadFile(file, { defaultRepresentation: true }).then(callback);
            }
            else {
                console.error('unknown filetype: ' + ext);
                callback();
            }
        };
        var queue = new NGL.Queue(fn, e.target.files);
    }
    var fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.multiple = true;
    fileInput.style.display = 'none';
    fileInput.accept = '.' + fileTypesOpen.join(',.');
    fileInput.addEventListener('change', fileInputOnChange, false);
    // export image
    var exportImageWidget = new NGL.ExportImageWidget(stage)
        .setDisplay('none')
        .attach(stage.viewer.container.parentElement);
    // event handlers
    function onOpenOptionClick() {
        fileInput.click();
    }
    function onImportOptionClick() {
        var dirWidget;
        function onListingClick(info) {
            var ext = info.path.split('.').pop().toLowerCase();
            if (NGL.ScriptExtensions.includes(ext)) {
                stage.loadScript(NGL.ListingDatasource.getUrl(info.path));
                dirWidget.dispose();
            }
            else if (fileTypesOpen.includes(ext)) {
                stage.loadFile(NGL.ListingDatasource.getUrl(info.path), {
                    defaultRepresentation: true
                });
                dirWidget.dispose();
            }
            else {
                console.error('unknown filetype: ' + ext);
            }
        }
        dirWidget = new NGL.DirectoryListingWidget(NGL.ListingDatasource, stage, 'Import file', fileTypesOpen, onListingClick);
        dirWidget
            .setOpacity('0.9')
            .setLeft('50px')
            .setTop('80px')
            .attach();
    }
    function onExportImageOptionClick() {
        exportImageWidget
            .setOpacity('0.9')
            .setLeft('50px')
            .setTop('80px')
            .setDisplay('block');
    }
    function onScreenshotOptionClick() {
        stage.makeImage({
            factor: 1,
            antialias: true,
            trim: false,
            transparent: false
        }).then(function (blob) {
            NGL.download(blob, 'screenshot.png');
        });
    }
    function onPdbInputKeyDown(e) {
        if (e.keyCode === 13) {
            stage.loadFile('rcsb://' + e.target.value.trim(), {
                defaultRepresentation: true
            });
            e.target.value = '';
        }
    }
    function onFirstModelOnlyChange(e) {
        stage.defaultFileParams.firstModelOnly = e.target.checked;
    }
    function onCAlphaOnlyChange(e) {
        stage.defaultFileParams.cAlphaOnly = e.target.checked;
    }
    // configure menu contents
    var createOption = UI.MenubarHelper.createOption;
    var createInput = UI.MenubarHelper.createInput;
    var createCheckbox = UI.MenubarHelper.createCheckbox;
    var createDivider = UI.MenubarHelper.createDivider;
    var menuConfig = [
        createOption('Open...', onOpenOptionClick),
        createInput('PDB', onPdbInputKeyDown),
        createCheckbox('firstModelOnly', false, onFirstModelOnlyChange),
        createCheckbox('cAlphaOnly', false, onCAlphaOnlyChange),
        createDivider(),
        createOption('Screenshot', onScreenshotOptionClick, 'camera'),
        createOption('Export image...', onExportImageOptionClick)
    ];
    if (NGL.ListingDatasource) {
        menuConfig.splice(1, 0, createOption('Import...', onImportOptionClick));
    }
    var optionsPanel = UI.MenubarHelper.createOptionsPanel(menuConfig);
    optionsPanel.dom.appendChild(fileInput);
    return UI.MenubarHelper.createMenuContainer('File', optionsPanel);
};
NGL.MenubarViewWidget = function (stage, preferences) {
    // event handlers
    function onLightThemeOptionClick() {
        preferences.setKey('theme', 'light');
    }
    function onDarkThemeOptionClick() {
        preferences.setKey('theme', 'dark');
    }
    function onPerspectiveCameraOptionClick() {
        stage.setParameters({ cameraType: 'perspective' });
    }
    function onOrthographicCameraOptionClick() {
        stage.setParameters({ cameraType: 'orthographic' });
    }
    function onStereoCameraOptionClick() {
        stage.setParameters({ cameraType: 'stereo' });
    }
    function onFullScreenOptionClick() {
        stage.toggleFullscreen(stage.viewer.container.parentElement);
    }
    function onCenterOptionClick() {
        stage.autoView(1000);
    }
    function onToggleSpinClick() {
        stage.toggleSpin();
    }
    function onToggleRockClick() {
        stage.toggleRock();
    }
    function onGetOrientationClick() {
        window.prompt('Get orientation', JSON.stringify(stage.viewerControls.getOrientation().toArray(), function (k, v) {
            return v.toFixed ? Number(v.toFixed(2)) : v;
        }));
    }
    function onSetOrientationClick() {
        stage.viewerControls.orient(JSON.parse(window.prompt('Set orientation')));
    }
    var that = this;
    stage.signals.fullscreenChanged.add(function (isFullscreen) {
        // const box = stage.viewer.container.parentElement.getBoundingClientRect()
        // stage.setSize(box.width+"px", box.height+"px")
        // stage.handleResize()
        var icon = menuConfig[4].children[0];
        if (isFullscreen) {
            icon.switchClass('compress', 'expand');
        }
        else {
            icon.switchClass('expand', 'compress');
        }
    });
    // configure menu contents
    var createOption = UI.MenubarHelper.createOption;
    var createDivider = UI.MenubarHelper.createDivider;
    var menuConfig = [
        // createOption('Light theme', onLightThemeOptionClick),
        // createOption('Dark theme', onDarkThemeOptionClick),
        // createDivider(),
        createOption('Perspective', onPerspectiveCameraOptionClick),
        createOption('Orthographic', onOrthographicCameraOptionClick),
        createOption('Stereo', onStereoCameraOptionClick),
        createDivider(),
        createOption('Full screen', onFullScreenOptionClick, 'expand'),
        createOption('Center', onCenterOptionClick, 'bullseye'),
        createDivider(),
        createOption('Toggle spin', onToggleSpinClick),
        createOption('Toggle rock', onToggleRockClick),
    ];
    var optionsPanel = UI.MenubarHelper.createOptionsPanel(menuConfig);
    return UI.MenubarHelper.createMenuContainer('View', optionsPanel);
};
NGL.MenubarExamplesWidget = function (stage) {
    // configure menu contents
    var createOption = UI.MenubarHelper.createOption;
    var optionsPanel = UI.MenubarHelper.createOptionsPanel([]);
    optionsPanel.setWidth('300px');
    var xhr = new XMLHttpRequest();
    xhr.open('GET', NGL.examplesListUrl);
    xhr.responseType = 'json';
    xhr.onload = function (e) {
        var response = this.response;
        if (typeof response === 'string') {
            // for ie11
            response = JSON.parse(response);
        }
        response.sort().forEach(function (name) {
            var option = createOption(name, function () {
                stage.loadScript(NGL.examplesScriptUrl + name + '.js');
            });
            optionsPanel.add(option);
        });
    };
    xhr.send();
    return UI.MenubarHelper.createMenuContainer('Examples', optionsPanel);
};
NGL.MenubarHelpWidget = function (stage, preferences) {
    // event handlers
    function onOverviewOptionClick() {
        overviewWidget
            .setOpacity('0.9')
            .setDisplay('block')
            .setWidgetPosition(50, 80);
    }
    function onDocOptionClick() {
        window.open(NGL.documentationUrl, '_blank');
    }
    function onDebugOnClick() {
        NGL.setDebug(true);
        stage.viewer.updateHelper();
        stage.viewer.requestRender();
    }
    function onDebugOffClick() {
        NGL.setDebug(false);
        stage.viewer.updateHelper();
        stage.viewer.requestRender();
    }
    function onPreferencesOptionClick() {
        preferencesWidget
            .setOpacity('0.9')
            .setDisplay('block')
            .setWidgetPosition(50, 80);
    }
    // export image
    var preferencesWidget = new NGL.PreferencesWidget(stage, preferences)
        .setDisplay('none')
        .attach(stage.viewer.container.parentElement);
    // overview
    var overviewWidget = new NGL.OverviewWidget(stage, preferences)
        .setDisplay('none')
        .attach(stage.viewer.container.parentElement);
    if (preferences.getKey('overview')) {
        onOverviewOptionClick();
    }
    // configure menu contents
    var createOption = UI.MenubarHelper.createOption;
    var createDivider = UI.MenubarHelper.createDivider;
    var menuConfig = [
        createOption('Overview', onOverviewOptionClick),
        // createOption('Documentation', onDocOptionClick),
        // createDivider(),
        // createOption('Debug on', onDebugOnClick),
        // createOption('Debug off', onDebugOffClick),
        // createDivider(),
        createOption('Preferences', onPreferencesOptionClick, 'sliders')
    ];
    var optionsPanel = UI.MenubarHelper.createOptionsPanel(menuConfig);
    return UI.MenubarHelper.createMenuContainer('Help', optionsPanel);
};
// Overview
NGL.OverviewWidget = function (stage, preferences) {
    var container = new UI.OverlayPanel();
    var xOffset = 0;
    var yOffset = 0;
    var prevX = 0;
    var prevY = 0;
    function onMousemove(e) {
        if (prevX === 0) {
            prevX = e.clientX;
            prevY = e.clientY;
        }
        xOffset -= prevX - e.clientX;
        yOffset -= prevY - e.clientY;
        prevX = e.clientX;
        prevY = e.clientY;
        container.dom.style.top = yOffset + 'px';
        container.dom.style.left = xOffset + 'px';
    }
    function setWidgetPosition(left, top) {
        xOffset = left;
        yOffset = top;
        prevX = 0;
        prevY = 0;
        container.dom.style.top = yOffset + 'px';
        container.dom.style.left = xOffset + 'px';
    }
    container.setWidgetPosition = setWidgetPosition;
    var headingPanel = new UI.Panel()
        .setBorderBottom('1px solid #555')
        .setHeight('25px')
        .setCursor('move')
        .onMouseDown(function (e) {
        if (e.which === 1) {
            document.addEventListener('mousemove', onMousemove);
        }
        document.addEventListener('mouseup', function (e) {
            document.removeEventListener('mousemove', onMousemove);
        });
    });
    var listingPanel = new UI.Panel()
        .setMarginTop('10px')
        .setMinHeight('100px')
        .setMaxHeight('500px')
        .setMaxWidth('600px')
        .setOverflow('auto');
    headingPanel.add(new UI.Text('NGL Viewer').setFontStyle('italic'), new UI.Html('&nbsp;&mdash;&nbsp;Overview'));
    headingPanel.add(new UI.Icon('times')
        .setCursor('pointer')
        .setMarginLeft('20px')
        .setFloat('right')
        .onClick(function () {
        container.setDisplay('none');
    }));
    container.add(headingPanel);
    container.add(listingPanel);
    //
    function addIcon(name, text) {
        var panel = new UI.Panel();
        var icon = new UI.Icon(name)
            .setWidth('20px')
            .setFloat('left');
        var label = new UI.Text(text)
            .setDisplay('inline')
            .setMarginLeft('5px');
        panel
            .setMarginLeft('20px')
            .add(icon, label);
        listingPanel.add(panel);
    }
    listingPanel
        .add(new UI.Panel().add(new UI.Html("To load a new structure use the <i>File</i> menu in the top left via drag'n'drop.")))
        .add(new UI.Break());
    listingPanel
        .add(new UI.Panel().add(new UI.Text('A number of clickable icons provide common actions. Most icons can be clicked on, just try it or hover the mouse pointer over it to see a tooltip.')))
        .add(new UI.Break());
    addIcon('eye', 'Controls the visibility of a component.');
    addIcon('trash-o', 'Deletes a component. Note that a second click is required to confirm the action.');
    addIcon('bullseye', 'Centers a component.');
    addIcon('bars', 'Opens a menu with further options.');
    addIcon('square', 'Opens a menu with coloring options.');
    addIcon('filter', 'Indicates atom-selection input fields.');
    listingPanel
        .add(new UI.Text('Mouse controls'))
        .add(new UI.Html('<ul>' +
        '<li>Left button hold and move to rotate camera around center.</li>' +
        '<li>Left button click to pick atom.</li>' +
        '<li>Middle button hold and move to zoom camera in and out.</li>' +
        '<li>Middle button click to center camera on atom.</li>' +
        '<li>Right button hold and move to translate camera in the screen plane.</li>' +
        '</ul>'));
    listingPanel
        .add(new UI.Panel().add(new UI.Html('For more information please visit the ' +
        "<a href='" + NGL.documentationUrl + "' target='_blank'>documentation pages</a>.")));
    var overview = preferences.getKey('overview');
    var showOverviewCheckbox = new UI.Checkbox(overview)
        .onClick(function () {
        preferences.setKey('overview', showOverviewCheckbox.getValue());
    });
    listingPanel
        .add(new UI.HorizontalRule()
        .setBorderTop('1px solid #555')
        .setMarginTop('15px'))
        .add(new UI.Panel().add(showOverviewCheckbox, new UI.Text('Show on startup. Always available from Menu > Help > Overview.').setMarginLeft('5px')));
    return container;
};
// Preferences
NGL.PreferencesWidget = function (stage, preferences) {
    var container = new UI.OverlayPanel();
    var xOffset = 0;
    var yOffset = 0;
    var prevX = 0;
    var prevY = 0;
    function onMousemove(e) {
        if (prevX === 0) {
            prevX = e.clientX;
            prevY = e.clientY;
        }
        xOffset -= prevX - e.clientX;
        yOffset -= prevY - e.clientY;
        prevX = e.clientX;
        prevY = e.clientY;
        container.dom.style.top = yOffset + 'px';
        container.dom.style.left = xOffset + 'px';
    }
    function setWidgetPosition(left, top) {
        xOffset = left;
        yOffset = top;
        prevX = 0;
        prevY = 0;
        container.dom.style.top = yOffset + 'px';
        container.dom.style.left = xOffset + 'px';
    }
    container.setWidgetPosition = setWidgetPosition;
    var headingPanel = new UI.Panel()
        .setBorderBottom('1px solid #555')
        .setHeight('25px')
        .setCursor('move')
        .onMouseDown(function (e) {
        if (e.which === 1) {
            document.addEventListener('mousemove', onMousemove);
        }
        document.addEventListener('mouseup', function (e) {
            document.removeEventListener('mousemove', onMousemove);
        });
    });
    var listingPanel = new UI.Panel()
        .setMarginTop('10px')
        .setMinHeight('100px')
        .setMaxHeight('500px')
        .setOverflow('auto');
    headingPanel.add(new UI.Text('Preferences'));
    headingPanel.add(new UI.Icon('times')
        .setCursor('pointer')
        .setMarginLeft('20px')
        .setFloat('right')
        .onClick(function () {
        container.setDisplay('none');
    }));
    container.add(headingPanel);
    container.add(listingPanel);
    //
    Object.keys(NGL.UIStageParameters).forEach(function (name) {
        var p = NGL.UIStageParameters[name];
        if (p.label === undefined)
            p.label = name;
        var input = NGL.createParameterInput(p, stage.parameters[name]);
        if (!input)
            return;
        preferences.signals.keyChanged.add(function (key, value) {
            if (key === name)
                input.setValue(value);
        });
        function setParam() {
            var sp = {};
            sp[name] = input.getValue();
            preferences.setKey(name, sp[name]);
        }
        var ua = navigator.userAgent;
        if (p.type === 'range' && !/Trident/.test(ua) && !/MSIE/.test(ua)) {
            input.onInput(setParam);
        }
        else {
            input.onChange(setParam);
        }
        listingPanel
            .add(new UI.Text(name).setWidth('120px'))
            .add(input)
            .add(new UI.Break());
    });
    return container;
};
// Export image
NGL.ExportImageWidget = function (stage) {
    var container = new UI.OverlayPanel();
    var headingPanel = new UI.Panel()
        .setBorderBottom('1px solid #555')
        .setHeight('25px');
    var listingPanel = new UI.Panel()
        .setMarginTop('10px')
        .setMinHeight('100px')
        .setMaxHeight('500px')
        .setOverflow('auto');
    headingPanel.add(new UI.Text('Image export'));
    headingPanel.add(new UI.Icon('times')
        .setCursor('pointer')
        .setMarginLeft('20px')
        .setFloat('right')
        .onClick(function () {
        container.setDisplay('none');
    }));
    container.add(headingPanel);
    container.add(listingPanel);
    var factorSelect = new UI.Select()
        .setOptions({
        '1': '1x',
        '2': '2x',
        '3': '3x',
        '4': '4x',
        '5': '5x',
        '6': '6x',
        '7': '7x',
        '8': '8x',
        '9': '9x',
        '10': '10x'
    })
        .setValue('4');
    var antialiasCheckbox = new UI.Checkbox()
        .setValue(true);
    var trimCheckbox = new UI.Checkbox()
        .setValue(false);
    var transparentCheckbox = new UI.Checkbox()
        .setValue(false);
    var progress = new UI.Progress()
        .setDisplay('none');
    var exportButton = new UI.Button('export')
        .onClick(function () {
        exportButton.setDisplay('none');
        progress.setDisplay('inline-block');
        function onProgress(i, n, finished) {
            if (i === 1) {
                progress.setMax(n);
            }
            if (i >= n) {
                progress.setIndeterminate();
            }
            else {
                progress.setValue(i);
            }
            if (finished) {
                progress.setDisplay('none');
                exportButton.setDisplay('inline-block');
            }
        }
        setTimeout(function () {
            stage.makeImage({
                factor: parseInt(factorSelect.getValue()),
                antialias: antialiasCheckbox.getValue(),
                trim: trimCheckbox.getValue(),
                transparent: transparentCheckbox.getValue(),
                onProgress: onProgress
            }).then(function (blob) {
                NGL.download(blob, 'screenshot.png');
            });
        }, 50);
    });
    function addEntry(label, entry) {
        listingPanel
            .add(new UI.Text(label).setWidth('80px'))
            .add(entry || new UI.Panel())
            .add(new UI.Break());
    }
    addEntry('scale', factorSelect);
    addEntry('antialias', antialiasCheckbox);
    addEntry('trim', trimCheckbox);
    addEntry('transparent', transparentCheckbox);
    listingPanel.add(new UI.Break(), exportButton, progress);
    return container;
};
// Sidebar
NGL.SidebarWidget = function (stage, view = undefined) {
    var signals = stage.signals;
    var container = new UI.Panel();
    container.view = view;
    var widgetContainer = new UI.Panel()
        .setClass('Content');
    var compList = [];
    var widgetList = [];
    function handleComponent(component) {
        var widget;
        switch (component.type) {
            case 'structure':
                widget = new NGL.StructureComponentWidget(component, stage);
                break;
            case 'surface':
                widget = new NGL.SurfaceComponentWidget(component, stage);
                break;
            case 'volume':
                widget = new NGL.VolumeComponentWidget(component, stage);
                break;
            case 'shape':
                widget = new NGL.ShapeComponentWidget(component, stage);
                break;
            default:
                console.warn('NGL.SidebarWidget: component type unknown', component);
                return;
        }
        widgetContainer.add(widget);
        compList.push(component);
        widgetList.push(widget);
    }
    // In case user adds components directly from notebook
    stage.compList.forEach(function (comp) {
        handleComponent(comp);
    });
    signals.componentAdded.add(handleComponent);
    signals.componentRemoved.add(function (component) {
        var idx = compList.indexOf(component);
        if (idx !== -1) {
            widgetList[idx].dispose();
            compList.splice(idx, 1);
            widgetList.splice(idx, 1);
        }
    });
    // actions
    var expandAll = new UI.Icon('plus-square')
        .setTitle('expand all')
        .setCursor('pointer')
        .onClick(function () {
        widgetList.forEach(function (widget) {
            widget.expand();
        });
    });
    var collapseAll = new UI.Icon('minus-square')
        .setTitle('collapse all')
        .setCursor('pointer')
        .setMarginLeft('10px')
        .onClick(function () {
        widgetList.forEach(function (widget) {
            widget.collapse();
        });
    });
    var centerAll = new UI.Icon('bullseye')
        .setTitle('center all')
        .setCursor('pointer')
        .setMarginLeft('10px')
        .onClick(function () {
        stage.autoView(1000);
    });
    var disposeAll = new UI.DisposeIcon()
        .setMarginLeft('10px')
        .setDisposeFunction(function () {
        stage.removeAllComponents();
    });
    var syncRepr = new UI.Icon('superpowers')
        .setTitle('sync representation')
        .setCursor('pointer')
        .setMarginLeft('10px')
        .onClick(function () {
        if (view) {
            view.syncReprWithMe();
        }
    });
    var settingsMenu = new UI.PopupMenu('cogs', 'Settings', 'window')
        .setIconTitle('settings')
        .setMarginLeft('10px');
    settingsMenu.entryLabelWidth = '120px';
    // Busy indicator
    var busy = new UI.Panel()
        .setDisplay('inline')
        .add(new UI.Icon('spinner')
        .addClass('spin')
        .setMarginLeft('45px'));
    stage.tasks.signals.countChanged.add(function (delta, count) {
        if (count > 0) {
            actions.add(busy);
        }
        else {
            try {
                actions.remove(busy);
            }
            catch (e) {
                // already removed
            }
        }
    });
    var paramNames = [
        'clipNear', 'clipFar', 'clipDist', 'fogNear', 'fogFar',
        'lightColor', 'lightIntensity', 'ambientColor', 'ambientIntensity'
    ];
    paramNames.forEach(function (name) {
        var p = NGL.UIStageParameters[name];
        if (p.label === undefined)
            p.label = name;
        var input = NGL.createParameterInput(p, stage.parameters[name]);
        if (!input)
            return;
        stage.signals.parametersChanged.add(function (params) {
            input.setValue(params[name]);
        });
        function setParam() {
            var sp = {};
            sp[name] = input.getValue();
            stage.setParameters(sp);
        }
        var ua = navigator.userAgent;
        if (p.type === 'range' && !/Trident/.test(ua) && !/MSIE/.test(ua)) {
            input.onInput(setParam);
        }
        else {
            input.onChange(setParam);
        }
        settingsMenu.addEntry(name, input);
    });
    //
    var actions = new UI.Panel()
        .setClass('Panel Sticky')
        .add(expandAll, collapseAll, centerAll, disposeAll, syncRepr, settingsMenu);
    container.add(actions, widgetContainer);
    return container;
};
// Component
NGL.StructureComponentWidget = function (component, stage) {
    var signals = component.signals;
    var container = new UI.CollapsibleIconPanel('minus-square', 'plus-square');
    var reprContainer = new UI.Panel();
    var trajContainer = new UI.Panel();
    function handleRepr(repr) {
        reprContainer.add(new NGL.RepresentationElementWidget(repr, stage, component));
    }
    component.reprList.forEach(function (repr) {
        handleRepr(repr);
    });
    signals.representationAdded.add(handleRepr);
    signals.trajectoryAdded.add(function (traj) {
        trajContainer.add(new NGL.TrajectoryElementWidget(traj, stage));
    });
    signals.defaultAssemblyChanged.add(function () {
        assembly.setValue(component.parameters.defaultAssembly);
    });
    // Selection
    container.add(new UI.SelectionPanel(component.selection)
        .setMarginLeft('20px')
        .setInputWidth('214px'));
    // Export PDB
    var pdb = new UI.Button('export').onClick(function () {
        var pdbWriter = new NGL.PdbWriter(component.structure);
        pdbWriter.download('structure');
        componentPanel.setMenuDisplay('none');
    });
    // Add representation
    var repr = new UI.Select()
        .setColor('#444')
        .setOptions((function () {
        var reprOptions = { '': '[ add ]' };
        NGL.RepresentationRegistry.names.forEach(function (key) {
            reprOptions[key] = key;
        });
        return reprOptions;
    })())
        .onChange(function () {
        component.addRepresentation(repr.getValue());
        repr.setValue('');
        componentPanel.setMenuDisplay('none');
    });
    // Assembly
    var assembly = new UI.Select()
        .setColor('#444')
        .setOptions((function () {
        var biomolDict = component.structure.biomolDict;
        var assemblyOptions = {
            '': (component.structure.unitcell ? 'AU' : 'FULL')
        };
        Object.keys(biomolDict).forEach(function (k) {
            assemblyOptions[k] = k;
        });
        return assemblyOptions;
    })())
        .setValue(component.parameters.defaultAssembly)
        .onChange(function () {
        component.setDefaultAssembly(assembly.getValue());
        componentPanel.setMenuDisplay('none');
    });
    // Open trajectory
    var trajExt = [];
    NGL.ParserRegistry.getTrajectoryExtensions().forEach(function (ext) {
        trajExt.push('.' + ext, '.' + ext + '.gz');
    });
    function framesInputOnChange(e) {
        var fn = function (file, callback) {
            NGL.autoLoad(file).then(function (frames) {
                component.addTrajectory(frames);
                callback();
            });
        };
        var queue = new NGL.Queue(fn, e.target.files);
        e.target.value = '';
    }
    var framesInput = document.createElement('input');
    framesInput.type = 'file';
    framesInput.multiple = true;
    framesInput.style.display = 'none';
    framesInput.accept = trajExt.join(',');
    framesInput.addEventListener('change', framesInputOnChange, false);
    var traj = new UI.Button('open').onClick(function () {
        framesInput.click();
        componentPanel.setMenuDisplay('none');
    });
    // Import remote trajectory
    var remoteTraj = new UI.Button('import').onClick(function () {
        componentPanel.setMenuDisplay('none');
        // TODO list of extensions should be provided by trajectory datasource
        var remoteTrajExt = [
            'xtc', 'trr', 'netcdf', 'dcd', 'ncdf', 'nc', 'gro', 'pdb',
            'lammpstrj', 'xyz', 'mdcrd', 'gz', 'binpos', 'h5', 'dtr',
            'arc', 'tng', 'trj', 'trz'
        ];
        var dirWidget;
        function onListingClick(info) {
            var ext = info.path.split('.').pop().toLowerCase();
            if (remoteTrajExt.indexOf(ext) !== -1) {
                component.addTrajectory(info.path + '?struc=' + component.structure.path);
                dirWidget.dispose();
            }
            else {
                NGL.log('unknown trajectory type: ' + ext);
            }
        }
        dirWidget = new NGL.DirectoryListingWidget(NGL.ListingDatasource, stage, 'Import trajectory', remoteTrajExt, onListingClick);
        dirWidget
            .setOpacity('0.9')
            .setLeft('50px')
            .setTop('80px')
            .attach();
    });
    // Superpose
    function setSuperposeOptions() {
        var superposeOptions = { '': '[ structure ]' };
        stage.eachComponent(function (o, i) {
            if (o !== component) {
                superposeOptions[i] = o.name;
            }
        }, NGL.StructureComponent);
        superpose.setOptions(superposeOptions);
    }
    stage.signals.componentAdded.add(setSuperposeOptions);
    stage.signals.componentRemoved.add(setSuperposeOptions);
    var superpose = new UI.Select()
        .setColor('#444')
        .onChange(function () {
        component.superpose(stage.compList[superpose.getValue()], true);
        component.autoView(1000);
        superpose.setValue('');
        componentPanel.setMenuDisplay('none');
    });
    setSuperposeOptions();
    // Principal axes
    var alignAxes = new UI.Button('align').onClick(function () {
        var pa = component.structure.getPrincipalAxes();
        var q = pa.getRotationQuaternion();
        q.multiply(component.quaternion.clone().inverse());
        stage.animationControls.rotate(q);
        stage.animationControls.move(component.getCenter());
    });
    // Measurements removal
    var removeMeasurements = new UI.Button('remove').onClick(function () {
        component.removeAllMeasurements();
    });
    // Annotations visibility
    var showAnnotations = new UI.Button('show').onClick(function () {
        component.annotationList.forEach(function (annotation) {
            annotation.setVisibility(true);
        });
    });
    var hideAnnotations = new UI.Button('hide').onClick(function () {
        component.annotationList.forEach(function (annotation) {
            annotation.setVisibility(false);
        });
    });
    var annotationButtons = new UI.Panel()
        .setDisplay('inline-block')
        .add(showAnnotations, hideAnnotations);
    // Open validation
    function validationInputOnChange(e) {
        var fn = function (file, callback) {
            NGL.autoLoad(file, { ext: 'validation' }).then(function (validation) {
                component.structure.validation = validation;
                callback();
            });
        };
        var queue = new NGL.Queue(fn, e.target.files);
    }
    var validationInput = document.createElement('input');
    validationInput.type = 'file';
    validationInput.style.display = 'none';
    validationInput.accept = '.xml';
    validationInput.addEventListener('change', validationInputOnChange, false);
    var vali = new UI.Button('open').onClick(function () {
        validationInput.click();
        componentPanel.setMenuDisplay('none');
    });
    // Position
    var position = new UI.Vector3()
        .onChange(function () {
        component.setPosition(position.getValue());
    });
    // Rotation
    var q = new NGL.Quaternion();
    var e = new NGL.Euler();
    var rotation = new UI.Vector3()
        .setRange(-6.28, 6.28)
        .onChange(function () {
        e.setFromVector3(rotation.getValue());
        q.setFromEuler(e);
        component.setRotation(q);
    });
    // Scale
    var scale = new UI.Number(1)
        .setRange(0.01, 100)
        .onChange(function () {
        component.setScale(scale.getValue());
    });
    // Matrix
    signals.matrixChanged.add(function () {
        position.setValue(component.position);
        rotation.setValue(e.setFromQuaternion(component.quaternion));
        scale.setValue(component.scale.x);
    });
    // Component panel
    var componentPanel = new UI.ComponentPanel(component)
        .setDisplay('inline-block')
        .setMargin('0px')
        .addMenuEntry('PDB file', pdb)
        .addMenuEntry('Representation', repr)
        .addMenuEntry('Assembly', assembly)
        .addMenuEntry('Superpose', superpose)
        .addMenuEntry('File', new UI.Text(component.structure.path)
        .setMaxWidth('100px')
        .setOverflow('auto')
    // .setWordWrap( "break-word" )
    )
        .addMenuEntry('Trajectory', traj)
        .addMenuEntry('Principal axes', alignAxes)
        .addMenuEntry('Measurements', removeMeasurements)
        .addMenuEntry('Annotations', annotationButtons)
        .addMenuEntry('Validation', vali)
        .addMenuEntry('Position', position)
        .addMenuEntry('Rotation', rotation)
        .addMenuEntry('Scale', scale);
    if (NGL.ListingDatasource && NGL.TrajectoryDatasource) {
        componentPanel.addMenuEntry('Remote trajectory', remoteTraj);
    }
    // Fill container
    container
        .addStatic(componentPanel)
        .add(trajContainer)
        .add(reprContainer);
    return container;
};
NGL.SurfaceComponentWidget = function (component, stage) {
    var signals = component.signals;
    var container = new UI.CollapsibleIconPanel('minus-square', 'plus-square');
    var reprContainer = new UI.Panel();
    signals.representationAdded.add(function (repr) {
        reprContainer.add(new NGL.RepresentationElementWidget(repr, stage));
    });
    // Add representation
    var repr = new UI.Select()
        .setColor('#444')
        .setOptions((function () {
        var reprOptions = {
            '': '[ add ]',
            'surface': 'surface',
            'dot': 'dot'
        };
        return reprOptions;
    })())
        .onChange(function () {
        component.addRepresentation(repr.getValue());
        repr.setValue('');
        componentPanel.setMenuDisplay('none');
    });
    // Position
    var position = new UI.Vector3()
        .onChange(function () {
        component.setPosition(position.getValue());
    });
    // Rotation
    var q = new NGL.Quaternion();
    var e = new NGL.Euler();
    var rotation = new UI.Vector3()
        .setRange(-6.28, 6.28)
        .onChange(function () {
        e.setFromVector3(rotation.getValue());
        q.setFromEuler(e);
        component.setRotation(q);
    });
    // Scale
    var scale = new UI.Number(1)
        .setRange(0.01, 100)
        .onChange(function () {
        component.setScale(scale.getValue());
    });
    // Matrix
    signals.matrixChanged.add(function () {
        position.setValue(component.position);
        rotation.setValue(e.setFromQuaternion(component.quaternion));
        scale.setValue(component.scale.x);
    });
    // Component panel
    var componentPanel = new UI.ComponentPanel(component)
        .setDisplay('inline-block')
        .setMargin('0px')
        .addMenuEntry('Representation', repr)
        .addMenuEntry('File', new UI.Text(component.surface.path)
        .setMaxWidth('100px')
        .setWordWrap('break-word'))
        .addMenuEntry('Position', position)
        .addMenuEntry('Rotation', rotation)
        .addMenuEntry('Scale', scale);
    // Fill container
    container
        .addStatic(componentPanel)
        .add(reprContainer);
    return container;
};
NGL.VolumeComponentWidget = function (component, stage) {
    var signals = component.signals;
    var container = new UI.CollapsibleIconPanel('minus-square', 'plus-square');
    var reprContainer = new UI.Panel();
    signals.representationAdded.add(function (repr) {
        reprContainer.add(new NGL.RepresentationElementWidget(repr, stage));
    });
    // Add representation
    var repr = new UI.Select()
        .setColor('#444')
        .setOptions((function () {
        var reprOptions = {
            '': '[ add ]',
            'surface': 'surface',
            'dot': 'dot',
            'slice': 'slice'
        };
        return reprOptions;
    })())
        .onChange(function () {
        component.addRepresentation(repr.getValue());
        repr.setValue('');
        componentPanel.setMenuDisplay('none');
    });
    // Position
    var position = new UI.Vector3()
        .onChange(function () {
        component.setPosition(position.getValue());
    });
    // Rotation
    var q = new NGL.Quaternion();
    var e = new NGL.Euler();
    var rotation = new UI.Vector3()
        .setRange(-6.28, 6.28)
        .onChange(function () {
        e.setFromVector3(rotation.getValue());
        q.setFromEuler(e);
        component.setRotation(q);
    });
    // Scale
    var scale = new UI.Number(1)
        .setRange(0.01, 100)
        .onChange(function () {
        component.setScale(scale.getValue());
    });
    // Matrix
    signals.matrixChanged.add(function () {
        position.setValue(component.position);
        rotation.setValue(e.setFromQuaternion(component.quaternion));
        scale.setValue(component.scale.x);
    });
    // Component panel
    var componentPanel = new UI.ComponentPanel(component)
        .setDisplay('inline-block')
        .setMargin('0px')
        .addMenuEntry('Representation', repr)
        .addMenuEntry('File', new UI.Text(component.volume.path)
        .setMaxWidth('100px')
        .setWordWrap('break-word'))
        .addMenuEntry('Position', position)
        .addMenuEntry('Rotation', rotation)
        .addMenuEntry('Scale', scale);
    // Fill container
    container
        .addStatic(componentPanel)
        .add(reprContainer);
    return container;
};
NGL.ShapeComponentWidget = function (component, stage) {
    var signals = component.signals;
    var container = new UI.CollapsibleIconPanel('minus-square', 'plus-square');
    var reprContainer = new UI.Panel();
    signals.representationAdded.add(function (repr) {
        reprContainer.add(new NGL.RepresentationElementWidget(repr, stage));
    });
    // Add representation
    var repr = new UI.Select()
        .setColor('#444')
        .setOptions((function () {
        var reprOptions = {
            '': '[ add ]',
            'buffer': 'buffer'
        };
        return reprOptions;
    })())
        .onChange(function () {
        component.addRepresentation(repr.getValue());
        repr.setValue('');
        componentPanel.setMenuDisplay('none');
    });
    // Position
    var position = new UI.Vector3()
        .onChange(function () {
        component.setPosition(position.getValue());
    });
    // Rotation
    var q = new NGL.Quaternion();
    var e = new NGL.Euler();
    var rotation = new UI.Vector3()
        .setRange(-6.28, 6.28)
        .onChange(function () {
        e.setFromVector3(rotation.getValue());
        q.setFromEuler(e);
        component.setRotation(q);
    });
    // Scale
    var scale = new UI.Number(1)
        .setRange(0.01, 100)
        .onChange(function () {
        component.setScale(scale.getValue());
    });
    // Matrix
    signals.matrixChanged.add(function () {
        position.setValue(component.position);
        rotation.setValue(e.setFromQuaternion(component.quaternion));
        scale.setValue(component.scale.x);
    });
    // Component panel
    var componentPanel = new UI.ComponentPanel(component)
        .setDisplay('inline-block')
        .setMargin('0px')
        .addMenuEntry('Representation', repr)
        .addMenuEntry('File', new UI.Text(component.shape.path)
        .setMaxWidth('100px')
        .setWordWrap('break-word'))
        .addMenuEntry('Position', position)
        .addMenuEntry('Rotation', rotation)
        .addMenuEntry('Scale', scale);
    // Fill container
    container
        .addStatic(componentPanel)
        .add(reprContainer);
    return container;
};
// Representation
NGL.RepresentationElementWidget = function (element, stage, component = undefined) {
    var signals = element.signals;
    var container = new UI.CollapsibleIconPanel('minus-square', 'plus-square')
        .setMarginLeft('20px');
    signals.visibilityChanged.add(function (value) {
        toggle.setValue(value);
    });
    signals.nameChanged.add(function (value) {
        name.setValue(value);
    });
    signals.disposed.add(function () {
        menu.dispose();
        container.dispose();
    });
    // Name
    var name = new UI.EllipsisText(element.name)
        .setWidth('103px');
    // Actions
    var toggle = new UI.ToggleIcon(element.visible, 'eye', 'eye-slash')
        .setTitle('hide/show')
        .setCursor('pointer')
        .setMarginLeft('25px')
        .onClick(function () {
        element.setVisibility(!element.visible);
    });
    var center = new UI.Icon('bullseye')
        .setTitle('center')
        .setCursor('pointer')
        .setMarginLeft('10px')
        .onClick(function () {
        component.autoView(element.repr.selection.string, 1000);
    });
    var disposeIcon = new UI.DisposeIcon()
        .setMarginLeft('10px')
        .setDisposeFunction(function () {
        element.dispose();
    });
    if (component) {
        container
            .addStatic(name)
            .addStatic(toggle)
            .addStatic(center)
            .addStatic(disposeIcon);
    }
    else {
        container
            .addStatic(name)
            .addStatic(toggle)
            .addStatic(disposeIcon);
    }
    // Selection
    if ((element.parent.type === 'structure' ||
        element.parent.type === 'trajectory') &&
        element.repr.selection && element.repr.selection.type === 'selection') {
        container.add(new UI.SelectionPanel(element.repr.selection)
            .setMarginLeft('20px')
            .setInputWidth('194px'));
    }
    // Menu
    var menu = new UI.PopupMenu('bars', 'Representation')
        .setMarginLeft('45px')
        .setEntryLabelWidth('190px');
    menu.addEntry('type', new UI.Text(element.repr.type));
    // Parameters
    var repr = element.repr;
    var rp = repr.getParameters();
    Object.keys(repr.parameters).forEach(function (name) {
        if (!repr.parameters[name])
            return;
        var p = Object.assign({}, repr.parameters[name]);
        p.value = rp[name];
        if (p.label === undefined)
            p.label = name;
        var input = NGL.createParameterInput(p);
        if (!input)
            return;
        signals.parametersChanged.add(function (params) {
            if (typeof input.setValue === 'function') {
                input.setValue(params[name]);
            }
        });
        function setParam() {
            var po = {};
            po[name] = input.getValue();
            element.setParameters(po);
            stage.viewer.requestRender();
        }
        var ua = navigator.userAgent;
        if (p.type === 'range' && !/Trident/.test(ua) && !/MSIE/.test(ua)) {
            input.onInput(setParam);
        }
        else {
            input.onChange(setParam);
        }
        menu.addEntry(name, input);
    });
    container
        .addStatic(menu);
    return container;
};
// Trajectory
NGL.TrajectoryElementWidget = function (element, stage) {
    var signals = element.signals;
    var traj = element.trajectory;
    var container = new UI.CollapsibleIconPanel('minus-square', 'plus-square')
        .setMarginLeft('20px');
    signals.disposed.add(function () {
        menu.dispose();
        container.dispose();
    });
    var frameCount = new UI.Panel()
        .setDisplay('inline')
        .add(new UI.Icon('spinner')
        .addClass('spin')
        .setMarginRight('99px'));
    var frameTime = new UI.Panel()
        .setMarginLeft('5px')
        .setDisplay('inline');
    function setFrame(value) {
        frame.setValue(value);
        if (traj.deltaTime && value >= 0) {
            var t = traj.getFrameTime(value) / 1000;
            time.setValue(t.toFixed(9).replace(/\.?0+$/g, '') + 'ns');
        }
        else {
            time.setValue('');
        }
        frameRange.setValue(value);
        frameCount.clear().add(frame.setWidth('40px'));
        frameTime.clear().add(time.setWidth('90px'));
    }
    function init(value) {
        frame.setRange(-1, value - 1);
        frameRange.setRange(-1, value - 1);
        setFrame(traj.currentFrame);
        if (element.parameters.defaultStep !== undefined) {
            step.setValue(element.parameters.defaultStep);
        }
        else {
            // 1000 = n / step
            step.setValue(Math.ceil((value + 1) / 100));
        }
        player.setParameters({ step: step.getValue() });
        player.setParameters({ end: value - 1 });
    }
    signals.countChanged.add(init);
    signals.frameChanged.add(setFrame);
    // Name
    var name = new UI.EllipsisText(element.parameters.name)
        .setWidth('103px');
    signals.nameChanged.add(function (value) {
        name.setValue(value);
    });
    container.addStatic(name);
    container.addStatic(frameTime);
    // frames
    var frame = new UI.Integer(-1)
        .setWidth('40px')
        .setTextAlign('right')
        .setMarginLeft('5px')
        .setRange(-1, -1)
        .onChange(function (e) {
        traj.setFrame(frame.getValue());
        menu.setMenuDisplay('none');
    });
    var time = new UI.Text()
        .setTextAlign('right')
        .setWidth('90px');
    var step = new UI.Integer(1)
        .setWidth('50px')
        .setRange(1, 10000)
        .onChange(function () {
        player.setParameters({ step: step.getValue() });
    });
    var frameRow = new UI.Panel();
    var frameRange = new UI.Range(-1, -1, -1, 1)
        .setWidth('147px')
        .setMargin('0px')
        .setPadding('0px')
        .setBorder('0px')
        .onInput(function (e) {
        var value = frameRange.getValue();
        if (value === traj.currentFrame) {
            return;
        }
        if (traj.player && traj.player.isRunning) {
            traj.setPlayer();
            traj.setFrame(value);
        }
        else if (!traj.inProgress) {
            traj.setFrame(value);
        }
    });
    var interpolateType = new UI.Select()
        .setColor('#444')
        .setOptions({
        '': 'none',
        'linear': 'linear',
        'spline': 'spline'
    })
        .setValue(element.parameters.defaultInterpolateType)
        .onChange(function () {
        player.setParameters({ interpolateType: interpolateType.getValue() });
    });
    var interpolateStep = new UI.Integer(element.parameters.defaultInterpolateStep)
        .setWidth('30px')
        .setRange(1, 50)
        .onChange(function () {
        player.setParameters({ interpolateStep: interpolateStep.getValue() });
    });
    var playDirection = new UI.Select()
        .setColor('#444')
        .setOptions({
        'forward': 'forward',
        'backward': 'backward',
        'bounce': 'bounce'
    })
        .setValue(element.parameters.defaultDirection)
        .onChange(function () {
        player.setParameters({ direction: playDirection.getValue() });
    });
    var playMode = new UI.Select()
        .setColor('#444')
        .setOptions({
        'loop': 'loop',
        'once': 'once'
    })
        .setValue(element.parameters.defaultMode)
        .onChange(function () {
        player.setParameters({ mode: playMode.getValue() });
    });
    // player
    var timeout = new UI.Integer(element.parameters.defaultTimeout)
        .setWidth('30px')
        .setRange(10, 1000)
        .onChange(function () {
        player.setParameters({ timeout: timeout.getValue() });
    });
    var player = new NGL.TrajectoryPlayer(traj, {
        step: step.getValue(),
        timeout: timeout.getValue(),
        start: 0,
        end: traj.frameCount - 1,
        interpolateType: interpolateType.getValue(),
        interpolateStep: interpolateStep.getValue(),
        direction: playDirection.getValue(),
        mode: playMode.getValue()
    });
    traj.setPlayer(player);
    var playerButton = new UI.ToggleIcon(true, 'play', 'pause')
        .setMarginRight('10px')
        .setMarginLeft('20px')
        .setCursor('pointer')
        .setWidth('12px')
        .setTitle('play')
        .onClick(function () {
        player.toggle();
    });
    player.signals.startedRunning.add(function () {
        playerButton
            .setTitle('pause')
            .setValue(false);
    });
    player.signals.haltedRunning.add(function () {
        playerButton
            .setTitle('play')
            .setValue(true);
    });
    frameRow.add(playerButton, frameRange, frameCount);
    // Selection
    container.add(new UI.SelectionPanel(traj.selection)
        .setMarginLeft('20px')
        .setInputWidth('194px'));
    // Options
    var setCenterPbc = new UI.Checkbox(traj.centerPbc)
        .onChange(function () {
        element.setParameters({
            'centerPbc': setCenterPbc.getValue()
        });
    });
    var setRemovePeriodicity = new UI.Checkbox(traj.removePeriodicity)
        .onChange(function () {
        element.setParameters({
            'removePeriodicity': setRemovePeriodicity.getValue()
        });
    });
    var setRemovePbc = new UI.Checkbox(traj.removePbc)
        .onChange(function () {
        element.setParameters({
            'removePbc': setRemovePbc.getValue()
        });
    });
    var setSuperpose = new UI.Checkbox(traj.superpose)
        .onChange(function () {
        element.setParameters({
            'superpose': setSuperpose.getValue()
        });
    });
    var setDeltaTime = new UI.Number(traj.deltaTime)
        .setWidth('55px')
        .setRange(0, 1000000)
        .onChange(function () {
        element.setParameters({
            'deltaTime': setDeltaTime.getValue()
        });
    });
    var setTimeOffset = new UI.Number(traj.timeOffset)
        .setWidth('55px')
        .setRange(0, 1000000000)
        .onChange(function () {
        element.setParameters({
            'timeOffset': setTimeOffset.getValue()
        });
    });
    signals.parametersChanged.add(function (params) {
        setCenterPbc.setValue(traj.centerPbc);
        setRemovePeriodicity.setValue(traj.removePeriodicity);
        setRemovePbc.setValue(traj.removePbc);
        setSuperpose.setValue(traj.superpose);
        setDeltaTime.setValue(traj.deltaTime);
        setTimeOffset.setValue(traj.timeOffset);
        traj.setFrame(frame.getValue());
    });
    // Dispose
    var dispose = new UI.DisposeIcon()
        .setDisposeFunction(function () {
        element.parent.removeTrajectory(element);
    });
    //
    if (traj.frameCount) {
        init(traj.frameCount);
    }
    // Menu
    var menu = new UI.PopupMenu('bars', 'Trajectory')
        .setMarginLeft('10px')
        .setEntryLabelWidth('130px')
        .addEntry('Center', setCenterPbc)
        .addEntry('Remove Periodicity', setRemovePeriodicity)
        .addEntry('Remove PBC', setRemovePbc)
        .addEntry('Superpose', setSuperpose)
        .addEntry('Step size', step)
        .addEntry('Interpolation type', interpolateType)
        .addEntry('Interpolation steps', interpolateStep)
        .addEntry('Play timeout', timeout)
        .addEntry('Play direction', playDirection)
        .addEntry('Play mode', playMode)
        .addEntry('Delta time [ps]', setDeltaTime)
        .addEntry('Time offset [ps]', setTimeOffset)
        .addEntry('File', new UI.Text(traj.trajPath)
        .setMaxWidth('100px')
        .setWordWrap('break-word'))
        .addEntry('Dispose', dispose);
    container
        .addStatic(menu);
    container
        .add(frameRow);
    return container;
};
// Listing
NGL.DirectoryListingWidget = function (datasource, stage, heading, filter, callback) {
    // from http://stackoverflow.com/a/20463021/1435042
    function fileSizeSI(a, b, c, d, e) {
        return (b = Math, c = b.log, d = 1e3, e = c(a) / c(d) | 0, a / b.pow(d, e)).toFixed(2) +
            String.fromCharCode(160) + (e ? 'kMGTPEZY'[--e] + 'B' : 'Bytes');
    }
    function getFolderDict(path) {
        path = path || '';
        var options = { '': '' };
        var full = [];
        path.split('/').forEach(function (chunk) {
            full.push(chunk);
            options[full.join('/')] = chunk;
        });
        return options;
    }
    var container = new UI.OverlayPanel();
    var headingPanel = new UI.Panel()
        .setBorderBottom('1px solid #555')
        .setHeight('30px');
    var listingPanel = new UI.Panel()
        .setMarginTop('10px')
        .setMinHeight('100px')
        .setMaxHeight('500px')
        .setPaddingRight('15px')
        .setOverflow('auto');
    var folderSelect = new UI.Select()
        .setColor('#444')
        .setMarginLeft('20px')
        .setWidth('')
        .setMaxWidth('200px')
        .setOptions(getFolderDict())
        .onChange(function () {
        datasource.getListing(folderSelect.getValue())
            .then(onListingLoaded);
    });
    heading = heading || 'Directoy listing';
    headingPanel.add(new UI.Text(heading));
    headingPanel.add(folderSelect);
    headingPanel.add(new UI.Icon('times')
        .setCursor('pointer')
        .setMarginLeft('20px')
        .setFloat('right')
        .onClick(function () {
        container.dispose();
    }));
    container.add(headingPanel);
    container.add(listingPanel);
    function onListingLoaded(listing) {
        var folder = listing.path;
        var data = listing.data;
        NGL.lastUsedDirectory = folder;
        listingPanel.clear();
        folderSelect
            .setOptions(getFolderDict(folder))
            .setValue(folder);
        data.forEach(function (info) {
            var ext = info.path.split('.').pop().toLowerCase();
            if (filter && !info.dir && filter.indexOf(ext) === -1) {
                return;
            }
            var icon, name;
            if (info.dir) {
                icon = 'folder-o';
                name = info.name;
            }
            else {
                icon = 'file-o';
                name = info.name + String.fromCharCode(160) +
                    '(' + fileSizeSI(info.size) + ')';
            }
            var pathRow = new UI.Panel()
                .setDisplay('block')
                .setWhiteSpace('nowrap')
                .add(new UI.Icon(icon).setWidth('20px'))
                .add(new UI.Text(name))
                .onClick(function () {
                if (info.dir) {
                    datasource.getListing(info.path)
                        .then(onListingLoaded);
                }
                else {
                    callback(info);
                }
            });
            if (info.restricted) {
                pathRow.add(new UI.Icon('lock').setMarginLeft('5px'));
            }
            listingPanel.add(pathRow);
        });
    }
    datasource.getListing(NGL.lastUsedDirectory)
        .then(onListingLoaded);
    return container;
};
module.exports = {
    "StageWidget": StageWidget
};
//# sourceMappingURL=data:application/json;base64, 

/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.FullscreenView = exports.ABC = exports.FullscreenModel = void 0;
const widgets = __webpack_require__(22);
const NGL = __webpack_require__(18);
const base_1 = __webpack_require__(29);
class FullscreenModel extends widgets.DOMWidgetModel {
    defaults() {
        return Object.assign(Object.assign({}, super.defaults()), { _model_name: 'FullscreenModel', _model_module: 'nglview-js-widgets', _model_module_version: __webpack_require__(12).version, _view_name: "FullscreenView", _view_module: "nglview-js-widgets", _view_module_version: __webpack_require__(12).version });
    }
}
exports.FullscreenModel = FullscreenModel;
class ABC {
}
exports.ABC = ABC;
class FullscreenView extends base_1.BaseView {
    render() {
        this.stage = new NGL.Stage(null, null);
        var that = this;
        this.model.on("msg:custom", function (msg) {
            that.on_msg(msg);
        });
        this.handleSignals();
    }
    fullscreen(model_id) {
        var that = this;
        this.model.widget_manager.get_model(model_id).then((model) => {
            var key = Object.keys(model.views)[0];
            model.views[key].then((view) => {
                that.stage.toggleFullscreen(view.el);
            });
        });
    }
    handleSignals() {
        var that = this;
        this.stage.signals.fullscreenChanged.add(function (isFullscreen) {
            that.model.set("_is_fullscreen", isFullscreen);
            that.touch();
        });
    }
    executeCode(code) {
        eval(code);
    }
    on_msg(msg) {
        if ('executeCode' in msg) {
            this.executeCode(msg.executeCode);
        }
    }
}
exports.FullscreenView = FullscreenView;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZnVsbHNjcmVlbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9mdWxsc2NyZWVuLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLGlEQUFnRDtBQUNoRCwyQkFBMEI7QUFDMUIsaUNBQWlDO0FBR2pDLE1BQ00sZUFBZ0IsU0FBUSxPQUFPLENBQUMsY0FBYztJQUNoRCxRQUFRO1FBQ0osdUNBQ1csS0FBSyxDQUFDLFFBQVEsRUFBRSxLQUNuQixXQUFXLEVBQUUsaUJBQWlCLEVBQzlCLGFBQWEsRUFBRSxvQkFBb0IsRUFDbkMscUJBQXFCLEVBQUUsT0FBTyxDQUFDLGlCQUFpQixDQUFDLENBQUMsT0FBTyxFQUN6RCxVQUFVLEVBQUUsZ0JBQWdCLEVBQzVCLFlBQVksRUFBRSxvQkFBb0IsRUFDbEMsb0JBQW9CLEVBQUUsT0FBTyxDQUFDLGlCQUFpQixDQUFDLENBQUMsT0FBTyxJQUMzRDtJQUNMLENBQUM7Q0FDUjtBQWJELDBDQWFDO0FBRUQsTUFDTSxHQUFHO0NBQ1I7QUFGRCxrQkFFQztBQUdELE1BQ00sY0FBZSxTQUFRLGVBQVE7SUFFakMsTUFBTTtRQUNGLElBQUksQ0FBQyxLQUFLLEdBQUcsSUFBSSxHQUFHLENBQUMsS0FBSyxDQUFDLElBQUksRUFBRSxJQUFJLENBQUMsQ0FBQTtRQUN0QyxJQUFJLElBQUksR0FBRyxJQUFJLENBQUE7UUFDZixJQUFJLENBQUMsS0FBSyxDQUFDLEVBQUUsQ0FBQyxZQUFZLEVBQUUsVUFBUyxHQUFHO1lBQ3BDLElBQUksQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLENBQUE7UUFDcEIsQ0FBQyxDQUFDLENBQUE7UUFDRixJQUFJLENBQUMsYUFBYSxFQUFFLENBQUE7SUFDeEIsQ0FBQztJQUVELFVBQVUsQ0FBQyxRQUFRO1FBQ2YsSUFBSSxJQUFJLEdBQUcsSUFBSSxDQUFBO1FBQ2YsSUFBSSxDQUFDLEtBQUssQ0FBQyxjQUFjLENBQUMsU0FBUyxDQUFDLFFBQVEsQ0FBQyxDQUFDLElBQUksQ0FBQyxDQUFDLEtBQUssRUFBRSxFQUFFO1lBQ3pELElBQUksR0FBRyxHQUFHLE1BQU0sQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLEtBQUssQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFBO1lBQ3JDLEtBQUssQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUMsSUFBSSxDQUFDLENBQUMsSUFBSSxFQUFFLEVBQUU7Z0JBQzNCLElBQUksQ0FBQyxLQUFLLENBQUMsZ0JBQWdCLENBQUMsSUFBSSxDQUFDLEVBQUUsQ0FBQyxDQUFBO1lBQ3hDLENBQUMsQ0FBQyxDQUFBO1FBQ04sQ0FBQyxDQUFDLENBQUE7SUFDTixDQUFDO0lBRUQsYUFBYTtRQUNULElBQUksSUFBSSxHQUFHLElBQUksQ0FBQTtRQUNmLElBQUksQ0FBQyxLQUFLLENBQUMsT0FBTyxDQUFDLGlCQUFpQixDQUFDLEdBQUcsQ0FBQyxVQUFVLFlBQVk7WUFDM0QsSUFBSSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsZ0JBQWdCLEVBQUUsWUFBWSxDQUFDLENBQUE7WUFDOUMsSUFBSSxDQUFDLEtBQUssRUFBRSxDQUFBO1FBQ2hCLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQztJQUVELFdBQVcsQ0FBQyxJQUFJO1FBQ1osSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO0lBQ2YsQ0FBQztJQUVELE1BQU0sQ0FBQyxHQUFHO1FBQ04sSUFBSSxhQUFhLElBQUksR0FBRyxFQUFDO1lBQ3JCLElBQUksQ0FBQyxXQUFXLENBQUMsR0FBRyxDQUFDLFdBQVcsQ0FBQyxDQUFBO1NBQ3BDO0lBQ0wsQ0FBQztDQUNKO0FBdkNELHdDQXVDQyJ9

/***/ }),
/* 236 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ColormakerRegistryView = exports.ColormakerRegistryModel = void 0;
const _ = __webpack_require__(34);
const NGL = __webpack_require__(18);
const base_1 = __webpack_require__(29);
const widgets = __webpack_require__(22);
class ColormakerRegistryModel extends widgets.DOMWidgetModel {
    defaults() {
        return _.extend(widgets.DOMWidgetModel.prototype.defaults(), {
            _model_name: 'ColormakerRegistryModel',
            _model_module: 'nglview-js-widgets',
            _model_module_version: __webpack_require__(12).version,
            _view_name: "ColormakerRegistryView",
            _view_module: "nglview-js-widgets",
            _view_module_version: __webpack_require__(12).version,
        });
    }
}
exports.ColormakerRegistryModel = ColormakerRegistryModel;
class ColormakerRegistryView extends base_1.BaseView {
    render() {
        super.render();
        if (this.isEmbeded()) {
            console.log("Embed mode for ColormakerRegistryView");
            this.handleEmbed();
        }
    }
    handleEmbed() {
        // should be called by NGLView later
        this.model.get("_msg_ar").forEach(msg => {
            this.on_msg(msg);
        });
    }
    addSelectionScheme(label, args) {
        var id = NGL.ColormakerRegistry.addSelectionScheme(args, label);
        this._updateId(id, label);
    }
    addSelectionSchemeOriginal(label, args) {
        var id = NGL.ColormakerRegistry.addSelectionScheme(args, label);
        var scheme = NGL.ColormakerRegistry.userSchemes[id];
        NGL.ColormakerRegistry.removeScheme(id);
        // hard code the scheme ID
        NGL.ColormakerRegistry.add(label, scheme);
    }
    addScheme(label, func_str) {
        var func = Function("return " + func_str)();
        var id = NGL.ColormakerRegistry.addScheme(function (params) {
            this.atomColor = func;
        });
        this._updateId(id, label);
    }
    _updateId(oldId, newId) {
        var scheme = NGL.ColormakerRegistry.userSchemes[oldId];
        NGL.ColormakerRegistry.add(newId, scheme);
        NGL.ColormakerRegistry.removeScheme(oldId);
    }
}
exports.ColormakerRegistryView = ColormakerRegistryView;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29sb3IuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvY29sb3IudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEsZ0NBQStCO0FBQy9CLDJCQUEwQjtBQUMxQixpQ0FBaUM7QUFDakMsaURBQWdEO0FBR2hELE1BQ00sdUJBQXdCLFNBQVEsT0FBTyxDQUFDLGNBQWM7SUFDeEQsUUFBUTtRQUNKLE9BQU8sQ0FBQyxDQUFDLE1BQU0sQ0FBQyxPQUFPLENBQUMsY0FBYyxDQUFDLFNBQVMsQ0FBQyxRQUFRLEVBQUUsRUFBRTtZQUN6RCxXQUFXLEVBQUUseUJBQXlCO1lBQ3RDLGFBQWEsRUFBRSxvQkFBb0I7WUFDbkMscUJBQXFCLEVBQUUsT0FBTyxDQUFDLGlCQUFpQixDQUFDLENBQUMsT0FBTztZQUN6RCxVQUFVLEVBQUUsd0JBQXdCO1lBQ3BDLFlBQVksRUFBRSxvQkFBb0I7WUFDbEMsb0JBQW9CLEVBQUUsT0FBTyxDQUFDLGlCQUFpQixDQUFDLENBQUMsT0FBTztTQUMzRCxDQUFDLENBQUE7SUFDTixDQUFDO0NBQ0o7QUFaRCwwREFZQztBQUdELE1BQ00sc0JBQXVCLFNBQVEsZUFBUTtJQUV6QyxNQUFNO1FBQ0YsS0FBSyxDQUFDLE1BQU0sRUFBRSxDQUFBO1FBQ2QsSUFBSSxJQUFJLENBQUMsU0FBUyxFQUFFLEVBQUM7WUFDakIsT0FBTyxDQUFDLEdBQUcsQ0FBQyx1Q0FBdUMsQ0FBQyxDQUFBO1lBQ3BELElBQUksQ0FBQyxXQUFXLEVBQUUsQ0FBQTtTQUNyQjtJQUNMLENBQUM7SUFFRCxXQUFXO1FBQ1Asb0NBQW9DO1FBQ3BDLElBQUksQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLFNBQVMsQ0FBQyxDQUFDLE9BQU8sQ0FBQyxHQUFHLENBQUMsRUFBRTtZQUNwQyxJQUFJLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFBO1FBQ3BCLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQztJQUVELGtCQUFrQixDQUFDLEtBQUssRUFBRSxJQUFJO1FBQzFCLElBQUksRUFBRSxHQUFHLEdBQUcsQ0FBQyxrQkFBa0IsQ0FBQyxrQkFBa0IsQ0FBQyxJQUFJLEVBQUUsS0FBSyxDQUFDLENBQUE7UUFDL0QsSUFBSSxDQUFDLFNBQVMsQ0FBQyxFQUFFLEVBQUUsS0FBSyxDQUFDLENBQUE7SUFDN0IsQ0FBQztJQUVELDBCQUEwQixDQUFDLEtBQUssRUFBRSxJQUFJO1FBQ2xDLElBQUksRUFBRSxHQUFHLEdBQUcsQ0FBQyxrQkFBa0IsQ0FBQyxrQkFBa0IsQ0FBQyxJQUFJLEVBQUUsS0FBSyxDQUFDLENBQUM7UUFDaEUsSUFBSSxNQUFNLEdBQUcsR0FBRyxDQUFDLGtCQUFrQixDQUFDLFdBQVcsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUNwRCxHQUFHLENBQUMsa0JBQWtCLENBQUMsWUFBWSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQ3hDLDBCQUEwQjtRQUMxQixHQUFHLENBQUMsa0JBQWtCLENBQUMsR0FBRyxDQUFDLEtBQUssRUFBRSxNQUFNLENBQUMsQ0FBQztJQUM5QyxDQUFDO0lBRUQsU0FBUyxDQUFDLEtBQUssRUFBRSxRQUFRO1FBQ3JCLElBQUksSUFBSSxHQUFHLFFBQVEsQ0FBQyxTQUFTLEdBQUcsUUFBUSxDQUFDLEVBQUUsQ0FBQTtRQUMzQyxJQUFJLEVBQUUsR0FBRyxHQUFHLENBQUMsa0JBQWtCLENBQUMsU0FBUyxDQUFDLFVBQVMsTUFBTTtZQUNyRCxJQUFJLENBQUMsU0FBUyxHQUFHLElBQUksQ0FBQTtRQUN6QixDQUFDLENBQUMsQ0FBQTtRQUNGLElBQUksQ0FBQyxTQUFTLENBQUMsRUFBRSxFQUFFLEtBQUssQ0FBQyxDQUFBO0lBQzdCLENBQUM7SUFFRCxTQUFTLENBQUMsS0FBSyxFQUFFLEtBQUs7UUFDbEIsSUFBSSxNQUFNLEdBQUcsR0FBRyxDQUFDLGtCQUFrQixDQUFDLFdBQVcsQ0FBQyxLQUFLLENBQUMsQ0FBQTtRQUN0RCxHQUFHLENBQUMsa0JBQWtCLENBQUMsR0FBRyxDQUFDLEtBQUssRUFBRSxNQUFNLENBQUMsQ0FBQTtRQUN6QyxHQUFHLENBQUMsa0JBQWtCLENBQUMsWUFBWSxDQUFDLEtBQUssQ0FBQyxDQUFBO0lBQzlDLENBQUM7Q0FDSjtBQTVDRCx3REE0Q0MifQ==

/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ThemeManagerView = exports.ThemeManagerModel = void 0;
const _ = __webpack_require__(34);
const base_1 = __webpack_require__(29);
const widgets = __webpack_require__(22);
class ThemeManagerModel extends widgets.DOMWidgetModel {
    defaults() {
        return _.extend(widgets.DOMWidgetModel.prototype.defaults(), {
            _model_name: 'ThemeManagerModel',
            _model_module: 'nglview-js-widgets',
            _model_module_version: __webpack_require__(12).version,
            _view_name: "ThemeManagerView",
            _view_module: "nglview-js-widgets",
            _view_module_version: __webpack_require__(12).version,
        });
    }
}
exports.ThemeManagerModel = ThemeManagerModel;
class ThemeManagerView extends base_1.BaseView {
    render() {
        super.render();
        this.displayed.then(() => this.handleThemeChanged());
    }
    handleThemeChanged() {
        console.log("ThemeManagerView: handleThemeChanged");
        this.setTheme(this.model.get("_theme_css"));
    }
    handleEmbed() {
        this.handleThemeChanged();
    }
    setTheme(cssContent) {
        if (cssContent == undefined) {
            return;
        }
        var ele = document.getElementById('nglview_style');
        if (ele) {
            document.head.removeChild(ele);
        }
        ele = document.createElement('style');
        ele.id = 'nglview_style';
        ele.appendChild(document.createTextNode(cssContent));
        document.head.appendChild(ele);
        this.send({ 'type': 'call_method', 'data': 'handle_resize' });
    }
}
exports.ThemeManagerView = ThemeManagerView;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGhlbWUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvdGhlbWUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQUEsZ0NBQStCO0FBQy9CLGlDQUFpQztBQUNqQyxpREFBZ0Q7QUFHaEQsTUFDTSxpQkFBa0IsU0FBUSxPQUFPLENBQUMsY0FBYztJQUNsRCxRQUFRO1FBQ0osT0FBTyxDQUFDLENBQUMsTUFBTSxDQUFDLE9BQU8sQ0FBQyxjQUFjLENBQUMsU0FBUyxDQUFDLFFBQVEsRUFBRSxFQUFFO1lBQ3pELFdBQVcsRUFBRSxtQkFBbUI7WUFDaEMsYUFBYSxFQUFFLG9CQUFvQjtZQUNuQyxxQkFBcUIsRUFBRSxPQUFPLENBQUMsaUJBQWlCLENBQUMsQ0FBQyxPQUFPO1lBQ3pELFVBQVUsRUFBRSxrQkFBa0I7WUFDOUIsWUFBWSxFQUFFLG9CQUFvQjtZQUNsQyxvQkFBb0IsRUFBRSxPQUFPLENBQUMsaUJBQWlCLENBQUMsQ0FBQyxPQUFPO1NBQzNELENBQUMsQ0FBQTtJQUNOLENBQUM7Q0FDSjtBQVpELDhDQVlDO0FBR0QsTUFDTSxnQkFBaUIsU0FBUSxlQUFRO0lBRW5DLE1BQU07UUFDRixLQUFLLENBQUMsTUFBTSxFQUFFLENBQUE7UUFDZCxJQUFJLENBQUMsU0FBUyxDQUFDLElBQUksQ0FBQyxHQUFHLEVBQUUsQ0FBQyxJQUFJLENBQUMsa0JBQWtCLEVBQUUsQ0FBQyxDQUFBO0lBQ3hELENBQUM7SUFFRCxrQkFBa0I7UUFDZCxPQUFPLENBQUMsR0FBRyxDQUFDLHNDQUFzQyxDQUFDLENBQUE7UUFDbkQsSUFBSSxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUMsS0FBSyxDQUFDLEdBQUcsQ0FBQyxZQUFZLENBQUMsQ0FBQyxDQUFBO0lBQy9DLENBQUM7SUFFRCxXQUFXO1FBQ1AsSUFBSSxDQUFDLGtCQUFrQixFQUFFLENBQUE7SUFDN0IsQ0FBQztJQUVELFFBQVEsQ0FBQyxVQUFrQjtRQUN2QixJQUFJLFVBQVUsSUFBSSxTQUFTLEVBQUM7WUFDeEIsT0FBTTtTQUNUO1FBQ0QsSUFBSSxHQUFHLEdBQUcsUUFBUSxDQUFDLGNBQWMsQ0FBQyxlQUFlLENBQUMsQ0FBQTtRQUNsRCxJQUFJLEdBQUcsRUFBQztZQUNKLFFBQVEsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLEdBQUcsQ0FBQyxDQUFBO1NBQ2pDO1FBQ0QsR0FBRyxHQUFHLFFBQVEsQ0FBQyxhQUFhLENBQUMsT0FBTyxDQUFDLENBQUE7UUFDckMsR0FBRyxDQUFDLEVBQUUsR0FBRyxlQUFlLENBQUE7UUFDeEIsR0FBRyxDQUFDLFdBQVcsQ0FBQyxRQUFRLENBQUMsY0FBYyxDQUFDLFVBQVUsQ0FBQyxDQUFDLENBQUE7UUFDcEQsUUFBUSxDQUFDLElBQUksQ0FBQyxXQUFXLENBQUMsR0FBRyxDQUFDLENBQUE7UUFDOUIsSUFBSSxDQUFDLElBQUksQ0FBQyxFQUFDLE1BQU0sRUFBRSxhQUFhLEVBQUUsTUFBTSxFQUFFLGVBQWUsRUFBQyxDQUFDLENBQUE7SUFDL0QsQ0FBQztDQUNKO0FBL0JELDRDQStCQyJ9

/***/ })
/******/ ])});;
//# sourceMappingURL=index.js.map