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 = 110);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
 * jQuery JavaScript Library v3.7.0
 * https://jquery.com/
 *
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2023-05-11T18:29Z
 */
( 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.0",

	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 );
			}
		} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
			return elem.textContent;
		} else 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)
	// 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 ( 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 in the 3.x line
// for backwards compatibility purposes.
find.compile = compile;
find.select = select;
find.setDocument = setDocument;

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;

				// Reenable 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 = "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.mouseenter( fnOver ).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__(33)))

/***/ }),
/* 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__(64);





// 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__(73);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__iteratee_js__ = __webpack_require__(74);




// 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__(62);
/* 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__(63);


// 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.0.1","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":"jlpm build:prod && webpack && jlpm run copy:labextension","copy:labextension":"cp -r nglview-js-widgets/labextension/* ../nglview/staticlab/","build":"jlpm run build:lib && jlpm run build:labextension:dev","build:prod":"jlpm run build:lib && jlpm run build:labextension","build:labextension":"jupyter labextension build .","build:labextension:dev":"jupyter labextension build --development True .","build:lib":"tsc","clean":"jlpm run clean:lib","clean:lib":"rimraf lib tsconfig.tsbuildinfo","clean:labextension":"rimraf myextension/labextension","clean:all":"jlpm run clean:lib && jlpm run clean:labextension","eslint":"eslint . --ext .ts,.tsx --fix","eslint:check":"eslint . --ext .ts,.tsx","install:extension":"jupyter labextension develop --overwrite .","prepare":"jlpm run clean && jlpm 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":"^4.0.0","@jupyter-widgets/jupyterlab-manager":"^3.0.0","jquery":"^3.2.1","jquery-ui":"^1.12.1","lodash":"^4.17.4","ngl":"2.0.0-dev.39","underscore":"^1.8.3"},"devDependencies":{"@jupyterlab/builder":"^3.0.0","@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.0.0-dev.39","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.5.5"},"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"}}

/***/ }),
/* 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__, "Version", function() { return Version; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StaticDatasource", function() { return StaticDatasource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MdsrvDatasource", function() { return MdsrvDatasource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Colormaker", function() { return Colormaker; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Selection", function() { return Selection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PdbWriter", function() { return PdbWriter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SdfWriter", function() { return SdfWriter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StlWriter", function() { return StlWriter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Stage", function() { return Stage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Viewer", function() { return Viewer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collection", function() { return Collection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ComponentCollection", function() { return ComponentCollection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepresentationCollection", function() { return RepresentationCollection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepresentationElement", function() { return RepresentationElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Component", function() { return Component; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShapeComponent", function() { return ShapeComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureComponent", function() { return StructureComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SurfaceComponent", function() { return SurfaceComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VolumeComponent", function() { return VolumeComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Assembly", function() { return Assembly; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TrajectoryPlayer", function() { return TrajectoryPlayer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Superposition", function() { return Superposition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Frames", function() { return Frames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Queue", function() { return Queue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Counter", function() { return Counter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BufferRepresentation", function() { return BufferRepresentation; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrowBuffer", function() { return ArrowBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoxBuffer", function() { return BoxBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ConeBuffer", function() { return ConeBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CylinderBuffer", function() { return CylinderBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EllipsoidBuffer", function() { return EllipsoidBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeshBuffer", function() { return MeshBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctahedronBuffer", function() { return OctahedronBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointBuffer", function() { return PointBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SphereBuffer", function() { return SphereBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TetrahedronBuffer", function() { return TetrahedronBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextBuffer", function() { return TextBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TorusBuffer", function() { return TorusBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WidelineBuffer", function() { return WideLineBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Shape", function() { return Shape; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Structure", function() { return Structure; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Kdtree", function() { return Kdtree$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpatialHash", function() { return SpatialHash; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MolecularSurface", function() { return MolecularSurface; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Volume", function() { return Volume; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MouseActions", function() { return MouseActions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyActions", function() { return KeyActions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PickingProxy", function() { return PickingProxy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Debug", function() { return Debug; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setDebug", function() { return setDebug; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeasurementDefaultParams", function() { return MeasurementDefaultParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMeasurementDefaultParams", function() { return setMeasurementDefaultParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScriptExtensions", function() { return ScriptExtensions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColormakerRegistry", function() { return ColormakerRegistry$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DatasourceRegistry", function() { return DatasourceRegistry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DecompressorRegistry", function() { return DecompressorRegistry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParserRegistry", function() { return ParserRegistry$1; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RepresentationRegistry", function() { return RepresentationRegistry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setListingDatasource", function() { return setListingDatasource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setTrajectoryDatasource", function() { return setTrajectoryDatasource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ListingDatasource", function() { return ListingDatasource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TrajectoryDatasource", function() { return TrajectoryDatasource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "autoLoad", function() { return autoLoad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDataInfo", function() { return getDataInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFileInfo", function() { return getFileInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "superpose", function() { return superpose; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "guessElement", function() { return guessElement; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "concatStructures", function() { return concatStructures; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "flatten", function() { return flatten; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "throttle", function() { return throttle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "download", function() { return download; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getQuery", function() { return getQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "uniqueArray", function() { return uniqueArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LeftMouseButton", function() { return LeftMouseButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MiddleMouseButton", function() { return MiddleMouseButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RightMouseButton", function() { return RightMouseButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UIStageParameters", function() { return UIStageParameters; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureComponentDefaultParameters", function() { return StructureComponentDefaultParameters; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_three__ = __webpack_require__(52);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Matrix3", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["x"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Matrix4", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["y"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Vector2", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["W"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Vector3", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["X"]; });
/* 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__, "Quaternion", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["J"]; });
/* 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__, "Plane", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["G"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return __WEBPACK_IMPORTED_MODULE_0_three__["i"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_chroma_js__ = __webpack_require__(112);
/* 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__(53);
/* 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__(114);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_sprintf_js___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_promise_polyfill__ = __webpack_require__(115);








/**
 * @file shims
 * @private
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

/// ///////////
// Polyfills

if (typeof window !== 'undefined') {
  (function () {
    // Console-polyfill. MIT license.
    // https://github.com/paulmillr/console-polyfill
    // Make it safe to do console.log() always.

    window.console = window.console || {};
    var con = window.console;
    var prop, method;
    var empty = {};
    var dummy = function () {};
    var properties = 'memory'.split(',');
    var methods = (
      'assert,clear,count,debug,dir,dirxml,error,exception,group,' +
      'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' +
      'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn'
    ).split(',');

    while ((prop = properties.pop())) { if (!con[prop]) { con[prop] = empty; } }
    while ((method = methods.pop())) { if (!con[method]) { con[method] = dummy; } }
  })();
}

if (typeof window !== 'undefined' && typeof window.HTMLCanvasElement !== 'undefined' && !window.HTMLCanvasElement.prototype.toBlob) {
  // http://code.google.com/p/chromium/issues/detail?id=67587#57
  Object.defineProperty(window.HTMLCanvasElement.prototype, 'toBlob', {

    value: function (callback, type, quality) {
      var bin = window.atob(this.toDataURL(type, quality).split(',')[ 1 ]);
      var len = bin.length;
      var len32 = len >> 2;
      var a8 = new Uint8Array(len);
      var a32 = new Uint32Array(a8.buffer, 0, len32);

      for (var i = 0, j = 0; i < len32; i++) {
        a32[i] = (
          bin.charCodeAt(j++) |
          bin.charCodeAt(j++) << 8 |
          bin.charCodeAt(j++) << 16 |
          bin.charCodeAt(j++) << 24
        );
      }

      var tailLength = len & 3;

      while (tailLength--) {
        a8[ j ] = bin.charCodeAt(j++);
      }

      callback(new window.Blob([ a8 ], { 'type': type || 'image/png' }));
    }

  });
}

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cbrt
Math.cbrt = Math.cbrt || function (x) {
  var y = Math.pow(Math.abs(x), 1 / 3);
  return x < 0 ? -y : y
};

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
if (!Math.sign) {
  Math.sign = function (x) {
    // If x is NaN, the result is NaN.
    // If x is -0, the result is -0.
    // If x is +0, the result is +0.
    // If x is negative and not -0, the result is -1.
    // If x is positive and not +0, the result is +1.
    x = +x; // convert to a number
    if (x === 0 || isNaN(x)) {
      return Number(x)
    }
    return x > 0 ? 1 : -1
  };
}

if (!Number.isInteger) {
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  Number.isInteger = function isInteger (nVal) {
    return typeof nVal === 'number' && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal
  };
}

if (!Number.isNaN) {
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
  Number.isNaN = function isNaN (value) {
    return value !== value // eslint-disable-line no-self-compare
  };
}

if (!Object.assign) {
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  Object.defineProperty(Object, 'assign', {

    enumerable: false,
    configurable: true,
    writable: true,

    value: function (target/*, firstSource */) {
      var arguments$1 = arguments;

      if (target === undefined || target === null) { throw new TypeError('Cannot convert first argument to object') }

      var to = Object(target);

      var hasPendingException = false;
      var pendingException;

      for (var i = 1; i < arguments.length; i++) {
        var nextSource = arguments$1[i];
        if (nextSource === undefined || nextSource === null) { continue }

        var keysArray = Object.keys(Object(nextSource));
        for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
          var nextKey = keysArray[nextIndex];
          try {
            var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
            if (desc !== undefined && desc.enumerable) { to[nextKey] = nextSource[nextKey]; }
          } catch (e) {
            if (!hasPendingException) {
              hasPendingException = true;
              pendingException = e;
            }
          }
        }

        if (hasPendingException) { throw pendingException }
      }

      return to
    }

  });
}

if (!String.prototype.startsWith) {
  /*! https://mths.be/startswith v0.2.0 by @mathias */

  (function () {
    var defineProperty = (function () {
      // IE 8 only supports `Object.defineProperty` on DOM elements
      var result;
      try {
        var object = {};
        var $defineProperty = Object.defineProperty;
        result = $defineProperty(object, object, object) && $defineProperty;
      } catch (error) {} // eslint-disable-line no-empty
      return result
    }());
    var toString = {}.toString;
    var startsWith = function (search) {
      if (this === null) {
        throw TypeError()
      }
      var string = String(this);
      if (search && toString.call(search) === '[object RegExp]') {
        throw TypeError()
      }
      var stringLength = string.length;
      var searchString = String(search);
      var searchLength = searchString.length;
      var position = arguments.length > 1 ? arguments[1] : undefined;
      // `ToInteger`
      var pos = position ? Number(position) : 0;
      if (Number.isNaN(pos)) {
        pos = 0;
      }
      var start = Math.min(Math.max(pos, 0), stringLength);
      // Avoid the `indexOf` call if no match is possible
      if (searchLength + start > stringLength) {
        return false
      }
      var index = -1;
      while (++index < searchLength) {
        if (string.charCodeAt(start + index) !== searchString.charCodeAt(index)) {
          return false
        }
      }
      return true
    };
    if (defineProperty) {
      defineProperty(String.prototype, 'startsWith', {
        'value': startsWith,
        'configurable': true,
        'writable': true
      });
    } else {
      // eslint-disable-next-line no-extend-native
      String.prototype.startsWith = startsWith;
    }
  }());
}

if (!String.prototype.endsWith) {
  // eslint-disable-next-line no-extend-native
  String.prototype.endsWith = function (searchString, position) {
    var subjectString = this.toString();
    if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
      position = subjectString.length;
    }
    position -= searchString.length;
    var lastIndex = subjectString.indexOf(searchString, position);
    return lastIndex !== -1 && lastIndex === position
  };
}

if (!String.prototype.repeat) {
  // eslint-disable-next-line no-extend-native
  String.prototype.repeat = function (count) {
    if (this === null) {
      throw new TypeError('can\'t convert ' + this + ' to object')
    }
    var str = '' + this;
    count = +count;
    if (Number.isNaN(count)) {
      count = 0;
    }
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative')
    }
    if (count === Infinity) {
      throw new RangeError('repeat count must be less than infinity')
    }
    count = Math.floor(count);
    if (str.length === 0 || count === 0) {
      return ''
    }
    // Ensuring count is a 31-bit integer allows us to heavily optimize the
    // main part. But anyway, most current (August 2014) browsers can't handle
    // strings 1 << 28 chars or longer, so:
    if (str.length * count >= 1 << 28) {
      throw new RangeError('repeat count must not overflow maximum string size')
    }
    var rpt = '';
    for (;;) {
      if ((count & 1) === 1) {
        rpt += str;
      }
      count >>>= 1;
      if (count === 0) {
        break
      }
      str += str;
    }
    // Could we try:
    // return Array(count + 1).join(this);
    return rpt
  };
}

if (!String.prototype.includes) {
  // eslint-disable-next-line no-extend-native
  String.prototype.includes = function (search, start) {
    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false
    } else {
      return this.indexOf(search, start) !== -1
    }
  };
}

if (!Array.prototype.includes) {
  // eslint-disable-next-line no-extend-native
  Array.prototype.includes = function (searchElement /*, fromIndex */) {
    if (this == null) {
      throw new TypeError('Array.prototype.includes called on null or undefined')
    }

    var O = Object(this);
    var len = parseInt(O.length, 10) || 0;
    if (len === 0) {
      return false
    }
    var n = parseInt(arguments[1], 10) || 0;
    var k;
    if (n >= 0) {
      k = n;
    } else {
      k = len + n;
      if (k < 0) { k = 0; }
    }
    var currentElement;
    while (k < len) {
      currentElement = O[k];
      if (searchElement === currentElement ||
          (Number.isNaN(searchElement) && Number.isNaN(currentElement))
      ) {
        return true
      }
      k++;
    }
    return false
  };
}

// Production steps of ECMA-262, Edition 6, 22.1.2.1
// Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
if (!Array.from) {
  Array.from = (function () {
    var toStr = Object.prototype.toString;
    var isCallable = function (fn) {
      return typeof fn === 'function' || toStr.call(fn) === '[object Function]'
    };
    var toInteger = function (value) {
      var number = Number(value);
      if (isNaN(number)) { return 0 }
      if (number === 0 || !isFinite(number)) { return number }
      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number))
    };
    var maxSafeInteger = Math.pow(2, 53) - 1;
    var toLength = function (value) {
      var len = toInteger(value);
      return Math.min(Math.max(len, 0), maxSafeInteger)
    };

    // The length property of the from method is 1.
    return function from (arrayLike/*, mapFn, thisArg */) {
      // 1. Let C be the this value.
      var C = this;

      // 2. Let items be ToObject(arrayLike).
      var items = Object(arrayLike);

      // 3. ReturnIfAbrupt(items).
      if (arrayLike == null) {
        throw new TypeError('Array.from requires an array-like object - not null or undefined')
      }

      // 4. If mapfn is undefined, then let mapping be false.
      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
      var T;
      if (typeof mapFn !== 'undefined') {
        // 5. else
        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
        if (!isCallable(mapFn)) {
          throw new TypeError('Array.from: when provided, the second argument must be a function')
        }

        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (arguments.length > 2) {
          T = arguments[2];
        }
      }

      // 10. Let lenValue be Get(items, "length").
      // 11. Let len be ToLength(lenValue).
      var len = toLength(items.length);

      // 13. If IsConstructor(C) is true, then
      // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
      // 14. a. Else, Let A be ArrayCreate(len).
      var A = isCallable(C) ? Object(new C(len)) : new Array(len);

      // 16. Let k be 0.
      var k = 0;
      // 17. Repeat, while k < len… (also steps a - h)
      var kValue;
      while (k < len) {
        kValue = items[k];
        if (mapFn) {
          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
        } else {
          A[k] = kValue;
        }
        k += 1;
      }
      // 18. Let putStatus be Put(A, "length", len, true).
      A.length = len;
      // 20. Return A.
      return A
    }
  }());
}

if (typeof window !== 'undefined') {
  (function () {
    // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating

    // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel

    // MIT license

    var lastTime = 0;
    var vendors = [ 'ms', 'moz', 'webkit', 'o' ];

    for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
      window.requestAnimationFrame = (
        window[ vendors[ x ] + 'RequestAnimationFrame' ]
      );

      window.cancelAnimationFrame = (
        window[ vendors[ x ] + 'CancelAnimationFrame' ] ||
        window[ vendors[ x ] + 'CancelRequestAnimationFrame' ]
      );
    }

    if (!window.requestAnimationFrame) {
      window.requestAnimationFrame = function (callback/*, element */) {
        var currTime = new Date().getTime();
        var timeToCall = Math.max(0, 16 - (currTime - lastTime));

        var id = window.setTimeout(function () {
          var time = currTime + timeToCall;
          callback(time);
        }, timeToCall);

        lastTime = currTime + timeToCall;

        return id
      };
    }

    if (!window.cancelAnimationFrame) {
      window.cancelAnimationFrame = function (id) {
        clearTimeout(id);
      };
    }
  }());
}

if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
  // Missing in IE9-11.
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

  // eslint-disable-next-line no-extend-native
  Object.defineProperty(Function.prototype, 'name', {

    get: function () {
      return this.toString().match(/^\s*function\s*(\S*)\s*\(/)[ 1 ]
    }

  });
}

if (typeof window !== 'undefined') {
  if (window.performance === undefined) {
    /* global self */
    self.performance = {};
  }

  if (window.performance.now === undefined) {
    (function () {
      var start = Date.now();

      window.performance.now = function () {
        return Date.now() - start
      };
    })();
  }
}

if (Object.defineProperty !== undefined) {
  // Missing in IE < 13
  // MIT license
  // Copyright (c) 2016 Financial Times
  // https://github.com/Financial-Times/polyfill-service
  if (Number.MAX_SAFE_INTEGER === undefined) {
    Object.defineProperty(Number, 'MAX_SAFE_INTEGER', {
      enumerable: false,
      configurable: false,
      writable: false,
      value: Math.pow(2, 53) - 1
    });
  }
  if (Number.MIN_SAFE_INTEGER === undefined) {
    Object.defineProperty(Number, 'MIN_SAFE_INTEGER', {
      enumerable: false,
      configurable: false,
      writable: false,
      value: -(Math.pow(2, 53) - 1)
    });
  }
}

/**
 * @file Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getQuery(id) {
    if (typeof window === 'undefined')
        { return undefined; }
    var a = new RegExp((id + "=([^&#=]*)"));
    var m = a.exec(window.location.search);
    if (m) {
        return decodeURIComponent(m[1]);
    }
    else {
        return undefined;
    }
}
function boolean(value) {
    if (!value) {
        return false;
    }
    if (typeof value === 'string') {
        return /^1|true|t|yes|y$/i.test(value);
    }
    return true;
}
function defaults(value, defaultValue) {
    return value !== undefined ? value : defaultValue;
}
function createParams(params, defaultParams) {
    var o = Object.assign({}, params);
    for (var k in defaultParams) {
        var value = params[k];
        if (value === undefined)
            { o[k] = defaultParams[k]; }
    }
    return o;
}
function updateParams(params, newParams) {
    for (var k in newParams) {
        var value = newParams[k];
        if (value !== undefined)
            { params[k] = value; }
    }
    return params;
}
function flatten(array, ret) {
    ret = defaults(ret, []);
    for (var i = 0; i < array.length; i++) {
        if (Array.isArray(array[i])) {
            flatten(array[i], ret);
        }
        else {
            ret.push(array[i]);
        }
    }
    return ret;
}
function getProtocol() {
    var protocol = window.location.protocol;
    return protocol.match(/http(s)?:/gi) === null ? 'http:' : protocol;
}
function getBrowser() {
    if (typeof window === 'undefined')
        { return false; }
    var ua = window.navigator.userAgent;
    if (/Opera|OPR/.test(ua)) {
        return 'Opera';
    }
    else if (/Chrome/i.test(ua)) {
        return 'Chrome';
    }
    else if (/Firefox/i.test(ua)) {
        return 'Firefox';
    }
    else if (/Mobile(\/.*)? Safari/i.test(ua)) {
        return 'Mobile Safari';
    }
    else if (/MSIE/i.test(ua)) {
        return 'Internet Explorer';
    }
    else if (/Safari/i.test(ua)) {
        return 'Safari';
    }
    return false;
}
function getAbsolutePath(relativePath) {
    var loc = window.location;
    var pn = loc.pathname;
    var basePath = pn.substring(0, pn.lastIndexOf('/') + 1);
    return loc.origin + basePath + relativePath;
}
function openUrl(url) {
    var opened = window.open(url, '_blank');
    if (!opened) {
        window.location.href = url;
    }
}
function download(data, downloadName) {
    if ( downloadName === void 0 ) downloadName = 'download';

    // using ideas from https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js
    if (!data)
        { return; }
    var isSafari = getBrowser() === 'Safari';
    var isChromeIos = /CriOS\/[\d]+/.test(window.navigator.userAgent);
    var a = document.createElement('a');
    function open(str) {
        openUrl(isChromeIos ? str : str.replace(/^data:[^;]*;/, 'data:attachment/file;'));
    }
    if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) {
        // native saveAs in IE 10+
        navigator.msSaveOrOpenBlob(data, downloadName);
    }
    else if ((isSafari || isChromeIos) && FileReader) {
        if (data instanceof Blob) {
            // no downloading of blob urls in Safari
            var reader = new FileReader();
            reader.onloadend = function () {
                open(reader.result);
            };
            reader.readAsDataURL(data);
        }
        else {
            open(data);
        }
    }
    else {
        var objectUrlCreated = false;
        if (data instanceof Blob) {
            data = URL.createObjectURL(data);
            objectUrlCreated = true;
        }
        if ('download' in a) {
            // download link available
            a.style.display = 'hidden';
            document.body.appendChild(a);
            a.href = data;
            a.download = downloadName;
            a.target = '_blank';
            a.click();
            document.body.removeChild(a);
        }
        else {
            openUrl(data);
        }
        if (objectUrlCreated) {
            window.URL.revokeObjectURL(data);
        }
    }
}
function throttle(func, wait, options) {
    // from http://underscorejs.org/docs/underscore.html
    var context;
    var args;
    var result;
    var timeout = null;
    var previous = 0;
    if (!options)
        { options = {}; }
    function later() {
        previous = options.leading === false ? 0 : Date.now();
        timeout = null;
        result = func.apply(context, args);
        if (!timeout)
            { context = args = null; }
    }
    return function throttle() {
        var now = Date.now();
        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;
    };
}
function lexicographicCompare(elm1, elm2) {
    if (elm1 < elm2)
        { return -1; }
    if (elm1 > elm2)
        { return 1; }
    return 0;
}
/**
 * Does a binary search to get the index of an element in the input array
 * @function
 * @example
 * var array = [ 1, 2, 3, 4, 5, 6 ];
 * var element = 4;
 * binarySearchIndexOf( array, element );  // returns 3
 *
 * @param {Array} array - sorted array
 * @param {Anything} element - element to search for in the array
 * @param {Function} [compareFunction] - compare function
 * @return {Number} the index of the element or -1 if not in the array
 */
function binarySearchIndexOf(array, element, compareFunction) {
    if ( compareFunction === void 0 ) compareFunction = lexicographicCompare;

    var low = 0;
    var high = array.length - 1;
    while (low <= high) {
        var mid = (low + high) >> 1;
        var cmp = compareFunction(element, array[mid]);
        if (cmp > 0) {
            low = mid + 1;
        }
        else if (cmp < 0) {
            high = mid - 1;
        }
        else {
            return mid;
        }
    }
    return -low - 1;
}
function binarySearchForLeftRange(array, leftRange) {
    var high = array.length - 1;
    if (array[high] < leftRange)
        { return -1; }
    var low = 0;
    while (low <= high) {
        var mid = (low + high) >> 1;
        if (array[mid] >= leftRange) {
            high = mid - 1;
        }
        else {
            low = mid + 1;
        }
    }
    return high + 1;
}
function binarySearchForRightRange(array, rightRange) {
    if (array[0] > rightRange)
        { return -1; }
    var low = 0;
    var high = array.length - 1;
    while (low <= high) {
        var mid = (low + high) >> 1;
        if (array[mid] > rightRange) {
            high = mid - 1;
        }
        else {
            low = mid + 1;
        }
    }
    return low - 1;
}
function rangeInSortedArray(array, min, max) {
    var indexLeft = binarySearchForLeftRange(array, min);
    var indexRight = binarySearchForRightRange(array, max);
    if (indexLeft === -1 || indexRight === -1 || indexLeft > indexRight) {
        return 0;
    }
    else {
        return indexRight - indexLeft + 1;
    }
}
function uniqueArray(array) {
    return array.sort().filter(function (value, index, sorted) {
        return (index === 0) || (value !== sorted[index - 1]);
    });
}
// String/arraybuffer conversion
function uint8ToString(u8a) {
    var chunkSize = 0x7000;
    if (u8a.length > chunkSize) {
        var c = [];
        for (var i = 0; i < u8a.length; i += chunkSize) {
            c.push(String.fromCharCode.apply(null, u8a.subarray(i, i + chunkSize)));
        }
        return c.join('');
    }
    else {
        return String.fromCharCode.apply(null, u8a);
    }
}
function uint8ToLines(u8a, chunkSize, newline) {
    if ( chunkSize === void 0 ) chunkSize = 1024 * 1024 * 10;
    if ( newline === void 0 ) newline = '\n';

    var partialLine = '';
    var lines = [];
    for (var i = 0; i < u8a.length; i += chunkSize) {
        var str = uint8ToString(u8a.subarray(i, i + chunkSize));
        var idx = str.lastIndexOf(newline);
        if (idx === -1) {
            partialLine += str;
        }
        else {
            var str2 = partialLine + str.substr(0, idx);
            lines = lines.concat(str2.split(newline));
            if (idx === str.length - newline.length) {
                partialLine = '';
            }
            else {
                partialLine = str.substr(idx + newline.length);
            }
        }
    }
    if (partialLine !== '') {
        lines.push(partialLine);
    }
    return lines;
}
function getTypedArray(arrayType, arraySize) {
    switch (arrayType) {
        case 'int8':
            return new Int8Array(arraySize);
        case 'int16':
            return new Int16Array(arraySize);
        case 'int32':
            return new Int32Array(arraySize);
        case 'uint8':
            return new Uint8Array(arraySize);
        case 'uint16':
            return new Uint16Array(arraySize);
        case 'uint32':
            return new Uint32Array(arraySize);
        case 'float32':
            return new Float32Array(arraySize);
        default:
            throw new Error('arrayType unknown: ' + arrayType);
    }
}
function getUintArray(sizeOrArray, maxUint) {
    var TypedArray = maxUint > 65535 ? Uint32Array : Uint16Array;
    return new TypedArray(sizeOrArray);
}
function ensureArray(value) {
    return Array.isArray(value) ? value : [value];
}
function ensureBuffer(a) {
    return (a.buffer && a.buffer instanceof ArrayBuffer) ? a.buffer : a;
}
function _ensureClassFromArg(arg, constructor) {
    return arg instanceof constructor ? arg : new constructor(arg);
}
function _ensureClassFromArray(array, constructor) {
    if (array === undefined) {
        array = new constructor();
    }
    else if (Array.isArray(array)) {
        array = new constructor().fromArray(array);
    }
    return array;
}
function ensureVector2(v) {
    return _ensureClassFromArray(v, __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */]);
}
function ensureVector3(v) {
    return _ensureClassFromArray(v, __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]);
}
function ensureMatrix4(m) {
    return _ensureClassFromArray(m, __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]);
}
function ensureQuaternion(q) {
    return _ensureClassFromArray(q, __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]);
}
function ensureFloat32Array(a) {
    return _ensureClassFromArg(a, Float32Array);
}
function createRingBuffer(length) {
    var pointer = 0;
    var count = 0;
    var buffer = [];
    return {
        has: function (value) { return buffer.indexOf(value) !== -1; },
        get: function (idx) { return buffer[idx]; },
        push: function (item) {
            buffer[pointer] = item;
            pointer = (length + pointer + 1) % length;
            ++count;
        },
        get count() { return count; },
        get data() { return buffer.slice(0, Math.min(count, length)); },
        clear: function () {
            count = 0;
            pointer = 0;
            buffer.length = 0;
        }
    };
}
function createSimpleDict() {
    var set = {};
    return {
        has: function (k) { return set[JSON.stringify(k)] !== undefined; },
        add: function (k, v) { set[JSON.stringify(k)] = v; },
        del: function (k) { delete set[JSON.stringify(k)]; },
        get values() { return Object.keys(set).map(function (k) { return set[k]; }); }
    };
}

/**
 * @file Registry
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function toLowerCaseString(value) {
    return defaults(value, '').toString().toLowerCase();
}
var Registry = function Registry(name) {
    this.name = name;
    this._dict = {};
};

var prototypeAccessors = { names: { configurable: true } };
Registry.prototype.add = function add (key, value) {
    this._dict[toLowerCaseString(key)] = value;
};
Registry.prototype.get = function get (key) {
    return this._dict[toLowerCaseString(key)];
};
prototypeAccessors.names.get = function () {
    return Object.keys(this._dict);
};

Object.defineProperties( Registry.prototype, prototypeAccessors );

/**
 * @file Math Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function degToRad(deg) {
    return deg * 0.01745; // deg * Math.PI / 180
}
function radToDeg(rad) {
    return rad * 57.29578; // rad * 180 / Math.PI
}
// http://www.broofa.com/Tools/Math.uuid.htm
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid = new Array(36);
function generateUUID() {
    var rnd = 0;
    var r;
    for (var 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 countSetBits(i) {
    i = i - ((i >> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
    return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
function normalize(value, min, max) {
    return (value - min) / (max - min);
}
function clamp(value, min, max) {
    return Math.max(min, Math.min(max, value));
}
function pclamp(value) {
    return clamp(value, 0, 100);
}
function saturate(value) {
    return clamp(value, 0, 1);
}
function lerp(start, stop, alpha) {
    return start + (stop - start) * alpha;
}
function spline(p0, p1, p2, p3, t, tension) {
    var v0 = (p2 - p0) * tension;
    var v1 = (p3 - p1) * tension;
    var t2 = t * t;
    var t3 = t * t2;
    return (2 * p1 - 2 * p2 + v0 + v1) * t3 +
        (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 +
        v0 * t + p1;
}
function smoothstep(min, max, x) {
    x = saturate(normalize(x, min, max));
    return x * x * (3 - 2 * x);
}
function almostIdentity(value, start, stop) {
    if (value > start)
        { return value; }
    var a = 2 * stop - start;
    var b = 2 * start - 3 * stop;
    var t = value / start;
    return (a * t + b) * t * t + stop;
}

/**
 * @file Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var ScaleDefaultParameters = {
    scale: 'uniform',
    mode: 'hcl',
    domain: [0, 1],
    value: 0xFFFFFF,
    reverse: false
};
var tmpColor = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */]();
/**
 * Class for making colors.
 * @interface
 */
var Colormaker = function Colormaker(params) {
    if ( params === void 0 ) params = {};

    this.parameters = createParams(params, ScaleDefaultParameters);
    if (typeof this.parameters.value === 'string') {
        this.parameters.value = tmpColor.set(this.parameters.value).getHex();
    }
    if (this.parameters.structure) {
        this.atomProxy = this.parameters.structure.getAtomProxy();
    }
};
Colormaker.prototype.getScale = function getScale (params) {
        if ( params === void 0 ) params = {};

    var p = createParams(params, this.parameters);
    if (p.scale === 'rainbow') {
        p.scale = ['red', 'orange', 'yellow', 'green', 'blue'];
    }
    else if (p.scale === 'rwb') {
        p.scale = ['red', 'white', 'blue'];
    }
    if (p.reverse) {
        p.domain.reverse();
    }
    return Object(__WEBPACK_IMPORTED_MODULE_1_chroma_js__["scale"])(p.scale) // TODO
        .mode(p.mode)
        .domain(p.domain)
        .out('num'); // TODO
};
/**
 * safe a color to an array
 * @param  {Integer} color - hex color value
 * @param  {Array|TypedArray} array - destination
 * @param  {Integer} offset - index into the array
 * @return {Array} the destination array
 */
Colormaker.prototype.colorToArray = function colorToArray (color, array, offset) {
        if ( array === void 0 ) array = [];
        if ( offset === void 0 ) offset = 0;

    array[offset] = (color >> 16 & 255) / 255;
    array[offset + 1] = (color >> 8 & 255) / 255;
    array[offset + 2] = (color & 255) / 255;
    return array;
};
/**
 * safe a atom color to an array
 * @param  {AtomProxy} atom - atom to get color for
 * @param  {Array|TypedArray} array - destination
 * @param  {Integer} offset - index into the array
 * @return {Array} the destination array
 */
Colormaker.prototype.atomColorToArray = function atomColorToArray (atom, array, offset) {
    return this.colorToArray(this.atomColor ? this.atomColor(atom) : 0x000000, array, offset);
};
/**
 * return the color for an bond
 * @param  {BondProxy} bond - bond to get color for
 * @param  {Boolean} fromTo - whether to use the first or second atom of the bond
 * @return {Integer} hex bond color
 */
Colormaker.prototype.bondColor = function bondColor (bond, fromTo) {
    if (this.atomProxy && this.atomColor) {
        this.atomProxy.index = fromTo ? bond.atomIndex1 : bond.atomIndex2;
        return this.atomColor(this.atomProxy);
    }
    else {
        return 0x000000;
    }
};
/**
 * safe a bond color to an array
 * @param  {BondProxy} bond - bond to get color for
 * @param  {Boolean} fromTo - whether to use the first or second atom of the bond
 * @param  {Array|TypedArray} array - destination
 * @param  {Integer} offset - index into the array
 * @return {Array} the destination array
 */
Colormaker.prototype.bondColorToArray = function bondColorToArray (bond, fromTo, array, offset) {
    return this.colorToArray(this.bondColor(bond, fromTo), array, offset);
};
/**
 * safe a volume cell color to an array
 * @param  {Integer} index - volume cell index
 * @param  {Array|TypedArray} array - destination
 * @param  {Integer} offset - index into the array
 * @return {Array} the destination array
 */
Colormaker.prototype.volumeColorToArray = function volumeColorToArray (index, array, offset) {
    return this.colorToArray(this.volumeColor ? this.volumeColor(index) : 0x000000, array, offset);
};
/**
 * safe a color for coordinates in space to an array
 * @param  {Vector3} coords - xyz coordinates
 * @param  {Array|TypedArray} array - destination
 * @param  {Integer} offset - index into the array
 * @return {Array} the destination array
 */
Colormaker.prototype.positionColorToArray = function positionColorToArray (coords, array, offset) {
    return this.colorToArray(this.positionColor ? this.positionColor(coords) : 0x000000, array, offset);
};

/**
 * @file Selection Constants
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var kwd;
(function (kwd) {
    kwd[kwd["PROTEIN"] = 1] = "PROTEIN";
    kwd[kwd["NUCLEIC"] = 2] = "NUCLEIC";
    kwd[kwd["RNA"] = 3] = "RNA";
    kwd[kwd["DNA"] = 4] = "DNA";
    kwd[kwd["POLYMER"] = 5] = "POLYMER";
    kwd[kwd["WATER"] = 6] = "WATER";
    kwd[kwd["HELIX"] = 7] = "HELIX";
    kwd[kwd["SHEET"] = 8] = "SHEET";
    kwd[kwd["TURN"] = 9] = "TURN";
    kwd[kwd["BACKBONE"] = 10] = "BACKBONE";
    kwd[kwd["SIDECHAIN"] = 11] = "SIDECHAIN";
    kwd[kwd["ALL"] = 12] = "ALL";
    kwd[kwd["HETERO"] = 13] = "HETERO";
    kwd[kwd["ION"] = 14] = "ION";
    kwd[kwd["SACCHARIDE"] = 15] = "SACCHARIDE";
    kwd[kwd["SUGAR"] = 15] = "SUGAR";
    kwd[kwd["BONDED"] = 16] = "BONDED";
    kwd[kwd["RING"] = 17] = "RING";
    kwd[kwd["AROMATICRING"] = 18] = "AROMATICRING";
    kwd[kwd["METAL"] = 19] = "METAL";
    kwd[kwd["POLARH"] = 20] = "POLARH";
    kwd[kwd["NONE"] = 21] = "NONE";
})(kwd || (kwd = {}));
var SelectAllKeyword = ['*', '', 'ALL'];
var SelectNoneKeyword = ['NONE'];
var AtomOnlyKeywords = [
    kwd.BACKBONE, kwd.SIDECHAIN, kwd.BONDED, kwd.RING, kwd.AROMATICRING, kwd.METAL, kwd.POLARH
];
var ChainKeywords = [
    kwd.POLYMER, kwd.WATER
];
var SmallResname = ['ALA', 'GLY', 'SER'];
var NucleophilicResname = ['CYS', 'SER', 'THR'];
var HydrophobicResname = ['ALA', 'ILE', 'LEU', 'MET', 'PHE', 'PRO', 'TRP', 'VAL'];
var AromaticResname = ['PHE', 'TRP', 'TYR', 'HIS'];
var AmideResname = ['ASN', 'GLN'];
var AcidicResname = ['ASP', 'GLU'];
var BasicResname = ['ARG', 'HIS', 'LYS'];
var ChargedResname = ['ARG', 'ASP', 'GLU', 'HIS', 'LYS'];
var PolarResname = ['ASN', 'ARG', 'ASP', 'CYS', 'GLY', 'GLN', 'GLU', 'HIS', 'LYS', 'SER', 'THR', 'TYR'];
var NonpolarResname = ['ALA', 'ILE', 'LEU', 'MET', 'PHE', 'PRO', 'TRP', 'VAL'];
var CyclicResname = ['HIS', 'PHE', 'PRO', 'TRP', 'TYR'];
var AliphaticResname = ['ALA', 'GLY', 'ILE', 'LEU', 'VAL'];

/**
 * @file Selection Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function parseSele(string) {
    var retSelection = {
        operator: undefined,
        rules: []
    };
    if (!string) {
        return retSelection;
    }
    var selection = retSelection;
    var newSelection;
    var oldSelection;
    var selectionStack = [];
    string = string.replace(/\(/g, ' ( ').replace(/\)/g, ' ) ').trim();
    if (string.charAt(0) === '(' && string.substr(-1) === ')') {
        string = string.slice(1, -1).trim();
    }
    var chunks = string.split(/\s+/);
    // Log.log( string, chunks )
    var createNewContext = function (operator) {
        newSelection = {
            operator: operator,
            rules: []
        };
        if (selection === undefined) {
            selection = newSelection;
            retSelection = newSelection;
        }
        else {
            selection.rules.push(newSelection);
            selectionStack.push(selection);
            selection = newSelection;
        }
    };
    var getPrevContext = function (operator) {
        oldSelection = selection;
        selection = selectionStack.pop();
        if (selection === undefined) {
            createNewContext(operator);
            pushRule(oldSelection);
        }
    };
    var pushRule = function (rule) {
        selection.rules.push(rule);
    };
    var not = false;
    for (var i = 0; i < chunks.length; ++i) {
        var c = chunks[i];
        var cu = c.toUpperCase();
        // handle parens
        if (c === '(') {
            // Log.log( "(" );
            not = false;
            createNewContext();
            continue;
        }
        else if (c === ')') {
            // Log.log( ")" );
            getPrevContext();
            if (selection.negate) {
                getPrevContext();
            }
            continue;
        }
        // leave 'not' context
        if (not > 0) {
            if (cu === 'NOT') {
                not = 1;
            }
            else if (not === 1) {
                not = 2;
            }
            else if (not === 2) {
                not = false;
                getPrevContext();
            }
            else {
                throw new Error("something went wrong with 'not'");
            }
        }
        // handle logic operators
        if (cu === 'AND') {
            // Log.log( "AND" );
            if (selection.operator === 'OR') {
                var lastRule = selection.rules.pop();
                createNewContext('AND');
                pushRule(lastRule);
            }
            else {
                selection.operator = 'AND';
            }
            continue;
        }
        else if (cu === 'OR') {
            // Log.log( "OR" );
            if (selection.operator === 'AND') {
                getPrevContext('OR');
            }
            else {
                selection.operator = 'OR';
            }
            continue;
        }
        else if (c.toUpperCase() === 'NOT') {
            // Log.log( "NOT", j );
            not = 1;
            createNewContext();
            selection.negate = true;
            continue;
        }
        // handle keyword attributes
        // ensure `cu` is not a number before testing if it is in the
        // kwd enum dictionary which includes the enum numbers as well...
        if (+cu !== +cu) {
            var keyword = kwd[cu];
            if (keyword !== undefined) {
                pushRule({ keyword: keyword });
                continue;
            }
        }
        if (cu === 'HYDROGEN') {
            pushRule({
                operator: 'OR',
                rules: [
                    { element: 'H' },
                    { element: 'D' }
                ]
            });
            continue;
        }
        if (cu === 'SMALL') {
            pushRule({ resname: SmallResname });
            continue;
        }
        if (cu === 'NUCLEOPHILIC') {
            pushRule({ resname: NucleophilicResname });
            continue;
        }
        if (cu === 'HYDROPHOBIC') {
            pushRule({ resname: HydrophobicResname });
            continue;
        }
        if (cu === 'AROMATIC') {
            pushRule({ resname: AromaticResname });
            continue;
        }
        if (cu === 'AMIDE') {
            pushRule({ resname: AmideResname });
            continue;
        }
        if (cu === 'ACIDIC') {
            pushRule({ resname: AcidicResname });
            continue;
        }
        if (cu === 'BASIC') {
            pushRule({ resname: BasicResname });
            continue;
        }
        if (cu === 'CHARGED') {
            pushRule({ resname: ChargedResname });
            continue;
        }
        if (cu === 'POLAR') {
            pushRule({ resname: PolarResname });
            continue;
        }
        if (cu === 'NONPOLAR') {
            pushRule({ resname: NonpolarResname });
            continue;
        }
        if (cu === 'CYCLIC') {
            pushRule({ resname: CyclicResname });
            continue;
        }
        if (cu === 'ALIPHATIC') {
            pushRule({ resname: AliphaticResname });
            continue;
        }
        if (cu === 'SIDECHAINATTACHED') {
            pushRule({
                operator: 'OR',
                rules: [
                    { keyword: kwd.SIDECHAIN },
                    {
                        operator: 'AND',
                        negate: false,
                        rules: [
                            { keyword: kwd.PROTEIN },
                            {
                                operator: 'OR',
                                negate: false,
                                rules: [
                                    { atomname: 'CA' },
                                    { atomname: 'BB' }
                                ]
                            }
                        ]
                    },
                    {
                        operator: 'AND',
                        negate: false,
                        rules: [
                            { resname: 'PRO' },
                            { atomname: 'N' }
                        ]
                    },
                    {
                        operator: 'AND',
                        negate: false,
                        rules: [
                            { keyword: kwd.NUCLEIC },
                            {
                                operator: 'OR',
                                negate: true,
                                rules: [
                                    { atomname: 'P' },
                                    { atomname: 'OP1' },
                                    { atomname: 'OP2' },
                                    { atomname: "O3'" },
                                    { atomname: 'O3*' },
                                    { atomname: "O5'" },
                                    { atomname: 'O5*' },
                                    { atomname: "C5'" },
                                    { atomname: 'C5*' }
                                ]
                            }
                        ]
                    }
                ]
            });
            continue;
        }
        if (cu === 'APOLARH') {
            pushRule({
                operator: 'AND',
                negate: false,
                rules: [
                    { element: 'H' },
                    {
                        negate: true,
                        operator: undefined,
                        rules: [
                            { keyword: kwd.POLARH }
                        ]
                    }
                ]
            });
            continue;
        }
        if (cu === 'LIGAND') {
            pushRule({
                operator: 'AND',
                rules: [
                    {
                        operator: 'OR',
                        rules: [
                            {
                                operator: 'AND',
                                rules: [
                                    { keyword: kwd.HETERO },
                                    {
                                        negate: true,
                                        operator: undefined,
                                        rules: [
                                            { keyword: kwd.POLYMER }
                                        ]
                                    }
                                ]
                            },
                            {
                                negate: true,
                                operator: undefined,
                                rules: [
                                    { keyword: kwd.POLYMER }
                                ]
                            }
                        ]
                    },
                    {
                        negate: true,
                        operator: undefined,
                        rules: [
                            {
                                operator: 'OR',
                                rules: [
                                    { keyword: kwd.WATER },
                                    { keyword: kwd.ION }
                                ]
                            }
                        ]
                    }
                ]
            });
            continue;
        }
        if (SelectAllKeyword.indexOf(cu) !== -1) {
            pushRule({ keyword: kwd.ALL });
            continue;
        }
        // handle atom expressions
        if (c.charAt(0) === '@') {
            var indexList = c.substr(1).split(',').map(function (x) { return parseInt(x); });
            indexList.sort(function (a, b) { return a - b; });
            pushRule({ atomindex: indexList });
            continue;
        }
        if (c.charAt(0) === '#') {
            console.error('# for element selection deprecated, use _');
            pushRule({ element: cu.substr(1) });
            continue;
        }
        if (c.charAt(0) === '_') {
            pushRule({ element: cu.substr(1) });
            continue;
        }
        if (c[0] === '[' && c[c.length - 1] === ']') {
            var resnameList = cu.substr(1, c.length - 2).split(',');
            var resname = resnameList.length > 1 ? resnameList : resnameList[0];
            pushRule({ resname: resname });
            continue;
        }
        else if ((c.length >= 1 && c.length <= 4) &&
            c[0] !== '^' && c[0] !== ':' && c[0] !== '.' && c[0] !== '%' && c[0] !== '/' &&
            isNaN(parseInt(c))) {
            pushRule({ resname: cu });
            continue;
        }
        // there must be only one constraint per rule
        // otherwise a test quickly becomes not applicable
        // e.g. chainTest for chainname when resno is present too
        var sele = {
            operator: 'AND',
            rules: []
        };
        var model = c.split('/');
        if (model.length > 1 && model[1]) {
            if (isNaN(parseInt(model[1]))) {
                throw new Error('model must be an integer');
            }
            sele.rules.push({
                model: parseInt(model[1])
            });
        }
        var altloc = model[0].split('%');
        if (altloc.length > 1) {
            sele.rules.push({
                altloc: altloc[1]
            });
        }
        var atomname = altloc[0].split('.');
        if (atomname.length > 1 && atomname[1]) {
            if (atomname[1].length > 4) {
                throw new Error('atomname must be one to four characters');
            }
            sele.rules.push({
                atomname: atomname[1].substring(0, 4).toUpperCase()
            });
        }
        var chain = atomname[0].split(':');
        if (chain.length > 1 && chain[1]) {
            sele.rules.push({
                chainname: chain[1]
            });
        }
        var inscode = chain[0].split('^');
        if (inscode.length > 1) {
            sele.rules.push({
                inscode: inscode[1]
            });
        }
        if (inscode[0]) {
            var negate = (void 0), negate2 = (void 0);
            if (inscode[0][0] === '-') {
                inscode[0] = inscode[0].substr(1);
                negate = true;
            }
            if (inscode[0].includes('--')) {
                inscode[0] = inscode[0].replace('--', '-');
                negate2 = true;
            }
            var resi = inscode[0].split('-');
            if (resi.length === 1) {
                var resiSingle = parseInt(resi[0]);
                if (isNaN(resiSingle)) {
                    throw new Error('resi must be an integer');
                }
                if (negate)
                    { resiSingle *= -1; }
                sele.rules.push({
                    resno: resiSingle
                });
            }
            else if (resi.length === 2) {
                var resiRange = resi.map(function (x) { return parseInt(x); });
                if (negate)
                    { resiRange[0] *= -1; }
                if (negate2)
                    { resiRange[1] *= -1; }
                sele.rules.push({
                    resno: [resiRange[0], resiRange[1]]
                });
            }
            else {
                throw new Error("resi range must contain one '-'");
            }
        }
        // round up
        if (sele.rules.length === 1) {
            pushRule(sele.rules[0]);
        }
        else if (sele.rules.length > 1) {
            pushRule(sele);
        }
        else {
            throw new Error('empty selection chunk');
        }
    }
    // cleanup
    if (retSelection.operator === undefined &&
        retSelection.rules.length === 1 &&
        retSelection.rules[0].hasOwnProperty('operator')) {
        retSelection = retSelection.rules[0];
    }
    return retSelection;
}

/**
 * @file Selection Test
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function atomTestFn(a, s) {
    // returning -1 means the rule is not applicable
    if (s.atomname === undefined && s.element === undefined &&
        s.altloc === undefined && s.atomindex === undefined &&
        s.keyword === undefined && s.inscode === undefined &&
        s.resname === undefined && s.sstruc === undefined &&
        s.resno === undefined && s.chainname === undefined &&
        s.model === undefined)
        { return -1; }
    if (s.keyword !== undefined) {
        if (s.keyword === kwd.BACKBONE && !a.isBackbone())
            { return false; }
        if (s.keyword === kwd.SIDECHAIN && !a.isSidechain())
            { return false; }
        if (s.keyword === kwd.BONDED && !a.isBonded())
            { return false; }
        if (s.keyword === kwd.RING && !a.isRing())
            { return false; }
        if (s.keyword === kwd.AROMATICRING && !a.isAromatic())
            { return false; }
        if (s.keyword === kwd.HETERO && !a.isHetero())
            { return false; }
        if (s.keyword === kwd.PROTEIN && !a.isProtein())
            { return false; }
        if (s.keyword === kwd.NUCLEIC && !a.isNucleic())
            { return false; }
        if (s.keyword === kwd.RNA && !a.isRna())
            { return false; }
        if (s.keyword === kwd.DNA && !a.isDna())
            { return false; }
        if (s.keyword === kwd.POLYMER && !a.isPolymer())
            { return false; }
        if (s.keyword === kwd.WATER && !a.isWater())
            { return false; }
        if (s.keyword === kwd.HELIX && !a.isHelix())
            { return false; }
        if (s.keyword === kwd.SHEET && !a.isSheet())
            { return false; }
        if (s.keyword === kwd.TURN && !a.isTurn())
            { return false; }
        if (s.keyword === kwd.ION && !a.isIon())
            { return false; }
        if (s.keyword === kwd.SACCHARIDE && !a.isSaccharide())
            { return false; }
        if (s.keyword === kwd.METAL && !a.isMetal())
            { return false; }
        if (s.keyword === kwd.POLARH && !a.isPolarHydrogen())
            { return false; }
    }
    if (s.atomname !== undefined && s.atomname !== a.atomname)
        { return false; }
    if (s.element !== undefined && s.element !== a.element)
        { return false; }
    if (s.altloc !== undefined && s.altloc !== a.altloc)
        { return false; }
    if (s.atomindex !== undefined &&
        binarySearchIndexOf(s.atomindex, a.index) < 0)
        { return false; }
    if (s.resname !== undefined) {
        if (Array.isArray(s.resname)) {
            if (!s.resname.includes(a.resname))
                { return false; }
        }
        else {
            if (s.resname !== a.resname)
                { return false; }
        }
    }
    if (s.sstruc !== undefined && s.sstruc !== a.sstruc)
        { return false; }
    if (s.resno !== undefined) {
        if (Array.isArray(s.resno) && s.resno.length === 2) {
            if (s.resno[0] > a.resno || s.resno[1] < a.resno)
                { return false; }
        }
        else {
            if (s.resno !== a.resno)
                { return false; }
        }
    }
    if (s.inscode !== undefined && s.inscode !== a.inscode)
        { return false; }
    if (s.chainname !== undefined && s.chainname !== a.chainname)
        { return false; }
    if (s.model !== undefined && s.model !== a.modelIndex)
        { return false; }
    return true;
}
function residueTestFn(r, s) {
    // returning -1 means the rule is not applicable
    if (s.resname === undefined && s.resno === undefined && s.inscode === undefined &&
        s.sstruc === undefined && s.model === undefined && s.chainname === undefined &&
        s.atomindex === undefined &&
        (s.keyword === undefined || AtomOnlyKeywords.includes(s.keyword)))
        { return -1; }
    if (s.keyword !== undefined) {
        if (s.keyword === kwd.HETERO && !r.isHetero())
            { return false; }
        if (s.keyword === kwd.PROTEIN && !r.isProtein())
            { return false; }
        if (s.keyword === kwd.NUCLEIC && !r.isNucleic())
            { return false; }
        if (s.keyword === kwd.RNA && !r.isRna())
            { return false; }
        if (s.keyword === kwd.DNA && !r.isDna())
            { return false; }
        if (s.keyword === kwd.POLYMER && !r.isPolymer())
            { return false; }
        if (s.keyword === kwd.WATER && !r.isWater())
            { return false; }
        if (s.keyword === kwd.HELIX && !r.isHelix())
            { return false; }
        if (s.keyword === kwd.SHEET && !r.isSheet())
            { return false; }
        if (s.keyword === kwd.TURN && !r.isTurn())
            { return false; }
        if (s.keyword === kwd.ION && !r.isIon())
            { return false; }
        if (s.keyword === kwd.SACCHARIDE && !r.isSaccharide())
            { return false; }
    }
    if (s.atomindex !== undefined &&
        rangeInSortedArray(s.atomindex, r.atomOffset, r.atomEnd) === 0)
        { return false; }
    if (s.resname !== undefined) {
        if (Array.isArray(s.resname)) {
            if (!s.resname.includes(r.resname))
                { return false; }
        }
        else {
            if (s.resname !== r.resname)
                { return false; }
        }
    }
    if (s.sstruc !== undefined && s.sstruc !== r.sstruc)
        { return false; }
    if (s.resno !== undefined) {
        if (Array.isArray(s.resno) && s.resno.length === 2) {
            if (s.resno[0] > r.resno || s.resno[1] < r.resno)
                { return false; }
        }
        else {
            if (s.resno !== r.resno)
                { return false; }
        }
    }
    if (s.inscode !== undefined && s.inscode !== r.inscode)
        { return false; }
    if (s.chainname !== undefined && s.chainname !== r.chainname)
        { return false; }
    if (s.model !== undefined && s.model !== r.modelIndex)
        { return false; }
    return true;
}
function chainTestFn(c, s) {
    // returning -1 means the rule is not applicable
    if (s.chainname === undefined && s.model === undefined && s.atomindex === undefined &&
        (s.keyword === undefined || !ChainKeywords.includes(s.keyword) || !c.entity))
        { return -1; }
    if (s.keyword !== undefined) {
        if (s.keyword === kwd.POLYMER && !c.entity.isPolymer())
            { return false; }
        if (s.keyword === kwd.WATER && !c.entity.isWater())
            { return false; }
    }
    if (s.atomindex !== undefined &&
        rangeInSortedArray(s.atomindex, c.atomOffset, c.atomEnd) === 0)
        { return false; }
    if (s.chainname !== undefined && s.chainname !== c.chainname)
        { return false; }
    if (s.model !== undefined && s.model !== c.modelIndex)
        { return false; }
    return true;
}
function modelTestFn(m, s) {
    // returning -1 means the rule is not applicable
    if (s.model === undefined && s.atomindex === undefined)
        { return -1; }
    if (s.atomindex !== undefined &&
        rangeInSortedArray(s.atomindex, m.atomOffset, m.atomEnd) === 0)
        { return false; }
    if (s.model !== undefined && s.model !== m.index)
        { return false; }
    return true;
}
function makeTest(selection, fn) {
    if (selection === null)
        { return false; }
    if (selection.error)
        { return false; }
    if (!selection.rules || selection.rules.length === 0)
        { return false; }
    var n = selection.rules.length;
    var t = !selection.negate;
    var f = !!selection.negate;
    var subTests = [];
    for (var i = 0; i < n; ++i) {
        var s = selection.rules[i];
        if (s.hasOwnProperty('operator')) {
            subTests[i] = makeTest(s, fn); // TODO
        }
    }
    // ( x and y ) can short circuit on false
    // ( x or y ) can short circuit on true
    // not ( x and y )
    return function test(entity) {
        var and = selection.operator === 'AND';
        var na = false;
        for (var i = 0; i < n; ++i) {
            var s = selection.rules[i]; // TODO
            var ret = (void 0);
            if (s.hasOwnProperty('operator')) {
                var test$1 = subTests[i];
                if (test$1 !== false) {
                    ret = test$1(entity);
                }
                else {
                    ret = -1;
                }
                if (ret === -1) {
                    na = true;
                    continue;
                }
                else if (ret === true) {
                    if (and) {
                        continue;
                    }
                    else {
                        return t;
                    }
                }
                else {
                    if (and) {
                        return f;
                    }
                    else {
                        continue;
                    }
                }
            }
            else {
                if (s.keyword === kwd.ALL) {
                    if (and) {
                        continue;
                    }
                    else {
                        return t;
                    }
                }
                else if (s.keyword === kwd.NONE) {
                    if (and) {
                        continue;
                    }
                    else {
                        return f;
                    }
                }
                ret = fn(entity, s);
                // console.log( entity.qualifiedName(), ret, s, selection.negate, "t", t, "f", f )
                if (ret === -1) {
                    na = true;
                    continue;
                }
                else if (ret === true) {
                    if (and) {
                        continue;
                    }
                    else {
                        return t;
                    }
                }
                else {
                    if (and) {
                        return f;
                    }
                    else {
                        continue;
                    }
                }
            }
        }
        if (na) {
            return -1;
        }
        else {
            if (and) {
                return t;
            }
            else {
                return f;
            }
        }
    };
}
function filter(selection, fn) {
    if (selection.error)
        { return selection; }
    if (!selection.rules || selection.rules.length === 0)
        { return selection; }
    var n = selection.rules.length;
    var filtered = {
        operator: selection.operator,
        rules: []
    };
    if (selection.hasOwnProperty('negate')) {
        filtered.negate = selection.negate;
    }
    for (var i = 0; i < n; ++i) {
        var s = selection.rules[i];
        if (s.hasOwnProperty('operator')) {
            var fs = filter(s, fn);
            if (fs !== null)
                { filtered.rules.push(fs); } // TODO
        }
        else if (!fn(s)) {
            filtered.rules.push(s); // TODO
        }
    }
    if (filtered.rules.length > 0) { // TODO
        // TODO maybe the filtered rules could be returned
        // in some case, but the way how tests are applied
        // e.g. when traversing a structure would also need
        // to change
        return selection;
        // return filtered;
    }
    else {
        return null;
    }
}
function makeAtomTest(selection, atomOnly) {
    if ( atomOnly === void 0 ) atomOnly = false;

    var filteredSelection = selection;
    if (atomOnly) {
        filteredSelection = filter(selection, function (s) {
            if (s.keyword !== undefined && !AtomOnlyKeywords.includes(s.keyword))
                { return true; }
            if (s.model !== undefined)
                { return true; }
            if (s.chainname !== undefined)
                { return true; }
            if (s.resname !== undefined)
                { return true; }
            if (s.resno !== undefined)
                { return true; }
            if (s.sstruc !== undefined)
                { return true; }
            return false;
        });
    }
    return makeTest(filteredSelection, atomTestFn);
}
function makeResidueTest(selection, residueOnly) {
    if ( residueOnly === void 0 ) residueOnly = false;

    var filteredSelection = selection;
    if (residueOnly) {
        filteredSelection = filter(selection, function (s) {
            if (s.keyword !== undefined && AtomOnlyKeywords.includes(s.keyword))
                { return true; }
            if (s.model !== undefined)
                { return true; }
            if (s.chainname !== undefined)
                { return true; }
            if (s.atomname !== undefined)
                { return true; }
            if (s.element !== undefined)
                { return true; }
            if (s.altloc !== undefined)
                { return true; }
            return false;
        });
    }
    return makeTest(filteredSelection, residueTestFn);
}
function makeChainTest(selection, chainOnly) {
    if ( chainOnly === void 0 ) chainOnly = false;

    var filteredSelection = selection;
    if (chainOnly) {
        filteredSelection = filter(selection, function (s) {
            if (s.keyword !== undefined && !ChainKeywords.includes(s.keyword))
                { return true; }
            // if( s.model!==undefined ) return true;
            if (s.resname !== undefined)
                { return true; }
            if (s.resno !== undefined)
                { return true; }
            if (s.atomname !== undefined)
                { return true; }
            if (s.element !== undefined)
                { return true; }
            if (s.altloc !== undefined)
                { return true; }
            if (s.sstruc !== undefined)
                { return true; }
            if (s.inscode !== undefined)
                { return true; }
            return false;
        });
    }
    return makeTest(filteredSelection, chainTestFn);
}
function makeModelTest(selection, modelOnly) {
    if ( modelOnly === void 0 ) modelOnly = false;

    var filteredSelection = selection;
    if (modelOnly) {
        filteredSelection = filter(selection, function (s) {
            if (s.keyword !== undefined)
                { return true; }
            if (s.chainname !== undefined)
                { return true; }
            if (s.resname !== undefined)
                { return true; }
            if (s.resno !== undefined)
                { return true; }
            if (s.atomname !== undefined)
                { return true; }
            if (s.element !== undefined)
                { return true; }
            if (s.altloc !== undefined)
                { return true; }
            if (s.sstruc !== undefined)
                { return true; }
            if (s.inscode !== undefined)
                { return true; }
            return false;
        });
    }
    return makeTest(filteredSelection, modelTestFn);
}

/**
 * @file Selection
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Selection
 */
var Selection = function Selection(string) {
    this.signals = {
        stringChanged: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]()
    };
    this.setString(string);
};

var prototypeAccessors$1 = { type: { configurable: true } };
prototypeAccessors$1.type.get = function () { return 'selection'; };
Selection.prototype.setString = function setString (string, silent) {
    if (string === undefined)
        { string = this.string || ''; }
    if (string === this.string)
        { return; }
    try {
        this.selection = parseSele(string);
    }
    catch (e) {
        // Log.error( e.stack );
        this.selection = { 'error': e.message };
    }
    var selection = this.selection;
    this.string = string;
    this.test = makeAtomTest(selection);
    this.residueTest = makeResidueTest(selection);
    this.chainTest = makeChainTest(selection);
    this.modelTest = makeModelTest(selection);
    this.atomOnlyTest = makeAtomTest(selection, true);
    this.residueOnlyTest = makeResidueTest(selection, true);
    this.chainOnlyTest = makeChainTest(selection, true);
    this.modelOnlyTest = makeModelTest(selection, true);
    if (!silent) {
        this.signals.stringChanged.dispatch(this.string);
    }
};
Selection.prototype.isAllSelection = function isAllSelection () {
    return SelectAllKeyword.includes(this.string.toUpperCase());
};
Selection.prototype.isNoneSelection = function isNoneSelection () {
    return SelectNoneKeyword.includes(this.string.toUpperCase());
};

Object.defineProperties( Selection.prototype, prototypeAccessors$1 );

/**
 * @file Selection Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color based on {@link Selection}
 */
var SelectionColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function SelectionColormaker(params) {
        var this$1 = this;

        Colormaker$$1.call(this, params);
        this.colormakerList = []; // TODO
        this.selectionList = [];
        var dataList = params.dataList || [];
        dataList.forEach(function (data) {
            var scheme = data[0];
            var sele = data[1];
            var params = data[2]; if ( params === void 0 ) params = {};
            if (ColormakerRegistry$1.hasScheme(scheme)) {
                Object.assign(params, {
                    scheme: scheme,
                    structure: this$1.parameters.structure
                });
            }
            else {
                Object.assign(params, {
                    scheme: 'uniform',
                    value: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](scheme).getHex()
                });
            }
            this$1.colormakerList.push(ColormakerRegistry$1.getScheme(params));
            this$1.selectionList.push(new Selection(sele));
        });
    }

    if ( Colormaker$$1 ) SelectionColormaker.__proto__ = Colormaker$$1;
    SelectionColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    SelectionColormaker.prototype.constructor = SelectionColormaker;
    SelectionColormaker.prototype.atomColor = function atomColor (a) {
        for (var i = 0, n = this.selectionList.length; i < n; ++i) {
            var test = this.selectionList[i].test;
            if (test && test(a)) {
                return this.colormakerList[i].atomColor(a);
            }
        }
        return 0xFFFFFF;
    };

    return SelectionColormaker;
}(Colormaker));

/**
 * @file Colormaker Registry
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var ColormakerScales = {
    '': '',
    // Sequential
    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',
    // Diverging
    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',
    // Qualitative
    Set1: '[Q] Set1',
    Set2: '[Q] Set2',
    Set3: '[Q] Set3',
    Dark2: '[Q] Dark2',
    Paired: '[Q] Paired',
    Pastel1: '[Q] Pastel1',
    Pastel2: '[Q] Pastel2',
    Accent: '[Q] Accent',
    // Other
    rainbow: '[?] Rainbow',
    rwb: '[?] Red-White-Blue'
};
var ColormakerModes = {
    '': '',
    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'
};
/**
 * Class for registering {@link Colormaker}s. Generally use the
 * global {@link src/globals.js~ColormakerRegistry} instance.
 */
var ColormakerRegistry = function ColormakerRegistry() {
    this.schemes = {};
    this.userSchemes = {};
};
ColormakerRegistry.prototype.getScheme = function getScheme (params) {
    var p = params || {};
    var id = (p.scheme || '').toLowerCase();
    var SchemeClass;
    if (id in this.schemes) {
        SchemeClass = this.schemes[id];
    }
    else if (id in this.userSchemes) {
        SchemeClass = this.userSchemes[id];
    }
    else {
        SchemeClass = Colormaker;
    }
    return new SchemeClass(params);
};
/**
 * Get an description of available schemes as an
 * object with id-label as key-value pairs
 * @return {Object} available schemes
 */
ColormakerRegistry.prototype.getSchemes = function getSchemes () {
    var types = {};
    Object.keys(this.schemes).forEach(function (k) {
        types[k] = k;
    });
    Object.keys(this.userSchemes).forEach(function (k) {
        types[k] = k.split('|')[1];
    });
    return types;
};
/**
 * Get an description of available scales as an
 * object with id-label as key-value pairs
 * @return {Object} available scales
 */
ColormakerRegistry.prototype.getScales = function getScales () {
    return ColormakerScales;
};
ColormakerRegistry.prototype.getModes = function getModes () {
    return ColormakerModes;
};
/**
 * Add a scheme with a hardcoded id
 * @param {String} id - the id
 * @param {Colormaker} scheme - the colormaker
 * @return {undefined}
 */
ColormakerRegistry.prototype.add = function add (id, scheme) {
    id = id.toLowerCase();
    this.schemes[id] = scheme;
};
/**
 * Register a custom scheme
 *
 * @example
 * // Create a class with a `atomColor` method that returns a hex color.
 * var schemeId = NGL.ColormakerRegistry.addScheme( function( params ){
 * this.atomColor = function( atom ){
 *     if( atom.serial < 1000 ){
 *         return 0x0000FF;  // blue
 *     }else if( atom.serial > 2000 ){
 *         return 0xFF0000;  // red
 *     }else{
 *         return 0x00FF00;  // green
 *     }
 * };
 * } );
 *
 * stage.loadFile( "rcsb://3dqb.pdb" ).then( function( o ){
 * o.addRepresentation( "cartoon", { color: schemeId } );  // pass schemeId here
 * o.autoView();
 * } );
 *
 * @param {Function|Colormaker} scheme - constructor or {@link Colormaker} instance
 * @param {String} label - scheme label
 * @return {String} id to refer to the registered scheme
 */
ColormakerRegistry.prototype.addScheme = function addScheme (scheme, label) {
    if (!(scheme instanceof Colormaker)) {
        scheme = this._createScheme(scheme);
    }
    return this._addUserScheme(scheme, label);
};
/**
 * Add a user-defined scheme
 * @param {Colormaker} scheme - the user-defined scheme
 * @param {String} [label] - scheme label
 * @return {String} id to refer to the registered scheme
 */
ColormakerRegistry.prototype._addUserScheme = function _addUserScheme (scheme, label) {
    label = label || '';
    var id = ((generateUUID()) + "|" + label).toLowerCase();
    this.userSchemes[id] = scheme;
    return id;
};
/**
 * Remove the scheme with the given id
 * @param  {String} id - scheme to remove
 * @return {undefined}
 */
ColormakerRegistry.prototype.removeScheme = function removeScheme (id) {
    id = id.toLowerCase();
    delete this.userSchemes[id];
};
ColormakerRegistry.prototype._createScheme = function _createScheme (constructor) {
    var _Colormaker = function (params) {
        Colormaker.call(this, params);
        constructor.call(this, params);
    };
    _Colormaker.prototype = Colormaker.prototype;
    _Colormaker.prototype.constructor = Colormaker;
    return _Colormaker;
};
/**
 * Create and a selection-based coloring scheme. Supply a list with pairs
 * of colorname and selection for coloring by selections. Use the last
 * entry as a default (catch all) coloring definition.
 *
 * @example
 * var schemeId = NGL.ColormakerRegistry.addSelectionScheme( [
 * [ "red", "64-74 or 134-154 or 222-254 or 310-310 or 322-326" ],
 * [ "green", "311-322" ],
 * [ "yellow", "40-63 or 75-95 or 112-133 or 155-173 or 202-221 or 255-277 or 289-309" ],
 * [ "blue", "1-39 or 96-112 or 174-201 or 278-288" ],
 * [ "white", "*" ]
 * ], "Transmembrane 3dqb" );
 *
 * stage.loadFile( "rcsb://3dqb.pdb" ).then( function( o ){
 * o.addRepresentation( "cartoon", { color: schemeId } );  // pass schemeId here
 * o.autoView();
 * } );
 *
 * @param {Array} dataList - cloror-selection pairs
 * @param {String} label - scheme name
 * @return {String} id to refer to the registered scheme
 */
ColormakerRegistry.prototype.addSelectionScheme = function addSelectionScheme (dataList, label) {
    var MySelectionColormaker = /*@__PURE__*/(function (SelectionColormaker$$1) {
            function MySelectionColormaker(params) {
            SelectionColormaker$$1.call(this, Object.assign({ dataList: dataList }, params));
        }

            if ( SelectionColormaker$$1 ) MySelectionColormaker.__proto__ = SelectionColormaker$$1;
            MySelectionColormaker.prototype = Object.create( SelectionColormaker$$1 && SelectionColormaker$$1.prototype );
            MySelectionColormaker.prototype.constructor = MySelectionColormaker;

            return MySelectionColormaker;
        }(SelectionColormaker));
    return this._addUserScheme(MySelectionColormaker, label);
};
/**
 * Check if a scheme with the given id exists
 * @param  {String}  id - the id to check
 * @return {Boolean} flag indicating if the scheme exists
 */
ColormakerRegistry.prototype.hasScheme = function hasScheme (id) {
    id = id.toLowerCase();
    return id in this.schemes || id in this.userSchemes;
};

/**
 * @file Parser Registry
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var ParserRegistry = /*@__PURE__*/(function (Registry$$1) {
    function ParserRegistry() {
        Registry$$1.call(this, 'parser');
    }

    if ( Registry$$1 ) ParserRegistry.__proto__ = Registry$$1;
    ParserRegistry.prototype = Object.create( Registry$$1 && Registry$$1.prototype );
    ParserRegistry.prototype.constructor = ParserRegistry;
    ParserRegistry.prototype.__hasObjName = function __hasObjName (key, objName) {
        var parser = this.get(key);
        return parser && parser.prototype.__objName === objName;
    };
    ParserRegistry.prototype.isTrajectory = function isTrajectory (key) {
        return this.__hasObjName(key, 'frames');
    };
    ParserRegistry.prototype.isStructure = function isStructure (key) {
        return this.__hasObjName(key, 'structure');
    };
    ParserRegistry.prototype.isVolume = function isVolume (key) {
        return this.__hasObjName(key, 'volume');
    };
    ParserRegistry.prototype.isSurface = function isSurface (key) {
        return this.__hasObjName(key, 'surface');
    };
    ParserRegistry.prototype.isBinary = function isBinary (key) {
        var parser = this.get(key);
        return parser && parser.prototype.isBinary;
    };
    ParserRegistry.prototype.isXml = function isXml (key) {
        var parser = this.get(key);
        return parser && parser.prototype.isXml;
    };
    ParserRegistry.prototype.isJson = function isJson (key) {
        var parser = this.get(key);
        return parser && parser.prototype.isJson;
    };
    ParserRegistry.prototype.getTrajectoryExtensions = function getTrajectoryExtensions () {
        var this$1 = this;

        return this.names.filter(function (name) { return this$1.isTrajectory(name); });
    };
    ParserRegistry.prototype.getStructureExtensions = function getStructureExtensions () {
        var this$1 = this;

        return this.names.filter(function (name) { return this$1.isStructure(name); });
    };
    ParserRegistry.prototype.getVolumeExtensions = function getVolumeExtensions () {
        var this$1 = this;

        return this.names.filter(function (name) { return this$1.isVolume(name); });
    };
    ParserRegistry.prototype.getSurfaceExtensions = function getSurfaceExtensions () {
        var this$1 = this;

        return this.names.filter(function (name) { return this$1.isSurface(name); });
    };

    return ParserRegistry;
}(Registry));

/**
 * @file Worker Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getWorkerDeps(vars) {
    var deps = vars;
    vars.forEach(function (sym) {
        if (sym.__deps) {
            Array.prototype.push.apply(deps, getWorkerDeps(sym.__deps));
        }
    });
    return deps;
}
function makeWorkerString(vars) {
    var deps = uniqueArray(getWorkerDeps(vars));
    return deps.map(function (sym) {
        return sym.toString();
    }).join('\n\n\n');
}
function onmessage(e) {
    var name = e.data.__name;
    var postId = e.data.__postId;
    /* global self */
    if (name === undefined) {
        console.error('message __name undefined');
    }
    else if (self.func === undefined) {
        console.error('worker func undefined', name);
    }
    else {
        var callback = function (aMessage, transferList) {
            aMessage = aMessage || {};
            if (postId !== undefined)
                { aMessage.__postId = postId; }
            try {
                self.postMessage(aMessage, transferList);
            }
            catch (error) {
                console.error('self.postMessage:', error);
                self.postMessage(aMessage);
            }
        };
        self.func(e, callback);
    }
}
function makeWorkerBlob(func, deps) {
    var str = "'use strict';\n\n" + makeWorkerString(deps);
    str += '\n\n\nself.func = ' + func.toString() + ';';
    str += '\n\n\nself.onmessage = ' + onmessage.toString() + ';';
    // console.log(str);
    return new Blob([str], { type: 'application/javascript' });
}

/**
 * @file Worker Registry
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var WorkerRegistry = function WorkerRegistry() {
    this.activeWorkerCount = 0;
    this._funcDict = {};
    this._depsDict = {};
    this._blobDict = {};
};
WorkerRegistry.prototype.add = function add (name, func, deps) {
    this._funcDict[name] = func;
    this._depsDict[name] = deps;
};
WorkerRegistry.prototype.get = function get (name) {
    if (!this._blobDict[name]) {
        this._blobDict[name] = makeWorkerBlob(this._funcDict[name], this._depsDict[name]);
    }
    return this._blobDict[name];
};

/**
 * @file Globals
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * The browser name: "Opera", "Chrome", "Firefox", "Mobile Safari",
 * "Internet Explorer", "Safari" or false.
 */
var Browser = getBrowser();
/**
 * Flag indicating support for the 'passive' option for event handler
 */
var SupportsPassiveEventHandler = false;
try {
    // Test via a getter in the options object to see if the passive property is accessed
    var opts = Object.defineProperty({}, 'passive', {
        get: function () {
            SupportsPassiveEventHandler = true;
        }
    });
    window.addEventListener('test', function (e) { }, opts);
}
catch (e) { }
/**
 * Flag indicating a mobile browser
 */
var Mobile = typeof window !== 'undefined' ? typeof window.orientation !== 'undefined' : false;
var SupportsReadPixelsFloat = false;
function setSupportsReadPixelsFloat(value) {
    SupportsReadPixelsFloat = value;
}
/**
 * Flag indicating support for the `EXT_frag_depth` WebGL extension
 * (Always present in WebGL2)
 */
var ExtensionFragDepth = false;
function setExtensionFragDepth(value) {
    ExtensionFragDepth = value;
}
var Log = {
    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)
};
var MeasurementDefaultParams = {
    color: 'green',
    labelColor: 0x808080,
    labelAttachment: 'bottom-center',
    labelSize: 0.7,
    labelZOffset: 0.5,
    labelYOffset: 0.1,
    labelBorder: true,
    labelBorderColor: 0xd3d3d3,
    labelBorderWidth: 0.25,
    lineOpacity: 0.8,
    linewidth: 5.0,
    opacity: 0.6,
    labelUnit: 'angstrom',
    arcVisible: true,
    planeVisible: false
};
function setMeasurementDefaultParams(params) {
    if ( params === void 0 ) params = {};

    Object.assign(MeasurementDefaultParams, params);
}
var Debug = boolean(getQuery('debug'));
function setDebug(value) {
    Debug = value;
}
var WebglErrorMessage = '<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>';
/**
 * List of file extensions to be recognized as scripts
 */
var ScriptExtensions = ['ngl', 'js'];
var WorkerRegistry$1 = new WorkerRegistry();
var ColormakerRegistry$1 = new ColormakerRegistry();
var DatasourceRegistry = new Registry('datasource');
var RepresentationRegistry = new Registry('representatation');
var ParserRegistry$1 = new ParserRegistry();
var ShaderRegistry = new Registry('shader');
var DecompressorRegistry = new Registry('decompressor');
var ComponentRegistry = new Registry('component');
var BufferRegistry = new Registry('buffer');
var PickerRegistry = new Registry('picker');
var ListingDatasource;
function setListingDatasource(value) {
    ListingDatasource = value;
}
var TrajectoryDatasource;
function setTrajectoryDatasource(value) {
    TrajectoryDatasource = value;
}

/**
 * @file Streamer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Streamer = function Streamer(src, params) {
    if ( params === void 0 ) params = {};

    this.chunkSize = 1024 * 1024 * 10;
    this.newline = '\n';
    this.__pointer = 0;
    this.__partialLine = '';
    this.compressed = defaults(params.compressed, false);
    this.binary = defaults(params.binary, false);
    this.json = defaults(params.json, false);
    this.xml = defaults(params.xml, false);
    this.src = src;
};
Streamer.prototype.isBinary = function isBinary () {
    return this.binary || this.compressed;
};
Streamer.prototype.read = function read () {
        var this$1 = this;

    return this._read().then(function (data) {
        var decompressFn = this$1.compressed ? DecompressorRegistry.get(this$1.compressed) : undefined;
        if (this$1.compressed && decompressFn) {
            this$1.data = decompressFn(data);
        }
        else {
            if ((this$1.binary || this$1.compressed) && data instanceof ArrayBuffer) {
                data = new Uint8Array(data);
            }
            this$1.data = data;
        }
        return this$1.data;
    });
};
Streamer.prototype._chunk = function _chunk (start, end) {
    end = Math.min(this.data.length, end);
    if (start === 0 && this.data.length === end) {
        return this.data;
    }
    else {
        if (this.isBinary()) {
            return this.data.subarray(start, end);
        }
        else {
            return this.data.substring(start, end);
        }
    }
};
Streamer.prototype.chunk = function chunk (start) {
    var end = start + this.chunkSize;
    return this._chunk(start, end);
};
Streamer.prototype.peekLines = function peekLines (m) {
    var data = this.data;
    var n = data.length;
    // FIXME does not work for multi-char newline
    var newline = this.isBinary() ? this.newline.charCodeAt(0) : this.newline;
    var i;
    var count = 0;
    for (i = 0; i < n; ++i) {
        if (data[i] === newline)
            { ++count; }
        if (count === m)
            { break; }
    }
    var chunk = this._chunk(0, i + 1);
    var d = this.chunkToLines(chunk, '', i > n);
    return d.lines;
};
Streamer.prototype.chunkCount = function chunkCount () {
    return Math.floor(this.data.length / this.chunkSize) + 1;
};
Streamer.prototype.asText = function asText () {
    return this.isBinary() ? uint8ToString(this.data) : this.data;
};
Streamer.prototype.chunkToLines = function chunkToLines (chunk, partialLine, isLast) {
    var newline = this.newline;
    if (!this.isBinary() && chunk.length === this.data.length) {
        return {
            lines: chunk.split(newline),
            partialLine: ''
        };
    }
    var lines = [];
    var str = this.isBinary() ? uint8ToString(chunk) : chunk;
    var idx = str.lastIndexOf(newline);
    if (idx === -1) {
        partialLine += str;
    }
    else {
        var str2 = partialLine + str.substr(0, idx);
        lines = lines.concat(str2.split(newline));
        if (idx === str.length - newline.length) {
            partialLine = '';
        }
        else {
            partialLine = str.substr(idx + newline.length);
        }
    }
    if (isLast && partialLine !== '') {
        lines.push(partialLine);
    }
    return {
        lines: lines,
        partialLine: partialLine
    };
};
Streamer.prototype.nextChunk = function nextChunk () {
    var start = this.__pointer;
    if (start > this.data.length) {
        return undefined;
    }
    this.__pointer += this.chunkSize;
    return this.chunk(start);
};
Streamer.prototype.nextChunkOfLines = function nextChunkOfLines () {
    var chunk = this.nextChunk();
    if (chunk === undefined) {
        return undefined;
    }
    var isLast = this.__pointer > this.data.length;
    var d = this.chunkToLines(chunk, this.__partialLine, isLast);
    this.__partialLine = d.partialLine;
    return d.lines;
};
Streamer.prototype.eachChunk = function eachChunk (callback) {
    var chunkSize = this.chunkSize;
    var n = this.data.length;
    var chunkCount = this.chunkCount();
    for (var i = 0; i < n; i += chunkSize) {
        var chunk = this.chunk(i);
        var chunkNo = Math.round(i / chunkSize);
        callback(chunk, chunkNo, chunkCount);
    }
};
Streamer.prototype.eachChunkOfLines = function eachChunkOfLines (callback) {
        var this$1 = this;

    this.eachChunk(function (chunk, chunkNo, chunkCount) {
        var isLast = chunkNo === chunkCount + 1;
        var d = this$1.chunkToLines(chunk, this$1.__partialLine, isLast);
        this$1.__partialLine = d.partialLine;
        callback(d.lines, chunkNo, chunkCount);
    });
};
Streamer.prototype.dispose = function dispose () {
    delete this.src;
};

/**
 * @file File Streamer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var FileStreamer = /*@__PURE__*/(function (Streamer$$1) {
    function FileStreamer () {
        Streamer$$1.apply(this, arguments);
    }

    if ( Streamer$$1 ) FileStreamer.__proto__ = Streamer$$1;
    FileStreamer.prototype = Object.create( Streamer$$1 && Streamer$$1.prototype );
    FileStreamer.prototype.constructor = FileStreamer;

    FileStreamer.prototype._read = function _read () {
        var this$1 = this;

        return new Promise(function (resolve, reject) {
            var file = this$1.src;
            var reader = new FileReader();
            reader.onload = function (event) {
                if (event.target)
                    { resolve(event.target.result); }
            };
            // if (typeof this.onprogress === 'function') {
            //   reader.onprogress = event => this.onprogress(event)
            // }
            reader.onerror = function (event) { return reject(event); };
            if (this$1.binary || this$1.compressed) {
                reader.readAsArrayBuffer(file);
            }
            else {
                reader.readAsText(file);
            }
        });
    };

    return FileStreamer;
}(Streamer));

/**
 * @file Network Streamer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var NetworkStreamer = /*@__PURE__*/(function (Streamer$$1) {
    function NetworkStreamer () {
        Streamer$$1.apply(this, arguments);
    }

    if ( Streamer$$1 ) NetworkStreamer.__proto__ = Streamer$$1;
    NetworkStreamer.prototype = Object.create( Streamer$$1 && Streamer$$1.prototype );
    NetworkStreamer.prototype.constructor = NetworkStreamer;

    NetworkStreamer.prototype._read = function _read () {
        var this$1 = this;

        return new Promise(function (resolve, reject) {
            var url = this$1.src;
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.addEventListener('load', function () {
                if (xhr.status === 200 || xhr.status === 304 ||
                    // when requesting from local file system
                    // the status in Google Chrome/Chromium is 0
                    xhr.status === 0) {
                    try {
                        resolve(xhr.response);
                    }
                    catch (e) {
                        reject(e);
                    }
                }
                else {
                    reject(xhr.statusText);
                }
            }, false);
            // if (typeof this.onprogress === 'function') {
            //   xhr.addEventListener('progress', event => this.onprogress(event), false);
            // }
            xhr.addEventListener('error', function (event) { return reject('network error'); }, false);
            if (this$1.isBinary()) {
                xhr.responseType = 'arraybuffer';
            }
            else if (this$1.json) {
                xhr.responseType = 'json';
            }
            else if (this$1.xml) {
                xhr.responseType = 'document';
            }
            else {
                xhr.responseType = 'text';
            }
            // xhr.crossOrigin = true;
            xhr.send();
        });
    };

    return NetworkStreamer;
}(Streamer));

/**
 * @file Loader
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Loader parameter object.
 * @typedef {Object} LoaderParameters - loader parameters
 * @property {String} ext - file extension, determines file type
 * @property {Boolean} compressed - flag data as compressed
 * @property {Boolean} binary - flag data as binary
 * @property {String} name - set data name
 */
/**
 * Loader base class
 */
var Loader = function Loader(src, params) {
    if ( params === void 0 ) params = {};

    this.parameters = createParams(params, {
        ext: '',
        compressed: false,
        binary: ParserRegistry$1.isBinary(params.ext || ''),
        name: '',
        dir: '',
        path: '',
        protocol: ''
    });
    var streamerParams = {
        compressed: this.parameters.compressed,
        binary: this.parameters.binary,
        json: ParserRegistry$1.isJson(this.parameters.ext),
        xml: ParserRegistry$1.isXml(this.parameters.ext)
    };
    if ((typeof File !== 'undefined' && src instanceof File) ||
        (typeof Blob !== 'undefined' && src instanceof Blob)) {
        this.streamer = new FileStreamer(src, streamerParams);
    }
    else {
        this.streamer = new NetworkStreamer(src, streamerParams);
    }
};

/**
 * @file Parser Loader
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Parser loader class
 * @extends Loader
 */
var ParserLoader = /*@__PURE__*/(function (Loader$$1) {
    function ParserLoader(src, params) {
        if ( params === void 0 ) params = {};

        Loader$$1.call(this, src, params);
        this.parserParams = {
            voxelSize: params.voxelSize,
            firstModelOnly: params.firstModelOnly,
            asTrajectory: params.asTrajectory,
            cAlphaOnly: params.cAlphaOnly,
            delimiter: params.delimiter,
            comment: params.comment,
            columnNames: params.columnNames,
            name: this.parameters.name,
            path: this.parameters.path
        };
    }

    if ( Loader$$1 ) ParserLoader.__proto__ = Loader$$1;
    ParserLoader.prototype = Object.create( Loader$$1 && Loader$$1.prototype );
    ParserLoader.prototype.constructor = ParserLoader;
    /**
     * Load parsed object
     * @return {Promise} resolves to the loaded & parsed {@link Structure},
     *                   {@link Volume}, {@link Surface} or data object
     */
    ParserLoader.prototype.load = function load () {
        var ParserClass = ParserRegistry$1.get(this.parameters.ext);
        var parser = new ParserClass(this.streamer, this.parserParams);
        return parser.parse();
    };

    return ParserLoader;
}(Loader));

/**
 * @file Script
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Script class
 */
var Script = function Script(functionBody, name, path) {
    this.name = name;
    this.path = path;
    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 = path.substring(0, path.lastIndexOf('/') + 1);
    try {
        /* eslint-disable no-new-func */
        this.fn = new Function('stage', '__name', '__path', '__dir', functionBody);
    }
    catch (e) {
        Log.error('Script compilation failed', e);
        this.fn = function () { };
    }
};
/**
 * Execute the script
 * @param  {Stage} stage - the stage context
 * @return {Promise} - resolve when script finished running
 */
Script.prototype.run = function run (stage) {
        var this$1 = this;

    return new Promise(function (resolve, reject) {
        try {
            this$1.fn.apply(null, [stage, this$1.name, this$1.path, this$1.dir]);
            resolve();
        }
        catch (e) {
            Log.error('Script.fn', e);
            reject(e);
        }
    });
};

/**
 * @file Script Loader
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Script loader class
 * @extends Loader
 */
var ScriptLoader = /*@__PURE__*/(function (Loader$$1) {
    function ScriptLoader () {
        Loader$$1.apply(this, arguments);
    }

    if ( Loader$$1 ) ScriptLoader.__proto__ = Loader$$1;
    ScriptLoader.prototype = Object.create( Loader$$1 && Loader$$1.prototype );
    ScriptLoader.prototype.constructor = ScriptLoader;

    ScriptLoader.prototype.load = function load () {
        var this$1 = this;

        return this.streamer.read().then(function () {
            return new Script(this$1.streamer.asText(), this$1.parameters.name, this$1.parameters.path);
        });
    };

    return ScriptLoader;
}(Loader));

/**
 * @file Loader Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getFileInfo(file) {
    var compressedExtList = DecompressorRegistry.names;
    var path;
    var compressed;
    var protocol = '';
    if (file instanceof File) {
        path = file.name;
    }
    else if (file instanceof Blob) {
        path = '';
    }
    else {
        path = file;
    }
    var queryIndex = path.lastIndexOf('?');
    var query = queryIndex !== -1 ? path.substring(queryIndex) : '';
    path = path.substring(0, queryIndex === -1 ? path.length : queryIndex);
    var name = path.replace(/^.*[\\/]/, '');
    var base = name.substring(0, name.lastIndexOf('.'));
    var nameSplit = name.split('.');
    var ext = nameSplit.length > 1 ? (nameSplit.pop() || '').toLowerCase() : '';
    var protocolMatch = path.match(/^(.+):\/\/(.+)$/);
    if (protocolMatch) {
        protocol = protocolMatch[1].toLowerCase();
        path = protocolMatch[2] || '';
    }
    var dir = path.substring(0, path.lastIndexOf('/') + 1);
    if (compressedExtList.includes(ext)) {
        compressed = ext;
        var n = path.length - ext.length - 1;
        ext = (path.substr(0, n).split('.').pop() || '').toLowerCase();
        var m = base.length - ext.length - 1;
        base = base.substr(0, m);
    }
    else {
        compressed = false;
    }
    return { path: path, name: name, ext: ext, base: base, dir: dir, compressed: compressed, protocol: protocol, query: query, 'src': file };
}
function getDataInfo(src) {
    var info = getFileInfo(src);
    var datasource = DatasourceRegistry.get(info.protocol);
    if (datasource) {
        info = getFileInfo(datasource.getUrl(info.src));
        if (!info.ext && datasource.getExt) {
            info.ext = datasource.getExt(src);
        }
    }
    return info;
}
/**
 * Load a file
 *
 * @example
 * // load from URL
 * NGL.autoLoad( "http://files.rcsb.org/download/5IOS.cif" );
 *
 * @example
 * // load binary data in CCP4 format via a Blob
 * var binaryBlob = new Blob( [ ccp4Data ], { type: 'application/octet-binary'} );
 * NGL.autoLoad( binaryBlob, { ext: "ccp4" } );
 *
 * @example
 * // load string data in PDB format via a Blob
 * var stringBlob = new Blob( [ pdbData ], { type: 'text/plain'} );
 * NGL.autoLoad( stringBlob, { ext: "pdb" } );
 *
 * @example
 * // load a File object
 * NGL.autoLoad( file );
 *
 * @param  {String|File|Blob} file - either a URL or an object containing the file data
 * @param  {LoaderParameters} params - loading parameters
 * @return {Promise} Promise resolves to the loaded data
 */
function autoLoad(file, params) {
    if ( params === void 0 ) params = {};

    var p = Object.assign(getDataInfo(file), params);
    var loader;
    if (ParserRegistry$1.names.includes(p.ext)) {
        loader = new ParserLoader(p.src, p);
    }
    else if (ScriptExtensions.includes(p.ext)) {
        loader = new ScriptLoader(p.src, p);
    }
    if (loader) {
        return loader.load();
    }
    else {
        return Promise.reject(new Error(("autoLoad: ext '" + (p.ext) + "' unknown")));
    }
}

/**
 * @file Writer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Base class for writers
 * @interface
 */
var Writer = function Writer () {};

Writer.prototype.getBlob = function getBlob () {
    return new Blob([this.getData()], { type: this.mimeType });
};
/**
 * Trigger a download of the
 * @param  {[type]} name [description]
 * @param  {[type]} ext  [description]
 * @return {[type]}  [description]
 */
Writer.prototype.download = function download$1 (name, ext) {
    name = defaults(name, this.defaultName);
    ext = defaults(ext, this.defaultExt);
    download(this.getBlob(), (name + "." + ext));
};

/**
 * @file Pdb Writer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// http://www.wwpdb.org/documentation/file-format
// Sample PDB line, the coords X,Y,Z are fields 5,6,7 on each line.
// ATOM      1  N   ARG     1      29.292  13.212 -12.751  1.00 33.78      1BPT 108
var AtomFormat = 'ATOM  %5d %-4s %3s %1s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f      %4s%2s';
var HetatmFormat = 'HETATM%5d %-4s %3s %1s%4d    %8.3f%8.3f%8.3f%6.2f%6.2f      %4s%2s';
/**
 * Create a PDB file from a Structure object
 */
var PdbWriter = /*@__PURE__*/(function (Writer$$1) {
    function PdbWriter(structure, params) {
        Writer$$1.call(this);
        this.mimeType = 'text/plain';
        this.defaultName = 'structure';
        this.defaultExt = 'pdb';
        var p = Object.assign({}, params);
        this.renumberSerial = defaults(p.renumberSerial, true);
        this.remarks = ensureArray(defaults(p.remarks, []));
        this.structure = structure;
        this._records = [];
    }

    if ( Writer$$1 ) PdbWriter.__proto__ = Writer$$1;
    PdbWriter.prototype = Object.create( Writer$$1 && Writer$$1.prototype );
    PdbWriter.prototype.constructor = PdbWriter;
    PdbWriter.prototype._writeRecords = function _writeRecords () {
        this._records.length = 0;
        this._writeTitle();
        this._writeRemarks();
        this._writeAtoms();
    };
    PdbWriter.prototype._writeTitle = function _writeTitle () {
        // FIXME multiline if title line longer than 80 chars
        this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])('TITLE %-74s', this.structure.name));
    };
    PdbWriter.prototype._writeRemarks = function _writeRemarks () {
        var this$1 = this;

        this.remarks.forEach(function (str) {
            this$1._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])('REMARK %-73s', str));
        });
        if (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)) // TODO
            ));
        }
    };
    PdbWriter.prototype._writeAtoms = function _writeAtoms () {
        var this$1 = this;

        var ia = 1;
        var im = 1;
        this.structure.eachModel(function (m) {
            this$1._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])('MODEL %-74d', im++));
            m.eachAtom(function (a) {
                var formatString = a.hetero ? HetatmFormat : AtomFormat;
                var serial = this$1.renumberSerial ? ia : a.serial;
                // Alignment of one-letter atom name such as C starts at column 14,
                // while two-letter atom name such as FE starts at column 13.
                var atomname = a.atomname;
                if (atomname.length === 1)
                    { atomname = ' ' + atomname; }
                this$1._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])(formatString, serial, atomname, a.resname, defaults(a.chainname, ' '), a.resno, a.x, a.y, a.z, defaults(a.occupancy, 1.0), defaults(a.bfactor, 0.0), '', // segid
                defaults(a.element, '')));
                ia += 1;
            }, this$1.structure.getSelection());
            this$1._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])('%-80s', 'ENDMDL'));
            im += 1;
        });
        this._records.push(Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])('%-80s', 'END'));
    };
    PdbWriter.prototype.getString = function getString () {
        console.warn('PdbWriter.getString() is deprecated, use .getData instead');
        return this.getData();
    };
    /**
     * Get string containing the PDB file data
     * @return {String} PDB file
     */
    PdbWriter.prototype.getData = function getData () {
        this._writeRecords();
        return this._records.join('\n');
    };

    return PdbWriter;
}(Writer));

/**
 * Writer class for sdf/mol files.
 */
// Hard-coded chiral as false as we don't specify it any atoms
var CountFormat = '%3i%3i  0  0  0  0  0  0  0  0999 V2000';
var AtomLine = '%10.4f%10.4f%10.4f %-3s 0%3i  0  0  0';
var BondFormat = '%3i%3i%3i  0  0  0';
var SdfWriter = /*@__PURE__*/(function (Writer$$1) {
    function SdfWriter(structure) {
        Writer$$1.call(this);
        this.mimeType = 'text/plain';
        this.defaultName = 'structure';
        this.defaultExt = 'sdf';
        this.structure = structure;
        // Follow the pdb-writer example:
        this._records = [];
    }

    if ( Writer$$1 ) SdfWriter.__proto__ = Writer$$1;
    SdfWriter.prototype = Object.create( Writer$$1 && Writer$$1.prototype );
    SdfWriter.prototype.constructor = SdfWriter;

    var prototypeAccessors = { idString: { configurable: true },titleString: { configurable: true },countsString: { configurable: true },chargeLines: { configurable: true } };
    prototypeAccessors.idString.get = function () {
        return this.structure.id;
    };
    prototypeAccessors.titleString.get = function () {
        return '  ' + this.structure.title;
    };
    prototypeAccessors.countsString.get = function () {
        return Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])(CountFormat, this.structure.atomCount, this.structure.bondCount);
    };
    prototypeAccessors.chargeLines.get = function () {
        var pairs = [];
        this.structure.eachAtom(function (ap) {
            if (ap.formalCharge != null && ap.formalCharge !== 0) {
                pairs.push([ap.index, ap.formalCharge]);
            }
        });
        var lines = [];
        for (var i = 0; i < pairs.length; i += 8) {
            var nCharges = Math.min(8, pairs.length - i);
            var s = Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])('M  CHG%3i', nCharges);
            for (var j = i; j < i + nCharges; j++) {
                s += Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])(' %3i %3i', pairs[j][0] + 1, pairs[j][1]);
            }
            lines.push(s);
        }
        return lines;
    };
    SdfWriter.prototype.formatAtom = function formatAtom (ap) {
        var charge = 0;
        if (ap.formalCharge != null && ap.formalCharge !== 0) {
            charge = 4 - ap.formalCharge;
        }
        var line = Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])(AtomLine, ap.x, ap.y, ap.z, ap.element, charge);
        if (line.length !== 48) {
            throw new Error('Incompatible atom for sdf format');
        }
        return line;
    };
    SdfWriter.prototype.formatBond = function formatBond (bp) {
        return Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])(BondFormat, bp.atomIndex1 + 1, bp.atomIndex2 + 1, bp.bondOrder);
    };
    SdfWriter.prototype._writeRecords = function _writeRecords () {
        this._records.length = 0;
        this._writeHeader();
        this._writeCTab();
        this._writeFooter();
    };
    SdfWriter.prototype._writeHeader = function _writeHeader () {
        this._records.push(this.idString, this.titleString, '');
    };
    SdfWriter.prototype._writeCTab = function _writeCTab () {
        var this$1 = this;

        this._records.push(this.countsString);
        this.structure.eachAtom(function (ap) {
            this$1._records.push(this$1.formatAtom(ap));
        });
        this.structure.eachBond(function (bp) {
            this$1._records.push(this$1.formatBond(bp));
        });
        this.chargeLines.forEach(function (line) {
            this$1._records.push(line);
        });
        this._records.push('M  END');
    };
    SdfWriter.prototype._writeFooter = function _writeFooter () {
        this._records.push('$$$$');
    };
    SdfWriter.prototype.getData = function getData () {
        this._writeRecords();
        return this._records.join('\n');
    };

    Object.defineProperties( SdfWriter.prototype, prototypeAccessors );

    return SdfWriter;
}(Writer));

/**
 * @file IO Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 *
 * Adapted and converted to TypeScript from https://github.com/image-js/iobuffer
 * MIT License, Copyright (c) 2015 Michaël Zasso
 */
var defaultByteLength = 1024 * 8;
var charArray = [];
/**
 * Class for writing and reading binary data
 */
var IOBuffer = function IOBuffer(data, params) {
    if ( params === void 0 ) params = {};

    this._mark = 0;
    this._marks = [];
    this.offset = 0; // The current offset of the buffer's pointer
    this.littleEndian = true;
    var dataIsGiven = false;
    if (data === undefined) {
        data = defaultByteLength;
    }
    if (typeof data === 'number') {
        data = new ArrayBuffer(data);
    }
    else {
        dataIsGiven = true;
    }
    var offset = params.offset ? params.offset >>> 0 : 0;
    var byteLength = data.byteLength - offset;
    var dvOffset = offset;
    if (!(data instanceof ArrayBuffer)) {
        if (data.byteLength !== data.buffer.byteLength) {
            dvOffset = data.byteOffset + offset;
        }
        data = data.buffer;
    }
    if (dataIsGiven) {
        this._lastWrittenByte = byteLength;
    }
    else {
        this._lastWrittenByte = 0;
    }
    this.buffer = data;
    this.length = byteLength;
    this.byteLength = byteLength;
    this.byteOffset = dvOffset;
    this._data = new DataView(this.buffer, dvOffset, byteLength);
};
/**
 * Checks if the memory allocated to the buffer is sufficient to store more bytes after the offset
 * @param {number} [byteLength=1] The needed memory in bytes
 * @return {boolean} Returns true if there is sufficient space and false otherwise
 */
IOBuffer.prototype.available = function available (byteLength) {
    if (byteLength === undefined)
        { byteLength = 1; }
    return (this.offset + byteLength) <= this.length;
};
/**
 * Check if little-endian mode is used for reading and writing multi-byte values
 * @return {boolean} Returns true if little-endian mode is used, false otherwise
 */
IOBuffer.prototype.isLittleEndian = function isLittleEndian () {
    return this.littleEndian;
};
/**
 * Set little-endian mode for reading and writing multi-byte values
 * @return {IOBuffer}
 */
IOBuffer.prototype.setLittleEndian = function setLittleEndian () {
    this.littleEndian = true;
    return this;
};
/**
 * Check if big-endian mode is used for reading and writing multi-byte values
 * @return {boolean} Returns true if big-endian mode is used, false otherwise
 */
IOBuffer.prototype.isBigEndian = function isBigEndian () {
    return !this.littleEndian;
};
/**
 * Switches to big-endian mode for reading and writing multi-byte values
 * @return {IOBuffer}
 */
IOBuffer.prototype.setBigEndian = function setBigEndian () {
    this.littleEndian = false;
    return this;
};
/**
 * Move the pointer n bytes forward
 * @param {number} n
 * @return {IOBuffer}
 */
IOBuffer.prototype.skip = function skip (n) {
    if (n === undefined)
        { n = 1; }
    this.offset += n;
    return this;
};
/**
 * Move the pointer to the given offset
 * @param {number} offset
 * @return {IOBuffer}
 */
IOBuffer.prototype.seek = function seek (offset) {
    this.offset = offset;
    return this;
};
/**
 * Store the current pointer offset.
 * @see {@link IOBuffer#reset}
 * @return {IOBuffer}
 */
IOBuffer.prototype.mark = function mark () {
    this._mark = this.offset;
    return this;
};
/**
 * Move the pointer back to the last pointer offset set by mark
 * @see {@link IOBuffer#mark}
 * @return {IOBuffer}
 */
IOBuffer.prototype.reset = function reset () {
    this.offset = this._mark;
    return this;
};
/**
 * Push the current pointer offset to the mark stack
 * @see {@link IOBuffer#popMark}
 * @return {IOBuffer}
 */
IOBuffer.prototype.pushMark = function pushMark () {
    this._marks.push(this.offset);
    return this;
};
/**
 * Pop the last pointer offset from the mark stack, and set the current pointer offset to the popped value
 * @see {@link IOBuffer#pushMark}
 * @return {IOBuffer}
 */
IOBuffer.prototype.popMark = function popMark () {
    var offset = this._marks.pop();
    if (offset === undefined)
        { throw new Error('Mark stack empty'); }
    this.seek(offset);
    return this;
};
/**
 * Move the pointer offset back to 0
 * @return {IOBuffer}
 */
IOBuffer.prototype.rewind = function rewind () {
    this.offset = 0;
    return this;
};
/**
 * Make sure the buffer has sufficient memory to write a given byteLength at the current pointer offset
 * If the buffer's memory is insufficient, this method will create a new buffer (a copy) with a length
 * that is twice (byteLength + current offset)
 * @param {number} [byteLength = 1]
 * @return {IOBuffer}
 */
IOBuffer.prototype.ensureAvailable = function ensureAvailable (byteLength) {
    if (byteLength === undefined)
        { byteLength = 1; }
    if (!this.available(byteLength)) {
        var lengthNeeded = this.offset + byteLength;
        var newLength = lengthNeeded * 2;
        var newArray = new Uint8Array(newLength);
        newArray.set(new Uint8Array(this.buffer));
        this.buffer = newArray.buffer;
        this.length = this.byteLength = newLength;
        this._data = new DataView(this.buffer);
    }
    return this;
};
/**
 * Read a byte and return false if the byte's value is 0, or true otherwise
 * Moves pointer forward
 * @return {boolean}
 */
IOBuffer.prototype.readBoolean = function readBoolean () {
    return this.readUint8() !== 0;
};
/**
 * Read a signed 8-bit integer and move pointer forward
 * @return {number}
 */
IOBuffer.prototype.readInt8 = function readInt8 () {
    return this._data.getInt8(this.offset++);
};
/**
 * Read an unsigned 8-bit integer and move pointer forward
 * @return {number}
 */
IOBuffer.prototype.readUint8 = function readUint8 () {
    return this._data.getUint8(this.offset++);
};
/**
 * Alias for {@link IOBuffer#readUint8}
 * @return {number}
 */
IOBuffer.prototype.readByte = function readByte () {
    return this.readUint8();
};
/**
 * Read n bytes and move pointer forward.
 * @param {number} n
 * @return {Uint8Array}
 */
IOBuffer.prototype.readBytes = function readBytes (n) {
    if (n === undefined)
        { n = 1; }
    var bytes = new Uint8Array(n);
    for (var i = 0; i < n; i++) {
        bytes[i] = this.readByte();
    }
    return bytes;
};
/**
 * Read a 16-bit signed integer and move pointer forward
 * @return {number}
 */
IOBuffer.prototype.readInt16 = function readInt16 () {
    var value = this._data.getInt16(this.offset, this.littleEndian);
    this.offset += 2;
    return value;
};
/**
 * Read a 16-bit unsigned integer and move pointer forward
 * @return {number}
 */
IOBuffer.prototype.readUint16 = function readUint16 () {
    var value = this._data.getUint16(this.offset, this.littleEndian);
    this.offset += 2;
    return value;
};
/**
 * Read a 32-bit signed integer and move pointer forward
 * @return {number}
 */
IOBuffer.prototype.readInt32 = function readInt32 () {
    var value = this._data.getInt32(this.offset, this.littleEndian);
    this.offset += 4;
    return value;
};
/**
 * Read a 32-bit unsigned integer and move pointer forward
 * @return {number}
 */
IOBuffer.prototype.readUint32 = function readUint32 () {
    var value = this._data.getUint32(this.offset, this.littleEndian);
    this.offset += 4;
    return value;
};
/**
 * Read a 32-bit floating number and move pointer forward
 * @return {number}
 */
IOBuffer.prototype.readFloat32 = function readFloat32 () {
    var value = this._data.getFloat32(this.offset, this.littleEndian);
    this.offset += 4;
    return value;
};
/**
 * Read a 64-bit floating number and move pointer forward
 * @return {number}
 */
IOBuffer.prototype.readFloat64 = function readFloat64 () {
    var value = this._data.getFloat64(this.offset, this.littleEndian);
    this.offset += 8;
    return value;
};
/**
 * Read 1-byte ascii character and move pointer forward
 * @return {string}
 */
IOBuffer.prototype.readChar = function readChar () {
    return String.fromCharCode(this.readInt8());
};
/**
 * Read n 1-byte ascii characters and move pointer forward
 * @param {number} n
 * @return {string}
 */
IOBuffer.prototype.readChars = function readChars (n) {
        if ( n === void 0 ) n = 1;

    charArray.length = n;
    for (var i = 0; i < n; i++) {
        charArray[i] = this.readChar();
    }
    return charArray.join('');
};
/**
 * Write 0xff if the passed value is truthy, 0x00 otherwise
 * @param {any} value
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeBoolean = function writeBoolean (value) {
        if ( value === void 0 ) value = false;

    this.writeUint8(value ? 0xff : 0x00);
    return this;
};
/**
 * Write value as an 8-bit signed integer
 * @param {number} value
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeInt8 = function writeInt8 (value) {
    this.ensureAvailable(1);
    this._data.setInt8(this.offset++, value);
    this._updateLastWrittenByte();
    return this;
};
/**
 * Write value as a 8-bit unsigned integer
 * @param {number} value
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeUint8 = function writeUint8 (value) {
    this.ensureAvailable(1);
    this._data.setUint8(this.offset++, value);
    this._updateLastWrittenByte();
    return this;
};
/**
 * An alias for {@link IOBuffer#writeUint8}
 * @param {number} value
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeByte = function writeByte (value) {
    return this.writeUint8(value);
};
/**
 * Write bytes
 * @param {Array|Uint8Array} bytes
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeBytes = function writeBytes (bytes) {
    this.ensureAvailable(bytes.length);
    for (var i = 0; i < bytes.length; i++) {
        this._data.setUint8(this.offset++, bytes[i]);
    }
    this._updateLastWrittenByte();
    return this;
};
/**
 * Write value as an 16-bit signed integer
 * @param {number} value
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeInt16 = function writeInt16 (value) {
    this.ensureAvailable(2);
    this._data.setInt16(this.offset, value, this.littleEndian);
    this.offset += 2;
    this._updateLastWrittenByte();
    return this;
};
/**
 * Write value as a 16-bit unsigned integer
 * @param {number} value
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeUint16 = function writeUint16 (value) {
    this.ensureAvailable(2);
    this._data.setUint16(this.offset, value, this.littleEndian);
    this.offset += 2;
    this._updateLastWrittenByte();
    return this;
};
/**
 * Write a 32-bit signed integer at the current pointer offset
 * @param {number} value
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeInt32 = function writeInt32 (value) {
    this.ensureAvailable(4);
    this._data.setInt32(this.offset, value, this.littleEndian);
    this.offset += 4;
    this._updateLastWrittenByte();
    return this;
};
/**
 * Write a 32-bit unsigned integer at the current pointer offset
 * @param {number} value - The value to set
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeUint32 = function writeUint32 (value) {
    this.ensureAvailable(4);
    this._data.setUint32(this.offset, value, this.littleEndian);
    this.offset += 4;
    this._updateLastWrittenByte();
    return this;
};
/**
 * Write a 32-bit floating number at the current pointer offset
 * @param {number} value - The value to set
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeFloat32 = function writeFloat32 (value) {
    this.ensureAvailable(4);
    this._data.setFloat32(this.offset, value, this.littleEndian);
    this.offset += 4;
    this._updateLastWrittenByte();
    return this;
};
/**
 * Write a 64-bit floating number at the current pointer offset
 * @param {number} value
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeFloat64 = function writeFloat64 (value) {
    this.ensureAvailable(8);
    this._data.setFloat64(this.offset, value, this.littleEndian);
    this.offset += 8;
    this._updateLastWrittenByte();
    return this;
};
/**
 * Write the charCode of the passed string's first character to the current pointer offset
 * @param {string} str - The character to set
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeChar = function writeChar (str) {
    return this.writeUint8(str.charCodeAt(0));
};
/**
 * Write the charCodes of the passed string's characters to the current pointer offset
 * @param {string} str
 * @return {IOBuffer}
 */
IOBuffer.prototype.writeChars = function writeChars (str) {
    for (var i = 0; i < str.length; i++) {
        this.writeUint8(str.charCodeAt(i));
    }
    return this;
};
/**
 * Export a Uint8Array view of the internal buffer.
 * The view starts at the byte offset and its length
 * is calculated to stop at the last written byte or the original length.
 * @return {Uint8Array}
 */
IOBuffer.prototype.toArray = function toArray () {
    return new Uint8Array(this.buffer, this.byteOffset, this._lastWrittenByte);
};
/**
 * Update the last written byte offset
 * @private
 */
IOBuffer.prototype._updateLastWrittenByte = function _updateLastWrittenByte () {
    if (this.offset > this._lastWrittenByte) {
        this._lastWrittenByte = this.offset;
    }
};

/**
 * @file STL Writer
 * @author Paul Pillot <paul.pillot@cimf.ca>
 * @private
 */
// https://en.wikipedia.org/wiki/STL_(file_format)#ASCII_STL
/**
 * Create an STL File from a surface Object (e.g. for 3D printing)
 *
 * @example
 * molsurf = new MolecularSurface(structure)
 * surf = molsurf.getSurface({type: 'av', probeRadius: 1.4})
 * stl = new StlWriter(surf)
 * stl.download('myFileName')
 */
var StlWriter = /*@__PURE__*/(function (Writer$$1) {
    function StlWriter(surface) {
        Writer$$1.call(this);
        this.mimeType = 'application/vnd.ms-pki.stl';
        this.defaultName = 'surface';
        this.defaultExt = 'stl';
        this.surface = surface;
    }

    if ( Writer$$1 ) StlWriter.__proto__ = Writer$$1;
    StlWriter.prototype = Object.create( Writer$$1 && Writer$$1.prototype );
    StlWriter.prototype.constructor = StlWriter;
    /*
     * Get STL Binary data
     *
     * Adapted from: https://github.com/mrdoob/three.js/blob/master/examples/js/exporters/STLBinaryExporter.js
     * see https://en.wikipedia.org/wiki/STL_(file_format)#Binary_STL for the file format description
     *
     * @return {DataView} the data
     */
    StlWriter.prototype.getData = function getData () {
        var triangles = this.surface.index.length / 3;
        var bufferLength = triangles * 2 + triangles * 3 * 4 * 4 + 80 + 4;
        var output = new IOBuffer(bufferLength);
        output.skip(80); // skip header
        output.writeUint32(triangles);
        var vector = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        var vectorNorm1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        var vectorNorm2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        var vectorNorm3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        // traversing vertices
        for (var i = 0; i < triangles; i++) {
            var indices = [
                this.surface.index[i * 3],
                this.surface.index[i * 3 + 1],
                this.surface.index[i * 3 + 2]
            ];
            vectorNorm1.fromArray(this.surface.normal, indices[0] * 3);
            vectorNorm2.fromArray(this.surface.normal, indices[1] * 3);
            vectorNorm3.fromArray(this.surface.normal, indices[2] * 3);
            vector.addVectors(vectorNorm1, vectorNorm2).add(vectorNorm3).normalize();
            output.writeFloat32(vector.x);
            output.writeFloat32(vector.y);
            output.writeFloat32(vector.z);
            for (var j = 0; j < 3; j++) {
                vector.fromArray(this.surface.position, indices[j] * 3);
                output.writeFloat32(vector.x); // vertices
                output.writeFloat32(vector.y);
                output.writeFloat32(vector.z);
            }
            output.writeUint16(0); // attribute byte count
        }
        return new DataView(output.buffer);
    };

    return StlWriter;
}(Writer));

/**
 * @file Counter
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Counter class for keeping track of counts
 */
var Counter = function Counter() {
    this.count = 0;
    this.signals = {
        countChanged: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]()
    };
};
/**
 * Set the `count` to zero
 * @return {undefined}
 */
Counter.prototype.clear = function clear () {
    this.change(-this.count);
};
/**
 * Change the `count`
 * @fires Counter#countChanged
 * @param {Integer} delta - count change
 * @return {undefined}
 */
Counter.prototype.change = function change (delta) {
    this.count += delta;
    this.signals.countChanged.dispatch(delta, this.count);
    if (this.count < 0) {
        Log.warn('Counter.count below zero', this.count);
    }
};
/**
 * Increments the `count` by one.
 * @return {undefined}
 */
Counter.prototype.increment = function increment () {
    this.change(1);
};
/**
 * Decrements the `count` by one.
 * @return {undefined}
 */
Counter.prototype.decrement = function decrement () {
    this.change(-1);
};
/**
 * Listen to another counter object and change this `count` by the
 * same amount
 * @param  {Counter} counter - the counter object to listen to
 * @return {undefined}
 */
Counter.prototype.listen = function listen (counter) {
    this.change(counter.count);
    counter.signals.countChanged.add(this.change, this);
};
/**
 * Stop listening to the other counter object
 * @param  {Counter} counter - the counter object to stop listening to
 * @return {undefined}
 */
Counter.prototype.unlisten = function unlisten (counter) {
    var countChanged = counter.signals.countChanged;
    if (countChanged.has(this.change, this)) {
        countChanged.remove(this.change, this);
    }
};
/**
 * Invole the callback function once, when the `count` becomes zero
 * @param  {Function} callback - the callback function
 * @param  {Object}   context - the context for the callback function
 * @return {undefined}
 */
Counter.prototype.onZeroOnce = function onZeroOnce (callback, context) {
        var this$1 = this;

    if (this.count === 0) {
        callback.call(context);
    }
    else {
        var fn = function () {
            if (this$1.count === 0) {
                this$1.signals.countChanged.remove(fn, this$1);
                callback.call(context);
            }
        };
        this.signals.countChanged.add(fn, this);
    }
};
Counter.prototype.dispose = function dispose () {
    this.clear();
    this.signals.countChanged.dispose();
};

ShaderRegistry.add('shader/BasicLine.vert', "void main(){\n#include begin_vertex\n#include project_vertex\n}");

ShaderRegistry.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}");

ShaderRegistry.add('shader/Quad.vert', "varying vec2 vUv;\nvoid main() {\nvUv = uv;\ngl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}");

ShaderRegistry.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}");

/**
 * @file Stats
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Stats = function Stats() {
    this.signals = {
        updated: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]()
    };
    this.maxDuration = -Infinity;
    this.minDuration = Infinity;
    this.avgDuration = 14;
    this.lastDuration = Infinity;
    this.prevFpsTime = 0;
    this.lastFps = Infinity;
    this.lastFrames = 1;
    this.frames = 0;
    this.count = 0;
    this.begin();
};
Stats.prototype.update = function update () {
    this.startTime = this.end();
    this.currentTime = this.startTime;
    this.signals.updated.dispatch();
};
Stats.prototype.begin = function begin () {
    this.startTime = window.performance.now();
    this.lastFrames = this.frames;
};
Stats.prototype.end = function end () {
    var time = window.performance.now();
    this.count += 1;
    this.frames += 1;
    this.lastDuration = time - 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;
    if (time > this.prevFpsTime + 1000) {
        this.lastFps = this.frames;
        this.prevFpsTime = time;
        this.frames = 0;
    }
    return time;
};

ShaderRegistry.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");

ShaderRegistry.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}");

ShaderRegistry.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}");

ShaderRegistry.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");

ShaderRegistry.add('shader/chunk/nearclip_fragment.glsl', "#ifdef NEAR_CLIP\nif( vViewPosition.z < clipNear )\ndiscard;\n#endif");

ShaderRegistry.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");

ShaderRegistry.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");

ShaderRegistry.add('shader/chunk/radiusclip_fragment.glsl', "#ifdef RADIUS_CLIP\nif( distance( vViewPosition, vClipCenter ) > clipRadius )\ndiscard;\n#endif");

ShaderRegistry.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}");

/**
 * @file Shader Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getDefines(defines) {
    if (defines === undefined)
        { return ''; }
    var lines = [];
    for (var name in defines) {
        var value = defines[name];
        if (!value)
            { continue; }
        lines.push(("#define " + name + " " + value));
    }
    return lines.join('\n') + '\n';
}
var reInclude = /^(?!\/\/)\s*#include\s+(\S+)/gmi;
var shaderCache = {};
function getShader(name, defines) {
    if ( defines === void 0 ) defines = {};

    var hash = name + '|';
    for (var key in defines) {
        hash += key + ':' + defines[key];
    }
    if (!shaderCache[hash]) {
        var definesText = getDefines(defines);
        var shaderText = ShaderRegistry.get(("shader/" + name));
        if (!shaderText) {
            throw new Error(("empty shader, '" + name + "'"));
        }
        shaderText = shaderText.replace(reInclude, function (match, p1) {
            var path = "shader/chunk/" + p1 + ".glsl";
            var chunk = ShaderRegistry.get(path) || __WEBPACK_IMPORTED_MODULE_0_three__["M" /* ShaderChunk */][p1];
            if (!chunk) {
                throw new Error(("empty chunk, '" + p1 + "'"));
            }
            return chunk;
        });
        shaderCache[hash] = definesText + shaderText;
    }
    return shaderCache[hash];
}

/**
 * @file Viewer Constants
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
if (typeof WebGLRenderingContext !== 'undefined') {
    var wrcp = WebGLRenderingContext.prototype;
    // wrap WebGL debug function used by three.js and
    // ignore calls to them when the debug flag is not set
    var _getShaderParameter = wrcp.getShaderParameter;
    wrcp.getShaderParameter = function getShaderParameter() {
        if (Debug) {
            return _getShaderParameter.apply(this, arguments);
        }
        else {
            return true;
        }
    };
    var _getShaderInfoLog = wrcp.getShaderInfoLog;
    wrcp.getShaderInfoLog = function getShaderInfoLog() {
        if (Debug) {
            return _getShaderInfoLog.apply(this, arguments);
        }
        else {
            return '';
        }
    };
    var _getProgramParameter = wrcp.getProgramParameter;
    wrcp.getProgramParameter = function getProgramParameter(program, pname) {
        if (Debug || pname !== wrcp.LINK_STATUS) {
            return _getProgramParameter.apply(this, arguments);
        }
        else {
            return true;
        }
    };
    var _getProgramInfoLog = wrcp.getProgramInfoLog;
    wrcp.getProgramInfoLog = function getProgramInfoLog() {
        if (Debug) {
            return _getProgramInfoLog.apply(this, arguments);
        }
        else {
            return '';
        }
    };
}
var JitterVectors = [
    [
        [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]
    ]
];
JitterVectors.forEach(function (offsetList) {
    offsetList.forEach(function (offset) {
        // 0.0625 = 1 / 16
        offset[0] *= 0.0625;
        offset[1] *= 0.0625;
    });
});

/**
 * @file Tiled Renderer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var TiledRenderer = function TiledRenderer(renderer, camera, viewer, params) {
    this.canvas = document.createElement('canvas');
    this._viewer = viewer;
    this._factor = defaults(params.factor, 2);
    this._antialias = defaults(params.antialias, false);
    this._onProgress = params.onProgress;
    this._onFinish = params.onFinish;
    if (this._antialias)
        { this._factor *= 2; }
    this._n = this._factor * this._factor;
    // canvas
    this._width = this._viewer.width;
    this._height = this._viewer.height;
    if (this._antialias) {
        this.canvas.width = this._width * this._factor / 2;
        this.canvas.height = this._height * this._factor / 2;
    }
    else {
        this.canvas.width = this._width * this._factor;
        this.canvas.height = this._height * this._factor;
    }
    this._ctx = this.canvas.getContext('2d');
    this._viewerSampleLevel = viewer.sampleLevel;
    this._viewer.setSampling(-1);
};
TiledRenderer.prototype._renderTile = function _renderTile (i) {
    var viewer = this._viewer;
    var width = this._width;
    var height = this._height;
    var factor = this._factor;
    var x = i % factor;
    var y = Math.floor(i / factor);
    var offsetX = x * width;
    var offsetY = y * height;
    viewer.camera.setViewOffset(width * factor, height * factor, offsetX, offsetY, width, height);
    viewer.render();
    if (this._antialias) {
        var w = Math.round((offsetX + width) / 2) - Math.round(offsetX / 2);
        var h = Math.round((offsetY + height) / 2) - Math.round(offsetY / 2);
        this._ctx.drawImage(viewer.renderer.domElement, Math.round(offsetX / 2), Math.round(offsetY / 2), w, h);
    }
    else {
        this._ctx.drawImage(viewer.renderer.domElement, Math.floor(offsetX), Math.floor(offsetY), Math.ceil(width), Math.ceil(height));
    }
    if (typeof this._onProgress === 'function') {
        this._onProgress(i + 1, this._n, false);
    }
};
TiledRenderer.prototype._finalize = function _finalize () {
    this._viewer.setSampling(this._viewerSampleLevel);
    this._viewer.camera.view = null; // TODO
    if (typeof this._onFinish === 'function') {
        this._onFinish(this._n + 1, this._n, false);
    }
};
TiledRenderer.prototype.render = function render () {
    for (var i = 0; i <= this._n; ++i) {
        if (i === this._n) {
            this._finalize();
        }
        else {
            this._renderTile(i);
        }
    }
};
TiledRenderer.prototype.renderAsync = function renderAsync () {
        var this$1 = this;

    var count = 0;
    var n = this._n;
    var fn = function () {
        if (count === n) {
            this$1._finalize();
        }
        else {
            this$1._renderTile(count);
        }
        count += 1;
    };
    for (var i = 0; i <= n; ++i) {
        setTimeout(fn, 0);
    }
};

/**
 * @file Math Constants
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var TwoPI = 2 * Math.PI;
var DEG2RAD = Math.PI / 180;
var RAD2DEG = 180 / Math.PI;

/**
 * @file Array Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function circularMean(array, max, stride, offset, indices) {
    if ( stride === void 0 ) stride = 1;
    if ( offset === void 0 ) offset = 0;

    // http://en.wikipedia.org/wiki/Center_of_mass#Systems_with_periodic_boundary_conditions
    // Bai, Linge; Breen, David (2008). Calculating Center of Mass in an Unbounded 2D Environment. Journal of Graphics, GPU, and Game Tools 13 (4): 53–60.
    // http://stackoverflow.com/questions/18166507/using-fft-to-find-the-center-of-mass-under-periodic-boundary-conditions
    var n = indices ? indices.length : array.length / stride;
    var cosMean = 0;
    var sinMean = 0;
    if (indices) {
        for (var i = 0; i < n; ++i) {
            var c = (array[indices[i] * stride + offset] + max) % max;
            var angle = (c / max) * TwoPI - Math.PI;
            cosMean += Math.cos(angle);
            sinMean += Math.sin(angle);
        }
    }
    else {
        for (var i$1 = offset; i$1 < n; i$1 += stride) {
            var c$1 = (array[i$1] + max) % max;
            var angle$1 = (c$1 / max) * TwoPI - Math.PI;
            cosMean += Math.cos(angle$1);
            sinMean += Math.sin(angle$1);
        }
    }
    cosMean /= n;
    sinMean /= n;
    var meanAngle = Math.atan2(sinMean, cosMean);
    var mean = (meanAngle + Math.PI) / TwoPI * max;
    return mean;
}
function calculateCenterArray(array1, array2, center, offset) {
    if ( offset === void 0 ) offset = 0;

    var n = array1.length;
    var c = center || new Float32Array(n);
    for (var i = 0; i < n; i += 3) {
        c[offset + i + 0] = (array1[i + 0] + array2[i + 0]) / 2.0;
        c[offset + i + 1] = (array1[i + 1] + array2[i + 1]) / 2.0;
        c[offset + i + 2] = (array1[i + 2] + array2[i + 2]) / 2.0;
    }
    return c;
}
function calculateDirectionArray(array1, array2) {
    var n = array1.length;
    var direction = new Float32Array(n);
    for (var i = 0; i < n; i += 3) {
        direction[i + 0] = array2[i + 0] - array1[i + 0];
        direction[i + 1] = array2[i + 1] - array1[i + 1];
        direction[i + 2] = array2[i + 2] - array1[i + 2];
    }
    return direction;
}
function uniformArray(n, a, optionalTarget) {
    var array = optionalTarget || new Float32Array(n);
    for (var i = 0; i < n; ++i) {
        array[i] = a;
    }
    return array;
}
function uniformArray3(n, a, b, c, optionalTarget) {
    var array = optionalTarget || new Float32Array(n * 3);
    for (var i = 0; i < n; ++i) {
        var j = i * 3;
        array[j + 0] = a;
        array[j + 1] = b;
        array[j + 2] = c;
    }
    return array;
}
function centerArray3(array, center) {
    if ( center === void 0 ) center = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();

    var n = array.length;
    for (var i = 0; i < n; i += 3) {
        center.x += array[i];
        center.y += array[i + 1];
        center.z += array[i + 2];
    }
    center.divideScalar(n / 3);
    return center;
}
function serialArray(n) {
    var array = new Float32Array(n);
    for (var i = 0; i < n; ++i) {
        array[i] = i;
    }
    return array;
}
function serialBlockArray(n, b, offset, optionalTarget) {
    if ( offset === void 0 ) offset = 0;

    var array = optionalTarget || new Float32Array(n * b);
    for (var i = 0; i < n; ++i) {
        var k = offset + i * b;
        for (var j = 0; j < b; ++j) {
            array[k + j] = i;
        }
    }
    return array;
}
function replicateArrayEntries(array, m) {
    var n = array.length;
    var repArr = new Float32Array(n * m);
    for (var i = 0; i < n; ++i) {
        var k = i * m;
        var a = array[i];
        for (var j = 0; j < m; ++j) {
            repArr[k + j] = a;
        }
    }
    return repArr;
}
function replicateArray3Entries(array, m) {
    var n = array.length / 3;
    var repArr = new Float32Array(n * m * 3);
    for (var i = 0; i < n; ++i) {
        var v = i * 3;
        var k = i * m * 3;
        var a = array[v + 0];
        var b = array[v + 1];
        var c = array[v + 2];
        for (var j = 0; j < m; ++j) {
            var l = k + j * 3;
            repArr[l + 0] = a;
            repArr[l + 1] = b;
            repArr[l + 2] = c;
        }
    }
    return repArr;
}
function calculateMinArray(array1, array2) {
    var n = array1.length;
    var min = new Float32Array(n);
    for (var i = 0; i < n; i++) {
        min[i] = Math.min(array1[i], array2[i]);
    }
    return min;
}
function copyArray(src, dst, srcOffset, dstOffset, length) {
    for (var i = 0; i < length; ++i) {
        dst[dstOffset + i] = src[srcOffset + i];
    }
}
function copyWithin(array, srcOffset, dstOffset, length) {
    copyArray(array, array, srcOffset, dstOffset, length);
}
function quicksortCmp(arr, cmp, begin, end) {
    if ( begin === void 0 ) begin = 0;

    cmp = cmp || function cmp(a, b) {
        if (a > b)
            { return 1; }
        if (a < b)
            { return -1; }
        return 0;
    };
    end = (end || arr.length) - 1;
    var stack = [];
    var sp = -1;
    var left = begin;
    var right = end;
    var tmp;
    function swap(a, b) {
        var tmp2 = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp2;
    }
    var i, j;
    while (true) {
        if (right - left <= 25) {
            for (var k = left + 1; k <= right; ++k) {
                tmp = arr[k];
                i = k - 1;
                while (i >= left && cmp(arr[i], tmp) > 0) {
                    arr[i + 1] = arr[i];
                    --i;
                }
                arr[i + 1] = tmp;
            }
            if (sp === -1)
                { break; }
            right = stack[sp--]; // ?
            left = stack[sp--];
        }
        else {
            var median = (left + right) >> 1;
            i = left + 1;
            j = right;
            swap(median, i);
            if (cmp(arr[left], arr[right]) > 0) {
                swap(left, right);
            }
            if (cmp(arr[i], arr[right]) > 0) {
                swap(i, right);
            }
            if (cmp(arr[left], arr[i]) > 0) {
                swap(left, i);
            }
            tmp = arr[i];
            while (true) {
                do
                    { i++; }
                while (cmp(arr[i], tmp) < 0);
                do
                    { j--; }
                while (cmp(arr[j], tmp) > 0);
                if (j < i)
                    { break; }
                swap(i, j);
            }
            arr[left + 1] = arr[j];
            arr[j] = tmp;
            if (right - i + 1 >= j - left) {
                stack[++sp] = i;
                stack[++sp] = right;
                right = j - 1;
            }
            else {
                stack[++sp] = left;
                stack[++sp] = j - 1;
                left = i;
            }
        }
    }
    return arr;
}
function arrayMax(array) {
    var max = -Infinity;
    for (var i = 0, il = array.length; i < il; ++i) {
        if (array[i] > max)
            { max = array[i]; }
    }
    return max;
}
function arrayMin(array) {
    var min = Infinity;
    for (var i = 0, il = array.length; i < il; ++i) {
        if (array[i] < min)
            { min = array[i]; }
    }
    return min;
}
function arraySum(array, stride, offset) {
    if ( stride === void 0 ) stride = 1;
    if ( offset === void 0 ) offset = 0;

    var n = array.length;
    var sum = 0;
    for (var i = offset; i < n; i += stride) {
        sum += array[i];
    }
    return sum;
}
function arrayMean(array, stride, offset) {
    if ( stride === void 0 ) stride = 1;
    if ( offset === void 0 ) offset = 0;

    return arraySum(array, stride, offset) / (array.length / stride);
}
function arrayRms(array) {
    var n = array.length;
    var sumSq = 0;
    for (var i = 0; i < n; ++i) {
        var di = array[i];
        sumSq += di * di;
    }
    return Math.sqrt(sumSq / n);
}

/**
 * @file Viewer Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function _trimCanvas(canvas, r, g, b, a) {
    var canvasHeight = canvas.height;
    var canvasWidth = canvas.width;
    var ctx = canvas.getContext('2d');
    var pixels = ctx.getImageData(0, 0, canvasWidth, canvasHeight).data;
    var x, y, doBreak, off;
    doBreak = false;
    for (y = 0; y < canvasHeight; y++) {
        for (x = 0; x < canvasWidth; x++) {
            off = (y * canvasWidth + x) * 4;
            if (pixels[off] !== r || pixels[off + 1] !== g ||
                pixels[off + 2] !== b || pixels[off + 3] !== a) {
                doBreak = true;
                break;
            }
        }
        if (doBreak) {
            break;
        }
    }
    var topY = y;
    doBreak = false;
    for (x = 0; x < canvasWidth; x++) {
        for (y = 0; y < canvasHeight; y++) {
            off = (y * canvasWidth + x) * 4;
            if (pixels[off] !== r || pixels[off + 1] !== g ||
                pixels[off + 2] !== b || pixels[off + 3] !== a) {
                doBreak = true;
                break;
            }
        }
        if (doBreak) {
            break;
        }
    }
    var topX = x;
    doBreak = false;
    for (y = canvasHeight - 1; y >= 0; y--) {
        for (x = canvasWidth - 1; x >= 0; x--) {
            off = (y * canvasWidth + x) * 4;
            if (pixels[off] !== r || pixels[off + 1] !== g ||
                pixels[off + 2] !== b || pixels[off + 3] !== a) {
                doBreak = true;
                break;
            }
        }
        if (doBreak) {
            break;
        }
    }
    var bottomY = y;
    doBreak = false;
    for (x = canvasWidth - 1; x >= 0; x--) {
        for (y = canvasHeight - 1; y >= 0; y--) {
            off = (y * canvasWidth + x) * 4;
            if (pixels[off] !== r || pixels[off + 1] !== g ||
                pixels[off + 2] !== b || pixels[off + 3] !== a) {
                doBreak = true;
                break;
            }
        }
        if (doBreak) {
            break;
        }
    }
    var bottomX = x;
    var trimedCanvas = document.createElement('canvas');
    trimedCanvas.width = bottomX - topX;
    trimedCanvas.height = bottomY - topY;
    var trimedCtx = trimedCanvas.getContext('2d');
    trimedCtx.drawImage(canvas, topX, topY, trimedCanvas.width, trimedCanvas.height, 0, 0, trimedCanvas.width, trimedCanvas.height);
    return trimedCanvas;
}
/**
 * Image parameter object.
 * @typedef {Object} ImageParameters - image generation parameters
 * @property {Boolean} trim - trim the image
 * @property {Integer} factor - scaling factor to apply to the viewer canvas
 * @property {Boolean} antialias - antialias the image
 * @property {Boolean} transparent - transparent image background
 */
var ImageDefaultParameters = {
    trim: false,
    factor: 1,
    antialias: false,
    transparent: false,
    onProgress: undefined
};
/**
 * Make image from what is shown in a viewer canvas
 * @param  {Viewer} viewer - the viewer
 * @param  {ImageParameters} params - parameters object
 * @return {Promise} A Promise object that resolves to an image {@link Blob}.
 */
function makeImage(viewer, params) {
    if ( params === void 0 ) params = {};

    var ref = createParams(params, ImageDefaultParameters);
    var trim = ref.trim;
    var factor = ref.factor;
    var antialias = ref.antialias;
    var transparent = ref.transparent;
    var renderer = viewer.renderer;
    var camera = viewer.camera;
    var originalClearAlpha = renderer.getClearAlpha();
    var backgroundColor = renderer.getClearColor();
    function setLineWidthAndPixelSize(invert) {
        if ( invert === void 0 ) invert = false;

        var _factor = factor;
        if (antialias)
            { _factor *= 2; }
        if (invert)
            { _factor = 1 / _factor; }
        viewer.scene.traverse(function (o) {
            var m = o.material;
            if (m && m.linewidth) {
                m.linewidth *= _factor;
            }
            if (m && m.uniforms && m.uniforms.size) {
                if (m.uniforms.size.__seen === undefined) {
                    m.uniforms.size.value *= _factor;
                    m.uniforms.size.__seen = true;
                }
            }
            if (m && m.uniforms && m.uniforms.linewidth) {
                if (m.uniforms.linewidth.__seen === undefined) {
                    m.uniforms.linewidth.value *= _factor;
                    m.uniforms.linewidth.__seen = true;
                }
            }
        });
        viewer.scene.traverse(function (o) {
            var m = o.material;
            if (m && m.uniforms && m.uniforms.size) {
                delete m.uniforms.size.__seen;
            }
            if (m && m.uniforms && m.uniforms.linewidth) {
                delete m.uniforms.linewidth.__seen;
            }
        });
    }
    function trimCanvas(canvas) {
        if (trim) {
            var bg = backgroundColor;
            var r = transparent ? 0 : bg.r * 255;
            var g = transparent ? 0 : bg.g * 255;
            var b = transparent ? 0 : bg.b * 255;
            var a = transparent ? 0 : 255;
            return _trimCanvas(canvas, r, g, b, a);
        }
        else {
            return canvas;
        }
    }
    function onProgress(i, n, finished) {
        if (typeof params.onProgress === 'function') {
            params.onProgress(i, n, finished);
        }
    }
    return new Promise(function (resolve, reject) {
        var tiledRenderer = new TiledRenderer(renderer, camera, viewer, { factor: factor, antialias: antialias, onProgress: onProgress, onFinish: onFinish });
        renderer.setClearAlpha(transparent ? 0 : 1);
        setLineWidthAndPixelSize();
        tiledRenderer.renderAsync();
        function onFinish(i, n) {
            var canvas = trimCanvas(tiledRenderer.canvas);
            canvas.toBlob(function (blob) {
                renderer.setClearAlpha(originalClearAlpha);
                setLineWidthAndPixelSize(true);
                viewer.requestRender();
                onProgress(n, n, true);
                if (blob) {
                    resolve(blob);
                }
                else {
                    reject('error creating image');
                }
            }, 'image/png');
        }
    });
}
var vertex = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var modelViewProjectionMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
function sortProjectedPosition(scene, camera) {
    // console.time( "sort" );
    scene.traverseVisible(function (o) {
        if (!(o instanceof __WEBPACK_IMPORTED_MODULE_0_three__["I" /* Points */]) || !o.userData.buffer.parameters.sortParticles) {
            return;
        }
        var attributes = o.geometry.attributes; // TODO
        var n = attributes.position.count;
        if (n === 0)
            { return; }
        matrix.multiplyMatrices(camera.matrixWorldInverse, o.matrixWorld);
        modelViewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, matrix);
        var sortData, sortArray, zArray, cmpFn;
        if (!o.userData.sortData) {
            zArray = new Float32Array(n);
            sortArray = new Uint32Array(n);
            cmpFn = function (ai, bi) {
                var a = zArray[ai];
                var b = zArray[bi];
                if (a > b)
                    { return 1; }
                if (a < b)
                    { return -1; }
                return 0;
            };
            sortData = {
                __zArray: zArray,
                __sortArray: sortArray,
                __cmpFn: cmpFn
            };
            o.userData.sortData = sortData;
        }
        else {
            sortData = o.userData.sortData;
            zArray = sortData.__zArray;
            sortArray = sortData.__sortArray;
            cmpFn = sortData.__cmpFn;
        }
        for (var i = 0; i < n; ++i) {
            vertex.fromArray(attributes.position.array, i * 3);
            vertex.applyMatrix4(modelViewProjectionMatrix);
            // negate, so that sorting order is reversed
            zArray[i] = -vertex.z;
            sortArray[i] = i;
        }
        quicksortCmp(sortArray, cmpFn);
        var index, indexSrc, indexDst, tmpTab;
        for (var name in attributes) {
            var attr = attributes[name];
            var array = attr.array;
            var itemSize = attr.itemSize;
            if (!sortData[name]) {
                sortData[name] = new Float32Array(itemSize * n);
            }
            tmpTab = sortData[name];
            sortData[name] = array;
            for (var i$1 = 0; i$1 < n; ++i$1) {
                index = sortArray[i$1];
                for (var j = 0; j < itemSize; ++j) {
                    indexSrc = index * itemSize + j;
                    indexDst = i$1 * itemSize + j;
                    tmpTab[indexDst] = array[indexSrc];
                }
            }
            attributes[name].array = tmpTab;
            attributes[name].needsUpdate = true;
        }
    });
    // console.timeEnd( "sort" );
}
var resolution = new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */]();
var projectionMatrixInverse = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var projectionMatrixTranspose = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
function updateMaterialUniforms(group, camera, renderer, cDist, bRadius) {
    var size = new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */]();
    renderer.getSize(size);
    var canvasHeight = size.height;
    var pixelRatio = renderer.getPixelRatio();
    var ortho = camera.type === 'OrthographicCamera';
    resolution.set(size.width, size.height);
    projectionMatrixInverse.getInverse(camera.projectionMatrix);
    projectionMatrixTranspose.copy(camera.projectionMatrix).transpose();
    group.traverse(function (o) {
        var m = o.material;
        if (!m)
            { return; }
        var u = m.uniforms;
        if (!u)
            { return; }
        if (m.clipNear) {
            var nearFactor = (50 - m.clipNear) / 50;
            var nearClip = cDist - (bRadius * nearFactor);
            u.clipNear.value = nearClip;
        }
        if (u.canvasHeight) {
            u.canvasHeight.value = canvasHeight;
        }
        if (u.resolution) {
            u.resolution.value.copy(resolution);
        }
        if (u.pixelRatio) {
            u.pixelRatio.value = pixelRatio;
        }
        if (u.projectionMatrixInverse) {
            u.projectionMatrixInverse.value.copy(projectionMatrixInverse);
        }
        if (u.projectionMatrixTranspose) {
            u.projectionMatrixTranspose.value.copy(projectionMatrixTranspose);
        }
        if (u.ortho) {
            u.ortho.value = ortho;
        }
    });
}
function updateCameraUniforms(group, camera) {
    projectionMatrixInverse.getInverse(camera.projectionMatrix);
    projectionMatrixTranspose.copy(camera.projectionMatrix).transpose();
    group.traverse(function (o) {
        var m = o.material;
        if (!m)
            { return; }
        var u = m.uniforms;
        if (!u)
            { return; }
        if (u.projectionMatrixInverse) {
            u.projectionMatrixInverse.value.copy(projectionMatrixInverse);
        }
        if (u.projectionMatrixTranspose) {
            u.projectionMatrixTranspose.value.copy(projectionMatrixTranspose);
        }
    });
}

/**
 * @file Viewer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// adapted from https://webglfundamentals.org/webgl/resources/webgl-utils.js
// Copyright 2012, Gregg Tavares. Modified BSD License
function createProgram(gl, shaders, attribs, locations) {
    var program = gl.createProgram();
    if (!program) {
        console.log("error creating WebGL program");
        return;
    }
    shaders.forEach(function (shader) { return gl.attachShader(program, shader); });
    if (attribs) {
        attribs.forEach(function (attrib, i) {
            gl.bindAttribLocation(program, locations ? locations[i] : i, attrib);
        });
    }
    gl.linkProgram(program);
    // Check the link status
    var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (!linked) {
        console.log(("error linking program: " + (gl.getProgramInfoLog(program))));
        gl.deleteProgram(program);
        return null;
    }
    return program;
}
function loadShader(gl, shaderSource, shaderType) {
    var shader = gl.createShader(shaderType);
    if (!shader) {
        console.log(("error creating WebGL shader " + shaderType));
        return; // can't create shader
    }
    gl.shaderSource(shader, shaderSource);
    gl.compileShader(shader);
    // Check the compile status
    var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (!compiled) {
        console.log(("error compiling shader " + shader + ": " + (gl.getShaderInfoLog(shader))));
        gl.deleteShader(shader);
        return null;
    }
    return shader;
}
//
function getErrorDescription(gl, error) {
    switch (error) {
        case gl.NO_ERROR: return 'no error';
        case gl.INVALID_ENUM: return 'invalid enum';
        case gl.INVALID_VALUE: return 'invalid value';
        case gl.INVALID_OPERATION: return 'invalid operation';
        case gl.INVALID_FRAMEBUFFER_OPERATION: return 'invalid framebuffer operation';
        case gl.OUT_OF_MEMORY: return 'out of memory';
        case gl.CONTEXT_LOST_WEBGL: return 'context lost';
    }
    return 'unknown error';
}
function getExtension(gl, name) {
    var ext = gl.getExtension(name);
    if (!ext)
        { console.log(("extension '" + name + "' not available")); }
    return ext;
}
var TextureTestVertShader = "\nattribute vec4 a_position;\n\nvoid main() {\n  gl_Position = a_position;\n}";
var TextureTestFragShader = "\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}";
var TextureTestTexCoords = new Float32Array([
    -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0
]);
function testTextureSupport(type) {
    // adapted from
    // https://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
    // Get A WebGL context
    var canvas = document.createElement('canvas');
    canvas.width = 16;
    canvas.height = 16;
    canvas.style.width = 16 + 'px';
    canvas.style.height = 16 + 'px';
    var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
    if (!gl) {
        console.log(("error creating webgl context for " + type));
        return false;
    }
    if (!(gl instanceof WebGLRenderingContext)) {
        console.log("Got unexpected type for WebGL rendering context");
        return false;
    }
    getExtension(gl, 'OES_texture_float');
    getExtension(gl, 'OES_texture_half_float');
    getExtension(gl, 'WEBGL_color_buffer_float');
    // setup shaders
    var vertShader = loadShader(gl, TextureTestVertShader, gl.VERTEX_SHADER);
    var fragShader = loadShader(gl, TextureTestFragShader, gl.FRAGMENT_SHADER);
    if (!vertShader || !fragShader)
        { return false; }
    // setup program
    var program = createProgram(gl, [vertShader, fragShader]);
    if (!program) {
        console.log("error creating WebGL program");
        return false;
    }
    gl.useProgram(program);
    // look up where the vertex data needs to go.
    var positionLocation = gl.getAttribLocation(program, "a_position");
    var colorLoc = gl.getUniformLocation(program, "u_color");
    if (!colorLoc) {
        console.log("error getting 'u_color' uniform location");
        return false;
    }
    // provide texture coordinates for the rectangle.
    var positionBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, TextureTestTexCoords, gl.STATIC_DRAW);
    gl.enableVertexAttribArray(positionLocation);
    gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
    var whiteTex = gl.createTexture();
    var whiteData = new Uint8Array([255, 255, 255, 255]);
    gl.bindTexture(gl.TEXTURE_2D, whiteTex);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, whiteData);
    var tex = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, type, null);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    var fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
    var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
    if (status !== gl.FRAMEBUFFER_COMPLETE) {
        console.log(("error creating framebuffer for " + type));
        return false;
    }
    // Draw the rectangle.
    gl.bindTexture(gl.TEXTURE_2D, whiteTex);
    gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
    gl.drawArrays(gl.TRIANGLES, 0, 6);
    gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    gl.clearColor(1, 0, 0, 1);
    gl.clear(gl.COLOR_BUFFER_BIT);
    gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
    gl.drawArrays(gl.TRIANGLES, 0, 6);
    // Check if rendered correctly
    var pixel = new Uint8Array(4);
    gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
    if (pixel[0] !== 0 || pixel[1] < 248 || pixel[2] < 248 || pixel[3] < 254) {
        console.log(("not able to actually render to " + type + " texture"));
        return false;
    }
    // Check reading from float texture
    if (type === gl.FLOAT) {
        gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
        var floatPixel = new Float32Array(4);
        gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.FLOAT, floatPixel);
        var error = gl.getError();
        if (error) {
            console.log(("error reading pixels as float: '" + (getErrorDescription(gl, error)) + "'"));
            return false;
        }
    }
    return true;
}

/**
 * @file Viewer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var pixelBufferFloat = new Float32Array(4 * 25);
var pixelBufferUint = new Uint8Array(4 * 25);
// When picking, we read a 25 pixel (5x5) array (readRenderTargetPixels)
// We read the pixels in the order below to find what was picked.
// This starts at the center and tries successively further points.
// (Many points will be at equal distance to the center, their order
// is arbitrary).
var pixelOrder = [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];
var tmpMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
function onBeforeRender(renderer, scene, camera, geometry, material /*, group */) {
    var u = material.uniforms;
    var updateList = [];
    if (u.objectId) {
        u.objectId.value = SupportsReadPixelsFloat ? this.id : this.id / 255;
        updateList.push('objectId');
    }
    if (u.modelViewMatrixInverse || u.modelViewMatrixInverseTranspose ||
        u.modelViewProjectionMatrix || u.modelViewProjectionMatrixInverse) {
        this.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, this.matrixWorld);
    }
    if (u.modelViewMatrixInverse) {
        u.modelViewMatrixInverse.value.getInverse(this.modelViewMatrix);
        updateList.push('modelViewMatrixInverse');
    }
    if (u.modelViewMatrixInverseTranspose) {
        if (u.modelViewMatrixInverse) {
            u.modelViewMatrixInverseTranspose.value.copy(u.modelViewMatrixInverse.value).transpose();
        }
        else {
            u.modelViewMatrixInverseTranspose.value
                .getInverse(this.modelViewMatrix)
                .transpose();
        }
        updateList.push('modelViewMatrixInverseTranspose');
    }
    if (u.modelViewProjectionMatrix) {
        u.modelViewProjectionMatrix.value.multiplyMatrices(camera.projectionMatrix, this.modelViewMatrix);
        updateList.push('modelViewProjectionMatrix');
    }
    if (u.modelViewProjectionMatrixInverse) {
        if (u.modelViewProjectionMatrix) {
            tmpMatrix.copy(u.modelViewProjectionMatrix.value);
            u.modelViewProjectionMatrixInverse.value.getInverse(tmpMatrix);
        }
        else {
            tmpMatrix.multiplyMatrices(camera.projectionMatrix, this.modelViewMatrix);
            u.modelViewProjectionMatrixInverse.value.getInverse(tmpMatrix);
        }
        updateList.push('modelViewProjectionMatrixInverse');
    }
    if (updateList.length) {
        var materialProperties = renderer.properties.get(material);
        if (materialProperties.program) {
            var gl = renderer.getContext();
            var p = materialProperties.program;
            gl.useProgram(p.program);
            var pu = p.getUniforms();
            updateList.forEach(function (name) {
                pu.setValue(gl, name, u[name].value);
            });
        }
    }
}
/**
 * Viewer class
 * @class
 * @param {String|Element} [idOrElement] - dom id or element
 */
var Viewer = function Viewer(idOrElement) {
    this.boundingBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    this.boundingBoxSize = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.boundingBoxLength = 0;
    this.info = {
        memory: {
            programs: 0,
            geometries: 0,
            textures: 0
        },
        render: {
            calls: 0,
            vertices: 0,
            faces: 0,
            points: 0
        }
    };
    this.distVector = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.signals = {
        ticked: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"](),
        rendered: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]()
    };
    if (typeof idOrElement === 'string') {
        var elm = document.getElementById(idOrElement);
        if (elm === null) {
            this.container = document.createElement('div');
        }
        else {
            this.container = elm;
        }
    }
    else if (idOrElement instanceof HTMLElement) {
        this.container = idOrElement;
    }
    else {
        this.container = document.createElement('div');
    }
    if (this.container === document.body) {
        this.width = window.innerWidth || 1;
        this.height = window.innerHeight || 1;
    }
    else {
        var box = this.container.getBoundingClientRect();
        this.width = box.width || 1;
        this.height = box.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();
    if (this._initRenderer() === false) {
        Log.error('Viewer: could not initialize renderer');
        return;
    }
    this._initHelper();
    // fog & background
    this.setBackground();
    this.setFog();
    this.animate = this.animate.bind(this);
};

var prototypeAccessors$2 = { cameraDistance: { configurable: true } };
Viewer.prototype._initParams = function _initParams () {
    this.parameters = {
        fogColor: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](0x000000),
        fogNear: 50,
        fogFar: 100,
        backgroundColor: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](0x000000),
        cameraType: 'perspective',
        cameraFov: 40,
        cameraEyeSep: 0.3,
        cameraZ: -80,
        clipNear: 0,
        clipFar: 100,
        clipDist: 10,
        clipMode: 'scene',
        clipScale: 'relative',
        lightColor: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](0xdddddd),
        lightIntensity: 1.0,
        ambientColor: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](0xdddddd),
        ambientIntensity: 0.2,
        sampleLevel: 0
    };
};
Viewer.prototype._initCamera = function _initCamera () {
    var lookAt = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 0, 0);
    var ref = this;
        var width = ref.width;
        var height = ref.height;
    this.perspectiveCamera = new __WEBPACK_IMPORTED_MODULE_0_three__["F" /* PerspectiveCamera */](this.parameters.cameraFov, width / height);
    this.perspectiveCamera.position.z = this.parameters.cameraZ;
    this.perspectiveCamera.lookAt(lookAt);
    this.orthographicCamera = new __WEBPACK_IMPORTED_MODULE_0_three__["E" /* OrthographicCamera */](width / -2, width / 2, height / 2, height / -2);
    this.orthographicCamera.position.z = this.parameters.cameraZ;
    this.orthographicCamera.lookAt(lookAt);
    this.stereoCamera = new __WEBPACK_IMPORTED_MODULE_0_three__["P" /* StereoCamera */]();
    this.stereoCamera.aspect = 0.5;
    this.stereoCamera.eyeSep = this.parameters.cameraEyeSep;
    var cameraType = this.parameters.cameraType;
    if (cameraType === 'orthographic') {
        this.camera = this.orthographicCamera;
    }
    else if (cameraType === 'perspective' || cameraType === 'stereo') {
        this.camera = this.perspectiveCamera;
    }
    else {
        throw new Error(("Unknown cameraType '" + cameraType + "'"));
    }
    this.camera.updateProjectionMatrix();
};
Viewer.prototype._initStats = function _initStats () {
    this.stats = new Stats();
};
Viewer.prototype._initScene = function _initScene () {
    if (!this.scene) {
        this.scene = new __WEBPACK_IMPORTED_MODULE_0_three__["L" /* 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);
    // fog
    this.scene.fog = new __WEBPACK_IMPORTED_MODULE_0_three__["q" /* Fog */](this.parameters.fogColor.getHex());
    // light
    this.spotLight = new __WEBPACK_IMPORTED_MODULE_0_three__["O" /* 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);
};
Viewer.prototype._initRenderer = function _initRenderer () {
    var dpr = window.devicePixelRatio;
    var ref = this;
        var width = ref.width;
        var height = ref.height;
    try {
        this.renderer = new __WEBPACK_IMPORTED_MODULE_0_three__["Z" /* WebGLRenderer */]({
            preserveDrawingBuffer: true,
            alpha: true,
            antialias: true
        });
    }
    catch (e) {
        this.wrapper.innerHTML = WebglErrorMessage;
        return false;
    }
    this.renderer.setPixelRatio(dpr);
    this.renderer.setSize(width, height);
    this.renderer.autoClear = false;
    this.renderer.sortObjects = true;
    var gl = this.renderer.getContext();
    // console.log(gl.getContextAttributes().antialias)
    // console.log(gl.getParameter(gl.SAMPLES))
    // For WebGL1, extensions must be explicitly enabled. 
    // The following are builtin to WebGL2 (and don't appear as 
    // extensions)
    // EXT_frag_depth, OES_element_index_uint, OES_texture_float 
    // OES_texture_half_float
    // The WEBGL_color_buffer_float extension is replaced by
    // EXT_color_buffer_float
    // If not webgl2 context, explicitly check for these
    if (!this.renderer.capabilities.isWebGL2) {
        setExtensionFragDepth(this.renderer.extensions.get('EXT_frag_depth'));
        this.renderer.extensions.get('OES_element_index_uint');
        setSupportsReadPixelsFloat((this.renderer.extensions.get('OES_texture_float') &&
            this.renderer.extensions.get('WEBGL_color_buffer_float')) ||
            (this.renderer.extensions.get('OES_texture_float') &&
                testTextureSupport(gl.FLOAT)));
        // picking texture
        this.renderer.extensions.get('OES_texture_float');
        this.supportsHalfFloat = (this.renderer.extensions.get('OES_texture_half_float') &&
            testTextureSupport(0x8D61));
    }
    else {
        setExtensionFragDepth(true);
        setSupportsReadPixelsFloat(this.renderer.extensions.get('EXT_color_buffer_float'));
        this.supportsHalfFloat = true;
    }
    this.wrapper.appendChild(this.renderer.domElement);
    var dprWidth = width * dpr;
    var dprHeight = height * dpr;
    if (Debug) {
        console.log(JSON.stringify({
            'Browser': Browser,
            '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': testTextureSupport(gl.FLOAT),
            'testTextureSupport HalfFloat': testTextureSupport(0x8D61),
            'this.supportsHalfFloat': this.supportsHalfFloat,
            'SupportsReadPixelsFloat': SupportsReadPixelsFloat
        }, null, 2));
    }
    this.pickingTarget = new __WEBPACK_IMPORTED_MODULE_0_three__["Y" /* WebGLRenderTarget */](dprWidth, dprHeight, {
        minFilter: __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */],
        magFilter: __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */],
        stencilBuffer: false,
        format: __WEBPACK_IMPORTED_MODULE_0_three__["K" /* RGBAFormat */],
        type: SupportsReadPixelsFloat ? __WEBPACK_IMPORTED_MODULE_0_three__["p" /* FloatType */] : __WEBPACK_IMPORTED_MODULE_0_three__["V" /* UnsignedByteType */]
    });
    this.pickingTarget.texture.generateMipmaps = false;
    // workaround to reset the gl state after using testTextureSupport
    // fixes some bug where nothing is rendered to the canvas
    // when animations are started on page load
    this.renderer.setRenderTarget(this.pickingTarget);
    this.renderer.clear();
    this.renderer.setRenderTarget(null);
    // ssaa textures
    this.sampleTarget = new __WEBPACK_IMPORTED_MODULE_0_three__["Y" /* WebGLRenderTarget */](dprWidth, dprHeight, {
        minFilter: __WEBPACK_IMPORTED_MODULE_0_three__["w" /* LinearFilter */],
        magFilter: __WEBPACK_IMPORTED_MODULE_0_three__["w" /* LinearFilter */],
        format: __WEBPACK_IMPORTED_MODULE_0_three__["K" /* RGBAFormat */]
    });
    this.holdTarget = new __WEBPACK_IMPORTED_MODULE_0_three__["Y" /* WebGLRenderTarget */](dprWidth, dprHeight, {
        minFilter: __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */],
        magFilter: __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */],
        format: __WEBPACK_IMPORTED_MODULE_0_three__["K" /* RGBAFormat */],
        type: __WEBPACK_IMPORTED_MODULE_0_three__["V" /* UnsignedByteType */]
        // using HalfFloatType or FloatType does not work on some Chrome 61 installations
        // type: this.supportsHalfFloat ? HalfFloatType : (
        //   SupportsReadPixelsFloat ? FloatType : UnsignedByteType
        // )
    });
    this.compositeUniforms = {
        'tForeground': new __WEBPACK_IMPORTED_MODULE_0_three__["S" /* Uniform */](this.sampleTarget.texture),
        'scale': new __WEBPACK_IMPORTED_MODULE_0_three__["S" /* Uniform */](1.0)
    };
    this.compositeMaterial = new __WEBPACK_IMPORTED_MODULE_0_three__["N" /* ShaderMaterial */]({
        uniforms: this.compositeUniforms,
        vertexShader: getShader('Quad.vert'),
        fragmentShader: getShader('Quad.frag'),
        premultipliedAlpha: true,
        transparent: true,
        blending: __WEBPACK_IMPORTED_MODULE_0_three__["a" /* AdditiveBlending */],
        depthTest: false,
        depthWrite: false
    });
    this.compositeCamera = new __WEBPACK_IMPORTED_MODULE_0_three__["E" /* OrthographicCamera */](-1, 1, 1, -1, 0, 1);
    this.compositeScene = new __WEBPACK_IMPORTED_MODULE_0_three__["L" /* Scene */]();
    this.compositeScene.name = 'compositeScene';
    this.compositeScene.add(new __WEBPACK_IMPORTED_MODULE_0_three__["z" /* Mesh */](new __WEBPACK_IMPORTED_MODULE_0_three__["H" /* PlaneGeometry */](2, 2), this.compositeMaterial));
};
Viewer.prototype._initHelper = function _initHelper () {
    var 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
    ]);
    var positions = new Float32Array(8 * 3);
    var bbGeometry = new __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]();
    bbGeometry.setIndex(new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](indices, 1));
    bbGeometry.setAttribute('position', new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](positions, 3));
    var bbMaterial = new __WEBPACK_IMPORTED_MODULE_0_three__["N" /* ShaderMaterial */]({
        uniforms: { 'uColor': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */]('skyblue') } },
        vertexShader: getShader('BasicLine.vert'),
        fragmentShader: getShader('BasicLine.frag')
    });
    this.boundingBoxMesh = new __WEBPACK_IMPORTED_MODULE_0_three__["v" /* LineSegments */](bbGeometry, bbMaterial);
    this.helperGroup.add(this.boundingBoxMesh);
};
Viewer.prototype.updateHelper = function updateHelper () {
    var position = this.boundingBoxMesh.geometry.attributes.position; // TODO
    var array = position.array;
    var ref = this.boundingBox;
        var min = ref.min;
        var max = ref.max;
    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;
    if (!this.boundingBox.isEmpty()) {
        this.boundingBoxMesh.geometry.computeBoundingSphere();
    }
};
/** Distance from origin (lookAt point) */
prototypeAccessors$2.cameraDistance.get = function () {
    return Math.abs(this.camera.position.z);
};
/** Set distance from origin (lookAt point); along the -z axis */
prototypeAccessors$2.cameraDistance.set = function (d) {
    this.camera.position.z = -d;
};
Viewer.prototype.add = function add (buffer, instanceList) {
        var this$1 = this;

    // Log.time( "Viewer.add" );
    if (instanceList) {
        instanceList.forEach(function (instance) { return this$1.addBuffer(buffer, instance); });
    }
    else {
        this.addBuffer(buffer);
    }
    buffer.group.name = 'meshGroup';
    buffer.wireframeGroup.name = 'wireframeGroup';
    if (buffer.parameters.background) {
        this.backgroundGroup.add(buffer.group);
        this.backgroundGroup.add(buffer.wireframeGroup);
    }
    else {
        this.modelGroup.add(buffer.group);
        this.modelGroup.add(buffer.wireframeGroup);
    }
    if (buffer.pickable) {
        this.pickingGroup.add(buffer.pickingGroup);
    }
    if (Debug)
        { this.updateHelper(); }
    // Log.timeEnd( "Viewer.add" );
};
Viewer.prototype.addBuffer = function addBuffer (buffer, instance) {
    // Log.time( "Viewer.addBuffer" );
    function setUserData(object) {
        if (object instanceof __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]) {
            object.children.forEach(setUserData);
        }
        else {
            object.userData.buffer = buffer;
            object.userData.instance = instance;
            object.onBeforeRender = onBeforeRender;
        }
    }
    var mesh = buffer.getMesh();
    if (instance) {
        mesh.applyMatrix4(instance.matrix);
    }
    setUserData(mesh);
    buffer.group.add(mesh);
    var wireframeMesh = buffer.getWireframeMesh();
    if (instance) {
        // wireframeMesh.applyMatrix( instance.matrix );
        wireframeMesh.matrix.copy(mesh.matrix);
        wireframeMesh.position.copy(mesh.position);
        wireframeMesh.quaternion.copy(mesh.quaternion);
        wireframeMesh.scale.copy(mesh.scale);
    }
    setUserData(wireframeMesh);
    buffer.wireframeGroup.add(wireframeMesh);
    if (buffer.pickable) {
        var pickingMesh = buffer.getPickingMesh();
        if (instance) {
            // pickingMesh.applyMatrix( instance.matrix );
            pickingMesh.matrix.copy(mesh.matrix);
            pickingMesh.position.copy(mesh.position);
            pickingMesh.quaternion.copy(mesh.quaternion);
            pickingMesh.scale.copy(mesh.scale);
        }
        setUserData(pickingMesh);
        buffer.pickingGroup.add(pickingMesh);
    }
    if (instance) {
        this._updateBoundingBox(buffer.geometry, buffer.matrix, instance.matrix);
    }
    else {
        this._updateBoundingBox(buffer.geometry, buffer.matrix);
    }
    // Log.timeEnd( "Viewer.addBuffer" );
};
Viewer.prototype.remove = function remove (buffer) {
    this.translationGroup.children.forEach(function (group) {
        group.remove(buffer.group);
        group.remove(buffer.wireframeGroup);
    });
    if (buffer.pickable) {
        this.pickingGroup.remove(buffer.pickingGroup);
    }
    this.updateBoundingBox();
    if (Debug)
        { this.updateHelper(); }
    // this.requestRender();
};
Viewer.prototype._updateBoundingBox = function _updateBoundingBox (geometry, matrix, instanceMatrix) {
    var boundingBox = this.boundingBox;
    function updateGeometry(geometry, matrix, instanceMatrix) {
        if (geometry.boundingBox == null) {
            geometry.computeBoundingBox();
        }
        var geoBoundingBox = geometry.boundingBox.clone();
        if (matrix) {
            geoBoundingBox.applyMatrix4(matrix);
        }
        if (instanceMatrix) {
            geoBoundingBox.applyMatrix4(instanceMatrix);
        }
        if (geoBoundingBox.min.equals(geoBoundingBox.max)) {
            // mainly to give a single impostor geometry some volume
            // as it is only expanded in the shader on the GPU
            geoBoundingBox.expandByScalar(5);
        }
        boundingBox.union(geoBoundingBox);
    }
    function updateNode(node) {
        if (node.geometry !== undefined) {
            var matrix, instanceMatrix;
            if (node.userData.buffer) {
                matrix = node.userData.buffer.matrix;
            }
            if (node.userData.instance) {
                instanceMatrix = node.userData.instance.matrix;
            }
            updateGeometry(node.geometry, matrix, instanceMatrix); // TODO
        }
    }
    if (geometry) {
        updateGeometry(geometry, matrix, instanceMatrix);
    }
    else {
        boundingBox.makeEmpty();
        this.modelGroup.traverse(updateNode);
        this.backgroundGroup.traverse(updateNode);
    }
    boundingBox.getSize(this.boundingBoxSize);
    this.boundingBoxLength = this.boundingBoxSize.length();
};
Viewer.prototype.updateBoundingBox = function updateBoundingBox () {
    this._updateBoundingBox();
    if (Debug)
        { this.updateHelper(); }
};
Viewer.prototype.getPickingPixels = function getPickingPixels () {
    var ref = this;
        var width = ref.width;
        var height = ref.height;
    var n = width * height * 4;
    var imgBuffer = SupportsReadPixelsFloat ? new Float32Array(n) : new Uint8Array(n);
    this.render(true);
    this.renderer.readRenderTargetPixels(this.pickingTarget, 0, 0, width, height, imgBuffer);
    return imgBuffer;
};
Viewer.prototype.getImage = function getImage (picking) {
        var this$1 = this;

    return new Promise(function (resolve) {
        if (picking) {
            var ref = this$1;
                var width = ref.width;
                var height = ref.height;
            var n = width * height * 4;
            var imgBuffer = this$1.getPickingPixels();
            if (SupportsReadPixelsFloat) {
                var imgBuffer2 = new Uint8Array(n);
                for (var i = 0; i < n; ++i) {
                    imgBuffer2[i] = Math.round(imgBuffer[i] * 255);
                }
                imgBuffer = imgBuffer2;
            }
            var canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            var ctx = canvas.getContext('2d'); // TODO
            var imgData = ctx.getImageData(0, 0, width, height);
            imgData.data.set(imgBuffer); // TODO
            ctx.putImageData(imgData, 0, 0);
            canvas.toBlob(resolve, 'image/png'); // TODO
        }
        else {
            this$1.renderer.domElement.toBlob(resolve, 'image/png'); // TODO
        }
    });
};
Viewer.prototype.makeImage = function makeImage$1 (params) {
        if ( params === void 0 ) params = {};

    return makeImage(this, params);
};
Viewer.prototype.setLight = function setLight (color, intensity, ambientColor, ambientIntensity) {
    var p = this.parameters;
    if (color !== undefined)
        { p.lightColor.set(color); } // TODO
    if (intensity !== undefined)
        { p.lightIntensity = intensity; }
    if (ambientColor !== undefined)
        { p.ambientColor.set(ambientColor); } // TODO
    if (ambientIntensity !== undefined)
        { p.ambientIntensity = ambientIntensity; }
    this.requestRender();
};
Viewer.prototype.setFog = function setFog (color, near, far) {
    var p = this.parameters;
    if (color !== undefined)
        { p.fogColor.set(color); } // TODO
    if (near !== undefined)
        { p.fogNear = near; }
    if (far !== undefined)
        { p.fogFar = far; }
    this.requestRender();
};
Viewer.prototype.setBackground = function setBackground (color) {
    var p = this.parameters;
    if (color)
        { p.backgroundColor.set(color); } // TODO
    this.setFog(p.backgroundColor);
    this.renderer.setClearColor(p.backgroundColor, 0);
    this.renderer.domElement.style.backgroundColor = p.backgroundColor.getStyle();
    this.requestRender();
};
Viewer.prototype.setSampling = function setSampling (level) {
    if (level !== undefined) {
        this.parameters.sampleLevel = level;
        this.sampleLevel = level;
    }
    this.requestRender();
};
Viewer.prototype.setCamera = function setCamera (type, fov, eyeSep) {
    var p = this.parameters;
    if (type)
        { p.cameraType = type; }
    if (fov)
        { p.cameraFov = fov; }
    if (eyeSep)
        { p.cameraEyeSep = eyeSep; }
    if (p.cameraType === 'orthographic') {
        if (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 (p.cameraType === 'perspective' || p.cameraType === 'stereo') {
        if (this.camera !== this.perspectiveCamera) {
            this.camera = this.perspectiveCamera;
            this.camera.position.copy(this.orthographicCamera.position);
            this.camera.up.copy(this.orthographicCamera.up);
        }
    }
    else {
        throw new Error(("Unknown cameraType '" + (p.cameraType) + "'"));
    }
    this.perspectiveCamera.fov = p.cameraFov;
    this.stereoCamera.eyeSep = p.cameraEyeSep;
    this.camera.updateProjectionMatrix();
    this.requestRender();
};
Viewer.prototype.setClip = function setClip (near, far, dist, clipMode, clipScale) {
    var p = this.parameters;
    if (near !== undefined)
        { p.clipNear = near; }
    if (far !== undefined)
        { p.clipFar = far; }
    if (dist !== undefined)
        { p.clipDist = dist; }
    if (clipMode !== undefined)
        { p.clipMode = clipMode; }
    if (clipScale !== undefined)
        { p.clipScale = clipScale; }
    this.requestRender();
};
Viewer.prototype.setSize = function setSize (width, height) {
    this.width = width || 1;
    this.height = height || 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();
    var dpr = window.devicePixelRatio;
    this.renderer.setPixelRatio(dpr);
    this.renderer.setSize(width, height);
    var dprWidth = this.width * dpr;
    var dprHeight = this.height * dpr;
    this.pickingTarget.setSize(dprWidth, dprHeight);
    this.sampleTarget.setSize(dprWidth, dprHeight);
    this.holdTarget.setSize(dprWidth, dprHeight);
    this.requestRender();
};
Viewer.prototype.handleResize = function handleResize () {
    if (this.container === document.body) {
        this.setSize(window.innerWidth, window.innerHeight);
    }
    else {
        var box = this.container.getBoundingClientRect();
        this.setSize(box.width, box.height);
    }
};
Viewer.prototype.updateInfo = function updateInfo (reset) {
    var ref = this.info;
        var memory = ref.memory;
        var render = ref.render;
    if (reset) {
        memory.programs = 0;
        memory.geometries = 0;
        memory.textures = 0;
        render.calls = 0;
        render.vertices = 0;
        render.points = 0;
    }
    else {
        var rInfo = this.renderer.info;
        var rMemory = rInfo.memory;
        var rRender = rInfo.render;
        memory.geometries = rMemory.geometries;
        memory.textures = rMemory.textures;
        render.calls += rRender.calls;
        render.faces += rRender.triangles;
        render.points += rRender.points;
    }
};
Viewer.prototype.animate = function animate () {
    this.signals.ticked.dispatch(this.stats);
    var delta = window.performance.now() - this.stats.startTime;
    if (delta > 500 && !this.isStill && this.sampleLevel < 3 && this.sampleLevel !== -1) {
        var currentSampleLevel = this.sampleLevel;
        this.sampleLevel = 3;
        this.renderPending = true;
        this.render();
        this.isStill = true;
        this.sampleLevel = currentSampleLevel;
        if (Debug)
            { Log.log('rendered still frame'); }
    }
    window.requestAnimationFrame(this.animate);
};
Viewer.prototype.pick = function pick (x, y) {
    if (this.parameters.cameraType === 'stereo') {
        // TODO picking broken for stereo camera
        return {
            'pid': 0,
            'instance': undefined,
            'picker': undefined
        };
    }
    x *= window.devicePixelRatio;
    y *= window.devicePixelRatio;
    x = Math.max(x - 2, 0);
    y = Math.max(y - 2, 0);
    var pid = 0, instance, picker;
    var pixelBuffer = SupportsReadPixelsFloat ? pixelBufferFloat : pixelBufferUint;
    this.render(true);
    this.renderer.readRenderTargetPixels(this.pickingTarget, x, y, 5, 5, pixelBuffer);
    for (var i = 0; i < pixelOrder.length; i++) {
        var offset = pixelOrder[i] * 4;
        var oid = Math.round(pixelBuffer[offset + 3]);
        var object = this.pickingGroup.getObjectById(oid);
        if (object) {
            instance = object.userData.instance;
            picker = object.userData.buffer.picking;
        }
        else {
            continue;
        }
        if (SupportsReadPixelsFloat) {
            pid =
                ((Math.round(pixelBuffer[offset] * 255) << 16) & 0xFF0000) |
                    ((Math.round(pixelBuffer[offset + 1] * 255) << 8) & 0x00FF00) |
                    ((Math.round(pixelBuffer[offset + 2] * 255)) & 0x0000FF);
        }
        else {
            pid =
                (pixelBuffer[offset] << 16) |
                    (pixelBuffer[offset + 1] << 8) |
                    (pixelBuffer[offset + 2]);
        }
    }
    // if( Debug ){
    //   const rgba = Array.apply( [], pixelBuffer );
    //   Log.log( pixelBuffer );
    //   Log.log(
    // "picked color",
    // rgba.map( c => { return c.toPrecision( 2 ) } )
    //   );
    //   Log.log( "picked pid", pid );
    //   Log.log( "picked oid", oid );
    //   Log.log( "picked object", object );
    //   Log.log( "picked instance", instance );
    //   Log.log( "picked position", x, y );
    //   Log.log( "devicePixelRatio", window.devicePixelRatio );
    // }
    return { pid: pid, instance: instance, picker: picker };
};
Viewer.prototype.requestRender = function requestRender () {
        var this$1 = this;

    if (this.renderPending) {
        // Log.info("there is still a 'render' call pending")
        return;
    }
    // start gathering stats anew after inactivity
    if (window.performance.now() - this.stats.startTime > 22) {
        this.stats.begin();
        this.isStill = false;
    }
    this.renderPending = true;
    window.requestAnimationFrame(function () {
        this$1.render();
        this$1.stats.update();
    });
};
Viewer.prototype.updateZoom = function updateZoom () {
    var fov = degToRad(this.perspectiveCamera.fov);
    var height = 2 * Math.tan(fov / 2) * this.cameraDistance;
    this.orthographicCamera.zoom = this.height / height;
};
/**
 * Convert an absolute clip value to a relative one using bRadius.
 *
 * 0.0 -> 50.0
 * bRadius -> 0.0
 */
Viewer.prototype.absoluteToRelative = function absoluteToRelative (d) {
    return 50 * (1 - d / this.bRadius);
};
/**
 * Convert a relative clip value to an absolute one using bRadius
 *
 * 0.0 -> bRadius
 * 50.0 -> 0.0
 */
Viewer.prototype.relativeToAbsolute = function relativeToAbsolute (d) {
    return this.bRadius * (1 - d / 50);
};
/**
 * Intepret clipMode, clipScale and set the camera and fog clipping.
 * Also ensures bRadius and cDist are valid
 */
Viewer.prototype.__updateClipping = function __updateClipping () {
    var p = this.parameters;
    // bRadius must always be updated for material-based clipping
    // and for focus calculations
    this.bRadius = Math.max(10, this.boundingBoxLength * 0.5);
    // FL: Removed below, but leaving commented as I don't understand intention
    // this.bRadius += this.boundingBox.getCenter(this.distVector).length()
    if (!isFinite(this.bRadius)) {
        this.bRadius = 50;
    }
    this.camera.getWorldPosition(this.distVector);
    this.cDist = this.distVector.length();
    if (!this.cDist) {
        // recover from a broken (NaN) camera position
        this.cameraDistance = Math.abs(p.cameraZ);
        this.cDist = Math.abs(p.cameraZ);
    }
    // fog
    var fog = this.scene.fog;
    fog.color.set(p.fogColor);
    if (p.clipMode === 'camera') {
        // Always interpret clipScale as absolute for clipMode camera
        this.camera.near = p.clipNear;
        this.camera.far = p.clipFar;
        fog.near = p.fogNear;
        fog.far = p.fogFar;
    }
    else {
        // scene mode
        if (p.clipScale === 'absolute') {
            // absolute scene mode; offset clip planes from scene center
            // (note: positive values move near plane towards camera and rear plane away)
            this.camera.near = this.cDist - p.clipNear;
            this.camera.far = this.cDist + p.clipFar;
            fog.near = this.cDist - p.fogNear;
            fog.far = this.cDist + p.fogFar;
        }
        else {
            // relative scene mode (default): convert pecentages to Angstroms
            var nearFactor = (50 - p.clipNear) / 50;
            var farFactor = -(50 - p.clipFar) / 50;
            this.camera.near = this.cDist - (this.bRadius * nearFactor);
            this.camera.far = this.cDist + (this.bRadius * farFactor);
            var fogNearFactor = (50 - p.fogNear) / 50;
            var fogFarFactor = -(50 - p.fogFar) / 50;
            fog.near = this.cDist - (this.bRadius * fogNearFactor);
            fog.far = this.cDist + (this.bRadius * fogFarFactor);
        }
    }
    if (p.clipMode !== 'camera') {
        if (this.camera.type === 'PerspectiveCamera') {
            this.camera.near = Math.max(0.1, p.clipDist, this.camera.near);
            this.camera.far = Math.max(1, this.camera.far);
            fog.near = Math.max(0.1, fog.near);
            fog.far = Math.max(1, fog.far);
        }
        else if (this.camera.type === 'OrthographicCamera') {
            if (p.clipDist > 0) {
                this.camera.near = Math.max(p.clipDist, this.camera.near);
            }
        }
    }
};
Viewer.prototype.__updateCamera = function __updateCamera () {
    var camera = this.camera;
    camera.updateMatrix();
    camera.updateMatrixWorld(true);
    camera.updateProjectionMatrix();
    updateMaterialUniforms(this.scene, camera, this.renderer, this.cDist, this.bRadius);
    sortProjectedPosition(this.scene, camera);
};
Viewer.prototype.__setVisibility = function __setVisibility (model, picking, background, helper) {
    this.modelGroup.visible = model;
    this.pickingGroup.visible = picking;
    this.backgroundGroup.visible = background;
    this.helperGroup.visible = helper;
};
Viewer.prototype.__updateLights = function __updateLights () {
    this.spotLight.color.set(this.parameters.lightColor);
    this.spotLight.intensity = this.parameters.lightIntensity;
    this.distVector.copy(this.camera.position).setLength(this.boundingBoxLength * 100);
    this.spotLight.position.copy(this.camera.position).add(this.distVector);
    this.ambientLight.color.set(this.parameters.ambientColor);
    this.ambientLight.intensity = this.parameters.ambientIntensity;
};
Viewer.prototype.__renderPickingGroup = function __renderPickingGroup (camera) {
    this.renderer.setRenderTarget(this.pickingTarget || null);
    this.renderer.clear();
    this.__setVisibility(false, true, false, false);
    this.renderer.render(this.scene, camera);
    this.renderer.setRenderTarget(null);
    this.updateInfo();
    //  back to standard render target
    this.renderer.setRenderTarget(null); // TODO
    // if (Debug) {
    //   this.__setVisibility(false, true, false, true);
    //   this.renderer.clear();
    //   this.renderer.render(this.scene, camera);
    // }
};
Viewer.prototype.__renderModelGroup = function __renderModelGroup (camera, renderTarget) {
    this.renderer.setRenderTarget(renderTarget || null);
    this.renderer.clear();
    this.__setVisibility(false, false, true, false);
    this.renderer.render(this.scene, camera);
    this.renderer.clear(false, true, true);
    this.updateInfo();
    this.__setVisibility(true, false, false, Debug);
    this.renderer.render(this.scene, camera);
    this.renderer.setRenderTarget(null); // set back to default canvas
    this.updateInfo();
};
Viewer.prototype.__renderSuperSample = function __renderSuperSample (camera) {
    // based on the Supersample Anti-Aliasing Render Pass
    // contributed to three.js by bhouston / http://clara.io/
    //
    // This manual approach to SSAA re-renders the scene ones for
    // each sample with camera jitter and accumulates the results.
    // References: https://en.wikipedia.org/wiki/Supersampling
    var offsetList = JitterVectors[Math.max(0, Math.min(this.sampleLevel, 5))];
    var baseSampleWeight = 1.0 / offsetList.length;
    var roundingRange = 1 / 32;
    this.compositeUniforms.tForeground.value = this.sampleTarget.texture;
    var width = this.sampleTarget.width;
    var height = this.sampleTarget.height;
    if (this.parameters.cameraType === 'stereo') {
        width /= 2;
    }
    // render the scene multiple times, each slightly jitter offset
    // from the last and accumulate the results.
    for (var i = 0; i < offsetList.length; ++i) {
        var offset = offsetList[i];
        camera.setViewOffset(width, height, offset[0], offset[1], width, height);
        camera.updateProjectionMatrix();
        updateCameraUniforms(this.scene, camera);
        var sampleWeight = baseSampleWeight;
        // the theory is that equal weights for each sample lead to an
        // accumulation of rounding errors.
        // The following equation varies the sampleWeight per sample
        // so that it is uniformly distributed across a range of values
        // whose rounding errors cancel each other out.
        var uniformCenteredDistribution = -0.5 + (i + 0.5) / offsetList.length;
        sampleWeight += roundingRange * uniformCenteredDistribution;
        this.compositeUniforms.scale.value = sampleWeight;
        this.__renderModelGroup(camera, this.sampleTarget);
        this.renderer.setRenderTarget(this.holdTarget);
        if (i === 0) {
            this.renderer.clear();
        }
        this.renderer.render(this.compositeScene, this.compositeCamera);
    }
    this.compositeUniforms.scale.value = 1.0;
    this.compositeUniforms.tForeground.value = this.holdTarget.texture;
    camera.clearViewOffset();
    this.renderer.setRenderTarget(null);
    this.renderer.clear();
    this.renderer.render(this.compositeScene, this.compositeCamera);
};
Viewer.prototype.__renderStereo = function __renderStereo (picking) {
        if ( picking === void 0 ) picking = false;

    var stereoCamera = this.stereoCamera;
    stereoCamera.update(this.perspectiveCamera);
    var renderer = this.renderer;
    var size = new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */]();
    renderer.getSize(size);
    renderer.setScissorTest(true);
    renderer.setScissor(0, 0, size.width / 2, size.height);
    renderer.setViewport(0, 0, size.width / 2, size.height);
    updateCameraUniforms(this.scene, stereoCamera.cameraL);
    this.__render(picking, stereoCamera.cameraL);
    renderer.setScissor(size.width / 2, 0, size.width / 2, size.height);
    renderer.setViewport(size.width / 2, 0, size.width / 2, size.height);
    updateCameraUniforms(this.scene, stereoCamera.cameraR);
    this.__render(picking, stereoCamera.cameraR);
    renderer.setScissorTest(false);
    renderer.setViewport(0, 0, size.width, size.height);
};
Viewer.prototype.__render = function __render (picking, camera) {
        if ( picking === void 0 ) picking = false;

    if (picking) {
        if (!this.lastRenderedPicking)
            { this.__renderPickingGroup(camera); }
    }
    else if (this.sampleLevel > 0 && this.parameters.cameraType !== 'stereo') {
        // TODO super sample broken for stereo camera
        this.__renderSuperSample(camera);
    }
    else {
        this.__renderModelGroup(camera);
    }
};
Viewer.prototype.render = function render (picking) {
        if ( picking === void 0 ) picking = false;

    if (this.rendering) {
        Log.warn("'tried to call 'render' from within 'render'");
        return;
    }
    // Log.time('Viewer.render')
    this.rendering = true;
    try {
        this.__updateClipping();
        this.__updateCamera();
        this.__updateLights();
        this.updateInfo(true);
        // render
        if (this.parameters.cameraType === 'stereo') {
            this.__renderStereo(picking);
        }
        else {
            this.__render(picking, this.camera);
        }
        this.lastRenderedPicking = picking;
    }
    finally {
        this.rendering = false;
        this.renderPending = false;
    }
    this.signals.rendered.dispatch();
    // Log.timeEnd('Viewer.render')
    // Log.log(this.info.memory, this.info.render)
};
Viewer.prototype.clear = function clear () {
    Log.log('scene cleared');
    this.scene.remove(this.rotationGroup);
    this._initScene();
    this.renderer.clear();
};
Viewer.prototype.dispose = function dispose () {
    this.renderer.dispose();
};

Object.defineProperties( Viewer.prototype, prototypeAccessors$2 );

/**
 * @file Constants
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var LeftMouseButton = 1;
var MiddleMouseButton = 2;
var RightMouseButton = 3;

/**
 * @file Mouse Observer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * @example
 * mouseObserver.signals.scrolled.add( function( delta ){ ... } );
 *
 * @typedef {Object} MouseSignals
 * @property {Signal<Integer, Integer>} moved - on move: deltaX, deltaY
 * @property {Signal<Number>} scrolled - on scroll: delta
 * @property {Signal<Integer, Integer>} dragged - on drag: deltaX, deltaY
 * @property {Signal} dropped - on drop
 * @property {Signal} clicked - on click
 * @property {Signal} hovered - on hover
 */
function getTouchDistance(event) {
    var dx = event.touches[0].pageX - event.touches[1].pageX;
    var dy = event.touches[0].pageY - event.touches[1].pageY;
    return Math.sqrt(dx * dx + dy * dy);
}
function getMouseButtons(event) {
    if (typeof event === 'object') {
        if ('buttons' in event) {
            return event.buttons;
        }
        else if ('which' in event) {
            var b = event.which;
            if (b === 2) {
                return 4;
            }
            else if (b === 3) {
                return 2;
            }
            else if (b > 0) {
                return 1 << (b - 1);
            }
        }
        else if ('button' in event) {
            var b$1 = event.button;
            if (b$1 === 1) {
                return 4;
            }
            else if (b$1 === 2) {
                return 2;
            }
            else if (b$1 >= 0) {
                return 1 << b$1;
            }
        }
    }
    return 0;
}
/**
 * Mouse observer
 *
 * @example
 * // listen to mouse moving (and touch-moving) events
 * mouseObserver.moved.moved.add( function( deltaX, deltaY ){ ... } );
 *
 * @example
 * // listen to scrolling (and pinching) events
 * mouseObserver.signals.scrolled.add( function( delta ){ ... } );
 *
 * @example
 * // listen to dragging (and touch-dragging) events
 * mouseObserver.signals.dragged.add( function( deltaX, deltaY ){ ... } );
 *
 * @example
 * // listen to clicking (and tapping) events
 * mouseObserver.signals.clicked.add( function(){ ... } );
 *
 * @example
 * // listen to double clicking (and double tapping) events
 * mouseObserver.signals.doubleClicked.add( function(){ ... } );
 *
 * @example
 * // listen to hovering events
 * mouseObserver.signals.hovered.add( function(){ ... } );
 */
var MouseObserver = function MouseObserver(domElement, params) {
    if ( params === void 0 ) params = {};

    this.domElement = domElement;
    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 __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */](); // Position on page
    this.prevPosition = new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */](); // Previous position on page
    this.down = new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */](); // Position on page when clicked
    this.canvasPosition = new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */](); // Position on dom element
    this.prevClickCP = new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */]();
    this.moving = false; // Flag indicating if the mouse is moving
    this.hovering = true; // Flag indicating if the mouse is hovering
    this.scrolled = false; // Flag indicating if there was a scolling event since the last mouse move
    this.lastMoved = Infinity; // Timestamp of last mouse move
    this.which = 0; // 0: No button; 1: Left button; 2: Middle button; 3: Right button
    this.buttons = 0; // 0: No button; 1: Left button; 2: Right button; 4: Middle button
    this.pressed = false; // Flag indicating if the mouse is pressed down
    this.altKey = false; // Flag indicating if the alt key is pressed
    this.ctrlKey = false; // Flag indicating if the ctrl key is pressed
    this.metaKey = false; // Flag indicating if the meta key is pressed
    this.shiftKey = false; // Flag indicating if the shift key is pressed
    this.domElement.style.touchAction = 'none';
    this.hoverTimeout = defaults(params.hoverTimeout, 50);
    this.handleScroll = defaults(params.handleScroll, true);
    this.doubleClickSpeed = defaults(params.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();
    var opt = { passive: false }; // treat as 'passive' so preventDefault can be called
    document.addEventListener('mousewheel', this._onMousewheel, opt);
    document.addEventListener('wheel', this._onMousewheel, opt);
    document.addEventListener('MozMousePixelScroll', this._onMousewheel, opt);
    document.addEventListener('mousemove', this._onMousemove, opt);
    document.addEventListener('mousedown', this._onMousedown, opt);
    document.addEventListener('mouseup', this._onMouseup, opt);
    document.addEventListener('contextmenu', this._onContextmenu, opt);
    document.addEventListener('touchstart', this._onTouchstart, opt);
    document.addEventListener('touchend', this._onTouchend, opt);
    document.addEventListener('touchmove', this._onTouchmove, opt);
};

var prototypeAccessors$3 = { key: { configurable: true } };
prototypeAccessors$3.key.get = function () {
    var key = 0;
    if (this.altKey)
        { key += 1; }
    if (this.ctrlKey)
        { key += 2; }
    if (this.metaKey)
        { key += 4; }
    if (this.shiftKey)
        { key += 8; }
    return key;
};
MouseObserver.prototype.setParameters = function setParameters (params) {
        if ( params === void 0 ) params = {};

    this.hoverTimeout = defaults(params.hoverTimeout, this.hoverTimeout);
};
/**
 * listen to mouse actions
 * @emits {MouseSignals.clicked} when clicked
 * @emits {MouseSignals.hovered} when hovered
 * @return {undefined}
 */
MouseObserver.prototype._listen = function _listen () {
    var now = window.performance.now();
    var cp = this.canvasPosition;
    if (this.doubleClickPending && now - this.lastClicked > this.doubleClickSpeed) {
        this.doubleClickPending = false;
    }
    if (now - this.lastMoved > this.hoverTimeout) {
        this.moving = false;
    }
    if (this.scrolled || (!this.moving && !this.hovering)) {
        this.scrolled = false;
        if (this.hoverTimeout !== -1 && this.overElement) {
            this.hovering = true;
            this.signals.hovered.dispatch(cp.x, cp.y);
        }
    }
    window.requestAnimationFrame(this._listen);
};
/**
 * handle mouse scroll
 * @emits {MouseSignals.scrolled} when scrolled
 * @param  {Event} event - mouse event
 * @return {undefined}
 */
MouseObserver.prototype._onMousewheel = function _onMousewheel (event) {
        var this$1 = this;

    if (event.target !== this.domElement || !this.handleScroll) {
        return;
    }
    event.preventDefault();
    this._setKeys(event);
    var delta = 0;
    if ('deltaY' in event && 'deltaMode' in event) {
        // all modern browsers, using WheelEvent; deltaY + down (toward user)
        if (event.deltaMode === WheelEvent.DOM_DELTA_PIXEL)
            // everything except Firefox: normally 100 per wheel click
            { delta = -event.deltaY * (2.5 / 100.0); }
        else if (event.deltaMode === WheelEvent.DOM_DELTA_LINE)
            // Firefox in line mode, normally 3 per wheel click
            { delta = -event.deltaY * (2.5 / 3.0); }
        else // page mode: 1 per wheel click
            { delta = -event.deltaY * 2.5; }
    }
    else if ('deltaY' in event && !('detail' in event)) {
        // Old Firefox or IE 11: deltaY but no deltaMode; treat as pixels
        delta = -event.deltaY * (2.5 / 100.0);
    }
    else if (event.wheelDelta !== undefined) {
        delta = -event.wheelDelta * (2.5 / 100);
    }
    else if (event.wheelDeltaY !== undefined) {
        delta = -event.wheelDeltaY * (2.5 / 100);
    }
    else {
        // Old Firefox, MouseWheelEvent
        delta = -event.detail / 3;
    }
    this.signals.scrolled.dispatch(delta);
    setTimeout(function () {
        this$1.scrolled = true;
    }, this.hoverTimeout);
};
/**
 * handle mouse move
 * @emits {MouseSignals.moved} when moved
 * @emits {MouseSignals.dragged} when dragged
 * @param  {Event} event - mouse event
 * @return {undefined}
 */
MouseObserver.prototype._onMousemove = function _onMousemove (event) {
    if (event.target === this.domElement) {
        event.preventDefault();
        this.overElement = true;
    }
    else {
        this.overElement = false;
    }
    this._setKeys(event);
    this.moving = true;
    this.hovering = false;
    this.lastMoved = window.performance.now();
    this.prevPosition.copy(this.position);
    this.position.set(event.clientX, event.clientY);
    this._setCanvasPosition(event);
    var dx = this.prevPosition.x - this.position.x;
    var dy = this.prevPosition.y - this.position.y;
    this.signals.moved.dispatch(dx, dy);
    if (this.pressed) {
        this.signals.dragged.dispatch(dx, dy);
    }
};
MouseObserver.prototype._onMousedown = function _onMousedown (event) {
    if (event.target !== this.domElement) {
        return;
    }
    event.preventDefault();
    this._setKeys(event);
    this.moving = false;
    this.hovering = false;
    this.down.set(event.clientX, event.clientY);
    this.position.set(event.clientX, event.clientY);
    this.which = event.which;
    this.buttons = getMouseButtons(event);
    this.pressed = true;
    this._setCanvasPosition(event);
};
/**
 * handle mouse up
 * @emits {MouseSignals.doubleClicked} when double clicked
 * @emits {MouseSignals.dropped} when dropped
 * @param  {Event} event - mouse event
 * @return {undefined}
 */
MouseObserver.prototype._onMouseup = function _onMouseup (event) {
    if (event.target === this.domElement) {
        event.preventDefault();
    }
    this._setKeys(event);
    var cp = this.canvasPosition;
    if (this._distance() < 4) {
        this.lastClicked = window.performance.now();
        if (this.doubleClickPending && this.prevClickCP.distanceTo(cp) < 4) {
            this.signals.doubleClicked.dispatch(cp.x, cp.y);
            this.doubleClickPending = false;
        }
        this.signals.clicked.dispatch(cp.x, cp.y);
        this.doubleClickPending = true;
        this.prevClickCP.copy(cp);
    }
    this.which = undefined;
    this.buttons = undefined;
    this.pressed = undefined;
    // if (this._distance() > 3 || event.which === RightMouseButton) {
    //   this.signals.dropped.dispatch();
    // }
};
MouseObserver.prototype._onContextmenu = function _onContextmenu (event) {
    if (event.target === this.domElement) {
        event.preventDefault();
    }
};
MouseObserver.prototype._onTouchstart = function _onTouchstart (event) {
    if (event.target !== this.domElement) {
        return;
    }
    event.preventDefault();
    this.pressed = true;
    switch (event.touches.length) {
        case 1: {
            this.moving = false;
            this.hovering = false;
            this.down.set(event.touches[0].pageX, event.touches[0].pageY);
            this.position.set(event.touches[0].pageX, event.touches[0].pageY);
            this._setCanvasPosition(event.touches[0]);
            break;
        }
        case 2: {
            this.down.set((event.touches[0].pageX + event.touches[1].pageX) / 2, (event.touches[0].pageY + event.touches[1].pageY) / 2);
            this.position.set((event.touches[0].pageX + event.touches[1].pageX) / 2, (event.touches[0].pageY + event.touches[1].pageY) / 2);
            this.lastTouchDistance = getTouchDistance(event);
        }
    }
};
MouseObserver.prototype._onTouchend = function _onTouchend (event) {
    if (event.target === this.domElement) {
        event.preventDefault();
    }
    this.which = undefined;
    this.buttons = undefined;
    this.pressed = undefined;
};
MouseObserver.prototype._onTouchmove = function _onTouchmove (event) {
    if (event.target === this.domElement) {
        event.preventDefault();
        this.overElement = true;
    }
    else {
        this.overElement = false;
    }
    switch (event.touches.length) {
        case 1: {
            this._setKeys(event);
            this.which = LeftMouseButton;
            this.buttons = 1;
            this.moving = true;
            this.hovering = false;
            this.lastMoved = window.performance.now();
            this.prevPosition.copy(this.position);
            this.position.set(event.touches[0].pageX, event.touches[0].pageY);
            this._setCanvasPosition(event.touches[0]);
            var dx = this.prevPosition.x - this.position.x;
            var dy = this.prevPosition.y - this.position.y;
            this.signals.moved.dispatch(dx, dy);
            if (this.pressed) {
                this.signals.dragged.dispatch(dx, dy);
            }
            break;
        }
        case 2: {
            var touchDistance = getTouchDistance(event);
            var delta = touchDistance - this.lastTouchDistance;
            this.lastTouchDistance = touchDistance;
            this.prevPosition.copy(this.position);
            this.position.set((event.touches[0].pageX + event.touches[1].pageX) / 2, (event.touches[0].pageY + event.touches[1].pageY) / 2);
            if (Math.abs(delta) > 2 && this.handleScroll &&
                this.position.distanceTo(this.prevPosition) < 2) {
                this.which = 0;
                this.buttons = 0;
                this.signals.scrolled.dispatch(delta / 2);
            }
            else {
                this.which = RightMouseButton;
                this.buttons = 2;
                var dx$1 = this.prevPosition.x - this.position.x;
                var dy$1 = this.prevPosition.y - this.position.y;
                this.signals.moved.dispatch(dx$1, dy$1);
                if (this.pressed) {
                    this.signals.dragged.dispatch(dx$1, dy$1);
                }
            }
        }
    }
};
MouseObserver.prototype._distance = function _distance () {
    return this.position.distanceTo(this.down);
};
MouseObserver.prototype._setCanvasPosition = function _setCanvasPosition (event) {
    var box = this.domElement.getBoundingClientRect();
    var offsetX, offsetY;
    if ('offsetX' in event && 'offsetY' in event) {
        offsetX = event.offsetX;
        offsetY = event.offsetY;
    }
    else {
        offsetX = event.clientX - box.left;
        offsetY = event.clientY - box.top;
    }
    this.canvasPosition.set(offsetX, box.height - offsetY);
};
MouseObserver.prototype._setKeys = function _setKeys (event) {
    this.altKey = event.altKey;
    this.ctrlKey = event.ctrlKey;
    this.metaKey = event.metaKey;
    this.shiftKey = event.shiftKey;
};
MouseObserver.prototype.dispose = function 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);
};

Object.defineProperties( MouseObserver.prototype, prototypeAccessors$3 );

/**
 * @file Trackball Controls
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var tmpRotateXMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var tmpRotateYMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var tmpRotateZMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var tmpRotateMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var tmpRotateCameraMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var tmpRotateVector = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var tmpRotateQuaternion = new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]();
var tmpRotateQuaternion2 = new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]();
var tmpPanMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var tmpPanVector = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var tmpAtomVector = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
/**
 * Trackball controls
 */
var TrackballControls = function TrackballControls(stage, params) {
    if ( params === void 0 ) params = {};

    this.stage = stage;
    this.rotateSpeed = defaults(params.rotateSpeed, 2.0);
    this.zoomSpeed = defaults(params.zoomSpeed, 1.2);
    this.panSpeed = defaults(params.panSpeed, 1.0);
    this.viewer = stage.viewer;
    this.mouse = stage.mouseObserver;
    this.controls = stage.viewerControls;
};

var prototypeAccessors$4 = { component: { configurable: true },atom: { configurable: true } };
prototypeAccessors$4.component.get = function () {
    return this.stage.transformComponent;
};
prototypeAccessors$4.atom.get = function () {
    return this.stage.transformAtom;
};
TrackballControls.prototype._setPanVector = function _setPanVector (x, y, z) {
        if ( z === void 0 ) z = 0;

    var scaleFactor = this.controls.getCanvasScaleFactor(z);
    tmpPanVector.set(x, y, 0);
    tmpPanVector.multiplyScalar(this.panSpeed * scaleFactor);
};
TrackballControls.prototype._getRotateXY = function _getRotateXY (x, y) {
    return [
        this.rotateSpeed * -x * 0.01,
        this.rotateSpeed * y * 0.01
    ];
};
TrackballControls.prototype._getCameraRotation = function _getCameraRotation (m) {
    m.extractRotation(this.viewer.camera.matrixWorld);
    m.multiply(tmpRotateYMatrix.makeRotationY(Math.PI));
    return m;
};
TrackballControls.prototype._transformPanVector = function _transformPanVector () {
    if (!this.component)
        { return; }
    // Adjust for component and scene rotation
    tmpPanMatrix.extractRotation(this.component.transform);
    tmpPanMatrix.premultiply(this.viewer.rotationGroup.matrix);
    tmpPanMatrix.getInverse(tmpPanMatrix);
    // Adjust for camera rotation
    tmpPanMatrix.multiply(this._getCameraRotation(tmpRotateMatrix));
    tmpPanVector.applyMatrix4(tmpPanMatrix);
};
TrackballControls.prototype.zoom = function zoom (delta) {
    this.controls.zoom(this.zoomSpeed * delta * 0.02);
};
TrackballControls.prototype.pan = function pan (x, y) {
    this._setPanVector(x, y);
    // Adjust for scene rotation
    tmpPanMatrix.getInverse(this.viewer.rotationGroup.matrix);
    // Adjust for camera rotation
    tmpPanMatrix.multiply(this._getCameraRotation(tmpRotateMatrix));
    tmpPanVector.applyMatrix4(tmpPanMatrix);
    this.controls.translate(tmpPanVector);
};
TrackballControls.prototype.panComponent = function panComponent (x, y) {
    if (!this.component)
        { return; }
    this._setPanVector(x, y);
    this._transformPanVector();
    this.component.position.add(tmpPanVector);
    this.component.updateMatrix();
};
TrackballControls.prototype.panAtom = function panAtom (x, y) {
    if (!this.atom || !this.component)
        { return; }
    this.atom.positionToVector3(tmpAtomVector);
    tmpAtomVector.add(this.viewer.translationGroup.position);
    tmpAtomVector.applyMatrix4(this.viewer.rotationGroup.matrix);
    this._setPanVector(x, y, tmpAtomVector.z);
    this._transformPanVector();
    this.atom.positionAdd(tmpPanVector);
    this.component.updateRepresentations({ 'position': true });
};
TrackballControls.prototype.rotate = function rotate (x, y) {
    var ref = this._getRotateXY(x, y);
        var dx = ref[0];
        var dy = ref[1];
    // rotate around screen X then screen Y
    this._getCameraRotation(tmpRotateMatrix);
    tmpRotateVector.set(1, 0, 0); // X axis
    tmpRotateVector.applyMatrix4(tmpRotateMatrix); // screen X
    tmpRotateQuaternion.setFromAxisAngle(tmpRotateVector, dy);
    tmpRotateVector.set(0, 1, 0); // Y axis
    tmpRotateVector.applyMatrix4(tmpRotateMatrix); // screen Y
    tmpRotateQuaternion2.setFromAxisAngle(tmpRotateVector, dx);
    tmpRotateQuaternion.multiply(tmpRotateQuaternion2);
    tmpRotateMatrix.makeRotationFromQuaternion(tmpRotateQuaternion);
    this.controls.applyMatrix(tmpRotateMatrix);
};
TrackballControls.prototype.zRotate = function zRotate (x, y) {
    var dz = this.rotateSpeed * ((-x + y) / -2) * 0.01;
    tmpRotateZMatrix.makeRotationZ(dz);
    this.controls.applyMatrix(tmpRotateZMatrix);
};
TrackballControls.prototype.rotateComponent = function rotateComponent (x, y) {
    if (!this.component)
        { return; }
    var ref = this._getRotateXY(x, y);
        var dx = ref[0];
        var dy = ref[1];
    this._getCameraRotation(tmpRotateCameraMatrix);
    tmpRotateMatrix.extractRotation(this.component.transform);
    tmpRotateMatrix.premultiply(this.viewer.rotationGroup.matrix);
    tmpRotateMatrix.getInverse(tmpRotateMatrix);
    tmpRotateMatrix.premultiply(tmpRotateCameraMatrix);
    tmpRotateVector.set(1, 0, 0);
    tmpRotateVector.applyMatrix4(tmpRotateMatrix);
    tmpRotateXMatrix.makeRotationAxis(tmpRotateVector, dy);
    tmpRotateVector.set(0, 1, 0);
    tmpRotateVector.applyMatrix4(tmpRotateMatrix);
    tmpRotateYMatrix.makeRotationAxis(tmpRotateVector, dx);
    tmpRotateXMatrix.multiply(tmpRotateYMatrix);
    tmpRotateQuaternion.setFromRotationMatrix(tmpRotateXMatrix);
    this.component.quaternion.premultiply(tmpRotateQuaternion);
    this.component.quaternion.normalize();
    this.component.updateMatrix();
};

Object.defineProperties( TrackballControls.prototype, prototypeAccessors$4 );

/**
 * @file Picking Proxy
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var tmpVec = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
function closer(x, a, b) {
    return x.distanceTo(a) < x.distanceTo(b);
}
/**
 * Picking proxy class.
 */
var PickingProxy = function PickingProxy(pickingData, stage) {
    this.stage = stage;
    this.pid = pickingData.pid;
    this.picker = pickingData.picker;
    /**
     * @type {Object}
     */
    this.instance = pickingData.instance;
    /**
     * @type {Stage}
     */
    this.stage = stage;
    /**
     * @type {ViewerControls}
     */
    this.controls = stage.viewerControls;
    /**
     * @type {MouseObserver}
     */
    this.mouse = stage.mouseObserver;
};

var prototypeAccessors$5 = { type: { configurable: true },altKey: { configurable: true },ctrlKey: { configurable: true },metaKey: { configurable: true },shiftKey: { configurable: true },canvasPosition: { configurable: true },component: { configurable: true },object: { configurable: true },position: { configurable: true },closestBondAtom: { configurable: true },closeAtom: { configurable: true },arrow: { configurable: true },atom: { configurable: true },axes: { configurable: true },bond: { configurable: true },box: { configurable: true },cone: { configurable: true },clash: { configurable: true },contact: { configurable: true },cylinder: { configurable: true },distance: { configurable: true },ellipsoid: { configurable: true },octahedron: { configurable: true },point: { configurable: true },mesh: { configurable: true },slice: { configurable: true },sphere: { configurable: true },tetrahedron: { configurable: true },torus: { configurable: true },surface: { configurable: true },unitcell: { configurable: true },unknown: { configurable: true },volume: { configurable: true },wideline: { configurable: true } };
/**
 * Kind of the picked data
 * @type {String}
 */
prototypeAccessors$5.type.get = function () { return this.picker.type; };
/**
 * If the `alt` key was pressed
 * @type {Boolean}
 */
prototypeAccessors$5.altKey.get = function () { return this.mouse.altKey; };
/**
 * If the `ctrl` key was pressed
 * @type {Boolean}
 */
prototypeAccessors$5.ctrlKey.get = function () { return this.mouse.ctrlKey; };
/**
 * If the `meta` key was pressed
 * @type {Boolean}
 */
prototypeAccessors$5.metaKey.get = function () { return this.mouse.metaKey; };
/**
 * If the `shift` key was pressed
 * @type {Boolean}
 */
prototypeAccessors$5.shiftKey.get = function () { return this.mouse.shiftKey; };
/**
 * Position of the mouse on the canvas
 * @type {Vector2}
 */
prototypeAccessors$5.canvasPosition.get = function () { return this.mouse.canvasPosition; };
/**
 * The component the picked data is part of
 * @type {Component}
 */
prototypeAccessors$5.component.get = function () {
    return this.stage.getComponentsByObject(this.picker.data).list[0]; // TODO
};
/**
 * The picked object data
 * @type {Object}
 */
prototypeAccessors$5.object.get = function () {
    return this.picker.getObject(this.pid);
};
/**
 * The 3d position in the scene of the picked object
 * @type {Vector3}
 */
prototypeAccessors$5.position.get = function () {
    return this.picker.getPosition(this.pid, this.instance, this.component);
};
/**
 * The atom of a picked bond that is closest to the mouse
 * @type {AtomProxy}
 */
prototypeAccessors$5.closestBondAtom.get = function () {
    if (this.type !== 'bond' || !this.bond)
        { return undefined; }
    var bond = this.bond;
    var controls = this.controls;
    var cp = this.canvasPosition;
    var v1 = bond.atom1.positionToVector3();
    var v2 = bond.atom2.positionToVector3();
    v1.applyMatrix4(this.component.matrix);
    v2.applyMatrix4(this.component.matrix);
    var acp1 = controls.getPositionOnCanvas(v1);
    var acp2 = controls.getPositionOnCanvas(v2);
    return closer(cp, acp1, acp2) ? bond.atom1 : bond.atom2;
};
/**
 * Close-by atom
 * @type {AtomProxy}
 */
prototypeAccessors$5.closeAtom.get = function () {
    var cp = this.canvasPosition;
    var ca = this.closestBondAtom;
    if (!ca)
        { return undefined; }
    var v = ca.positionToVector3().applyMatrix4(this.component.matrix);
    var acp = this.controls.getPositionOnCanvas(v);
    ca.positionToVector3(tmpVec);
    if (this.instance)
        { tmpVec.applyMatrix4(this.instance.matrix); }
    tmpVec.applyMatrix4(this.component.matrix);
    var viewer = this.controls.viewer;
    tmpVec.add(viewer.translationGroup.position);
    tmpVec.applyMatrix4(viewer.rotationGroup.matrix);
    var scaleFactor = this.controls.getCanvasScaleFactor(tmpVec.z);
    var sc = this.component;
    var radius = sc.getMaxRepresentationRadius(ca.index);
    //console.log(scaleFactor, cp.distanceTo(acp), radius/scaleFactor, radius)
    if (cp.distanceTo(acp) <= radius / scaleFactor) {
        return ca;
    }
    else {
        return undefined;
    }
};
/**
 * @type {Object}
 */
prototypeAccessors$5.arrow.get = function () { return this._objectIfType('arrow'); };
/**
 * @type {AtomProxy}
 */
prototypeAccessors$5.atom.get = function () { return this._objectIfType('atom'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.axes.get = function () { return this._objectIfType('axes'); };
/**
 * @type {BondProxy}
 */
prototypeAccessors$5.bond.get = function () { return this._objectIfType('bond'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.box.get = function () { return this._objectIfType('box'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.cone.get = function () { return this._objectIfType('cone'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.clash.get = function () { return this._objectIfType('clash'); };
/**
 * @type {BondProxy}
 */
prototypeAccessors$5.contact.get = function () { return this._objectIfType('contact'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.cylinder.get = function () { return this._objectIfType('cylinder'); };
/**
 * @type {BondProxy}
 */
prototypeAccessors$5.distance.get = function () { return this._objectIfType('distance'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.ellipsoid.get = function () { return this._objectIfType('ellipsoid'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.octahedron.get = function () { return this._objectIfType('octahedron'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.point.get = function () { return this._objectIfType('point'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.mesh.get = function () { return this._objectIfType('mesh'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.slice.get = function () { return this._objectIfType('slice'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.sphere.get = function () { return this._objectIfType('sphere'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.tetrahedron.get = function () { return this._objectIfType('tetrahedron'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.torus.get = function () { return this._objectIfType('torus'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.surface.get = function () { return this._objectIfType('surface'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.unitcell.get = function () { return this._objectIfType('unitcell'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.unknown.get = function () { return this._objectIfType('unknown'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.volume.get = function () { return this._objectIfType('volume'); };
/**
 * @type {Object}
 */
prototypeAccessors$5.wideline.get = function () { return this._objectIfType('wideline'); };
PickingProxy.prototype._objectIfType = function _objectIfType (type) {
    return this.type === type ? this.object : undefined;
};
PickingProxy.prototype.getLabel = function getLabel () {
    var atom = this.atom || this.closeAtom;
    var msg = 'nothing';
    if (this.arrow) {
        msg = this.arrow.name;
    }
    else if (atom) {
        msg = "atom: " + (atom.qualifiedName()) + " (" + (atom.structure.name) + ")";
    }
    else if (this.axes) {
        msg = 'axes';
    }
    else if (this.bond) {
        msg = "bond: " + (this.bond.atom1.qualifiedName()) + " - " + (this.bond.atom2.qualifiedName()) + " (" + (this.bond.structure.name) + ")";
    }
    else if (this.box) {
        msg = this.box.name;
    }
    else if (this.cone) {
        msg = this.cone.name;
    }
    else if (this.clash) {
        msg = "clash: " + (this.clash.clash.sele1) + " - " + (this.clash.clash.sele2);
    }
    else if (this.contact) {
        msg = (this.contact.type) + ": " + (this.contact.atom1.qualifiedName()) + " - " + (this.contact.atom2.qualifiedName()) + " (" + (this.contact.atom1.structure.name) + ")";
    }
    else if (this.cylinder) {
        msg = this.cylinder.name;
    }
    else if (this.distance) {
        msg = "distance: " + (this.distance.atom1.qualifiedName()) + " - " + (this.distance.atom2.qualifiedName()) + " (" + (this.distance.structure.name) + ")";
    }
    else if (this.ellipsoid) {
        msg = this.ellipsoid.name;
    }
    else if (this.octahedron) {
        msg = this.octahedron.name;
    }
    else if (this.point) {
        msg = this.point.name;
    }
    else if (this.mesh) {
        msg = "mesh: " + (this.mesh.name || this.mesh.serial) + " (" + (this.mesh.shape.name) + ")";
    }
    else if (this.slice) {
        msg = "slice: " + (this.slice.value.toPrecision(3)) + " (" + (this.slice.volume.name) + ")";
    }
    else if (this.sphere) {
        msg = this.sphere.name;
    }
    else if (this.surface) {
        msg = "surface: " + (this.surface.surface.name);
    }
    else if (this.tetrahedron) {
        msg = this.tetrahedron.name;
    }
    else if (this.torus) {
        msg = this.torus.name;
    }
    else if (this.unitcell) {
        msg = "unitcell: " + (this.unitcell.unitcell.spacegroup) + " (" + (this.unitcell.structure.name) + ")";
    }
    else if (this.unknown) {
        msg = 'unknown';
    }
    else if (this.volume) {
        msg = "volume: " + (this.volume.value.toPrecision(3)) + " (" + (this.volume.volume.name) + ")";
    }
    else if (this.wideline) {
        msg = this.wideline.name;
    }
    return msg;
};

Object.defineProperties( PickingProxy.prototype, prototypeAccessors$5 );

/**
 * @file Picking Controls
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Picking controls
 */
var PickingControls = function PickingControls(stage) {
    this.stage = stage;
    this.viewer = stage.viewer;
};
/**
 * get picking data
 * @param {Number} x - canvas x coordinate
 * @param {Number} y - canvas y coordinate
 * @return {PickingProxy|undefined} picking proxy
 */
PickingControls.prototype.pick = function pick (x, y) {
    var pickingData = this.viewer.pick(x, y);
    if (pickingData.picker &&
        pickingData.picker.type !== 'ignore' &&
        pickingData.pid !== undefined) {
        var pickerArray = pickingData.picker.array;
        if (pickerArray && pickingData.pid >= pickerArray.length) {
            console.error('pid >= picker.array.length');
        }
        else {
            return new PickingProxy(pickingData, this.stage);
        }
    }
};

/**
 * @file Viewer Controls
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Orientation matrix, a 4x4 transformation matrix with rotation part
 * used for scene rotation, scale part for scene camera distance and
 * position part for scene translation
 * @typedef {Matrix4} OrientationMatrix - orientation matrix
 */
var tmpQ = new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]();
var tmpP = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var tmpS = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var tmpCanvasVector = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var tmpScaleVector = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var tmpRotateMatrix$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var tmpRotateVector$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var tmpAlignMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
/**
 * Viewer controls
 */
var ViewerControls = function ViewerControls(stage) {
    this.stage = stage;
    this.signals = {
        changed: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]()
    };
    this.viewer = stage.viewer;
};

var prototypeAccessors$6 = { position: { configurable: true },rotation: { configurable: true } };
/**
 * scene center position
 * @type {Vector3}
 */
prototypeAccessors$6.position.get = function () {
    return this.viewer.translationGroup.position;
};
/**
 * scene rotation
 * @type {Quaternion}
 */
prototypeAccessors$6.rotation.get = function () {
    return this.viewer.rotationGroup.quaternion;
};
/**
 * Trigger render and emit changed event
 * @emits {ViewerControls.signals.changed}
 * @return {undefined}
 */
ViewerControls.prototype.changed = function changed () {
    this.viewer.requestRender();
    this.signals.changed.dispatch();
};
ViewerControls.prototype.getPositionOnCanvas = function getPositionOnCanvas (position, optionalTarget) {
    var canvasPosition = ensureVector2(optionalTarget);
    var viewer = this.viewer;
    tmpCanvasVector.copy(position)
        .add(viewer.translationGroup.position)
        .applyMatrix4(viewer.rotationGroup.matrix)
        .project(viewer.camera);
    return canvasPosition.set((tmpCanvasVector.x + 1) * viewer.width / 2, (tmpCanvasVector.y + 1) * viewer.height / 2);
};
ViewerControls.prototype.getCanvasScaleFactor = function getCanvasScaleFactor (z) {
        if ( z === void 0 ) z = 0;

    var camera = this.viewer.camera;
    if (camera instanceof __WEBPACK_IMPORTED_MODULE_0_three__["E" /* OrthographicCamera */]) {
        return 1 / camera.zoom;
    }
    else {
        z = Math.abs(z);
        z += this.getCameraDistance();
        var fov = degToRad(camera.fov);
        var unitHeight = 2.0 * z * Math.tan(fov / 2);
        return unitHeight / this.viewer.height;
    }
};
/**
 * get scene orientation
 * @param {Matrix4} optionalTarget - pre-allocated target matrix
 * @return {OrientationMatrix} scene orientation
 */
ViewerControls.prototype.getOrientation = function getOrientation (optionalTarget) {
    var m = ensureMatrix4(optionalTarget);
    m.copy(this.viewer.rotationGroup.matrix);
    var z = this.getCameraDistance();
    m.scale(tmpScaleVector.set(z, z, z));
    m.setPosition(this.viewer.translationGroup.position);
    return m;
};
/**
 * set scene orientation
 * @param {OrientationMatrix|Array} orientation - scene orientation
 * @return {undefined}
 */
ViewerControls.prototype.orient = function orient (orientation) {
    ensureMatrix4(orientation).decompose(tmpP, tmpQ, tmpS);
    var v = this.viewer;
    v.rotationGroup.setRotationFromQuaternion(tmpQ);
    v.translationGroup.position.copy(tmpP);
    v.cameraDistance = tmpS.z;
    v.updateZoom();
    this.changed();
};
/**
 * translate scene
 * @param  {Vector3|Array} vector - translation vector
 * @return {undefined}
 */
ViewerControls.prototype.translate = function translate (vector) {
    this.viewer.translationGroup.position
        .add(ensureVector3(vector));
    this.changed();
};
/**
 * center scene
 * @param  {Vector3|Array} position - center position
 * @return {undefined}
 */
ViewerControls.prototype.center = function center (position) {
    this.viewer.translationGroup.position
        .copy(ensureVector3(position)).negate();
    this.changed();
};
/**
 * "zoom" scene by moving camera closer to origin
 * @param  {Number} delta - zoom change
 * @return {undefined}
 */
ViewerControls.prototype.zoom = function zoom (delta) {
    this.distance(this.getCameraDistance() * (1 - delta));
};
/**
 * get camera distance
 */
ViewerControls.prototype.getCameraDistance = function getCameraDistance () {
    return this.viewer.cameraDistance;
};
/**
 * camera distance
 * @param  {Number} z - distance
 * @return {undefined}
 */
ViewerControls.prototype.distance = function distance (distance$1) {
    // Math.abs because distance used to be "z", normally negative.
    // Math.max to prevent us from getting _too_ close.
    this.viewer.cameraDistance = Math.max(Math.abs(distance$1), 0.2);
    this.viewer.updateZoom();
    this.changed();
};
/**
 * spin scene on axis
 * @param  {Vector3|Array} axis - rotation axis
 * @param  {Number} angle - amount to spin
 * @return {undefined}
 */
ViewerControls.prototype.spin = function spin (axis, angle) {
    tmpRotateMatrix$1.getInverse(this.viewer.rotationGroup.matrix);
    tmpRotateVector$1
        .copy(ensureVector3(axis)).applyMatrix4(tmpRotateMatrix$1);
    this.viewer.rotationGroup.rotateOnAxis(tmpRotateVector$1, angle);
    this.changed();
};
/**
 * rotate scene
 * @param  {Quaternion|Array} quaternion - rotation quaternion
 * @return {undefined}
 */
ViewerControls.prototype.rotate = function rotate (quaternion) {
    this.viewer.rotationGroup
        .setRotationFromQuaternion(ensureQuaternion(quaternion));
    this.changed();
};
/**
 * align scene to basis matrix
 * @param  {Matrix4|Array} basis - basis matrix
 * @return {undefined}
 */
ViewerControls.prototype.align = function align (basis) {
    tmpAlignMatrix.getInverse(ensureMatrix4(basis));
    this.viewer.rotationGroup.setRotationFromMatrix(tmpAlignMatrix);
    this.changed();
};
/**
 * apply rotation matrix to scene
 * @param  {Matrix4|Array} matrix - rotation matrix
 * @return {undefined}
 */
ViewerControls.prototype.applyMatrix = function applyMatrix (matrix) {
    this.viewer.rotationGroup.applyMatrix4(ensureMatrix4(matrix));
    this.changed();
};

Object.defineProperties( ViewerControls.prototype, prototypeAccessors$6 );

/**
 * @file Animation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Animation. Base animation class.
 * @interface
 */
var Animation = function Animation(duration, controls) {
    var ref;

    var args = [], len = arguments.length - 2;
    while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ];
    this.pausedTime = -1;
    this.elapsedDuration = 0;
    this.pausedDuration = 0;
    this.ignoreGlobalToggle = false;
    this._paused = false;
    this._resolveList = [];
    this.duration = defaults(duration, 1000);
    this.controls = controls;
    this.startTime = window.performance.now();
    (ref = this)._init.apply(ref, args);
};

var prototypeAccessors$7 = { done: { configurable: true },paused: { configurable: true } };
/**
 * True when animation has finished
 */
prototypeAccessors$7.done.get = function () {
    return this.alpha === 1;
};
/**
 * True when animation is paused
 */
prototypeAccessors$7.paused.get = function () {
    return this._paused;
};
Animation.prototype.tick = function tick (stats) {
    if (this._paused)
        { return; }
    this.elapsedDuration = stats.currentTime - this.startTime - this.pausedDuration;
    if (this.duration === 0) {
        this.alpha = 1;
    }
    else {
        this.alpha = smoothstep(0, 1, this.elapsedDuration / this.duration);
    }
    this._tick(stats);
    if (this.done) {
        this._resolveList.forEach(function (resolve) { return resolve(); });
    }
    return this.done;
};
/**
 * Pause animation
 * @param {boolean} [hold] - put animation on a hold which
 *                       must be release before it can be resumed
 */
Animation.prototype.pause = function pause (hold) {
    if (hold)
        { this._hold = true; }
    if (this.pausedTime === -1) {
        this.pausedTime = window.performance.now();
    }
    this._paused = true;
};
/**
 * Resume animation
 * @param {Boolean} [releaseHold] - release a hold on the animation
 */
Animation.prototype.resume = function resume (releaseHold) {
    if (!releaseHold && this._hold)
        { return; }
    this.pausedDuration += window.performance.now() - this.pausedTime;
    this._paused = false;
    this._hold = false;
    this.pausedTime = -1;
};
/**
 * Toggle animation
 */
Animation.prototype.toggle = function toggle () {
    if (this._paused) {
        this.resume();
    }
    else {
        this.pause();
    }
};
/**
 * Promise-like interface
 */
Animation.prototype.then = function then (callback) {
        var this$1 = this;

    var p;
    if (this.done) {
        p = Promise.resolve();
    }
    else {
        p = new Promise(function (resolve) { return this$1._resolveList.push(resolve); });
    }
    return p.then(callback);
};

Object.defineProperties( Animation.prototype, prototypeAccessors$7 );
/**
 * Spin animation. Spin around an axis.
 */
var SpinAnimation = /*@__PURE__*/(function (Animation) {
    function SpinAnimation(duration, controls) {
        var args = [], len = arguments.length - 2;
        while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ];

        Animation.apply(this, [ defaults(duration, Infinity), controls ].concat( args ));
    }

    if ( Animation ) SpinAnimation.__proto__ = Animation;
    SpinAnimation.prototype = Object.create( Animation && Animation.prototype );
    SpinAnimation.prototype.constructor = SpinAnimation;
    SpinAnimation.prototype._init = function _init (axis, angle) {
        if (Array.isArray(axis)) {
            this.axis = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().fromArray(axis);
        }
        else {
            this.axis = defaults(axis, new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 1, 0));
        }
        this.angle = defaults(angle, 0.01);
    };
    SpinAnimation.prototype._tick = function _tick (stats) {
        if (!this.axis || !this.angle)
            { return; }
        this.controls.spin(this.axis, this.angle * stats.lastDuration / 16);
    };

    return SpinAnimation;
}(Animation));
/**
 * Rock animation. Rock around an axis.
 */
var RockAnimation = /*@__PURE__*/(function (Animation) {
    function RockAnimation(duration, controls) {
        var args = [], len = arguments.length - 2;
        while ( len-- > 0 ) args[ len ] = arguments[ len + 2 ];

        Animation.apply(this, [ defaults(duration, Infinity), controls ].concat( args ));
        this.angleSum = 0;
        this.direction = 1;
    }

    if ( Animation ) RockAnimation.__proto__ = Animation;
    RockAnimation.prototype = Object.create( Animation && Animation.prototype );
    RockAnimation.prototype.constructor = RockAnimation;
    RockAnimation.prototype._init = function _init (axis, angleStep, angleEnd) {
        if (Array.isArray(axis)) {
            this.axis = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().fromArray(axis);
        }
        else {
            this.axis = defaults(axis, new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 1, 0));
        }
        this.angleStep = defaults(angleStep, 0.01);
        this.angleEnd = defaults(angleEnd, 0.2);
    };
    RockAnimation.prototype._tick = function _tick (stats) {
        if (!this.axis || !this.angleStep || !this.angleEnd)
            { return; }
        var alpha = smoothstep(0, 1, Math.abs(this.angleSum) / this.angleEnd);
        var angle = this.angleStep * this.direction * (1.1 - alpha);
        this.controls.spin(this.axis, angle * stats.lastDuration / 16);
        this.angleSum += this.angleStep;
        if (this.angleSum >= this.angleEnd) {
            this.direction *= -1;
            this.angleSum = -this.angleEnd;
        }
    };

    return RockAnimation;
}(Animation));
/**
 * Move animation. Move from one position to another.
 */
var MoveAnimation = /*@__PURE__*/(function (Animation) {
    function MoveAnimation () {
        Animation.apply(this, arguments);
    }

    if ( Animation ) MoveAnimation.__proto__ = Animation;
    MoveAnimation.prototype = Object.create( Animation && Animation.prototype );
    MoveAnimation.prototype.constructor = MoveAnimation;

    MoveAnimation.prototype._init = function _init (moveFrom, moveTo) {
        this.moveFrom = ensureVector3(defaults(moveFrom, new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]()));
        this.moveTo = ensureVector3(defaults(moveTo, new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]()));
    };
    MoveAnimation.prototype._tick = function _tick ( /* stats */) {
        this.controls.position.lerpVectors(this.moveFrom, this.moveTo, this.alpha).negate();
        this.controls.changed();
    };

    return MoveAnimation;
}(Animation));
/**
 * Zoom animation. Gradually change the zoom level.
 */
var ZoomAnimation = /*@__PURE__*/(function (Animation) {
    function ZoomAnimation () {
        Animation.apply(this, arguments);
    }

    if ( Animation ) ZoomAnimation.__proto__ = Animation;
    ZoomAnimation.prototype = Object.create( Animation && Animation.prototype );
    ZoomAnimation.prototype.constructor = ZoomAnimation;

    ZoomAnimation.prototype._init = function _init (zoomFrom, zoomTo) {
        this.zoomFrom = zoomFrom;
        this.zoomTo = zoomTo;
    };
    ZoomAnimation.prototype._tick = function _tick () {
        this.controls.distance(lerp(this.zoomFrom, this.zoomTo, this.alpha));
    };

    return ZoomAnimation;
}(Animation));
/**
 * Rotate animation. Rotate from one orientation to another.
 */
var RotateAnimation = /*@__PURE__*/(function (Animation) {
    function RotateAnimation() {
        Animation.apply(this, arguments);
        this._currentRotation = new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]();
    }

    if ( Animation ) RotateAnimation.__proto__ = Animation;
    RotateAnimation.prototype = Object.create( Animation && Animation.prototype );
    RotateAnimation.prototype.constructor = RotateAnimation;
    RotateAnimation.prototype._init = function _init (rotateFrom, rotateTo) {
        this.rotateFrom = ensureQuaternion(rotateFrom);
        this.rotateTo = ensureQuaternion(rotateTo);
        this._currentRotation = new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]();
    };
    RotateAnimation.prototype._tick = function _tick () {
        this._currentRotation
            .copy(this.rotateFrom)
            .slerp(this.rotateTo, this.alpha);
        this.controls.rotate(this._currentRotation);
    };

    return RotateAnimation;
}(Animation));
/**
 * Value animation. Call callback with interpolated value.
 */
var ValueAnimation = /*@__PURE__*/(function (Animation) {
    function ValueAnimation () {
        Animation.apply(this, arguments);
    }

    if ( Animation ) ValueAnimation.__proto__ = Animation;
    ValueAnimation.prototype = Object.create( Animation && Animation.prototype );
    ValueAnimation.prototype.constructor = ValueAnimation;

    ValueAnimation.prototype._init = function _init (valueFrom, valueTo, callback) {
        this.valueFrom = valueFrom;
        this.valueTo = valueTo;
        this.callback = callback;
    };
    ValueAnimation.prototype._tick = function _tick ( /* stats */) {
        this.callback(lerp(this.valueFrom, this.valueTo, this.alpha));
    };

    return ValueAnimation;
}(Animation));
/**
 * Timeout animation. Call callback after duration.
 */
var TimeoutAnimation = /*@__PURE__*/(function (Animation) {
    function TimeoutAnimation () {
        Animation.apply(this, arguments);
    }

    if ( Animation ) TimeoutAnimation.__proto__ = Animation;
    TimeoutAnimation.prototype = Object.create( Animation && Animation.prototype );
    TimeoutAnimation.prototype.constructor = TimeoutAnimation;

    TimeoutAnimation.prototype._init = function _init (callback) {
        this.callback = callback;
    };
    TimeoutAnimation.prototype._tick = function _tick () {
        if (this.alpha === 1)
            { this.callback(); }
    };

    return TimeoutAnimation;
}(Animation));
/**
 * Animation list.
 */
var AnimationList = function AnimationList(list) {
    if ( list === void 0 ) list = [];

    this._resolveList = [];
    this._list = list;
};

var prototypeAccessors$1$1 = { done: { configurable: true } };
/**
 * True when all animations have finished
 */
prototypeAccessors$1$1.done.get = function () {
    return this._list.every(function (animation) {
        return animation.done;
    });
};
/**
 * Promise-like interface
 */
AnimationList.prototype.then = function then (callback) {
        var this$1 = this;

    var p;
    if (this.done) {
        p = Promise.resolve();
    }
    else {
        p = new Promise(function (resolve) {
            this$1._resolveList.push(resolve);
            this$1._list.forEach(function (animation) {
                animation.then(function () {
                    this$1._resolveList.forEach(function (callback) {
                        callback();
                    });
                    this$1._resolveList.length = 0;
                });
            });
        });
    }
    return p.then(callback);
};

Object.defineProperties( AnimationList.prototype, prototypeAccessors$1$1 );

/**
 * @file Animation Controls
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Animation controls
 */
var AnimationControls = function AnimationControls(stage) {
    this.stage = stage;
    this.animationList = [];
    this.finishedList = [];
    this.viewer = stage.viewer;
    this.controls = stage.viewerControls;
};

var prototypeAccessors$8 = { paused: { configurable: true } };
/**
 * True when all animations are paused
 * @type {Boolean}
 */
prototypeAccessors$8.paused.get = function () {
    return this.animationList.every(function (animation) { return animation.paused; });
};
/**
 * Add an animation
 */
AnimationControls.prototype.add = function add (animation) {
    if (animation.duration === 0) {
        animation.tick(this.viewer.stats);
    }
    else {
        this.animationList.push(animation);
    }
    return animation;
};
/**
 * Remove an animation
 */
AnimationControls.prototype.remove = function remove (animation) {
    var list = this.animationList;
    var index = list.indexOf(animation);
    if (index > -1) {
        list.splice(index, 1);
    }
};
/**
 * Run all animations
 */
AnimationControls.prototype.run = function run (stats) {
    var finishedList = this.finishedList;
    var animationList = this.animationList;
    var n = animationList.length;
    for (var i = 0; i < n; ++i) {
        var animation = animationList[i];
        // tick returns true when finished
        if (animation.tick(stats)) {
            finishedList.push(animation);
        }
    }
    var m = finishedList.length;
    if (m) {
        for (var j = 0; j < m; ++j) {
            this.remove(finishedList[j]);
        }
        finishedList.length = 0;
    }
};
/**
 * Add a spin animation
 * @param  {Vector3} axis - axis to spin around
 * @param  {Number} angle - amount to spin per frame, radians
 * @param  {Number} duration - animation time in milliseconds
 * @return {SpinAnimation} the animation
 */
AnimationControls.prototype.spin = function spin (axis, angle, duration) {
    return this.add(new SpinAnimation(duration, this.controls, axis, angle));
};
/**
 * Add a rock animation
 * @param  {Vector3} axis - axis to rock around
 * @param  {Number} angle - amount to spin per frame, radians
 * @param  {Number} end - maximum extend of motion, radians
 * @param  {Number} duration - animation time in milliseconds
 * @return {SpinAnimation} the animation
 */
AnimationControls.prototype.rock = function rock (axis, angle, end, duration) {
    return this.add(new RockAnimation(duration, this.controls, axis, angle, end));
};
/**
 * Add a rotate animation
 * @param  {Quaternion} rotateTo - target rotation
 * @param  {Number} duration - animation time in milliseconds
 * @return {RotateAnimation} the animation
 */
AnimationControls.prototype.rotate = function rotate (rotateTo, duration) {
    var rotateFrom = this.viewer.rotationGroup.quaternion.clone();
    return this.add(new RotateAnimation(duration, this.controls, rotateFrom, rotateTo));
};
/**
 * Add a move animation
 * @param  {Vector3} moveTo - target position
 * @param  {Number} duration - animation time in milliseconds
 * @return {MoveAnimation} the animation
 */
AnimationControls.prototype.move = function move (moveTo, duration) {
    var moveFrom = this.controls.position.clone().negate();
    return this.add(new MoveAnimation(duration, this.controls, moveFrom, moveTo));
};
/**
 * Add a zoom animation
 * @param  {Number} zoomTo - target distance
 * @param  {Number} duration - animation time in milliseconds
 * @return {ZoomAnimation} the animation
 */
AnimationControls.prototype.zoom = function zoom (zoomTo, duration) {
    var zoomFrom = this.viewer.camera.position.z;
    return this.add(new ZoomAnimation(duration, this.controls, zoomFrom, zoomTo));
};
/**
 * Add a zoom and a move animation
 * @param  {Vector3} moveTo - target position
 * @param  {Number} zoomTo - target distance
 * @param  {Number} duration - animation time in milliseconds
 * @return {Array} the animations
 */
AnimationControls.prototype.zoomMove = function zoomMove (moveTo, zoomTo, duration) {
    return new AnimationList([
        this.move(moveTo, duration),
        this.zoom(zoomTo, duration)
    ]);
};
/**
 * Add an orient animation
 * @param  {OrientationMatrix|Array} orientTo - target orientation
 * @param  {Number} duration - animation time in milliseconds
 * @return {Array} the animations
 */
AnimationControls.prototype.orient = function orient (orientTo, duration) {
    var p = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var q = new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]();
    var s = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    ensureMatrix4(orientTo).decompose(p, q, s);
    return new AnimationList([
        this.move(p.negate(), duration),
        this.rotate(q, duration),
        this.zoom(-s.x, duration)
    ]);
};
/**
 * Add a value animation
 * @param  {Number} valueFrom - start value
 * @param  {Number} valueTo - target value
 * @param  {Function} callback - called on every tick
 * @param  {Number} duration - animation time in milliseconds
 * @return {ValueAnimation} the animation
 */
AnimationControls.prototype.value = function value (valueFrom, valueTo, callback, duration) {
    return this.add(new ValueAnimation(duration, this.controls, valueFrom, valueTo, callback));
};
/**
 * Add a timeout animation
 * @param  {Function} callback - called after duration
 * @param  {Number} duration - timeout in milliseconds
 * @return {TimeoutAnimation} the animation
 */
AnimationControls.prototype.timeout = function timeout (callback, duration) {
    return this.add(new TimeoutAnimation(duration, this.controls, callback));
};
/**
 * Add a component spin animation
 * @param  {Component} component - object to move
 * @param  {Vector3} axis - axis to spin around
 * @param  {Number} angle - amount to spin per frame, radians
 * @param  {Number} duration - animation time in milliseconds
 * @return {SpinAnimation} the animation
 */
AnimationControls.prototype.spinComponent = function spinComponent (component, axis, angle, duration) {
    return this.add(
    // TODO
    new SpinAnimation(duration, component.controls, axis, angle));
};
/**
 * Add a component rock animation
 * @param  {Component} component - object to move
 * @param  {Vector3} axis - axis to rock around
 * @param  {Number} angle - amount to spin per frame, radians
 * @param  {Number} end - maximum extend of motion, radians
 * @param  {Number} duration - animation time in milliseconds
 * @return {SpinAnimation} the animation
 */
AnimationControls.prototype.rockComponent = function rockComponent (component, axis, angle, end, duration) {
    return this.add(
    // TODO
    new RockAnimation(duration, component.controls, axis, angle, end));
};
/**
 * Add a component move animation
 * @param  {Component} component - object to move
 * @param  {Vector3} moveTo - target position
 * @param  {Number} duration - animation time in milliseconds
 * @return {MoveAnimation} the animation
 */
AnimationControls.prototype.moveComponent = function moveComponent (component, moveTo, duration) {
    var moveFrom = component.controls.position.clone().negate();
    return this.add(
    // TODO
    new MoveAnimation(duration, component.controls, moveFrom, moveTo));
};
/**
 * Pause all animations
 * @return {undefined}
 */
AnimationControls.prototype.pause = function pause () {
    this.animationList.forEach(function (animation) { return animation.pause(); });
};
/**
 * Resume all animations
 * @return {undefined}
 */
AnimationControls.prototype.resume = function resume () {
    this.animationList.forEach(function (animation) { return animation.resume(); });
};
/**
 * Toggle all animations
 * @return {undefined}
 */
AnimationControls.prototype.toggle = function toggle () {
    if (this.paused) {
        this.resume();
    }
    else {
        this.pause();
    }
};
/**
 * Clear all animations
 * @return {undefined}
 */
AnimationControls.prototype.clear = function clear () {
    this.animationList.length = 0;
};
AnimationControls.prototype.dispose = function dispose () {
    this.clear();
};

Object.defineProperties( AnimationControls.prototype, prototypeAccessors$8 );

/**
 * @file Queue
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Queue = function Queue(fn, argList) {
    this.fn = fn;
    this.queue = [];
    this.pending = false;
    this.next = this.next.bind(this);
    if (argList) {
        for (var i = 0, il = argList.length; i < il; ++i) {
            this.queue.push(argList[i]);
        }
        this.next();
    }
};
Queue.prototype.run = function run (arg) {
    this.fn(arg, this.next);
};
Queue.prototype.next = function next () {
        var this$1 = this;

    var arg = this.queue.shift();
    if (arg !== undefined) {
        this.pending = true;
        setTimeout(function () { return this$1.run(arg); });
    }
    else {
        this.pending = false;
    }
};
Queue.prototype.push = function push (arg) {
    this.queue.push(arg);
    if (!this.pending)
        { this.next(); }
};
Queue.prototype.kill = function kill () {
    this.queue.length = 0;
};
Queue.prototype.length = function length () {
    return this.queue.length;
};

/**
 * @file Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Representation parameter object.
 * @typedef {Object} RepresentationParameters - representation parameters
 * @property {Boolean} [lazy] - only build & update the representation when visible
 *                            otherwise defer changes until set visible again
 * @property {Integer} [clipNear] - position of camera near/front clipping plane
 *                                in percent of scene bounding box
 * @property {Integer} [clipRadius] - radius of clipping sphere
 * @property {Vector3} [clipCenter] - position of for spherical clipping
 * @property {Boolean} [flatShaded] - render flat shaded
 * @property {Float} [opacity] - translucency: 1 is fully opaque, 0 is fully transparent
 * @property {Boolean} [depthWrite] - depth write
 * @property {String} [side] - which triangle sides to render, "front" front-side,
 *                            "back" back-side, "double" front- and back-side
 * @property {Boolean} [wireframe] - render as wireframe
 * @property {String} [colorScheme] - color scheme
 * @property {String} [colorScale] - color scale, either a string for a
 *                                 predefined scale or an array of
 *                                 colors to be used as the scale
 * @property {Boolean} [colorReverse] - reverse color scale
 * @property {Color} [colorValue] - color value
 * @property {Integer[]} [colorDomain] - scale value range
 * @property {Integer} colorDomain.0 - min value
 * @property {Integer} colorDomain.1 - max value
 * @property {String} [colorMode] - color mode, one of rgb, hsv, hsl, hsi, lab, hcl
 * @property {Float} [roughness] - how rough the material is, between 0 and 1
 * @property {Float} [metalness] - how metallic the material is, between 0 and 1
 * @property {Color} [diffuse] - diffuse color for lighting
 * @property {Boolean} [diffuseInterior] - diffuse interior, i.e. ignore normal
 * @property {Boolean} [useInteriorColor] - use interior color
 * @property {Color} [interiorColor] - interior color
 * @property {Float} [interiorDarkening] - interior darkening: 0 no darking, 1 fully darkened
 * @property {Boolean} [disablePicking] - disable picking
 */
/**
 * Representation object
 * @interface
 * @param {Object} object - the object to be represented
 * @param {Viewer} viewer - a viewer object
 * @param {RepresentationParameters} [params] - representation parameters
 */
var Representation = function Representation(object, viewer, params) {
    // eslint-disable-next-line no-unused-vars
    // const p = params || {}
    this.type = '';
    this.parameters = {
        lazy: {
            type: 'boolean'
        },
        clipNear: {
            type: 'range', step: 1, max: 100, min: 0, buffer: true
        },
        clipRadius: {
            type: 'number', precision: 1, max: 1000, min: 0, buffer: true
        },
        clipCenter: {
            type: 'vector3', precision: 1, buffer: true
        },
        flatShaded: {
            type: 'boolean', buffer: true
        },
        opacity: {
            type: 'range', step: 0.01, max: 1, min: 0, buffer: true
        },
        depthWrite: {
            type: 'boolean', buffer: true
        },
        side: {
            type: 'select',
            buffer: true,
            options: { front: 'front', back: 'back', double: 'double' }
        },
        wireframe: {
            type: 'boolean', buffer: true
        },
        colorScheme: {
            type: 'select',
            update: 'color',
            options: {}
        },
        colorScale: {
            type: 'select',
            update: 'color',
            options: ColormakerRegistry$1.getScales()
        },
        colorReverse: {
            type: 'boolean', update: 'color'
        },
        colorValue: {
            type: 'color', update: 'color'
        },
        colorDomain: {
            type: 'hidden', update: 'color'
        },
        colorMode: {
            type: 'select',
            update: 'color',
            options: ColormakerRegistry$1.getModes()
        },
        roughness: {
            type: 'range', step: 0.01, max: 1, min: 0, buffer: true
        },
        metalness: {
            type: 'range', step: 0.01, max: 1, min: 0, buffer: true
        },
        diffuse: {
            type: 'color', buffer: true
        },
        diffuseInterior: {
            type: 'boolean', buffer: true
        },
        useInteriorColor: {
            type: 'boolean', buffer: true
        },
        interiorColor: {
            type: 'color', buffer: true
        },
        interiorDarkening: {
            type: 'range', step: 0.01, max: 1, min: 0, buffer: true
        },
        matrix: {
            type: 'hidden', buffer: true
        },
        disablePicking: {
            type: 'boolean', rebuild: true
        }
    };
    /**
     * @type {Viewer}
     */
    this.viewer = viewer;
    /**
     * Counter that keeps track of tasks related to the creation of
     * the representation, including surface calculations.
     * @type {Counter}
     */
    this.tasks = new Counter();
    /**
     * @type {Queue}
     * @private
     */
    this.queue = new Queue(this.make.bind(this));
    /**
     * @type {Array}
     * @private
     */
    this.bufferList = [];
    if (this.parameters.colorScheme) {
        this.parameters.colorScheme.options = ColormakerRegistry$1.getSchemes();
    }
    this.toBePrepared = false;
};
Representation.prototype.init = function init (params) {
    var p = params || {};
    this.clipNear = defaults(p.clipNear, 0);
    this.clipRadius = defaults(p.clipRadius, 0);
    this.clipCenter = defaults(p.clipCenter, new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]());
    this.flatShaded = defaults(p.flatShaded, false);
    this.side = defaults(p.side, 'double');
    this.opacity = defaults(p.opacity, 1.0);
    this.depthWrite = defaults(p.depthWrite, true);
    this.wireframe = defaults(p.wireframe, false);
    this.setColor(p.color, p);
    this.colorScheme = defaults(p.colorScheme, 'uniform');
    this.colorScale = defaults(p.colorScale, '');
    this.colorReverse = defaults(p.colorReverse, false);
    this.colorValue = defaults(p.colorValue, 0x909090);
    this.colorDomain = defaults(p.colorDomain, undefined);
    this.colorMode = defaults(p.colorMode, 'hcl');
    this.visible = defaults(p.visible, true);
    this.quality = defaults(p.quality, undefined);
    this.roughness = defaults(p.roughness, 0.4);
    this.metalness = defaults(p.metalness, 0.0);
    this.diffuse = defaults(p.diffuse, 0xffffff);
    this.diffuseInterior = defaults(p.diffuseInterior, false);
    this.useInteriorColor = defaults(p.useInteriorColor, false);
    this.interiorColor = defaults(p.interiorColor, 0x222222);
    this.interiorDarkening = defaults(p.interiorDarkening, 0);
    this.lazy = defaults(p.lazy, false);
    this.lazyProps = {
        build: false,
        bufferParams: {},
        what: {}
    };
    this.matrix = defaults(p.matrix, new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]());
    this.disablePicking = defaults(p.disablePicking, false);
    // handle common parameters when applicable
    var tp = this.parameters;
    if (tp.sphereDetail === true) {
        tp.sphereDetail = {
            type: 'integer', max: 3, min: 0, rebuild: 'impostor'
        };
    }
    if (tp.radialSegments === true) {
        tp.radialSegments = {
            type: 'integer', max: 25, min: 5, rebuild: 'impostor'
        };
    }
    if (tp.openEnded === true) {
        tp.openEnded = {
            type: 'boolean', rebuild: 'impostor', buffer: true
        };
    }
    if (tp.disableImpostor === true) {
        tp.disableImpostor = {
            type: 'boolean', rebuild: true
        };
    }
    if (p.quality === 'low') {
        if (tp.sphereDetail)
            { this.sphereDetail = 0; }
        if (tp.radialSegments)
            { this.radialSegments = 5; }
    }
    else if (p.quality === 'medium') {
        if (tp.sphereDetail)
            { this.sphereDetail = 1; }
        if (tp.radialSegments)
            { this.radialSegments = 10; }
    }
    else if (p.quality === 'high') {
        if (tp.sphereDetail)
            { this.sphereDetail = 2; }
        if (tp.radialSegments)
            { this.radialSegments = 20; }
    }
    else {
        if (tp.sphereDetail) {
            this.sphereDetail = defaults(p.sphereDetail, 1);
        }
        if (tp.radialSegments) {
            this.radialSegments = defaults(p.radialSegments, 10);
        }
    }
    if (tp.openEnded) {
        this.openEnded = defaults(p.openEnded, true);
    }
    if (tp.disableImpostor) {
        this.disableImpostor = defaults(p.disableImpostor, false);
    }
};
Representation.prototype.getColorParams = function getColorParams (p) {
    return Object.assign({
        scheme: this.colorScheme,
        scale: this.colorScale,
        reverse: this.colorReverse,
        value: this.colorValue,
        domain: this.colorDomain,
        mode: this.colorMode
    }, p);
};
Representation.prototype.getBufferParams = function getBufferParams (p) {
        if ( p === void 0 ) p = {};

    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
    }, p);
};
Representation.prototype.setColor = function setColor (value, p) {
    var types = Object.keys(ColormakerRegistry$1.getSchemes());
    if (typeof value === 'string' && types.includes(value.toLowerCase())) {
        if (p) {
            p.colorScheme = value;
        }
        else {
            this.setParameters({ colorScheme: value });
        }
    }
    else if (value !== undefined) {
        var val = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](value).getHex(); //TODO
        if (p) {
            p.colorScheme = 'uniform';
            p.colorValue = val;
        }
        else {
            this.setParameters({
                colorScheme: 'uniform', colorValue: val
            });
        }
    }
    return this;
};
// TODO
Representation.prototype.prepare = function prepare (cb) {
};
Representation.prototype.create = function create () {
    // this.bufferList.length = 0;
};
Representation.prototype.update = function update (what) {
    this.build();
};
Representation.prototype.build = function build (updateWhat) {
    if (this.lazy && (!this.visible || !this.opacity)) {
        this.lazyProps.build = true;
        return;
    }
    if (!this.toBePrepared) {
        this.tasks.increment();
        this.make();
        return;
    }
    // don't let tasks accumulate
    if (this.queue.length() > 0) {
        this.tasks.change(1 - this.queue.length());
        this.queue.kill();
    }
    else {
        this.tasks.increment();
    }
    this.queue.push(updateWhat || false);
};
Representation.prototype.make = function make (updateWhat, callback) {
        var this$1 = this;

    if (Debug)
        { Log.time('Representation.make ' + this.type); }
    var _make = function () {
        if (updateWhat) {
            this$1.update(updateWhat);
            this$1.viewer.requestRender();
            this$1.tasks.decrement();
            if (callback)
                { callback(); }
        }
        else {
            this$1.clear();
            this$1.create();
            if (!this$1.manualAttach && !this$1.disposed) {
                if (Debug)
                    { Log.time('Representation.attach ' + this$1.type); }
                this$1.attach(function () {
                    if (Debug)
                        { Log.timeEnd('Representation.attach ' + this$1.type); }
                    this$1.tasks.decrement();
                    if (callback)
                        { callback(); }
                });
            }
        }
        if (Debug)
            { Log.timeEnd('Representation.make ' + this$1.type); }
    };
    if (this.toBePrepared) {
        this.prepare(_make);
    }
    else {
        _make();
    }
};
Representation.prototype.attach = function attach (callback) {
    this.setVisibility(this.visible);
    callback();
};
/**
 * Set the visibility of the representation
 * @param {Boolean} value - visibility flag
 * @param {Boolean} [noRenderRequest] - whether or not to request a re-render from the viewer
 * @return {Representation} this object
 */
Representation.prototype.setVisibility = function setVisibility (value, noRenderRequest) {
    this.visible = value;
    if (this.visible && this.opacity) {
        var lazyProps = this.lazyProps;
        var bufferParams = lazyProps.bufferParams;
        var what = lazyProps.what;
        if (lazyProps.build) {
            lazyProps.build = false;
            this.build();
            return this;
        }
        else if (Object.keys(bufferParams).length || Object.keys(what).length) {
            lazyProps.bufferParams = {};
            lazyProps.what = {};
            this.updateParameters(bufferParams, what);
        }
    }
    this.bufferList.forEach(function (buffer) {
        buffer.setVisibility(value);
    });
    if (!noRenderRequest)
        { this.viewer.requestRender(); }
    return this;
};
/**
 * Set the visibility of the representation
 * @param {RepresentationParameters} params - parameters object
 * @param {Object} [what] - buffer data attributes to be updated,
 *                    note that this needs to be implemented in the
 *                    derived classes. Generally it allows more
 *                    fine-grained control over updating than
 *                    forcing a rebuild.
 * @param {Boolean} what.position - update position data
 * @param {Boolean} what.color - update color data
 * @param {Boolean} [rebuild] - whether or not to rebuild the representation
 * @return {Representation} this object
 */
Representation.prototype.setParameters = function setParameters (params, what, rebuild) {
        if ( what === void 0 ) what = {};
        if ( rebuild === void 0 ) rebuild = false;

    var p = params || {};
    var tp = this.parameters;
    var bufferParams = {};
    if (!this.opacity && p.opacity !== undefined) {
        if (this.lazyProps.build) {
            this.lazyProps.build = false;
            rebuild = true;
        }
        else {
            Object.assign(bufferParams, this.lazyProps.bufferParams);
            Object.assign(what, this.lazyProps.what);
            this.lazyProps.bufferParams = {};
            this.lazyProps.what = {};
        }
    }
    this.setColor(p.color, p);
    for (var name in p) {
        if (p[name] === undefined)
            { continue; }
        if (tp[name] === undefined)
            { continue; }
        if (tp[name].int)
            { p[name] = parseInt(p[name]); }
        if (tp[name].float)
            { p[name] = parseFloat(p[name]); }
        // no value change
        if (p[name] === this[name] && (!p[name].equals || p[name].equals(this[name])))
            { continue; }
        if (this[name] && this[name].copy && p[name].copy) {
            this[name].copy(p[name]);
        }
        else if (this[name] && this[name].set) {
            this[name].set(p[name]);
        }
        else {
            this[name] = p[name];
        }
        // buffer param
        if (tp[name].buffer) {
            if (tp[name].buffer === true) {
                bufferParams[name] = p[name];
            }
            else {
                var key = tp[name].buffer;
                bufferParams[key] = p[name];
            }
        }
        // mark for update
        if (tp[name].update) {
            what[tp[name].update] = true;
        }
        // mark for rebuild
        if (tp[name].rebuild &&
            !(tp[name].rebuild === 'impostor' &&
                ExtensionFragDepth && !this.disableImpostor)) {
            rebuild = true;
        }
    }
    //
    if (rebuild) {
        this.build();
    }
    else {
        this.updateParameters(bufferParams, what);
    }
    return this;
};
Representation.prototype.updateParameters = function updateParameters (bufferParams, what) {
        if ( bufferParams === void 0 ) bufferParams = {};

    if (this.lazy && (!this.visible || !this.opacity) && bufferParams.hasOwnProperty('opacity') === false) {
        Object.assign(this.lazyProps.bufferParams, bufferParams);
        Object.assign(this.lazyProps.what, what);
        return;
    }
    this.bufferList.forEach(function (buffer) {
        buffer.setParameters(bufferParams);
    });
    if (Object.keys(what).length) {
        this.update(what); // update buffer attribute
    }
    this.viewer.requestRender();
};
Representation.prototype.getParameters = function getParameters () {
        var this$1 = this;

    var params = {
        lazy: this.lazy,
        visible: this.visible,
        quality: this.quality
    };
    Object.keys(this.parameters).forEach(function (name) {
        if (this$1.parameters[name] !== null) {
            params[name] = this$1[name];
        }
    });
    return params;
};
Representation.prototype.clear = function clear () {
        var this$1 = this;

    this.bufferList.forEach(function (buffer) {
        this$1.viewer.remove(buffer);
        buffer.dispose();
    });
    this.bufferList.length = 0;
    this.viewer.requestRender();
};
Representation.prototype.dispose = function dispose () {
    this.disposed = true;
    this.queue.kill();
    this.tasks.dispose();
    this.clear();
};

/**
 * @file Worker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var _Worker = function _Worker(name) {
    var this$1 = this;

    this.pending = 0;
    this.postCount = 0;
    this.onmessageDict = {};
    this.onerrorDict = {};
    this.name = name;
    this.blobUrl = window.URL.createObjectURL(WorkerRegistry$1.get(name));
    this.worker = new Worker(this.blobUrl);
    WorkerRegistry$1.activeWorkerCount += 1;
    this.worker.onmessage = function (event) {
        this$1.pending -= 1;
        var postId = event.data.__postId;
        if (Debug)
            { Log.timeEnd('Worker.postMessage ' + name + ' #' + postId); }
        var onmessage = this$1.onmessageDict[postId];
        if (onmessage) {
            onmessage.call(this$1.worker, event);
        }
        delete this$1.onmessageDict[postId];
        delete this$1.onerrorDict[postId];
    };
    this.worker.onerror = function (event) {
        this$1.pending -= 1;
        if (event.data) {
            var postId = event.data.__postId;
            var onerror = this$1.onerrorDict[postId];
            if (onerror) {
                onerror.call(this$1.worker, event);
            }
            else {
                Log.error('Worker.onerror', postId, name, event);
            }
            delete this$1.onmessageDict[postId];
            delete this$1.onerrorDict[postId];
        }
        else {
            Log.error('Worker.onerror', name, event);
        }
    };
};
_Worker.prototype.post = function post (aMessage, transferList, onmessage, onerror) {
        if ( aMessage === void 0 ) aMessage = {};

    this.onmessageDict[this.postCount] = onmessage;
    this.onerrorDict[this.postCount] = onerror;
    aMessage.__name = this.name;
    aMessage.__postId = this.postCount;
    aMessage.__debug = Debug;
    if (Debug)
        { Log.time(("Worker.postMessage " + (this.name) + " #" + (this.postCount))); }
    try {
        this.worker.postMessage(aMessage, transferList);
    }
    catch (error) {
        Log.error('worker.post:', error);
        this.worker.postMessage(aMessage);
    }
    this.pending += 1;
    this.postCount += 1;
    return this;
};
_Worker.prototype.terminate = function terminate () {
    if (this.worker) {
        this.worker.terminate();
        window.URL.revokeObjectURL(this.blobUrl);
        WorkerRegistry$1.activeWorkerCount -= 1;
    }
    else {
        Log.log('no worker to terminate');
    }
};

/**
 * @file Worker Pool
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var WorkerPool = function WorkerPool(name, maxCount) {
    if ( maxCount === void 0 ) maxCount = 2;

    this.pool = [];
    this.count = 0;
    this.maxCount = Math.min(8, maxCount);
    this.name = name;
};
WorkerPool.prototype.post = function post (aMessage, transferList, onmessage, onerror) {
        if ( aMessage === void 0 ) aMessage = {};

    var worker = this.getNextWorker();
    if (worker) {
        worker.post(aMessage, transferList, onmessage, onerror);
    }
    else {
        console.error('unable to get worker from pool');
    }
    return this;
};
WorkerPool.prototype.terminate = function terminate () {
    this.pool.forEach(function (worker) {
        worker.terminate();
    });
};
WorkerPool.prototype.getNextWorker = function getNextWorker () {
    var nextWorker;
    var minPending = Infinity;
    for (var i = 0; i < this.maxCount; ++i) {
        if (i >= this.count) {
            nextWorker = new _Worker(this.name);
            this.pool.push(nextWorker);
            this.count += 1;
            break;
        }
        var worker = this.pool[i];
        if (worker.pending === 0) {
            nextWorker = worker;
            break;
        }
        else if (worker.pending < minPending) {
            minPending = worker.pending;
            nextWorker = worker;
        }
    }
    return nextWorker;
};
WorkerPool.prototype.constructor = WorkerPool;

/**
 * @file Vector Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function calculateMeanVector3(array) {
    var n = array.length;
    var m = n / 3;
    var x = 0;
    var y = 0;
    var z = 0;
    for (var i = 0; i < n; i += 3) {
        x += array[i + 0];
        y += array[i + 1];
        z += array[i + 2];
    }
    return new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](x / m, y / m, z / m);
}
function projectPointOnVector(point, vector, origin) {
    if (origin) {
        point.sub(origin).projectOnVector(vector).add(origin);
    }
    else {
        point.projectOnVector(vector);
    }
    return point;
}
function computeBoundingBox(array) {
    var minX = +Infinity;
    var minY = +Infinity;
    var minZ = +Infinity;
    var maxX = -Infinity;
    var maxY = -Infinity;
    var maxZ = -Infinity;
    for (var i = 0, l = array.length; i < l; i += 3) {
        var x = array[i];
        var y = array[i + 1];
        var 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; }
    }
    return [
        v3new([minX, minY, minZ]),
        v3new([maxX, maxY, maxZ])
    ];
}
computeBoundingBox.__deps = [v3new];
function applyMatrix4toVector3array(m, a) {
    for (var i = 0, il = a.length; i < il; i += 3) {
        var x = a[i];
        var y = a[i + 1];
        var z = a[i + 2];
        a[i] = m[0] * x + m[4] * y + m[8] * z + m[12];
        a[i + 1] = m[1] * x + m[5] * y + m[9] * z + m[13];
        a[i + 2] = m[2] * x + m[6] * y + m[10] * z + m[14];
    }
}
function applyMatrix3toVector3array(m, a) {
    for (var i = 0, il = a.length; i < il; i += 3) {
        var x = a[i];
        var y = a[i + 1];
        var z = a[i + 2];
        a[i] = m[0] * x + m[3] * y + m[6] * z;
        a[i + 1] = m[1] * x + m[4] * y + m[7] * z;
        a[i + 2] = m[2] * x + m[5] * y + m[8] * z;
    }
}
function normalizeVector3array(a) {
    for (var i = 0, il = a.length; i < il; i += 3) {
        var x = a[i];
        var y = a[i + 1];
        var z = a[i + 2];
        var len2 = x * x + y * y + z * z;
        if (len2 > 0) { // avoid divide by zero
            var s = 1 / Math.sqrt(len2);
            a[i] = x * s;
            a[i + 1] = y * s;
            a[i + 2] = z * s;
        }
        // else leave as all zeros
    }
}
function v3new(array) {
    return new Float32Array(array || 3); // TODO
}
function v3cross(out, a, b) {
    var ax = a[0];
    var ay = a[1];
    var az = a[2];
    var bx = b[0];
    var by = b[1];
    var bz = b[2];
    out[0] = ay * bz - az * by;
    out[1] = az * bx - ax * bz;
    out[2] = ax * by - ay * bx;
}
function v3dot(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
function v3sub(out, a, b) {
    out[0] = a[0] - b[0];
    out[1] = a[1] - b[1];
    out[2] = a[2] - b[2];
}
function v3add(out, a, b) {
    out[0] = a[0] + b[0];
    out[1] = a[1] + b[1];
    out[2] = a[2] + b[2];
}
function v3fromArray(out, array, offset) {
    if ( offset === void 0 ) offset = 0;

    out[0] = array[offset];
    out[1] = array[offset + 1];
    out[2] = array[offset + 2];
}
function v3toArray(input, array, offset) {
    if ( offset === void 0 ) offset = 0;

    array[offset] = input[0];
    array[offset + 1] = input[1];
    array[offset + 2] = input[2];
}
function v3length2(a) {
    return a[0] * a[0] + a[1] * a[1] + a[2] * a[2];
}
function v3length(a) {
    return Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]);
}
function v3divideScalar(out, a, s) {
    v3multiplyScalar(out, a, 1 / s);
}
v3divideScalar.__deps = [v3multiplyScalar];
function v3multiplyScalar(out, a, s) {
    out[0] = a[0] * s;
    out[1] = a[1] * s;
    out[2] = a[2] * s;
}
function v3normalize(out, a) {
    var length2 = v3length2(a);
    if (length2 == 0) {
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
    }
    else {
        v3multiplyScalar(out, a, 1 / Math.sqrt(length2));
    }
}
v3normalize.__deps = [v3multiplyScalar, v3length2];
function v3subScalar(out, a, s) {
    out[0] = a[0] - s;
    out[1] = a[1] - s;
    out[2] = a[2] - s;
}
function v3addScalar(out, a, s) {
    out[0] = a[0] + s;
    out[1] = a[1] + s;
    out[2] = a[2] + s;
}
function v3floor(out, a) {
    out[0] = Math.floor(a[0]);
    out[1] = Math.floor(a[1]);
    out[2] = Math.floor(a[2]);
}
function v3ceil(out, a) {
    out[0] = Math.ceil(a[0]);
    out[1] = Math.ceil(a[1]);
    out[2] = Math.ceil(a[2]);
}
function v3negate(out, a) {
    out[0] = -a[0];
    out[1] = -a[1];
    out[2] = -a[2];
}

/**
 * @file Dash
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getFixedCountDashData(data, segmentCount) {
    if ( segmentCount === void 0 ) segmentCount = 9;

    var s = Math.floor(segmentCount / 2);
    var n = data.position1.length / 3;
    var sn = s * n;
    var sn3 = sn * 3;
    var step = 1 / segmentCount;
    var direction = calculateDirectionArray(data.position1, data.position2);
    var position1 = new Float32Array(sn3);
    var position2 = new Float32Array(sn3);
    var v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    for (var i = 0; i < n; ++i) {
        var i3 = i * 3;
        v.set(direction[i3], direction[i3 + 1], direction[i3 + 2]);
        var x = data.position1[i3];
        var y = data.position1[i3 + 1];
        var z = data.position1[i3 + 2];
        for (var j = 0; j < s; ++j) {
            var j3 = s * i3 + j * 3;
            var f1 = step * (j * 2 + 1);
            var f2 = step * (j * 2 + 2);
            position1[j3] = x + v.x * f1;
            position1[j3 + 1] = y + v.y * f1;
            position1[j3 + 2] = z + v.z * f1;
            position2[j3] = x + v.x * f2;
            position2[j3 + 1] = y + v.y * f2;
            position2[j3 + 2] = z + v.z * f2;
        }
    }
    var position = calculateCenterArray(position1, position2);
    var color = replicateArray3Entries(data.color, s); // TODO
    var color2 = color;
    var d = { position: position, position1: position1, position2: position2, color: color, color2: color2 };
    if (data.radius) { // TODO
        d.radius = replicateArrayEntries(data.radius, s); // TODO
    }
    if (data.picking && data.picking.array) {
        data.picking.array = replicateArrayEntries(data.picking.array, s);
        d.picking = data.picking;
    }
    if (data.primitiveId) {
        d.primitiveId = replicateArrayEntries(data.primitiveId, s);
    }
    return d;
}
function getFixedLengthDashData(data, segmentLength) {
    if ( segmentLength === void 0 ) segmentLength = 0.1;

    var direction = calculateDirectionArray(data.position1, data.position2);
    var pos1 = [];
    var pos2 = [];
    var col = [];
    var rad = data.radius ? [] : undefined;
    var pick = data.picking ? [] : undefined;
    var id = data.primitiveId ? [] : undefined;
    var v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var n = data.position1.length / 3;
    var k = 0;
    for (var i = 0; i < n; ++i) {
        var i3 = i * 3;
        v.set(direction[i3], direction[i3 + 1], direction[i3 + 2]);
        var vl = v.length();
        var segmentCount = vl / segmentLength;
        var s = Math.floor(segmentCount / 2);
        var step = 1 / segmentCount;
        var x = data.position1[i3];
        var y = data.position1[i3 + 1];
        var z = data.position1[i3 + 2];
        for (var j = 0; j < s; ++j) {
            var j3 = k * 3 + j * 3;
            var f1 = step * (j * 2 + 1);
            var f2 = step * (j * 2 + 2);
            pos1[j3] = x + v.x * f1;
            pos1[j3 + 1] = y + v.y * f1;
            pos1[j3 + 2] = z + v.z * f1;
            pos2[j3] = x + v.x * f2;
            pos2[j3 + 1] = y + v.y * f2;
            pos2[j3 + 2] = z + v.z * f2;
            if (data.color) {
                col[j3] = data.color[i3];
                col[j3 + 1] = data.color[i3 + 1];
                col[j3 + 2] = data.color[i3 + 2];
            }
            if (rad)
                { rad[k + j] = data.radius[i]; }
            if (pick) {
                if (data.picking.array) {
                    pick[k + j] = data.picking.array[i];
                }
                else {
                    pick[k + j] = i;
                }
            }
            if (id)
                { id[k + j] = data.primitiveId[i]; }
        }
        k += s;
    }
    var position1 = new Float32Array(pos1);
    var position2 = new Float32Array(pos2);
    var position = calculateCenterArray(position1, position2);
    var color = new Float32Array(col);
    var color2 = color;
    var d = { position: position, position1: position1, position2: position2, color: color, color2: color2 };
    if (rad)
        { d.radius = new Float32Array(rad); }
    if (pick && data.picking) {
        data.picking.array = new Float32Array(pick);
        d.picking = data.picking;
    }
    if (id)
        { d.primitiveId = new Float32Array(id); }
    return d;
}
function getFixedLengthWrappedDashData(data, segmentLength) {
    if ( segmentLength === void 0 ) segmentLength = 0.1;

    var direction = calculateDirectionArray(data.position1, data.position2);
    var pos1 = [];
    var pos2 = [];
    var col = [];
    var rad = data.radius ? [] : undefined;
    var pick = data.picking ? [] : undefined;
    var id = data.primitiveId ? [] : undefined;
    var v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var n = data.position1.length / 3;
    var remaining = segmentLength;
    var drawing = true;
    var k = 0;
    var k3 = 0;
    var kprev = 0;
    for (var i = 0; i < n; ++i) {
        var i3 = i * 3;
        var x = data.position1[i3];
        var y = data.position1[i3 + 1];
        var z = data.position1[i3 + 2];
        v.set(direction[i3], direction[i3 + 1], direction[i3 + 2]);
        var vl = v.length();
        if (drawing) {
            pos1[k3] = x;
            pos1[k3 + 1] = y;
            pos1[k3 + 2] = z;
        }
        var dist = remaining;
        var inv = 1 / vl;
        while (dist < vl) {
            var a = drawing ? pos2 : pos1;
            a[k3] = x + v.x * dist * inv;
            a[k3 + 1] = y + v.y * dist * inv;
            a[k3 + 2] = z + v.z * dist * inv;
            if (drawing) {
                k++;
                k3 = k * 3;
            }
            drawing = !drawing;
            remaining = segmentLength;
            dist += segmentLength;
        }
        if (drawing) {
            pos2[k3] = data.position2[i3];
            pos2[k3 + 1] = data.position2[i3 + 1];
            pos2[k3 + 2] = data.position2[i3 + 2];
            k++;
            k3 = k * 3;
        }
        remaining = dist - vl;
        for (var j = kprev; j < k; j++) {
            if (data.color) {
                var j3 = j * 3;
                col[j3] = data.color[i3];
                col[j3 + 1] = data.color[i3 + 1];
                col[j3 + 2] = data.color[i3 + 2];
            }
            if (rad)
                { rad[j] = data.radius[i]; }
            if (pick) {
                if (data.picking.array) {
                    pick[j] = data.picking.array[i];
                }
                else {
                    pick[j] = i;
                }
            }
            if (id)
                { id[j] = data.primitiveId[i]; }
        }
        kprev = k;
    }
    if (!drawing && n > 0) {
        var k3$1 = k * 3;
        pos2[k3$1] = data.position2[3 * n - 3];
        pos2[k3$1 + 1] = data.position2[3 * n - 2];
        pos2[k3$1 + 1] = data.position2[3 * n - 1];
    }
    var position1 = new Float32Array(pos1);
    var position2 = new Float32Array(pos2);
    var position = calculateCenterArray(position1, position2);
    var color = new Float32Array(col);
    var color2 = color;
    var d = { position: position, position1: position1, position2: position2, color: color, color2: color2 };
    if (rad)
        { d.radius = new Float32Array(rad); }
    if (pick && data.picking) {
        data.picking.array = new Float32Array(pick);
        d.picking = data.picking;
    }
    if (id)
        { d.primitiveId = new Float32Array(id); }
    return d;
}

/**
 * @file Primitive
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function addElement(elm, array) {
    if (elm.toArray !== undefined) {
        elm = elm.toArray();
    }
    else if (elm.x !== undefined) {
        elm = [elm.x, elm.y, elm.z];
    }
    else if (elm.r !== undefined) {
        elm = [elm.r, elm.g, elm.b];
    }
    array.push.apply(array, elm);
}
var tmpVec$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
/**
 * Base class for geometry primitives
 * @interface
 */
var Primitive = function Primitive () {};

var staticAccessors = { Picker: { configurable: true },Buffer: { configurable: true } };

staticAccessors.Picker.get = function () { return PickerRegistry.get(this.type); };
staticAccessors.Buffer.get = function () { return BufferRegistry.get(this.type); };
Primitive.getShapeKey = function getShapeKey (name) {
    return this.type + name[0].toUpperCase() + name.substr(1);
};
Primitive.expandBoundingBox = function expandBoundingBox (box, data) { };
Primitive.valueToShape = function valueToShape (shape, name, value) {
    var data = shape._primitiveData[this.getShapeKey(name)];
    var type = this.fields[name];
    switch (type) {
        case 'v3':
        case 'c':
            addElement(value, data);
            break;
        default:
            data.push(value);
    }
};
Primitive.objectToShape = function objectToShape (shape, data) {
        var this$1 = this;

    Object.keys(this.fields).forEach(function (name) {
        this$1.valueToShape(shape, name, data[name]);
    });
    this.valueToShape(shape, 'name', data.name);
    this.expandBoundingBox(shape.boundingBox, data);
};
Primitive.valueFromShape = function valueFromShape (shape, pid, name) {
    var data = shape._primitiveData[this.getShapeKey(name)];
    var type = this.fields[name];
    switch (type) {
        case 'v3':
            return new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().fromArray(data, 3 * pid);
        case 'c':
            return new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */]().fromArray(data, 3 * pid);
        default:
            return data[pid];
    }
};
Primitive.objectFromShape = function objectFromShape (shape, pid) {
        var this$1 = this;

    var name = this.valueFromShape(shape, pid, 'name');
    if (name === undefined) {
        name = (this.type) + ": " + pid + " (" + (shape.name) + ")";
    }
    var o = { shape: shape, name: name };
    Object.keys(this.fields).forEach(function (name) {
        o[name] = this$1.valueFromShape(shape, pid, name);
    });
    return o;
};
Primitive.arrayFromShape = function arrayFromShape (shape, name) {
    var data = shape._primitiveData[this.getShapeKey(name)];
    var type = this.fields[name];
    switch (type) {
        case 's':
            return data;
        default:
            return new Float32Array(data);
    }
};
Primitive.dataFromShape = function dataFromShape (shape) {
        var this$1 = this;

    var data = {};
    if (this.Picker) {
        data.picking = new this.Picker(shape);
    }
    Object.keys(this.fields).forEach(function (name) {
        data[name] = this$1.arrayFromShape(shape, name);
    });
    return data;
};
Primitive.bufferFromShape = function bufferFromShape (shape, params) {
    return new this.Buffer(this.dataFromShape(shape), params);
};

Object.defineProperties( Primitive, staticAccessors );
Primitive.type = '';
Primitive.fields = {};
/**
 * Sphere geometry primitive
 */
var SpherePrimitive = /*@__PURE__*/(function (Primitive) {
    function SpherePrimitive () {
        Primitive.apply(this, arguments);
    }

    if ( Primitive ) SpherePrimitive.__proto__ = Primitive;
    SpherePrimitive.prototype = Object.create( Primitive && Primitive.prototype );
    SpherePrimitive.prototype.constructor = SpherePrimitive;

    SpherePrimitive.positionFromShape = function positionFromShape (shape, pid) {
        return this.valueFromShape(shape, pid, 'position');
    };
    SpherePrimitive.expandBoundingBox = function expandBoundingBox (box, data) {
        box.expandByPoint(tmpVec$1.fromArray(data.position));
    };

    return SpherePrimitive;
}(Primitive));
SpherePrimitive.type = 'sphere';
SpherePrimitive.fields = {
    position: 'v3',
    color: 'c',
    radius: 'f'
};
/**
 * Box geometry primitive
 */
var BoxPrimitive = /*@__PURE__*/(function (Primitive) {
    function BoxPrimitive () {
        Primitive.apply(this, arguments);
    }

    if ( Primitive ) BoxPrimitive.__proto__ = Primitive;
    BoxPrimitive.prototype = Object.create( Primitive && Primitive.prototype );
    BoxPrimitive.prototype.constructor = BoxPrimitive;

    BoxPrimitive.positionFromShape = function positionFromShape (shape, pid) {
        return this.valueFromShape(shape, pid, 'position');
    };
    BoxPrimitive.expandBoundingBox = function expandBoundingBox (box, data) {
        box.expandByPoint(tmpVec$1.fromArray(data.position));
    };

    return BoxPrimitive;
}(Primitive));
BoxPrimitive.type = 'box';
BoxPrimitive.fields = {
    position: 'v3',
    color: 'c',
    size: 'f',
    heightAxis: 'v3',
    depthAxis: 'v3'
};
/**
 * Octahedron geometry primitive
 */
var OctahedronPrimitive = /*@__PURE__*/(function (BoxPrimitive) {
    function OctahedronPrimitive () {
        BoxPrimitive.apply(this, arguments);
    }if ( BoxPrimitive ) OctahedronPrimitive.__proto__ = BoxPrimitive;
    OctahedronPrimitive.prototype = Object.create( BoxPrimitive && BoxPrimitive.prototype );
    OctahedronPrimitive.prototype.constructor = OctahedronPrimitive;

    

    return OctahedronPrimitive;
}(BoxPrimitive));
OctahedronPrimitive.type = 'octahedron';
/**
 * Tetrahedron geometry primitive
 */
var TetrahedronPrimitive = /*@__PURE__*/(function (BoxPrimitive) {
    function TetrahedronPrimitive () {
        BoxPrimitive.apply(this, arguments);
    }if ( BoxPrimitive ) TetrahedronPrimitive.__proto__ = BoxPrimitive;
    TetrahedronPrimitive.prototype = Object.create( BoxPrimitive && BoxPrimitive.prototype );
    TetrahedronPrimitive.prototype.constructor = TetrahedronPrimitive;

    

    return TetrahedronPrimitive;
}(BoxPrimitive));
TetrahedronPrimitive.type = 'tetrahedron';
/**
 * Cylinder geometry primitive
 */
var CylinderPrimitive = /*@__PURE__*/(function (Primitive) {
    function CylinderPrimitive () {
        Primitive.apply(this, arguments);
    }

    if ( Primitive ) CylinderPrimitive.__proto__ = Primitive;
    CylinderPrimitive.prototype = Object.create( Primitive && Primitive.prototype );
    CylinderPrimitive.prototype.constructor = CylinderPrimitive;

    CylinderPrimitive.positionFromShape = function positionFromShape (shape, pid) {
        var p1 = this.valueFromShape(shape, pid, 'position1');
        var p2 = this.valueFromShape(shape, pid, 'position2');
        return p1.add(p2).multiplyScalar(0.5);
    };
    CylinderPrimitive.expandBoundingBox = function expandBoundingBox (box, data) {
        box.expandByPoint(tmpVec$1.fromArray(data.position1));
        box.expandByPoint(tmpVec$1.fromArray(data.position2));
    };
    CylinderPrimitive.bufferFromShape = function bufferFromShape (shape, params) {
        if ( params === void 0 ) params = {};

        var data = this.dataFromShape(shape);
        if (this.type === 'cylinder' && params.dashedCylinder) {
            data = getFixedLengthDashData(data);
        }
        return new this.Buffer(data, params);
    };

    return CylinderPrimitive;
}(Primitive));
CylinderPrimitive.type = 'cylinder';
CylinderPrimitive.fields = {
    position1: 'v3',
    position2: 'v3',
    color: 'c',
    radius: 'f'
};
/**
 * Arrow geometry primitive
 */
var ArrowPrimitive = /*@__PURE__*/(function (CylinderPrimitive) {
    function ArrowPrimitive () {
        CylinderPrimitive.apply(this, arguments);
    }if ( CylinderPrimitive ) ArrowPrimitive.__proto__ = CylinderPrimitive;
    ArrowPrimitive.prototype = Object.create( CylinderPrimitive && CylinderPrimitive.prototype );
    ArrowPrimitive.prototype.constructor = ArrowPrimitive;

    

    return ArrowPrimitive;
}(CylinderPrimitive));
ArrowPrimitive.type = 'arrow';
/**
 * Cone geometry primitive
 */
var ConePrimitive = /*@__PURE__*/(function (CylinderPrimitive) {
    function ConePrimitive () {
        CylinderPrimitive.apply(this, arguments);
    }if ( CylinderPrimitive ) ConePrimitive.__proto__ = CylinderPrimitive;
    ConePrimitive.prototype = Object.create( CylinderPrimitive && CylinderPrimitive.prototype );
    ConePrimitive.prototype.constructor = ConePrimitive;

    

    return ConePrimitive;
}(CylinderPrimitive));
ConePrimitive.type = 'cone';
/**
 * Ellipsoid geometry primitive
 */
var EllipsoidPrimitive = /*@__PURE__*/(function (SpherePrimitive) {
    function EllipsoidPrimitive () {
        SpherePrimitive.apply(this, arguments);
    }if ( SpherePrimitive ) EllipsoidPrimitive.__proto__ = SpherePrimitive;
    EllipsoidPrimitive.prototype = Object.create( SpherePrimitive && SpherePrimitive.prototype );
    EllipsoidPrimitive.prototype.constructor = EllipsoidPrimitive;

    

    return EllipsoidPrimitive;
}(SpherePrimitive));
EllipsoidPrimitive.type = 'ellipsoid';
EllipsoidPrimitive.fields = {
    position: 'v3',
    color: 'c',
    radius: 'f',
    majorAxis: 'v3',
    minorAxis: 'v3'
};
/**
 * Torus geometry primitive
 */
var TorusPrimitive = /*@__PURE__*/(function (EllipsoidPrimitive) {
    function TorusPrimitive () {
        EllipsoidPrimitive.apply(this, arguments);
    }if ( EllipsoidPrimitive ) TorusPrimitive.__proto__ = EllipsoidPrimitive;
    TorusPrimitive.prototype = Object.create( EllipsoidPrimitive && EllipsoidPrimitive.prototype );
    TorusPrimitive.prototype.constructor = TorusPrimitive;

    

    return TorusPrimitive;
}(EllipsoidPrimitive));
TorusPrimitive.type = 'torus';
/**
 * Text geometry primitive
 */
var TextPrimitive = /*@__PURE__*/(function (Primitive) {
    function TextPrimitive () {
        Primitive.apply(this, arguments);
    }

    if ( Primitive ) TextPrimitive.__proto__ = Primitive;
    TextPrimitive.prototype = Object.create( Primitive && Primitive.prototype );
    TextPrimitive.prototype.constructor = TextPrimitive;

    TextPrimitive.positionFromShape = function positionFromShape (shape, pid) {
        return this.valueFromShape(shape, pid, 'position');
    };
    TextPrimitive.expandBoundingBox = function expandBoundingBox (box, data) {
        box.expandByPoint(tmpVec$1.fromArray(data.position));
    };

    return TextPrimitive;
}(Primitive));
TextPrimitive.type = 'text';
TextPrimitive.fields = {
    position: 'v3',
    color: 'c',
    size: 'f',
    text: 's'
};
/**
 * Point primitive
 */
var PointPrimitive = /*@__PURE__*/(function (Primitive) {
    function PointPrimitive () {
        Primitive.apply(this, arguments);
    }

    if ( Primitive ) PointPrimitive.__proto__ = Primitive;
    PointPrimitive.prototype = Object.create( Primitive && Primitive.prototype );
    PointPrimitive.prototype.constructor = PointPrimitive;

    PointPrimitive.positionFromShape = function positionFromShape (shape, pid) {
        return this.valueFromShape(shape, pid, 'position');
    };
    PointPrimitive.expandBoundingBox = function expandBoundingBox (box, data) {
        box.expandByPoint(tmpVec$1.fromArray(data.position));
    };

    return PointPrimitive;
}(Primitive));
PointPrimitive.type = 'point';
PointPrimitive.fields = {
    position: 'v3',
    color: 'c',
};
/**
 * Wideline geometry primitive
 */
var WidelinePrimitive = /*@__PURE__*/(function (Primitive) {
    function WidelinePrimitive () {
        Primitive.apply(this, arguments);
    }

    if ( Primitive ) WidelinePrimitive.__proto__ = Primitive;
    WidelinePrimitive.prototype = Object.create( Primitive && Primitive.prototype );
    WidelinePrimitive.prototype.constructor = WidelinePrimitive;

    WidelinePrimitive.positionFromShape = function positionFromShape (shape, pid) {
        var p1 = this.valueFromShape(shape, pid, 'position1');
        var p2 = this.valueFromShape(shape, pid, 'position2');
        return p1.add(p2).multiplyScalar(0.5);
    };
    WidelinePrimitive.expandBoundingBox = function expandBoundingBox (box, data) {
        box.expandByPoint(tmpVec$1.fromArray(data.position1));
        box.expandByPoint(tmpVec$1.fromArray(data.position2));
    };

    return WidelinePrimitive;
}(Primitive));
WidelinePrimitive.type = 'wideline';
WidelinePrimitive.fields = {
    position1: 'v3',
    position2: 'v3',
    color: 'c'
};

/**
 * @file Spatial Hash
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function createBoundingBox(positions) {
    var x = positions.x;
    var y = positions.y;
    var z = positions.z;
    var boundingBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    var count = x.length;
    var min = boundingBox.min;
    var max = boundingBox.max;
    for (var i = 0; i < count; i++) {
        min.x = Math.min(x[i], min.x);
        min.y = Math.min(y[i], min.y);
        min.z = Math.min(z[i], min.z);
        max.x = Math.max(x[i], max.x);
        max.y = Math.max(y[i], max.y);
        max.z = Math.max(z[i], max.z);
    }
    return boundingBox;
}
var SpatialHash = function SpatialHash(positions, boundingBox) {
    this.exp = 3;
    var bb = boundingBox || createBoundingBox(positions);
    this.minX = bb.min.x;
    this.minY = bb.min.y;
    this.minZ = bb.min.z;
    this.boundX = ((bb.max.x - this.minX) >> this.exp) + 1;
    this.boundY = ((bb.max.y - this.minY) >> this.exp) + 1;
    this.boundZ = ((bb.max.z - this.minZ) >> this.exp) + 1;
    var n = this.boundX * this.boundY * this.boundZ;
    var an = (positions.count !== undefined) ? positions.count : positions.x.length;
    var xArray = positions.x;
    var yArray = positions.y;
    var zArray = positions.z;
    var count = 0;
    var grid = new Uint32Array(n);
    var bucketIndex = new Int32Array(an);
    for (var i = 0; i < an; ++i) {
        var x = (xArray[i] - this.minX) >> this.exp;
        var y = (yArray[i] - this.minY) >> this.exp;
        var z = (zArray[i] - this.minZ) >> this.exp;
        var idx = (((x * this.boundY) + y) * this.boundZ) + z;
        if ((grid[idx] += 1) === 1) {
            count += 1;
        }
        bucketIndex[i] = idx;
    }
    var bucketCount = new Uint16Array(count);
    for (var i$1 = 0, j = 0; i$1 < n; ++i$1) {
        var c = grid[i$1];
        if (c > 0) {
            grid[i$1] = j + 1;
            bucketCount[j] = c;
            j += 1;
        }
    }
    var bucketOffset = new Uint32Array(count);
    for (var i$2 = 1; i$2 < count; ++i$2) {
        bucketOffset[i$2] += bucketOffset[i$2 - 1] + bucketCount[i$2 - 1];
    }
    var bucketFill = new Uint16Array(count);
    var bucketArray = new Int32Array(an);
    for (var i$3 = 0; i$3 < an; ++i$3) {
        var bucketIdx = grid[bucketIndex[i$3]];
        if (bucketIdx > 0) {
            var k = bucketIdx - 1;
            bucketArray[bucketOffset[k] + bucketFill[k]] = i$3;
            bucketFill[k] += 1;
        }
    }
    this.grid = grid;
    this.bucketCount = bucketCount;
    this.bucketOffset = bucketOffset;
    this.bucketArray = bucketArray;
    this.xArray = xArray;
    this.yArray = yArray;
    this.zArray = zArray;
};
SpatialHash.prototype.within = function within (x, y, z, r) {
    var result = [];
    this.eachWithin(x, y, z, r, function (atomIndex) { return result.push(atomIndex); });
    return result;
};
SpatialHash.prototype.eachWithin = function eachWithin (x, y, z, r, callback) {
    var rSq = r * r;
    var loX = Math.max(0, (x - r - this.minX) >> this.exp);
    var loY = Math.max(0, (y - r - this.minY) >> this.exp);
    var loZ = Math.max(0, (z - r - this.minZ) >> this.exp);
    var hiX = Math.min(this.boundX, ((x + r - this.minX) >> this.exp) + 1);
    var hiY = Math.min(this.boundY, ((y + r - this.minY) >> this.exp) + 1);
    var hiZ = Math.min(this.boundZ, ((z + r - this.minZ) >> this.exp) + 1);
    for (var ix = loX; ix < hiX; ++ix) {
        for (var iy = loY; iy < hiY; ++iy) {
            for (var iz = loZ; iz < hiZ; ++iz) {
                var idx = (((ix * this.boundY) + iy) * this.boundZ) + iz;
                var bucketIdx = this.grid[idx];
                if (bucketIdx > 0) {
                    var k = bucketIdx - 1;
                    var offset = this.bucketOffset[k];
                    var count = this.bucketCount[k];
                    var end = offset + count;
                    for (var i = offset; i < end; ++i) {
                        var atomIndex = this.bucketArray[i];
                        var dx = this.xArray[atomIndex] - x;
                        var dy = this.yArray[atomIndex] - y;
                        var dz = this.zArray[atomIndex] - z;
                        var dSq = dx * dx + dy * dy + dz * dz;
                        if (dSq <= rSq)
                            { callback(atomIndex, dSq); }
                    }
                }
            }
        }
    }
};

/**
 * @file Store
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Store base class
 * @interface
 */
var Store = function Store(size) {
    if ( size === void 0 ) size = 0;

    this._fields = this._defaultFields;
    this._init(0);
};
/**
 * Initialize the store
 * @param  {Integer} size - size to initialize
 * @return {undefined}
 */
Store.prototype._init = function _init (size) {
    this.length = size;
    this.count = 0;
    for (var i = 0, il = this._fields.length; i < il; ++i) {
        var ref = this._fields[i];
            var name = ref[0];
            var size$1 = ref[1];
            var type = ref[2];
        this._initField(name, size$1, type);
    }
};
/**
 * Initialize a field
 * @param  {String} name - field name
 * @param  {Integer} size - element size
 * @param  {String} type - data type, one of int8, int16, int32,
 *                     uint8, uint16, uint32, float32
 * @return {undefined}
 */
Store.prototype._initField = function _initField (name, size, type) {
    this[name] = getTypedArray(type, this.length * size);
};
/**
 * Add a field
 * @param  {String} name - field name
 * @param  {Integer} size - element size
 * @param  {String} type - data type, one of int8, int16, int32,
 *                     uint8, uint16, uint32, float32
 * @return {undefined}
 */
Store.prototype.addField = function addField (name, size, type) {
    this._fields.push([name, size, type]);
    this._initField(name, size, type);
};
/**
 * Resize the store to the new size
 * @param  {Integer} size - new size
 * @return {undefined}
 */
Store.prototype.resize = function resize (size) {
    // Log.time( "Store.resize" );
    this.length = Math.round(size || 0);
    this.count = Math.min(this.count, this.length);
    for (var i = 0, il = this._fields.length; i < il; ++i) {
        var name = this._fields[i][0];
        var itemSize = this._fields[i][1];
        var arraySize = this.length * itemSize;
        var tmpArray = new this[name].constructor(arraySize);
        if (this[name].length > arraySize) {
            tmpArray.set(this[name].subarray(0, arraySize));
        }
        else {
            tmpArray.set(this[name]);
        }
        this[name] = tmpArray;
    }
    // Log.timeEnd( "Store.resize" );
};
/**
 * Resize the store to 1.5 times its current size if full
 * @return {undefined}
 */
Store.prototype.growIfFull = function growIfFull () {
    if (this.count >= this.length) {
        var size = Math.round(this.length * 1.5);
        this.resize(Math.max(256, size));
    }
};
/**
 * Copy data from one store to another
 * @param  {Store} other - store to copy from
 * @param  {Integer} thisOffset - offset to start copying to
 * @param  {Integer} otherOffset - offset to start copying from
 * @param  {Integer} length - number of entries to copy
 * @return {undefined}
 */
Store.prototype.copyFrom = function copyFrom (other, thisOffset, otherOffset, length) {
    for (var i = 0, il = this._fields.length; i < il; ++i) {
        var name = this._fields[i][0];
        var itemSize = this._fields[i][1];
        var thisField = this[name];
        var otherField = other[name];
        for (var j = 0; j < length; ++j) {
            var thisIndex = itemSize * (thisOffset + j);
            var otherIndex = itemSize * (otherOffset + j);
            for (var k = 0; k < itemSize; ++k) {
                thisField[thisIndex + k] = otherField[otherIndex + k];
            }
        }
    }
};
/**
 * Copy data within this store
 * @param  {Integer} thisOffset - offset to start copying to
 * @param  {Integer} otherOffset - offset to start copying from
 * @param  {Integer} length - number of entries to copy
 * @return {undefined}
 */
Store.prototype.copyWithin = function copyWithin (offsetTarget, offsetSource, length) {
    for (var i = 0, il = this._fields.length; i < il; ++i) {
        var name = this._fields[i][0];
        var itemSize = this._fields[i][1];
        var thisField = this[name];
        for (var j = 0; j < length; ++j) {
            var targetIndex = itemSize * (offsetTarget + j);
            var sourceIndex = itemSize * (offsetSource + j);
            for (var k = 0; k < itemSize; ++k) {
                thisField[targetIndex + k] = thisField[sourceIndex + k];
            }
        }
    }
};
/**
 * Sort entries in the store given the compare function
 * @param  {[type]} compareFunction - function to sort by
 * @return {undefined}
 */
Store.prototype.sort = function sort (compareFunction) {
    Log.time('Store.sort');
    var thisStore = this;
    var tmpStore = new this.constructor(1);
    function swap(index1, index2) {
        if (index1 === index2)
            { return; }
        tmpStore.copyFrom(thisStore, 0, index1, 1);
        thisStore.copyWithin(index1, index2, 1);
        thisStore.copyFrom(tmpStore, index2, 0, 1);
    }
    function quicksort(left, right) {
        if (left < right) {
            var pivot = Math.floor((left + right) / 2);
            var leftNew = left;
            var rightNew = right;
            do {
                while (compareFunction(leftNew, pivot) < 0) {
                    leftNew += 1;
                }
                while (compareFunction(rightNew, pivot) > 0) {
                    rightNew -= 1;
                }
                if (leftNew <= rightNew) {
                    if (leftNew === pivot) {
                        pivot = rightNew;
                    }
                    else if (rightNew === pivot) {
                        pivot = leftNew;
                    }
                    swap(leftNew, rightNew);
                    leftNew += 1;
                    rightNew -= 1;
                }
            } while (leftNew <= rightNew);
            quicksort(left, rightNew);
            quicksort(leftNew, right);
        }
    }
    quicksort(0, this.count - 1);
    Log.timeEnd('Store.sort');
};
/**
 * Empty the store
 * @return {undefined}
 */
Store.prototype.clear = function clear () {
    this.count = 0;
};
/**
 * Dispose of the store entries and fields
 * @return {undefined}
 */
Store.prototype.dispose = function dispose () {
    delete this.length;
    delete this.count;
    for (var i = 0, il = this._fields.length; i < il; ++i) {
        var name = this._fields[i][0];
        delete this[name];
    }
};

/**
 * @file Contact Store
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Bond store
 */
var ContactStore = /*@__PURE__*/(function (Store$$1) {
    function ContactStore () {
        Store$$1.apply(this, arguments);
    }

    if ( Store$$1 ) ContactStore.__proto__ = Store$$1;
    ContactStore.prototype = Object.create( Store$$1 && Store$$1.prototype );
    ContactStore.prototype.constructor = ContactStore;

    var prototypeAccessors = { _defaultFields: { configurable: true } };

    prototypeAccessors._defaultFields.get = function () {
        return [
            ['index1', 1, 'int32'],
            ['index2', 1, 'int32'],
            ['type', 1, 'int8']
        ];
    };
    ContactStore.prototype.addContact = function addContact (index1, index2, type) {
        this.growIfFull();
        var i = this.count;
        if (index1 < index2) {
            this.index1[i] = index1;
            this.index2[i] = index2;
        }
        else {
            this.index2[i] = index1;
            this.index1[i] = index2;
        }
        if (type)
            { this.type[i] = type; }
        this.count += 1;
    };

    Object.defineProperties( ContactStore.prototype, prototypeAccessors );

    return ContactStore;
}(Store));

/**
 * @file Bit array
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Paul Pillot <paulpillot@gmail.com>
 * @private
 */
/**
 * Compute the Hamming weight of a 32-bit unsigned integer
 * @param  {Integer} v - a 32-bit unsigned integer
 * @return {Integer} the Hamming weight
 */
function hammingWeight(v) {
    // works with signed or unsigned shifts
    v -= ((v >>> 1) & 0x55555555);
    v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
    return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24;
}
/**
 * Bit array
 *
 * Based heavily on https://github.com/lemire/FastBitSet.js
 * which is licensed under the Apache License, Version 2.0.
 */
var BitArray = function BitArray(length, setAll) {
    this.length = length;
    this._words = new Uint32Array((length + 32) >>> 5);
    if (setAll === true) {
        this.setAll();
    }
};
/**
 * Get value at index
 * @param  {Integer} index - the index
 * @return {Boolean} value
 */
BitArray.prototype.get = function get (index) {
    return (this._words[index >>> 5] & (1 << index)) !== 0;
};
/**
 * Set value at index to true
 * @param  {Integer} index - the index
 * @return {undefined}
 */
BitArray.prototype.set = function set (index) {
    this._words[index >>> 5] |= 1 << index;
};
/**
 * Set value at index to false
 * @param  {Integer} index - the index
 * @return {undefined}
 */
BitArray.prototype.clear = function clear (index) {
    this._words[index >>> 5] &= ~(1 << index);
};
/**
 * Flip value at index
 * @param  {Integer} index - the index
 * @return {undefined}
 */
BitArray.prototype.flip = function flip (index) {
    this._words[index >>> 5] ^= 1 << index;
};
BitArray.prototype._assignRange = function _assignRange (start, end, value) {
    if (end < start)
        { return; }
    var words = this._words;
    var wordValue = value === true ? 0xFFFFFFFF : 0;
    var wordStart = start >>> 5;
    var wordEnd = end >>> 5;
    // set complete words when applicable
    for (var k = wordStart; k < wordEnd; ++k) {
        words[k] = wordValue;
    }
    // set parts of the range not spanning complete words
    var startWord = wordStart << 5;
    var endWord = wordEnd << 5;
    if (value === true) {
        if (end - start < 32) {
            for (var i = start, n = end + 1; i < n; ++i) {
                words[i >>> 5] |= 1 << i;
            }
        }
        else {
            for (var i$1 = start, n$1 = startWord; i$1 < n$1; ++i$1) {
                words[i$1 >>> 5] |= 1 << i$1;
            }
            for (var i$2 = endWord, n$2 = end + 1; i$2 < n$2; ++i$2) {
                words[i$2 >>> 5] |= 1 << i$2;
            }
        }
    }
    else {
        if (end - start < 32) {
            for (var i$3 = start, n$3 = end + 1; i$3 < n$3; ++i$3) {
                words[i$3 >>> 5] &= ~(1 << i$3);
            }
        }
        else {
            for (var i$4 = start, n$4 = startWord; i$4 < n$4; ++i$4) {
                words[i$4 >>> 5] &= ~(1 << i$4);
            }
            for (var i$5 = endWord, n$5 = end + 1; i$5 < n$5; ++i$5) {
                words[i$5 >>> 5] &= ~(1 << i$5);
            }
        }
    }
    return this;
};
/**
 * Set bits of the given range
 * @param {Integer} start - start index
 * @param {Integer} end - end index
 * @return {BitArray} this object
 */
BitArray.prototype.setRange = function setRange (start, end) {
    return this._assignRange(start, end, true);
};
/**
 * Clear bits of the given range
 * @param {Integer} start - start index
 * @param {Integer} end - end index
 * @return {BitArray} this object
 */
BitArray.prototype.clearRange = function clearRange (start, end) {
    return this._assignRange(start, end, false);
};
/**
 * Set bits at all given indices
 * @param {...Integer} arguments - indices
 * @return {Boolean} this object
 */
BitArray.prototype.setBits = function setBits () {
        var indices = [], len = arguments.length;
        while ( len-- ) indices[ len ] = arguments[ len ];

    var words = this._words;
    var n = indices.length;
    for (var i = 0; i < n; ++i) {
        var index = indices[i];
        words[index >>> 5] |= 1 << index;
    }
    return this;
};
/**
 * Clear bits at all given indices
 * @param {...Integer} arguments - indices
 * @return {Boolean} this object
 */
BitArray.prototype.clearBits = function clearBits () {
        var indices = [], len = arguments.length;
        while ( len-- ) indices[ len ] = arguments[ len ];

    var words = this._words;
    var n = indices.length;
    for (var i = 0; i < n; ++i) {
        var index = indices[i];
        words[index >>> 5] &= ~(1 << index);
    }
    return this;
};
/**
 * Set all bits of the array
 * @return {BitArray} this object
 */
BitArray.prototype.setAll = function setAll () {
    return this._assignRange(0, this.length - 1, true);
};
/**
 * Clear all bits of the array
 * @return {BitArray} this object
 */
BitArray.prototype.clearAll = function clearAll () {
    return this._assignRange(0, this.length - 1, false);
};
/**
 * Flip all the values in the array
 * @return {BitArray} this object
 */
BitArray.prototype.flipAll = function flipAll () {
    var count = this._words.length;
    var words = this._words;
    var bs = 32 - this.length % 32;
    for (var k = 0; k < count - 1; ++k) {
        words[k] = ~words[k];
    }
    words[count - 1] = (~(words[count - 1] << bs)) >>> bs;
    return this;
};
BitArray.prototype._isRangeValue = function _isRangeValue (start, end, value) {
    if (end < start)
        { return; }
    var words = this._words;
    var wordValue = value === true ? 0xFFFFFFFF : 0;
    var wordStart = start >>> 5;
    var wordEnd = end >>> 5;
    // set complete words when applicable
    for (var k = wordStart; k < wordEnd; ++k) {
        if (words[k] !== wordValue)
            { return false; }
    }
    // set parts of the range not spanning complete words
    if (end - start < 32) {
        for (var i = start, n = end + 1; i < n; ++i) {
            if (!!(words[i >>> 5] & (1 << i)) !== value)
                { return false; }
        }
    }
    else {
        var startWord = wordStart << 5;
        var endWord = wordEnd << 5;
        for (var i$1 = start, n$1 = startWord << 5; i$1 < n$1; ++i$1) {
            if (!!(words[i$1 >>> 5] & (1 << i$1)) !== value)
                { return false; }
        }
        for (var i$2 = endWord, n$2 = end + 1; i$2 < n$2; ++i$2) {
            if (!!(words[i$2 >>> 5] & (1 << i$2)) !== value)
                { return false; }
        }
    }
    return true;
};
/**
 * Test if bits in given range are set
 * @param {Integer} start - start index
 * @param {Integer} end - end index
 * @return {BitArray} this object
 */
BitArray.prototype.isRangeSet = function isRangeSet (start, end) {
    return this._isRangeValue(start, end, true);
};
/**
 * Test if bits in given range are clear
 * @param {Integer} start - start index
 * @param {Integer} end - end index
 * @return {BitArray} this object
 */
BitArray.prototype.isRangeClear = function isRangeClear (start, end) {
    return this._isRangeValue(start, end, false);
};
/**
 * Test if all bits in the array are set
 * @return {Boolean} test result
 */
BitArray.prototype.isAllSet = function isAllSet () {
    return this._isRangeValue(0, this.length - 1, true);
};
/**
 * Test if all bits in the array are clear
 * @return {Boolean} test result
 */
BitArray.prototype.isAllClear = function isAllClear () {
    return this._isRangeValue(0, this.length - 1, false);
};
/**
 * Test if bits at all given indices are set
 * @param {...Integer} arguments - indices
 * @return {Boolean} test result
 */
BitArray.prototype.isSet = function isSet () {
        var indices = [], len = arguments.length;
        while ( len-- ) indices[ len ] = arguments[ len ];

    var words = this._words;
    var n = indices.length;
    for (var i = 0; i < n; ++i) {
        var index = indices[i];
        if ((words[index >>> 5] & (1 << index)) === 0)
            { return false; }
    }
    return true;
};
/**
 * Test if bits at all given indices are clear
 * @param {...Integer} arguments - indices
 * @return {Boolean} test result
 */
BitArray.prototype.isClear = function isClear () {
        var indices = [], len = arguments.length;
        while ( len-- ) indices[ len ] = arguments[ len ];

    var words = this._words;
    var n = indices.length;
    for (var i = 0; i < n; ++i) {
        var index = indices[i];
        if ((words[index >>> 5] & (1 << index)) !== 0)
            { return false; }
    }
    return true;
};
/**
 * Test if two BitArrays are identical in all their values
 * @param {BitArray} otherBitarray - the other BitArray
 * @return {Boolean} test result
 */
BitArray.prototype.isEqualTo = function isEqualTo (otherBitarray) {
    var words1 = this._words;
    var words2 = otherBitarray._words;
    var count = Math.min(words1.length, words2.length);
    for (var k = 0; k < count; ++k) {
        if (words1[k] !== words2[k]) {
            return false;
        }
    }
    return true;
};
/**
 * How many set bits?
 * @return {Integer} number of set bits
 */
BitArray.prototype.getSize = function getSize () {
    var count = this._words.length;
    var words = this._words;
    var size = 0;
    for (var i = 0; i < count; ++i) {
        size += hammingWeight(words[i]);
    }
    return size;
};
/**
 * Calculate difference betwen this and another bit array.
 * Store result in this object.
 * @param  {BitArray} otherBitarray - the other bit array
 * @return {BitArray} this object
 */
BitArray.prototype.difference = function difference (otherBitarray) {
    var words1 = this._words;
    var words2 = otherBitarray._words;
    var count = Math.min(words1.length, words2.length);
    for (var k = 0; k < count; ++k) {
        words1[k] = words1[k] & ~words2[k];
    }
    for (var k$1 = words1.length; k$1 < count; ++k$1) {
        words1[k$1] = 0;
    }
    return this;
};
/**
 * Calculate union betwen this and another bit array.
 * Store result in this object.
 * @param  {BitArray} otherBitarray - the other bit array
 * @return {BitArray} this object
 */
BitArray.prototype.union = function union (otherBitarray) {
    var words1 = this._words;
    var words2 = otherBitarray._words;
    var count = Math.min(words1.length, words2.length);
    for (var k = 0; k < count; ++k) {
        words1[k] |= words2[k];
    }
    for (var k$1 = words1.length; k$1 < count; ++k$1) {
        words1[k$1] = 0;
    }
    return this;
};
/**
 * Calculate intersection betwen this and another bit array.
 * Store result in this object.
 * @param  {BitArray} otherBitarray - the other bit array
 * @return {BitArray} this object
 */
BitArray.prototype.intersection = function intersection (otherBitarray) {
    var words1 = this._words;
    var words2 = otherBitarray._words;
    var count = Math.min(words1.length, words2.length);
    for (var k = 0; k < count; ++k) {
        words1[k] &= words2[k];
    }
    for (var k$1 = words1.length; k$1 < count; ++k$1) {
        words1[k$1] = 0;
    }
    return this;
};
/**
 * Test if there is any intersection betwen this and another bit array.
 * @param  {BitArray} otherBitarray - the other bit array
 * @return {Boolean} test result
 */
BitArray.prototype.intersects = function intersects (otherBitarray) {
    var words1 = this._words;
    var words2 = otherBitarray._words;
    var count = Math.min(words1.length, words2.length);
    for (var k = 0; k < count; ++k) {
        if ((words1[k] & words2[k]) !== 0) {
            return true;
        }
    }
    return false;
};
/**
 * Calculate the number of bits in common betwen this and another bit array.
 * @param  {BitArray} otherBitarray - the other bit array
 * @return {Integer} size
 */
BitArray.prototype.getIntersectionSize = function getIntersectionSize (otherBitarray) {
    var words1 = this._words;
    var words2 = otherBitarray._words;
    var count = Math.min(words1.length, words2.length);
    var size = 0;
    for (var k = 0; k < count; ++k) {
        size += hammingWeight(words1[k] & words2[k]);
    }
    return size;
};
/**
 * Calculate intersection betwen this and another bit array.
 * Store result in a new bit array.
 * @param  {BitArray} otherBitarray - the other bit array
 * @return {BitArray} the new bit array
 */
BitArray.prototype.makeIntersection = function makeIntersection (otherBitarray) {
    var words1 = this._words;
    var words2 = otherBitarray._words;
    var count = Math.min(words1.length, words2.length);
    var wordsA = new Uint32Array(count);
    var intersection = Object.create(BitArray.prototype);
    intersection._words = wordsA;
    intersection.length = Math.min(this.length, otherBitarray.length);
    for (var k = 0; k < count; ++k) {
        wordsA[k] = words1[k] & words2[k];
    }
    return intersection;
};
/**
 * Iterate over all set bits in the array
 * @param  {function( index: Integer, i: Integer )} callback - the callback
 * @return {undefined}
 */
BitArray.prototype.forEach = function forEach (callback) {
    var count = this._words.length;
    var words = this._words;
    var i = 0;
    for (var k = 0; k < count; ++k) {
        var w = words[k];
        while (w !== 0) {
            var t = w & -w;
            var index = (k << 5) + hammingWeight(t - 1);
            callback(index, i);
            w ^= t;
            ++i;
        }
    }
};
/**
 * Get an array with the set bits
 * @return {Array} bit indices
 */
BitArray.prototype.toArray = function toArray () {
    var words = this._words;
    var answer = new Array(this.getSize());
    var count = this._words.length;
    var pos = 0;
    for (var k = 0; k < count; ++k) {
        var w = words[k];
        while (w !== 0) {
            var t = w & -w;
            answer[pos++] = (k << 5) + hammingWeight(t - 1);
            w ^= t;
        }
    }
    return answer;
};
BitArray.prototype.toString = function toString () {
    return '{' + this.toArray().join(',') + '}';
};
BitArray.prototype.toSeleString = function toSeleString () {
    var sele = this.toArray().join(',');
    return sele ? '@' + sele : 'NONE';
};
/**
 * Clone this object
 * @return {BitArray} the cloned object
 */
BitArray.prototype.clone = function clone () {
    var clone = Object.create(BitArray.prototype);
    clone.length = this.length;
    clone._words = new Uint32Array(this._words);
    return clone;
};

/**
 * @file Adjacency List
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function createAdjacencyList(edges) {
    var edgeCount = edges.edgeCount;
    var nodeCount = edges.nodeCount;
    var nodeArray1 = edges.nodeArray1;
    var nodeArray2 = edges.nodeArray2;
    var countArray = new Uint8Array(nodeCount);
    var offsetArray = new Int32Array(nodeCount);
    // count edges per node
    for (var i = 0; i < edgeCount; ++i) {
        countArray[nodeArray1[i]] += 1;
        countArray[nodeArray2[i]] += 1;
    }
    // get offsets to node edges
    for (var i$1 = 1; i$1 < nodeCount; ++i$1) {
        offsetArray[i$1] += offsetArray[i$1 - 1] + countArray[i$1 - 1];
    }
    // prepare index array
    var bondCount2 = edgeCount * 2;
    var indexArray = new Int32Array(bondCount2);
    for (var j = 0; j < bondCount2; ++j) {
        indexArray[j] = -1;
    }
    // build index array
    for (var i$2 = 0; i$2 < edgeCount; ++i$2) {
        var idx1 = nodeArray1[i$2];
        var idx2 = nodeArray2[i$2];
        var j1 = offsetArray[idx1];
        while (indexArray[j1] !== -1 && j1 < bondCount2) {
            j1 += 1;
        }
        indexArray[j1] = i$2;
        var j2 = offsetArray[idx2];
        while (indexArray[j2] !== -1 && j2 < bondCount2) {
            j2 += 1;
        }
        indexArray[j2] = i$2;
    }
    return { countArray: countArray, offsetArray: offsetArray, indexArray: indexArray };
}

/**
 * @file Features
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function createFeatures() {
    return {
        types: [],
        groups: [],
        centers: { x: [], y: [], z: [] },
        atomSets: []
    };
}
function createFeatureState(type /* Unknown */, group /* Unknown */) {
    if ( type === void 0 ) type = 0;
    if ( group === void 0 ) group = 0;

    return { type: type, group: group, x: 0, y: 0, z: 0, atomSet: [] };
}
function addAtom(state, atom) {
    state.x += atom.x;
    state.y += atom.y;
    state.z += atom.z;
    state.atomSet.push(atom.index);
}
function addFeature(features, state) {
    var n = state.atomSet.length;
    if (n > 0) {
        var types = features.types;
        var groups = features.groups;
        var centers = features.centers;
        var atomSets = features.atomSets;
        types.push(state.type);
        groups.push(state.group);
        centers.x.push(state.x / n);
        centers.y.push(state.y / n);
        centers.z.push(state.z / n);
        atomSets.push(state.atomSet);
    }
}

/**
 * @file Structure Constants
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// entity types
var UnknownEntity = 0;
var PolymerEntity = 1;
var NonPolymerEntity = 2;
var MacrolideEntity = 3;
var WaterEntity = 4;
// molecule types
var UnknownType = 0;
var WaterType = 1;
var IonType = 2;
var ProteinType = 3;
var RnaType = 4;
var DnaType = 5;
var SaccharideType = 6;
// backbone types
var UnknownBackboneType = 0;
var ProteinBackboneType = 1;
var RnaBackboneType = 2;
var DnaBackboneType = 3;
var CgProteinBackboneType = 4;
var CgRnaBackboneType = 5;
var CgDnaBackboneType = 6;
// chemical component types
var ChemCompProtein = [
    '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'
];
var ChemCompRna = [
    'RNA OH 3 PRIME TERMINUS', 'RNA OH 5 PRIME TERMINUS', 'RNA LINKING'
];
var ChemCompDna = [
    'DNA OH 3 PRIME TERMINUS', 'DNA OH 5 PRIME TERMINUS', 'DNA LINKING',
    'L-DNA LINKING', 'L-RNA LINKING'
];
var ChemCompSaccharide = [
    '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'
];
var ChemCompOther = [
    'OTHER'
];
var ChemCompNonPolymer = [
    'NON-POLYMER'
];
var ChemCompHetero = ChemCompNonPolymer.concat(ChemCompOther, ChemCompSaccharide);
// secondary structure
var SecStrucHelix = ['h', 'g', 'i'];
var SecStrucSheet = ['e', 'b'];
var SecStrucTurn = ['s', 't', 'l', ''];
var AtomicNumbers = {
    '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
};
var DefaultAtomicNumber = 0;
// http://dx.doi.org/10.1021/jp8111556 (or 2.0)
var VdwRadii = {
    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.0, 28: 2.0, 29: 2.0, 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.0, 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.0, 77: 2.0, 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.0, 90: 2.4, 91: 2.0, 92: 2.3, 93: 2.0, 94: 2.0, 95: 2.0, 96: 2.0, 97: 2.0, 98: 2.0, 99: 2.0, 100: 2.0, 101: 2.0, 102: 2.0, 103: 2.0, 104: 2.0, 105: 2.0, 106: 2.0, 107: 2.0, 108: 2.0, 109: 2.0, 110: 2.0, 111: 2.0, 112: 2.0, 113: 2.0, 114: 2.0, 115: 2.0, 116: 2.0, 117: 2.0, 118: 2.0
};
var DefaultVdwRadius = 2.0; // C
// http://dx.doi.org/10.1039/b801115j (or 1.6)
var CovalentRadii = {
    1: 0.31, 2: 0.28, 3: 1.28, 4: 0.96, 5: 0.84, 6: 0.76, 7: 0.71, 8: 0.66, 9: 0.57, 10: 0.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.0, 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
};
var DefaultCovalentRadius = 1.6;
var Valences = {
    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]
};
var DefaultValence = -1;
var OuterShellElectronCounts = {
    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
};
var DefaultOuterShellElectronCount = 2;
// http://blanco.biomol.uci.edu/Whole_residue_HFscales.txt
// https://www.nature.com/articles/nsb1096-842
var ResidueHydrophobicity = {
    // AA  DGwif   DGwoct  Oct-IF
    'ALA': [0.17, 0.50, 0.33],
    'ARG': [0.81, 1.81, 1.00],
    'ASN': [0.42, 0.85, 0.43],
    'ASP': [1.23, 3.64, 2.41],
    'ASH': [-0.07, 0.43, 0.50],
    'CYS': [-0.24, -0.02, 0.22],
    'GLN': [0.58, 0.77, 0.19],
    'GLU': [2.02, 3.63, 1.61],
    'GLH': [-0.01, 0.11, 0.12],
    'GLY': [0.01, 1.15, 1.14],
    // "His+": [  0.96,  2.33,  1.37 ],
    'HIS': [0.17, 0.11, -0.06],
    'ILE': [-0.31, -1.12, -0.81],
    'LEU': [-0.56, -1.25, -0.69],
    'LYS': [0.99, 2.80, 1.81],
    'MET': [-0.23, -0.67, -0.44],
    'PHE': [-1.13, -1.71, -0.58],
    'PRO': [0.45, 0.14, -0.31],
    'SER': [0.13, 0.46, 0.33],
    'THR': [0.14, 0.25, 0.11],
    'TRP': [-1.85, -2.09, -0.24],
    'TYR': [-0.94, -0.71, 0.23],
    'VAL': [0.07, -0.46, -0.53]
};
var DefaultResidueHydrophobicity = [0.00, 0.00, 0.00];
var AA1 = {
    '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',
};
var AA3 = Object.keys(AA1);
var RnaBases = ['A', 'C', 'T', 'G', 'U', 'I'];
var DnaBases = ['DA', 'DC', 'DT', 'DG', 'DU', 'DI'];
var PurinBases = ['A', 'G', 'I', 'DA', 'DG', 'DI'];
var Bases = RnaBases.concat(DnaBases);
var WaterNames = [
    'SOL', 'WAT', 'HOH', 'H2O', 'W', 'DOD', 'D3O', 'TIP3', 'TIP4', 'SPC'
];
// all chemical components with the word "ion" in their name, Sep 2016
//
// SET SESSION group_concat_max_len = 1000000;
// SELECT GROUP_CONCAT(id_ ORDER BY id_ ASC SEPARATOR '", "') from
// (
//     SELECT count(obj_id) as c, id_
//     FROM pdb.chem_comp WHERE name LIKE "% ION%"
//     GROUP BY id_
// ) AS t1;
var IonNames = [
    '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',
    // additional ion names
    'OHX'
];
// all chemical components with the word "%saccharide%" in their type, Sep 2016
//
// SET SESSION group_concat_max_len = 1000000;
// select GROUP_CONCAT(id_ ORDER BY id_ ASC SEPARATOR '", "') from
// (
//     SELECT count(obj_id), id_
//     FROM pdb.chem_comp WHERE type like "%SACCHARIDE%"
//     GROUP BY id_
// ) AS t1;
var SaccharideNames = [
    '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'
];
var ProteinBackboneAtoms = [
    'CA', 'C', 'N', 'O',
    'O1', 'O2', 'OC1', 'OC2', 'OX1', 'OXT', 'OT1', 'OT2',
    'H', 'H1', 'H2', 'H3', 'HA', 'HN',
    'BB'
];
var NucleicBackboneAtoms = [
    '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*'
];
var ResidueTypeAtoms = {};
ResidueTypeAtoms[ProteinBackboneType] = {
    trace: 'CA',
    direction1: 'C',
    direction2: ['O', 'OC1', 'O1', 'OX1', 'OXT', 'OT1', 'OT2'],
    backboneStart: 'N',
    backboneEnd: 'C'
};
ResidueTypeAtoms[RnaBackboneType] = {
    trace: ["C4'", 'C4*'],
    direction1: ["C1'", 'C1*'],
    direction2: ["C3'", 'C3*'],
    backboneStart: 'P',
    backboneEnd: ["O3'", 'O3*']
};
ResidueTypeAtoms[DnaBackboneType] = {
    trace: ["C3'", 'C3*'],
    direction1: ["C2'", 'C2*'],
    direction2: ["O4'", 'O4*'],
    backboneStart: 'P',
    backboneEnd: ["O3'", 'O3*']
};
ResidueTypeAtoms[CgProteinBackboneType] = {
    trace: ['CA', 'BB'],
    backboneStart: ['CA', 'BB'],
    backboneEnd: ['CA', 'BB']
};
ResidueTypeAtoms[CgRnaBackboneType] = {
    trace: ["C4'", 'C4*', 'P'],
    backboneStart: ["C4'", 'C4*', 'P'],
    backboneEnd: ["C4'", 'C4*', 'P']
};
ResidueTypeAtoms[CgDnaBackboneType] = {
    trace: ["C3'", 'C3*', "C2'", 'P'],
    backboneStart: ["C3'", 'C3*', "C2'", 'P'],
    backboneEnd: ["C3'", 'C3*', "C2'", 'P']
};
ResidueTypeAtoms[UnknownBackboneType] = {};

/**
 * @file Geometry
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function assignGeometry(totalCoordination) {
    switch (totalCoordination) {
        case 0:
            return 0 /* Spherical */;
        case 1:
            return 1 /* Terminal */;
        case 2:
            return 2 /* Linear */;
        case 3:
            return 3 /* Trigonal */;
        case 4:
            return 4 /* Tetrahedral */;
        default:
            return 8 /* Unknown */;
    }
}
var Angles = new Map([
    [2 /* Linear */, degToRad(180)],
    [3 /* Trigonal */, degToRad(120)],
    [4 /* Tetrahedral */, degToRad(109.4721)],
    [6 /* Octahedral */, degToRad(90)]
]);
/**
 * Calculate the angles x-1-2 for all x where x is a heavy atom bonded to ap1.
 * @param  {AtomProxy} ap1 First atom (angle centre)
 * @param  {AtomProxy} ap2 Second atom
 * @return {number[]}        Angles in radians
 */
function calcAngles(ap1, ap2) {
    var angles = [];
    var d1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var d2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    d1.subVectors(ap2, ap1);
    ap1.eachBondedAtom(function (x) {
        if (x.number !== 1 /* H */) {
            d2.subVectors(x, ap1);
            angles.push(d1.angleTo(d2));
        }
    });
    return angles;
}
/**
 * Find two neighbours of ap1 to define a plane (if possible) and
 * measure angle out of plane to ap2
 * @param  {AtomProxy} ap1 First atom (angle centre)
 * @param  {AtomProxy} ap2 Second atom (out-of-plane)
 * @return {number}        Angle from plane to second atom
 */
function calcPlaneAngle(ap1, ap2) {
    var x1 = ap1.clone();
    var v12 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    v12.subVectors(ap2, ap1);
    var neighbours = [new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](), new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]()];
    var ni = 0;
    ap1.eachBondedAtom(function (x) {
        if (ni > 1) {
            return;
        }
        if (x.number !== 1 /* H */) {
            x1.index = x.index;
            neighbours[ni++].subVectors(x, ap1);
        }
    });
    if (ni === 1) {
        x1.eachBondedAtom(function (x) {
            if (ni > 1) {
                return;
            }
            if (x.number !== 1 /* H */ && x.index !== ap1.index) {
                neighbours[ni++].subVectors(x, ap1);
            }
        });
    }
    if (ni !== 2) {
        return;
    }
    var cp = neighbours[0].cross(neighbours[1]);
    return Math.abs((Math.PI / 2) - cp.angleTo(v12));
}

/**
 * @file Valence Model
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/**
 * Are we involved in some kind of pi system. Either explicitly forming
 * double bond or N, O next to a double bond, except:
 *
 *   N,O with degree 4 cannot be conjugated.
 *   N,O adjacent to P=O or S=O do not qualify (keeps sulfonamide N sp3 geom)
 */
function isConjugated(a) {
    var _bp = a.structure.getBondProxy();
    var atomicNumber = a.number;
    var hetero = atomicNumber === 8 /* O */ || atomicNumber === 7 /* N */;
    if (hetero && a.bondCount === 4) {
        return false;
    }
    var flag = false;
    a.eachBond(function (b) {
        if (b.bondOrder > 1) {
            flag = true;
            return;
        }
        if (hetero) {
            var a2 = b.getOtherAtom(a);
            a2.eachBond(function (b2) {
                if (b2.bondOrder > 1) {
                    var atomicNumber2 = a2.number;
                    if ((atomicNumber2 === 15 /* P */ || atomicNumber2 === 16 /* S */) &&
                        b2.getOtherAtom(a2).number === 8 /* O */) {
                        return;
                    }
                    flag = true;
                }
            }, _bp); // Avoid reuse of structure._bp
        }
    });
    return flag;
}
/* function hasExplicitCharge(r: ResidueProxy) {
  let flag = false
  r.eachAtom(a => {
    if (a.formalCharge != null && a.formalCharge !== 0) flag = true
  })
  return flag
}

function hasExplicitHydrogen(r: ResidueProxy) {
  let flag = false
  r.eachAtom(a => {
    if (a.number === Elements.H) flag = true
  })
  return flag
} */
function explicitValence(a) {
    var v = 0;
    a.eachBond(function (b) { return v += b.bondOrder; });
    return v;
}
/**
 * Attempts to produce a consistent charge and implicit
 * H-count for an atom.
 *
 * If both params.assignCharge and params.assignH, this
 * approximately followsthe rules described in
 * https://docs.eyesopen.com/toolkits/python/oechemtk/valence.html#openeye-hydrogen-count-model
 *
 * If only charge or hydrogens are to be assigned it takes
 * a much simpler view and deduces one from the other
 *
 * @param {AtomProxy}           a      Atom to analyze
 * @param {assignChargeHParams} params What to assign
 */
function calculateHydrogensCharge(a, params) {
    var hydrogenCount = a.bondToElementCount(1 /* H */);
    var charge = a.formalCharge || 0;
    var assignCharge = (params.assignCharge === 'always' ||
        (params.assignCharge === 'auto' && charge === 0));
    var assignH = (params.assignH === 'always' ||
        (params.assignH === 'auto' && hydrogenCount === 0));
    var degree = a.bondCount;
    var valence = explicitValence(a);
    var conjugated = isConjugated(a);
    var multiBond = (valence - degree > 0);
    var implicitHCount = 0;
    var geom = 8 /* Unknown */;
    switch (a.number) {
        case 1 /* H */:
            if (assignCharge) {
                if (degree === 0) {
                    charge = 1;
                    geom = 0 /* Spherical */;
                }
                else if (degree === 1) {
                    charge = 0;
                    geom = 1 /* Terminal */;
                }
            }
            break;
        case 6 /* C */:
            // TODO: Isocyanide?
            if (assignCharge) {
                charge = 0; // Assume carbon always neutral
            }
            if (assignH) {
                // Carbocation/carbanion are 3-valent
                implicitHCount = Math.max(0, 4 - valence - Math.abs(charge));
            }
            // Carbocation is planar, carbanion is tetrahedral
            geom = assignGeometry(degree + implicitHCount + Math.max(0, -charge));
            break;
        case 7 /* N */:
            if (assignCharge) {
                if (!assignH) { // Trust input H explicitly:
                    charge = valence - 3;
                }
                else if (conjugated && valence < 4) {
                    // Neutral unless amidine/guanidine double-bonded N:
                    if (degree - hydrogenCount === 1 && valence - hydrogenCount === 2) {
                        charge = 1;
                    }
                    else {
                        charge = 0;
                    }
                }
                else {
                    // Sulfonamide nitrogen and classed as sp3 in conjugation model but
                    // they won't be charged
                    // Don't assign charge to nitrogens bound to metals
                    var flag = false;
                    a.eachBondedAtom(function (ba) {
                        if (ba.number === 16 /* S */ || ba.isMetal())
                            { flag = true; }
                    });
                    if (flag)
                        { charge = 0; }
                    else
                        { charge = 1; }
                    // TODO: Planarity sanity check?
                }
            }
            if (assignH) {
                // NH4+ -> 4, 1' amide -> 2, nitro N/N+ depiction -> 0
                implicitHCount = Math.max(0, 3 - valence + charge);
            }
            if (conjugated && !multiBond) {
                // Amide, anilinic N etc. cannot consider lone-pair for geometry purposes
                // Anilinic N geometry is depenent on ring electronics, for our purposes we
                // assume it's trigonal!
                geom = assignGeometry(degree + implicitHCount - charge);
            }
            else {
                // Everything else, pyridine, amine, nitrile, lp plays normal role:
                geom = assignGeometry(degree + implicitHCount + 1 - charge);
            }
            break;
        case 8 /* O */:
            if (assignCharge) {
                if (!assignH) {
                    charge = valence - 2; //
                }
                if (valence === 1) {
                    a.eachBondedAtom(function (ba) {
                        ba.eachBond(function (b) {
                            var oa = b.getOtherAtom(ba);
                            if (oa.index !== a.index && oa.number === 8 /* O */ && b.bondOrder === 2) {
                                charge = -1;
                            }
                        });
                    });
                }
            }
            if (assignH) {
                // ethanol -> 1, carboxylate -> -1
                implicitHCount = Math.max(0, 2 - valence + charge);
            }
            if (conjugated && !multiBond) {
                // carboxylate OH, phenol OH, one lone-pair taken up with conjugation
                geom = assignGeometry(degree + implicitHCount - charge + 1);
            }
            else {
                // Carbonyl (trigonal)
                geom = assignGeometry(degree + implicitHCount - charge + 2);
            }
            break;
        // Only handles thiols/thiolates/thioether/sulfonium. Sulfoxides and higher
        // oxidiation states are assumed neutral S (charge carried on O if required)
        case 16 /* S */:
            if (assignCharge) {
                if (!assignH) {
                    if (valence <= 3 && !a.bondToElementCount(8 /* O */)) {
                        charge = valence - 2; // e.g. explicitly deprotonated thiol
                    }
                    else {
                        charge = 0;
                    }
                }
            }
            if (assignH) {
                if (valence < 2) {
                    implicitHCount = Math.max(0, 2 - valence + charge);
                }
            }
            if (valence <= 3) {
                // Thiol, thiolate, tioether -> tetrahedral
                geom = assignGeometry(degree + implicitHCount - charge + 2);
            }
            break;
        case 9 /* F */:
        case 17 /* CL */:
        case 35 /* BR */:
        case 53 /* I */:
        case 85 /* AT */:
            // Never implicitly protonate halides
            if (assignCharge) {
                charge = valence - 1;
            }
            break;
        case 3 /* LI */:
        case 11 /* NA */:
        case 19 /* K */:
        case 37 /* RB */:
        case 55 /* CS */:
        case 87 /* FR */:
            if (assignCharge) {
                charge = 1 - valence;
            }
            break;
        case 4 /* BE */:
        case 12 /* MG */:
        case 20 /* CA */:
        case 38 /* SR */:
        case 56 /* BA */:
        case 88 /* RA */:
            if (assignCharge) {
                charge = 2 - valence;
            }
            break;
        default:
            console.warn('Requested charge, protonation for an unhandled element', a.element);
    }
    return [charge, implicitHCount, implicitHCount + hydrogenCount, geom];
}
function ValenceModel(data, params) {
    var structure = data.structure;
    var n = structure.atomCount;
    var charge = new Int8Array(n);
    var implicitH = new Int8Array(n);
    var totalH = new Int8Array(n);
    var idealGeometry = new Int8Array(n);
    structure.eachAtom(function (a) {
        var i = a.index;
        var ref = calculateHydrogensCharge(a, params);
        var chg = ref[0];
        var implH = ref[1];
        var totH = ref[2];
        var geom = ref[3];
        charge[i] = chg;
        implicitH[i] = implH;
        totalH[i] = totH;
        idealGeometry[i] = geom;
    });
    return { charge: charge, implicitH: implicitH, totalH: totalH, idealGeometry: idealGeometry };
}

function createData(structure) {
    return {
        structure: structure,
        '@spatialLookup': undefined,
        '@valenceModel': undefined
    };
}
function valenceModel(data) {
    if (data['@valenceModel'])
        { return data['@valenceModel']; }
    var valenceModel = ValenceModel(data, { assignCharge: 'auto', assignH: 'auto' });
    data['@valenceModel'] = valenceModel;
    return valenceModel;
}

/**
 * @file Functional Groups
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/**
 * Sulfur in a sulfonic acid or sulfonate group
 */
function isSulfonicAcid(a) {
    return (a.number === 16 &&
        a.bondToElementCount(8 /* O */) === 3);
}
/**
 * Sulfur in a sulfate group
 */
function isSulfate(a) {
    return (a.number === 16 &&
        a.bondToElementCount(8 /* O */) === 4);
}
/**
 * Phosphor in a phosphate group
 */
function isPhosphate(a) {
    return (a.number === 15 &&
        a.bondToElementCount(8 /* O */) === a.bondCount);
}
/**
 * Carbon in a carboxylate group
 */
function isCarboxylate(a) {
    var terminalOxygenCount = 0;
    if (a.number === 6 &&
        a.bondToElementCount(8 /* O */) === 2 &&
        a.bondToElementCount(6 /* C */) === 1) {
        a.eachBondedAtom(function (ba) {
            if (ba.number === 8 && ba.bondCount - ba.bondToElementCount(1 /* H */) === 1) {
                ++terminalOxygenCount;
            }
        });
    }
    return terminalOxygenCount === 2;
}
/**
 * Carbon in a guanidine group
 */
function isGuanidine(a) {
    var terminalNitrogenCount = 0;
    if (a.number === 6 &&
        a.bondCount === 3 &&
        a.bondToElementCount(7 /* N */) === 3) {
        a.eachBondedAtom(function (ba) {
            if (ba.bondCount - ba.bondToElementCount(1 /* H */) === 1) {
                ++terminalNitrogenCount;
            }
        });
    }
    return terminalNitrogenCount === 2;
}
/**
 * Carbon in a acetamidine group
 */
function isAcetamidine(a) {
    var terminalNitrogenCount = 0;
    if (a.number === 6 &&
        a.bondCount === 3 &&
        a.bondToElementCount(7 /* N */) === 2 &&
        a.bondToElementCount(6 /* C */) === 1) {
        a.eachBondedAtom(function (ba) {
            if (ba.bondCount - ba.bondToElementCount(1 /* H */) === 1) {
                ++terminalNitrogenCount;
            }
        });
    }
    return terminalNitrogenCount === 2;
}

/**
 * @file Charged
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 */
var PositvelyCharged = ['ARG', 'HIS', 'LYS'];
var NegativelyCharged = ['GLU', 'ASP'];
function addPositiveCharges(structure, features) {
    var ref = valenceModel(structure.data);
    var charge = ref.charge;
    var atomInGroupDict = {};
    structure.eachResidue(function (r) {
        if (PositvelyCharged.includes(r.resname)) {
            var state = createFeatureState(1 /* PositiveCharge */);
            r.eachAtom(function (a) {
                if (a.number === 7 /* N */ && a.isSidechain()) {
                    addAtom(state, a);
                }
            });
            addFeature(features, state);
        }
        else if (!AA3.includes(r.resname) && !r.isNucleic()) {
            r.eachAtom(function (a) {
                var addGroup = false;
                var state = createFeatureState(1 /* PositiveCharge */);
                if (isGuanidine(a)) {
                    state.group = 8 /* Guanidine */;
                    addGroup = true;
                }
                else if (isAcetamidine(a)) {
                    state.group = 9 /* Acetamidine */;
                    addGroup = true;
                }
                if (addGroup) {
                    a.eachBondedAtom(function (a) {
                        if (a.number === 7 /* N */) {
                            atomInGroupDict[a.index] = true;
                            addAtom(state, a);
                        }
                    });
                    addFeature(features, state);
                }
            });
            r.eachAtom(function (a) {
                var state = createFeatureState(1 /* PositiveCharge */);
                if (charge[a.index] > 0) {
                    if (!atomInGroupDict[a.index]) {
                        addAtom(state, a);
                        addFeature(features, state);
                    }
                }
            });
        }
    });
}
function addNegativeCharges(structure, features) {
    var ref = valenceModel(structure.data);
    var charge = ref.charge;
    var atomInGroupDict = {};
    structure.eachResidue(function (r) {
        if (NegativelyCharged.includes(r.resname)) {
            var state = createFeatureState(2 /* NegativeCharge */);
            r.eachAtom(function (a) {
                if (a.number === 8 /* O */ && a.isSidechain()) {
                    addAtom(state, a);
                }
            });
            addFeature(features, state);
        }
        else if (Bases.includes(r.resname)) {
            var state$1 = createFeatureState(2 /* NegativeCharge */);
            r.eachAtom(function (a) {
                if (isPhosphate(a)) {
                    state$1.group = 6 /* Phosphate */;
                    a.eachBondedAtom(function (a) {
                        if (a.number === 8 /* O */)
                            { addAtom(state$1, a); }
                    });
                    addFeature(features, state$1);
                }
            });
        }
        else if (!AA3.includes(r.resname) && !Bases.includes(r.resname)) {
            r.eachAtom(function (a) {
                var addGroup = false;
                var state = createFeatureState(2 /* NegativeCharge */);
                if (isSulfonicAcid(a)) {
                    state.group = 4 /* SulfonicAcid */;
                    addGroup = true;
                }
                else if (isPhosphate(a)) {
                    state.group = 6 /* Phosphate */;
                    addGroup = true;
                }
                else if (isSulfate(a)) {
                    state.group = 5 /* Sulfate */;
                    addGroup = true;
                }
                else if (isCarboxylate(a)) {
                    state.group = 10 /* Carboxylate */;
                    addGroup = true;
                }
                if (addGroup) {
                    a.eachBondedAtom(function (a) {
                        if (a.number === 8 /* O */) {
                            atomInGroupDict[a.index] = true;
                            addAtom(state, a);
                        }
                    });
                    addFeature(features, state);
                }
            });
            r.eachAtom(function (a) {
                var state = createFeatureState(2 /* NegativeCharge */);
                if (charge[a.index] < 0) {
                    if (!atomInGroupDict[a.index]) {
                        addAtom(state, a);
                        addFeature(features, state);
                    }
                }
            });
        }
    });
}
function addAromaticRings(structure, features) {
    var a = structure.getAtomProxy();
    structure.eachResidue(function (r) {
        var rings = r.getAromaticRings();
        if (rings) {
            var offset = r.atomOffset;
            rings.forEach(function (ring) {
                var state = createFeatureState(3 /* AromaticRing */);
                ring.forEach(function (i) {
                    a.index = i + offset;
                    addAtom(state, a);
                });
                addFeature(features, state);
            });
        }
    });
}
function isIonicInteraction(ti, tj) {
    return ((ti === 2 /* NegativeCharge */ && tj === 1 /* PositiveCharge */) ||
        (ti === 1 /* PositiveCharge */ && tj === 2 /* NegativeCharge */));
}
function isPiStacking(ti, tj) {
    return ti === 3 /* AromaticRing */ && tj === 3 /* AromaticRing */;
}
function isCationPi(ti, tj) {
    return ((ti === 3 /* AromaticRing */ && tj === 1 /* PositiveCharge */) ||
        (ti === 1 /* PositiveCharge */ && tj === 3 /* AromaticRing */));
}
function addChargedContacts(structure, contacts, params) {
    if ( params === void 0 ) params = {};

    var maxIonicDist = defaults(params.maxIonicDist, ContactDefaultParams.maxIonicDist);
    var maxPiStackingDist = defaults(params.maxPiStackingDist, ContactDefaultParams.maxPiStackingDist);
    var maxPiStackingOffset = defaults(params.maxPiStackingOffset, ContactDefaultParams.maxPiStackingOffset);
    var maxPiStackingAngle = defaults(params.maxPiStackingAngle, ContactDefaultParams.maxPiStackingAngle);
    var maxCationPiDist = defaults(params.maxCationPiDist, ContactDefaultParams.maxCationPiDist);
    var maxCationPiOffset = defaults(params.maxCationPiOffset, ContactDefaultParams.maxCationPiOffset);
    var masterIdx = defaults(params.masterModelIndex, ContactDefaultParams.masterModelIndex);
    var maxDistance = Math.max(maxIonicDist + 2, maxPiStackingDist, maxCationPiDist);
    // const maxSaltBridgeDistSq = maxSaltBridgeDist * maxSaltBridgeDist
    var maxPiStackingDistSq = maxPiStackingDist * maxPiStackingDist;
    var maxCationPiDistSq = maxCationPiDist * maxCationPiDist;
    var features = contacts.features;
    var spatialHash = contacts.spatialHash;
    var contactStore = contacts.contactStore;
    var featureSet = contacts.featureSet;
    var types = features.types;
    var centers = features.centers;
    var atomSets = features.atomSets;
    var x = centers.x;
    var y = centers.y;
    var z = centers.z;
    var n = types.length;
    var ax = structure.atomStore.x;
    var ay = structure.atomStore.y;
    var az = structure.atomStore.z;
    var ap1 = structure.getAtomProxy();
    var ap2 = structure.getAtomProxy();
    var areAtomSetsWithinDist = function (atomSet1, atomSet2, maxDist) {
        var sn = atomSet1.length;
        var sm = atomSet2.length;
        for (var si = 0; si < sn; ++si) {
            ap1.index = atomSet1[si];
            for (var sj = 0; sj < sm; ++sj) {
                ap2.index = atomSet2[sj];
                if (ap1.distanceTo(ap2) <= maxDist) {
                    return true;
                }
            }
        }
        return false;
    };
    var v1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var v2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var v3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var d1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var d2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var n1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var n2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var getNormal = function (atoms, normal) {
        v1.set(ax[atoms[0]], ay[atoms[0]], az[atoms[0]]);
        v2.set(ax[atoms[1]], ay[atoms[1]], az[atoms[1]]);
        v3.set(ax[atoms[2]], ay[atoms[2]], az[atoms[2]]);
        d1.subVectors(v1, v2);
        d2.subVectors(v1, v3);
        normal.crossVectors(d1, d2);
    };
    var getOffset = function (i, j, normal) {
        v1.set(x[i], y[i], z[i]);
        v2.set(x[j], y[j], z[j]);
        return v1.sub(v2).projectOnPlane(normal).add(v2).distanceTo(v2);
    };
    var add = function (i, j, ct) {
        featureSet.setBits(i, j);
        contactStore.addContact(i, j, ct);
    };
    var loop = function ( i ) {
        spatialHash.eachWithin(x[i], y[i], z[i], maxDistance, function (j, dSq) {
            if (j <= i)
                { return; }
            ap1.index = atomSets[i][0];
            ap2.index = atomSets[j][0];
            if (invalidAtomContact$1(ap1, ap2, masterIdx))
                { return; }
            var ti = types[i];
            var tj = types[j];
            if (isIonicInteraction(ti, tj)) {
                if (areAtomSetsWithinDist(atomSets[i], atomSets[j], maxIonicDist)) {
                    add(i, j, 1 /* IonicInteraction */);
                }
            }
            else if (isPiStacking(ti, tj)) {
                if (dSq <= maxPiStackingDistSq) {
                    getNormal(atomSets[i], n1);
                    getNormal(atomSets[j], n2);
                    var angle = radToDeg(n1.angleTo(n2));
                    var offset = Math.min(getOffset(i, j, n2), getOffset(j, i, n1));
                    if (offset <= maxPiStackingOffset) {
                        if (angle <= maxPiStackingAngle || angle >= 180 - maxPiStackingAngle) {
                            add(i, j, 3 /* PiStacking */); // parallel
                        }
                        else if (angle <= maxPiStackingAngle + 90 && angle >= 90 - maxPiStackingAngle) {
                            add(i, j, 3 /* PiStacking */); // t-shaped
                        }
                    }
                }
            }
            else if (isCationPi(ti, tj)) {
                if (dSq <= maxCationPiDistSq) {
                    var ref = ti === 3 /* AromaticRing */ ? [i, j] : [j, i];
                    var l = ref[0];
                    var k = ref[1];
                    getNormal(atomSets[l], n1);
                    var offset$1 = getOffset(k, l, n1);
                    if (offset$1 <= maxCationPiOffset) {
                        add(l, k, 2 /* CationPi */);
                    }
                }
            }
        });
    };

    for (var i = 0; i < n; ++i) loop( i );
}

/**
 * @file Hydrogen Bonds
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 */
// Geometric characteristics of hydrogen bonds involving sulfur atoms in proteins
// https://doi.org/10.1002/prot.22327
// Satisfying Hydrogen Bonding Potential in Proteins (HBPLUS)
// https://doi.org/10.1006/jmbi.1994.1334
// http://www.csb.yale.edu/userguides/datamanip/hbplus/hbplus_descrip.html
/**
 * Potential hydrogen donor
 */
function addHydrogenDonors(structure, features) {
    var ref = valenceModel(structure.data);
    var totalH = ref.totalH;
    structure.eachAtom(function (a) {
        var state = createFeatureState(4 /* HydrogenDonor */);
        var an = a.number;
        if (isHistidineNitrogen(a)) {
            // include both nitrogen atoms in histidine due to
            // their often ambiguous protonation assignment
            addAtom(state, a);
            addFeature(features, state);
        }
        else if (totalH[a.index] > 0 &&
            (an === 7 /* N */ || an === 8 /* O */ || an === 16 /* S */)) {
            addAtom(state, a);
            addFeature(features, state);
        }
    });
}
/**
 * Weak hydrogen donor.
 */
function addWeakHydrogenDonors(structure, features) {
    var ref = valenceModel(structure.data);
    var totalH = ref.totalH;
    structure.eachAtom(function (a) {
        if (a.number === 6 /* C */ &&
            totalH[a.index] > 0 &&
            (a.bondToElementCount(7 /* N */) > 0 ||
                a.bondToElementCount(8 /* O */) > 0 ||
                inAromaticRingWithElectronNegativeElement(a))) {
            var state = createFeatureState(9 /* WeakHydrogenDonor */);
            addAtom(state, a);
            addFeature(features, state);
        }
    });
}
function inAromaticRingWithElectronNegativeElement(a) {
    if (!a.isAromatic())
        { return false; }
    var ringData = a.residueType.getRings();
    if (!ringData)
        { return false; }
    var hasElement = false;
    var rings = ringData.rings;
    rings.forEach(function (ring) {
        if (hasElement)
            { return; } // already found one
        if (ring.some(function (idx) { return (a.index - a.residueAtomOffset) === idx; })) { // in ring
            hasElement = ring.some(function (idx) {
                var atomTypeId = a.residueType.atomTypeIdList[idx];
                var number = a.atomMap.get(atomTypeId).number;
                return number === 7 /* N */ || number === 8 /* O */;
            });
        }
    });
    return hasElement;
}
/**
 * Potential hydrogen acceptor
 */
function addHydrogenAcceptors(structure, features) {
    var ref = valenceModel(structure.data);
    var charge = ref.charge;
    var implicitH = ref.implicitH;
    var idealGeometry = ref.idealGeometry;
    structure.eachAtom(function (a) {
        var state = createFeatureState(5 /* HydrogenAcceptor */);
        var an = a.number;
        if (an === 8 /* O */) {
            // Basically assume all oxygen atoms are acceptors!
            addAtom(state, a);
            addFeature(features, state);
        }
        else if (an === 7 /* N */) {
            if (isHistidineNitrogen(a)) {
                // include both nitrogen atoms in histidine due to
                // their often ambiguous protonation assignment
                addAtom(state, a);
                addFeature(features, state);
            }
            else if (charge[a.index] < 1) {
                // Neutral nitrogen might be an acceptor
                // It must have at least one lone pair not conjugated
                var totalBonds = a.bondCount + implicitH[a.index];
                var ig = idealGeometry[a.index];
                if ((ig === 4 /* Tetrahedral */ && totalBonds < 4) ||
                    (ig === 3 /* Trigonal */ && totalBonds < 3) ||
                    (ig === 2 /* Linear */ && totalBonds < 2)) {
                    addAtom(state, a);
                    addFeature(features, state);
                }
            }
        }
        else if (an === 16) { // S
            if (a.resname === 'CYS' || a.resname === 'MET' || a.formalCharge === -1) {
                addAtom(state, a);
                addFeature(features, state);
            }
        }
    });
}
/**
 * Atom that is only bound to carbon or hydrogen
 */
// function isHydrocarbon (atom: AtomProxy) {
//   let flag = true
//   atom.eachBondedAtom(ap => {
//     const e = ap.element
//     if (e !== 'C' && e !== 'H') flag = false
//   })
//   return flag
// }
function isHistidineNitrogen(ap) {
    return ap.resname === 'HIS' && ap.number == 7 /* N */ && ap.isRing();
}
function isBackboneHydrogenBond(ap1, ap2) {
    return ap1.isBackbone() && ap2.isBackbone();
}
function isWaterHydrogenBond(ap1, ap2) {
    return ap1.isWater() && ap2.isWater();
}
function isHydrogenBond(ti, tj) {
    return ((ti === 5 /* HydrogenAcceptor */ && tj === 4 /* HydrogenDonor */) ||
        (ti === 4 /* HydrogenDonor */ && tj === 5 /* HydrogenAcceptor */));
}
function isWeakHydrogenBond(ti, tj) {
    return ((ti === 9 /* WeakHydrogenDonor */ && tj === 5 /* HydrogenAcceptor */) ||
        (ti === 5 /* HydrogenAcceptor */ && tj === 9 /* WeakHydrogenDonor */));
}
function getHydrogenBondType(ap1, ap2) {
    if (isWaterHydrogenBond(ap1, ap2)) {
        return 9 /* WaterHydrogenBond */;
    }
    else if (isBackboneHydrogenBond(ap1, ap2)) {
        return 10 /* BackboneHydrogenBond */;
    }
    else {
        return 4 /* HydrogenBond */;
    }
}
/**
 * All pairs of hydrogen donor and acceptor atoms
 */
function addHydrogenBonds(structure, contacts, params) {
    if ( params === void 0 ) params = {};

    var maxHbondDist = defaults(params.maxHbondDist, ContactDefaultParams.maxHbondDist);
    var maxHbondSulfurDist = defaults(params.maxHbondSulfurDist, ContactDefaultParams.maxHbondSulfurDist);
    var maxHbondAccAngle = degToRad(defaults(params.maxHbondAccAngle, ContactDefaultParams.maxHbondAccAngle));
    var maxHbondDonAngle = degToRad(defaults(params.maxHbondDonAngle, ContactDefaultParams.maxHbondDonAngle));
    var maxHbondAccPlaneAngle = degToRad(defaults(params.maxHbondAccPlaneAngle, ContactDefaultParams.maxHbondAccPlaneAngle));
    var maxHbondDonPlaneAngle = degToRad(defaults(params.maxHbondDonPlaneAngle, ContactDefaultParams.maxHbondDonPlaneAngle));
    var masterIdx = defaults(params.masterModelIndex, ContactDefaultParams.masterModelIndex);
    var maxDist = Math.max(maxHbondDist, maxHbondSulfurDist);
    var maxHbondDistSq = maxHbondDist * maxHbondDist;
    var features = contacts.features;
    var spatialHash = contacts.spatialHash;
    var contactStore = contacts.contactStore;
    var featureSet = contacts.featureSet;
    var types = features.types;
    var centers = features.centers;
    var atomSets = features.atomSets;
    var x = centers.x;
    var y = centers.y;
    var z = centers.z;
    var n = types.length;
    var ref = valenceModel(structure.data);
    var idealGeometry = ref.idealGeometry;
    var donor = structure.getAtomProxy();
    var acceptor = structure.getAtomProxy();
    var loop = function ( i ) {
        spatialHash.eachWithin(x[i], y[i], z[i], maxDist, function (j, dSq) {
            if (j <= i)
                { return; }
            var ti = types[i];
            var tj = types[j];
            var isWeak = isWeakHydrogenBond(ti, tj);
            if (!isWeak && !isHydrogenBond(ti, tj))
                { return; }
            var ref = tj === 5 /* HydrogenAcceptor */ ? [i, j] : [j, i];
            var l = ref[0];
            var k = ref[1];
            donor.index = atomSets[l][0];
            acceptor.index = atomSets[k][0];
            if (acceptor.index === donor.index)
                { return; } // DA to self
            if (invalidAtomContact$1(donor, acceptor, masterIdx))
                { return; }
            if (donor.number !== 16 /* S */ && acceptor.number !== 16 /* S */ && dSq > maxHbondDistSq)
                { return; }
            if (donor.connectedTo(acceptor))
                { return; }
            var donorAngles = calcAngles(donor, acceptor);
            var idealDonorAngle = Angles.get(idealGeometry[donor.index]) || degToRad(120);
            if (donorAngles.some(function (donorAngle) {
                return Math.abs(idealDonorAngle - donorAngle) > maxHbondDonAngle;
            }))
                { return; }
            if (idealGeometry[donor.index] === 3 /* Trigonal */) {
                var outOfPlane = calcPlaneAngle(donor, acceptor);
                if (outOfPlane !== undefined && outOfPlane > maxHbondDonPlaneAngle)
                    { return; }
            }
            var acceptorAngles = calcAngles(acceptor, donor);
            var idealAcceptorAngle = Angles.get(idealGeometry[acceptor.index]) || degToRad(120);
            if (acceptorAngles.some(function (acceptorAngle) {
                // Do not limit large acceptor angles
                return idealAcceptorAngle - acceptorAngle > maxHbondAccAngle;
            }))
                { return; }
            if (idealGeometry[acceptor.index] === 3 /* Trigonal */) {
                var outOfPlane$1 = calcPlaneAngle(acceptor, donor);
                if (outOfPlane$1 !== undefined && outOfPlane$1 > maxHbondAccPlaneAngle)
                    { return; }
            }
            featureSet.setBits(l, k);
            var bondType = isWeak ? 8 /* WeakHydrogenBond */ : getHydrogenBondType(donor, acceptor);
            contactStore.addContact(l, k, bondType);
        });
    };

    for (var i = 0; i < n; ++i) loop( i );
}

/**
 * @file Metal Binding
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var IonicTypeMetals = [
    3 /* LI */, 11 /* NA */, 19 /* K */, 37 /* RB */, 55 /* CS */,
    12 /* MG */, 20 /* CA */, 38 /* SR */, 56 /* BA */, 13 /* AL */,
    31 /* GA */, 49 /* IN */, 81 /* TL */, 21 /* SC */, 50 /* SN */,
    82 /* PB */, 83 /* BI */, 51 /* SB */, 80 /* HG */
];
/**
 * Metal binding partners (dative bond or ionic-type interaction)
 */
function addMetalBinding(structure, features) {
    structure.eachAtom(function (a) {
        var dative = false;
        var ionic = false;
        var isStandardAminoacid = AA3.includes(a.resname);
        var isStandardBase = Bases.includes(a.resname);
        if (!isStandardAminoacid && !isStandardBase) {
            if (a.isHalogen() || a.number === 8 /* O */ || a.number === 16 /* S */) {
                dative = true;
                ionic = true;
            }
            else if (a.number === 7 /* N */) {
                dative = true;
            }
        }
        else if (isStandardAminoacid) {
            // main chain oxygen atom or oxygen, nitrogen and sulfur from specific amino acids
            if (a.number === 8 /* O */) {
                if (['ASP', 'GLU', 'SER', 'THR', 'TYR', 'ASN', 'GLN'].includes(a.resname) && a.isSidechain()) {
                    dative = true;
                    ionic = true;
                }
                else if (a.isBackbone()) {
                    dative = true;
                    ionic = true;
                }
            }
            else if (a.number === 16 /* S */ && 'CYS' === a.resname) {
                dative = true;
                ionic = true;
            }
            else if (a.number === 7 /* N */) {
                if (a.resname === 'HIS' && a.isSidechain()) {
                    dative = true;
                }
            }
        }
        else if (isStandardBase) {
            // http://pubs.acs.org/doi/pdf/10.1021/acs.accounts.6b00253
            // http://onlinelibrary.wiley.com/doi/10.1002/anie.200900399/full
            if (a.number === 8 /* O */ && a.isBackbone()) {
                dative = true;
                ionic = true;
            }
            else if (['N3', 'N4', 'N7'].includes(a.atomname)) {
                dative = true;
            }
            else if (['O2', 'O4', 'O6'].includes(a.atomname)) {
                dative = true;
                ionic = true;
            }
        }
        if (dative) {
            var state = createFeatureState(11 /* DativeBondPartner */);
            addAtom(state, a);
            addFeature(features, state);
        }
        if (ionic) {
            var state$1 = createFeatureState(10 /* IonicTypePartner */);
            addAtom(state$1, a);
            addFeature(features, state$1);
        }
    });
}
/**
 * Metal Pi complexation partner
 */
// export function addMetalPiPartners (structure: Structure, features: Features) {
//   const { charge } = valenceModel(structure.data)
//   structure.eachAtom(a => {
//     const state = createFeatureState(FeatureType.MetalPiPartner)
//     const resname = a.resname
//     const element = a.element
//     const atomname = a.atomname
//     if (!a.isPolymer()) {
//       // water oxygen, as well as oxygen from carboxylate, phosphoryl, phenolate, alcohol;
//       // nitrogen from imidazole; sulfur from thiolate
//       if (element === 'O') {
//         // Water oxygen
//         if (a.bondCount === 0 || a.isWater()) {
//           addAtom(state, a)
//           addFeature(features, state)
//           return
//         }
//         // Oxygen in alcohol (R-[O]-H)
//         if (a.bondCount === 2 && charge[ a.index ] || a.hasBondToElement('H')) {
//           addAtom(state, a)
//           addFeature(features, state)
//           return
//         }
//         // Phenolate oxygen
//         if (hasAromaticNeighbour(a) && !a.aromatic) {
//           addAtom(state, a)
//           addFeature(features, state)
//           return
//         }
//         // Carboxylic acid oxygen
//         if (a.bondToElementCount('C') === 1) {
//           let flag = false
//           a.eachBondedAtom(ba => {
//             if (ba.element === 'C' && ba.bondToElementCount('O') === 2 && ba.bondToElementCount('C') === 1) {
//               flag = true
//             }
//           })
//           if (flag) {
//             addAtom(state, a)
//             addFeature(features, state)
//             return
//           }
//         }
//         // Phosphoryl oxygen
//         if (a.bondToElementCount('P') === 1) {
//           let flag = false
//           a.eachBondedAtom(ba => {
//             if (ba.element === 'P' && ba.bondToElementCount('O') >= 3) {
//               flag = true
//             }
//           })
//           if (flag) {
//             addAtom(state, a)
//             addFeature(features, state)
//             return
//           }
//         }
//       } else if (element === 'N') {
//         // Imidazole/pyrrole or similar
//         if (a.bondToElementCount('C') === 2) {
//           addAtom(state, a)
//           addFeature(features, state)
//           return
//         }
//       } else if (element === 'S') {
//         // Thiolate
//         if (hasAromaticNeighbour(a) && !a.aromatic) {
//           addAtom(state, a)
//           addFeature(features, state)
//           return
//         }
//         // Sulfur in Iron sulfur cluster
//         const ironCount = a.bondToElementCount('FE')
//         if (ironCount > 0 && ironCount === a.bondCount) {
//           addAtom(state, a)
//           addFeature(features, state)
//           return
//         }
//       }
//     }
//   })
// }
function addMetals(structure, features) {
    structure.eachAtom(function (a) {
        if (a.isTransitionMetal() || a.number === 30 /* ZN */ || a.number === 48 /* CD */) {
            var state = createFeatureState(12 /* TransitionMetal */);
            addAtom(state, a);
            addFeature(features, state);
        }
        else if (IonicTypeMetals.includes(a.number)) {
            var state$1 = createFeatureState(13 /* IonicTypeMetal */);
            addAtom(state$1, a);
            addFeature(features, state$1);
        }
    });
}
function isMetalComplex(ti, tj) {
    if (ti === 12 /* TransitionMetal */) {
        return (tj === 11 /* DativeBondPartner */ ||
            tj === 12 /* TransitionMetal */);
    }
    else if (ti === 13 /* IonicTypeMetal */) {
        return (tj === 10 /* IonicTypePartner */);
    }
}
/**
 * Metal complexes of metals and appropriate groups in protein and ligand, including water
 */
function addMetalComplexation(structure, contacts, params) {
    if ( params === void 0 ) params = {};

    var maxMetalDist = defaults(params.maxMetalDist, ContactDefaultParams.maxMetalDist);
    var masterIdx = defaults(params.masterModelIndex, ContactDefaultParams.masterModelIndex);
    var features = contacts.features;
    var spatialHash = contacts.spatialHash;
    var contactStore = contacts.contactStore;
    var featureSet = contacts.featureSet;
    var types = features.types;
    var centers = features.centers;
    var atomSets = features.atomSets;
    var x = centers.x;
    var y = centers.y;
    var z = centers.z;
    var n = types.length;
    var ap1 = structure.getAtomProxy();
    var ap2 = structure.getAtomProxy();
    var loop = function ( i ) {
        spatialHash.eachWithin(x[i], y[i], z[i], maxMetalDist, function (j, dSq) {
            if (j <= i)
                { return; }
            ap1.index = atomSets[i][0];
            ap2.index = atomSets[j][0];
            if (invalidAtomContact$1(ap1, ap2, masterIdx))
                { return; }
            var m1 = ap1.isMetal();
            var m2 = ap2.isMetal();
            if (!m1 && !m2)
                { return; }
            var ref = m1 ? [types[i], types[j]] : [types[j], types[i]];
            var ti = ref[0];
            var tj = ref[1];
            if (isMetalComplex(ti, tj)) {
                featureSet.setBits(i, j);
                contactStore.addContact(i, j, 7 /* MetalCoordination */);
            }
        });
    };

    for (var i = 0; i < n; ++i) loop( i );
}

/**
 * @file Hydrophobic
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/**
 * Hydrophobic carbon (only bonded to carbon or hydrogen); fluorine
 */
function addHydrophobic(structure, features) {
    structure.eachAtom(function (a) {
        var state = createFeatureState(8 /* Hydrophobic */);
        var flag = false;
        if (a.number === 6 /* C */) {
            flag = true;
            a.eachBondedAtom(function (ap) {
                var an = ap.number;
                if (an !== 6 /* C */ && an !== 1 /* H */)
                    { flag = false; }
            });
        }
        else if (a.number === 9 /* F */) {
            flag = true;
        }
        if (flag) {
            addAtom(state, a);
            addFeature(features, state);
        }
    });
}
function isHydrophobicContact(ti, tj) {
    return ti === 8 /* Hydrophobic */ && tj === 8 /* Hydrophobic */;
}
/**
 * All hydrophobic contacts
 */
function addHydrophobicContacts(structure, contacts, params) {
    if ( params === void 0 ) params = {};

    var maxHydrophobicDist = defaults(params.maxHydrophobicDist, ContactDefaultParams.maxHydrophobicDist);
    var masterIdx = defaults(params.masterModelIndex, ContactDefaultParams.masterModelIndex);
    var features = contacts.features;
    var spatialHash = contacts.spatialHash;
    var contactStore = contacts.contactStore;
    var featureSet = contacts.featureSet;
    var types = features.types;
    var centers = features.centers;
    var atomSets = features.atomSets;
    var x = centers.x;
    var y = centers.y;
    var z = centers.z;
    var n = types.length;
    var ap1 = structure.getAtomProxy();
    var ap2 = structure.getAtomProxy();
    var loop = function ( i ) {
        spatialHash.eachWithin(x[i], y[i], z[i], maxHydrophobicDist, function (j, dSq) {
            if (j <= i)
                { return; }
            ap1.index = atomSets[i][0];
            ap2.index = atomSets[j][0];
            if (invalidAtomContact$1(ap1, ap2, masterIdx))
                { return; }
            if (ap1.number === 9 /* F */ && ap2.number === 9 /* F */)
                { return; }
            if (ap1.connectedTo(ap2))
                { return; }
            if (isHydrophobicContact(types[i], types[j])) {
                featureSet.setBits(i, j);
                contactStore.addContact(i, j, 6 /* Hydrophobic */);
            }
        });
    };

    for (var i = 0; i < n; ++i) loop( i );
}

/**
 * @file Halogen Bonds
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 */
var halBondElements = [17, 35, 53, 85];
/**
 * Halogen bond donors (X-C, with X one of Cl, Br, I or At) not F!
 */
function addHalogenDonors(structure, features) {
    structure.eachAtom(function (a) {
        if (halBondElements.includes(a.number) && a.bondToElementCount(6 /* C */) === 1) {
            var state = createFeatureState(6 /* HalogenDonor */);
            addAtom(state, a);
            addFeature(features, state);
        }
    });
}
var X = [7 /* N */, 8 /* O */, 16 /* S */];
var Y = [6 /* C */, 7 /* N */, 15 /* P */, 16 /* S */];
/**
 * Halogen bond acceptors (Y-{O|N|S}, with Y=C,P,N,S)
 */
function addHalogenAcceptors(structure, features) {
    structure.eachAtom(function (a) {
        if (X.includes(a.number)) {
            var flag = false;
            a.eachBondedAtom(function (ba) {
                if (Y.includes(ba.number)) {
                    flag = true;
                }
            });
            if (flag) {
                var state = createFeatureState(7 /* HalogenAcceptor */);
                addAtom(state, a);
                addFeature(features, state);
            }
        }
    });
}
function isHalogenBond(ti, tj) {
    return ((ti === 7 /* HalogenAcceptor */ && tj === 6 /* HalogenDonor */) ||
        (ti === 6 /* HalogenDonor */ && tj === 7 /* HalogenAcceptor */));
}
// http://www.pnas.org/content/101/48/16789.full
var OptimalHalogenAngle = degToRad(180); // adjusted from 165 to account for spherical statistics
var OptimalAcceptorAngle = degToRad(120);
/**
 * All pairs of halogen donor and acceptor atoms
 */
function addHalogenBonds(structure, contacts, params) {
    if ( params === void 0 ) params = {};

    var maxHalogenBondDist = defaults(params.maxHalogenBondDist, ContactDefaultParams.maxHalogenBondDist);
    var maxHalogenBondAngle = degToRad(defaults(params.maxHalogenBondAngle, ContactDefaultParams.maxHalogenBondAngle));
    var masterIdx = defaults(params.masterModelIndex, ContactDefaultParams.masterModelIndex);
    var features = contacts.features;
    var spatialHash = contacts.spatialHash;
    var contactStore = contacts.contactStore;
    var featureSet = contacts.featureSet;
    var types = features.types;
    var centers = features.centers;
    var atomSets = features.atomSets;
    var x = centers.x;
    var y = centers.y;
    var z = centers.z;
    var n = types.length;
    var ap1 = structure.getAtomProxy();
    var ap2 = structure.getAtomProxy();
    var loop = function ( i ) {
        spatialHash.eachWithin(x[i], y[i], z[i], maxHalogenBondDist, function (j, dSq) {
            if (j <= i)
                { return; }
            ap1.index = atomSets[i][0];
            ap2.index = atomSets[j][0];
            if (invalidAtomContact$1(ap1, ap2, masterIdx))
                { return; }
            if (!isHalogenBond(types[i], types[j]))
                { return; }
            var ref = types[i] === 6 /* HalogenDonor */ ? [ap1, ap2] : [ap2, ap1];
            var halogen = ref[0];
            var acceptor = ref[1];
            var halogenAngles = calcAngles(halogen, acceptor);
            // Singly bonded halogen only (not bromide ion for example)
            if (halogenAngles.length !== 1)
                { return; }
            if (OptimalHalogenAngle - halogenAngles[0] > maxHalogenBondAngle)
                { return; }
            var acceptorAngles = calcAngles(acceptor, halogen);
            // Angle must be defined. Excludes water as acceptor. Debatable
            if (acceptorAngles.length === 0)
                { return; }
            if (acceptorAngles.some(function (acceptorAngle) {
                return (OptimalAcceptorAngle - acceptorAngle > maxHalogenBondAngle);
            }))
                { return; }
            featureSet.setBits(i, j);
            contactStore.addContact(i, j, 5 /* HalogenBond */);
        });
    };

    for (var i = 0; i < n; ++i) loop( i );
}

/**
 * @file Refine Contacts
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// also allows intra-residue contacts
function invalidAtomContact(ap1, ap2, masterIdx) {
    return !isMasterContact(ap1, ap2, masterIdx) && (ap1.modelIndex !== ap2.modelIndex ||
        (ap1.altloc && ap2.altloc && ap1.altloc !== ap2.altloc));
}
function refineLineOfSight(structure, contacts, params) {
    if ( params === void 0 ) params = {};

    if (Debug)
        { Log.time('refineLineOfSight'); }
    var lineOfSightDistFactor = defaults(params.lineOfSightDistFactor, ContactDefaultParams.lineOfSightDistFactor);
    var masterIdx = defaults(params.masterModelIndex, ContactDefaultParams.masterModelIndex);
    var spatialHash = structure.spatialHash;
    var contactSet = contacts.contactSet;
    var contactStore = contacts.contactStore;
    var features = contacts.features;
    var index1 = contactStore.index1;
    var index2 = contactStore.index2;
    var centers = features.centers;
    var atomSets = features.atomSets;
    var x = centers.x;
    var y = centers.y;
    var z = centers.z;
    var ac1 = structure.getAtomProxy();
    var ac2 = structure.getAtomProxy();
    var aw = structure.getAtomProxy();
    var c1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var c2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var lineOfSightDist = 3 * lineOfSightDistFactor;
    var lineOfSightDistFactorSq = lineOfSightDistFactor * lineOfSightDistFactor;
    contactSet.forEach(function (i) {
        c1.set(x[index1[i]], y[index1[i]], z[index1[i]]);
        c2.set(x[index2[i]], y[index2[i]], z[index2[i]]);
        var cx = (c1.x + c2.x) / 2;
        var cy = (c1.y + c2.y) / 2;
        var cz = (c1.z + c2.z) / 2;
        var as1 = atomSets[index1[i]];
        var as2 = atomSets[index2[i]];
        ac1.index = as1[0];
        ac2.index = as2[0];
        spatialHash.eachWithin(cx, cy, cz, lineOfSightDist, function (j, dSq) {
            aw.index = j;
            if (aw.number !== 1 /* H */ &&
                (aw.vdw * aw.vdw * lineOfSightDistFactorSq) > dSq &&
                !invalidAtomContact(ac1, aw, masterIdx) &&
                !invalidAtomContact(ac2, aw, masterIdx) &&
                !as1.includes(j) &&
                !as2.includes(j) &&
                // to ignore atoms in the center of functional groups
                c1.distanceToSquared(aw) > 1 &&
                c2.distanceToSquared(aw) > 1) {
                contactSet.clear(i);
                if (Debug)
                    { Log.log('removing', ac1.qualifiedName(), ac2.qualifiedName(), 'because', aw.qualifiedName()); }
            }
        });
    });
    if (Debug)
        { Log.timeEnd('refineLineOfSight'); }
}
/**
 * For atoms interacting with several atoms in the same residue
 * only the one with the closest distance is kept.
 */
function refineHydrophobicContacts(structure, contacts) {
    var contactSet = contacts.contactSet;
    var contactStore = contacts.contactStore;
    var features = contacts.features;
    var type = contactStore.type;
    var index1 = contactStore.index1;
    var index2 = contactStore.index2;
    var atomSets = features.atomSets;
    var ap1 = structure.getAtomProxy();
    var ap2 = structure.getAtomProxy();
    var residueContactDict = {};
    /* keep only closest contact between residues */
    var handleResidueContact = function (dist, i, key) {
        var ref = residueContactDict[key] || [Infinity, -1];
        var minDist = ref[0];
        var minIndex = ref[1];
        if (dist < minDist) {
            if (minIndex !== -1)
                { contactSet.clear(minIndex); }
            residueContactDict[key] = [dist, i];
        }
        else {
            contactSet.clear(i);
        }
    };
    contactSet.forEach(function (i) {
        if (type[i] !== 6 /* Hydrophobic */)
            { return; }
        ap1.index = atomSets[index1[i]][0];
        ap2.index = atomSets[index2[i]][0];
        var dist = ap1.distanceTo(ap2);
        handleResidueContact(dist, i, ((ap1.index) + "|" + (ap2.residueIndex)));
        handleResidueContact(dist, i, ((ap2.index) + "|" + (ap1.residueIndex)));
    });
}
function isHydrogenBondType(type) {
    return (type === 4 /* HydrogenBond */ ||
        type === 9 /* WaterHydrogenBond */ ||
        type === 10 /* BackboneHydrogenBond */);
}
/**
 * Remove hydrogen bonds between groups that also form
 * a salt bridge between each other
 */
function refineSaltBridges(structure, contacts) {
    var contactSet = contacts.contactSet;
    var contactStore = contacts.contactStore;
    var features = contacts.features;
    var type = contactStore.type;
    var index1 = contactStore.index1;
    var index2 = contactStore.index2;
    var atomSets = features.atomSets;
    var ionicInteractionDict = {};
    var add = function (idx, i) {
        if (!ionicInteractionDict[idx])
            { ionicInteractionDict[idx] = []; }
        ionicInteractionDict[idx].push(i);
    };
    contactSet.forEach(function (i) {
        if (type[i] !== 1 /* IonicInteraction */)
            { return; }
        atomSets[index1[i]].forEach(function (idx) { return add(idx, i); });
        atomSets[index2[i]].forEach(function (idx) { return add(idx, i); });
    });
    contactSet.forEach(function (i) {
        if (!isHydrogenBondType(type[i]))
            { return; }
        var iil1 = ionicInteractionDict[atomSets[index1[i]][0]];
        var iil2 = ionicInteractionDict[atomSets[index2[i]][0]];
        if (!iil1 || !iil2)
            { return; }
        var n = iil1.length;
        for (var j = 0; j < n; ++j) {
            if (iil2.includes(iil1[j])) {
                contactSet.clear(i);
                return;
            }
        }
    });
}
/**
 * Remove hydrophobic and cation-pi interactions between groups that also form
 * a pi-stacking interaction between each other
 */
function refinePiStacking(structure, contacts) {
    var contactSet = contacts.contactSet;
    var contactStore = contacts.contactStore;
    var features = contacts.features;
    var type = contactStore.type;
    var index1 = contactStore.index1;
    var index2 = contactStore.index2;
    var atomSets = features.atomSets;
    var piStackingDict = {};
    var add = function (idx, i) {
        if (!piStackingDict[idx])
            { piStackingDict[idx] = []; }
        piStackingDict[idx].push(i);
    };
    contactSet.forEach(function (i) {
        if (type[i] !== 3 /* PiStacking */)
            { return; }
        atomSets[index1[i]].forEach(function (idx) { return add(idx, i); });
        atomSets[index2[i]].forEach(function (idx) { return add(idx, i); });
    });
    contactSet.forEach(function (i) {
        if (type[i] !== 6 /* Hydrophobic */ &&
            type[i] !== 2 /* CationPi */)
            { return; }
        var pil1 = piStackingDict[atomSets[index1[i]][0]];
        var pil2 = piStackingDict[atomSets[index2[i]][0]];
        if (!pil1 || !pil2)
            { return; }
        var n = pil1.length;
        for (var j = 0; j < n; ++j) {
            if (pil2.includes(pil1[j])) {
                contactSet.clear(i);
                return;
            }
        }
    });
}
/**
 * Remove ionic interactions between groups that also form
 * a metal coordination between each other
 */
function refineMetalCoordination(structure, contacts) {
    var contactSet = contacts.contactSet;
    var contactStore = contacts.contactStore;
    var features = contacts.features;
    var type = contactStore.type;
    var index1 = contactStore.index1;
    var index2 = contactStore.index2;
    var atomSets = features.atomSets;
    var ionicInteractionDict = {};
    var add = function (idx, i) {
        if (!ionicInteractionDict[idx])
            { ionicInteractionDict[idx] = []; }
        ionicInteractionDict[idx].push(i);
    };
    contactSet.forEach(function (i) {
        if (type[i] !== 1 /* IonicInteraction */)
            { return; }
        atomSets[index1[i]].forEach(function (idx) { return add(idx, i); });
        atomSets[index2[i]].forEach(function (idx) { return add(idx, i); });
    });
    contactSet.forEach(function (i) {
        if (type[i] !== 7 /* MetalCoordination */)
            { return; }
        var iil1 = ionicInteractionDict[atomSets[index1[i]][0]];
        var iil2 = ionicInteractionDict[atomSets[index2[i]][0]];
        if (!iil1 || !iil2)
            { return; }
        var n = iil1.length;
        for (var j = 0; j < n; ++j) {
            if (iil2.includes(iil1[j])) {
                contactSet.clear(iil1[j]);
                return;
            }
        }
    });
}
// TODO: refactor refineSaltBridges, refinePiStacking and refineMetalCoordination to be DRY

/**
 * @file Contact
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var ContactDefaultParams = {
    maxHydrophobicDist: 4.0,
    maxHbondDist: 3.5,
    maxHbondSulfurDist: 4.1,
    maxHbondAccAngle: 45,
    maxHbondDonAngle: 45,
    maxHbondAccPlaneAngle: 90,
    maxHbondDonPlaneAngle: 30,
    maxPiStackingDist: 5.5,
    maxPiStackingOffset: 2.0,
    maxPiStackingAngle: 30,
    maxCationPiDist: 6.0,
    maxCationPiOffset: 2.0,
    maxIonicDist: 5.0,
    maxHalogenBondDist: 4.0,
    maxHalogenBondAngle: 30,
    maxMetalDist: 3.0,
    refineSaltBridges: true,
    masterModelIndex: -1,
    lineOfSightDistFactor: 1.0
};
function isMasterContact(ap1, ap2, masterIdx) {
    return ((ap1.modelIndex === masterIdx && ap2.modelIndex !== masterIdx) ||
        (ap2.modelIndex === masterIdx && ap1.modelIndex !== masterIdx));
}
function invalidAtomContact$1(ap1, ap2, masterIdx) {
    return !isMasterContact(ap1, ap2, masterIdx) && (ap1.modelIndex !== ap2.modelIndex ||
        ap1.residueIndex === ap2.residueIndex ||
        (ap1.altloc && ap2.altloc && ap1.altloc !== ap2.altloc));
}
function createContacts(features) {
    var types = features.types;
    var centers = features.centers;
    var spatialHash = new SpatialHash(centers);
    var contactStore = new ContactStore();
    var featureSet = new BitArray(types.length, false);
    return { features: features, spatialHash: spatialHash, contactStore: contactStore, featureSet: featureSet };
}
function createFrozenContacts(contacts) {
    var ref = contacts.contactStore;
    var index1 = ref.index1;
    var index2 = ref.index2;
    var count = ref.count;
    var adjacencyList = createAdjacencyList({
        nodeArray1: index1,
        nodeArray2: index2,
        edgeCount: count,
        nodeCount: contacts.featureSet.length
    });
    var contactSet = new BitArray(contacts.contactStore.count, true);
    return Object.assign({ adjacencyList: adjacencyList, contactSet: contactSet }, contacts);
}
function calculateFeatures(structure) {
    var features = createFeatures();
    if (Debug)
        { Log.time('calculateFeatures'); }
    addPositiveCharges(structure, features);
    addNegativeCharges(structure, features);
    addAromaticRings(structure, features);
    addHydrogenAcceptors(structure, features);
    addHydrogenDonors(structure, features);
    addWeakHydrogenDonors(structure, features);
    addMetalBinding(structure, features);
    addMetals(structure, features);
    addHydrophobic(structure, features);
    addHalogenAcceptors(structure, features);
    addHalogenDonors(structure, features);
    if (Debug)
        { Log.timeEnd('calculateFeatures'); }
    return features;
}
function calculateContacts(structure, params) {
    if ( params === void 0 ) params = ContactDefaultParams;

    var features = calculateFeatures(structure);
    var contacts = createContacts(features);
    if (Debug)
        { Log.time('calculateContacts'); }
    addChargedContacts(structure, contacts, params);
    addHydrogenBonds(structure, contacts, params);
    addMetalComplexation(structure, contacts, params);
    addHydrophobicContacts(structure, contacts, params);
    addHalogenBonds(structure, contacts, params);
    var frozenContacts = createFrozenContacts(contacts);
    refineLineOfSight(structure, frozenContacts, params);
    refineHydrophobicContacts(structure, frozenContacts);
    if (params.refineSaltBridges)
        { refineSaltBridges(structure, frozenContacts); }
    refinePiStacking(structure, frozenContacts);
    refineMetalCoordination(structure, frozenContacts);
    if (Debug)
        { Log.timeEnd('calculateContacts'); }
    return frozenContacts;
}
function contactTypeName(type) {
    switch (type) {
        case 4 /* HydrogenBond */:
        case 9 /* WaterHydrogenBond */:
        case 10 /* BackboneHydrogenBond */:
            return 'hydrogen bond';
        case 6 /* Hydrophobic */:
            return 'hydrophobic contact';
        case 5 /* HalogenBond */:
            return 'halogen bond';
        case 1 /* IonicInteraction */:
            return 'ionic interaction';
        case 7 /* MetalCoordination */:
            return 'metal coordination';
        case 2 /* CationPi */:
            return 'cation-pi interaction';
        case 3 /* PiStacking */:
            return 'pi-pi stacking';
        case 8 /* WeakHydrogenBond */:
            return 'weak hydrogen bond';
        default:
            return 'unknown contact';
    }
}
var ContactDataDefaultParams = {
    hydrogenBond: true,
    hydrophobic: true,
    halogenBond: true,
    ionicInteraction: true,
    metalCoordination: true,
    cationPi: true,
    piStacking: true,
    weakHydrogenBond: true,
    waterHydrogenBond: true,
    backboneHydrogenBond: true,
    radius: 1,
    filterSele: ''
};
var tmpColor$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */]();
function contactColor(type) {
    switch (type) {
        case 4 /* HydrogenBond */:
        case 9 /* WaterHydrogenBond */:
        case 10 /* BackboneHydrogenBond */:
            return tmpColor$1.setHex(0x2B83BA).toArray();
        case 6 /* Hydrophobic */:
            return tmpColor$1.setHex(0x808080).toArray();
        case 5 /* HalogenBond */:
            return tmpColor$1.setHex(0x40FFBF).toArray();
        case 1 /* IonicInteraction */:
            return tmpColor$1.setHex(0xF0C814).toArray();
        case 7 /* MetalCoordination */:
            return tmpColor$1.setHex(0x8C4099).toArray();
        case 2 /* CationPi */:
            return tmpColor$1.setHex(0xFF8000).toArray();
        case 3 /* PiStacking */:
            return tmpColor$1.setHex(0x8CB366).toArray();
        case 8 /* WeakHydrogenBond */:
            return tmpColor$1.setHex(0xC5DDEC).toArray();
        default:
            return tmpColor$1.setHex(0xCCCCCC).toArray();
    }
}
function getContactData(contacts, structure, params) {
    var p = createParams(params, ContactDataDefaultParams);
    var types = [];
    if (p.hydrogenBond)
        { types.push(4 /* HydrogenBond */); }
    if (p.hydrophobic)
        { types.push(6 /* Hydrophobic */); }
    if (p.halogenBond)
        { types.push(5 /* HalogenBond */); }
    if (p.ionicInteraction)
        { types.push(1 /* IonicInteraction */); }
    if (p.metalCoordination)
        { types.push(7 /* MetalCoordination */); }
    if (p.cationPi)
        { types.push(2 /* CationPi */); }
    if (p.piStacking)
        { types.push(3 /* PiStacking */); }
    if (p.weakHydrogenBond)
        { types.push(8 /* WeakHydrogenBond */); }
    if (p.waterHydrogenBond)
        { types.push(9 /* WaterHydrogenBond */); }
    if (p.backboneHydrogenBond)
        { types.push(10 /* BackboneHydrogenBond */); }
    var features = contacts.features;
    var contactSet = contacts.contactSet;
    var contactStore = contacts.contactStore;
    var centers = features.centers;
    var atomSets = features.atomSets;
    var x = centers.x;
    var y = centers.y;
    var z = centers.z;
    var index1 = contactStore.index1;
    var index2 = contactStore.index2;
    var type = contactStore.type;
    var position1 = [];
    var position2 = [];
    var color = [];
    var radius = [];
    var picking = [];
    var filterSet;
    if (p.filterSele) {
        if (Array.isArray(p.filterSele)) {
            filterSet = p.filterSele.map(function (sele) {
                return structure.getAtomSet(new Selection(sele));
            });
        }
        else {
            filterSet = structure.getAtomSet(new Selection(p.filterSele));
        }
    }
    contactSet.forEach(function (i) {
        var ti = type[i];
        if (!types.includes(ti))
            { return; }
        if (filterSet) {
            var idx1 = atomSets[index1[i]][0];
            var idx2 = atomSets[index2[i]][0];
            if (Array.isArray(filterSet)) {
                if (!(filterSet[0].isSet(idx1) && filterSet[1].isSet(idx2) || (filterSet[1].isSet(idx1) && filterSet[0].isSet(idx2))))
                    { return; }
            }
            else {
                if (!filterSet.isSet(idx1) && !filterSet.isSet(idx2))
                    { return; }
            }
        }
        var k = index1[i];
        var l = index2[i];
        position1.push(x[k], y[k], z[k]);
        position2.push(x[l], y[l], z[l]);
        color.push.apply(color, contactColor(ti));
        radius.push(p.radius);
        picking.push(i);
    });
    return {
        position1: new Float32Array(position1),
        position2: new Float32Array(position2),
        color: new Float32Array(color),
        color2: new Float32Array(color),
        radius: new Float32Array(radius),
        picking: new ContactPicker(picking, contacts, structure)
    };
}
function getLabelData(contactData, params) {
    var position = calculateCenterArray(contactData.position1, contactData.position2);
    var text = [];
    var direction = calculateDirectionArray(contactData.position1, contactData.position2);
    var n = direction.length / 3;
    for (var i = 0; i < n; i++) {
        var j = 3 * i;
        var d = Math.sqrt(Math.pow(direction[j], 2) + Math.pow(direction[j + 1], 2) + Math.pow(direction[j + 2], 2));
        switch (params.unit) {
            case 'angstrom':
                text[i] = d.toFixed(2) + ' ' + String.fromCharCode(0x212B);
                break;
            case 'nm':
                text[i] = (d / 10).toFixed(2) + ' nm';
                break;
            default:
                text[i] = d.toFixed(2);
                break;
        }
    }
    return {
        position: position,
        size: uniformArray(position.length / 3, params.size),
        color: contactData.color,
        text: text
    };
}

/**
 * @file Picker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Picker class
 * @interface
 */
var Picker = function Picker(array) {
    this.array = array;
};

var prototypeAccessors$9 = { type: { configurable: true },data: { configurable: true } };
prototypeAccessors$9.type.get = function () { return ''; };
prototypeAccessors$9.data.get = function () { return {}; };
/**
 * Get the index for the given picking id
 * @param  {Integer} pid - the picking id
 * @return {Integer} the index
 */
Picker.prototype.getIndex = function getIndex (pid) {
    return this.array ? this.array[pid] : pid;
};
/**
 * Get object data
 * @abstract
 * @param  {Integer} pid - the picking id
 * @return {Object} the object data
 */
Picker.prototype.getObject = function getObject (pid) {
    return {};
};
Picker.prototype._applyTransformations = function _applyTransformations (vector, instance, component) {
    if (instance) {
        vector.applyMatrix4(instance.matrix);
    }
    if (component) {
        vector.applyMatrix4(component.matrix);
    }
    return vector;
};
/**
 * Get object position
 * @abstract
 * @param  {Integer} pid - the picking id
 * @return {Vector3} the object position
 */
Picker.prototype._getPosition = function _getPosition (pid) {
    return new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
};
/**
 * Get position for the given picking id
 * @param  {Integer} pid - the picking id
 * @param  {Object} instance - the instance that should be applied
 * @param  {Component} component - the component of the picked object
 * @return {Vector3} the position
 */
Picker.prototype.getPosition = function getPosition (pid, instance, component) {
    return this._applyTransformations(this._getPosition(pid), instance, component);
};

Object.defineProperties( Picker.prototype, prototypeAccessors$9 );
/**
 * Shape picker class
 * @interface
 */
var ShapePicker = /*@__PURE__*/(function (Picker) {
    function ShapePicker(shape) {
        Picker.call(this);
        this.shape = shape;
    }

    if ( Picker ) ShapePicker.__proto__ = Picker;
    ShapePicker.prototype = Object.create( Picker && Picker.prototype );
    ShapePicker.prototype.constructor = ShapePicker;

    var prototypeAccessors$1 = { primitive: { configurable: true },data: { configurable: true },type: { configurable: true } };
    prototypeAccessors$1.primitive.get = function () { return; };
    prototypeAccessors$1.data.get = function () { return this.shape; };
    prototypeAccessors$1.type.get = function () { return this.primitive.type; };
    ShapePicker.prototype.getObject = function getObject (pid) {
        return this.primitive.objectFromShape(this.shape, this.getIndex(pid));
    };
    ShapePicker.prototype._getPosition = function _getPosition (pid) {
        return this.primitive.positionFromShape(this.shape, this.getIndex(pid));
    };

    Object.defineProperties( ShapePicker.prototype, prototypeAccessors$1 );

    return ShapePicker;
}(Picker));
//
var CylinderPicker = /*@__PURE__*/(function (ShapePicker) {
    function CylinderPicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) CylinderPicker.__proto__ = ShapePicker;
    CylinderPicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    CylinderPicker.prototype.constructor = CylinderPicker;

    var prototypeAccessors$2 = { primitive: { configurable: true } };

    prototypeAccessors$2.primitive.get = function () { return CylinderPrimitive; };

    Object.defineProperties( CylinderPicker.prototype, prototypeAccessors$2 );

    return CylinderPicker;
}(ShapePicker));
var ArrowPicker = /*@__PURE__*/(function (ShapePicker) {
    function ArrowPicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) ArrowPicker.__proto__ = ShapePicker;
    ArrowPicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    ArrowPicker.prototype.constructor = ArrowPicker;

    var prototypeAccessors$3 = { primitive: { configurable: true } };

    prototypeAccessors$3.primitive.get = function () { return ArrowPrimitive; };

    Object.defineProperties( ArrowPicker.prototype, prototypeAccessors$3 );

    return ArrowPicker;
}(ShapePicker));
var AtomPicker = /*@__PURE__*/(function (Picker) {
    function AtomPicker(array, structure) {
        Picker.call(this, array);
        this.structure = structure;
    }

    if ( Picker ) AtomPicker.__proto__ = Picker;
    AtomPicker.prototype = Object.create( Picker && Picker.prototype );
    AtomPicker.prototype.constructor = AtomPicker;

    var prototypeAccessors$4 = { type: { configurable: true },data: { configurable: true } };
    prototypeAccessors$4.type.get = function () { return 'atom'; };
    prototypeAccessors$4.data.get = function () { return this.structure; };
    AtomPicker.prototype.getObject = function getObject (pid) {
        return this.structure.getAtomProxy(this.getIndex(pid));
    };
    AtomPicker.prototype._getPosition = function _getPosition (pid) {
        return new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().copy(this.getObject(pid));
    };

    Object.defineProperties( AtomPicker.prototype, prototypeAccessors$4 );

    return AtomPicker;
}(Picker));
var AxesPicker = /*@__PURE__*/(function (Picker) {
    function AxesPicker(axes) {
        Picker.call(this);
        this.axes = axes;
    }

    if ( Picker ) AxesPicker.__proto__ = Picker;
    AxesPicker.prototype = Object.create( Picker && Picker.prototype );
    AxesPicker.prototype.constructor = AxesPicker;

    var prototypeAccessors$5 = { type: { configurable: true },data: { configurable: true } };
    prototypeAccessors$5.type.get = function () { return 'axes'; };
    prototypeAccessors$5.data.get = function () { return this.axes; };
    AxesPicker.prototype.getObject = function getObject ( /* pid */) {
        return {
            axes: this.axes
        };
    };
    AxesPicker.prototype._getPosition = function _getPosition ( /* pid */) {
        return this.axes.center.clone();
    };

    Object.defineProperties( AxesPicker.prototype, prototypeAccessors$5 );

    return AxesPicker;
}(Picker));
var BondPicker = /*@__PURE__*/(function (Picker) {
    function BondPicker(array, structure, bondStore) {
        Picker.call(this, array);
        this.structure = structure;
        this.bondStore = bondStore || structure.bondStore;
    }

    if ( Picker ) BondPicker.__proto__ = Picker;
    BondPicker.prototype = Object.create( Picker && Picker.prototype );
    BondPicker.prototype.constructor = BondPicker;

    var prototypeAccessors$6 = { type: { configurable: true },data: { configurable: true } };
    prototypeAccessors$6.type.get = function () { return 'bond'; };
    prototypeAccessors$6.data.get = function () { return this.structure; };
    BondPicker.prototype.getObject = function getObject (pid) {
        var bp = this.structure.getBondProxy(this.getIndex(pid));
        bp.bondStore = this.bondStore;
        return bp;
    };
    BondPicker.prototype._getPosition = function _getPosition (pid) {
        var b = this.getObject(pid);
        return new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]()
            .copy(b.atom1)
            .add(b.atom2)
            .multiplyScalar(0.5);
    };

    Object.defineProperties( BondPicker.prototype, prototypeAccessors$6 );

    return BondPicker;
}(Picker));
var ContactPicker = /*@__PURE__*/(function (Picker) {
    function ContactPicker(array, contacts, structure) {
        Picker.call(this, array);
        this.contacts = contacts;
        this.structure = structure;
    }

    if ( Picker ) ContactPicker.__proto__ = Picker;
    ContactPicker.prototype = Object.create( Picker && Picker.prototype );
    ContactPicker.prototype.constructor = ContactPicker;

    var prototypeAccessors$7 = { type: { configurable: true },data: { configurable: true } };
    prototypeAccessors$7.type.get = function () { return 'contact'; };
    prototypeAccessors$7.data.get = function () { return this.contacts; };
    ContactPicker.prototype.getObject = function getObject (pid) {
        var idx = this.getIndex(pid);
        var ref = this.contacts;
        var features = ref.features;
        var contactStore = ref.contactStore;
        var centers = features.centers;
        var atomSets = features.atomSets;
        var x = centers.x;
        var y = centers.y;
        var z = centers.z;
        var index1 = contactStore.index1;
        var index2 = contactStore.index2;
        var type = contactStore.type;
        var k = index1[idx];
        var l = index2[idx];
        return {
            center1: new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](x[k], y[k], z[k]),
            center2: new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](x[l], y[l], z[l]),
            atom1: this.structure.getAtomProxy(atomSets[k][0]),
            atom2: this.structure.getAtomProxy(atomSets[l][0]),
            type: contactTypeName(type[idx])
        };
    };
    ContactPicker.prototype._getPosition = function _getPosition (pid) {
        var ref = this.getObject(pid);
        var center1 = ref.center1;
        var center2 = ref.center2;
        return new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().addVectors(center1, center2).multiplyScalar(0.5);
    };

    Object.defineProperties( ContactPicker.prototype, prototypeAccessors$7 );

    return ContactPicker;
}(Picker));
var ConePicker = /*@__PURE__*/(function (ShapePicker) {
    function ConePicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) ConePicker.__proto__ = ShapePicker;
    ConePicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    ConePicker.prototype.constructor = ConePicker;

    var prototypeAccessors$8 = { primitive: { configurable: true } };

    prototypeAccessors$8.primitive.get = function () { return ConePrimitive; };

    Object.defineProperties( ConePicker.prototype, prototypeAccessors$8 );

    return ConePicker;
}(ShapePicker));
var ClashPicker = /*@__PURE__*/(function (Picker) {
    function ClashPicker(array, validation, structure) {
        Picker.call(this, array);
        this.validation = validation;
        this.structure = structure;
    }

    if ( Picker ) ClashPicker.__proto__ = Picker;
    ClashPicker.prototype = Object.create( Picker && Picker.prototype );
    ClashPicker.prototype.constructor = ClashPicker;

    var prototypeAccessors$9 = { type: { configurable: true },data: { configurable: true } };
    prototypeAccessors$9.type.get = function () { return 'clash'; };
    prototypeAccessors$9.data.get = function () { return this.validation; };
    ClashPicker.prototype.getObject = function getObject (pid) {
        var val = this.validation;
        var idx = this.getIndex(pid);
        return {
            validation: val,
            index: idx,
            clash: val.clashArray[idx]
        };
    };
    ClashPicker.prototype._getAtomProxyFromSele = function _getAtomProxyFromSele (sele) {
        var selection = new Selection(sele);
        var idx = this.structure.getAtomIndices(selection)[0];
        return this.structure.getAtomProxy(idx);
    };
    ClashPicker.prototype._getPosition = function _getPosition (pid) {
        var clash = this.getObject(pid).clash;
        var ap1 = this._getAtomProxyFromSele(clash.sele1);
        var ap2 = this._getAtomProxyFromSele(clash.sele2);
        return new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().copy(ap1).add(ap2).multiplyScalar(0.5);
    };

    Object.defineProperties( ClashPicker.prototype, prototypeAccessors$9 );

    return ClashPicker;
}(Picker));
var DistancePicker = /*@__PURE__*/(function (BondPicker) {
    function DistancePicker () {
        BondPicker.apply(this, arguments);
    }

    if ( BondPicker ) DistancePicker.__proto__ = BondPicker;
    DistancePicker.prototype = Object.create( BondPicker && BondPicker.prototype );
    DistancePicker.prototype.constructor = DistancePicker;

    var prototypeAccessors$10 = { type: { configurable: true } };

    prototypeAccessors$10.type.get = function () { return 'distance'; };

    Object.defineProperties( DistancePicker.prototype, prototypeAccessors$10 );

    return DistancePicker;
}(BondPicker));
var EllipsoidPicker = /*@__PURE__*/(function (ShapePicker) {
    function EllipsoidPicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) EllipsoidPicker.__proto__ = ShapePicker;
    EllipsoidPicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    EllipsoidPicker.prototype.constructor = EllipsoidPicker;

    var prototypeAccessors$11 = { primitive: { configurable: true } };

    prototypeAccessors$11.primitive.get = function () { return EllipsoidPrimitive; };

    Object.defineProperties( EllipsoidPicker.prototype, prototypeAccessors$11 );

    return EllipsoidPicker;
}(ShapePicker));
var OctahedronPicker = /*@__PURE__*/(function (ShapePicker) {
    function OctahedronPicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) OctahedronPicker.__proto__ = ShapePicker;
    OctahedronPicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    OctahedronPicker.prototype.constructor = OctahedronPicker;

    var prototypeAccessors$12 = { primitive: { configurable: true } };

    prototypeAccessors$12.primitive.get = function () { return OctahedronPrimitive; };

    Object.defineProperties( OctahedronPicker.prototype, prototypeAccessors$12 );

    return OctahedronPicker;
}(ShapePicker));
var BoxPicker = /*@__PURE__*/(function (ShapePicker) {
    function BoxPicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) BoxPicker.__proto__ = ShapePicker;
    BoxPicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    BoxPicker.prototype.constructor = BoxPicker;

    var prototypeAccessors$13 = { primitive: { configurable: true } };

    prototypeAccessors$13.primitive.get = function () { return BoxPrimitive; };

    Object.defineProperties( BoxPicker.prototype, prototypeAccessors$13 );

    return BoxPicker;
}(ShapePicker));
var IgnorePicker = /*@__PURE__*/(function (Picker) {
    function IgnorePicker () {
        Picker.apply(this, arguments);
    }

    if ( Picker ) IgnorePicker.__proto__ = Picker;
    IgnorePicker.prototype = Object.create( Picker && Picker.prototype );
    IgnorePicker.prototype.constructor = IgnorePicker;

    var prototypeAccessors$14 = { type: { configurable: true } };

    prototypeAccessors$14.type.get = function () { return 'ignore'; };

    Object.defineProperties( IgnorePicker.prototype, prototypeAccessors$14 );

    return IgnorePicker;
}(Picker));
var MeshPicker = /*@__PURE__*/(function (ShapePicker) {
    function MeshPicker(shape, mesh) {
        ShapePicker.call(this, shape);
        this.mesh = mesh;
    }

    if ( ShapePicker ) MeshPicker.__proto__ = ShapePicker;
    MeshPicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    MeshPicker.prototype.constructor = MeshPicker;

    var prototypeAccessors$15 = { type: { configurable: true } };
    prototypeAccessors$15.type.get = function () { return 'mesh'; };
    MeshPicker.prototype.getObject = function getObject ( /* pid */) {
        var m = this.mesh;
        return {
            shape: this.shape,
            name: m.name,
            serial: m.serial
        };
    };
    MeshPicker.prototype._getPosition = function _getPosition ( /* pid */) {
        if (!this.__position) {
            this.__position = calculateMeanVector3(this.mesh.position);
        }
        return this.__position;
    };

    Object.defineProperties( MeshPicker.prototype, prototypeAccessors$15 );

    return MeshPicker;
}(ShapePicker));
var SpherePicker = /*@__PURE__*/(function (ShapePicker) {
    function SpherePicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) SpherePicker.__proto__ = ShapePicker;
    SpherePicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    SpherePicker.prototype.constructor = SpherePicker;

    var prototypeAccessors$16 = { primitive: { configurable: true } };

    prototypeAccessors$16.primitive.get = function () { return SpherePrimitive; };

    Object.defineProperties( SpherePicker.prototype, prototypeAccessors$16 );

    return SpherePicker;
}(ShapePicker));
var SurfacePicker = /*@__PURE__*/(function (Picker) {
    function SurfacePicker(array, surface) {
        Picker.call(this, array);
        this.surface = surface;
    }

    if ( Picker ) SurfacePicker.__proto__ = Picker;
    SurfacePicker.prototype = Object.create( Picker && Picker.prototype );
    SurfacePicker.prototype.constructor = SurfacePicker;

    var prototypeAccessors$17 = { type: { configurable: true },data: { configurable: true } };
    prototypeAccessors$17.type.get = function () { return 'surface'; };
    prototypeAccessors$17.data.get = function () { return this.surface; };
    SurfacePicker.prototype.getObject = function getObject (pid) {
        return {
            surface: this.surface,
            index: this.getIndex(pid)
        };
    };
    SurfacePicker.prototype._getPosition = function _getPosition ( /* pid */) {
        return this.surface.center.clone();
    };

    Object.defineProperties( SurfacePicker.prototype, prototypeAccessors$17 );

    return SurfacePicker;
}(Picker));
var TetrahedronPicker = /*@__PURE__*/(function (ShapePicker) {
    function TetrahedronPicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) TetrahedronPicker.__proto__ = ShapePicker;
    TetrahedronPicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    TetrahedronPicker.prototype.constructor = TetrahedronPicker;

    var prototypeAccessors$18 = { primitive: { configurable: true } };

    prototypeAccessors$18.primitive.get = function () { return TetrahedronPrimitive; };

    Object.defineProperties( TetrahedronPicker.prototype, prototypeAccessors$18 );

    return TetrahedronPicker;
}(ShapePicker));
var TorusPicker = /*@__PURE__*/(function (ShapePicker) {
    function TorusPicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) TorusPicker.__proto__ = ShapePicker;
    TorusPicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    TorusPicker.prototype.constructor = TorusPicker;

    var prototypeAccessors$19 = { primitive: { configurable: true } };

    prototypeAccessors$19.primitive.get = function () { return TorusPrimitive; };

    Object.defineProperties( TorusPicker.prototype, prototypeAccessors$19 );

    return TorusPicker;
}(ShapePicker));
var UnitcellPicker = /*@__PURE__*/(function (Picker) {
    function UnitcellPicker(unitcell, structure) {
        Picker.call(this);
        this.unitcell = unitcell;
        this.structure = structure;
    }

    if ( Picker ) UnitcellPicker.__proto__ = Picker;
    UnitcellPicker.prototype = Object.create( Picker && Picker.prototype );
    UnitcellPicker.prototype.constructor = UnitcellPicker;

    var prototypeAccessors$20 = { type: { configurable: true },data: { configurable: true } };
    prototypeAccessors$20.type.get = function () { return 'unitcell'; };
    prototypeAccessors$20.data.get = function () { return this.unitcell; };
    UnitcellPicker.prototype.getObject = function getObject ( /* pid */) {
        return {
            unitcell: this.unitcell,
            structure: this.structure
        };
    };
    UnitcellPicker.prototype._getPosition = function _getPosition ( /* pid */) {
        return this.unitcell.getCenter(this.structure);
    };

    Object.defineProperties( UnitcellPicker.prototype, prototypeAccessors$20 );

    return UnitcellPicker;
}(Picker));
var UnknownPicker = /*@__PURE__*/(function (Picker) {
    function UnknownPicker () {
        Picker.apply(this, arguments);
    }

    if ( Picker ) UnknownPicker.__proto__ = Picker;
    UnknownPicker.prototype = Object.create( Picker && Picker.prototype );
    UnknownPicker.prototype.constructor = UnknownPicker;

    var prototypeAccessors$21 = { type: { configurable: true } };

    prototypeAccessors$21.type.get = function () { return 'unknown'; };

    Object.defineProperties( UnknownPicker.prototype, prototypeAccessors$21 );

    return UnknownPicker;
}(Picker));
var VolumePicker = /*@__PURE__*/(function (Picker) {
    function VolumePicker(array, volume) {
        Picker.call(this, array);
        this.volume = volume;
    }

    if ( Picker ) VolumePicker.__proto__ = Picker;
    VolumePicker.prototype = Object.create( Picker && Picker.prototype );
    VolumePicker.prototype.constructor = VolumePicker;

    var prototypeAccessors$22 = { type: { configurable: true },data: { configurable: true } };
    prototypeAccessors$22.type.get = function () { return 'volume'; };
    prototypeAccessors$22.data.get = function () { return this.volume; };
    VolumePicker.prototype.getObject = function getObject (pid) {
        var vol = this.volume;
        var idx = this.getIndex(pid);
        return {
            volume: vol,
            index: idx,
            value: vol.data[idx]
        };
    };
    VolumePicker.prototype._getPosition = function _getPosition (pid) {
        var dp = this.volume.position;
        var idx = this.getIndex(pid);
        return new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](dp[idx * 3], dp[idx * 3 + 1], dp[idx * 3 + 2]);
    };

    Object.defineProperties( VolumePicker.prototype, prototypeAccessors$22 );

    return VolumePicker;
}(Picker));
var SlicePicker = /*@__PURE__*/(function (VolumePicker) {
    function SlicePicker () {
        VolumePicker.apply(this, arguments);
    }

    if ( VolumePicker ) SlicePicker.__proto__ = VolumePicker;
    SlicePicker.prototype = Object.create( VolumePicker && VolumePicker.prototype );
    SlicePicker.prototype.constructor = SlicePicker;

    var prototypeAccessors$23 = { type: { configurable: true } };

    prototypeAccessors$23.type.get = function () { return 'slice'; };

    Object.defineProperties( SlicePicker.prototype, prototypeAccessors$23 );

    return SlicePicker;
}(VolumePicker));
var PointPicker = /*@__PURE__*/(function (ShapePicker) {
    function PointPicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) PointPicker.__proto__ = ShapePicker;
    PointPicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    PointPicker.prototype.constructor = PointPicker;

    var prototypeAccessors$24 = { primitive: { configurable: true } };

    prototypeAccessors$24.primitive.get = function () { return PointPrimitive; };

    Object.defineProperties( PointPicker.prototype, prototypeAccessors$24 );

    return PointPicker;
}(ShapePicker));
var WidelinePicker = /*@__PURE__*/(function (ShapePicker) {
    function WidelinePicker () {
        ShapePicker.apply(this, arguments);
    }

    if ( ShapePicker ) WidelinePicker.__proto__ = ShapePicker;
    WidelinePicker.prototype = Object.create( ShapePicker && ShapePicker.prototype );
    WidelinePicker.prototype.constructor = WidelinePicker;

    var prototypeAccessors$25 = { primitive: { configurable: true } };

    prototypeAccessors$25.primitive.get = function () { return WidelinePrimitive; };

    Object.defineProperties( WidelinePicker.prototype, prototypeAccessors$25 );

    return WidelinePicker;
}(ShapePicker));
PickerRegistry.add('arrow', ArrowPicker);
PickerRegistry.add('box', BoxPicker);
PickerRegistry.add('cone', ConePicker);
PickerRegistry.add('cylinder', CylinderPicker);
PickerRegistry.add('ellipsoid', EllipsoidPicker);
PickerRegistry.add('octahedron', OctahedronPicker);
PickerRegistry.add('sphere', SpherePicker);
PickerRegistry.add('tetrahedron', TetrahedronPicker);
PickerRegistry.add('torus', TorusPicker);
PickerRegistry.add('point', PointPicker);
PickerRegistry.add('wideline', WidelinePicker);

/**
 * @file Marching Cubes
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getEdgeTable() {
    return new Uint32Array([
        0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c,
        0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
        0x190, 0x99, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c,
        0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
        0x230, 0x339, 0x33, 0x13a, 0x636, 0x73f, 0x435, 0x53c,
        0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
        0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6, 0x6af, 0x5a5, 0x4ac,
        0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
        0x460, 0x569, 0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c,
        0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
        0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff, 0x3f5, 0x2fc,
        0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
        0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55, 0x15c,
        0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
        0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc,
        0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
        0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc,
        0xcc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
        0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c,
        0x15c, 0x55, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
        0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc,
        0x2fc, 0x3f5, 0xff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
        0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c,
        0x36c, 0x265, 0x16f, 0x66, 0x76a, 0x663, 0x569, 0x460,
        0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac,
        0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa, 0x1a3, 0x2a9, 0x3a0,
        0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c,
        0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33, 0x339, 0x230,
        0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c,
        0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99, 0x190,
        0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c,
        0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0
    ]);
}
function getTriTable() {
    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
    ]);
}
// Triangles are constructed between points on cube edges.
// allowedContours[edge1][edge1] indicates which lines from a given
// triangle should be shown in line mode.
// Values are bitmasks:
// In loop over cubes we keep another bitmask indicating whether our current
// cell is the first x-value (1),
// first y-value (2) or first z-value (4) of the current loop.
// We draw all lines on leading faces but only draw trailing face lines the first
// time through the loop
// A value of 8 below means the edge is always drawn (leading face)
// E.g. the first row, lines between edge0 and other edges in the bottom
// x-y plane are only drawn for the first value of z, edges in the
// x-z plane are only drawn for the first value of y. No other lines
// are drawn as they're redundant
// The line between edge 1 and 5 is always drawn as it's on the leading edge
function getAllowedContours() {
    return [
        [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]
    ];
}
function MarchingCubes(field, nx, ny, nz, atomindex) {
    // Based on alteredq / http://alteredqualia.com/
    // port of greggman's ThreeD version of marching cubes to Three.js
    // http://webglsamples.googlecode.com/hg/blob/blob.html
    //
    // Adapted for NGL by Alexander Rose
    var isolevel = 0;
    var noNormals = false;
    var contour = false;
    var wrap = false;
    var isNegativeIso = false;
    var normalFactor = -1;
    var n = nx * ny * nz;
    // deltas
    var yd = nx;
    var zd = nx * ny;
    var normalCache, vertexIndex;
    var count, icount;
    var ilist = new Int32Array(12);
    var positionArray = [];
    var normalArray = [];
    var indexArray = [];
    var atomindexArray = [];
    var edgeTable = getEdgeTable();
    var triTable = getTriTable();
    var allowedContours = getAllowedContours();
    var mx, my, mz;
    //
    this.triangulate = function (_isolevel, _noNormals, _box, _contour, _wrap) {
        isolevel = _isolevel;
        isNegativeIso = isolevel < 0.0;
        contour = _contour;
        wrap = _wrap;
        // Normals currently disabled in contour mode for performance (unused)
        noNormals = _noNormals || contour;
        if (!noNormals) {
            normalFactor = isolevel > 0 ? -1.0 : 1.0;
            if (!normalCache) {
                normalCache = new Float32Array(n * 3);
            }
        }
        var vIndexLength = n * 3;
        if (!vertexIndex || vertexIndex.length !== vIndexLength) {
            vertexIndex = new Int32Array(vIndexLength);
        }
        count = 0;
        icount = 0;
        if (_box !== undefined) {
            var min = _box[0].map(Math.round);
            var max = _box[1].map(Math.round);
            mx = nx * Math.ceil(Math.abs(min[0]) / nx);
            my = ny * Math.ceil(Math.abs(min[1]) / ny);
            mz = nz * Math.ceil(Math.abs(min[2]) / nz);
            triangulate(min[0], min[1], min[2], max[0], max[1], max[2]);
        }
        else {
            mx = my = mz = 0;
            triangulate();
        }
        positionArray.length = count * 3;
        if (!noNormals)
            { normalArray.length = count * 3; }
        indexArray.length = icount;
        if (atomindex)
            { atomindexArray.length = count; }
        return {
            position: new Float32Array(positionArray),
            normal: noNormals ? undefined : new Float32Array(normalArray),
            index: getUintArray(indexArray, positionArray.length / 3),
            atomindex: atomindex ? new Int32Array(atomindexArray) : undefined,
            contour: contour
        };
    };
    // polygonization
    function lerp(a, b, t) { return a + (b - a) * t; }
    function index(x, y, z) {
        x = (x + mx) % nx;
        y = (y + my) % ny;
        z = (z + mz) % nz;
        return ((zd * z) + yd * y) + x;
    }
    function VIntX(q, offset, x, y, z, valp1, valp2) {
        var _q = 3 * q;
        if (vertexIndex[_q] < 0) {
            var mu = (isolevel - valp1) / (valp2 - valp1);
            var nc = normalCache;
            var c = count * 3;
            positionArray[c + 0] = x + mu;
            positionArray[c + 1] = y;
            positionArray[c + 2] = z;
            if (!noNormals) {
                var q3 = q * 3;
                normalArray[c] = normalFactor * lerp(nc[q3], nc[q3 + 3], mu);
                normalArray[c + 1] = normalFactor * lerp(nc[q3 + 1], nc[q3 + 4], mu);
                normalArray[c + 2] = normalFactor * lerp(nc[q3 + 2], nc[q3 + 5], mu);
            }
            if (atomindex)
                { atomindexArray[count] = atomindex[q + Math.round(mu)]; }
            vertexIndex[_q] = count;
            ilist[offset] = count;
            count += 1;
        }
        else {
            ilist[offset] = vertexIndex[_q];
        }
    }
    function VIntY(q, offset, x, y, z, valp1, valp2) {
        var _q = 3 * q + 1;
        if (vertexIndex[_q] < 0) {
            var mu = (isolevel - valp1) / (valp2 - valp1);
            var nc = normalCache;
            var c = count * 3;
            positionArray[c] = x;
            positionArray[c + 1] = y + mu;
            positionArray[c + 2] = z;
            if (!noNormals) {
                var q3 = q * 3;
                var q6 = q3 + yd * 3;
                normalArray[c] = normalFactor * lerp(nc[q3], nc[q6], mu);
                normalArray[c + 1] = normalFactor * lerp(nc[q3 + 1], nc[q6 + 1], mu);
                normalArray[c + 2] = normalFactor * lerp(nc[q3 + 2], nc[q6 + 2], mu);
            }
            if (atomindex)
                { atomindexArray[count] = atomindex[q + Math.round(mu) * yd]; }
            vertexIndex[_q] = count;
            ilist[offset] = count;
            count += 1;
        }
        else {
            ilist[offset] = vertexIndex[_q];
        }
    }
    function VIntZ(q, offset, x, y, z, valp1, valp2) {
        var _q = 3 * q + 2;
        if (vertexIndex[_q] < 0) {
            var mu = (isolevel - valp1) / (valp2 - valp1);
            var nc = normalCache;
            var c = count * 3;
            positionArray[c] = x;
            positionArray[c + 1] = y;
            positionArray[c + 2] = z + mu;
            if (!noNormals) {
                var q3 = q * 3;
                var q6 = q3 + zd * 3;
                normalArray[c] = normalFactor * lerp(nc[q3], nc[q6], mu);
                normalArray[c + 1] = normalFactor * lerp(nc[q3 + 1], nc[q6 + 1], mu);
                normalArray[c + 2] = normalFactor * lerp(nc[q3 + 2], nc[q6 + 2], mu);
            }
            if (atomindex)
                { atomindexArray[count] = atomindex[q + Math.round(mu) * zd]; }
            vertexIndex[_q] = count;
            ilist[offset] = count;
            count += 1;
        }
        else {
            ilist[offset] = vertexIndex[_q];
        }
    }
    function compNorm(q) {
        var q3 = q * 3;
        if (normalCache[q3] === 0.0) {
            normalCache[q3] = field[(q - 1 + n) % n] - field[(q + 1) % n];
            normalCache[q3 + 1] = field[(q - yd + n) % n] - field[(q + yd) % n];
            normalCache[q3 + 2] = field[(q - zd + n) % n] - field[(q + zd) % n];
        }
    }
    function polygonize(fx, fy, fz, q, edgeFilter) {
        // cache indices
        var q1;
        var qy;
        var qz;
        var q1y;
        var q1z;
        var qyz;
        var q1yz;
        if (wrap) {
            q = index(fx, fy, fz);
            q1 = index(fx + 1, fy, fz);
            qy = index(fx, fy + 1, fz);
            qz = index(fx, fy, fz + 1);
            q1y = index(fx + 1, fy + 1, fz);
            q1z = index(fx + 1, fy, fz + 1);
            qyz = index(fx, fy + 1, fz + 1);
            q1yz = index(fx + 1, fy + 1, fz + 1);
        }
        else {
            q1 = q + 1;
            qy = q + yd;
            qz = q + zd;
            q1y = qy + 1;
            q1z = qz + 1;
            qyz = qy + zd;
            q1yz = qyz + 1;
        }
        var cubeindex = 0;
        var field0 = field[q];
        var field1 = field[q1];
        var field2 = field[qy];
        var field3 = field[q1y];
        var field4 = field[qz];
        var field5 = field[q1z];
        var field6 = field[qyz];
        var field7 = field[q1yz];
        if (field0 < isolevel)
            { cubeindex |= 1; }
        if (field1 < isolevel)
            { cubeindex |= 2; }
        if (field2 < isolevel)
            { cubeindex |= 8; }
        if (field3 < isolevel)
            { cubeindex |= 4; }
        if (field4 < isolevel)
            { cubeindex |= 16; }
        if (field5 < isolevel)
            { cubeindex |= 32; }
        if (field6 < isolevel)
            { cubeindex |= 128; }
        if (field7 < isolevel)
            { cubeindex |= 64; }
        // if cube is entirely in/out of the surface - bail, nothing to draw
        var bits = edgeTable[cubeindex];
        if (bits === 0)
            { return 0; }
        var fx2 = fx + 1;
        var fy2 = fy + 1;
        var fz2 = fz + 1;
        // top of the cube
        if (bits & 1) {
            if (!noNormals) {
                compNorm(q);
                compNorm(q1);
            }
            VIntX(q, 0, fx, fy, fz, field0, field1);
        }
        if (bits & 2) {
            if (!noNormals) {
                compNorm(q1);
                compNorm(q1y);
            }
            VIntY(q1, 1, fx2, fy, fz, field1, field3);
        }
        if (bits & 4) {
            if (!noNormals) {
                compNorm(qy);
                compNorm(q1y);
            }
            VIntX(qy, 2, fx, fy2, fz, field2, field3);
        }
        if (bits & 8) {
            if (!noNormals) {
                compNorm(q);
                compNorm(qy);
            }
            VIntY(q, 3, fx, fy, fz, field0, field2);
        }
        // bottom of the cube
        if (bits & 16) {
            if (!noNormals) {
                compNorm(qz);
                compNorm(q1z);
            }
            VIntX(qz, 4, fx, fy, fz2, field4, field5);
        }
        if (bits & 32) {
            if (!noNormals) {
                compNorm(q1z);
                compNorm(q1yz);
            }
            VIntY(q1z, 5, fx2, fy, fz2, field5, field7);
        }
        if (bits & 64) {
            if (!noNormals) {
                compNorm(qyz);
                compNorm(q1yz);
            }
            VIntX(qyz, 6, fx, fy2, fz2, field6, field7);
        }
        if (bits & 128) {
            if (!noNormals) {
                compNorm(qz);
                compNorm(qyz);
            }
            VIntY(qz, 7, fx, fy, fz2, field4, field6);
        }
        // vertical lines of the cube
        if (bits & 256) {
            if (!noNormals) {
                compNorm(q);
                compNorm(qz);
            }
            VIntZ(q, 8, fx, fy, fz, field0, field4);
        }
        if (bits & 512) {
            if (!noNormals) {
                compNorm(q1);
                compNorm(q1z);
            }
            VIntZ(q1, 9, fx2, fy, fz, field1, field5);
        }
        if (bits & 1024) {
            if (!noNormals) {
                compNorm(q1y);
                compNorm(q1yz);
            }
            VIntZ(q1y, 10, fx2, fy2, fz, field3, field7);
        }
        if (bits & 2048) {
            if (!noNormals) {
                compNorm(qy);
                compNorm(qyz);
            }
            VIntZ(qy, 11, fx, fy2, fz, field2, field6);
        }
        var triIndex = cubeindex << 4; // re-purpose cubeindex into an offset into triTable
        var e1;
        var e2;
        var e3;
        var i = 0;
        // here is where triangles are created
        while (triTable[triIndex + i] !== -1) {
            e1 = triTable[triIndex + i];
            e2 = triTable[triIndex + i + 1];
            e3 = triTable[triIndex + i + 2];
            if (contour) {
                if (allowedContours[e1][e2] & edgeFilter) {
                    indexArray[icount++] = ilist[e1];
                    indexArray[icount++] = ilist[e2];
                }
                if (allowedContours[e2][e3] & edgeFilter) {
                    indexArray[icount++] = ilist[e2];
                    indexArray[icount++] = ilist[e3];
                }
                if (allowedContours[e1][e3] & edgeFilter) {
                    indexArray[icount++] = ilist[e1];
                    indexArray[icount++] = ilist[e3];
                }
            }
            else {
                indexArray[icount++] = ilist[isNegativeIso ? e1 : e2];
                indexArray[icount++] = ilist[isNegativeIso ? e2 : e1];
                indexArray[icount++] = ilist[e3];
            }
            i += 3;
        }
    }
    function triangulate(xBeg, yBeg, zBeg, xEnd, yEnd, zEnd) {
        var q;
        var q3;
        var x;
        var y;
        var z;
        var yOffset;
        var zOffset;
        xBeg = xBeg !== undefined ? xBeg : 0;
        yBeg = yBeg !== undefined ? yBeg : 0;
        zBeg = zBeg !== undefined ? zBeg : 0;
        xEnd = xEnd !== undefined ? xEnd : nx - 1;
        yEnd = yEnd !== undefined ? yEnd : ny - 1;
        zEnd = zEnd !== undefined ? zEnd : nz - 1;
        if (!wrap) {
            if (noNormals) {
                xBeg = Math.max(0, xBeg);
                yBeg = Math.max(0, yBeg);
                zBeg = Math.max(0, zBeg);
                xEnd = Math.min(nx - 1, xEnd);
                yEnd = Math.min(ny - 1, yEnd);
                zEnd = Math.min(nz - 1, zEnd);
            }
            else {
                xBeg = Math.max(1, xBeg);
                yBeg = Math.max(1, yBeg);
                zBeg = Math.max(1, zBeg);
                xEnd = Math.min(nx - 2, xEnd);
                yEnd = Math.min(ny - 2, yEnd);
                zEnd = Math.min(nz - 2, zEnd);
            }
        }
        var xBeg2, yBeg2, zBeg2, xEnd2, yEnd2, zEnd2;
        if (!wrap) {
            // init part of the vertexIndex
            // (takes a significant amount of time to do for all)
            xBeg2 = Math.max(0, xBeg - 2);
            yBeg2 = Math.max(0, yBeg - 2);
            zBeg2 = Math.max(0, zBeg - 2);
            xEnd2 = Math.min(nx, xEnd + 2);
            yEnd2 = Math.min(ny, yEnd + 2);
            zEnd2 = Math.min(nz, zEnd + 2);
            for (z = zBeg2; z < zEnd2; ++z) {
                zOffset = zd * z;
                for (y = yBeg2; y < yEnd2; ++y) {
                    yOffset = zOffset + yd * y;
                    for (x = xBeg2; x < xEnd2; ++x) {
                        q = 3 * (yOffset + x);
                        vertexIndex[q] = -1;
                        vertexIndex[q + 1] = -1;
                        vertexIndex[q + 2] = -1;
                    }
                }
            }
        }
        else {
            xBeg2 = xBeg - 2;
            yBeg2 = yBeg - 2;
            zBeg2 = zBeg - 2;
            xEnd2 = xEnd + 2;
            yEnd2 = yEnd + 2;
            zEnd2 = zEnd + 2;
            for (z = zBeg2; z < zEnd2; ++z) {
                for (y = yBeg2; y < yEnd2; ++y) {
                    for (x = xBeg2; x < xEnd2; ++x) {
                        q3 = index(x, y, z) * 3;
                        vertexIndex[q3] = -1;
                        vertexIndex[q3 + 1] = -1;
                        vertexIndex[q3 + 2] = -1;
                    }
                }
            }
        }
        if (!wrap) {
            // clip space where the isovalue is too low
            var __break;
            var __xBeg = xBeg;
            var __yBeg = yBeg;
            var __zBeg = zBeg;
            var __xEnd = xEnd;
            var __yEnd = yEnd;
            var __zEnd = zEnd;
            __break = false;
            for (z = zBeg; z < zEnd; ++z) {
                for (y = yBeg; y < yEnd; ++y) {
                    for (x = xBeg; x < xEnd; ++x) {
                        q = ((nx * ny) * z) + (nx * y) + x;
                        if (field[q] >= isolevel) {
                            __zBeg = z;
                            __break = true;
                            break;
                        }
                    }
                    if (__break)
                        { break; }
                }
                if (__break)
                    { break; }
            }
            __break = false;
            for (y = yBeg; y < yEnd; ++y) {
                for (z = __zBeg; z < zEnd; ++z) {
                    for (x = xBeg; x < xEnd; ++x) {
                        q = ((nx * ny) * z) + (nx * y) + x;
                        if (field[q] >= isolevel) {
                            __yBeg = y;
                            __break = true;
                            break;
                        }
                    }
                    if (__break)
                        { break; }
                }
                if (__break)
                    { break; }
            }
            __break = false;
            for (x = xBeg; x < xEnd; ++x) {
                for (y = __yBeg; y < yEnd; ++y) {
                    for (z = __zBeg; z < zEnd; ++z) {
                        q = ((nx * ny) * z) + (nx * y) + x;
                        if (field[q] >= isolevel) {
                            __xBeg = x;
                            __break = true;
                            break;
                        }
                    }
                    if (__break)
                        { break; }
                }
                if (__break)
                    { break; }
            }
            __break = false;
            for (z = zEnd; z >= zBeg; --z) {
                for (y = yEnd; y >= yBeg; --y) {
                    for (x = xEnd; x >= xBeg; --x) {
                        q = ((nx * ny) * z) + (nx * y) + x;
                        if (field[q] >= isolevel) {
                            __zEnd = z;
                            __break = true;
                            break;
                        }
                    }
                    if (__break)
                        { break; }
                }
                if (__break)
                    { break; }
            }
            __break = false;
            for (y = yEnd; y >= yBeg; --y) {
                for (z = __zEnd; z >= zBeg; --z) {
                    for (x = xEnd; x >= xBeg; --x) {
                        q = ((nx * ny) * z) + (nx * y) + x;
                        if (field[q] >= isolevel) {
                            __yEnd = y;
                            __break = true;
                            break;
                        }
                    }
                    if (__break)
                        { break; }
                }
                if (__break)
                    { break; }
            }
            __break = false;
            for (x = xEnd; x >= xBeg; --x) {
                for (y = __yEnd; y >= yBeg; --y) {
                    for (z = __zEnd; z >= zBeg; --z) {
                        q = ((nx * ny) * z) + (nx * y) + x;
                        if (field[q] >= isolevel) {
                            __xEnd = x;
                            __break = true;
                            break;
                        }
                    }
                    if (__break)
                        { break; }
                }
                if (__break)
                    { break; }
            }
            //
            if (noNormals) {
                xBeg = Math.max(0, __xBeg - 1);
                yBeg = Math.max(0, __yBeg - 1);
                zBeg = Math.max(0, __zBeg - 1);
                xEnd = Math.min(nx - 1, __xEnd + 1);
                yEnd = Math.min(ny - 1, __yEnd + 1);
                zEnd = Math.min(nz - 1, __zEnd + 1);
            }
            else {
                xBeg = Math.max(1, __xBeg - 1);
                yBeg = Math.max(1, __yBeg - 1);
                zBeg = Math.max(1, __zBeg - 1);
                xEnd = Math.min(nx - 2, __xEnd + 1);
                yEnd = Math.min(ny - 2, __yEnd + 1);
                zEnd = Math.min(nz - 2, __zEnd + 1);
            }
        }
        // polygonize part of the grid
        var edgeFilter = 15;
        for (z = zBeg; z < zEnd; ++z, edgeFilter &= ~4) {
            zOffset = zd * z;
            edgeFilter |= 2;
            for (y = yBeg; y < yEnd; ++y, edgeFilter &= ~2) {
                yOffset = zOffset + yd * y;
                edgeFilter |= 1;
                for (x = xBeg; x < xEnd; ++x, edgeFilter &= ~1) {
                    q = yOffset + x;
                    polygonize(x, y, z, q, edgeFilter);
                }
            }
        }
    }
}
Object.assign(MarchingCubes, { __deps: [getEdgeTable, getTriTable, getAllowedContours, getUintArray] });

/**
 * @file Matrix Utils
 * @private
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * svd methods from Eugene Zatepyakin / http://inspirit.github.io/jsfeat/
 */
var Matrix = function Matrix(cols, rows) {
    this.cols = cols;
    this.rows = rows;
    this.size = this.cols * this.rows;
    this.data = new Float32Array(this.size);
};
Matrix.prototype.copyTo = function copyTo (matrix) {
    matrix.data.set(this.data);
};
function transpose(At, A) {
    var i = 0;
    var j = 0;
    var nrows = A.rows;
    var ncols = A.cols;
    var Ai = 0;
    var Ati = 0;
    var pAt = 0;
    var ad = A.data;
    var atd = At.data;
    for (; i < nrows; Ati += 1, Ai += ncols, i++) {
        pAt = Ati;
        for (j = 0; j < ncols; pAt += nrows, j++)
            { atd[pAt] = ad[Ai + j]; }
    }
}
// C = A * B
function multiply(C, A, B) {
    var i = 0;
    var j = 0;
    var k = 0;
    var Ap = 0;
    var pA = 0;
    var pB = 0;
    var _pB = 0;
    var Cp = 0;
    var ncols = A.cols;
    var nrows = A.rows;
    var mcols = B.cols;
    var ad = A.data;
    var bd = B.data;
    var cd = C.data;
    var sum = 0.0;
    for (; i < nrows; Ap += ncols, i++) {
        for (_pB = 0, j = 0; j < mcols; Cp++, _pB++, j++) {
            pB = _pB;
            pA = Ap;
            sum = 0.0;
            for (k = 0; k < ncols; pA++, pB += mcols, k++) {
                sum += ad[pA] * bd[pB];
            }
            cd[Cp] = sum;
        }
    }
}
// C = A * B'
function multiplyABt(C, A, B) {
    var i = 0;
    var j = 0;
    var k = 0;
    var Ap = 0;
    var pA = 0;
    var pB = 0;
    var Cp = 0;
    var ncols = A.cols;
    var nrows = A.rows;
    var mrows = B.rows;
    var ad = A.data;
    var bd = B.data;
    var cd = C.data;
    var sum = 0.0;
    for (; i < nrows; Ap += ncols, i++) {
        for (pB = 0, j = 0; j < mrows; Cp++, j++) {
            pA = Ap;
            sum = 0.0;
            for (k = 0; k < ncols; pA++, pB++, k++) {
                sum += ad[pA] * bd[pB];
            }
            cd[Cp] = sum;
        }
    }
}
function invert3x3(from, to) {
    var A = from.data;
    var invA = to.data;
    var t1 = A[4];
    var t2 = A[8];
    var t4 = A[5];
    var t5 = A[7];
    var t8 = A[0];
    var t9 = t8 * t1;
    var t11 = t8 * t4;
    var t13 = A[3];
    var t14 = A[1];
    var t15 = t13 * t14;
    var t17 = A[2];
    var t18 = t13 * t17;
    var t20 = A[6];
    var t21 = t20 * t14;
    var t23 = t20 * t17;
    var t26 = 1.0 / (t9 * t2 - t11 * t5 - t15 * t2 + t18 * t5 + t21 * t4 - t23 * t1);
    invA[0] = (t1 * t2 - t4 * t5) * t26;
    invA[1] = -(t14 * t2 - t17 * t5) * t26;
    invA[2] = -(-t14 * t4 + t17 * t1) * t26;
    invA[3] = -(t13 * t2 - t4 * t20) * t26;
    invA[4] = (t8 * t2 - t23) * t26;
    invA[5] = -(t11 - t18) * t26;
    invA[6] = -(-t13 * t5 + t1 * t20) * t26;
    invA[7] = -(t8 * t5 - t21) * t26;
    invA[8] = (t9 - t15) * t26;
}
function mat3x3determinant(M) {
    var md = M.data;
    return md[0] * md[4] * md[8] -
        md[0] * md[5] * md[7] -
        md[3] * md[1] * md[8] +
        md[3] * md[2] * md[7] +
        md[6] * md[1] * md[5] -
        md[6] * md[2] * md[4];
}
// C = A * B
function multiply3x3(C, A, B) {
    var Cd = C.data;
    var Ad = A.data;
    var Bd = B.data;
    var m10 = Ad[0];
    var m11 = Ad[1];
    var m12 = Ad[2];
    var m13 = Ad[3];
    var m14 = Ad[4];
    var m15 = Ad[5];
    var m16 = Ad[6];
    var m17 = Ad[7];
    var m18 = Ad[8];
    var m20 = Bd[0];
    var m21 = Bd[1];
    var m22 = Bd[2];
    var m23 = Bd[3];
    var m24 = Bd[4];
    var m25 = Bd[5];
    var m26 = Bd[6];
    var m27 = Bd[7];
    var m28 = Bd[8];
    Cd[0] = m10 * m20 + m11 * m23 + m12 * m26;
    Cd[1] = m10 * m21 + m11 * m24 + m12 * m27;
    Cd[2] = m10 * m22 + m11 * m25 + m12 * m28;
    Cd[3] = m13 * m20 + m14 * m23 + m15 * m26;
    Cd[4] = m13 * m21 + m14 * m24 + m15 * m27;
    Cd[5] = m13 * m22 + m14 * m25 + m15 * m28;
    Cd[6] = m16 * m20 + m17 * m23 + m18 * m26;
    Cd[7] = m16 * m21 + m17 * m24 + m18 * m27;
    Cd[8] = m16 * m22 + m17 * m25 + m18 * m28;
}
function meanRows(A) {
    var nrows = A.rows;
    var ncols = A.cols;
    var Ad = A.data;
    var mean = new Array(ncols);
    for (var j = 0; j < ncols; ++j) {
        mean[j] = 0.0;
    }
    for (var i = 0, p = 0; i < nrows; ++i) {
        for (var j$1 = 0; j$1 < ncols; ++j$1, ++p) {
            mean[j$1] += Ad[p];
        }
    }
    for (var j$2 = 0; j$2 < ncols; ++j$2) {
        mean[j$2] /= nrows;
    }
    return mean;
}
function subRows(A, row) {
    var nrows = A.rows;
    var ncols = A.cols;
    var Ad = A.data;
    for (var i = 0, p = 0; i < nrows; ++i) {
        for (var j = 0; j < ncols; ++j, ++p) {
            Ad[p] -= row[j];
        }
    }
}
function swap$1(A, i0, i1, t) {
    t = A[i0];
    A[i0] = A[i1];
    A[i1] = t;
}
function hypot(a, b) {
    a = Math.abs(a);
    b = Math.abs(b);
    if (a > b) {
        b /= a;
        return a * Math.sqrt(1.0 + b * b);
    }
    if (b > 0) {
        a /= b;
        return b * Math.sqrt(1.0 + a * a);
    }
    return 0.0;
}
var EPSILON = 0.0000001192092896;
var FLT_MIN = 1E-37;
function JacobiSVDImpl(At, astep, _W, Vt, vstep, m, n, n1) {
    var eps = EPSILON * 2.0;
    var minval = FLT_MIN;
    var i = 0;
    var j = 0;
    var k = 0;
    var iter = 0;
    var maxIter = Math.max(m, 30);
    var Ai = 0;
    var Aj = 0;
    var Vi = 0;
    var Vj = 0;
    var changed = 0;
    var c = 0.0;
    var s = 0.0;
    var t = 0.0;
    var t0 = 0.0;
    var t1 = 0.0;
    var sd = 0.0;
    var beta = 0.0;
    var gamma = 0.0;
    var delta = 0.0;
    var a = 0.0;
    var p = 0.0;
    var b = 0.0;
    var seed = 0x1234;
    var val = 0.0;
    var val0 = 0.0;
    var asum = 0.0;
    var W = new Float64Array(n << 3);
    for (; i < n; i++) {
        for (k = 0, sd = 0; k < m; k++) {
            t = At[i * astep + k];
            sd += t * t;
        }
        W[i] = sd;
        if (Vt) {
            for (k = 0; k < n; k++) {
                Vt[i * vstep + k] = 0;
            }
            Vt[i * vstep + i] = 1;
        }
    }
    for (; iter < maxIter; iter++) {
        changed = 0;
        for (i = 0; i < n - 1; i++) {
            for (j = i + 1; j < n; j++) {
                Ai = (i * astep) | 0;
                Aj = (j * astep) | 0;
                a = W[i];
                p = 0;
                b = W[j];
                k = 2;
                p += At[Ai] * At[Aj];
                p += At[Ai + 1] * At[Aj + 1];
                for (; k < m; k++) {
                    p += At[Ai + k] * At[Aj + k];
                }
                if (Math.abs(p) <= eps * Math.sqrt(a * b))
                    { continue; }
                p *= 2.0;
                beta = a - b;
                gamma = hypot(p, beta);
                if (beta < 0) {
                    delta = (gamma - beta) * 0.5;
                    s = Math.sqrt(delta / gamma);
                    c = (p / (gamma * s * 2.0));
                }
                else {
                    c = Math.sqrt((gamma + beta) / (gamma * 2.0));
                    s = (p / (gamma * c * 2.0));
                }
                a = 0.0;
                b = 0.0;
                k = 2; // unroll
                t0 = c * At[Ai] + s * At[Aj];
                t1 = -s * At[Ai] + c * At[Aj];
                At[Ai] = t0;
                At[Aj] = t1;
                a += t0 * t0;
                b += t1 * t1;
                t0 = c * At[Ai + 1] + s * At[Aj + 1];
                t1 = -s * At[Ai + 1] + c * At[Aj + 1];
                At[Ai + 1] = t0;
                At[Aj + 1] = t1;
                a += t0 * t0;
                b += t1 * t1;
                for (; k < m; k++) {
                    t0 = c * At[Ai + k] + s * At[Aj + k];
                    t1 = -s * At[Ai + k] + c * At[Aj + k];
                    At[Ai + k] = t0;
                    At[Aj + k] = t1;
                    a += t0 * t0;
                    b += t1 * t1;
                }
                W[i] = a;
                W[j] = b;
                changed = 1;
                if (Vt) {
                    Vi = (i * vstep) | 0;
                    Vj = (j * vstep) | 0;
                    k = 2;
                    t0 = c * Vt[Vi] + s * Vt[Vj];
                    t1 = -s * Vt[Vi] + c * Vt[Vj];
                    Vt[Vi] = t0;
                    Vt[Vj] = t1;
                    t0 = c * Vt[Vi + 1] + s * Vt[Vj + 1];
                    t1 = -s * Vt[Vi + 1] + c * Vt[Vj + 1];
                    Vt[Vi + 1] = t0;
                    Vt[Vj + 1] = t1;
                    for (; k < n; k++) {
                        t0 = c * Vt[Vi + k] + s * Vt[Vj + k];
                        t1 = -s * Vt[Vi + k] + c * Vt[Vj + k];
                        Vt[Vi + k] = t0;
                        Vt[Vj + k] = t1;
                    }
                }
            }
        }
        if (changed === 0)
            { break; }
    }
    for (i = 0; i < n; i++) {
        for (k = 0, sd = 0; k < m; k++) {
            t = At[i * astep + k];
            sd += t * t;
        }
        W[i] = Math.sqrt(sd);
    }
    for (i = 0; i < n - 1; i++) {
        j = i;
        for (k = i + 1; k < n; k++) {
            if (W[j] < W[k]) {
                j = k;
            }
        }
        if (i !== j) {
            swap$1(W, i, j, sd);
            if (Vt) {
                for (k = 0; k < m; k++) {
                    swap$1(At, i * astep + k, j * astep + k, t);
                }
                for (k = 0; k < n; k++) {
                    swap$1(Vt, i * vstep + k, j * vstep + k, t);
                }
            }
        }
    }
    for (i = 0; i < n; i++) {
        _W[i] = W[i];
    }
    if (!Vt) {
        return;
    }
    for (i = 0; i < n1; i++) {
        sd = i < n ? W[i] : 0;
        while (sd <= minval) {
            // if we got a zero singular value, then in order to get the corresponding left singular vector
            // we generate a random vector, project it to the previously computed left singular vectors,
            // subtract the projection and normalize the difference.
            val0 = (1.0 / m);
            for (k = 0; k < m; k++) {
                seed = (seed * 214013 + 2531011);
                val = (((seed >> 16) & 0x7fff) & 256) !== 0 ? val0 : -val0;
                At[i * astep + k] = val;
            }
            for (iter = 0; iter < 2; iter++) {
                for (j = 0; j < i; j++) {
                    sd = 0;
                    for (k = 0; k < m; k++) {
                        sd += At[i * astep + k] * At[j * astep + k];
                    }
                    asum = 0.0;
                    for (k = 0; k < m; k++) {
                        t = (At[i * astep + k] - sd * At[j * astep + k]);
                        At[i * astep + k] = t;
                        asum += Math.abs(t);
                    }
                    asum = asum ? 1.0 / asum : 0;
                    for (k = 0; k < m; k++) {
                        At[i * astep + k] *= asum;
                    }
                }
            }
            sd = 0;
            for (k = 0; k < m; k++) {
                t = At[i * astep + k];
                sd += t * t;
            }
            sd = Math.sqrt(sd);
        }
        s = (1.0 / sd);
        for (k = 0; k < m; k++) {
            At[i * astep + k] *= s;
        }
    }
}
function svd(A, W, U, V) {
    var at = 0;
    var i = 0;
    var _m = A.rows;
    var _n = A.cols;
    var m = _m;
    var n = _n;
    if (m < n) {
        at = 1;
        i = m;
        m = n;
        n = i;
    }
    var amt = new Matrix(m, m);
    var wmt = new Matrix(1, n);
    var vmt = new Matrix(n, n);
    if (at === 0) {
        transpose(amt, A);
    }
    else {
        for (i = 0; i < _n * _m; i++) {
            amt.data[i] = A.data[i];
        }
        for (; i < n * m; i++) {
            amt.data[i] = 0;
        }
    }
    JacobiSVDImpl(amt.data, m, wmt.data, vmt.data, n, m, n, m);
    if (W) {
        for (i = 0; i < n; i++) {
            W.data[i] = wmt.data[i];
        }
        for (; i < _n; i++) {
            W.data[i] = 0;
        }
    }
    if (at === 0) {
        if (U)
            { transpose(U, amt); }
        if (V)
            { transpose(V, vmt); }
    }
    else {
        if (U)
            { transpose(U, vmt); }
        if (V)
            { transpose(V, amt); }
    }
}
//
function m4new() {
    return new Float32Array([
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1
    ]);
}
function m4set(out, n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
    out[0] = n11;
    out[4] = n12;
    out[8] = n13;
    out[12] = n14;
    out[1] = n21;
    out[5] = n22;
    out[9] = n23;
    out[13] = n24;
    out[2] = n31;
    out[6] = n32;
    out[10] = n33;
    out[14] = n34;
    out[3] = n41;
    out[7] = n42;
    out[11] = n43;
    out[15] = n44;
}
function m4multiply(out, a, b) {
    var a11 = a[0];
    var a12 = a[4];
    var a13 = a[8];
    var a14 = a[12];
    var a21 = a[1];
    var a22 = a[5];
    var a23 = a[9];
    var a24 = a[13];
    var a31 = a[2];
    var a32 = a[6];
    var a33 = a[10];
    var a34 = a[14];
    var a41 = a[3];
    var a42 = a[7];
    var a43 = a[11];
    var a44 = a[15];
    var b11 = b[0];
    var b12 = b[4];
    var b13 = b[8];
    var b14 = b[12];
    var b21 = b[1];
    var b22 = b[5];
    var b23 = b[9];
    var b24 = b[13];
    var b31 = b[2];
    var b32 = b[6];
    var b33 = b[10];
    var b34 = b[14];
    var b41 = b[3];
    var b42 = b[7];
    var b43 = b[11];
    var b44 = b[15];
    out[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
    out[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
    out[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
    out[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
    out[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
    out[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
    out[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
    out[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
    out[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
    out[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
    out[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
    out[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
    out[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
    out[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
    out[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
    out[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
}
function m4makeScale(out, x, y, z) {
    m4set(out, x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
}
m4makeScale.__deps = [m4set];
function m4makeTranslation(out, x, y, z) {
    m4set(out, 1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
}
m4makeTranslation.__deps = [m4set];
function m4makeRotationY(out, theta) {
    var c = Math.cos(theta);
    var s = Math.sin(theta);
    m4set(out, c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
}
m4makeRotationY.__deps = [m4set];
//
function m3new() {
    return new Float32Array([
        1, 0, 0,
        0, 1, 0,
        0, 0, 1
    ]);
}
function m3makeNormal(out, m4) {
    var r0 = v3new([m4[0], m4[1], m4[2]]);
    var r1 = v3new([m4[4], m4[5], m4[6]]);
    var r2 = v3new([m4[8], m4[9], m4[10]]);
    var cp = v3new();
    //        [ r0 ]       [ r1 x r2 ]
    // M3x3 = [ r1 ]   N = [ r2 x r0 ]
    //        [ r2 ]       [ r0 x r1 ]
    v3cross(cp, r1, r2);
    out[0] = cp[0];
    out[1] = cp[1];
    out[2] = cp[2];
    v3cross(cp, r2, r0);
    out[3] = cp[0];
    out[4] = cp[1];
    out[5] = cp[2];
    v3cross(cp, r0, r1);
    out[6] = cp[0];
    out[7] = cp[1];
    out[8] = cp[2];
}
m3makeNormal.__deps = [v3new, v3cross];

/**
 * @file Surface Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function laplacianSmooth(verts, faces, numiter, inflate) {
    // based on D. Xu, Y. Zhang (2009) Generating Triangulated Macromolecular
    // Surfaces by Euclidean Distance Transform. PLoS ONE 4(12): e8140.
    //
    // Permission to use, copy, modify, and distribute this program for
    // any purpose, with or without fee, is hereby granted, provided that
    // the notices on the head, the reference information, and this
    // copyright notice appear in all copies or substantial portions of
    // the Software. It is provided "as is" without express or implied
    // warranty.
    //
    // ported to JavaScript and adapted to NGL by Alexander Rose
    numiter = numiter || 1;
    inflate = inflate || true;
    var nv = verts.length / 3;
    var nf = faces.length / 3;
    var norms = undefined;
    if (inflate) {
        norms = new Float32Array(nv * 3);
    }
    var tps = new Float32Array(nv * 3);
    var i;
    var ndeg = 20;
    var vertdeg = new Array(ndeg);
    for (i = 0; i < ndeg; ++i) {
        vertdeg[i] = new Uint32Array(nv);
    }
    for (i = 0; i < nv; ++i) {
        vertdeg[0][i] = 0;
    }
    var j, jl;
    var flagvert;
    // for each face
    for (i = 0; i < nf; ++i) {
        var ao = i * 3;
        var bo = i * 3 + 1;
        var co = i * 3 + 2;
        // vertex a
        flagvert = true;
        for (j = 0, jl = vertdeg[0][faces[ao]]; j < jl; ++j) {
            if (faces[bo] === vertdeg[j + 1][faces[ao]]) {
                flagvert = false;
                break;
            }
        }
        if (flagvert) {
            vertdeg[0][faces[ao]]++;
            vertdeg[vertdeg[0][faces[ao]]][faces[ao]] = faces[bo];
        }
        flagvert = true;
        for (j = 0, jl = vertdeg[0][faces[ao]]; j < jl; ++j) {
            if (faces[co] === vertdeg[j + 1][faces[ao]]) {
                flagvert = false;
                break;
            }
        }
        if (flagvert) {
            vertdeg[0][faces[ao]]++;
            vertdeg[vertdeg[0][faces[ao]]][faces[ao]] = faces[co];
        }
        // vertex b
        flagvert = true;
        for (j = 0, jl = vertdeg[0][faces[bo]]; j < jl; ++j) {
            if (faces[ao] === vertdeg[j + 1][faces[bo]]) {
                flagvert = false;
                break;
            }
        }
        if (flagvert) {
            vertdeg[0][faces[bo]]++;
            vertdeg[vertdeg[0][faces[bo]]][faces[bo]] = faces[ao];
        }
        flagvert = true;
        for (j = 0, jl = vertdeg[0][faces[bo]]; j < jl; ++j) {
            if (faces[co] === vertdeg[j + 1][faces[bo]]) {
                flagvert = false;
                break;
            }
        }
        if (flagvert) {
            vertdeg[0][faces[bo]]++;
            vertdeg[vertdeg[0][faces[bo]]][faces[bo]] = faces[co];
        }
        // vertex c
        flagvert = true;
        for (j = 0; j < vertdeg[0][faces[co]]; ++j) {
            if (faces[ao] === vertdeg[j + 1][faces[co]]) {
                flagvert = false;
                break;
            }
        }
        if (flagvert) {
            vertdeg[0][faces[co]]++;
            vertdeg[vertdeg[0][faces[co]]][faces[co]] = faces[ao];
        }
        flagvert = true;
        for (j = 0, jl = vertdeg[0][faces[co]]; j < jl; ++j) {
            if (faces[bo] === vertdeg[j + 1][faces[co]]) {
                flagvert = false;
                break;
            }
        }
        if (flagvert) {
            vertdeg[0][faces[co]]++;
            vertdeg[vertdeg[0][faces[co]]][faces[co]] = faces[bo];
        }
    }
    var wt = 1.0;
    var wt2 = 0.5;
    var i3, vi3, vdi, wtvi, wt2vi;
    var ssign = -1;
    var scaleFactor = 1;
    var outwt = 0.75 / (scaleFactor + 3.5); // area-preserving
    // smoothing iterations
    for (var k = 0; k < numiter; ++k) {
        // for each vertex
        for (i = 0; i < nv; ++i) {
            i3 = i * 3;
            vdi = vertdeg[0][i];
            if (vdi < 3) {
                tps[i3] = verts[i3];
                tps[i3 + 1] = verts[i3 + 1];
                tps[i3 + 2] = verts[i3 + 2];
            }
            else if (vdi === 3 || vdi === 4) {
                tps[i3] = 0;
                tps[i3 + 1] = 0;
                tps[i3 + 2] = 0;
                for (j = 0; j < vdi; ++j) {
                    vi3 = vertdeg[j + 1][i] * 3;
                    tps[i3] += verts[vi3];
                    tps[i3 + 1] += verts[vi3 + 1];
                    tps[i3 + 2] += verts[vi3 + 2];
                }
                tps[i3] += wt2 * verts[i3];
                tps[i3 + 1] += wt2 * verts[i3 + 1];
                tps[i3 + 2] += wt2 * verts[i3 + 2];
                wt2vi = wt2 + vdi;
                tps[i3] /= wt2vi;
                tps[i3 + 1] /= wt2vi;
                tps[i3 + 2] /= wt2vi;
            }
            else {
                tps[i3] = 0;
                tps[i3 + 1] = 0;
                tps[i3 + 2] = 0;
                for (j = 0; j < vdi; ++j) {
                    vi3 = vertdeg[j + 1][i] * 3;
                    tps[i3] += verts[vi3];
                    tps[i3 + 1] += verts[vi3 + 1];
                    tps[i3 + 2] += verts[vi3 + 2];
                }
                tps[i3] += wt * verts[i3];
                tps[i3 + 1] += wt * verts[i3 + 1];
                tps[i3 + 2] += wt * verts[i3 + 2];
                wtvi = wt + vdi;
                tps[i3] /= wtvi;
                tps[i3 + 1] /= wtvi;
                tps[i3 + 2] /= wtvi;
            }
        }
        verts.set(tps); // copy smoothed positions
        if (inflate) {
            computeVertexNormals(verts, faces, norms);
            var nv3 = nv * 3;
            for (i3 = 0; i3 < nv3; i3 += 3) {
                // if(verts[i].inout) ssign=1;
                // else ssign=-1;
                verts[i3] += ssign * outwt * norms[i3];
                verts[i3 + 1] += ssign * outwt * norms[i3 + 1];
                verts[i3 + 2] += ssign * outwt * norms[i3 + 2];
            }
        }
    }
}
Object.assign(laplacianSmooth, { __deps: [computeVertexNormals] });
function computeVertexNormals(position, index, normal) {
    var i, il;
    if (normal === undefined) {
        normal = new Float32Array(position.length);
    }
    else {
        // reset existing normals to zero
        for (i = 0, il = normal.length; i < il; i++) {
            normal[i] = 0;
        }
    }
    var a = new Float32Array(3);
    var b = new Float32Array(3);
    var c = new Float32Array(3);
    var cb = new Float32Array(3);
    var ab = new Float32Array(3);
    if (index) {
        // indexed elements
        for (i = 0, il = index.length; i < il; i += 3) {
            var ai = index[i] * 3;
            var bi = index[i + 1] * 3;
            var ci = index[i + 2] * 3;
            v3fromArray(a, position, ai);
            v3fromArray(b, position, bi);
            v3fromArray(c, position, ci);
            v3sub(cb, c, b);
            v3sub(ab, a, b);
            v3cross(cb, cb, ab);
            normal[ai] += cb[0];
            normal[ai + 1] += cb[1];
            normal[ai + 2] += cb[2];
            normal[bi] += cb[0];
            normal[bi + 1] += cb[1];
            normal[bi + 2] += cb[2];
            normal[ci] += cb[0];
            normal[ci + 1] += cb[1];
            normal[ci + 2] += cb[2];
        }
    }
    else {
        // non-indexed elements (unconnected triangle soup)
        for (i = 0, il = position.length; i < il; i += 9) {
            v3fromArray(a, position, i);
            v3fromArray(b, position, i + 3);
            v3fromArray(c, position, i + 6);
            v3sub(cb, c, b);
            v3sub(ab, a, b);
            v3cross(cb, cb, ab);
            normal[i] = cb[0];
            normal[i + 1] = cb[1];
            normal[i + 2] = cb[2];
            normal[i + 3] = cb[0];
            normal[i + 4] = cb[1];
            normal[i + 5] = cb[2];
            normal[i + 6] = cb[0];
            normal[i + 7] = cb[1];
            normal[i + 8] = cb[2];
        }
    }
    normalizeVector3array(normal);
    return normal;
}
Object.assign(computeVertexNormals, { __deps: [
        v3sub, v3cross, v3fromArray, normalizeVector3array
    ] });
function getRadiusDict(radiusList) {
    var radiusDict = {};
    for (var i = 0, il = radiusList.length; i < il; ++i) {
        radiusDict[radiusList[i]] = true;
    }
    return radiusDict;
}
function getSurfaceGrid(min, max, maxRadius, scaleFactor, extraMargin) {
    // need margin to avoid boundary/round off effects
    var margin = (1 / scaleFactor) * 3;
    margin += maxRadius;
    v3subScalar(min, min, extraMargin + margin);
    v3addScalar(max, max, extraMargin + margin);
    v3multiplyScalar(min, min, scaleFactor);
    v3floor(min, min);
    v3divideScalar(min, min, scaleFactor);
    v3multiplyScalar(max, max, scaleFactor);
    v3ceil(max, max);
    v3divideScalar(max, max, scaleFactor);
    var dim = new Float32Array(3);
    v3sub(dim, max, min);
    v3multiplyScalar(dim, dim, scaleFactor);
    v3ceil(dim, dim);
    v3addScalar(dim, dim, 1);
    var maxSize = Math.pow(10, 6) * 256;
    var tmpSize = dim[0] * dim[1] * dim[2] * 3;
    if (maxSize <= tmpSize) {
        scaleFactor *= Math.pow(maxSize / tmpSize, 1 / 3);
        v3multiplyScalar(min, min, scaleFactor);
        v3floor(min, min);
        v3divideScalar(min, min, scaleFactor);
        v3multiplyScalar(max, max, scaleFactor);
        v3ceil(max, max);
        v3divideScalar(max, max, scaleFactor);
        v3sub(dim, max, min);
        v3multiplyScalar(dim, dim, scaleFactor);
        v3ceil(dim, dim);
        v3addScalar(dim, dim, 1);
    }
    var tran = new Float32Array(min);
    v3negate(tran, tran);
    // coordinate transformation matrix
    var matrix = m4new();
    var mroty = m4new();
    m4makeRotationY(mroty, degToRad(90));
    m4multiply(matrix, matrix, mroty);
    var mscale = m4new();
    m4makeScale(mscale, -1 / scaleFactor, 1 / scaleFactor, 1 / scaleFactor);
    m4multiply(matrix, matrix, mscale);
    var mtrans = m4new();
    m4makeTranslation(mtrans, -scaleFactor * tran[2], -scaleFactor * tran[1], -scaleFactor * tran[0]);
    m4multiply(matrix, matrix, mtrans);
    return {
        dim: dim,
        tran: tran,
        matrix: matrix,
        scaleFactor: scaleFactor
    };
}
Object.assign(getSurfaceGrid, { '__deps': [
        degToRad,
        v3subScalar, v3addScalar, v3divideScalar, v3multiplyScalar,
        v3floor, v3ceil, v3sub, v3negate,
        m4new, m4multiply, m4makeTranslation, m4makeScale, m4makeRotationY
    ] });

/**
 * @file Surface
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Surface
 */
var Surface = function Surface(name, path, data) {
    this.name = name || '';
    this.path = path || '';
    this.info = {};
    this.center = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.boundingBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    if (data instanceof __WEBPACK_IMPORTED_MODULE_0_three__["s" /* Geometry */] ||
        data instanceof __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */] ||
        data instanceof __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]) {
        // to be removed
        this.fromGeometry(data);
    }
    else if (data) {
        this.set(data.position, data.index, data.normal, data.color, data.atomindex, data.contour);
        this.boundingBox.setFromArray(data.position);
        this.boundingBox.getCenter(this.center);
    }
};

var prototypeAccessors$a = { type: { configurable: true } };
prototypeAccessors$a.type.get = function () { return 'Surface'; };
/**
 * set surface data
 * @param {Float32Array} position - surface positions
 * @param {Int32Array} index - surface indices
 * @param {Float32Array} normal - surface normals
 * @param {Float32Array} color - surface colors
 * @param {Int32Array} atomindex - atom indices
 * @param {boolean} contour - contour mode flag
 * @return {undefined}
 */
Surface.prototype.set = function set (position, index, normal, color, atomindex, contour) {
        if ( contour === void 0 ) contour = false;

    /**
     * @type {Float32Array}
     */
    this.position = position;
    /**
     * @type {Uint32Array|Uint16Array|undefined}
     */
    this.index = index;
    /**
     * @type {Float32Array|undefined}
     */
    this.normal = normal;
    /**
     * @type {Float32Array|undefined}
     */
    this.color = color;
    /**
     * @type {Int32Array|undefined}
     */
    this.atomindex = atomindex;
    this.size = position.length / 3;
    this.contour = contour;
};
Surface.prototype.fromGeometry = function fromGeometry (geometry) {
    if (Debug)
        { Log.time('GeometrySurface.fromGeometry'); }
    var geo;
    if (geometry instanceof __WEBPACK_IMPORTED_MODULE_0_three__["s" /* Geometry */]) {
        geometry.computeVertexNormals(true);
        geo = new __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]().fromGeometry(geometry);
    }
    else if (geometry instanceof __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]) {
        geo = geometry;
    }
    else {
        geo = geometry[0];
    }
    if (!geo.boundingBox)
        { geo.computeBoundingBox(); }
    this.boundingBox.copy(geo.boundingBox);
    this.boundingBox.getCenter(this.center);
    var position, color, index, normal;
    if (geo instanceof __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]) {
        var attr = geo.attributes;
        var an = attr.normal ? attr.normal.array : false;
        // assume there are no normals if the first is zero
        if (!an || (an[0] === 0 && an[1] === 0 && an[2] === 0)) {
            geo.computeVertexNormals();
        }
        position = attr.position.array;
        index = attr.index ? attr.index.array : null;
        normal = attr.normal.array;
    }
    this.set(position, index, normal, color, undefined);
    if (Debug)
        { Log.timeEnd('GeometrySurface.setGeometry'); }
};
Surface.prototype.getPosition = function getPosition () {
    return this.position;
};
Surface.prototype.getColor = function getColor (params) {
    var p = params || {};
    p.surface = this;
    var n = this.size;
    var array = new Float32Array(n * 3);
    var colormaker = ColormakerRegistry$1.getScheme(p);
    if (colormaker.volumeColor || p.scheme === 'random') {
        for (var i = 0; i < n; ++i) {
            colormaker.volumeColorToArray(i, array, i * 3);
        }
    }
    else if (colormaker.positionColor) {
        var v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        var pos = this.position;
        for (var i$1 = 0; i$1 < n; ++i$1) {
            var i3 = i$1 * 3;
            v.set(pos[i3], pos[i3 + 1], pos[i3 + 2]);
            colormaker.positionColorToArray(v, array, i3);
        }
    }
    else if (colormaker.atomColor && this.atomindex) {
        var atomProxy = p.structure.getAtomProxy();
        var atomindex = this.atomindex;
        for (var i$2 = 0; i$2 < n; ++i$2) {
            atomProxy.index = atomindex[i$2];
            colormaker.atomColorToArray(atomProxy, array, i$2 * 3);
        }
    }
    else {
        var tc = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](p.value);
        uniformArray3(n, tc.r, tc.g, tc.b, array);
    }
    return array;
};
Surface.prototype.getPicking = function getPicking (structure) {
    if (this.atomindex && structure) {
        return new AtomPicker(this.atomindex, structure);
    }
    else {
        return new SurfacePicker(serialArray(this.size), this);
    }
};
Surface.prototype.getNormal = function getNormal () {
    return this.normal;
};
Surface.prototype.getSize = function getSize (size, scale$$1) {
    return uniformArray(this.size, size * scale$$1);
};
Surface.prototype.getIndex = function getIndex () {
    return this.index;
};
Surface.prototype.getFilteredIndex = function getFilteredIndex (sele, structure) {
    if (sele && this.atomindex) {
        var selection = new Selection(sele);
        var atomSet = structure.getAtomSet(selection);
        var filteredIndex = [];
        var atomindex = this.atomindex;
        var index = this.index;
        var n = index.length;
        var elementSize = this.contour ? 2 : 3;
        var j = 0;
        for (var i = 0; i < n; i += elementSize) {
            var include = true;
            for (var a = 0; a < elementSize; a++) {
                var idx = index[i + a];
                var ai = atomindex[idx];
                if (!atomSet.get(ai)) {
                    include = false;
                    break;
                }
            }
            if (!include) {
                continue;
            }
            for (var a$1 = 0; a$1 < elementSize; a$1++, j++) {
                filteredIndex[j] = index[i + a$1];
            }
        }
        return getUintArray(filteredIndex, this.position.length / 3);
    }
    else {
        return this.index;
    }
};
Surface.prototype.getAtomindex = function getAtomindex () {
    return this.atomindex;
};
Surface.prototype.dispose = function dispose () {
    //
};

Object.defineProperties( Surface.prototype, prototypeAccessors$a );

/**
 * @file Volume
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function VolumeSurface(data, nx, ny, nz, atomindex) {
    var mc = new MarchingCubes(data, nx, ny, nz, atomindex);
    function getSurface(isolevel, smooth, box, matrix, contour, wrap) {
        if ( wrap === void 0 ) wrap = false;

        var sd = mc.triangulate(isolevel, smooth, box, contour, wrap);
        if (smooth && !contour) {
            laplacianSmooth(sd.position, sd.index, smooth, true);
            sd.normal = computeVertexNormals(sd.position, sd.index);
        }
        if (matrix) {
            applyMatrix4toVector3array(matrix, sd.position);
            if (sd.normal) {
                var normalMatrix = m3new();
                m3makeNormal(normalMatrix, matrix);
                applyMatrix3toVector3array(normalMatrix, sd.normal);
            }
        }
        return sd;
    }
    this.getSurface = getSurface;
}
Object.assign(VolumeSurface, { __deps: [
        laplacianSmooth, computeVertexNormals, MarchingCubes,
        applyMatrix4toVector3array, applyMatrix3toVector3array,
        m3new, m3makeNormal
    ] });
WorkerRegistry$1.add('surf', function func(e, callback) {
    var a = e.data.args;
    var p = e.data.params;
    if (a) {
        /* global self */
        self.volsurf = new VolumeSurface(a[0], a[1], a[2], a[3], a[4]);
    }
    if (p) {
        var sd = self.volsurf.getSurface(p.isolevel, p.smooth, p.box, p.matrix, p.contour, p.wrap);
        var transferList = [sd.position.buffer, sd.index.buffer];
        if (sd.normal)
            { transferList.push(sd.normal.buffer); }
        if (sd.atomindex)
            { transferList.push(sd.atomindex.buffer); }
        var data = {
            sd: sd,
            p: p
        };
        callback(data, transferList);
    }
}, [VolumeSurface]);
/**
 * Volume
 */
var Volume = function Volume(name, path, data, nx, ny, nz, atomindex) {
    this.name = name;
    this.path = path;
    this.matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    this.normalMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["x" /* Matrix3 */]();
    this.inverseMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    this.center = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.boundingBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    this.setData(data, nx, ny, nz, atomindex);
};

var prototypeAccessors$b = { type: { configurable: true },position: { configurable: true },min: { configurable: true },max: { configurable: true },sum: { configurable: true },mean: { configurable: true },rms: { configurable: true } };
prototypeAccessors$b.type.get = function () { return 'Volume'; };
/**
 * set volume data
 * @param {Float32array} data - volume 3d grid
 * @param {Integer} nx - x dimension of the 3d volume
 * @param {Integer} ny - y dimension of the 3d volume
 * @param {Integer} nz - z dimension of the 3d volume
 * @param {Int32Array} atomindex - atom indices corresponding to the cells in the 3d grid
 * @return {undefined}
 */
Volume.prototype.setData = function setData (data, nx, ny, nz, atomindex) {
    this.nx = nx || 1;
    this.ny = ny || 1;
    this.nz = nz || 1;
    this.data = data || new Float32Array(1);
    this.setAtomindex(atomindex);
    delete this._position;
    delete this._min;
    delete this._max;
    delete this._mean;
    delete this._rms;
    if (this.worker)
        { this.worker.terminate(); }
};
/**
 * Set statistics, which can be different from the data in this volume,
 * if this volume is a slice of a bigger volume
 * @param {Number|undefined} min - minimum value of the whole data set
 * @param {Number|undefined} max - maximum value of the whole data set
 * @param {Number|undefined} mean - average value of the whole data set
 * @param {Number|undefined} rms - sigma value of the whole data set
 */
Volume.prototype.setStats = function setStats (min, max, mean, rms) {
    this._min = min;
    this._max = max;
    this._mean = mean;
    this._rms = rms;
};
/**
 * set transformation matrix
 * @param {Matrix4} matrix - 4x4 transformation matrix
 * @return {undefined}
 */
Volume.prototype.setMatrix = function setMatrix (matrix) {
    this.matrix.copy(matrix);
    var bb = this.boundingBox;
    var v = this.center; // temporary re-purposing
    var x = this.nx - 1;
    var y = this.ny - 1;
    var z = this.nz - 1;
    bb.makeEmpty();
    bb.expandByPoint(v.set(x, y, z));
    bb.expandByPoint(v.set(x, y, 0));
    bb.expandByPoint(v.set(x, 0, z));
    bb.expandByPoint(v.set(x, 0, 0));
    bb.expandByPoint(v.set(0, y, z));
    bb.expandByPoint(v.set(0, 0, z));
    bb.expandByPoint(v.set(0, y, 0));
    bb.expandByPoint(v.set(0, 0, 0));
    bb.applyMatrix4(this.matrix);
    bb.getCenter(this.center);
    // make normal matrix
    var me = this.matrix.elements;
    var r0 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](me[0], me[1], me[2]);
    var r1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](me[4], me[5], me[6]);
    var r2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](me[8], me[9], me[10]);
    var cp = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    //    [ r0 ]   [ r1 x r2 ]
    // M3x3 = [ r1 ]   N = [ r2 x r0 ]
    //    [ r2 ]   [ r0 x r1 ]
    var ne = this.normalMatrix.elements;
    cp.crossVectors(r1, r2);
    ne[0] = cp.x;
    ne[1] = cp.y;
    ne[2] = cp.z;
    cp.crossVectors(r2, r0);
    ne[3] = cp.x;
    ne[4] = cp.y;
    ne[5] = cp.z;
    cp.crossVectors(r0, r1);
    ne[6] = cp.x;
    ne[7] = cp.y;
    ne[8] = cp.z;
    this.inverseMatrix.getInverse(this.matrix);
};
/**
 * set atom indices
 * @param {Int32Array} atomindex - atom indices corresponding to the cells in the 3d grid
 * @return {undefined}
   */
Volume.prototype.setAtomindex = function setAtomindex (atomindex) {
    this.atomindex = atomindex;
};
Volume.prototype.getBox = function getBox (center, size, target) {
    if (!target)
        { target = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */](); }
    target.set(center, center);
    target.expandByScalar(size);
    target.applyMatrix4(this.inverseMatrix);
    target.min.round();
    target.max.round();
    return target;
};
Volume.prototype._getBox = function _getBox (center, size) {
    if (!center || !size)
        { return; }
    if (!this.__box)
        { this.__box = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */](); }
    var box = this.getBox(center, size, this.__box);
    return [box.min.toArray(), box.max.toArray()];
};
Volume.prototype._makeSurface = function _makeSurface (sd, isolevel, smooth) {
    var name = this.name + '@' + isolevel.toPrecision(2);
    var surface = new Surface(name, '', sd);
    surface.info.isolevel = isolevel;
    surface.info.smooth = smooth;
    surface.info.volume = this;
    return surface;
};
Volume.prototype.getSurface = function getSurface (isolevel, smooth, center, size, contour, wrap) {
        if ( wrap === void 0 ) wrap = false;

    isolevel = isNaN(isolevel) ? this.getValueForSigma(2) : isolevel;
    smooth = defaults(smooth, 0);
    //
    if (this.volsurf === undefined) {
        this.volsurf = new VolumeSurface(this.data, this.nx, this.ny, this.nz, this.atomindex);
    }
    var box = this._getBox(center, size);
    var sd = this.volsurf.getSurface(isolevel, smooth, box, this.matrix.elements, contour, wrap);
    return this._makeSurface(sd, isolevel, smooth);
};
Volume.prototype.getSurfaceWorker = function getSurfaceWorker (isolevel, smooth, center, size, contour, wrap, callback) {
        var this$1 = this;

    isolevel = isNaN(isolevel) ? this.getValueForSigma(2) : isolevel;
    smooth = smooth || 0;
    //
    if (window.hasOwnProperty('Worker')) {
        if (this.workerPool === undefined) {
            this.workerPool = new WorkerPool('surf', 2);
        }
        var msg = {};
        var worker = this.workerPool.getNextWorker();
        if (worker.postCount === 0) {
            Object.assign(msg, {
                args: [
                    this.data, this.nx, this.ny, this.nz, this.atomindex
                ]
            });
        }
        Object.assign(msg, {
            params: {
                isolevel: isolevel,
                smooth: smooth,
                box: this._getBox(center, size),
                matrix: this.matrix.elements,
                contour: contour,
                wrap: wrap
            }
        });
        worker.post(msg, undefined, function (e) {
            var sd = e.data.sd;
            var p = e.data.p;
            callback(this$1._makeSurface(sd, p.isolevel, p.smooth));
        }, function (e) {
            console.warn('Volume.getSurfaceWorker error - trying without worker', e);
            var surface = this$1.getSurface(isolevel, smooth, center, size, contour, wrap);
            callback(surface);
        });
    }
    else {
        var surface = this.getSurface(isolevel, smooth, center, size, contour, wrap);
        callback(surface);
    }
};
Volume.prototype.getValueForSigma = function getValueForSigma (sigma) {
    return this.mean + defaults(sigma, 2) * this.rms;
};
Volume.prototype.getSigmaForValue = function getSigmaForValue (value) {
    return (defaults(value, 0) - this.mean) / this.rms;
};
prototypeAccessors$b.position.get = function () {
    if (!this._position) {
        var nz = this.nz;
        var ny = this.ny;
        var nx = this.nx;
        var position = new Float32Array(nx * ny * nz * 3);
        var p = 0;
        for (var z = 0; z < nz; ++z) {
            for (var y = 0; y < ny; ++y) {
                for (var x = 0; x < nx; ++x) {
                    position[p + 0] = x;
                    position[p + 1] = y;
                    position[p + 2] = z;
                    p += 3;
                }
            }
        }
        applyMatrix4toVector3array(this.matrix.elements, position);
        this._position = position;
    }
    return this._position;
};
Volume.prototype.getDataAtomindex = function getDataAtomindex () {
    return this.atomindex;
};
Volume.prototype.getDataPosition = function getDataPosition () {
    return this.position;
};
Volume.prototype.getDataColor = function getDataColor (params) {
    var p = params || {};
    p.volume = this;
    p.scale = p.scale || 'Spectral';
    p.domain = p.domain || [this.min, this.max];
    var colormaker = ColormakerRegistry$1.getScheme(p);
    var n = this.position.length / 3;
    var array = new Float32Array(n * 3);
    // var atoms = p.structure.atoms;
    // var atomindex = this.atomindex;
    for (var i = 0; i < n; ++i) {
        colormaker.volumeColorToArray(i, array, i * 3);
        // a = atoms[ atomindex[ i ] ];
        // if( a ) colormaker.atomColorToArray( a, array, i * 3 );
    }
    return array;
};
Volume.prototype.getDataPicking = function getDataPicking () {
    var picking = serialArray(this.position.length / 3);
    return new VolumePicker(picking, this);
};
Volume.prototype.getDataSize = function getDataSize (size, scale$$1) {
    var data = this.data;
    var n = this.position.length / 3;
    var array;
    switch (size) {
        case 'value':
            array = new Float32Array(data);
            break;
        case 'abs-value':
            array = new Float32Array(data);
            for (var i = 0; i < n; ++i) {
                array[i] = Math.abs(array[i]);
            }
            break;
        case 'value-min': {
            array = new Float32Array(data);
            var min = this.min;
            for (var i$1 = 0; i$1 < n; ++i$1) {
                array[i$1] -= min;
            }
            break;
        }
        case 'deviation':
            array = new Float32Array(data);
            break;
        default:
            array = uniformArray(n, size);
            break;
    }
    if (scale$$1 !== 1.0) {
        for (var i$2 = 0; i$2 < n; ++i$2) {
            array[i$2] *= scale$$1;
        }
    }
    return array;
};
prototypeAccessors$b.min.get = function () {
    if (this._min === undefined) {
        this._min = arrayMin(this.data);
    }
    return this._min;
};
prototypeAccessors$b.max.get = function () {
    if (this._max === undefined) {
        this._max = arrayMax(this.data);
    }
    return this._max;
};
prototypeAccessors$b.sum.get = function () {
    if (this._sum === undefined) {
        this._sum = arraySum(this.data);
    }
    return this._sum;
};
prototypeAccessors$b.mean.get = function () {
    if (this._mean === undefined) {
        this._mean = arrayMean(this.data);
    }
    return this._mean;
};
prototypeAccessors$b.rms.get = function () {
    if (this._rms === undefined) {
        this._rms = arrayRms(this.data);
    }
    return this._rms;
};
Volume.prototype.clone = function clone () {
    var vol = new Volume(this.name, this.path, this.data, this.nx, this.ny, this.nz, this.atomindex);
    vol.matrix.copy(this.matrix);
    vol.header = Object.assign({}, this.header);
    return vol;
};
Volume.prototype.dispose = function dispose () {
    if (this.workerPool)
        { this.workerPool.terminate(); }
};

Object.defineProperties( Volume.prototype, prototypeAccessors$b );

ShaderRegistry.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}");

ShaderRegistry.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}");

/**
 * @file Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getThreeSide(side) {
    if (side === 'front') {
        return __WEBPACK_IMPORTED_MODULE_0_three__["r" /* FrontSide */];
    }
    else if (side === 'back') {
        return __WEBPACK_IMPORTED_MODULE_0_three__["c" /* BackSide */];
    }
    else if (side === 'double') {
        return __WEBPACK_IMPORTED_MODULE_0_three__["m" /* DoubleSide */];
    }
    else {
        return __WEBPACK_IMPORTED_MODULE_0_three__["m" /* DoubleSide */];
    }
}
var itemSize = {
    'f': 1, 'v2': 2, 'v3': 3, 'c': 3
};
function setObjectMatrix(object, matrix) {
    object.matrix.copy(matrix);
    object.matrix.decompose(object.position, object.quaternion, object.scale);
    object.matrixWorldNeedsUpdate = true;
}
var BufferDefaultParameters = {
    opaqueBack: false,
    side: 'double',
    opacity: 1.0,
    depthWrite: true,
    clipNear: 0,
    clipRadius: 0,
    clipCenter: new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](),
    flatShaded: false,
    wireframe: false,
    roughness: 0.4,
    metalness: 0.0,
    diffuse: 0xffffff,
    diffuseInterior: false,
    useInteriorColor: false,
    interiorColor: 0xdddddd,
    interiorDarkening: 0,
    forceTransparent: false,
    matrix: new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */](),
    disablePicking: false,
    sortParticles: false,
    background: false
};
var BufferParameterTypes = {
    opaqueBack: { updateShader: true },
    side: { updateShader: true, property: true },
    opacity: { uniform: true },
    depthWrite: { property: true },
    clipNear: { updateShader: true, property: true },
    clipRadius: { updateShader: true, uniform: true },
    clipCenter: { uniform: true },
    flatShaded: { updateShader: true },
    background: { updateShader: true },
    wireframe: { updateVisibility: true },
    roughness: { uniform: true },
    metalness: { uniform: true },
    diffuse: { uniform: true },
    diffuseInterior: { updateShader: true },
    useInteriorColor: { updateShader: true },
    interiorColor: { uniform: true },
    interiorDarkening: { uniform: true },
    matrix: {}
};
/**
 * Buffer class. Base class for buffers.
 * @interface
 */
var Buffer = function Buffer(data, params) {
    if ( params === void 0 ) params = {};

    this.parameterTypes = BufferParameterTypes;
    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 = false;
    this.isText = false;
    this.isSurface = false;
    this.isPoint = false;
    this.isLine = false;
    this.dynamic = true;
    this.visible = true;
    this.wireframeIndexCount = 0;
    this.parameters = createParams(params, this.defaultParameters);
    this.uniforms = __WEBPACK_IMPORTED_MODULE_0_three__["U" /* UniformsUtils */].merge([
        __WEBPACK_IMPORTED_MODULE_0_three__["T" /* UniformsLib */].common,
        {
            fogColor: { value: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](0x000000) },
            fogNear: { value: 0.0 },
            fogFar: { value: 0.0 },
            opacity: { value: this.parameters.opacity },
            clipNear: { value: 0.0 },
            clipRadius: { value: this.parameters.clipRadius },
            clipCenter: { value: this.parameters.clipCenter }
        },
        {
            emissive: { value: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](0x000000) },
            roughness: { value: this.parameters.roughness },
            metalness: { value: this.parameters.metalness },
            interiorColor: { value: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.parameters.interiorColor) },
            interiorDarkening: { value: this.parameters.interiorDarkening },
        },
        __WEBPACK_IMPORTED_MODULE_0_three__["T" /* UniformsLib */].lights
    ]);
    this.uniforms.diffuse.value.set(this.parameters.diffuse);
    this.pickingUniforms = {
        clipNear: { value: 0.0 },
        objectId: { value: 0 },
        opacity: { value: this.parameters.opacity }
    };
    //
    var position = data.position || data.position1;
    this._positionDataSize = position ? position.length / 3 : 0;
    if (!data.primitiveId) {
        data.primitiveId = serialArray(this._positionDataSize);
    }
    this.addAttributes({
        position: { type: 'v3', value: data.position },
        color: { type: 'c', value: data.color },
        primitiveId: { type: 'f', value: data.primitiveId }
    });
    if (params.matrix) {
        this.matrix = params.matrix;
    }
    if (data.index) {
        this.initIndex(data.index);
    }
    this.picking = data.picking;
    this.makeWireframeGeometry();
};

var prototypeAccessors$c = { defaultParameters: { configurable: true },matrix: { configurable: true },transparent: { configurable: true },size: { configurable: true },attributeSize: { configurable: true },pickable: { configurable: true } };
prototypeAccessors$c.defaultParameters.get = function () { return BufferDefaultParameters; };
prototypeAccessors$c.matrix.set = function (m) {
    this.setMatrix(m);
};
prototypeAccessors$c.matrix.get = function () {
    return this.group.matrix.clone();
};
prototypeAccessors$c.transparent.get = function () {
    return this.parameters.opacity < 1 || this.parameters.forceTransparent;
};
prototypeAccessors$c.size.get = function () {
    return this._positionDataSize;
};
prototypeAccessors$c.attributeSize.get = function () {
    return this.size;
};
prototypeAccessors$c.pickable.get = function () {
    return !!this.picking && !this.parameters.disablePicking;
};
Buffer.prototype.setMatrix = function setMatrix (m) {
    setObjectMatrix(this.group, m);
    setObjectMatrix(this.wireframeGroup, m);
    setObjectMatrix(this.pickingGroup, m);
};
Buffer.prototype.initIndex = function initIndex (index) {
    this.geometry.setIndex(new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](index, 1));
    var nindex = this.geometry.getIndex();
    if (!nindex) {
        Log.error('Index is null');
        return;
    }
    nindex.setUsage(this.dynamic ? WebGLRenderingContext.DYNAMIC_DRAW : 0);
};
Buffer.prototype.makeMaterial = function makeMaterial () {
    var side = getThreeSide(this.parameters.side);
    var m = new __WEBPACK_IMPORTED_MODULE_0_three__["N" /* ShaderMaterial */]({
        uniforms: this.uniforms,
        vertexShader: '',
        fragmentShader: '',
        depthTest: true,
        transparent: this.transparent,
        depthWrite: this.parameters.depthWrite,
        lights: true,
        fog: true,
        side: side
    });
    m.vertexColors = true;
    m.extensions.derivatives = true;
    m.extensions.fragDepth = this.isImpostor;
    var wm = new __WEBPACK_IMPORTED_MODULE_0_three__["N" /* ShaderMaterial */]({
        uniforms: this.uniforms,
        vertexShader: '',
        fragmentShader: '',
        depthTest: true,
        transparent: this.transparent,
        depthWrite: this.parameters.depthWrite,
        lights: false,
        fog: true,
        side: side
    });
    wm.vertexColors = true;
    var pm = new __WEBPACK_IMPORTED_MODULE_0_three__["N" /* ShaderMaterial */]({
        uniforms: this.pickingUniforms,
        vertexShader: '',
        fragmentShader: '',
        depthTest: true,
        transparent: false,
        depthWrite: this.parameters.depthWrite,
        lights: false,
        fog: false,
        side: side,
        blending: __WEBPACK_IMPORTED_MODULE_0_three__["B" /* NoBlending */]
    });
    pm.vertexColors = true;
    pm.extensions.fragDepth = this.isImpostor;
    m.clipNear = this.parameters.clipNear;
    wm.clipNear = this.parameters.clipNear;
    pm.clipNear = this.parameters.clipNear;
    this.material = m;
    this.wireframeMaterial = wm;
    this.pickingMaterial = pm;
    // also sets vertexShader/fragmentShader
    this.updateShader();
};
Buffer.prototype.makeWireframeGeometry = function makeWireframeGeometry () {
    this.makeWireframeIndex();
    var geometry = this.geometry;
    var wireframeIndex = this.wireframeIndex;
    var wireframeGeometry = new __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]();
    wireframeGeometry.attributes = geometry.attributes;
    if (wireframeIndex) {
        wireframeGeometry.setIndex(new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](wireframeIndex, 1).setUsage(this.dynamic ? WebGLRenderingContext.DYNAMIC_DRAW : 0));
        wireframeGeometry.setDrawRange(0, this.wireframeIndexCount);
    }
    this.wireframeGeometry = wireframeGeometry;
};
Buffer.prototype.makeWireframeIndex = function makeWireframeIndex () {
    var edges = [];
    function checkEdge(a, b) {
        if (a > b) {
            var tmp = a;
            a = b;
            b = tmp;
        }
        var list = edges[a];
        if (list === undefined) {
            edges[a] = [b];
            return true;
        }
        else if (!list.includes(b)) {
            list.push(b);
            return true;
        }
        return false;
    }
    var geometry = this.geometry;
    var index = geometry.index;
    if (!this.parameters.wireframe) {
        this.wireframeIndex = new Uint16Array(0);
        this.wireframeIndexCount = 0;
    }
    else if (index) {
        var array = index.array;
        var n = array.length;
        if (geometry.drawRange.count !== Infinity) {
            n = geometry.drawRange.count;
        }
        var wireframeIndex;
        if (this.wireframeIndex && this.wireframeIndex.length > n * 2) {
            wireframeIndex = this.wireframeIndex;
        }
        else {
            var count = geometry.attributes.position.count; // TODO
            wireframeIndex = getUintArray(n * 2, count);
        }
        var j = 0;
        edges.length = 0;
        for (var i = 0; i < n; i += 3) {
            var a = array[i + 0];
            var b = array[i + 1];
            var c = array[i + 2];
            if (checkEdge(a, b)) {
                wireframeIndex[j + 0] = a;
                wireframeIndex[j + 1] = b;
                j += 2;
            }
            if (checkEdge(b, c)) {
                wireframeIndex[j + 0] = b;
                wireframeIndex[j + 1] = c;
                j += 2;
            }
            if (checkEdge(c, a)) {
                wireframeIndex[j + 0] = c;
                wireframeIndex[j + 1] = a;
                j += 2;
            }
        }
        this.wireframeIndex = wireframeIndex;
        this.wireframeIndexCount = j;
        this.wireframeIndexVersion = this.indexVersion;
    }
    else {
        var n$1 = geometry.attributes.position.count; // TODO
        var wireframeIndex$1;
        if (this.wireframeIndex && this.wireframeIndex.length > n$1 * 2) {
            wireframeIndex$1 = this.wireframeIndex;
        }
        else {
            wireframeIndex$1 = getUintArray(n$1 * 2, n$1);
        }
        for (var i$1 = 0, j$1 = 0; i$1 < n$1; i$1 += 3) {
            wireframeIndex$1[j$1 + 0] = i$1;
            wireframeIndex$1[j$1 + 1] = i$1 + 1;
            wireframeIndex$1[j$1 + 2] = i$1 + 1;
            wireframeIndex$1[j$1 + 3] = i$1 + 2;
            wireframeIndex$1[j$1 + 4] = i$1 + 2;
            wireframeIndex$1[j$1 + 5] = i$1;
            j$1 += 6;
        }
        this.wireframeIndex = wireframeIndex$1;
        this.wireframeIndexCount = n$1 * 2;
        this.wireframeIndexVersion = this.indexVersion;
    }
};
Buffer.prototype.updateWireframeIndex = function updateWireframeIndex () {
    if (!this.wireframeGeometry || !this.wireframeIndex)
        { return; }
    this.wireframeGeometry.setDrawRange(0, Infinity);
    if (this.wireframeIndexVersion < this.indexVersion)
        { this.makeWireframeIndex(); }
    if (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 {
        var index = this.wireframeGeometry.getIndex();
        if (!index) {
            Log.error('Index is null');
            return;
        }
        index.set(this.wireframeIndex);
        index.needsUpdate = this.wireframeIndexCount > 0;
        index.updateRange.count = this.wireframeIndexCount;
    }
    this.wireframeGeometry.setDrawRange(0, this.wireframeIndexCount);
};
Buffer.prototype.getRenderOrder = function getRenderOrder () {
    var renderOrder = 0;
    if (this.isText) {
        renderOrder = 1;
    }
    else if (this.transparent) {
        if (this.isSurface) {
            renderOrder = 3;
        }
        else {
            renderOrder = 2;
        }
    }
    return renderOrder;
};
Buffer.prototype._getMesh = function _getMesh (materialName) {
    if (!this.material)
        { this.makeMaterial(); }
    var g = this.geometry;
    var m = this[materialName];
    var mesh;
    if (this.isLine) {
        mesh = new __WEBPACK_IMPORTED_MODULE_0_three__["v" /* LineSegments */](g, m);
    }
    else if (this.isPoint) {
        mesh = new __WEBPACK_IMPORTED_MODULE_0_three__["I" /* Points */](g, m);
    }
    else {
        mesh = new __WEBPACK_IMPORTED_MODULE_0_three__["z" /* Mesh */](g, m);
    }
    mesh.frustumCulled = false;
    mesh.renderOrder = this.getRenderOrder();
    return mesh;
};
Buffer.prototype.getMesh = function getMesh () {
    return this._getMesh('material');
};
Buffer.prototype.getWireframeMesh = function getWireframeMesh () {
    var mesh;
    if (!this.material)
        { this.makeMaterial(); }
    if (!this.wireframeGeometry)
        { this.makeWireframeGeometry(); }
    mesh = new __WEBPACK_IMPORTED_MODULE_0_three__["v" /* LineSegments */](this.wireframeGeometry, this.wireframeMaterial);
    mesh.frustumCulled = false;
    mesh.renderOrder = this.getRenderOrder();
    return mesh;
};
Buffer.prototype.getPickingMesh = function getPickingMesh () {
    return this._getMesh('pickingMaterial');
};
Buffer.prototype.getShader = function getShader$1 (name, type) {
    return getShader(name, this.getDefines(type));
};
Buffer.prototype.getVertexShader = function getVertexShader (type) {
    return this.getShader(this.vertexShader, type);
};
Buffer.prototype.getFragmentShader = function getFragmentShader (type) {
    return this.getShader(this.fragmentShader, type);
};
Buffer.prototype.getDefines = function getDefines (type) {
    var defines = {};
    if (this.parameters.clipNear) {
        defines.NEAR_CLIP = 1;
    }
    if (this.parameters.clipRadius) {
        defines.RADIUS_CLIP = 1;
    }
    if (type === 'picking') {
        defines.PICKING = 1;
    }
    else {
        if (type === 'background' || this.parameters.background) {
            defines.NOLIGHT = 1;
        }
        if (this.parameters.flatShaded) {
            defines.FLAT_SHADED = 1;
        }
        if (this.parameters.opaqueBack) {
            defines.OPAQUE_BACK = 1;
        }
        if (this.parameters.diffuseInterior) {
            defines.DIFFUSE_INTERIOR = 1;
        }
        if (this.parameters.useInteriorColor) {
            defines.USE_INTERIOR_COLOR = 1;
        }
    }
    return defines;
};
Buffer.prototype.getParameters = function getParameters () {
    return this.parameters;
};
Buffer.prototype.addUniforms = function addUniforms (uniforms) {
    this.uniforms = __WEBPACK_IMPORTED_MODULE_0_three__["U" /* UniformsUtils */].merge([this.uniforms, uniforms]);
    this.pickingUniforms = __WEBPACK_IMPORTED_MODULE_0_three__["U" /* UniformsUtils */].merge([this.pickingUniforms, uniforms]);
};
Buffer.prototype.addAttributes = function addAttributes (attributes) {
    for (var name in attributes) {
        var buf = (void 0);
        var a = attributes[name];
        var arraySize = this.attributeSize * itemSize[a.type];
        if (a.value) {
            if (arraySize !== a.value.length) {
                Log.error('attribute value has wrong length', name);
            }
            buf = a.value;
        }
        else {
            buf = getTypedArray('float32', arraySize);
        }
        this.geometry.setAttribute(name, new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](buf, itemSize[a.type]).setUsage(this.dynamic ? WebGLRenderingContext.DYNAMIC_DRAW : 0));
    }
};
Buffer.prototype.updateRenderOrder = function updateRenderOrder () {
    var renderOrder = this.getRenderOrder();
    function setRenderOrder(mesh) {
        mesh.renderOrder = renderOrder;
    }
    this.group.children.forEach(setRenderOrder);
    if (this.pickingGroup) {
        this.pickingGroup.children.forEach(setRenderOrder);
    }
};
Buffer.prototype.updateShader = function updateShader () {
    var m = this.material;
    var wm = this.wireframeMaterial;
    var pm = this.pickingMaterial;
    m.vertexShader = this.getVertexShader();
    m.fragmentShader = this.getFragmentShader();
    m.needsUpdate = true;
    wm.vertexShader = this.getShader('Line.vert');
    wm.fragmentShader = this.getShader('Line.frag');
    wm.needsUpdate = true;
    pm.vertexShader = this.getVertexShader('picking');
    pm.fragmentShader = this.getFragmentShader('picking');
    pm.needsUpdate = true;
};
/**
 * Set buffer parameters
 * @param {BufferParameters} params - buffer parameters object
 * @return {undefined}
 */
Buffer.prototype.setParameters = function setParameters (params) {
    var p = params;
    var pt = this.parameterTypes;
    var pv = this.parameters;
    var propertyData = {};
    var uniformData = {};
    var doShaderUpdate = false;
    var doVisibilityUpdate = false;
    for (var name in p) {
        var value = p[name];
        if (value === undefined)
            { continue; }
        pv[name] = value;
        if (pt[name] === undefined)
            { continue; }
        if (pt[name].property) {
            if (pt[name].property !== true) {
                propertyData[pt[name].property] = value;
            }
            else {
                propertyData[name] = value;
            }
        }
        if (pt[name].uniform) {
            if (pt[name].uniform !== true) {
                uniformData[pt[name].uniform] = value;
            }
            else {
                uniformData[name] = value;
            }
        }
        if (pt[name].updateShader) {
            doShaderUpdate = true;
        }
        if (pt[name].updateVisibility) {
            doVisibilityUpdate = true;
        }
        if (this.dynamic && name === 'wireframe' && value === true) {
            this.updateWireframeIndex();
        }
        if (name === 'forceTransparent') {
            propertyData.transparent = this.transparent;
        }
        if (name === 'matrix') {
            this.matrix = value;
        }
    }
    this.setProperties(propertyData);
    this.setUniforms(uniformData);
    if (doShaderUpdate)
        { this.updateShader(); }
    if (doVisibilityUpdate)
        { this.setVisibility(this.visible); }
};
/**
 * Sets buffer attributes
 * @param {Object} data - An object where the keys are the attribute names
 *  and the values are the attribute data.
 * @example
 * var buffer = new Buffer();
 * buffer.setAttributes({ attrName: attrData });
 */
Buffer.prototype.setAttributes = function setAttributes (data) {
    var geometry = this.geometry;
    var attributes = geometry.attributes; // TODO
    for (var name in data) {
        if (name === 'picking')
            { continue; }
        var array = data[name];
        var length = array.length;
        if (name === 'index') {
            var index = geometry.getIndex();
            if (!index) {
                Log.error('Index is null');
                continue;
            }
            geometry.setDrawRange(0, Infinity);
            if (length > index.array.length) {
                geometry.setIndex(new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](array, 1)
                    .setUsage(this.dynamic ? WebGLRenderingContext.DYNAMIC_DRAW : 0));
            }
            else {
                index.set(array);
                index.needsUpdate = length > 0;
                index.updateRange.count = length;
                geometry.setDrawRange(0, length);
            }
            this.indexVersion++;
            if (this.parameters.wireframe)
                { this.updateWireframeIndex(); }
        }
        else {
            var attribute = attributes[name];
            if (length > attribute.array.length) {
                geometry.setAttribute(name, new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](array, attribute.itemSize)
                    .setUsage(this.dynamic ? WebGLRenderingContext.DYNAMIC_DRAW : 0));
            }
            else {
                attributes[name].set(array);
                attributes[name].needsUpdate = length > 0;
                attributes[name].updateRange.count = length;
            }
        }
    }
};
Buffer.prototype.setUniforms = function setUniforms (data) {
    if (!data)
        { return; }
    var u = this.material.uniforms;
    var wu = this.wireframeMaterial.uniforms;
    var pu = this.pickingMaterial.uniforms;
    for (var name in data) {
        if (name === 'opacity') {
            this.setProperties({ transparent: this.transparent });
        }
        if (u[name] !== undefined) {
            if (u[name].value.isVector3) {
                u[name].value.copy(data[name]);
            }
            else if (u[name].value.set) {
                u[name].value.set(data[name]);
            }
            else {
                u[name].value = data[name];
            }
        }
        if (wu[name] !== undefined) {
            if (wu[name].value.isVector3) {
                wu[name].value.copy(data[name]);
            }
            else if (wu[name].value.set) {
                wu[name].value.set(data[name]);
            }
            else {
                wu[name].value = data[name];
            }
        }
        if (pu[name] !== undefined) {
            if (pu[name].value.isVector3) {
                pu[name].value.copy(data[name]);
            }
            else if (pu[name].value.set) {
                pu[name].value.set(data[name]);
            }
            else {
                pu[name].value = data[name];
            }
        }
    }
};
Buffer.prototype.setProperties = function setProperties (data) {
    if (!data)
        { return; }
    var m = this.material;
    var wm = this.wireframeMaterial;
    var pm = this.pickingMaterial;
    for (var _name in data) {
        var name = _name; // TODO
        var value = data[name];
        if (name === 'transparent') {
            this.updateRenderOrder();
        }
        else if (name === 'side') {
            value = getThreeSide(value);
        }
        m[name] = value;
        wm[name] = value;
        pm[name] = value;
    }
    m.needsUpdate = true;
    wm.needsUpdate = true;
    pm.needsUpdate = true;
};
/**
 * Set buffer visibility
 * @param {Boolean} value - visibility value
 * @return {undefined}
 */
Buffer.prototype.setVisibility = function setVisibility (value) {
    this.visible = value;
    if (this.parameters.wireframe) {
        this.group.visible = false;
        this.wireframeGroup.visible = value;
        if (this.pickable) {
            this.pickingGroup.visible = false;
        }
    }
    else {
        this.group.visible = value;
        this.wireframeGroup.visible = false;
        if (this.pickable) {
            this.pickingGroup.visible = value;
        }
    }
};
/**
 * Free buffer resources
 * @return {undefined}
 */
Buffer.prototype.dispose = function dispose () {
    if (this.material)
        { this.material.dispose(); }
    if (this.wireframeMaterial)
        { this.wireframeMaterial.dispose(); }
    if (this.pickingMaterial)
        { this.pickingMaterial.dispose(); }
    this.geometry.dispose();
    if (this.wireframeGeometry)
        { this.wireframeGeometry.dispose(); }
};
/**
 * Customize JSON serialization to avoid circular references
 */
Buffer.prototype.toJSON = function toJSON () {
    var result = {};
    for (var x in this) {
        if (x !== "group" && x !== "wireframeGroup" && x != "pickingGroup"
            && x !== "picking") {
            result[x] = this[x];
        }
    }
    return result;
};

Object.defineProperties( Buffer.prototype, prototypeAccessors$c );

/**
 * @file Mesh Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Mesh buffer. Draws a triangle mesh.
 *
 * @example
 * var meshBuffer = new MeshBuffer({
 *   position: new Float32Array(
 *     [ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1 ]
 *   ),
 *   color: new Float32Array(
 *     [ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 ]
 *   )
 * });
 */
var MeshBuffer = /*@__PURE__*/(function (Buffer$$1) {
    function MeshBuffer(data, params) {
        if ( params === void 0 ) params = {};

        Buffer$$1.call(this, data, params);
        this.vertexShader = 'Mesh.vert';
        this.fragmentShader = 'Mesh.frag';
        this.addAttributes({
            'normal': { type: 'v3', value: data.normal }
        });
        if (data.normal === undefined) {
            this.geometry.computeVertexNormals();
        }
    }

    if ( Buffer$$1 ) MeshBuffer.__proto__ = Buffer$$1;
    MeshBuffer.prototype = Object.create( Buffer$$1 && Buffer$$1.prototype );
    MeshBuffer.prototype.constructor = MeshBuffer;

    return MeshBuffer;
}(Buffer));

/**
 * @file Surface Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Surface buffer. Like a {@link MeshBuffer}, but with `.isSurface` set to `true`.
 */
var SurfaceBuffer = /*@__PURE__*/(function (MeshBuffer$$1) {
    function SurfaceBuffer() {
        MeshBuffer$$1.apply(this, arguments);
        this.isSurface = true;
    }

    if ( MeshBuffer$$1 ) SurfaceBuffer.__proto__ = MeshBuffer$$1;
    SurfaceBuffer.prototype = Object.create( MeshBuffer$$1 && MeshBuffer$$1.prototype );
    SurfaceBuffer.prototype.constructor = SurfaceBuffer;

    return SurfaceBuffer;
}(MeshBuffer));

/**
 * @file Double Sided Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function setVisibilityTrue(m) { m.visible = true; }
function setVisibilityFalse(m) { m.visible = false; }
/**
 * A double-sided mesh buffer. Takes a buffer and renders the front and
 * the back as seperate objects to avoid some artifacts when rendering
 * transparent meshes. Also allows to render the back of a mesh opaque
 * while the front is transparent.
 * @implements {Buffer}
 *
 * @example
 * var sphereGeometryBuffer = new SphereGeometryBuffer({
 *   position: new Float32Array([ 0, 0, 0 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   radius: new Float32Array([ 1 ])
 * });
 * var doubleSidedBuffer = new DoubleSidedBuffer(sphereGeometryBuffer);
 */
var DoubleSidedBuffer = function DoubleSidedBuffer(buffer) {
    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 = buffer.size;
    this.side = buffer.parameters.side;
    this.visible = buffer.visible;
    this.geometry = buffer.geometry;
    this.picking = buffer.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 */]();
    // requires Group objects to be present
    this.matrix = buffer.matrix;
    var frontBuffer = buffer;
    var backBuffer = new buffer.constructor({
        position: new Float32Array(0)
    });
    frontBuffer.makeMaterial();
    backBuffer.makeMaterial();
    backBuffer.picking = buffer.picking;
    backBuffer.geometry = buffer.geometry;
    backBuffer.wireframeGeometry = buffer.wireframeGeometry;
    backBuffer.setParameters(buffer.getParameters());
    backBuffer.updateShader();
    frontBuffer.setParameters({
        side: 'front'
    });
    backBuffer.setParameters({
        side: 'back',
        opacity: backBuffer.parameters.opacity
    });
    this.buffer = buffer;
    this.frontBuffer = frontBuffer;
    this.backBuffer = backBuffer;
};

var prototypeAccessors$d = { matrix: { configurable: true },pickable: { configurable: true },parameters: { configurable: true } };
prototypeAccessors$d.matrix.set = function (m) {
    Buffer.prototype.setMatrix.call(this, m);
};
prototypeAccessors$d.matrix.get = function () {
    return this.group.matrix.clone();
};
prototypeAccessors$d.pickable.get = function () {
    return !!this.picking && !this.parameters.disablePicking;
};
prototypeAccessors$d.parameters.get = function () {
    return this.buffer.parameters;
};
DoubleSidedBuffer.prototype.getParameters = function getParameters () {
    var p = Object.assign({}, this.buffer.parameters);
    p.side = this.side;
    return p;
};
DoubleSidedBuffer.prototype.getMesh = function getMesh (picking) {
    var front, back;
    if (picking) {
        back = this.backBuffer.getPickingMesh();
        front = this.frontBuffer.getPickingMesh();
    }
    else {
        back = this.backBuffer.getMesh();
        front = this.frontBuffer.getMesh();
    }
    this.frontMeshes.push(front);
    this.backMeshes.push(back);
    this.setParameters({ side: this.side });
    return new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]().add(back, front);
};
DoubleSidedBuffer.prototype.getWireframeMesh = function getWireframeMesh () {
    return this.buffer.getWireframeMesh();
};
DoubleSidedBuffer.prototype.getPickingMesh = function getPickingMesh () {
    return this.getMesh(true);
};
DoubleSidedBuffer.prototype.setAttributes = function setAttributes (data) {
    this.buffer.setAttributes(data);
};
DoubleSidedBuffer.prototype.setParameters = function setParameters (data) {
    data = Object.assign({}, data);
    if (data.side === 'front') {
        this.frontMeshes.forEach(setVisibilityTrue);
        this.backMeshes.forEach(setVisibilityFalse);
    }
    else if (data.side === 'back') {
        this.frontMeshes.forEach(setVisibilityFalse);
        this.backMeshes.forEach(setVisibilityTrue);
    }
    else if (data.side === 'double') {
        this.frontMeshes.forEach(setVisibilityTrue);
        this.backMeshes.forEach(setVisibilityTrue);
    }
    if (data.side !== undefined) {
        this.side = data.side;
    }
    delete data.side;
    if (data.matrix !== undefined) {
        this.matrix = data.matrix;
    }
    delete data.matrix;
    this.frontBuffer.setParameters(data);
    if (data.wireframe !== undefined) {
        this.wireframe = data.wireframe;
        this.setVisibility(this.visible);
    }
    delete data.wireframe;
    this.backBuffer.setParameters(data);
};
DoubleSidedBuffer.prototype.setVisibility = function setVisibility (value) {
    this.visible = value;
    if (this.parameters.wireframe) {
        this.group.visible = false;
        this.wireframeGroup.visible = value;
        if (this.pickable) {
            this.pickingGroup.visible = false;
        }
    }
    else {
        this.group.visible = value;
        this.wireframeGroup.visible = false;
        if (this.pickable) {
            this.pickingGroup.visible = value;
        }
    }
};
DoubleSidedBuffer.prototype.dispose = function dispose () {
    this.frontBuffer.dispose();
    this.backBuffer.dispose();
};
/**
 * Customize JSON serialization to avoid circular references.
 * Only export simple params which could be useful.
 */
DoubleSidedBuffer.prototype.toJSON = function toJSON () {
    var result = {};
    for (var x in this) {
        if (['side', 'size', 'visible', 'matrix', 'parameters'].includes(x)) {
            result[x] = this[x];
        }
    }
    return result;
};

Object.defineProperties( DoubleSidedBuffer.prototype, prototypeAccessors$d );

ShaderRegistry.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}");

ShaderRegistry.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}");

/**
 * @file Contour Buffer
 * @author Fred ludlow <fred.ludlow@gmail.com>
 * @private
 */
/**
 * Contour buffer. A buffer that draws lines (instead of triangle meshes).
 */
var ContourBuffer = /*@__PURE__*/(function (Buffer$$1) {
    function ContourBuffer() {
        Buffer$$1.apply(this, arguments);
        this.isLine = true;
        this.vertexShader = 'Line.vert';
        this.fragmentShader = 'Line.frag';
    }

    if ( Buffer$$1 ) ContourBuffer.__proto__ = Buffer$$1;
    ContourBuffer.prototype = Object.create( Buffer$$1 && Buffer$$1.prototype );
    ContourBuffer.prototype.constructor = ContourBuffer;

    return ContourBuffer;
}(Buffer));

/**
 * @file Surface Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Surface representation
 */
/**
   * Create Surface representation object
   * @param {Surface|Volume} surface - the surface or volume to be represented
   * @param {Viewer} viewer - a viewer object
   * @param {SurfaceRepresentationParameters} params - surface representation parameters
   */
var SurfaceRepresentation = /*@__PURE__*/(function (Representation$$1) {
   function SurfaceRepresentation(surface, viewer, params) {
        Representation$$1.call(this, surface, viewer, params);
        this.type = 'surface';
        this.parameters = Object.assign({
            isolevelType: {
                type: 'select',
                options: {
                    'value': 'value', 'sigma': 'sigma'
                }
            },
            isolevel: {
                type: 'number', precision: 2, max: 1000, min: -1000
            },
            negateIsolevel: {
                type: 'boolean'
            },
            isolevelScroll: {
                type: 'boolean'
            },
            smooth: {
                type: 'integer', precision: 1, max: 10, min: 0
            },
            background: {
                type: 'boolean', rebuild: true // FIXME
            },
            opaqueBack: {
                type: 'boolean', buffer: true
            },
            boxSize: {
                type: 'integer', precision: 1, max: 100, min: 0
            },
            colorVolume: {
                type: 'hidden'
            },
            contour: {
                type: 'boolean', rebuild: true
            },
            useWorker: {
                type: 'boolean', rebuild: true
            },
            wrap: {
                type: 'boolean', rebuild: true
            }
        }, this.parameters);
        if (surface instanceof Volume) {
            this.surface = undefined;
            this.volume = surface;
        }
        else {
            this.surface = surface;
            this.volume = undefined;
        }
        this.boxCenter = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        this.__boxCenter = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        this.box = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
        this.__box = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
        this._position = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        this.inverseMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
        this.setBox = function setBox() {
            this._position.copy(viewer.translationGroup.position).negate();
            this._position.applyMatrix4(this.inverseMatrix);
            if (!this._position.equals(this.boxCenter)) {
                this.setParameters({ 'boxCenter': this._position });
            }
        };
        this.toBePrepared = true;
        this.viewer.signals.ticked.add(this.setBox, this);
        this.init(params);
    }

   if ( Representation$$1 ) SurfaceRepresentation.__proto__ = Representation$$1;
   SurfaceRepresentation.prototype = Object.create( Representation$$1 && Representation$$1.prototype );
   SurfaceRepresentation.prototype.constructor = SurfaceRepresentation;
    SurfaceRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.colorScheme = defaults(p.colorScheme, 'uniform');
        p.colorValue = defaults(p.colorValue, 0xDDDDDD);
        this.isolevelType = defaults(p.isolevelType, 'sigma');
        this.isolevel = defaults(p.isolevel, 2.0);
        this.negateIsolevel = defaults(p.negateIsolevel, false);
        this.isolevelScroll = defaults(p.isolevelScroll, false);
        this.smooth = defaults(p.smooth, 0);
        this.background = defaults(p.background, false);
        this.opaqueBack = defaults(p.opaqueBack, true);
        this.boxSize = defaults(p.boxSize, 0);
        this.colorVolume = defaults(p.colorVolume, undefined);
        this.contour = defaults(p.contour, false);
        this.useWorker = defaults(p.useWorker, true);
        this.wrap = defaults(p.wrap, false);
        Representation$$1.prototype.init.call(this, p);
        this.inverseMatrix.getInverse(this.matrix);
        this.build();
    };
    SurfaceRepresentation.prototype.attach = function attach (callback) {
        var this$1 = this;

        this.bufferList.forEach(function (buffer) {
            this$1.viewer.add(buffer);
        });
        this.setVisibility(this.visible);
        callback();
    };
    SurfaceRepresentation.prototype.prepare = function prepare (callback) {
        var this$1 = this;

        if (this.volume) {
            var isolevel;
            if (this.isolevelType === 'sigma') {
                isolevel = this.volume.getValueForSigma(this.isolevel);
            }
            else {
                isolevel = this.isolevel;
            }
            if (this.negateIsolevel)
                { isolevel *= -1; }
            if (!this.surface ||
                this.__isolevel !== isolevel ||
                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 = isolevel;
                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);
                var onSurfaceFinish = function (surface) {
                    this$1.surface = surface;
                    callback();
                };
                if (this.useWorker) {
                    this.volume.getSurfaceWorker(isolevel, this.smooth, this.boxCenter, this.boxSize, this.contour, this.wrap, onSurfaceFinish);
                }
                else {
                    onSurfaceFinish(this.volume.getSurface(isolevel, this.smooth, this.boxCenter, this.boxSize, this.contour, this.wrap));
                }
            }
            else {
                callback();
            }
        }
        else {
            callback();
        }
    };
    SurfaceRepresentation.prototype.create = function create () {
        var sd = {
            position: this.surface.getPosition(),
            color: this.surface.getColor(this.getColorParams()),
            index: this.surface.getIndex()
        };
        var buffer;
        if (this.contour) {
            buffer = new ContourBuffer(sd, this.getBufferParams({ wireframe: false }));
        }
        else {
            Object.assign(sd, {
                normal: this.surface.getNormal(),
                picking: this.surface.getPicking()
            });
            var surfaceBuffer = new SurfaceBuffer(sd, this.getBufferParams({
                background: this.background,
                opaqueBack: this.opaqueBack,
                dullInterior: false
            }));
            buffer = new DoubleSidedBuffer(surfaceBuffer);
        }
        this.bufferList.push(buffer);
    };
    SurfaceRepresentation.prototype.update = function update (what) {
        if (this.bufferList.length === 0)
            { return; }
        what = what || {};
        var surfaceData = {};
        if (what.position) {
            surfaceData.position = this.surface.getPosition();
        }
        if (what.color) {
            surfaceData.color = this.surface.getColor(this.getColorParams());
        }
        if (what.index) {
            surfaceData.index = this.surface.getIndex();
        }
        if (what.normal) {
            surfaceData.normal = this.surface.getNormal();
        }
        this.bufferList.forEach(function (buffer) {
            buffer.setAttributes(surfaceData);
        });
    };
    /**
     * Set representation parameters
     * @alias SurfaceRepresentation#setParameters
     * @param {SurfaceRepresentationParameters} params - surface parameter object
     * @param {Object} [what] - buffer data attributes to be updated,
     *                        note that this needs to be implemented in the
     *                        derived classes. Generally it allows more
     *                        fine-grained control over updating than
     *                        forcing a rebuild.
     * @param {Boolean} what.position - update position data
     * @param {Boolean} what.color - update color data
     * @param {Boolean} [rebuild] - whether or not to rebuild the representation
     * @return {SurfaceRepresentation} this object
     */
    SurfaceRepresentation.prototype.setParameters = function setParameters (params, what, rebuild) {
        if (params && params.isolevelType !== undefined &&
            this.volume) {
            if (this.isolevelType === 'value' &&
                params.isolevelType === 'sigma') {
                this.isolevel = this.volume.getSigmaForValue(this.isolevel);
            }
            else if (this.isolevelType === 'sigma' &&
                params.isolevelType === 'value') {
                this.isolevel = this.volume.getValueForSigma(this.isolevel);
            }
            this.isolevelType = params.isolevelType;
        }
        if (params && params.boxCenter) {
            this.boxCenter.copy(params.boxCenter);
            delete params.boxCenter;
        }
        // Forbid wireframe && contour as in molsurface
        if (params && params.wireframe && (params.contour || (params.contour === undefined && this.contour))) {
            params.wireframe = false;
        }
        Representation$$1.prototype.setParameters.call(this, params, what, rebuild);
        if (params.matrix) {
            this.inverseMatrix.getInverse(params.matrix);
        }
        if (this.volume) {
            this.volume.getBox(this.boxCenter, this.boxSize, this.box);
        }
        if (params && params.colorVolume !== undefined) {
            if (what)
                { what.color = true; }
        }
        if (this.surface && (params.isolevel !== undefined ||
            params.negateIsolevel !== undefined ||
            params.smooth !== undefined ||
            params.wrap !== undefined ||
            params.boxSize !== undefined ||
            (this.boxSize > 0 &&
                !this.__box.equals(this.box)))) {
            this.build({
                'position': true,
                'color': true,
                'index': true,
                'normal': !this.contour
            });
        }
        return this;
    };
    SurfaceRepresentation.prototype.getColorParams = function getColorParams () {
        var p = Representation$$1.prototype.getColorParams.call(this);
        p.volume = this.colorVolume;
        return p;
    };
    SurfaceRepresentation.prototype.dispose = function dispose () {
        this.viewer.signals.ticked.remove(this.setBox, this);
        Representation$$1.prototype.dispose.call(this);
    };

   return SurfaceRepresentation;
}(Representation));

/**
 * @file Mouse Actions
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Mouse actions provided as static methods
 */
var MouseActions = function MouseActions () {};

MouseActions.zoomScroll = function zoomScroll (stage, delta) {
    stage.trackballControls.zoom(delta);
};
/**
 * Move near clipping plane based on scroll-delta
 * @param {Stage} stage - the stage
 * @param {Number} delta - amount to move clipping plane
 * @return {undefined}
 */
MouseActions.clipNearScroll = function clipNearScroll (stage, delta) {
    var sp = stage.getParameters();
    stage.setParameters({ clipNear: sp.clipNear + delta / 10 });
};
/**
 * Move clipping planes based on scroll-delta.
 * @param {Stage} stage - the stage
 * @param {Number} delta - direction to move planes
 * @return {undefined}
 */
MouseActions.focusScroll = function focusScroll (stage, delta) {
    var focus = stage.getFocus();
    var sign = Math.sign(delta);
    var step = sign * almostIdentity((100 - focus) / 10, 5, 0.2);
    stage.setFocus(focus + step);
};
/**
 * Zoom scene based on scroll-delta and
 * move focus planes based on camera position (zoom)
 * @param {Stage} stage - the stage
 * @param {Number} delta - amount to move focus planes and zoom
 * @return {undefined}
 */
MouseActions.zoomFocusScroll = function zoomFocusScroll (stage, delta) {
    stage.trackballControls.zoom(delta);
    var z = stage.viewer.camera.position.z;
    stage.setFocus(100 - Math.abs(z / 8));
};
/**
 * Change isolevel of volume surfaces based on scroll-delta
 * @param {Stage} stage - the stage
 * @param {Number} delta - amount to change isolevel
 * @return {undefined}
 */
MouseActions.isolevelScroll = function isolevelScroll (stage, delta) {
    var d = Math.sign(delta) / 10;
    stage.eachRepresentation(function (reprElem, comp) {
        if (reprElem.repr instanceof SurfaceRepresentation) {
            var p = reprElem.getParameters(); // TODO
            if (p.isolevelScroll) {
                reprElem.setParameters({ isolevel: p.isolevel + d });
            }
        }
    });
};
/**
 * Pan scene based on mouse coordinate changes
 * @param {Stage} stage - the stage
 * @param {Number} dx - amount to pan in x direction
 * @param {Number} dy - amount to pan in y direction
 * @return {undefined}
 */
MouseActions.panDrag = function panDrag (stage, dx, dy) {
    stage.trackballControls.pan(dx, dy);
};
/**
 * Rotate scene based on mouse coordinate changes
 * @param {Stage} stage - the stage
 * @param {Number} dx - amount to rotate in x direction
 * @param {Number} dy - amount to rotate in y direction
 * @return {undefined}
 */
MouseActions.rotateDrag = function rotateDrag (stage, dx, dy) {
    stage.trackballControls.rotate(dx, dy);
};
/**
 * Rotate scene around z axis based on mouse coordinate changes
 * @param {Stage} stage - the stage
 * @param {Number} dx - amount to rotate in x direction
 * @param {Number} dy - amount to rotate in y direction
 * @return {undefined}
 */
MouseActions.zRotateDrag = function zRotateDrag (stage, dx, dy) {
    stage.trackballControls.zRotate(dx, dy);
};
/**
 * Zoom scene based on mouse coordinate changes
 * @param {Stage} stage - the stage
 * @param {Number} dx - amount to zoom
 * @param {Number} dy - amount to zoom
 * @return {undefined}
 */
MouseActions.zoomDrag = function zoomDrag (stage, dx, dy) {
    stage.trackballControls.zoom((dx + dy) / -2);
};
/**
 * Zoom scene based on mouse coordinate changes and
 * move focus planes based on camera position (zoom)
 * @param {Stage} stage - the stage
 * @param {Number} dx - amount to zoom and focus
 * @param {Number} dy - amount to zoom and focus
 * @return {undefined}
 */
MouseActions.zoomFocusDrag = function zoomFocusDrag (stage, dx, dy) {
    stage.trackballControls.zoom((dx + dy) / -2);
    var z = stage.viewer.camera.position.z;
    stage.setFocus(100 - Math.abs(z / 8));
};
/**
 * Pan picked component based on mouse coordinate changes
 * @param {Stage} stage - the stage
 * @param {Number} dx - amount to pan in x direction
 * @param {Number} dy - amount to pan in y direction
 * @return {undefined}
 */
MouseActions.panComponentDrag = function panComponentDrag (stage, dx, dy) {
    stage.trackballControls.panComponent(dx, dy);
};
/**
 * Pan picked atom based on mouse coordinate changes
 * @param {Stage} stage - the stage
 * @param {Number} dx - amount to pan in x direction
 * @param {Number} dy - amount to pan in y direction
 * @return {undefined}
 */
MouseActions.panAtomDrag = function panAtomDrag (stage, dx, dy) {
    stage.trackballControls.panAtom(dx, dy);
};
/**
 * Rotate picked component based on mouse coordinate changes
 * @param {Stage} stage - the stage
 * @param {Number} dx - amount to rotate in x direction
 * @param {Number} dy - amount to rotate in y direction
 * @return {undefined}
 */
MouseActions.rotateComponentDrag = function rotateComponentDrag (stage, dx, dy) {
    stage.trackballControls.rotateComponent(dx, dy);
};
/**
 * Move picked element to the center of the screen
 * @param {Stage} stage - the stage
 * @param {PickingProxy} pickingProxy - the picking data object
 * @return {undefined}
 */
MouseActions.movePick = function movePick (stage, pickingProxy) {
    if (pickingProxy) {
        stage.animationControls.move(pickingProxy.position.clone());
    }
};
/**
 * Show tooltip with information of picked element
 * @param {Stage} stage - the stage
 * @param {PickingProxy} pickingProxy - the picking data object
 * @return {undefined}
 */
MouseActions.tooltipPick = function tooltipPick (stage, pickingProxy) {
    var tt = stage.tooltip;
    var sp = stage.getParameters();
    if (sp.tooltip && pickingProxy) {
        var mp = pickingProxy.mouse.position;
        tt.innerText = pickingProxy.getLabel();
        tt.style.bottom = (window.innerHeight - mp.y + 3) + 'px';
        tt.style.left = (mp.x + 3) + 'px';
        tt.style.display = 'block';
    }
    else {
        tt.style.display = 'none';
    }
};
MouseActions.measurePick = function measurePick (stage, pickingProxy) {
    if (pickingProxy && (pickingProxy.atom || pickingProxy.bond)) {
        var atom = pickingProxy.atom || pickingProxy.closestBondAtom;
        var sc = pickingProxy.component;
        sc.measurePick(atom);
    }
    else {
        stage.measureClear();
    }
};
var MouseActionPresets = {
    default: [
        ['scroll', MouseActions.zoomScroll],
        ['scroll-shift', MouseActions.focusScroll],
        ['scroll-ctrl', MouseActions.isolevelScroll],
        ['scroll-shift-ctrl', MouseActions.zoomFocusScroll],
        ['drag-left', MouseActions.rotateDrag],
        ['drag-right', MouseActions.panDrag],
        ['drag-ctrl-left', MouseActions.panDrag],
        ['drag-ctrl-right', MouseActions.zRotateDrag],
        ['drag-shift-left', MouseActions.zoomDrag],
        ['drag-middle', MouseActions.zoomFocusDrag],
        ['drag-ctrl-shift-right', MouseActions.panComponentDrag],
        ['drag-ctrl-shift-left', MouseActions.rotateComponentDrag],
        ['clickPick-right', MouseActions.measurePick],
        ['clickPick-ctrl-left', MouseActions.measurePick],
        ['clickPick-middle', MouseActions.movePick],
        ['clickPick-left', MouseActions.movePick],
        ['hoverPick', MouseActions.tooltipPick]
    ],
    pymol: [
        ['drag-left', MouseActions.rotateDrag],
        ['drag-middle', MouseActions.panDrag],
        ['drag-right', MouseActions.zoomDrag],
        ['drag-shift-right', MouseActions.focusScroll],
        ['clickPick-ctrl+shift-middle', MouseActions.movePick],
        ['hoverPick', MouseActions.tooltipPick]
    ],
    coot: [
        ['scroll', MouseActions.isolevelScroll],
        ['drag-left', MouseActions.rotateDrag],
        ['drag-middle', MouseActions.panDrag],
        ['drag-ctrl-left', MouseActions.panDrag],
        ['drag-right', MouseActions.zoomFocusDrag],
        ['drag-ctrl-right', MouseActions.focusScroll],
        ['clickPick-middle', MouseActions.movePick],
        ['hoverPick', MouseActions.tooltipPick]
    ],
    astexviewer: [
        ['drag-left', MouseActions.rotateDrag],
        ['drag-ctrl-left', MouseActions.panDrag],
        ['drag-shift-left', MouseActions.zoomDrag],
        ['scroll', MouseActions.focusScroll],
        ['clickPick-middle', MouseActions.movePick],
        ['hoverPick', MouseActions.tooltipPick]
    ]
};

/**
 * @file Mouse Controls
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Strings to describe mouse events (including optional keyboard modifiers).
 * Must contain an event type: "scroll", "drag", "click", "doubleClick",
 * "hover", "clickPick" or "hoverPick". Optionally contain one or more
 * (seperated by plus signs) keyboard modifiers: "alt", "ctrl", "meta" or
 * "shift". Can contain the mouse button performing the event: "left",
 * "middle" or "right". The type, key and button parts must be seperated by
 * dashes.
 *
 * @example
 * // triggered on scroll event (no key or button)
 * "scroll"
 *
 * @example
 * // triggered on scroll event while shift key is pressed
 * "scroll-shift"
 *
 * @example
 * // triggered on drag event with left mouse button
 * "drag-left"
 *
 * @example
 * // triggered on drag event with right mouse button
 * // while ctrl and shift keys are pressed
 * "drag-right-ctrl+shift"
 *
 * @typedef {String} TriggerString
 */
/**
 * Get event type, key and button
 * @param  {TriggerString} str - input trigger string
 * @return {Array} event type, key and button
 */
function triggerFromString(str) {
    var tokens = str.split(/[-+]/);
    var type = '';
    if (tokens.includes('scroll'))
        { type = 'scroll'; }
    if (tokens.includes('drag'))
        { type = 'drag'; }
    if (tokens.includes('click'))
        { type = 'click'; }
    if (tokens.includes('doubleClick'))
        { type = 'doubleClick'; }
    if (tokens.includes('hover'))
        { type = 'hover'; }
    if (tokens.includes('clickPick'))
        { type = 'clickPick'; }
    if (tokens.includes('hoverPick'))
        { type = 'hoverPick'; }
    var key = 0;
    if (tokens.includes('alt'))
        { key += 1; }
    if (tokens.includes('ctrl'))
        { key += 2; }
    if (tokens.includes('meta'))
        { key += 4; }
    if (tokens.includes('shift'))
        { key += 8; }
    var button = 0;
    if (tokens.includes('left'))
        { button += 1; }
    if (tokens.includes('right'))
        { button += 2; }
    if (tokens.includes('middle'))
        { button += 4; }
    return [type, key, button];
}
/**
 * Mouse controls
 */
var MouseControls = function MouseControls(stage, params) {
    if ( params === void 0 ) params = {};

    this.stage = stage;
    this.actionList = [];
    this.mouse = stage.mouseObserver;
    this.disabled = params.disabled || false;
    this.preset(params.preset || 'default');
};
MouseControls.prototype.run = function run (type) {
        var this$1 = this;
        var args = [], len = arguments.length - 1;
        while ( len-- > 0 ) args[ len ] = arguments[ len + 1 ];

    if (this.disabled)
        { return; }
    var key = this.mouse.key || 0;
    var button = this.mouse.buttons || 0;
    this.actionList.forEach(function (a) {
        if (a.type === type && a.key === key && a.button === button) {
            a.callback.apply(a, [ this$1.stage ].concat( args )); // TODO
        }
    });
};
/**
 * Add a new mouse action triggered by an event, key and button combination.
 * The {@link MouseActions} class provides a number of static methods for
 * use as callback functions.
 *
 * @example
 * // change ambient light intensity on mouse scroll
 * // while the ctrl and shift keys are pressed
 * stage.mouseControls.add( "scroll-ctrl+shift", function( stage, delta ){
 * var ai = stage.getParameters().ambientIntensity;
 * stage.setParameters( { ambientIntensity: Math.max( 0, ai + delta / 50 ) } );
 * } );
 *
 * @example
 * // Call the MouseActions.zoomDrag method on mouse drag events
 * // with left and right mouse buttons simultaneous
 * stage.mouseControls.add( "drag-left+right", MouseActions.zoomDrag );
 *
 * @param {TriggerString} triggerStr - the trigger for the action
 * @param {function(stage: Stage, ...args: Any)} callback - the callback function for the action
 * @return {undefined}
 */
MouseControls.prototype.add = function add (triggerStr, callback) {
    var ref = triggerFromString(triggerStr);
        var type = ref[0];
        var key = ref[1];
        var button = ref[2];
    this.actionList.push({ type: type, key: key, button: button, callback: callback });
};
/**
 * Remove a mouse action. The trigger string can contain an asterix (*)
 * as a wildcard for any key or mouse button. When the callback function
 * is given, only actions that call that function are removed.
 *
 * @example
 * // remove actions triggered solely by a scroll event
 * stage.mouseControls.remove( "scroll" );
 *
 * @example
 * // remove actions triggered by a scroll event, including
 * // those requiring a key pressed or mouse button used
 * stage.mouseControls.remove( "scroll-*" );
 *
 * @example
 * // remove actions triggered by a scroll event
 * // while the shift key is pressed
 * stage.mouseControls.remove( "scroll-shift" );
 *
 * @param {TriggerString} triggerStr - the trigger for the action
 * @param {Function} [callback] - the callback function for the action
 * @return {undefined}
 */
MouseControls.prototype.remove = function remove (triggerStr, callback) {
    var wildcard = triggerStr.includes('*');
    var ref = triggerFromString(triggerStr);
        var type = ref[0];
        var key = ref[1];
        var button = ref[2];
    var actionList = this.actionList.filter(function (a) {
        return !((a.type === type || (wildcard && type === '')) &&
            (a.key === key || (wildcard && key === 0)) &&
            (a.button === button || (wildcard && button === 0)) &&
            (a.callback === callback || callback === undefined));
    });
    this.actionList = actionList;
};
/**
 * Set mouse action preset
 * @param  {String} name - one of "default", "pymol", "coot"
 * @return {undefined}
 */
MouseControls.prototype.preset = function preset (name) {
        var this$1 = this;

    this.clear();
    var list = MouseActionPresets[name] || [];
    list.forEach(function (action) { return this$1.add(action[0], action[1]); });
};
/**
 * Remove all mouse actions
 * @return {undefined}
 */
MouseControls.prototype.clear = function clear () {
    this.actionList.length = 0;
};

/**
 * @file Key Actions
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Key actions provided as static methods
 */
var KeyActions = function KeyActions () {};

KeyActions.autoView = function autoView (stage) {
    stage.autoView(1000);
};
/**
 * Toggle stage animations
 */
KeyActions.toggleAnimations = function toggleAnimations (stage) {
    stage.animationControls.toggle();
};
/**
 * Toggle stage rocking
 */
KeyActions.toggleRock = function toggleRock (stage) {
    stage.toggleRock();
};
/**
 * Toggle stage spinning
 */
KeyActions.toggleSpin = function toggleSpin (stage) {
    stage.toggleSpin();
};
/**
 * Toggle anti-aliasing
 */
KeyActions.toggleAntialiasing = function toggleAntialiasing (stage) {
    var p = stage.getParameters();
    stage.setParameters({ sampleLevel: p.sampleLevel === -1 ? 0 : -1 });
};
var KeyActionPresets = {
    default: [
        ['i', KeyActions.toggleSpin],
        ['k', KeyActions.toggleRock],
        ['p', KeyActions.toggleAnimations],
        ['a', KeyActions.toggleAntialiasing],
        ['r', KeyActions.autoView]
    ]
};

/**
 * @file Key Controls
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Mouse controls
 */
var KeyControls = function KeyControls(stage, params) {
    if ( params === void 0 ) params = {};

    this.stage = stage;
    this.actionList = [];
    this.disabled = params.disabled || false;
    this.preset(params.preset || 'default');
};
KeyControls.prototype.run = function run (key) {
        var this$1 = this;

    if (this.disabled)
        { return; }
    this.actionList.forEach(function (a) {
        if (a.key === key) {
            a.callback(this$1.stage);
        }
    });
};
/**
 * Add a key action triggered by pressing the given character.
 * The {@link KeyActions} class provides a number of static methods for
 * use as callback functions.
 *
 * @example
 * // call KeyActions.toggleRock when "k" is pressed
 * stage.keyControls.remove( "k", KeyActions.toggleRock );
 *
 * @param {Char} char - the key/character
 * @param {Function} callback - the callback function for the action
 * @return {undefined}
 */
KeyControls.prototype.add = function add (char, callback) {
    this.actionList.push({ key: char, callback: callback });
};
/**
 * Remove a key action. When the callback function
 * is given, only actions that call that function are removed.
 *
 * @example
 * // remove all actions triggered by pressing "k"
 * stage.keyControls.remove( "k" );
 *
 * @example
 * // remove action `toggleRock` triggered by pressing "k"
 * stage.keyControls.remove( "k", toggleRock );
 *
 * @param {Char} char - the key/character
 * @param {Function} [callback] - the callback function for the action
 * @return {undefined}
 */
KeyControls.prototype.remove = function remove (char, callback) {
    var actionList = this.actionList.filter(function (a) {
        return !((a.key === char) &&
            (a.callback === callback || callback === undefined));
    });
    this.actionList = actionList;
};
/**
 * Set key action preset
 * @param  {String} name - one of "default"
 * @return {undefined}
 */
KeyControls.prototype.preset = function preset (name) {
        var this$1 = this;

    this.clear();
    var list = KeyActionPresets[name] || [];
    list.forEach(function (action) { return this$1.add(action[0], action[1]); });
};
/**
 * Remove all key actions
 * @return {undefined}
 */
KeyControls.prototype.clear = function clear () {
    this.actionList.length = 0;
};

/**
 * @file Picking Behavior
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var PickingBehavior = function PickingBehavior(stage) {
    this.stage = stage;
    this.stage = stage;
    this.mouse = stage.mouseObserver;
    this.controls = stage.mouseControls;
    this.mouse.signals.clicked.add(this._onClick, this);
    this.mouse.signals.hovered.add(this._onHover, this);
};
PickingBehavior.prototype._onClick = function _onClick (x, y) {
    var pickingProxy = this.stage.pickingControls.pick(x, y);
    this.stage.signals.clicked.dispatch(pickingProxy);
    this.controls.run('clickPick', pickingProxy);
};
PickingBehavior.prototype._onHover = function _onHover (x, y) {
    var pickingProxy = this.stage.pickingControls.pick(x, y);
    if (pickingProxy && this.mouse.down.equals(this.mouse.position)) {
        this.stage.transformComponent = pickingProxy.component;
        this.stage.transformAtom = pickingProxy.atom;
    }
    this.stage.signals.hovered.dispatch(pickingProxy);
    this.controls.run('hoverPick', pickingProxy);
};
PickingBehavior.prototype.dispose = function dispose () {
    this.mouse.signals.clicked.remove(this._onClick, this);
    this.mouse.signals.hovered.remove(this._onHover, this);
};

/**
 * @file Mouse Behavior
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var MouseBehavior = function MouseBehavior(stage) {
    this.stage = stage;
    this.stage = stage;
    this.mouse = stage.mouseObserver;
    this.controls = stage.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);
};
MouseBehavior.prototype._onMove = function _onMove ( /* x, y */) {
    this.stage.tooltip.style.display = 'none';
};
MouseBehavior.prototype._onScroll = function _onScroll (delta) {
    this.controls.run('scroll', delta);
};
MouseBehavior.prototype._onDrag = function _onDrag (dx, dy) {
    this.controls.run('drag', dx, dy);
};
MouseBehavior.prototype._onClick = function _onClick (x, y) {
    this.controls.run('click', x, y);
};
MouseBehavior.prototype._onDblclick = function _onDblclick (x, y) {
    this.controls.run('doubleClick', x, y);
};
MouseBehavior.prototype._onHover = function _onHover (x, y) {
    this.controls.run('hover', x, y);
};
MouseBehavior.prototype.dispose = function 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);
};

/**
 * @file Animation Behavior
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var AnimationBehavior = function AnimationBehavior(stage) {
    this.stage = stage;
    this.viewer = stage.viewer;
    this.animationControls = stage.animationControls;
    this.viewer.signals.ticked.add(this._onTick, this);
};
AnimationBehavior.prototype._onTick = function _onTick (stats) {
    this.animationControls.run(stats);
};
AnimationBehavior.prototype.dispose = function dispose () {
    this.viewer.signals.ticked.remove(this._onTick, this);
};

/**
 * @file Key Behavior
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var passive = SupportsPassiveEventHandler ? { passive: true } : false;
var KeyBehavior = function KeyBehavior(stage) {
    this.stage = stage;
    this.stage = stage;
    this.controls = stage.keyControls;
    this.domElement = stage.viewer.renderer.domElement;
    // ensure the domElement is focusable
    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, passive); // TODO
    this.domElement.addEventListener('keydown', this._onKeydown);
    this.domElement.addEventListener('keyup', this._onKeyup);
    this.domElement.addEventListener('keypress', this._onKeypress);
};
/**
 * handle key down
 * @param  {Event} event - key event
 * @return {undefined}
 */
KeyBehavior.prototype._onKeydown = function _onKeydown ( /* event */) {
    // console.log( "down", event.keyCode, String.fromCharCode( event.keyCode ) );
};
/**
 * handle key up
 * @param  {Event} event - key event
 * @return {undefined}
 */
KeyBehavior.prototype._onKeyup = function _onKeyup ( /* event */) {
    // console.log( "up", event.keyCode, String.fromCharCode( event.keyCode ) );
};
/**
 * handle key press
 * @param  {Event} event - key event
 * @return {undefined}
 */
KeyBehavior.prototype._onKeypress = function _onKeypress (event) {
    // console.log( "press", event.keyCode, String.fromCharCode( event.keyCode ) );
    var pressedKey;
    if ("key" in KeyboardEvent.prototype) {
        pressedKey = event.key;
        // some mobile browsers don't support this attribute
    }
    else {
        pressedKey = String.fromCharCode(event.which || event.keyCode);
    }
    this.controls.run(pressedKey);
};
KeyBehavior.prototype._focusDomElement = function _focusDomElement () {
    this.domElement.focus();
};
KeyBehavior.prototype.dispose = function dispose () {
    this.domElement.removeEventListener('mousedown', this._focusDomElement);
    this.domElement.removeEventListener('touchstart', this._focusDomElement, passive); // TODO
    this.domElement.removeEventListener('keydown', this._onKeypress);
    this.domElement.removeEventListener('keyup', this._onKeypress);
    this.domElement.removeEventListener('keypress', this._onKeypress);
};

/**
 * @file Annotation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Annotation HTML element floating on top of a position rendered in 3d
 */
var Annotation = function Annotation(component, position, content, params) {
    if ( params === void 0 ) params = {};

    this.component = component;
    this.position = position;
    this.offsetX = defaults(params.offsetX, 0);
    this.offsetY = defaults(params.offsetY, 0);
    this.visible = defaults(params.visible, true);
    this.stage = component.stage;
    this.viewer = component.stage.viewer;
    this._viewerPosition = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this._updateViewerPosition();
    this._canvasPosition = new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */]();
    this._cameraPosition = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    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(content);
    this.updateVisibility();
    this.viewer.signals.rendered.add(this._update, this);
    this.component.signals.matrixChanged.add(this._updateViewerPosition, this);
};
/**
 * Set HTML content of the annotation
 * @param {String|Element} value - HTML content
 * @return {undefined}
 */
Annotation.prototype.setContent = function setContent (value) {
    var displayValue = this.element.style.display;
    if (displayValue === 'none') {
        this.element.style.left = '-10000px';
        this.element.style.display = 'block';
    }
    if (value instanceof HTMLElement) {
        this.element.appendChild(value);
    }
    else {
        var content = document.createElement('div');
        content.innerText = value;
        Object.assign(content.style, {
            backgroundColor: 'rgba( 0, 0, 0, 0.6 )',
            color: 'lightgrey',
            padding: '8px',
            fontFamily: 'sans-serif',
        });
        this.element.appendChild(content);
    }
    this._clientRect = this.element.getBoundingClientRect();
    if (displayValue === 'none') {
        this.element.style.display = displayValue;
    }
};
/**
 * Set visibility of the annotation
 * @param {Boolean} value - visibility flag
 * @return {undefined}
 */
Annotation.prototype.setVisibility = function setVisibility (value) {
    this.visible = value;
    this.updateVisibility();
};
Annotation.prototype.getVisibility = function getVisibility () {
    return this.visible && this.component.parameters.visible;
};
Annotation.prototype.updateVisibility = function updateVisibility () {
    this.element.style.display = this.getVisibility() ? 'block' : 'none';
};
Annotation.prototype._updateViewerPosition = function _updateViewerPosition () {
    this._viewerPosition
        .copy(this.position)
        .applyMatrix4(this.component.matrix);
};
Annotation.prototype._update = function _update () {
    if (!this.getVisibility())
        { return; }
    var s = this.element.style;
    var cp = this._canvasPosition;
    var vp = this._viewerPosition;
    var cr = this._clientRect;
    this._cameraPosition.copy(vp)
        .add(this.viewer.translationGroup.position)
        .applyMatrix4(this.viewer.rotationGroup.matrix)
        .sub(this.viewer.camera.position);
    if (this._cameraPosition.z < 0) {
        s.display = 'none';
        return;
    }
    else {
        s.display = 'block';
    }
    var depth = this._cameraPosition.length();
    var fog = this.viewer.scene.fog; // TODO
    s.opacity = (1 - smoothstep(fog.near, fog.far, depth)).toString();
    s.zIndex = (Math.round((fog.far - depth) * 100)).toString();
    this.stage.viewerControls.getPositionOnCanvas(vp, cp);
    s.bottom = (this.offsetX + cp.y + cr.height / 2) + 'px';
    s.left = (this.offsetY + cp.x - cr.width / 2) + 'px';
};
/**
 * Safely remove the annotation
 * @return {undefined}
 */
Annotation.prototype.dispose = function dispose () {
    this.viewer.wrapper.removeChild(this.element);
    this.viewer.signals.ticked.remove(this._update, this);
    this.component.signals.matrixChanged.remove(this._updateViewerPosition, this);
};

/**
 * @file Component Controls
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var tmpRotateMatrix$2 = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var tmpRotateVector$2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var tmpRotateQuaternion$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]();
/**
 * Component controls
 */
var ComponentControls = function ComponentControls(component) {
    this.component = component;
    this.signals = {
        changed: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]()
    };
    this.stage = component.stage;
    this.viewer = component.stage.viewer;
};

var prototypeAccessors$e = { position: { configurable: true },rotation: { configurable: true } };
/**
 * component center position
 * @type {Vector3}
 */
prototypeAccessors$e.position.get = function () {
    return this.component.position;
};
/**
 * component rotation
 * @type {Quaternion}
 */
prototypeAccessors$e.rotation.get = function () {
    return this.component.quaternion;
};
/**
 * Trigger render and emit changed event
 * @emits {ComponentControls.signals.changed}
 * @return {undefined}
 */
ComponentControls.prototype.changed = function changed () {
    this.component.updateMatrix();
    this.viewer.requestRender();
    this.signals.changed.dispatch();
};
/**
 * spin component on axis
 * @param  {Vector3|Array} axis - rotation axis
 * @param  {Number} angle - amount to spin
 * @return {undefined}
 */
ComponentControls.prototype.spin = function spin (axis, angle) {
    tmpRotateMatrix$2.getInverse(this.viewer.rotationGroup.matrix);
    tmpRotateVector$2
        .copy(ensureVector3(axis)).applyMatrix4(tmpRotateMatrix$2);
    tmpRotateMatrix$2.extractRotation(this.component.transform);
    tmpRotateMatrix$2.premultiply(this.viewer.rotationGroup.matrix);
    tmpRotateMatrix$2.getInverse(tmpRotateMatrix$2);
    tmpRotateVector$2.copy(ensureVector3(axis));
    tmpRotateVector$2.applyMatrix4(tmpRotateMatrix$2);
    tmpRotateMatrix$2.makeRotationAxis(tmpRotateVector$2, angle);
    tmpRotateQuaternion$1.setFromRotationMatrix(tmpRotateMatrix$2);
    this.component.quaternion.premultiply(tmpRotateQuaternion$1);
    this.changed();
};

Object.defineProperties( ComponentControls.prototype, prototypeAccessors$e );

/**
 * @file Radius Factory
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var RadiusFactoryTypes = {
    '': '',
    'vdw': 'by vdW radius',
    'covalent': 'by covalent radius',
    'sstruc': 'by secondary structure',
    'bfactor': 'by bfactor',
    'size': 'size',
    'data': 'data',
    'explicit': 'explicit'
};
var RadiusFactory = function RadiusFactory(params) {
    if ( params === void 0 ) params = {};

    this.max = 10;
    this.type = defaults(params.type, 'size');
    this.scale = defaults(params.scale, 1);
    this.size = defaults(params.size, 1);
    this.data = defaults(params.data, {});
};
RadiusFactory.prototype.atomRadius = function atomRadius (a) {
    var r;
    switch (this.type) {
        case 'vdw':
            r = a.vdw;
            break;
        case 'covalent':
            r = a.covalent;
            break;
        case 'bfactor':
            r = a.bfactor || 1.0;
            break;
        case 'sstruc':
            var sstruc = a.sstruc;
            if (sstruc === 'h') {
                r = 0.25;
            }
            else if (sstruc === 'g') {
                r = 0.25;
            }
            else if (sstruc === 'i') {
                r = 0.25;
            }
            else if (sstruc === 'e') {
                r = 0.25;
            }
            else if (sstruc === 'b') {
                r = 0.25;
            }
            else if (NucleicBackboneAtoms.includes(a.atomname)) {
                r = 0.4;
            }
            else {
                r = 0.1;
            }
            break;
        case 'data':
            r = defaults(this.data[a.index], 1.0);
            break;
        case 'explicit':
            // defaults is inappropriate as AtomProxy.radius returns
            // null for missing radii
            r = a.radius;
            if (r === null)
                { r = this.size; }
            break;
        default:
            r = this.size;
            break;
    }
    return Math.min(r * this.scale, this.max);
};
RadiusFactory.types = RadiusFactoryTypes;

/**
 * @file Principal Axes
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var negateVector = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](-1, -1, -1);
var tmpMatrix$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
/**
 * Principal axes
 */
var PrincipalAxes = function PrincipalAxes(points) {
    // console.time( "PrincipalAxes" );
    var n = points.rows;
    var n3 = n / 3;
    var pointsT = new Matrix(n, 3);
    var A = new Matrix(3, 3);
    var W = new Matrix(1, 3);
    var U = new Matrix(3, 3);
    var V = new Matrix(3, 3);
    // calculate
    var mean = meanRows(points);
    subRows(points, mean);
    transpose(pointsT, points);
    multiplyABt(A, pointsT, pointsT);
    svd(A, W, U, V);
    // console.log( points, pointsT, mean )
    // console.log( n, A, W, U, V );
    // center
    var vm = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](mean[0], mean[1], mean[2]);
    // normalized
    var van = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](U.data[0], U.data[3], U.data[6]);
    var vbn = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](U.data[1], U.data[4], U.data[7]);
    var vcn = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](U.data[2], U.data[5], U.data[8]);
    // scaled
    var va = van.clone().multiplyScalar(Math.sqrt(W.data[0] / n3));
    var vb = vbn.clone().multiplyScalar(Math.sqrt(W.data[1] / n3));
    var vc = vcn.clone().multiplyScalar(Math.sqrt(W.data[2] / n3));
    // points
    this.begA = vm.clone().sub(va);
    this.endA = vm.clone().add(va);
    this.begB = vm.clone().sub(vb);
    this.endB = vm.clone().add(vb);
    this.begC = vm.clone().sub(vc);
    this.endC = vm.clone().add(vc);
    //
    this.center = vm;
    this.vecA = va;
    this.vecB = vb;
    this.vecC = vc;
    this.normVecA = van;
    this.normVecB = vbn;
    this.normVecC = vcn;
    // console.timeEnd( "PrincipalAxes" );
};
/**
 * Get the basis matrix descriping the axes
 * @param  {Matrix4} [optionalTarget] - target object
 * @return {Matrix4} the basis
 */
PrincipalAxes.prototype.getBasisMatrix = function getBasisMatrix (optionalTarget) {
        if ( optionalTarget === void 0 ) optionalTarget = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();

    var basis = optionalTarget;
    basis.makeBasis(this.normVecB, this.normVecA, this.normVecC);
    if (basis.determinant() < 0) {
        basis.scale(negateVector);
    }
    return basis;
};
/**
 * Get a quaternion descriping the axes rotation
 * @param  {Quaternion} [optionalTarget] - target object
 * @return {Quaternion} the rotation
 */
PrincipalAxes.prototype.getRotationQuaternion = function getRotationQuaternion (optionalTarget) {
        if ( optionalTarget === void 0 ) optionalTarget = new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]();

    var q = optionalTarget;
    q.setFromRotationMatrix(this.getBasisMatrix(tmpMatrix$1));
    return q.inverse();
};
/**
 * Get the scale/length for each dimension for a box around the axes
 * to enclose the atoms of a structure
 * @param  {Structure|StructureView} structure - the structure
 * @return {{d1a: Number, d2a: Number, d3a: Number, d1b: Number, d2b: Number, d3b: Number}} scale
 */
PrincipalAxes.prototype.getProjectedScaleForAtoms = function getProjectedScaleForAtoms (structure) {
    var d1a = -Infinity;
    var d1b = -Infinity;
    var d2a = -Infinity;
    var d2b = -Infinity;
    var d3a = -Infinity;
    var d3b = -Infinity;
    var p = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var t = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var center = this.center;
    var ax1 = this.normVecA;
    var ax2 = this.normVecB;
    var ax3 = this.normVecC;
    structure.eachAtom(function (ap) {
        projectPointOnVector(p.copy(ap), ax1, center); // TODO
        var dp1 = t.subVectors(p, center).normalize().dot(ax1);
        var dt1 = p.distanceTo(center);
        if (dp1 > 0) {
            if (dt1 > d1a)
                { d1a = dt1; }
        }
        else {
            if (dt1 > d1b)
                { d1b = dt1; }
        }
        projectPointOnVector(p.copy(ap), ax2, center);
        var dp2 = t.subVectors(p, center).normalize().dot(ax2);
        var dt2 = p.distanceTo(center);
        if (dp2 > 0) {
            if (dt2 > d2a)
                { d2a = dt2; }
        }
        else {
            if (dt2 > d2b)
                { d2b = dt2; }
        }
        projectPointOnVector(p.copy(ap), ax3, center);
        var dp3 = t.subVectors(p, center).normalize().dot(ax3);
        var dt3 = p.distanceTo(center);
        if (dp3 > 0) {
            if (dt3 > d3a)
                { d3a = dt3; }
        }
        else {
            if (dt3 > d3b)
                { d3b = dt3; }
        }
    });
    return {
        d1a: d1a,
        d2a: d2a,
        d3a: d3a,
        d1b: -d1b,
        d2b: -d2b,
        d3b: -d3b
    };
};

/**
 * @file Filtered Volume
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var FilteredVolume = function FilteredVolume(volume, minValue, maxValue, outside) {
    this.volume = volume;
    this.setFilter(minValue, maxValue, outside);
};

var prototypeAccessors$f = { header: { configurable: true },matrix: { configurable: true },normalMatrix: { configurable: true },inverseMatrix: { configurable: true },center: { configurable: true },boundingBox: { configurable: true },min: { configurable: true },max: { configurable: true },mean: { configurable: true },rms: { configurable: true } };
prototypeAccessors$f.header.get = function () { return this.volume.header; };
prototypeAccessors$f.matrix.get = function () { return this.volume.matrix; };
prototypeAccessors$f.normalMatrix.get = function () { return this.volume.normalMatrix; };
prototypeAccessors$f.inverseMatrix.get = function () { return this.volume.inverseMatrix; };
prototypeAccessors$f.center.get = function () { return this.volume.center; };
prototypeAccessors$f.boundingBox.get = function () { return this.volume.boundingBox; };
prototypeAccessors$f.min.get = function () { return this.volume.min; };
prototypeAccessors$f.max.get = function () { return this.volume.max; };
prototypeAccessors$f.mean.get = function () { return this.volume.mean; };
prototypeAccessors$f.rms.get = function () { return this.volume.rms; };
FilteredVolume.prototype._getFilterHash = function _getFilterHash (minValue, maxValue, outside) {
    return JSON.stringify([minValue, maxValue, outside]);
};
FilteredVolume.prototype.setFilter = function setFilter (minValue, maxValue, outside) {
    if (isNaN(minValue) && this.header) {
        minValue = this.header.DMEAN + 2.0 * this.header.ARMS;
    }
    minValue = (minValue !== undefined && !isNaN(minValue)) ? minValue : -Infinity;
    maxValue = defaults(maxValue, Infinity);
    outside = defaults(outside, false);
    var data = this.volume.data;
    var position = this.volume.position;
    var atomindex = this.volume.atomindex;
    var filterHash = this._getFilterHash(minValue, maxValue, outside);
    if (filterHash === this._filterHash) {
        // already filtered
        return;
    }
    else if (minValue === -Infinity && maxValue === Infinity) {
        this.data = data;
        this.position = position;
        this.atomindex = atomindex;
    }
    else {
        var n = data.length;
        if (!this._dataBuffer) {
            // ArrayBuffer for re-use as Float32Array backend
            this._dataBuffer = new ArrayBuffer(n * 4);
            this._positionBuffer = new ArrayBuffer(n * 3 * 4);
            if (atomindex)
                { this._atomindexBuffer = new ArrayBuffer(n * 4); }
        }
        var filteredData = new Float32Array(this._dataBuffer);
        var filteredPosition = new Float32Array(this._positionBuffer);
        var filteredAtomindex;
        if (atomindex)
            { filteredAtomindex = new Uint32Array(this._atomindexBuffer); }
        var j = 0;
        for (var i = 0; i < n; ++i) {
            var i3 = i * 3;
            var v = data[i];
            if ((!outside && v >= minValue && v <= maxValue) ||
                (outside && (v < minValue || v > maxValue))) {
                var j3 = j * 3;
                filteredData[j] = v;
                filteredPosition[j3 + 0] = position[i3 + 0];
                filteredPosition[j3 + 1] = position[i3 + 1];
                filteredPosition[j3 + 2] = position[i3 + 2];
                if (atomindex && filteredAtomindex)
                    { filteredAtomindex[j] = atomindex[i]; }
                j += 1;
            }
        }
        // set views
        this.data = new Float32Array(this._dataBuffer, 0, j);
        this.position = new Float32Array(this._positionBuffer, 0, j * 3);
        if (atomindex)
            { this.atomindex = new Int32Array(this._atomindexBuffer, 0, j); }
    }
    this._filterHash = filterHash;
};

Object.defineProperties( FilteredVolume.prototype, prototypeAccessors$f );
FilteredVolume.prototype.getValueForSigma = Volume.prototype.getValueForSigma;
FilteredVolume.prototype.getSigmaForValue = Volume.prototype.getSigmaForValue;
FilteredVolume.prototype.getDataAtomindex = Volume.prototype.getDataAtomindex;
FilteredVolume.prototype.getDataPosition = Volume.prototype.getDataPosition;
FilteredVolume.prototype.getDataColor = Volume.prototype.getDataColor;
FilteredVolume.prototype.getDataPicking = Volume.prototype.getDataPicking;
FilteredVolume.prototype.getDataSize = Volume.prototype.getDataSize;

/**
 * @file Bond Hash
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var BondHash = function BondHash(bondStore, atomCount) {
    var al = createAdjacencyList({
        nodeArray1: bondStore.atomIndex1,
        nodeArray2: bondStore.atomIndex2,
        edgeCount: bondStore.count,
        nodeCount: atomCount
    });
    this.countArray = al.countArray;
    this.offsetArray = al.offsetArray;
    this.indexArray = al.indexArray;
};

/**
 * @file Bond Store
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Bond store
 */
var BondStore = /*@__PURE__*/(function (Store$$1) {
    function BondStore () {
        Store$$1.apply(this, arguments);
    }

    if ( Store$$1 ) BondStore.__proto__ = Store$$1;
    BondStore.prototype = Object.create( Store$$1 && Store$$1.prototype );
    BondStore.prototype.constructor = BondStore;

    var prototypeAccessors = { _defaultFields: { configurable: true } };

    prototypeAccessors._defaultFields.get = function () {
        return [
            ['atomIndex1', 1, 'int32'],
            ['atomIndex2', 1, 'int32'],
            ['bondOrder', 1, 'int8']
        ];
    };
    BondStore.prototype.addBond = function addBond (atom1, atom2, bondOrder) {
        this.growIfFull();
        var i = this.count;
        var ai1 = atom1.index;
        var ai2 = atom2.index;
        if (ai1 < ai2) {
            this.atomIndex1[i] = ai1;
            this.atomIndex2[i] = ai2;
        }
        else {
            this.atomIndex2[i] = ai1;
            this.atomIndex1[i] = ai2;
        }
        if (bondOrder)
            { this.bondOrder[i] = bondOrder; }
        this.count += 1;
    };
    BondStore.prototype.addBondIfConnected = function addBondIfConnected (atom1, atom2, bondOrder) {
        if (atom1.connectedTo(atom2)) {
            this.addBond(atom1, atom2, bondOrder);
            return true;
        }
        return false;
    };

    Object.defineProperties( BondStore.prototype, prototypeAccessors );

    return BondStore;
}(Store));

/**
 * @file Atom Store
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Atom store
 */
var AtomStore = /*@__PURE__*/(function (Store$$1) {
    function AtomStore () {
        Store$$1.apply(this, arguments);
    }

    if ( Store$$1 ) AtomStore.__proto__ = Store$$1;
    AtomStore.prototype = Object.create( Store$$1 && Store$$1.prototype );
    AtomStore.prototype.constructor = AtomStore;

    var prototypeAccessors = { _defaultFields: { configurable: true } };

    prototypeAccessors._defaultFields.get = function () {
        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']
        ];
    };
    AtomStore.prototype.setAltloc = function setAltloc (i, str) {
        this.altloc[i] = str.charCodeAt(0);
    };
    AtomStore.prototype.getAltloc = function getAltloc (i) {
        var code = this.altloc[i];
        return code ? String.fromCharCode(code) : '';
    };

    Object.defineProperties( AtomStore.prototype, prototypeAccessors );

    return AtomStore;
}(Store));

/**
 * @file Residue Store
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Residue store
 */
var ResidueStore = /*@__PURE__*/(function (Store$$1) {
    function ResidueStore () {
        Store$$1.apply(this, arguments);
    }

    if ( Store$$1 ) ResidueStore.__proto__ = Store$$1;
    ResidueStore.prototype = Object.create( Store$$1 && Store$$1.prototype );
    ResidueStore.prototype.constructor = ResidueStore;

    var prototypeAccessors = { _defaultFields: { configurable: true } };

    prototypeAccessors._defaultFields.get = function () {
        return [
            ['chainIndex', 1, 'uint32'],
            ['atomOffset', 1, 'uint32'],
            ['atomCount', 1, 'uint32'],
            ['residueTypeId', 1, 'uint16'],
            ['resno', 1, 'int32'],
            ['sstruc', 1, 'uint8'],
            ['inscode', 1, 'uint8']
        ];
    };
    ResidueStore.prototype.setSstruc = function setSstruc (i, str) {
        this.sstruc[i] = str.charCodeAt(0);
    };
    ResidueStore.prototype.getSstruc = function getSstruc (i) {
        var code = this.sstruc[i];
        return code ? String.fromCharCode(code) : '';
    };
    ResidueStore.prototype.setInscode = function setInscode (i, str) {
        this.inscode[i] = str.charCodeAt(0);
    };
    ResidueStore.prototype.getInscode = function getInscode (i) {
        var code = this.inscode[i];
        return code ? String.fromCharCode(code) : '';
    };

    Object.defineProperties( ResidueStore.prototype, prototypeAccessors );

    return ResidueStore;
}(Store));

/**
 * @file Chain Store
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Chain store
 */
var ChainStore = /*@__PURE__*/(function (Store$$1) {
    function ChainStore () {
        Store$$1.apply(this, arguments);
    }

    if ( Store$$1 ) ChainStore.__proto__ = Store$$1;
    ChainStore.prototype = Object.create( Store$$1 && Store$$1.prototype );
    ChainStore.prototype.constructor = ChainStore;

    var prototypeAccessors = { _defaultFields: { configurable: true } };

    prototypeAccessors._defaultFields.get = function () {
        return [
            ['entityIndex', 1, 'uint16'],
            ['modelIndex', 1, 'uint16'],
            ['residueOffset', 1, 'uint32'],
            ['residueCount', 1, 'uint32'],
            ['chainname', 4, 'uint8'],
            ['chainid', 4, 'uint8']
        ];
    };
    ChainStore.prototype.setChainname = function setChainname (i, str) {
        var j = 4 * i;
        this.chainname[j] = str.charCodeAt(0);
        this.chainname[j + 1] = str.charCodeAt(1);
        this.chainname[j + 2] = str.charCodeAt(2);
        this.chainname[j + 3] = str.charCodeAt(3);
    };
    ChainStore.prototype.getChainname = function getChainname (i) {
        var chainname = '';
        for (var k = 0; k < 4; ++k) {
            var code = this.chainname[4 * i + k];
            if (code) {
                chainname += String.fromCharCode(code);
            }
            else {
                break;
            }
        }
        return chainname;
    };
    ChainStore.prototype.setChainid = function setChainid (i, str) {
        var j = 4 * i;
        this.chainid[j] = str.charCodeAt(0);
        this.chainid[j + 1] = str.charCodeAt(1);
        this.chainid[j + 2] = str.charCodeAt(2);
        this.chainid[j + 3] = str.charCodeAt(3);
    };
    ChainStore.prototype.getChainid = function getChainid (i) {
        var chainid = '';
        for (var k = 0; k < 4; ++k) {
            var code = this.chainid[4 * i + k];
            if (code) {
                chainid += String.fromCharCode(code);
            }
            else {
                break;
            }
        }
        return chainid;
    };

    Object.defineProperties( ChainStore.prototype, prototypeAccessors );

    return ChainStore;
}(Store));

/**
 * @file Model Store
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Model store
 */
var ModelStore = /*@__PURE__*/(function (Store$$1) {
    function ModelStore () {
        Store$$1.apply(this, arguments);
    }

    if ( Store$$1 ) ModelStore.__proto__ = Store$$1;
    ModelStore.prototype = Object.create( Store$$1 && Store$$1.prototype );
    ModelStore.prototype.constructor = ModelStore;

    var prototypeAccessors = { _defaultFields: { configurable: true } };

    prototypeAccessors._defaultFields.get = function () {
        return [
            ['chainOffset', 1, 'uint32'],
            ['chainCount', 1, 'uint32']
        ];
    };

    Object.defineProperties( ModelStore.prototype, prototypeAccessors );

    return ModelStore;
}(Store));

/**
 * @file Helixorient
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Helixorient = function Helixorient(polymer) {
    this.polymer = polymer;
    this.size = polymer.residueCount;
};
Helixorient.prototype.getCenterIterator = function getCenterIterator (smooth) {
        if ( smooth === void 0 ) smooth = 0;

    var center = this.getPosition().center;
    var size = center.length / 3;
    var i = 0;
    var j = -1;
    var cache = [
        new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](),
        new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](),
        new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](),
        new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]()
    ];
    function next() {
        var vector = this.get(j);
        j += 1;
        return vector;
    }
    function get(idx) {
        idx = Math.min(size - 1, Math.max(0, idx));
        var v = cache[i % 4];
        var idx3 = 3 * idx;
        v.fromArray(center, idx3); // TODO
        if (smooth) {
            var w = Math.min(smooth, idx, size - idx - 1);
            for (var k = 1; k <= w; ++k) {
                var l = k * 3;
                var t = (w + 1 - k) / (w + 1);
                v.x += t * center[idx3 - l + 0] + t * center[idx3 + l + 0];
                v.y += t * center[idx3 - l + 1] + t * center[idx3 + l + 1];
                v.z += t * center[idx3 - l + 2] + t * center[idx3 + l + 2];
            }
            v.x /= w + 1;
            v.y /= w + 1;
            v.z /= w + 1;
        }
        i += 1;
        return v;
    }
    function reset() {
        i = 0;
        j = -1;
    }
    return { size: size, next: next, get: get, reset: reset };
};
Helixorient.prototype.getColor = function getColor (params) {
    var polymer = this.polymer;
    var structure = polymer.structure;
    var n = polymer.residueCount;
    var residueIndexStart = polymer.residueIndexStart;
    var col = new Float32Array(n * 3);
    var p = params || {};
    p.structure = structure;
    var colormaker = ColormakerRegistry$1.getScheme(p);
    var rp = structure.getResidueProxy();
    var ap = structure.getAtomProxy();
    for (var i = 0; i < n; ++i) {
        rp.index = residueIndexStart + i;
        ap.index = rp.traceAtomIndex;
        colormaker.atomColorToArray(ap, col, i * 3);
    }
    return {
        'color': col
    };
};
Helixorient.prototype.getPicking = function getPicking () {
    var polymer = this.polymer;
    var structure = polymer.structure;
    var n = polymer.residueCount;
    var residueIndexStart = polymer.residueIndexStart;
    var pick = new Float32Array(n);
    var rp = structure.getResidueProxy();
    for (var i = 0; i < n; ++i) {
        rp.index = residueIndexStart + i;
        pick[i] = rp.traceAtomIndex;
    }
    return {
        'picking': new AtomPicker(pick, structure)
    };
};
Helixorient.prototype.getSize = function getSize (params) {
    var polymer = this.polymer;
    var structure = polymer.structure;
    var n = polymer.residueCount;
    var residueIndexStart = polymer.residueIndexStart;
    var size = new Float32Array(n);
    var radiusFactory = new RadiusFactory(params);
    var rp = structure.getResidueProxy();
    var ap = structure.getAtomProxy();
    for (var i = 0; i < n; ++i) {
        rp.index = residueIndexStart + i;
        ap.index = rp.traceAtomIndex;
        size[i] = radiusFactory.atomRadius(ap);
    }
    return { size: size };
};
Helixorient.prototype.getPosition = function getPosition () {
    var polymer = this.polymer;
    var structure = polymer.structure;
    var n = polymer.residueCount;
    var n3 = n - 3;
    var center = new Float32Array(3 * n);
    var axis = new Float32Array(3 * n);
    var diff = new Float32Array(n);
    var radius = new Float32Array(n);
    var rise = new Float32Array(n);
    var twist = new Float32Array(n);
    var resdir = new Float32Array(3 * n);
    var r12 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var r23 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var r34 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var diff13 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var diff24 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var v1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var v2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var vt = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var _axis = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var _prevAxis = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var _resdir = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var _center = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 0, 0);
    var type = 'trace';
    var a1 = structure.getAtomProxy();
    var a2 = structure.getAtomProxy(polymer.getAtomIndexByType(0, type));
    var a3 = structure.getAtomProxy(polymer.getAtomIndexByType(1, type));
    var a4 = structure.getAtomProxy(polymer.getAtomIndexByType(2, type));
    for (var i = 0; i < n3; ++i) {
        a1.index = a2.index;
        a2.index = a3.index;
        a3.index = a4.index;
        a4.index = polymer.getAtomIndexByType(i + 3, type); // TODO
        var j = 3 * i;
        // ported from GROMACS src/tools/gmx_helixorient.c
        r12.subVectors(a2, a1); // TODO
        r23.subVectors(a3, a2); // TODO
        r34.subVectors(a4, a3); // TODO
        diff13.subVectors(r12, r23);
        diff24.subVectors(r23, r34);
        _axis.crossVectors(diff13, diff24).normalize();
        _axis.toArray(axis, j); // TODO
        if (i > 0) {
            diff[i] = _axis.angleTo(_prevAxis);
        }
        var tmp = Math.cos(diff13.angleTo(diff24));
        twist[i] = 180.0 / Math.PI * Math.acos(tmp);
        var diff13Length = diff13.length();
        var diff24Length = diff24.length();
        radius[i] = (Math.sqrt(diff24Length * diff13Length) /
            // clamp, to avoid instabilities for when
            // angle between diff13 and diff24 is near 0
            Math.max(2.0, 2.0 * (1.0 - tmp)));
        rise[i] = Math.abs(r23.dot(_axis));
        //
        v1.copy(diff13).multiplyScalar(radius[i] / diff13Length);
        v2.copy(diff24).multiplyScalar(radius[i] / diff24Length);
        v1.subVectors(a2, v1); // TODO
        v2.subVectors(a3, v2); // TODO
        v1.toArray(center, j + 3); // TODO
        v2.toArray(center, j + 6); // TODO
        //
        _resdir.subVectors(a1, _center); // TODO
        _resdir.toArray(resdir, j); // TODO
        _prevAxis.copy(_axis);
        _center.copy(v1);
    }
    //
    // calc axis as dir of second and third center pos
    // project first traceAtom onto axis to get first center pos
    v1.fromArray(center, 3); // TODO
    v2.fromArray(center, 6); // TODO
    _axis.subVectors(v1, v2).normalize();
    // _center.copy( res[ 0 ].getTraceAtom() );
    a1.index = polymer.getAtomIndexByType(0, type); // TODO
    _center.copy(a1); // TODO
    vt.copy(a1); // TODO
    projectPointOnVector(vt, _axis, v1);
    vt.toArray(center, 0); // TODO
    // calc first resdir
    _resdir.subVectors(_center, v1);
    _resdir.toArray(resdir, 0); // TODO
    // calc axis as dir of n-1 and n-2 center pos
    // project last traceAtom onto axis to get last center pos
    v1.fromArray(center, 3 * n - 6); // TODO
    v2.fromArray(center, 3 * n - 9); // TODO
    _axis.subVectors(v1, v2).normalize();
    // _center.copy( res[ n - 1 ].getTraceAtom() );
    a1.index = polymer.getAtomIndexByType(n - 1, type); // TODO
    _center.copy(a1); // TODO
    vt.copy(a1); // TODO
    projectPointOnVector(vt, _axis, v1);
    vt.toArray(center, 3 * n - 3); // TODO
    // calc last three resdir
    for (var i$1 = n - 3; i$1 < n; ++i$1) {
        v1.fromArray(center, 3 * i$1); // TODO
        // _center.copy( res[ i ].getTraceAtom() );
        a1.index = polymer.getAtomIndexByType(i$1, type); // TODO
        _center.copy(a1); // TODO
        _resdir.subVectors(_center, v1);
        _resdir.toArray(resdir, 3 * i$1); // TODO
    }
    // average measures to define them on the residues
    var resRadius = new Float32Array(n);
    var resTwist = new Float32Array(n);
    var resRise = new Float32Array(n);
    var resBending = new Float32Array(n);
    resRadius[1] = radius[0];
    resTwist[1] = twist[0];
    resRise[1] = radius[0];
    for (var i$2 = 2; i$2 < n - 2; ++i$2) {
        resRadius[i$2] = 0.5 * (radius[i$2 - 2] + radius[i$2 - 1]);
        resTwist[i$2] = 0.5 * (twist[i$2 - 2] + twist[i$2 - 1]);
        resRise[i$2] = 0.5 * (rise[i$2 - 2] + rise[i$2 - 1]);
        v1.fromArray(axis, 3 * (i$2 - 2)); // TODO
        v2.fromArray(axis, 3 * (i$2 - 1)); // TODO
        resBending[i$2] = 180.0 / Math.PI * Math.acos(Math.cos(v1.angleTo(v2)));
    }
    resRadius[n - 2] = radius[n - 4];
    resTwist[n - 2] = twist[n - 4];
    resRise[n - 2] = rise[n - 4];
    // average helix axes to define them on the residues
    var resAxis = new Float32Array(3 * n);
    copyArray(axis, resAxis, 0, 0, 3);
    copyArray(axis, resAxis, 0, 3, 3);
    for (var i$3 = 2; i$3 < n - 2; ++i$3) {
        v1.fromArray(axis, 3 * (i$3 - 2)); // TODO
        v2.fromArray(axis, 3 * (i$3 - 1)); // TODO
        _axis.addVectors(v2, v1).multiplyScalar(0.5).normalize();
        _axis.toArray(resAxis, 3 * i$3); // TODO
    }
    copyArray(axis, resAxis, 3 * n - 12, 3 * n - 6, 3);
    copyArray(axis, resAxis, 3 * n - 12, 3 * n - 3, 3);
    return {
        center: center,
        axis: resAxis,
        bending: resBending,
        radius: resRadius,
        rise: resRise,
        twist: resTwist,
        resdir: resdir
    };
};

/**
 * @file Helixbundle
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Helixbundle = function Helixbundle(polymer) {
    this.polymer = polymer;
    this.helixorient = new Helixorient(polymer);
    this.position = this.helixorient.getPosition();
};
Helixbundle.prototype.getAxis = function getAxis (localAngle, centerDist, ssBorder, colorParams, radiusParams) {
    localAngle = localAngle || 30;
    centerDist = centerDist || 2.5;
    ssBorder = ssBorder === undefined ? false : ssBorder;
    var polymer = this.polymer;
    var structure = polymer.structure;
    var n = polymer.residueCount;
    var residueIndexStart = polymer.residueIndexStart;
    var pos = this.position;
    var cp = colorParams || {};
    cp.structure = structure;
    var colormaker = ColormakerRegistry$1.getScheme(cp);
    var radiusFactory = new RadiusFactory(radiusParams);
    var j = 0;
    var k = 0;
    var axis = [];
    var center = [];
    var beg = [];
    var end = [];
    var col = [];
    var pick = [];
    var size = [];
    var residueOffset = [];
    var residueCount = [];
    var tmpAxis = new Float32Array(n * 3);
    var tmpCenter = new Float32Array(n * 3);
    var _axis, _center;
    var _beg = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var _end = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var rp1 = structure.getResidueProxy();
    var rp2 = structure.getResidueProxy();
    var ap = structure.getAtomProxy();
    var c1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var c2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var split = false;
    for (var i = 0; i < n; ++i) {
        rp1.index = residueIndexStart + i;
        c1.fromArray(pos.center, i * 3);
        if (i === n - 1) {
            split = true;
        }
        else {
            rp2.index = residueIndexStart + i + 1;
            c2.fromArray(pos.center, i * 3 + 3);
            if (ssBorder && rp1.sstruc !== rp2.sstruc) {
                split = true;
            }
            else if (c1.distanceTo(c2) > centerDist) {
                split = true;
            }
            else if (pos.bending[i] > localAngle) {
                split = true;
            }
        }
        if (split) {
            if (i - j < 4) {
                j = i;
                split = false;
                continue;
            }
            ap.index = rp1.traceAtomIndex;
            // ignore first and last axis
            tmpAxis = pos.axis.subarray(j * 3 + 3, i * 3);
            tmpCenter = pos.center.subarray(j * 3, i * 3 + 3);
            _axis = calculateMeanVector3(tmpAxis).normalize();
            _center = calculateMeanVector3(tmpCenter);
            _beg.fromArray(tmpCenter);
            projectPointOnVector(_beg, _axis, _center);
            _end.fromArray(tmpCenter, tmpCenter.length - 3);
            projectPointOnVector(_end, _axis, _center);
            _axis.subVectors(_end, _beg);
            _axis.toArray(axis, k);
            _center.toArray(center, k);
            _beg.toArray(beg, k);
            _end.toArray(end, k);
            colormaker.atomColorToArray(ap, col, k);
            pick.push(ap.index);
            size.push(radiusFactory.atomRadius(ap));
            residueOffset.push(residueIndexStart + j);
            residueCount.push(residueIndexStart + i + 1 - j);
            k += 3;
            j = i;
            split = false;
        }
    }
    var picking = new Float32Array(pick);
    return {
        axis: new Float32Array(axis),
        center: new Float32Array(center),
        begin: new Float32Array(beg),
        end: new Float32Array(end),
        color: new Float32Array(col),
        picking: new AtomPicker(picking, structure),
        size: new Float32Array(size),
        residueOffset: residueOffset,
        residueCount: residueCount
    };
};

/**
 * @file Binary Heap
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Binary heap implementation
 * @class
 * @author http://eloquentjavascript.net/appendix2.htm
 * @param {Function} scoreFunction - the heap scoring function
 */
var BinaryHeap = function BinaryHeap(scoreFunction) {
    this.scoreFunction = scoreFunction;
    this.content = [];
    this.scoreFunction = scoreFunction;
};
BinaryHeap.prototype.push = function push (element) {
    // Add the new element to the end of the array.
    this.content.push(element);
    // Allow it to bubble up.
    this.bubbleUp(this.content.length - 1);
};
BinaryHeap.prototype.pop = function pop () {
    // Store the first element so we can return it later.
    var result = this.content[0];
    // Get the element at the end of the array.
    var end = this.content.pop();
    // If there are any elements left, put the end element at the
    // start, and let it sink down.
    if (end && this.content.length > 0) {
        this.content[0] = end;
        this.sinkDown(0);
    }
    return result;
};
BinaryHeap.prototype.peek = function peek () {
    return this.content[0];
};
BinaryHeap.prototype.remove = function remove (element) {
    var len = this.content.length;
    // To remove a value, we must search through the array to find it.
    for (var i = 0; i < len; i++) {
        if (this.content[i] === element) {
            // When it is found, the process seen in 'pop' is repeated
            // to fill up the hole.
            var end = this.content.pop();
            if (end && i !== len - 1) {
                this.content[i] = end;
                if (this.scoreFunction(end) < this.scoreFunction(element)) {
                    this.bubbleUp(i);
                }
                else {
                    this.sinkDown(i);
                }
            }
            return;
        }
    }
    throw new Error('Node not found.');
};
BinaryHeap.prototype.size = function size () {
    return this.content.length;
};
BinaryHeap.prototype.bubbleUp = function bubbleUp (n) {
    // Fetch the element that has to be moved.
    var element = this.content[n];
    // When at 0, an element can not go up any further.
    while (n > 0) {
        // Compute the parent element's index, and fetch it.
        var parentN = Math.floor((n + 1) / 2) - 1;
        var parent = this.content[parentN];
        // Swap the elements if the parent is greater.
        if (this.scoreFunction(element) < this.scoreFunction(parent)) {
            this.content[parentN] = element;
            this.content[n] = parent;
            // Update 'n' to continue at the new position.
            n = parentN;
        }
        else {
            // Found a parent that is less, no need to move it further.
            break;
        }
    }
};
BinaryHeap.prototype.sinkDown = function sinkDown (n) {
    // Look up the target element and its score.
    var length = this.content.length;
    var element = this.content[n];
    var elemScore = this.scoreFunction(element);
    var child1Score = 0;
    var child2Score = 0;
    while (true) {
        // Compute the indices of the child elements.
        var child2N = (n + 1) * 2;
        var child1N = child2N - 1;
        // This is used to store the new position of the element, if any.
        var swap = null;
        // If the first child exists (is inside the array)...
        if (child1N < length) {
            // Look it up and compute its score.
            var child1 = this.content[child1N];
            child1Score = this.scoreFunction(child1);
            // If the score is less than our element's, we need to swap.
            if (child1Score < elemScore)
                { swap = child1N; }
        }
        // Do the same checks for the other child.
        if (child2N < length) {
            var child2 = this.content[child2N];
            child2Score = this.scoreFunction(child2);
            if (child2Score < (swap === null ? elemScore : child1Score))
                { swap = child2N; }
        }
        // If the element needs to be moved, swap it, and continue.
        if (swap !== null) {
            this.content[n] = this.content[swap];
            this.content[swap] = element;
            n = swap;
        }
        else {
            // Otherwise, we are done.
            break;
        }
    }
};

/**
 * @file Kdtree
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * 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
 */
var Kdtree = function Kdtree(points, metric) {
    this.points = points;
    this.metric = metric;
    this.maxDepth = 0;
    this.currentNode = 0;
    var n = points.length / 3;
    var indices = new Uint32Array(n);
    for (var i = 0; i < n; ++i) {
        indices[i] = i;
    }
    this.indices = indices;
    this.nodes = new Int32Array(n * 4);
    this.rootIndex = this.buildTree(0, -1, 0, n);
};
Kdtree.prototype.buildTree = function buildTree (depth, parent, arrBegin, arrEnd) {
    if (depth > this.maxDepth)
        { this.maxDepth = depth; }
    var plength = arrEnd - arrBegin;
    if (plength === 0) {
        return -1;
    }
    var nodeIndex = this.currentNode * 4;
    var nodes = this.nodes;
    this.currentNode += 1;
    if (plength === 1) {
        nodes[nodeIndex] = arrBegin;
        nodes[nodeIndex + 1] = -1;
        nodes[nodeIndex + 2] = -1;
        nodes[nodeIndex + 3] = parent;
        return nodeIndex;
    }
    // if(plength <= 32){
    //   return nodeIndex;
    // }
    var indices = this.indices;
    var points = this.points;
    var arrMedian = arrBegin + Math.floor(plength / 2);
    var currentDim = depth % 3;
    // inlined quickselect function
    var j, tmp, pivotIndex, pivotValue, storeIndex;
    var left = arrBegin;
    var right = arrEnd - 1;
    while (right > left) {
        pivotIndex = (left + right) >> 1;
        pivotValue = points[indices[pivotIndex] * 3 + currentDim];
        // swap( pivotIndex, right );
        tmp = indices[pivotIndex];
        indices[pivotIndex] = indices[right];
        indices[right] = tmp;
        storeIndex = left;
        for (j = left; j < right; ++j) {
            if (points[indices[j] * 3 + currentDim] < pivotValue) {
                // swap( storeIndex, j );
                tmp = indices[storeIndex];
                indices[storeIndex] = indices[j];
                indices[j] = tmp;
                ++storeIndex;
            }
        }
        // swap( right, storeIndex );
        tmp = indices[right];
        indices[right] = indices[storeIndex];
        indices[storeIndex] = tmp;
        pivotIndex = storeIndex;
        if (arrMedian === pivotIndex) {
            break;
        }
        else if (arrMedian < pivotIndex) {
            right = pivotIndex - 1;
        }
        else {
            left = pivotIndex + 1;
        }
    }
    nodes[nodeIndex] = arrMedian;
    nodes[nodeIndex + 1] = this.buildTree(depth + 1, nodeIndex, arrBegin, arrMedian);
    nodes[nodeIndex + 2] = this.buildTree(depth + 1, nodeIndex, arrMedian + 1, arrEnd);
    nodes[nodeIndex + 3] = parent;
    return nodeIndex;
};
Kdtree.prototype.getNodeDepth = function getNodeDepth (nodeIndex) {
    var parentIndex = this.nodes[nodeIndex + 3];
    return (parentIndex === -1) ? 0 : this.getNodeDepth(parentIndex) + 1;
};
// TODO
// function getNodePos (node) {}
/**
 * find nearest points
 * @param {Array} point - array of size 3
 * @param {Integer} maxNodes - max amount of nodes to return
 * @param {Float} maxDistance - maximum distance of point to result nodes
 * @return {Array} array of point, distance pairs
 */
Kdtree.prototype.nearest = function nearest (point, maxNodes, maxDistance) {
        var this$1 = this;

    var bestNodes = new BinaryHeap(function (e) { return -e[1]; });
    var nodes = this.nodes;
    var points = this.points;
    var indices = this.indices;
    var nearestSearch = function (nodeIndex) {
        var bestChild, otherChild;
        var dimension = this$1.getNodeDepth(nodeIndex) % 3;
        var pointIndex = indices[nodes[nodeIndex]] * 3;
        var ownPoint = [
            points[pointIndex + 0],
            points[pointIndex + 1],
            points[pointIndex + 2]
        ];
        var ownDistance = this$1.metric(point, ownPoint);
        function saveNode(nodeIndex, distance) {
            bestNodes.push([nodeIndex, distance]);
            if (bestNodes.size() > maxNodes) {
                bestNodes.pop();
            }
        }
        var leftIndex = nodes[nodeIndex + 1];
        var rightIndex = nodes[nodeIndex + 2];
        // if it's a leaf
        if (rightIndex === -1 && leftIndex === -1) {
            if ((bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) &&
                ownDistance <= maxDistance) {
                saveNode(nodeIndex, ownDistance);
            }
            return;
        }
        if (rightIndex === -1) {
            bestChild = leftIndex;
        }
        else if (leftIndex === -1) {
            bestChild = rightIndex;
        }
        else {
            if (point[dimension] <= points[pointIndex + dimension]) {
                bestChild = leftIndex;
            }
            else {
                bestChild = rightIndex;
            }
        }
        // recursive search
        nearestSearch(bestChild);
        if ((bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) &&
            ownDistance <= maxDistance) {
            saveNode(nodeIndex, ownDistance);
        }
        // if there's still room or the current distance is nearer than the best distance
        var linearPoint = [];
        for (var i = 0; i < 3; i += 1) {
            if (i === dimension) {
                linearPoint[i] = point[i];
            }
            else {
                linearPoint[i] = points[pointIndex + i];
            }
        }
        var linearDistance = this$1.metric(linearPoint, ownPoint);
        if ((bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) &&
            Math.abs(linearDistance) <= maxDistance) {
            if (bestChild === leftIndex) {
                otherChild = rightIndex;
            }
            else {
                otherChild = leftIndex;
            }
            if (otherChild !== -1) {
                nearestSearch(otherChild);
            }
        }
    };
    nearestSearch(this.rootIndex);
    var result = [];
    for (var i = 0, il = Math.min(bestNodes.size(), maxNodes); i < il; i += 1) {
        result.push(bestNodes.content[i]);
    }
    return result;
};
Kdtree.prototype.verify = function verify (nodeIndex, depth) {
        if ( depth === void 0 ) depth = 0;

    var count = 1;
    if (nodeIndex === undefined) {
        nodeIndex = this.rootIndex;
    }
    if (nodeIndex === -1) {
        throw new Error('node is null');
    }
    var dim = depth % 3;
    var nodes = this.nodes;
    var points = this.points;
    var indices = this.indices;
    var leftIndex = nodes[nodeIndex + 1];
    var rightIndex = nodes[nodeIndex + 2];
    if (leftIndex !== -1) {
        if (points[indices[nodes[leftIndex]] * 3 + dim] >
            points[indices[nodes[nodeIndex]] * 3 + dim]) {
            throw new Error('left child is > parent!');
        }
        count += this.verify(leftIndex, depth + 1);
    }
    if (rightIndex !== -1) {
        if (points[indices[nodes[rightIndex]] * 3 + dim] <
            points[indices[nodes[nodeIndex]] * 3 + dim]) {
            throw new Error('right child is < parent!');
        }
        count += this.verify(rightIndex, depth + 1);
    }
    return count;
};

/**
 * @file Atom Proxy
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Atom proxy
 */
var AtomProxy = function AtomProxy(structure, index) {
    if ( index === void 0 ) index = 0;

    this.structure = structure;
    this.index = index;
    this.chainStore = structure.chainStore;
    this.residueStore = structure.residueStore;
    this.atomStore = structure.atomStore;
    this.residueMap = structure.residueMap;
    this.atomMap = structure.atomMap;
};

var prototypeAccessors$g = { bondHash: { configurable: true },entity: { configurable: true },entityIndex: { configurable: true },modelIndex: { configurable: true },chainIndex: { configurable: true },residue: { configurable: true },residueIndex: { configurable: true },sstruc: { configurable: true },inscode: { configurable: true },resno: { configurable: true },chainname: { configurable: true },chainid: { configurable: true },residueType: { configurable: true },atomType: { configurable: true },residueAtomOffset: { configurable: true },resname: { configurable: true },hetero: { configurable: true },atomname: { configurable: true },number: { configurable: true },element: { configurable: true },vdw: { configurable: true },covalent: { configurable: true },x: { configurable: true },y: { configurable: true },z: { configurable: true },serial: { configurable: true },bfactor: { configurable: true },occupancy: { configurable: true },altloc: { configurable: true },partialCharge: { configurable: true },radius: { configurable: true },formalCharge: { configurable: true },aromatic: { configurable: true },bondCount: { configurable: true } };
/**
 * @type {BondHash}
 */
prototypeAccessors$g.bondHash.get = function () { return this.structure.bondHash; };
/**
 * Molecular enity
 * @type {Entity}
 */
prototypeAccessors$g.entity.get = function () {
    return this.structure.entityList[this.entityIndex];
};
prototypeAccessors$g.entityIndex.get = function () {
    return this.chainStore.entityIndex[this.chainIndex];
};
prototypeAccessors$g.modelIndex.get = function () {
    return this.chainStore.modelIndex[this.chainIndex];
};
prototypeAccessors$g.chainIndex.get = function () {
    return this.residueStore.chainIndex[this.residueIndex];
};
/**
 * @type {ResidueProxy}
 */
prototypeAccessors$g.residue.get = function () {
    console.warn('residue - might be expensive');
    return this.structure.getResidueProxy(this.residueIndex);
};
prototypeAccessors$g.residueIndex.get = function () {
    return this.atomStore.residueIndex[this.index];
};
prototypeAccessors$g.residueIndex.set = function (value) {
    this.atomStore.residueIndex[this.index] = value;
};
//
/**
 * Secondary structure code
 * @type {String}
 */
prototypeAccessors$g.sstruc.get = function () {
    return this.residueStore.getSstruc(this.residueIndex);
};
/**
 * Insertion code
 * @type {String}
 */
prototypeAccessors$g.inscode.get = function () {
    return this.residueStore.getInscode(this.residueIndex);
};
/**
 * Residue number/label
 * @type {Integer}
 */
prototypeAccessors$g.resno.get = function () {
    return this.residueStore.resno[this.residueIndex];
};
/**
 * Chain name
 * @type {String}
 */
prototypeAccessors$g.chainname.get = function () {
    return this.chainStore.getChainname(this.chainIndex);
};
/**
 * Chain id
 * @type {String}
 */
prototypeAccessors$g.chainid.get = function () {
    return this.chainStore.getChainid(this.chainIndex);
};
//
/**
 * @type {ResidueType}
 */
prototypeAccessors$g.residueType.get = function () {
    return this.residueMap.get(this.residueStore.residueTypeId[this.residueIndex]);
};
/**
 * @type {AtomType}
 */
prototypeAccessors$g.atomType.get = function () {
    return this.atomMap.get(this.atomStore.atomTypeId[this.index]);
};
prototypeAccessors$g.residueAtomOffset.get = function () {
    return this.residueStore.atomOffset[this.residueIndex];
};
//
/**
 * Residue name
 */
prototypeAccessors$g.resname.get = function () {
    return this.residueType.resname;
};
/**
 * Hetero flag
 */
prototypeAccessors$g.hetero.get = function () {
    return this.residueType.hetero;
};
//
/**
 * Atom name
 */
prototypeAccessors$g.atomname.get = function () {
    return this.atomType.atomname;
};
/**
 * Atomic number
 */
prototypeAccessors$g.number.get = function () {
    return this.atomType.number;
};
/**
 * Element
 */
prototypeAccessors$g.element.get = function () {
    return this.atomType.element;
};
/**
 * Van-der-Waals radius
 */
prototypeAccessors$g.vdw.get = function () {
    return this.atomType.vdw;
};
/**
 * Covalent radius
 */
prototypeAccessors$g.covalent.get = function () {
    return this.atomType.covalent;
};
//
/**
 * X coordinate
 */
prototypeAccessors$g.x.get = function () {
    return this.atomStore.x[this.index];
};
prototypeAccessors$g.x.set = function (value) {
    this.atomStore.x[this.index] = value;
};
/**
 * Y coordinate
 */
prototypeAccessors$g.y.get = function () {
    return this.atomStore.y[this.index];
};
prototypeAccessors$g.y.set = function (value) {
    this.atomStore.y[this.index] = value;
};
/**
 * Z coordinate
 */
prototypeAccessors$g.z.get = function () {
    return this.atomStore.z[this.index];
};
prototypeAccessors$g.z.set = function (value) {
    this.atomStore.z[this.index] = value;
};
/**
 * Serial number
 */
prototypeAccessors$g.serial.get = function () {
    return this.atomStore.serial[this.index];
};
prototypeAccessors$g.serial.set = function (value) {
    this.atomStore.serial[this.index] = value;
};
/**
 * B-factor value
 */
prototypeAccessors$g.bfactor.get = function () {
    return this.atomStore.bfactor[this.index];
};
prototypeAccessors$g.bfactor.set = function (value) {
    this.atomStore.bfactor[this.index] = value;
};
/**
 * Occupancy value
 */
prototypeAccessors$g.occupancy.get = function () {
    return this.atomStore.occupancy[this.index];
};
prototypeAccessors$g.occupancy.set = function (value) {
    this.atomStore.occupancy[this.index] = value;
};
/**
 * Alternate location identifier
 */
prototypeAccessors$g.altloc.get = function () {
    return this.atomStore.getAltloc(this.index);
};
prototypeAccessors$g.altloc.set = function (value) {
    this.atomStore.setAltloc(this.index, value);
};
/**
 * Partial charge
 */
prototypeAccessors$g.partialCharge.get = function () {
    return this.atomStore.partialCharge ? this.atomStore.partialCharge[this.index] : null;
};
prototypeAccessors$g.partialCharge.set = function (value) {
    if (this.atomStore.partialCharge) {
        this.atomStore.partialCharge[this.index] = value;
    }
};
/**
 * Explicit radius
 */
prototypeAccessors$g.radius.get = function () {
    return this.atomStore.radius ? this.atomStore.radius[this.index] : null;
};
prototypeAccessors$g.radius.set = function (value) {
    if (this.atomStore.radius) {
        this.atomStore.radius[this.index] = value;
    }
};
/**
 * Formal charge
 */
prototypeAccessors$g.formalCharge.get = function () {
    return this.atomStore.formalCharge ? this.atomStore.formalCharge[this.index] : null;
};
prototypeAccessors$g.formalCharge.set = function (value) {
    if (this.atomStore.formalCharge) {
        this.atomStore.formalCharge[this.index] = value;
    }
};
/**
 * Aromaticity flag
 */
prototypeAccessors$g.aromatic.get = function () {
    if (this.atomStore.aromatic) {
        return this.atomStore.aromatic[this.index];
    }
    else {
        return this.residueType.isAromatic(this) ? 1 : 0;
    }
};
prototypeAccessors$g.aromatic.set = function (value) {
    if (this.atomStore.aromatic) {
        this.atomStore.aromatic[this.index] = value;
    }
};
//
prototypeAccessors$g.bondCount.get = function () {
    return this.bondHash.countArray[this.index]; // TODO
};
//
/**
 * Iterate over each bond
 * @param  {function(bond: BondProxy)} callback - iterator callback function
 * @param  {BondProxy} [bp] - optional target bond proxy for use in the callback
 * @return {undefined}
 */
AtomProxy.prototype.eachBond = function eachBond (callback, bp) {
    bp = bp || this.structure._bp;
    var idx = this.index;
    var bondHash = this.bondHash; // TODO
    var indexArray = bondHash.indexArray;
    var n = bondHash.countArray[idx];
    var offset = bondHash.offsetArray[idx];
    for (var i = 0; i < n; ++i) {
        bp.index = indexArray[offset + i];
        callback(bp);
    }
};
/**
 * Iterate over each bonded atom
 * @param  {function(atom: AtomProxy)} callback - iterator callback function
 * @param  {AtomProxy} [ap] - optional target atom proxy for use in the callback
 * @return {undefined}
 */
AtomProxy.prototype.eachBondedAtom = function eachBondedAtom (callback, _ap) {
    var ap = _ap ? _ap : this.structure._ap;
    var idx = this.index;
    this.eachBond(function (bp) {
        ap.index = idx !== bp.atomIndex1 ? bp.atomIndex1 : bp.atomIndex2;
        callback(ap);
    });
    this.index = idx;
};
/**
 * Check if this atom is bonded to the given atom,
 * assumes both atoms are from the same structure
 * @param  {AtomProxy} ap - the given atom
 * @return {Boolean} whether a bond exists or not
 */
AtomProxy.prototype.hasBondTo = function hasBondTo (ap) {
    var flag = false;
    this.eachBondedAtom(function (bap) {
        if (ap.index === bap.index)
            { flag = true; }
    });
    return flag;
};
AtomProxy.prototype.bondToElementCount = function bondToElementCount (element) {
    var count = 0;
    var idx = this.index; // Avoid reentrancy problems
    this.eachBondedAtom(function (bap) {
        if (bap.number === element)
            { count += 1; }
    });
    this.index = idx;
    return count;
};
AtomProxy.prototype.hasBondToElement = function hasBondToElement (element) {
    return this.bondToElementCount(element) > 0;
};
//
/**
 * If atom is part of a backbone
 * @return {Boolean} flag
 */
AtomProxy.prototype.isBackbone = function isBackbone () {
    var backboneIndexList = this.residueType.backboneIndexList;
    if (backboneIndexList.length > 0) {
        return backboneIndexList.includes(this.index - this.residueAtomOffset);
    }
    else {
        return false;
    }
};
/**
 * If atom is part of a polymer
 * @return {Boolean} flag
 */
AtomProxy.prototype.isPolymer = function isPolymer () {
    if (this.structure.entityList.length > 0) {
        return this.entity.isPolymer();
    }
    else {
        var moleculeType = this.residueType.moleculeType;
        return (moleculeType === ProteinType ||
            moleculeType === RnaType ||
            moleculeType === DnaType);
    }
};
/**
 * If atom is part of a sidechin
 * @return {Boolean} flag
 */
AtomProxy.prototype.isSidechain = function isSidechain () {
    return this.isPolymer() && !this.isBackbone();
};
/**
 * If atom is part of a coarse-grain group
 * @return {Boolean} flag
 */
AtomProxy.prototype.isCg = function isCg () {
    var backboneType = this.residueType.backboneType;
    return (backboneType === CgProteinBackboneType ||
        backboneType === CgRnaBackboneType ||
        backboneType === CgDnaBackboneType);
};
AtomProxy.prototype.isTrace = function isTrace () {
    return this.index === (this.residueType.traceAtomIndex + this.residueAtomOffset);
};
/**
 * If atom is part of a hetero group
 * @return {Boolean} flag
 */
AtomProxy.prototype.isHetero = function isHetero () {
    return this.residueType.hetero === 1;
};
/**
 * If atom is part of a protein molecule
 * @return {Boolean} flag
 */
AtomProxy.prototype.isProtein = function isProtein () {
    return this.residueType.moleculeType === ProteinType;
};
/**
 * If atom is part of a nucleic molecule
 * @return {Boolean} flag
 */
AtomProxy.prototype.isNucleic = function isNucleic () {
    var moleculeType = this.residueType.moleculeType;
    return moleculeType === RnaType || moleculeType === DnaType;
};
/**
 * If atom is part of a rna
 * @return {Boolean} flag
 */
AtomProxy.prototype.isRna = function isRna () {
    return this.residueType.moleculeType === RnaType;
};
/**
 * If atom is part of a dna
 * @return {Boolean} flag
 */
AtomProxy.prototype.isDna = function isDna () {
    return this.residueType.moleculeType === DnaType;
};
/**
 * If atom is part of a water molecule
 * @return {Boolean} flag
 */
AtomProxy.prototype.isWater = function isWater () {
    return this.residueType.moleculeType === WaterType;
};
/**
 * If atom is part of an ion
 * @return {Boolean} flag
 */
AtomProxy.prototype.isIon = function isIon () {
    return this.residueType.moleculeType === IonType;
};
/**
 * If atom is part of a saccharide
 * @return {Boolean} flag
 */
AtomProxy.prototype.isSaccharide = function isSaccharide () {
    return this.residueType.moleculeType === SaccharideType;
};
/**
 * If atom is part of a helix
 * @return {Boolean} flag
 */
AtomProxy.prototype.isHelix = function isHelix () {
    return SecStrucHelix.includes(this.sstruc);
};
/**
 * If atom is part of a sheet
 * @return {Boolean} flag
 */
AtomProxy.prototype.isSheet = function isSheet () {
    return SecStrucSheet.includes(this.sstruc);
};
/**
 * If atom is part of a turn
 * @return {Boolean} flag
 */
AtomProxy.prototype.isTurn = function isTurn () {
    return SecStrucTurn.includes(this.sstruc) && this.isProtein();
};
AtomProxy.prototype.isBonded = function isBonded () {
    return this.bondHash.countArray[this.index] !== 0; // TODO
};
/**
 * If atom is part of a ring
 * @return {Boolean} flag
 */
AtomProxy.prototype.isRing = function isRing () {
    var atomRings = this.residueType.getRings().atomRings; // TODO
    return atomRings[this.index - this.residueAtomOffset] !== undefined;
};
AtomProxy.prototype.isAromatic = function isAromatic () {
    return this.aromatic === 1;
};
AtomProxy.prototype.isPolarHydrogen = function isPolarHydrogen () {
    var result = false;
    if (this.number !== 1)
        { return result; }
    result = !this.hasBondToElement(6 /* C */);
    return result;
};
AtomProxy.prototype.isMetal = function isMetal () { return this.atomType.isMetal(); };
AtomProxy.prototype.isNonmetal = function isNonmetal () { return this.atomType.isNonmetal(); };
AtomProxy.prototype.isMetalloid = function isMetalloid () { return this.atomType.isMetalloid(); };
AtomProxy.prototype.isHalogen = function isHalogen () { return this.atomType.isHalogen(); };
AtomProxy.prototype.isDiatomicNonmetal = function isDiatomicNonmetal () { return this.atomType.isDiatomicNonmetal(); };
AtomProxy.prototype.isPolyatomicNonmetal = function isPolyatomicNonmetal () { return this.atomType.isPolyatomicNonmetal(); };
AtomProxy.prototype.isAlkaliMetal = function isAlkaliMetal () { return this.atomType.isAlkaliMetal(); };
AtomProxy.prototype.isAlkalineEarthMetal = function isAlkalineEarthMetal () { return this.atomType.isAlkalineEarthMetal(); };
AtomProxy.prototype.isNobleGas = function isNobleGas () { return this.atomType.isNobleGas(); };
AtomProxy.prototype.isTransitionMetal = function isTransitionMetal () { return this.atomType.isTransitionMetal(); };
AtomProxy.prototype.isPostTransitionMetal = function isPostTransitionMetal () { return this.atomType.isPostTransitionMetal(); };
AtomProxy.prototype.isLanthanide = function isLanthanide () { return this.atomType.isLanthanide(); };
AtomProxy.prototype.isActinide = function isActinide () { return this.atomType.isActinide(); };
AtomProxy.prototype.getDefaultValence = function getDefaultValence () { return this.atomType.getDefaultValence(); };
AtomProxy.prototype.getValenceList = function getValenceList () { return this.atomType.getValenceList(); };
AtomProxy.prototype.getOuterShellElectronCount = function getOuterShellElectronCount () { return this.atomType.getOuterShellElectronCount(); };
/**
 * Distance to another atom
 * @param  {AtomProxy} atom - the other atom
 * @return {Number} the distance
 */
AtomProxy.prototype.distanceTo = function distanceTo (atom) {
    var taa = this.atomStore;
    var aaa = atom.atomStore;
    var ti = this.index;
    var ai = atom.index;
    var x = taa.x[ti] - aaa.x[ai];
    var y = taa.y[ti] - aaa.y[ai];
    var z = taa.z[ti] - aaa.z[ai];
    var distSquared = x * x + y * y + z * z;
    return Math.sqrt(distSquared);
};
/**
 * If connected to another atom
 * @param  {AtomProxy} atom - the other atom
 * @return {Boolean} flag
 */
AtomProxy.prototype.connectedTo = function connectedTo (atom) {
    var taa = this.atomStore;
    var aaa = atom.atomStore;
    var ti = this.index;
    var ai = atom.index;
    if (taa.altloc && aaa.altloc) {
        var ta = taa.altloc[ti]; // use Uint8 value to compare
        var aa = aaa.altloc[ai]; // no need to convert to char
        // 0 is the Null character, 32 is the space character
        if (!(ta === 0 || aa === 0 || ta === 32 || aa === 32 || (ta === aa)))
            { return false; }
    }
    var x = taa.x[ti] - aaa.x[ai];
    var y = taa.y[ti] - aaa.y[ai];
    var z = taa.z[ti] - aaa.z[ai];
    var distSquared = x * x + y * y + z * z;
    // if( this.isCg() ) console.log( this.qualifiedName(), Math.sqrt( distSquared ), distSquared )
    if (distSquared < 48.0 && this.isCg())
        { return true; }
    if (isNaN(distSquared))
        { return false; }
    var d = this.covalent + atom.covalent;
    var d1 = d + 0.3;
    var d2 = d - 0.5;
    return distSquared < (d1 * d1) && distSquared > (d2 * d2);
};
/**
 * Set atom position from array
 * @param  {Array|TypedArray} array - input array
 * @param  {Integer} [offset] - the offset
 * @return {AtomProxy} this object
 */
AtomProxy.prototype.positionFromArray = function positionFromArray (array, offset) {
        if ( offset === void 0 ) offset = 0;

    this.x = array[offset + 0];
    this.y = array[offset + 1];
    this.z = array[offset + 2];
    return this;
};
/**
 * Write atom position to array
 * @param  {Array|TypedArray} [array] - target array
 * @param  {Integer} [offset] - the offset
 * @return {Array|TypedArray} target array
 */
AtomProxy.prototype.positionToArray = function positionToArray (array, offset) {
        if ( array === void 0 ) array = [];
        if ( offset === void 0 ) offset = 0;

    var index = this.index;
    var atomStore = this.atomStore;
    array[offset + 0] = atomStore.x[index];
    array[offset + 1] = atomStore.y[index];
    array[offset + 2] = atomStore.z[index];
    return array;
};
/**
 * Write atom position to vector
 * @param  {Vector3} [v] - target vector
 * @return {Vector3} target vector
 */
AtomProxy.prototype.positionToVector3 = function positionToVector3 (v) {
    if (v === undefined)
        { v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](); }
    v.x = this.x;
    v.y = this.y;
    v.z = this.z;
    return v;
};
/**
 * Set atom position from vector
 * @param  {Vector3} v - input vector
 * @return {AtomProxy} this object
 */
AtomProxy.prototype.positionFromVector3 = function positionFromVector3 (v) {
    this.x = v.x;
    this.y = v.y;
    this.z = v.z;
    return this;
};
/**
 * Add vector to atom position
 * @param  {Vector3} v - input vector
 * @return {AtomProxy} this object
 */
AtomProxy.prototype.positionAdd = function positionAdd (v) {
    this.x += v.x;
    this.y += v.y;
    this.z += v.z;
    return this;
};
/**
 * Subtract vector from atom position
 * @param  {Vector3} v - input vector
 * @return {AtomProxy} this object
 */
AtomProxy.prototype.positionSub = function positionSub (v) {
    this.x -= v.x;
    this.y -= v.y;
    this.z -= v.z;
    return this;
};
/**
 * Get intra group/residue bonds
 * @param  {Boolean} firstOnly - immediately return the first connected atomIndex
 * @return {Integer[]|Integer|undefined} connected atomIndices
 */
AtomProxy.prototype.getResidueBonds = function getResidueBonds (firstOnly) {
        if ( firstOnly === void 0 ) firstOnly = false;

    var residueAtomOffset = this.residueAtomOffset;
    var relativeIndex = this.index - this.residueAtomOffset;
    var bonds = this.residueType.getBonds(); // TODO
    var atomIndices1 = bonds.atomIndices1;
    var atomIndices2 = bonds.atomIndices2;
    var idx1, idx2, connectedAtomIndex;
    var connectedAtomIndices;
    if (!firstOnly)
        { connectedAtomIndices = []; }
    idx1 = atomIndices1.indexOf(relativeIndex);
    while (idx1 !== -1) {
        connectedAtomIndex = atomIndices2[idx1] + residueAtomOffset;
        if (connectedAtomIndices) {
            connectedAtomIndices.push(connectedAtomIndex);
            idx1 = atomIndices1.indexOf(relativeIndex, idx1 + 1);
        }
        else {
            return connectedAtomIndex;
        }
    }
    idx2 = atomIndices2.indexOf(relativeIndex);
    while (idx2 !== -1) {
        connectedAtomIndex = atomIndices1[idx2] + residueAtomOffset;
        if (connectedAtomIndices) {
            connectedAtomIndices.push(connectedAtomIndex);
            idx2 = atomIndices2.indexOf(relativeIndex, idx2 + 1);
        }
        else {
            return connectedAtomIndex;
        }
    }
    return connectedAtomIndices;
};
//
AtomProxy.prototype.qualifiedName = function qualifiedName (noResname) {
        if ( noResname === void 0 ) noResname = false;

    var name = '';
    if (this.resname && !noResname)
        { name += '[' + this.resname + ']'; }
    if (this.resno !== undefined)
        { name += this.resno; }
    if (this.inscode)
        { name += '^' + this.inscode; }
    if (this.chainname)
        { name += ':' + this.chainname; }
    if (this.atomname)
        { name += '.' + this.atomname; }
    if (this.altloc)
        { name += '%' + this.altloc; }
    if (this.structure.modelStore.count > 1)
        { name += '/' + this.modelIndex; }
    return name;
};
/**
 * Clone object
 * @return {AtomProxy} cloned atom
 */
AtomProxy.prototype.clone = function clone () {
    return new AtomProxy(this.structure, this.index);
};
AtomProxy.prototype.toObject = function 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
    };
};

Object.defineProperties( AtomProxy.prototype, prototypeAccessors$g );

/**
 * @file Kdtree
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function euclideanDistSq(a, b) {
    var dx = a[0] - b[0];
    var dy = a[1] - b[1];
    var dz = a[2] - b[2];
    return dx * dx + dy * dy + dz * dz;
}
function euclideanDist(a, b) {
    return Math.sqrt(euclideanDistSq(a, b));
}
var pointArray = new Float32Array(3);
var Kdtree$1 = function Kdtree$$1(structure, useSquaredDist) {
    if ( useSquaredDist === void 0 ) useSquaredDist = false;

    if (Debug)
        { Log.time('Kdtree build'); }
    var metric = useSquaredDist ? euclideanDistSq : euclideanDist;
    var points = new Float32Array(structure.atomCount * 3);
    var atomIndices = new Uint32Array(structure.atomCount);
    var i = 0;
    structure.eachAtom(function (ap) {
        points[i + 0] = ap.x;
        points[i + 1] = ap.y;
        points[i + 2] = ap.z;
        atomIndices[i / 3] = ap.index;
        i += 3;
    });
    this.atomIndices = atomIndices;
    this.points = points;
    this.kdtree = new Kdtree(points, metric);
    if (Debug)
        { Log.timeEnd('Kdtree build'); }
    // console.log("this.kdtree.verify()", this.kdtree.verify())
};
Kdtree$1.prototype.nearest = function nearest (point, maxNodes, maxDistance) {
    // Log.time( "Kdtree nearest" );
    if (point instanceof __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]) {
        point.toArray(pointArray);
    }
    else if (point instanceof AtomProxy) {
        point.positionToArray(pointArray);
    }
    var nodeList = this.kdtree.nearest(pointArray, maxNodes, maxDistance);
    var indices = this.kdtree.indices;
    var nodes = this.kdtree.nodes;
    var atomIndices = this.atomIndices;
    var resultList = [];
    for (var i = 0, n = nodeList.length; i < n; ++i) {
        var d = nodeList[i];
        var nodeIndex = d[0];
        var dist = d[1];
        resultList.push({
            index: atomIndices[indices[nodes[nodeIndex]]],
            distance: dist
        });
    }
    // Log.timeEnd( "Kdtree nearest" );
    return resultList;
};

/**
 * @file Symmetry Constants
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var SymOpCode = {
    ' ': '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'
};
// encoded, originally from CCP4 symop.lib
var EncodedSymOp = {
    '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': " !#*,#.%&$'&!# ,- '&$%/$# !-*!/$%&.%()+$%+ ,-*!-)+(%&(!-*,#*+()&$)#*,- ,"
};

/**
 * @file Symmetry Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var reInteger = /^[1-9]$/;
function getSymmetryOperations(spacegroup) {
    var encodedSymopList = EncodedSymOp[spacegroup];
    var matrixDict = {};
    if (encodedSymopList === undefined) {
        console.warn(("spacegroup '" + spacegroup + "' not found in symop library"));
        return matrixDict;
    }
    var symopList = [];
    for (var i = 0, il = encodedSymopList.length; i < il; i += 3) {
        var symop = [];
        for (var j = 0; j < 3; ++j) {
            symop.push(SymOpCode[encodedSymopList[i + j]]);
        }
        symopList.push(symop);
    }
    symopList.forEach(function (symop) {
        var row = 0;
        var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
        var me = matrix.elements;
        matrixDict[symop.toString()] = matrix;
        symop.forEach(function (elm) {
            var negate = false;
            var denominator = false;
            for (var i = 0, n = elm.length; i < n; ++i) {
                var c = elm[i];
                if (c === '-') {
                    negate = true;
                }
                else if (c === '+') {
                    negate = false;
                }
                else if (c === '/') {
                    denominator = true;
                }
                else if (c === 'X') {
                    me[0 + row] = negate ? -1 : 1;
                }
                else if (c === 'Y') {
                    me[4 + row] = negate ? -1 : 1;
                }
                else if (c === 'Z') {
                    me[8 + row] = negate ? -1 : 1;
                }
                else if (reInteger.test(c)) {
                    var integer = parseInt(c);
                    if (denominator) {
                        me[12 + row] /= integer;
                    }
                    else {
                        me[12 + row] = integer;
                    }
                }
                else {
                    Log.warn(("getSymmetryOperations: unknown token '" + c + "'"));
                }
            }
            row += 1;
        });
    });
    return matrixDict;
}

/**
 * @file Assembly
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function selectionFromChains(chainList) {
    var sele = '';
    if (chainList.length > 0) {
        sele = ':' + uniqueArray(chainList).join(' OR :');
    }
    return new Selection(sele);
}
/**
 * Assembly of transformed parts of a {@link Structure}
 */
var Assembly = function Assembly(name) {
    if ( name === void 0 ) name = '';

    this.name = name;
    this.partList = [];
};

var prototypeAccessors$h = { type: { configurable: true } };
prototypeAccessors$h.type.get = function () { return 'Assembly'; };
/**
 * Add transformed parts to the assembly
 * @example
 * var m1 = new NGL.Matrix4().set( ... );
 * var m2 = new NGL.Matrix4().set( ... );
 * var assembly = new NGL.Assembly( "myAssembly" );
 * // add part that transforms chain 'A' and 'B' using matrices `m1` and `m2`
 * assembly.addPart( [ m1, m2 ], [ "A", "B" ] )
 *
 * @param {Matrix4[]} matrixList - array of 4x4 transformation matrices
 * @param {String[]} chainList - array of chain names
 * @return {AssemblyPart} the added assembly part
 */
Assembly.prototype.addPart = function addPart (matrixList, chainList) {
    var part = new AssemblyPart(matrixList, chainList);
    this.partList.push(part);
    return part;
};
/**
 * Get the number of atom for a given structure
 * @param  {Structure} structure - the given structure
 * @return {Integer} number of atoms in the assembly
 */
Assembly.prototype.getAtomCount = function getAtomCount (structure) {
    return this.partList.reduce(function (count, part) { return count + part.getAtomCount(structure); }, 0);
};
/**
 * Get the number of residues for a given structure
 * @param  {Structure} structure - the given structure
 * @return {Integer} number of residues in the assembly
 */
Assembly.prototype.getResidueCount = function getResidueCount (structure) {
    return this.partList.reduce(function (count, part) { return count + part.getResidueCount(structure); }, 0);
};
/**
 * Get number of instances the assembly will produce, i.e.
 * the number of transformations performed by the assembly
 * @return {Integer} number of instances
 */
Assembly.prototype.getInstanceCount = function getInstanceCount () {
    var instanceCount = 0;
    this.partList.forEach(function (part) {
        instanceCount += part.matrixList.length;
    });
    return instanceCount;
};
/**
 * Determine if the assembly is the full and untransformed structure
 * @param  {Structure}  structure - the given structure
 * @return {Boolean} whether the assembly is identical to the structure
 */
Assembly.prototype.isIdentity = function isIdentity (structure) {
    if (this.partList.length !== 1)
        { return false; }
    var part = this.partList[0];
    if (part.matrixList.length !== 1)
        { return false; }
    var identityMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    if (!identityMatrix.equals(part.matrixList[0]))
        { return false; }
    var structureChainList = [];
    structure.eachChain(function (cp) {
        structureChainList.push(cp.chainname);
    });
    structureChainList = uniqueArray(structureChainList);
    if (part.chainList.length !== structureChainList.length)
        { return false; }
    return true;
};
Assembly.prototype.getBoundingBox = function getBoundingBox (structure) {
    var boundingBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    this.partList.forEach(function (part) {
        var partBox = part.getBoundingBox(structure);
        boundingBox.expandByPoint(partBox.min);
        boundingBox.expandByPoint(partBox.max);
    });
    return boundingBox;
};
Assembly.prototype.getCenter = function getCenter (structure) {
    return this.getBoundingBox(structure).getCenter(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]());
};
Assembly.prototype.getSelection = function getSelection () {
    var chainList = [];
    this.partList.forEach(function (part) {
        chainList = chainList.concat(part.chainList);
    });
    return selectionFromChains(chainList);
};

Object.defineProperties( Assembly.prototype, prototypeAccessors$h );
var AssemblyPart = function AssemblyPart(matrixList, chainList) {
    if ( matrixList === void 0 ) matrixList = [];
    if ( chainList === void 0 ) chainList = [];

    this.matrixList = matrixList;
    this.chainList = chainList;
};

var prototypeAccessors$1$2 = { type: { configurable: true } };
prototypeAccessors$1$2.type.get = function () { return 'AssemblyPart'; };
AssemblyPart.prototype._getCount = function _getCount (structure, propertyName) {
        var this$1 = this;

    var count = 0;
    structure.eachChain(function (cp) {
        if (this$1.chainList.length === 0 || this$1.chainList.includes(cp.chainname)) {
            count += cp[propertyName];
        }
    });
    return this.matrixList.length * count;
};
AssemblyPart.prototype.getAtomCount = function getAtomCount (structure) {
    return this._getCount(structure, 'atomCount');
};
AssemblyPart.prototype.getResidueCount = function getResidueCount (structure) {
    return this._getCount(structure, 'residueCount');
};
AssemblyPart.prototype.getBoundingBox = function getBoundingBox (structure) {
    var partBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    var instanceBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    var selection = this.getSelection();
    var structureBox = structure.getBoundingBox(selection);
    this.matrixList.forEach(function (matrix) {
        instanceBox.copy(structureBox).applyMatrix4(matrix);
        partBox.expandByPoint(instanceBox.min);
        partBox.expandByPoint(instanceBox.max);
    });
    return partBox;
};
AssemblyPart.prototype.getSelection = function getSelection () {
    return selectionFromChains(this.chainList);
};
AssemblyPart.prototype.getView = function getView (structure) {
    var selection = this.getSelection();
    if (selection) {
        return structure.getView(selection);
    }
    else {
        return structure;
    }
};
AssemblyPart.prototype.getInstanceList = function getInstanceList () {
    var instanceList = [];
    for (var j = 0, jl = this.matrixList.length; j < jl; ++j) {
        instanceList.push({
            id: j + 1,
            name: j,
            matrix: this.matrixList[j]
        });
    }
    return instanceList;
};

Object.defineProperties( AssemblyPart.prototype, prototypeAccessors$1$2 );

/**
 * @file Structure Builder
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var StructureBuilder = function StructureBuilder(structure) {
    this.structure = structure;
    this.currentModelindex = null;
    this.currentChainid = null;
    this.currentResname = null;
    this.currentResno = null;
    this.currentInscode = undefined;
    this.currentHetero = null;
    this.previousResname = '';
    this.previousHetero = null;
    this.ai = -1;
    this.ri = -1;
    this.ci = -1;
    this.mi = -1;
};
StructureBuilder.prototype.addResidueType = function addResidueType (ri) {
    var atomStore = this.structure.atomStore;
    var residueStore = this.structure.residueStore;
    var residueMap = this.structure.residueMap;
    var count = residueStore.atomCount[ri];
    var offset = residueStore.atomOffset[ri];
    var atomTypeIdList = new Array(count);
    for (var i = 0; i < count; ++i) {
        atomTypeIdList[i] = atomStore.atomTypeId[offset + i];
    }
    residueStore.residueTypeId[ri] = residueMap.add(this.previousResname, atomTypeIdList, this.previousHetero // TODO
    );
};
StructureBuilder.prototype.addAtom = function addAtom (modelindex, chainname, chainid, resname, resno, hetero, sstruc, inscode) {
    var atomStore = this.structure.atomStore;
    var residueStore = this.structure.residueStore;
    var chainStore = this.structure.chainStore;
    var modelStore = this.structure.modelStore;
    var addModel = false;
    var addChain = false;
    var addResidue = false;
    if (this.currentModelindex !== modelindex) {
        addModel = true;
        addChain = true;
        addResidue = true;
        this.mi += 1;
        this.ci += 1;
        this.ri += 1;
    }
    else if (this.currentChainid !== chainid) {
        addChain = true;
        addResidue = true;
        this.ci += 1;
        this.ri += 1;
    }
    else if (this.currentResno !== resno || this.currentResname !== resname || this.currentInscode !== inscode) {
        addResidue = true;
        this.ri += 1;
    }
    this.ai += 1;
    if (addModel) {
        modelStore.growIfFull();
        modelStore.chainOffset[this.mi] = this.ci;
        modelStore.chainCount[this.mi] = 0;
        modelStore.count += 1;
        chainStore.modelIndex[this.ci] = this.mi;
    }
    if (addChain) {
        chainStore.growIfFull();
        chainStore.setChainname(this.ci, chainname);
        chainStore.setChainid(this.ci, chainid);
        chainStore.residueOffset[this.ci] = this.ri;
        chainStore.residueCount[this.ci] = 0;
        chainStore.count += 1;
        chainStore.modelIndex[this.ci] = this.mi;
        modelStore.chainCount[this.mi] += 1;
        residueStore.chainIndex[this.ri] = this.ci;
    }
    if (addResidue) {
        this.previousResname = this.currentResname;
        this.previousHetero = this.currentHetero;
        if (this.ri > 0)
            { this.addResidueType(this.ri - 1); }
        residueStore.growIfFull();
        residueStore.resno[this.ri] = resno;
        if (sstruc !== undefined) {
            residueStore.sstruc[this.ri] = sstruc.charCodeAt(0);
        }
        if (inscode !== undefined) {
            residueStore.inscode[this.ri] = inscode.charCodeAt(0);
        }
        residueStore.atomOffset[this.ri] = this.ai;
        residueStore.atomCount[this.ri] = 0;
        residueStore.count += 1;
        residueStore.chainIndex[this.ri] = this.ci;
        chainStore.residueCount[this.ci] += 1;
    }
    atomStore.count += 1;
    atomStore.residueIndex[this.ai] = this.ri;
    residueStore.atomCount[this.ri] += 1;
    this.currentModelindex = modelindex;
    this.currentChainid = chainid;
    this.currentResname = resname;
    this.currentResno = resno;
    this.currentInscode = inscode;
    this.currentHetero = hetero;
};
StructureBuilder.prototype.finalize = function finalize () {
    this.previousResname = this.currentResname;
    this.previousHetero = this.currentHetero;
    if (this.ri > -1)
        { this.addResidueType(this.ri); }
};

/**
 * @file Structure Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function assignSecondaryStructure(structure, secStruct) {
    if (!secStruct)
        { return; }
    if (Debug)
        { Log.time('assignSecondaryStructure'); }
    var chainnames = [];
    structure.eachModel(function (mp) {
        mp.eachChain(function (cp) {
            chainnames.push(cp.chainname);
        });
    });
    var chainnamesSorted = chainnames.slice().sort();
    var chainnamesIndex = [];
    chainnamesSorted.forEach(function (c) {
        chainnamesIndex.push(chainnames.indexOf(c));
    });
    // helix assignment
    var helices = secStruct.helices.filter(function (h) {
        return binarySearchIndexOf(chainnamesSorted, h[0]) >= 0;
    });
    helices.sort(function (h1, h2) {
        var c1 = h1[0];
        var c2 = h2[0];
        var r1 = h1[1];
        var r2 = h2[1];
        if (c1 === c2) {
            if (r1 === r2) {
                return 0;
            }
            else {
                return r1 < r2 ? -1 : 1;
            }
        }
        else {
            var idx1 = binarySearchIndexOf(chainnamesSorted, c1);
            var idx2 = binarySearchIndexOf(chainnamesSorted, c2);
            return chainnamesIndex[idx1] < chainnamesIndex[idx2] ? -1 : 1;
        }
    });
    var residueStore = structure.residueStore;
    structure.eachModel(function (mp) {
        var i = 0;
        var n = helices.length;
        if (n === 0)
            { return; }
        var helix = helices[i];
        var helixRun = false;
        var done = false;
        mp.eachChain(function (cp) {
            var chainChange = false;
            if (cp.chainname === helix[0]) {
                var count = cp.residueCount;
                var offset = cp.residueOffset;
                var end = offset + count;
                for (var j = offset; j < end; ++j) {
                    if (residueStore.resno[j] === helix[1] && // resnoBeg
                        residueStore.getInscode(j) === helix[2] // inscodeBeg
                    ) {
                        helixRun = true;
                    }
                    if (helixRun) {
                        residueStore.sstruc[j] = helix[6];
                        if (residueStore.resno[j] === helix[4] && // resnoEnd
                            residueStore.getInscode(j) === helix[5] // inscodeEnd
                        ) {
                            helixRun = false;
                            i += 1;
                            if (i < n) {
                                // must look at previous residues as
                                // residues may not be ordered by resno
                                j = offset - 1;
                                helix = helices[i];
                                chainChange = cp.chainname !== helix[0];
                            }
                            else {
                                done = true;
                            }
                        }
                    }
                    if (chainChange || done)
                        { return; }
                }
            }
        });
    });
    // sheet assignment
    var sheets = secStruct.sheets.filter(function (s) {
        return binarySearchIndexOf(chainnamesSorted, s[0]) >= 0;
    });
    sheets.sort(function (s1, s2) {
        var c1 = s1[0];
        var c2 = s2[0];
        if (c1 === c2)
            { return 0; }
        var idx1 = binarySearchIndexOf(chainnamesSorted, c1);
        var idx2 = binarySearchIndexOf(chainnamesSorted, c2);
        return chainnamesIndex[idx1] < chainnamesIndex[idx2] ? -1 : 1;
    });
    var strandCharCode = 'e'.charCodeAt(0);
    structure.eachModel(function (mp) {
        var i = 0;
        var n = sheets.length;
        if (n === 0)
            { return; }
        var sheet = sheets[i];
        var sheetRun = false;
        var done = false;
        mp.eachChain(function (cp) {
            var chainChange = false;
            if (cp.chainname === sheet[0]) {
                var count = cp.residueCount;
                var offset = cp.residueOffset;
                var end = offset + count;
                for (var j = offset; j < end; ++j) {
                    if (residueStore.resno[j] === sheet[1] && // resnoBeg
                        residueStore.getInscode(j) === sheet[2] // inscodeBeg
                    ) {
                        sheetRun = true;
                    }
                    if (sheetRun) {
                        residueStore.sstruc[j] = strandCharCode;
                        if (residueStore.resno[j] === sheet[4] && // resnoEnd
                            residueStore.getInscode(j) === sheet[5] // inscodeEnd
                        ) {
                            sheetRun = false;
                            i += 1;
                            if (i < n) {
                                // must look at previous residues as
                                // residues may not be ordered by resno
                                j = offset - 1;
                                sheet = sheets[i];
                                chainChange = cp.chainname !== sheet[0];
                            }
                            else {
                                done = true;
                            }
                        }
                    }
                    if (chainChange || done)
                        { return; }
                }
            }
        });
    });
    if (Debug)
        { Log.timeEnd('assignSecondaryStructure'); }
}
var calculateSecondaryStructure = (function () {
    // Implementation for proteins based on "pv"
    //
    // assigns secondary structure information based on a simple and very fast
    // algorithm published by Zhang and Skolnick in their TM-align paper.
    // Reference:
    //
    // TM-align: a protein structure alignment algorithm based on the Tm-score
    // (2005) NAR, 33(7) 2302-2309
    var zhangSkolnickSS = function (polymer, i, distances, delta) {
        var structure = polymer.structure;
        var offset = polymer.residueIndexStart;
        var rp1 = structure.getResidueProxy();
        var rp2 = structure.getResidueProxy();
        var ap1 = structure.getAtomProxy();
        var ap2 = structure.getAtomProxy();
        for (var j = Math.max(0, i - 2); j <= i; ++j) {
            for (var k = 2; k < 5; ++k) {
                if (j + k >= polymer.residueCount) {
                    continue;
                }
                rp1.index = offset + j;
                rp2.index = offset + j + k;
                ap1.index = rp1.traceAtomIndex;
                ap2.index = rp2.traceAtomIndex;
                var d = ap1.distanceTo(ap2);
                if (Math.abs(d - distances[k - 2]) > delta) {
                    return false;
                }
            }
        }
        return true;
    };
    var isHelical = function (polymer, i) {
        var helixDistances = [5.45, 5.18, 6.37];
        var helixDelta = 2.1;
        return zhangSkolnickSS(polymer, i, helixDistances, helixDelta);
    };
    var isSheet = function (polymer, i) {
        var sheetDistances = [6.1, 10.4, 13.0];
        var sheetDelta = 1.42;
        return zhangSkolnickSS(polymer, i, sheetDistances, sheetDelta);
    };
    var proteinPolymer = function (p) {
        var residueStore = p.residueStore;
        var offset = p.residueIndexStart;
        for (var i = 0, il = p.residueCount; i < il; ++i) {
            var sstruc = 'c';
            if (isHelical(p, i)) {
                sstruc = 'h';
            }
            else if (isSheet(p, i)) {
                sstruc = 'e';
            }
            residueStore.sstruc[offset + i] = sstruc.charCodeAt(0);
        }
    };
    var cgPolymer = function (p) {
        var localAngle = 20;
        var centerDist = 2.0;
        var residueStore = p.residueStore;
        var offset = p.residueIndexStart;
        var helixbundle = new Helixbundle(p);
        var pos = helixbundle.position;
        var c1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        var c2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        for (var i = 0, il = p.residueCount; i < il; ++i) {
            c1.fromArray(pos.center, i * 3); // TODO
            c2.fromArray(pos.center, i * 3 + 3); // TODO
            var d = c1.distanceTo(c2);
            if (d < centerDist && d > 1.0 && pos.bending[i] < localAngle) {
                residueStore.sstruc[offset + i] = 'h'.charCodeAt(0);
                residueStore.sstruc[offset + i + 1] = 'h'.charCodeAt(0);
            }
        }
    };
    return function calculateSecondaryStructure(structure) {
        if (Debug)
            { Log.time('calculateSecondaryStructure'); }
        structure.eachPolymer(function (p) {
            // assign secondary structure
            if (p.residueCount < 4)
                { return; }
            if (p.isCg()) {
                cgPolymer(p);
            }
            else if (p.isProtein()) {
                proteinPolymer(p);
            }
            else {
                return;
            }
            // set lone secondary structure assignments to "c"
            var prevSstruc;
            var sstrucCount = 0;
            p.eachResidue(function (r) {
                if (r.sstruc === prevSstruc) {
                    sstrucCount += 1;
                }
                else {
                    if (sstrucCount === 1) {
                        r.index -= 1;
                        r.sstruc = 'c';
                    }
                    sstrucCount = 1;
                    prevSstruc = r.sstruc;
                }
            });
        });
        if (Debug)
            { Log.timeEnd('calculateSecondaryStructure'); }
    };
}());
// const ChainnameAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
//                           "abcdefghijklmnopqrstuvwxyz" +
//                           "0123456789";
var ChainnameAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
function getChainname(index) {
    var n = ChainnameAlphabet.length;
    var j = index;
    var k = 0;
    var chainname = ChainnameAlphabet[j % n];
    while (j >= n) {
        j = Math.floor(j / n);
        chainname += ChainnameAlphabet[j % n];
        k += 1;
    }
    if (k >= 5) {
        Log.warn('chainname overflow');
    }
    return chainname;
}
function calculateChainnames(structure, useExistingBonds) {
    if ( useExistingBonds === void 0 ) useExistingBonds = false;

    if (Debug)
        { Log.time('calculateChainnames'); }
    var doAutoChainName = true;
    structure.eachChain(function (c) {
        if (c.chainname)
            { doAutoChainName = false; }
    });
    if (doAutoChainName) {
        var modelStore = structure.modelStore;
        var chainStore = structure.chainStore;
        var residueStore = structure.residueStore;
        var addChain = function (mIndex, chainname, rOffset, rCount) {
            var ci = chainStore.count;
            for (var i = 0; i < rCount; ++i) {
                residueStore.chainIndex[rOffset + i] = ci;
            }
            chainStore.growIfFull();
            chainStore.modelIndex[ci] = mIndex;
            chainStore.setChainname(ci, chainname);
            chainStore.setChainid(ci, chainname);
            chainStore.residueOffset[ci] = rOffset;
            chainStore.residueCount[ci] = rCount;
            chainStore.count += 1;
            modelStore.chainCount[mIndex] += 1;
        };
        var ap1 = structure.getAtomProxy();
        var ap2 = structure.getAtomProxy();
        var i = 0;
        var mi = 0;
        var rStart = 0;
        var rEnd = 0;
        var chainData = [];
        if (residueStore.count === 1) {
            chainData.push({
                mIndex: 0,
                chainname: 'A',
                rStart: 0,
                rCount: 1
            });
        }
        else {
            structure.eachResidueN(2, function (rp1, rp2) {
                var newChain = false;
                var bbType1 = rp1.backboneType;
                var bbType2 = rp2.backboneType;
                var bbTypeUnk = UnknownBackboneType;
                rEnd = rp1.index;
                if (rp1.modelIndex !== rp2.modelIndex) {
                    newChain = true;
                }
                else if (rp1.moleculeType !== rp2.moleculeType) {
                    newChain = true;
                }
                else if (bbType1 !== bbTypeUnk && bbType1 === bbType2) {
                    ap1.index = rp1.backboneEndAtomIndex;
                    ap2.index = rp2.backboneStartAtomIndex;
                    if (useExistingBonds) {
                        newChain = !ap1.hasBondTo(ap2);
                    }
                    else {
                        newChain = !ap1.connectedTo(ap2);
                    }
                }
                // current chain goes to end of the structure
                if (!newChain && rp2.index === residueStore.count - 1) {
                    newChain = true;
                    rEnd = rp2.index;
                }
                if (newChain) {
                    chainData.push({
                        mIndex: mi,
                        chainname: getChainname(i),
                        rStart: rStart,
                        rCount: rEnd - rStart + 1
                    });
                    i += 1;
                    if (rp1.modelIndex !== rp2.modelIndex) {
                        i = 0;
                        mi += 1;
                    }
                    // new chain for the last residue of the structure
                    if (rp2.index === residueStore.count - 1 && rEnd !== rp2.index) {
                        chainData.push({
                            mIndex: mi,
                            chainname: getChainname(i),
                            rStart: residueStore.count - 1,
                            rCount: 1
                        });
                    }
                    rStart = rp2.index;
                    rEnd = rp2.index;
                }
            });
        }
        //
        chainStore.count = 0;
        chainData.forEach(function (d) {
            addChain(d.mIndex, d.chainname, d.rStart, d.rCount);
        });
        var chainOffset = 0;
        structure.eachModel(function (mp) {
            modelStore.chainOffset[mp.index] = chainOffset;
            modelStore.chainCount[mp.index] -= 1;
            chainOffset += modelStore.chainCount[mp.index];
        });
    }
    if (Debug)
        { Log.timeEnd('calculateChainnames'); }
}
function calculateBonds(structure) {
    if (Debug)
        { Log.time('calculateBonds'); }
    calculateBondsWithin(structure);
    calculateBondsBetween(structure);
    if (Debug)
        { Log.timeEnd('calculateBonds'); }
}
var BondOrderTable = {
    '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 getBondOrderFromTable(resname, atomname1, atomname2) {
    var assign;

    (assign = atomname1 < atomname2 ? [atomname1, atomname2] : [atomname2, atomname1], atomname1 = assign[0], atomname2 = assign[1]);
    if (AA3.includes(resname) && atomname1 === 'C' && atomname2 === 'O')
        { return 2; }
    if (Bases.includes(resname) && atomname1 === 'OP1' && atomname2 === 'P')
        { return 2; }
    return BondOrderTable[(resname + "|" + atomname1 + "|" + atomname2)] || 1;
}
function calculateResidueBonds(r) {
    var structure = r.structure;
    var a1 = structure.getAtomProxy();
    var a2 = structure.getAtomProxy();
    var count = r.atomCount;
    var offset = r.atomOffset;
    var end = offset + count;
    var end1 = end - 1;
    var atomIndices1 = [];
    var atomIndices2 = [];
    var bondOrders = [];
    if (count > 500) {
        if (Debug)
            { Log.warn('more than 500 atoms, skip residue for auto-bonding', r.qualifiedName()); }
    }
    else {
        if (count > 50) {
            var kdtree = new Kdtree$1(r, true);
            var radius = r.isCg() ? 1.2 : 2.3;
            for (var i = offset; i < end1; ++i) {
                a1.index = i;
                var maxd = a1.covalent + radius + 0.3;
                var nearestAtoms = kdtree.nearest(a1, Infinity, maxd * maxd); // TODO
                var m = nearestAtoms.length;
                for (var j = 0; j < m; ++j) {
                    a2.index = nearestAtoms[j].index;
                    if (a1.index < a2.index) {
                        if (a1.connectedTo(a2)) {
                            atomIndices1.push(a1.index - offset);
                            atomIndices2.push(a2.index - offset);
                            bondOrders.push(getBondOrderFromTable(a1.resname, a1.atomname, a2.atomname));
                        }
                    }
                }
            }
        }
        else {
            for (var i$1 = offset; i$1 < end1; ++i$1) {
                a1.index = i$1;
                for (var j$1 = i$1 + 1; j$1 <= end1; ++j$1) {
                    a2.index = j$1;
                    if (a1.connectedTo(a2)) {
                        atomIndices1.push(i$1 - offset);
                        atomIndices2.push(j$1 - offset);
                        bondOrders.push(getBondOrderFromTable(a1.resname, a1.atomname, a2.atomname));
                    }
                }
            }
        }
    }
    return {
        atomIndices1: atomIndices1,
        atomIndices2: atomIndices2,
        bondOrders: bondOrders
    };
}
function calculateAtomBondMap(structure) {
    if (Debug)
        { Log.time('calculateAtomBondMap'); }
    var atomBondMap = [];
    structure.eachBond(function (bp) {
        var ai1 = bp.atomIndex1;
        var ai2 = bp.atomIndex2;
        if (atomBondMap[ai1] === undefined)
            { atomBondMap[ai1] = []; }
        atomBondMap[ai1][ai2] = bp.index;
    });
    if (Debug)
        { Log.timeEnd('calculateAtomBondMap'); }
    return atomBondMap;
}
function calculateBondsWithin(structure, onlyAddRung) {
    if ( onlyAddRung === void 0 ) onlyAddRung = false;

    if (Debug)
        { Log.time('calculateBondsWithin'); }
    var bondStore = structure.bondStore;
    var rungBondStore = structure.rungBondStore;
    var rungAtomSet = structure.getAtomSet(false);
    var a1 = structure.getAtomProxy();
    var a2 = structure.getAtomProxy();
    var bp = structure.getBondProxy();
    var atomBondMap = onlyAddRung ? null : calculateAtomBondMap(structure);
    structure.eachResidue(function (r) {
        if (!onlyAddRung && atomBondMap) {
            var count = r.atomCount;
            var offset = r.atomOffset;
            if (count > 500) {
                Log.warn('more than 500 atoms, skip residue for auto-bonding', r.qualifiedName());
                return;
            }
            var bonds = r.getBonds();
            var atomIndices1 = bonds.atomIndices1;
            var atomIndices2 = bonds.atomIndices2;
            var bondOrders = bonds.bondOrders;
            var nn = atomIndices1.length;
            for (var i = 0; i < nn; ++i) {
                var rai1 = atomIndices1[i];
                var rai2 = atomIndices2[i];
                var ai1 = rai1 + offset;
                var ai2 = rai2 + offset;
                var tmp = atomBondMap[ai1];
                if (tmp !== undefined && tmp[ai2] !== undefined) {
                    bp.index = tmp[ai2];
                    var residueTypeBondIndex = r.residueType.getBondIndex(rai1, rai2); // TODO
                    // overwrite residueType bondOrder with value from existing bond
                    bondOrders[residueTypeBondIndex] = bp.bondOrder;
                }
                else {
                    a1.index = ai1;
                    a2.index = ai2;
                    // only add bond if not already in bondStore
                    bondStore.addBond(a1, a2, bondOrders[i]);
                }
            }
        }
        // get RNA/DNA rung pseudo bonds
        var traceAtomIndex = r.residueType.traceAtomIndex;
        var rungEndAtomIndex = r.residueType.rungEndAtomIndex;
        if (traceAtomIndex !== -1 && rungEndAtomIndex !== -1) {
            a1.index = r.traceAtomIndex;
            a2.index = r.rungEndAtomIndex;
            rungBondStore.addBond(a1, a2);
            rungAtomSet.set(a1.index);
            rungAtomSet.set(a2.index);
        }
    });
    structure.atomSetDict.rung = rungAtomSet;
    if (Debug)
        { Log.timeEnd('calculateBondsWithin'); }
}
function calculateBondsBetween(structure, onlyAddBackbone, useExistingBonds) {
    if ( onlyAddBackbone === void 0 ) onlyAddBackbone = false;
    if ( useExistingBonds === void 0 ) useExistingBonds = false;

    if (Debug)
        { Log.time('calculateBondsBetween'); }
    var bondStore = structure.bondStore;
    var backboneBondStore = structure.backboneBondStore;
    var backboneAtomSet = structure.getAtomSet(false);
    var ap1 = structure.getAtomProxy();
    var ap2 = structure.getAtomProxy();
    if (backboneBondStore.count === 0) {
        backboneBondStore.resize(structure.residueStore.count);
    }
    function addBondIfConnected(rp1, rp2) {
        var bbType1 = rp1.backboneType;
        var bbType2 = rp2.backboneType;
        if (bbType1 !== UnknownBackboneType && bbType1 === bbType2) {
            ap1.index = rp1.backboneEndAtomIndex;
            ap2.index = rp2.backboneStartAtomIndex;
            if ((useExistingBonds && ap1.hasBondTo(ap2)) || ap1.connectedTo(ap2)) {
                if (!onlyAddBackbone) {
                    bondStore.addBond(ap1, ap2, 1); // assume single bond
                }
                ap1.index = rp1.traceAtomIndex;
                ap2.index = rp2.traceAtomIndex;
                backboneBondStore.addBond(ap1, ap2);
                backboneAtomSet.set(ap1.index);
                backboneAtomSet.set(ap2.index);
            }
        }
    }
    structure.eachResidueN(2, addBondIfConnected);
    var rp1 = structure.getResidueProxy();
    var rp2 = structure.getResidueProxy();
    // check for cyclic chains
    structure.eachChain(function (cp) {
        if (cp.residueCount === 0)
            { return; }
        rp1.index = cp.residueOffset;
        rp2.index = cp.residueOffset + cp.residueCount - 1;
        addBondIfConnected(rp2, rp1);
    });
    structure.atomSetDict.backbone = backboneAtomSet;
    if (!onlyAddBackbone) {
        if (Debug)
            { Log.time('calculateBondsBetween inter'); }
        var spatialHash = structure.spatialHash;
        structure.eachResidue(function (rp) {
            if (rp.backboneType === UnknownBackboneType && !rp.isWater()) {
                rp.eachAtom(function (ap) {
                    if (ap.isMetal())
                        { return; }
                    spatialHash.eachWithin(ap.x, ap.y, ap.z, 4, function (idx) {
                        ap2.index = idx;
                        if (ap.modelIndex === ap2.modelIndex &&
                            ap.residueIndex !== ap2.residueIndex &&
                            !ap2.isMetal()) {
                            bondStore.addBondIfConnected(ap, ap2, 1); // assume single bond
                        }
                    });
                });
            }
        });
        if (Debug)
            { Log.timeEnd('calculateBondsBetween inter'); }
    }
    if (Debug)
        { Log.timeEnd('calculateBondsBetween'); }
}
function buildUnitcellAssembly(structure) {
    if (!structure.unitcell)
        { return; }
    if (Debug)
        { Log.time('buildUnitcellAssembly'); }
    var uc = structure.unitcell;
    var structureCenterFrac = structure.center.clone().applyMatrix4(uc.cartToFrac);
    var centerFrac = structureCenterFrac.clone().floor();
    var symopDict = getSymmetryOperations(uc.spacegroup);
    var centerFracSymop = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var positionFracSymop = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    function getMatrixList(shift) {
        var matrixList = [];
        Object.keys(symopDict).forEach(function (name) {
            var m = symopDict[name].clone();
            centerFracSymop.copy(structureCenterFrac).applyMatrix4(m).floor();
            positionFracSymop.setFromMatrixPosition(m);
            positionFracSymop.sub(centerFracSymop);
            positionFracSymop.add(centerFrac);
            if (shift)
                { positionFracSymop.add(shift); }
            m.setPosition(positionFracSymop);
            m.multiplyMatrices(uc.fracToCart, m);
            m.multiply(uc.cartToFrac);
            matrixList.push(m);
        });
        return matrixList;
    }
    var unitcellAssembly = new Assembly('UNITCELL');
    var unitcellMatrixList = getMatrixList();
    var ncsMatrixList = [];
    if (structure.biomolDict.NCS) {
        ncsMatrixList.push.apply(ncsMatrixList, [ new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]() ].concat( structure.biomolDict.NCS.partList[0].matrixList ));
        var ncsUnitcellMatrixList = [];
        unitcellMatrixList.forEach(function (sm) {
            ncsMatrixList.forEach(function (nm) {
                ncsUnitcellMatrixList.push(sm.clone().multiply(nm));
            });
        });
        unitcellAssembly.addPart(ncsUnitcellMatrixList);
    }
    else {
        unitcellAssembly.addPart(unitcellMatrixList);
    }
    var vec = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var supercellAssembly = new Assembly('SUPERCELL');
    var supercellMatrixList = Array.prototype.concat.call(getMatrixList(vec.set(1, 0, 0)), // 655
    getMatrixList(vec.set(0, 1, 0)), // 565
    getMatrixList(vec.set(0, 0, 1)), // 556
    getMatrixList(vec.set(-1, 0, 0)), // 455
    getMatrixList(vec.set(0, -1, 0)), // 545
    getMatrixList(vec.set(0, 0, -1)), // 554
    getMatrixList(vec.set(1, 1, 0)), // 665
    getMatrixList(vec.set(1, 0, 1)), // 656
    getMatrixList(vec.set(0, 1, 1)), // 566
    getMatrixList(vec.set(-1, -1, 0)), // 445
    getMatrixList(vec.set(-1, 0, -1)), // 454
    getMatrixList(vec.set(0, -1, -1)), // 544
    getMatrixList(vec.set(1, -1, -1)), // 644
    getMatrixList(vec.set(1, 1, -1)), // 664
    getMatrixList(vec.set(1, -1, 1)), // 646
    getMatrixList(vec.set(-1, 1, 1)), // 466
    getMatrixList(vec.set(-1, -1, 1)), // 446
    getMatrixList(vec.set(-1, 1, -1)), // 464
    getMatrixList(vec.set(0, 1, -1)), // 564
    getMatrixList(vec.set(0, -1, 1)), // 546
    getMatrixList(vec.set(1, 0, -1)), // 654
    getMatrixList(vec.set(-1, 0, 1)), // 456
    getMatrixList(vec.set(1, -1, 0)), // 645
    getMatrixList(vec.set(-1, 1, 0)), // 465
    getMatrixList(), // 555
    getMatrixList(vec.set(1, 1, 1)), // 666
    getMatrixList(vec.set(-1, -1, -1)) // 444
    );
    if (structure.biomolDict.NCS) {
        var ncsSupercellMatrixList = [];
        supercellMatrixList.forEach(function (sm) {
            ncsMatrixList.forEach(function (nm) {
                ncsSupercellMatrixList.push(sm.clone().multiply(nm));
            });
        });
        supercellAssembly.addPart(ncsSupercellMatrixList);
    }
    else {
        supercellAssembly.addPart(supercellMatrixList);
    }
    structure.biomolDict.UNITCELL = unitcellAssembly;
    structure.biomolDict.SUPERCELL = supercellAssembly;
    if (Debug)
        { Log.timeEnd('buildUnitcellAssembly'); }
}
var elm1 = ['H', 'C', 'O', 'N', 'S', 'P'];
var elm2 = ['NA', 'CL', 'FE'];
function guessElement(atomName) {
    var at = atomName.trim().toUpperCase();
    // parseInt('C') -> NaN; (NaN > -1) -> false
    if (parseInt(at.charAt(0)) > -1)
        { at = at.substr(1); }
    // parse again to check for a second integer
    if (parseInt(at.charAt(0)) > -1)
        { at = at.substr(1); }
    var n = at.length;
    if (n === 0)
        { return ''; }
    if (n === 1)
        { return at; }
    if (n === 2) {
        if (elm2.indexOf(at) !== -1)
            { return at; }
        if (elm1.indexOf(at[0]) !== -1)
            { return at[0]; }
    }
    if (n >= 3) {
        if (elm1.indexOf(at[0]) !== -1)
            { return at[0]; }
    }
    return '';
}
/**
 * Assigns ResidueType bonds.
 * @param {Structure} structure - the structure object
 * @return {undefined}
 */
function assignResidueTypeBonds(structure) {
    // if( Debug ) Log.time( "assignResidueTypeBonds" )
    var bondHash = structure.bondHash; // TODO
    var countArray = bondHash.countArray;
    var offsetArray = bondHash.offsetArray;
    var indexArray = bondHash.indexArray;
    var bp = structure.getBondProxy();
    structure.eachResidue(function (rp) {
        var residueType = rp.residueType;
        if (residueType.bonds !== undefined)
            { return; }
        var atomOffset = rp.atomOffset;
        var atomIndices1 = [];
        var atomIndices2 = [];
        var bondOrders = [];
        var bondDict = {};
        var nextAtomOffset = atomOffset + rp.atomCount;
        rp.eachAtom(function (ap) {
            var index = ap.index;
            var offset = offsetArray[index];
            var count = countArray[index];
            for (var i = 0, il = count; i < il; ++i) {
                bp.index = indexArray[offset + i];
                var idx1 = bp.atomIndex1;
                if (idx1 < atomOffset || idx1 >= nextAtomOffset) {
                    // Don't add bonds outside of this resiude
                    continue;
                }
                var idx2 = bp.atomIndex2;
                if (idx2 < atomOffset || idx2 >= nextAtomOffset) {
                    continue;
                }
                if (idx1 > idx2) {
                    var tmp = idx2;
                    idx2 = idx1;
                    idx1 = tmp;
                }
                var hash = idx1 + '|' + idx2;
                if (bondDict[hash] === undefined) {
                    bondDict[hash] = true;
                    atomIndices1.push(idx1 - atomOffset);
                    atomIndices2.push(idx2 - atomOffset);
                    bondOrders.push(bp.bondOrder);
                }
            }
        });
        residueType.bonds = {
            atomIndices1: atomIndices1,
            atomIndices2: atomIndices2,
            bondOrders: bondOrders
        };
    });
    // if( Debug ) Log.timeEnd( "assignResidueTypeBonds" )
}
function concatStructures(name) {
    var structures = [], len = arguments.length - 1;
    while ( len-- > 0 ) structures[ len ] = arguments[ len + 1 ];

    if (Debug)
        { Log.time("concatStructures"); }
    var s = new Structure(name, '');
    var sb = new StructureBuilder(s);
    var atomStore = s.atomStore;
    var atomMap = s.atomMap;
    atomStore.addField('formalCharge', 1, 'int8');
    atomStore.addField('partialCharge', 1, 'float32');
    var atomIndexDict = {};
    var idx = 0;
    var atomCount = 0;
    var modelCount = 0;
    structures.forEach(function (structure) {
        structure.eachAtom(function (a) {
            atomStore.growIfFull();
            atomStore.atomTypeId[idx] = atomMap.add(a.atomname, a.element);
            atomStore.x[idx] = a.x;
            atomStore.y[idx] = a.y;
            atomStore.z[idx] = a.z;
            atomStore.serial[idx] = a.serial;
            atomStore.formalCharge[idx] = a.formalCharge;
            atomStore.partialCharge[idx] = a.partialCharge;
            atomStore.altloc[idx] = a.altloc;
            atomStore.occupancy[idx] = a.occupancy;
            atomStore.bfactor[idx] = a.bfactor;
            sb.addAtom(a.modelIndex + modelCount, a.chainname, a.chainid, a.resname, a.resno, a.hetero === 1, a.sstruc, a.inscode);
            atomIndexDict[a.index + atomCount] = idx;
            idx += 1;
        });
        atomCount += structure.atomStore.count;
        modelCount += structure.modelStore.count;
    });
    var bondStore = s.bondStore;
    var a1 = s.getAtomProxy();
    var a2 = s.getAtomProxy();
    atomCount = 0;
    structures.forEach(function (structure) {
        structure.eachBond(function (b) {
            a1.index = atomIndexDict[b.atomIndex1 + atomCount];
            a2.index = atomIndexDict[b.atomIndex2 + atomCount];
            bondStore.addBond(a1, a2, b.bondOrder);
        });
        atomCount += structure.atomStore.count;
    });
    sb.finalize();
    calculateBondsBetween(s, true); // calculate backbone bonds
    calculateBondsWithin(s, true); // calculate rung bonds
    s.finalizeAtoms();
    s.finalizeBonds();
    assignResidueTypeBonds(s);
    if (Debug)
        { Log.timeEnd("concatStructures"); }
    return s;
}

/**
 * @file Atom Type
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// Li, Na, K, Rb, Cs Fr
var AlkaliMetals = [3, 11, 19, 37, 55, 87];
// Be, Mg, Ca, Sr, Ba, Ra
var AlkalineEarthMetals = [4, 12, 20, 38, 56, 88];
// C, P, S, Se
var PolyatomicNonmetals = [6, 15, 16, 34 ];
// H, N, O, F, Cl, Br, I
var DiatomicNonmetals = [1, 7, 8, 9, 17, 35, 53];
// He, Ne, Ar, Kr, Xe, Rn
var NobleGases = [2, 10, 18, 36, 54, 86];
// Zn, Ga, Cd, In, Sn, Hg, Ti, Pb, Bi, Po, Cn
var PostTransitionMetals = [13, 30, 31, 48, 49, 50, 80, 81, 82, 83, 84, 85, 112];
// B, Si, Ge, As, Sb, Te, At
var Metalloids = [5, 14, 32, 33, 51, 52, 85];
// F, Cl, Br, I, At
var Halogens = [9, 17, 35, 53, 85];
/**
 * Atom type
 */
var AtomType = function AtomType(structure, atomname, element) {
    this.structure = structure;
    this.atomname = atomname;
    element = element || guessElement(atomname);
    this.element = element;
    this.number = AtomicNumbers[element] || DefaultAtomicNumber;
    this.vdw = VdwRadii[this.number] || DefaultVdwRadius;
    this.covalent = CovalentRadii[this.number] || DefaultCovalentRadius;
};
AtomType.prototype.getDefaultValence = function getDefaultValence () {
    var vl = Valences[this.number];
    return vl ? vl[0] : DefaultValence;
};
AtomType.prototype.getValenceList = function getValenceList () {
    return Valences[this.number] || [];
};
AtomType.prototype.getOuterShellElectronCount = function getOuterShellElectronCount () {
    return OuterShellElectronCounts[this.number] || DefaultOuterShellElectronCount;
};
AtomType.prototype.isMetal = function isMetal () {
    return (this.isAlkaliMetal() ||
        this.isAlkalineEarthMetal() ||
        this.isLanthanide() ||
        this.isActinide() ||
        this.isTransitionMetal() ||
        this.isPostTransitionMetal());
};
AtomType.prototype.isNonmetal = function isNonmetal () {
    return (this.isDiatomicNonmetal() ||
        this.isPolyatomicNonmetal() ||
        this.isNobleGas());
};
AtomType.prototype.isMetalloid = function isMetalloid () {
    return Metalloids.includes(this.number);
};
AtomType.prototype.isHalogen = function isHalogen () {
    return Halogens.includes(this.number);
};
AtomType.prototype.isDiatomicNonmetal = function isDiatomicNonmetal () {
    return DiatomicNonmetals.includes(this.number);
};
AtomType.prototype.isPolyatomicNonmetal = function isPolyatomicNonmetal () {
    return PolyatomicNonmetals.includes(this.number);
};
AtomType.prototype.isAlkaliMetal = function isAlkaliMetal () {
    return AlkaliMetals.includes(this.number);
};
AtomType.prototype.isAlkalineEarthMetal = function isAlkalineEarthMetal () {
    return AlkalineEarthMetals.includes(this.number);
};
AtomType.prototype.isNobleGas = function isNobleGas () {
    return NobleGases.includes(this.number);
};
AtomType.prototype.isTransitionMetal = function isTransitionMetal () {
    var no = this.number;
    return ((no >= 21 && no <= 29) ||
        (no >= 39 && no <= 47) ||
        (no >= 72 && no <= 79) ||
        (no >= 104 && no <= 108));
};
AtomType.prototype.isPostTransitionMetal = function isPostTransitionMetal () {
    return PostTransitionMetals.includes(this.number);
};
AtomType.prototype.isLanthanide = function isLanthanide () {
    return this.number >= 57 && this.number <= 71;
};
AtomType.prototype.isActinide = function isActinide () {
    return this.number >= 89 && this.number <= 103;
};

/**
 * @file Atom Map
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getHash(atomname, element) {
    return atomname + '|' + element;
}
var AtomMap = function AtomMap(structure) {
    this.structure = structure;
    this.dict = {};
    this.list = [];
    this.structure = structure;
};
AtomMap.prototype.add = function add (atomname, element) {
    atomname = atomname.toUpperCase();
    if (!element) {
        element = guessElement(atomname);
    }
    else {
        element = element.toUpperCase();
    }
    var hash = getHash(atomname, element);
    var id = this.dict[hash];
    if (id === undefined) {
        var atomType = new AtomType(this.structure, atomname, element);
        id = this.list.length;
        this.dict[hash] = id;
        this.list.push(atomType);
    }
    return id;
};
AtomMap.prototype.get = function get (id) {
    return this.list[id];
};

/**
 * @file Residue Type
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow
 * @private
 */
/**
 * Residue type
 */
var ResidueType = function ResidueType(structure, resname, atomTypeIdList, hetero, chemCompType, bonds) {
    this.structure = structure;
    // Sparse array containing the reference atom index for each bond.
    this.bondReferenceAtomIndices = [];
    this.resname = resname;
    this.atomTypeIdList = atomTypeIdList;
    this.hetero = hetero ? 1 : 0;
    this.chemCompType = chemCompType;
    this.bonds = bonds;
    this.atomCount = atomTypeIdList.length;
    this.moleculeType = this.getMoleculeType();
    this.backboneType = this.getBackboneType(0);
    this.backboneEndType = this.getBackboneType(-1);
    this.backboneStartType = this.getBackboneType(1);
    this.backboneIndexList = this.getBackboneIndexList();
    var atomnames = ResidueTypeAtoms[this.backboneType];
    var atomnamesStart = ResidueTypeAtoms[this.backboneStartType];
    var atomnamesEnd = ResidueTypeAtoms[this.backboneEndType];
    var traceIndex = this.getAtomIndexByName(atomnames.trace);
    this.traceAtomIndex = defaults(traceIndex, -1);
    var dir1Index = this.getAtomIndexByName(atomnames.direction1);
    this.direction1AtomIndex = defaults(dir1Index, -1);
    var dir2Index = this.getAtomIndexByName(atomnames.direction2);
    this.direction2AtomIndex = defaults(dir2Index, -1);
    var bbStartIndex = this.getAtomIndexByName(atomnamesStart.backboneStart);
    this.backboneStartAtomIndex = defaults(bbStartIndex, -1);
    var bbEndIndex = this.getAtomIndexByName(atomnamesEnd.backboneEnd);
    this.backboneEndAtomIndex = defaults(bbEndIndex, -1);
    var rungEndIndex;
    if (PurinBases.includes(resname)) {
        rungEndIndex = this.getAtomIndexByName('N1');
    }
    else {
        rungEndIndex = this.getAtomIndexByName('N3');
    }
    this.rungEndAtomIndex = defaults(rungEndIndex, -1);
};
ResidueType.prototype.getBackboneIndexList = function getBackboneIndexList () {
    var backboneIndexList = [];
    var atomnameList;
    switch (this.moleculeType) {
        case ProteinType:
            atomnameList = ProteinBackboneAtoms;
            break;
        case RnaType:
        case DnaType:
            atomnameList = NucleicBackboneAtoms;
            break;
        default:
            return backboneIndexList;
    }
    var atomMap = this.structure.atomMap;
    var atomTypeIdList = this.atomTypeIdList;
    for (var i = 0, il = this.atomCount; i < il; ++i) {
        var atomType = atomMap.get(atomTypeIdList[i]);
        if (atomnameList.includes(atomType.atomname)) {
            backboneIndexList.push(i);
        }
    }
    return backboneIndexList;
};
ResidueType.prototype.getMoleculeType = function getMoleculeType () {
    if (this.isProtein()) {
        return ProteinType;
    }
    else if (this.isRna()) {
        return RnaType;
    }
    else if (this.isDna()) {
        return DnaType;
    }
    else if (this.isWater()) {
        return WaterType;
    }
    else if (this.isIon()) {
        return IonType;
    }
    else if (this.isSaccharide()) {
        return SaccharideType;
    }
    else {
        return UnknownType;
    }
};
ResidueType.prototype.getBackboneType = function getBackboneType (position) {
    if (this.hasProteinBackbone(position)) {
        return ProteinBackboneType;
    }
    else if (this.hasRnaBackbone(position)) {
        return RnaBackboneType;
    }
    else if (this.hasDnaBackbone(position)) {
        return DnaBackboneType;
    }
    else if (this.hasCgProteinBackbone(position)) {
        return CgProteinBackboneType;
    }
    else if (this.hasCgRnaBackbone(position)) {
        return CgRnaBackboneType;
    }
    else if (this.hasCgDnaBackbone(position)) {
        return CgDnaBackboneType;
    }
    else {
        return UnknownBackboneType;
    }
};
ResidueType.prototype.isProtein = function isProtein () {
    if (this.chemCompType) {
        return ChemCompProtein.includes(this.chemCompType);
    }
    else {
        return (this.hasAtomWithName('CA', 'C', 'N') ||
            AA3.includes(this.resname));
    }
};
ResidueType.prototype.isCg = function isCg () {
    var backboneType = this.backboneType;
    return (backboneType === CgProteinBackboneType ||
        backboneType === CgRnaBackboneType ||
        backboneType === CgDnaBackboneType);
};
ResidueType.prototype.isNucleic = function isNucleic () {
    return this.isRna() || this.isDna();
};
ResidueType.prototype.isRna = function isRna () {
    if (this.chemCompType) {
        return ChemCompRna.includes(this.chemCompType);
    }
    else if (this.hetero === 1) {
        return false;
    }
    else {
        return (this.hasAtomWithName(['P', "O3'", 'O3*'], ["C4'", 'C4*'], ["O2'", 'O2*', "F2'", 'F2*']) ||
            (RnaBases.includes(this.resname) &&
                (this.hasAtomWithName(["O2'", 'O2*', "F2'", 'F2*']))));
    }
};
ResidueType.prototype.isDna = function isDna () {
    if (this.chemCompType) {
        return ChemCompDna.includes(this.chemCompType);
    }
    else if (this.hetero === 1) {
        return false;
    }
    else {
        return ((this.hasAtomWithName(['P', "O3'", 'O3*'], ["C3'", 'C3*']) &&
            !this.hasAtomWithName(["O2'", 'O2*', "F2'", 'F2*'])) ||
            DnaBases.includes(this.resname));
    }
};
ResidueType.prototype.isHetero = function isHetero () {
    return this.hetero === 1;
};
ResidueType.prototype.isIon = function isIon () {
    return IonNames.includes(this.resname);
};
ResidueType.prototype.isWater = function isWater () {
    return WaterNames.includes(this.resname);
};
ResidueType.prototype.isSaccharide = function isSaccharide () {
    if (this.chemCompType) {
        return ChemCompSaccharide.includes(this.chemCompType);
    }
    else {
        return SaccharideNames.includes(this.resname);
    }
};
ResidueType.prototype.isStandardAminoacid = function isStandardAminoacid () {
    return AA3.includes(this.resname);
};
ResidueType.prototype.isStandardBase = function isStandardBase () {
    return Bases.includes(this.resname);
};
ResidueType.prototype.hasBackboneAtoms = function hasBackboneAtoms (position, type) {
    var atomnames = ResidueTypeAtoms[type];
    if (position === -1) {
        return this.hasAtomWithName(atomnames.trace, atomnames.backboneEnd, atomnames.direction1, atomnames.direction2);
    }
    else if (position === 0) {
        return this.hasAtomWithName(atomnames.trace, atomnames.direction1, atomnames.direction2);
    }
    else if (position === 1) {
        return this.hasAtomWithName(atomnames.trace, atomnames.backboneStart, atomnames.direction1, atomnames.direction2);
    }
    else {
        return this.hasAtomWithName(atomnames.trace, atomnames.backboneStart, atomnames.backboneEnd, atomnames.direction1, atomnames.direction2);
    }
};
ResidueType.prototype.hasProteinBackbone = function hasProteinBackbone (position) {
    return (this.isProtein() &&
        this.hasBackboneAtoms(position, ProteinBackboneType));
};
ResidueType.prototype.hasRnaBackbone = function hasRnaBackbone (position) {
    return (this.isRna() &&
        this.hasBackboneAtoms(position, RnaBackboneType));
};
ResidueType.prototype.hasDnaBackbone = function hasDnaBackbone (position) {
    return (this.isDna() &&
        this.hasBackboneAtoms(position, DnaBackboneType));
};
ResidueType.prototype.hasCgProteinBackbone = function hasCgProteinBackbone (position) {
    return (this.atomCount < 7 &&
        this.isProtein() &&
        this.hasBackboneAtoms(position, CgProteinBackboneType));
};
ResidueType.prototype.hasCgRnaBackbone = function hasCgRnaBackbone (position) {
    return (this.atomCount < 11 &&
        this.isRna() &&
        this.hasBackboneAtoms(position, CgRnaBackboneType));
};
ResidueType.prototype.hasCgDnaBackbone = function hasCgDnaBackbone (position) {
    return (this.atomCount < 11 &&
        this.isDna() &&
        this.hasBackboneAtoms(position, CgDnaBackboneType));
};
ResidueType.prototype.hasBackbone = function hasBackbone (position) {
    return (this.hasProteinBackbone(position) ||
        this.hasRnaBackbone(position) ||
        this.hasDnaBackbone(position) ||
        this.hasCgProteinBackbone(position) ||
        this.hasCgRnaBackbone(position) ||
        this.hasCgDnaBackbone(position));
};
ResidueType.prototype.getAtomIndexByName = function getAtomIndexByName (atomname) {
    var n = this.atomCount;
    var atomMap = this.structure.atomMap;
    var atomTypeIdList = this.atomTypeIdList;
    if (Array.isArray(atomname)) {
        for (var i = 0; i < n; ++i) {
            var index = atomTypeIdList[i];
            if (atomname.includes(atomMap.get(index).atomname)) {
                return i;
            }
        }
    }
    else {
        for (var i$1 = 0; i$1 < n; ++i$1) {
            var index$1 = atomTypeIdList[i$1];
            if (atomname === atomMap.get(index$1).atomname) {
                return i$1;
            }
        }
    }
    return undefined;
};
ResidueType.prototype.hasAtomWithName = function hasAtomWithName () {
        var atomnames = [], len = arguments.length;
        while ( len-- ) atomnames[ len ] = arguments[ len ];

    var n = atomnames.length;
    for (var i = 0; i < n; ++i) {
        if (atomnames[i] === undefined)
            { continue; }
        if (this.getAtomIndexByName(atomnames[i]) === undefined) {
            return false;
        }
    }
    return true;
};
ResidueType.prototype.getBonds = function getBonds (r) {
    if (this.bonds === undefined) {
        this.bonds = calculateResidueBonds(r); // TODO
    }
    return this.bonds;
};
ResidueType.prototype.getRings = function getRings () {
    if (this.rings === undefined) {
        this.calculateRings();
    }
    return this.rings;
};
ResidueType.prototype.getBondGraph = function getBondGraph () {
    if (this.bondGraph === undefined) {
        this.calculateBondGraph();
    }
    return this.bondGraph;
};
ResidueType.prototype.getAromatic = function getAromatic (a) {
    if (this.aromaticAtoms === undefined) {
        this.calculateAromatic(this.structure.getResidueProxy((a).residueIndex)); // TODO
    }
    return this.aromaticAtoms;
};
ResidueType.prototype.getAromaticRings = function getAromaticRings (r) {
    if (this.aromaticRings === undefined) {
        this.calculateAromatic(r); // TODO
    }
    return this.aromaticRings;
};
/**
 * @return {Object} bondGraph - represents the bonding in this
 *   residue: { ai1: [ ai2, ai3, ...], ...}
 */
ResidueType.prototype.calculateBondGraph = function calculateBondGraph () {
    var bondGraph = this.bondGraph = {};
    var bonds = this.getBonds();
    var nb = bonds.atomIndices1.length;
    var atomIndices1 = bonds.atomIndices1;
    var atomIndices2 = bonds.atomIndices2;
    for (var i = 0; i < nb; ++i) {
        var ai1 = atomIndices1[i];
        var ai2 = atomIndices2[i];
        var a1 = bondGraph[ai1] = bondGraph[ai1] || [];
        a1.push(ai2);
        var a2 = bondGraph[ai2] = bondGraph[ai2] || [];
        a2.push(ai1);
    }
};
/**
 * Find all rings up to 2 * RingFinderMaxDepth
 */
ResidueType.prototype.calculateRings = function calculateRings () {
    var bondGraph = this.getBondGraph(); // TODO
    var state = RingFinderState(bondGraph, this.atomCount);
    for (var i = 0; i < state.count; i++) {
        if (state.visited[i] >= 0)
            { continue; }
        findRings(state, i);
    }
    this.rings = { atomRings: state.atomRings, rings: state.rings };
};
ResidueType.prototype.isAromatic = function isAromatic (atom) {
    this.aromaticAtoms = this.getAromatic(atom); // TODO
    return this.aromaticAtoms[atom.index - atom.residueAtomOffset] === 1;
};
ResidueType.prototype.calculateAromatic = function calculateAromatic (r) {
        var this$1 = this;

    var aromaticAtoms = this.aromaticAtoms = new Uint8Array(this.atomCount);
    var rings = this.getRings().rings;
    var aromaticRingFlags = rings.map(function (ring) {
        return isRingAromatic(ring.map(function (idx) {
            return this$1.structure.getAtomProxy(idx + r.atomOffset);
        }));
    });
    var aromaticRings = this.aromaticRings = [];
    rings.forEach(function (ring, i) {
        if (aromaticRingFlags[i]) {
            aromaticRings.push(ring);
            ring.forEach(function (idx) { return aromaticAtoms[idx] = 1; });
        }
    });
};
/**
 * For bonds with order > 1, pick a reference atom
 * @return {undefined}
 */
ResidueType.prototype.assignBondReferenceAtomIndices = function assignBondReferenceAtomIndices () {
    var bondGraph = this.getBondGraph(); // TODO
    var rings = this.getRings(); // TODO
    var atomRings = rings.atomRings;
    var ringData = rings.rings;
    var bonds = this.bonds; // TODO
    var atomIndices1 = bonds.atomIndices1;
    var atomIndices2 = bonds.atomIndices2;
    var bondOrders = bonds.bondOrders;
    var bondReferenceAtomIndices = this.bondReferenceAtomIndices;
    var nb = bonds.atomIndices1.length;
    bondReferenceAtomIndices.length = 0; // reset array
    for (var i = 0; i < nb; ++i) {
        // Not required for single bonds
        if (bondOrders[i] <= 1)
            { continue; }
        var refRing = (void 0);
        var ai1 = atomIndices1[i];
        var ai2 = atomIndices2[i];
        var rings1 = atomRings[ai1];
        var rings2 = atomRings[ai2];
        // Are both atoms in a ring?
        if (rings1 && rings2) {
            // Are they in the same ring? (If not, ignore ring info)
            for (var ri1 = 0; ri1 < rings1.length; ri1++) {
                if (rings2.indexOf(rings1[ri1]) !== -1) {
                    refRing = ringData[rings1[ri1]];
                    break;
                }
            }
        }
        // Find the first neighbour.
        if (bondGraph[ai1].length > 1) {
            for (var j = 0; j < bondGraph[ai1].length; ++j) {
                var ai3 = bondGraph[ai1][j];
                if (ai3 !== ai2) {
                    if (refRing === undefined || refRing.indexOf(ai3) !== -1) {
                        bondReferenceAtomIndices[i] = ai3;
                        break;
                    }
                }
            }
        }
        else if (bondGraph[ai2].length > 1) {
            for (var j$1 = 0; j$1 < bondGraph[ai2].length; ++j$1) {
                var ai3$1 = bondGraph[ai2][j$1];
                if (ai3$1 !== ai1) {
                    if (refRing === undefined || refRing.indexOf(ai3$1) !== -1) {
                        bondReferenceAtomIndices[i] = ai3$1;
                        break;
                    }
                }
            }
        } // No reference atom could be found (e.g. diatomic molecule/fragment)
    }
};
ResidueType.prototype.getBondIndex = function getBondIndex (atomIndex1, atomIndex2) {
    var bonds = this.bonds; // TODO
    var atomIndices1 = bonds.atomIndices1;
    var atomIndices2 = bonds.atomIndices2;
    var idx1 = atomIndices1.indexOf(atomIndex1);
    var idx2 = atomIndices2.indexOf(atomIndex2);
    var _idx2 = idx2;
    while (idx1 !== -1) {
        while (idx2 !== -1) {
            if (idx1 === idx2)
                { return idx1; }
            idx2 = atomIndices2.indexOf(atomIndex2, idx2 + 1);
        }
        idx1 = atomIndices1.indexOf(atomIndex1, idx1 + 1);
        idx2 = _idx2;
    }
    // returns undefined when no bond is found
};
ResidueType.prototype.getBondReferenceAtomIndex = function getBondReferenceAtomIndex (atomIndex1, atomIndex2) {
    var bondIndex = this.getBondIndex(atomIndex1, atomIndex2);
    if (bondIndex === undefined)
        { return undefined; }
    if (this.bondReferenceAtomIndices.length === 0) {
        this.assignBondReferenceAtomIndices();
    }
    return this.bondReferenceAtomIndices[bondIndex];
};
//
var AromaticRingElements = [
    5 /* B */, 6 /* C */, 7 /* N */, 8 /* O */,
    14 /* SI */, 15 /* P */, 16 /* S */,
    32 /* GE */, 33 /* AS */,
    50 /* SN */, 51 /* SB */,
    83 /* BI */
];
var AromaticRingPlanarityThreshold = 0.05;
function isRingAromatic(ring) {
    if (ring.some(function (a) { return !AromaticRingElements.includes(a.number); }))
        { return false; }
    var i = 0;
    var coords = new Matrix(3, ring.length);
    var cd = coords.data;
    ring.forEach(function (a) {
        cd[i + 0] = a.x;
        cd[i + 1] = a.y;
        cd[i + 2] = a.z;
        i += 3;
    });
    var pa = new PrincipalAxes(coords);
    return pa.vecC.length() < AromaticRingPlanarityThreshold;
}
//
/**
 * Ring finding code below adapted from MolQL
 * Copyright (c) 2017 MolQL contributors, licensed under MIT
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function addRing(state, a, b) {
    // only "monotonous" rings
    if (b < a)
        { return; }
    var pred = state.pred;
    var color = state.color;
    var left = state.left;
    var right = state.right;
    var nc = ++state.currentColor;
    var current = a;
    for (var t = 0; t < RingFinderMaxDepth; t++) {
        color[current] = nc;
        current = pred[current];
        if (current < 0)
            { break; }
    }
    var leftOffset = 0;
    var rightOffset = 0;
    var found = false;
    var target = 0;
    current = b;
    for (var t$1 = 0; t$1 < RingFinderMaxDepth; t$1++) {
        if (color[current] === nc) {
            target = current;
            found = true;
            break;
        }
        right[rightOffset++] = current;
        current = pred[current];
        if (current < 0)
            { break; }
    }
    if (!found)
        { return; }
    current = a;
    for (var t$2 = 0; t$2 < RingFinderMaxDepth; t$2++) {
        left[leftOffset++] = current;
        if (target === current)
            { break; }
        current = pred[current];
        if (current < 0)
            { break; }
    }
    var rn = leftOffset + rightOffset;
    var ring = new Array(rn);
    var ringOffset = 0;
    for (var t$3 = 0; t$3 < leftOffset; t$3++) {
        ring[ringOffset++] = left[t$3];
    }
    for (var t$4 = rightOffset - 1; t$4 >= 0; t$4--) {
        ring[ringOffset++] = right[t$4];
    }
    var ri = state.rings.length;
    // set atomRing indices:
    for (var i = 0; i < rn; ++i) {
        var ai = ring[i];
        if (state.atomRings[ai]) {
            state.atomRings[ai].push(ri);
        }
        else {
            state.atomRings[ai] = [ri];
        }
    }
    state.rings.push(ring);
}
function findRings(state, from) {
    var bonds = state.bonds;
    var visited = state.visited;
    var queue = state.queue;
    var pred = state.pred;
    visited[from] = 1;
    queue[0] = from;
    var head = 0;
    var size = 1;
    while (head < size) {
        var top = queue[head++];
        var start = 0;
        if (bonds[top] === undefined) {
            continue;
        }
        var end = bonds[top].length;
        for (var i = start; i < end; i++) {
            var other = bonds[top][i];
            if (visited[other] > 0) {
                if (pred[other] !== top && pred[top] !== other) {
                    addRing(state, top, other);
                }
                continue;
            }
            visited[other] = 1;
            queue[size++] = other;
            pred[other] = top;
        }
    }
}
var RingFinderMaxDepth = 4;
function RingFinderState(bonds, capacity) {
    var state = {
        count: capacity,
        visited: new Int32Array(capacity),
        queue: new Int32Array(capacity),
        pred: new Int32Array(capacity),
        left: new Int32Array(RingFinderMaxDepth),
        right: new Int32Array(RingFinderMaxDepth),
        color: new Int32Array(capacity),
        currentColor: 0,
        rings: [],
        atomRings: [],
        bonds: bonds
    };
    for (var i = 0; i < capacity; i++) {
        state.visited[i] = -1;
        state.pred[i] = -1;
    }
    return state;
}

/**
 * @file Residue Map
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getHash$1(resname, atomTypeIdList, hetero, chemCompType) {
    if ( chemCompType === void 0 ) chemCompType = '';

    return (resname + '|' +
        atomTypeIdList.join(',') + '|' +
        (hetero ? 1 : 0) + '|' +
        chemCompType);
}
var ResidueMap = function ResidueMap(structure) {
    this.structure = structure;
    this.dict = {};
    this.list = [];
};
ResidueMap.prototype.add = function add (resname, atomTypeIdList, hetero, chemCompType, bonds) {
        if ( chemCompType === void 0 ) chemCompType = '';

    resname = resname.toUpperCase();
    var hash = getHash$1(resname, atomTypeIdList, hetero, chemCompType);
    var id = this.dict[hash];
    if (id === undefined) {
        var residueType = new ResidueType(this.structure, resname, atomTypeIdList, hetero, chemCompType, bonds);
        id = this.list.length;
        this.dict[hash] = id;
        this.list.push(residueType);
    }
    return id;
};
ResidueMap.prototype.get = function get (id) {
    return this.list[id];
};

/**
 * @file Bond Proxy
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Bond proxy
 */
var BondProxy = function BondProxy(structure, index) {
    if ( index === void 0 ) index = 0;

    this.structure = structure;
    this.index = index;
    this.bondStore = structure.bondStore;
    this._v12 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this._v13 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this._ap1 = this.structure.getAtomProxy();
    this._ap2 = this.structure.getAtomProxy();
    this._ap3 = this.structure.getAtomProxy();
};

var prototypeAccessors$i = { atom1: { configurable: true },atom2: { configurable: true },atomIndex1: { configurable: true },atomIndex2: { configurable: true },bondOrder: { configurable: true } };
/**
 * @type {AtomProxy}
 */
prototypeAccessors$i.atom1.get = function () {
    return this.structure.getAtomProxy(this.atomIndex1);
};
/**
 * @type {AtomProxy}
 */
prototypeAccessors$i.atom2.get = function () {
    return this.structure.getAtomProxy(this.atomIndex2);
};
/**
 * @type {Integer}
 */
prototypeAccessors$i.atomIndex1.get = function () {
    return this.bondStore.atomIndex1[this.index];
};
prototypeAccessors$i.atomIndex1.set = function (value) {
    this.bondStore.atomIndex1[this.index] = value;
};
/**
 * @type {Integer}
 */
prototypeAccessors$i.atomIndex2.get = function () {
    return this.bondStore.atomIndex2[this.index];
};
prototypeAccessors$i.atomIndex2.set = function (value) {
    this.bondStore.atomIndex2[this.index] = value;
};
/**
 * @type {Integer}
 */
prototypeAccessors$i.bondOrder.get = function () {
    return this.bondStore.bondOrder[this.index];
};
prototypeAccessors$i.bondOrder.set = function (value) {
    this.bondStore.bondOrder[this.index] = value;
};
BondProxy.prototype.getOtherAtomIndex = function getOtherAtomIndex (atomIndex) {
    return atomIndex === this.atomIndex1 ? this.atomIndex2 : this.atomIndex1;
};
BondProxy.prototype.getOtherAtom = function getOtherAtom (atom) {
    return this.structure.getAtomProxy(this.getOtherAtomIndex(atom.index));
};
/**
 * Get reference atom index for the bond
 * @return {Integer|undefined} atom index, or `undefined` if unavailable
 */
BondProxy.prototype.getReferenceAtomIndex = function getReferenceAtomIndex () {
    var ap1 = this._ap1;
    var ap2 = this._ap2;
    ap1.index = this.atomIndex1;
    ap2.index = this.atomIndex2;
    if (ap1.residueIndex !== ap2.residueIndex) {
        return undefined; // Bond between residues, for now ignore (could detect)
    }
    var typeAtomIndex1 = ap1.index - ap1.residueAtomOffset;
    var typeAtomIndex2 = ap2.index - ap2.residueAtomOffset;
    var residueType = ap1.residueType;
    var ix = residueType.getBondReferenceAtomIndex(typeAtomIndex1, typeAtomIndex2);
    if (ix !== undefined) {
        return ix + ap1.residueAtomOffset;
    }
    else {
        console.warn('No reference atom found', ap1.index, ap2.index);
    }
};
/**
 * calculate shift direction for displaying double/triple bonds
 * @param  {Vector3} [v] pre-allocated output vector
 * @return {Vector3} the shift direction vector
 */
BondProxy.prototype.calculateShiftDir = function calculateShiftDir (v) {
        if ( v === void 0 ) v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();

    var ap1 = this._ap1;
    var ap2 = this._ap2;
    var ap3 = this._ap3;
    var v12 = this._v12;
    var v13 = this._v13;
    ap1.index = this.atomIndex1;
    ap2.index = this.atomIndex2;
    var ai3 = this.getReferenceAtomIndex();
    v12.subVectors(ap1, ap2).normalize(); // TODO
    if (ai3 !== undefined) {
        ap3.index = ai3;
        v13.subVectors(ap1, ap3); // TODO
    }
    else {
        v13.copy(ap1); // no reference point, use origin  // TODO
    }
    v13.normalize();
    // make sure v13 and v12 are not colinear
    var dp = v12.dot(v13);
    if (1 - Math.abs(dp) < 1e-5) {
        v13.set(1, 0, 0);
        dp = v12.dot(v13);
        if (1 - Math.abs(dp) < 1e-5) {
            v13.set(0, 1, 0);
            dp = v12.dot(v13);
        }
    }
    return v.copy(v13.sub(v12.multiplyScalar(dp))).normalize();
};
BondProxy.prototype.qualifiedName = function qualifiedName () {
    return this.atomIndex1 + '=' + this.atomIndex2;
};
/**
 * Clone object
 * @return {BondProxy} cloned bond
 */
BondProxy.prototype.clone = function clone () {
    return new BondProxy(this.structure, this.index);
};
BondProxy.prototype.toObject = function toObject () {
    return {
        atomIndex1: this.atomIndex1,
        atomIndex2: this.atomIndex2,
        bondOrder: this.bondOrder
    };
};

Object.defineProperties( BondProxy.prototype, prototypeAccessors$i );

/**
 * @file Residue Proxy
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Residue proxy
 */
var ResidueProxy = function ResidueProxy(structure, index) {
    if ( index === void 0 ) index = 0;

    this.structure = structure;
    this.index = index;
    this.chainStore = structure.chainStore;
    this.residueStore = structure.residueStore;
    this.atomStore = structure.atomStore;
    this.residueMap = structure.residueMap;
    this.atomMap = structure.atomMap;
};

var prototypeAccessors$j = { entity: { configurable: true },entityIndex: { configurable: true },chain: { configurable: true },chainIndex: { configurable: true },atomOffset: { configurable: true },atomCount: { configurable: true },atomEnd: { configurable: true },modelIndex: { configurable: true },chainname: { configurable: true },chainid: { configurable: true },resno: { configurable: true },sstruc: { configurable: true },inscode: { configurable: true },residueType: { configurable: true },resname: { configurable: true },hetero: { configurable: true },moleculeType: { configurable: true },backboneType: { configurable: true },backboneStartType: { configurable: true },backboneEndType: { configurable: true },traceAtomIndex: { configurable: true },direction1AtomIndex: { configurable: true },direction2AtomIndex: { configurable: true },backboneStartAtomIndex: { configurable: true },backboneEndAtomIndex: { configurable: true },rungEndAtomIndex: { configurable: true },x: { configurable: true },y: { configurable: true },z: { configurable: true } };
/**
 * Entity
 * @type {Entity}
 */
prototypeAccessors$j.entity.get = function () {
    return this.structure.entityList[this.entityIndex];
};
prototypeAccessors$j.entityIndex.get = function () {
    return this.chainStore.entityIndex[this.chainIndex];
};
/**
 * Chain
 * @type {ChainProxy}
 */
prototypeAccessors$j.chain.get = function () {
    return this.structure.getChainProxy(this.chainIndex);
};
prototypeAccessors$j.chainIndex.get = function () {
    return this.residueStore.chainIndex[this.index];
};
prototypeAccessors$j.chainIndex.set = function (value) {
    this.residueStore.chainIndex[this.index] = value;
};
prototypeAccessors$j.atomOffset.get = function () {
    return this.residueStore.atomOffset[this.index];
};
prototypeAccessors$j.atomOffset.set = function (value) {
    this.residueStore.atomOffset[this.index] = value;
};
/**
 * Atom count
 * @type {Integer}
 */
prototypeAccessors$j.atomCount.get = function () {
    return this.residueStore.atomCount[this.index];
};
prototypeAccessors$j.atomCount.set = function (value) {
    this.residueStore.atomCount[this.index] = value;
};
prototypeAccessors$j.atomEnd.get = function () {
    return this.atomOffset + this.atomCount - 1;
};
//
prototypeAccessors$j.modelIndex.get = function () {
    return this.chainStore.modelIndex[this.chainIndex];
};
/**
 * Chain name
 * @type {String}
 */
prototypeAccessors$j.chainname.get = function () {
    return this.chainStore.getChainname(this.chainIndex);
};
/**
 * Chain id
 * @type {String}
 */
prototypeAccessors$j.chainid.get = function () {
    return this.chainStore.getChainid(this.chainIndex);
};
//
/**
 * Residue number/label
 * @type {Integer}
 */
prototypeAccessors$j.resno.get = function () {
    return this.residueStore.resno[this.index];
};
prototypeAccessors$j.resno.set = function (value) {
    this.residueStore.resno[this.index] = value;
};
/**
 * Secondary structure code
 * @type {String}
 */
prototypeAccessors$j.sstruc.get = function () {
    return this.residueStore.getSstruc(this.index);
};
prototypeAccessors$j.sstruc.set = function (value) {
    this.residueStore.setSstruc(this.index, value);
};
/**
 * Insertion code
 * @type {String}
 */
prototypeAccessors$j.inscode.get = function () {
    return this.residueStore.getInscode(this.index);
};
prototypeAccessors$j.inscode.set = function (value) {
    this.residueStore.setInscode(this.index, value);
};
//
prototypeAccessors$j.residueType.get = function () {
    return this.residueMap.get(this.residueStore.residueTypeId[this.index]);
};
/**
 * Residue name
 * @type {String}
 */
prototypeAccessors$j.resname.get = function () {
    return this.residueType.resname;
};
/**
 * Hetero flag
 * @type {Boolean}
 */
prototypeAccessors$j.hetero.get = function () {
    return this.residueType.hetero;
};
prototypeAccessors$j.moleculeType.get = function () {
    return this.residueType.moleculeType;
};
prototypeAccessors$j.backboneType.get = function () {
    return this.residueType.backboneType;
};
prototypeAccessors$j.backboneStartType.get = function () {
    return this.residueType.backboneStartType;
};
prototypeAccessors$j.backboneEndType.get = function () {
    return this.residueType.backboneEndType;
};
prototypeAccessors$j.traceAtomIndex.get = function () {
    return this.residueType.traceAtomIndex + this.atomOffset;
};
prototypeAccessors$j.direction1AtomIndex.get = function () {
    return this.residueType.direction1AtomIndex + this.atomOffset;
};
prototypeAccessors$j.direction2AtomIndex.get = function () {
    return this.residueType.direction2AtomIndex + this.atomOffset;
};
prototypeAccessors$j.backboneStartAtomIndex.get = function () {
    return this.residueType.backboneStartAtomIndex + this.atomOffset;
};
prototypeAccessors$j.backboneEndAtomIndex.get = function () {
    return this.residueType.backboneEndAtomIndex + this.atomOffset;
};
prototypeAccessors$j.rungEndAtomIndex.get = function () {
    return this.residueType.rungEndAtomIndex + this.atomOffset;
};
//
prototypeAccessors$j.x.get = function () {
    var x = 0;
    for (var i = this.atomOffset; i <= this.atomEnd; ++i) {
        x += this.atomStore.x[i];
    }
    return x / this.atomCount;
};
prototypeAccessors$j.y.get = function () {
    var y = 0;
    for (var i = this.atomOffset; i <= this.atomEnd; ++i) {
        y += this.atomStore.y[i];
    }
    return y / this.atomCount;
};
prototypeAccessors$j.z.get = function () {
    var z = 0;
    for (var i = this.atomOffset; i <= this.atomEnd; ++i) {
        z += this.atomStore.z[i];
    }
    return z / this.atomCount;
};
//
/**
 * Atom iterator
 * @param  {function(atom: AtomProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
ResidueProxy.prototype.eachAtom = function eachAtom (callback, selection) {
    var count = this.atomCount;
    var offset = this.atomOffset;
    var ap = this.structure._ap;
    var end = offset + count;
    if (selection && selection.atomOnlyTest) {
        var atomOnlyTest = selection.atomOnlyTest;
        for (var i = offset; i < end; ++i) {
            ap.index = i;
            if (atomOnlyTest(ap))
                { callback(ap); }
        }
    }
    else {
        for (var i$1 = offset; i$1 < end; ++i$1) {
            ap.index = i$1;
            callback(ap);
        }
    }
};
//
/**
 * Write residue center position to array
 * @param  {Array|TypedArray} [array] - target array
 * @param  {Integer} [offset] - the offset
 * @return {Array|TypedArray} target array
 */
ResidueProxy.prototype.positionToArray = function positionToArray (array, offset) {
        if ( array === void 0 ) array = [];
        if ( offset === void 0 ) offset = 0;

    array[offset + 0] = this.x;
    array[offset + 1] = this.y;
    array[offset + 2] = this.z;
    return array;
};
//
/**
 * If residue is from a protein
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isProtein = function isProtein () {
    return this.residueType.moleculeType === ProteinType;
};
/**
 * If residue is nucleic
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isNucleic = function isNucleic () {
    var moleculeType = this.residueType.moleculeType;
    return moleculeType === RnaType || moleculeType === DnaType;
};
/**
 * If residue is rna
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isRna = function isRna () {
    return this.residueType.moleculeType === RnaType;
};
/**
 * If residue is dna
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isDna = function isDna () {
    return this.residueType.moleculeType === DnaType;
};
/**
 * If residue is coarse-grain
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isCg = function isCg () {
    var backboneType = this.residueType.backboneType;
    return (backboneType === CgProteinBackboneType ||
        backboneType === CgRnaBackboneType ||
        backboneType === CgDnaBackboneType);
};
/**
 * If residue is from a polymer
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isPolymer = function isPolymer () {
    if (this.structure.entityList.length > 0) {
        return this.entity.isPolymer();
    }
    else {
        var moleculeType = this.residueType.moleculeType;
        return (moleculeType === ProteinType ||
            moleculeType === RnaType ||
            moleculeType === DnaType);
    }
};
/**
 * If residue is hetero
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isHetero = function isHetero () {
    return this.residueType.hetero === 1;
};
/**
 * If residue is a water molecule
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isWater = function isWater () {
    return this.residueType.moleculeType === WaterType;
};
/**
 * If residue is an ion
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isIon = function isIon () {
    return this.residueType.moleculeType === IonType;
};
/**
 * If residue is a saccharide
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isSaccharide = function isSaccharide () {
    return this.residueType.moleculeType === SaccharideType;
};
ResidueProxy.prototype.isStandardAminoacid = function isStandardAminoacid () {
    return this.residueType.isStandardAminoacid();
};
ResidueProxy.prototype.isStandardBase = function isStandardBase () {
    return this.residueType.isStandardBase();
};
/**
 * If residue is part of a helix
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isHelix = function isHelix () {
    return SecStrucHelix.includes(this.sstruc);
};
/**
 * If residue is part of a sheet
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isSheet = function isSheet () {
    return SecStrucSheet.includes(this.sstruc);
};
/**
 * If residue is part of a turn
 * @return {Boolean} flag
 */
ResidueProxy.prototype.isTurn = function isTurn () {
    return SecStrucTurn.includes(this.sstruc) && this.isProtein();
};
ResidueProxy.prototype.getAtomType = function getAtomType (index) {
    return this.atomMap.get(this.atomStore.atomTypeId[index]);
};
ResidueProxy.prototype.getResname1 = function getResname1 () {
    // FIXME nucleic support
    return AA1[this.resname.toUpperCase()] || 'X';
};
ResidueProxy.prototype.getBackboneType = function getBackboneType (position) {
    switch (position) {
        case -1:
            return this.residueType.backboneStartType;
        case 1:
            return this.residueType.backboneEndType;
        default:
            return this.residueType.backboneType;
    }
};
ResidueProxy.prototype.getAtomIndexByName = function getAtomIndexByName (atomname) {
    var index = this.residueType.getAtomIndexByName(atomname);
    if (index !== undefined) {
        index += this.atomOffset;
    }
    return index;
};
ResidueProxy.prototype.hasAtomWithName = function hasAtomWithName (atomname) {
    return this.residueType.hasAtomWithName(atomname);
};
ResidueProxy.prototype.getAtomnameList = function getAtomnameList () {
    console.warn('getAtomnameList - might be expensive');
    var n = this.atomCount;
    var offset = this.atomOffset;
    var list = new Array(n);
    for (var i = 0; i < n; ++i) {
        list[i] = this.getAtomType(offset + i).atomname;
    }
    return list;
};
/**
 * If residue is connected to another
 * @param  {ResidueProxy} rNext - the other residue
 * @return {Boolean} - flag
 */
ResidueProxy.prototype.connectedTo = function connectedTo (rNext) {
    var bbAtomEnd = this.structure.getAtomProxy(this.backboneEndAtomIndex);
    var bbAtomStart = this.structure.getAtomProxy(rNext.backboneStartAtomIndex);
    if (bbAtomEnd && bbAtomStart) {
        return bbAtomEnd.connectedTo(bbAtomStart);
    }
    else {
        return false;
    }
};
ResidueProxy.prototype.getNextConnectedResidue = function getNextConnectedResidue () {
    var rOffset = this.chainStore.residueOffset[this.chainIndex];
    var rCount = this.chainStore.residueCount[this.chainIndex];
    var nextIndex = this.index + 1;
    if (nextIndex < rOffset + rCount) {
        var rpNext = this.structure.getResidueProxy(nextIndex);
        if (this.connectedTo(rpNext)) {
            return rpNext;
        }
    }
    else if (nextIndex === rOffset + rCount) { // cyclic
        var rpFirst = this.structure.getResidueProxy(rOffset);
        if (this.connectedTo(rpFirst)) {
            return rpFirst;
        }
    }
    return undefined;
};
ResidueProxy.prototype.getPreviousConnectedResidue = function getPreviousConnectedResidue (residueProxy) {
    var rOffset = this.chainStore.residueOffset[this.chainIndex];
    var prevIndex = this.index - 1;
    if (prevIndex >= rOffset) {
        var rpPrev = defaults(residueProxy, this.structure.getResidueProxy());
        rpPrev.index = prevIndex;
        if (rpPrev.connectedTo(this)) {
            return rpPrev;
        }
    }
    else if (prevIndex === rOffset - 1) { // cyclic
        var rCount = this.chainStore.residueCount[this.chainIndex];
        var rpLast = defaults(residueProxy, this.structure.getResidueProxy());
        rpLast.index = rOffset + rCount - 1;
        if (rpLast.connectedTo(this)) {
            return rpLast;
        }
    }
    return undefined;
};
ResidueProxy.prototype.getBonds = function getBonds () {
    return this.residueType.getBonds(this);
};
ResidueProxy.prototype.getRings = function getRings () {
    return this.residueType.getRings();
};
ResidueProxy.prototype.getAromaticRings = function getAromaticRings () {
    return this.residueType.getAromaticRings(this);
};
ResidueProxy.prototype.qualifiedName = function qualifiedName (noResname) {
        if ( noResname === void 0 ) noResname = false;

    var name = '';
    if (this.resname && !noResname)
        { name += '[' + this.resname + ']'; }
    if (this.resno !== undefined)
        { name += this.resno; }
    if (this.inscode)
        { name += '^' + this.inscode; }
    if (this.chain)
        { name += ':' + this.chainname; }
    name += '/' + this.modelIndex;
    return name;
};
/**
 * Clone object
 * @return {ResidueProxy} cloned residue
 */
ResidueProxy.prototype.clone = function clone () {
    return new ResidueProxy(this.structure, this.index);
};
ResidueProxy.prototype.toObject = function toObject () {
    return {
        index: this.index,
        chainIndex: this.chainIndex,
        atomOffset: this.atomOffset,
        atomCount: this.atomCount,
        resno: this.resno,
        resname: this.resname,
        sstruc: this.sstruc
    };
};

Object.defineProperties( ResidueProxy.prototype, prototypeAccessors$j );

/**
 * @file Polymer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Polymer
 */
var Polymer = function Polymer(structure, residueIndexStart, residueIndexEnd) {
    this.structure = structure;
    this.residueIndexStart = residueIndexStart;
    this.residueIndexEnd = residueIndexEnd;
    this.chainStore = structure.chainStore;
    this.residueStore = structure.residueStore;
    this.atomStore = structure.atomStore;
    /**
     * @type {Integer}
     */
    this.residueCount = residueIndexEnd - residueIndexStart + 1;
    var rpStart = this.structure.getResidueProxy(this.residueIndexStart);
    var rpEnd = this.structure.getResidueProxy(this.residueIndexEnd);
    this.isPrevConnected = rpStart.getPreviousConnectedResidue() !== undefined;
    var rpNext = rpEnd.getNextConnectedResidue();
    this.isNextConnected = rpNext !== undefined;
    this.isNextNextConnected = rpNext !== undefined && rpNext.getNextConnectedResidue() !== undefined;
    this.isCyclic = rpEnd.connectedTo(rpStart);
    this.__residueProxy = this.structure.getResidueProxy();
    // console.log( this.qualifiedName(), this );
};

var prototypeAccessors$k = { chainIndex: { configurable: true },modelIndex: { configurable: true },chainname: { configurable: true } };
prototypeAccessors$k.chainIndex.get = function () {
    return this.residueStore.chainIndex[this.residueIndexStart];
};
prototypeAccessors$k.modelIndex.get = function () {
    return this.chainStore.modelIndex[this.chainIndex];
};
/**
 * @type {String}
 */
prototypeAccessors$k.chainname.get = function () {
    return this.chainStore.getChainname(this.chainIndex);
};
//
/**
 * If first residue is from aprotein
 * @return {Boolean} flag
 */
Polymer.prototype.isProtein = function isProtein () {
    this.__residueProxy.index = this.residueIndexStart;
    return this.__residueProxy.isProtein();
};
/**
 * If atom is part of a coarse-grain group
 * @return {Boolean} flag
 */
Polymer.prototype.isCg = function isCg () {
    this.__residueProxy.index = this.residueIndexStart;
    return this.__residueProxy.isCg();
};
/**
 * If atom is part of a nucleic molecule
 * @return {Boolean} flag
 */
Polymer.prototype.isNucleic = function isNucleic () {
    this.__residueProxy.index = this.residueIndexStart;
    return this.__residueProxy.isNucleic();
};
Polymer.prototype.getMoleculeType = function getMoleculeType () {
    this.__residueProxy.index = this.residueIndexStart;
    return this.__residueProxy.moleculeType;
};
Polymer.prototype.getBackboneType = function getBackboneType (position) {
    this.__residueProxy.index = this.residueIndexStart;
    return this.__residueProxy.getBackboneType(position);
};
Polymer.prototype.getAtomIndexByType = function getAtomIndexByType (index, type) {
    // TODO pre-calculate, add to residueStore???
    if (this.isCyclic) {
        if (index === -1) {
            index = this.residueCount - 1;
        }
        else if (index === this.residueCount) {
            index = 0;
        }
    }
    else {
        if (index === -1 && !this.isPrevConnected)
            { index += 1; }
        if (index === this.residueCount && !this.isNextNextConnected)
            { index -= 1; }
        // if( index === this.residueCount - 1 && !this.isNextConnected ) index -= 1;
    }
    var rp = this.__residueProxy;
    rp.index = this.residueIndexStart + index;
    var aIndex;
    switch (type) {
        case 'trace':
            aIndex = rp.traceAtomIndex;
            break;
        case 'direction1':
            aIndex = rp.direction1AtomIndex;
            break;
        case 'direction2':
            aIndex = rp.direction2AtomIndex;
            break;
        default:
            aIndex = rp.getAtomIndexByName(type);
    }
    // if (!ap){
    //   console.log(this, type, rp.residueType)
    //   // console.log(rp.qualifiedName(), rp.index, index, this.residueCount - 1)
    //   // rp.index = this.residueIndexStart;
    //   // console.log(rp.qualifiedName(), this.residueIndexStart)
    //   // rp.index = this.residueIndexEnd;
    //   // console.log(rp.qualifiedName(), this.residueIndexEnd)
    // }
    return aIndex;
};
/**
 * Atom iterator
 * @param  {function(atom: AtomProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
Polymer.prototype.eachAtom = function eachAtom (callback, selection) {
    this.eachResidue(function (rp) {
        rp.eachAtom(callback, selection);
    });
};
Polymer.prototype.eachAtomN = function eachAtomN (n, callback, type) {
    var m = this.residueCount;
    var array = new Array(n);
    for (var i = 0; i < n; ++i) {
        array[i] = this.structure.getAtomProxy(this.getAtomIndexByType(i, type));
    }
    callback.apply(this, array);
    for (var j = n; j < m; ++j) {
        for (var i$1 = 1; i$1 < n; ++i$1) {
            array[i$1 - 1].index = array[i$1].index;
        }
        array[n - 1].index = this.getAtomIndexByType(j, type); // TODO
        callback.apply(this, array);
    }
};
/**
 * Residue iterator
 * @param  {function(residue: ResidueProxy)} callback - the callback
 * @return {undefined}
 */
Polymer.prototype.eachResidue = function eachResidue (callback) {
    var rp = this.structure.getResidueProxy();
    var n = this.residueCount;
    var rStartIndex = this.residueIndexStart;
    for (var i = 0; i < n; ++i) {
        rp.index = rStartIndex + i;
        callback(rp);
    }
};
Polymer.prototype.qualifiedName = function qualifiedName () {
    var rpStart = this.structure.getResidueProxy(this.residueIndexStart);
    var rpEnd = this.structure.getResidueProxy(this.residueIndexEnd);
    return rpStart.qualifiedName() + ' - ' + rpEnd.qualifiedName();
};

Object.defineProperties( Polymer.prototype, prototypeAccessors$k );

/**
 * @file Chain Proxy
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Chain proxy
 */
var ChainProxy = function ChainProxy(structure, index) {
    if ( index === void 0 ) index = 0;

    this.structure = structure;
    this.index = index;
    this.chainStore = structure.chainStore;
    this.residueStore = structure.residueStore;
};

var prototypeAccessors$l = { entity: { configurable: true },model: { configurable: true },entityIndex: { configurable: true },modelIndex: { configurable: true },residueOffset: { configurable: true },residueCount: { configurable: true },residueEnd: { configurable: true },atomOffset: { configurable: true },atomEnd: { configurable: true },atomCount: { configurable: true },chainname: { configurable: true },chainid: { configurable: true } };
/**
 * Entity
 * @type {Entity}
 */
prototypeAccessors$l.entity.get = function () {
    return this.structure.entityList[this.entityIndex];
};
/**
 * Model
 * @type {ModelProxy}
 */
prototypeAccessors$l.model.get = function () {
    return this.structure.getModelProxy(this.modelIndex);
};
prototypeAccessors$l.entityIndex.get = function () {
    return this.chainStore.entityIndex[this.index];
};
prototypeAccessors$l.entityIndex.set = function (value) {
    this.chainStore.entityIndex[this.index] = value;
};
prototypeAccessors$l.modelIndex.get = function () {
    return this.chainStore.modelIndex[this.index];
};
prototypeAccessors$l.modelIndex.set = function (value) {
    this.chainStore.modelIndex[this.index] = value;
};
prototypeAccessors$l.residueOffset.get = function () {
    return this.chainStore.residueOffset[this.index];
};
prototypeAccessors$l.residueOffset.set = function (value) {
    this.chainStore.residueOffset[this.index] = value;
};
/**
 * Residue count
 * @type {Integer}
 */
prototypeAccessors$l.residueCount.get = function () {
    return this.chainStore.residueCount[this.index];
};
prototypeAccessors$l.residueCount.set = function (value) {
    this.chainStore.residueCount[this.index] = value;
};
prototypeAccessors$l.residueEnd.get = function () {
    return this.residueOffset + this.residueCount - 1;
};
prototypeAccessors$l.atomOffset.get = function () {
    return this.residueStore.atomOffset[this.residueOffset];
};
prototypeAccessors$l.atomEnd.get = function () {
    return (this.residueStore.atomOffset[this.residueEnd] +
        this.residueStore.atomCount[this.residueEnd] - 1);
};
/**
 * Atom count
 * @type {Integer}
 */
prototypeAccessors$l.atomCount.get = function () {
    if (this.residueCount === 0) {
        return 0;
    }
    else {
        return this.atomEnd - this.atomOffset + 1;
    }
};
//
/**
 * Chain name
 * @type {String}
 */
prototypeAccessors$l.chainname.get = function () {
    return this.chainStore.getChainname(this.index);
};
prototypeAccessors$l.chainname.set = function (value) {
    this.chainStore.setChainname(this.index, value);
};
/**
 * Chain id
 * @type {String}
 */
prototypeAccessors$l.chainid.get = function () {
    return this.chainStore.getChainid(this.index);
};
prototypeAccessors$l.chainid.set = function (value) {
    this.chainStore.setChainid(this.index, value);
};
//
/**
 * Atom iterator
 * @param  {function(atom: AtomProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
ChainProxy.prototype.eachAtom = function eachAtom (callback, selection) {
    this.eachResidue(function (rp) {
        rp.eachAtom(callback, selection);
    }, selection);
};
/**
 * Residue iterator
 * @param  {function(residue: ResidueProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
ChainProxy.prototype.eachResidue = function eachResidue (callback, selection) {
    var count = this.residueCount;
    var offset = this.residueOffset;
    var rp = this.structure._rp;
    var end = offset + count;
    if (selection && selection.test) {
        var residueOnlyTest = selection.residueOnlyTest;
        if (residueOnlyTest) {
            for (var i = offset; i < end; ++i) {
                rp.index = i;
                if (residueOnlyTest(rp)) {
                    callback(rp);
                }
            }
        }
        else {
            for (var i$1 = offset; i$1 < end; ++i$1) {
                rp.index = i$1;
                callback(rp);
            }
        }
    }
    else {
        for (var i$2 = offset; i$2 < end; ++i$2) {
            rp.index = i$2;
            callback(rp);
        }
    }
};
/**
 * Multi-residue iterator
 * @param {Integer} n - window size
 * @param  {function(residueList: ResidueProxy[])} callback - the callback
 * @return {undefined}
 */
ChainProxy.prototype.eachResidueN = function eachResidueN (n, callback) {
    var count = this.residueCount;
    var offset = this.residueOffset;
    var end = offset + count;
    if (count < n)
        { return; }
    var array = new Array(n);
    for (var i = 0; i < n; ++i) {
        array[i] = this.structure.getResidueProxy(offset + i);
    }
    callback.apply(this, array);
    for (var j = offset + n; j < end; ++j) {
        for (var i$1 = 0; i$1 < n; ++i$1) {
            array[i$1].index += 1;
        }
        callback.apply(this, array);
    }
};
/**
 * Polymer iterator
 * @param  {function(polymer: Polymer)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
ChainProxy.prototype.eachPolymer = function eachPolymer (callback, selection) {
    var rStartIndex = 0;
    var rNextIndex = 0;
    var test = selection ? selection.residueOnlyTest : undefined;
    var structure = this.model.structure;
    var count = this.residueCount;
    var offset = this.residueOffset;
    var end = offset + count;
    var rp1 = this.structure.getResidueProxy();
    var rp2 = this.structure.getResidueProxy(offset);
    var ap1 = this.structure.getAtomProxy();
    var ap2 = this.structure.getAtomProxy();
    var first = true;
    for (var i = offset + 1; i < end; ++i) {
        rp1.index = rp2.index;
        rp2.index = i;
        var bbType1 = first ? rp1.backboneEndType : rp1.backboneType;
        var bbType2 = rp2.backboneType;
        if (first) {
            rStartIndex = rp1.index;
            first = false;
        }
        rNextIndex = rp2.index;
        if (bbType1 !== UnknownBackboneType && bbType1 === bbType2) {
            ap1.index = rp1.backboneEndAtomIndex;
            ap2.index = rp2.backboneStartAtomIndex;
        }
        else {
            if (bbType1 !== UnknownBackboneType) {
                if (rp1.index - rStartIndex > 1) {
                    // console.log("FOO1",rStartIndex, rp1.index)
                    callback(new Polymer(structure, rStartIndex, rp1.index));
                }
            }
            rStartIndex = rNextIndex;
            continue;
        }
        if (!ap1 || !ap2 || !ap1.connectedTo(ap2) ||
            (test && (!test(rp1) || !test(rp2)))) {
            if (rp1.index - rStartIndex > 1) {
                // console.log("FOO2",rStartIndex, rp1.index)
                callback(new Polymer(structure, rStartIndex, rp1.index));
            }
            rStartIndex = rNextIndex;
        }
    }
    if (rNextIndex - rStartIndex > 1) {
        if (this.structure.getResidueProxy(rStartIndex).backboneEndType) {
            // console.log("FOO3",rStartIndex, rNextIndex)
            callback(new Polymer(structure, rStartIndex, rNextIndex));
        }
    }
};
//
ChainProxy.prototype.qualifiedName = function qualifiedName () {
    var name = ':' + this.chainname + '/' + this.modelIndex;
    return name;
};
/**
 * Clone object
 * @return {ChainProxy} cloned chain
 */
ChainProxy.prototype.clone = function clone () {
    return new ChainProxy(this.structure, this.index);
};
ChainProxy.prototype.toObject = function toObject () {
    return {
        index: this.index,
        residueOffset: this.residueOffset,
        residueCount: this.residueCount,
        chainname: this.chainname
    };
};

Object.defineProperties( ChainProxy.prototype, prototypeAccessors$l );

/**
 * @file Model Proxy
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Model proxy
 */
var ModelProxy = function ModelProxy(structure, index) {
    if ( index === void 0 ) index = 0;

    this.structure = structure;
    this.index = index;
    this.modelStore = structure.modelStore;
    this.chainStore = structure.chainStore;
    this.residueStore = structure.residueStore;
};

var prototypeAccessors$m = { chainOffset: { configurable: true },chainCount: { configurable: true },residueOffset: { configurable: true },atomOffset: { configurable: true },chainEnd: { configurable: true },residueEnd: { configurable: true },atomEnd: { configurable: true },residueCount: { configurable: true },atomCount: { configurable: true } };
prototypeAccessors$m.chainOffset.get = function () {
    return this.modelStore.chainOffset[this.index];
};
prototypeAccessors$m.chainOffset.set = function (value) {
    this.modelStore.chainOffset[this.index] = value;
};
prototypeAccessors$m.chainCount.get = function () {
    return this.modelStore.chainCount[this.index];
};
prototypeAccessors$m.chainCount.set = function (value) {
    this.modelStore.chainCount[this.index] = value;
};
prototypeAccessors$m.residueOffset.get = function () {
    return this.chainStore.residueOffset[this.chainOffset];
};
prototypeAccessors$m.atomOffset.get = function () {
    return this.residueStore.atomOffset[this.residueOffset];
};
prototypeAccessors$m.chainEnd.get = function () {
    return this.chainOffset + this.chainCount - 1;
};
prototypeAccessors$m.residueEnd.get = function () {
    return (this.chainStore.residueOffset[this.chainEnd] +
        this.chainStore.residueCount[this.chainEnd] - 1);
};
prototypeAccessors$m.atomEnd.get = function () {
    return (this.residueStore.atomOffset[this.residueEnd] +
        this.residueStore.atomCount[this.residueEnd] - 1);
};
/**
 * Residue count
 * @type {Integer}
 */
prototypeAccessors$m.residueCount.get = function () {
    if (this.chainCount === 0) {
        return 0;
    }
    else {
        return this.residueEnd - this.residueOffset + 1;
    }
};
/**
 * Atom count
 * @type {Integer}
 */
prototypeAccessors$m.atomCount.get = function () {
    if (this.residueCount === 0) {
        return 0;
    }
    else {
        return this.atomEnd - this.atomOffset + 1;
    }
};
//
/**
 * Atom iterator
 * @param  {function(atom: AtomProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
ModelProxy.prototype.eachAtom = function eachAtom (callback, selection) {
    this.eachChain(function (cp) {
        cp.eachAtom(callback, selection);
    }, selection);
};
/**
 * Residue iterator
 * @param  {function(residue: ResidueProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
ModelProxy.prototype.eachResidue = function eachResidue (callback, selection) {
    this.eachChain(function (cp) {
        cp.eachResidue(callback, selection);
    }, selection);
};
/**
 * Polymer iterator
 * @param  {function(polymer: Polymer)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
ModelProxy.prototype.eachPolymer = function eachPolymer (callback, selection) {
    if (selection && selection.chainOnlyTest) {
        var chainOnlyTest = selection.chainOnlyTest;
        this.eachChain(function (cp) {
            if (chainOnlyTest(cp)) {
                cp.eachPolymer(callback, selection);
            }
        });
    }
    else {
        this.eachChain(function (cp) {
            cp.eachPolymer(callback, selection);
        });
    }
};
/**
 * Chain iterator
 * @param  {function(chain: ChainProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
ModelProxy.prototype.eachChain = function eachChain (callback, selection) {
    var count = this.chainCount;
    var offset = this.chainOffset;
    var cp = this.structure._cp;
    var end = offset + count;
    if (selection && selection.test) {
        var chainOnlyTest = selection.chainOnlyTest;
        if (chainOnlyTest) {
            for (var i = offset; i < end; ++i) {
                cp.index = i;
                if (chainOnlyTest(cp)) {
                    callback(cp);
                }
            }
        }
        else {
            for (var i$1 = offset; i$1 < end; ++i$1) {
                cp.index = i$1;
                callback(cp);
            }
        }
    }
    else {
        for (var i$2 = offset; i$2 < end; ++i$2) {
            cp.index = i$2;
            callback(cp);
        }
    }
};
//
ModelProxy.prototype.qualifiedName = function qualifiedName () {
    var name = '/' + this.index;
    return name;
};
/**
 * Clone object
 * @return {ModelProxy} cloned model
 */
ModelProxy.prototype.clone = function clone () {
    return new ModelProxy(this.structure, this.index);
};
ModelProxy.prototype.toObject = function toObject () {
    return {
        index: this.index,
        chainOffset: this.chainOffset,
        chainCount: this.chainCount
    };
};

Object.defineProperties( ModelProxy.prototype, prototypeAccessors$m );

/**
 * @file Structure
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Structure
 */
var Structure = function Structure(name, path) {
    if ( name === void 0 ) name = '';
    if ( path === void 0 ) path = '';

    this.signals = {
        refreshed: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]()
    };
    this.init(name, path);
};

var prototypeAccessors$n = { type: { configurable: true } };
Structure.prototype.init = function init (name, path) {
    this.name = name;
    this.path = path;
    this.title = '';
    this.id = '';
    this.data = createData(this);
    this.header = {};
    this.extraData = {};
    this.atomSetCache = {};
    this.atomSetDict = {};
    this.biomolDict = {};
    this.entityList = [];
    this.unitcell = undefined;
    this.frames = [];
    this.boxes = [];
    this.validation = undefined;
    this.bondStore = new BondStore(0);
    this.backboneBondStore = new BondStore(0);
    this.rungBondStore = new BondStore(0);
    this.atomStore = new AtomStore(0);
    this.residueStore = new ResidueStore(0);
    this.chainStore = new ChainStore(0);
    this.modelStore = new ModelStore(0);
    this.atomMap = new AtomMap(this);
    this.residueMap = new ResidueMap(this);
    this.bondHash = undefined;
    this.spatialHash = undefined;
    this.atomSet = undefined;
    this.bondSet = undefined;
    this.center = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    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();
};
prototypeAccessors$n.type.get = function () { return 'Structure'; };
Structure.prototype.finalizeAtoms = function finalizeAtoms () {
    this.atomSet = this.getAtomSet();
    this.atomCount = this.atomStore.count;
    this.boundingBox = this.getBoundingBox(undefined, this.boundingBox);
    this.center = this.boundingBox.getCenter(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]());
    this.spatialHash = new SpatialHash(this.atomStore, this.boundingBox);
};
Structure.prototype.finalizeBonds = function finalizeBonds () {
    this.bondSet = this.getBondSet();
    this.bondCount = this.bondStore.count;
    this.bondHash = new BondHash(this.bondStore, this.atomStore.count);
    this.atomSetCache = {};
    if (!this.atomSetDict.rung) {
        this.atomSetDict.rung = this.getAtomSet(false);
    }
    for (var name in this.atomSetDict) {
        this.atomSetCache['__' + name] = this.atomSetDict[name].clone();
    }
};
//
Structure.prototype.getBondProxy = function getBondProxy (index) {
    return new BondProxy(this, index);
};
Structure.prototype.getAtomProxy = function getAtomProxy (index) {
    return new AtomProxy(this, index);
};
Structure.prototype.getResidueProxy = function getResidueProxy (index) {
    return new ResidueProxy(this, index);
};
Structure.prototype.getChainProxy = function getChainProxy (index) {
    return new ChainProxy(this, index);
};
Structure.prototype.getModelProxy = function getModelProxy (index) {
    return new ModelProxy(this, index);
};
//
Structure.prototype.getBondSet = function getBondSet ( /* selection */) {
    // TODO implement selection parameter
    var n = this.bondStore.count;
    var bondSet = new BitArray(n);
    var atomSet = this.atomSet;
    if (atomSet) {
        if (atomSet.isAllSet()) {
            bondSet.setAll();
        }
        else if (atomSet.isAllClear()) {
            bondSet.clearAll();
        }
        else {
            var bp = this.getBondProxy();
            for (var i = 0; i < n; ++i) {
                bp.index = i;
                if (atomSet.isSet(bp.atomIndex1, bp.atomIndex2)) {
                    bondSet.set(bp.index);
                }
            }
        }
    }
    else {
        bondSet.setAll();
    }
    return bondSet;
};
Structure.prototype.getBackboneBondSet = function getBackboneBondSet ( /* selection */) {
    // TODO implement selection parameter
    var n = this.backboneBondStore.count;
    var backboneBondSet = new BitArray(n);
    var backboneAtomSet = this.atomSetCache.__backbone;
    if (backboneAtomSet) {
        var bp = this.getBondProxy();
        bp.bondStore = this.backboneBondStore;
        for (var i = 0; i < n; ++i) {
            bp.index = i;
            if (backboneAtomSet.isSet(bp.atomIndex1, bp.atomIndex2)) {
                backboneBondSet.set(bp.index);
            }
        }
    }
    else {
        backboneBondSet.setAll();
    }
    return backboneBondSet;
};
Structure.prototype.getRungBondSet = function getRungBondSet ( /* selection */) {
    // TODO implement selection parameter
    var n = this.rungBondStore.count;
    var rungBondSet = new BitArray(n);
    var rungAtomSet = this.atomSetCache.__rung;
    if (rungAtomSet) {
        var bp = this.getBondProxy();
        bp.bondStore = this.rungBondStore;
        for (var i = 0; i < n; ++i) {
            bp.index = i;
            if (rungAtomSet.isSet(bp.atomIndex1, bp.atomIndex2)) {
                rungBondSet.set(bp.index);
            }
        }
    }
    else {
        rungBondSet.setAll();
    }
    return rungBondSet;
};
/**
 * Get a set of atoms
 * @param  {Boolean|Selection|BitArray} selection - object defining how to
 *                                  initialize the atom set.
 *                                  Boolean: init with value;
 *                                  Selection: init with selection;
 *                                  BitArray: return bit array
 * @return {BitArray} set of atoms
 */
Structure.prototype.getAtomSet = function getAtomSet (selection) {
    var n = this.atomStore.count;
    if (selection === undefined) {
        return new BitArray(n, true);
    }
    else if (selection instanceof BitArray) {
        return selection;
    }
    else if (selection === true) {
        return new BitArray(n, true);
    }
    else if (selection && selection.test) {
        var seleString = selection.string;
        if (seleString in this.atomSetCache) {
            return this.atomSetCache[seleString];
        }
        else {
            if (seleString === '') {
                return new BitArray(n, true);
            }
            else {
                var atomSet = new BitArray(n);
                this.eachAtom(function (ap) {
                    atomSet.set(ap.index);
                }, selection);
                this.atomSetCache[seleString] = atomSet;
                return atomSet;
            }
        }
    }
    else if (selection === false) {
        return new BitArray(n);
    }
    return new BitArray(n, true);
};
/**
 * Get set of atoms around a set of atoms from a selection
 * @param  {Selection} selection - the selection object
 * @param  {Number} radius - radius to select within
 * @return {BitArray} set of atoms
 */
Structure.prototype.getAtomSetWithinSelection = function getAtomSetWithinSelection (selection, radius) {
    var spatialHash = this.spatialHash;
    var atomSet = this.getAtomSet(false);
    var ap = this.getAtomProxy();
    if (!spatialHash)
        { return atomSet; }
    this.getAtomSet(selection).forEach(function (idx) {
        ap.index = idx;
        spatialHash.within(ap.x, ap.y, ap.z, radius).forEach(function (idx2) {
            atomSet.set(idx2);
        });
    });
    return atomSet;
};
/**
 * Get set of atoms around a point
 * @param  {Vector3|AtomProxy} point - the point
 * @param  {Number} radius - radius to select within
 * @return {BitArray} set of atoms
 */
Structure.prototype.getAtomSetWithinPoint = function getAtomSetWithinPoint (point, radius) {
    var p = point;
    var atomSet = this.getAtomSet(false);
    if (!this.spatialHash)
        { return atomSet; }
    this.spatialHash.within(p.x, p.y, p.z, radius).forEach(function (idx) {
        atomSet.set(idx);
    });
    return atomSet;
};
/**
 * Get set of atoms within a volume
 * @param  {Volume} volume - the volume
 * @param  {Number} radius - radius to select within
 * @param  {[type]} minValue - minimum value to be considered as within the volume
 * @param  {[type]} maxValue - maximum value to be considered as within the volume
 * @param  {[type]} outside - use only values falling outside of the min/max values
 * @return {BitArray} set of atoms
 */
Structure.prototype.getAtomSetWithinVolume = function getAtomSetWithinVolume (volume, radius, minValue, maxValue, outside) {
    var fv = new FilteredVolume(volume, minValue, maxValue, outside); // TODO
    var dp = fv.getDataPosition();
    var n = dp.length;
    var r = fv.matrix.getMaxScaleOnAxis();
    var atomSet = this.getAtomSet(false);
    if (!this.spatialHash)
        { return atomSet; }
    for (var i = 0; i < n; i += 3) {
        this.spatialHash.within(dp[i], dp[i + 1], dp[i + 2], r).forEach(function (idx) {
            atomSet.set(idx);
        });
    }
    return atomSet;
};
/**
 * Get set of all atoms within the groups of a selection
 * @param  {Selection} selection - the selection object
 * @return {BitArray} set of atoms
 */
Structure.prototype.getAtomSetWithinGroup = function getAtomSetWithinGroup (selection) {
    var atomResidueIndex = this.atomStore.residueIndex;
    var atomSet = this.getAtomSet(false);
    var rp = this.getResidueProxy();
    this.getAtomSet(selection).forEach(function (idx) {
        rp.index = atomResidueIndex[idx];
        for (var idx2 = rp.atomOffset; idx2 <= rp.atomEnd; ++idx2) {
            atomSet.set(idx2);
        }
    });
    return atomSet;
};
//
Structure.prototype.getSelection = function getSelection () {
    return;
};
Structure.prototype.getStructure = function getStructure () {
    return this;
};
/**
 * Entity iterator
 * @param  {function(entity: Entity)} callback - the callback
 * @param  {EntityType} type - entity type
 * @return {undefined}
 */
Structure.prototype.eachEntity = function eachEntity (callback, type) {
    this.entityList.forEach(function (entity) {
        if (type === undefined || entity.getEntityType() === type) {
            callback(entity);
        }
    });
};
/**
 * Bond iterator
 * @param  {function(bond: BondProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
Structure.prototype.eachBond = function eachBond (callback, selection) {
    var bp = this.getBondProxy();
    var bondSet;
    if (selection && selection.test) {
        bondSet = this.getBondSet( /*selection*/);
        if (this.bondSet) {
            bondSet.intersection(this.bondSet);
        }
    }
    if (bondSet) {
        bondSet.forEach(function (index) {
            bp.index = index;
            callback(bp);
        });
    }
    else {
        var n = this.bondStore.count;
        for (var i = 0; i < n; ++i) {
            bp.index = i;
            callback(bp);
        }
    }
};
/**
 * Atom iterator
 * @param  {function(atom: AtomProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
Structure.prototype.eachAtom = function eachAtom (callback, selection) {
    if (selection && selection.test) {
        this.eachModel(function (mp) {
            mp.eachAtom(callback, selection);
        }, selection);
    }
    else {
        var an = this.atomStore.count;
        var ap = this.getAtomProxy();
        for (var i = 0; i < an; ++i) {
            ap.index = i;
            callback(ap);
        }
    }
};
/**
 * Residue iterator
 * @param  {function(residue: ResidueProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
Structure.prototype.eachResidue = function eachResidue (callback, selection) {
    if (selection && selection.test) {
        var mn = this.modelStore.count;
        var mp = this.getModelProxy();
        var modelOnlyTest = selection.modelOnlyTest;
        if (modelOnlyTest) {
            for (var i = 0; i < mn; ++i) {
                mp.index = i;
                if (modelOnlyTest(mp)) {
                    mp.eachResidue(callback, selection);
                }
            }
        }
        else {
            for (var i$1 = 0; i$1 < mn; ++i$1) {
                mp.index = i$1;
                mp.eachResidue(callback, selection);
            }
        }
    }
    else {
        var rn = this.residueStore.count;
        var rp = this.getResidueProxy();
        for (var i$2 = 0; i$2 < rn; ++i$2) {
            rp.index = i$2;
            callback(rp);
        }
    }
};
/**
 * Multi-residue iterator
 * @param {Integer} n - window size
 * @param  {function(residueList: ResidueProxy[])} callback - the callback
 * @return {undefined}
 */
Structure.prototype.eachResidueN = function eachResidueN (n, callback) {
    var rn = this.residueStore.count;
    if (rn < n)
        { return; }
    var array = new Array(n);
    for (var i = 0; i < n; ++i) {
        array[i] = this.getResidueProxy(i);
    }
    callback.apply(this, array);
    for (var j = n; j < rn; ++j) {
        for (var i$1 = 0; i$1 < n; ++i$1) {
            array[i$1].index += 1;
        }
        callback.apply(this, array);
    }
};
/**
 * Polymer iterator
 * @param  {function(polymer: Polymer)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
Structure.prototype.eachPolymer = function eachPolymer (callback, selection) {
    if (selection && selection.modelOnlyTest) {
        var modelOnlyTest = selection.modelOnlyTest;
        this.eachModel(function (mp) {
            if (modelOnlyTest(mp)) {
                mp.eachPolymer(callback, selection);
            }
        });
    }
    else {
        this.eachModel(function (mp) {
            mp.eachPolymer(callback, selection);
        });
    }
};
/**
 * Chain iterator
 * @param  {function(chain: ChainProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
Structure.prototype.eachChain = function eachChain (callback, selection) {
    if (selection && selection.test) {
        this.eachModel(function (mp) {
            mp.eachChain(callback, selection);
        });
    }
    else {
        var cn = this.chainStore.count;
        var cp = this.getChainProxy();
        for (var i = 0; i < cn; ++i) {
            cp.index = i;
            callback(cp);
        }
    }
};
/**
 * Model iterator
 * @param  {function(model: ModelProxy)} callback - the callback
 * @param  {Selection} [selection] - the selection
 * @return {undefined}
 */
Structure.prototype.eachModel = function eachModel (callback, selection) {
    var n = this.modelStore.count;
    var mp = this.getModelProxy();
    if (selection && selection.test) {
        var modelOnlyTest = selection.modelOnlyTest;
        if (modelOnlyTest) {
            for (var i = 0; i < n; ++i) {
                mp.index = i;
                if (modelOnlyTest(mp)) {
                    callback(mp);
                }
            }
        }
        else {
            for (var i$1 = 0; i$1 < n; ++i$1) {
                mp.index = i$1;
                callback(mp);
            }
        }
    }
    else {
        for (var i$2 = 0; i$2 < n; ++i$2) {
            mp.index = i$2;
            callback(mp);
        }
    }
};
//
Structure.prototype.getAtomData = function getAtomData (params) {
    var p = Object.assign({}, params);
    if (p.colorParams)
        { p.colorParams.structure = this.getStructure(); }
    var what = p.what;
    var atomSet = defaults(p.atomSet, this.atomSet);
    var radiusFactory; // TODO
    var colormaker; // TODO
    var atomData = {};
    var ap = this.getAtomProxy();
    var atomCount = atomSet.getSize();
    if (!what || what.position) {
        atomData.position = new Float32Array(atomCount * 3);
    }
    if ((!what || what.color) && p.colorParams) {
        atomData.color = new Float32Array(atomCount * 3);
        colormaker = ColormakerRegistry$1.getScheme(p.colorParams);
    }
    if (!what || what.picking) {
        atomData.picking = new AtomPicker(new Float32Array(atomCount), this.getStructure());
    }
    if (!what || what.radius) {
        atomData.radius = new Float32Array(atomCount);
        radiusFactory = new RadiusFactory(p.radiusParams);
    }
    if (!what || what.index) {
        atomData.index = new Uint32Array(atomCount);
    }
    var position = atomData.position;
        var color = atomData.color;
        var picking = atomData.picking;
        var radius = atomData.radius;
        var index = atomData.index;
    atomSet.forEach(function (idx, i) {
        var i3 = i * 3;
        ap.index = idx;
        if (position) {
            ap.positionToArray(position, i3);
        }
        if (color) {
            colormaker.atomColorToArray(ap, color, i3);
        }
        if (picking) {
            picking.array[i] = idx;
        }
        if (radius) {
            radius[i] = radiusFactory.atomRadius(ap);
        }
        if (index) {
            index[i] = idx;
        }
    });
    return atomData;
};
Structure.prototype.getBondData = function getBondData (params) {
    var p = Object.assign({}, params);
    if (p.colorParams)
        { p.colorParams.structure = this.getStructure(); }
    var what = p.what;
    var bondSet = defaults(p.bondSet, this.bondSet);
    var multipleBond = defaults(p.multipleBond, 'off');
    var isMulti = multipleBond !== 'off';
    var isOffset = multipleBond === 'offset';
    var bondScale = defaults(p.bondScale, 0.4);
    var bondSpacing = defaults(p.bondSpacing, 1.0);
    var radiusFactory; // TODO
    var colormaker; // TODO
    var bondData = {};
    var bp = this.getBondProxy();
    if (p.bondStore)
        { bp.bondStore = p.bondStore; }
    var ap1 = this.getAtomProxy();
    var ap2 = this.getAtomProxy();
    var bondCount;
    if (isMulti) {
        var storeBondOrder = bp.bondStore.bondOrder;
        bondCount = 0;
        bondSet.forEach(function (index) {
            bondCount += storeBondOrder[index];
        });
    }
    else {
        bondCount = bondSet.getSize();
    }
    if (!what || what.position) {
        bondData.position1 = new Float32Array(bondCount * 3);
        bondData.position2 = new Float32Array(bondCount * 3);
    }
    if ((!what || what.color) && p.colorParams) {
        bondData.color = new Float32Array(bondCount * 3);
        bondData.color2 = new Float32Array(bondCount * 3);
        colormaker = ColormakerRegistry$1.getScheme(p.colorParams);
    }
    if (!what || what.picking) {
        bondData.picking = new BondPicker(new Float32Array(bondCount), this.getStructure(), p.bondStore);
    }
    if (!what || what.radius || (isMulti && what.position)) {
        radiusFactory = new RadiusFactory(p.radiusParams);
    }
    if (!what || what.radius) {
        bondData.radius = new Float32Array(bondCount);
        if (p.radius2) {
            bondData.radius2 = new Float32Array(bondCount);
        }
    }
    var position1 = bondData.position1;
        var position2 = bondData.position2;
        var color = bondData.color;
        var color2 = bondData.color2;
        var picking = bondData.picking;
        var radius = bondData.radius;
        var radius2 = bondData.radius2;
    var i = 0;
    var j, i3, k, bondOrder, absOffset;
    var multiRadius;
    var vt = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var vShortening = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var vShift = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    bondSet.forEach(function (index) {
        i3 = i * 3;
        bp.index = index;
        ap1.index = bp.atomIndex1;
        ap2.index = bp.atomIndex2;
        bondOrder = bp.bondOrder;
        if (position1) {
            if (isMulti && bondOrder > 1) {
                var atomRadius = radiusFactory.atomRadius(ap1);
                multiRadius = atomRadius * bondScale / (0.5 * bondOrder);
                bp.calculateShiftDir(vShift);
                if (isOffset) {
                    absOffset = 2 * bondSpacing * atomRadius;
                    vShift.multiplyScalar(absOffset);
                    vShift.negate();
                    // Shortening is calculated so that neighbouring double
                    // bonds on tetrahedral geometry (e.g. sulphonamide)
                    // are not quite touching (arccos(1.9 / 2) ~ 109deg)
                    // but don't shorten beyond 10% each end or it looks odd
                    vShortening.subVectors(ap2, ap1).multiplyScalar(// TODO
                    Math.max(0.1, absOffset / 1.88));
                    ap1.positionToArray(position1, i3);
                    ap2.positionToArray(position2, i3);
                    if (bondOrder >= 2) {
                        vt.addVectors(ap1, vShift).add(vShortening).toArray(position1, i3 + 3); // TODO
                        vt.addVectors(ap2, vShift).sub(vShortening).toArray(position2, i3 + 3); // TODO
                        if (bondOrder >= 3) {
                            vt.subVectors(ap1, vShift).add(vShortening).toArray(position1, i3 + 6); // TODO
                            vt.subVectors(ap2, vShift).sub(vShortening).toArray(position2, i3 + 6); // TODO
                        }
                    }
                }
                else {
                    absOffset = (bondSpacing - bondScale) * atomRadius;
                    vShift.multiplyScalar(absOffset);
                    if (bondOrder === 2) {
                        vt.addVectors(ap1, vShift).toArray(position1, i3); // TODO
                        vt.subVectors(ap1, vShift).toArray(position1, i3 + 3); // TODO
                        vt.addVectors(ap2, vShift).toArray(position2, i3); // TODO
                        vt.subVectors(ap2, vShift).toArray(position2, i3 + 3); // TODO
                    }
                    else if (bondOrder === 3) {
                        ap1.positionToArray(position1, i3);
                        vt.addVectors(ap1, vShift).toArray(position1, i3 + 3); // TODO
                        vt.subVectors(ap1, vShift).toArray(position1, i3 + 6); // TODO
                        ap2.positionToArray(position2, i3);
                        vt.addVectors(ap2, vShift).toArray(position2, i3 + 3); // TODO
                        vt.subVectors(ap2, vShift).toArray(position2, i3 + 6); // TODO
                    }
                    else {
                        // todo, better fallback
                        ap1.positionToArray(position1, i3);
                        ap2.positionToArray(position2, i3);
                    }
                }
            }
            else {
                ap1.positionToArray(position1, i3);
                ap2.positionToArray(position2, i3);
            }
        }
        if (color && color2) {
            colormaker.bondColorToArray(bp, 1, color, i3);
            colormaker.bondColorToArray(bp, 0, color2, i3);
            if (isMulti && bondOrder > 1) {
                for (j = 1; j < bondOrder; ++j) {
                    k = j * 3 + i3;
                    copyWithin(color, i3, k, 3);
                    copyWithin(color2, i3, k, 3);
                }
            }
        }
        if (picking && picking.array) {
            picking.array[i] = index;
            if (isMulti && bondOrder > 1) {
                for (j = 1; j < bondOrder; ++j) {
                    picking.array[i + j] = index;
                }
            }
        }
        if (radius) {
            radius[i] = radiusFactory.atomRadius(ap1);
            if (isMulti && bondOrder > 1) {
                multiRadius = radius[i] * bondScale / (isOffset ? 1 : (0.5 * bondOrder));
                for (j = isOffset ? 1 : 0; j < bondOrder; ++j) {
                    radius[i + j] = multiRadius;
                }
            }
        }
        if (radius2) {
            radius2[i] = radiusFactory.atomRadius(ap2);
            if (isMulti && bondOrder > 1) {
                multiRadius = radius2[i] * bondScale / (isOffset ? 1 : (0.5 * bondOrder));
                for (j = isOffset ? 1 : 0; j < bondOrder; ++j) {
                    radius2[i + j] = multiRadius;
                }
            }
        }
        i += isMulti ? bondOrder : 1;
    });
    return bondData;
};
Structure.prototype.getBackboneAtomData = function getBackboneAtomData (params) {
    params = Object.assign({
        atomSet: this.atomSetCache.__backbone
    }, params);
    return this.getAtomData(params);
};
Structure.prototype.getBackboneBondData = function getBackboneBondData (params) {
    params = Object.assign({
        bondSet: this.getBackboneBondSet(),
        bondStore: this.backboneBondStore
    }, params);
    return this.getBondData(params);
};
Structure.prototype.getRungAtomData = function getRungAtomData (params) {
    params = Object.assign({
        atomSet: this.atomSetCache.__rung
    }, params);
    return this.getAtomData(params);
};
Structure.prototype.getRungBondData = function getRungBondData (params) {
    params = Object.assign({
        bondSet: this.getRungBondSet(),
        bondStore: this.rungBondStore
    }, params);
    return this.getBondData(params);
};
//
/**
 * Gets the bounding box of the (selected) structure atoms
 * @param  {Selection} [selection] - the selection
 * @param  {Box3} [box] - optional target
 * @return {Vector3} the box
 */
Structure.prototype.getBoundingBox = function getBoundingBox (selection, box) {
    if (Debug)
        { Log.time('getBoundingBox'); }
    box = box || new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    var minX = +Infinity;
    var minY = +Infinity;
    var minZ = +Infinity;
    var maxX = -Infinity;
    var maxY = -Infinity;
    var maxZ = -Infinity;
    this.eachAtom(function (ap) {
        var x = ap.x;
        var y = ap.y;
        var z = ap.z;
        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; }
    }, selection);
    box.min.set(minX, minY, minZ);
    box.max.set(maxX, maxY, maxZ);
    if (Debug)
        { Log.timeEnd('getBoundingBox'); }
    return box;
};
/**
 * Gets the principal axes of the (selected) structure atoms
 * @param  {Selection} [selection] - the selection
 * @return {PrincipalAxes} the principal axes
 */
Structure.prototype.getPrincipalAxes = function getPrincipalAxes (selection) {
    if (Debug)
        { Log.time('getPrincipalAxes'); }
    var i = 0;
    var coords = new Matrix(3, this.atomCount);
    var cd = coords.data;
    this.eachAtom(function (a) {
        cd[i + 0] = a.x;
        cd[i + 1] = a.y;
        cd[i + 2] = a.z;
        i += 3;
    }, selection);
    if (Debug)
        { Log.timeEnd('getPrincipalAxes'); }
    return new PrincipalAxes(coords);
};
/**
 * Gets the center of the (selected) structure atoms
 * @param  {Selection} [selection] - the selection
 * @return {Vector3} the center
 */
Structure.prototype.atomCenter = function atomCenter (selection) {
    if (selection) {
        return this.getBoundingBox(selection).getCenter(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]());
    }
    else {
        return this.center.clone();
    }
};
Structure.prototype.hasCoords = function hasCoords () {
    if (this._hasCoords === undefined) {
        var atomStore = this.atomStore;
        this._hasCoords = (arrayMin(atomStore.x) !== 0 || arrayMax(atomStore.x) !== 0 ||
            arrayMin(atomStore.y) !== 0 || arrayMax(atomStore.y) !== 0 ||
            arrayMin(atomStore.z) !== 0 || arrayMax(atomStore.z) !== 0) || (
        // allow models with a single atom at the origin
        atomStore.count / this.modelStore.count === 1);
    }
    return this._hasCoords;
};
Structure.prototype.getSequence = function getSequence (selection) {
    var seq = [];
    var rp = this.getResidueProxy();
    this.eachAtom(function (ap) {
        rp.index = ap.residueIndex;
        if (ap.index === rp.traceAtomIndex) {
            seq.push(rp.getResname1());
        }
    }, selection);
    return seq;
};
Structure.prototype.getAtomIndices = function getAtomIndices (selection) {
    if (selection && selection.string) {
        var indices = [];
        this.eachAtom(function (ap) {
            indices.push(ap.index);
        }, selection);
        return new Uint32Array(indices);
    }
    else {
        var p = { what: { index: true } };
        return this.getAtomData(p).index;
    }
};
/**
 * Get number of unique chainnames
 * @param  {Selection} selection - limit count to selection
 * @return {Integer} count
 */
Structure.prototype.getChainnameCount = function getChainnameCount (selection) {
    var chainnames = new Set();
    this.eachChain(function (cp) {
        if (cp.residueCount) {
            chainnames.add(cp.chainname);
        }
    }, selection);
    return chainnames.size;
};
//
Structure.prototype.updatePosition = function updatePosition (position) {
    var i = 0;
    this.eachAtom(function (ap) {
        ap.positionFromArray(position, i);
        i += 3;
    }, undefined);
    this._hasCoords = undefined; // to trigger recalculation
};
Structure.prototype.refreshPosition = function refreshPosition () {
    this.getBoundingBox(undefined, this.boundingBox);
    this.boundingBox.getCenter(this.center);
    this.spatialHash = new SpatialHash(this.atomStore, this.boundingBox);
};
/**
 * Calls dispose() method of property objects.
 * Unsets properties to help garbage collection.
 * @return {undefined}
 */
Structure.prototype.dispose = function dispose () {
    if (this.frames)
        { this.frames.length = 0; }
    if (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.bondStore;
    delete this.atomStore;
    delete this.residueStore;
    delete this.chainStore;
    delete this.modelStore;
    delete this.frames;
    delete this.boxes;
    delete this.bondSet;
    delete this.atomSet;
};

Object.defineProperties( Structure.prototype, prototypeAccessors$n );

/**
 * @file Shape
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var tmpBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
var Primitives = [
    ArrowPrimitive, BoxPrimitive, ConePrimitive, CylinderPrimitive,
    EllipsoidPrimitive, OctahedronPrimitive, SpherePrimitive, TetrahedronPrimitive,
    TextPrimitive, TorusPrimitive, PointPrimitive, WidelinePrimitive
];
var ShapeDefaultParameters = {
    aspectRatio: 1.5,
    sphereDetail: 2,
    radialSegments: 50,
    disableImpostor: false,
    openEnded: false,
    dashedCylinder: false,
    labelParams: {},
    pointSize: 2,
    sizeAttenuation: false,
    useTexture: true,
    linewidth: 2
};
/**
 * Class for building custom shapes.
 *
 * @example
 * var shape = new NGL.Shape('shape', { disableImpostor: true });
 * shape.addSphere([ 0, 0, 9 ], [ 1, 0, 0 ], 1.5 );
 * shape.addEllipsoid([ 6, 0, 0 ], [ 1, 0, 0 ], 1.5, [ 3, 0, 0 ], [ 0, 2, 0 ]);
 * shape.addCylinder([ 0, 2, 7 ], [ 0, 0, 9 ], [ 1, 1, 0 ], 0.5);
 * shape.addCone([ 0, 2, 7 ], [ 0, 3, 3 ], [ 1, 1, 0 ], 1.5);
 * shape.addArrow([ 1, 2, 7 ], [ 30, 3, 3 ], [ 1, 0, 1 ], 1.0);
 * shape.addBox([ 0, 3, 0 ], [ 1, 0, 1 ], 2, [ 0, 1, 1 ], [ 1, 0, 1 ]);
 * var shapeComp = stage.addComponentFromObject(shape);
 * geoComp.addRepresentation('buffer');
 */
var Shape = function Shape(name, params) {
    var this$1 = this;
    if ( name === void 0 ) name = 'shape';
    if ( params === void 0 ) params = {};

    this.boundingBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    this.bufferList = [];
    this.meshCount = 0;
    this._primitiveData = {};
    this.name = name;
    this.parameters = createParams(params, ShapeDefaultParameters);
    Primitives.forEach(function (P) {
        Object.keys(P.fields).forEach(function (name) {
            this$1._primitiveData[P.getShapeKey(name)] = [];
        });
        this$1._primitiveData[P.getShapeKey('name')] = [];
    });
};

var prototypeAccessors$o = { center: { configurable: true },type: { configurable: true } };
/**
 * Add a buffer
 * @param {Buffer} buffer - buffer object
 * @return {Shape} this object
 */
Shape.prototype.addBuffer = function addBuffer (buffer) {
    this.bufferList.push(buffer);
    var geometry = buffer.geometry; // TODO
    if (!geometry.boundingBox) {
        geometry.computeBoundingBox();
    }
    this.boundingBox.union(geometry.boundingBox);
    return this;
};
/**
 * Add a mesh
 * @example
 * shape.addMesh(
 *   [ 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1 ],
 *   [ 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0 ]
 * );
 *
 * @param {Float32Array|Array} position - positions
 * @param {Float32Array|Array} color - colors
 * @param {Uint32Array|Uint16Array|Array} [index] - indices
 * @param {Float32Array|Array} [normal] - normals
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addMesh = function addMesh (position, color, index, normal, name) {
    position = ensureFloat32Array(position);
    color = ensureFloat32Array(color);
    if (Array.isArray(index)) {
        index = getUintArray(index, position.length);
    }
    if (normal) {
        normal = ensureFloat32Array(normal);
    }
    var data;
    if (normal === undefined || normal.length == 0) {
        data = { position: position, color: color, index: index };
    }
    else {
        data = { position: position, color: color, index: index, normal: normal };
    }
    //const data = { position, color, index, normal }
    var picking = new MeshPicker(this, Object.assign({ serial: this.meshCount, name: name }, data));
    var meshBuffer = new MeshBuffer(Object.assign({ picking: picking }, data));
    this.bufferList.push(meshBuffer);
    tmpBox.setFromArray(position);
    this.boundingBox.union(tmpBox);
    this.meshCount += 1;
    return this;
};
/**
 * Add a sphere
 * @example
 * shape.addSphere([ 0, 0, 9 ], [ 1, 0, 0 ], 1.5);
 *
 * @param {Vector3|Array} position - position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} radius - radius value
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addSphere = function addSphere (position, color, radius, name) {
    SpherePrimitive.objectToShape(this, { position: position, color: color, radius: radius, name: name });
    return this;
};
/**
 * Add an ellipsoid
 * @example
 * shape.addEllipsoid([ 6, 0, 0 ], [ 1, 0, 0 ], 1.5, [ 3, 0, 0 ], [ 0, 2, 0 ]);
 *
 * @param {Vector3|Array} position - position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} radius - radius value
 * @param {Vector3|Array} majorAxis - major axis vector or array
 * @param {Vector3|Array} minorAxis - minor axis vector or array
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addEllipsoid = function addEllipsoid (position, color, radius, majorAxis, minorAxis, name) {
    EllipsoidPrimitive.objectToShape(this, { position: position, color: color, radius: radius, majorAxis: majorAxis, minorAxis: minorAxis, name: name });
    return this;
};
/**
 * Add a torus
 * @example
 * shape.addTorus([ 6, 0, 0 ], [ 1, 0, 0 ], 1.5, [ 3, 0, 0 ], [ 0, 2, 0 ]);
 *
 * @param {Vector3|Array} position - position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} radius - radius value
 * @param {Vector3|Array} majorAxis - major axis vector or array
 * @param {Vector3|Array} minorAxis - minor axis vector or array
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addTorus = function addTorus (position, color, radius, majorAxis, minorAxis, name) {
    TorusPrimitive.objectToShape(this, { position: position, color: color, radius: radius, majorAxis: majorAxis, minorAxis: minorAxis, name: name });
    return this;
};
/**
 * Add a cylinder
 * @example
 * shape.addCylinder([ 0, 2, 7 ], [ 0, 0, 9 ], [ 1, 1, 0 ], 0.5);
 *
 * @param {Vector3|Array} position1 - from position vector or array
 * @param {Vector3|Array} position2 - to position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} radius - radius value
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addCylinder = function addCylinder (position1, position2, color, radius, name) {
    CylinderPrimitive.objectToShape(this, { position1: position1, position2: position2, color: color, radius: radius, name: name });
    return this;
};
/**
 * Add a cone
 * @example
 * shape.addCone([ 0, 2, 7 ], [ 0, 3, 3 ], [ 1, 1, 0 ], 1.5);
 *
 * @param {Vector3|Array} position1 - from position vector or array
 * @param {Vector3|Array} position2 - to position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} radius - radius value
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addCone = function addCone (position1, position2, color, radius, name) {
    ConePrimitive.objectToShape(this, { position1: position1, position2: position2, color: color, radius: radius, name: name });
    return this;
};
/**
 * Add an arrow
 * @example
 * shape.addArrow([ 0, 2, 7 ], [ 0, 0, 9 ], [ 1, 1, 0 ], 0.5);
 *
 * @param {Vector3|Array} position1 - from position vector or array
 * @param {Vector3|Array} position2 - to position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} radius - radius value
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addArrow = function addArrow (position1, position2, color, radius, name) {
    ArrowPrimitive.objectToShape(this, { position1: position1, position2: position2, color: color, radius: radius, name: name });
    return this;
};
/**
 * Add a box
 * @example
 * shape.addBox([ 0, 3, 0 ], [ 1, 0, 1 ], 2, [ 0, 1, 1 ], [ 1, 0, 1 ]);
 *
 * @param {Vector3|Array} position - position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} size - size value
 * @param {Vector3|Array} heightAxis - height axis vector or array
 * @param {Vector3|Array} depthAxis - depth axis vector or array
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addBox = function addBox (position, color, size, heightAxis, depthAxis, name) {
    BoxPrimitive.objectToShape(this, { position: position, color: color, size: size, heightAxis: heightAxis, depthAxis: depthAxis, name: name });
    return this;
};
/**
 * Add an octahedron
 * @example
 * shape.addOctahedron([ 0, 3, 0 ], [ 1, 0, 1 ], 2, [ 0, 1, 1 ], [ 1, 0, 1 ]);
 *
 * @param {Vector3|Array} position - position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} size - size value
 * @param {Vector3|Array} heightAxis - height axis vector or array
 * @param {Vector3|Array} depthAxis - depth axis vector or array
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addOctahedron = function addOctahedron (position, color, size, heightAxis, depthAxis, name) {
    OctahedronPrimitive.objectToShape(this, { position: position, color: color, size: size, heightAxis: heightAxis, depthAxis: depthAxis, name: name });
    return this;
};
/**
 * Add a tetrahedron
 * @example
 * shape.addTetrahedron([ 0, 3, 0 ], [ 1, 0, 1 ], 2, [ 0, 1, 1 ], [ 1, 0, 1 ]);
 *
 * @param {Vector3|Array} position - position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} size - size value
 * @param {Vector3|Array} heightAxis - height axis vector or array
 * @param {Vector3|Array} depthAxis - depth axis vector or array
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addTetrahedron = function addTetrahedron (position, color, size, heightAxis, depthAxis, name) {
    TetrahedronPrimitive.objectToShape(this, { position: position, color: color, size: size, heightAxis: heightAxis, depthAxis: depthAxis, name: name });
    return this;
};
/**
 * Add text
 * @example
 * shape.addText([ 10, -2, 4 ], [ 0.2, 0.5, 0.8 ], 0.5, "Hello");
 *
 * @param {Vector3|Array} position - position vector or array
 * @param {Color|Array} color - color object or array
 * @param {Float} size - size value
 * @param {String} text - text value
 * @return {Shape} this object
 */
Shape.prototype.addText = function addText (position, color, size, text) {
    TextPrimitive.objectToShape(this, { position: position, color: color, size: size, text: text });
    return this;
};
/**
 * Add point
 * @example
 * shape.addPoint([ 10, -2, 4 ], [ 0.2, 0.5, 0.8 ]);
 *
 * @param {Vector3|Array} position - position vector or array
 * @param {Color|Array} color - color object or array
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addPoint = function addPoint (position, color, name) {
    PointPrimitive.objectToShape(this, { position: position, color: color, name: name });
    return this;
};
/**
 * Add a wideline
 * @example
 * shape.addWideline([ 0, 2, 7 ], [ 0, 0, 9 ], [ 1, 1, 0 ]);
 *
 * @param {Vector3|Array} position1 - from position vector or array
 * @param {Vector3|Array} position2 - to position vector or array
 * @param {Color|Array} color - color object or array
 * @param {String} [name] - text
 * @return {Shape} this object
 */
Shape.prototype.addWideline = function addWideline (position1, position2, color, linewidth, name) {
    this.parameters.linewidth = linewidth;
    WidelinePrimitive.objectToShape(this, { position1: position1, position2: position2, color: color, name: name });
    return this;
};
/**
 * Deprecated, use `.addText`
 */
Shape.prototype.addLabel = function addLabel (position, color, size, text) {
    console.warn('Shape.addLabel is deprecated, use .addText instead');
    return this.addText(position, color, size, text);
};
Shape.prototype.getBufferList = function getBufferList () {
        var this$1 = this;

    var buffers = [];
    Primitives.forEach(function (P) {
        if (this$1._primitiveData[P.getShapeKey('color')].length) {
            buffers.push(P.bufferFromShape(this$1, this$1.parameters));
        }
    });
    return this.bufferList.concat(buffers);
};
Shape.prototype.dispose = function dispose () {
        var this$1 = this;

    this.bufferList.forEach(function (buffer) {
        buffer.dispose();
    });
    this.bufferList.length = 0;
    Primitives.forEach(function (P) {
        Object.keys(P.fields).forEach(function (name) {
            this$1._primitiveData[P.getShapeKey(name)].length = 0;
        });
        this$1._primitiveData[P.getShapeKey('name')].length = 0;
    });
};
prototypeAccessors$o.center.get = function () {
    if (!this._center) {
        this._center = this.boundingBox.getCenter(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]());
    }
    return this._center;
};
prototypeAccessors$o.type.get = function () { return 'Shape'; };

Object.defineProperties( Shape.prototype, prototypeAccessors$o );

/**
 * @file Buffer Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Representation for showing buffer objects. Good for efficiently showing
 * large amounts of geometric primitives e.g. spheres via {@link SphereBuffer}.
 * Smaller numbers of geometric primitives are more easily shown with help
 * from the {@link Shape} class.
 *
 * __Name:__ _buffer_
 *
 * @example
 * // add a single red sphere from a buffer to a shape instance
 * var shape = new NGL.Shape( "shape" );
 * var sphereBuffer = new NGL.SphereBuffer( {
 *     position: new Float32Array( [ 0, 0, 0 ] ),
 *     color: new Float32Array( [ 1, 0, 0 ] ),
 *     radius: new Float32Array( [ 1 ] )
 * } );
 * shape.addBuffer( sphereBuffer );
 * var shapeComp = stage.addComponentFromObject( shape );
 * shapeComp.addRepresentation( "buffer" );
 *
 * @example
 * // add a single red sphere from a buffer to a structure component instance
 * stage.loadFile( "rcsb://1crn" ).then( function( o ){
 *     var sphereBuffer = new NGL.SphereBuffer( {
 *         position: new Float32Array( [ 0, 0, 0 ] ),
 *         color: new Float32Array( [ 1, 0, 0 ] ),
 *         radius: new Float32Array( [ 1 ] )
 *     } );
 *     o.addBufferRepresentation( sphereBuffer, { opacity: 0.5 } );
 * } );
 */
var BufferRepresentation = /*@__PURE__*/(function (Representation$$1) {
    function BufferRepresentation(buffer, viewer, params) {
        if (!Array.isArray(buffer)) {
            buffer = [buffer];
        }
        Representation$$1.call(this, buffer, viewer, params);
        this.type = 'buffer';
        this.parameters = Object.assign({}, this.parameters, {
            colorScheme: null,
            colorScale: null,
            colorValue: null,
            colorDomain: null,
            colorMode: null
        });
        this.buffer = buffer;
        this.init(params);
    }

    if ( Representation$$1 ) BufferRepresentation.__proto__ = Representation$$1;
    BufferRepresentation.prototype = Object.create( Representation$$1 && Representation$$1.prototype );
    BufferRepresentation.prototype.constructor = BufferRepresentation;
    BufferRepresentation.prototype.init = function init (params) {
        Representation$$1.prototype.init.call(this, params);
        this.build();
    };
    BufferRepresentation.prototype.create = function create () {
        this.bufferList.push.apply(this.bufferList, this.buffer);
    };
    BufferRepresentation.prototype.attach = function attach (callback) {
        var this$1 = this;

        this.bufferList.forEach(function (buffer) {
            this$1.viewer.add(buffer);
            buffer.setParameters(this$1.getBufferParams());
        });
        this.setVisibility(this.visible);
        callback();
    };

    return BufferRepresentation;
}(Representation));

/**
 * @file Geometry Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var matrix$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var normalMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["x" /* Matrix3 */]();
function getData(data, geo) {
    var geoPosition = geo.attributes.position.array;
    var geoIndex = geo.index ? geo.index.array : undefined;
    var n = data.position.length / 3;
    var m = geoPosition.length / 3;
    var size = n * m;
    var meshPosition = new Float32Array(size * 3);
    var meshNormal = new Float32Array(size * 3);
    var meshColor = new Float32Array(size * 3);
    var meshIndex;
    if (geoIndex) {
        meshIndex = getUintArray(n * geoIndex.length, size);
    }
    return {
        position: meshPosition,
        color: meshColor,
        index: meshIndex,
        normal: meshNormal,
        primitiveId: data.primitiveId || serialBlockArray(n, m),
        picking: data.picking
    };
}
/**
 * Geometry buffer. Base class for geometry-based buffers. Used to draw
 * geometry primitives given a mesh.
 * @interface
 */
var GeometryBuffer = /*@__PURE__*/(function (MeshBuffer$$1) {
    function GeometryBuffer(data, params, geo) {
        if ( params === void 0 ) params = {};

        MeshBuffer$$1.call(this, getData(data, geo), params);
        this.updateNormals = false;
        var geoPosition = geo.attributes.position.array;
        var geoNormal = geo.attributes.normal.array;
        var geoIndex = geo.index ? geo.index.array : undefined;
        this.geoPosition = geoPosition;
        this.geoNormal = geoNormal;
        this.geoIndex = geoIndex;
        this.positionCount = data.position.length / 3;
        this.geoPositionCount = geoPosition.length / 3;
        this.transformedGeoPosition = new Float32Array(this.geoPositionCount * 3);
        this.transformedGeoNormal = new Float32Array(this.geoPositionCount * 3);
        var attributes = this.geometry.attributes; // TODO
        this.meshPosition = attributes.position.array;
        this.meshColor = attributes.color.array;
        this.meshNormal = attributes.normal.array;
        this.setAttributes(data);
        if (geoIndex) {
            var index = this.geometry.getIndex();
            if (!index) {
                Log.error('Index is null');
                return;
            }
            this.meshIndex = index.array;
            this.makeIndex();
        }
    }

    if ( MeshBuffer$$1 ) GeometryBuffer.__proto__ = MeshBuffer$$1;
    GeometryBuffer.prototype = Object.create( MeshBuffer$$1 && MeshBuffer$$1.prototype );
    GeometryBuffer.prototype.constructor = GeometryBuffer;
    GeometryBuffer.prototype.setAttributes = function setAttributes (data, initNormals) {
        if ( data === void 0 ) data = {};
        if ( initNormals === void 0 ) initNormals = false;

        var attributes = this.geometry.attributes; // TODO
        var position, color;
        var geoPosition, geoNormal;
        var transformedGeoPosition, transformedGeoNormal;
        var meshPosition, meshColor, meshNormal;
        var updateNormals = this.updateNormals;
        if (data.position) {
            position = data.position;
            geoPosition = this.geoPosition;
            meshPosition = this.meshPosition;
            transformedGeoPosition = this.transformedGeoPosition;
            attributes.position.needsUpdate = true;
            if (updateNormals || initNormals) {
                geoNormal = this.geoNormal;
                meshNormal = this.meshNormal;
                transformedGeoNormal = this.transformedGeoNormal;
                attributes.normal.needsUpdate = true;
            }
        }
        if (data.color) {
            color = data.color;
            meshColor = this.meshColor;
            attributes.color.needsUpdate = true;
        }
        var n = this.positionCount;
        var m = this.geoPositionCount;
        for (var i = 0; i < n; ++i) {
            var j = (void 0), l = (void 0);
            var k = i * m * 3;
            var i3 = i * 3;
            if (position && transformedGeoPosition && meshPosition && meshNormal && geoPosition && geoNormal) {
                transformedGeoPosition.set(geoPosition);
                matrix$1.makeTranslation(position[i3], position[i3 + 1], position[i3 + 2]);
                this.applyPositionTransform(matrix$1, i, i3);
                applyMatrix4toVector3array(matrix$1.elements, transformedGeoPosition);
                meshPosition.set(transformedGeoPosition, k);
                if (updateNormals && transformedGeoNormal) {
                    transformedGeoNormal.set(geoNormal);
                    normalMatrix.getNormalMatrix(matrix$1);
                    applyMatrix3toVector3array(normalMatrix.elements, transformedGeoNormal);
                    meshNormal.set(transformedGeoNormal, k);
                }
                else if (initNormals) {
                    meshNormal.set(geoNormal, k);
                }
            }
            if (color && meshColor) {
                for (j = 0; j < m; ++j) {
                    l = k + 3 * j;
                    meshColor[l] = color[i3];
                    meshColor[l + 1] = color[i3 + 1];
                    meshColor[l + 2] = color[i3 + 2];
                }
            }
        }
    };
    GeometryBuffer.prototype.makeIndex = function makeIndex () {
        var geoIndex = this.geoIndex;
        var meshIndex = this.meshIndex;
        if (!geoIndex)
            { return; }
        var n = this.positionCount;
        var m = this.geoPositionCount;
        var o = geoIndex.length / 3;
        var o3 = o * 3;
        for (var i = 0; i < n; ++i) {
            var j = i * o3;
            var q = j + o3;
            meshIndex.set(geoIndex, j);
            for (var p = j; p < q; ++p)
                { meshIndex[p] += i * m; }
        }
    };

    return GeometryBuffer;
}(MeshBuffer));

/**
 * @file Sphere Geometry Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var scale$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var SphereGeometryBufferDefaultParameters = Object.assign({
    sphereDetail: 1
}, BufferDefaultParameters);
/**
 * Sphere geometry buffer.
 *
 * @example
 * var sphereGeometryBuffer = new SphereGeometryBuffer({
 *   position: new Float32Array([ 0, 0, 0 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   radius: new Float32Array([ 1 ])
 * });
 */
var SphereGeometryBuffer = /*@__PURE__*/(function (GeometryBuffer$$1) {
    function SphereGeometryBuffer(data, params) {
        if ( params === void 0 ) params = {};

        GeometryBuffer$$1.call(this, data, params, new __WEBPACK_IMPORTED_MODULE_0_three__["u" /* IcosahedronBufferGeometry */](1, defaults(params.sphereDetail, 1)));
        this.setAttributes(data, true);
    }

    if ( GeometryBuffer$$1 ) SphereGeometryBuffer.__proto__ = GeometryBuffer$$1;
    SphereGeometryBuffer.prototype = Object.create( GeometryBuffer$$1 && GeometryBuffer$$1.prototype );
    SphereGeometryBuffer.prototype.constructor = SphereGeometryBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return SphereGeometryBufferDefaultParameters; };
    SphereGeometryBuffer.prototype.applyPositionTransform = function applyPositionTransform (matrix, i) {
        var r = this._radius[i];
        scale$1.set(r, r, r);
        matrix.scale(scale$1);
    };
    SphereGeometryBuffer.prototype.setAttributes = function setAttributes (data, initNormals) {
        if ( data === void 0 ) data = {};

        if (data.radius)
            { this._radius = data.radius; }
        GeometryBuffer$$1.prototype.setAttributes.call(this, data, initNormals);
    };

    Object.defineProperties( SphereGeometryBuffer.prototype, prototypeAccessors );

    return SphereGeometryBuffer;
}(GeometryBuffer));

ShaderRegistry.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}");

ShaderRegistry.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}");

/**
 * @file Mapped Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Mapped buffer. Sends mapping attribute to the GPU and repeats data in
 * others attributes. Used to render imposters.
 * @interface
 */
var MappedBuffer = /*@__PURE__*/(function (Buffer$$1) {
    function MappedBuffer(mappingType, data, params) {
        if ( params === void 0 ) params = {};

        Buffer$$1.call(this, data, params);
        this.index = getUintArray(this.indexSize, this.attributeSize);
        this.makeIndex();
        this.initIndex(this.index);
        this.addAttributes({
            'mapping': { type: mappingType, value: null }
        });
        this.setAttributes({ primitiveId: serialArray(this.size) });
    }

    if ( Buffer$$1 ) MappedBuffer.__proto__ = Buffer$$1;
    MappedBuffer.prototype = Object.create( Buffer$$1 && Buffer$$1.prototype );
    MappedBuffer.prototype.constructor = MappedBuffer;

    var prototypeAccessors = { attributeSize: { configurable: true },indexSize: { configurable: true } };
    prototypeAccessors.attributeSize.get = function () {
        return this.size * this.mappingSize;
    };
    prototypeAccessors.indexSize.get = function () {
        return this.size * this.mappingIndicesSize;
    };
    MappedBuffer.prototype.addAttributes = function addAttributes (attributes) {
        var nullValueAttributes = {};
        for (var name in attributes) {
            var a = attributes[name];
            nullValueAttributes[name] = {
                type: a.type,
                value: null
            };
        }
        Buffer$$1.prototype.addAttributes.call(this, nullValueAttributes);
    };
    MappedBuffer.prototype.getAttributeIndex = function getAttributeIndex (dataIndex) {
        return dataIndex * 3 * this.mappingSize;
    };
    MappedBuffer.prototype.setAttributes = function setAttributes (data) {
        if (data && !data.position && data.position1 && data.position2) {
            data.position = calculateCenterArray(data.position1, data.position2);
        }
        var size = this.size;
        var mappingSize = this.mappingSize;
        var attributes = this.geometry.attributes; // TODO
        var a, d, itemSize, array, n, i, j;
        for (var name in data) {
            if (name === 'index' || name === 'picking')
                { continue; }
            d = data[name];
            a = attributes[name];
            itemSize = a.itemSize;
            array = a.array;
            for (var k = 0; k < size; ++k) {
                n = k * itemSize;
                i = n * mappingSize;
                for (var l = 0; l < mappingSize; ++l) {
                    j = i + (itemSize * l);
                    for (var m = 0; m < itemSize; ++m) {
                        array[j + m] = d[n + m];
                    }
                }
            }
            a.needsUpdate = true;
        }
    };
    MappedBuffer.prototype.makeMapping = function makeMapping () {
        var size = this.size;
        var mapping = this.mapping;
        var mappingSize = this.mappingSize;
        var mappingItemSize = this.mappingItemSize;
        var attributes = this.geometry.attributes; // TODO
        var aMapping = attributes.mapping.array;
        for (var v = 0; v < size; v++) {
            aMapping.set(mapping, v * mappingItemSize * mappingSize);
        }
    };
    MappedBuffer.prototype.makeIndex = function makeIndex () {
        var size = this.size;
        var mappingSize = this.mappingSize;
        var mappingIndices = this.mappingIndices;
        var mappingIndicesSize = this.mappingIndicesSize;
        var index = this.index;
        for (var v = 0; v < size; v++) {
            var ix = v * mappingIndicesSize;
            var it = v * mappingSize;
            index.set(mappingIndices, ix);
            for (var s = 0; s < mappingIndicesSize; ++s) {
                index[ix + s] += it;
            }
        }
    };

    Object.defineProperties( MappedBuffer.prototype, prototypeAccessors );

    return MappedBuffer;
}(Buffer));

/**
 * @file Mapped Quad Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var mapping = new Float32Array([
    -1.0, 1.0,
    -1.0, -1.0,
    1.0, 1.0,
    1.0, -1.0
]);
var mappingIndices = new Uint16Array([
    0, 1, 2,
    1, 3, 2
]);
/**
 * Mapped Quad buffer. Draws screen-aligned quads. Used to render impostors.
 * @interface
 */
var MappedQuadBuffer = /*@__PURE__*/(function (MappedBuffer$$1) {
    function MappedQuadBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MappedBuffer$$1.call(this, 'v2', data, params);
    }

    if ( MappedBuffer$$1 ) MappedQuadBuffer.__proto__ = MappedBuffer$$1;
    MappedQuadBuffer.prototype = Object.create( MappedBuffer$$1 && MappedBuffer$$1.prototype );
    MappedQuadBuffer.prototype.constructor = MappedQuadBuffer;

    var prototypeAccessors = { mapping: { configurable: true },mappingIndices: { configurable: true },mappingIndicesSize: { configurable: true },mappingSize: { configurable: true },mappingItemSize: { configurable: true } };
    prototypeAccessors.mapping.get = function () { return mapping; };
    prototypeAccessors.mappingIndices.get = function () { return mappingIndices; };
    prototypeAccessors.mappingIndicesSize.get = function () { return 6; };
    prototypeAccessors.mappingSize.get = function () { return 4; };
    prototypeAccessors.mappingItemSize.get = function () { return 2; };

    Object.defineProperties( MappedQuadBuffer.prototype, prototypeAccessors );

    return MappedQuadBuffer;
}(MappedBuffer));

/**
 * @file Sphere Impostor Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Sphere impostor buffer.
 *
 * @example
 * var sphereImpostorBuffer = new SphereImpostorBuffer({
 *   position: new Float32Array([ 0, 0, 0 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   radius: new Float32Array([ 1 ])
 * });
 */
var SphereImpostorBuffer = /*@__PURE__*/(function (MappedQuadBuffer$$1) {
    function SphereImpostorBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MappedQuadBuffer$$1.call(this, data, params);
        this.isImpostor = true;
        this.vertexShader = 'SphereImpostor.vert';
        this.fragmentShader = 'SphereImpostor.frag';
        this.addUniforms({
            'projectionMatrixInverse': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]() },
            'ortho': { value: 0.0 }
        });
        this.addAttributes({
            'radius': { type: 'f', value: null }
        });
        this.setAttributes(data);
        this.makeMapping();
    }

    if ( MappedQuadBuffer$$1 ) SphereImpostorBuffer.__proto__ = MappedQuadBuffer$$1;
    SphereImpostorBuffer.prototype = Object.create( MappedQuadBuffer$$1 && MappedQuadBuffer$$1.prototype );
    SphereImpostorBuffer.prototype.constructor = SphereImpostorBuffer;

    return SphereImpostorBuffer;
}(MappedQuadBuffer));

/**
 * @file Sphere Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var SphereBufferDefaultParameters = Object.assign({
    disableImpostor: false
}, SphereGeometryBufferDefaultParameters);
/**
 * Sphere buffer. Depending on the value {@link ExtensionFragDepth} and
 * `params.disableImpostor` the constructor returns either a
 * {@link SphereGeometryBuffer} or a {@link SphereImpostorBuffer}
 * @implements {Buffer}
 *
 * @example
 * var sphereBuffer = new SphereBuffer( {
 *     position: new Float32Array( [ 0, 0, 0 ] ),
 *     color: new Float32Array( [ 1, 0, 0 ] ),
 *     radius: new Float32Array( [ 1 ] )
 * } );
 */
var SphereBuffer = function SphereBuffer(data, params) {
    if (!ExtensionFragDepth || (params && params.disableImpostor)) {
        return new SphereGeometryBuffer(data, params);
    }
    else {
        return new SphereImpostorBuffer(data, params);
    }
};
BufferRegistry.add('sphere', SphereBuffer);

ShaderRegistry.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}");

ShaderRegistry.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}");

/**
 * @file Point Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function distance(x0, y0, x1, y1) {
    var dx = x1 - x0;
    var dy = y1 - y0;
    return Math.sqrt(dx * dx + dy * dy);
}
function makePointTexture(params) {
    var p = params || {};
    var width = defaults(p.width, 256);
    var height = defaults(p.height, 256);
    var center = [width / 2, height / 2];
    var radius = Math.min(width / 2, height / 2);
    var delta = defaults(p.delta, 1 / (radius + 1)) * radius;
    var x = 0;
    var y = 0;
    var data = new Uint8Array(width * height * 4);
    for (var i = 0, il = data.length; i < il; i += 4) {
        var dist = distance(x, y, center[0], center[1]);
        var value = 1 - smoothstep(radius - delta, radius, dist);
        data[i] = value * 255;
        data[i + 1] = value * 255;
        data[i + 2] = value * 255;
        data[i + 3] = value * 255;
        if (++x === width) {
            x = 0;
            y++;
        }
    }
    var tex = new __WEBPACK_IMPORTED_MODULE_0_three__["l" /* DataTexture */](data, width, height);
    tex.needsUpdate = true;
    return tex;
}
var PointBufferDefaultParameters = Object.assign({
    pointSize: 1,
    sizeAttenuation: true,
    sortParticles: false,
    alphaTest: 0.5,
    useTexture: false,
    forceTransparent: false,
    edgeBleach: 0.0
}, BufferDefaultParameters);
var PointBufferParameterTypes = Object.assign({
    pointSize: { uniform: 'size' },
    sizeAttenuation: { updateShader: true },
    sortParticles: {},
    alphaTest: { updateShader: true },
    useTexture: { updateShader: true },
    forceTransparent: {},
    edgeBleach: { uniform: true }
}, BufferParameterTypes);
/**
 * Point buffer. Draws points. Optionally textured.
 *
 * @example
 * var pointBuffer = new PointBuffer( {
 *     position: new Float32Array( [ 0, 0, 0 ] ),
 *     color: new Float32Array( [ 1, 0, 0 ] )
 * } );
 */
var PointBuffer = /*@__PURE__*/(function (Buffer$$1) {
    function PointBuffer(data, params) {
        if ( params === void 0 ) params = {};

        Buffer$$1.call(this, data, params);
        this.parameterTypes = PointBufferParameterTypes;
        this.vertexShader = 'Point.vert';
        this.fragmentShader = 'Point.frag';
        this.isPoint = true;
        this.addUniforms({
            'size': { value: this.parameters.pointSize },
            'canvasHeight': { value: 1.0 },
            'pixelRatio': { value: 1.0 },
            'map': { value: null }
        });
    }

    if ( Buffer$$1 ) PointBuffer.__proto__ = Buffer$$1;
    PointBuffer.prototype = Object.create( Buffer$$1 && Buffer$$1.prototype );
    PointBuffer.prototype.constructor = PointBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return PointBufferDefaultParameters; };
    PointBuffer.prototype.makeMaterial = function makeMaterial () {
        Buffer$$1.prototype.makeMaterial.call(this);
        this.makeTexture();
        var m = this.material;
        var wm = this.wireframeMaterial;
        var pm = this.pickingMaterial;
        m.uniforms.map.value = this.tex;
        m.needsUpdate = true;
        wm.uniforms.map.value = this.tex;
        wm.needsUpdate = true;
        pm.uniforms.map.value = this.tex;
        pm.needsUpdate = true;
    };
    PointBuffer.prototype.makeTexture = function makeTexture () {
        if (this.tex)
            { this.tex.dispose(); }
        this.tex = makePointTexture({ delta: this.parameters.edgeBleach });
    };
    PointBuffer.prototype.getDefines = function getDefines (type) {
        var defines = Buffer$$1.prototype.getDefines.call(this, type);
        if (this.parameters.sizeAttenuation) {
            defines.USE_SIZEATTENUATION = 1;
        }
        if (this.parameters.useTexture) {
            defines.USE_MAP = 1;
        }
        if (this.parameters.alphaTest > 0 && this.parameters.alphaTest <= 1) {
            defines.ALPHATEST = this.parameters.alphaTest.toPrecision(2);
        }
        return defines;
    };
    PointBuffer.prototype.setUniforms = function setUniforms (data) {
        if (data && data.edgeBleach !== undefined) {
            this.makeTexture();
            data.map = this.tex;
        }
        Buffer$$1.prototype.setUniforms.call(this, data);
    };
    PointBuffer.prototype.dispose = function dispose () {
        Buffer$$1.prototype.dispose.call(this);
        if (this.tex)
            { this.tex.dispose(); }
    };

    Object.defineProperties( PointBuffer.prototype, prototypeAccessors );

    return PointBuffer;
}(Buffer));
BufferRegistry.add('point', PointBuffer);

/**
 * @file Dot Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Dot representation
 */
var DotRepresentation = /*@__PURE__*/(function (Representation$$1) {
    function DotRepresentation(surface, viewer, params) {
        Representation$$1.call(this, surface, viewer, params);
        this.type = 'dot';
        this.parameters = Object.assign({
            thresholdType: {
                type: 'select',
                rebuild: true,
                options: {
                    'value': 'value', 'sigma': 'sigma'
                }
            },
            thresholdMin: {
                type: 'number', precision: 3, max: Infinity, min: -Infinity, rebuild: true
            },
            thresholdMax: {
                type: 'number', precision: 3, max: Infinity, min: -Infinity, rebuild: true
            },
            thresholdOut: {
                type: 'boolean', rebuild: true
            },
            dotType: {
                type: 'select',
                rebuild: true,
                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.0, min: 0.001, property: 'size'
            },
            scale: {
                type: 'number', precision: 3, max: 10.0, min: 0.001
            },
            sphereDetail: true,
            disableImpostor: true,
            pointSize: {
                type: 'number', precision: 1, max: 100, min: 0, buffer: true
            },
            sizeAttenuation: {
                type: 'boolean', buffer: true
            },
            sortParticles: {
                type: 'boolean', rebuild: true
            },
            useTexture: {
                type: 'boolean', buffer: true
            },
            alphaTest: {
                type: 'range', step: 0.001, max: 1, min: 0, buffer: true
            },
            forceTransparent: {
                type: 'boolean', buffer: true
            },
            edgeBleach: {
                type: 'range', step: 0.001, max: 1, min: 0, buffer: true
            }
        }, this.parameters, {
            colorScheme: {
                type: 'select',
                update: 'color',
                options: {
                    '': '',
                    'value': 'value',
                    'uniform': 'uniform',
                    'random': 'random'
                }
            }
        });
        if (surface instanceof Volume) {
            this.surface = undefined;
            this.volume = new FilteredVolume(surface);
        }
        else {
            this.surface = surface;
            this.volume = undefined;
        }
        this.init(params);
    }

    if ( Representation$$1 ) DotRepresentation.__proto__ = Representation$$1;
    DotRepresentation.prototype = Object.create( Representation$$1 && Representation$$1.prototype );
    DotRepresentation.prototype.constructor = DotRepresentation;
    DotRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.colorScheme = defaults(p.colorScheme, 'uniform');
        p.colorValue = defaults(p.colorValue, 0xDDDDDD);
        this.thresholdType = defaults(p.thresholdType, 'sigma');
        this.thresholdMin = defaults(p.thresholdMin, 2.0);
        this.thresholdMax = defaults(p.thresholdMax, Infinity);
        this.thresholdOut = defaults(p.thresholdOut, false);
        this.dotType = defaults(p.dotType, 'point');
        this.radius = defaults(p.radius, 0.1);
        this.scale = defaults(p.scale, 1.0);
        this.pointSize = defaults(p.pointSize, 1);
        this.sizeAttenuation = defaults(p.sizeAttenuation, true);
        this.sortParticles = defaults(p.sortParticles, false);
        this.useTexture = defaults(p.useTexture, false);
        this.alphaTest = defaults(p.alphaTest, 0.5);
        this.forceTransparent = defaults(p.forceTransparent, false);
        this.edgeBleach = defaults(p.edgeBleach, 0.0);
        Representation$$1.prototype.init.call(this, p);
        this.build();
    };
    DotRepresentation.prototype.attach = function attach (callback) {
        var this$1 = this;

        this.bufferList.forEach(function (buffer) {
            this$1.viewer.add(buffer);
        });
        this.setVisibility(this.visible);
        callback();
    };
    DotRepresentation.prototype.create = function create () {
        var dotData = {};
        if (this.volume) {
            var volume = this.volume;
            var thresholdMin, thresholdMax;
            if (this.thresholdType === 'sigma') {
                thresholdMin = volume.getValueForSigma(this.thresholdMin);
                thresholdMax = volume.getValueForSigma(this.thresholdMax);
            }
            else {
                thresholdMin = this.thresholdMin;
                thresholdMax = this.thresholdMax;
            }
            volume.setFilter(thresholdMin, thresholdMax, this.thresholdOut);
            Object.assign(dotData, {
                position: volume.getDataPosition(),
                color: volume.getDataColor(this.getColorParams())
            });
            if (this.dotType === 'sphere') {
                Object.assign(dotData, {
                    radius: volume.getDataSize(this.radius, this.scale),
                    picking: volume.getDataPicking()
                });
            }
        }
        else {
            var surface = this.surface;
            Object.assign(dotData, {
                position: surface.getPosition(),
                color: surface.getColor(this.getColorParams())
            });
            if (this.dotType === 'sphere') {
                Object.assign(dotData, {
                    radius: surface.getSize(this.radius, this.scale),
                    picking: surface.getPicking()
                });
            }
        }
        if (this.dotType === 'sphere') {
            this.dotBuffer = new SphereBuffer(dotData, this.getBufferParams({
                sphereDetail: this.sphereDetail,
                disableImpostor: this.disableImpostor,
                dullInterior: false
            }));
        }
        else {
            this.dotBuffer = new PointBuffer(dotData, 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);
    };
    DotRepresentation.prototype.update = function update (what) {
        if ( what === void 0 ) what = {};

        if (this.bufferList.length === 0)
            { return; }
        var dotData = {};
        if (what.color) {
            if (this.volume) {
                Object.assign(dotData, {
                    color: this.volume.getDataColor(this.getColorParams())
                });
            }
            else {
                Object.assign(dotData, {
                    color: this.surface.getColor(this.getColorParams())
                });
            }
        }
        if (this.dotType === 'sphere' && (what.radius || what.scale)) {
            if (this.volume) {
                Object.assign(dotData, {
                    radius: this.volume.getDataSize(this.radius, this.scale)
                });
            }
            else {
                Object.assign(dotData, {
                    radius: this.surface.getSize(this.radius, this.scale)
                });
            }
        }
        this.dotBuffer.setAttributes(dotData);
    };
    DotRepresentation.prototype.setParameters = function setParameters (params, what, rebuild) {
        if ( what === void 0 ) what = {};

        if (params && params.thresholdType !== undefined &&
            this.volume instanceof Volume) {
            if (this.thresholdType === 'value' &&
                params.thresholdType === 'sigma') {
                this.thresholdMin = this.volume.getSigmaForValue(this.thresholdMin);
                this.thresholdMax = this.volume.getSigmaForValue(this.thresholdMax);
            }
            else if (this.thresholdType === 'sigma' &&
                params.thresholdType === 'value') {
                this.thresholdMin = this.volume.getValueForSigma(this.thresholdMin);
                this.thresholdMax = this.volume.getValueForSigma(this.thresholdMax);
            }
            this.thresholdType = params.thresholdType;
        }
        if (params && params.radiusType !== undefined) {
            if (params.radiusType === 'radius') {
                this.radius = 0.1;
            }
            else {
                this.radius = parseFloat(params.radiusType);
            }
            what.radius = true;
            if (this.dotType === 'sphere' &&
                (!ExtensionFragDepth || this.disableImpostor)) {
                rebuild = true;
            }
        }
        if (params && params.radius !== undefined) {
            what.radius = true;
            if (this.dotType === 'sphere' &&
                (!ExtensionFragDepth || this.disableImpostor)) {
                rebuild = true;
            }
        }
        if (params && params.scale !== undefined) {
            what.scale = true;
            if (this.dotType === 'sphere' &&
                (!ExtensionFragDepth || this.disableImpostor)) {
                rebuild = true;
            }
        }
        Representation$$1.prototype.setParameters.call(this, params, what, rebuild);
        return this;
    };

    return DotRepresentation;
}(Representation));

ShaderRegistry.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}");

ShaderRegistry.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}");

/**
 * @file Image Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var quadIndices = new Uint16Array([
    0, 1, 2,
    1, 3, 2
]);
var quadUvs = new Float32Array([
    0, 1,
    0, 0,
    1, 1,
    1, 0
]);
var ImageBufferDefaultParameters = Object.assign({
    filter: 'nearest',
    forceTransparent: true
}, BufferDefaultParameters);
var ImageBufferParameterTypes = Object.assign({
    filter: { updateShader: true, uniform: true }
}, BufferParameterTypes);
/**
 * Image buffer. Draw a single image. Optionally interpolate.
 */
var ImageBuffer = /*@__PURE__*/(function (Buffer$$1) {
    function ImageBuffer(data, params) {
        Buffer$$1.call(this, {
            position: data.position,
            index: quadIndices,
            picking: data.picking
        }, params);
        this.parameterTypes = ImageBufferParameterTypes;
        this.alwaysTransparent = true;
        this.hasWireframe = false;
        this.vertexShader = 'Image.vert';
        this.fragmentShader = 'Image.frag';
        var imageData = data.imageData;
        var width = data.width;
        var height = data.height;
        var tex = new __WEBPACK_IMPORTED_MODULE_0_three__["l" /* DataTexture */](imageData, width, height);
        tex.flipY = true;
        this.tex = tex;
        var n = imageData.length;
        var pickingData = new Uint8Array(n);
        for (var i = 0; i < n; i += 4) {
            var j = i / 4;
            pickingData[i] = j >> 16 & 255;
            pickingData[i + 1] = j >> 8 & 255;
            pickingData[i + 2] = j & 255;
        }
        var pickingTex = new __WEBPACK_IMPORTED_MODULE_0_three__["l" /* DataTexture */](pickingData, width, height);
        pickingTex.flipY = true;
        pickingTex.minFilter = __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */];
        pickingTex.magFilter = __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */];
        this.pickingTex = pickingTex;
        this.addUniforms({
            'map': { value: tex },
            'pickingMap': { value: pickingTex },
            'mapSize': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */](width, height) }
        });
        this.geometry.setAttribute('uv', new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](quadUvs, 2));
    }

    if ( Buffer$$1 ) ImageBuffer.__proto__ = Buffer$$1;
    ImageBuffer.prototype = Object.create( Buffer$$1 && Buffer$$1.prototype );
    ImageBuffer.prototype.constructor = ImageBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return ImageBufferDefaultParameters; };
    ImageBuffer.prototype.getDefines = function getDefines (type) {
        var defines = Buffer$$1.prototype.getDefines.call(this, type);
        var filter = this.parameters.filter;
        if (filter.startsWith('cubic')) {
            defines.CUBIC_INTERPOLATION = 1;
            if (filter.endsWith('bspline')) {
                defines.BSPLINE_FILTER = 1;
            }
            else if (filter.endsWith('catmulrom')) {
                defines.CATMULROM_FILTER = 1;
            }
            else if (filter.endsWith('mitchell')) {
                defines.MITCHELL_FILTER = 1;
            }
        }
        return defines;
    };
    ImageBuffer.prototype.updateTexture = function updateTexture () {
        var tex = this.tex;
        var filter = this.parameters.filter;
        if (filter.startsWith('cubic')) {
            tex.minFilter = __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */];
            tex.magFilter = __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */];
        }
        else if (filter === 'linear') {
            tex.minFilter = __WEBPACK_IMPORTED_MODULE_0_three__["w" /* LinearFilter */];
            tex.magFilter = __WEBPACK_IMPORTED_MODULE_0_three__["w" /* LinearFilter */];
        }
        else { // filter === "nearest"
            tex.minFilter = __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */];
            tex.magFilter = __WEBPACK_IMPORTED_MODULE_0_three__["A" /* NearestFilter */];
        }
        tex.needsUpdate = true;
        this.pickingTex.needsUpdate = true;
    };
    ImageBuffer.prototype.makeMaterial = function makeMaterial () {
        Buffer$$1.prototype.makeMaterial.call(this);
        this.updateTexture();
        var m = this.material;
        m.uniforms.map.value = this.tex;
        m.blending = __WEBPACK_IMPORTED_MODULE_0_three__["C" /* NormalBlending */];
        m.needsUpdate = true;
        var wm = this.wireframeMaterial;
        wm.uniforms.map.value = this.tex;
        wm.blending = __WEBPACK_IMPORTED_MODULE_0_three__["C" /* NormalBlending */];
        wm.needsUpdate = true;
        var pm = this.pickingMaterial;
        pm.uniforms.map.value = this.tex;
        pm.uniforms.pickingMap.value = this.pickingTex;
        pm.blending = __WEBPACK_IMPORTED_MODULE_0_three__["C" /* NormalBlending */];
        pm.needsUpdate = true;
    };
    ImageBuffer.prototype.setUniforms = function setUniforms (data) {
        if (data && data.filter !== undefined) {
            this.updateTexture();
            data.map = this.tex;
        }
        Buffer$$1.prototype.setUniforms.call(this, data);
    };

    Object.defineProperties( ImageBuffer.prototype, prototypeAccessors );

    return ImageBuffer;
}(Buffer));

/**
 * @file Volume Slice
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var VolumeSlice = function VolumeSlice(volume, params) {
    var p = params || {};
    this.dimension = defaults(p.dimension, 'x');
    this.positionType = defaults(p.positionType, 'percent');
    this.position = defaults(p.position, 30);
    this.thresholdType = defaults(p.thresholdType, 'sigma');
    this.thresholdMin = defaults(p.thresholdMin, -Infinity);
    this.thresholdMax = defaults(p.thresholdMax, Infinity);
    this.normalize = defaults(p.normalize, false);
    this.volume = volume;
};
VolumeSlice.prototype.getPositionFromCoordinate = function getPositionFromCoordinate (coord) {
    var dim = this.dimension;
    var v = this.volume;
    var m = v.matrix;
    var mp = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().setFromMatrixPosition(m)[dim];
    var ms = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().setFromMatrixScale(m)[dim];
    var vn;
    if (dim === 'x') {
        vn = v.nx;
    }
    else if (dim === 'y') {
        vn = v.ny;
    }
    else {
        vn = v.nz;
    }
    return Math.round((((coord - mp) / (vn / 100)) + 1) / ms);
};
VolumeSlice.prototype.getData = function getData (params) {
    params = params || {};
    var v = this.volume;
    var d = v.data;
    var m = v.matrix;
    var p;
    if (this.positionType === 'coordinate') {
        p = this.getPositionFromCoordinate(this.position);
    }
    else {
        p = this.position;
    }
    function pos(dimLen) {
        return Math.round((dimLen / 100) * (p - 1));
    }
    function index(x, y, z, i) {
        return (z * v.ny * v.nx + y * v.nx + x) * 3 + i;
    }
    var position = new Float32Array(4 * 3);
    var vec = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var width, height;
    var x;
    var y;
    var z;
    var x0 = 0;
    var y0 = 0;
    var z0 = 0;
    var nx = v.nx;
    var ny = v.ny;
    var nz = v.nz;
    function setVec(x, y, z, offset) {
        vec.set(x, y, z).applyMatrix4(m).toArray(position, offset);
    }
    if (this.dimension === 'x') {
        x = pos(v.nx);
        y = v.ny - 1;
        z = v.nz - 1;
        width = v.nz;
        height = v.ny;
        x0 = x;
        nx = x0 + 1;
        setVec(x, 0, 0, 0);
        setVec(x, y, 0, 3);
        setVec(x, 0, z, 6);
        setVec(x, y, z, 9);
    }
    else if (this.dimension === 'y') {
        x = v.nx - 1;
        y = pos(v.ny);
        z = v.nz - 1;
        width = v.nz;
        height = v.nx;
        y0 = y;
        ny = y0 + 1;
        setVec(0, y, 0, 0);
        setVec(x, y, 0, 3);
        setVec(0, y, z, 6);
        setVec(x, y, z, 9);
    }
    else if (this.dimension === 'z') {
        x = v.nx - 1;
        y = v.ny - 1;
        z = pos(v.nz);
        width = v.nx;
        height = v.ny;
        z0 = z;
        nz = z0 + 1;
        setVec(0, 0, z, 0);
        setVec(0, y, z, 3);
        setVec(x, 0, z, 6);
        setVec(x, y, z, 9);
    }
    var i = 0;
    var j = 0;
    var imageData = new Uint8Array(width * height * 4);
    var pickingArray = new Float32Array(width * height);
    var tMin, tMax;
    if (this.thresholdType === 'sigma') {
        tMin = v.getValueForSigma(this.thresholdMin);
        tMax = v.getValueForSigma(this.thresholdMax);
    }
    else {
        tMin = this.thresholdMin;
        tMax = this.thresholdMax;
    }
    var cp = Object.assign({}, params.colorParams, { volume: v });
    if (this.normalize) {
        cp.domain = [0, 1];
    }
    var colormaker = ColormakerRegistry$1.getScheme(cp);
    var tmp = new Float32Array(3);
    var scale$$1 = colormaker.getScale();
    var min = 0, max, diff = 0;
    if (this.normalize) {
        min = +Infinity;
        max = -Infinity;
        for (var iy = y0; iy < ny; ++iy) {
            for (var ix = x0; ix < nx; ++ix) {
                for (var iz = z0; iz < nz; ++iz) {
                    var idx = index(ix, iy, iz, 0) / 3;
                    var val = d[idx];
                    if (val < min)
                        { min = val; }
                    if (val > max)
                        { max = val; }
                }
            }
        }
        diff = max - min;
    }
    for (var iy$1 = y0; iy$1 < ny; ++iy$1) {
        for (var ix$1 = x0; ix$1 < nx; ++ix$1) {
            for (var iz$1 = z0; iz$1 < nz; ++iz$1) {
                var idx$1 = index(ix$1, iy$1, iz$1, 0) / 3;
                var val$1 = d[idx$1];
                if (this.normalize) {
                    val$1 = (val$1 - min) / diff;
                }
                colormaker.colorToArray(scale$$1(val$1), tmp);
                imageData[i] = Math.round(tmp[0] * 255);
                imageData[i + 1] = Math.round(tmp[1] * 255);
                imageData[i + 2] = Math.round(tmp[2] * 255);
                imageData[i + 3] = (val$1 > tMin && val$1 < tMax) ? 255 : 0;
                pickingArray[j] = idx$1;
                ++j;
                i += 4;
            }
        }
    }
    var picking = new SlicePicker(pickingArray, v);
    return { position: position, imageData: imageData, width: width, height: height, picking: picking };
};

/**
 * @file Slice Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Slice representation
 */
var SliceRepresentation = /*@__PURE__*/(function (Representation$$1) {
    function SliceRepresentation(volume, viewer, params) {
        Representation$$1.call(this, volume, viewer, params);
        this.type = 'slice';
        this.parameters = Object.assign({
            filter: {
                type: 'select',
                buffer: true,
                options: {
                    'nearest': 'nearest',
                    'linear': 'linear',
                    'cubic-bspline': 'cubic-bspline',
                    'cubic-catmulrom': 'cubic-catmulrom',
                    'cubic-mitchell': 'cubic-mitchell'
                }
            },
            positionType: {
                type: 'select',
                rebuild: true,
                options: {
                    'percent': 'percent', 'coordinate': 'coordinate'
                }
            },
            position: {
                type: 'range',
                step: 0.1,
                max: 100,
                min: 1,
                rebuild: true
            },
            dimension: {
                type: 'select',
                rebuild: true,
                options: {
                    'x': 'x', 'y': 'y', 'z': 'z'
                }
            },
            thresholdType: {
                type: 'select',
                rebuild: true,
                options: {
                    'value': 'value', 'sigma': 'sigma'
                }
            },
            thresholdMin: {
                type: 'number', precision: 3, max: Infinity, min: -Infinity, rebuild: true
            },
            thresholdMax: {
                type: 'number', precision: 3, max: Infinity, min: -Infinity, rebuild: true
            },
            normalize: {
                type: 'boolean', rebuild: true
            }
        }, this.parameters, {
            flatShaded: null,
            side: null,
            wireframe: null,
            linewidth: null,
            colorScheme: null,
            roughness: null,
            metalness: null,
            diffuse: null
        });
        this.volume = volume;
        this.init(params);
    }

    if ( Representation$$1 ) SliceRepresentation.__proto__ = Representation$$1;
    SliceRepresentation.prototype = Object.create( Representation$$1 && Representation$$1.prototype );
    SliceRepresentation.prototype.constructor = SliceRepresentation;
    SliceRepresentation.prototype.init = function init (params) {
        var v = this.volume;
        var p = params || {};
        p.colorDomain = defaults(p.colorDomain, [v.min, v.max]);
        p.colorScheme = defaults(p.colorScheme, 'value');
        p.colorScale = defaults(p.colorScale, 'Spectral');
        this.colorScheme = 'value';
        this.dimension = defaults(p.dimension, 'x');
        this.filter = defaults(p.filter, 'cubic-bspline');
        this.positionType = defaults(p.positionType, 'percent');
        this.position = defaults(p.position, 30);
        this.thresholdType = defaults(p.thresholdType, 'sigma');
        this.thresholdMin = defaults(p.thresholdMin, -Infinity);
        this.thresholdMax = defaults(p.thresholdMax, Infinity);
        this.normalize = defaults(p.normalize, false);
        Representation$$1.prototype.init.call(this, p);
        this.build();
    };
    SliceRepresentation.prototype.attach = function attach (callback) {
        var this$1 = this;

        this.bufferList.forEach(function (buffer) {
            this$1.viewer.add(buffer);
        });
        this.setVisibility(this.visible);
        callback();
    };
    SliceRepresentation.prototype.create = function create () {
        var volumeSlice = new VolumeSlice(this.volume, {
            positionType: this.positionType,
            position: this.position,
            dimension: this.dimension,
            thresholdType: this.thresholdType,
            thresholdMin: this.thresholdMin,
            thresholdMax: this.thresholdMax,
            normalize: this.normalize
        });
        var sliceBuffer = new ImageBuffer(volumeSlice.getData({ colorParams: this.getColorParams() }), this.getBufferParams({
            filter: this.filter
        }));
        this.bufferList.push(sliceBuffer);
    };

    return SliceRepresentation;
}(Representation));

/**
 * @file Representation Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function logReprUnknown(type) {
    Log.error(("makeRepresentation: representation type " + type + " unknown"));
}
function makeRepresentation(type, object, viewer, params) {
    if (Debug)
        { Log.time('makeRepresentation ' + type); }
    var ReprClass;
    if (object instanceof Structure) {
        ReprClass = RepresentationRegistry.get(type);
        if (!ReprClass) {
            logReprUnknown(type);
            return;
        }
    }
    else if (object instanceof Surface) {
        if (type === 'surface') {
            ReprClass = SurfaceRepresentation;
        }
        else if (type === 'dot') {
            ReprClass = DotRepresentation;
        }
        else {
            logReprUnknown(type);
            return;
        }
    }
    else if (object instanceof Volume) {
        if (type === 'surface') {
            ReprClass = SurfaceRepresentation;
        }
        else if (type === 'dot') {
            ReprClass = DotRepresentation;
        }
        else if (type === 'slice') {
            ReprClass = SliceRepresentation;
        }
        else {
            logReprUnknown(type);
            return;
        }
    }
    else if (object instanceof Shape) {
        ReprClass = BufferRepresentation;
        object = object.getBufferList();
    }
    else if (type === 'buffer') {
        ReprClass = BufferRepresentation;
    }
    else {
        Log.error('makeRepresentation: object ' + object + ' unknown');
        return;
    }
    var repr = new ReprClass(object, viewer, params);
    if (Debug)
        { Log.timeEnd('makeRepresentation ' + type); }
    return repr;
}

/**
 * @file Element
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var ElementDefaultParameters = {
    name: 'some element',
    status: ''
};
/**
 * Element base class
 */
var Element = function Element(stage, params) {
    if ( params === void 0 ) params = {};

    this.stage = stage;
    /**
     * Events emitted by the element
     */
    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 = createParams(params, this.defaultParameters);
    this.uuid = generateUUID();
};

var prototypeAccessors$p = { defaultParameters: { configurable: true },name: { configurable: true } };
prototypeAccessors$p.defaultParameters.get = function () { return ElementDefaultParameters; };
prototypeAccessors$p.name.get = function () { return this.parameters.name; };
Element.prototype.setStatus = function setStatus (value) {
    this.parameters.status = value;
    this.signals.statusChanged.dispatch(value);
    return this;
};
Element.prototype.setName = function setName (value) {
    this.parameters.name = value;
    this.signals.nameChanged.dispatch(value);
    return this;
};
Element.prototype.dispose = function dispose () {
    this.signals.disposed.dispatch();
};

Object.defineProperties( Element.prototype, prototypeAccessors$p );

/**
 * @file Representation Element
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var RepresentationElementDefaultParameters = Object.assign({
    visible: true
}, ElementDefaultParameters);
/**
 * Element wrapping a {@link Representation} object
 */
var RepresentationElement = /*@__PURE__*/(function (Element$$1) {
    function RepresentationElement(stage, repr, params, parent) {
        if ( params === void 0 ) params = {};

        Element$$1.call(this, stage, Object.assign({ name: repr.type }, params));
        this.parent = parent;
        this.signals = Object.assign({
            visibilityChanged: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"](),
            parametersChanged: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]()
        }, this.signals);
        this.setRepresentation(repr);
    }

    if ( Element$$1 ) RepresentationElement.__proto__ = Element$$1;
    RepresentationElement.prototype = Object.create( Element$$1 && Element$$1.prototype );
    RepresentationElement.prototype.constructor = RepresentationElement;

    var prototypeAccessors = { defaultParameters: { configurable: true },visible: { configurable: true },type: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return RepresentationElementDefaultParameters; };
    prototypeAccessors.visible.get = function () { return this.parameters.visible; };
    /**
     * Component type
     * @type {String}
     */
    prototypeAccessors.type.get = function () { return 'representation'; };
    RepresentationElement.prototype.getType = function getType () {
        return this.repr.type;
    };
    RepresentationElement.prototype.setRepresentation = function setRepresentation (repr) {
        this._disposeRepresentation();
        this.repr = repr;
        // this.name = repr.type;
        this.stage.tasks.listen(this.repr.tasks);
        this.updateVisibility();
    };
    RepresentationElement.prototype._disposeRepresentation = function _disposeRepresentation () {
        if (this.repr) {
            this.stage.tasks.unlisten(this.repr.tasks);
            this.repr.dispose();
        }
    };
    RepresentationElement.prototype.dispose = function dispose () {
        if (this.parent && this.parent.hasRepresentation(this)) {
            this.parent.removeRepresentation(this);
        }
        else {
            this._disposeRepresentation();
            this.signals.disposed.dispatch();
        }
    };
    /**
     * Set the visibility of the component, takes parent visibility into account
     * @param {Boolean} value - visibility flag
     * @return {RepresentationElement} this object
     */
    RepresentationElement.prototype.setVisibility = function setVisibility (value) {
        this.parameters.visible = value;
        this.updateVisibility();
        this.signals.visibilityChanged.dispatch(this.parameters.visible);
        return this;
    };
    RepresentationElement.prototype.getVisibility = function getVisibility () {
        if (this.parent) {
            return this.parent.parameters.visible && this.parameters.visible;
        }
        else {
            return this.parameters.visible;
        }
    };
    /**
     * Toggle visibility of the component, takes parent visibility into account
     * @return {RepresentationElement} this object
     */
    RepresentationElement.prototype.toggleVisibility = function toggleVisibility () {
        return this.setVisibility(!this.parameters.visible);
    };
    RepresentationElement.prototype.updateVisibility = function updateVisibility () {
        this.repr.setVisibility(this.getVisibility());
    };
    /**
     * Set selection
     * @param {Object} what - flags indicating what attributes to update
     * @param {Boolean} what.position - update position attribute
     * @param {Boolean} what.color - update color attribute
     * @param {Boolean} what.radius - update radius attribute
     * @return {RepresentationElement} this object
     */
    RepresentationElement.prototype.update = function update (what) {
        this.repr.update(what); // TODO
        return this;
    };
    RepresentationElement.prototype.build = function build (params) {
        this.repr.build(params);
        return this;
    };
    /**
     * Set selection
     * @param {String} string - selection string
     * @return {RepresentationElement} this object
     */
    RepresentationElement.prototype.setSelection = function setSelection (string) {
        var repr = this.repr; // TODO
        if (repr.setSelection) {
            repr.setSelection(string);
        }
        return this;
    };
    /**
     * Set representation parameters
     * @param {RepresentationParameters} params - parameter object
     * @return {RepresentationElement} this object
     */
    RepresentationElement.prototype.setParameters = function setParameters (params) {
        this.repr.setParameters(params);
        this.signals.parametersChanged.dispatch(this.repr.getParameters());
        return this;
    };
    /**
     * Get representation parameters
     * @return {RepresentationParameters} parameter object
     */
    RepresentationElement.prototype.getParameters = function getParameters () {
        return this.repr.getParameters();
    };
    /**
     * Set color
     * @param {String|Color|Hex} value - color value
     * @return {RepresentationElement} this object
     */
    RepresentationElement.prototype.setColor = function setColor (value) {
        this.repr.setColor(value);
        return this;
    };

    Object.defineProperties( RepresentationElement.prototype, prototypeAccessors );

    return RepresentationElement;
}(Element));

/**
 * @file Component
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var _m = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
var _v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var ComponentDefaultParameters = {
    name: '',
    status: '',
    visible: true
};
/**
 * Base class for components
 */
var Component = function Component(stage, object, params) {
    if ( params === void 0 ) params = {};

    this.stage = stage;
    this.object = object;
    /**
     * Events emitted by the component
     */
    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 __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    this.position = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.quaternion = new __WEBPACK_IMPORTED_MODULE_0_three__["J" /* Quaternion */]();
    this.scale = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](1, 1, 1);
    this.transform = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    this.parameters = createParams(params, this.defaultParameters);
    this.uuid = generateUUID();
    this.viewer = stage.viewer;
    this.controls = new ComponentControls(this);
};

var prototypeAccessors$q = { defaultParameters: { configurable: true },name: { configurable: true },status: { configurable: true },visible: { configurable: true } };
prototypeAccessors$q.defaultParameters.get = function () { return ComponentDefaultParameters; };
prototypeAccessors$q.name.get = function () { return this.parameters.name; };
prototypeAccessors$q.status.get = function () { return this.parameters.status; };
prototypeAccessors$q.visible.get = function () { return this.parameters.visible; };
/**
 * Set position transform
 *
 * @example
 * // translate by 25 angstrom along x axis
 * component.setPosition([ 25, 0, 0 ]);
 *
 * @param {Vector3|Array} p - the coordinates
 * @return {Component} this object
 */
Component.prototype.setPosition = function setPosition (p) {
    if (Array.isArray(p)) {
        this.position.fromArray(p);
    }
    else {
        this.position.copy(p);
    }
    this.updateMatrix();
    return this;
};
/**
 * Set local rotation transform
 * (for global rotation use setTransform)
 *
 * @example
 * // rotate by 2 degree radians on x axis
 * component.setRotation( [ 2, 0, 0 ] );
 *
 * @param {Quaternion|Euler|Array} r - the rotation
 * @return {Component} this object
 */
Component.prototype.setRotation = function setRotation (r) {
    if (Array.isArray(r)) {
        if (r.length === 3) {
            var e = new __WEBPACK_IMPORTED_MODULE_0_three__["n" /* Euler */]().fromArray(r);
            this.quaternion.setFromEuler(e);
        }
        else {
            this.quaternion.fromArray(r);
        }
    }
    else if (r instanceof __WEBPACK_IMPORTED_MODULE_0_three__["n" /* Euler */]) {
        this.quaternion.setFromEuler(r);
    }
    else {
        this.quaternion.copy(r);
    }
    this.updateMatrix();
    return this;
};
/**
 * Set scale transform
 *
 * @example
 * // scale by factor of two
 * component.setScale( 2 );
 *
 * @param {Number} s - the scale
 * @return {Component} this object
 */
Component.prototype.setScale = function setScale (s) {
    this.scale.set(s, s, s);
    this.updateMatrix();
    return this;
};
/**
 * Set general transform. Is applied before and in addition
 * to the position, rotation and scale transformations
 *
 * @example
 * component.setTransform( matrix );
 *
 * @param {Matrix4} m - the matrix
 * @return {Component} this object
 */
Component.prototype.setTransform = function setTransform (m) {
    this.transform.copy(m);
    this.updateMatrix();
    return this;
};
Component.prototype.updateMatrix = function updateMatrix () {
    var c = this.getCenterUntransformed(_v);
    this.matrix.makeTranslation(-c.x, -c.y, -c.z);
    _m.makeRotationFromQuaternion(this.quaternion);
    this.matrix.premultiply(_m);
    _m.makeScale(this.scale.x, this.scale.y, this.scale.z);
    this.matrix.premultiply(_m);
    var p = this.position;
    _m.makeTranslation(p.x + c.x, p.y + c.y, p.z + c.z);
    this.matrix.premultiply(_m);
    this.matrix.premultiply(this.transform);
    this.updateRepresentationMatrices();
    this.stage.viewer.updateBoundingBox();
    this.signals.matrixChanged.dispatch(this.matrix);
};
/**
 * Propogates our matrix to each representation
 */
Component.prototype.updateRepresentationMatrices = function updateRepresentationMatrices () {
        var this$1 = this;

    this.reprList.forEach(function (repr) {
        repr.setParameters({ matrix: this$1.matrix });
    });
};
/**
 * Add an anotation object
 * @param {Vector3} position - the 3d position
 * @param {String|Element} content - the HTML content
 * @param {Object} [params] - parameters
 * @param {Integer} params.offsetX - 2d offset in x direction
 * @param {Integer} params.offsetY - 2d offset in y direction
 * @return {Annotation} the added annotation object
 */
Component.prototype.addAnnotation = function addAnnotation (position, content, params) {
    var annotation = new Annotation(this, position, content, params);
    this.annotationList.push(annotation);
    return annotation;
};
/**
 * Iterator over each annotation and executing the callback
 * @param  {Function} callback - function to execute
 * @return {undefined}
 */
Component.prototype.eachAnnotation = function eachAnnotation (callback) {
    this.annotationList.slice().forEach(callback);
};
/**
 * Remove the give annotation from the component
 * @param {Annotation} annotation - the annotation to remove
 * @return {undefined}
 */
Component.prototype.removeAnnotation = function removeAnnotation (annotation) {
    var idx = this.annotationList.indexOf(annotation);
    if (idx !== -1) {
        this.annotationList.splice(idx, 1);
        annotation.dispose();
    }
};
/**
 * Remove all annotations from the component
 * @return {undefined}
 */
Component.prototype.removeAllAnnotations = function removeAllAnnotations () {
    this.eachAnnotation(function (annotation) { return annotation.dispose(); });
    this.annotationList.length = 0;
};
/**
 * Add a new representation to the component
 * @param {String} type - the name of the representation
 * @param {Object} object - the object on which the representation should be based
 * @param {RepresentationParameters} [params] - representation parameters
 * @return {RepresentationElement} the created representation wrapped into
 *                               a representation element object
 */
Component.prototype._addRepresentation = function _addRepresentation (type, object, params, hidden) {
        if ( hidden === void 0 ) hidden = false;

    var p = params || {};
    var sp = this.stage.getParameters(); // TODO
    p.matrix = this.matrix.clone();
    p.quality = p.quality || sp.quality;
    p.disableImpostor = defaults(p.disableImpostor, !sp.impostor);
    p.useWorker = defaults(p.useWorker, sp.workerDefault);
    p.visible = defaults(p.visible, true);
    var p2 = Object.assign({}, p, { visible: this.parameters.visible && p.visible });
    var repr = makeRepresentation(type, object, this.viewer, p2);
    var reprElem = new RepresentationElement(this.stage, repr, p, this);
    if (!hidden) {
        this.reprList.push(reprElem);
        this.signals.representationAdded.dispatch(reprElem);
    }
    return reprElem;
};
Component.prototype.addBufferRepresentation = function addBufferRepresentation (buffer, params) {
    return this._addRepresentation.call(this, 'buffer', buffer, params);
};
Component.prototype.hasRepresentation = function hasRepresentation (repr) {
    return this.reprList.indexOf(repr) !== -1;
};
/**
 * Iterator over each representation and executing the callback
 * @param  {Function} callback - function to execute
 * @return {undefined}
 */
Component.prototype.eachRepresentation = function eachRepresentation (callback) {
    this.reprList.slice().forEach(callback);
};
/**
 * Removes a representation component
 * @param {RepresentationElement} repr - the representation element
 * @return {undefined}
 */
Component.prototype.removeRepresentation = function removeRepresentation (repr) {
    var idx = this.reprList.indexOf(repr);
    if (idx !== -1) {
        this.reprList.splice(idx, 1);
        repr.dispose();
        this.signals.representationRemoved.dispatch(repr);
    }
};
Component.prototype.updateRepresentations = function updateRepresentations (what) {
    this.reprList.forEach(function (repr) { return repr.update(what); });
    this.stage.viewer.requestRender();
};
/**
 * Removes all representation components
 * @return {undefined}
 */
Component.prototype.removeAllRepresentations = function removeAllRepresentations () {
    this.eachRepresentation(function (repr) { return repr.dispose(); });
};
Component.prototype.dispose = function dispose () {
    this.removeAllAnnotations();
    this.removeAllRepresentations();
    delete this.annotationList;
    delete this.reprList;
    this.signals.disposed.dispatch();
};
/**
 * Set the visibility of the component, including added representations
 * @param {Boolean} value - visibility flag
 * @return {Component} this object
 */
Component.prototype.setVisibility = function setVisibility (value) {
    this.parameters.visible = value;
    this.eachRepresentation(function (repr) { return repr.updateVisibility(); });
    this.eachAnnotation(function (annotation) { return annotation.updateVisibility(); });
    this.signals.visibilityChanged.dispatch(value);
    return this;
};
Component.prototype.setStatus = function setStatus (value) {
    this.parameters.status = value;
    this.signals.statusChanged.dispatch(value);
    return this;
};
Component.prototype.setName = function setName (value) {
    this.parameters.name = value;
    this.signals.nameChanged.dispatch(value);
    return this;
};
/**
 * @return {Box3} the component's bounding box
 */
Component.prototype.getBox = function getBox () {
        var ref;

        var args = [], len = arguments.length;
        while ( len-- ) args[ len ] = arguments[ len ];
    return (ref = this).getBoxUntransformed.apply(ref, args)
        .clone().applyMatrix4(this.matrix);
};
/**
 * @return {Vector3} the component's center position
 */
Component.prototype.getCenter = function getCenter () {
        var ref;

        var args = [], len = arguments.length;
        while ( len-- ) args[ len ] = arguments[ len ];
    return (ref = this).getCenterUntransformed.apply(ref, args)
        .clone().applyMatrix4(this.matrix);
};
Component.prototype.getZoom = function getZoom () {
        var ref;

        var args = [], len = arguments.length;
        while ( len-- ) args[ len ] = arguments[ len ];
    return this.stage.getZoomForBox((ref = this).getBox.apply(ref, args));
};
/**
 * @abstract
 * @return {Box3} the untransformed component's bounding box
 */
Component.prototype.getBoxUntransformed = function getBoxUntransformed () {
        var args = [], len = arguments.length;
        while ( len-- ) args[ len ] = arguments[ len ];

    return new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
};
Component.prototype.getCenterUntransformed = function getCenterUntransformed () {
        var args = [], len = arguments.length;
        while ( len-- ) args[ len ] = arguments[ len ];

    return this.getBoxUntransformed().getCenter(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]());
};
/**
 * Automatically center and zoom the component
 * @param  {Integer} [duration] - duration of the animation, defaults to 0
 * @return {undefined}
 */
Component.prototype.autoView = function autoView (duration) {
    this.stage.animationControls.zoomMove(this.getCenter(), this.getZoom(), defaults(duration, 0));
};

Object.defineProperties( Component.prototype, prototypeAccessors$q );

/**
 * @file Collection
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Collection = function Collection(list) {
    if ( list === void 0 ) list = [];

    this.list = list;
    // remove elements from list when they get disposed
    var n = list.length;
    for (var i = 0; i < n; ++i) {
        var elm = list[i];
        elm.signals.disposed.add(this._remove, this);
    }
};

var prototypeAccessors$r = { first: { configurable: true } };
Collection.prototype._remove = function _remove (elm) {
    var idx = this.list.indexOf(elm);
    if (idx !== -1) {
        this.list.splice(idx, 1);
    }
};
prototypeAccessors$r.first.get = function () {
    return this.list.length > 0 ? this.list[0] : undefined;
};
Collection.prototype.forEach = function forEach (fn) {
    this.list.forEach(fn);
    return this;
};
Collection.prototype.dispose = function dispose () {
    return this.forEach(function (elm) { return elm.dispose(); });
};

Object.defineProperties( Collection.prototype, prototypeAccessors$r );

/**
 * @file Component Collection
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var RepresentationCollection = /*@__PURE__*/(function (Collection$$1) {
    function RepresentationCollection () {
        Collection$$1.apply(this, arguments);
    }

    if ( Collection$$1 ) RepresentationCollection.__proto__ = Collection$$1;
    RepresentationCollection.prototype = Object.create( Collection$$1 && Collection$$1.prototype );
    RepresentationCollection.prototype.constructor = RepresentationCollection;

    RepresentationCollection.prototype.setParameters = function setParameters (params) {
        return this.forEach(function (repr) { return repr.setParameters(params); });
    };
    RepresentationCollection.prototype.setVisibility = function setVisibility (value) {
        return this.forEach(function (repr) { return repr.setVisibility(value); });
    };
    RepresentationCollection.prototype.setSelection = function setSelection (string) {
        return this.forEach(function (repr) { return repr.setSelection(string); });
    };
    RepresentationCollection.prototype.setColor = function setColor (color) {
        return this.forEach(function (repr) { return repr.setColor(color); });
    };
    RepresentationCollection.prototype.update = function update (what) {
        return this.forEach(function (repr) { return repr.update(what); });
    };
    RepresentationCollection.prototype.build = function build (params) {
        return this.forEach(function (repr) { return repr.build(params); });
    };
    RepresentationCollection.prototype.dispose = function dispose (params) {
        return this.forEach(function (repr) { return repr.dispose(); });
    };

    return RepresentationCollection;
}(Collection));

/**
 * @file Trajectory Component
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Trajectory component parameter object.
 * @typedef {Object} TrajectoryComponentParameters - component parameters
 *
 * @property {String} name - component name
 * @property {Integer} initialFrame - initial frame the trajectory is set to
 * @property {Integer} defaultStep - default step size to be used by trajectory players
 * @property {Integer} defaultTimeout - default timeout to be used by trajectory players
 * @property {String} defaultInterpolateType - one of "" (empty string), "linear" or "spline"
 * @property {Integer} defaultInterpolateStep - window size used for interpolation
 * @property {String} defaultMode - either "loop" or "once"
 * @property {String} defaultDirection - either "forward" or "backward"
 */
var TrajectoryElementDefaultParameters = Object.assign({
    defaultStep: 1,
    defaultTimeout: 50,
    defaultInterpolateType: '',
    defaultInterpolateStep: 5,
    defaultMode: 'loop',
    defaultDirection: 'forward',
    initialFrame: 0
}, ElementDefaultParameters);
/**
 * Component wrapping a {@link Trajectory} object
 */
var TrajectoryElement = /*@__PURE__*/(function (Element$$1) {
    function TrajectoryElement(stage, trajectory, params) {
        var this$1 = this;
        if ( params === void 0 ) params = {};

        Element$$1.call(this, stage, Object.assign({ name: trajectory.name }, params));
        this.trajectory = trajectory;
        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"]()
        });
        // signals
        trajectory.signals.frameChanged.add(function (i) {
            this$1.signals.frameChanged.dispatch(i);
        });
        trajectory.signals.playerChanged.add(function (player) {
            this$1.signals.playerChanged.dispatch(player);
        });
        trajectory.signals.countChanged.add(function (n) {
            this$1.signals.countChanged.dispatch(n);
        });
        //
        if (params.initialFrame !== undefined) {
            this.setFrame(params.initialFrame);
        }
    }

    if ( Element$$1 ) TrajectoryElement.__proto__ = Element$$1;
    TrajectoryElement.prototype = Object.create( Element$$1 && Element$$1.prototype );
    TrajectoryElement.prototype.constructor = TrajectoryElement;

    var prototypeAccessors = { defaultParameters: { configurable: true },type: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return TrajectoryElementDefaultParameters; };
    /**
     * Component type
     * @type {String}
     */
    prototypeAccessors.type.get = function () { return 'trajectory'; };
    /**
     * Set the frame of the trajectory
     * @param {Integer} i - frame number
     * @return {undefined}
     */
    TrajectoryElement.prototype.setFrame = function setFrame (i) {
        this.trajectory.setFrame(i);
    };
    /**
     * Set trajectory parameters
     * @param {TrajectoryParameters} params - trajectory parameters
     * @return {undefined}
     */
    TrajectoryElement.prototype.setParameters = function setParameters (params) {
        if ( params === void 0 ) params = {};

        this.trajectory.setParameters(params);
        this.signals.parametersChanged.dispatch(params);
    };
    TrajectoryElement.prototype.dispose = function dispose () {
        this.trajectory.dispose();
        Element$$1.prototype.dispose.call(this);
    };

    Object.defineProperties( TrajectoryElement.prototype, prototypeAccessors );

    return TrajectoryElement;
}(Element));

/**
 * @file Frames
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Frames = function Frames(name, path) {
    this.name = name;
    this.path = path;
    this.coordinates = [];
    this.boxes = [];
    this.times = [];
    this.timeOffset = 0;
    this.deltaTime = 1;
};

var prototypeAccessors$s = { type: { configurable: true } };
prototypeAccessors$s.type.get = function () { return 'Frames'; };

Object.defineProperties( Frames.prototype, prototypeAccessors$s );

/**
 * @file Superposition
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Superposition = function Superposition(atoms1, atoms2) {
    // allocate & init data structures
    this.A = new Matrix(3, 3);
    this.W = new Matrix(1, 3);
    this.U = new Matrix(3, 3);
    this.V = new Matrix(3, 3);
    this.VH = new Matrix(3, 3);
    this.R = new Matrix(3, 3);
    this.tmp = new Matrix(3, 3);
    this.c = new Matrix(3, 3);
    var n1;
    if (atoms1 instanceof Structure) {
        n1 = atoms1.atomCount;
    }
    else if (atoms1 instanceof Float32Array) {
        n1 = atoms1.length / 3;
    }
    else {
        return;
    }
    var n2;
    if (atoms2 instanceof Structure) {
        n2 = atoms2.atomCount;
    }
    else if (atoms2 instanceof Float32Array) {
        n2 = atoms2.length / 3;
    }
    else {
        return;
    }
    var n = Math.min(n1, n2);
    var coords1 = new Matrix(3, n);
    var coords2 = new Matrix(3, n);
    this.coords1t = new Matrix(n, 3);
    this.coords2t = new Matrix(n, 3);
    this.transformationMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    this.c.data.set([1, 0, 0, 0, 1, 0, 0, 0, -1]);
    // prep coords
    this.prepCoords(atoms1, coords1, n, false);
    this.prepCoords(atoms2, coords2, n, false);
    // superpose
    this._superpose(coords1, coords2);
};
Superposition.prototype._superpose = function _superpose (coords1, coords2) {
    this.mean1 = meanRows(coords1);
    this.mean2 = meanRows(coords2);
    subRows(coords1, this.mean1);
    subRows(coords2, this.mean2);
    transpose(this.coords1t, coords1);
    transpose(this.coords2t, coords2);
    multiplyABt(this.A, this.coords2t, this.coords1t);
    svd(this.A, this.W, this.U, this.V);
    invert3x3(this.V, this.VH);
    multiply3x3(this.R, this.U, this.VH);
    if (mat3x3determinant(this.R) < 0.0) {
        if (Debug)
            { Log.log('R not a right handed system'); }
        multiply3x3(this.tmp, this.c, this.VH);
        multiply3x3(this.R, this.U, this.tmp);
    }
    //get the transformation matrix
    var transformMat_ = new Matrix(4, 4);
    var tmp_1 = new Matrix(4, 4);
    var tmp_2 = new Matrix(4, 4);
    var sub = new Matrix(4, 4);
    var mult = new Matrix(4, 4);
    var add = new Matrix(4, 4);
    var R = this.R.data;
    var M1 = this.mean1;
    var M2 = this.mean2;
    sub.data.set([1, 0, 0, -M1[0],
        0, 1, 0, -M1[1],
        0, 0, 1, -M1[2],
        0, 0, 0, 1]);
    mult.data.set([R[0], R[1], R[2], 0,
        R[3], R[4], R[5], 0,
        R[6], R[7], R[8], 0,
        0, 0, 0, 1]);
    add.data.set([1, 0, 0, M2[0],
        0, 1, 0, M2[1],
        0, 0, 1, M2[2],
        0, 0, 0, 1]);
    transpose(tmp_1, sub);
    multiplyABt(transformMat_, mult, tmp_1);
    transpose(tmp_2, transformMat_);
    multiplyABt(tmp_1, add, tmp_2);
    transpose(transformMat_, tmp_1);
    this.transformationMatrix.elements = transformMat_.data;
};
Superposition.prototype.prepCoords = function prepCoords (atoms, coords, n, is4X4) {
    var i = 0;
    var cd = coords.data;
    var c = 3;
    var d = n * 3;
    if (is4X4) {
        d = n * 4;
        c = 4;
    }
    if (atoms instanceof Structure) {
        atoms.eachAtom(function (a) {
            if (i < d) {
                cd[i + 0] = a.x;
                cd[i + 1] = a.y;
                cd[i + 2] = a.z;
                if (is4X4)
                    { cd[i + 3] = 1; }
                i += c;
            }
        });
    }
    else if (atoms instanceof Float32Array) {
        for (; i < d; i += c) {
            if (i < d) {
                cd[i] = atoms[i];
                cd[i + 1] = atoms[i + 1];
                cd[i + 2] = atoms[i + 2];
                if (is4X4)
                    { cd[i + 3] = 1; }
            }
        }
    }
    else {
        Log.warn('prepCoords: input type unknown');
    }
};
Superposition.prototype.transform = function transform (atoms) {
    // allocate data structures
    var n;
    if (atoms instanceof Structure) {
        n = atoms.atomCount;
    }
    else if (atoms instanceof Float32Array) {
        n = atoms.length / 3;
    }
    else {
        return;
    }
    var coords = new Matrix(4, n);
    var tCoords = new Matrix(n, 4);
    // prep coords
    this.prepCoords(atoms, coords, n, true);
    // check for transformation matrix correctness
    var transform = this.transformationMatrix;
    var det = transform.determinant();
    if (!det) {
        return det;
    }
    // do transform
    var mult = new Matrix(4, 4);
    mult.data = transform.elements;
    multiply(tCoords, coords, mult);
    var i = 0;
    var cd = tCoords.data;
    if (atoms instanceof Structure) {
        atoms.eachAtom(function (a) {
            a.x = cd[i];
            a.y = cd[i + 1];
            a.z = cd[i + 2];
            i += 4;
        });
        //update transformation matrices for each assembly
        var invertTrasform = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
        invertTrasform.getInverse(transform);
        var biomolDict = atoms.biomolDict;
        for (var key in biomolDict) {
            if (biomolDict.hasOwnProperty(key)) {
                var assembly = biomolDict[key];
                assembly.partList.forEach(function (part) {
                    part.matrixList.forEach(function (mat) {
                        mat.premultiply(transform);
                        mat.multiply(invertTrasform);
                    });
                });
            }
        }
    }
    else if (atoms instanceof Float32Array) {
        var n4 = n * 4;
        for (; i < n4; i += 4) {
            atoms[i] = cd[i];
            atoms[i + 1] = cd[i + 1];
            atoms[i + 2] = cd[i + 2];
        }
    }
    else {
        Log.warn('transform: input type unknown');
    }
    return this.transformationMatrix;
};

/**
 * @file Trajectory Player
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var TrajectoryPlayerDefaultParameters = {
    step: 1,
    timeout: 50,
    start: 0,
    end: 0,
    interpolateType: '',
    interpolateStep: 5,
    mode: 'loop',
    direction: 'forward'
};
/**
 * Trajectory player for animating coordinate frames
 * @example
 * var player = new TrajectoryPlayer(trajectory, {step: 1, timeout: 50});
 * player.play();
 */
var TrajectoryPlayer = function TrajectoryPlayer(traj, params) {
    var this$1 = this;
    if ( params === void 0 ) params = {};

    this.signals = {
        startedRunning: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"](),
        haltedRunning: new __WEBPACK_IMPORTED_MODULE_2_signals__["Signal"]()
    };
    this._run = false;
    this._previousTime = 0;
    this._currentTime = 0;
    this._currentStep = 1;
    traj.signals.playerChanged.add(function (player) {
        if (player !== this$1) {
            this$1.pause();
        }
    }, this);
    var n = defaults(traj.frameCount, 1);
    this.traj = traj;
    this.parameters = createParams(params, TrajectoryPlayerDefaultParameters);
    this.parameters.end = Math.min(defaults(params.end, n - 1), n - 1);
    this.parameters.step = defaults(params.step, Math.ceil((n + 1) / 100));
    this._currentFrame = this.parameters.start;
    this._direction = this.parameters.direction === 'bounce' ? 'forward' : this.parameters.direction;
    traj.signals.countChanged.add(function (n) {
        this$1.parameters.end = Math.min(defaults(this$1.parameters.end, n - 1), n - 1);
    }, this);
    this._animate = this._animate.bind(this);
};

var prototypeAccessors$t = { isRunning: { configurable: true } };
prototypeAccessors$t.isRunning.get = function () { return this._run; };
/**
 * set player parameters
 * @param {TrajectoryPlayerParameters} [params] - parameter object
 */
TrajectoryPlayer.prototype.setParameters = function setParameters (params) {
        if ( params === void 0 ) params = {};

    updateParams(this.parameters, params);
    if (params.direction !== undefined && this.parameters.direction !== 'bounce') {
        this._direction = this.parameters.direction;
    }
};
TrajectoryPlayer.prototype._animate = function _animate () {
    if (!this._run)
        { return; }
    this._currentTime = window.performance.now();
    var dt = this._currentTime - this._previousTime;
    var step = this.parameters.interpolateType ? this.parameters.interpolateStep : 1;
    var timeout = this.parameters.timeout / step;
    var traj = this.traj;
    if (traj && traj.frameCount && !traj.inProgress && dt >= timeout) {
        if (this.parameters.interpolateType) {
            if (this._currentStep > this.parameters.interpolateStep) {
                this._currentStep = 1;
            }
            if (this._currentStep === 1) {
                this._currentFrame = this._nextInterpolated();
            }
            if (traj.hasFrame(this._currentFrame)) {
                this._currentStep += 1;
                var t = this._currentStep / (this.parameters.interpolateStep + 1);
                var ref = this._currentFrame;
                    var i = ref[0];
                    var ip = ref[1];
                    var ipp = ref[2];
                    var ippp = ref[3];
                traj.setFrameInterpolated(i, ip, ipp, ippp, t, this.parameters.interpolateType);
                this._previousTime = this._currentTime;
            }
            else {
                traj.loadFrame(this._currentFrame);
            }
        }
        else {
            var i$1 = this._next();
            if (traj.hasFrame(i$1)) {
                traj.setFrame(i$1);
                this._previousTime = this._currentTime;
            }
            else {
                traj.loadFrame(i$1);
            }
        }
    }
    window.requestAnimationFrame(this._animate);
};
TrajectoryPlayer.prototype._next = function _next () {
    var p = this.parameters;
    var i;
    if (this._direction === 'forward') {
        i = this.traj.currentFrame + p.step;
    }
    else {
        i = this.traj.currentFrame - p.step;
    }
    if (i > p.end || i < p.start) {
        if (p.direction === 'bounce') {
            if (this._direction === 'forward') {
                this._direction = 'backward';
            }
            else {
                this._direction = 'forward';
            }
        }
        if (p.mode === 'once') {
            this.pause();
            if (p.direction === 'forward') {
                i = p.end;
            }
            else if (p.direction === 'backward') {
                i = p.start;
            }
            else {
                if (this._direction === 'forward') {
                    i = p.start;
                }
                else {
                    i = p.end;
                }
            }
        }
        else {
            if (this._direction === 'forward') {
                i = p.start;
                if (p.interpolateType) {
                    i = Math.min(p.end, i + p.step);
                }
            }
            else {
                i = p.end;
                if (p.interpolateType) {
                    i = Math.max(p.start, i - p.step);
                }
            }
        }
    }
    return i;
};
TrajectoryPlayer.prototype._nextInterpolated = function _nextInterpolated () {
    var p = this.parameters;
    var i = this._next();
    var ip, ipp, ippp;
    if (this._direction === 'forward') {
        ip = Math.max(p.start, i - p.step);
        ipp = Math.max(p.start, i - 2 * p.step);
        ippp = Math.max(p.start, i - 3 * p.step);
    }
    else {
        ip = Math.min(p.end, i + p.step);
        ipp = Math.min(p.end, i + 2 * p.step);
        ippp = Math.min(p.end, i + 3 * p.step);
    }
    return [i, ip, ipp, ippp];
};
/**
 * toggle between playing and pausing the animation
 * @return {undefined}
 */
TrajectoryPlayer.prototype.toggle = function toggle () {
    if (this._run) {
        this.pause();
    }
    else {
        this.play();
    }
};
/**
 * start the animation
 * @return {undefined}
 */
TrajectoryPlayer.prototype.play = function play () {
    if (!this._run) {
        if (this.traj.player !== this) {
            this.traj.setPlayer(this);
        }
        this._currentStep = 1;
        var p = this.parameters;
        var frame = this.traj.currentFrame;
        // snap to the grid implied by this.step division and multiplication
        // thus minimizing cache misses
        var i = Math.ceil(frame / p.step) * p.step;
        // wrap when restarting from the limit (i.e. end or start)
        if (p.direction === 'forward' && frame >= p.end) {
            i = p.start;
        }
        else if (p.direction === 'backward' && frame <= p.start) {
            i = p.end;
        }
        this.traj.setFrame(i);
        this._run = true;
        this._animate();
        this.signals.startedRunning.dispatch();
    }
};
/**
 * pause the animation
 * @return {undefined}
 */
TrajectoryPlayer.prototype.pause = function pause () {
    this._run = false;
    this.signals.haltedRunning.dispatch();
};
/**
 * stop the animation (pause and go to start-frame)
 * @return {undefined}
 */
TrajectoryPlayer.prototype.stop = function stop () {
    this.pause();
    this.traj.setFrame(this.parameters.start);
};

Object.defineProperties( TrajectoryPlayer.prototype, prototypeAccessors$t );

/**
 * @file Trajectory
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function centerPbc(coords, mean, box) {
    if (box[0] === 0 || box[8] === 0 || box[4] === 0) {
        return;
    }
    var n = coords.length;
    var bx = box[0];
    var by = box[1];
    var bz = box[2];
    var mx = mean[0];
    var my = mean[1];
    var mz = mean[2];
    var fx = -mx + bx + bx / 2;
    var fy = -my + by + by / 2;
    var fz = -mz + bz + bz / 2;
    for (var i = 0; i < n; i += 3) {
        coords[i + 0] = (coords[i + 0] + fx) % bx;
        coords[i + 1] = (coords[i + 1] + fy) % by;
        coords[i + 2] = (coords[i + 2] + fz) % bz;
    }
}
function removePbc(x, box) {
    if (box[0] === 0 || box[8] === 0 || box[4] === 0) {
        return;
    }
    // ported from GROMACS src/gmxlib/rmpbc.c:rm_gropbc()
    // in-place
    var n = x.length;
    for (var i = 3; i < n; i += 3) {
        for (var j = 0; j < 3; ++j) {
            var dist = x[i + j] - x[i - 3 + j];
            if (Math.abs(dist) > 0.9 * box[j * 3 + j]) {
                if (dist > 0) {
                    for (var d = 0; d < 3; ++d) {
                        x[i + d] -= box[j * 3 + d];
                    }
                }
                else {
                    for (var d$1 = 0; d$1 < 3; ++d$1) {
                        x[i + d$1] += box[j * 3 + d$1];
                    }
                }
            }
        }
    }
    return x;
}
function removePeriodicity(x, box, mean) {
    if (box[0] === 0 || box[8] === 0 || box[4] === 0) {
        return;
    }
    var n = x.length;
    for (var i = 3; i < n; i += 3) {
        for (var j = 0; j < 3; ++j) {
            var f = (x[i + j] - mean[j]) / box[j * 3 + j];
            if (Math.abs(f) > 0.5) {
                x[i + j] -= box[j * 3 + j] * Math.round(f);
            }
        }
    }
    return x;
}
function circularMean3(indices, coords, box) {
    return [
        circularMean(coords, box[0], 3, 0, indices),
        circularMean(coords, box[1], 3, 1, indices),
        circularMean(coords, box[2], 3, 2, indices)
    ];
}
function arrayMean3(coords) {
    return [
        arrayMean(coords, 3, 0),
        arrayMean(coords, 3, 1),
        arrayMean(coords, 3, 2)
    ];
}
function interpolateSpline(c, cp, cpp, cppp, t) {
    var m = c.length;
    var coords = new Float32Array(m);
    for (var j0 = 0; j0 < m; j0 += 3) {
        var j1 = j0 + 1;
        var j2 = j0 + 2;
        coords[j0] = spline(cppp[j0], cpp[j0], cp[j0], c[j0], t, 1);
        coords[j1] = spline(cppp[j1], cpp[j1], cp[j1], c[j1], t, 1);
        coords[j2] = spline(cppp[j2], cpp[j2], cp[j2], c[j2], t, 1);
    }
    return coords;
}
function interpolateLerp(c, cp, t) {
    var m = c.length;
    var coords = new Float32Array(m);
    for (var j0 = 0; j0 < m; j0 += 3) {
        var j1 = j0 + 1;
        var j2 = j0 + 2;
        coords[j0] = lerp(cp[j0], c[j0], t);
        coords[j1] = lerp(cp[j1], c[j1], t);
        coords[j2] = lerp(cp[j2], c[j2], t);
    }
    return coords;
}
/**
 * Base class for trajectories, tying structures and coordinates together
 * @interface
 */
var Trajectory = function Trajectory(trajPath, structure, params) {
    var this$1 = this;
    if ( params === void 0 ) params = {};

    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 = false;
    this.deltaTime = defaults(params.deltaTime, 0);
    this.timeOffset = defaults(params.timeOffset, 0);
    this.centerPbc = defaults(params.centerPbc, false);
    this.removePbc = defaults(params.removePbc, false);
    this.removePeriodicity = defaults(params.removePeriodicity, false);
    this.superpose = defaults(params.superpose, false);
    this.name = trajPath.replace(/^.*[\\/]/, '');
    this.trajPath = trajPath;
    this.selection = new Selection(defaults(params.sele, 'backbone and not hydrogen'));
    this.selection.signals.stringChanged.add(function () {
        this$1.selectionIndices = this$1.structure.getAtomIndices(this$1.selection);
        this$1._resetCache();
        this$1._saveInitialCoords();
        this$1.setFrame(this$1._currentFrame);
    });
};

var prototypeAccessors$u = { frameCount: { configurable: true },currentFrame: { configurable: true } };
/**
 * Number of frames in the trajectory
 */
prototypeAccessors$u.frameCount.get = function () {
    return this._frameCount;
};
/**
 * Currently set frame of the trajectory
 */
prototypeAccessors$u.currentFrame.get = function () {
    return this._currentFrame;
};
Trajectory.prototype._init = function _init (structure) {
    this.setStructure(structure);
    this._loadFrameCount();
    this.setPlayer(new TrajectoryPlayer(this));
};
Trajectory.prototype._loadFrameCount = function _loadFrameCount () { };
Trajectory.prototype.setStructure = function setStructure (structure) {
    this.structure = structure;
    this.atomCount = structure.atomCount;
    this.backboneIndices = this._getIndices(new Selection('backbone and not hydrogen'));
    this._makeAtomIndices();
    this._saveStructureCoords();
    this.selectionIndices = this._getIndices(this.selection);
    this._resetCache();
    this._saveInitialCoords();
    this.setFrame(this._currentFrame);
};
Trajectory.prototype._saveInitialCoords = function _saveInitialCoords () {
        var this$1 = this;

    if (this.structure.hasCoords()) {
        this.initialCoords = new Float32Array(this.structureCoords);
        this._makeSuperposeCoords();
    }
    else if (this.frameCache[0]) {
        this.initialCoords = new Float32Array(this.frameCache[0]);
        this._makeSuperposeCoords();
    }
    else {
        this.loadFrame(0, function () { return this$1._saveInitialCoords(); });
    }
};
Trajectory.prototype._saveStructureCoords = function _saveStructureCoords () {
    var p = { what: { position: true } };
    this.structureCoords = this.structure.getAtomData(p).position;
};
Trajectory.prototype.setSelection = function setSelection (string) {
    this.selection.setString(string);
    return this;
};
Trajectory.prototype._getIndices = function _getIndices (selection) {
    var i = 0;
    var test = selection.test;
    var indices = [];
    if (test) {
        this.structure.eachAtom(function (ap) {
            if (test(ap))
                { indices.push(i); }
            i += 1;
        });
    }
    return indices;
};
Trajectory.prototype._makeSuperposeCoords = function _makeSuperposeCoords () {
    var n = this.selectionIndices.length * 3;
    this.coords1 = new Float32Array(n);
    this.coords2 = new Float32Array(n);
    var y = this.initialCoords;
    var coords2 = this.coords2;
    for (var i = 0; i < n; i += 3) {
        var j = this.selectionIndices[i / 3] * 3;
        coords2[i + 0] = y[j + 0];
        coords2[i + 1] = y[j + 1];
        coords2[i + 2] = y[j + 2];
    }
};
Trajectory.prototype._makeAtomIndices = function _makeAtomIndices () {
    Log.error('Trajectory._makeAtomIndices not implemented');
};
Trajectory.prototype._resetCache = function _resetCache () {
    this.frameCache = {};
    this.loadQueue = {};
    this.boxCache = {};
    this.pathCache = {};
    this.frameCacheSize = 0;
    this.initialCoords = new Float32Array(0);
};
Trajectory.prototype.setParameters = function setParameters (params) {
        if ( params === void 0 ) params = {};

    var resetCache = false;
    if (params.centerPbc !== undefined && params.centerPbc !== this.centerPbc) {
        this.centerPbc = params.centerPbc;
        resetCache = true;
    }
    if (params.removePeriodicity !== undefined && params.removePeriodicity !== this.removePeriodicity) {
        this.removePeriodicity = params.removePeriodicity;
        resetCache = true;
    }
    if (params.removePbc !== undefined && params.removePbc !== this.removePbc) {
        this.removePbc = params.removePbc;
        resetCache = true;
    }
    if (params.superpose !== undefined && params.superpose !== this.superpose) {
        this.superpose = params.superpose;
        resetCache = true;
    }
    this.deltaTime = defaults(params.deltaTime, this.deltaTime);
    this.timeOffset = defaults(params.timeOffset, this.timeOffset);
    if (resetCache) {
        this._resetCache();
        this.setFrame(this._currentFrame);
    }
};
/**
 * Check if a frame is available
 * @param  {Integer|Integer[]} i - the frame index
 * @return {Boolean} frame availability
 */
Trajectory.prototype.hasFrame = function hasFrame (i) {
        var this$1 = this;

    if (Array.isArray(i)) {
        return i.every(function (j) { return !!this$1.frameCache[j]; });
    }
    else {
        return !!this.frameCache[i];
    }
};
/**
 * Set trajectory to a frame index
 * @param {Integer} i - the frame index
 * @param {Function} [callback] - fired when the frame has been set
 */
Trajectory.prototype.setFrame = function setFrame (i, callback) {
        var this$1 = this;

    if (i === undefined)
        { return this; }
    this.inProgress = true;
    // i = parseInt(i)  // TODO
    if (i === -1 || this.frameCache[i]) {
        this._updateStructure(i);
        if (callback)
            { callback(); }
    }
    else {
        this.loadFrame(i, function () {
            this$1._updateStructure(i);
            if (callback)
                { callback(); }
        });
    }
    return this;
};
Trajectory.prototype._interpolate = function _interpolate (i, ip, ipp, ippp, t, type) {
    var fc = this.frameCache;
    var coords;
    if (type === 'spline') {
        coords = interpolateSpline(fc[i], fc[ip], fc[ipp], fc[ippp], t);
    }
    else {
        coords = interpolateLerp(fc[i], fc[ip], t);
    }
    this.structure.updatePosition(coords);
    this._currentFrame = i;
    this.signals.frameChanged.dispatch(i);
};
/**
 * Interpolated and set trajectory to frame indices
 * @param {Integer} i - the frame index
 * @param {Integer} ip - one before frame index
 * @param {Integer} ipp - two before frame index
 * @param {Integer} ippp - three before frame index
 * @param {Number} t - interpolation step [0,1]
 * @param {String} type - interpolation type, '', 'spline' or 'linear'
 * @param {Function} callback - fired when the frame has been set
 */
Trajectory.prototype.setFrameInterpolated = function setFrameInterpolated (i, ip, ipp, ippp, t, type, callback) {
        var this$1 = this;

    if (i === undefined)
        { return this; }
    var fc = this.frameCache;
    var iList = [];
    if (!fc[ippp])
        { iList.push(ippp); }
    if (!fc[ipp])
        { iList.push(ipp); }
    if (!fc[ip])
        { iList.push(ip); }
    if (!fc[i])
        { iList.push(i); }
    if (iList.length) {
        this.loadFrame(iList, function () {
            this$1._interpolate(i, ip, ipp, ippp, t, type);
            if (callback)
                { callback(); }
        });
    }
    else {
        this._interpolate(i, ip, ipp, ippp, t, type);
        if (callback)
            { callback(); }
    }
    return this;
};
/**
 * Load frame index
 * @param {Integer|Integer[]} i - the frame index
 * @param {Function} callback - fired when the frame has been loaded
 */
Trajectory.prototype.loadFrame = function loadFrame (i, callback) {
        var this$1 = this;

    if (Array.isArray(i)) {
        i.forEach(function (j) {
            if (!this$1.loadQueue[j] && !this$1.frameCache[j]) {
                this$1.loadQueue[j] = true;
                this$1._loadFrame(j, function () {
                    delete this$1.loadQueue[j];
                });
            }
        });
    }
    else {
        if (!this.loadQueue[i] && !this.frameCache[i]) {
            this.loadQueue[i] = true;
            this._loadFrame(i, function () {
                delete this$1.loadQueue[i];
                if (callback)
                    { callback(); }
            });
        }
    }
};
/**
 * Load frame index
 * @abstract
 * @param {Integer} i - the frame index
 * @param {Function} callback - fired when the frame has been loaded
 */
Trajectory.prototype._loadFrame = function _loadFrame (i, callback) {
    Log.error('Trajectory._loadFrame not implemented', i, callback);
};
Trajectory.prototype._updateStructure = function _updateStructure (i) {
    if (this._disposed) {
        console.error('updateStructure: traj disposed');
        return;
    }
    if (i === -1) {
        if (this.structureCoords) {
            this.structure.updatePosition(this.structureCoords);
        }
    }
    else {
        this.structure.updatePosition(this.frameCache[i]);
    }
    this.structure.trajectory = {
        name: this.trajPath,
        frame: i
    };
    this._currentFrame = i;
    this.inProgress = false;
    this.signals.frameChanged.dispatch(i);
};
Trajectory.prototype._doSuperpose = function _doSuperpose (x) {
    var n = this.selectionIndices.length * 3;
    var coords1 = this.coords1;
    var coords2 = this.coords2;
    for (var i = 0; i < n; i += 3) {
        var j = this.selectionIndices[i / 3] * 3;
        coords1[i + 0] = x[j + 0];
        coords1[i + 1] = x[j + 1];
        coords1[i + 2] = x[j + 2];
    }
    // TODO re-use superposition object
    var sp = new Superposition(coords1, coords2);
    sp.transform(x);
};
Trajectory.prototype._process = function _process (i, box, coords, frameCount) {
    this._setFrameCount(frameCount);
    if (box) {
        if (this.backboneIndices.length > 0 && this.centerPbc) {
            var box2 = [box[0], box[4], box[8]];
            var circMean = circularMean3(this.backboneIndices, coords, box2);
            centerPbc(coords, circMean, box2);
        }
        if (this.removePeriodicity) {
            var mean = arrayMean3(coords);
            removePeriodicity(coords, box, mean);
        }
        if (this.removePbc) {
            removePbc(coords, box);
        }
    }
    if (this.selectionIndices.length > 0 && this.coords1 && this.superpose) {
        this._doSuperpose(coords);
    }
    this.frameCache[i] = coords;
    this.boxCache[i] = box;
    this.frameCacheSize += 1;
};
Trajectory.prototype._setFrameCount = function _setFrameCount (n) {
    if (n !== this._frameCount) {
        this._frameCount = n;
        this.signals.countChanged.dispatch(n);
    }
};
/**
 * Dispose of the trajectory object
 * @return {undefined}
 */
Trajectory.prototype.dispose = function dispose () {
    this._resetCache(); // aid GC
    this._disposed = true;
    if (this.player)
        { this.player.stop(); }
};
/**
 * Set player for this trajectory
 * @param {TrajectoryPlayer} player - the player
 */
Trajectory.prototype.setPlayer = function setPlayer (player) {
    this.player = player;
    this.signals.playerChanged.dispatch(player);
};
/**
 * Get time for frame
 * @param  {Integer} i - frame index
 * @return {Number} time in picoseconds
 */
Trajectory.prototype.getFrameTime = function getFrameTime (i) {
    return this.timeOffset + i * this.deltaTime;
};

Object.defineProperties( Trajectory.prototype, prototypeAccessors$u );

/**
 * @file Frames Trajectory
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Frames trajectory class. Gets data from a frames object.
 */
var FramesTrajectory = /*@__PURE__*/(function (Trajectory$$1) {
    function FramesTrajectory(frames, structure, params) {
        var p = params || {};
        p.timeOffset = defaults(p.timeOffset, frames.timeOffset);
        p.deltaTime = defaults(p.deltaTime, frames.deltaTime);
        Trajectory$$1.call(this, '', structure, p);
        this.name = frames.name;
        this.path = frames.path;
        this.frames = frames.coordinates;
        this.boxes = frames.boxes;
        this._init(structure);
    }

    if ( Trajectory$$1 ) FramesTrajectory.__proto__ = Trajectory$$1;
    FramesTrajectory.prototype = Object.create( Trajectory$$1 && Trajectory$$1.prototype );
    FramesTrajectory.prototype.constructor = FramesTrajectory;

    var prototypeAccessors = { type: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'frames'; };
    FramesTrajectory.prototype._makeAtomIndices = function _makeAtomIndices () {
        if (this.structure.type === 'StructureView') {
            this.atomIndices = this.structure.getAtomIndices();
        }
        else {
            this.atomIndices = undefined;
        }
    };
    FramesTrajectory.prototype._loadFrame = function _loadFrame (i, callback) {
        var coords;
        var frame = this.frames[i];
        if (this.atomIndices) {
            var indices = this.atomIndices;
            var m = indices.length;
            coords = new Float32Array(m * 3);
            for (var j = 0; j < m; ++j) {
                var j3 = j * 3;
                var idx3 = indices[j] * 3;
                coords[j3 + 0] = frame[idx3 + 0];
                coords[j3 + 1] = frame[idx3 + 1];
                coords[j3 + 2] = frame[idx3 + 2];
            }
        }
        else {
            coords = new Float32Array(frame);
        }
        var box = this.boxes[i];
        var frameCount = this.frames.length;
        this._process(i, box, coords, frameCount);
        if (typeof callback === 'function') {
            callback();
        }
    };
    FramesTrajectory.prototype._loadFrameCount = function _loadFrameCount () {
        if (this.frames) {
            this._setFrameCount(this.frames.length);
        }
    };

    Object.defineProperties( FramesTrajectory.prototype, prototypeAccessors );

    return FramesTrajectory;
}(Trajectory));

/**
 * @file Structure Trajectory
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Structure trajectory class. Gets data from a structure object.
 */
var StructureTrajectory = /*@__PURE__*/(function (Trajectory$$1) {
    function StructureTrajectory(trajPath, structure, params) {
        Trajectory$$1.call(this, '', structure, params);
        this._init(structure);
    }

    if ( Trajectory$$1 ) StructureTrajectory.__proto__ = Trajectory$$1;
    StructureTrajectory.prototype = Object.create( Trajectory$$1 && Trajectory$$1.prototype );
    StructureTrajectory.prototype.constructor = StructureTrajectory;

    var prototypeAccessors = { type: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'structure'; };
    StructureTrajectory.prototype._makeAtomIndices = function _makeAtomIndices () {
        if (this.structure.atomSet && this.structure.atomSet.getSize() < this.structure.atomStore.count) {
            this.atomIndices = this.structure.getAtomIndices();
        }
        else {
            this.atomIndices = undefined;
        }
    };
    StructureTrajectory.prototype._loadFrame = function _loadFrame (i, callback) {
        var coords;
        var structure = this.structure;
        var frame = structure.frames[i];
        if (this.atomIndices) {
            var indices = this.atomIndices;
            var m = indices.length;
            coords = new Float32Array(m * 3);
            for (var j = 0; j < m; ++j) {
                var j3 = j * 3;
                var idx3 = indices[j] * 3;
                coords[j3 + 0] = frame[idx3 + 0];
                coords[j3 + 1] = frame[idx3 + 1];
                coords[j3 + 2] = frame[idx3 + 2];
            }
        }
        else {
            coords = new Float32Array(frame);
        }
        var box = structure.boxes[i];
        var frameCount = structure.frames.length;
        this._process(i, box, coords, frameCount);
        if (typeof callback === 'function') {
            callback();
        }
    };
    StructureTrajectory.prototype._loadFrameCount = function _loadFrameCount () {
        this._setFrameCount(this.structure.frames.length);
    };

    Object.defineProperties( StructureTrajectory.prototype, prototypeAccessors );

    return StructureTrajectory;
}(Trajectory));

/**
 * @file Remote Trajectory
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Remote trajectory class. Gets data from an MDsrv instance.
 */
var RemoteTrajectory = /*@__PURE__*/(function (Trajectory$$1) {
    function RemoteTrajectory(trajPath, structure, params) {
        Trajectory$$1.call(this, trajPath, structure, params);
        this._init(structure);
    }

    if ( Trajectory$$1 ) RemoteTrajectory.__proto__ = Trajectory$$1;
    RemoteTrajectory.prototype = Object.create( Trajectory$$1 && Trajectory$$1.prototype );
    RemoteTrajectory.prototype.constructor = RemoteTrajectory;

    var prototypeAccessors = { type: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'remote'; };
    RemoteTrajectory.prototype._makeAtomIndices = function _makeAtomIndices () {
        var atomIndices = [];
        if (this.structure.type === 'StructureView') {
            var indices = this.structure.getAtomIndices(); // TODO
            var n = indices.length;
            var p = indices[0];
            var q = indices[0];
            for (var i = 1; i < n; ++i) {
                var r = indices[i];
                if (q + 1 < r) {
                    atomIndices.push([p, q + 1]);
                    p = r;
                }
                q = r;
            }
            atomIndices.push([p, q + 1]);
        }
        else {
            atomIndices.push([0, this.atomCount]);
        }
        this.atomIndices = atomIndices;
    };
    RemoteTrajectory.prototype._loadFrame = function _loadFrame (i, callback) {
        var this$1 = this;

        // TODO implement max frameCache size, re-use arrays
        var request = new XMLHttpRequest();
        var url = TrajectoryDatasource.getFrameUrl(this.trajPath, i);
        var params = TrajectoryDatasource.getFrameParams(this.trajPath, this.atomIndices);
        request.open('POST', url, true);
        request.responseType = 'arraybuffer';
        request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        request.addEventListener('load', function () {
            var arrayBuffer = request.response;
            if (!arrayBuffer) {
                Log.error(("empty arrayBuffer for '" + url + "'"));
                return;
            }
            var frameCount = new Int32Array(arrayBuffer, 0, 1)[0];
            // const time = new Float32Array( arrayBuffer, 1 * 4, 1 )[ 0 ];
            var box = new Float32Array(arrayBuffer, 2 * 4, 9);
            var coords = new Float32Array(arrayBuffer, 11 * 4);
            this$1._process(i, box, coords, frameCount);
            if (typeof callback === 'function') {
                callback();
            }
        }, false);
        request.send(params);
    };
    RemoteTrajectory.prototype._loadFrameCount = function _loadFrameCount () {
        var this$1 = this;

        var request = new XMLHttpRequest();
        var url = TrajectoryDatasource.getCountUrl(this.trajPath);
        request.open('GET', url, true);
        request.addEventListener('load', function () {
            this$1._setFrameCount(parseInt(request.response));
        }, false);
        request.send();
    };

    Object.defineProperties( RemoteTrajectory.prototype, prototypeAccessors );

    return RemoteTrajectory;
}(Trajectory));

/**
 * @file Callback Trajectory
 * @author Tarn W. Burton <twburton@gmail.com>
 * @private
 */
/**
 * Callback trajectory class. Gets data from an JavaScript function.
 */
var CallbackTrajectory = /*@__PURE__*/(function (Trajectory$$1) {
    function CallbackTrajectory(requestCallback, structure, params) {
        Trajectory$$1.call(this, '', structure, params);
        this.requestCallback = requestCallback;
        this._init(structure);
    }

    if ( Trajectory$$1 ) CallbackTrajectory.__proto__ = Trajectory$$1;
    CallbackTrajectory.prototype = Object.create( Trajectory$$1 && Trajectory$$1.prototype );
    CallbackTrajectory.prototype.constructor = CallbackTrajectory;

    var prototypeAccessors = { type: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'callback'; };
    CallbackTrajectory.prototype._makeAtomIndices = function _makeAtomIndices () {
        var atomIndices = [];
        if (this.structure.type === 'StructureView') {
            var indices = this.structure.getAtomIndices(); // TODO
            var n = indices.length;
            var p = indices[0];
            var q = indices[0];
            for (var i = 1; i < n; ++i) {
                var r = indices[i];
                if (q + 1 < r) {
                    atomIndices.push([p, q + 1]);
                    p = r;
                }
                q = r;
            }
            atomIndices.push([p, q + 1]);
        }
        else {
            atomIndices.push([0, this.atomCount]);
        }
        this.atomIndices = atomIndices;
    };
    CallbackTrajectory.prototype._loadFrame = function _loadFrame (i, callback) {
        var this$1 = this;

        this.requestCallback(function (i, box, coords, frameCount) {
            this$1._process(i, box, coords, frameCount);
            if (typeof callback === 'function') {
                callback();
            }
        }, i, this.atomIndices);
    };
    CallbackTrajectory.prototype._loadFrameCount = function _loadFrameCount () {
        var this$1 = this;

        this.requestCallback(function (count) { return this$1._setFrameCount(count); });
    };

    Object.defineProperties( CallbackTrajectory.prototype, prototypeAccessors );

    return CallbackTrajectory;
}(Trajectory));

/**
 * @file Trajectory Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function makeTrajectory(trajSrc, structure, params) {
    var traj;
    if (trajSrc && trajSrc instanceof Frames) {
        traj = new FramesTrajectory(trajSrc, structure, params);
    }
    else if (!trajSrc && structure.frames) {
        traj = new StructureTrajectory(trajSrc, structure, params);
    }
    else if (trajSrc && typeof trajSrc === 'function') {
        traj = new CallbackTrajectory(trajSrc, structure, params);
    }
    else {
        traj = new RemoteTrajectory(trajSrc, structure, params);
    }
    return traj;
}

/**
 * @file Structure View
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Get view on structure restricted to the selection
 * @param  {Selection} selection - the selection
 * @return {StructureView} the view on the structure
 */
Structure.prototype.getView = function (selection) {
    // added here to avoid cyclic import dependency
    return new StructureView(this, selection);
};
/**
 * View on the structure, restricted to the selection
 */
var StructureView = /*@__PURE__*/(function (Structure$$1) {
    function StructureView(structure, selection) {
        Structure$$1.call(this);
        this.structure = structure;
        this.selection = selection;
        this.center = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        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();
        if (this.selection) {
            this.selection.signals.stringChanged.add(this.refresh, this);
        }
        this.structure.signals.refreshed.add(this.refresh, this);
        this.refresh();
    }

    if ( Structure$$1 ) StructureView.__proto__ = Structure$$1;
    StructureView.prototype = Object.create( Structure$$1 && Structure$$1.prototype );
    StructureView.prototype.constructor = StructureView;

    var prototypeAccessors = { type: { configurable: true },name: { configurable: true },path: { configurable: true },title: { configurable: true },id: { configurable: true },data: { configurable: true },atomSetDict: { configurable: true },biomolDict: { configurable: true },entityList: { configurable: true },unitcell: { configurable: true },frames: { configurable: true },boxes: { configurable: true },validation: { configurable: true },bondStore: { configurable: true },backboneBondStore: { configurable: true },rungBondStore: { configurable: true },atomStore: { configurable: true },residueStore: { configurable: true },chainStore: { configurable: true },modelStore: { configurable: true },atomMap: { configurable: true },residueMap: { configurable: true },bondHash: { configurable: true },spatialHash: { configurable: true },_hasCoords: { configurable: true } };
    StructureView.prototype.init = function init () { };
    prototypeAccessors.type.get = function () { return 'StructureView'; };
    prototypeAccessors.name.get = function () { return this.structure.name; };
    prototypeAccessors.path.get = function () { return this.structure.path; };
    prototypeAccessors.title.get = function () { return this.structure.title; };
    prototypeAccessors.id.get = function () { return this.structure.id; };
    prototypeAccessors.data.get = function () { return this.structure.data; };
    prototypeAccessors.atomSetDict.get = function () { return this.structure.atomSetDict; };
    prototypeAccessors.biomolDict.get = function () { return this.structure.biomolDict; };
    prototypeAccessors.entityList.get = function () { return this.structure.entityList; };
    prototypeAccessors.unitcell.get = function () { return this.structure.unitcell; };
    prototypeAccessors.frames.get = function () { return this.structure.frames; };
    prototypeAccessors.boxes.get = function () { return this.structure.boxes; };
    prototypeAccessors.validation.get = function () { return this.structure.validation; };
    prototypeAccessors.bondStore.get = function () { return this.structure.bondStore; };
    prototypeAccessors.backboneBondStore.get = function () { return this.structure.backboneBondStore; };
    prototypeAccessors.rungBondStore.get = function () { return this.structure.rungBondStore; };
    prototypeAccessors.atomStore.get = function () { return this.structure.atomStore; };
    prototypeAccessors.residueStore.get = function () { return this.structure.residueStore; };
    prototypeAccessors.chainStore.get = function () { return this.structure.chainStore; };
    prototypeAccessors.modelStore.get = function () { return this.structure.modelStore; };
    prototypeAccessors.atomMap.get = function () { return this.structure.atomMap; };
    prototypeAccessors.residueMap.get = function () { return this.structure.residueMap; };
    prototypeAccessors.bondHash.get = function () { return this.structure.bondHash; };
    prototypeAccessors.spatialHash.get = function () { return this.structure.spatialHash; };
    prototypeAccessors._hasCoords.get = function () { return this.structure._hasCoords; };
    prototypeAccessors._hasCoords.set = function (value) { this.structure._hasCoords = value; };
    /**
     * Updates atomSet, bondSet, atomSetCache, atomCount, bondCount, boundingBox, center.
     * @emits {Structure.signals.refreshed} when refreshed
     * @return {undefined}
     */
    StructureView.prototype.refresh = function refresh () {
        if (Debug)
            { Log.time('StructureView.refresh'); }
        this.atomSetCache = {};
        var structure = this.structure;
        if (this.selection.isAllSelection() &&
            structure !== this && structure.atomSet && structure.bondSet) {
            this.atomSet = structure.atomSet.clone();
            this.bondSet = structure.bondSet.clone();
            for (var name in this.atomSetDict) {
                var atomSet = this.atomSetDict[name];
                this.atomSetCache['__' + name] = atomSet.clone();
            }
            this.atomCount = structure.atomCount;
            this.bondCount = structure.bondCount;
            this.boundingBox.copy(structure.boundingBox);
            this.center.copy(structure.center);
        }
        else if (this.selection.isNoneSelection() &&
            structure !== this && structure.atomSet && structure.bondSet) {
            this.atomSet = new BitArray(structure.atomCount);
            this.bondSet = new BitArray(structure.bondCount);
            for (var name$1 in this.atomSetDict) {
                this.atomSetCache['__' + name$1] = new BitArray(structure.atomCount);
            }
            this.atomCount = 0;
            this.bondCount = 0;
            this.boundingBox.makeEmpty();
            this.center.set(0, 0, 0);
        }
        else {
            this.atomSet = this.getAtomSet(this.selection, true);
            if (structure.atomSet) {
                this.atomSet = this.atomSet.intersection(structure.atomSet);
            }
            this.bondSet = this.getBondSet();
            for (var name$2 in this.atomSetDict) {
                var atomSet$1 = this.atomSetDict[name$2];
                this.atomSetCache['__' + name$2] = atomSet$1.makeIntersection(this.atomSet);
            }
            this.atomCount = this.atomSet.getSize();
            this.bondCount = this.bondSet.getSize();
            this.boundingBox = this.getBoundingBox();
            this.center = this.boundingBox.getCenter(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]());
        }
        if (Debug)
            { Log.timeEnd('StructureView.refresh'); }
        this.signals.refreshed.dispatch();
    };
    //
    StructureView.prototype.setSelection = function setSelection (selection) {
        this.selection = selection;
        this.refresh();
    };
    StructureView.prototype.getSelection = function getSelection (selection) {
        var seleList = [];
        if (selection && selection.string) {
            seleList.push(selection.string);
        }
        var parentSelection = this.structure.getSelection();
        if (parentSelection && parentSelection.string) {
            seleList.push(parentSelection.string);
        }
        if (this.selection && this.selection.string) {
            seleList.push(this.selection.string);
        }
        var sele = '';
        if (seleList.length > 0) {
            sele = "( " + (seleList.join(' ) AND ( ')) + " )";
        }
        return new Selection(sele);
    };
    StructureView.prototype.getStructure = function getStructure () {
        return this.structure.getStructure();
    };
    //
    StructureView.prototype.eachBond = function eachBond (callback, selection) {
        this.structure.eachBond(callback, this.getSelection(selection));
    };
    StructureView.prototype.eachAtom = function eachAtom (callback, selection) {
        var ap = this.getAtomProxy();
        var atomSet = this.getAtomSet(selection);
        var n = this.atomStore.count;
        if (atomSet.getSize() < n) {
            atomSet.forEach(function (index) {
                ap.index = index;
                callback(ap);
            });
        }
        else {
            for (var i = 0; i < n; ++i) {
                ap.index = i;
                callback(ap);
            }
        }
    };
    StructureView.prototype.eachResidue = function eachResidue (callback, selection) {
        this.structure.eachResidue(callback, this.getSelection(selection));
    };
    /**
     * Not implemented
     * @alias StructureView#eachResidueN
     * @return {undefined}
     */
    StructureView.prototype.eachResidueN = function eachResidueN (n, callback) {
        console.error('StructureView.eachResidueN() not implemented');
    };
    StructureView.prototype.eachChain = function eachChain (callback, selection) {
        this.structure.eachChain(callback, this.getSelection(selection));
    };
    StructureView.prototype.eachModel = function eachModel (callback, selection) {
        this.structure.eachModel(callback, this.getSelection(selection));
    };
    //
    StructureView.prototype.getAtomSet = function getAtomSet (selection, ignoreView) {
        if ( ignoreView === void 0 ) ignoreView = false;

        var atomSet = this.structure.getAtomSet(selection);
        if (!ignoreView && this.atomSet) {
            atomSet = atomSet.makeIntersection(this.atomSet);
        }
        return atomSet;
    };
    //
    StructureView.prototype.getAtomIndices = function getAtomIndices (selection) {
        return this.structure.getAtomIndices(this.getSelection(selection));
    };
    StructureView.prototype.refreshPosition = function refreshPosition () {
        return this.structure.refreshPosition();
    };
    //
    StructureView.prototype.dispose = function dispose () {
        if (this.selection) {
            this.selection.signals.stringChanged.remove(this.refresh, this);
        }
        this.structure.signals.refreshed.remove(this.refresh, this);
        delete this.structure;
        delete this.atomSet;
        delete this.bondSet;
        delete this.atomCount;
        delete this.bondCount;
    };

    Object.defineProperties( StructureView.prototype, prototypeAccessors );

    return StructureView;
}(Structure));

/**
 * @file Alignment
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// const nucleotides = 'ACTG';
var aminoacidsX = 'ACDEFGHIKLMNPQRSTVWY';
var aminoacids = 'ARNDCQEGHILKMFPSTWYVBZ?';
var blosum62x = [
    [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] // Y
];
var blosum62 = [
    // A  R  N  D  C  Q  E  G  H  I  L  K  M  F  P  S  T  W  Y  V  B  Z  X
    [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] // X
];
function prepareMatrix(cellNames, mat) {
    var j;
    var i = 0;
    var matDict = {};
    mat.forEach(function (row) {
        j = 0;
        var rowDict = {};
        row.forEach(function (elm) {
            rowDict[cellNames[j++]] = elm;
        });
        matDict[cellNames[i++]] = rowDict;
    });
    return matDict;
}
var SubstitutionMatrices = (function () {
    return {
        blosum62: prepareMatrix(aminoacids, blosum62),
        blosum62x: prepareMatrix(aminoacidsX, blosum62x)
    };
}());
var Alignment = function Alignment(seq1, seq2, gapPenalty, gapExtensionPenalty, substMatrix) {
    if ( gapPenalty === void 0 ) gapPenalty = -10;
    if ( gapExtensionPenalty === void 0 ) gapExtensionPenalty = -1;
    if ( substMatrix === void 0 ) substMatrix = 'blosum62';

    // TODO try encoding seqs as integers and use array subst matrix, maybe faster
    this.seq1 = seq1;
    this.seq2 = seq2;
    this.gapPenalty = gapPenalty;
    this.gapExtensionPenalty = gapExtensionPenalty;
    if (substMatrix) {
        this.substMatrix = SubstitutionMatrices[substMatrix];
    }
};
Alignment.prototype.initMatrices = function initMatrices () {
    this.n = this.seq1.length;
    this.m = this.seq2.length;
    // Log.log(this.n, this.m);
    this.score = undefined;
    this.ali = '';
    this.S = [];
    this.V = [];
    this.H = [];
    for (var i = 0; i <= this.n; ++i) {
        this.S[i] = [];
        this.V[i] = [];
        this.H[i] = [];
        for (var j = 0; j <= this.m; ++j) {
            this.S[i][j] = 0;
            this.V[i][j] = 0;
            this.H[i][j] = 0;
        }
    }
    for (var i$1 = 0; i$1 <= this.n; ++i$1) {
        this.S[i$1][0] = this.gap(0);
        this.H[i$1][0] = -Infinity;
    }
    for (var j$1 = 0; j$1 <= this.m; ++j$1) {
        this.S[0][j$1] = this.gap(0);
        this.V[0][j$1] = -Infinity;
    }
    this.S[0][0] = 0;
    // Log.log(this.S, this.V, this.H);
};
Alignment.prototype.gap = function gap (len) {
    return this.gapPenalty + len * this.gapExtensionPenalty;
};
Alignment.prototype.makeScoreFn = function makeScoreFn () {
    var seq1 = this.seq1;
    var seq2 = this.seq2;
    var substMatrix = this.substMatrix;
    if (substMatrix) {
        return function score(i, j) {
            var c1 = seq1[i];
            var c2 = seq2[j];
            try {
                return substMatrix[c1][c2];
            }
            catch (e) {
                return -4;
            }
        };
    }
    else {
        Log.warn('Alignment: no subst matrix');
        return function scoreNoSubstMat(i, j) {
            var c1 = seq1[i];
            var c2 = seq2[j];
            return c1 === c2 ? 5 : -3;
        };
    }
};
Alignment.prototype.calc = function calc () {
    if (Debug)
        { Log.time('Alignment.calc'); }
    this.initMatrices();
    var gap0 = this.gap(0);
    var scoreFn = this.makeScoreFn();
    var gapExtensionPenalty = this.gapExtensionPenalty;
    var V = this.V;
    var H = this.H;
    var S = this.S;
    var n = this.n;
    var m = this.m;
    var Vi1, Si1, Vi, Hi, Si;
    for (var i = 1; i <= n; ++i) {
        Si1 = S[i - 1];
        Vi1 = V[i - 1];
        Vi = V[i];
        Hi = H[i];
        Si = S[i];
        for (var j = 1; j <= m; ++j) {
            Vi[j] = Math.max(Si1[j] + gap0, Vi1[j] + gapExtensionPenalty);
            Hi[j] = Math.max(Si[j - 1] + gap0, Hi[j - 1] + gapExtensionPenalty);
            Si[j] = Math.max(Si1[j - 1] + scoreFn(i - 1, j - 1), // match
            Vi[j], // del
            Hi[j] // ins
            );
        }
    }
    if (Debug)
        { Log.timeEnd('Alignment.calc'); }
    if (Debug)
        { Log.log(this.S, this.V, this.H); }
};
Alignment.prototype.trace = function trace () {
    if (Debug)
        { Log.time('Alignment.trace'); }
    this.ali1 = '';
    this.ali2 = '';
    var scoreFn = this.makeScoreFn();
    var i = this.n;
    var j = this.m;
    var mat;
    if (this.S[i][j] >= this.V[i][j]) {
        mat = 'S';
        this.score = this.S[i][j];
    }
    else if (this.V[i][j] >= this.H[i][j]) {
        mat = 'V';
        this.score = this.V[i][j];
    }
    else {
        mat = 'H';
        this.score = this.H[i][j];
    }
    if (Debug)
        { Log.log('Alignment: SCORE', this.score); }
    if (Debug)
        { Log.log('Alignment: S, V, H', this.S[i][j], this.V[i][j], this.H[i][j]); }
    while (i > 0 && j > 0) {
        if (mat === 'S') {
            if (this.S[i][j] === this.S[i - 1][j - 1] + scoreFn(i - 1, j - 1)) {
                this.ali1 = this.seq1[i - 1] + this.ali1;
                this.ali2 = this.seq2[j - 1] + this.ali2;
                --i;
                --j;
                mat = 'S';
            }
            else if (this.S[i][j] === this.V[i][j]) {
                mat = 'V';
            }
            else if (this.S[i][j] === this.H[i][j]) {
                mat = 'H';
            }
            else {
                // Log.debug('Alignment: S');
                --i;
                --j;
            }
        }
        else if (mat === 'V') {
            if (this.V[i][j] === this.V[i - 1][j] + this.gapExtensionPenalty) {
                this.ali1 = this.seq1[i - 1] + this.ali1;
                this.ali2 = '-' + this.ali2;
                --i;
                mat = 'V';
            }
            else if (this.V[i][j] === this.S[i - 1][j] + this.gap(0)) {
                this.ali1 = this.seq1[i - 1] + this.ali1;
                this.ali2 = '-' + this.ali2;
                --i;
                mat = 'S';
            }
            else {
                // Log.debug('Alignment: V');
                --i;
            }
        }
        else if (mat === 'H') {
            if (this.H[i][j] === this.H[i][j - 1] + this.gapExtensionPenalty) {
                this.ali1 = '-' + this.ali1;
                this.ali2 = this.seq2[j - 1] + this.ali2;
                --j;
                mat = 'H';
            }
            else if (this.H[i][j] === this.S[i][j - 1] + this.gap(0)) {
                this.ali1 = '-' + this.ali1;
                this.ali2 = this.seq2[j - 1] + this.ali2;
                --j;
                mat = 'S';
            }
            else {
                // Log.debug('Alignment: H');
                --j;
            }
        }
        else {
            Log.error('Alignment: no matrix');
        }
    }
    while (i > 0) {
        this.ali1 = this.seq1[i - 1] + this.ali1;
        this.ali2 = '-' + this.ali2;
        --i;
    }
    while (j > 0) {
        this.ali1 = '-' + this.ali1;
        this.ali2 = this.seq2[j - 1] + this.ali2;
        --j;
    }
    if (Debug)
        { Log.timeEnd('Alignment.trace'); }
    if (Debug)
        { Log.log([this.ali1, this.ali2]); }
};

/**
 * @file Align Utils
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Perform structural superposition of two structures,
 * optionally guided by a sequence alignment
 * @param  {Structure|StructureView} s1 - structure 1 which is superposed onto structure 2
 * @param  {Structure|StructureView} s2 - structure 2 onto which structure 1 is superposed
 * @param  {Boolean} [align] - guide the superposition by a sequence alignment
 * @param  {String} [sele1] - selection string for structure 1
 * @param  {String} [sele2] - selection string for structure 2
 * @return {undefined}
 */
function superpose(s1, s2, align, sele1, sele2) {
    if ( align === void 0 ) align = false;
    if ( sele1 === void 0 ) sele1 = '';
    if ( sele2 === void 0 ) sele2 = '';

    var i;
    var j;
    var n;
    var atoms1;
    var atoms2;
    if (align) {
        var _s1 = s1;
        var _s2 = s2;
        if (sele1 && sele2) {
            _s1 = s1.getView(new Selection(sele1));
            _s2 = s2.getView(new Selection(sele2));
        }
        var seq1 = _s1.getSequence();
        var seq2 = _s2.getSequence();
        // Log.log( seq1.join("") );
        // Log.log( seq2.join("") );
        var ali = new Alignment(seq1.join(''), seq2.join(''));
        ali.calc();
        ali.trace();
        // Log.log( "superpose alignment score", ali.score );
        // Log.log( ali.ali1 );
        // Log.log( ali.ali2 );
        var _i, _j;
        i = 0;
        j = 0;
        n = ali.ali1.length;
        var aliIdx1 = [];
        var aliIdx2 = [];
        for (var l = 0; l < n; ++l) {
            var x = ali.ali1[l];
            var y = ali.ali2[l];
            _i = 0;
            _j = 0;
            if (x === '-') {
                aliIdx2[j] = false;
            }
            else {
                aliIdx2[j] = true;
                _i = 1;
            }
            if (y === '-') {
                aliIdx1[i] = false;
            }
            else {
                aliIdx1[i] = true;
                _j = 1;
            }
            i += _i;
            j += _j;
        }
        // Log.log( i, j );
        // Log.log( aliIdx1 );
        // Log.log( aliIdx2 );
        var _atoms1 = [];
        var _atoms2 = [];
        var ap1 = _s1.getAtomProxy();
        var ap2 = _s2.getAtomProxy();
        i = 0;
        _s1.eachResidue(function (r) {
            if (r.traceAtomIndex === undefined ||
                r.traceAtomIndex !== r.getAtomIndexByName('CA'))
                { return; }
            if (aliIdx1[i]) {
                ap1.index = r.getAtomIndexByName('CA'); // TODO
                _atoms1.push(ap1.x, ap1.y, ap1.z);
            }
            i += 1;
        });
        i = 0;
        _s2.eachResidue(function (r) {
            if (r.traceAtomIndex === undefined ||
                r.traceAtomIndex !== r.getAtomIndexByName('CA'))
                { return; }
            if (aliIdx2[i]) {
                ap2.index = r.getAtomIndexByName('CA'); // TODO
                _atoms2.push(ap2.x, ap2.y, ap2.z);
            }
            i += 1;
        });
        atoms1 = new Float32Array(_atoms1);
        atoms2 = new Float32Array(_atoms2);
    }
    else {
        var sviewCa1 = s1.getView(new Selection((sele1 + " and .CA")));
        var sviewCa2 = s2.getView(new Selection((sele2 + " and .CA")));
        atoms1 = sviewCa1;
        atoms2 = sviewCa2;
    }
    var superpose = new Superposition(atoms1, atoms2);
    var result = superpose.transform(s1);
    s1.refreshPosition();
    return result;
}

/**
 * @file Sturucture Component
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var StructureComponentDefaultParameters = Object.assign({
    sele: '',
    defaultAssembly: ''
}, ComponentDefaultParameters);
/**
 * Component wrapping a {@link Structure} object
 *
 * @example
 * // get a structure component by loading a structure file into the stage
 * stage.loadFile( "rcsb://4opj" ).then( function( structureComponent ){
 *     structureComponent.addRepresentation( "cartoon" );
 *     structureComponent.autoView();
 * } );
 */
var StructureComponent = /*@__PURE__*/(function (Component$$1) {
    function StructureComponent(stage, structure, params) {
        if ( params === void 0 ) params = {};

        Component$$1.call(this, stage, structure, Object.assign({ name: structure.name }, params));
        this.structure = structure;
        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 = createRingBuffer(4);
        this.pickDict = createSimpleDict();
        this.spacefillRepresentation = this.addRepresentation('spacefill', {
            sele: 'none',
            opacity: MeasurementDefaultParams.opacity,
            color: MeasurementDefaultParams.color,
            disablePicking: true,
            radiusType: 'data'
        }, true);
        this.distanceRepresentation = this.addRepresentation('distance', MeasurementDefaultParams, true);
        this.angleRepresentation = this.addRepresentation('angle', MeasurementDefaultParams, true);
        this.dihedralRepresentation = this.addRepresentation('dihedral', MeasurementDefaultParams, true);
        this.measureRepresentations = new RepresentationCollection([
            this.spacefillRepresentation,
            this.distanceRepresentation,
            this.angleRepresentation,
            this.dihedralRepresentation
        ]);
        //
        this.setDefaultAssembly(this.parameters.defaultAssembly);
    }

    if ( Component$$1 ) StructureComponent.__proto__ = Component$$1;
    StructureComponent.prototype = Object.create( Component$$1 && Component$$1.prototype );
    StructureComponent.prototype.constructor = StructureComponent;

    var prototypeAccessors = { defaultParameters: { configurable: true },type: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return StructureComponentDefaultParameters; };
    /**
     * Component type
     * @type {String}
     */
    prototypeAccessors.type.get = function () { return 'structure'; };
    /**
     * Initialize selection
     * @private
     * @param {String} sele - selection string
     * @return {undefined}
     */
    StructureComponent.prototype.initSelection = function initSelection (sele) {
        var this$1 = this;

        /**
         * Selection for {@link StructureComponent#structureView}
         * @private
         * @type {Selection}
         */
        this.selection = new Selection(sele);
        /**
         * View on {@link StructureComponent#structure}.
         * Change its selection via {@link StructureComponent#setSelection}.
         * @type {StructureView}
         */
        this.structureView = new StructureView(this.structure, this.selection);
        this.selection.signals.stringChanged.add(function () {
            this$1.structureView.setSelection(this$1.selection);
            this$1.rebuildRepresentations();
            this$1.rebuildTrajectories();
        });
    };
    /**
     * Set selection of {@link StructureComponent#structureView}
     * @param {String} string - selection string
     * @return {StructureComponent} this object
     */
    StructureComponent.prototype.setSelection = function setSelection (string) {
        this.parameters.sele = string;
        this.selection.setString(string);
        return this;
    };
    /**
     * Set the default assembly
     * @param {String} value - assembly name
     * @return {undefined}
     */
    StructureComponent.prototype.setDefaultAssembly = function setDefaultAssembly (value) {
        // filter out non-exsisting assemblies
        if (this.structure.biomolDict[value] === undefined)
            { value = ''; }
        // only set default assembly when changed
        if (this.parameters.defaultAssembly !== value) {
            var reprParams = { defaultAssembly: value };
            this.reprList.forEach(function (repr) { return repr.setParameters(reprParams); });
            this.measureRepresentations.setParameters(reprParams);
            this.parameters.defaultAssembly = value;
            this.signals.defaultAssemblyChanged.dispatch(value);
        }
        return this;
    };
    /**
     * Rebuild all representations
     * @return {undefined}
     */
    StructureComponent.prototype.rebuildRepresentations = function rebuildRepresentations () {
        this.reprList.forEach(function (repr) {
            repr.build();
        });
        this.measureRepresentations.build();
    };
    /**
     * Rebuild all trajectories
     * @return {undefined}
     */
    StructureComponent.prototype.rebuildTrajectories = function rebuildTrajectories () {
        var this$1 = this;

        this.trajList.forEach(function (trajComp) {
            trajComp.trajectory.setStructure(this$1.structureView);
        });
    };
    StructureComponent.prototype.updateRepresentations = function updateRepresentations (what) {
        Component$$1.prototype.updateRepresentations.call(this, what);
        this.measureRepresentations.update(what);
    };
    /**
     * Overrides {@link Component.updateRepresentationMatrices}
     * to also update matrix for measureRepresentations
     */
    StructureComponent.prototype.updateRepresentationMatrices = function updateRepresentationMatrices () {
        Component$$1.prototype.updateRepresentationMatrices.call(this);
        this.measureRepresentations.setParameters({ matrix: this.matrix });
    };
    StructureComponent.prototype.addRepresentation = function addRepresentation (type, params, hidden) {
        var this$1 = this;
        if ( params === void 0 ) params = {};
        if ( hidden === void 0 ) hidden = false;

        params.defaultAssembly = this.parameters.defaultAssembly;
        var reprComp = this._addRepresentation(type, this.structureView, params, hidden);
        if (!hidden) {
            reprComp.signals.parametersChanged.add(function () { return this$1.measureUpdate(); });
        }
        return reprComp;
    };
    /**
     * Add a new trajectory component to the structure
     */
    StructureComponent.prototype.addTrajectory = function addTrajectory (trajPath, params) {
        var this$1 = this;
        if ( trajPath === void 0 ) trajPath = '';
        if ( params === void 0 ) params = {};

        var traj = makeTrajectory(trajPath, this.structureView, params);
        traj.signals.frameChanged.add(function () {
            this$1.updateRepresentations({ 'position': true });
        });
        var trajComp = new TrajectoryElement(this.stage, traj, params);
        this.trajList.push(trajComp);
        this.signals.trajectoryAdded.dispatch(trajComp);
        return trajComp;
    };
    StructureComponent.prototype.removeTrajectory = function removeTrajectory (traj) {
        var idx = this.trajList.indexOf(traj);
        if (idx !== -1) {
            this.trajList.splice(idx, 1);
        }
        traj.dispose();
        this.signals.trajectoryRemoved.dispatch(traj);
    };
    StructureComponent.prototype.dispose = function dispose () {
        // copy via .slice because side effects may change trajList
        this.trajList.slice().forEach(function (traj) { return traj.dispose(); });
        this.trajList.length = 0;
        this.structure.dispose();
        this.measureRepresentations.dispose();
        Component$$1.prototype.dispose.call(this);
    };
    StructureComponent.prototype.autoView = function autoView (sele, duration) {
        if (typeof sele === 'number') {
            duration = sele;
            sele = '';
        }
        this.stage.animationControls.zoomMove(this.getCenter(sele), this.getZoom(sele), defaults(duration, 0));
    };
    StructureComponent.prototype.getBoxUntransformed = function getBoxUntransformed (sele) {
        var bb;
        if (sele) {
            bb = this.structureView.getBoundingBox(new Selection(sele));
        }
        else {
            bb = this.structureView.boundingBox;
        }
        return bb;
    };
    StructureComponent.prototype.getCenterUntransformed = function getCenterUntransformed (sele) {
        if (sele && typeof sele === 'string') {
            return this.structure.atomCenter(new Selection(sele));
        }
        else {
            return this.structure.center;
        }
    };
    StructureComponent.prototype.superpose = function superpose$1 (component, align, sele1, sele2) {
        superpose(this.structureView, component.structureView, align, sele1, sele2);
        this.updateRepresentations({ 'position': true });
        return this;
    };
    StructureComponent.prototype.getMaxRepresentationRadius = function getMaxRepresentationRadius (atomIndex) {
        var maxRadius = 0;
        var atom = this.structure.getAtomProxy(atomIndex);
        this.eachRepresentation(function (reprElem) {
            if (reprElem.getVisibility()) {
                var repr = reprElem.repr; // TODO
                maxRadius = Math.max(repr.getAtomRadius(atom), maxRadius);
            }
        });
        return maxRadius;
    };
    StructureComponent.prototype.measurePick = function measurePick (atom) {
        var pickCount = this.pickBuffer.count;
        if (this.lastPick === atom.index && pickCount >= 1) {
            if (pickCount > 1) {
                var atomList = this.pickBuffer.data;
                var atomListSorted = this.pickBuffer.data.sort();
                if (this.pickDict.has(atomListSorted)) {
                    this.pickDict.del(atomListSorted);
                }
                else {
                    this.pickDict.add(atomListSorted, atomList);
                }
                if (pickCount === 2) {
                    this.distanceRepresentation.setParameters({
                        atomPair: this.pickDict.values.filter(function (l) { return l.length === 2; })
                    });
                }
                else if (pickCount === 3) {
                    this.angleRepresentation.setParameters({
                        atomTriple: this.pickDict.values.filter(function (l) { return l.length === 3; })
                    });
                }
                else if (pickCount === 4) {
                    this.dihedralRepresentation.setParameters({
                        atomQuad: this.pickDict.values.filter(function (l) { return l.length === 4; })
                    });
                }
            }
            this.pickBuffer.clear();
            this.lastPick = undefined;
        }
        else {
            if (!this.pickBuffer.has(atom.index)) {
                this.pickBuffer.push(atom.index);
            }
            this.lastPick = atom.index;
        }
        this.measureUpdate();
    };
    StructureComponent.prototype.measureClear = function measureClear () {
        this.pickBuffer.clear();
        this.lastPick = undefined;
        this.spacefillRepresentation.setSelection('none');
    };
    StructureComponent.prototype.measureBuild = function measureBuild () {
        var md = this.measureData();
        this.distanceRepresentation.setParameters({ atomPair: md.distance });
        this.angleRepresentation.setParameters({ atomTriple: md.angle });
        this.dihedralRepresentation.setParameters({ atomQuad: md.dihedral });
    };
    StructureComponent.prototype.measureUpdate = function measureUpdate () {
        var this$1 = this;

        var pickData = this.pickBuffer.data;
        var radiusData = {};
        pickData.forEach(function (ai) {
            var r = Math.max(0.1, this$1.getMaxRepresentationRadius(ai));
            radiusData[ai] = r * (2.3 - smoothstep(0.1, 2, r));
        });
        this.spacefillRepresentation.setSelection(pickData.length ? ('@' + pickData.join(',')) : 'none');
        if (pickData.length)
            { this.spacefillRepresentation.setParameters({ radiusData: radiusData }); }
    };
    StructureComponent.prototype.measureData = function measureData () {
        var pv = this.pickDict.values;
        return {
            distance: pv.filter(function (l) { return l.length === 2; }),
            angle: pv.filter(function (l) { return l.length === 3; }),
            dihedral: pv.filter(function (l) { return l.length === 4; })
        };
    };
    /**
     * Remove all measurements, optionally limit to distance, angle or dihedral
     */
    StructureComponent.prototype.removeAllMeasurements = function removeAllMeasurements (type) {
        var pd = this.pickDict;
        var pv = pd.values;
        var remove = function (len) {
            pv.filter(function (l) { return l.length === len; }).forEach(function (l) { return pd.del(l.slice().sort()); });
        };
        if (!type || type & 1 /* Distance */)
            { remove(2); }
        if (!type || type & 2 /* Angle */)
            { remove(3); }
        if (!type || type & 4 /* Dihedral */)
            { remove(4); }
        this.measureBuild();
    };
    /**
     * Remove a measurement given as a pair, triple, quad of atom indices
     */
    StructureComponent.prototype.removeMeasurement = function removeMeasurement (atomList) {
        this.pickDict.del(atomList.slice().sort());
        this.measureBuild();
    };
    /**
     * Add a measurement given as a pair, triple, quad of atom indices
     */
    StructureComponent.prototype.addMeasurement = function addMeasurement (atomList) {
        if (atomList.length < 2 || atomList.length > 4)
            { return; }
        var atomListSorted = atomList.slice().sort();
        if (!this.pickDict.has(atomListSorted)) {
            this.pickDict.add(atomListSorted, atomList);
        }
        this.measureBuild();
    };

    Object.defineProperties( StructureComponent.prototype, prototypeAccessors );

    return StructureComponent;
}(Component));
ComponentRegistry.add('structure', StructureComponent);
ComponentRegistry.add('structureview', StructureComponent);

/**
 * @file Surface Component
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Component wrapping a {@link Surface} object
 *
 * @example
 * // get a surface component by loading a surface file into the stage
 * stage.loadFile( "url/for/surface" ).then( function( surfaceComponent ){
 *     surfaceComponent.addRepresentation( "surface" );
 *     surfaceComponent.autoView();
 * } );
 */
var SurfaceComponent = /*@__PURE__*/(function (Component$$1) {
    function SurfaceComponent(stage, surface, params) {
        if ( params === void 0 ) params = {};

        Component$$1.call(this, stage, surface, Object.assign({ name: surface.name }, params));
        this.surface = surface;
    }

    if ( Component$$1 ) SurfaceComponent.__proto__ = Component$$1;
    SurfaceComponent.prototype = Object.create( Component$$1 && Component$$1.prototype );
    SurfaceComponent.prototype.constructor = SurfaceComponent;

    var prototypeAccessors = { type: { configurable: true } };
    /**
     * Component type
     * @type {String}
     */
    prototypeAccessors.type.get = function () { return 'surface'; };
    /**
     * Add a new surface representation to the component
     * @param {String} type - the name of the representation, one of:
     *                        surface, dot.
     * @param {SurfaceRepresentationParameters} params - representation parameters
     * @return {RepresentationComponent} the created representation wrapped into
     *                                   a representation component object
     */
    SurfaceComponent.prototype.addRepresentation = function addRepresentation (type, params) {
        if ( params === void 0 ) params = {};

        return this._addRepresentation(type, this.surface, params);
    };
    SurfaceComponent.prototype.getBoxUntransformed = function getBoxUntransformed () {
        return this.surface.boundingBox;
    };
    SurfaceComponent.prototype.getCenterUntransformed = function getCenterUntransformed () {
        return this.surface.center;
    };
    SurfaceComponent.prototype.dispose = function dispose () {
        this.surface.dispose();
        Component$$1.prototype.dispose.call(this);
    };

    Object.defineProperties( SurfaceComponent.prototype, prototypeAccessors );

    return SurfaceComponent;
}(Component));
ComponentRegistry.add('surface', SurfaceComponent);

/**
 * @file Volume Component
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Component wrapping a {@link Volume} object
 *
 * @example
 * // get a volume component by loading a volume file into the stage
 * stage.loadFile( "url/for/volume" ).then(function(volumeComponent){
 *   volumeComponent.addRepresentation('surface');
 *   volumeComponent.autoView();
 * });
 */
var VolumeComponent = /*@__PURE__*/(function (Component$$1) {
    function VolumeComponent(stage, volume, params) {
        if ( params === void 0 ) params = {};

        Component$$1.call(this, stage, volume, Object.assign({ name: volume.name }, params));
        this.volume = volume;
    }

    if ( Component$$1 ) VolumeComponent.__proto__ = Component$$1;
    VolumeComponent.prototype = Object.create( Component$$1 && Component$$1.prototype );
    VolumeComponent.prototype.constructor = VolumeComponent;

    var prototypeAccessors = { type: { configurable: true } };
    /**
     * Component type
     * @type {String}
     */
    prototypeAccessors.type.get = function () { return 'volume'; };
    /**
     * Add a new volume representation to the component
     */
    VolumeComponent.prototype.addRepresentation = function addRepresentation (type, params) {
        if ( params === void 0 ) params = {};

        return this._addRepresentation(type, this.volume, params);
    };
    VolumeComponent.prototype.getBoxUntransformed = function getBoxUntransformed () {
        return this.volume.boundingBox;
    };
    VolumeComponent.prototype.getCenterUntransformed = function getCenterUntransformed () {
        return this.volume.center;
    };
    VolumeComponent.prototype.dispose = function dispose () {
        this.volume.dispose();
        Component$$1.prototype.dispose.call(this);
    };

    Object.defineProperties( VolumeComponent.prototype, prototypeAccessors );

    return VolumeComponent;
}(Component));
ComponentRegistry.add('volume', VolumeComponent);

/**
 * @file Component Collection
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var ComponentCollection = /*@__PURE__*/(function (Collection$$1) {
    function ComponentCollection () {
        Collection$$1.apply(this, arguments);
    }

    if ( Collection$$1 ) ComponentCollection.__proto__ = Collection$$1;
    ComponentCollection.prototype = Object.create( Collection$$1 && Collection$$1.prototype );
    ComponentCollection.prototype.constructor = ComponentCollection;

    ComponentCollection.prototype.addRepresentation = function addRepresentation (name, params) {
        return this.forEach(function (comp) { return comp.addRepresentation(name, params); });
    };
    ComponentCollection.prototype.autoView = function autoView (duration) {
        return this.forEach(function (comp) { return comp.autoView(duration); });
    };

    return ComponentCollection;
}(Collection));

/**
 * @file Stage
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function matchName(name, object) {
    if (name instanceof RegExp) {
        return object.name.match(name) !== null;
    }
    else {
        return object.name === name;
    }
}
var tmpZoomVector = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var StageDefaultParameters = {
    impostor: true,
    quality: 'medium',
    workerDefault: true,
    sampleLevel: 0,
    backgroundColor: 'black',
    rotateSpeed: 2.0,
    zoomSpeed: 1.2,
    panSpeed: 1.0,
    clipNear: 0,
    clipFar: 100,
    clipDist: 10,
    clipMode: 'scene',
    clipScale: 'relative',
    fogNear: 50,
    fogFar: 100,
    cameraFov: 40,
    cameraEyeSep: 0.3,
    cameraType: 'perspective',
    lightColor: 0xdddddd,
    lightIntensity: 1.0,
    ambientColor: 0xdddddd,
    ambientIntensity: 0.2,
    hoverTimeout: 0,
    tooltip: true,
    mousePreset: 'default'
};
/**
 * Stage class, central for creating molecular scenes with NGL.
 *
 * @example
 * var stage = new Stage( "elementId", { backgroundColor: "white" } );
 */
var Stage = function Stage(idOrElement, params) {
    if ( params === void 0 ) params = {};

    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"]()
    };
    /**
     * Counter that keeps track of various potentially long-running tasks,
     * including file loading and surface calculation.
     */
    this.tasks = new Counter();
    this.compList = [];
    this.defaultFileParams = {};
    this.logList = [];
    this.viewer = new Viewer(idOrElement);
    if (!this.viewer.renderer)
        { return; }
    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 MouseObserver(this.viewer.renderer.domElement);
    this.viewerControls = new ViewerControls(this);
    this.trackballControls = new TrackballControls(this);
    this.pickingControls = new PickingControls(this);
    this.animationControls = new AnimationControls(this);
    this.mouseControls = new MouseControls(this);
    this.keyControls = new KeyControls(this);
    this.pickingBehavior = new PickingBehavior(this);
    this.mouseBehavior = new MouseBehavior(this);
    this.animationBehavior = new AnimationBehavior(this);
    this.keyBehavior = new KeyBehavior(this);
    this.spinAnimation = this.animationControls.spin([0, 1, 0], 0.005);
    this.spinAnimation.pause(true);
    this.rockAnimation = this.animationControls.rock([0, 1, 0], 0.005);
    this.rockAnimation.pause(true);
    // must come after the viewer has been instantiated
    this.parameters = createParams(params, StageDefaultParameters);
    this.setParameters(this.parameters);
    this.viewer.animate();
};
/**
 * Set stage parameters
 */
Stage.prototype.setParameters = function setParameters (params) {
        if ( params === void 0 ) params = {};

    updateParams(this.parameters, params);
    var p = params;
    var tp = this.parameters;
    var viewer = this.viewer;
    var controls = this.trackballControls;
    // apply parameters
    if (p.quality !== undefined)
        { this.setQuality(tp.quality); }
    if (p.impostor !== undefined)
        { this.setImpostor(tp.impostor); }
    if (p.rotateSpeed !== undefined)
        { controls.rotateSpeed = tp.rotateSpeed; }
    if (p.zoomSpeed !== undefined)
        { controls.zoomSpeed = tp.zoomSpeed; }
    if (p.panSpeed !== undefined)
        { controls.panSpeed = tp.panSpeed; }
    if (p.mousePreset !== undefined)
        { this.mouseControls.preset(tp.mousePreset); }
    this.mouseObserver.setParameters({ hoverTimeout: tp.hoverTimeout });
    viewer.setClip(tp.clipNear, tp.clipFar, tp.clipDist, tp.clipMode, tp.clipScale);
    viewer.setFog(undefined, tp.fogNear, tp.fogFar);
    viewer.setCamera(tp.cameraType, tp.cameraFov, tp.cameraEyeSep);
    viewer.setSampling(tp.sampleLevel);
    viewer.setBackground(tp.backgroundColor);
    viewer.setLight(tp.lightColor, tp.lightIntensity, tp.ambientColor, tp.ambientIntensity);
    this.signals.parametersChanged.dispatch(this.getParameters());
    return this;
};
Stage.prototype.log = function log (msg) {
    console.log('STAGE LOG', msg);
    this.logList.push(msg);
};
/**
 * Get stage parameters
 */
Stage.prototype.getParameters = function getParameters () {
    return Object.assign({}, this.parameters);
};
/**
 * Create default representations for the given component
 * @param  {StructureComponent|SurfaceComponent} object - component to create the representations for
 * @return {undefined}
 */
Stage.prototype.defaultFileRepresentation = function defaultFileRepresentation (component) {
    if (component instanceof StructureComponent) {
        component.setSelection('/0');
        var atomCount, residueCount, instanceCount;
        var structure = component.structure;
        if (structure.biomolDict.BU1) {
            var assembly = structure.biomolDict.BU1;
            atomCount = assembly.getAtomCount(structure);
            residueCount = assembly.getResidueCount(structure);
            instanceCount = assembly.getInstanceCount();
            component.setDefaultAssembly('BU1');
        }
        else {
            atomCount = structure.getModelProxy(0).atomCount;
            residueCount = structure.getModelProxy(0).residueCount;
            instanceCount = 1;
        }
        var sizeScore = atomCount;
        if (Mobile) {
            sizeScore *= 4;
        }
        var backboneOnly = structure.atomStore.count / structure.residueStore.count < 2;
        if (backboneOnly) {
            sizeScore *= 10;
        }
        var colorScheme = 'chainname';
        var colorScale = 'RdYlBu';
        var colorReverse = false;
        if (structure.getChainnameCount(new Selection('polymer and /0')) === 1) {
            colorScheme = 'residueindex';
            colorScale = 'spectral';
            colorReverse = true;
        }
        if (Debug)
            { console.log(sizeScore, atomCount, instanceCount, backboneOnly); }
        if (residueCount / instanceCount < 4) {
            component.addRepresentation('ball+stick', {
                colorScheme: 'element',
                radiusScale: 2.0,
                aspectRatio: 1.5,
                bondScale: 0.3,
                bondSpacing: 0.75,
                quality: 'auto'
            });
        }
        else if ((instanceCount > 5 && sizeScore > 15000) || sizeScore > 700000) {
            var scaleFactor = (Math.min(1.5, Math.max(0.1, 2000 / (sizeScore / instanceCount))));
            if (backboneOnly)
                { scaleFactor = Math.min(scaleFactor, 0.15); }
            component.addRepresentation('surface', {
                colorScheme: colorScheme, colorScale: colorScale, colorReverse: colorReverse,
                sele: 'polymer',
                surfaceType: 'sas',
                probeRadius: 1.4,
                scaleFactor: scaleFactor,
                useWorker: false
            });
        }
        else if (sizeScore > 250000) {
            component.addRepresentation('backbone', {
                colorScheme: colorScheme, colorScale: colorScale, colorReverse: colorReverse,
                lineOnly: true
            });
        }
        else if (sizeScore > 100000) {
            component.addRepresentation('backbone', {
                colorScheme: colorScheme, colorScale: colorScale, colorReverse: colorReverse,
                quality: 'low',
                disableImpostor: true,
                radiusScale: 2.0
            });
        }
        else if (sizeScore > 80000) {
            component.addRepresentation('backbone', {
                colorScheme: colorScheme, colorScale: colorScale, colorReverse: colorReverse,
                radiusScale: 2.0
            });
        }
        else {
            component.addRepresentation('cartoon', {
                colorScheme: colorScheme, colorScale: colorScale, colorReverse: colorReverse,
                radiusScale: 0.7,
                aspectRatio: 5,
                quality: 'auto'
            });
            if (sizeScore < 50000) {
                component.addRepresentation('base', {
                    colorScheme: colorScheme, colorScale: colorScale, colorReverse: colorReverse,
                    quality: 'auto'
                });
            }
            component.addRepresentation('ball+stick', {
                sele: 'ligand',
                colorScheme: 'element',
                radiusScale: 2.0,
                aspectRatio: 1.5,
                bondScale: 0.3,
                bondSpacing: 0.75,
                quality: 'auto'
            });
        }
        // add frames as trajectory
        if (component.structure.frames.length) {
            component.addTrajectory();
        }
    }
    else if (component instanceof SurfaceComponent) {
        component.addRepresentation('surface');
    }
    else if (component instanceof VolumeComponent) {
        component.addRepresentation('surface');
    }
    this.tasks.onZeroOnce(this.autoView, this);
};
/**
 * Load a file onto the stage
 *
 * @example
 * // load from URL
 * stage.loadFile( "http://files.rcsb.org/download/5IOS.cif" );
 *
 * @example
 * // load binary data in CCP4 format via a Blob
 * var binaryBlob = new Blob( [ ccp4Data ], { type: 'application/octet-binary'} );
 * stage.loadFile( binaryBlob, { ext: "ccp4" } );
 *
 * @example
 * // load string data in PDB format via a Blob
 * var stringBlob = new Blob( [ pdbData ], { type: 'text/plain'} );
 * stage.loadFile( stringBlob, { ext: "pdb" } );
 *
 * @example
 * // load a File object
 * stage.loadFile( file );
 *
 * @example
 * // load from URL and add a 'ball+stick' representation with double/triple bonds
 * stage.loadFile( "http://files.rcsb.org/download/1crn.cif" ).then( function( comp ){
 * comp.addRepresentation( "ball+stick", { multipleBond: true } );
 * } );
 *
 * @param  {String|File|Blob} path - either a URL or an object containing the file data
 * @param  {LoaderParameters} params - loading parameters
 * @param  {Boolean} params.asTrajectory - load multi-model structures as a trajectory
 * @return {Promise} A Promise object that resolves to a {@link StructureComponent},
 *               a {@link SurfaceComponent} or a {@link ScriptComponent} object,
 *               depending on the type of the loaded file.
 */
Stage.prototype.loadFile = function loadFile (path, params) {
        var this$1 = this;
        if ( params === void 0 ) params = {};

    var p = Object.assign({}, this.defaultFileParams, params);
    var name = getFileInfo(path).name;
    this.tasks.increment();
    this.log(("loading file '" + name + "'"));
    var onLoadFn = function (object) {
        this$1.log(("loaded '" + name + "'"));
        var component = this$1.addComponentFromObject(object, p);
        if (p.defaultRepresentation) {
            this$1.defaultFileRepresentation(component);
        }
        this$1.tasks.decrement();
        return component;
    };
    var onErrorFn = function (e) {
        this$1.tasks.decrement();
        var errorMsg = "error loading file: '" + e + "'";
        this$1.log(errorMsg);
        throw errorMsg; // throw so it can be catched
    };
    var ext = defaults(p.ext, getFileInfo(path).ext);
    var promise;
    if (ParserRegistry$1.isTrajectory(ext)) {
        promise = Promise.reject(new Error(("loadFile: ext '" + ext + "' is a trajectory and must be loaded into a structure component")));
    }
    else {
        promise = autoLoad(path, p);
    }
    return promise.then(onLoadFn, onErrorFn);
};
Stage.prototype.loadScript = function loadScript (path) {
        var this$1 = this;

    var name = getFileInfo(path).name;
    this.log(("loading script '" + name + "'"));
    return autoLoad(path).then(function (script) {
        this$1.tasks.increment();
        this$1.log(("running script '" + name + "'"));
        script.run(this$1).then(function () {
            this$1.tasks.decrement();
            this$1.log(("finished script '" + name + "'"));
        });
        this$1.log(("called script '" + name + "'"));
    }, function (error) {
        this$1.tasks.decrement();
        var errorMsg = "errored script '" + name + "' \"" + error + "\"";
        this$1.log(errorMsg);
        throw errorMsg; // throw so it can be catched
    });
};
/**
 * Add the given component to the stage
 * @param {Component} component - the component to add
 * @return {undefined}
 */
Stage.prototype.addComponent = function addComponent (component) {
    if (!component) {
        Log.warn('Stage.addComponent: no component given');
        return;
    }
    this.compList.push(component);
    this.signals.componentAdded.dispatch(component);
};
/**
 * Create a component from the given object and add to the stage
 */
Stage.prototype.addComponentFromObject = function addComponentFromObject (object, params) {
        if ( params === void 0 ) params = {};

    var CompClass = ComponentRegistry.get(object.type);
    if (CompClass) {
        var component = new CompClass(this, object, params);
        this.addComponent(component);
        return component;
    }
    Log.warn('no component for object type', object.type);
};
/**
 * Remove the given component
 * @param  {Component} component - the component to remove
 * @return {undefined}
 */
Stage.prototype.removeComponent = function removeComponent (component) {
    var idx = this.compList.indexOf(component);
    if (idx !== -1) {
        this.compList.splice(idx, 1);
        component.dispose();
        this.signals.componentRemoved.dispatch(component);
    }
};
/**
 * Remove all components from the stage
 */
Stage.prototype.removeAllComponents = function removeAllComponents () {
        var this$1 = this;

    this.compList.slice().forEach(function (o) { return this$1.removeComponent(o); });
};
/**
 * Handle any size-changes of the container element
 * @return {undefined}
 */
Stage.prototype.handleResize = function handleResize () {
    this.viewer.handleResize();
};
/**
 * Set width and height
 * @param {String} width - CSS width value
 * @param {String} height - CSS height value
 * @return {undefined}
 */
Stage.prototype.setSize = function setSize (width, height) {
    var container = this.viewer.container;
    if (container !== document.body) {
        if (width !== undefined)
            { container.style.width = width; }
        if (height !== undefined)
            { container.style.height = height; }
        this.handleResize();
    }
};
/**
 * Toggle fullscreen
 * @param  {Element} [element] - document element to put into fullscreen,
 *                           defaults to the viewer container
 * @return {undefined}
 */
Stage.prototype.toggleFullscreen = function toggleFullscreen (element) {
    if (!document.fullscreenEnabled && !document.mozFullScreenEnabled &&
        !document.webkitFullscreenEnabled && !document.msFullscreenEnabled) {
        Log.log('fullscreen mode (currently) not possible');
        return;
    }
    var self = this;
    element = element || this.viewer.container;
    this.lastFullscreenElement = element;
    //
    function getFullscreenElement() {
        return document.fullscreenElement || document.mozFullScreenElement ||
            document.webkitFullscreenElement || document.msFullscreenElement;
    }
    function resizeElement() {
        if (!getFullscreenElement() && self.lastFullscreenElement) {
            var element = self.lastFullscreenElement;
            element.style.width = element.dataset.normalWidth || '';
            element.style.height = element.dataset.normalHeight || '';
            document.removeEventListener('fullscreenchange', resizeElement);
            document.removeEventListener('mozfullscreenchange', resizeElement);
            document.removeEventListener('webkitfullscreenchange', resizeElement);
            document.removeEventListener('MSFullscreenChange', resizeElement);
            self.handleResize();
            self.signals.fullscreenChanged.dispatch(false);
        }
    }
    //
    if (!getFullscreenElement()) {
        element.dataset.normalWidth = element.style.width || '';
        element.dataset.normalHeight = element.style.height || '';
        element.style.width = window.screen.width + 'px';
        element.style.height = window.screen.height + 'px';
        if (element.requestFullscreen) {
            element.requestFullscreen();
        }
        else if (element.msRequestFullscreen) {
            element.msRequestFullscreen();
        }
        else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        }
        else if (element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
        }
        document.addEventListener('fullscreenchange', resizeElement);
        document.addEventListener('mozfullscreenchange', resizeElement);
        document.addEventListener('webkitfullscreenchange', resizeElement);
        document.addEventListener('MSFullscreenChange', resizeElement);
        this.handleResize();
        this.signals.fullscreenChanged.dispatch(true);
        // workaround for Safari
        setTimeout(function () { self.handleResize(); }, 100);
    }
    else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
        else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
        else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        }
        else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }
};
/**
 * Set spin
 * @param {Boolean} flag - if true start rocking and stop spinning
 * @return {undefined}
 */
Stage.prototype.setSpin = function setSpin (flag) {
    if (flag) {
        this.spinAnimation.resume(true);
        this.rockAnimation.pause(true);
    }
    else {
        this.spinAnimation.pause(true);
    }
};
/**
 * Set rock
 * @param {Boolean} flag - if true start rocking and stop spinning
 * @return {undefined}
 */
Stage.prototype.setRock = function setRock (flag) {
    if (flag) {
        this.rockAnimation.resume(true);
        this.spinAnimation.pause(true);
    }
    else {
        this.rockAnimation.pause(true);
    }
};
/**
 * Toggle spin
 * @return {undefined}
 */
Stage.prototype.toggleSpin = function toggleSpin () {
    this.setSpin(this.spinAnimation.paused);
};
/**
 * Toggle rock
 * @return {undefined}
 */
Stage.prototype.toggleRock = function toggleRock () {
    this.setRock(this.rockAnimation.paused);
};
/**
 * Get the current focus from the current clipNear value expressed
 * as 0 (full view) to 100 (completely clipped)
 * Negative values may be returned in some cases.
 *
 * In 'camera' clipMode focus isn't applicable, this method returns 0.0
 *
 * @return {number} focus
 */
Stage.prototype.getFocus = function getFocus () {
    var p = this.parameters;
    if (p.clipMode !== 'scene')
        { return 0.0; }
    var clipNear = p.clipNear;
    if (p.clipScale === 'absolute') {
        clipNear = this.viewer.absoluteToRelative(clipNear);
    }
    return clipNear * 2;
};
/**
 * Set the focus, a value of 0 sets clipping planes to show full scene,
 * while a value of 100 will compltely clip the scene.
 *
 * @param {number} value focus
 */
Stage.prototype.setFocus = function setFocus (value) {
    if (this.parameters.clipMode !== 'scene')
        { return; }
    var clipNear;
    var clipFar;
    var fogNear;
    var fogFar;
    if (this.parameters.clipScale === 'relative') {
        clipNear = clamp(value / 2.0, 0.0, 49.9);
        clipFar = 100 - clipNear;
        fogNear = 50;
        fogFar = pclamp(2 * clipFar - 50);
    }
    else {
        clipNear = this.viewer.relativeToAbsolute(value / 2.0);
        clipFar = clipNear;
        fogNear = 0;
        fogFar = 2 * clipFar;
    }
    this.setParameters({ clipNear: clipNear, clipFar: clipFar, fogNear: fogNear, fogFar: fogFar });
};
Stage.prototype.getZoomForBox = function getZoomForBox (boundingBox) {
    var bbSize = boundingBox.getSize(tmpZoomVector);
    var maxSize = Math.max(bbSize.x, bbSize.y, bbSize.z);
    var minSize = Math.min(bbSize.x, bbSize.y, bbSize.z);
    var distance = maxSize + Math.sqrt(minSize);
    var fov = degToRad(this.viewer.perspectiveCamera.fov);
    var width = this.viewer.width;
    var height = this.viewer.height;
    var aspect = width / height;
    var aspectFactor = (height < width ? 1 : aspect);
    distance = Math.abs(((distance * 0.5) / aspectFactor) / Math.sin(fov / 2));
    distance += this.parameters.clipDist;
    return -distance;
};
Stage.prototype.getBox = function getBox () {
    return this.viewer.boundingBox;
};
Stage.prototype.getZoom = function getZoom () {
    return this.getZoomForBox(this.getBox());
};
Stage.prototype.getCenter = function getCenter (optionalTarget) {
    return this.getBox().getCenter(optionalTarget || new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]());
};
/**
 * Add a zoom and a move animation with automatic targets
 * @param  {Integer} duration - animation time in milliseconds
 * @return {undefined}
 */
Stage.prototype.autoView = function autoView (duration) {
    this.animationControls.zoomMove(this.getCenter(), this.getZoom(), defaults(duration, 0));
};
/**
 * Make image from what is shown in a viewer canvas
 */
Stage.prototype.makeImage = function makeImage (params) {
        var this$1 = this;
        if ( params === void 0 ) params = {};

    return new Promise(function (resolve, reject) {
        this$1.tasks.onZeroOnce(function () {
            this$1.tasks.increment();
            this$1.viewer.makeImage(params).then(function (blob) {
                this$1.tasks.decrement();
                resolve(blob);
            }).catch(function (e) {
                this$1.tasks.decrement();
                reject(e);
            });
        });
    });
};
Stage.prototype.setImpostor = function setImpostor (value) {
    this.parameters.impostor = value;
    var types = [
        'spacefill', 'ball+stick', 'licorice', 'hyperball',
        'backbone', 'rocket', 'helixorient', 'contact', 'distance',
        'dot'
    ];
    this.eachRepresentation(function (reprElem) {
        if (!types.includes(reprElem.getType()))
            { return; }
        var p = reprElem.getParameters(); // TODO
        p.disableImpostor = !value;
        reprElem.build(p);
    });
};
Stage.prototype.setQuality = function setQuality (value) {
    this.parameters.quality = value;
    var types = [
        'tube', 'cartoon', 'ribbon', 'trace', 'rope'
    ];
    var impostorTypes = [
        'spacefill', 'ball+stick', 'licorice', 'hyperball',
        'backbone', 'rocket', 'helixorient', 'contact', 'distance',
        'dot'
    ];
    this.eachRepresentation(function (repr) {
        var p = repr.getParameters(); // TODO
        if (!types.includes(repr.getType())) {
            if (!impostorTypes.includes(repr.getType()))
                { return; }
            if (!p.disableImpostor) {
                repr.repr.quality = value; // TODO
                return;
            }
        }
        p.quality = value;
        repr.build(p);
    });
};
/**
 * Iterator over each component and executing the callback
 */
Stage.prototype.eachComponent = function eachComponent (callback, type) {
    this.compList.slice().forEach(function (comp) {
        if (type === undefined || type === comp.type)
            { callback(comp); }
    });
};
/**
 * Iterator over each representation and executing the callback
 */
Stage.prototype.eachRepresentation = function eachRepresentation (callback, type) {
    this.eachComponent(function (comp) {
        comp.reprList.slice().forEach(function (reprElem) {
            if (type === undefined || type === reprElem.getType())
                { callback(reprElem, comp); }
        });
    });
};
/**
 * Get collection of components by name
 */
Stage.prototype.getComponentsByName = function getComponentsByName (name) {
    var compList = [];
    this.eachComponent(function (comp) {
        if (name === undefined || matchName(name, comp))
            { compList.push(comp); }
    });
    return new ComponentCollection(compList);
};
/**
 * Get collection of components by object
 */
Stage.prototype.getComponentsByObject = function getComponentsByObject (object) {
    var compList = [];
    this.eachComponent(function (comp) {
        if (comp.object === object)
            { compList.push(comp); }
    });
    return new ComponentCollection(compList);
};
/**
 * Get collection of representations by name
 */
Stage.prototype.getRepresentationsByName = function getRepresentationsByName (name) {
    var reprList = [];
    this.eachRepresentation(function (repr, comp) {
        if (name === undefined || matchName(name, repr))
            { reprList.push(repr); }
    });
    return new RepresentationCollection(reprList);
};
Stage.prototype.measureClear = function measureClear () {
    this.eachComponent(function (sc) { return sc.measureClear(); }, 'structure');
};
Stage.prototype.measureUpdate = function measureUpdate () {
    this.eachComponent(function (sc) { return sc.measureUpdate(); }, 'structure');
};
/**
 * Cleanup when disposing of a stage object
 */
Stage.prototype.dispose = function dispose () {
    this.tasks.dispose();
    this.viewer.dispose();
};

/**
 * @file Shape Component
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Component wrapping a {@link Shape} object
 *
 * @example
 * // get a shape component by adding a shape object to the stage
 * var shape = new NGL.Shape( "shape" );
 * shape.addSphere( [ 0, 0, 0 ], [ 1, 0, 0 ], 1.5 );
 * var shapeComponent = stage.addComponentFromObject( shape );
 * shapeComponent.addRepresentation( "buffer" );
 */
var ShapeComponent = /*@__PURE__*/(function (Component$$1) {
    function ShapeComponent(stage, shape, params) {
        if ( params === void 0 ) params = {};

        Component$$1.call(this, stage, shape, Object.assign({ name: shape.name }, params));
        this.shape = shape;
    }

    if ( Component$$1 ) ShapeComponent.__proto__ = Component$$1;
    ShapeComponent.prototype = Object.create( Component$$1 && Component$$1.prototype );
    ShapeComponent.prototype.constructor = ShapeComponent;

    var prototypeAccessors = { type: { configurable: true } };
    /**
     * Component type
     * @type {String}
     */
    prototypeAccessors.type.get = function () { return 'shape'; };
    /**
     * Add a new shape representation to the component
     * @param {String} type - the name of the representation, one of:
     *                        buffer.
     * @param {BufferRepresentationParameters} params - representation parameters
     * @return {RepresentationComponent} the created representation wrapped into
     *                                   a representation component object
     */
    ShapeComponent.prototype.addRepresentation = function addRepresentation (type, params) {
        if ( params === void 0 ) params = {};

        return this._addRepresentation(type, this.shape, params);
    };
    ShapeComponent.prototype.getBoxUntransformed = function getBoxUntransformed () {
        return this.shape.boundingBox;
    };
    ShapeComponent.prototype.getCenterUntransformed = function getCenterUntransformed () {
        return this.shape.center;
    };
    ShapeComponent.prototype.dispose = function dispose () {
        this.shape.dispose();
        Component$$1.prototype.dispose.call(this);
    };

    Object.defineProperties( ShapeComponent.prototype, prototypeAccessors );

    return ShapeComponent;
}(Component));
ComponentRegistry.add('shape', ShapeComponent);

/**
 * @file Atomindex Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by atom index. The {@link AtomProxy.index} property is used for coloring.
 * Each {@link ModelProxy} of a {@link Structure} is colored seperately. The
 * `params.domain` parameter is ignored.
 *
 * __Name:__ _atomindex_
 *
 * @example
 * stage.loadFile( "rcsb://1crn" ).then( function( o ){
 *     o.addRepresentation( "ball+stick", { colorScheme: "atomindex" } );
 *     o.autoView();
 * } );
 */
var AtomindexColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function AtomindexColormaker(params) {
        var this$1 = this;

        Colormaker$$1.call(this, params);
        if (!params.scale) {
            this.parameters.scale = 'rainbow';
            this.parameters.reverse = defaults(params.reverse, true);
        }
        this.scalePerModel = {};
        params.structure.eachModel(function (mp) {
            this$1.parameters.domain = [mp.atomOffset, mp.atomEnd];
            this$1.scalePerModel[mp.index] = this$1.getScale(); // TODO
        });
    }

    if ( Colormaker$$1 ) AtomindexColormaker.__proto__ = Colormaker$$1;
    AtomindexColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    AtomindexColormaker.prototype.constructor = AtomindexColormaker;
    /**
     * get color for an atom
     * @param  {AtomProxy} atom - atom to get color for
     * @return {Integer} hex atom color
     */
    AtomindexColormaker.prototype.atomColor = function atomColor (atom) {
        return this.scalePerModel[atom.modelIndex](atom.index);
    };

    return AtomindexColormaker;
}(Colormaker));
ColormakerRegistry$1.add('atomindex', AtomindexColormaker); // TODO

/**
 * @file Bfactor Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by b-factor. The {@link AtomProxy.bfactor} property is used for coloring.
 * By default the min and max b-factor values are used for the scale`s domain.
 *
 * __Name:__ _bfactor_
 *
 * @example
 * stage.loadFile( "rcsb://1crn" ).then( function( o ){
 *     o.addRepresentation( "ball+stick", { colorScheme: "bfactor" } );
 *     o.autoView();
 * } );
 */
var BfactorColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function BfactorColormaker(params) {
        Colormaker$$1.call(this, params);
        if (!params.scale) {
            this.parameters.scale = 'OrRd';
        }
        if (!params.domain) {
            var selection;
            var min = Infinity;
            var max = -Infinity;
            if (params.sele) {
                selection = new Selection(params.sele);
            }
            params.structure.eachAtom(function (a) {
                var bfactor = a.bfactor;
                min = Math.min(min, bfactor);
                max = Math.max(max, bfactor);
            }, selection);
            this.parameters.domain = [min, max];
        }
        this.bfactorScale = this.getScale();
    }

    if ( Colormaker$$1 ) BfactorColormaker.__proto__ = Colormaker$$1;
    BfactorColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    BfactorColormaker.prototype.constructor = BfactorColormaker;
    BfactorColormaker.prototype.atomColor = function atomColor (a) {
        return this.bfactorScale(a.bfactor);
    };

    return BfactorColormaker;
}(Colormaker));
ColormakerRegistry$1.add('bfactor', BfactorColormaker);

/**
 * @file Chainid Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by chain id
 */
var ChainidColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function ChainidColormaker(params) {
        var this$1 = this;

        Colormaker$$1.call(this, params);
        this.chainidDictPerModel = {};
        this.scalePerModel = {};
        if (!params.scale) {
            this.parameters.scale = 'Spectral';
        }
        params.structure.eachModel(function (mp) {
            var i = 0;
            var chainidDict = {};
            mp.eachChain(function (cp) {
                if (chainidDict[cp.chainid] === undefined) {
                    chainidDict[cp.chainid] = i;
                    i += 1;
                }
            });
            this$1.parameters.domain = [0, i - 1];
            this$1.chainidDictPerModel[mp.index] = chainidDict;
            this$1.scalePerModel[mp.index] = this$1.getScale();
        });
    }

    if ( Colormaker$$1 ) ChainidColormaker.__proto__ = Colormaker$$1;
    ChainidColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    ChainidColormaker.prototype.constructor = ChainidColormaker;
    ChainidColormaker.prototype.atomColor = function atomColor (a) {
        var chainidDict = this.chainidDictPerModel[a.modelIndex];
        return this.scalePerModel[a.modelIndex](chainidDict[a.chainid]);
    };

    return ChainidColormaker;
}(Colormaker));
ColormakerRegistry$1.add('chainid', ChainidColormaker);

/**
 * @file Chainindex Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by chain index
 */
var ChainindexColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function ChainindexColormaker(params) {
        var this$1 = this;

        Colormaker$$1.call(this, params);
        this.scalePerModel = {};
        if (!params.scale) {
            this.parameters.scale = 'Spectral';
        }
        params.structure.eachModel(function (mp) {
            this$1.parameters.domain = [mp.chainOffset, mp.chainEnd];
            this$1.scalePerModel[mp.index] = this$1.getScale();
        });
    }

    if ( Colormaker$$1 ) ChainindexColormaker.__proto__ = Colormaker$$1;
    ChainindexColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    ChainindexColormaker.prototype.constructor = ChainindexColormaker;
    ChainindexColormaker.prototype.atomColor = function atomColor (a) {
        return this.scalePerModel[a.modelIndex](a.chainIndex);
    };

    return ChainindexColormaker;
}(Colormaker));
ColormakerRegistry$1.add('chainindex', ChainindexColormaker);

/**
 * @file Chainname Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by chain name
 */
var ChainnameColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function ChainnameColormaker(params) {
        var this$1 = this;

        Colormaker$$1.call(this, params);
        this.chainnameDictPerModel = {};
        this.scalePerModel = {};
        if (!params.scale) {
            this.parameters.scale = 'Spectral';
        }
        params.structure.eachModel(function (mp) {
            var i = 0;
            var chainnameDict = {};
            mp.eachChain(function (cp) {
                if (chainnameDict[cp.chainname] === undefined) {
                    chainnameDict[cp.chainname] = i;
                    i += 1;
                }
            });
            this$1.parameters.domain = [0, i - 1];
            this$1.chainnameDictPerModel[mp.index] = chainnameDict;
            this$1.scalePerModel[mp.index] = this$1.getScale();
        });
    }

    if ( Colormaker$$1 ) ChainnameColormaker.__proto__ = Colormaker$$1;
    ChainnameColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    ChainnameColormaker.prototype.constructor = ChainnameColormaker;
    ChainnameColormaker.prototype.atomColor = function atomColor (a) {
        var chainnameDict = this.chainnameDictPerModel[a.modelIndex];
        return this.scalePerModel[a.modelIndex](chainnameDict[a.chainname]);
    };

    return ChainnameColormaker;
}(Colormaker));
ColormakerRegistry$1.add('chainname', ChainnameColormaker);

/**
 * @file Densityfit Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by validation density fit
 */
var DensityfitColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function DensityfitColormaker(params) {
        Colormaker$$1.call(this, params);
        this.rsrzDict = {};
        this.rsccDict = {};
        if (!params.scale) {
            this.parameters.scale = 'RdYlBu';
        }
        this.rsrzScale = this.getScale({ domain: [2, 0] });
        this.rsccScale = this.getScale({ domain: [0.678, 1.0] });
        var val = params.structure.validation;
        if (val) {
            this.rsrzDict = val.rsrzDict;
            this.rsccDict = val.rsccDict;
        }
    }

    if ( Colormaker$$1 ) DensityfitColormaker.__proto__ = Colormaker$$1;
    DensityfitColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    DensityfitColormaker.prototype.constructor = DensityfitColormaker;
    DensityfitColormaker.prototype.atomColor = function atomColor (atom) {
        var sele = atom.resno + '';
        if (atom.inscode)
            { sele += '^' + atom.inscode; }
        if (atom.chainname)
            { sele += ':' + atom.chainname; }
        sele += '/' + atom.modelIndex;
        var rsrz = this.rsrzDict[sele];
        if (rsrz !== undefined) {
            return this.rsrzScale(rsrz);
        }
        var rscc = this.rsccDict[sele];
        if (rscc !== undefined) {
            return this.rsccScale(rscc);
        }
        return 0x909090;
    };

    return DensityfitColormaker;
}(Colormaker));
ColormakerRegistry$1.add('densityfit', DensityfitColormaker);

/**
 * @file Atomindex Colormaker
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// from CHARMM
var partialCharges = {
    'ARG': {
        'CD': 0.1,
        'CZ': 0.5,
        'NE': -0.1
    },
    'ASN': {
        'CG': 0.55,
        'OD1': -0.55
    },
    'ASP': {
        'CB': -0.16,
        'CG': 0.36,
        'OD1': -0.6,
        'OD2': -0.6
    },
    'CYS': {
        'CB': 0.19,
        'SG': -0.19
    },
    'GLN': {
        'CD': 0.55,
        'OE1': -0.55
    },
    'GLU': {
        'CD': 0.36,
        'CG': -0.16,
        'OE1': -0.6,
        'OE2': -0.6
    },
    'HIS': {
        'CB': 0.1,
        'CD2': 0.2,
        'CE1': 0.45,
        'CG': 0.15,
        'ND1': 0.05,
        'NE2': 0.05
    },
    'LYS': {
        'CE': 0.25,
        'NZ': 0.75
    },
    'MET': {
        'CE': 0.06,
        'CG': 0.06,
        'SD': -0.12
    },
    'PTR': {
        'C': 0.55,
        'CA': 0.1,
        'CZ': 0.25,
        'N': -0.35,
        'O': -0.55,
        'O1P': -0.85,
        'O2P': -0.85,
        'O3P': -0.85,
        'OG1': -1.1,
        'P': 1.4
    },
    'SEP': {
        'C': 0.55,
        'CA': 0.1,
        'CB': 0.25,
        'N': -0.35,
        'O': -0.55,
        'O1P': -0.85,
        'O2P': -0.85,
        'O3P': -0.85,
        'OG1': -1.1,
        'P': 1.4
    },
    'SER': {
        'CB': 0.25,
        'OG': -0.25
    },
    'THR': {
        'CB': 0.25,
        'OG1': -0.25
    },
    'TPO': {
        'C': 0.55,
        'CA': 0.1,
        'CB': 0.25,
        'N': -0.35,
        'O': -0.55,
        'OG1': -1.1,
        'O1P': -0.85,
        'O2P': -0.85,
        'O3P': -0.85,
        'P': 1.4
    },
    'TRP': {
        'CD1': 0.06,
        'CD2': 0.1,
        'CE2': -0.04,
        'CE3': -0.03,
        'CG': -0.03,
        'NE1': -0.06
    },
    'TYR': {
        'CZ': 0.25,
        'OH': -0.25
    },
    'backbone': {
        'C': 0.55,
        'O': -0.55,
        'N': -0.35,
        'CA': 0.1
    }
};
var maxRadius = 12.0;
var nHBondDistance = 1.04;
var nHCharge = 0.25;
/**
 * Populates position vector with location of implicit or explicit H
 * Returns position or undefined if not able to locate H
 *
 * @param {AtomProxy} ap - the nitrogen atom
 * @param {Vector3} [position] - optional target
 * @return {Vectors|undefined} the hydrogen atom position
 */
function backboneNHPosition(ap, position) {
    if ( position === void 0 ) position = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();

    var h = false;
    var ca = false;
    var c = false;
    position.set(2 * ap.x, 2 * ap.y, 2 * ap.z);
    ap.eachBondedAtom(function (a2) {
        // Any time we detect H, reset position and skip
        // future tests
        if (h)
            { return; }
        if (a2.atomname === 'H') {
            position.set(a2.x, a2.y, a2.z);
            h = true;
            return;
        }
        if (!ca && a2.atomname === 'CA') {
            position.sub(a2); // TODO
            ca = true;
        }
        else if (!c && a2.atomname === 'C') {
            c = true;
            position.sub(a2); // TODO
        }
    });
    if (h) {
        return position;
    }
    if (ca && c) {
        position.normalize();
        position.multiplyScalar(nHBondDistance);
        position.add(ap);
        return position;
    }
}
/**
 * Takes an array of Vector3 objects and
 * converts to an object that looks like an AtomStore
 *
 * @param {Vector3[]} positions - array of positions
 * @return {Object} AtomStore-like object
 */
function buildStoreLike(positions) {
    var n = positions.length;
    var x = new Float32Array(n);
    var y = new Float32Array(n);
    var z = new Float32Array(n);
    for (var i = 0; i < positions.length; i++) {
        var v = positions[i];
        x[i] = v.x;
        y[i] = v.y;
        z[i] = v.z;
    }
    return { x: x, y: y, z: z, count: n };
}
function chargeForAtom(a) {
    if (a.partialCharge !== null)
        { return a.partialCharge; }
    if (!a.isProtein()) {
        return 0.0;
    }
    return ((partialCharges[a.resname] &&
        partialCharges[a.resname][a.atomname]) ||
        partialCharges['backbone'][a.atomname] || 0.0);
}
/**
 * Color a surface by electrostatic charge. This is a highly approximate
 * calculation! The partial charges are CHARMM with hydrogens added to heavy
 * atoms and hydrogen positions generated for amides.
 *
 * __Name:__ _electrostatic_
 *
 * @example
 * stage.loadFile( "rcsb://3dqb" ).then( function( o ){
 *     o.addRepresentation( "surface", { colorScheme: "electrostatic" } );
 *     o.autoView();
 * } );
 */
var ElectrostaticColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function ElectrostaticColormaker(params) {
        var this$1 = this;

        Colormaker$$1.call(this, params);
        this.delta = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        this.hCharges = [];
        if (!params.scale) {
            this.parameters.scale = 'rwb';
        }
        if (!params.domain) {
            this.parameters.domain = [-50, 50];
        }
        this.scale = this.getScale();
        this.charges = new Float32Array(params.structure.atomCount);
        var hPositions = [];
        params.structure.eachAtom(function (ap) {
            this$1.charges[ap.index] = chargeForAtom(ap) * ap.occupancy;
            if (ap.atomname === 'N') {
                // In the specific case where N forms two bonds to
                // CA and C, try and place a dummy hydrogen
                if (ap.bondCount >= 3)
                    { return; } // Skip if 3 bonds already (e.g. PRO)
                if (ap.bondToElementCount(1))
                    { return; } // Skip if any H specificed
                var hPos = backboneNHPosition(ap);
                if (hPos !== undefined) {
                    hPositions.push(hPos);
                    this$1.hCharges.push(nHCharge * ap.occupancy);
                }
            }
        });
        var bbox = params.structure.getBoundingBox();
        bbox.expandByScalar(nHBondDistance); // Worst case
        // SpatialHash requires x,y,z and count
        this.hStore = buildStoreLike(hPositions);
        this.hHash = new SpatialHash(this.hStore, bbox); // TODO
        this.hash = new SpatialHash(params.structure.atomStore, bbox);
    }

    if ( Colormaker$$1 ) ElectrostaticColormaker.__proto__ = Colormaker$$1;
    ElectrostaticColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    ElectrostaticColormaker.prototype.constructor = ElectrostaticColormaker;
    ElectrostaticColormaker.prototype.positionColor = function positionColor (v) {
        var charges = this.charges;
        var hCharges = this.hCharges;
        var p = 0.0;
        this.hash.eachWithin(v.x, v.y, v.z, maxRadius, function (atomIndex, dSq) {
            var charge = charges[atomIndex];
            if (charge === 0.0)
                { return; }
            p += charge / dSq;
        });
        this.hHash.eachWithin(v.x, v.y, v.z, maxRadius, function (atomIndex, dSq) {
            var charge = hCharges[atomIndex];
            if (charge === 0.0)
                { return; }
            p += charge / dSq;
        });
        return this.scale(p * 332); // 332 to convert to kcal/mol
    };

    return ElectrostaticColormaker;
}(Colormaker));
ColormakerRegistry$1.add('electrostatic', ElectrostaticColormaker);

/**
 * @file Element Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// from Jmol http://jmol.sourceforge.net/jscolors/ (or 0xFFFFFF)
var ElementColors = {
    'H': 0xFFFFFF,
    'HE': 0xD9FFFF,
    'LI': 0xCC80FF,
    'BE': 0xC2FF00,
    'B': 0xFFB5B5,
    'C': 0x909090,
    'N': 0x3050F8,
    'O': 0xFF0D0D,
    'F': 0x90E050,
    'NE': 0xB3E3F5,
    'NA': 0xAB5CF2,
    'MG': 0x8AFF00,
    'AL': 0xBFA6A6,
    'SI': 0xF0C8A0,
    'P': 0xFF8000,
    'S': 0xFFFF30,
    'CL': 0x1FF01F,
    'AR': 0x80D1E3,
    'K': 0x8F40D4,
    'CA': 0x3DFF00,
    'SC': 0xE6E6E6,
    'TI': 0xBFC2C7,
    'V': 0xA6A6AB,
    'CR': 0x8A99C7,
    'MN': 0x9C7AC7,
    'FE': 0xE06633,
    'CO': 0xF090A0,
    'NI': 0x50D050,
    'CU': 0xC88033,
    'ZN': 0x7D80B0,
    'GA': 0xC28F8F,
    'GE': 0x668F8F,
    'AS': 0xBD80E3,
    'SE': 0xFFA100,
    'BR': 0xA62929,
    'KR': 0x5CB8D1,
    'RB': 0x702EB0,
    'SR': 0x00FF00,
    'Y': 0x94FFFF,
    'ZR': 0x94E0E0,
    'NB': 0x73C2C9,
    'MO': 0x54B5B5,
    'TC': 0x3B9E9E,
    'RU': 0x248F8F,
    'RH': 0x0A7D8C,
    'PD': 0x006985,
    'AG': 0xC0C0C0,
    'CD': 0xFFD98F,
    'IN': 0xA67573,
    'SN': 0x668080,
    'SB': 0x9E63B5,
    'TE': 0xD47A00,
    'I': 0x940094,
    'XE': 0x940094,
    'CS': 0x57178F,
    'BA': 0x00C900,
    'LA': 0x70D4FF,
    'CE': 0xFFFFC7,
    'PR': 0xD9FFC7,
    'ND': 0xC7FFC7,
    'PM': 0xA3FFC7,
    'SM': 0x8FFFC7,
    'EU': 0x61FFC7,
    'GD': 0x45FFC7,
    'TB': 0x30FFC7,
    'DY': 0x1FFFC7,
    'HO': 0x00FF9C,
    'ER': 0x00E675,
    'TM': 0x00D452,
    'YB': 0x00BF38,
    'LU': 0x00AB24,
    'HF': 0x4DC2FF,
    'TA': 0x4DA6FF,
    'W': 0x2194D6,
    'RE': 0x267DAB,
    'OS': 0x266696,
    'IR': 0x175487,
    'PT': 0xD0D0E0,
    'AU': 0xFFD123,
    'HG': 0xB8B8D0,
    'TL': 0xA6544D,
    'PB': 0x575961,
    'BI': 0x9E4FB5,
    'PO': 0xAB5C00,
    'AT': 0x754F45,
    'RN': 0x428296,
    'FR': 0x420066,
    'RA': 0x007D00,
    'AC': 0x70ABFA,
    'TH': 0x00BAFF,
    'PA': 0x00A1FF,
    'U': 0x008FFF,
    'NP': 0x0080FF,
    'PU': 0x006BFF,
    'AM': 0x545CF2,
    'CM': 0x785CE3,
    'BK': 0x8A4FE3,
    'CF': 0xA136D4,
    'ES': 0xB31FD4,
    'FM': 0xB31FBA,
    'MD': 0xB30DA6,
    'NO': 0xBD0D87,
    'LR': 0xC70066,
    'RF': 0xCC0059,
    'DB': 0xD1004F,
    'SG': 0xD90045,
    'BH': 0xE00038,
    'HS': 0xE6002E,
    'MT': 0xEB0026,
    'DS': 0xFFFFFF,
    'RG': 0xFFFFFF,
    'CN': 0xFFFFFF,
    'UUT': 0xFFFFFF,
    'FL': 0xFFFFFF,
    'UUP': 0xFFFFFF,
    'LV': 0xFFFFFF,
    'UUH': 0xFFFFFF,
    'D': 0xFFFFC0,
    'T': 0xFFFFA0
};
var DefaultElementColor = 0xFFFFFF;
/**
 * Color by element
 */
var ElementColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function ElementColormaker(params) {
        params.value = defaults(params.value, ElementColors.C);
        Colormaker$$1.call(this, params);
    }

    if ( Colormaker$$1 ) ElementColormaker.__proto__ = Colormaker$$1;
    ElementColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    ElementColormaker.prototype.constructor = ElementColormaker;
    ElementColormaker.prototype.atomColor = function atomColor (a) {
        var element = a.element;
        if (element === 'C') {
            return this.parameters.value;
        }
        else {
            return ElementColors[element] || DefaultElementColor;
        }
    };

    return ElementColormaker;
}(Colormaker));
ColormakerRegistry$1.add('element', ElementColormaker);

/**
 * @file Entityindex Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by entity index
 */
var EntityindexColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function EntityindexColormaker(params) {
        Colormaker$$1.call(this, params);
        if (!params.scale) {
            this.parameters.scale = 'Spectral';
        }
        if (!params.domain) {
            this.parameters.domain = [0, params.structure.entityList.length - 1];
        }
        this.entityindexScale = this.getScale();
    }

    if ( Colormaker$$1 ) EntityindexColormaker.__proto__ = Colormaker$$1;
    EntityindexColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    EntityindexColormaker.prototype.constructor = EntityindexColormaker;
    EntityindexColormaker.prototype.atomColor = function atomColor (a) {
        return this.entityindexScale(a.entityIndex);
    };

    return EntityindexColormaker;
}(Colormaker));
ColormakerRegistry$1.add('entityindex', EntityindexColormaker);

/**
 * @file Entitytype Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by entity type
 */
var EntitytypeColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function EntitytypeColormaker () {
        Colormaker$$1.apply(this, arguments);
    }

    if ( Colormaker$$1 ) EntitytypeColormaker.__proto__ = Colormaker$$1;
    EntitytypeColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    EntitytypeColormaker.prototype.constructor = EntitytypeColormaker;

    EntitytypeColormaker.prototype.atomColor = function atomColor (a) {
        var e = a.entity;
        var et = e ? e.entityType : undefined;
        switch (et) {
            case PolymerEntity:
                return 0x7fc97f;
            case NonPolymerEntity:
                return 0xfdc086;
            case MacrolideEntity:
                return 0xbeaed4;
            case WaterEntity:
                return 0x386cb0;
            default:
                return 0xffff99;
        }
    };

    return EntitytypeColormaker;
}(Colormaker));
ColormakerRegistry$1.add('entitytype', EntitytypeColormaker);

/**
 * @file Geoquality Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by validation gometry quality
 */
var GeoqualityColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function GeoqualityColormaker(params) {
        Colormaker$$1.call(this, params);
        this.geoAtomDict = {};
        this.geoDict = {};
        var val = params.structure.validation;
        if (val) {
            this.geoAtomDict = val.geoAtomDict;
            this.geoDict = val.geoDict;
        }
    }

    if ( Colormaker$$1 ) GeoqualityColormaker.__proto__ = Colormaker$$1;
    GeoqualityColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    GeoqualityColormaker.prototype.constructor = GeoqualityColormaker;
    GeoqualityColormaker.prototype.atomColor = function atomColor (atom) {
        var sele = atom.resno + '';
        if (atom.inscode)
            { sele += '^' + atom.inscode; }
        if (atom.chainname)
            { sele += ':' + atom.chainname; }
        sele += '/' + atom.modelIndex;
        var geoProblemCount;
        var geoAtom = this.geoAtomDict[sele];
        if (geoAtom !== undefined) {
            var atomProblems = geoAtom[atom.atomname] || 0;
            geoProblemCount = countSetBits(atomProblems);
        }
        else {
            geoProblemCount = this.geoDict[sele] || 0;
        }
        if (geoProblemCount === 0) {
            return 0x2166ac;
        }
        else if (geoProblemCount === 1) {
            return 0xfee08b;
        }
        else if (geoProblemCount === 2) {
            return 0xf46d43;
        }
        else if (geoProblemCount >= 3) {
            return 0xa50026;
        }
        return 0x909090;
    };

    return GeoqualityColormaker;
}(Colormaker));
ColormakerRegistry$1.add('geoquality', GeoqualityColormaker);

/**
 * @file Hydrophobicity Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by hydrophobicity
 */
var HydrophobicityColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function HydrophobicityColormaker(params) {
        Colormaker$$1.call(this, params);
        this.resHF = {};
        if (!params.scale) {
            this.parameters.scale = 'RdYlGn';
        }
        var idx = 0; // 0: DGwif, 1: DGwoct, 2: Oct-IF
        for (var name in ResidueHydrophobicity) {
            this.resHF[name] = ResidueHydrophobicity[name][idx];
        }
        this.defaultResidueHydrophobicity = DefaultResidueHydrophobicity[idx];
        if (!params.domain) {
            var min = Infinity;
            var max = -Infinity;
            for (var name$1 in this.resHF) {
                var val = this.resHF[name$1];
                min = Math.min(min, val);
                max = Math.max(max, val);
            }
            this.parameters.domain = [min, 0, max];
        }
        this.hfScale = this.getScale();
    }

    if ( Colormaker$$1 ) HydrophobicityColormaker.__proto__ = Colormaker$$1;
    HydrophobicityColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    HydrophobicityColormaker.prototype.constructor = HydrophobicityColormaker;
    HydrophobicityColormaker.prototype.atomColor = function atomColor (a) {
        return this.hfScale(this.resHF[a.resname] || this.defaultResidueHydrophobicity);
    };

    return HydrophobicityColormaker;
}(Colormaker));
ColormakerRegistry$1.add('hydrophobicity', HydrophobicityColormaker);

/**
 * @file Modelindex Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by model index
 */
var ModelindexColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function ModelindexColormaker(params) {
        Colormaker$$1.call(this, params);
        if (!params.scale) {
            this.parameters.scale = 'rainbow';
        }
        if (!params.domain) {
            this.parameters.domain = [0, params.structure.modelStore.count];
        }
        this.modelindexScale = this.getScale();
    }

    if ( Colormaker$$1 ) ModelindexColormaker.__proto__ = Colormaker$$1;
    ModelindexColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    ModelindexColormaker.prototype.constructor = ModelindexColormaker;
    ModelindexColormaker.prototype.atomColor = function atomColor (a) {
        return this.modelindexScale(a.modelIndex);
    };

    return ModelindexColormaker;
}(Colormaker));
ColormakerRegistry$1.add('modelindex', ModelindexColormaker);

/**
 * @file Moleculetype Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by molecule type
 */
var MoleculetypeColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function MoleculetypeColormaker () {
        Colormaker$$1.apply(this, arguments);
    }

    if ( Colormaker$$1 ) MoleculetypeColormaker.__proto__ = Colormaker$$1;
    MoleculetypeColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    MoleculetypeColormaker.prototype.constructor = MoleculetypeColormaker;

    MoleculetypeColormaker.prototype.atomColor = function atomColor (a) {
        switch (a.residueType.moleculeType) {
            case WaterType:
                return 0x386cb0;
            case IonType:
                return 0xf0027f;
            case ProteinType:
                return 0xbeaed4;
            case RnaType:
                return 0xfdc086;
            case DnaType:
                return 0xbf5b17;
            case SaccharideType:
                return 0x7fc97f;
            default:
                return 0xffff99;
        }
    };

    return MoleculetypeColormaker;
}(Colormaker));
ColormakerRegistry$1.add('moleculetype', MoleculetypeColormaker);

/**
 * @file Occupancy Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by occupancy
 */
var OccupancyColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function OccupancyColormaker(params) {
        Colormaker$$1.call(this, params);
        if (!params.scale) {
            this.parameters.scale = 'PuBu';
        }
        if (!params.domain) {
            this.parameters.domain = [0.0, 1.0];
        }
        this.occupancyScale = this.getScale();
    }

    if ( Colormaker$$1 ) OccupancyColormaker.__proto__ = Colormaker$$1;
    OccupancyColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    OccupancyColormaker.prototype.constructor = OccupancyColormaker;
    OccupancyColormaker.prototype.atomColor = function atomColor (a) {
        return this.occupancyScale(a.occupancy);
    };

    return OccupancyColormaker;
}(Colormaker));
ColormakerRegistry$1.add('occupancy', OccupancyColormaker);

/**
 * @file Partialcharge Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by partial charge. The {@link AtomProxy.partialCharge} property is used for coloring.
 * The default domain is [-1, 1].
 *
 * __Name:__ _partialCharge_
 *
 * @example
 * stage.loadFile("rcsb://1crn").then(function (o) {
 *   o.addRepresentation("ball+stick", {colorScheme: "partialCharge"});
 *   o.autoView();
 * });
 */
var PartialchargeColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function PartialchargeColormaker(params) {
        Colormaker$$1.call(this, params);
        if (!params.scale) {
            this.parameters.scale = 'rwb';
        }
        if (!params.domain) {
            this.parameters.domain = [-1, 1];
        }
        this.partialchargeScale = this.getScale();
    }

    if ( Colormaker$$1 ) PartialchargeColormaker.__proto__ = Colormaker$$1;
    PartialchargeColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    PartialchargeColormaker.prototype.constructor = PartialchargeColormaker;
    PartialchargeColormaker.prototype.atomColor = function atomColor (a) {
        return this.partialchargeScale(a.partialCharge || 0);
    };

    return PartialchargeColormaker;
}(Colormaker));
ColormakerRegistry$1.add('partialcharge', PartialchargeColormaker);

/**
 * @file Random Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function randomColor() {
    return Math.random() * 0xFFFFFF;
}
/**
 * Class by random color
 */
var RandomColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function RandomColormaker () {
        Colormaker$$1.apply(this, arguments);
    }

    if ( Colormaker$$1 ) RandomColormaker.__proto__ = Colormaker$$1;
    RandomColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    RandomColormaker.prototype.constructor = RandomColormaker;

    RandomColormaker.prototype.atomColor = function atomColor () {
        return randomColor();
    };
    /**
     * get color for volume cell
     * @return {Integer} random hex color
     */
    RandomColormaker.prototype.volumeColor = function volumeColor () {
        return randomColor();
    };
    /**
     * get color for coordinates in space
     * @return {Integer} random hex color
     */
    RandomColormaker.prototype.positionColor = function positionColor () {
        return randomColor();
    };

    return RandomColormaker;
}(Colormaker));
ColormakerRegistry$1.add('random', RandomColormaker);

/**
 * @file Randomcoilindex Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by random coil index
 */
var RandomcoilindexColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function RandomcoilindexColormaker(params) {
        Colormaker$$1.call(this, params);
        this.rciDict = {};
        if (!params.scale) {
            this.parameters.scale = 'RdYlBu';
        }
        this.rciScale = this.getScale({ domain: [0.6, 0] });
        var val = params.structure.validation;
        if (val)
            { this.rciDict = val.rciDict; }
    }

    if ( Colormaker$$1 ) RandomcoilindexColormaker.__proto__ = Colormaker$$1;
    RandomcoilindexColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    RandomcoilindexColormaker.prototype.constructor = RandomcoilindexColormaker;
    RandomcoilindexColormaker.prototype.atomColor = function atomColor (atom) {
        var sele = "[" + (atom.resname) + "]" + (atom.resno);
        if (atom.chainname)
            { sele += ':' + atom.chainname; }
        var rci = this.rciDict[sele];
        return rci !== undefined ? this.rciScale(rci) : 0x909090;
    };

    return RandomcoilindexColormaker;
}(Colormaker));
ColormakerRegistry$1.add('randomcoilindex', RandomcoilindexColormaker);

/**
 * @file Residueindex Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by residue index
 */
var ResidueindexColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function ResidueindexColormaker(params) {
        var this$1 = this;

        Colormaker$$1.call(this, params);
        this.scalePerChain = {};
        if (!params.scale) {
            this.parameters.scale = 'rainbow';
            this.parameters.reverse = defaults(params.reverse, true);
        }
        params.structure.eachChain(function (cp) {
            this$1.parameters.domain = [cp.residueOffset, cp.residueEnd];
            this$1.scalePerChain[cp.index] = this$1.getScale();
        });
    }

    if ( Colormaker$$1 ) ResidueindexColormaker.__proto__ = Colormaker$$1;
    ResidueindexColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    ResidueindexColormaker.prototype.constructor = ResidueindexColormaker;
    ResidueindexColormaker.prototype.atomColor = function atomColor (a) {
        return this.scalePerChain[a.chainIndex](a.residueIndex);
    };

    return ResidueindexColormaker;
}(Colormaker));
ColormakerRegistry$1.add('residueindex', ResidueindexColormaker);

/**
 * @file Resname Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// protein colors from Jmol http://jmol.sourceforge.net/jscolors/
var ResidueColors = {
    'ALA': 0x8CFF8C,
    'ARG': 0x00007C,
    'ASN': 0xFF7C70,
    'ASP': 0xA00042,
    'CYS': 0xFFFF70,
    'GLN': 0xFF4C4C,
    'GLU': 0x660000,
    'GLY': 0xFFFFFF,
    'HIS': 0x7070FF,
    'ILE': 0x004C00,
    'LEU': 0x455E45,
    'LYS': 0x4747B8,
    'MET': 0xB8A042,
    'PHE': 0x534C52,
    'PRO': 0x525252,
    'SER': 0xFF7042,
    'THR': 0xB84C00,
    'TRP': 0x4F4600,
    'TYR': 0x8C704C,
    'VAL': 0xFF8CFF,
    'ASX': 0xFF00FF,
    'GLX': 0xFF00FF,
    'ASH': 0xFF00FF,
    'GLH': 0xFF00FF,
    'A': 0xDC143C,
    'G': 0x32CD32,
    'I': 0x9ACD32,
    'X': 0x7CFC00,
    'C': 0xFFD700,
    'T': 0x4169E1,
    'U': 0x40E0D0,
    'D': 0x008B8B,
    'DA': 0xDC143C,
    'DG': 0x32CD32,
    'DI': 0x9ACD32,
    'DX': 0x7CFC00,
    'DC': 0xFFD700,
    'DT': 0x4169E1,
    'DU': 0x40E0D0,
    'DD': 0x008B8B
};
var DefaultResidueColor = 0xFF00FF;
/**
 * Color by residue name
 */
var ResnameColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function ResnameColormaker () {
        Colormaker$$1.apply(this, arguments);
    }

    if ( Colormaker$$1 ) ResnameColormaker.__proto__ = Colormaker$$1;
    ResnameColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    ResnameColormaker.prototype.constructor = ResnameColormaker;

    ResnameColormaker.prototype.atomColor = function atomColor (a) {
        return ResidueColors[a.resname] || DefaultResidueColor;
    };

    return ResnameColormaker;
}(Colormaker));
ColormakerRegistry$1.add('resname', ResnameColormaker);

/**
 * @file Sstruc Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// from Jmol http://jmol.sourceforge.net/jscolors/ (shapely)
var StructureColors = {
    'alphaHelix': 0xFF0080,
    'threeTenHelix': 0xA00080,
    'piHelix': 0x600080,
    'betaStrand': 0xFFC800,
    'betaTurn': 0x6080FF,
    'coil': 0xFFFFFF,
    'dna': 0xAE00FE,
    'rna': 0xFD0162,
    'carbohydrate': 0xA6A6FA
};
var DefaultStructureColor = 0x808080;
/**
 * Color by secondary structure
 */
var SstrucColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function SstrucColormaker(params) {
        Colormaker$$1.call(this, params);
        this.residueProxy = params.structure.getResidueProxy();
    }

    if ( Colormaker$$1 ) SstrucColormaker.__proto__ = Colormaker$$1;
    SstrucColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    SstrucColormaker.prototype.constructor = SstrucColormaker;
    SstrucColormaker.prototype.atomColor = function atomColor (ap) {
        var sstruc = ap.sstruc;
        var rp = this.residueProxy;
        if (sstruc === 'h') {
            return StructureColors.alphaHelix;
        }
        else if (sstruc === 'g') {
            return StructureColors.threeTenHelix;
        }
        else if (sstruc === 'i') {
            return StructureColors.piHelix;
        }
        else if (sstruc === 'e' || sstruc === 'b') {
            return StructureColors.betaStrand;
        }
        else if (sstruc === 't') {
            return StructureColors.betaTurn;
        }
        else {
            rp.index = ap.residueIndex;
            if (rp.isDna()) {
                return StructureColors.dna;
            }
            else if (rp.isRna()) {
                return StructureColors.rna;
            }
            else if (rp.isSaccharide()) {
                return StructureColors.carbohydrate;
            }
            else if (rp.isProtein() || sstruc === 's' || sstruc === 'l') {
                return StructureColors.coil;
            }
            else {
                return DefaultStructureColor;
            }
        }
    };

    return SstrucColormaker;
}(Colormaker));
ColormakerRegistry$1.add('sstruc', SstrucColormaker);

/**
 * @file Uniform Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by uniform color
 */
var UniformColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function UniformColormaker () {
        Colormaker$$1.apply(this, arguments);
    }

    if ( Colormaker$$1 ) UniformColormaker.__proto__ = Colormaker$$1;
    UniformColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    UniformColormaker.prototype.constructor = UniformColormaker;

    UniformColormaker.prototype.atomColor = function atomColor () {
        return this.parameters.value;
    };
    UniformColormaker.prototype.bondColor = function bondColor () {
        return this.parameters.value;
    };
    UniformColormaker.prototype.valueColor = function valueColor () {
        return this.parameters.value;
    };
    UniformColormaker.prototype.volumeColor = function volumeColor () {
        return this.parameters.value;
    };

    return UniformColormaker;
}(Colormaker));
ColormakerRegistry$1.add('uniform', UniformColormaker);

/**
 * @file Value Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by volume value
 */
var ValueColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function ValueColormaker(params) {
        Colormaker$$1.call(this, params);
        this.valueScale = this.getScale();
    }

    if ( Colormaker$$1 ) ValueColormaker.__proto__ = Colormaker$$1;
    ValueColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    ValueColormaker.prototype.constructor = ValueColormaker;
    /**
     * return the color for a volume cell
     * @param  {Integer} index - volume cell index
     * @return {Integer} hex cell color
     */
    ValueColormaker.prototype.volumeColor = function volumeColor (index) {
        return this.valueScale(this.parameters.volume.data[index]); // TODO
    };

    return ValueColormaker;
}(Colormaker));
ColormakerRegistry$1.add('value', ValueColormaker);

/**
 * @file Volume Colormaker
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Color by volume position
 */
var VolumeColormaker = /*@__PURE__*/(function (Colormaker$$1) {
    function VolumeColormaker(params) {
        Colormaker$$1.call(this, params);
        this.vec = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        this.valueScale = this.getScale();
    }

    if ( Colormaker$$1 ) VolumeColormaker.__proto__ = Colormaker$$1;
    VolumeColormaker.prototype = Object.create( Colormaker$$1 && Colormaker$$1.prototype );
    VolumeColormaker.prototype.constructor = VolumeColormaker;
    /**
     * return the color for coordinates in space
     * @param  {Vector3} coords - xyz coordinates
     * @return {Integer} hex coords color
     */
    VolumeColormaker.prototype.positionColor = function positionColor (coords) {
        var volume = this.parameters.volume; // TODO
        if (!volume || !volume.inverseMatrix) {
            return this.parameters.value;
        }
        var vec = this.vec;
        var data = volume.data;
        var nx = volume.nx;
        var ny = volume.ny;
        var nxy = nx * ny;
        vec.copy(coords);
        vec.applyMatrix4(volume.inverseMatrix);
        // position of grid cell
        var x0 = Math.floor(vec.x);
        var y0 = Math.floor(vec.y);
        var z0 = Math.floor(vec.z);
        // Indices
        var i = ((((z0 * ny) + y0) * nx) + x0);
        var i1 = i + 1;
        var iy = i + nx;
        var iz = i + nxy;
        var i1y = iy + 1;
        var i1z = iz + 1;
        var iyz = iy + nxy;
        var i1yz = iyz + 1;
        // Values
        var v = data[i];
        var v1 = data[i1];
        var vy = data[iy];
        var vz = data[iz];
        var v1y = data[i1y];
        var v1z = data[i1z];
        var vyz = data[iyz];
        var v1yz = data[i1yz];
        // Position of point in fraction of grid
        var xd = vec.x - x0;
        var yd = vec.y - y0;
        var zd = vec.z - z0;
        // 1st Dimension
        var c00 = lerp(v, v1, xd);
        var c01 = lerp(vz, v1z, xd);
        var c10 = lerp(vy, v1y, xd);
        var c11 = lerp(vyz, v1yz, xd);
        // 2nd Dimension
        var c0 = lerp(c00, c10, yd);
        var c1 = lerp(c01, c11, yd);
        // 3rd Dimension
        var c = lerp(c0, c1, zd);
        return this.valueScale(c);
    };

    return VolumeColormaker;
}(Colormaker));
ColormakerRegistry$1.add('volume', VolumeColormaker);

/**
 * @file Structure Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Structure representation
 * @interface
 */
var StructureRepresentation = /*@__PURE__*/(function (Representation$$1) {
    function StructureRepresentation(structure, viewer, params) {
        var p = params || {};
        Representation$$1.call(this, structure, viewer, p);
        this.type = 'structure';
        this.parameters = Object.assign({
            radiusType: {
                type: 'select', options: RadiusFactory.types
            },
            radiusData: {
                type: 'hidden'
            },
            radiusSize: {
                type: 'number', precision: 3, max: 10.0, min: 0.001
            },
            radiusScale: {
                type: 'number', precision: 3, max: 10.0, min: 0.001
            },
            assembly: null,
            defaultAssembly: {
                type: 'hidden'
            }
        }, this.parameters);
        /**
         * @type {Selection}
         * @private
         */
        this.selection = new Selection(p.sele);
        /**
         * @type {Array}
         * @private
         */
        this.dataList = [];
        /**
         * @type {Structure}
         */
        this.structure = structure;
        /**
         * @type {StructureView}
         */
        this.structureView = this.structure.getView(this.selection);
        if (structure.biomolDict) {
            var biomolOptions = {
                'default': 'default',
                '': (structure.unitcell ? 'AU' : 'FULL')
            };
            Object.keys(structure.biomolDict).forEach(function (k) {
                biomolOptions[k] = k;
            });
            this.parameters.assembly = {
                type: 'select',
                options: biomolOptions,
                rebuild: true
            };
        }
        else {
            this.parameters.assembly = null;
        }
    }

    if ( Representation$$1 ) StructureRepresentation.__proto__ = Representation$$1;
    StructureRepresentation.prototype = Object.create( Representation$$1 && Representation$$1.prototype );
    StructureRepresentation.prototype.constructor = StructureRepresentation;

    var prototypeAccessors = { defaultScale: { configurable: true } };
    prototypeAccessors.defaultScale.get = function () {
        return {
            'vdw': 1.0,
            'covalent': 1.0,
            'bfactor': 0.01,
            'sstruc': 1.0
        };
    };
    StructureRepresentation.prototype.init = function init (params) {
        var this$1 = this;

        var p = params || {};
        p.colorScheme = defaults(p.colorScheme, 'element');
        this.setRadius(p.radius, p);
        this.radiusType = defaults(p.radiusType, 'vdw');
        this.radiusData = defaults(p.radiusData, {});
        this.radiusSize = defaults(p.radiusSize, 1.0);
        this.radiusScale = defaults(p.radiusScale, 1.0);
        this.assembly = defaults(p.assembly, 'default');
        this.defaultAssembly = defaults(p.defaultAssembly, '');
        if (p.quality === 'auto') {
            p.quality = this.getQuality();
        }
        Representation$$1.prototype.init.call(this, p);
        this.selection.signals.stringChanged.add(function ( /* sele */) {
            this$1.build();
        });
        this.build();
    };
    StructureRepresentation.prototype.setRadius = function setRadius (value, p) {
        var types = Object.keys(RadiusFactoryTypes);
        if (typeof value === 'string' && types.includes(value.toLowerCase())) {
            p.radiusType = value;
        }
        else if (value !== undefined) {
            p.radiusType = 'size';
            p.radiusSize = value;
        }
        return this;
    };
    StructureRepresentation.prototype.getAssembly = function getAssembly () {
        var name = this.assembly === 'default' ? this.defaultAssembly : this.assembly;
        return this.structure.biomolDict[name];
    };
    StructureRepresentation.prototype.getQuality = function getQuality () {
        var atomCount;
        var s = this.structureView;
        var assembly = this.getAssembly();
        if (assembly) {
            atomCount = assembly.getAtomCount(s);
        }
        else {
            atomCount = s.atomCount;
        }
        if (Mobile) {
            atomCount *= 4;
        }
        var backboneOnly = s.atomStore.count / s.residueStore.count < 2;
        if (backboneOnly) {
            atomCount *= 10;
        }
        if (atomCount < 15000) {
            return 'high';
        }
        else if (atomCount < 80000) {
            return 'medium';
        }
        else {
            return 'low';
        }
    };
    StructureRepresentation.prototype.create = function create () {
        var this$1 = this;

        if (this.structureView.atomCount === 0)
            { return; }
        if (!this.structureView.hasCoords()) {
            this.needsBuild = true;
            return;
        }
        else {
            this.needsBuild = false;
        }
        var assembly = this.getAssembly();
        if (assembly) {
            assembly.partList.forEach(function (part, i) {
                var sview = part.getView(this$1.structureView);
                if (sview.atomCount === 0)
                    { return; }
                var data = this$1.createData(sview, i);
                if (data) {
                    data.sview = sview;
                    data.instanceList = part.getInstanceList();
                    this$1.dataList.push(data);
                }
            });
        }
        else {
            var data = this.createData(this.structureView, 0);
            if (data) {
                data.sview = this.structureView;
                this.dataList.push(data);
            }
        }
    };
    StructureRepresentation.prototype.update = function update (what) {
        var this$1 = this;

        if (this.lazy && !this.visible) {
            Object.assign(this.lazyProps.what, what);
            return;
        }
        if (this.needsBuild) {
            this.build();
            return;
        }
        this.dataList.forEach(function (data) {
            if (data.bufferList.length > 0) {
                this$1.updateData(what, data);
            }
        }, this);
    };
    StructureRepresentation.prototype.updateData = function updateData (what, data) {
        this.build();
    };
    StructureRepresentation.prototype.getColorParams = function getColorParams () {
        return Object.assign(Object.assign({}, Representation$$1.prototype.getColorParams.call(this)), { structure: this.structure });
    };
    StructureRepresentation.prototype.getRadiusParams = function getRadiusParams (param) {
        return {
            type: this.radiusType,
            scale: this.radiusScale,
            size: this.radiusSize,
            data: this.radiusData
        };
    };
    StructureRepresentation.prototype.getAtomParams = function getAtomParams (what, params) {
        return Object.assign({
            what: what,
            colorParams: this.getColorParams(),
            radiusParams: this.getRadiusParams()
        }, params);
    };
    StructureRepresentation.prototype.getBondParams = function getBondParams (what, params) {
        return Object.assign({
            what: what,
            colorParams: this.getColorParams(),
            radiusParams: this.getRadiusParams()
        }, params);
    };
    StructureRepresentation.prototype.getAtomRadius = function getAtomRadius (atom) {
        if (this.structureView.atomSet.isSet(atom.index)) {
            var radiusFactory = new RadiusFactory(this.getRadiusParams());
            return radiusFactory.atomRadius(atom);
        }
        return 0;
    };
    /**
     * Set representation parameters
     * @alias StructureRepresentation#setSelection
     * @param {String} string - selection string, see {@tutorial selection-language}
     * @param {Boolean} [silent] - don't trigger a change event in the selection
     * @return {StructureRepresentation} this object
     */
    StructureRepresentation.prototype.setSelection = function setSelection (string, silent) {
        this.selection.setString(string, silent);
        return this;
    };
    /**
     * Set representation parameters
     * @alias StructureRepresentation#setParameters
     * @param {StructureRepresentationParameters} params - structure parameter object
     * @param {Object} [what] - buffer data attributes to be updated,
     *                        note that this needs to be implemented in the
     *                        derived classes. Generally it allows more
     *                        fine-grained control over updating than
     *                        forcing a rebuild.
     * @param {Boolean} what.position - update position data
     * @param {Boolean} what.color - update color data
     * @param {Boolean} [rebuild] - whether or not to rebuild the representation
     * @return {StructureRepresentation} this object
     */
    StructureRepresentation.prototype.setParameters = function setParameters (params, what, rebuild) {
        if ( what === void 0 ) what = {};
        if ( rebuild === void 0 ) rebuild = false;

        var p = params || {};
        this.setRadius(p.radius, p);
        if (p.radiusType !== undefined || p.radiusData !== undefined || p.radiusSize !== undefined || p.radiusScale !== undefined) {
            what.radius = true;
            if (!ExtensionFragDepth || this.disableImpostor) {
                rebuild = true;
            }
        }
        if (p.defaultAssembly !== undefined &&
            p.defaultAssembly !== this.defaultAssembly &&
            ((this.assembly === 'default' && p.assembly === undefined) ||
                p.assembly === 'default')) {
            rebuild = true;
        }
        Representation$$1.prototype.setParameters.call(this, p, what, rebuild);
        return this;
    };
    StructureRepresentation.prototype.getParameters = function getParameters () {
        var params = Object.assign(Representation$$1.prototype.getParameters.call(this), {
            sele: this.selection ? this.selection.string : undefined,
            defaultAssembly: this.defaultAssembly
        });
        return params;
    };
    StructureRepresentation.prototype.attach = function attach (callback) {
        var viewer = this.viewer;
        var bufferList = this.bufferList;
        this.dataList.forEach(function (data) {
            data.bufferList.forEach(function (buffer) {
                bufferList.push(buffer);
                viewer.add(buffer, data.instanceList);
            });
        });
        this.setVisibility(this.visible);
        callback();
    };
    StructureRepresentation.prototype.clear = function clear () {
        this.dataList.length = 0;
        Representation$$1.prototype.clear.call(this);
    };
    StructureRepresentation.prototype.dispose = function dispose () {
        this.structureView.dispose();
        delete this.structure;
        delete this.structureView;
        Representation$$1.prototype.dispose.call(this);
    };

    Object.defineProperties( StructureRepresentation.prototype, prototypeAccessors );

    return StructureRepresentation;
}(Representation));

/**
 * @file Measurement Representation
 * @author Fred Ludlow <fred.ludlow@gmail.com>
 * @private
 */
/**
 * Measurement representation
 * @interface
 */
var MeasurementRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function MeasurementRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.n = 0; // Subclass create sets value
        this.parameters = Object.assign({
            labelVisible: {
                type: 'boolean'
            },
            labelSize: {
                type: 'number', precision: 3, max: 10.0, min: 0.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: true
            },
            labelBorder: {
                type: 'boolean', buffer: 'showBorder'
            },
            labelBorderColor: {
                type: 'color', buffer: 'borderColor'
            },
            labelBorderWidth: {
                type: 'number', precision: 2, max: 0.3, min: 0, buffer: 'borderWidth'
            },
            labelBackground: {
                type: 'boolean', rebuild: true
            },
            labelBackgroundColor: {
                type: 'color', buffer: 'backgroundColor'
            },
            labelBackgroundMargin: {
                type: 'number', precision: 2, max: 2, min: 0, rebuild: true
            },
            labelBackgroundOpacity: {
                type: 'range', step: 0.01, max: 1, min: 0, buffer: 'backgroundOpacity'
            },
            labelFixedSize: {
                type: 'boolean', buffer: 'fixedSize'
            },
            lineOpacity: {
                type: 'range', min: 0.0, max: 1.0, step: 0.01
            },
            linewidth: {
                type: 'integer', max: 50, min: 1, buffer: true
            }
        }, this.parameters, {
            flatShaded: null
        });
    }

    if ( StructureRepresentation$$1 ) MeasurementRepresentation.__proto__ = StructureRepresentation$$1;
    MeasurementRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    MeasurementRepresentation.prototype.constructor = MeasurementRepresentation;
    MeasurementRepresentation.prototype.init = function init (params) {
        var p = params || {};
        this.labelVisible = defaults(p.labelVisible, true);
        this.labelSize = defaults(p.labelSize, 2.0);
        this.labelColor = defaults(p.labelColor, 0xFFFFFF);
        this.labelFontFamily = defaults(p.labelFontFamily, 'sans-serif');
        this.labelFontStyle = defaults(p.labelFontstyle, 'normal');
        this.labelFontWeight = defaults(p.labelFontWeight, 'bold');
        this.labelsdf = defaults(p.labelsdf, Browser === 'Chrome');
        this.labelXOffset = defaults(p.labelXOffset, 0.0);
        this.labelYOffset = defaults(p.labelYOffset, 0.0);
        this.labelZOffset = defaults(p.labelZOffset, 0.5);
        this.labelAttachment = defaults(p.labelAttachment, 'bottom-left');
        this.labelBorder = defaults(p.labelBorder, false);
        this.labelBorderColor = defaults(p.labelBorderColor, 'lightgrey');
        this.labelBorderWidth = defaults(p.labelBorderWidth, 0.15);
        this.labelBackground = defaults(p.labelBackground, false);
        this.labelBackgroundColor = defaults(p.labelBackgroundColor, 'lightgrey');
        this.labelBackgroundMargin = defaults(p.labelBackgroundMargin, 0.5);
        this.labelBackgroundOpacity = defaults(p.labelBackgroundOpacity, 1.0);
        this.labelFixedSize = defaults(p.labelFixedSize, false);
        this.lineOpacity = defaults(p.lineOpacity, 1.0);
        this.linewidth = defaults(p.linewidth, 2);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    // All measurements need to rebuild on position change
    MeasurementRepresentation.prototype.update = function update (what) {
        if (what.position) {
            this.build();
        }
        else {
            StructureRepresentation$$1.prototype.update.call(this, what);
        }
    };
    MeasurementRepresentation.prototype.updateData = function updateData (what, data) {
        var textData = {};
        if (!what || what.labelSize) {
            Object.assign(textData, { size: uniformArray(this.n, this.labelSize) });
        }
        if (!what || what.labelColor) {
            var c = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.labelColor);
            Object.assign(textData, { color: uniformArray3(this.n, c.r, c.g, c.b) });
        }
        this.textBuffer.setAttributes(textData);
    };
    MeasurementRepresentation.prototype.setParameters = function setParameters (params, what, rebuild) {
        if ( what === void 0 ) what = {};
        if ( rebuild === void 0 ) rebuild = false;

        if (params && params.labelSize) {
            what.labelSize = true;
        }
        if (params && (params.labelColor || params.labelColor === 0x000000)) {
            what.labelColor = true;
            rebuild = true;
        }
        StructureRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        if (params && params.opacity !== undefined) {
            this.textBuffer.setParameters({ opacity: 1.0 }); // only opaque labels
        }
        if (params && params.labelVisible !== undefined) {
            this.setVisibility(this.visible);
        }
        return this;
    };
    MeasurementRepresentation.prototype.setVisibility = function setVisibility (value, noRenderRequest) {
        StructureRepresentation$$1.prototype.setVisibility.call(this, value, true);
        if (this.textBuffer) {
            this.textBuffer.setVisibility(this.labelVisible && this.visible);
        }
        if (!noRenderRequest)
            { this.viewer.requestRender(); }
        return this;
    };
    MeasurementRepresentation.prototype.getLabelBufferParams = function getLabelBufferParams (params) {
        if ( params === void 0 ) params = {};

        return StructureRepresentation$$1.prototype.getBufferParams.call(this, 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: true,
            visible: this.labelVisible
        }, params, {
            opacity: 1.0 // only opaque labels
        }));
    };
    MeasurementRepresentation.prototype.getAtomRadius = function getAtomRadius () {
        return 0;
    };

    return MeasurementRepresentation;
}(StructureRepresentation));
/**
 * MeasurementRepresentations take atom[Pair|Triple|Quad] parameters.
 *
 * Parses nested array of either integer atom indices or selection
 * expressions into a flat array of coordinates.
 *
 * @param  {Structure} sview The structure to which the atoms refer
 * @param  {Array} atoms Nested array of atom pairs|triples|quads as
 *   Integer indices or selection expressions
 * @return {Float32Array} Flattened array of position coordinates
 */
function parseNestedAtoms(sview, atoms) {
    var ap = sview.getAtomProxy();
    var sele = new Selection();
    var nSets = atoms.length;
    if (nSets === 0)
        { return new Float32Array(0); }
    // Peek-ahead at first item to determine order and parse mode
    var order = atoms[0].length;
    var selected = sview.getAtomSet();
    var a = new Float32Array(nSets * order * 3);
    var p = 0;
    atoms.forEach(function (group) {
        var _break = false;
        for (var j = 0; j < order; j++) {
            var value = group[j];
            if (typeof (value) === 'number' && Number.isInteger(value)) {
                if (selected.get(value)) {
                    ap.index = value;
                }
                else {
                    _break = true;
                    break;
                }
            }
            else {
                sele.setString(value);
                var atomIndices = sview.getAtomIndices(sele);
                if (atomIndices.length) {
                    ap.index = atomIndices[0];
                }
                else {
                    _break = true;
                    break;
                }
            }
            var offset = p + j * 3;
            a[offset++] = ap.x;
            a[offset++] = ap.y;
            a[offset++] = ap.z;
        }
        if (!_break)
            { p += 3 * order; }
    });
    return a.subarray(0, p);
}
/* out = v1 * cos(angle) + v2 * sin(angle) */
function calcArcPoint(out, center, v1, v2, angle) {
    var x = Math.cos(angle);
    var y = Math.sin(angle);
    out[0] = center[0] + v1[0] * x + v2[0] * y;
    out[1] = center[1] + v1[1] * x + v2[1] * y;
    out[2] = center[2] + v1[2] * x + v2[2] * y;
}

ShaderRegistry.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}");

ShaderRegistry.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}");

/**
 * @file Edt
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf
function edt(data, width, height, f, d, v, z) {
    for (var x = 0; x < width; x++) {
        for (var y = 0; y < height; y++) {
            f[y] = data[y * width + x];
        }
        edt1d(f, d, v, z, height);
        for (var y$1 = 0; y$1 < height; y$1++) {
            data[y$1 * width + x] = d[y$1];
        }
    }
    for (var y$2 = 0; y$2 < height; y$2++) {
        for (var x$1 = 0; x$1 < width; x$1++) {
            f[x$1] = data[y$2 * width + x$1];
        }
        edt1d(f, d, v, z, width);
        for (var x$2 = 0; x$2 < width; x$2++) {
            data[y$2 * width + x$2] = Math.sqrt(d[x$2]);
        }
    }
}
// 1D squared distance transform
function edt1d(f, d, v, z, n) {
    v[0] = 0;
    z[0] = Number.MIN_SAFE_INTEGER;
    z[1] = Number.MAX_SAFE_INTEGER;
    for (var q = 1, k = 0; q < n; q++) {
        var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
        while (s <= z[k]) {
            k--;
            s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
        }
        k++;
        v[k] = q;
        z[k] = s;
        z[k + 1] = Number.MAX_SAFE_INTEGER;
    }
    for (var q$1 = 0, k$1 = 0; q$1 < n; q$1++) {
        while (z[k$1 + 1] < q$1)
            { k$1++; }
        d[q$1] = (q$1 - v[k$1]) * (q$1 - v[k$1]) + f[v[k$1]];
    }
}

/**
 * @file Text Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var TextAtlasCache = {};
function getTextAtlas(params) {
    var hash = JSON.stringify(params);
    if (TextAtlasCache[hash] === undefined) {
        TextAtlasCache[hash] = new TextAtlas(params);
    }
    return TextAtlasCache[hash];
}
var TextAtlasDefaultParams = {
    font: 'sans-serif',
    size: 36,
    style: 'normal',
    variant: 'normal',
    weight: 'normal',
    outline: 3,
    width: 1024,
    height: 1024
};
var TextAtlas = function TextAtlas(params) {
    if ( params === void 0 ) params = {};

    this.gamma = 1;
    this.mapped = {};
    this.scratchW = 0;
    this.scratchH = 0;
    this.currentX = 0;
    this.currentY = 0;
    this.cutoff = 0.25;
    this.parameters = createParams(params, TextAtlasDefaultParams);
    var p = this.parameters;
    this.radius = p.size / 8;
    this.padding = p.size / 3;
    // Prepare line-height with room for outline and descenders/ascenders
    var lineHeight = this.lineHeight = p.size + 2 * p.outline + Math.round(p.size / 4);
    var maxWidth = this.maxWidth = p.width / 4;
    // Prepare scratch canvas
    var canvas = this.canvas = document.createElement('canvas');
    canvas.width = maxWidth;
    canvas.height = lineHeight;
    var ctx = this.context = this.canvas.getContext('2d');
    ctx.font = (p.style) + " " + (p.variant) + " " + (p.weight) + " " + (p.size) + "px " + (p.font);
    ctx.fillStyle = 'black';
    ctx.textAlign = 'left';
    ctx.textBaseline = 'bottom';
    ctx.lineJoin = 'round';
    // temporary arrays for the distance transform
    this.gridOuter = new Float64Array(lineHeight * maxWidth);
    this.gridInner = new Float64Array(lineHeight * maxWidth);
    this.f = new Float64Array(Math.max(lineHeight, maxWidth));
    this.d = new Float64Array(Math.max(lineHeight, maxWidth));
    this.z = new Float64Array(Math.max(lineHeight, maxWidth) + 1);
    this.v = new Int16Array(Math.max(lineHeight, maxWidth));
    //
    this.data = new Uint8Array(p.width * p.height * 4);
    this.canvas2 = document.createElement('canvas');
    this.canvas2.width = p.width;
    this.canvas2.height = p.height;
    this.context2 = this.canvas2.getContext('2d');
    // Replacement Character
    this.placeholder = this.map(String.fromCharCode(0xFFFD));
    // Basic Latin (subset)
    for (var i = 0x0020; i <= 0x007E; ++i) {
        this.map(String.fromCharCode(i));
    }
    // TODO: to slow to always prepare them
    // // Latin-1 Supplement (subset)
    // for (let i = 0x00A1; i <= 0x00FF; ++i) {
    //   this.map(String.fromCharCode(i))
    // }
    // Degree sign
    this.map(String.fromCharCode(0x00B0));
    // // Greek and Coptic (subset)
    // for (let i = 0x0391; i <= 0x03C9; ++i) {
    //   this.map(String.fromCharCode(i))
    // }
    // // Cyrillic (subset)
    // for (let i = 0x0400; i <= 0x044F; ++i) {
    //   this.map(String.fromCharCode(i))
    // }
    // Angstrom Sign
    this.map(String.fromCharCode(0x212B));
    this.texture = new __WEBPACK_IMPORTED_MODULE_0_three__["h" /* CanvasTexture */](this.canvas2);
    this.texture.flipY = false;
    this.texture.needsUpdate = true;
};
TextAtlas.prototype.map = function map (text) {
    var p = this.parameters;
    if (this.mapped[text] === undefined) {
        this.draw(text);
        if (this.currentX + this.scratchW > p.width) {
            this.currentX = 0;
            this.currentY += this.scratchH;
        }
        if (this.currentY + this.scratchH > p.height) {
            console.warn('canvas to small');
        }
        this.mapped[text] = {
            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;
    }
    return this.mapped[text];
};
TextAtlas.prototype.get = function get (text) {
    return this.mapped[text] || this.placeholder;
};
TextAtlas.prototype.draw = function draw (text) {
    var p = this.parameters;
    var h = this.lineHeight;
    var o = p.outline;
    var ctx = this.context;
    // const dst = this.scratch
    var max = this.maxWidth;
    // const colors = this.colors
    // Bottom aligned, take outline into account
    var x = o;
    var y = h - p.outline;
    // Measure text
    var m = ctx.measureText(text);
    var w = Math.min(max, Math.ceil(m.width + 2 * x + 1));
    var n = w * h;
    // Clear scratch area
    ctx.clearRect(0, 0, w, h);
    // Draw text
    ctx.fillText(text, x, y);
    var imageData = ctx.getImageData(0, 0, w, h);
    var data = imageData.data;
    for (var i = 0; i < n; i++) {
        var a = imageData.data[i * 4 + 3] / 255; // alpha value
        this.gridOuter[i] = a === 1 ? 0 : a === 0 ? Number.MAX_SAFE_INTEGER : Math.pow(Math.max(0, 0.5 - a), 2);
        this.gridInner[i] = a === 1 ? Number.MAX_SAFE_INTEGER : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2);
    }
    edt(this.gridOuter, w, h, this.f, this.d, this.v, this.z);
    edt(this.gridInner, w, h, this.f, this.d, this.v, this.z);
    for (var i$1 = 0; i$1 < n; i$1++) {
        var d = this.gridOuter[i$1] - this.gridInner[i$1];
        data[i$1 * 4 + 3] = Math.max(0, Math.min(255, Math.round(255 - 255 * (d / this.radius + this.cutoff))));
    }
    ctx.putImageData(imageData, 0, 0);
    this.scratchW = w;
    this.scratchH = h;
};
var TextBufferDefaultParameters = Object.assign({
    fontFamily: 'sans-serif',
    fontStyle: 'normal',
    fontWeight: 'bold',
    fontSize: 36,
    xOffset: 0.0,
    yOffset: 0.0,
    zOffset: 0.5,
    attachment: 'bottom-left',
    showBorder: false,
    borderColor: 'lightgrey',
    borderWidth: 0.15,
    showBackground: false,
    backgroundColor: 'lightgrey',
    backgroundMargin: 0.5,
    backgroundOpacity: 1.0,
    forceTransparent: true,
    fixedSize: false
}, BufferDefaultParameters);
var TextBufferParameterTypes = Object.assign({
    fontFamily: { uniform: true },
    fontStyle: { uniform: true },
    fontWeight: { uniform: true },
    fontSize: { uniform: true },
    xOffset: { uniform: true },
    yOffset: { uniform: true },
    zOffset: { uniform: true },
    showBorder: { uniform: true },
    borderColor: { uniform: true },
    borderWidth: { uniform: true },
    backgroundColor: { uniform: true },
    backgroundOpacity: { uniform: true },
    fixedSize: { updateShader: true }
}, BufferParameterTypes);
function getCharCount(data, params) {
    var n = data.position.length / 3;
    var charCount = 0;
    for (var i = 0; i < n; ++i) {
        charCount += data.text[i].length;
    }
    if (params.showBackground)
        { charCount += n; }
    return charCount;
}
/**
 * Text buffer. Renders screen-aligned text strings.
 *
 * @example
 * var textBuffer = new TextBuffer({
 *   position: new Float32Array([ 0, 0, 0 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   size: new Float32Array([ 2 ]),
 *   text: [ "Hello" ]
 * });
 */
var TextBuffer = /*@__PURE__*/(function (MappedQuadBuffer$$1) {
    function TextBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MappedQuadBuffer$$1.call(this, {
            position: new Float32Array(getCharCount(data, params) * 3),
            color: new Float32Array(getCharCount(data, params) * 3),
            picking: new IgnorePicker()
        }, params);
        this.parameterTypes = TextBufferParameterTypes;
        this.alwaysTransparent = true;
        this.hasWireframe = false;
        this.isText = true;
        this.vertexShader = 'SDFFont.vert';
        this.fragmentShader = 'SDFFont.frag';
        this.text = data.text;
        this.positionCount = data.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: false },
            'showBorder': { value: this.parameters.showBorder },
            'borderColor': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.parameters.borderColor) },
            'borderWidth': { value: this.parameters.borderWidth },
            'backgroundColor': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.parameters.backgroundColor) },
            'backgroundOpacity': { value: this.parameters.backgroundOpacity },
            'canvasHeight': { value: 1.0 },
            'pixelRatio': { value: 1.0 }
        });
        this.addAttributes({
            'inputTexCoord': { type: 'v2', value: null },
            'inputSize': { type: 'f', value: null }
        });
        this.setAttributes(data);
        this.makeTexture();
        this.makeMapping();
    }

    if ( MappedQuadBuffer$$1 ) TextBuffer.__proto__ = MappedQuadBuffer$$1;
    TextBuffer.prototype = Object.create( MappedQuadBuffer$$1 && MappedQuadBuffer$$1.prototype );
    TextBuffer.prototype.constructor = TextBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return TextBufferDefaultParameters; };
    TextBuffer.prototype.makeMaterial = function makeMaterial () {
        MappedQuadBuffer$$1.prototype.makeMaterial.call(this);
        var tex = this.texture;
        var m = this.material;
        m.transparent = true;
        m.extensions.derivatives = true;
        m.lights = false;
        m.uniforms.fontTexture.value = tex;
        m.needsUpdate = true;
        var wm = this.wireframeMaterial;
        wm.transparent = true;
        wm.extensions.derivatives = true;
        wm.lights = false;
        wm.uniforms.fontTexture.value = tex;
        wm.needsUpdate = true;
        var pm = this.pickingMaterial;
        pm.extensions.derivatives = true;
        pm.lights = false;
        pm.uniforms.fontTexture.value = tex;
        pm.needsUpdate = true;
    };
    TextBuffer.prototype.setAttributes = function setAttributes (data) {
        if ( data === void 0 ) data = {};

        var position, size, color;
        var aPosition, inputSize, aColor;
        var text = this.text;
        var attributes = this.geometry.attributes; // TODO
        if (data.position) {
            position = data.position;
            aPosition = attributes.position.array;
            attributes.position.needsUpdate = true;
        }
        if (data.size) {
            size = data.size;
            inputSize = attributes.inputSize.array;
            attributes.inputSize.needsUpdate = true;
        }
        if (data.color) {
            color = data.color;
            aColor = attributes.color.array;
            attributes.color.needsUpdate = true;
        }
        var n = this.positionCount;
        var j, o;
        var iCharAll = 0;
        var txt, iChar, nChar;
        for (var v = 0; v < n; ++v) {
            o = 3 * v;
            txt = text[v];
            nChar = txt.length;
            if (this.parameters.showBackground)
                { nChar += 1; }
            for (iChar = 0; iChar < nChar; ++iChar, ++iCharAll) {
                for (var m = 0; m < 4; m++) {
                    j = iCharAll * 4 * 3 + (3 * m);
                    if (position) {
                        aPosition[j] = position[o];
                        aPosition[j + 1] = position[o + 1];
                        aPosition[j + 2] = position[o + 2];
                    }
                    if (size) {
                        inputSize[(iCharAll * 4) + m] = size[v];
                    }
                    if (color) {
                        aColor[j] = color[o];
                        aColor[j + 1] = color[o + 1];
                        aColor[j + 2] = color[o + 2];
                    }
                }
            }
        }
    };
    TextBuffer.prototype.makeTexture = function makeTexture () {
        this.textAtlas = getTextAtlas({
            font: this.parameters.fontFamily,
            style: this.parameters.fontStyle,
            weight: this.parameters.fontWeight,
            size: this.parameters.fontSize
        });
        this.texture = this.textAtlas.texture;
    };
    TextBuffer.prototype.makeMapping = function makeMapping () {
        var ta = this.textAtlas;
        var text = this.text;
        var attachment = this.parameters.attachment;
        var margin = (ta.lineHeight * this.parameters.backgroundMargin * 0.1) - 10;
        var attribs = this.geometry.attributes; // TODO
        var inputTexCoord = attribs.inputTexCoord.array;
        var inputMapping = attribs.mapping.array;
        var n = this.positionCount;
        var iCharAll = 0;
        var c, i, txt, xadvance, iChar, nChar, xShift, yShift;
        for (var v = 0; v < n; ++v) {
            txt = text[v];
            xadvance = 0;
            nChar = txt.length;
            // calculate width
            for (iChar = 0; iChar < nChar; ++iChar) {
                c = ta.get(txt[iChar]);
                xadvance += c.w - 2 * ta.parameters.outline;
            }
            // attachment
            if (attachment.startsWith('top')) {
                yShift = ta.lineHeight / 1.25;
            }
            else if (attachment.startsWith('middle')) {
                yShift = ta.lineHeight / 2.5;
            }
            else {
                yShift = 0; // "bottom"
            }
            if (attachment.endsWith('right')) {
                xShift = xadvance;
            }
            else if (attachment.endsWith('center')) {
                xShift = xadvance / 2;
            }
            else {
                xShift = 0; // "left"
            }
            xShift += ta.parameters.outline;
            yShift += ta.parameters.outline;
            // background
            if (this.parameters.showBackground) {
                i = iCharAll * 2 * 4;
                inputMapping[i + 0] = -ta.lineHeight / 6 - xShift - margin; // top left
                inputMapping[i + 1] = ta.lineHeight - yShift + margin;
                inputMapping[i + 2] = -ta.lineHeight / 6 - xShift - margin; // bottom left
                inputMapping[i + 3] = 0 - yShift - margin;
                inputMapping[i + 4] = xadvance + ta.lineHeight / 6 - xShift + 2 * ta.parameters.outline + margin; // top right
                inputMapping[i + 5] = ta.lineHeight - yShift + margin;
                inputMapping[i + 6] = xadvance + ta.lineHeight / 6 - xShift + 2 * ta.parameters.outline + margin; // bottom right
                inputMapping[i + 7] = 0 - yShift - margin;
                inputTexCoord[i + 0] = 10;
                inputTexCoord[i + 2] = 10;
                inputTexCoord[i + 4] = 10;
                inputTexCoord[i + 6] = 10;
                iCharAll += 1;
            }
            xadvance = 0;
            for (iChar = 0; iChar < nChar; ++iChar, ++iCharAll) {
                c = ta.get(txt[iChar]);
                i = iCharAll * 2 * 4;
                inputMapping[i + 0] = xadvance - xShift; // top left
                inputMapping[i + 1] = c.h - yShift;
                inputMapping[i + 2] = xadvance - xShift; // bottom left
                inputMapping[i + 3] = 0 - yShift;
                inputMapping[i + 4] = xadvance + c.w - xShift; // top right
                inputMapping[i + 5] = c.h - yShift;
                inputMapping[i + 6] = xadvance + c.w - xShift; // bottom right
                inputMapping[i + 7] = 0 - yShift;
                var texWidth = ta.parameters.width;
                var texHeight = ta.parameters.height;
                var texCoords = [
                    c.x / texWidth, c.y / texHeight,
                    c.x / texWidth, (c.y + c.h) / texHeight,
                    (c.x + c.w) / texWidth, c.y / texHeight,
                    (c.x + c.w) / texWidth, (c.y + c.h) / texHeight // bottom right
                ];
                inputTexCoord.set(texCoords, i);
                xadvance += c.w - 2 * ta.parameters.outline;
            }
        }
        attribs.inputTexCoord.needsUpdate = true;
        attribs.mapping.needsUpdate = true;
    };
    TextBuffer.prototype.getDefines = function getDefines (type) {
        var defines = MappedQuadBuffer$$1.prototype.getDefines.call(this, type);
        if (this.parameters.fixedSize) {
            defines.FIXED_SIZE = 1;
        }
        return defines;
    };
    TextBuffer.prototype.setUniforms = function setUniforms (data) {
        if (data && (data.fontFamily !== undefined ||
            data.fontStyle !== undefined ||
            data.fontWeight !== undefined ||
            data.fontSize !== undefined)) {
            this.makeTexture();
            this.makeMapping();
            this.texture.needsUpdate = true;
            data.fontTexture = this.texture;
        }
        MappedQuadBuffer$$1.prototype.setUniforms.call(this, data);
    };

    Object.defineProperties( TextBuffer.prototype, prototypeAccessors );

    return TextBuffer;
}(MappedQuadBuffer));
BufferRegistry.add('text', TextBuffer);

ShaderRegistry.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}");

ShaderRegistry.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}");

/**
 * @file Wide Line Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var WideLineBufferDefaultParameters = Object.assign({
    linewidth: 2
}, BufferDefaultParameters);
var WideLineBufferParameterTypes = Object.assign({
    linewidth: { uniform: true }
}, BufferParameterTypes);
/**
 * Wide Line buffer. Draws lines with a fixed width in pixels.
 *
 * @example
 * var lineBuffer = new WideLineBuffer({
 *   position1: new Float32Array([ 0, 0, 0 ]),
 *   position2: new Float32Array([ 1, 1, 1 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   color2: new Float32Array([ 0, 1, 0 ])
 * });
 */
var WideLineBuffer = /*@__PURE__*/(function (MappedQuadBuffer$$1) {
    function WideLineBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MappedQuadBuffer$$1.call(this, data, params);
        this.parameterTypes = WideLineBufferParameterTypes;
        this.vertexShader = 'WideLine.vert';
        this.fragmentShader = 'WideLine.frag';
        if (!data.color2 && data.color)
            { data.color2 = data.color; }
        this.addUniforms({
            'linewidth': { value: this.parameters.linewidth },
            'resolution': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["W" /* Vector2 */]() },
            'projectionMatrixInverse': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]() }
        });
        this.addAttributes({
            'position1': { type: 'v3', value: null },
            'position2': { type: 'v3', value: null },
            'color2': { type: 'c', value: null }
        });
        this.setAttributes(data);
        this.makeMapping();
    }

    if ( MappedQuadBuffer$$1 ) WideLineBuffer.__proto__ = MappedQuadBuffer$$1;
    WideLineBuffer.prototype = Object.create( MappedQuadBuffer$$1 && MappedQuadBuffer$$1.prototype );
    WideLineBuffer.prototype.constructor = WideLineBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return WideLineBufferDefaultParameters; };
    WideLineBuffer.prototype.setParameters = function setParameters (params) {
        MappedQuadBuffer$$1.prototype.setParameters.call(this, params);
    };

    Object.defineProperties( WideLineBuffer.prototype, prototypeAccessors );

    return WideLineBuffer;
}(MappedQuadBuffer));
BufferRegistry.add('wideline', WideLineBuffer);

/**
 * @file Angle Representation
 * @author Fred Ludlow <fred.ludlow@gmail.com>
 * @private
 */
/**
 * Angle representation object
 *
 * Reperesentation consists of four parts, visibility can be set for each
 * label - the text label with the angle size
 * vectors - lines joining the three points
 * sector - triangles representing the angle
 * arc - line bordering the sector
 *
 * @param {Structure} structure - the structure to measure angles in
 * @param {Viewer} viewer - a viewer object
 * @param {AngleRepresentationParameters} params - angle representation parameters
 */
var AngleRepresentation = /*@__PURE__*/(function (MeasurementRepresentation$$1) {
    function AngleRepresentation(structure, viewer, params) {
        MeasurementRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'angle';
        this.parameters = Object.assign({
            atomTriple: {
                type: 'hidden', rebuild: true
            },
            vectorVisible: {
                type: 'boolean', default: true
            },
            arcVisible: {
                type: 'boolean', default: true
            },
            sectorVisible: {
                type: 'boolean', default: true
            }
        }, this.parameters);
        this.init(params);
    }

    if ( MeasurementRepresentation$$1 ) AngleRepresentation.__proto__ = MeasurementRepresentation$$1;
    AngleRepresentation.prototype = Object.create( MeasurementRepresentation$$1 && MeasurementRepresentation$$1.prototype );
    AngleRepresentation.prototype.constructor = AngleRepresentation;
    AngleRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.side = defaults(p.side, 'double');
        p.opacity = defaults(p.opacity, 0.5);
        this.atomTriple = defaults(p.atomTriple, []);
        this.arcVisible = defaults(p.arcVisible, true);
        this.sectorVisible = defaults(p.sectorVisible, true);
        this.vectorVisible = defaults(p.vectorVisible, true);
        MeasurementRepresentation$$1.prototype.init.call(this, p);
    };
    AngleRepresentation.prototype.createData = function createData (sview) {
        if (!sview.atomCount || !this.atomTriple.length)
            { return; }
        var atomPosition = atomTriplePositions(sview, this.atomTriple);
        var angleData = getAngleData(atomPosition);
        var n = this.n = angleData.labelPosition.length / 3;
        var labelColor = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.labelColor);
        // Create buffers
        this.textBuffer = new TextBuffer({
            position: angleData.labelPosition,
            size: uniformArray(n, this.labelSize),
            color: uniformArray3(n, labelColor.r, labelColor.g, labelColor.b),
            text: angleData.labelText
        }, this.getLabelBufferParams());
        var c = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.colorValue);
        this.vectorBuffer = new WideLineBuffer(getFixedLengthWrappedDashData({
            position1: angleData.vectorPosition1,
            position2: angleData.vectorPosition2,
            color: uniformArray3(2 * n, c.r, c.g, c.b),
            color2: uniformArray3(2 * n, c.r, c.g, c.b)
        }), this.getBufferParams({
            linewidth: this.linewidth,
            visible: this.vectorVisible,
            opacity: this.lineOpacity
        }));
        this.arcLength = angleData.arcPosition1.length / 3;
        this.arcBuffer = new WideLineBuffer(getFixedLengthWrappedDashData({
            position1: angleData.arcPosition1,
            position2: angleData.arcPosition2,
            color: uniformArray3(this.arcLength, c.r, c.g, c.b),
            color2: uniformArray3(this.arcLength, c.r, c.g, c.b)
        }), this.getBufferParams({
            linewidth: this.linewidth,
            visible: this.arcVisible,
            opacity: this.lineOpacity
        }));
        this.sectorLength = angleData.sectorPosition.length / 3;
        this.sectorBuffer = new MeshBuffer({
            position: angleData.sectorPosition,
            color: uniformArray3(this.sectorLength, c.r, c.g, c.b)
        }, this.getBufferParams({
            visible: this.sectorVisible
        }));
        return {
            bufferList: [
                this.textBuffer,
                this.vectorBuffer,
                this.arcBuffer,
                this.sectorBuffer
            ]
        };
    };
    AngleRepresentation.prototype.updateData = function updateData (what, data) {
        MeasurementRepresentation$$1.prototype.updateData.call(this, what, data);
        var vectorData = {};
        var arcData = {};
        var sectorData = {};
        if (what.color) {
            var c = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.colorValue);
            Object.assign(vectorData, {
                color: uniformArray3(this.n * 2, c.r, c.g, c.b),
                color2: uniformArray3(this.n * 2, c.r, c.g, c.b)
            });
            Object.assign(arcData, {
                color: uniformArray3(this.arcLength, c.r, c.g, c.b),
                color2: uniformArray3(this.arcLength, c.r, c.g, c.b)
            });
            Object.assign(sectorData, {
                color: uniformArray3(this.sectorLength, c.r, c.g, c.b)
            });
        }
        // if (what.sectorOpacity) {
        //   this.sectorBuffer.opacity = what.sectorOpacity
        // }
        this.vectorBuffer.setAttributes(vectorData);
        this.arcBuffer.setAttributes(arcData);
        this.sectorBuffer.setAttributes(sectorData);
    };
    AngleRepresentation.prototype.setParameters = function setParameters (params) {
        var rebuild = false;
        var what = {};
        MeasurementRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        if (params && (params.vectorVisible !== undefined ||
            params.arcVisible !== undefined ||
            params.sectorVisible !== undefined)) {
            this.setVisibility(this.visible);
        }
        if (params && params.lineOpacity) {
            this.vectorBuffer.setParameters({ opacity: params.lineOpacity });
            this.arcBuffer.setParameters({ opacity: params.lineOpacity });
        }
        if (params && params.opacity !== undefined) {
            this.vectorBuffer.setParameters({ opacity: this.lineOpacity });
            this.arcBuffer.setParameters({ opacity: this.lineOpacity });
        }
        if (params && params.linewidth) {
            this.vectorBuffer.setParameters({ linewidth: params.linewidth });
            this.arcBuffer.setParameters({ linewidth: params.linewidth });
        }
        return this;
    };
    AngleRepresentation.prototype.setVisibility = function setVisibility (value, noRenderRequest) {
        MeasurementRepresentation$$1.prototype.setVisibility.call(this, value, true);
        if (this.vectorBuffer) {
            this.vectorBuffer.setVisibility(this.vectorVisible && this.visible);
        }
        if (this.arcBuffer) {
            this.arcBuffer.setVisibility(this.arcVisible && this.visible);
        }
        if (this.sectorBuffer) {
            this.sectorBuffer.setVisibility(this.sectorVisible && this.visible);
        }
        if (!noRenderRequest)
            { this.viewer.requestRender(); }
        return this;
    };

    return AngleRepresentation;
}(MeasurementRepresentation));
/**
 * Ensure mid point does not coincide with first or second
 * @param  {Float32Array} position 9*nAngle array of coordinates
 * @return {Float32Array}          Filtered position array, may be shorter
 */
function validatePositions(position) {
    var include = [];
    var n = position.length / 9;
    for (var i = 0; i < n; i++) {
        // Check that first point not same as second and that second not same as third
        var okay = true;
        for (var j = i; j < i + 3; j += 3) {
            if (position[j] === position[j + 3] &&
                position[j + 1] === position[j + 4] &&
                position[j + 2] === position[j + 5]) {
                okay = false;
            }
        }
        if (okay)
            { include.push(i); }
    }
    var outPosition = new Float32Array(include.length * 9);
    var outIdx = 0;
    include.forEach(function (i) {
        copyArray(position, outPosition, i * 9, outIdx * 9, 9);
        outIdx++;
    });
    return outPosition;
}
function atomTriplePositions(sview, atomTriple) {
    return validatePositions(parseNestedAtoms(sview, atomTriple));
}
/**
 * Converts triple positions into data required to build various buffers.
 */
function getAngleData(position, params) {
    if ( params === void 0 ) params = {};

    var angleStep = defaults(params.angleStep, Math.PI / 90);
    var n = position.length / 9;
    var angles = new Float32Array(n);
    var labelPosition = new Float32Array(n * 3);
    var labelText = new Array(n);
    var vectorPosition1 = new Float32Array(n * 6); // Two lines per angle
    var vectorPosition2 = new Float32Array(n * 6);
    var arcPositionTmp1 = new Array(n); // Start points for arc lines
    var arcPositionTmp2 = new Array(n); // End points for arc lines
    var sectorPositionTmp = new Array(n); // Triangle points
    var totalSegments = 0;
    // Re-used vectors etc
    var p1 = v3new(); // Positions of points for each angel
    var p2 = v3new();
    var p3 = v3new();
    var v21 = v3new(); // Vectors
    var v23 = v3new();
    var cross = v3new(); // Cross product v21xv23
    var cross2 = v3new(); // In-plane cross product v21 x (v21 x v23)
    var labelTmp = v3new();
    var arcPoint = v3new();
    var loop = function ( i ) {
        var p = 9 * i;
        v3fromArray(p1, position, p);
        v3fromArray(p2, position, p + 3);
        v3fromArray(p3, position, p + 6);
        var v = 6 * i;
        v3toArray(p1, vectorPosition1, v);
        v3toArray(p2, vectorPosition2, v);
        v3toArray(p2, vectorPosition1, v + 3);
        v3toArray(p3, vectorPosition2, v + 3);
        v3sub(v21, p1, p2);
        v3sub(v23, p3, p2);
        v3normalize(v21, v21); // validatePositions ensures valid
        v3normalize(v23, v23);
        v3cross(cross, v21, v23);
        var crossLength = v3length(cross);
        var dot = v3dot(v21, v23);
        var angle = angles[i] = Math.atan2(crossLength, dot);
        labelText[i] = (RAD2DEG * angle).toFixed(1) + String.fromCharCode(0x00B0);
        if (v3length(cross) === 0.0) {
            // Angle exactly 0/180, pick an arbitrary direction
            cross[0] = 1.0;
            cross[1] = 0.0;
            cross[2] = 0.0;
        }
        v3cross(cross2, cross, v21);
        v3normalize(cross2, cross2);
        calcArcPoint(labelTmp, p2, v21, cross2, angle / 2.0);
        // TODO: Scale label position?
        v3toArray(labelTmp, labelPosition, 3 * i);
        // Build the arc and sector
        var nSegments = Math.ceil(angle / angleStep);
        var sectorVertices = new Float32Array(nSegments * 9);
        sectorPositionTmp[i] = sectorVertices;
        var arcVertices1 = new Float32Array(nSegments * 3);
        var arcVertices2 = new Float32Array(nSegments * 3);
        arcPositionTmp1[i] = arcVertices1;
        arcPositionTmp2[i] = arcVertices2;
        v3add(arcPoint, p2, v21); // Our initial arc point
        var appendArcSection = function (a, j) {
            var si = j * 9;
            var ai = j * 3;
            v3toArray(p2, sectorVertices, si);
            v3toArray(arcPoint, sectorVertices, si + 3);
            v3toArray(arcPoint, arcVertices1, ai);
            calcArcPoint(arcPoint, p2, v21, cross2, a);
            v3toArray(arcPoint, sectorVertices, si + 6);
            v3toArray(arcPoint, arcVertices2, ai);
        };
        var j = 0;
        for (var a = angleStep; a < angle; a += angleStep) {
            appendArcSection(a, j);
            j++;
        }
        appendArcSection(angle, j);
        totalSegments += nSegments;
    };

    for (var i = 0; i < n; i++) loop( i );
    // Flatten nested arrays of arc/segment points
    var arcSize = totalSegments * 3;
    var sectorSize = totalSegments * 9;
    var arcPosition1 = new Float32Array(arcSize);
    var arcPosition2 = new Float32Array(arcSize);
    var sectorPosition = new Float32Array(sectorSize);
    var sectorOffset = 0;
    var arcOffset = 0;
    for (var i$1 = 0; i$1 < n; i$1++) {
        var ap1 = arcPositionTmp1[i$1];
        var ap2 = arcPositionTmp2[i$1];
        copyArray(ap1, arcPosition1, 0, arcOffset, ap1.length);
        copyArray(ap2, arcPosition2, 0, arcOffset, ap2.length);
        arcOffset += ap1.length; // === ap2.length
        var sp = sectorPositionTmp[i$1];
        copyArray(sp, sectorPosition, 0, sectorOffset, sp.length);
        sectorOffset += sp.length;
    }
    return {
        labelPosition: labelPosition,
        labelText: labelText,
        vectorPosition1: vectorPosition1,
        vectorPosition2: vectorPosition2,
        arcPosition1: arcPosition1,
        arcPosition2: arcPosition2,
        sectorPosition: sectorPosition
    };
}
RepresentationRegistry.add('angle', AngleRepresentation);

/**
 * @file Cylinder Geometry Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var scale$2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var eye = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var target = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var up = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 1, 0);
var CylinderGeometryBufferDefaultParameters = Object.assign({
    radialSegments: 1,
    openEnded: true
}, BufferDefaultParameters);
function getData$1(data, params) {
    if ( params === void 0 ) params = {};

    var geo = getGeo(params);
    var n = data.position1.length;
    var geoLength = geo.attributes.position.array.length / 3;
    var count = n / 3;
    var primitiveId = new Float32Array(count * 2 * geoLength);
    serialBlockArray(count, geoLength, 0, primitiveId);
    serialBlockArray(count, geoLength, count * geoLength, primitiveId);
    var position = new Float32Array(n * 2);
    var color = new Float32Array(n * 2);
    return {
        position: position, color: color, primitiveId: primitiveId, picking: data.picking
    };
}
function getGeo(params) {
    if ( params === void 0 ) params = {};

    var radialSegments = defaults(params.radialSegments, 10);
    var openEnded = defaults(params.openEnded, true);
    var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeRotationX(Math.PI / 2);
    var geo = new __WEBPACK_IMPORTED_MODULE_0_three__["k" /* CylinderBufferGeometry */](1, // radiusTop,
    1, // radiusBottom,
    1, // height,
    radialSegments, // radialSegments,
    1, // heightSegments,
    openEnded // openEnded
    );
    geo.applyMatrix4(matrix);
    return geo;
}
/**
 * Cylinder geometry buffer.
 *
 * @example
 * var cylinderGeometryBuffer = new CylinderGeometryBuffer({
 *   position1: new Float32Array([ 0, 0, 0 ]),
 *   position2: new Float32Array([ 1, 1, 1 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   color2: new Float32Array([ 0, 1, 0 ]),
 *   radius: new Float32Array([ 1 ])
 * });
 */
var CylinderGeometryBuffer = /*@__PURE__*/(function (GeometryBuffer$$1) {
    function CylinderGeometryBuffer(data, params) {
        if ( params === void 0 ) params = {};

        GeometryBuffer$$1.call(this, getData$1(data, params), params, getGeo(params));
        this.updateNormals = true;
        var n = data.position1.length;
        var m = data.radius.length;
        this.__center = new Float32Array(n);
        this._position = new Float32Array(n * 2);
        this._color = new Float32Array(n * 2);
        this._from = new Float32Array(n * 2);
        this._to = new Float32Array(n * 2);
        this._radius = new Float32Array(m * 2);
        this.setAttributes(data, true);
    }

    if ( GeometryBuffer$$1 ) CylinderGeometryBuffer.__proto__ = GeometryBuffer$$1;
    CylinderGeometryBuffer.prototype = Object.create( GeometryBuffer$$1 && GeometryBuffer$$1.prototype );
    CylinderGeometryBuffer.prototype.constructor = CylinderGeometryBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return CylinderGeometryBufferDefaultParameters; };
    CylinderGeometryBuffer.prototype.applyPositionTransform = function applyPositionTransform (matrix, i, i3) {
        eye.fromArray(this._from, i3);
        target.fromArray(this._to, i3);
        matrix.lookAt(eye, target, up);
        var r = this._radius[i];
        scale$2.set(r, r, eye.distanceTo(target));
        matrix.scale(scale$2);
    };
    CylinderGeometryBuffer.prototype.setAttributes = function setAttributes (data, initNormals) {
        if ( data === void 0 ) data = {};

        var meshData = {};
        if (data.position1 && data.position2) {
            calculateCenterArray(data.position1, data.position2, this.__center);
            calculateCenterArray(data.position1, this.__center, this._position);
            calculateCenterArray(this.__center, data.position2, this._position, data.position1.length);
            this._from.set(data.position1);
            this._from.set(this.__center, data.position1.length);
            this._to.set(this.__center);
            this._to.set(data.position2, this.__center.length);
            meshData.position = this._position;
        }
        if (data.color && data.color2) {
            this._color.set(data.color);
            this._color.set(data.color2, data.color.length);
            meshData.color = this._color;
        }
        if (data.radius) {
            this._radius.set(data.radius);
            this._radius.set(data.radius, data.radius.length);
            meshData.radius = this._radius;
        }
        GeometryBuffer$$1.prototype.setAttributes.call(this, meshData, initNormals);
    };

    Object.defineProperties( CylinderGeometryBuffer.prototype, prototypeAccessors );

    return CylinderGeometryBuffer;
}(GeometryBuffer));

ShaderRegistry.add('shader/CylinderImpostor.vert', "\nattribute vec3 mapping;\nattribute vec3 position1;\nattribute vec3 position2;\nattribute float radius;\nvarying vec3 axis;\nvarying vec4 base_radius;\nvarying vec4 end_b;\nvarying vec3 U;\nvarying 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 = normalize( cross( cam_dir, ldir ) );\nleft = radius * left;\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 top_position = modelViewMatrix * vec4( center + ldir, 1.0 );\nvec4 end4 = top_position;\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}");

ShaderRegistry.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 point = w.xyz / w.w;\nvec3 base = base_radius.xyz;\nfloat vRadius = base_radius.w;\nvec3 end = end_b.xyz;\nfloat b = end_b.w;\nvec3 end_cyl = end;\nvec3 surface_point = point;\nvec3 ray_target = surface_point;\nvec3 ray_origin = vec3(0.0);\nvec3 ray_direction = mix(normalize(ray_origin - ray_target), vec3(0.0, 0.0, 1.0), ortho);\nmat3 basis = mat3( U, V, axis );\nvec3 diff = ray_target - 0.5 * (base + end_cyl);\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;\nfloat dist = (-a1 + sqrt(d)) / a2;\nvec3 new_point = ray_target + dist * ray_direction;\nvec3 tmp_point = new_point - base;\nvec3 _normal = normalize( tmp_point - axis * dot(tmp_point, axis) );\nray_origin = mix( ray_origin, surface_point, ortho );\nfloat front_cap_test = dot( tmp_point, axis );\nfloat end_cap_test = dot((new_point - end_cyl), axis);\n#ifndef CAP\nvec3 new_point2 = ray_target + ( (-a1 - sqrt(d)) / a2 ) * ray_direction;\nvec3 tmp_point2 = new_point2 - base;\n#endif\nif (front_cap_test < 0.0)\n{\nfloat dNV = dot(-axis, ray_direction);\nif (dNV < 0.0)\ndiscard;\nfloat near = dot(-axis, (base)) / dNV;\nvec3 front_point = ray_direction * near + ray_origin;\nif (dot(front_point - base, front_point-base) > radius2)\ndiscard;\n#ifdef CAP\nnew_point = front_point;\n_normal = axis;\n#else\nnew_point = ray_target + ( (-a1 - sqrt(d)) / a2 ) * ray_direction;\ndNV = dot(-axis, ray_direction);\nnear = dot(axis, end_cyl) / dNV;\nnew_point2 = ray_direction * near + ray_origin;\nif (dot(new_point2 - end_cyl, new_point2-base) < radius2)\ndiscard;\ninterior = true;\n#endif\n}\nif( end_cap_test > 0.0 )\n{\nfloat dNV = dot(axis, ray_direction);\nif (dNV < 0.0)\ndiscard;\nfloat near = dot(axis, end_cyl) / dNV;\nvec3 end_point = ray_direction * near + ray_origin;\nif( dot(end_point - end_cyl, end_point-base) > radius2 )\ndiscard;\n#ifdef CAP\nnew_point = end_point;\n_normal = axis;\n#else\nnew_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;\ninterior = true;\n#endif\n}\ngl_FragDepthEXT = calcDepth( new_point );\n#ifdef NEAR_CLIP\nif( calcClip( new_point ) > 0.0 ){\ndist = (-a1 - sqrt(d)) / a2;\nnew_point = ray_target + dist * ray_direction;\nif( calcClip( new_point ) > 0.0 )\ndiscard;\ninterior = true;\ngl_FragDepthEXT = calcDepth( new_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;\nnew_point = ray_target + dist * ray_direction;\ninterior = true;\ngl_FragDepthEXT = calcDepth( new_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;\nnew_point = ray_target + dist * ray_direction;\ninterior = true;\ngl_FragDepthEXT = calcDepth( new_point );\nif( gl_FragDepthEXT >= 0.0 ){\ngl_FragDepthEXT = 0.0 + ( 0.0000001 / vRadius );\n}\n}\n#endif\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 vViewPosition = -new_point;\nvec3 vNormal = _normal;\nvec3 vColor;\nif( distSq3( new_point, end_cyl ) < distSq3( new_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}");

/**
 * @file Mapped Aligned Box Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var mapping$1 = new Float32Array([
    -1.0, 1.0, -1.0,
    -1.0, -1.0, -1.0,
    1.0, 1.0, -1.0,
    1.0, 1.0, 1.0,
    1.0, -1.0, -1.0,
    1.0, -1.0, 1.0
]);
var mappingIndices$1 = new Uint16Array([
    0, 1, 2,
    1, 4, 2,
    2, 4, 3,
    4, 5, 3
]);
/**
 * Mapped Aligned box buffer. Draws boxes where one side is always screen-space aligned.
 * Used to render cylinder imposters.
 * @interface
 */
var MappedAlignedBoxBuffer = /*@__PURE__*/(function (MappedBuffer$$1) {
    function MappedAlignedBoxBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MappedBuffer$$1.call(this, 'v3', data, params);
    }

    if ( MappedBuffer$$1 ) MappedAlignedBoxBuffer.__proto__ = MappedBuffer$$1;
    MappedAlignedBoxBuffer.prototype = Object.create( MappedBuffer$$1 && MappedBuffer$$1.prototype );
    MappedAlignedBoxBuffer.prototype.constructor = MappedAlignedBoxBuffer;

    var prototypeAccessors = { mapping: { configurable: true },mappingIndices: { configurable: true },mappingIndicesSize: { configurable: true },mappingSize: { configurable: true },mappingItemSize: { configurable: true } };
    prototypeAccessors.mapping.get = function () { return mapping$1; };
    prototypeAccessors.mappingIndices.get = function () { return mappingIndices$1; };
    prototypeAccessors.mappingIndicesSize.get = function () { return 12; };
    prototypeAccessors.mappingSize.get = function () { return 6; };
    prototypeAccessors.mappingItemSize.get = function () { return 3; };

    Object.defineProperties( MappedAlignedBoxBuffer.prototype, prototypeAccessors );

    return MappedAlignedBoxBuffer;
}(MappedBuffer));

/**
 * @file Cylinder Impostor Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var CylinderImpostorBufferDefaultParameters = Object.assign({
    openEnded: false
}, BufferDefaultParameters);
var CylinderImpostorBufferParameterTypes = Object.assign({
    openEnded: { updateShader: true }
}, BufferParameterTypes);
/**
 * Cylinder impostor buffer.
 *
 * @example
 * var cylinderimpostorBuffer = new CylinderImpostorBuffer({
 *     position1: new Float32Array([ 0, 0, 0 ]),
 *     position2: new Float32Array([ 1, 1, 1 ]),
 *     color: new Float32Array([ 1, 0, 0 ]),
 *     color2: new Float32Array([ 0, 1, 0 ]),
 *     radius: new Float32Array([ 1 ])
 * });
 */
var CylinderImpostorBuffer = /*@__PURE__*/(function (MappedAlignedBoxBuffer$$1) {
    function CylinderImpostorBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MappedAlignedBoxBuffer$$1.call(this, data, params);
        this.parameterTypes = CylinderImpostorBufferParameterTypes;
        this.isImpostor = true;
        this.vertexShader = 'CylinderImpostor.vert';
        this.fragmentShader = 'CylinderImpostor.frag';
        this.addUniforms({
            'modelViewMatrixInverse': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]() },
            'ortho': { value: 0.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(data);
        this.makeMapping();
    }

    if ( MappedAlignedBoxBuffer$$1 ) CylinderImpostorBuffer.__proto__ = MappedAlignedBoxBuffer$$1;
    CylinderImpostorBuffer.prototype = Object.create( MappedAlignedBoxBuffer$$1 && MappedAlignedBoxBuffer$$1.prototype );
    CylinderImpostorBuffer.prototype.constructor = CylinderImpostorBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return CylinderImpostorBufferDefaultParameters; };
    CylinderImpostorBuffer.prototype.getDefines = function getDefines (type) {
        var defines = MappedAlignedBoxBuffer$$1.prototype.getDefines.call(this, type);
        if (!this.parameters.openEnded) {
            defines.CAP = 1;
        }
        return defines;
    };

    Object.defineProperties( CylinderImpostorBuffer.prototype, prototypeAccessors );

    return CylinderImpostorBuffer;
}(MappedAlignedBoxBuffer));

/**
 * @file Cylinder Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var CylinderBufferDefaultParameters = Object.assign({
    disableImpostor: false
}, CylinderGeometryBufferDefaultParameters, CylinderImpostorBufferDefaultParameters);
/**
 * Cylinder buffer. Depending on the value {@link ExtensionFragDepth} and
 * `params.disableImpostor` the constructor returns either a
 * {@link CylinderGeometryBuffer} or a {@link CylinderImpostorBuffer}
 * @implements {Buffer}
 *
 * @example
 * var cylinderBuffer = new CylinderBuffer({
 *   position1: new Float32Array([ 0, 0, 0 ]),
 *   position2: new Float32Array([ 1, 1, 1 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   color2: new Float32Array([ 0, 1, 0 ]),
 *   radius: new Float32Array([ 1 ])
 * });
 */
var CylinderBuffer = function CylinderBuffer(data, params) {
    if ( params === void 0 ) params = {};

    if (!data.color2 && data.color)
        { data.color2 = data.color; }
    if (!ExtensionFragDepth || (params && params.disableImpostor)) {
        return new CylinderGeometryBuffer(data, params);
    }
    else {
        return new CylinderImpostorBuffer(data, params);
    }
};
BufferRegistry.add('cylinder', CylinderBuffer);

/**
 * @file Axes Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Axes representation. Show principal axes and/or a box aligned with them
 * that fits the structure or selection.
 *
 * __Name:__ _axes_
 *
 * @example
 * stage.loadFile( "rcsb://3pqr", {
 *     assembly: "BU1"
 * } ).then( function( o ){
 *     o.addRepresentation( "cartoon" );
 *     o.addRepresentation( "axes", {
 *         sele: "RET", showAxes: false, showBox: true, radius: 0.2
 *     } );
 *     o.addRepresentation( "ball+stick", { sele: "RET" } );
 *     o.addRepresentation( "axes", {
 *         sele: ":B and backbone", showAxes: false, showBox: true, radius: 0.2
 *     } );
 *     stage.autoView();
 *     var pa = o.structure.getPrincipalAxes();
 *     stage.animationControls.rotate( pa.getRotationQuaternion(), 1500 );
 * } );
 */
var AxesRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function AxesRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'axes';
        this.parameters = Object.assign({
            radiusSize: {
                type: 'number', precision: 3, max: 10.0, min: 0.001
            },
            sphereDetail: true,
            radialSegments: true,
            disableImpostor: true,
            showAxes: {
                type: 'boolean', rebuild: true
            },
            showBox: {
                type: 'boolean', rebuild: true
            }
        }, this.parameters, {
            assembly: null
        });
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) AxesRepresentation.__proto__ = StructureRepresentation$$1;
    AxesRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    AxesRepresentation.prototype.constructor = AxesRepresentation;
    AxesRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.radiusSize = defaults(p.radiusSize, 0.5);
        p.colorValue = defaults(p.colorValue, 'lightgreen');
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        this.showAxes = defaults(p.showAxes, true);
        this.showBox = defaults(p.showBox, false);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    AxesRepresentation.prototype.getPrincipalAxes = function getPrincipalAxes () {
        var selection;
        var assembly = this.getAssembly();
        if (assembly) {
            selection = assembly.partList[0].getSelection();
        }
        return this.structureView.getPrincipalAxes(selection);
    };
    AxesRepresentation.prototype.getAxesData = function getAxesData (sview) {
        var pa = this.getPrincipalAxes();
        var c = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.colorValue);
        var vn = 0;
        var en = 0;
        if (this.showAxes) {
            vn += 6;
            en += 3;
        }
        if (this.showBox) {
            vn += 8;
            en += 12;
        }
        var vertexPosition = new Float32Array(3 * vn);
        var vertexColor = uniformArray3(vn, c.r, c.g, c.b);
        var vertexRadius = uniformArray(vn, this.radiusSize);
        var edgePosition1 = new Float32Array(3 * en);
        var edgePosition2 = new Float32Array(3 * en);
        var edgeColor = uniformArray3(en, c.r, c.g, c.b);
        var edgeRadius = uniformArray(en, this.radiusSize);
        var offset = 0;
        if (this.showAxes) {
            var addAxis = function (v1, v2) {
                v1.toArray(vertexPosition, offset * 2);
                v2.toArray(vertexPosition, offset * 2 + 3);
                v1.toArray(edgePosition1, offset);
                v2.toArray(edgePosition2, offset);
                offset += 3;
            };
            addAxis(pa.begA, pa.endA);
            addAxis(pa.begB, pa.endB);
            addAxis(pa.begC, pa.endC);
        }
        if (this.showBox) {
            var v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
            var ref = pa.getProjectedScaleForAtoms(sview);
            var d1a = ref.d1a;
            var d2a = ref.d2a;
            var d3a = ref.d3a;
            var d1b = ref.d1b;
            var d2b = ref.d2b;
            var d3b = ref.d3b;
            // console.log(d1a, d2a, d3a, d1b, d2b, d3b)
            var offset2 = offset * 2;
            var addCorner = function (d1, d2, d3) {
                v.copy(pa.center)
                    .addScaledVector(pa.normVecA, d1)
                    .addScaledVector(pa.normVecB, d2)
                    .addScaledVector(pa.normVecC, d3);
                v.toArray(vertexPosition, offset2);
                offset2 += 3;
            };
            addCorner(d1a, d2a, d3a);
            addCorner(d1a, d2a, d3b);
            addCorner(d1a, d2b, d3b);
            addCorner(d1a, d2b, d3a);
            addCorner(d1b, d2b, d3b);
            addCorner(d1b, d2b, d3a);
            addCorner(d1b, d2a, d3a);
            addCorner(d1b, d2a, d3b);
            var edgeOffset = offset;
            var addEdge = function (a, b) {
                v.fromArray(vertexPosition, offset * 2 + a * 3)
                    .toArray(edgePosition1, edgeOffset);
                v.fromArray(vertexPosition, offset * 2 + b * 3)
                    .toArray(edgePosition2, edgeOffset);
                edgeOffset += 3;
            };
            addEdge(0, 1);
            addEdge(0, 3);
            addEdge(0, 6);
            addEdge(1, 2);
            addEdge(1, 7);
            addEdge(2, 3);
            addEdge(2, 4);
            addEdge(3, 5);
            addEdge(4, 5);
            addEdge(4, 7);
            addEdge(5, 6);
            addEdge(6, 7);
        }
        var picker = new AxesPicker(pa);
        return {
            vertex: {
                position: vertexPosition,
                color: vertexColor,
                radius: vertexRadius,
                picking: picker
            },
            edge: {
                position1: edgePosition1,
                position2: edgePosition2,
                color: edgeColor,
                color2: edgeColor,
                radius: edgeRadius,
                picking: picker
            }
        };
    };
    AxesRepresentation.prototype.create = function create () {
        var axesData = this.getAxesData(this.structureView);
        this.sphereBuffer = new SphereBuffer(axesData.vertex, this.getBufferParams({
            sphereDetail: this.sphereDetail,
            disableImpostor: this.disableImpostor,
            dullInterior: true
        }));
        this.cylinderBuffer = new CylinderBuffer(axesData.edge, this.getBufferParams({
            openEnded: true,
            radialSegments: this.radialSegments,
            disableImpostor: this.disableImpostor,
            dullInterior: true
        }));
        this.dataList.push({
            sview: this.structureView,
            bufferList: [this.sphereBuffer, this.cylinderBuffer]
        });
    };
    AxesRepresentation.prototype.createData = function createData (sview) {
        return;
    };
    AxesRepresentation.prototype.updateData = function updateData (what, data) {
        var axesData = this.getAxesData(data.sview);
        var sphereData = {};
        var cylinderData = {};
        if (!what || what.position) {
            Object.assign(sphereData, {
                position: axesData.vertex.position
            });
            Object.assign(cylinderData, {
                position1: axesData.edge.position1,
                position2: axesData.edge.position2
            });
        }
        if (!what || what.color) {
            Object.assign(sphereData, {
                color: axesData.vertex.color
            });
            Object.assign(cylinderData, {
                color: axesData.edge.color,
                color2: axesData.edge.color
            });
        }
        if (!what || what.radius) {
            Object.assign(sphereData, {
                radius: axesData.vertex.radius
            });
            Object.assign(cylinderData, {
                radius: axesData.edge.radius
            });
        }
        this.sphereBuffer.setAttributes(sphereData);
        this.cylinderBuffer.setAttributes(cylinderData);
    };

    return AxesRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('axes', AxesRepresentation);

/**
 * @file Ball And Stick Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Ball And Stick representation parameter object. Extends {@link RepresentationParameters} and
 * {@link StructureRepresentationParameters}.
 *
 * @typedef {Object} BallAndStickRepresentationParameters - ball and stick representation parameters
 *
 * @property {Integer} sphereDetail - sphere quality (icosahedron subdivisions)
 * @property {Integer} radialSegments - cylinder quality (number of segments)
 * @property {Boolean} openEnded - capped or not
 * @property {Boolean} disableImpostor - disable use of raycasted impostors for rendering
 * @property {Float} aspectRatio - size difference between atom and bond radii
 * @property {Boolean} lineOnly - render only bonds, and only as lines
 * @property {Integer} linewidth - width of lines
 * @property {Boolean} cylinderOnly - render only bonds (no atoms)
 * @property {String} multipleBond - one off "off", "symmetric", "offset"
 * @property {Float} bondSpacing - spacing for multiple bond rendering
 * @property {Float} bondScale - scale/radius for multiple bond rendering
 */
/**
 * Ball And Stick representation. Show atoms as spheres and bonds as cylinders.
 *
 * __Name:__ _ball+stick_
 *
 * @example
 * stage.loadFile( "rcsb://1crn" ).then( function( o ){
 *     o.addRepresentation( "ball+stick" );
 *     o.autoView();
 * } );
 */
var BallAndStickRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function BallAndStickRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'ball+stick';
        this.parameters = Object.assign({
            sphereDetail: true,
            radialSegments: true,
            openEnded: true,
            disableImpostor: true,
            aspectRatio: {
                type: 'number', precision: 1, max: 10.0, min: 1.0
            },
            lineOnly: {
                type: 'boolean', rebuild: true
            },
            cylinderOnly: {
                type: 'boolean', rebuild: true
            },
            multipleBond: {
                type: 'select',
                rebuild: true,
                options: {
                    'off': 'off',
                    'symmetric': 'symmetric',
                    'offset': 'offset'
                }
            },
            bondScale: {
                type: 'number', precision: 2, max: 1.0, min: 0.01
            },
            bondSpacing: {
                type: 'number', precision: 2, max: 2.0, min: 0.5
            },
            linewidth: {
                type: 'integer', max: 50, min: 1, buffer: true
            }
        }, this.parameters);
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) BallAndStickRepresentation.__proto__ = StructureRepresentation$$1;
    BallAndStickRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    BallAndStickRepresentation.prototype.constructor = BallAndStickRepresentation;
    BallAndStickRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.radiusType = defaults(p.radiusType, 'size');
        p.radiusSize = defaults(p.radiusSize, 0.15);
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        this.aspectRatio = defaults(p.aspectRatio, 2.0);
        this.lineOnly = defaults(p.lineOnly, false);
        this.cylinderOnly = defaults(p.cylinderOnly, false);
        this.multipleBond = defaults(p.multipleBond, 'off');
        this.bondSpacing = defaults(p.bondSpacing, 1.0);
        this.bondScale = defaults(p.bondScale, 0.4);
        this.linewidth = defaults(p.linewidth, 2);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    BallAndStickRepresentation.prototype.getAtomRadius = function getAtomRadius (atom) {
        return this.aspectRatio * StructureRepresentation$$1.prototype.getAtomRadius.call(this, atom);
    };
    BallAndStickRepresentation.prototype.getAtomParams = function getAtomParams (what, params) {
        var p = StructureRepresentation$$1.prototype.getAtomParams.call(this, what, params);
        p.radiusParams.scale *= this.aspectRatio;
        return p;
    };
    BallAndStickRepresentation.prototype.getAtomData = function getAtomData (sview, what, params) {
        return sview.getAtomData(this.getAtomParams(what, params));
    };
    BallAndStickRepresentation.prototype.getBondParams = function getBondParams (what, params) {
        params = Object.assign({
            multipleBond: this.multipleBond,
            bondSpacing: this.bondSpacing,
            bondScale: this.bondScale
        }, params);
        return StructureRepresentation$$1.prototype.getBondParams.call(this, what, params);
    };
    BallAndStickRepresentation.prototype.getBondData = function getBondData (sview, what, params) {
        return sview.getBondData(this.getBondParams(what, params));
    };
    BallAndStickRepresentation.prototype.createData = function createData (sview) {
        var bufferList = [];
        if (this.lineOnly) {
            this.lineBuffer = new WideLineBuffer(this.getBondData(sview, { position: true, color: true, picking: true }), this.getBufferParams({ linewidth: this.linewidth }));
            bufferList.push(this.lineBuffer);
        }
        else {
            var cylinderBuffer = new CylinderBuffer(this.getBondData(sview), this.getBufferParams({
                openEnded: this.openEnded,
                radialSegments: this.radialSegments,
                disableImpostor: this.disableImpostor,
                dullInterior: true
            }));
            bufferList.push(cylinderBuffer);
            if (!this.cylinderOnly) {
                var sphereBuffer = new SphereBuffer(this.getAtomData(sview), this.getBufferParams({
                    sphereDetail: this.sphereDetail,
                    disableImpostor: this.disableImpostor,
                    dullInterior: true
                }));
                bufferList.push(sphereBuffer);
            }
        }
        return {
            bufferList: bufferList
        };
    };
    BallAndStickRepresentation.prototype.updateData = function updateData (what, data) {
        if (this.multipleBond !== 'off' && what && what.radius) {
            what.position = true;
        }
        var bondData = this.getBondData(data.sview, what);
        if (this.lineOnly) {
            var lineData = {};
            if (!what || what.position) {
                Object.assign(lineData, {
                    position1: bondData.position1,
                    position2: bondData.position2
                });
            }
            if (!what || what.color) {
                Object.assign(lineData, {
                    color: bondData.color,
                    color2: bondData.color2
                });
            }
            data.bufferList[0].setAttributes(lineData);
        }
        else {
            var cylinderData = {};
            if (!what || what.position) {
                Object.assign(cylinderData, {
                    position1: bondData.position1,
                    position2: bondData.position2
                });
            }
            if (!what || what.color) {
                Object.assign(cylinderData, {
                    color: bondData.color,
                    color2: bondData.color2
                });
            }
            if (!what || what.radius) {
                Object.assign(cylinderData, {
                    radius: bondData.radius
                });
            }
            data.bufferList[0].setAttributes(cylinderData);
            if (!this.cylinderOnly) {
                var atomData = this.getAtomData(data.sview, what);
                var sphereData = {};
                if (!what || what.position) {
                    Object.assign(sphereData, {
                        position: atomData.position
                    });
                }
                if (!what || what.color) {
                    Object.assign(sphereData, {
                        color: atomData.color
                    });
                }
                if (!what || what.radius) {
                    Object.assign(sphereData, {
                        radius: atomData.radius
                    });
                }
                data.bufferList[1].setAttributes(sphereData);
            }
        }
    };
    BallAndStickRepresentation.prototype.setParameters = function setParameters (params) {
        if ( params === void 0 ) params = {};

        var rebuild = false;
        var what = {};
        if (params.aspectRatio || params.bondSpacing || params.bondScale) {
            Object.assign(what, { radius: true });
            if (!ExtensionFragDepth || this.disableImpostor) {
                rebuild = true;
            }
        }
        StructureRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        return this;
    };

    return BallAndStickRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('ball+stick', BallAndStickRepresentation);

/**
 * @file Backbone Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Backbone representation. Show cylinders (or lines) connecting .CA (protein)
 * or .C4'/.C3' (RNA/DNA) of polymers.
 *
 * __Name:__ _backbone_
 *
 * @example
 * stage.loadFile( "rcsb://1sfi" ).then( function( o ){
 *     o.addRepresentation( "backbone" );
 *     o.autoView();
 * } );
 */
var BackboneRepresentation = /*@__PURE__*/(function (BallAndStickRepresentation$$1) {
    function BackboneRepresentation(structure, viewer, params) {
        BallAndStickRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'backbone';
        this.parameters = Object.assign({}, this.parameters, {
            multipleBond: null,
            bondSpacing: null
        });
        this.init(params);
    }

    if ( BallAndStickRepresentation$$1 ) BackboneRepresentation.__proto__ = BallAndStickRepresentation$$1;
    BackboneRepresentation.prototype = Object.create( BallAndStickRepresentation$$1 && BallAndStickRepresentation$$1.prototype );
    BackboneRepresentation.prototype.constructor = BackboneRepresentation;
    BackboneRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.aspectRatio = defaults(p.aspectRatio, 1.0);
        p.radiusSize = defaults(p.radiusSize, 0.25);
        BallAndStickRepresentation$$1.prototype.init.call(this, p);
    };
    BackboneRepresentation.prototype.getAtomRadius = function getAtomRadius (atom) {
        return atom.isTrace() ? BallAndStickRepresentation$$1.prototype.getAtomRadius.call(this, atom) : 0;
    };
    BackboneRepresentation.prototype.getAtomData = function getAtomData (sview, what, params) {
        return sview.getBackboneAtomData(this.getAtomParams(what, params));
    };
    BackboneRepresentation.prototype.getBondData = function getBondData (sview, what, params) {
        return sview.getBackboneBondData(this.getBondParams(what, params));
    };

    return BackboneRepresentation;
}(BallAndStickRepresentation));
RepresentationRegistry.add('backbone', BackboneRepresentation);

/**
 * @file Base Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Base representation. Show cylinders for RNA/DNA ladders.
 *
 * __Name:__ _base_
 *
 * @example
 * stage.loadFile( "rcsb://1d66" ).then( function( o ){
 *     o.addRepresentation( "cartoon", { sele: "nucleic" } );
 *     o.addRepresentation( "base", { color: "resname" } );
 *     o.autoView( "nucleic" );
 * } );
 */
var BaseRepresentation = /*@__PURE__*/(function (BallAndStickRepresentation$$1) {
    function BaseRepresentation(structure, viewer, params) {
        BallAndStickRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'base';
        this.parameters = Object.assign({}, this.parameters, {
            multipleBond: null,
            bondSpacing: null
        });
    }

    if ( BallAndStickRepresentation$$1 ) BaseRepresentation.__proto__ = BallAndStickRepresentation$$1;
    BaseRepresentation.prototype = Object.create( BallAndStickRepresentation$$1 && BallAndStickRepresentation$$1.prototype );
    BaseRepresentation.prototype.constructor = BaseRepresentation;
    BaseRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.aspectRatio = defaults(p.aspectRatio, 1.0);
        p.radiusSize = defaults(p.radiusSize, 0.3);
        BallAndStickRepresentation$$1.prototype.init.call(this, p);
    };
    BaseRepresentation.prototype.getAtomData = function getAtomData (sview, what, params) {
        return sview.getRungAtomData(this.getAtomParams(what, params));
    };
    BaseRepresentation.prototype.getBondData = function getBondData (sview, what, params) {
        var p = this.getBondParams(what, params);
        Object.assign(p.colorParams, { rung: true });
        return sview.getRungBondData(p);
    };

    return BaseRepresentation;
}(BallAndStickRepresentation));
RepresentationRegistry.add('base', BaseRepresentation);

/**
 * @file Spline
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Interpolator = function Interpolator(m, tension) {
    this.m = m;
    this.tension = tension;
    this.dt = 1.0 / this.m;
    this.delta = 0.0001;
    this.vec1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.vec2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.vDir = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.vTan = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.vNorm = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.vBin = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    this.m2 = Math.ceil(this.m / 2);
};
Interpolator.prototype.interpolateToArr = function interpolateToArr (v0, v1, v2, v3, t, arr, offset) {
    arr[offset + 0] = spline(v0.x, v1.x, v2.x, v3.x, t, this.tension);
    arr[offset + 1] = spline(v0.y, v1.y, v2.y, v3.y, t, this.tension);
    arr[offset + 2] = spline(v0.z, v1.z, v2.z, v3.z, t, this.tension);
};
Interpolator.prototype.interpolateToVec = function interpolateToVec (v0, v1, v2, v3, t, vec) {
    vec.x = spline(v0.x, v1.x, v2.x, v3.x, t, this.tension);
    vec.y = spline(v0.y, v1.y, v2.y, v3.y, t, this.tension);
    vec.z = spline(v0.z, v1.z, v2.z, v3.z, t, this.tension);
};
Interpolator.prototype.interpolatePosition = function interpolatePosition (v0, v1, v2, v3, pos, offset) {
    for (var j = 0; j < this.m; ++j) {
        var l = offset + j * 3;
        var d = this.dt * j;
        this.interpolateToArr(v0, v1, v2, v3, d, pos, l);
    }
};
Interpolator.prototype.interpolateTangent = function interpolateTangent (v0, v1, v2, v3, tan, offset) {
    for (var j = 0; j < this.m; ++j) {
        var d = this.dt * j;
        var d1 = d - this.delta;
        var d2 = d + this.delta;
        var l = offset + j * 3;
        // capping as a precaution
        if (d1 < 0)
            { d1 = 0; }
        if (d2 > 1)
            { d2 = 1; }
        //
        this.interpolateToVec(v0, v1, v2, v3, d1, this.vec1);
        this.interpolateToVec(v0, v1, v2, v3, d2, this.vec2);
        //
        this.vec2.sub(this.vec1).normalize();
        this.vec2.toArray(tan, l);
    }
};
Interpolator.prototype.vectorSubdivide = function vectorSubdivide (interpolationFn, iterator, array, offset, isCyclic) {
    var v0;
    var v1 = iterator.next();
    var v2 = iterator.next();
    var v3 = iterator.next();
    //
    var n = iterator.size;
    var n1 = n - 1;
    var k = offset || 0;
    for (var i = 0; i < n1; ++i) {
        v0 = v1;
        v1 = v2;
        v2 = v3;
        v3 = iterator.next();
        interpolationFn.apply(this, [v0, v1, v2, v3, array, k]);
        k += 3 * this.m;
    }
    if (isCyclic) {
        v0 = iterator.get(n - 2);
        v1 = iterator.get(n - 1);
        v2 = iterator.get(0);
        v3 = iterator.get(1);
        interpolationFn.apply(this, [v0, v1, v2, v3, array, k]);
        k += 3 * this.m;
    }
};
//
Interpolator.prototype.getPosition = function getPosition (iterator, array, offset, isCyclic) {
    iterator.reset();
    this.vectorSubdivide(this.interpolatePosition, iterator, array, offset, isCyclic);
    var n1 = iterator.size - 1;
    var k = n1 * this.m * 3;
    if (isCyclic)
        { k += this.m * 3; }
    var v = iterator.get(isCyclic ? 0 : n1);
    array[k] = v.x;
    array[k + 1] = v.y;
    array[k + 2] = v.z;
};
Interpolator.prototype.getTangent = function getTangent (iterator, array, offset, isCyclic) {
    iterator.reset();
    this.vectorSubdivide(this.interpolateTangent, iterator, array, offset, isCyclic);
    var n1 = iterator.size - 1;
    var k = n1 * this.m * 3;
    if (isCyclic)
        { k += this.m * 3; }
    copyArray(array, array, k - 3, k, 3);
};
Interpolator.prototype.interpolateNormalDir = function interpolateNormalDir (u0, u1, u2, u3, v0, v1, v2, v3, tan, norm, bin, offset, shift) {
    for (var j = 0; j < this.m; ++j) {
        var l = offset + j * 3;
        if (shift)
            { l += this.m2 * 3; }
        var d = this.dt * j;
        this.interpolateToVec(u0, u1, u2, u3, d, this.vec1);
        this.interpolateToVec(v0, v1, v2, v3, d, this.vec2);
        this.vDir.subVectors(this.vec2, this.vec1).normalize();
        this.vTan.fromArray(tan, l);
        this.vBin.crossVectors(this.vDir, this.vTan).normalize();
        this.vBin.toArray(bin, l);
        this.vNorm.crossVectors(this.vTan, this.vBin).normalize();
        this.vNorm.toArray(norm, l);
    }
};
Interpolator.prototype.interpolateNormal = function interpolateNormal (vDir, tan, norm, bin, offset) {
    for (var j = 0; j < this.m; ++j) {
        var l = offset + j * 3;
        vDir.copy(this.vNorm);
        this.vTan.fromArray(tan, l);
        this.vBin.crossVectors(vDir, this.vTan).normalize();
        this.vBin.toArray(bin, l);
        this.vNorm.crossVectors(this.vTan, this.vBin).normalize();
        this.vNorm.toArray(norm, l);
    }
};
Interpolator.prototype.getNormal = function getNormal (size, tan, norm, bin, offset, isCyclic) {
    this.vNorm.set(0, 0, 1);
    var n = size;
    var n1 = n - 1;
    var k = offset || 0;
    for (var i = 0; i < n1; ++i) {
        this.interpolateNormal(this.vDir, tan, norm, bin, k);
        k += 3 * this.m;
    }
    if (isCyclic) {
        this.interpolateNormal(this.vDir, tan, norm, bin, k);
        k += 3 * this.m;
    }
    this.vBin.toArray(bin, k);
    this.vNorm.toArray(norm, k);
};
Interpolator.prototype.getNormalDir = function getNormalDir (iterDir1, iterDir2, tan, norm, bin, offset, isCyclic, shift) {
    iterDir1.reset();
    iterDir2.reset();
    //
    var vSub1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var vSub2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var vSub3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var vSub4 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    //
    var d1v1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var d1v2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().copy(iterDir1.next());
    var d1v3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().copy(iterDir1.next());
    var d1v4 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().copy(iterDir1.next());
    var d2v1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var d2v2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().copy(iterDir2.next());
    var d2v3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().copy(iterDir2.next());
    var d2v4 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]().copy(iterDir2.next());
    //
    this.vNorm.set(0, 0, 1);
    var n = iterDir1.size;
    var n1 = n - 1;
    var k = offset || 0;
    for (var i = 0; i < n1; ++i) {
        d1v1.copy(d1v2);
        d1v2.copy(d1v3);
        d1v3.copy(d1v4);
        d1v4.copy(iterDir1.next());
        d2v1.copy(d2v2);
        d2v2.copy(d2v3);
        d2v3.copy(d2v4);
        d2v4.copy(iterDir2.next());
        //
        if (i === 0) {
            vSub1.subVectors(d2v1, d1v1);
            vSub2.subVectors(d2v2, d1v2);
            if (vSub1.dot(vSub2) < 0) {
                vSub2.multiplyScalar(-1);
                d2v2.addVectors(d1v2, vSub2);
            }
            vSub3.subVectors(d2v3, d1v3);
            if (vSub2.dot(vSub3) < 0) {
                vSub3.multiplyScalar(-1);
                d2v3.addVectors(d1v3, vSub3);
            }
        }
        else {
            vSub3.copy(vSub4);
        }
        vSub4.subVectors(d2v4, d1v4);
        if (vSub3.dot(vSub4) < 0) {
            vSub4.multiplyScalar(-1);
            d2v4.addVectors(d1v4, vSub4);
        }
        this.interpolateNormalDir(d1v1, d1v2, d1v3, d1v4, d2v1, d2v2, d2v3, d2v4, tan, norm, bin, k, shift);
        k += 3 * this.m;
    }
    if (isCyclic) {
        d1v1.copy(iterDir1.get(n - 2));
        d1v2.copy(iterDir1.get(n - 1));
        d1v3.copy(iterDir1.get(0));
        d1v4.copy(iterDir1.get(1));
        d2v1.copy(iterDir2.get(n - 2));
        d2v2.copy(iterDir2.get(n - 1));
        d2v3.copy(iterDir2.get(0));
        d2v4.copy(iterDir2.get(1));
        //
        vSub3.copy(vSub4);
        vSub4.subVectors(d2v4, d1v4);
        if (vSub3.dot(vSub4) < 0) {
            vSub4.multiplyScalar(-1);
            d2v4.addVectors(d1v4, vSub4);
        }
        this.interpolateNormalDir(d1v1, d1v2, d1v3, d1v4, d2v1, d2v2, d2v3, d2v4, tan, norm, bin, k, shift);
        k += 3 * this.m;
    }
    if (shift) {
        // FIXME shift requires data from one this.more preceeding residue
        this.vBin.fromArray(bin, this.m2 * 3);
        this.vNorm.fromArray(norm, this.m2 * 3);
        for (var j = 0; j < this.m2; ++j) {
            this.vBin.toArray(bin, j * 3);
            this.vNorm.toArray(norm, j * 3);
        }
    }
    else {
        this.vBin.toArray(bin, k);
        this.vNorm.toArray(norm, k);
    }
};
//
Interpolator.prototype.interpolateColor = function interpolateColor (item1, item2, colFn, col, offset) {
    var j, l;
    for (j = 0; j < this.m2; ++j) {
        l = offset + j * 3;
        colFn.apply(this, [item1, col, l]); // itemColorToArray
    }
    for (j = this.m2; j < this.m; ++j) {
        l = offset + j * 3;
        colFn.apply(this, [item2, col, l]); // itemColorToArray
    }
};
Interpolator.prototype.getColor = function getColor (iterator, colFn, col, offset, isCyclic) {
    iterator.reset();
    iterator.next(); // first element not needed
    var i0;
    var i1 = iterator.next();
    //
    var n = iterator.size;
    var n1 = n - 1;
    var k = offset || 0;
    for (var i = 0; i < n1; ++i) {
        i0 = i1;
        i1 = iterator.next();
        this.interpolateColor(i0, i1, colFn, col, k);
        k += 3 * this.m;
    }
    if (isCyclic) {
        i0 = iterator.get(n - 1);
        i1 = iterator.get(0);
        this.interpolateColor(i0, i1, colFn, col, k);
        k += 3 * this.m;
    }
    //
    col[k] = col[k - 3];
    col[k + 1] = col[k - 2];
    col[k + 2] = col[k - 1];
};
//
Interpolator.prototype.interpolatePicking = function interpolatePicking (item1, item2, pickFn, pick, offset) {
    var j;
    for (j = 0; j < this.m2; ++j) {
        pick[offset + j] = pickFn.apply(this, [item1]);
    }
    for (j = this.m2; j < this.m; ++j) {
        pick[offset + j] = pickFn.apply(this, [item2]);
    }
};
Interpolator.prototype.getPicking = function getPicking (iterator, pickFn, pick, offset, isCyclic) {
    iterator.reset();
    iterator.next(); // first element not needed
    var i0;
    var i1 = iterator.next();
    //
    var n = iterator.size;
    var n1 = n - 1;
    var k = offset || 0;
    for (var i = 0; i < n1; ++i) {
        i0 = i1;
        i1 = iterator.next();
        this.interpolatePicking(i0, i1, pickFn, pick, k);
        k += this.m;
    }
    if (isCyclic) {
        i0 = iterator.get(n - 1);
        i1 = iterator.get(0);
        this.interpolatePicking(i0, i1, pickFn, pick, k);
        k += this.m;
    }
    //
    pick[k] = pick[k - 1];
};
//
Interpolator.prototype.interpolateSize = function interpolateSize (item1, item2, sizeFn, size, offset) {
    var s1 = sizeFn.apply(this, [item1]);
    var s2 = sizeFn.apply(this, [item2]);
    for (var j = 0; j < this.m; ++j) {
        // linear interpolation
        var t = j / this.m;
        size[offset + j] = (1 - t) * s1 + t * s2;
    }
};
Interpolator.prototype.getSize = function getSize (iterator, sizeFn, size, offset, isCyclic) {
    iterator.reset();
    iterator.next(); // first element not needed
    var i0;
    var i1 = iterator.next();
    //
    var n = iterator.size;
    var n1 = n - 1;
    var k = offset || 0;
    for (var i = 0; i < n1; ++i) {
        i0 = i1;
        i1 = iterator.next();
        this.interpolateSize(i0, i1, sizeFn, size, k);
        k += this.m;
    }
    if (isCyclic) {
        i0 = iterator.get(n - 1);
        i1 = iterator.get(0);
        this.interpolateSize(i0, i1, sizeFn, size, k);
        k += this.m;
    }
    //
    size[k] = size[k - 1];
};
var Spline = function Spline(polymer, params) {
    this.polymer = polymer;
    this.size = polymer.residueCount;
    var p = params || {};
    this.directional = p.directional || false;
    this.positionIterator = p.positionIterator || false;
    this.subdiv = p.subdiv || 1;
    this.smoothSheet = p.smoothSheet || false;
    if (!p.tension) {
        this.tension = this.polymer.isNucleic() ? 0.5 : 0.9;
    }
    else {
        this.tension = p.tension;
    }
    this.interpolator = new Interpolator(this.subdiv, this.tension);
};
Spline.prototype.getAtomIterator = function getAtomIterator (type, smooth) {
    var polymer = this.polymer;
    var structure = polymer.structure;
    var n = polymer.residueCount;
    var i = 0;
    var j = -1;
    var cache = [
        structure.getAtomProxy(),
        structure.getAtomProxy(),
        structure.getAtomProxy(),
        structure.getAtomProxy()
    ];
    var cache2 = [
        new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](),
        new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](),
        new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](),
        new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]()
    ];
    function next() {
        var atomProxy = get(j);
        j += 1;
        return atomProxy;
    }
    var apPrev = structure.getAtomProxy();
    var apNext = structure.getAtomProxy();
    function get(idx) {
        var atomProxy = cache[i % 4];
        atomProxy.index = polymer.getAtomIndexByType(idx, type);
        if (smooth && idx > 0 && idx < n && atomProxy.sstruc === 'e') {
            var vec = cache2[i % 4];
            apPrev.index = polymer.getAtomIndexByType(idx + 1, type);
            apNext.index = polymer.getAtomIndexByType(idx - 1, type);
            vec.addVectors(apPrev, apNext)
                .add(atomProxy).add(atomProxy)
                .multiplyScalar(0.25);
            i += 1;
            return vec;
        }
        i += 1;
        return atomProxy;
    }
    function reset() {
        i = 0;
        j = -1;
    }
    return {
        size: n,
        next: next,
        get: get,
        reset: reset
    };
};
Spline.prototype.getSubdividedColor = function getSubdividedColor (params) {
    var m = this.subdiv;
    var polymer = this.polymer;
    var n = polymer.residueCount;
    var n1 = n - 1;
    var nCol = n1 * m * 3 + 3;
    if (polymer.isCyclic)
        { nCol += m * 3; }
    var col = new Float32Array(nCol);
    var iterator = this.getAtomIterator('trace');
    var p = params || {};
    p.structure = polymer.structure;
    var colormaker = ColormakerRegistry$1.getScheme(p);
    function colFn(item, array, offset) {
        colormaker.atomColorToArray(item, array, offset);
    }
    this.interpolator.getColor(iterator, colFn, col, 0, polymer.isCyclic);
    return {
        'color': col
    };
};
Spline.prototype.getSubdividedPicking = function getSubdividedPicking () {
    var m = this.subdiv;
    var polymer = this.polymer;
    var n = polymer.residueCount;
    var n1 = n - 1;
    var nCol = n1 * m + 1;
    if (polymer.isCyclic)
        { nCol += m; }
    var structure = polymer.structure;
    var iterator = this.getAtomIterator('trace');
    var pick = new Float32Array(nCol);
    function pickFn(item) {
        return item.index;
    }
    this.interpolator.getPicking(iterator, pickFn, pick, 0, polymer.isCyclic);
    return {
        'picking': new AtomPicker(pick, structure)
    };
};
Spline.prototype.getSubdividedPosition = function getSubdividedPosition () {
    var pos = this.getPosition();
    return {
        'position': pos
    };
};
Spline.prototype.getSubdividedOrientation = function getSubdividedOrientation () {
    var tan = this.getTangent();
    var normals = this.getNormals(tan);
    return {
        'tangent': tan,
        'normal': normals.normal,
        'binormal': normals.binormal
    };
};
Spline.prototype.getSubdividedSize = function getSubdividedSize (params) {
    var m = this.subdiv;
    var polymer = this.polymer;
    var n = polymer.residueCount;
    var n1 = n - 1;
    var nSize = n1 * m + 1;
    if (polymer.isCyclic)
        { nSize += m; }
    var size = new Float32Array(nSize);
    var iterator = this.getAtomIterator('trace');
    var radiusFactory = new RadiusFactory(params);
    function sizeFn(item) {
        return radiusFactory.atomRadius(item);
    }
    this.interpolator.getSize(iterator, sizeFn, size, 0, polymer.isCyclic);
    return {
        'size': size
    };
};
Spline.prototype.getPosition = function getPosition () {
    var m = this.subdiv;
    var polymer = this.polymer;
    var n = polymer.residueCount;
    var n1 = n - 1;
    var nPos = n1 * m * 3 + 3;
    if (polymer.isCyclic)
        { nPos += m * 3; }
    var pos = new Float32Array(nPos);
    var iterator = this.positionIterator || this.getAtomIterator('trace', this.smoothSheet);
    this.interpolator.getPosition(iterator, pos, 0, polymer.isCyclic);
    return pos;
};
Spline.prototype.getTangent = function getTangent () {
    var m = this.subdiv;
    var polymer = this.polymer;
    var n = this.size;
    var n1 = n - 1;
    var nTan = n1 * m * 3 + 3;
    if (polymer.isCyclic)
        { nTan += m * 3; }
    var tan = new Float32Array(nTan);
    var iterator = this.positionIterator || this.getAtomIterator('trace', this.smoothSheet);
    this.interpolator.getTangent(iterator, tan, 0, polymer.isCyclic);
    return tan;
};
Spline.prototype.getNormals = function getNormals (tan) {
    var m = this.subdiv;
    var polymer = this.polymer;
    var isProtein = polymer.isProtein();
    var n = this.size;
    var n1 = n - 1;
    var nNorm = n1 * m * 3 + 3;
    if (polymer.isCyclic)
        { nNorm += m * 3; }
    var norm = new Float32Array(nNorm);
    var bin = new Float32Array(nNorm);
    if (this.directional && !this.polymer.isCg()) {
        var iterDir1 = this.getAtomIterator('direction1');
        var iterDir2 = this.getAtomIterator('direction2');
        this.interpolator.getNormalDir(iterDir1, iterDir2, tan, norm, bin, 0, polymer.isCyclic, isProtein);
    }
    else {
        this.interpolator.getNormal(n, tan, norm, bin, 0, polymer.isCyclic);
    }
    return {
        'normal': norm,
        'binormal': bin
    };
};

/**
 * @file Tube Mesh Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var vTangent = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var vMeshNormal = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var TubeMeshBufferDefaultParameters = Object.assign({
    radialSegments: 4,
    capped: false,
    aspectRatio: 1.0
}, BufferDefaultParameters);
function getData$2(data, params) {
    if ( params === void 0 ) params = {};

    var radialSegments = defaults(params.radialSegments, 4);
    var capped = defaults(params.capped, false);
    var capVertices = capped ? radialSegments : 0;
    var capTriangles = capped ? radialSegments - 2 : 0;
    var n = data.position.length / 3;
    var n1 = n - 1;
    var x = n * radialSegments * 3 + 2 * capVertices * 3;
    var xi = n1 * 2 * radialSegments * 3 + 2 * capTriangles * 3;
    return {
        position: new Float32Array(x),
        color: new Float32Array(x),
        index: getUintArray(xi, x / 3),
        normal: new Float32Array(x),
        picking: data.picking
    };
}
/**
 * Tube mesh buffer. Draws a tube.
 */
var TubeMeshBuffer = /*@__PURE__*/(function (MeshBuffer$$1) {
    function TubeMeshBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MeshBuffer$$1.call(this, getData$2(data, params), params);
        this.capVertices = this.parameters.capped ? this.parameters.radialSegments : 0;
        this.capTriangles = this.parameters.capped ? this.parameters.radialSegments - 2 : 0;
        this.size2 = data.position.length / 3;
        data.primitiveId = serialArray(this.size2);
        this.setAttributes(data);
        this.makeIndex();
    }

    if ( MeshBuffer$$1 ) TubeMeshBuffer.__proto__ = MeshBuffer$$1;
    TubeMeshBuffer.prototype = Object.create( MeshBuffer$$1 && MeshBuffer$$1.prototype );
    TubeMeshBuffer.prototype.constructor = TubeMeshBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return TubeMeshBufferDefaultParameters; };
    TubeMeshBuffer.prototype.setAttributes = function setAttributes (data) {
        if ( data === void 0 ) data = {};

        var aspectRatio = this.parameters.aspectRatio;
        var n = this.size2;
        var n1 = n - 1;
        var radialSegments = this.parameters.radialSegments;
        var attributes = this.geometry.attributes;
        var position, normal, binormal, tangent, color, size, primitiveId;
        var meshPosition, meshColor, meshNormal, meshPrimitiveId;
        if (data.position) {
            position = data.position;
            normal = data.normal;
            binormal = data.binormal;
            tangent = data.tangent;
            size = data.size;
            meshPosition = attributes.position.array;
            meshNormal = attributes.normal.array;
            attributes.position.needsUpdate = true;
            attributes.normal.needsUpdate = true;
        }
        if (data.color) {
            color = data.color;
            meshColor = attributes.color.array;
            attributes.color.needsUpdate = true;
        }
        if (data.primitiveId) {
            primitiveId = data.primitiveId;
            meshPrimitiveId = attributes.primitiveId.array;
            attributes.primitiveId.needsUpdate = true;
        }
        var k, l;
        var radius = 0;
        var normX = 0;
        var normY = 0;
        var normZ = 0;
        var biX = 0;
        var biY = 0;
        var biZ = 0;
        var posX = 0;
        var posY = 0;
        var posZ = 0;
        var cxArr = [];
        var cyArr = [];
        var cx1Arr = [];
        var cy1Arr = [];
        var cx2Arr = [];
        var cy2Arr = [];
        if (position) {
            for (var j = 0; j < radialSegments; ++j) {
                var v = (j / radialSegments) * 2 * Math.PI;
                cxArr[j] = aspectRatio * Math.cos(v);
                cyArr[j] = Math.sin(v);
                cx1Arr[j] = aspectRatio * Math.cos(v - 0.01);
                cy1Arr[j] = Math.sin(v - 0.01);
                cx2Arr[j] = aspectRatio * Math.cos(v + 0.01);
                cy2Arr[j] = Math.sin(v + 0.01);
            }
        }
        for (var i = 0; i < n; ++i) {
            k = i * 3;
            l = k * radialSegments;
            if (position && tangent && normal && binormal && size) {
                vTangent.set(tangent[k], tangent[k + 1], tangent[k + 2]);
                normX = normal[k];
                normY = normal[k + 1];
                normZ = normal[k + 2];
                biX = binormal[k];
                biY = binormal[k + 1];
                biZ = binormal[k + 2];
                posX = position[k];
                posY = position[k + 1];
                posZ = position[k + 2];
                radius = size[i];
            }
            for (var j$1 = 0; j$1 < radialSegments; ++j$1) {
                var s = l + j$1 * 3;
                if (position) {
                    var cx = -radius * cxArr[j$1]; // TODO: Hack: Negating it so it faces outside.
                    var cy = radius * cyArr[j$1];
                    var cx1 = -radius * cx1Arr[j$1];
                    var cy1 = radius * cy1Arr[j$1];
                    var cx2 = -radius * cx2Arr[j$1];
                    var cy2 = radius * cy2Arr[j$1];
                    meshPosition[s] = posX + cx * normX + cy * biX;
                    meshPosition[s + 1] = posY + cx * normY + cy * biY;
                    meshPosition[s + 2] = posZ + cx * normZ + cy * biZ;
                    // TODO half of these are symmetric
                    vMeshNormal.set(
                    // ellipse tangent approximated as vector from/to adjacent points
                    (cx2 * normX + cy2 * biX) - (cx1 * normX + cy1 * biX), (cx2 * normY + cy2 * biY) - (cx1 * normY + cy1 * biY), (cx2 * normZ + cy2 * biZ) - (cx1 * normZ + cy1 * biZ)).cross(vTangent);
                    meshNormal[s] = vMeshNormal.x;
                    meshNormal[s + 1] = vMeshNormal.y;
                    meshNormal[s + 2] = vMeshNormal.z;
                }
                if (color) {
                    meshColor[s] = color[k];
                    meshColor[s + 1] = color[k + 1];
                    meshColor[s + 2] = color[k + 2];
                }
                if (primitiveId) {
                    meshPrimitiveId[i * radialSegments + j$1] = primitiveId[i];
                }
            }
        }
        // front cap
        k = 0;
        l = n * 3 * radialSegments;
        for (var j$2 = 0; j$2 < radialSegments; ++j$2) {
            var s$1 = k + j$2 * 3;
            var t = l + j$2 * 3;
            if (position && tangent) {
                meshPosition[t] = meshPosition[s$1];
                meshPosition[t + 1] = meshPosition[s$1 + 1];
                meshPosition[t + 2] = meshPosition[s$1 + 2];
                meshNormal[t] = tangent[k];
                meshNormal[t + 1] = tangent[k + 1];
                meshNormal[t + 2] = tangent[k + 2];
            }
            if (color) {
                meshColor[t] = meshColor[s$1];
                meshColor[t + 1] = meshColor[s$1 + 1];
                meshColor[t + 2] = meshColor[s$1 + 2];
            }
            if (primitiveId) {
                meshPrimitiveId[n * radialSegments + j$2] = meshPrimitiveId[0 + j$2];
            }
        }
        // back cap
        k = (n - 1) * 3 * radialSegments;
        l = (n + 1) * 3 * radialSegments;
        for (var j$3 = 0; j$3 < radialSegments; ++j$3) {
            var s$2 = k + j$3 * 3;
            var t$1 = l + j$3 * 3;
            if (position && tangent) {
                meshPosition[t$1] = meshPosition[s$2];
                meshPosition[t$1 + 1] = meshPosition[s$2 + 1];
                meshPosition[t$1 + 2] = meshPosition[s$2 + 2];
                meshNormal[t$1] = tangent[n1 * 3];
                meshNormal[t$1 + 1] = tangent[n1 * 3 + 1];
                meshNormal[t$1 + 2] = tangent[n1 * 3 + 2];
            }
            if (color) {
                meshColor[t$1] = meshColor[s$2];
                meshColor[t$1 + 1] = meshColor[s$2 + 1];
                meshColor[t$1 + 2] = meshColor[s$2 + 2];
            }
            if (primitiveId) {
                meshPrimitiveId[(n + 1) * radialSegments + j$3] = meshPrimitiveId[(n - 1) * radialSegments + j$3];
            }
        }
    };
    TubeMeshBuffer.prototype.makeIndex = function makeIndex () {
        var index = this.geometry.getIndex();
        if (!index) {
            Log.error('Index is null');
            return;
        }
        var meshIndex = index.array;
        var n = this.size2;
        var n1 = n - 1;
        var capTriangles = this.capTriangles;
        var radialSegments = this.parameters.radialSegments;
        var radialSegments1 = this.parameters.radialSegments + 1;
        var k, l;
        for (var i = 0; i < n1; ++i) {
            var k$1 = i * radialSegments * 3 * 2;
            var irs = i * radialSegments;
            var irs1 = (i + 1) * radialSegments;
            for (var j = 0; j < radialSegments; ++j) {
                l = k$1 + j * 3 * 2;
                // meshIndex[ l + 0 ] = irs + ( ( j + 0 ) % radialSegments );
                meshIndex[l] = irs + j;
                meshIndex[l + 1] = irs + ((j + 1) % radialSegments);
                // meshIndex[ l + 2 ] = irs1 + ( ( j + 0 ) % radialSegments );
                meshIndex[l + 2] = irs1 + j;
                // meshIndex[ l + 3 ] = irs1 + ( ( j + 0 ) % radialSegments );
                meshIndex[l + 3] = irs1 + j;
                meshIndex[l + 4] = irs + ((j + 1) % radialSegments);
                meshIndex[l + 5] = irs1 + ((j + 1) % radialSegments);
            }
        }
        // capping
        var strip = [0];
        for (var j$1 = 1; j$1 < radialSegments1 / 2; ++j$1) {
            strip.push(j$1);
            if (radialSegments - j$1 !== j$1) {
                strip.push(radialSegments - j$1);
            }
        }
        // front cap
        l = n1 * radialSegments * 3 * 2;
        k = n * radialSegments;
        for (var j$2 = 0; j$2 < strip.length - 2; ++j$2) {
            if (j$2 % 2 === 0) {
                meshIndex[l + j$2 * 3 + 0] = k + strip[j$2 + 0];
                meshIndex[l + j$2 * 3 + 1] = k + strip[j$2 + 1];
                meshIndex[l + j$2 * 3 + 2] = k + strip[j$2 + 2];
            }
            else {
                meshIndex[l + j$2 * 3 + 0] = k + strip[j$2 + 2];
                meshIndex[l + j$2 * 3 + 1] = k + strip[j$2 + 1];
                meshIndex[l + j$2 * 3 + 2] = k + strip[j$2 + 0];
            }
        }
        // back cap
        l = n1 * radialSegments * 3 * 2 + 3 * capTriangles;
        k = n * radialSegments + radialSegments;
        for (var j$3 = 0; j$3 < strip.length - 2; ++j$3) {
            if (j$3 % 2 === 0) {
                meshIndex[l + j$3 * 3 + 0] = k + strip[j$3 + 0];
                meshIndex[l + j$3 * 3 + 1] = k + strip[j$3 + 1];
                meshIndex[l + j$3 * 3 + 2] = k + strip[j$3 + 2];
            }
            else {
                meshIndex[l + j$3 * 3 + 0] = k + strip[j$3 + 2];
                meshIndex[l + j$3 * 3 + 1] = k + strip[j$3 + 1];
                meshIndex[l + j$3 * 3 + 2] = k + strip[j$3 + 0];
            }
        }
    };

    Object.defineProperties( TubeMeshBuffer.prototype, prototypeAccessors );

    return TubeMeshBuffer;
}(MeshBuffer));

/**
 * @file Cartoon Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Cartoon representation. Show a thick ribbon that
 * smoothly connecting backbone atoms in polymers.
 *
 * __Name:__ _cartoon_
 *
 * @example
 * stage.loadFile( "rcsb://1crn" ).then( function( o ){
 *     o.addRepresentation( "cartoon" );
 *     o.autoView();
 * } );
 */
var CartoonRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function CartoonRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'cartoon';
        this.parameters = Object.assign({
            aspectRatio: {
                type: 'number', precision: 1, max: 10.0, min: 1.0, rebuild: true
            },
            subdiv: {
                type: 'integer', max: 50, min: 1, rebuild: true
            },
            radialSegments: {
                type: 'integer', max: 50, min: 1, rebuild: true
            },
            tension: {
                type: 'number', precision: 1, max: 1.0, min: 0.1
            },
            capped: {
                type: 'boolean', rebuild: true
            },
            smoothSheet: {
                type: 'boolean', rebuild: true
            }
        }, this.parameters);
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) CartoonRepresentation.__proto__ = StructureRepresentation$$1;
    CartoonRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    CartoonRepresentation.prototype.constructor = CartoonRepresentation;
    CartoonRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.colorScheme = defaults(p.colorScheme, 'chainname');
        p.colorScale = defaults(p.colorScale, 'RdYlBu');
        p.radiusType = defaults(p.radiusType, 'sstruc');
        p.radiusScale = defaults(p.radiusScale, 0.7);
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        this.aspectRatio = defaults(p.aspectRatio, 5.0);
        this.tension = defaults(p.tension, NaN);
        this.capped = defaults(p.capped, true);
        this.smoothSheet = defaults(p.smoothSheet, false);
        if (p.quality === 'low') {
            this.subdiv = 3;
            this.radialSegments = 6;
        }
        else if (p.quality === 'medium') {
            this.subdiv = 6;
        }
        else if (p.quality === 'high') {
            this.subdiv = 12;
        }
        else {
            this.subdiv = defaults(p.subdiv, 6);
        }
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    CartoonRepresentation.prototype.getSplineParams = function getSplineParams (params) {
        return Object.assign({
            subdiv: this.subdiv,
            tension: this.tension,
            directional: this.aspectRatio !== 1.0,
            smoothSheet: this.smoothSheet
        }, params);
    };
    CartoonRepresentation.prototype.getSpline = function getSpline (polymer) {
        return new Spline(polymer, this.getSplineParams());
    };
    CartoonRepresentation.prototype.getAspectRatio = function getAspectRatio (polymer) {
        return polymer.isCg() ? 1.0 : this.aspectRatio;
    };
    CartoonRepresentation.prototype.getAtomRadius = function getAtomRadius (atom) {
        return atom.isTrace() ? StructureRepresentation$$1.prototype.getAtomRadius.call(this, atom) : 0;
    };
    CartoonRepresentation.prototype.createData = function createData (sview) {
        var this$1 = this;

        var bufferList = [];
        var polymerList = [];
        this.structure.eachPolymer(function (polymer) {
            if (polymer.residueCount < 4)
                { return; }
            polymerList.push(polymer);
            var spline = this$1.getSpline(polymer);
            var aspectRatio = this$1.getAspectRatio(polymer);
            var subPos = spline.getSubdividedPosition();
            var subOri = spline.getSubdividedOrientation();
            var subCol = spline.getSubdividedColor(this$1.getColorParams());
            var subPick = spline.getSubdividedPicking();
            var subSize = spline.getSubdividedSize(this$1.getRadiusParams());
            bufferList.push(new TubeMeshBuffer(Object.assign({}, subPos, subOri, subCol, subPick, subSize), this$1.getBufferParams({
                radialSegments: this$1.radialSegments,
                aspectRatio: aspectRatio,
                capped: this$1.capped
            })));
        }, sview.getSelection());
        return {
            bufferList: bufferList,
            polymerList: polymerList
        };
    };
    CartoonRepresentation.prototype.updateData = function updateData (what, data) {
        if (Debug)
            { Log.time(this.type + ' repr update'); }
        what = what || {};
        for (var i = 0, il = data.polymerList.length; i < il; ++i) {
            var bufferData = {};
            var polymer = data.polymerList[i];
            var spline = this.getSpline(polymer);
            var aspectRatio = this.getAspectRatio(polymer);
            Object.assign(data.bufferList[i], { aspectRatio: aspectRatio });
            if (what.position || what.radius) {
                var subPos = spline.getSubdividedPosition();
                var subOri = spline.getSubdividedOrientation();
                var subSize = spline.getSubdividedSize(this.getRadiusParams(aspectRatio));
                bufferData.position = subPos.position;
                bufferData.normal = subOri.normal;
                bufferData.binormal = subOri.binormal;
                bufferData.tangent = subOri.tangent;
                bufferData.size = subSize.size;
            }
            if (what.color) {
                var subCol = spline.getSubdividedColor(this.getColorParams());
                bufferData.color = subCol.color;
            }
            if (what.picking) {
                var subPick = spline.getSubdividedPicking();
                bufferData.picking = subPick.picking;
            }
            data.bufferList[i].setAttributes(bufferData);
        }
        if (Debug)
            { Log.timeEnd(this.type + ' repr update'); }
    };
    CartoonRepresentation.prototype.setParameters = function setParameters (params) {
        var rebuild = false;
        var what = {};
        if (params && params.aspectRatio) {
            what.radius = true;
        }
        if (params && params.tension) {
            what.position = true;
        }
        StructureRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        return this;
    };

    return CartoonRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('cartoon', CartoonRepresentation);

/**
 * @file Contact Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Contact representation.
 */
var ContactRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function ContactRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'contact';
        this.parameters = Object.assign({
            hydrogenBond: {
                type: 'boolean', rebuild: true
            },
            weakHydrogenBond: {
                type: 'boolean', rebuild: true
            },
            waterHydrogenBond: {
                type: 'boolean', rebuild: true
            },
            backboneHydrogenBond: {
                type: 'boolean', rebuild: true
            },
            hydrophobic: {
                type: 'boolean', rebuild: true
            },
            halogenBond: {
                type: 'boolean', rebuild: true
            },
            ionicInteraction: {
                type: 'boolean', rebuild: true
            },
            metalCoordination: {
                type: 'boolean', rebuild: true
            },
            cationPi: {
                type: 'boolean', rebuild: true
            },
            piStacking: {
                type: 'boolean', rebuild: true
            },
            filterSele: {
                type: 'text', rebuild: true
            },
            labelVisible: {
                type: 'boolean', rebuild: true
            },
            labelFixedSize: {
                type: 'boolean', buffer: 'fixedSize'
            },
            labelSize: {
                type: 'number', precision: 3, max: 10.0, min: 0.001, rebuild: true
            },
            labelUnit: {
                type: 'select',
                rebuild: true,
                options: { '': '', angstrom: 'angstrom', nm: 'nm' }
            },
            maxHydrophobicDist: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            maxHbondDist: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            maxHbondSulfurDist: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            maxHbondAccAngle: {
                type: 'integer', max: 180, min: 0, rebuild: true
            },
            maxHbondDonAngle: {
                type: 'integer', max: 180, min: 0, rebuild: true
            },
            maxHbondAccPlaneAngle: {
                type: 'integer', max: 90, min: 0, rebuild: true
            },
            maxHbondDonPlaneAngle: {
                type: 'integer', max: 90, min: 0, rebuild: true
            },
            maxPiStackingDist: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            maxPiStackingOffset: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            maxPiStackingAngle: {
                type: 'integer', max: 180, min: 0, rebuild: true
            },
            maxCationPiDist: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            maxCationPiOffset: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            maxIonicDist: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            maxHalogenBondDist: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            maxHalogenBondAngle: {
                type: 'integer', max: 180, min: 0, rebuild: true
            },
            maxMetalDist: {
                type: 'number', precision: 1, max: 10, min: 0.1, rebuild: true
            },
            refineSaltBridges: {
                type: 'boolean', rebuild: true
            },
            masterModelIndex: {
                type: 'integer', max: 1000, min: -1, rebuild: true
            },
            lineOfSightDistFactor: {
                type: 'number', precision: 1, max: 10, min: 0.0, rebuild: true
            },
            radialSegments: true,
            disableImpostor: true
        }, this.parameters);
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) ContactRepresentation.__proto__ = StructureRepresentation$$1;
    ContactRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    ContactRepresentation.prototype.constructor = ContactRepresentation;
    ContactRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.radiusSize = defaults(p.radiusSize, 0.05);
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        this.hydrogenBond = defaults(p.hydrogenBond, true);
        this.weakHydrogenBond = defaults(p.weakHydrogenBond, false);
        this.waterHydrogenBond = defaults(p.waterHydrogenBond, false);
        this.backboneHydrogenBond = defaults(p.backboneHydrogenBond, false);
        this.hydrophobic = defaults(p.hydrophobic, false);
        this.halogenBond = defaults(p.halogenBond, true);
        this.ionicInteraction = defaults(p.ionicInteraction, true);
        this.metalCoordination = defaults(p.metalCoordination, true);
        this.cationPi = defaults(p.cationPi, true);
        this.piStacking = defaults(p.piStacking, true);
        this.filterSele = defaults(p.filterSele, '');
        this.labelVisible = defaults(p.labelVisible, false);
        this.labelFixedSize = defaults(p.labelFixedSize, false);
        this.labelSize = defaults(p.labelSize, 2.0);
        this.labelUnit = defaults(p.labelUnit, '');
        this.maxHydrophobicDist = defaults(p.maxHydrophobicDist, 4.0);
        this.maxHbondDist = defaults(p.maxHbondDist, 3.5);
        this.maxHbondSulfurDist = defaults(p.maxHbondSulfurDist, 4.1);
        this.maxHbondAccAngle = defaults(p.maxHbondAccAngle, 45);
        this.maxHbondDonAngle = defaults(p.maxHbondDonAngle, 45);
        this.maxHbondAccPlaneAngle = defaults(p.maxHbondAccPlaneAngle, 90);
        this.maxHbondDonPlaneAngle = defaults(p.maxHbondDonPlaneAngle, 30);
        this.maxPiStackingDist = defaults(p.maxPiStackingDist, 5.5);
        this.maxPiStackingOffset = defaults(p.maxPiStackingOffset, 2.0);
        this.maxPiStackingAngle = defaults(p.maxPiStackingAngle, 30);
        this.maxCationPiDist = defaults(p.maxCationPiDist, 6.0);
        this.maxCationPiOffset = defaults(p.maxCationPiOffset, 2.0);
        this.maxIonicDist = defaults(p.maxIonicDist, 5.0);
        this.maxHalogenBondDist = defaults(p.maxHalogenBondDist, 3.5);
        this.maxHalogenBondAngle = defaults(p.maxHalogenBondAngle, 30);
        this.maxMetalDist = defaults(p.maxMetalDist, 3.0);
        this.refineSaltBridges = defaults(p.refineSaltBridges, true);
        this.masterModelIndex = defaults(p.masterModelIndex, -1);
        this.lineOfSightDistFactor = defaults(p.lineOfSightDistFactor, 1.0);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    ContactRepresentation.prototype.getAtomRadius = function getAtomRadius () {
        return 0;
    };
    ContactRepresentation.prototype.getContactData = function getContactData$1 (sview) {
        var params = {
            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
        };
        var dataParams = {
            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
        };
        var contacts = calculateContacts(sview, params);
        return getContactData(contacts, sview, dataParams);
    };
    ContactRepresentation.prototype.createData = function createData (sview) {
        var contactData = this.getContactData(sview);
        var bufferList = [
            new CylinderBuffer(getFixedCountDashData(contactData), this.getBufferParams({
                sphereDetail: 1,
                dullInterior: true,
                disableImpostor: this.disableImpostor
            }))
        ];
        if (this.labelVisible) {
            var labelParams = {
                size: this.labelSize,
                unit: this.labelUnit
            };
            bufferList.push(new TextBuffer(getLabelData(contactData, labelParams), this.getBufferParams({ fixedSize: this.labelFixedSize })));
        }
        return { bufferList: bufferList };
    };

    return ContactRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('contact', ContactRepresentation);

/**
 * @file Dihedral Representation
 * @author Fred Ludlow <fred.ludlow@gmail.com>
 * @private
 */
/**
 * Dihedral representation object
 *
 * Reperesentation consists of three parts, visibility can be set for each
 * label - text label indicating dihedral angle
 * line - line indicating four positions that define the dihedral
 * sector - filled arc section
 *
 * @param {Structure} structure - the structure to measure angles in
 * @param {Viewer} viewer - a viewer object
 * @param {AngleRepresentationParameters} params - angle representation parameters
 */
var DihedralRepresentation = /*@__PURE__*/(function (MeasurementRepresentation$$1) {
    function DihedralRepresentation(structure, viewer, params) {
        MeasurementRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'dihedral';
        this.parameters = Object.assign({
            atomQuad: {
                type: 'hidden', rebuild: true
            },
            extendLine: {
                type: 'boolean', rebuild: true, default: true
            },
            lineVisible: {
                type: 'boolean', default: true
            },
            planeVisible: {
                type: 'boolean', default: true
            },
            sectorVisible: {
                type: 'boolean', default: true
            }
        }, this.parameters);
        this.init(params);
    }

    if ( MeasurementRepresentation$$1 ) DihedralRepresentation.__proto__ = MeasurementRepresentation$$1;
    DihedralRepresentation.prototype = Object.create( MeasurementRepresentation$$1 && MeasurementRepresentation$$1.prototype );
    DihedralRepresentation.prototype.constructor = DihedralRepresentation;
    DihedralRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.side = defaults(p.side, 'double');
        p.opacity = defaults(p.opacity, 0.5);
        this.atomQuad = defaults(p.atomQuad, []);
        this.extendLine = defaults(p.extendLine, true);
        this.lineVisible = defaults(p.lineVisible, true);
        this.planeVisible = defaults(p.planeVisible, true);
        this.sectorVisible = defaults(p.sectorVisible, true);
        MeasurementRepresentation$$1.prototype.init.call(this, p);
    };
    DihedralRepresentation.prototype.createData = function createData (sview) {
        if (!sview.atomCount || !this.atomQuad.length)
            { return; }
        var atomPosition = parseNestedAtoms(sview, this.atomQuad);
        var dihedralData = getDihedralData(atomPosition, {
            extendLine: this.extendLine
        });
        var n = this.n = dihedralData.labelText.length;
        var labelColor = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.labelColor);
        this.textBuffer = new TextBuffer({
            position: dihedralData.labelPosition,
            size: uniformArray(n, this.labelSize),
            color: uniformArray3(n, labelColor.r, labelColor.g, labelColor.b),
            text: dihedralData.labelText
        }, this.getLabelBufferParams());
        var c = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.colorValue);
        this.lineLength = dihedralData.linePosition1.length / 3;
        var lineColor = uniformArray3(this.lineLength, c.r, c.g, c.b);
        this.lineBuffer = new WideLineBuffer(getFixedLengthWrappedDashData({
            position1: dihedralData.linePosition1,
            position2: dihedralData.linePosition2,
            color: lineColor,
            color2: lineColor
        }), this.getBufferParams({
            linewidth: this.linewidth,
            visible: this.lineVisible,
            opacity: this.lineOpacity
        }));
        this.planeLength = dihedralData.planePosition.length / 3;
        this.planeBuffer = new MeshBuffer({
            position: dihedralData.planePosition,
            color: uniformArray3(this.planeLength, c.r, c.g, c.b)
        }, this.getBufferParams({
            visible: this.planeVisible
        }));
        this.sectorLength = dihedralData.sectorPosition.length / 3;
        this.sectorBuffer = new MeshBuffer({
            position: dihedralData.sectorPosition,
            color: uniformArray3(this.sectorLength, c.r, c.g, c.b)
        }, this.getBufferParams({
            visible: this.sectorVisible
        }));
        return {
            bufferList: [
                this.textBuffer,
                this.lineBuffer,
                this.planeBuffer,
                this.sectorBuffer
            ]
        };
    };
    DihedralRepresentation.prototype.updateData = function updateData (what, data) {
        MeasurementRepresentation$$1.prototype.updateData.call(this, what, data);
        var lineData = {};
        var planeData = {};
        var sectorData = {};
        if (what.color) {
            var c = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.colorValue);
            Object.assign(lineData, {
                color: uniformArray3(this.lineLength, c.r, c.g, c.b),
                color2: uniformArray3(this.lineLength, c.r, c.g, c.b)
            });
            Object.assign(planeData, {
                color: uniformArray3(this.planeLength, c.r, c.g, c.b)
            });
            Object.assign(sectorData, {
                color: uniformArray3(this.sectorLength, c.r, c.g, c.b)
            });
        }
        this.lineBuffer.setAttributes(lineData);
        this.planeBuffer.setAttributes(planeData);
        this.sectorBuffer.setAttributes(sectorData);
    };
    DihedralRepresentation.prototype.setParameters = function setParameters (params) {
        var rebuild = false;
        var what = {};
        MeasurementRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        if (params && (params.lineVisible !== undefined ||
            params.sectorVisible !== undefined ||
            params.planeVisible !== undefined)) {
            this.setVisibility(this.visible);
        }
        if (params && params.lineOpacity) {
            this.lineBuffer.setParameters({ opacity: params.lineOpacity });
        }
        if (params && params.opacity !== undefined) {
            this.lineBuffer.setParameters({ opacity: this.lineOpacity });
        }
        if (params && params.linewidth) {
            this.lineBuffer.setParameters({ linewidth: params.linewidth });
        }
        return this;
    };
    DihedralRepresentation.prototype.setVisibility = function setVisibility (value, noRenderRequest) {
        MeasurementRepresentation$$1.prototype.setVisibility.call(this, value, true);
        if (this.lineBuffer) {
            this.lineBuffer.setVisibility(this.lineVisible && this.visible);
        }
        if (this.planeBuffer) {
            this.planeBuffer.setVisibility(this.planeVisible && this.visible);
        }
        if (this.sectorBuffer) {
            this.sectorBuffer.setVisibility(this.sectorVisible && this.visible);
        }
        if (!noRenderRequest)
            { this.viewer.requestRender(); }
        return this;
    };

    return DihedralRepresentation;
}(MeasurementRepresentation));
/**
 * Build the data required to create {Buffer} objects, given positions
 * @param  {Float32Array} atomPosition 3*4*nDihedral array of coordinates
 * @return {Object}              Arrays for building buffers
 */
function getDihedralData(position, params) {
    if ( params === void 0 ) params = {};

    var angleStep = defaults(params.angleStep, Math.PI / 90);
    var nPos = position.length;
    var n = position.length / 12;
    var angles = new Float32Array(n);
    var labelPosition = new Float32Array(n * 3);
    var labelText = new Array(n);
    // Temporary arrays as don't know output length yet
    var lineTmp1 = new Array(n);
    var lineTmp2 = new Array(n);
    var sectorTmp = new Array(n);
    var planeTmp = new Array(n);
    // Eventual sizes of output arrays
    var totalLines = 0;
    var totalSegments = 0;
    var totalPlanes = 0;
    var p1 = v3new();
    var p2 = v3new();
    var p3 = v3new();
    var p4 = v3new();
    var v21 = v3new();
    var v23 = v3new();
    var v34 = v3new();
    var tmp = v3new();
    var mid = v3new();
    var inPlane1 = v3new();
    var inPlane2 = v3new();
    var start = v3new();
    var end = v3new();
    var cross = v3new();
    var arcPoint = v3new();
    var i = 0; // Actual output index (after skipping inappropriate)
    var loop = function ( p ) {
        // Set Positions
        v3fromArray(p1, position, p);
        v3fromArray(p2, position, p + 3);
        v3fromArray(p3, position, p + 6);
        v3fromArray(p4, position, p + 9);
        // Vectors between points
        v3sub(v21, p1, p2);
        v3sub(v23, p3, p2);
        if (v3length(v23) === 0.0) {
            return; // Can't define axis
        }
        v3sub(v34, p4, p3);
        v3multiplyScalar(tmp, v23, 0.5);
        v3add(mid, p2, tmp);
        v3normalize(v21, v21);
        v3normalize(v23, v23);
        v3normalize(v34, v34);
        // Which side of plane are p1, p4 (are we measuring something that
        // looks more like an improper? e.g. C, CA, CB, N)
        v3sub(tmp, p1, mid);
        var improperStart = v3dot(tmp, v23) > 0.0;
        v3sub(tmp, p4, mid);
        var improperEnd = v3dot(tmp, v23) < 0.0;
        // Calculate vectors perp to v23 (lying in plane (1,2,3) and (2,3,4))
        v3multiplyScalar(tmp, v23, v3dot(v23, v21));
        v3sub(inPlane1, v21, tmp);
        v3multiplyScalar(tmp, v23, v3dot(v23, v34));
        v3sub(inPlane2, v34, tmp);
        if (v3length(inPlane1) === 0.0 || v3length(inPlane2) === 0.0) {
            return; // Indeterminate angle
        }
        v3normalize(inPlane1, inPlane1);
        v3normalize(inPlane2, inPlane2);
        // Can use acos as normalized and non-zero
        var angle = angles[i] = Math.acos(v3dot(inPlane1, inPlane2));
        labelText[i] = (RAD2DEG * angle).toFixed(1) + String.fromCharCode(0x00B0);
        v3cross(cross, inPlane1, v23);
        v3normalize(cross, cross);
        if (v3dot(cross, inPlane2) < 0.0) {
            v3negate(cross, cross); // Ensure cp faces correct way
        }
        calcArcPoint(tmp, mid, inPlane1, cross, angle / 2.0);
        v3toArray(tmp, labelPosition, 3 * i);
        var nSegments = Math.ceil(angle / angleStep);
        // For extended display mode, 4 straight lines plus arc/segment edge
        // For non-extended, 2 straight lines plus segment edge
        var nLines = nSegments + ((params.extendLine) ? 4 : 2);
        // Don't draw planes if not extending lines
        var nPlanes = params.extendLine ? 36 : 0;
        var line1 = new Float32Array(nLines * 3);
        var line2 = new Float32Array(nLines * 3);
        var sector = new Float32Array(nSegments * 9);
        // 2 planes, 2 triangles each per dihedral (2*2*9)
        var plane = new Float32Array(nPlanes);
        lineTmp1[i] = line1;
        lineTmp2[i] = line2;
        sectorTmp[i] = sector;
        planeTmp[i] = plane;
        // Start points for lines/planes, only required
        // if extending lines
        if (params.extendLine) {
            if (improperStart) { // We'll start on the v3->1 line (tmp)
                v3sub(tmp, p1, p3);
                v3normalize(tmp, tmp);
                v3multiplyScalar(start, tmp, 1.0 / v3dot(inPlane1, tmp));
                v3add(start, start, p3);
            }
            else { // start on the 2->1 line
                v3multiplyScalar(start, v21, 1.0 / v3dot(inPlane1, v21));
                v3add(start, start, p2);
            }
            if (improperEnd) { // Finish on 2->4 line
                v3sub(tmp, p4, p2);
                v3normalize(tmp, tmp);
                v3multiplyScalar(end, tmp, 1.0 / v3dot(inPlane2, tmp));
                v3add(end, end, p2);
            }
            else { // end on the 3->4 line
                v3multiplyScalar(end, v34, 1.0 / v3dot(inPlane2, v34));
                v3add(end, end, p3);
            }
        }
        v3add(arcPoint, mid, inPlane1);
        // index into line1, line2
        var li = 0;
        // If extending lines, there's a bit of stuff to do here
        // figuring out start and end positions
        if (params.extendLine) {
            v3toArray(p1, line1, li);
            v3toArray(start, line2, li);
            li += 3;
            v3toArray(start, line1, li);
            v3toArray(arcPoint, line2, li);
            li += 3;
            // Construct plane at start, if not extening lines
            // this is skipped
            v3toArray(start, plane, 0);
            v3toArray(arcPoint, plane, 3);
            v3toArray(improperStart ? p3 : p2, plane, 6);
            v3toArray(improperStart ? p3 : p2, plane, 9);
            v3toArray(arcPoint, plane, 12);
            v3toArray(mid, plane, 15);
        }
        else {
            // Not extending lines
            v3toArray(mid, line1, li);
            v3toArray(arcPoint, line2, li);
            li += 3;
        }
        var appendArcSection = function (a, j) {
            var si = j * 9;
            v3toArray(mid, sector, si);
            v3toArray(arcPoint, sector, si + 3);
            v3toArray(arcPoint, line1, li);
            calcArcPoint(arcPoint, mid, inPlane1, cross, a);
            v3toArray(arcPoint, sector, si + 6);
            v3toArray(arcPoint, line2, li);
            li += 3;
        };
        var j = 0;
        for (var a = angleStep; a < angle; a += angleStep) {
            appendArcSection(a, j++);
        }
        appendArcSection(angle, j++);
        if (params.extendLine) {
            v3toArray(arcPoint, line1, (nLines - 2) * 3);
            v3toArray(end, line2, (nLines - 2) * 3);
            v3toArray(end, line1, (nLines - 1) * 3);
            v3toArray(p4, line2, (nLines - 1) * 3);
            // Construct plane at end
            v3toArray(end, plane, 18);
            v3toArray(arcPoint, plane, 21);
            v3toArray(improperEnd ? p2 : p3, plane, 24);
            v3toArray(improperEnd ? p2 : p3, plane, 27);
            v3toArray(arcPoint, plane, 30);
            v3toArray(mid, plane, 33);
        }
        else {
            v3toArray(arcPoint, line1, li);
            v3toArray(mid, line2, li);
            li += 3;
        }
        totalLines += nLines * 3;
        totalSegments += nSegments * 9;
        totalPlanes += nPlanes;
        i += 1;
    };

    for (var p = 0; p < nPos; p += 12) loop( p );
    var nSuccess = i;
    var linePosition1 = new Float32Array(totalLines);
    var linePosition2 = new Float32Array(totalLines);
    var sectorPosition = new Float32Array(totalSegments);
    var planePosition = new Float32Array(totalPlanes);
    var lineOffset = 0;
    var sectorOffset = 0;
    var planeOffset = 0;
    for (var i$1 = 0; i$1 < nSuccess; i$1++) {
        var lp1 = lineTmp1[i$1];
        var lp2 = lineTmp2[i$1];
        var sp = sectorTmp[i$1];
        var pp = planeTmp[i$1];
        copyArray(lp1, linePosition1, 0, lineOffset, lp1.length);
        copyArray(lp2, linePosition2, 0, lineOffset, lp2.length);
        copyArray(sp, sectorPosition, 0, sectorOffset, sp.length);
        copyArray(pp, planePosition, 0, planeOffset, pp.length);
        lineOffset += lp1.length;
        sectorOffset += sp.length;
        planeOffset += pp.length;
    }
    return {
        labelPosition: labelPosition.subarray(0, nSuccess * 3),
        labelText: labelText.slice(0, nSuccess),
        linePosition1: linePosition1,
        linePosition2: linePosition2,
        planePosition: planePosition,
        sectorPosition: sectorPosition
    };
}
RepresentationRegistry.add('dihedral', DihedralRepresentation);

/**
 * @file Dihedral Histogram Representation
 * @author Rudolfs Petrovs <rudolfs.petrovs@astx.com>
 * @private
 */
var pointLength = 3; // One Point Length (number of coordinates of one point in 3D)
var pointsInTriangle = 3;
function createUpdatedObject(o, updateSource) {
    function hasKey(obj, key) {
        return key in obj;
    }
    var result = Object.assign({}, o); // Shallow copy
    for (var key in result) {
        if (hasKey(result, key) && hasKey(updateSource, key)) {
            result[key] = defaults(updateSource[key], result[key]);
        }
    }
    return result;
}
function createColorArray(color, arrayLength) {
    var colorValue = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](color);
    var targetArray = new Float32Array(arrayLength * 3);
    uniformArray3(arrayLength, colorValue.r, colorValue.g, colorValue.b, targetArray);
    return targetArray;
}
/**
 * Dihedral Histogram representation object
 *
 * Reperesentation consists of several parts:
 * opaqueMiddleDisc - opaque disc in the middle of the dihedral between front and back histograms
 * frontHistogram - circular histogram from the adjacent bond viewpoint
 * backHistogram - circular histogram from the distant bond viewpoint
 * histogramBinBorder - lines, which separate histogram bins
 * bondArrows - lines, which show the actual angle on the histogram disc
 *
 * @param {Structure} structure - the structure to measure angles in
 * @param {Viewer} viewer - a viewer object
 * @param {DihedralHistogramRepresentationParameters} params - Dihedral histogram representation parameters
 */
var DihedralHistogramRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function DihedralHistogramRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'dihedral-histogram';
        this.parameters = Object.assign({
            histogramsData: {
                type: 'hidden', rebuild: true
            },
            histogramBinBorderVisible: {
                type: 'boolean', default: true
            },
            scaleBinToSectorArea: {
                type: 'boolean',
                rebuild: true,
                default: false
            }
        }, this.parameters);
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) DihedralHistogramRepresentation.__proto__ = StructureRepresentation$$1;
    DihedralHistogramRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    DihedralHistogramRepresentation.prototype.constructor = DihedralHistogramRepresentation;
    DihedralHistogramRepresentation.prototype.init = function init (params) {
        var p = params || {};
        var defaultColorData = {
            histogramBinBorderColor: 'grey',
            adjacentBondArrowColor: 'black',
            distantBondArrowColor: 'magenta',
            frontHistogramColor: 'green',
            backHistogramColor: 'blue',
            opaqueMiddleDiscColor: 'white'
        };
        var colorData = createUpdatedObject(defaultColorData, p);
        Object.assign(this, colorData);
        var defaultParameters = {
            histogramsData: [],
            histogramOpacity: 1.0,
            opaqueMiddleDiscVisible: true,
            opaqueMiddleDiscOpacity: 1.0,
            histogramBinBorderVisible: true,
            histogramBinBorderWidth: 1,
            histogramBinBorderOpacity: 0.5,
            bondArrowVisible: true,
            bondArrowWidth: 2,
            bondArrowOpacity: 1.0,
            scaleBinToSectorArea: false,
        };
        var parameters = createUpdatedObject(defaultParameters, p);
        Object.assign(this, parameters);
        this.histogramsData.forEach(function (x) {
            var specificColorData = createUpdatedObject(colorData, x);
            Object.assign(x, specificColorData);
        });
        p.side = defaults(p.side, 'double');
        p.opacity = defaults(p.opacity, 0.5);
        p.radiusType = defaults(p.radiusType, 'size');
        p.radiusSize = defaults(p.radiusSize, 0.15);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    DihedralHistogramRepresentation.prototype.getHistogramBinBorderBufferParameters = function getHistogramBinBorderBufferParameters () {
        return this.getBufferParams({
            linewidth: this.histogramBinBorderWidth,
            visible: this.histogramBinBorderVisible,
            opacity: this.histogramBinBorderOpacity,
        });
    };
    DihedralHistogramRepresentation.prototype.getBondArrowsBufferParameters = function getBondArrowsBufferParameters () {
        return this.getBufferParams({
            linewidth: this.bondArrowWidth,
            visible: this.bondArrowVisible,
            opacity: this.bondArrowOpacity,
        });
    };
    DihedralHistogramRepresentation.prototype.getOpaqueMiddleDiscBufferParameters = function getOpaqueMiddleDiscBufferParameters () {
        return this.getBufferParams({
            visible: this.opaqueMiddleDiscVisible,
            opacity: this.opaqueMiddleDiscOpacity
        });
    };
    DihedralHistogramRepresentation.prototype.getHistogramBufferParameters = function getHistogramBufferParameters () {
        return this.getBufferParams({
            visible: true,
            opacity: this.histogramOpacity,
            side: "double"
        });
    };
    DihedralHistogramRepresentation.prototype.createData = function createData (sview) {
        if (!sview.atomCount || !this.histogramsData.length)
            { return; }
        this.histogramsData.forEach(function (x) { return x.atomPositions = parseNestedAtoms(sview, [x.atomQuad]); });
        var scaleData = this.scaleBinToSectorArea ? function (y) { return Math.sqrt(y); } : function (y) { return y; };
        this.histogramsData.forEach(function (x) { return x.histogram360Scaled = x.histogram360.map(scaleData); });
        function Float32Concat(arrays) {
            var lengths = arrays.map(function (x) { return x.length; });
            var result = new Float32Array(arraySum(lengths));
            var accumulatedOffset = 0;
            for (var i = 0; i < arrays.length; i++) {
                result.set(arrays[i], accumulatedOffset);
                accumulatedOffset += arrays[i].length;
            }
            return result;
        }
        function createWideLineBuffer(linesList, params) {
            return new WideLineBuffer({
                position1: Float32Concat(linesList.map(function (x) { return x.startPoints; })),
                position2: Float32Concat(linesList.map(function (x) { return x.endPoints; })),
                color: Float32Concat(linesList.map(function (x) { return x.startColors; })),
                color2: Float32Concat(linesList.map(function (x) { return x.endColors; })),
            }, params);
        }
        function createMeshBuffer(mesh, params) {
            return new MeshBuffer({
                position: Float32Concat(mesh.map(function (x) { return x.triangles; })),
                color: Float32Concat(mesh.map(function (x) { return x.triangleColors; }))
            }, params);
        }
        var dihedralDataArray = [];
        for (var i = 0; i < this.histogramsData.length; i++) {
            var dihedralData = undefined;
            var currentHistogramData = this.histogramsData[i];
            var currentHistogram360 = currentHistogramData.histogram360;
            if (currentHistogram360.length >= 3) {
                dihedralData = calculateDihedralHistogram(currentHistogramData);
            }
            if (typeof dihedralData === "undefined")
                { continue; }
            dihedralDataArray.push(dihedralData);
        }
        this.frontHistogramBinBordersBuffer = createWideLineBuffer(dihedralDataArray.map(function (x) { return x.frontHistogramBinBorders; }), this.getHistogramBinBorderBufferParameters());
        this.backHistogramBinBordersBuffer = createWideLineBuffer(dihedralDataArray.map(function (x) { return x.backHistogramBinBorders; }), this.getHistogramBinBorderBufferParameters());
        this.adjacentBondArrowsBuffer = createWideLineBuffer(dihedralDataArray.map(function (x) { return x.adjacentBondArrows; }), this.getBondArrowsBufferParameters());
        this.distantBondArrowsBuffer = createWideLineBuffer(dihedralDataArray.map(function (x) { return x.distantBondArrows; }), this.getBondArrowsBufferParameters());
        this.opaqueMiddleDiscBuffer = createMeshBuffer(dihedralDataArray.map(function (x) { return x.opaqueMiddleDisc; }), this.getOpaqueMiddleDiscBufferParameters());
        this.frontHistogramBuffer = createMeshBuffer(dihedralDataArray.map(function (x) { return x.frontHistogram; }), this.getHistogramBufferParameters());
        this.backHistogramBuffer = createMeshBuffer(dihedralDataArray.map(function (x) { return x.backHistogram; }), this.getHistogramBufferParameters());
        return {
            bufferList: [].concat(this.frontHistogramBinBordersBuffer, this.backHistogramBinBordersBuffer, this.adjacentBondArrowsBuffer, this.distantBondArrowsBuffer, this.opaqueMiddleDiscBuffer, this.frontHistogramBuffer, this.backHistogramBuffer)
        };
    };
    DihedralHistogramRepresentation.prototype.setParameters = function setParameters (params) {
        var rebuild = false;
        var what = {};
        StructureRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        if (params && (params.histogramBinBorderVisible !== undefined)) {
            this.setVisibility(this.visible);
        }
        return this;
    };
    DihedralHistogramRepresentation.prototype.setVisibility = function setVisibility (value, noRenderRequest) {
        StructureRepresentation$$1.prototype.setVisibility.call(this, value, true);
        if (this.frontHistogramBinBordersBuffer) {
            this.frontHistogramBinBordersBuffer.setVisibility(this.histogramBinBorderVisible);
        }
        if (this.backHistogramBinBordersBuffer) {
            this.backHistogramBinBordersBuffer.setVisibility(this.histogramBinBorderVisible);
        }
        if (!noRenderRequest)
            { this.viewer.requestRender(); }
        return this;
    };

    return DihedralHistogramRepresentation;
}(StructureRepresentation));
/**
 * Calculates the data required to create {Buffer} objects for one histogram, given positions
 * @param  Float32Array positionOfDihedralAtoms 3*4 array of coordinates
 * @param  NumberArray histogram array of coordinates
 * @return Arrays for building buffers
 */
function calculateDihedralHistogram(histogramData) {
    var positionOfDihedralAtoms = histogramData.atomPositions;
    var histogram = histogramData.histogram360Scaled;
    var totalSectorTrianglesInOpaqueMiddleDisc = histogram.length <= 180 ? 360 : histogram.length * 2;
    var frontAndBack = 2;
    var opaqueMiddleDisc = {
        triangles: new Float32Array(totalSectorTrianglesInOpaqueMiddleDisc * pointsInTriangle * pointLength),
        triangleColors: createColorArray(histogramData.opaqueMiddleDiscColor, totalSectorTrianglesInOpaqueMiddleDisc * pointsInTriangle)
    };
    var frontHistogram = {
        triangles: new Float32Array(histogram.length * pointsInTriangle * pointLength),
        triangleColors: createColorArray(histogramData.frontHistogramColor, histogram.length * pointsInTriangle)
    };
    var backHistogram = {
        triangles: new Float32Array(histogram.length * pointsInTriangle * pointLength),
        triangleColors: createColorArray(histogramData.backHistogramColor, histogram.length * pointsInTriangle)
    };
    var frontHistogramBinBorders = {
        startPoints: new Float32Array(histogram.length * pointLength),
        endPoints: new Float32Array(histogram.length * pointLength),
        startColors: createColorArray(histogramData.histogramBinBorderColor, histogram.length),
        endColors: createColorArray(histogramData.histogramBinBorderColor, histogram.length)
    };
    var backHistogramBinBorders = {
        startPoints: new Float32Array(histogram.length * pointLength),
        endPoints: new Float32Array(histogram.length * pointLength),
        startColors: createColorArray(histogramData.histogramBinBorderColor, histogram.length),
        endColors: createColorArray(histogramData.histogramBinBorderColor, histogram.length)
    };
    var adjacentBondArrows = {
        startPoints: new Float32Array(frontAndBack * pointLength),
        endPoints: new Float32Array(frontAndBack * pointLength),
        startColors: createColorArray(histogramData.adjacentBondArrowColor, histogram.length),
        endColors: createColorArray(histogramData.adjacentBondArrowColor, histogram.length)
    };
    var distantBondArrows = {
        startPoints: new Float32Array(frontAndBack * pointLength),
        endPoints: new Float32Array(frontAndBack * pointLength),
        startColors: createColorArray(histogramData.distantBondArrowColor, histogram.length),
        endColors: createColorArray(histogramData.distantBondArrowColor, histogram.length)
    };
    var p1 = v3new();
    var p2 = v3new();
    var p3 = v3new();
    var p4 = v3new();
    var v21 = v3new();
    var v23 = v3new();
    var v32 = v3new();
    var v34 = v3new();
    var mid = v3new();
    var inPlane1 = v3new();
    var inPlane2 = v3new();
    var cross1 = v3new();
    var cross2 = v3new();
    var arcPoint = v3new();
    var tmp = v3new();
    var tmp2 = v3new();
    // Set Atom Coordinates
    var dihedralAtomVectors = [p1, p2, p3, p4];
    for (var i = 0; i < dihedralAtomVectors.length; i++) {
        v3fromArray(dihedralAtomVectors[i], positionOfDihedralAtoms, i * pointLength);
    }
    // Vectors between points
    v3sub(v21, p1, p2);
    v3sub(v23, p3, p2);
    v3sub(v34, p4, p3);
    if (v3length(v23) === 0.0) {
        return; // Can't define axis
    }
    v3multiplyScalar(tmp, v23, 0.5);
    v3add(mid, p2, tmp);
    v3normalize(v21, v21);
    v3normalize(v23, v23);
    v3normalize(v34, v34);
    v3negate(v32, v23);
    // Calculate vectors perp to v23 (lying in plane (1,2,3) and (2,3,4))
    v3multiplyScalar(tmp, v32, v3dot(v32, v21));
    v3sub(inPlane1, v21, tmp);
    v3multiplyScalar(tmp, v23, v3dot(v23, v34));
    v3sub(inPlane2, v34, tmp);
    if (v3length(inPlane1) === 0.0 || v3length(inPlane2) === 0.0) {
        return; // Indeterminate angle
    }
    v3normalize(inPlane1, inPlane1);
    v3normalize(inPlane2, inPlane2);
    // Can use acos as normalized and non-zero
    var absAngle = Math.acos(v3dot(inPlane1, inPlane2));
    v3cross(cross1, v32, inPlane1);
    v3cross(cross2, v23, inPlane2);
    v3normalize(cross1, cross1);
    v3normalize(cross2, cross2);
    var angle = absAngle;
    if (v3dot(cross1, inPlane2) < 0.0) {
        angle = -absAngle;
    }
    v3add(arcPoint, mid, inPlane1);
    // Calculate necessary constants
    var maxHist = Math.max.apply(null, histogram);
    var histBinAngleStep = (Math.PI * 2) / histogram.length;
    function setHistogramBinCoordinates(out, ind, zeroDegreeVector, crossVector, histBinAngleStep) {
        var startOffset = ind * pointsInTriangle * pointLength;
        v3toArray(mid, out, startOffset);
        var scalingFactor = Number(histogram[ind]) / maxHist;
        v3multiplyScalar(tmp, zeroDegreeVector, scalingFactor);
        v3multiplyScalar(tmp2, crossVector, scalingFactor);
        calcArcPoint(arcPoint, mid, tmp, tmp2, ind * histBinAngleStep);
        v3toArray(arcPoint, out, startOffset + 1 * pointLength);
        calcArcPoint(arcPoint, mid, tmp, tmp2, (ind + 1) * histBinAngleStep);
        v3toArray(arcPoint, out, startOffset + 2 * pointLength);
    }
    function setOneSideHistogram(discHistogram, binBorders, ind, zeroDegreeVector, crossVector) {
        // Set Bond Arrows
        copyArray(mid, adjacentBondArrows.startPoints, 0, ind * pointLength, mid.length);
        calcArcPoint(tmp, mid, zeroDegreeVector, crossVector, 0 + histBinAngleStep * 0);
        copyArray(tmp, adjacentBondArrows.endPoints, 0, ind * pointLength, mid.length);
        copyArray(mid, distantBondArrows.startPoints, 0, ind * pointLength, mid.length);
        calcArcPoint(tmp, mid, zeroDegreeVector, crossVector, angle);
        copyArray(tmp, distantBondArrows.endPoints, 0, ind * pointLength, mid.length);
        // Set Histogram Bin Borders
        for (var i = 0; i < histogram.length; i++) {
            copyArray(mid, binBorders.startPoints, 0, i * 3, mid.length);
            calcArcPoint(tmp, mid, zeroDegreeVector, crossVector, 0 + histBinAngleStep * i);
            copyArray(tmp, binBorders.endPoints, 0, i * 3, tmp.length);
        }
        // Set Histogram Bins
        for (var sectionIndex = 0; sectionIndex < histogram.length; sectionIndex++) {
            setHistogramBinCoordinates(discHistogram.triangles, sectionIndex, zeroDegreeVector, crossVector, histBinAngleStep);
        }
    }
    // Opaque disc
    var opaqueCircleSectorAngleStep = Math.PI * 2 / totalSectorTrianglesInOpaqueMiddleDisc;
    for (var sectionIndex = 0; sectionIndex < totalSectorTrianglesInOpaqueMiddleDisc; sectionIndex++) {
        var startOffset = sectionIndex * pointsInTriangle * pointLength;
        v3toArray(mid, opaqueMiddleDisc.triangles, startOffset);
        calcArcPoint(arcPoint, mid, inPlane1, cross1, sectionIndex * opaqueCircleSectorAngleStep);
        v3toArray(arcPoint, opaqueMiddleDisc.triangles, startOffset + 1 * pointLength);
        calcArcPoint(arcPoint, mid, inPlane1, cross1, (sectionIndex + 1) * opaqueCircleSectorAngleStep);
        v3toArray(arcPoint, opaqueMiddleDisc.triangles, startOffset + 2 * pointLength);
    }
    // Front Histogram
    var distanceToOpaqueDisc = 0.01;
    v3multiplyScalar(tmp, v23, -distanceToOpaqueDisc); // Get a vector to move "mid" just a bit from opaque disc
    v3add(mid, mid, tmp);
    setOneSideHistogram(frontHistogram, frontHistogramBinBorders, 0, inPlane1, cross1);
    // Back Histogram
    v3multiplyScalar(tmp, v23, 2 * distanceToOpaqueDisc); // Get a vector to move "mid" back and plus just a bit from opaque disc the other way
    v3add(mid, mid, tmp);
    setOneSideHistogram(backHistogram, backHistogramBinBorders, 1, inPlane2, cross2);
    return {
        opaqueMiddleDisc: opaqueMiddleDisc,
        frontHistogram: frontHistogram,
        backHistogram: backHistogram,
        frontHistogramBinBorders: frontHistogramBinBorders,
        backHistogramBinBorders: backHistogramBinBorders,
        adjacentBondArrows: adjacentBondArrows,
        distantBondArrows: distantBondArrows
    };
}
RepresentationRegistry.add('dihedral-histogram', DihedralHistogramRepresentation);

/**
 * @file Distance Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow <fred.ludlow@gmail.com>
 * @private
 */
/**
 * Distance representation
 */
var DistanceRepresentation = /*@__PURE__*/(function (MeasurementRepresentation$$1) {
    function DistanceRepresentation(structure, viewer, params) {
        MeasurementRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'distance';
        this.parameters = Object.assign({
            radialSegments: true,
            openEnded: true,
            disableImpostor: true,
            labelUnit: {
                type: 'select',
                rebuild: true,
                options: { '': '', angstrom: 'angstrom', nm: 'nm' }
            },
            useCylinder: {
                type: 'boolean', rebuild: true
            },
            atomPair: {
                type: 'hidden', rebuild: true
            }
        }, this.parameters);
        this.init(params);
    }

    if ( MeasurementRepresentation$$1 ) DistanceRepresentation.__proto__ = MeasurementRepresentation$$1;
    DistanceRepresentation.prototype = Object.create( MeasurementRepresentation$$1 && MeasurementRepresentation$$1.prototype );
    DistanceRepresentation.prototype.constructor = DistanceRepresentation;
    DistanceRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.linewidth = defaults(p.linewidth, 5.0);
        p.radiusType = defaults(p.radiusType, 'size');
        p.radiusSize = defaults(p.radiusSize, 0.2);
        this.labelUnit = defaults(p.labelUnit, '');
        this.useCylinder = defaults(p.useCylinder, false);
        this.atomPair = defaults(p.atomPair, []);
        MeasurementRepresentation$$1.prototype.init.call(this, p);
    };
    DistanceRepresentation.prototype.getDistanceData = function getDistanceData (sview, atomPair) {
        var this$1 = this;

        var n = atomPair.length;
        var text = new Array(n);
        var position = new Float32Array(n * 3);
        var sele1 = new Selection();
        var sele2 = new Selection();
        var bondStore = new BondStore();
        var ap1 = sview.getAtomProxy();
        var ap2 = sview.getAtomProxy();
        var j = 0; // Skipped pairs
        var selected = sview.getAtomSet();
        atomPair.forEach(function (pair, i) {
            var v1 = pair[0];
            var v2 = pair[1];
            if (typeof (v1) === 'number' && Number.isInteger(v1) && typeof (v2) === 'number' && Number.isInteger(v2)) {
                if (selected.get(v1) && selected.get(v2)) {
                    ap1.index = v1;
                    ap2.index = v2;
                }
                else {
                    j += 1;
                    return;
                }
            }
            else {
                sele1.setString(v1);
                sele2.setString(v2);
                var atomIndices1 = sview.getAtomIndices(sele1);
                var atomIndices2 = sview.getAtomIndices(sele2);
                if (atomIndices1.length && atomIndices2.length) {
                    ap1.index = atomIndices1[0];
                    ap2.index = atomIndices2[0];
                }
                else {
                    j += 1;
                    return;
                }
            }
            bondStore.addBond(ap1, ap2, 1);
            i -= j;
            var d = ap1.distanceTo(ap2);
            switch (this$1.labelUnit) {
                case 'angstrom':
                    text[i] = d.toFixed(2) + ' ' + String.fromCharCode(0x212B);
                    break;
                case 'nm':
                    text[i] = (d / 10).toFixed(2) + ' nm';
                    break;
                default:
                    text[i] = d.toFixed(2);
                    break;
            }
            var i3 = i * 3;
            position[i3 + 0] = (ap1.x + ap2.x) / 2;
            position[i3 + 1] = (ap1.y + ap2.y) / 2;
            position[i3 + 2] = (ap1.z + ap2.z) / 2;
        });
        if (j > 0) {
            n -= j;
            position = position.subarray(0, n * 3);
        }
        var bondSet = new BitArray(bondStore.count, true);
        return {
            text: text,
            position: position,
            bondSet: bondSet,
            bondStore: bondStore
        };
    };
    DistanceRepresentation.prototype.getBondData = function getBondData (sview, what, params) {
        var bondData = sview.getBondData(this.getBondParams(what, params));
        if (bondData.picking) {
            bondData.picking = new DistancePicker(bondData.picking.array, bondData.picking.structure, params.bondStore);
        }
        return bondData;
    };
    DistanceRepresentation.prototype.createData = function createData (sview) {
        if (!sview.atomCount || !this.atomPair.length)
            { return; }
        var n = this.atomPair.length;
        var c = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.labelColor);
        var distanceData = this.getDistanceData(sview, this.atomPair);
        this.textBuffer = new TextBuffer({
            position: distanceData.position,
            size: uniformArray(n, this.labelSize),
            color: uniformArray3(n, c.r, c.g, c.b),
            text: distanceData.text
        }, this.getLabelBufferParams());
        var bondParams = {
            bondSet: distanceData.bondSet,
            bondStore: distanceData.bondStore
        };
        var bondData = this.getBondData(sview, { position: true, color: true, picking: true, radius: this.useCylinder }, bondParams);
        if (this.useCylinder) {
            this.distanceBuffer = new CylinderBuffer(bondData, this.getBufferParams({
                openEnded: this.openEnded,
                radialSegments: this.radialSegments,
                disableImpostor: this.disableImpostor,
                dullInterior: true
            }));
        }
        else {
            this.distanceBuffer = new WideLineBuffer(getFixedLengthDashData(bondData), this.getBufferParams({
                linewidth: this.linewidth,
                visible: this.lineVisible,
                opacity: this.lineOpacity
            }));
        }
        return {
            bondSet: distanceData.bondSet,
            bondStore: distanceData.bondStore,
            position: distanceData.position,
            bufferList: [this.textBuffer, this.distanceBuffer]
        };
    };
    DistanceRepresentation.prototype.updateData = function updateData (what, data) {
        MeasurementRepresentation$$1.prototype.updateData.call(this, what, data);
        var bondParams = {
            bondSet: data.bondSet,
            bondStore: data.bondStore
        };
        var bondData = this.getBondData(data.sview, what, bondParams);
        var distanceData = {};
        if (!what || what.color) {
            Object.assign(distanceData, {
                color: bondData.color,
                color2: bondData.color2
            });
        }
        if (!what || what.radius) {
            Object.assign(distanceData, { radius: bondData.radius });
        }
        this.distanceBuffer.setAttributes(distanceData);
    };
    DistanceRepresentation.prototype.setParameters = function setParameters (params) {
        var rebuild = false;
        var what = {};
        MeasurementRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        if (!this.useCylinder) {
            if (params && params.lineOpacity) {
                this.distanceBuffer.setParameters({ opacity: params.lineOpacity });
            }
            if (params && params.opacity !== undefined) {
                this.distanceBuffer.setParameters({ opacity: this.lineOpacity });
            }
            if (params && params.linewidth) {
                this.distanceBuffer.setParameters({ linewidth: params.linewidth });
            }
        }
        return this;
    };

    return DistanceRepresentation;
}(MeasurementRepresentation));
RepresentationRegistry.add('distance', DistanceRepresentation);

/**
 * @file Vector Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getSize(data) {
    var n = data.position.length / 3;
    return n * 2 * 3;
}
var VectorBufferDefaultParameters = Object.assign({
    scale: 1,
    color: 'grey'
}, BufferDefaultParameters);
/**
 * Vector buffer. Draws vectors as lines.
 */
var VectorBuffer = /*@__PURE__*/(function (Buffer$$1) {
    function VectorBuffer(data, params) {
        if ( params === void 0 ) params = {};

        Buffer$$1.call(this, {
            position: new Float32Array(getSize(data)),
            color: new Float32Array(getSize(data))
        }, params);
        this.isLine = true;
        this.vertexShader = 'Line.vert';
        this.fragmentShader = 'Line.frag';
        var color = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](this.parameters.color);
        var attributes = this.geometry.attributes; // TODO
        uniformArray3(getSize(data) / 3, color.r, color.g, color.b, attributes.color.array);
        this.setAttributes(data);
    }

    if ( Buffer$$1 ) VectorBuffer.__proto__ = Buffer$$1;
    VectorBuffer.prototype = Object.create( Buffer$$1 && Buffer$$1.prototype );
    VectorBuffer.prototype.constructor = VectorBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return VectorBufferDefaultParameters; };
    VectorBuffer.prototype.setAttributes = function setAttributes (data) {
        if ( data === void 0 ) data = {};

        var attributes = this.geometry.attributes; // TODO
        var position, vector;
        var aPosition;
        if (data.position && data.vector) {
            position = data.position;
            vector = data.vector;
            aPosition = attributes.position.array;
            attributes.position.needsUpdate = true;
        }
        var n = this.size / 2;
        var scale$$1 = this.parameters.scale;
        if (position && vector) {
            for (var v = 0; v < n; v++) {
                var i = v * 2 * 3;
                var j = v * 3;
                aPosition[i + 0] = position[j + 0];
                aPosition[i + 1] = position[j + 1];
                aPosition[i + 2] = position[j + 2];
                aPosition[i + 3] = position[j + 0] + vector[j + 0] * scale$$1;
                aPosition[i + 4] = position[j + 1] + vector[j + 1] * scale$$1;
                aPosition[i + 5] = position[j + 2] + vector[j + 2] * scale$$1;
            }
        }
    };

    Object.defineProperties( VectorBuffer.prototype, prototypeAccessors );

    return VectorBuffer;
}(Buffer));

/**
 * @file Helixorient Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Helixorient Representation
 */
var HelixorientRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function HelixorientRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'helixorient';
        this.parameters = Object.assign({
            sphereDetail: true,
            disableImpostor: true
        }, this.parameters);
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) HelixorientRepresentation.__proto__ = StructureRepresentation$$1;
    HelixorientRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    HelixorientRepresentation.prototype.constructor = HelixorientRepresentation;
    HelixorientRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.colorScheme = defaults(p.colorScheme, 'sstruc');
        p.radiusType = defaults(p.radiusType, 'size');
        p.radiusSize = defaults(p.radiusSize, 0.15);
        p.radiusScale = defaults(p.radiusScale, 1.0);
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    HelixorientRepresentation.prototype.createData = function createData (sview) {
        var this$1 = this;

        var bufferList = [];
        var polymerList = [];
        this.structure.eachPolymer(function (polymer) {
            if (polymer.residueCount < 4)
                { return; }
            polymerList.push(polymer);
            var helixorient = new Helixorient(polymer);
            var position = helixorient.getPosition();
            var color = helixorient.getColor(this$1.getColorParams());
            var size = helixorient.getSize(this$1.getRadiusParams());
            var picking = helixorient.getPicking();
            bufferList.push(new SphereBuffer({
                position: position.center,
                color: color.color,
                radius: size.size,
                picking: picking.picking
            }, this$1.getBufferParams({
                sphereDetail: this$1.sphereDetail,
                disableImpostor: this$1.disableImpostor,
                dullInterior: true
            })), new VectorBuffer({
                position: position.center,
                vector: position.axis
            }, this$1.getBufferParams({
                color: 'skyblue',
                scale: 1
            })), new VectorBuffer({
                position: position.center,
                vector: position.resdir
            }, this$1.getBufferParams({
                color: 'lightgreen',
                scale: 1
            })));
        }, sview.getSelection());
        return {
            bufferList: bufferList,
            polymerList: polymerList
        };
    };
    HelixorientRepresentation.prototype.updateData = function updateData (what, data) {
        if (Debug)
            { Log.time(this.type + ' repr update'); }
        what = what || {};
        for (var i = 0, il = data.polymerList.length; i < il; ++i) {
            var j = i * 3;
            var bufferData = {};
            var polymer = data.polymerList[i];
            var helixorient = new Helixorient(polymer);
            if (what.position) {
                var position = helixorient.getPosition();
                Object.assign(bufferData, { position: position.center });
                data.bufferList[j + 1].setAttributes({
                    'position': position.center,
                    'vector': position.axis
                });
                data.bufferList[j + 2].setAttributes({
                    'position': position.center,
                    'vector': position.resdir
                });
            }
            data.bufferList[j].setAttributes(bufferData);
        }
        if (Debug)
            { Log.timeEnd(this.type + ' repr update'); }
    };

    return HelixorientRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('helixorient', HelixorientRepresentation);

/**
 * @file Licorice Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Licorice representation object ({@link BallAndStickRepresentation} with `aspectRatio` fixed at 1.0)
 */
var LicoriceRepresentation = /*@__PURE__*/(function (BallAndStickRepresentation$$1) {
    function LicoriceRepresentation(structure, viewer, params) {
        BallAndStickRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'licorice';
        this.parameters = Object.assign({}, this.parameters, { aspectRatio: null });
    }

    if ( BallAndStickRepresentation$$1 ) LicoriceRepresentation.__proto__ = BallAndStickRepresentation$$1;
    LicoriceRepresentation.prototype = Object.create( BallAndStickRepresentation$$1 && BallAndStickRepresentation$$1.prototype );
    LicoriceRepresentation.prototype.constructor = LicoriceRepresentation;
    LicoriceRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.aspectRatio = 1.0;
        BallAndStickRepresentation$$1.prototype.init.call(this, p);
    };

    return LicoriceRepresentation;
}(BallAndStickRepresentation));
RepresentationRegistry.add('licorice', LicoriceRepresentation);

ShaderRegistry.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}");

ShaderRegistry.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}");

/**
 * @file Mapped Box Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var mapping$2 = new Float32Array([
    -1.0, -1.0, -1.0,
    1.0, -1.0, -1.0,
    1.0, -1.0, 1.0,
    -1.0, -1.0, 1.0,
    -1.0, 1.0, -1.0,
    1.0, 1.0, -1.0,
    1.0, 1.0, 1.0,
    -1.0, 1.0, 1.0
]);
var mappingIndices$2 = 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
]);
/**
 * Mapped Box buffer. Draws boxes. Used to render general imposters.
 * @interface
 */
var MappedBoxBuffer = /*@__PURE__*/(function (MappedBuffer$$1) {
    function MappedBoxBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MappedBuffer$$1.call(this, 'v3', data, params);
    }

    if ( MappedBuffer$$1 ) MappedBoxBuffer.__proto__ = MappedBuffer$$1;
    MappedBoxBuffer.prototype = Object.create( MappedBuffer$$1 && MappedBuffer$$1.prototype );
    MappedBoxBuffer.prototype.constructor = MappedBoxBuffer;

    var prototypeAccessors = { mapping: { configurable: true },mappingIndices: { configurable: true },mappingIndicesSize: { configurable: true },mappingSize: { configurable: true },mappingItemSize: { configurable: true } };
    prototypeAccessors.mapping.get = function () { return mapping$2; };
    prototypeAccessors.mappingIndices.get = function () { return mappingIndices$2; };
    prototypeAccessors.mappingIndicesSize.get = function () { return 36; };
    prototypeAccessors.mappingSize.get = function () { return 8; };
    prototypeAccessors.mappingItemSize.get = function () { return 3; };

    Object.defineProperties( MappedBoxBuffer.prototype, prototypeAccessors );

    return MappedBoxBuffer;
}(MappedBuffer));

/**
 * @file Hyperball Stick Impostor Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var HyperballStickImpostorBufferDefaultParameters = Object.assign({
    shrink: 0.14
}, BufferDefaultParameters);
var HyperballStickImpostorBufferParameterTypes = Object.assign({
    shrink: { uniform: true }
}, BufferParameterTypes);
/**
 * Hyperball stick impostor buffer.
 *
 * @example
 * var hyperballStickImpostorBuffer = new HyperballStickImpostorBuffer({
 *   position1: new Float32Array([ 0, 0, 0 ]),
 *   position2: new Float32Array([ 2, 2, 2 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   color2: new Float32Array([ 0, 1, 0 ]),
 *   radius: new Float32Array([ 1 ]),
 *   radius2: new Float32Array([ 2 ])
 * });
 */
var HyperballStickImpostorBuffer = /*@__PURE__*/(function (MappedBoxBuffer$$1) {
    function HyperballStickImpostorBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MappedBoxBuffer$$1.call(this, data, params);
        this.parameterTypes = HyperballStickImpostorBufferParameterTypes;
        this.isImpostor = true;
        this.vertexShader = 'HyperballStickImpostor.vert';
        this.fragmentShader = 'HyperballStickImpostor.frag';
        this.addUniforms({
            'modelViewProjectionMatrix': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]() },
            'modelViewProjectionMatrixInverse': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]() },
            'modelViewMatrixInverseTranspose': { value: new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]() },
            '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(data);
        this.makeMapping();
    }

    if ( MappedBoxBuffer$$1 ) HyperballStickImpostorBuffer.__proto__ = MappedBoxBuffer$$1;
    HyperballStickImpostorBuffer.prototype = Object.create( MappedBoxBuffer$$1 && MappedBoxBuffer$$1.prototype );
    HyperballStickImpostorBuffer.prototype.constructor = HyperballStickImpostorBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return HyperballStickImpostorBufferDefaultParameters; };

    Object.defineProperties( HyperballStickImpostorBuffer.prototype, prototypeAccessors );

    return HyperballStickImpostorBuffer;
}(MappedBoxBuffer));

/**
 * @file Hyperball Stick Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var HyperballStickBufferDefaultParameters = Object.assign({
    disableImpostor: false
}, CylinderGeometryBufferDefaultParameters, HyperballStickImpostorBufferDefaultParameters);
/**
 * Hyperball stick buffer. Depending on the value {@link ExtensionFragDepth} and
 * `params.disableImpostor` the constructor returns either a
 * {@link CylinderGeometryBuffer} or a {@link HyperballStickImpostorBuffer}
 * @implements {Buffer}
 *
 * @example
 * var hyperballStickBuffer = new HyperballStickBuffer({
 *   position1: new Float32Array([ 0, 0, 0 ]),
 *   position2: new Float32Array([ 2, 2, 2 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   color2: new Float32Array([ 0, 1, 0 ]),
 *   radius: new Float32Array([ 1 ]),
 *   radius2: new Float32Array([ 2 ])
 * });
 */
var HyperballStickBuffer = function HyperballStickBuffer(data, params) {
    if ( params === void 0 ) params = {};

    if (!ExtensionFragDepth || (params && params.disableImpostor)) {
        data.radius = calculateMinArray(data.radius, data.radius2);
        return new CylinderGeometryBuffer(data, params);
    }
    else {
        return new HyperballStickImpostorBuffer(data, params);
    }
};

/**
 * @file Hyperball Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Hyperball Representation
 */
var HyperballRepresentation = /*@__PURE__*/(function (LicoriceRepresentation$$1) {
    function HyperballRepresentation(structure, viewer, params) {
        LicoriceRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'hyperball';
        this.parameters = Object.assign({
            shrink: {
                type: 'number', precision: 3, max: 1.0, min: 0.001, buffer: true
            }
        }, this.parameters, {
            multipleBond: null,
            bondSpacing: null
        });
    }

    if ( LicoriceRepresentation$$1 ) HyperballRepresentation.__proto__ = LicoriceRepresentation$$1;
    HyperballRepresentation.prototype = Object.create( LicoriceRepresentation$$1 && LicoriceRepresentation$$1.prototype );
    HyperballRepresentation.prototype.constructor = HyperballRepresentation;
    HyperballRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.radiusScale = defaults(p.radiusScale, 0.2);
        p.radiusType = defaults(p.radiusType, 'vdw');
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        this.shrink = defaults(p.shrink, 0.12);
        LicoriceRepresentation$$1.prototype.init.call(this, p);
    };
    HyperballRepresentation.prototype.getBondParams = function getBondParams (what, params) {
        if (!what || what.radius) {
            params = Object.assign({ radius2: true }, params);
        }
        return LicoriceRepresentation$$1.prototype.getBondParams.call(this, what, params);
    };
    HyperballRepresentation.prototype.createData = function createData (sview) {
        var sphereBuffer = new SphereBuffer(sview.getAtomData(this.getAtomParams()), this.getBufferParams({
            sphereDetail: this.sphereDetail,
            disableImpostor: this.disableImpostor,
            dullInterior: true
        }));
        this.__center = new Float32Array(sview.bondCount * 3);
        var stickBuffer = new HyperballStickBuffer(sview.getBondData(this.getBondParams()), this.getBufferParams({
            shrink: this.shrink,
            radialSegments: this.radialSegments,
            disableImpostor: this.disableImpostor,
            dullInterior: true
        }));
        return {
            bufferList: [sphereBuffer, stickBuffer]
        };
    };
    HyperballRepresentation.prototype.updateData = function updateData (what, data) {
        var atomData = data.sview.getAtomData(this.getAtomParams());
        var bondData = data.sview.getBondData(this.getBondParams());
        var sphereData = {};
        var stickData = {};
        if (!what || what.position) {
            Object.assign(sphereData, { position: atomData.position });
            var from = bondData.position1;
            var to = bondData.position2;
            Object.assign(stickData, {
                position: calculateCenterArray(from, to, this.__center),
                position1: from,
                position2: to
            });
        }
        if (!what || what.color) {
            Object.assign(sphereData, { color: atomData.color });
            Object.assign(stickData, {
                color: bondData.color,
                color2: bondData.color2
            });
        }
        if (!what || what.radius) {
            Object.assign(sphereData, { radius: atomData.radius });
            Object.assign(stickData, {
                radius: bondData.radius,
                radius2: bondData.radius2
            });
        }
        data.bufferList[0].setAttributes(sphereData);
        data.bufferList[1].setAttributes(stickData);
    };

    return HyperballRepresentation;
}(LicoriceRepresentation));
RepresentationRegistry.add('hyperball', HyperballRepresentation);

/**
 * @file Label Factory
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var LabelFactoryTypes = {
    '': '',
    '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'
};
var LabelFactory = function LabelFactory(type, text, format) {
    if ( text === void 0 ) text = {};
    if ( format === void 0 ) format = '';

    this.type = type;
    this.text = text;
    this.format = format;
    this.errorLogged = false;
};
LabelFactory.prototype.atomLabel = function atomLabel (a) {
    var type = this.type;
    var l;
    switch (type) {
        case 'atomname':
            l = a.atomname;
            break;
        case 'atomindex':
            l = "" + (a.index);
            break;
        case 'occupancy':
            l = a.occupancy.toFixed(2);
            break;
        case 'bfactor':
            l = a.bfactor.toFixed(2);
            break;
        case 'serial':
            l = "" + (a.serial);
            break;
        case 'element':
            l = a.element;
            break;
        case 'atom':
            l = (a.atomname) + "|" + (a.index);
            break;
        case 'resname':
            l = a.resname;
            break;
        case 'resno':
            l = "" + (a.resno);
            break;
        case 'res':
            l = "" + ((AA1[a.resname.toUpperCase()] || a.resname)) + (a.resno);
            break;
        case 'residue':
            var aa1 = AA1[a.resname.toUpperCase()];
            if (aa1 && !a.inscode) {
                l = "" + aa1 + (a.resno);
            }
            else {
                l = "[" + (a.resname) + "]" + (a.resno) + (a.inscode);
            }
            break;
        case 'text':
            l = this.text[a.index];
            break;
        case 'format':
            try {
                l = Object(__WEBPACK_IMPORTED_MODULE_3_sprintf_js__["sprintf"])(this.format, a);
            }
            catch (e) {
                if (!this.errorLogged) {
                    this.errorLogged = true;
                    console.log(e.message);
                }
            }
            break;
        // case "qualified":
        default:
            l = a.qualifiedName();
            break;
    }
    return l === undefined ? '' : l;
};
LabelFactory.types = LabelFactoryTypes;

/**
 * @file Label Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Label representation
 */
var LabelRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function LabelRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'label';
        this.parameters = Object.assign({
            labelType: {
                type: 'select', options: LabelFactory.types, rebuild: true
            },
            labelText: {
                type: 'hidden', rebuild: true
            },
            labelFormat: {
                type: 'text', rebuild: true
            },
            labelGrouping: {
                type: 'select',
                options: {
                    'atom': 'atom',
                    'residue': 'residue'
                },
                rebuild: true
            },
            fontFamily: {
                type: 'select',
                options: {
                    'sans-serif': 'sans-serif',
                    'monospace': 'monospace',
                    'serif': 'serif'
                },
                buffer: true
            },
            fontStyle: {
                type: 'select',
                options: {
                    'normal': 'normal',
                    'italic': 'italic'
                },
                buffer: true
            },
            fontWeight: {
                type: 'select',
                options: {
                    'normal': 'normal',
                    'bold': 'bold'
                },
                buffer: true
            },
            xOffset: {
                type: 'number', precision: 1, max: 20, min: -20, buffer: true
            },
            yOffset: {
                type: 'number', precision: 1, max: 20, min: -20, buffer: true
            },
            zOffset: {
                type: 'number', precision: 1, max: 20, min: -20, buffer: true
            },
            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: true
            },
            showBorder: {
                type: 'boolean', buffer: true
            },
            borderColor: {
                type: 'color', buffer: true
            },
            borderWidth: {
                type: 'number', precision: 2, max: 0.3, min: 0, buffer: true
            },
            showBackground: {
                type: 'boolean', rebuild: true
            },
            backgroundColor: {
                type: 'color', buffer: true
            },
            backgroundMargin: {
                type: 'number', precision: 2, max: 2, min: 0, rebuild: true
            },
            backgroundOpacity: {
                type: 'range', step: 0.01, max: 1, min: 0, buffer: true
            },
            fixedSize: {
                type: 'boolean', buffer: true
            }
        }, this.parameters, {
            side: null,
            flatShaded: null,
            wireframe: null,
            linewidth: null,
            roughness: null,
            metalness: null,
            diffuse: null
        });
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) LabelRepresentation.__proto__ = StructureRepresentation$$1;
    LabelRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    LabelRepresentation.prototype.constructor = LabelRepresentation;
    LabelRepresentation.prototype.init = function init (params) {
        var p = params || {};
        this.labelType = defaults(p.labelType, 'res');
        this.labelText = defaults(p.labelText, {});
        this.labelFormat = defaults(p.labelFormat, '');
        this.labelGrouping = defaults(p.labelGrouping, 'atom');
        this.fontFamily = defaults(p.fontFamily, 'sans-serif');
        this.fontStyle = defaults(p.fontStyle, 'normal');
        this.fontWeight = defaults(p.fontWeight, 'bold');
        this.xOffset = defaults(p.xOffset, 0.0);
        this.yOffset = defaults(p.yOffset, 0.0);
        this.zOffset = defaults(p.zOffset, 0.5);
        this.attachment = defaults(p.attachment, 'bottom-left');
        this.showBorder = defaults(p.showBorder, false);
        this.borderColor = defaults(p.borderColor, 'lightgrey');
        this.borderWidth = defaults(p.borderWidth, 0.15);
        this.showBackground = defaults(p.showBackground, false);
        this.backgroundColor = defaults(p.backgroundColor, 'lightgrey');
        this.backgroundMargin = defaults(p.backgroundMargin, 0.5);
        this.backgroundOpacity = defaults(p.backgroundOpacity, 1.0);
        this.fixedSize = defaults(p.fixedSize, false);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    LabelRepresentation.prototype.getTextData = function getTextData (sview, what) {
        var p = this.getAtomParams(what);
        var labelFactory = new LabelFactory(this.labelType, this.labelText, this.labelFormat);
        var position, size, color, text, positionN, sizeN, colorN;
        if (this.labelGrouping === 'atom') {
            var atomData = sview.getAtomData(p);
            position = atomData.position;
            size = atomData.radius;
            color = atomData.color;
            if (!what || what.text) {
                text = [];
                sview.eachAtom(function (ap) { return text.push(labelFactory.atomLabel(ap)); });
            }
        }
        else if (this.labelGrouping === 'residue') {
            if (!what || what.position)
                { positionN = []; }
            if (!what || what.color)
                { colorN = []; }
            if (!what || what.radius)
                { sizeN = []; }
            if (!what || what.text)
                { text = []; }
            if (p.colorParams)
                { p.colorParams.structure = sview.getStructure(); }
            var colormaker = ColormakerRegistry$1.getScheme(p.colorParams);
            var radiusFactory = new RadiusFactory(p.radiusParams);
            var ap1 = sview.getAtomProxy();
            var i = 0;
            sview.eachResidue(function (rp) {
                var i3 = i * 3;
                if (rp.isProtein() || rp.isNucleic()) {
                    ap1.index = rp.traceAtomIndex;
                    if (!what || what.position) {
                        ap1.positionToArray(positionN, i3);
                    }
                }
                else {
                    ap1.index = rp.atomOffset;
                    if (!what || what.position) {
                        rp.positionToArray(positionN, i3);
                    }
                }
                if (!what || what.color) {
                    colormaker.atomColorToArray(ap1, colorN, i3);
                }
                if (!what || what.radius) {
                    sizeN[i] = radiusFactory.atomRadius(ap1);
                }
                if (!what || what.text) {
                    text.push(labelFactory.atomLabel(ap1));
                }
                ++i;
            });
            if (!what || what.position)
                { position = new Float32Array(positionN); }
            if (!what || what.color)
                { color = new Float32Array(colorN); }
            if (!what || what.radius)
                { size = new Float32Array(sizeN); }
        }
        return { position: position, size: size, color: color, text: text };
    };
    LabelRepresentation.prototype.createData = function createData (sview) {
        var what = { position: true, color: true, radius: true, text: true };
        var textBuffer = new TextBuffer(this.getTextData(sview, what), 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
        }));
        return { bufferList: [textBuffer] };
    };
    LabelRepresentation.prototype.updateData = function updateData (what, data) {
        data.bufferList[0].setAttributes(this.getTextData(data.sview, what));
    };
    LabelRepresentation.prototype.getAtomRadius = function getAtomRadius () {
        return 0;
    };

    return LabelRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('label', LabelRepresentation);

/**
 * @file Line Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Determine which atoms in  a Structure[View] form no bonds to any other atoms
 * in that Structure.
 *
 * This differs from setting the selection to "nonbonded" as it finds atoms
 * that have no bonds within the current selection.
 * @param  {Structure} structure - The Structure or StructureView object
 * @return {AtomSet} AtomSet of lone atoms
 */
function getLoneAtomSet(structure) {
    var atomSet = structure.getAtomSet();
    var bondSet = structure.getBondSet();
    var bp = structure.getBondProxy();
    bondSet.forEach(function (idx) {
        bp.index = idx;
        atomSet.clear(bp.atomIndex1);
        atomSet.clear(bp.atomIndex2);
    });
    return atomSet;
}
/**
 * Line representation
 */
var LineRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function LineRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'line';
        this.parameters = Object.assign({
            multipleBond: {
                type: 'select',
                rebuild: true,
                options: {
                    'off': 'off',
                    'symmetric': 'symmetric',
                    'offset': 'offset'
                }
            },
            bondSpacing: {
                type: 'number', precision: 2, max: 2.0, min: 0.5
            },
            linewidth: {
                type: 'integer', max: 50, min: 1, buffer: true
            },
            lines: {
                type: 'boolean', rebuild: true
            },
            crosses: {
                type: 'select',
                rebuild: true,
                options: {
                    'off': 'off',
                    'lone': 'lone',
                    'all': 'all'
                }
            },
            crossSize: {
                type: 'number', precision: 2, max: 2.0, min: 0.1
            }
        }, this.parameters, {
            flatShaded: null,
            side: null,
            wireframe: null,
            roughness: null,
            metalness: null
        });
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) LineRepresentation.__proto__ = StructureRepresentation$$1;
    LineRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    LineRepresentation.prototype.constructor = LineRepresentation;
    LineRepresentation.prototype.init = function init (params) {
        var p = params || {};
        this.multipleBond = defaults(p.multipleBond, 'off');
        this.bondSpacing = defaults(p.bondSpacing, 1.0);
        this.linewidth = defaults(p.linewidth, 2);
        this.lines = defaults(p.lines, true);
        this.crosses = defaults(p.crosses, 'lone');
        this.crossSize = defaults(p.crossSize, 0.4);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    LineRepresentation.prototype.getAtomRadius = function getAtomRadius (atom) {
        return 0.1;
    };
    LineRepresentation.prototype.getBondParams = function getBondParams (what, params) {
        params = Object.assign({
            multipleBond: this.multipleBond,
            bondSpacing: this.bondSpacing,
            radiusParams: { 'type': 'size', 'size': 0.1, 'scale': 1 }
        }, params);
        return StructureRepresentation$$1.prototype.getBondParams.call(this, what, params);
    };
    LineRepresentation.prototype._crossData = function _crossData (what, sview) {
        if (what) {
            if (!what.position && !what.color)
                { return; }
        }
        var p = {};
        if (this.crosses === 'lone') {
            Object.assign(p, { atomSet: getLoneAtomSet(sview) });
        }
        var atomData = sview.getAtomData(this.getAtomParams(what, p));
        var crossData = {};
        var position = atomData.position;
        var color = atomData.color;
        var picking = atomData.picking;
        var size = (position || color).length;
        var attrSize = size * 3;
        var cPosition1 = new Float32Array(0);
        var cPosition2 = new Float32Array(0);
        var cColor = new Float32Array(0);
        var cColor2 = new Float32Array(0);
        var cOffset = 0;
        var pickingArray = new Float32Array(0);
        if (!what || what.position) {
            cPosition1 = crossData.position1 = new Float32Array(attrSize);
            cPosition2 = crossData.position2 = new Float32Array(attrSize);
            cOffset = this.crossSize / 2;
        }
        if (!what || what.color) {
            cColor = crossData.color = new Float32Array(attrSize);
            cColor2 = crossData.color2 = new Float32Array(attrSize);
        }
        if (!what || what.picking) {
            pickingArray = new Float32Array(atomData.picking.array.length * 3); // Needs padding??
        }
        for (var v = 0; v < size; v++) {
            var j = v * 3;
            var i = j * 3;
            if (!what || what.position) {
                var x = position[j];
                var y = position[j + 1];
                var z = position[j + 2];
                cPosition1[i] = x - cOffset;
                cPosition1[i + 1] = y;
                cPosition1[i + 2] = z;
                cPosition2[i] = x + cOffset;
                cPosition2[i + 1] = y;
                cPosition2[i + 2] = z;
                cPosition1[i + 3] = x;
                cPosition1[i + 4] = y - cOffset;
                cPosition1[i + 5] = z;
                cPosition2[i + 3] = x;
                cPosition2[i + 4] = y + cOffset;
                cPosition2[i + 5] = z;
                cPosition1[i + 6] = x;
                cPosition1[i + 7] = y;
                cPosition1[i + 8] = z - cOffset;
                cPosition2[i + 6] = x;
                cPosition2[i + 7] = y;
                cPosition2[i + 8] = z + cOffset;
            }
            if (!what || what.color) {
                var cimax = i + 9;
                for (var ci = i; ci < cimax; ci += 3) {
                    cColor[ci] = cColor2[ci] = color[j];
                    cColor[ci + 1] = cColor2[ci + 1] = color[j + 1];
                    cColor[ci + 2] = cColor2[ci + 2] = color[j + 2];
                }
            }
            if (!what || what.picking) {
                pickingArray[j] =
                    pickingArray[j + 1] =
                        pickingArray[j + 2] = picking.array[v];
            }
        }
        if (!what || what.picking) {
            crossData.picking = new AtomPicker(pickingArray, picking.structure);
        }
        return crossData;
    };
    LineRepresentation.prototype.createData = function createData (sview) {
        var what = { position: true, color: true, picking: true };
        var bufferList = [];
        if (this.lines) {
            var bondData = sview.getBondData(this.getBondParams(what));
            var lineBuffer = new WideLineBuffer(bondData, this.getBufferParams({ linewidth: this.linewidth }));
            bufferList.push(lineBuffer);
        }
        if (this.crosses !== 'off') {
            var crossBuffer = new WideLineBuffer(this._crossData(what, sview), this.getBufferParams({ linewidth: this.linewidth }));
            bufferList.push(crossBuffer);
        }
        return {
            bufferList: bufferList
        };
    };
    LineRepresentation.prototype.updateData = function updateData (what, data) {
        var bufferIdx = 0;
        if (this.lines) {
            var bondData = data.sview.getBondData(this.getBondParams(what));
            var lineAttributes = {};
            if (!what || what.position) {
                Object.assign(lineAttributes, {
                    position1: bondData.position1,
                    position2: bondData.position2
                });
            }
            if (!what || what.color) {
                Object.assign(lineAttributes, {
                    color: bondData.color,
                    color2: bondData.color2
                });
            }
            data.bufferList[bufferIdx++].setAttributes(lineAttributes);
        }
        if (this.crosses !== 'off') {
            var crossData = this._crossData(what, data.sview);
            var crossAttributes = {};
            if (!what || what.position) {
                Object.assign(crossAttributes, {
                    position1: crossData.position1,
                    position2: crossData.position2
                });
            }
            if (!what || what.color) {
                Object.assign(crossAttributes, {
                    color: crossData.color,
                    color2: crossData.color2
                });
            }
            data.bufferList[bufferIdx++].setAttributes(crossAttributes);
        }
    };
    LineRepresentation.prototype.setParameters = function setParameters (params) {
        var rebuild = false;
        var what = {};
        if (params && (params.bondSpacing || params.crossSize)) {
            Object.assign(what, { position: true });
        }
        StructureRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        return this;
    };

    return LineRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('line', LineRepresentation);

function makeGrid(length, width, height, DataCtor, elemSize) {
    DataCtor = DataCtor || Int32Array;
    elemSize = elemSize || 1;
    var data = new DataCtor(length * width * height * elemSize);
    function index(x, y, z) {
        return ((((x * width) + y) * height) + z) * elemSize;
    }
    function set(x, y, z) {
        var args = [], len = arguments.length - 3;
        while ( len-- > 0 ) args[ len ] = arguments[ len + 3 ];

        var i = index(x, y, z);
        for (var j = 0; j < elemSize; ++j) {
            data[i + j] = args[j];
        }
    }
    function toArray(x, y, z, array, offset) {
        if ( array === void 0 ) array = [];
        if ( offset === void 0 ) offset = 0;

        var i = index(x, y, z);
        for (var j = 0; j < elemSize; ++j) {
            array[offset + j] = data[i + j];
        }
    }
    function fromArray(x, y, z, array, offset) {
        if ( offset === void 0 ) offset = 0;

        var i = index(x, y, z);
        for (var j = 0; j < elemSize; ++j) {
            data[i + j] = array[offset + j];
        }
    }
    function copy(grid) {
        data.set(grid.data);
    }
    // function clone() {
    //   return makeGrid(
    //     length, width, height, DataCtor, elemSize
    //   ).copy(this)
    // }
    return { data: data, index: index, set: set, toArray: toArray, fromArray: fromArray, copy: copy };
}

/**
 * @file EDT Surface
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function EDTSurface(coordList, radiusList, indexList) {
    // based on D. Xu, Y. Zhang (2009) Generating Triangulated Macromolecular
    // Surfaces by Euclidean Distance Transform. PLoS ONE 4(12): e8140.
    //
    // Permission to use, copy, modify, and distribute this program for
    // any purpose, with or without fee, is hereby granted, provided that
    // the notices on the head, the reference information, and this
    // copyright notice appear in all copies or substantial portions of
    // the Software. It is provided "as is" without express or implied
    // warranty.
    //
    // ported to JavaScript by biochem_fan (http://webglmol.sourceforge.jp/)
    // refactored by dkoes (https://github.com/dkoes)
    //
    // adapted to NGL by Alexander Rose
    var radiusDict = getRadiusDict(radiusList);
    var bbox = computeBoundingBox(coordList);
    if (coordList.length === 0) {
        bbox[0].set([0, 0, 0]);
        bbox[1].set([0, 0, 0]);
    }
    var min = bbox[0];
    var max = bbox[1];
    var probeRadius, scaleFactor, cutoff;
    var pLength, pWidth, pHeight;
    var matrix, ptran;
    var depty, widxz;
    var cutRadius;
    var setAtomID;
    var vpBits, vpDistance, vpAtomID;
    function init(btype, _probeRadius, _scaleFactor, _cutoff, _setAtomID) {
        probeRadius = _probeRadius || 1.4;
        scaleFactor = _scaleFactor || 2.0;
        setAtomID = _setAtomID || true;
        var maxRadius = 0;
        for (var radius in radiusDict) {
            maxRadius = Math.max(maxRadius, radius);
        }
        var grid = getSurfaceGrid(min, max, maxRadius, scaleFactor, btype ? probeRadius : 0);
        pLength = grid.dim[0];
        pWidth = grid.dim[1];
        pHeight = grid.dim[2];
        matrix = grid.matrix;
        ptran = grid.tran;
        scaleFactor = grid.scaleFactor;
        // boundingatom caches
        depty = {};
        widxz = {};
        boundingatom(btype);
        cutRadius = probeRadius * scaleFactor;
        if (_cutoff) {
            cutoff = _cutoff;
        }
        else {
            // cutoff = Math.max( 0.1, -1.2 + scaleFactor * probeRadius );
            cutoff = probeRadius / scaleFactor;
        }
        vpBits = new Uint8Array(pLength * pWidth * pHeight);
        if (btype) {
            vpDistance = new Float64Array(pLength * pWidth * pHeight);
        }
        if (setAtomID) {
            vpAtomID = new Int32Array(pLength * pWidth * pHeight);
        }
    }
    // constants for vpBits bitmasks
    var INOUT = 1;
    var ISDONE = 2;
    var ISBOUND = 4;
    var nb = [
        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])
    ];
    //
    this.getVolume = function (type, probeRadius, scaleFactor, cutoff, setAtomID) {
        console.time('EDTSurface.getVolume');
        var btype = type !== 'vws';
        init(btype, probeRadius, scaleFactor, cutoff, setAtomID);
        fillvoxels(btype);
        buildboundary();
        if (type === 'ms' || type === 'ses') {
            fastdistancemap();
        }
        if (type === 'ses') {
            boundingatom(false);
            fillvoxelswaals();
        }
        marchingcubeinit(type);
        // set atomindex in the volume data
        for (var i = 0, il = vpAtomID.length; i < il; ++i) {
            vpAtomID[i] = indexList[vpAtomID[i]];
        }
        console.timeEnd('EDTSurface.getVolume');
        return {
            data: vpBits,
            nx: pHeight,
            ny: pWidth,
            nz: pLength,
            atomindex: vpAtomID
        };
    };
    this.getSurface = function (type, probeRadius, scaleFactor, cutoff, setAtomID, smooth, contour) {
        var vd = this.getVolume(type, probeRadius, scaleFactor, cutoff, setAtomID);
        var volsurf = new VolumeSurface(vd.data, vd.nx, vd.ny, vd.nz, vd.atomindex);
        return volsurf.getSurface(1, smooth, undefined, matrix, contour);
    };
    function boundingatom(btype) {
        var r;
        var j;
        var k;
        var txz;
        var tdept;
        var sradius;
        var tradius;
        var widxzR;
        var deptyName;
        var indx;
        for (var name in radiusDict) {
            r = parseFloat(name);
            if (depty[name])
                { continue; }
            if (!btype) {
                tradius = r * scaleFactor + 0.5;
            }
            else {
                tradius = (r + probeRadius) * scaleFactor + 0.5;
            }
            sradius = tradius * tradius;
            widxzR = Math.floor(tradius) + 1;
            deptyName = new Int32Array(widxzR * widxzR);
            indx = 0;
            for (j = 0; j < widxzR; ++j) {
                for (k = 0; k < widxzR; ++k) {
                    txz = j * j + k * k;
                    if (txz > sradius) {
                        deptyName[indx] = -1;
                    }
                    else {
                        tdept = Math.sqrt(sradius - txz);
                        deptyName[indx] = Math.floor(tdept);
                    }
                    ++indx;
                }
            }
            widxz[name] = widxzR;
            depty[name] = deptyName;
        }
    }
    function fillatom(idx) {
        var ci = idx * 3;
        var ri = idx;
        var cx, cy, cz, ox, oy, oz, mi, mj, mk, i, j, k, si, sj, sk;
        var ii, jj, kk;
        cx = Math.floor(0.5 + scaleFactor * (coordList[ci] + ptran[0]));
        cy = Math.floor(0.5 + scaleFactor * (coordList[ci + 1] + ptran[1]));
        cz = Math.floor(0.5 + scaleFactor * (coordList[ci + 2] + ptran[2]));
        var at = radiusList[ri];
        var deptyAt = depty[at];
        var nind = 0;
        var pWH = pWidth * pHeight;
        var n = widxz[at];
        var deptyAtNind;
        for (i = 0; i < n; ++i) {
            for (j = 0; j < n; ++j) {
                deptyAtNind = deptyAt[nind];
                if (deptyAtNind !== -1) {
                    for (ii = -1; ii < 2; ++ii) {
                        for (jj = -1; jj < 2; ++jj) {
                            for (kk = -1; kk < 2; ++kk) {
                                if (ii !== 0 && jj !== 0 && kk !== 0) {
                                    mi = ii * i;
                                    mk = kk * j;
                                    for (k = 0; k <= deptyAtNind; ++k) {
                                        mj = k * jj;
                                        si = cx + mi;
                                        sj = cy + mj;
                                        sk = cz + mk;
                                        if (si < 0 || sj < 0 || sk < 0 ||
                                            si >= pLength || sj >= pWidth || sk >= pHeight) {
                                            continue;
                                        }
                                        var index = si * pWH + sj * pHeight + sk;
                                        if (!setAtomID) {
                                            vpBits[index] |= INOUT;
                                        }
                                        else {
                                            if (!(vpBits[index] & INOUT)) {
                                                vpBits[index] |= INOUT;
                                                vpAtomID[index] = idx;
                                            }
                                            else if (vpBits[index] & INOUT) {
                                                var ci2 = vpAtomID[index];
                                                if (ci2 !== ci) {
                                                    ox = cx + mi - Math.floor(0.5 + scaleFactor * (coordList[ci2] + ptran[0]));
                                                    oy = cy + mj - Math.floor(0.5 + scaleFactor * (coordList[ci2 + 1] + ptran[1]));
                                                    oz = cz + mk - Math.floor(0.5 + scaleFactor * (coordList[ci2 + 2] + ptran[2]));
                                                    if (mi * mi + mj * mj + mk * mk < ox * ox + oy * oy + oz * oz) {
                                                        vpAtomID[index] = idx;
                                                    }
                                                }
                                            }
                                        }
                                    } // k
                                } // if
                            } // kk
                        } // jj
                    } // ii
                } // if
                nind++;
            } // j
        } // i
    }
    function fillvoxels(btype) {
        console.time('EDTSurface fillvoxels');
        var i, il;
        for (i = 0, il = vpBits.length; i < il; ++i) {
            vpBits[i] = 0;
            if (btype)
                { vpDistance[i] = -1.0; }
            if (setAtomID)
                { vpAtomID[i] = -1; }
        }
        for (i = 0, il = coordList.length / 3; i < il; ++i) {
            fillatom(i);
        }
        for (i = 0, il = vpBits.length; i < il; ++i) {
            if (vpBits[i] & INOUT) {
                vpBits[i] |= ISDONE;
            }
        }
        console.timeEnd('EDTSurface fillvoxels');
    }
    function fillAtomWaals(idx) {
        var ci = idx * 3;
        var ri = idx;
        var cx;
        var cy;
        var cz;
        var ox;
        var oy;
        var oz;
        var nind = 0;
        var mi;
        var mj;
        var mk;
        var si;
        var sj;
        var sk;
        var i;
        var j;
        var k;
        var ii;
        var jj;
        var kk;
        var n;
        cx = Math.floor(0.5 + scaleFactor * (coordList[ci] + ptran[0]));
        cy = Math.floor(0.5 + scaleFactor * (coordList[ci + 1] + ptran[1]));
        cz = Math.floor(0.5 + scaleFactor * (coordList[ci + 2] + ptran[2]));
        var at = radiusList[ri];
        var pWH = pWidth * pHeight;
        for (i = 0, n = widxz[at]; i < n; ++i) {
            for (j = 0; j < n; ++j) {
                if (depty[at][nind] !== -1) {
                    for (ii = -1; ii < 2; ++ii) {
                        for (jj = -1; jj < 2; ++jj) {
                            for (kk = -1; kk < 2; ++kk) {
                                if (ii !== 0 && jj !== 0 && kk !== 0) {
                                    mi = ii * i;
                                    mk = kk * j;
                                    for (k = 0; k <= depty[at][nind]; ++k) {
                                        mj = k * jj;
                                        si = cx + mi;
                                        sj = cy + mj;
                                        sk = cz + mk;
                                        if (si < 0 || sj < 0 || sk < 0 ||
                                            si >= pLength || sj >= pWidth || sk >= pHeight) {
                                            continue;
                                        }
                                        var index = si * pWH + sj * pHeight + sk;
                                        if (!(vpBits[index] & ISDONE)) {
                                            vpBits[index] |= ISDONE;
                                            if (setAtomID)
                                                { vpAtomID[index] = idx; }
                                        }
                                        else if (setAtomID) {
                                            var ci2 = vpAtomID[index];
                                            ox = Math.floor(0.5 + scaleFactor * (coordList[ci2] + ptran[0]));
                                            oy = Math.floor(0.5 + scaleFactor * (coordList[ci2 + 1] + ptran[1]));
                                            oz = Math.floor(0.5 + scaleFactor * (coordList[ci2 + 2] + ptran[2]));
                                            if (mi * mi + mj * mj + mk * mk < ox * ox + oy * oy + oz * oz) {
                                                vpAtomID[index] = idx;
                                            }
                                        }
                                    } // k
                                } // if
                            } // kk
                        } // jj
                    } // ii
                } // if
                nind++;
            } // j
        } // i
    }
    function fillvoxelswaals() {
        var i, il;
        for (i = 0, il = vpBits.length; i < il; ++i) {
            vpBits[i] &= ~ISDONE; // not isdone
        }
        for (i = 0, il = coordList.length / 3; i < il; ++i) {
            fillAtomWaals(i);
        }
    }
    function buildboundary() {
        var i, j, k;
        var pWH = pWidth * pHeight;
        for (i = 0; i < pLength; ++i) {
            for (j = 0; j < pHeight; ++j) {
                for (k = 0; k < pWidth; ++k) {
                    var index = i * pWH + k * pHeight + j;
                    if (vpBits[index] & INOUT) {
                        // var flagbound = false;
                        var ii = 0;
                        // while( !flagbound && ii < 26 ){
                        while (ii < 26) {
                            var ti = i + nb[ii][0];
                            var tj = j + nb[ii][2];
                            var tk = k + nb[ii][1];
                            if (ti > -1 && ti < pLength &&
                                tk > -1 && tk < pWidth &&
                                tj > -1 && tj < pHeight &&
                                !(vpBits[ti * pWH + tk * pHeight + tj] & INOUT)) {
                                vpBits[index] |= ISBOUND;
                                // flagbound = true;
                                break;
                            }
                            else {
                                ii++;
                            }
                        }
                    }
                } // k
            } // j
        } // i
    }
    function fastdistancemap() {
        console.time('EDTSurface fastdistancemap');
        var i, j, k, n;
        var boundPoint = makeGrid(pLength, pWidth, pHeight, Uint16Array, 3);
        var pWH = pWidth * pHeight;
        var cutRSq = cutRadius * cutRadius;
        var totalsurfacevox = 0;
        // var totalinnervox = 0;
        var index;
        for (i = 0; i < pLength; ++i) {
            for (j = 0; j < pWidth; ++j) {
                for (k = 0; k < pHeight; ++k) {
                    index = i * pWH + j * pHeight + k;
                    vpBits[index] &= ~ISDONE;
                    if (vpBits[index] & INOUT) {
                        if (vpBits[index] & ISBOUND) {
                            boundPoint.set(i, j, k, i, j, k);
                            vpDistance[index] = 0;
                            vpBits[index] |= ISDONE;
                            totalsurfacevox += 1;
                        } /* else{
                            totalinnervox += 1;
                        } */
                    }
                }
            }
        }
        var inarray = new Int32Array(3 * totalsurfacevox);
        var positin = 0;
        var outarray = new Int32Array(3 * totalsurfacevox);
        var positout = 0;
        for (i = 0; i < pLength; ++i) {
            for (j = 0; j < pWidth; ++j) {
                for (k = 0; k < pHeight; ++k) {
                    index = i * pWH + j * pHeight + k;
                    if (vpBits[index] & ISBOUND) {
                        inarray[positin] = i;
                        inarray[positin + 1] = j;
                        inarray[positin + 2] = k;
                        positin += 3;
                        vpBits[index] &= ~ISBOUND;
                    }
                }
            }
        }
        do {
            positout = fastoneshell(inarray, boundPoint, positin, outarray);
            positin = 0;
            for (i = 0, n = positout; i < n; i += 3) {
                index = pWH * outarray[i] + pHeight * outarray[i + 1] + outarray[i + 2];
                vpBits[index] &= ~ISBOUND;
                if (vpDistance[index] <= 1.0404 * cutRSq) {
                    // if( vpDistance[ index ] <= 1.02 * cutRadius ){
                    inarray[positin] = outarray[i];
                    inarray[positin + 1] = outarray[i + 1];
                    inarray[positin + 2] = outarray[i + 2];
                    positin += 3;
                }
            }
        } while (positin > 0);
        // var cutsf = Math.max( 0, scaleFactor - 0.5 );
        // cutoff = cutRadius - 0.5 / ( 0.1 + cutsf );
        var cutoffSq = cutoff * cutoff;
        var index2;
        var bp = new Uint16Array(3);
        for (i = 0; i < pLength; ++i) {
            for (j = 0; j < pWidth; ++j) {
                for (k = 0; k < pHeight; ++k) {
                    index = i * pWH + j * pHeight + k;
                    vpBits[index] &= ~ISBOUND;
                    // ses solid
                    if (vpBits[index] & INOUT) {
                        if (!(vpBits[index] & ISDONE) ||
                            ((vpBits[index] & ISDONE) && vpDistance[index] >= cutoffSq)) {
                            vpBits[index] |= ISBOUND;
                            if (setAtomID && (vpBits[index] & ISDONE)) {
                                boundPoint.toArray(i, j, k, bp);
                                index2 = bp[0] * pWH + bp[1] * pHeight + bp[2];
                                vpAtomID[index] = vpAtomID[index2];
                            }
                        }
                    }
                }
            }
        }
        console.timeEnd('EDTSurface fastdistancemap');
    }
    function fastoneshell(inarray, boundPoint, positin, outarray) {
        // *allocout,voxel2
        // ***boundPoint, int*
        // outnum, int *elimi)
        var tx, ty, tz;
        var dx, dy, dz;
        var i, j, n;
        var square;
        var index;
        var nbj;
        var bp = new Uint16Array(3);
        var positout = 0;
        if (positin === 0) {
            return positout;
        }
        var tnvix = -1;
        var tnviy = -1;
        var tnviz = -1;
        var pWH = pWidth * pHeight;
        for (i = 0, n = positin; i < n; i += 3) {
            tx = inarray[i];
            ty = inarray[i + 1];
            tz = inarray[i + 2];
            boundPoint.toArray(tx, ty, tz, bp);
            for (j = 0; j < 6; ++j) {
                nbj = nb[j];
                tnvix = tx + nbj[0];
                tnviy = ty + nbj[1];
                tnviz = tz + nbj[2];
                if (tnvix < pLength && tnvix > -1 &&
                    tnviy < pWidth && tnviy > -1 &&
                    tnviz < pHeight && tnviz > -1) {
                    index = tnvix * pWH + pHeight * tnviy + tnviz;
                    if ((vpBits[index] & INOUT) && !(vpBits[index] & ISDONE)) {
                        boundPoint.fromArray(tnvix, tnviy, tnviz, bp);
                        dx = tnvix - bp[0];
                        dy = tnviy - bp[1];
                        dz = tnviz - bp[2];
                        square = dx * dx + dy * dy + dz * dz;
                        // square = Math.sqrt( square );
                        vpDistance[index] = square;
                        vpBits[index] |= ISDONE;
                        vpBits[index] |= ISBOUND;
                        outarray[positout] = tnvix;
                        outarray[positout + 1] = tnviy;
                        outarray[positout + 2] = tnviz;
                        positout += 3;
                    }
                    else if ((vpBits[index] & INOUT) && (vpBits[index] & ISDONE)) {
                        dx = tnvix - bp[0];
                        dy = tnviy - bp[1];
                        dz = tnviz - bp[2];
                        square = dx * dx + dy * dy + dz * dz;
                        // square = Math.sqrt( square );
                        if (square < vpDistance[index]) {
                            boundPoint.fromArray(tnvix, tnviy, tnviz, bp);
                            vpDistance[index] = square;
                            if (!(vpBits[index] & ISBOUND)) {
                                vpBits[index] |= ISBOUND;
                                outarray[positout] = tnvix;
                                outarray[positout + 1] = tnviy;
                                outarray[positout + 2] = tnviz;
                                positout += 3;
                            }
                        }
                    }
                }
            }
        }
        for (i = 0, n = positin; i < n; i += 3) {
            tx = inarray[i];
            ty = inarray[i + 1];
            tz = inarray[i + 2];
            boundPoint.toArray(tx, ty, tz, bp);
            for (j = 6; j < 18; j++) {
                nbj = nb[j];
                tnvix = tx + nbj[0];
                tnviy = ty + nbj[1];
                tnviz = tz + nbj[2];
                if (tnvix < pLength && tnvix > -1 &&
                    tnviy < pWidth && tnviy > -1 &&
                    tnviz < pHeight && tnviz > -1) {
                    index = tnvix * pWH + pHeight * tnviy + tnviz;
                    if ((vpBits[index] & INOUT) && !(vpBits[index] & ISDONE)) {
                        boundPoint.fromArray(tnvix, tnviy, tnviz, bp);
                        dx = tnvix - bp[0];
                        dy = tnviy - bp[1];
                        dz = tnviz - bp[2];
                        square = dx * dx + dy * dy + dz * dz;
                        // square = Math.sqrt( square );
                        vpDistance[index] = square;
                        vpBits[index] |= ISDONE;
                        vpBits[index] |= ISBOUND;
                        outarray[positout] = tnvix;
                        outarray[positout + 1] = tnviy;
                        outarray[positout + 2] = tnviz;
                        positout += 3;
                    }
                    else if ((vpBits[index] & INOUT) && (vpBits[index] & ISDONE)) {
                        dx = tnvix - bp[0];
                        dy = tnviy - bp[1];
                        dz = tnviz - bp[2];
                        square = dx * dx + dy * dy + dz * dz;
                        // square = Math.sqrt( square );
                        if (square < vpDistance[index]) {
                            boundPoint.fromArray(tnvix, tnviy, tnviz, bp);
                            vpDistance[index] = square;
                            if (!(vpBits[index] & ISBOUND)) {
                                vpBits[index] |= ISBOUND;
                                outarray[positout] = tnvix;
                                outarray[positout + 1] = tnviy;
                                outarray[positout + 2] = tnviz;
                                positout += 3;
                            }
                        }
                    }
                }
            }
        }
        for (i = 0, n = positin; i < n; i += 3) {
            tx = inarray[i];
            ty = inarray[i + 1];
            tz = inarray[i + 2];
            boundPoint.toArray(tx, ty, tz, bp);
            for (j = 18; j < 26; j++) {
                nbj = nb[j];
                tnvix = tx + nbj[0];
                tnviy = ty + nbj[1];
                tnviz = tz + nbj[2];
                if (tnvix < pLength && tnvix > -1 &&
                    tnviy < pWidth && tnviy > -1 &&
                    tnviz < pHeight && tnviz > -1) {
                    index = tnvix * pWH + pHeight * tnviy + tnviz;
                    if ((vpBits[index] & INOUT) && !(vpBits[index] & ISDONE)) {
                        boundPoint.fromArray(tnvix, tnviy, tnviz, bp);
                        dx = tnvix - bp[0];
                        dy = tnviy - bp[1];
                        dz = tnviz - bp[2];
                        square = dx * dx + dy * dy + dz * dz;
                        // square = Math.sqrt( square );
                        vpDistance[index] = square;
                        vpBits[index] |= ISDONE;
                        vpBits[index] |= ISBOUND;
                        outarray[positout] = tnvix;
                        outarray[positout + 1] = tnviy;
                        outarray[positout + 2] = tnviz;
                        positout += 3;
                    }
                    else if ((vpBits[index] & INOUT) && (vpBits[index] & ISDONE)) {
                        dx = tnvix - bp[0];
                        dy = tnviy - bp[1];
                        dz = tnviz - bp[2];
                        square = dx * dx + dy * dy + dz * dz;
                        // square = Math.sqrt( square );
                        if (square < vpDistance[index]) {
                            boundPoint.fromArray(tnvix, tnviy, tnviz, bp);
                            vpDistance[index] = square;
                            if (!(vpBits[index] & ISBOUND)) {
                                vpBits[index] |= ISBOUND;
                                outarray[positout] = tnvix;
                                outarray[positout + 1] = tnviy;
                                outarray[positout + 2] = tnviz;
                                positout += 3;
                            }
                        }
                    }
                }
            }
        }
        return positout;
    }
    function marchingcubeinit(stype) {
        var i;
        var n = vpBits.length;
        if (stype === 'vws') {
            for (i = 0; i < n; ++i) {
                vpBits[i] &= ~ISBOUND;
                vpBits[i] = (vpBits[i] & ISDONE) ? 1 : 0;
            }
        }
        else if (stype === 'ms') { // ses without vdw => ms
            for (i = 0; i < n; ++i) {
                vpBits[i] &= ~ISDONE;
                if (vpBits[i] & ISBOUND) {
                    vpBits[i] |= ISDONE;
                }
                vpBits[i] &= ~ISBOUND;
                vpBits[i] = (vpBits[i] & ISDONE) ? 1 : 0;
            }
        }
        else if (stype === 'ses') {
            for (i = 0; i < n; ++i) {
                if ((vpBits[i] & ISBOUND) && (vpBits[i] & ISDONE)) {
                    vpBits[i] &= ~ISBOUND;
                }
                else if ((vpBits[i] & ISBOUND) && !(vpBits[i] & ISDONE)) {
                    vpBits[i] |= ISDONE;
                }
                vpBits[i] = (vpBits[i] & ISDONE) ? 1 : 0;
            }
        }
        else if (stype === 'sas') {
            for (i = 0; i < n; ++i) {
                vpBits[i] &= ~ISBOUND;
                vpBits[i] = (vpBits[i] & ISDONE) ? 1 : 0;
            }
        }
    }
}
Object.assign(EDTSurface, { __deps: [
        getSurfaceGrid, getRadiusDict, VolumeSurface, computeBoundingBox, makeGrid
    ] });

/**
 * @file AV Surface
 * @author Fred Ludlow <fred.ludlow@gmail.com>
 * @private
 */
function makeAVHash(atomsX, atomsY, atomsZ, atomsR, min, max, maxDistance) {
    maxDistance = Math.max(0.1, maxDistance); // Avoid maxDistance of zero, see #802
    var nAtoms = atomsX.length;
    var minX = min[0];
    var minY = min[1];
    var minZ = min[2];
    var maxX = max[0];
    var maxY = max[1];
    var maxZ = max[2];
    function hashFunc(w, minW) {
        return Math.floor((w - minW) / maxDistance);
    }
    var iDim = hashFunc(maxX, minX) + 1;
    var jDim = hashFunc(maxY, minY) + 1;
    var kDim = hashFunc(maxZ, minZ) + 1;
    var nCells = iDim * jDim * kDim;
    var jkDim = jDim * kDim;
    /* Get cellID for cartesian x,y,z */
    var cellID = function (x, y, z) {
        return (((hashFunc(x, minX) * jDim) + hashFunc(y, minY)) * kDim) + hashFunc(z, minZ);
    };
    /* Initial building, could probably be optimized further */
    var preHash = []; // preHash[ cellID ] = [ atomId1, atomId2 ];
    for (var i = 0; i < nAtoms; i++) {
        var cid = cellID(atomsX[i], atomsY[i], atomsZ[i]);
        if (preHash[cid] === undefined) {
            preHash[cid] = [i];
        }
        else {
            preHash[cid].push(i);
        }
    }
    var cellOffsets = new Uint32Array(nCells);
    var cellLengths = new Uint16Array(nCells);
    var data = new Uint32Array(nAtoms);
    var offset = 0;
    var maxCellLength = 0;
    for (i = 0; i < nCells; i++) {
        var start = cellOffsets[i] = offset;
        var subArray = preHash[i];
        if (subArray !== undefined) {
            for (var j = 0; j < subArray.length; j++) {
                data[offset] = subArray[j];
                offset++;
            }
        }
        var cellLength = offset - start;
        cellLengths[i] = cellLength;
        if (cellLength > maxCellLength) {
            maxCellLength = cellLength;
        }
    }
    // Maximum number of neighbours we could ever produce (27 adjacent cells of equal population)
    var neighbourListLength = (27 * maxCellLength) + 1;
    /**
     * Populate the supplied out array with atom indices that are within rAtom + rExtra
     * of x,y,z
     *
     * -1 in out array indicates the end of the list
     *
     * @param  {Float} x - x coordinate
     * @param  {Float} y - y coordinate
     * @param  {Float} z - z coordinate
     * @param  {Float} rExtra - additional radius
     * @param  {Float32Array} out - pre-allocated output array
     * @return {undefined}
     */
    var withinRadii = function (x, y, z, rExtra, out) {
        var outIdx = 0;
        var nearI = hashFunc(x, minX);
        var nearJ = hashFunc(y, minY);
        var nearK = hashFunc(z, minZ);
        var loI = Math.max(0, nearI - 1);
        var loJ = Math.max(0, nearJ - 1);
        var loK = Math.max(0, nearK - 1);
        var hiI = Math.min(iDim, nearI + 2);
        var hiJ = Math.min(jDim, nearJ + 2);
        var hiK = Math.min(kDim, nearK + 2);
        for (var i = loI; i < hiI; ++i) {
            var iOffset = i * jkDim;
            for (var j = loJ; j < hiJ; ++j) {
                var jOffset = j * kDim;
                for (var k = loK; k < hiK; ++k) {
                    var cid = iOffset + jOffset + k;
                    var cellStart = cellOffsets[cid];
                    var cellEnd = cellStart + cellLengths[cid];
                    for (var dataIndex = cellStart; dataIndex < cellEnd; dataIndex++) {
                        var atomIndex = data[dataIndex];
                        var dx = atomsX[atomIndex] - x;
                        var dy = atomsY[atomIndex] - y;
                        var dz = atomsZ[atomIndex] - z;
                        var rSum = atomsR[atomIndex] + rExtra;
                        if ((dx * dx + dy * dy + dz * dz) <= (rSum * rSum)) {
                            out[outIdx++] = data[dataIndex];
                        }
                    }
                }
            }
        }
        // Add terminator
        out[outIdx] = -1;
    };
    return {
        neighbourListLength: neighbourListLength,
        withinRadii: withinRadii
    };
}
function AVSurface(coordList, radiusList, indexList) {
    // Field generation method adapted from AstexViewer (Mike Hartshorn)
    // by Fred Ludlow.
    // Other parts based heavily on NGL (Alexander Rose) EDT Surface class
    //
    // Should work as a drop-in alternative to EDTSurface (though some of
    // the EDT paramters are not relevant in this method).
    var nAtoms = radiusList.length;
    var x = new Float32Array(nAtoms);
    var y = new Float32Array(nAtoms);
    var z = new Float32Array(nAtoms);
    for (var i = 0; i < nAtoms; i++) {
        var ci = 3 * i;
        x[i] = coordList[ci];
        y[i] = coordList[ci + 1];
        z[i] = coordList[ci + 2];
    }
    var bbox = computeBoundingBox(coordList);
    if (coordList.length === 0) {
        bbox[0].set([0, 0, 0]);
        bbox[1].set([0, 0, 0]);
    }
    var min = bbox[0];
    var max = bbox[1];
    var r, r2; // Atom positions, expanded radii (squared)
    var maxRadius;
    // Parameters
    var probeRadius, scaleFactor, setAtomID, probePositions;
    // Cache last value for obscured test
    var lastClip = -1;
    // Grid params
    var dim, matrix, grid, atomIndex;
    // grid indices -> xyz coords
    var gridx, gridy, gridz;
    // Lookup tables:
    var sinTable, cosTable;
    // Spatial Hash
    var hash;
    // Neighbour array to be filled by hash
    var neighbours;
    // Vectors for Torus Projection
    var atob = new Float32Array([0.0, 0.0, 0.0]);
    var mid = new Float32Array([0.0, 0.0, 0.0]);
    var n1 = new Float32Array([0.0, 0.0, 0.0]);
    var n2 = new Float32Array([0.0, 0.0, 0.0]);
    var ngTorus;
    function init(_probeRadius, _scaleFactor, _setAtomID, _probePositions) {
        probeRadius = defaults(_probeRadius, 1.4);
        scaleFactor = defaults(_scaleFactor, 2.0);
        setAtomID = defaults(_setAtomID, true);
        probePositions = defaults(_probePositions, 30);
        r = new Float32Array(nAtoms);
        r2 = new Float32Array(nAtoms);
        for (var i = 0; i < r.length; ++i) {
            var rExt = radiusList[i] + probeRadius;
            r[i] = rExt;
            r2[i] = rExt * rExt;
        }
        maxRadius = 0;
        for (var j = 0; j < r.length; ++j) {
            if (r[j] > maxRadius)
                { maxRadius = r[j]; }
        }
        initializeGrid();
        initializeAngleTables();
        initializeHash();
        lastClip = -1;
    }
    function fillGridDim(a, start, step) {
        for (var i = 0; i < a.length; i++) {
            a[i] = start + (step * i);
        }
    }
    function initializeGrid() {
        var surfGrid = getSurfaceGrid(min, max, maxRadius, scaleFactor, 0.0);
        scaleFactor = surfGrid.scaleFactor;
        dim = surfGrid.dim;
        matrix = surfGrid.matrix;
        ngTorus = Math.max(5, 2 + Math.floor(probeRadius * scaleFactor));
        grid = uniformArray(dim[0] * dim[1] * dim[2], -1001.0);
        atomIndex = new Int32Array(grid.length);
        gridx = new Float32Array(dim[0]);
        gridy = new Float32Array(dim[1]);
        gridz = new Float32Array(dim[2]);
        fillGridDim(gridx, min[0], 1 / scaleFactor);
        fillGridDim(gridy, min[1], 1 / scaleFactor);
        fillGridDim(gridz, min[2], 1 / scaleFactor);
    }
    function initializeAngleTables() {
        var theta = 0.0;
        var step = 2 * Math.PI / probePositions;
        cosTable = new Float32Array(probePositions);
        sinTable = new Float32Array(probePositions);
        for (var i = 0; i < probePositions; i++) {
            cosTable[i] = Math.cos(theta);
            sinTable[i] = Math.sin(theta);
            theta += step;
        }
    }
    function initializeHash() {
        hash = makeAVHash(x, y, z, r, min, max, 2.01 * maxRadius);
        neighbours = new Int32Array(hash.neighbourListLength);
    }
    function obscured(x, y, z, a, b) {
        // Is the point at x,y,z obscured by any of the atoms
        // specifeid by indices in neighbours. Ignore indices
        // a and b (these are the relevant atoms in projectPoints/Torii)
        // Cache the last clipped atom (as very often the same one in
        // subsequent calls)
        var ai;
        if (lastClip !== -1) {
            ai = lastClip;
            if (ai !== a && ai !== b && singleAtomObscures(ai, x, y, z)) {
                return ai;
            }
            else {
                lastClip = -1;
            }
        }
        var ni = 0;
        ai = neighbours[ni];
        while (ai >= 0) {
            if (ai !== a && ai !== b && singleAtomObscures(ai, x, y, z)) {
                lastClip = ai;
                return ai;
            }
            ai = neighbours[++ni];
        }
        lastClip = -1;
        return -1;
    }
    function singleAtomObscures(ai, x, y, z) {
        var ci = 3 * ai;
        var ra2 = r2[ai];
        var dx = coordList[ci] - x;
        var dy = coordList[ci + 1] - y;
        var dz = coordList[ci + 2] - z;
        var d2 = dx * dx + dy * dy + dz * dz;
        return d2 < ra2;
    }
    function projectPoints() {
        // For each atom:
        //     Iterate over a subsection of the grid, for each point:
        //         If current value < 0.0, unvisited, set positive
        //
        //         In any case: Project this point onto surface of the atomic sphere
        //         If this projected point is not obscured by any other atom
        //             Calcualte delta distance and set grid value to minimum of
        //             itself and delta
        // Should we alias frequently accessed closure variables??
        // Assume JS engine capable of optimizing this
        // anyway...
        for (var i = 0; i < nAtoms; i++) {
            var ax = x[i];
            var ay = y[i];
            var az = z[i];
            var ar = r[i];
            var ar2 = r2[i];
            hash.withinRadii(ax, ay, az, ar, neighbours);
            // Number of grid points, round this up...
            var ng = Math.ceil(ar * scaleFactor);
            // Center of the atom, mapped to grid points (take floor)
            var iax = Math.floor(scaleFactor * (ax - min[0]));
            var iay = Math.floor(scaleFactor * (ay - min[1]));
            var iaz = Math.floor(scaleFactor * (az - min[2]));
            // Extents of grid to consider for this atom
            var minx = Math.max(0, iax - ng);
            var miny = Math.max(0, iay - ng);
            var minz = Math.max(0, iaz - ng);
            // Add two to these points:
            // - iax are floor'd values so this ensures coverage
            // - these are loop limits (exclusive)
            var maxx = Math.min(dim[0], iax + ng + 2);
            var maxy = Math.min(dim[1], iay + ng + 2);
            var maxz = Math.min(dim[2], iaz + ng + 2);
            for (var ix = minx; ix < maxx; ix++) {
                var dx = gridx[ix] - ax;
                var xoffset = dim[1] * dim[2] * ix;
                for (var iy = miny; iy < maxy; iy++) {
                    var dy = gridy[iy] - ay;
                    var dxy2 = dx * dx + dy * dy;
                    var xyoffset = xoffset + dim[2] * iy;
                    for (var iz = minz; iz < maxz; iz++) {
                        var dz = gridz[iz] - az;
                        var d2 = dxy2 + dz * dz;
                        if (d2 < ar2) {
                            var idx = iz + xyoffset;
                            if (grid[idx] < 0.0) {
                                // Unvisited, make positive
                                grid[idx] = -grid[idx];
                            }
                            // Project on to the surface of the sphere
                            // sp is the projected point ( dx, dy, dz ) * ( ra / d )
                            var d = Math.sqrt(d2);
                            var ap = ar / d;
                            var spx = dx * ap;
                            var spy = dy * ap;
                            var spz = dz * ap;
                            spx += ax;
                            spy += ay;
                            spz += az;
                            if (obscured(spx, spy, spz, i, -1) === -1) {
                                var dd = ar - d;
                                if (dd < grid[idx]) {
                                    grid[idx] = dd;
                                    if (setAtomID)
                                        { atomIndex[idx] = i; }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    function projectTorii() {
        for (var i = 0; i < nAtoms; i++) {
            hash.withinRadii(x[i], y[i], z[i], r[i], neighbours);
            var ia = 0;
            var ni = neighbours[ia];
            while (ni >= 0) {
                if (i < ni) {
                    projectTorus(i, ni);
                }
                ni = neighbours[++ia];
            }
        }
    }
    function projectTorus(a, b) {
        var r1 = r[a];
        var r2 = r[b];
        var dx = atob[0] = x[b] - x[a];
        var dy = atob[1] = y[b] - y[a];
        var dz = atob[2] = z[b] - z[a];
        var d2 = dx * dx + dy * dy + dz * dz;
        // This check now redundant as already done in AVHash.withinRadii
        // if( d2 > (( r1 + r2 ) * ( r1 + r2 )) ){ return; }
        var d = Math.sqrt(d2);
        // Find angle between a->b vector and the circle
        // of their intersection by cosine rule
        var cosA = (r1 * r1 + d * d - r2 * r2) / (2.0 * r1 * d);
        // distance along a->b at intersection
        var dmp = r1 * cosA;
        v3normalize(atob, atob);
        // Create normal to line
        normalToLine(n1, atob);
        v3normalize(n1, n1);
        // Cross together for second normal vector
        v3cross(n2, atob, n1);
        v3normalize(n2, n2);
        // r is radius of circle of intersection
        var rInt = Math.sqrt(r1 * r1 - dmp * dmp);
        v3multiplyScalar(n1, n1, rInt);
        v3multiplyScalar(n2, n2, rInt);
        v3multiplyScalar(atob, atob, dmp);
        mid[0] = atob[0] + x[a];
        mid[1] = atob[1] + y[a];
        mid[2] = atob[2] + z[a];
        lastClip = -1;
        var ng = ngTorus;
        for (var i = 0; i < probePositions; i++) {
            var cost = cosTable[i];
            var sint = sinTable[i];
            var px = mid[0] + cost * n1[0] + sint * n2[0];
            var py = mid[1] + cost * n1[1] + sint * n2[1];
            var pz = mid[2] + cost * n1[2] + sint * n2[2];
            if (obscured(px, py, pz, a, b) === -1) {
                // As above, iterate over our grid...
                // px, py, pz in grid coords
                var iax = Math.floor(scaleFactor * (px - min[0]));
                var iay = Math.floor(scaleFactor * (py - min[1]));
                var iaz = Math.floor(scaleFactor * (pz - min[2]));
                var minx = Math.max(0, iax - ng);
                var miny = Math.max(0, iay - ng);
                var minz = Math.max(0, iaz - ng);
                var maxx = Math.min(dim[0], iax + ng + 2);
                var maxy = Math.min(dim[1], iay + ng + 2);
                var maxz = Math.min(dim[2], iaz + ng + 2);
                for (var ix = minx; ix < maxx; ix++) {
                    dx = px - gridx[ix];
                    var xoffset = dim[1] * dim[2] * ix;
                    for (var iy = miny; iy < maxy; iy++) {
                        dy = py - gridy[iy];
                        var dxy2 = dx * dx + dy * dy;
                        var xyoffset = xoffset + dim[2] * iy;
                        for (var iz = minz; iz < maxz; iz++) {
                            dz = pz - gridz[iz];
                            d2 = dxy2 + dz * dz;
                            var idx = iz + xyoffset;
                            var current = grid[idx];
                            if (current > 0.0 && d2 < (current * current)) {
                                grid[idx] = Math.sqrt(d2);
                                if (setAtomID) {
                                    // Is this grid point closer to a or b?
                                    // Take dot product of atob and gridpoint->p (dx, dy, dz)
                                    var dp = dx * atob[0] + dy * atob[1] + dz * atob[2];
                                    atomIndex[idx] = dp < 0.0 ? b : a;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    function normalToLine(out, p) {
        out[0] = out[1] = out[2] = 1.0;
        if (p[0] !== 0) {
            out[0] = (p[1] + p[2]) / -p[0];
        }
        else if (p[1] !== 0) {
            out[1] = (p[0] + p[2]) / -p[1];
        }
        else if (p[2] !== 0) {
            out[2] = (p[0] + p[1]) / -p[2];
        }
        return out;
    }
    function fixNegatives() {
        for (var i = 0; i < grid.length; i++) {
            if (grid[i] < 0)
                { grid[i] = 0; }
        }
    }
    function fixAtomIDs() {
        for (var i = 0; i < atomIndex.length; i++) {
            atomIndex[i] = indexList[atomIndex[i]];
        }
    }
    function getVolume(probeRadius, scaleFactor, setAtomID) {
        // Basic steps are:
        // 1) Initialize
        // 2) Project points
        // 3) Project torii
        console.time('AVSurface.getVolume');
        console.time('AVSurface.init');
        init(probeRadius, scaleFactor, setAtomID);
        console.timeEnd('AVSurface.init');
        console.time('AVSurface.projectPoints');
        projectPoints();
        console.timeEnd('AVSurface.projectPoints');
        console.time('AVSurface.projectTorii');
        projectTorii();
        console.timeEnd('AVSurface.projectTorii');
        fixNegatives();
        fixAtomIDs();
        console.timeEnd('AVSurface.getVolume');
    }
    this.getSurface = function (type, probeRadius, scaleFactor, cutoff, setAtomID, smooth, contour) {
        // type and cutoff left in for compatibility with EDTSurface.getSurface
        // function signature
        getVolume(probeRadius, scaleFactor, setAtomID);
        var volsurf = new VolumeSurface(grid, dim[2], dim[1], dim[0], atomIndex);
        return volsurf.getSurface(probeRadius, false, undefined, matrix, contour);
    };
}
Object.assign(AVSurface, { __deps: [
        getSurfaceGrid, VolumeSurface, uniformArray, computeBoundingBox,
        v3multiplyScalar, v3cross, v3normalize,
        makeAVHash,
        defaults
    ] });

/**
 * @file Molecular Surface
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
WorkerRegistry$1.add('molsurf', function func(e, callback) {
    var a = e.data.args;
    var p = e.data.params;
    if (a && p) {
        var SurfClass = (p.type === 'av') ? AVSurface : EDTSurface;
        var surf = new SurfClass(a.coordList, a.radiusList, a.indexList);
        var sd = surf.getSurface(p.type, p.probeRadius, p.scaleFactor, p.cutoff, true, p.smooth, p.contour);
        var transferList = [sd.position.buffer, sd.index.buffer];
        if (sd.normal)
            { transferList.push(sd.normal.buffer); }
        if (sd.atomindex)
            { transferList.push(sd.atomindex.buffer); }
        var data = {
            sd: sd,
            p: p
        };
        callback(data, transferList);
    }
}, [EDTSurface, AVSurface]);
/**
 * Create Molecular surfaces
 */
var MolecularSurface = function MolecularSurface(structure) {
    this.structure = structure;
};
MolecularSurface.prototype._getAtomData = function _getAtomData (params) {
    return this.structure.getAtomData({
        what: { position: true, radius: true, index: true },
        radiusParams: defaults(params.radiusParams, {
            type: 'vdw', scale: 1.0
        })
    });
};
MolecularSurface.prototype._makeSurface = function _makeSurface (sd, p) {
    var surface = new Surface(p.name, '', sd);
    surface.info.type = p.type;
    surface.info.probeRadius = p.probeRadius;
    surface.info.scaleFactor = p.scaleFactor;
    surface.info.smooth = p.smooth;
    surface.info.cutoff = p.cutoff;
    return surface;
};
/**
 * Get molecular surface
 * @param {MolecularSurfaceParameters} params - parameters for surface creation
 * @return {Surface} the surface
 */
MolecularSurface.prototype.getSurface = function getSurface (params) {
    var p = params || {};
    var atomData = this._getAtomData(params);
    var coordList = atomData.position;
    var radiusList = atomData.radius;
    var indexList = atomData.index;
    var SurfClass = (p.type === 'av') ? AVSurface : EDTSurface;
    var surf = new SurfClass(coordList, radiusList, indexList);
    var sd = surf.getSurface(p.type, p.probeRadius, p.scaleFactor, p.cutoff, true, p.smooth, p.contour);
    return this._makeSurface(sd, p);
};
/**
 * Get molecular surface asynchronous
 * @param {MolecularSurfaceParameters} params - parameters for surface creation
 * @param {function(surface: Surface)} callback - function to be called after surface is created
 * @return {undefined}
 */
MolecularSurface.prototype.getSurfaceWorker = function getSurfaceWorker (params, callback) {
        var this$1 = this;

    var p = Object.assign({}, params);
    if (window.hasOwnProperty('Worker')) {
        if (this.worker === undefined) {
            this.worker = new _Worker('molsurf');
        }
        var atomData = this._getAtomData(params);
        var coordList = atomData.position;
        var radiusList = atomData.radius;
        var indexList = atomData.index;
        var msg = {
            args: {
                coordList: coordList,
                radiusList: radiusList,
                indexList: indexList
            },
            params: p
        };
        var transferList = [
            coordList.buffer, radiusList.buffer, indexList.buffer
        ];
        this.worker.post(msg, transferList, function (e) {
            callback(this$1._makeSurface(e.data.sd, p));
        }, function (e) {
            console.warn('MolecularSurface.getSurfaceWorker error - trying without worker', e);
            this$1.worker.terminate();
            this$1.worker = undefined;
            var surface = this$1.getSurface(p);
            callback(surface);
        });
    }
    else {
        var surface = this.getSurface(p);
        callback(surface);
    }
};
/**
 * Cleanup
 * @return {undefined}
 */
MolecularSurface.prototype.dispose = function dispose () {
    if (this.worker)
        { this.worker.terminate(); }
};

/**
 * @file Molecular Surface Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Molecular Surface Representation
 */
var MolecularSurfaceRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function MolecularSurfaceRepresentation(structure, viewer, params) {
        var this$1 = this;

        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'surface';
        this.parameters = Object.assign({
            surfaceType: {
                type: 'select',
                rebuild: true,
                options: {
                    'vws': 'vws',
                    'sas': 'sas',
                    'ms': 'ms',
                    'ses': 'ses',
                    'av': 'av'
                }
            },
            probeRadius: {
                type: 'number',
                precision: 1,
                max: 20,
                min: 0,
                rebuild: true
            },
            smooth: {
                type: 'integer',
                precision: 1,
                max: 10,
                min: 0,
                rebuild: true
            },
            scaleFactor: {
                type: 'number',
                precision: 1,
                max: 5,
                min: 0,
                rebuild: true
            },
            cutoff: {
                type: 'number',
                precision: 2,
                max: 50,
                min: 0,
                rebuild: true
            },
            contour: {
                type: 'boolean', rebuild: true
            },
            background: {
                type: 'boolean', rebuild: true // FIXME
            },
            opaqueBack: {
                type: 'boolean', buffer: true
            },
            filterSele: {
                type: 'text', rebuild: true
            },
            colorVolume: {
                type: 'hidden'
            },
            useWorker: {
                type: 'boolean', rebuild: true
            }
        }, this.parameters, {
            radius: null,
            scale: null
        });
        this.__infoList = [];
        // TODO find a more direct way
        this.structure.signals.refreshed.add(function () {
            this$1.__forceNewMolsurf = true;
        });
        this.toBePrepared = true;
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) MolecularSurfaceRepresentation.__proto__ = StructureRepresentation$$1;
    MolecularSurfaceRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    MolecularSurfaceRepresentation.prototype.constructor = MolecularSurfaceRepresentation;
    MolecularSurfaceRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.colorScheme = defaults(p.colorScheme, 'uniform');
        p.colorValue = defaults(p.colorValue, 0xDDDDDD);
        p.disablePicking = defaults(p.disablePicking, true);
        this.surfaceType = defaults(p.surfaceType, 'ms');
        this.probeRadius = defaults(p.probeRadius, 1.4);
        this.smooth = defaults(p.smooth, 2);
        this.scaleFactor = defaults(p.scaleFactor, 2.0);
        this.cutoff = defaults(p.cutoff, 0.0);
        this.contour = defaults(p.contour, false);
        this.background = defaults(p.background, false);
        this.opaqueBack = defaults(p.opaqueBack, true);
        this.filterSele = defaults(p.filterSele, '');
        this.colorVolume = defaults(p.colorVolume, undefined);
        this.useWorker = defaults(p.useWorker, true);
        StructureRepresentation$$1.prototype.init.call(this, params);
    };
    MolecularSurfaceRepresentation.prototype.prepareData = function prepareData (sview, i, callback) {
        var info = this.__infoList[i];
        if (!info) {
            info = {};
            this.__infoList[i] = info;
        }
        if (!info.molsurf || info.sele !== sview.selection.string) {
            if (this.filterSele) {
                var sviewFilter = sview.structure.getView(new Selection(this.filterSele));
                var bbSize = sviewFilter.boundingBox.getSize(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]());
                var maxDim = Math.max(bbSize.x, bbSize.y, bbSize.z);
                var asWithin = sview.getAtomSetWithinPoint(sviewFilter.center, (maxDim / 2) + 6.0);
                sview = sview.getView(new Selection(sview.getAtomSetWithinSelection(asWithin, 3).toSeleString()));
                if (sview.atomCount === 0) {
                    callback(i);
                    return;
                }
            }
            info.sele = sview.selection.string;
            info.molsurf = new MolecularSurface(sview);
            var p = this.getSurfaceParams();
            var onSurfaceFinish = function (surface) {
                info.surface = surface;
                callback(i);
            };
            if (this.useWorker) {
                info.molsurf.getSurfaceWorker(p, onSurfaceFinish);
            }
            else {
                onSurfaceFinish(info.molsurf.getSurface(p));
            }
        }
        else {
            callback(i);
        }
    };
    MolecularSurfaceRepresentation.prototype.prepare = function prepare (callback) {
        var this$1 = this;

        if (this.__forceNewMolsurf || this.__sele !== this.selection.string ||
            this.__surfaceParams !== JSON.stringify(this.getSurfaceParams())) {
            this.__infoList.forEach(function (info) {
                if (info && info.molsurf) {
                    info.molsurf.dispose();
                }
            });
            this.__infoList.length = 0;
        }
        if (this.structureView.atomCount === 0) {
            callback();
            return;
        }
        var after = function () {
            this$1.__sele = this$1.selection.string;
            this$1.__surfaceParams = JSON.stringify(this$1.getSurfaceParams());
            this$1.__forceNewMolsurf = false;
            callback();
        };
        var name = this.assembly === 'default' ? this.defaultAssembly : this.assembly;
        var assembly = this.structure.biomolDict[name];
        if (assembly) {
            assembly.partList.forEach(function (part, i) {
                var sview = part.getView(this$1.structureView);
                this$1.prepareData(sview, i, function (_i) {
                    if (_i === assembly.partList.length - 1)
                        { after(); }
                });
            });
        }
        else {
            this.prepareData(this.structureView, 0, after);
        }
    };
    MolecularSurfaceRepresentation.prototype.createData = function createData (sview, i) {
        var info = this.__infoList[i];
        var surface = info.surface;
        if (!surface) {
            // Surface creation bailed (no surface generated for this sview)
            return;
        }
        var surfaceData = {
            position: surface.getPosition(),
            color: surface.getColor(this.getColorParams()),
            index: surface.getFilteredIndex(this.filterSele, sview)
        };
        var bufferList = [];
        if (surface.contour) {
            var contourBuffer = new ContourBuffer(surfaceData, this.getBufferParams({
                wireframe: false
            }));
            bufferList.push(contourBuffer);
        }
        else {
            Object.assign(surfaceData, {
                normal: surface.getNormal(),
                picking: surface.getPicking(sview.getStructure())
            });
            var surfaceBuffer = new SurfaceBuffer(surfaceData, this.getBufferParams({
                background: this.background,
                opaqueBack: this.opaqueBack,
                dullInterior: false
            }));
            if (this.getBufferParams().side == 'double') {
                var doubleSidedBuffer = new DoubleSidedBuffer(surfaceBuffer);
                bufferList.push(doubleSidedBuffer);
            }
            else {
                bufferList.push(surfaceBuffer);
            }
        }
        return { bufferList: bufferList, info: info };
    };
    MolecularSurfaceRepresentation.prototype.updateData = function updateData (what, data) {
        var surfaceData = {};
        if (what.position || what.radius) {
            this.__forceNewMolsurf = true;
            this.build();
            return;
        }
        if (what.color) {
            surfaceData.color = data.info.surface.getColor(this.getColorParams());
        }
        if (what.index) {
            surfaceData.index = data.info.surface.getFilteredIndex(this.filterSele, data.sview);
        }
        data.bufferList[0].setAttributes(surfaceData);
    };
    MolecularSurfaceRepresentation.prototype.setParameters = function setParameters (params, what, rebuild) {
        if ( what === void 0 ) what = {};

        if (params && params.filterSele) {
            what.index = true;
        }
        if (params && params.colorVolume !== undefined) {
            what.color = true;
        }
        // forbid setting wireframe to true when contour is true
        if (params && params.wireframe && (params.contour || (params.contour === undefined && this.contour))) {
            params.wireframe = false;
        }
        StructureRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        return this;
    };
    MolecularSurfaceRepresentation.prototype.getSurfaceParams = function getSurfaceParams (params) {
        if ( params === void 0 ) params = {};

        var p = 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()
        }, params);
        return p;
    };
    MolecularSurfaceRepresentation.prototype.getColorParams = function getColorParams () {
        var p = StructureRepresentation$$1.prototype.getColorParams.call(this);
        p.volume = this.colorVolume;
        return p;
    };
    MolecularSurfaceRepresentation.prototype.getAtomRadius = function getAtomRadius () {
        return 0;
    };
    MolecularSurfaceRepresentation.prototype.clear = function clear () {
        StructureRepresentation$$1.prototype.clear.call(this);
    };
    MolecularSurfaceRepresentation.prototype.dispose = function dispose () {
        this.__infoList.forEach(function (info) {
            if (info && info.molsurf) {
                info.molsurf.dispose();
            }
        });
        this.__infoList.length = 0;
        StructureRepresentation$$1.prototype.dispose.call(this);
    };

    return MolecularSurfaceRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('surface', MolecularSurfaceRepresentation);

/**
 * @file Point Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Point Representation
 */
var PointRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function PointRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'point';
        this.parameters = Object.assign({
            pointSize: {
                type: 'number', precision: 1, max: 100, min: 0, buffer: true
            },
            sizeAttenuation: {
                type: 'boolean', buffer: true
            },
            sortParticles: {
                type: 'boolean', rebuild: true
            },
            useTexture: {
                type: 'boolean', buffer: true
            },
            alphaTest: {
                type: 'range', step: 0.001, max: 1, min: 0, buffer: true
            },
            forceTransparent: {
                type: 'boolean', buffer: true
            },
            edgeBleach: {
                type: 'range', step: 0.001, max: 1, min: 0, buffer: true
            }
        }, this.parameters, {
            flatShaded: null,
            wireframe: null,
            linewidth: null,
            side: null,
            roughness: null,
            metalness: null
        });
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) PointRepresentation.__proto__ = StructureRepresentation$$1;
    PointRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    PointRepresentation.prototype.constructor = PointRepresentation;
    PointRepresentation.prototype.init = function init (params) {
        var p = params || {};
        this.pointSize = defaults(p.pointSize, 1);
        this.sizeAttenuation = defaults(p.sizeAttenuation, true);
        this.sortParticles = defaults(p.sortParticles, false);
        this.useTexture = defaults(p.useTexture, false);
        this.alphaTest = defaults(p.alphaTest, 0.5);
        this.forceTransparent = defaults(p.forceTransparent, false);
        this.edgeBleach = defaults(p.edgeBleach, 0.0);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    PointRepresentation.prototype.createData = function createData (sview) {
        var what = { position: true, color: true, picking: true };
        var atomData = sview.getAtomData(this.getAtomParams(what));
        var pointBuffer = new PointBuffer(atomData, this.getBufferParams({
            pointSize: this.pointSize,
            sizeAttenuation: this.sizeAttenuation,
            sortParticles: this.sortParticles,
            useTexture: this.useTexture,
            alphaTest: this.alphaTest,
            forceTransparent: this.forceTransparent,
            edgeBleach: this.edgeBleach
        }));
        return {
            bufferList: [pointBuffer]
        };
    };
    PointRepresentation.prototype.updateData = function updateData (what, data) {
        var atomData = data.sview.getAtomData(this.getAtomParams(what));
        var pointData = {};
        if (!what || what.position) {
            Object.assign(pointData, { position: atomData.position });
        }
        if (!what || what.color) {
            Object.assign(pointData, { color: atomData.color });
        }
        data.bufferList[0].setAttributes(pointData);
    };
    PointRepresentation.prototype.getAtomRadius = function getAtomRadius () {
        return 0.1;
    };

    return PointRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('point', PointRepresentation);

ShaderRegistry.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}");

/**
 * @file Ribbon Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var quadIndices$1 = new Uint16Array([
    0, 1, 2,
    1, 3, 2
]);
function getSize$1(data) {
    var n = (data.position.length / 3) - 1;
    var n4 = n * 4;
    var x = n4 * 3;
    return x;
}
/**
 * Ribbon buffer. Draws a thin ribbon.
 */
var RibbonBuffer = /*@__PURE__*/(function (MeshBuffer$$1) {
    function RibbonBuffer(data, params) {
        if ( params === void 0 ) params = {};

        MeshBuffer$$1.call(this, {
            position: new Float32Array(getSize$1(data)),
            color: new Float32Array(getSize$1(data)),
            index: getUintArray(getSize$1(data), getSize$1(data) / 3),
            normal: new Float32Array(getSize$1(data)),
            picking: data.picking
        }, params);
        this.vertexShader = 'Ribbon.vert';
        var n = (data.position.length / 3) - 1;
        var n4 = n * 4;
        var x = n4 * 3;
        this.addAttributes({
            'dir': { type: 'v3', value: new Float32Array(x) }
        });
        this.addAttributes({
            'size': { type: 'f', value: new Float32Array(n4) }
        });
        data.primitiveId = serialArray(n);
        this.setAttributes(data);
        this.makeIndex();
    }

    if ( MeshBuffer$$1 ) RibbonBuffer.__proto__ = MeshBuffer$$1;
    RibbonBuffer.prototype = Object.create( MeshBuffer$$1 && MeshBuffer$$1.prototype );
    RibbonBuffer.prototype.constructor = RibbonBuffer;
    RibbonBuffer.prototype.setAttributes = function setAttributes (data) {
        if ( data === void 0 ) data = {};

        var n4 = this.size;
        var n = n4 / 4;
        var attributes = this.geometry.attributes; // TODO
        var position, normal, size, dir, color, primitiveId;
        var aPosition, aNormal, aSize, aDir, aColor, aPrimitiveId;
        if (data.position) {
            position = data.position;
            aPosition = attributes.position.array;
            attributes.position.needsUpdate = true;
        }
        if (data.normal) {
            normal = data.normal;
            aNormal = attributes.normal.array;
            attributes.normal.needsUpdate = true;
        }
        if (data.size) {
            size = data.size;
            aSize = attributes.size.array;
            attributes.size.needsUpdate = true;
        }
        if (data.dir) {
            dir = data.dir;
            aDir = attributes.dir.array;
            attributes.dir.needsUpdate = true;
        }
        if (data.color) {
            color = data.color;
            aColor = attributes.color.array;
            attributes.color.needsUpdate = true;
        }
        if (data.primitiveId) {
            primitiveId = data.primitiveId;
            aPrimitiveId = attributes.primitiveId.array;
            attributes.primitiveId.needsUpdate = true;
        }
        var v, i, k, p, l, v3;
        var currSize;
        var prevSize = size ? size[0] : null;
        for (v = 0; v < n; ++v) {
            v3 = v * 3;
            k = v * 3 * 4;
            l = v * 4;
            if (position) {
                aPosition[k] = aPosition[k + 3] = position[v3];
                aPosition[k + 1] = aPosition[k + 4] = position[v3 + 1];
                aPosition[k + 2] = aPosition[k + 5] = position[v3 + 2];
                aPosition[k + 6] = aPosition[k + 9] = position[v3 + 3];
                aPosition[k + 7] = aPosition[k + 10] = position[v3 + 4];
                aPosition[k + 8] = aPosition[k + 11] = position[v3 + 5];
            }
            if (normal) {
                aNormal[k] = aNormal[k + 3] = -normal[v3];
                aNormal[k + 1] = aNormal[k + 4] = -normal[v3 + 1];
                aNormal[k + 2] = aNormal[k + 5] = -normal[v3 + 2];
                aNormal[k + 6] = aNormal[k + 9] = -normal[v3 + 3];
                aNormal[k + 7] = aNormal[k + 10] = -normal[v3 + 4];
                aNormal[k + 8] = aNormal[k + 11] = -normal[v3 + 5];
            }
            for (i = 0; i < 4; ++i) {
                p = k + 3 * i;
                if (color) {
                    aColor[p] = color[v3];
                    aColor[p + 1] = color[v3 + 1];
                    aColor[p + 2] = color[v3 + 2];
                }
                if (primitiveId) {
                    aPrimitiveId[l + i] = primitiveId[v];
                }
            }
            if (size) {
                currSize = size[v];
                if (prevSize !== size[v]) {
                    aSize[l] = prevSize;
                    aSize[l + 1] = prevSize;
                    aSize[l + 2] = currSize;
                    aSize[l + 3] = currSize;
                }
                else {
                    aSize[l] = currSize;
                    aSize[l + 1] = currSize;
                    aSize[l + 2] = currSize;
                    aSize[l + 3] = currSize;
                }
                prevSize = currSize;
            }
            if (dir) {
                aDir[k] = dir[v3];
                aDir[k + 1] = dir[v3 + 1];
                aDir[k + 2] = dir[v3 + 2];
                aDir[k + 3] = -dir[v3];
                aDir[k + 4] = -dir[v3 + 1];
                aDir[k + 5] = -dir[v3 + 2];
                aDir[k + 6] = dir[v3 + 3];
                aDir[k + 7] = dir[v3 + 4];
                aDir[k + 8] = dir[v3 + 5];
                aDir[k + 9] = -dir[v3 + 3];
                aDir[k + 10] = -dir[v3 + 4];
                aDir[k + 11] = -dir[v3 + 5];
            }
        }
    };
    RibbonBuffer.prototype.makeIndex = function makeIndex () {
        var index = this.geometry.getIndex();
        if (!index) {
            Log.error('Index is null');
            return;
        }
        var meshIndex = index.array;
        var n = meshIndex.length / 4 / 3;
        for (var v = 0; v < n; ++v) {
            var ix = v * 6;
            var it = v * 4;
            meshIndex.set(quadIndices$1, ix);
            for (var s = 0; s < 6; ++s) {
                meshIndex[ix + s] += it;
            }
        }
    };

    return RibbonBuffer;
}(MeshBuffer));

/**
 * @file Ribbon Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Ribbon Representation
 */
var RibbonRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function RibbonRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'ribbon';
        this.parameters = Object.assign({
            subdiv: {
                type: 'integer', max: 50, min: 1, rebuild: true
            },
            tension: {
                type: 'number', precision: 1, max: 1.0, min: 0.1
            },
            smoothSheet: {
                type: 'boolean', rebuild: true
            }
        }, this.parameters, {
            side: null,
            wireframe: null,
            linewidth: null
        });
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) RibbonRepresentation.__proto__ = StructureRepresentation$$1;
    RibbonRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    RibbonRepresentation.prototype.constructor = RibbonRepresentation;
    RibbonRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.colorScheme = defaults(p.colorScheme, 'chainname');
        p.colorScale = defaults(p.colorScale, 'RdYlBu');
        p.radiusType = defaults(p.radiusType, 'sstruc');
        p.radiusScale = defaults(p.radiusScale, 4.0);
        if (p.quality === 'low') {
            this.subdiv = 3;
        }
        else if (p.quality === 'medium') {
            this.subdiv = 6;
        }
        else if (p.quality === 'high') {
            this.subdiv = 12;
        }
        else {
            this.subdiv = defaults(p.subdiv, 6);
        }
        this.tension = defaults(p.tension, NaN);
        this.smoothSheet = defaults(p.smoothSheet, false);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    RibbonRepresentation.prototype.getSplineParams = function getSplineParams (params) {
        return Object.assign({
            subdiv: this.subdiv,
            tension: this.tension,
            directional: true,
            smoothSheet: this.smoothSheet
        }, params);
    };
    RibbonRepresentation.prototype.getAtomRadius = function getAtomRadius (atom) {
        return atom.isTrace() ? StructureRepresentation$$1.prototype.getAtomRadius.call(this, atom) : 0;
    };
    RibbonRepresentation.prototype.createData = function createData (sview) {
        var this$1 = this;

        var bufferList = [];
        var polymerList = [];
        this.structure.eachPolymer(function (polymer) {
            if (polymer.residueCount < 4)
                { return; }
            polymerList.push(polymer);
            var spline = new Spline(polymer, this$1.getSplineParams());
            var subPos = spline.getSubdividedPosition();
            var subOri = spline.getSubdividedOrientation();
            var subCol = spline.getSubdividedColor(this$1.getColorParams());
            var subPick = spline.getSubdividedPicking();
            var subSize = spline.getSubdividedSize(this$1.getRadiusParams());
            bufferList.push(new RibbonBuffer(({
                position: subPos.position,
                normal: subOri.binormal,
                dir: subOri.normal,
                color: subCol.color,
                size: subSize.size,
                picking: subPick.picking
            }), this$1.getBufferParams()));
        }, sview.getSelection());
        return {
            bufferList: bufferList,
            polymerList: polymerList
        };
    };
    RibbonRepresentation.prototype.updateData = function updateData (what, data) {
        what = what || {};
        var i = 0;
        var n = data.polymerList.length;
        for (i = 0; i < n; ++i) {
            var bufferData = {};
            var spline = new Spline(data.polymerList[i], this.getSplineParams());
            if (what.position) {
                var subPos = spline.getSubdividedPosition();
                var subOri = spline.getSubdividedOrientation();
                Object.assign(bufferData, {
                    position: subPos.position,
                    normal: subOri.binormal,
                    dir: subOri.normal
                });
            }
            if (what.radius || what.scale) {
                var subSize = spline.getSubdividedSize(this.getRadiusParams());
                Object.assign(bufferData, { size: subSize.size });
            }
            if (what.color) {
                var subCol = spline.getSubdividedColor(this.getColorParams());
                Object.assign(bufferData, { color: subCol.color });
            }
            data.bufferList[i].setAttributes(bufferData);
        }
    };
    RibbonRepresentation.prototype.setParameters = function setParameters (params) {
        var rebuild = false;
        var what = {};
        if (params && params.tension) {
            Object.assign(what, { position: true });
        }
        StructureRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        return this;
    };

    return RibbonRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('ribbon', RibbonRepresentation);

/**
 * @file Rocket Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Rocket Representation
 */
var RocketRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function RocketRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'rocket';
        this.parameters = Object.assign({
            localAngle: {
                type: 'integer', max: 180, min: 0, rebuild: true
            },
            centerDist: {
                type: 'number', precision: 1, max: 10, min: 0, rebuild: true
            },
            ssBorder: {
                type: 'boolean', rebuild: true
            },
            radialSegments: true,
            openEnded: true,
            disableImpostor: true
        }, this.parameters);
        // this.helixbundleList = []
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) RocketRepresentation.__proto__ = StructureRepresentation$$1;
    RocketRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    RocketRepresentation.prototype.constructor = RocketRepresentation;
    RocketRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.colorScheme = defaults(p.colorScheme, 'sstruc');
        p.radiusSize = defaults(p.radiusSize, 1.5);
        p.radiusScale = defaults(p.radiusScale, 1.0);
        p.openEnded = defaults(p.openEnded, false);
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        this.localAngle = defaults(p.localAngle, 30);
        this.centerDist = defaults(p.centerDist, 2.5);
        this.ssBorder = defaults(p.ssBorder, false);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    RocketRepresentation.prototype.createData = function createData (sview) {
        var this$1 = this;

        var length = 0;
        var axisList = [];
        var helixbundleList = [];
        this.structure.eachPolymer(function (polymer) {
            if (polymer.residueCount < 4 || polymer.isNucleic())
                { return; }
            var helixbundle = new Helixbundle(polymer);
            var axis = helixbundle.getAxis(this$1.localAngle, this$1.centerDist, this$1.ssBorder, this$1.getColorParams(), this$1.getRadiusParams());
            length += axis.size.length;
            axisList.push(axis);
            helixbundleList.push(helixbundle);
        }, sview.getSelection());
        var axisData = {
            begin: new Float32Array(length * 3),
            end: new Float32Array(length * 3),
            size: new Float32Array(length),
            color: new Float32Array(length * 3),
            picking: {}
        };
        var picking = new Float32Array(length);
        var offset = 0;
        axisList.forEach(function (axis) {
            axisData.begin.set(axis.begin, offset * 3);
            axisData.end.set(axis.end, offset * 3);
            axisData.size.set(axis.size, offset);
            axisData.color.set(axis.color, offset * 3);
            picking.set(axis.picking.array, offset);
            offset += axis.size.length;
        });
        if (length) {
            axisData.picking = new AtomPicker(picking, sview.getStructure());
        }
        var cylinderBuffer = new CylinderBuffer({
            position1: axisData.begin,
            position2: axisData.end,
            color: axisData.color,
            color2: axisData.color,
            radius: axisData.size,
            picking: axisData.picking
        }, this.getBufferParams({
            openEnded: this.openEnded,
            radialSegments: this.radialSegments,
            disableImpostor: this.disableImpostor,
            dullInterior: true
        }));
        return {
            bufferList: [cylinderBuffer],
            axisList: axisList,
            helixbundleList: helixbundleList,
            axisData: axisData
        };
    };
    RocketRepresentation.prototype.updateData = function updateData (what, data) {
        var this$1 = this;

        what = what || {};
        if (what.position) {
            this.build();
            return;
        }
        var cylinderData = {};
        if (what.color || what.radius) {
            var offset = 0;
            data.helixbundleList.forEach(function (helixbundle) {
                var axis = helixbundle.getAxis(this$1.localAngle, this$1.centerDist, this$1.ssBorder, this$1.getColorParams(), this$1.getRadiusParams());
                if (what.color) {
                    data.axisData.color.set(axis.color, offset * 3);
                }
                if (what.radius || what.scale) {
                    data.axisData.size.set(axis.size, offset);
                }
                offset += axis.size.length;
            });
            if (what.color) {
                Object.assign(cylinderData, {
                    color: data.axisData.color,
                    color2: data.axisData.color
                });
            }
            if (what.radius || what.scale) {
                Object.assign(cylinderData, {
                    radius: data.axisData.size
                });
            }
        }
        data.bufferList[0].setAttributes(cylinderData);
    };

    return RocketRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('rocket', RocketRepresentation);

/**
 * @file Rope Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Rope Representation
 */
var RopeRepresentation = /*@__PURE__*/(function (CartoonRepresentation$$1) {
    function RopeRepresentation(structure, viewer, params) {
        CartoonRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'rope';
        this.parameters = Object.assign({
            smooth: {
                type: 'integer', max: 15, min: 0, rebuild: true
            }
        }, this.parameters, {
            aspectRatio: null,
            smoothSheet: null
        });
    }

    if ( CartoonRepresentation$$1 ) RopeRepresentation.__proto__ = CartoonRepresentation$$1;
    RopeRepresentation.prototype = Object.create( CartoonRepresentation$$1 && CartoonRepresentation$$1.prototype );
    RopeRepresentation.prototype.constructor = RopeRepresentation;
    RopeRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.aspectRatio = 1.0;
        p.tension = defaults(p.tension, 0.5);
        p.radiusScale = defaults(p.radiusScale, 5.0);
        p.smoothSheet = false;
        this.smooth = defaults(p.smooth, 2);
        CartoonRepresentation$$1.prototype.init.call(this, p);
    };
    RopeRepresentation.prototype.getSpline = function getSpline (polymer) {
        var helixorient = new Helixorient(polymer);
        return new Spline(polymer, this.getSplineParams({
            directional: false,
            positionIterator: helixorient.getCenterIterator(this.smooth)
        }));
    };

    return RopeRepresentation;
}(CartoonRepresentation));
RepresentationRegistry.add('rope', RopeRepresentation);

/**
 * @file Spacefill Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Spacefill Representation
 */
var SpacefillRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function SpacefillRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'spacefill';
        this.parameters = Object.assign({
            sphereDetail: true,
            disableImpostor: true
        }, this.parameters);
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) SpacefillRepresentation.__proto__ = StructureRepresentation$$1;
    SpacefillRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    SpacefillRepresentation.prototype.constructor = SpacefillRepresentation;
    SpacefillRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    SpacefillRepresentation.prototype.createData = function createData (sview) {
        var sphereBuffer = new SphereBuffer(sview.getAtomData(this.getAtomParams()), this.getBufferParams({
            sphereDetail: this.sphereDetail,
            dullInterior: true,
            disableImpostor: this.disableImpostor
        }));
        return {
            bufferList: [sphereBuffer]
        };
    };
    SpacefillRepresentation.prototype.updateData = function updateData (what, data) {
        var atomData = data.sview.getAtomData(this.getAtomParams(what));
        var sphereData = {};
        if (!what || what.position) {
            Object.assign(sphereData, { position: atomData.position });
        }
        if (!what || what.color) {
            Object.assign(sphereData, { color: atomData.color });
        }
        if (!what || what.radius) {
            Object.assign(sphereData, { radius: atomData.radius });
        }
        data.bufferList[0].setAttributes(sphereData);
    };

    return SpacefillRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('spacefill', SpacefillRepresentation);

/**
 * @file Trace Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getSize$2(data) {
    var n = data.position.length / 3;
    var n1 = n - 1;
    return n1 * 3 * 2;
}
/**
 * Trace buffer. Draws a series of lines.
 */
var TraceBuffer = /*@__PURE__*/(function (Buffer$$1) {
    function TraceBuffer(data, params) {
        if ( params === void 0 ) params = {};

        Buffer$$1.call(this, {
            position: new Float32Array(getSize$2(data)),
            color: new Float32Array(getSize$2(data))
        }, params);
        this.isLine = true;
        this.vertexShader = 'Line.vert';
        this.fragmentShader = 'Line.frag';
        this.setAttributes(data);
    }

    if ( Buffer$$1 ) TraceBuffer.__proto__ = Buffer$$1;
    TraceBuffer.prototype = Object.create( Buffer$$1 && Buffer$$1.prototype );
    TraceBuffer.prototype.constructor = TraceBuffer;
    TraceBuffer.prototype.setAttributes = function setAttributes (data) {
        var position, color;
        var linePosition, lineColor;
        var attributes = this.geometry.attributes; // TODO
        if (data.position) {
            position = data.position;
            linePosition = attributes.position.array;
            attributes.position.needsUpdate = true;
        }
        if (data.color) {
            color = data.color;
            lineColor = attributes.color.array;
            attributes.color.needsUpdate = true;
        }
        if (!position && !color) {
            Log.warn('TraceBuffer.prototype.setAttributes no data');
            return;
        }
        var v, v2;
        var n = this.size;
        var n1 = n - 1;
        for (var i = 0; i < n1; ++i) {
            v = 3 * i;
            v2 = 3 * i * 2;
            if (position) {
                linePosition[v2] = position[v];
                linePosition[v2 + 1] = position[v + 1];
                linePosition[v2 + 2] = position[v + 2];
                linePosition[v2 + 3] = position[v + 3];
                linePosition[v2 + 4] = position[v + 4];
                linePosition[v2 + 5] = position[v + 5];
            }
            if (color) {
                lineColor[v2] = color[v];
                lineColor[v2 + 1] = color[v + 1];
                lineColor[v2 + 2] = color[v + 2];
                lineColor[v2 + 3] = color[v + 3];
                lineColor[v2 + 4] = color[v + 4];
                lineColor[v2 + 5] = color[v + 5];
            }
        }
    };

    return TraceBuffer;
}(Buffer));

/**
 * @file Trace Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Trace Representation
 */
var TraceRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function TraceRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'trace';
        this.parameters = Object.assign({
            subdiv: {
                type: 'integer', max: 50, min: 1, rebuild: true
            },
            tension: {
                type: 'number', precision: 1, max: 1.0, min: 0.1
            },
            smoothSheet: {
                type: 'boolean', rebuild: true
            }
        }, this.parameters, {
            flatShaded: null,
            side: null,
            wireframe: null
        });
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) TraceRepresentation.__proto__ = StructureRepresentation$$1;
    TraceRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    TraceRepresentation.prototype.constructor = TraceRepresentation;
    TraceRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.colorScheme = defaults(p.colorScheme, 'chainname');
        p.colorScale = defaults(p.colorScale, 'RdYlBu');
        if (p.quality === 'low') {
            this.subdiv = 3;
        }
        else if (p.quality === 'medium') {
            this.subdiv = 6;
        }
        else if (p.quality === 'high') {
            this.subdiv = 12;
        }
        else {
            this.subdiv = defaults(p.subdiv, 6);
        }
        this.tension = defaults(p.tension, NaN);
        this.smoothSheet = defaults(p.smoothSheet, false);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    TraceRepresentation.prototype.getSplineParams = function getSplineParams (params) {
        return Object.assign({
            subdiv: this.subdiv,
            tension: this.tension,
            directional: false,
            smoothSheet: this.smoothSheet
        }, params);
    };
    TraceRepresentation.prototype.getAtomRadius = function getAtomRadius (atom) {
        return atom.isTrace() ? 0.1 : 0;
    };
    TraceRepresentation.prototype.createData = function createData (sview) {
        var this$1 = this;

        var bufferList = [];
        var polymerList = [];
        this.structure.eachPolymer(function (polymer) {
            if (polymer.residueCount < 4)
                { return; }
            polymerList.push(polymer);
            var spline = new Spline(polymer, this$1.getSplineParams());
            var subPos = spline.getSubdividedPosition();
            var subCol = spline.getSubdividedColor(this$1.getColorParams());
            bufferList.push(new TraceBuffer(Object.assign({}, subPos, subCol), this$1.getBufferParams()));
        }, sview.getSelection());
        return {
            bufferList: bufferList,
            polymerList: polymerList
        };
    };
    TraceRepresentation.prototype.updateData = function updateData (what, data) {
        what = what || {};
        var i = 0;
        var n = data.polymerList.length;
        for (i = 0; i < n; ++i) {
            var bufferData = {};
            var spline = new Spline(data.polymerList[i], this.getSplineParams());
            if (what.position) {
                var subPos = spline.getSubdividedPosition();
                Object.assign(bufferData, { position: subPos.position });
            }
            if (what.color) {
                var subCol = spline.getSubdividedColor(this.getColorParams());
                Object.assign(bufferData, { color: subCol.color });
            }
            data.bufferList[i].setAttributes(bufferData);
        }
    };
    TraceRepresentation.prototype.setParameters = function setParameters (params) {
        var rebuild = false;
        var what = {};
        if (params && params.tension) {
            Object.assign(what, { position: true });
        }
        StructureRepresentation$$1.prototype.setParameters.call(this, params, what, rebuild);
        return this;
    };

    return TraceRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('trace', TraceRepresentation);

/**
 * @file Tube Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Tube Representation
 */
var TubeRepresentation = /*@__PURE__*/(function (CartoonRepresentation$$1) {
    function TubeRepresentation(structure, viewer, params) {
        CartoonRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'tube';
        this.parameters = Object.assign({}, this.parameters, { aspectRatio: null });
    }

    if ( CartoonRepresentation$$1 ) TubeRepresentation.__proto__ = CartoonRepresentation$$1;
    TubeRepresentation.prototype = Object.create( CartoonRepresentation$$1 && CartoonRepresentation$$1.prototype );
    TubeRepresentation.prototype.constructor = TubeRepresentation;
    TubeRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.aspectRatio = 1.0;
        p.radiusScale = defaults(p.radiusScale, 2.0);
        if (p.quality === 'low') {
            this.radialSegments = 5;
        }
        CartoonRepresentation$$1.prototype.init.call(this, p);
    };
    TubeRepresentation.prototype.getSplineParams = function getSplineParams ( /* params */) {
        return CartoonRepresentation$$1.prototype.getSplineParams.call(this, {
            directional: false
        });
    };

    return TubeRepresentation;
}(CartoonRepresentation));
RepresentationRegistry.add('tube', TubeRepresentation);

/**
 * @file Unitcell Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Unitcell Representation
 */
var UnitcellRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function UnitcellRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'unitcell';
        this.parameters = Object.assign({
            radiusSize: {
                type: 'number', precision: 3, max: 10.0, min: 0.001
            },
            sphereDetail: true,
            radialSegments: true,
            disableImpostor: true
        }, this.parameters, {
            assembly: null
        });
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) UnitcellRepresentation.__proto__ = StructureRepresentation$$1;
    UnitcellRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    UnitcellRepresentation.prototype.constructor = UnitcellRepresentation;
    UnitcellRepresentation.prototype.init = function init (params) {
        var p = params || {};
        var defaultRadius = 0.5;
        if (this.structure.unitcell) {
            defaultRadius = Math.cbrt(this.structure.unitcell.volume) / 200;
        }
        p.radiusSize = defaults(p.radiusSize, defaultRadius);
        p.colorValue = defaults(p.colorValue, 'orange');
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    UnitcellRepresentation.prototype.getUnitcellData = function getUnitcellData (structure) {
        return structure.unitcell.getData(structure);
    };
    UnitcellRepresentation.prototype.create = function create () {
        var structure = this.structureView.getStructure();
        if (!structure.unitcell)
            { return; }
        var unitcellData = this.getUnitcellData(structure);
        this.sphereBuffer = new SphereBuffer(unitcellData.vertex, this.getBufferParams({
            sphereDetail: this.sphereDetail,
            disableImpostor: this.disableImpostor,
            dullInterior: true
        }));
        this.cylinderBuffer = new CylinderBuffer(unitcellData.edge, this.getBufferParams({
            openEnded: true,
            radialSegments: this.radialSegments,
            disableImpostor: this.disableImpostor,
            dullInterior: true
        }));
        this.dataList.push({
            sview: this.structureView,
            bufferList: [this.sphereBuffer, this.cylinderBuffer]
        });
    };
    UnitcellRepresentation.prototype.createData = function createData (sview) {
        return;
    };
    UnitcellRepresentation.prototype.updateData = function updateData (what, data) {
        var structure = data.sview.getStructure();
        if (!structure.unitcell)
            { return; }
        var unitcellData = this.getUnitcellData(structure);
        var sphereData = {};
        var cylinderData = {};
        if (!what || what.position) {
            Object.assign(sphereData, { position: unitcellData.vertex.position });
            Object.assign(cylinderData, {
                position1: unitcellData.edge.position1,
                position2: unitcellData.edge.position2
            });
        }
        if (!what || what.color) {
            Object.assign(sphereData, { color: unitcellData.vertex.color });
            Object.assign(cylinderData, {
                color: unitcellData.edge.color,
                color2: unitcellData.edge.color2
            });
        }
        if (!what || what.radius) {
            Object.assign(sphereData, { radius: unitcellData.vertex.radius });
            Object.assign(cylinderData, { radius: unitcellData.edge.radius });
        }
        this.sphereBuffer.setAttributes(sphereData);
        this.cylinderBuffer.setAttributes(cylinderData);
    };

    return UnitcellRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('unitcell', UnitcellRepresentation);

/**
 * @file Validation Representation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Validation representation
 */
var ValidationRepresentation = /*@__PURE__*/(function (StructureRepresentation$$1) {
    function ValidationRepresentation(structure, viewer, params) {
        StructureRepresentation$$1.call(this, structure, viewer, params);
        this.type = 'validation';
        this.parameters = Object.assign({}, this.parameters, {
            radiusType: null,
            radiusSize: null,
            radiusScale: null
        });
        this.init(params);
    }

    if ( StructureRepresentation$$1 ) ValidationRepresentation.__proto__ = StructureRepresentation$$1;
    ValidationRepresentation.prototype = Object.create( StructureRepresentation$$1 && StructureRepresentation$$1.prototype );
    ValidationRepresentation.prototype.constructor = ValidationRepresentation;
    ValidationRepresentation.prototype.init = function init (params) {
        var p = params || {};
        p.colorValue = defaults(p.colorValue, '#f0027f');
        p.useInteriorColor = defaults(p.useInteriorColor, true);
        StructureRepresentation$$1.prototype.init.call(this, p);
    };
    ValidationRepresentation.prototype.createData = function createData (sview) {
        if (!sview.validation)
            { return; }
        var clashData = sview.validation.getClashData({
            structure: sview,
            color: this.colorValue
        });
        var cylinderBuffer = new CylinderBuffer(clashData, this.getBufferParams({ openEnded: false }));
        return {
            bufferList: [cylinderBuffer]
        };
    };

    return ValidationRepresentation;
}(StructureRepresentation));
RepresentationRegistry.add('validation', ValidationRepresentation);

/**
 * @file Cone Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var scale$3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var eye$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var target$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var up$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 1, 0);
function getGeo$1(params) {
    if ( params === void 0 ) params = {};

    var geo = new __WEBPACK_IMPORTED_MODULE_0_three__["j" /* ConeBufferGeometry */](1, // radius
    1, // height
    defaults(params.radialSegments, 60), // radialSegments
    1, // heightSegments
    defaults(params.openEnded, false) // openEnded
    );
    geo.applyMatrix4(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeRotationX(-Math.PI / 2));
    return geo;
}
var ConeBufferDefaultParameters = Object.assign({
    radialSegments: 60,
    openEnded: false
}, BufferDefaultParameters);
/**
 * Cone geometry buffer.
 *
 * @example
 * var coneBuffer = new ConeBuffer({
 *   position1: new Float32Array([ 0, 0, 0 ]),
 *   position2: new Float32Array([ 1, 1, 1 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   color2: new Float32Array([ 0, 1, 0 ]),
 *   radius: new Float32Array([ 1 ])
 * });
 */
var ConeBuffer = /*@__PURE__*/(function (GeometryBuffer$$1) {
    function ConeBuffer(data, params) {
        if ( params === void 0 ) params = {};

        GeometryBuffer$$1.call(this, {
            position: new Float32Array(data.position1.length),
            color: data.color,
            picking: data.picking
        }, params, getGeo$1(params));
        this.updateNormals = true;
        this._position = new Float32Array(data.position1.length);
        this.setAttributes(data, true);
    }

    if ( GeometryBuffer$$1 ) ConeBuffer.__proto__ = GeometryBuffer$$1;
    ConeBuffer.prototype = Object.create( GeometryBuffer$$1 && GeometryBuffer$$1.prototype );
    ConeBuffer.prototype.constructor = ConeBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return ConeBufferDefaultParameters; };
    ConeBuffer.prototype.applyPositionTransform = function applyPositionTransform (matrix, i, i3) {
        eye$1.fromArray(this._position1, i3);
        target$1.fromArray(this._position2, i3);
        matrix.lookAt(eye$1, target$1, up$1);
        var r = this._radius[i];
        scale$3.set(r, r, eye$1.distanceTo(target$1));
        matrix.scale(scale$3);
    };
    ConeBuffer.prototype.setAttributes = function setAttributes (data, initNormals) {
        if ( data === void 0 ) data = {};

        if (data.position1 && data.position2) {
            calculateCenterArray(data.position1, data.position2, this._position);
            this._position1 = data.position1;
            this._position2 = data.position2;
            data.position = this._position;
        }
        if (data.radius)
            { this._radius = data.radius; }
        GeometryBuffer$$1.prototype.setAttributes.call(this, data, initNormals);
    };

    Object.defineProperties( ConeBuffer.prototype, prototypeAccessors );

    return ConeBuffer;
}(GeometryBuffer));
BufferRegistry.add('cone', ConeBuffer);

/**
 * @file Geometry Group
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var GeometryGroup = function GeometryGroup(geometryList) {
    if ( geometryList === void 0 ) geometryList = [];

    this.geometryList = geometryList;
};
GeometryGroup.prototype.computeBoundingBox = function computeBoundingBox () {
        var this$1 = this;

    if (!this.boundingBox) {
        this.boundingBox = new __WEBPACK_IMPORTED_MODULE_0_three__["d" /* Box3 */]();
    }
    else {
        this.boundingBox.empty();
    }
    this.geometryList.forEach(function (geo) {
        if (!geo.boundingBox)
            { geo.computeBoundingBox(); }
        this$1.boundingBox.union(geo.boundingBox);
    });
};

/**
 * @file Arrow Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var ArrowBufferDefaultParameters = Object.assign({
    aspectRatio: 1.5,
    radialSegments: 50,
    openEnded: false,
    disableImpostor: false
}, BufferDefaultParameters);
/**
 * Arrow buffer. Draws arrows made from a cylinder and a cone.
 * @implements {Buffer}
 *
 * @example
 * var arrowBuffer = new ArrowBuffer({
 *   position1: new Float32Array([ 0, 0, 0 ]),
 *   position2: new Float32Array([ 10, 1, 1 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   radius: new Float32Array([ 1 ])
 * });
 */
var ArrowBuffer = function ArrowBuffer(data, params) {
    if ( params === void 0 ) params = {};

    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 = true;
    this.parameters = createParams(params, this.defaultParameters);
    this.splitPosition = new Float32Array(data.position1.length);
    this.cylinderRadius = new Float32Array(data.radius.length);
    var attr = this.makeAttributes(data);
    var bufferParams = {
        radialSegments: this.parameters.radialSegments,
        openEnded: this.parameters.openEnded,
        disableImpostor: this.parameters.disableImpostor
    };
    this.cylinderBuffer = new CylinderBuffer(attr.cylinder, bufferParams);
    this.coneBuffer = new ConeBuffer(attr.cone, bufferParams);
    this.geometry = new GeometryGroup([
        this.cylinderBuffer.geometry,
        this.coneBuffer.geometry
    ]);
    // requires Group objects to be present
    this.matrix = defaults(params.matrix, new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]());
    this.picking = data.picking;
};

var prototypeAccessors$v = { defaultParameters: { configurable: true },matrix: { configurable: true },pickable: { configurable: true } };
prototypeAccessors$v.defaultParameters.get = function () { return ArrowBufferDefaultParameters; };
prototypeAccessors$v.matrix.set = function (m) {
    Buffer.prototype.setMatrix.call(this, m);
};
prototypeAccessors$v.matrix.get = function () {
    return this.group.matrix.clone();
};
prototypeAccessors$v.pickable.get = function () {
    return !!this.picking;
};
ArrowBuffer.prototype.makeAttributes = function makeAttributes (data) {
        if ( data === void 0 ) data = {};

    var splitPosition = this.splitPosition;
    var cylinderRadius = this.cylinderRadius;
    var aspectRatio = this.parameters.aspectRatio;
    var i, il;
    var cylinder = {};
    var cone = {};
    if (data.radius) {
        for (i = 0, il = cylinderRadius.length; i < il; ++i) {
            cylinderRadius[i] = data.radius[i] / aspectRatio;
        }
        cylinder.radius = cylinderRadius;
        cone.radius = data.radius;
    }
    if (data.position1 && data.position2) {
        var vFrom = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        var vTo = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        var vDir = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        var vSplit = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        for (i = 0, il = splitPosition.length; i < il; i += 3) {
            vFrom.fromArray(data.position1, i);
            vTo.fromArray(data.position2, i);
            vDir.subVectors(vFrom, vTo);
            var fullLength = vDir.length();
            var coneLength = cylinderRadius[i / 3] * aspectRatio * 2;
            var length = Math.min(fullLength, coneLength);
            vDir.setLength(length);
            vSplit.copy(vTo).add(vDir);
            vSplit.toArray(splitPosition, i);
        }
        cylinder.position1 = data.position1;
        cylinder.position2 = splitPosition;
        cone.position1 = splitPosition;
        cone.position2 = data.position2;
    }
    if (data.color) {
        cylinder.color = data.color;
        cylinder.color2 = data.color;
        cone.color = data.color;
    }
    return {
        cylinder: cylinder,
        cone: cone
    };
};
ArrowBuffer.prototype.getMesh = function getMesh () {
    return new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]().add(this.cylinderBuffer.getMesh(), this.coneBuffer.getMesh());
};
ArrowBuffer.prototype.getWireframeMesh = function getWireframeMesh () {
    return new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]().add(this.cylinderBuffer.getWireframeMesh(), this.coneBuffer.getWireframeMesh());
};
ArrowBuffer.prototype.getPickingMesh = function getPickingMesh () {
    return new __WEBPACK_IMPORTED_MODULE_0_three__["t" /* Group */]().add(this.cylinderBuffer.getPickingMesh(), this.coneBuffer.getPickingMesh());
};
ArrowBuffer.prototype.setAttributes = function setAttributes (data) {
        if ( data === void 0 ) data = {};

    var attr = this.makeAttributes(data);
    this.cylinderBuffer.setAttributes(attr.cylinder);
    this.coneBuffer.setAttributes(attr.cone);
};
/**
 * Set buffer parameters
 * @param {BufferParameters} params - buffer parameters object
 * @return {undefined}
 */
ArrowBuffer.prototype.setParameters = function setParameters (params) {
        if ( params === void 0 ) params = {};

    params = Object.assign({}, params);
    if (params && params.matrix !== undefined) {
        this.matrix = params.matrix;
    }
    delete params.matrix;
    if (params && params.wireframe !== undefined) {
        this.parameters.wireframe = params.wireframe;
        this.setVisibility(this.visible);
    }
    this.cylinderBuffer.setParameters(params);
    this.coneBuffer.setParameters(params);
};
ArrowBuffer.prototype.setVisibility = function setVisibility (value) {
    Buffer.prototype.setVisibility.call(this, value);
};
ArrowBuffer.prototype.dispose = function dispose () {
    this.cylinderBuffer.dispose();
    this.coneBuffer.dispose();
};

Object.defineProperties( ArrowBuffer.prototype, prototypeAccessors$v );
BufferRegistry.add('arrow', ArrowBuffer);

/**
 * @file Box Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var scale$4 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var target$2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var up$2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var eye$2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 0, 0);
/**
 * Box buffer. Draws boxes.
 *
 * @example
 * var boxBuffer = new BoxBuffer({
 *   position: new Float32Array([ 0, 3, 0, -2, 0, 0 ]),
 *   color: new Float32Array([ 1, 0, 1, 0, 1, 0 ]),
 *   size: new Float32Array([ 2, 1.5 ]),
 *   heightAxis: new Float32Array([ 0, 1, 1, 0, 2, 0 ]),
 *   depthAxis: new Float32Array([ 1, 0, 1, 0, 0, 2 ])
 * })
 */
var BoxBuffer = /*@__PURE__*/(function (GeometryBuffer$$1) {
    function BoxBuffer(data, params) {
        if ( params === void 0 ) params = {};

        GeometryBuffer$$1.call(this, data, params, new __WEBPACK_IMPORTED_MODULE_0_three__["e" /* BoxBufferGeometry */](1, 1, 1));
        this.updateNormals = true;
        this.setAttributes(data, true);
    }

    if ( GeometryBuffer$$1 ) BoxBuffer.__proto__ = GeometryBuffer$$1;
    BoxBuffer.prototype = Object.create( GeometryBuffer$$1 && GeometryBuffer$$1.prototype );
    BoxBuffer.prototype.constructor = BoxBuffer;
    BoxBuffer.prototype.applyPositionTransform = function applyPositionTransform (matrix, i, i3) {
        target$2.fromArray(this._heightAxis, i3);
        up$2.fromArray(this._depthAxis, i3);
        matrix.lookAt(eye$2, target$2, up$2);
        scale$4.set(this._size[i], up$2.length(), target$2.length());
        matrix.scale(scale$4);
    };
    BoxBuffer.prototype.setAttributes = function setAttributes (data, initNormals) {
        if ( data === void 0 ) data = {};

        if (data.size)
            { this._size = data.size; }
        if (data.heightAxis)
            { this._heightAxis = data.heightAxis; }
        if (data.depthAxis)
            { this._depthAxis = data.depthAxis; }
        GeometryBuffer$$1.prototype.setAttributes.call(this, data, initNormals);
    };

    return BoxBuffer;
}(GeometryBuffer));
BufferRegistry.add('box', BoxBuffer);

/**
 * @file Ellipsoid Geometry Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var scale$5 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var target$3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var up$3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var eye$3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 0, 0);
var EllipsoidBufferDefaultParameters = Object.assign({
    sphereDetail: 2,
}, BufferDefaultParameters);
/**
 * Ellipsoid buffer. Draws ellipsoids.
 *
 * @example
 * var ellipsoidBuffer = new EllipsoidBuffer({
 *   position: new Float32Array([ 0, 0, 0 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   radius: new Float32Array([ 1 ]),
 *   majorAxis: new Float32Array([ 1, 1, 0 ]),
 *   minorAxis: new Float32Array([ 0.5, 0, 0.5 ]),
 * });
 */
var EllipsoidBuffer = /*@__PURE__*/(function (GeometryBuffer$$1) {
    function EllipsoidBuffer(data, params) {
        if ( params === void 0 ) params = {};

        GeometryBuffer$$1.call(this, data, params, new __WEBPACK_IMPORTED_MODULE_0_three__["u" /* IcosahedronBufferGeometry */](1, defaults(params.sphereDetail, 2)));
        this.updateNormals = true;
        this.setAttributes(data, true);
    }

    if ( GeometryBuffer$$1 ) EllipsoidBuffer.__proto__ = GeometryBuffer$$1;
    EllipsoidBuffer.prototype = Object.create( GeometryBuffer$$1 && GeometryBuffer$$1.prototype );
    EllipsoidBuffer.prototype.constructor = EllipsoidBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return EllipsoidBufferDefaultParameters; };
    EllipsoidBuffer.prototype.applyPositionTransform = function applyPositionTransform (matrix, i, i3) {
        target$3.fromArray(this._majorAxis, i3);
        up$3.fromArray(this._minorAxis, i3);
        matrix.lookAt(eye$3, target$3, up$3);
        scale$5.set(this._radius[i], up$3.length(), target$3.length());
        matrix.scale(scale$5);
    };
    EllipsoidBuffer.prototype.setAttributes = function setAttributes (data, initNormals) {
        if ( data === void 0 ) data = {};

        if (data.radius)
            { this._radius = data.radius; }
        if (data.majorAxis)
            { this._majorAxis = data.majorAxis; }
        if (data.minorAxis)
            { this._minorAxis = data.minorAxis; }
        GeometryBuffer$$1.prototype.setAttributes.call(this, data, initNormals);
    };

    Object.defineProperties( EllipsoidBuffer.prototype, prototypeAccessors );

    return EllipsoidBuffer;
}(GeometryBuffer));
BufferRegistry.add('ellipsoid', EllipsoidBuffer);

/**
 * @file Octahedron Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var scale$6 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var target$4 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var up$4 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var eye$4 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 0, 0);
/**
 * Octahedron buffer. Draws octahedrons.
 *
 * @example
 * var octahedronBuffer = new OctahedronBuffer({
 *   position: new Float32Array([ 0, 3, 0, -2, 0, 0 ]),
 *   color: new Float32Array([ 1, 0, 1, 0, 1, 0 ]),
 *   size: new Float32Array([ 2, 1.5 ]),
 *   heightAxis: new Float32Array([ 0, 1, 1, 0, 2, 0 ]),
 *   depthAxis: new Float32Array([ 1, 0, 1, 0, 0, 2 ])
 * })
 */
var OctahedronBuffer = /*@__PURE__*/(function (GeometryBuffer$$1) {
    function OctahedronBuffer(data, params) {
        if ( params === void 0 ) params = {};

        GeometryBuffer$$1.call(this, data, params, new __WEBPACK_IMPORTED_MODULE_0_three__["D" /* OctahedronBufferGeometry */](1, 0));
        this.updateNormals = true;
        this.setAttributes(data, true);
    }

    if ( GeometryBuffer$$1 ) OctahedronBuffer.__proto__ = GeometryBuffer$$1;
    OctahedronBuffer.prototype = Object.create( GeometryBuffer$$1 && GeometryBuffer$$1.prototype );
    OctahedronBuffer.prototype.constructor = OctahedronBuffer;
    OctahedronBuffer.prototype.applyPositionTransform = function applyPositionTransform (matrix, i, i3) {
        target$4.fromArray(this._heightAxis, i3);
        up$4.fromArray(this._depthAxis, i3);
        matrix.lookAt(eye$4, target$4, up$4);
        scale$6.set(this._size[i], up$4.length(), target$4.length());
        matrix.scale(scale$6);
    };
    OctahedronBuffer.prototype.setAttributes = function setAttributes (data, initNormals) {
        if ( data === void 0 ) data = {};

        if (data.size)
            { this._size = data.size; }
        if (data.heightAxis)
            { this._heightAxis = data.heightAxis; }
        if (data.depthAxis)
            { this._depthAxis = data.depthAxis; }
        GeometryBuffer$$1.prototype.setAttributes.call(this, data, initNormals);
    };

    return OctahedronBuffer;
}(GeometryBuffer));
BufferRegistry.add('octahedron', OctahedronBuffer);

/**
 * @file Tetrahedron Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var scale$7 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var target$5 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var up$5 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var eye$5 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 0, 0);
/**
 * Tetrahedron buffer. Draws tetrahedrons.
 *
 * @example
 * var tetrahedronBuffer = new TetrahedronBuffer({
 *   position: new Float32Array([ 0, 3, 0, -2, 0, 0 ]),
 *   color: new Float32Array([ 1, 0, 1, 0, 1, 0 ]),
 *   size: new Float32Array([ 2, 1.5 ]),
 *   heightAxis: new Float32Array([ 0, 1, 1, 0, 2, 0 ]),
 *   depthAxis: new Float32Array([ 1, 0, 1, 0, 0, 2 ])
 * })
 */
var TetrahedronBuffer = /*@__PURE__*/(function (GeometryBuffer$$1) {
    function TetrahedronBuffer(data, params) {
        if ( params === void 0 ) params = {};

        GeometryBuffer$$1.call(this, data, params, new __WEBPACK_IMPORTED_MODULE_0_three__["Q" /* TetrahedronBufferGeometry */](1, 0));
        this.updateNormals = true;
        this.setAttributes(data, true);
    }

    if ( GeometryBuffer$$1 ) TetrahedronBuffer.__proto__ = GeometryBuffer$$1;
    TetrahedronBuffer.prototype = Object.create( GeometryBuffer$$1 && GeometryBuffer$$1.prototype );
    TetrahedronBuffer.prototype.constructor = TetrahedronBuffer;
    TetrahedronBuffer.prototype.applyPositionTransform = function applyPositionTransform (matrix, i, i3) {
        target$5.fromArray(this._heightAxis, i3);
        up$5.fromArray(this._depthAxis, i3);
        matrix.lookAt(eye$5, target$5, up$5);
        scale$7.set(this._size[i], up$5.length(), target$5.length());
        matrix.scale(scale$7);
    };
    TetrahedronBuffer.prototype.setAttributes = function setAttributes (data, initNormals) {
        if ( data === void 0 ) data = {};

        if (data.size)
            { this._size = data.size; }
        if (data.heightAxis)
            { this._heightAxis = data.heightAxis; }
        if (data.depthAxis)
            { this._depthAxis = data.depthAxis; }
        GeometryBuffer$$1.prototype.setAttributes.call(this, data, initNormals);
    };

    return TetrahedronBuffer;
}(GeometryBuffer));
BufferRegistry.add('tetrahedron', TetrahedronBuffer);

/**
 * @file Tetrahedron Geometry Buffer
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var scale$8 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var target$6 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var up$6 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
var eye$6 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](0, 0, 0);
var TorusBufferDefaultParameters = Object.assign({
    radiusRatio: 0.2,
    radialSegments: 16,
    tubularSegments: 32
}, BufferDefaultParameters);
/**
 * Torus geometry buffer. Draws torii.
 *
 * @example
 * var torusBuffer = new TorusBuffer({
 *   position: new Float32Array([ 0, 0, 0 ]),
 *   color: new Float32Array([ 1, 0, 0 ]),
 *   radius: new Float32Array([ 1 ]),
 *   majorAxis: new Float32Array([ 1, 1, 0 ]),
 *   minorAxis: new Float32Array([ 0.5, 0, 0.5 ]),
 * });
 */
var TorusBuffer = /*@__PURE__*/(function (GeometryBuffer$$1) {
    function TorusBuffer(data, params) {
        if ( params === void 0 ) params = {};

        GeometryBuffer$$1.call(this, data, params, new __WEBPACK_IMPORTED_MODULE_0_three__["R" /* TorusBufferGeometry */](1, defaults(params.radiusRatio, 0.2), defaults(params.radialSegments, 16), defaults(params.tubularSegments, 32)));
        this.updateNormals = true;
        this.setAttributes(data, true);
    }

    if ( GeometryBuffer$$1 ) TorusBuffer.__proto__ = GeometryBuffer$$1;
    TorusBuffer.prototype = Object.create( GeometryBuffer$$1 && GeometryBuffer$$1.prototype );
    TorusBuffer.prototype.constructor = TorusBuffer;

    var prototypeAccessors = { defaultParameters: { configurable: true } };
    prototypeAccessors.defaultParameters.get = function () { return TorusBufferDefaultParameters; };
    TorusBuffer.prototype.applyPositionTransform = function applyPositionTransform (matrix, i, i3) {
        target$6.fromArray(this._majorAxis, i3);
        up$6.fromArray(this._minorAxis, i3);
        matrix.lookAt(eye$6, target$6, up$6);
        var r = this._radius[i];
        scale$8.set(r, r, r);
        matrix.scale(scale$8);
    };
    TorusBuffer.prototype.setAttributes = function setAttributes (data, initNormals) {
        if ( data === void 0 ) data = {};

        if (data.radius)
            { this._radius = data.radius; }
        if (data.majorAxis)
            { this._majorAxis = data.majorAxis; }
        if (data.minorAxis)
            { this._minorAxis = data.minorAxis; }
        GeometryBuffer$$1.prototype.setAttributes.call(this, data, initNormals);
    };

    Object.defineProperties( TorusBuffer.prototype, prototypeAccessors );

    return TorusBuffer;
}(GeometryBuffer));
BufferRegistry.add('torus', TorusBuffer);

/**
 * @file Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Parser = function Parser(streamer, params) {
    var p = params || {};
    this.streamer = streamer;
    this.name = defaults(p.name, '');
    this.path = defaults(p.path, '');
};

var prototypeAccessors$w = { type: { configurable: true },__objName: { configurable: true },isBinary: { configurable: true },isJson: { configurable: true },isXml: { configurable: true } };
prototypeAccessors$w.type.get = function () { return ''; };
prototypeAccessors$w.__objName.get = function () { return ''; };
prototypeAccessors$w.isBinary.get = function () { return false; };
prototypeAccessors$w.isJson.get = function () { return false; };
prototypeAccessors$w.isXml.get = function () { return false; };
Parser.prototype.parse = function parse () {
        var this$1 = this;

    return this.streamer.read().then(function () {
        this$1._beforeParse();
        this$1._parse();
        this$1._afterParse();
        return this$1[this$1.__objName];
    });
};
Parser.prototype._parse = function _parse () { };
Parser.prototype._beforeParse = function _beforeParse () { };
Parser.prototype._afterParse = function _afterParse () {
    if (Debug)
        { Log.log(this[this.__objName]); }
};

Object.defineProperties( Parser.prototype, prototypeAccessors$w );

/**
 * @file Structure Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var StructureParser = /*@__PURE__*/(function (Parser$$1) {
    function StructureParser(streamer, params) {
        var p = params || {};
        Parser$$1.call(this, streamer, p);
        this.firstModelOnly = defaults(p.firstModelOnly, false);
        this.asTrajectory = defaults(p.asTrajectory, false);
        this.cAlphaOnly = defaults(p.cAlphaOnly, false);
        this.structure = new Structure(this.name, this.path);
        this.structureBuilder = new StructureBuilder(this.structure);
    }

    if ( Parser$$1 ) StructureParser.__proto__ = Parser$$1;
    StructureParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    StructureParser.prototype.constructor = StructureParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'structure'; };
    prototypeAccessors.__objName.get = function () { return 'structure'; };

    Object.defineProperties( StructureParser.prototype, prototypeAccessors );

    return StructureParser;
}(Parser));

/**
 * @file Entity
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function entityTypeFromString(string) {
    string = string.toLowerCase();
    switch (string) {
        case 'polymer':
            return PolymerEntity;
        case 'non-polymer':
            return NonPolymerEntity;
        case 'macrolide':
            return MacrolideEntity;
        case 'water':
            return WaterEntity;
        default:
            return UnknownEntity;
    }
}
function entityFromType(type) {
    switch (type) {
        case PolymerEntity:
            return 'polymer';
        case NonPolymerEntity:
            return 'non-polymer';
        case MacrolideEntity:
            return 'macrolide';
        case WaterEntity:
            return 'water';
        default:
            return undefined;
    }
}
/**
 * Entity of a {@link Structure}
 */
var Entity = function Entity(structure, index, description, type, chainIndexList) {
    if ( description === void 0 ) description = '';
    if ( chainIndexList === void 0 ) chainIndexList = [];

    this.structure = structure;
    this.index = index;
    this.description = description;
    this.entityType = entityTypeFromString(type || '');
    this.chainIndexList = chainIndexList;
    chainIndexList.forEach(function (ci) {
        structure.chainStore.entityIndex[ci] = index;
    });
};

var prototypeAccessors$x = { type: { configurable: true } };
prototypeAccessors$x.type.get = function () { return entityFromType(this.entityType); };
Entity.prototype.getEntityType = function getEntityType () {
    return this.entityType;
};
Entity.prototype.isPolymer = function isPolymer () {
    return this.entityType === PolymerEntity;
};
Entity.prototype.isNonPolymer = function isNonPolymer () {
    return this.entityType === NonPolymerEntity;
};
Entity.prototype.isMacrolide = function isMacrolide () {
    return this.entityType === MacrolideEntity;
};
Entity.prototype.isWater = function isWater () {
    return this.entityType === WaterEntity;
};
Entity.prototype.eachChain = function eachChain (callback) {
    var cp = this.structure.getChainProxy();
    this.chainIndexList.forEach(function (index) {
        cp.index = index;
        callback(cp);
    });
};

Object.defineProperties( Entity.prototype, prototypeAccessors$x );

/**
 * @file Unitcell
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var DefaultBoxParams = {
    a: 1,
    b: 1,
    c: 1,
    alpha: 90,
    beta: 90,
    gamma: 90,
    spacegroup: 'P 1'
};
/**
 * Unitcell class
 */
var Unitcell = function Unitcell(params) {
    if ( params === void 0 ) params = DefaultBoxParams;

    this.cartToFrac = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    this.fracToCart = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    this.a = params.a;
    this.b = params.b;
    this.c = params.c;
    this.alpha = params.alpha;
    this.beta = params.beta;
    this.gamma = params.gamma;
    this.spacegroup = params.spacegroup;
    var alphaRad = degToRad(this.alpha);
    var betaRad = degToRad(this.beta);
    var gammaRad = degToRad(this.gamma);
    var cosAlpha = Math.cos(alphaRad);
    var cosBeta = Math.cos(betaRad);
    var cosGamma = Math.cos(gammaRad);
    var sinBeta = Math.sin(betaRad);
    var sinGamma = Math.sin(gammaRad);
    this.volume = (this.a * this.b * this.c *
        Math.sqrt(1 - cosAlpha * cosAlpha - cosBeta * cosBeta - cosGamma * cosGamma +
            2.0 * cosAlpha * cosBeta * cosGamma));
    if (params.cartToFrac === undefined) {
        // https://github.com/biojava/biojava/blob/master/biojava-structure/src/main/java/org/biojava/nbio/structure/xtal/CrystalCell.java
        var cStar = (this.a * this.b * sinGamma) / this.volume;
        var cosAlphaStar = ((cosBeta * cosGamma - cosAlpha) / (sinBeta * sinGamma));
        this.fracToCart.set(this.a, 0, 0, 0, this.b * cosGamma, this.b * sinGamma, 0, 0, this.c * cosBeta, -this.c * sinBeta * cosAlphaStar, 1.0 / cStar, 0, 0, 0, 0, 1).transpose();
        this.cartToFrac.getInverse(this.fracToCart);
    }
    else {
        this.cartToFrac.copy(params.cartToFrac);
        this.fracToCart.getInverse(this.cartToFrac);
    }
};
Unitcell.prototype.getPosition = function getPosition (structure) {
    var vertexPosition = new Float32Array(3 * 8);
    if (structure.unitcell) {
        var uc = structure.unitcell;
        var centerFrac = structure.center.clone().applyMatrix4(uc.cartToFrac).floor();
        var v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
        var cornerOffset = 0;
        var addCorner = function (x, y, z) {
            v.set(x, y, z)
                .add(centerFrac)
                .applyMatrix4(uc.fracToCart)
                .toArray(vertexPosition, cornerOffset);
            cornerOffset += 3;
        };
        addCorner(0, 0, 0);
        addCorner(1, 0, 0);
        addCorner(0, 1, 0);
        addCorner(0, 0, 1);
        addCorner(1, 1, 0);
        addCorner(1, 0, 1);
        addCorner(0, 1, 1);
        addCorner(1, 1, 1);
    }
    return vertexPosition;
};
Unitcell.prototype.getCenter = function getCenter (structure) {
    return centerArray3(this.getPosition(structure));
};
Unitcell.prototype.getData = function getData (structure, params) {
        if ( params === void 0 ) params = {};

    var colorValue = defaults(params.colorValue, 'orange');
    var radius = defaults(params.radius, Math.cbrt(this.volume) / 200);
    var c = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](colorValue);
    var v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var vertexPosition = this.getPosition(structure);
    var vertexColor = uniformArray3(8, c.r, c.g, c.b);
    var vertexRadius = uniformArray(8, radius);
    var edgePosition1 = new Float32Array(3 * 12);
    var edgePosition2 = new Float32Array(3 * 12);
    var edgeColor = uniformArray3(12, c.r, c.g, c.b);
    var edgeRadius = uniformArray(12, radius);
    var edgeOffset = 0;
    function addEdge(a, b) {
        v.fromArray(vertexPosition, a * 3)
            .toArray(edgePosition1, edgeOffset);
        v.fromArray(vertexPosition, b * 3)
            .toArray(edgePosition2, edgeOffset);
        edgeOffset += 3;
    }
    addEdge(0, 1);
    addEdge(0, 2);
    addEdge(0, 3);
    addEdge(1, 4);
    addEdge(1, 5);
    addEdge(2, 6);
    addEdge(3, 5);
    addEdge(4, 7);
    addEdge(5, 7);
    addEdge(2, 4);
    addEdge(7, 6);
    addEdge(3, 6);
    var picker = new UnitcellPicker(this, structure);
    return {
        vertex: {
            position: vertexPosition,
            color: vertexColor,
            radius: vertexRadius,
            picking: picker
        },
        edge: {
            position1: edgePosition1,
            position2: edgePosition2,
            color: edgeColor,
            color2: edgeColor,
            radius: edgeRadius,
            picking: picker
        }
    };
};

/**
 * @file Pdb Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// PDB helix record encoding
var HelixTypes = {
    1: 'h',
    2: 'h',
    3: 'i',
    4: 'h',
    5: 'g',
    6: 'h',
    7: 'h',
    8: 'h',
    9: 'h',
    10: 'h',
    0: 'h' //Used to be ''
};
var dAminoAcids = [
    'DAL',
    'DAR',
    'DSG',
    'DAS',
    'DCY',
    'DGL',
    'DGN',
    'DHI',
    'DIL',
    'DLE',
    'DLY',
    'MED',
    'DPN',
    'DPR',
    'DSN',
    'DTH',
    'DTR',
    'DTY',
    'DVA',
    'DNE' // D-NORLEUCINE
    // ???  // D-SELENOCYSTEINE
];
var entityKeyList = [
    'MOL_ID', 'MOLECULE', 'CHAIN', 'FRAGMENT', 'SYNONYM',
    'EC', 'ENGINEERED', 'MUTATION', 'OTHER_DETAILS'
];
var reWhitespace = /\s+/;
function getModresId(resno, chainname, inscode) {
    var id = "" + resno;
    if (chainname)
        { id += ":" + chainname; }
    if (inscode)
        { id += "^" + inscode; }
    return id;
}
var PdbParser = /*@__PURE__*/(function (StructureParser$$1) {
    function PdbParser(streamer, params) {
        var p = params || {};
        StructureParser$$1.call(this, streamer, p);
        this.hex = defaults(p.hex, false);
    }

    if ( StructureParser$$1 ) PdbParser.__proto__ = StructureParser$$1;
    PdbParser.prototype = Object.create( StructureParser$$1 && StructureParser$$1.prototype );
    PdbParser.prototype.constructor = PdbParser;

    var prototypeAccessors = { type: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'pdb'; };
    PdbParser.prototype._parse = function _parse () {
        // http://www.wwpdb.org/documentation/file-format.php
        if (Debug)
            { Log.time('PdbParser._parse ' + this.name); }
        var isLegacy = false;
        var headerLine = this.streamer.peekLines(1)[0];
        var headerId = headerLine.substr(62, 4);
        var legacyId = headerLine.substr(72, 4);
        if (headerId === legacyId && legacyId.trim()) {
            isLegacy = true;
        }
        var isPqr = this.type === 'pqr';
        var isPdbqt = this.type === 'pdbqt';
        var s = this.structure;
        var sb = this.structureBuilder;
        var hex = this.hex;
        var serialRadix = 10;
        var resnoRadix = 10;
        var firstModelOnly = this.firstModelOnly;
        var asTrajectory = this.asTrajectory;
        var cAlphaOnly = this.cAlphaOnly;
        var frames = s.frames;
        var boxes = s.boxes;
        var doFrames = false;
        var currentFrame, currentCoord;
        var biomolDict = s.biomolDict;
        var currentBiomol;
        var currentPart;
        var currentMatrix;
        var line, recordName;
        var serial, chainname, resno, resname, occupancy;
        var inscode, atomname, hetero, bfactor, altloc;
        var startChain, startResi, startIcode;
        var endChain, endResi, endIcode;
        var serialDict = {};
        var unitcellDict = {};
        var bondDict = {};
        var entityDataList = [];
        var currentEntityData;
        var currentEntityKey;
        // MOL_ID                 Numbers each component; also used in  SOURCE to associate
        //                        the information.
        // MOLECULE               Name of the macromolecule.
        // CHAIN                  Comma-separated list of chain  identifier(s).
        // FRAGMENT               Specifies a domain or region of the  molecule.
        // SYNONYM                Comma-separated list of synonyms for  the MOLECULE.
        // EC                     The Enzyme Commission number associated  with the molecule.
        //                        If there is more than one EC number,  they are presented
        //                        as a comma-separated list.
        // ENGINEERED             Indicates that the molecule was  produced using
        //                        recombinant technology or by purely  chemical synthesis.
        // MUTATION               Indicates if there is a mutation.
        // OTHER_DETAILS          Additional comments.
        var hetnameDict = {};
        var modresDict = {};
        var chainDict = {};
        var chainIdx, chainid, newChain;
        var currentChainname, currentResno, currentResname, currentInscode;
        var seqresDict = {};
        var currentSeqresChainname;
        var secStruct = {
            helices: [],
            sheets: []
        };
        var helices = secStruct.helices;
        var sheets = secStruct.sheets;
        var atomMap = s.atomMap;
        var atomStore = s.atomStore;
        atomStore.resize(Math.round(this.streamer.data.length / 80));
        if (isPqr || isPdbqt)
            { atomStore.addField('partialCharge', 1, 'float32'); }
        if (isPqr)
            { atomStore.addField('radius', 1, 'float32'); }
        var ap1 = s.getAtomProxy();
        var ap2 = s.getAtomProxy();
        var idx = 0;
        var modelIdx = 0;
        var pendingStart = true;
        function _parseChunkOfLines(_i, _n, lines) {
            var ref;

            for (var i = _i; i < _n; ++i) {
                line = lines[i];
                recordName = line.substr(0, 6);
                if (recordName === 'ATOM  ' || recordName === 'HETATM') {
                    // http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#ATOM
                    // PQR: Field_name Atom_number Atom_name Residue_name Chain_ID Residue_number X Y Z Charge Radius
                    if (pendingStart) {
                        if (asTrajectory) {
                            if (doFrames) {
                                currentFrame = new Float32Array(atomStore.count * 3);
                                frames.push(currentFrame);
                            }
                            else {
                                currentFrame = [];
                            }
                            currentCoord = 0;
                        }
                        else {
                            if (!firstModelOnly)
                                { serialDict = {}; }
                        }
                        chainIdx = 1;
                        chainid = chainIdx.toString();
                        newChain = true;
                        pendingStart = false;
                    }
                    if (firstModelOnly && modelIdx > 0)
                        { continue; }
                    var x = (void 0), y = (void 0), z = (void 0), ls = (void 0), dd = 0;
                    if (isPqr) {
                        ls = line.split(reWhitespace);
                        dd = ls.length === 10 ? 1 : 0;
                        atomname = ls[2];
                        if (cAlphaOnly && atomname !== 'CA')
                            { continue; }
                        x = parseFloat(ls[6 - dd]);
                        y = parseFloat(ls[7 - dd]);
                        z = parseFloat(ls[8 - dd]);
                    }
                    else {
                        atomname = line.substr(12, 4).trim();
                        if (cAlphaOnly && atomname !== 'CA')
                            { continue; }
                        x = parseFloat(line.substr(30, 8));
                        y = parseFloat(line.substr(38, 8));
                        z = parseFloat(line.substr(46, 8));
                    }
                    if (asTrajectory) {
                        var j = currentCoord * 3;
                        currentFrame[j + 0] = x;
                        currentFrame[j + 1] = y;
                        currentFrame[j + 2] = z;
                        currentCoord += 1;
                        if (doFrames)
                            { continue; }
                    }
                    var element = (void 0);
                    if (isPqr) {
                        serial = parseInt(ls[1]);
                        element = '';
                        hetero = (line[0] === 'H') ? 1 : 0;
                        chainname = dd ? '' : ls[4];
                        resno = parseInt(ls[5 - dd]);
                        inscode = '';
                        resname = ls[3];
                        altloc = '';
                        occupancy = 1.0;
                    }
                    else {
                        serial = parseInt(line.substr(6, 5), serialRadix);
                        if (hex && serial === 99999) {
                            serialRadix = 16;
                        }
                        hetero = (line[0] === 'H') ? 1 : 0;
                        chainname = line[21].trim();
                        resno = parseInt(line.substr(22, 4), resnoRadix);
                        if (hex && resno === 9999) {
                            resnoRadix = 16;
                        }
                        inscode = line[26].trim();
                        resname = line.substr(17, 4).trim() || 'MOL';
                        bfactor = parseFloat(line.substr(60, 6));
                        altloc = line[16].trim();
                        occupancy = parseFloat(line.substr(54, 6));
                        if (!isLegacy) {
                            if (isPdbqt) {
                                element = line.substr(12, 2).trim();
                            }
                            else {
                                element = line.substr(76, 2).trim();
                                if (!chainname) {
                                    chainname = line.substr(72, 4).trim(); // segid
                                }
                            }
                        }
                    }
                    atomStore.growIfFull();
                    atomStore.atomTypeId[idx] = atomMap.add(atomname, element);
                    atomStore.x[idx] = x;
                    atomStore.y[idx] = y;
                    atomStore.z[idx] = z;
                    atomStore.serial[idx] = serial;
                    atomStore.altloc[idx] = altloc.charCodeAt(0);
                    atomStore.occupancy[idx] = isNaN(occupancy) ? 0 : occupancy;
                    if (isPqr) {
                        atomStore.partialCharge[idx] = parseFloat(ls[9 - dd]);
                        atomStore.radius[idx] = parseFloat(ls[10 - dd]);
                    }
                    else {
                        atomStore.bfactor[idx] = isNaN(bfactor) ? 0 : bfactor;
                        if (isPdbqt) {
                            atomStore.partialCharge[idx] = parseFloat(line.substr(70, 6));
                        }
                    }
                    var modresId = getModresId(resno, chainname, inscode);
                    // TODO instead of looking at MODRES look at SEQRES and
                    //      missing residues in REMARK 465
                    if (hetero && !modresDict[modresId] && !dAminoAcids.includes(resname)) {
                        if (currentChainname !== chainname || currentResname !== resname ||
                            (!WaterNames.includes(resname) &&
                                (currentResno !== resno || currentInscode !== inscode))) {
                            chainIdx += 1;
                            chainid = chainIdx.toString();
                            currentResno = resno;
                            currentResname = resname;
                            currentInscode = inscode;
                        }
                    }
                    else if (!newChain && currentChainname !== chainname) {
                        chainIdx += 1;
                        chainid = chainIdx.toString();
                    }
                    sb.addAtom(modelIdx, chainname, chainid, resname, resno, hetero, undefined, inscode);
                    serialDict[serial] = idx;
                    idx += 1;
                    newChain = false;
                    currentChainname = chainname;
                }
                else if (recordName === 'CONECT') {
                    var fromIdx = serialDict[parseInt(line.substr(6, 5))];
                    var pos = [11, 16, 21, 26];
                    var bondIndex = {};
                    if (fromIdx === undefined) {
                        // Log.log( "missing CONNECT serial" );
                        continue;
                    }
                    for (var j$1 = 0; j$1 < 4; ++j$1) {
                        var toIdx = parseInt(line.substr(pos[j$1], 5));
                        if (Number.isNaN(toIdx))
                            { continue; }
                        toIdx = serialDict[toIdx];
                        if (toIdx === undefined) {
                            // Log.log( "missing CONNECT serial" );
                            continue;
                        } /* else if( toIdx < fromIdx ){
                            // likely a duplicate in standard PDB format
                            // but not necessarily, so better remove duplicates
                            // in a pass after parsing (and auto bonding)
                            continue;
                        } */
                        if (fromIdx < toIdx) {
                            ap1.index = fromIdx;
                            ap2.index = toIdx;
                        }
                        else {
                            ap1.index = toIdx;
                            ap2.index = fromIdx;
                        }
                        // interpret records where a 'toIdx' atom is given multiple times
                        // as double/triple bonds, e.g. CONECT 1529 1528 1528 is a double bond
                        if (bondIndex[toIdx] !== undefined) {
                            s.bondStore.bondOrder[bondIndex[toIdx]] += 1;
                        }
                        else {
                            var hash = ap1.index + '|' + ap2.index;
                            if (bondDict[hash] === undefined) {
                                bondDict[hash] = true;
                                bondIndex[toIdx] = s.bondStore.count;
                                s.bondStore.addBond(ap1, ap2, 1); // start/assume with single bond
                            }
                        }
                    }
                }
                else if (recordName === 'HELIX ') {
                    startChain = line[19].trim();
                    startResi = parseInt(line.substr(21, 4));
                    startIcode = line[25].trim();
                    endChain = line[31].trim();
                    endResi = parseInt(line.substr(33, 4));
                    endIcode = line[37].trim();
                    var helixType = parseInt(line.substr(39, 1));
                    helixType = (HelixTypes[helixType] || HelixTypes[0]).charCodeAt(0);
                    helices.push([
                        startChain, startResi, startIcode,
                        endChain, endResi, endIcode,
                        helixType
                    ]);
                }
                else if (recordName === 'SHEET ') {
                    startChain = line[21].trim();
                    startResi = parseInt(line.substr(22, 4));
                    startIcode = line[26].trim();
                    endChain = line[32].trim();
                    endResi = parseInt(line.substr(33, 4));
                    endIcode = line[37].trim();
                    sheets.push([
                        startChain, startResi, startIcode,
                        endChain, endResi, endIcode
                    ]);
                }
                else if (recordName === 'HETNAM') {
                    hetnameDict[line.substr(11, 3)] = line.substr(15).trim();
                }
                else if (recordName === 'SEQRES') {
                    var seqresChainname = line[11].trim();
                    if (seqresChainname !== currentSeqresChainname) {
                        seqresDict[seqresChainname] = [];
                        currentSeqresChainname = seqresChainname;
                    }
                    (ref = seqresDict[seqresChainname]).push.apply(ref, line.substr(19).trim().split(reWhitespace));
                }
                else if (recordName === 'MODRES') {
                    // MODRES 2SRC PTR A  527  TYR  O-PHOSPHOTYROSINE
                    var resname$1 = line.substr(12, 3).trim();
                    var chainname$1 = line[16].trim();
                    var inscode$1 = line[22].trim();
                    var resno$1 = parseInt(line.substr(18, 4).trim());
                    var id = getModresId(resno$1, chainname$1, inscode$1);
                    modresDict[id] = { resname: resname$1, chainname: chainname$1, inscode: inscode$1, resno: resno$1 };
                }
                else if (recordName === 'COMPND') {
                    var comp = line.substr(10, 70).trim();
                    var keyEnd = comp.indexOf(':');
                    var key = comp.substring(0, keyEnd);
                    var value = (void 0);
                    if (entityKeyList.includes(key)) {
                        currentEntityKey = key;
                        value = comp.substring(keyEnd + 2);
                    }
                    else {
                        value = comp;
                    }
                    value = value.replace(/;$/, '');
                    if (currentEntityKey === 'MOL_ID') {
                        currentEntityData = {
                            chainList: [],
                            name: ''
                        };
                        entityDataList.push(currentEntityData);
                    }
                    else if (currentEntityKey === 'MOLECULE') {
                        if (currentEntityData.name)
                            { currentEntityData.name += ' '; }
                        currentEntityData.name += value;
                    }
                    else if (currentEntityKey === 'CHAIN') {
                        Array.prototype.push.apply(currentEntityData.chainList, value.split(/\s*,\s*/));
                    }
                }
                else if (line.startsWith('TER')) {
                    var cp = s.getChainProxy(s.chainStore.count - 1);
                    chainDict[cp.chainname] = cp.index;
                    chainIdx += 1;
                    chainid = chainIdx.toString();
                    newChain = true;
                }
                else if (recordName === 'REMARK' && line.substr(7, 3) === '350') {
                    if (line.substr(11, 12) === 'BIOMOLECULE:') {
                        var name = line.substr(23).trim();
                        if (/^(0|[1-9][0-9]*)$/.test(name))
                            { name = 'BU' + name; }
                        currentBiomol = new Assembly(name);
                        biomolDict[name] = currentBiomol;
                    }
                    else if (line.substr(13, 5) === 'BIOMT') {
                        var biomt = line.split(/\s+/);
                        var row = parseInt(line[18]) - 1;
                        if (row === 0) {
                            currentMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
                            currentPart.matrixList.push(currentMatrix);
                        }
                        var biomtElms = currentMatrix.elements;
                        biomtElms[4 * 0 + row] = parseFloat(biomt[4]);
                        biomtElms[4 * 1 + row] = parseFloat(biomt[5]);
                        biomtElms[4 * 2 + row] = parseFloat(biomt[6]);
                        biomtElms[4 * 3 + row] = parseFloat(biomt[7]);
                    }
                    else if (line.substr(11, 30) === 'APPLY THE FOLLOWING TO CHAINS:' ||
                        line.substr(11, 30) === '                   AND CHAINS:') {
                        if (line.substr(11, 5) === 'APPLY') {
                            currentPart = currentBiomol.addPart();
                        }
                        var chainList = line.substr(41, 30).split(',');
                        for (var j$2 = 0, jl = chainList.length; j$2 < jl; ++j$2) {
                            var c = chainList[j$2].trim();
                            if (c)
                                { currentPart.chainList.push(c); }
                        }
                    }
                }
                else if (recordName === 'HEADER') {
                    s.id = line.substr(62, 4);
                }
                else if (recordName === 'TITLE ') {
                    s.title += (s.title ? ' ' : '') + line.substr(10, 70).trim();
                }
                else if (recordName === 'MODEL ') {
                    pendingStart = true;
                }
                else if (recordName === 'ENDMDL' || line.trim() === 'END') {
                    if (pendingStart)
                        { continue; }
                    if (asTrajectory && !doFrames) {
                        frames.push(new Float32Array(currentFrame));
                        doFrames = true;
                    }
                    modelIdx += 1;
                    pendingStart = true;
                }
                else if (line.substr(0, 5) === 'MTRIX') {
                    // ignore 'given' operators
                    if (line[59] === '1')
                        { continue; }
                    if (!currentBiomol || currentBiomol.name !== 'NCS') {
                        var ncsName = 'NCS';
                        currentBiomol = new Assembly(ncsName);
                        biomolDict[ncsName] = currentBiomol;
                        currentPart = currentBiomol.addPart();
                    }
                    var ncs = line.split(/\s+/);
                    var ncsRow = parseInt(line[5]) - 1;
                    if (ncsRow === 0) {
                        currentMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
                        currentPart.matrixList.push(currentMatrix);
                    }
                    var ncsElms = currentMatrix.elements;
                    ncsElms[4 * 0 + ncsRow] = parseFloat(ncs[2]);
                    ncsElms[4 * 1 + ncsRow] = parseFloat(ncs[3]);
                    ncsElms[4 * 2 + ncsRow] = parseFloat(ncs[4]);
                    ncsElms[4 * 3 + ncsRow] = parseFloat(ncs[5]);
                }
                else if (line.substr(0, 5) === 'ORIGX') {
                    if (!unitcellDict.origx) {
                        unitcellDict.origx = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
                    }
                    var orgix = line.split(/\s+/);
                    var origxRow = parseInt(line[5]) - 1;
                    var origxElms = unitcellDict.origx.elements;
                    origxElms[4 * 0 + origxRow] = parseFloat(orgix[1]);
                    origxElms[4 * 1 + origxRow] = parseFloat(orgix[2]);
                    origxElms[4 * 2 + origxRow] = parseFloat(orgix[3]);
                    origxElms[4 * 3 + origxRow] = parseFloat(orgix[4]);
                }
                else if (line.substr(0, 5) === 'SCALE') {
                    if (!unitcellDict.scale) {
                        unitcellDict.scale = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
                    }
                    var scale$$1 = line.split(/\s+/);
                    var scaleRow = parseInt(line[5]) - 1;
                    var scaleElms = unitcellDict.scale.elements;
                    scaleElms[4 * 0 + scaleRow] = parseFloat(scale$$1[1]);
                    scaleElms[4 * 1 + scaleRow] = parseFloat(scale$$1[2]);
                    scaleElms[4 * 2 + scaleRow] = parseFloat(scale$$1[3]);
                    scaleElms[4 * 3 + scaleRow] = parseFloat(scale$$1[4]);
                }
                else if (recordName === 'CRYST1') {
                    // CRYST1   55.989   55.989   55.989  90.00  90.00  90.00 P 1           1
                    //  7 - 15       Real(9.3)      a (Angstroms)
                    // 16 - 24       Real(9.3)      b (Angstroms)
                    // 25 - 33       Real(9.3)      c (Angstroms)
                    // 34 - 40       Real(7.2)      alpha         alpha (degrees).
                    // 41 - 47       Real(7.2)      beta          beta (degrees).
                    // 48 - 54       Real(7.2)      gamma         gamma (degrees).
                    // 56 - 66       LString        sGroup        Space group.
                    // 67 - 70       Integer        z             Z value.
                    var aLength = parseFloat(line.substr(6, 9));
                    var bLength = parseFloat(line.substr(15, 9));
                    var cLength = parseFloat(line.substr(24, 9));
                    var alpha = parseFloat(line.substr(33, 7));
                    var beta = parseFloat(line.substr(40, 7));
                    var gamma = parseFloat(line.substr(47, 7));
                    var sGroup = line.substr(55, 11).trim();
                    // const zValue = parseInt( line.substr( 66, 4 ) );
                    var box = new Float32Array(9);
                    box[0] = aLength;
                    box[4] = bLength;
                    box[8] = cLength;
                    boxes.push(box);
                    if (modelIdx === 0) {
                        unitcellDict.a = aLength;
                        unitcellDict.b = bLength;
                        unitcellDict.c = cLength;
                        unitcellDict.alpha = alpha;
                        unitcellDict.beta = beta;
                        unitcellDict.gamma = gamma;
                        unitcellDict.spacegroup = sGroup;
                    }
                }
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        // finalize ensures resname will be defined for all rp.resname
        // (required in entity handling below)
        sb.finalize();
        //
        var en = entityDataList.length;
        if (en) {
            s.eachChain(function (cp) {
                cp.entityIndex = en;
            });
            entityDataList.forEach(function (e, i) {
                var chainIndexList = e.chainList.map(function (chainname) {
                    return chainDict[chainname];
                });
                s.entityList.push(new Entity(s, i, e.name, 'polymer', chainIndexList));
            });
            var ei = entityDataList.length;
            var rp = s.getResidueProxy();
            var residueDict = {};
            s.eachChain(function (cp) {
                if (cp.entityIndex === en) {
                    rp.index = cp.residueOffset;
                    if (!residueDict[rp.resname]) {
                        residueDict[rp.resname] = [];
                    }
                    residueDict[rp.resname].push(cp.index);
                }
            });
            Object.keys(residueDict).forEach(function (resname) {
                var chainList = residueDict[resname];
                var type = 'non-polymer';
                var name = hetnameDict[resname] || resname;
                if (WaterNames.includes(resname)) {
                    name = 'water';
                    type = 'water';
                }
                s.entityList.push(new Entity(s, ei, name, type, chainList));
                ei += 1;
            });
        }
        //
        if (unitcellDict.a !== undefined) {
            s.unitcell = new Unitcell(unitcellDict);
        }
        else {
            s.unitcell = undefined;
        }
        if (helices.length || sheets.length) {
            assignSecondaryStructure(s, secStruct);
        }
        s.finalizeAtoms();
        if (!isLegacy)
            { calculateChainnames(s); }
        calculateBonds(s);
        s.finalizeBonds();
        if (!helices.length && !sheets.length) {
            calculateSecondaryStructure(s);
        }
        buildUnitcellAssembly(s);
        if (Debug)
            { Log.timeEnd('PdbParser._parse ' + this.name); }
    };

    Object.defineProperties( PdbParser.prototype, prototypeAccessors );

    return PdbParser;
}(StructureParser));
ParserRegistry$1.add('pdb', PdbParser);
ParserRegistry$1.add('pdb1', PdbParser);
ParserRegistry$1.add('ent', PdbParser);

/**
 * @file Cif Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var reWhitespace$1 = /\s+/;
var reQuotedWhitespace = /'((?:(?!'\s).)*)'|"((?:(?!"\s).)*)"|(\S+)/g;
var reDoubleQuote = /"/g;
var reTrimQuotes = /^['"]+|['"]+$/g;
function trimQuotes(str) {
    if (str && str[0] === str[str.length - 1] && (str[0] === "'" || str[0] === '"')) {
        return str.substring(1, str.length - 1);
    }
    else {
        return str;
    }
}
function ensureArray$1(dict, field) {
    if (!Array.isArray(dict[field])) {
        Object.keys(dict).forEach(function (key) {
            dict[key] = [dict[key]];
        });
    }
}
function hasValue(d) {
    return d !== '?';
}
function cifDefaults(value, defaultValue) {
    return hasValue(value) ? value : defaultValue;
}
function getBondOrder(valueOrder) {
    switch (valueOrder.toLowerCase()) {
        case '?': // assume single bond
        case 'sing':
            return 1;
        case 'doub':
            return 2;
        case 'trip':
            return 3;
        case 'quad':
            return 4;
    }
    return 0;
}
function parseChemComp(cif, structure, structureBuilder) {
    var atomStore = structure.atomStore;
    var atomMap = structure.atomMap;
    var i, n;
    var cc = cif.chem_comp;
    var cca = cif.chem_comp_atom;
    var ccb = cif.chem_comp_bond;
    if (cc) {
        if (cc.name) {
            structure.title = cc.name.trim().replace(reTrimQuotes, '');
        }
        if (cc.id) {
            structure.id = cc.id.trim().replace(reTrimQuotes, '');
        }
    }
    var atomnameDict = {};
    if (cca) {
        ensureArray$1(cca, 'comp_id');
        var atomname, element, resname, resno;
        n = cca.comp_id.length;
        for (i = 0; i < n; ++i) {
            atomStore.growIfFull();
            atomname = cca.atom_id[i].replace(reDoubleQuote, '');
            element = cca.type_symbol[i];
            atomnameDict[atomname] = i;
            atomStore.atomTypeId[i] = atomMap.add(atomname, element);
            atomStore.x[i] = cca.model_Cartn_x[i];
            atomStore.y[i] = cca.model_Cartn_y[i];
            atomStore.z[i] = cca.model_Cartn_z[i];
            atomStore.serial[i] = i;
            resname = cca.pdbx_component_comp_id[i];
            resno = cca.pdbx_residue_numbering ? cca.pdbx_residue_numbering[i] : 1;
            structureBuilder.addAtom(0, '', '', resname, resno, true);
        }
        for (i = 0; i < n; ++i) {
            var j = i + n;
            atomStore.growIfFull();
            atomname = cca.atom_id[i].replace(reDoubleQuote, '');
            element = cca.type_symbol[i];
            atomStore.atomTypeId[j] = atomMap.add(atomname, element);
            atomStore.x[j] = cca.pdbx_model_Cartn_x_ideal[i];
            atomStore.y[j] = cca.pdbx_model_Cartn_y_ideal[i];
            atomStore.z[j] = cca.pdbx_model_Cartn_z_ideal[i];
            atomStore.serial[j] = j;
            resname = cca.pdbx_component_comp_id[i];
            resno = cca.pdbx_residue_numbering ? cca.pdbx_residue_numbering[i] : 1;
            structureBuilder.addAtom(1, '', '', resname, resno, true);
        }
    }
    if (cca && ccb) {
        ensureArray$1(ccb, 'comp_id');
        var atomname1, atomname2, bondOrder;
        n = ccb.comp_id.length;
        var na = cca.comp_id.length;
        var ap1 = structure.getAtomProxy();
        var ap2 = structure.getAtomProxy();
        for (i = 0; i < n; ++i) {
            atomname1 = ccb.atom_id_1[i].replace(reDoubleQuote, '');
            atomname2 = ccb.atom_id_2[i].replace(reDoubleQuote, '');
            bondOrder = getBondOrder(ccb.value_order[i]);
            ap1.index = atomnameDict[atomname1];
            ap2.index = atomnameDict[atomname2];
            structure.bondStore.growIfFull();
            structure.bondStore.addBond(ap1, ap2, bondOrder);
            ap1.index += na;
            ap2.index += na;
            structure.bondStore.growIfFull();
            structure.bondStore.addBond(ap1, ap2, bondOrder);
        }
    }
}
function parseCore(cif, structure, structureBuilder) {
    var atomStore = structure.atomStore;
    var atomMap = structure.atomMap;
    if (cif.data) {
        structure.id = cif.data;
        structure.name = cif.data;
    }
    structure.unitcell = new Unitcell({
        a: parseFloat(cif.cell_length_a),
        b: parseFloat(cif.cell_length_b),
        c: parseFloat(cif.cell_length_c),
        alpha: parseFloat(cif.cell_angle_alpha),
        beta: parseFloat(cif.cell_angle_beta),
        gamma: parseFloat(cif.cell_angle_gamma),
        spacegroup: trimQuotes(cif['symmetry_space_group_name_H-M'])
    });
    var v = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var c = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var n = cif.atom_site_type_symbol.length;
    for (var i = 0; i < n; ++i) {
        atomStore.growIfFull();
        var atomname = cif.atom_site_label[i];
        var element = cif.atom_site_type_symbol[i];
        atomStore.atomTypeId[i] = atomMap.add(atomname, element);
        v.set(cif.atom_site_fract_x[i], cif.atom_site_fract_y[i], cif.atom_site_fract_z[i]);
        v.applyMatrix4(structure.unitcell.fracToCart);
        c.add(v);
        atomStore.x[i] = v.x;
        atomStore.y[i] = v.y;
        atomStore.z[i] = v.z;
        if (cif.atom_site_occupancy) {
            atomStore.occupancy[i] = parseFloat(cif.atom_site_occupancy[i]);
        }
        atomStore.serial[i] = i;
        structureBuilder.addAtom(0, '', '', 'HET', 1, true);
    }
    c.divideScalar(n);
    structure.center = c;
    buildUnitcellAssembly(structure);
    var v2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var v3 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var ml = structure.biomolDict.SUPERCELL.partList[0].matrixList;
    var k = n;
    function covalent(idx) {
        return atomMap.get(atomStore.atomTypeId[idx]).covalent;
    }
    var identityMatrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    var loop = function ( i ) {
        var covalentI = covalent(i);
        v.set(atomStore.x[i], atomStore.y[i], atomStore.z[i]);
        ml.forEach(function (m) {
            if (identityMatrix.equals(m))
                { return; }
            v2.copy(v);
            v2.applyMatrix4(m);
            for (var j = 0; j < n; ++j) {
                v3.set(atomStore.x[j], atomStore.y[j], atomStore.z[j]);
                var distSquared = v2.distanceToSquared(v3);
                var d = covalent(j) + covalentI;
                var d1 = d + 0.3;
                var d2 = d - 0.5;
                if (distSquared < (d1 * d1) && distSquared > (d2 * d2)) {
                    atomStore.growIfFull();
                    atomStore.atomTypeId[k] = atomStore.atomTypeId[i];
                    atomStore.x[k] = v2.x;
                    atomStore.y[k] = v2.y;
                    atomStore.z[k] = v2.z;
                    atomStore.occupancy[k] = atomStore.occupancy[i];
                    atomStore.serial[k] = k;
                    atomStore.altloc[k] = 'A'.charCodeAt(0);
                    structureBuilder.addAtom(0, '', '', 'HET', 1, true);
                    k += 1;
                    return;
                }
            }
        });
    };

    for (var i$1 = 0; i$1 < n; ++i$1) loop( i$1 );
}
function processSecondaryStructure(cif, structure, asymIdDict) {
    var helices = [];
    var sheets = [];
    var i, il, begIcode, endIcode;
    // get helices
    var sc = cif.struct_conf;
    if (sc) {
        ensureArray$1(sc, 'id');
        for (i = 0, il = sc.beg_auth_seq_id.length; i < il; ++i) {
            var helixType = parseInt(sc.pdbx_PDB_helix_class[i]);
            if (!Number.isNaN(helixType)) {
                begIcode = sc.pdbx_beg_PDB_ins_code[i];
                endIcode = sc.pdbx_end_PDB_ins_code[i];
                helices.push([
                    asymIdDict[sc.beg_label_asym_id[i]],
                    parseInt(sc.beg_auth_seq_id[i]),
                    cifDefaults(begIcode, ''),
                    asymIdDict[sc.end_label_asym_id[i]],
                    parseInt(sc.end_auth_seq_id[i]),
                    cifDefaults(endIcode, ''),
                    (HelixTypes[helixType] || HelixTypes[0]).charCodeAt(0)
                ]);
            }
        }
    }
    // get sheets
    var ssr = cif.struct_sheet_range;
    if (ssr) {
        ensureArray$1(ssr, 'id');
        for (i = 0, il = ssr.beg_auth_seq_id.length; i < il; ++i) {
            begIcode = ssr.pdbx_beg_PDB_ins_code[i];
            endIcode = ssr.pdbx_end_PDB_ins_code[i];
            sheets.push([
                asymIdDict[ssr.beg_label_asym_id[i]],
                parseInt(ssr.beg_auth_seq_id[i]),
                cifDefaults(begIcode, ''),
                asymIdDict[ssr.end_label_asym_id[i]],
                parseInt(ssr.end_auth_seq_id[i]),
                cifDefaults(endIcode, '')
            ]);
        }
    }
    if (sc || ssr) {
        return {
            helices: helices,
            sheets: sheets
        };
    }
    else {
        return false;
    }
}
function processSymmetry(cif, structure, asymIdDict) {
    // biomol & ncs processing
    var operDict = {};
    var biomolDict = structure.biomolDict;
    if (cif.pdbx_struct_oper_list) {
        var biomolOp = cif.pdbx_struct_oper_list;
        ensureArray$1(biomolOp, 'id');
        biomolOp.id.forEach(function (id, i) {
            var m = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
            var elms = m.elements;
            elms[0] = parseFloat(biomolOp['matrix[1][1]'][i]);
            elms[1] = parseFloat(biomolOp['matrix[1][2]'][i]);
            elms[2] = parseFloat(biomolOp['matrix[1][3]'][i]);
            elms[4] = parseFloat(biomolOp['matrix[2][1]'][i]);
            elms[5] = parseFloat(biomolOp['matrix[2][2]'][i]);
            elms[6] = parseFloat(biomolOp['matrix[2][3]'][i]);
            elms[8] = parseFloat(biomolOp['matrix[3][1]'][i]);
            elms[9] = parseFloat(biomolOp['matrix[3][2]'][i]);
            elms[10] = parseFloat(biomolOp['matrix[3][3]'][i]);
            elms[3] = parseFloat(biomolOp['vector[1]'][i]);
            elms[7] = parseFloat(biomolOp['vector[2]'][i]);
            elms[11] = parseFloat(biomolOp['vector[3]'][i]);
            m.transpose();
            operDict[id] = m;
        });
    }
    if (cif.pdbx_struct_assembly_gen) {
        var gen = cif.pdbx_struct_assembly_gen;
        ensureArray$1(gen, 'assembly_id');
        var getMatrixDict = function (expr) {
            var matDict = {};
            var l = expr.replace(/[()']/g, '').split(',');
            l.forEach(function (e) {
                if (e.includes('-')) {
                    var es = e.split('-');
                    var j = parseInt(es[0]);
                    var m = parseInt(es[1]);
                    for (; j <= m; ++j) {
                        matDict[j] = operDict[j];
                    }
                }
                else {
                    matDict[e] = operDict[e];
                }
            });
            return matDict;
        };
        gen.assembly_id.forEach(function (id, i) {
            var md = {};
            var oe = gen.oper_expression[i].replace(/['"]\(|['"]/g, '');
            if (oe.includes(')(') || oe.indexOf('(') > 0) {
                oe = oe.split('(');
                var md1 = getMatrixDict(oe[0]);
                var md2 = getMatrixDict(oe[1]);
                Object.keys(md1).forEach(function (k1) {
                    Object.keys(md2).forEach(function (k2) {
                        var mat = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
                        mat.multiplyMatrices(md1[k1], md2[k2]);
                        md[k1 + 'x' + k2] = mat;
                    });
                });
            }
            else {
                md = getMatrixDict(oe);
            }
            var matrixList = [];
            for (var k in md) {
                matrixList.push(md[k]);
            }
            var name = id;
            if (/^(0|[1-9][0-9]*)$/.test(name))
                { name = 'BU' + name; }
            var chainList = gen.asym_id_list[i].split(',');
            for (var j = 0, jl = chainList.length; j < jl; ++j) {
                chainList[j] = asymIdDict[chainList[j]];
            }
            if (biomolDict[name] === undefined) {
                biomolDict[name] = new Assembly(name);
            }
            biomolDict[name].addPart(matrixList, chainList);
        });
    }
    // non-crystallographic symmetry operations
    if (cif.struct_ncs_oper) {
        var ncsOp = cif.struct_ncs_oper;
        ensureArray$1(ncsOp, 'id');
        var ncsName = 'NCS';
        biomolDict[ncsName] = new Assembly(ncsName);
        var ncsPart = biomolDict[ncsName].addPart();
        ncsOp.id.forEach(function (id, i) {
            // ignore 'given' operators
            if (ncsOp.code[i] === 'given')
                { return; }
            var m = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
            var elms = m.elements;
            elms[0] = parseFloat(ncsOp['matrix[1][1]'][i]);
            elms[1] = parseFloat(ncsOp['matrix[1][2]'][i]);
            elms[2] = parseFloat(ncsOp['matrix[1][3]'][i]);
            elms[4] = parseFloat(ncsOp['matrix[2][1]'][i]);
            elms[5] = parseFloat(ncsOp['matrix[2][2]'][i]);
            elms[6] = parseFloat(ncsOp['matrix[2][3]'][i]);
            elms[8] = parseFloat(ncsOp['matrix[3][1]'][i]);
            elms[9] = parseFloat(ncsOp['matrix[3][2]'][i]);
            elms[10] = parseFloat(ncsOp['matrix[3][3]'][i]);
            elms[3] = parseFloat(ncsOp['vector[1]'][i]);
            elms[7] = parseFloat(ncsOp['vector[2]'][i]);
            elms[11] = parseFloat(ncsOp['vector[3]'][i]);
            m.transpose();
            ncsPart.matrixList.push(m);
        });
        if (ncsPart.matrixList.length === 0) {
            delete biomolDict[ncsName];
        }
    }
    // cell & symmetry
    var unitcellDict = {};
    if (cif.cell) {
        var cell = cif.cell;
        var a = parseFloat(cell.length_a);
        var b = parseFloat(cell.length_b);
        var c = parseFloat(cell.length_c);
        var box = new Float32Array(9);
        box[0] = a;
        box[4] = b;
        box[8] = c;
        structure.boxes.push(box);
        unitcellDict.a = a;
        unitcellDict.b = b;
        unitcellDict.c = c;
        unitcellDict.alpha = parseFloat(cell.angle_alpha);
        unitcellDict.beta = parseFloat(cell.angle_beta);
        unitcellDict.gamma = parseFloat(cell.angle_gamma);
    }
    if (cif.symmetry) {
        unitcellDict.spacegroup = trimQuotes(cif.symmetry['space_group_name_H-M']);
    }
    // origx
    var origx = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    if (cif.database_PDB_matrix) {
        var origxMat = cif.database_PDB_matrix;
        var origxElms = origx.elements;
        origxElms[0] = parseFloat(origxMat['origx[1][1]']);
        origxElms[1] = parseFloat(origxMat['origx[1][2]']);
        origxElms[2] = parseFloat(origxMat['origx[1][3]']);
        origxElms[4] = parseFloat(origxMat['origx[2][1]']);
        origxElms[5] = parseFloat(origxMat['origx[2][2]']);
        origxElms[6] = parseFloat(origxMat['origx[2][3]']);
        origxElms[8] = parseFloat(origxMat['origx[3][1]']);
        origxElms[9] = parseFloat(origxMat['origx[3][2]']);
        origxElms[10] = parseFloat(origxMat['origx[3][3]']);
        origxElms[3] = parseFloat(origxMat['origx_vector[1]']);
        origxElms[7] = parseFloat(origxMat['origx_vector[2]']);
        origxElms[11] = parseFloat(origxMat['origx_vector[3]']);
        origx.transpose();
        unitcellDict.origx = origx;
    }
    // scale
    var scale$$1 = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    if (cif.atom_sites) {
        var scaleMat = cif.atom_sites;
        var scaleElms = scale$$1.elements;
        scaleElms[0] = parseFloat(scaleMat['fract_transf_matrix[1][1]']);
        scaleElms[1] = parseFloat(scaleMat['fract_transf_matrix[1][2]']);
        scaleElms[2] = parseFloat(scaleMat['fract_transf_matrix[1][3]']);
        scaleElms[4] = parseFloat(scaleMat['fract_transf_matrix[2][1]']);
        scaleElms[5] = parseFloat(scaleMat['fract_transf_matrix[2][2]']);
        scaleElms[6] = parseFloat(scaleMat['fract_transf_matrix[2][3]']);
        scaleElms[8] = parseFloat(scaleMat['fract_transf_matrix[3][1]']);
        scaleElms[9] = parseFloat(scaleMat['fract_transf_matrix[3][2]']);
        scaleElms[10] = parseFloat(scaleMat['fract_transf_matrix[3][3]']);
        scaleElms[3] = parseFloat(scaleMat['fract_transf_vector[1]']);
        scaleElms[7] = parseFloat(scaleMat['fract_transf_vector[2]']);
        scaleElms[11] = parseFloat(scaleMat['fract_transf_vector[3]']);
        scale$$1.transpose();
        unitcellDict.scale = scale$$1;
    }
    if (unitcellDict.a !== undefined) {
        structure.unitcell = new Unitcell(unitcellDict);
    }
    else {
        structure.unitcell = undefined;
    }
}
function processConnections(cif, structure, asymIdDict) {
    // add connections
    var sc = cif.struct_conn;
    if (sc) {
        ensureArray$1(sc, 'id');
        var reDoubleQuote = /"/g;
        var ap1 = structure.getAtomProxy();
        var ap2 = structure.getAtomProxy();
        var atomIndicesCache = {};
        for (var i = 0, il = sc.id.length; i < il; ++i) {
            // ignore:
            // hydrog - hydrogen bond
            // mismat - mismatched base pairs
            // saltbr - ionic interaction
            var connTypeId = sc.conn_type_id[i];
            if (connTypeId === 'hydrog' ||
                connTypeId === 'mismat' ||
                connTypeId === 'saltbr')
                { continue; }
            // ignore bonds between symmetry mates
            if (sc.ptnr1_symmetry[i] !== '1_555' ||
                sc.ptnr2_symmetry[i] !== '1_555')
                { continue; }
            // process:
            // covale - covalent bond
            // covale_base -
            //      covalent modification of a nucleotide base
            // covale_phosphate -
            //      covalent modification of a nucleotide phosphate
            // covale_sugar -
            //      covalent modification of a nucleotide sugar
            // disulf - disulfide bridge
            // metalc - metal coordination
            // modres - covalent residue modification
            var inscode1 = sc.pdbx_ptnr1_PDB_ins_code[i];
            var altloc1 = sc.pdbx_ptnr1_label_alt_id[i];
            var sele1 = (sc.ptnr1_auth_seq_id[i] +
                (hasValue(inscode1) ? ('^' + inscode1) : '') +
                ':' + asymIdDict[sc.ptnr1_label_asym_id[i]] +
                '.' + sc.ptnr1_label_atom_id[i].replace(reDoubleQuote, '') +
                (hasValue(altloc1) ? ('%' + altloc1) : ''));
            var atomIndices1 = atomIndicesCache[sele1];
            if (!atomIndices1) {
                var selection1 = new Selection(sele1);
                if (selection1.selection.error) {
                    if (Debug)
                        { Log.warn('invalid selection for connection', sele1); }
                    continue;
                }
                atomIndices1 = structure.getAtomIndices(selection1);
                atomIndicesCache[sele1] = atomIndices1;
            }
            var inscode2 = sc.pdbx_ptnr2_PDB_ins_code[i];
            var altloc2 = sc.pdbx_ptnr2_label_alt_id[i];
            var sele2 = (sc.ptnr2_auth_seq_id[i] +
                (hasValue(inscode2) ? ('^' + inscode2) : '') +
                ':' + asymIdDict[sc.ptnr2_label_asym_id[i]] +
                '.' + sc.ptnr2_label_atom_id[i].replace(reDoubleQuote, '') +
                (hasValue(altloc2) ? ('%' + altloc2) : ''));
            var atomIndices2 = atomIndicesCache[sele2];
            if (!atomIndices2) {
                var selection2 = new Selection(sele2);
                if (selection2.selection.error) {
                    if (Debug)
                        { Log.warn('invalid selection for connection', sele2); }
                    continue;
                }
                atomIndices2 = structure.getAtomIndices(selection2);
                atomIndicesCache[sele2] = atomIndices2;
            }
            // cases with more than one atom per selection
            // - #altloc1 to #altloc2
            // - #model to #model
            // - #altloc1 * #model to #altloc2 * #model
            var k = atomIndices1.length;
            var l = atomIndices2.length;
            if (k > l) {
                var tmpA = k;
                k = l;
                l = tmpA;
                var tmpB = atomIndices1;
                atomIndices1 = atomIndices2;
                atomIndices2 = tmpB;
            }
            // console.log( k, l );
            if (k === 0 || l === 0) {
                if (Debug)
                    { Log.warn('no atoms found for', sele1, sele2); }
                continue;
            }
            for (var j = 0; j < l; ++j) {
                ap1.index = atomIndices1[j % k];
                ap2.index = atomIndices2[j];
                if (ap1 && ap2) {
                    structure.bondStore.addBond(ap1, ap2, getBondOrder(sc.pdbx_value_order[i]));
                }
                else {
                    Log.log('atoms for connection not found');
                }
            }
        }
    }
}
function processEntities(cif, structure, chainIndexDict) {
    if (cif.entity) {
        ensureArray$1(cif.entity, 'id');
        var e = cif.entity;
        var n = e.id.length;
        for (var i = 0; i < n; ++i) {
            var description = e.pdbx_description[i];
            var type = e.type[i];
            var chainIndexList = Array.from(chainIndexDict[e.id[i]]);
            structure.entityList[i] = new Entity(structure, i, description, type, chainIndexList);
        }
    }
}
//
var CifParser = /*@__PURE__*/(function (StructureParser$$1) {
    function CifParser () {
        StructureParser$$1.apply(this, arguments);
    }

    if ( StructureParser$$1 ) CifParser.__proto__ = StructureParser$$1;
    CifParser.prototype = Object.create( StructureParser$$1 && StructureParser$$1.prototype );
    CifParser.prototype.constructor = CifParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'cif'; };
    CifParser.prototype._parse = function _parse () {
        // http://mmcif.wwpdb.org/
        Log.time('CifParser._parse ' + this.name);
        var s = this.structure;
        var sb = this.structureBuilder;
        var firstModelOnly = this.firstModelOnly;
        var asTrajectory = this.asTrajectory;
        var cAlphaOnly = this.cAlphaOnly;
        var frames = s.frames;
        var currentFrame, currentCoord;
        var rawline, line;
        //
        var cif = {};
        var asymIdDict = {};
        var chainIndexDict = {};
        var pendingString = false;
        var currentString = null;
        var pendingValue = false;
        var pendingLoop = false;
        var pendingName = false;
        var loopPointers = [];
        var currentLoopIndex = null;
        var currentCategory = null;
        var currentName = null;
        var first = null;
        var pointerNames = [];
        var authAsymId, authSeqId, labelAtomId, labelCompId, labelAsymId, labelEntityId, labelAltId, groupPDB, id, typeSymbol, pdbxPDBmodelNum, pdbxPDBinsCode, CartnX, CartnY, CartnZ, bIsoOrEquiv, occupancy;
        //
        var atomMap = s.atomMap;
        var atomStore = s.atomStore;
        atomStore.resize(this.streamer.data.length / 100);
        var idx = 0;
        var modelIdx = 0;
        var modelNum;
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                rawline = lines[i];
                line = rawline.trim();
                if ((!line && !pendingString && !pendingLoop) || line[0] === '#') {
                    // Log.log( "NEW BLOCK" );
                    pendingString = false;
                    pendingLoop = false;
                    pendingValue = false;
                    loopPointers.length = 0;
                    currentLoopIndex = null;
                    currentCategory = null;
                    currentName = null;
                    first = null;
                    pointerNames.length = 0;
                }
                else if (line.substring(0, 5) === 'data_') {
                    cif.data = line.substring(5).trim();
                    // Log.log( "DATA", data );
                }
                else if (line[0] === ';') {
                    if (pendingString) {
                        // Log.log( "STRING END", currentString );
                        if (pendingLoop) {
                            if (currentLoopIndex === loopPointers.length) {
                                currentLoopIndex = 0;
                            }
                            loopPointers[currentLoopIndex].push(currentString);
                            currentLoopIndex += 1;
                        }
                        else {
                            if (currentName === false) {
                                cif[currentCategory] = currentString;
                            }
                            else {
                                cif[currentCategory][currentName] = currentString; //TODO currentname can equals null
                            }
                        }
                        pendingString = false;
                        currentString = null;
                    }
                    else {
                        // Log.log( "STRING START" );
                        pendingString = true;
                        currentString = line.substring(1);
                    }
                }
                else if (line === 'loop_') {
                    // Log.log( "LOOP START" );
                    pendingLoop = true;
                    pendingName = true;
                    loopPointers.length = 0;
                    pointerNames.length = 0;
                    currentLoopIndex = 0;
                }
                else if (line[0] === '_') {
                    var keyParts, category, name;
                    if (pendingLoop && !pendingName) {
                        pendingLoop = false;
                    }
                    if (pendingLoop) {
                        // Log.log( "LOOP KEY", line );
                        keyParts = line.split('.');
                        category = keyParts[0].substring(1);
                        name = keyParts[1];
                        if (keyParts.length === 1) {
                            name = false;
                            if (!cif[category])
                                { cif[category] = []; }
                            loopPointers.push(cif[category]);
                        }
                        else {
                            if (!cif[category])
                                { cif[category] = {}; }
                            if (cif[category][name]) {
                                if (Debug)
                                    { Log.warn(category, name, 'already exists'); }
                            }
                            else {
                                cif[category][name] = [];
                                loopPointers.push(cif[category][name]);
                                pointerNames.push(name);
                            }
                        }
                        currentCategory = category;
                        currentName = name;
                        first = true;
                    }
                    else {
                        var keyValuePair = line.match(reQuotedWhitespace);
                        var key = keyValuePair[0];
                        var value = keyValuePair[1];
                        keyParts = key.split('.');
                        category = keyParts[0].substring(1);
                        name = keyParts[1];
                        if (keyParts.length === 1) {
                            name = false;
                            cif[category] = value;
                        }
                        else {
                            if (!cif[category])
                                { cif[category] = {}; }
                            if (cif[category][name]) {
                                if (Debug)
                                    { Log.warn(category, name, 'already exists'); }
                            }
                            else {
                                cif[category][name] = value;
                            }
                        }
                        if (!value)
                            { pendingValue = true; }
                        currentCategory = category;
                        currentName = name;
                    }
                }
                else {
                    if (pendingString) {
                        // Log.log( "STRING VALUE", line );
                        currentString += rawline;
                    }
                    else if (pendingLoop) {
                        // Log.log( "LOOP VALUE", line );
                        if (!line) {
                            continue;
                        }
                        else if (currentCategory === 'atom_site') {
                            var ls = line.split(reWhitespace$1);
                            if (first) {
                                authAsymId = pointerNames.indexOf('auth_asym_id');
                                authSeqId = pointerNames.indexOf('auth_seq_id');
                                labelAtomId = pointerNames.indexOf('label_atom_id');
                                labelCompId = pointerNames.indexOf('label_comp_id');
                                labelAsymId = pointerNames.indexOf('label_asym_id');
                                labelEntityId = pointerNames.indexOf('label_entity_id');
                                labelAltId = pointerNames.indexOf('label_alt_id');
                                CartnX = pointerNames.indexOf('Cartn_x');
                                CartnY = pointerNames.indexOf('Cartn_y');
                                CartnZ = pointerNames.indexOf('Cartn_z');
                                id = pointerNames.indexOf('id');
                                typeSymbol = pointerNames.indexOf('type_symbol');
                                groupPDB = pointerNames.indexOf('group_PDB');
                                bIsoOrEquiv = pointerNames.indexOf('B_iso_or_equiv');
                                pdbxPDBmodelNum = pointerNames.indexOf('pdbx_PDB_model_num');
                                pdbxPDBinsCode = pointerNames.indexOf('pdbx_PDB_ins_code');
                                occupancy = pointerNames.indexOf('occupancy');
                                first = false;
                                modelNum = parseInt(ls[pdbxPDBmodelNum]);
                                if (asTrajectory) {
                                    currentFrame = [];
                                    currentCoord = 0;
                                }
                            }
                            //
                            var _modelNum = parseInt(ls[pdbxPDBmodelNum]);
                            if (modelNum !== _modelNum) {
                                if (asTrajectory) {
                                    if (modelIdx === 0) {
                                        frames.push(new Float32Array(currentFrame));
                                    }
                                    currentFrame = new Float32Array(atomStore.count * 3);
                                    frames.push(currentFrame);
                                    currentCoord = 0;
                                }
                                modelIdx += 1;
                            }
                            modelNum = _modelNum;
                            if (firstModelOnly && modelIdx > 0)
                                { continue; }
                            //
                            var atomname = ls[labelAtomId].replace(reDoubleQuote, '');
                            if (cAlphaOnly && atomname !== 'CA')
                                { continue; }
                            var x = parseFloat(ls[CartnX]);
                            var y = parseFloat(ls[CartnY]);
                            var z = parseFloat(ls[CartnZ]);
                            if (asTrajectory) {
                                var frameOffset = currentCoord * 3;
                                currentFrame[frameOffset + 0] = x;
                                currentFrame[frameOffset + 1] = y;
                                currentFrame[frameOffset + 2] = z;
                                currentCoord += 1;
                                if (modelIdx > 0)
                                    { continue; }
                            }
                            //
                            var resname = ls[labelCompId];
                            var resno = parseInt(ls[authSeqId]);
                            var inscode = ls[pdbxPDBinsCode];
                            inscode = (inscode === '?') ? '' : inscode;
                            var chainname = ls[authAsymId];
                            var chainid = ls[labelAsymId];
                            var hetero = (ls[groupPDB][0] === 'H') ? 1 : 0;
                            //
                            var element = ls[typeSymbol];
                            var bfactor = parseFloat(ls[bIsoOrEquiv]);
                            var occ = parseFloat(ls[occupancy]);
                            var altloc = ls[labelAltId];
                            altloc = (altloc === '.') ? '' : altloc;
                            atomStore.growIfFull();
                            atomStore.atomTypeId[idx] = atomMap.add(atomname, element);
                            atomStore.x[idx] = x;
                            atomStore.y[idx] = y;
                            atomStore.z[idx] = z;
                            atomStore.serial[idx] = parseInt(ls[id]);
                            atomStore.bfactor[idx] = isNaN(bfactor) ? 0 : bfactor;
                            atomStore.occupancy[idx] = isNaN(occ) ? 0 : occ;
                            atomStore.altloc[idx] = altloc.charCodeAt(0);
                            sb.addAtom(modelIdx, chainname, chainid, resname, resno, hetero, undefined, inscode);
                            if (Debug) {
                                // check if one-to-many (chainname-asymId) relationship is
                                // actually a many-to-many mapping
                                var assignedChainname = asymIdDict[chainid];
                                if (assignedChainname !== undefined && assignedChainname !== chainname) {
                                    if (Debug)
                                        { Log.warn(assignedChainname, chainname); }
                                }
                            }
                            // chainname mapping: label_asym_id -> auth_asym_id
                            asymIdDict[chainid] = chainname;
                            // entity mapping: chainIndex -> label_entity_id
                            var entityId = ls[labelEntityId];
                            if (!chainIndexDict[entityId]) {
                                chainIndexDict[entityId] = new Set();
                            }
                            chainIndexDict[entityId].add(s.chainStore.count - 1);
                            idx += 1;
                        }
                        else {
                            var ls$1 = line.match(reQuotedWhitespace);
                            var nn = ls$1.length;
                            if (currentLoopIndex === loopPointers.length) {
                                currentLoopIndex = 0;
                            } /* else if( currentLoopIndex + nn > loopPointers.length ){
                              Log.warn( "cif parsing error, wrong number of loop data entries", nn, loopPointers.length );
                            } */
                            for (var j = 0; j < nn; ++j) {
                                loopPointers[currentLoopIndex + j].push(ls$1[j]);
                            }
                            currentLoopIndex += nn;
                        }
                        pendingName = false;
                    }
                    else if (line[0] === "'" && line[line.length - 1] === "'") {
                        // Log.log( "NEWLINE STRING", line );
                        var str = line.substring(1, line.length - 1);
                        if (currentName === false) {
                            cif[currentCategory] = str;
                        }
                        else {
                            cif[currentCategory][currentName] = str;
                        }
                    }
                    else if (pendingValue) {
                        // Log.log( "NEWLINE VALUE", line );
                        if (currentName === false) {
                            cif[currentCategory] = line;
                        }
                        else {
                            cif[currentCategory][currentName] = line;
                        }
                    }
                    else {
                        if (Debug)
                            { Log.log('CifParser._parse: unknown state', line); }
                    }
                }
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        if (cif.chem_comp && cif.chem_comp_atom) {
            parseChemComp(cif, s, sb);
            sb.finalize();
            s.finalizeAtoms();
            s.finalizeBonds();
            assignResidueTypeBonds(s);
        }
        else if (cif.atom_site_type_symbol && cif.atom_site_label && cif.atom_site_fract_x) {
            parseCore(cif, s, sb);
            sb.finalize();
            s.finalizeAtoms();
            calculateBonds(s);
            s.finalizeBonds();
            // assignResidueTypeBonds( s );
        }
        else {
            var secStruct = processSecondaryStructure(cif, s, asymIdDict);
            processSymmetry(cif, s, asymIdDict);
            processConnections(cif, s, asymIdDict);
            processEntities(cif, s, chainIndexDict);
            if (cif.struct && cif.struct.title) {
                s.title = cif.struct.title.trim().replace(reTrimQuotes, '');
            }
            if (cif.entry && cif.entry.id) {
                s.id = cif.entry.id.trim().replace(reTrimQuotes, '');
            }
            // structure header (mimicking biojava)
            if (cif.pdbx_audit_revision_history) {
                if (cif.pdbx_audit_revision_history.revision_date) {
                    ensureArray$1(cif.pdbx_audit_revision_history, 'revision_date');
                    var dates = cif.pdbx_audit_revision_history.revision_date.filter(hasValue);
                    if (dates.length) {
                        s.header.releaseDate = dates[0];
                    }
                }
                if (cif.pdbx_database_status.recvd_initial_deposition_date) {
                    ensureArray$1(cif.pdbx_database_status, 'recvd_initial_deposition_date');
                    var depDates = cif.pdbx_database_status.recvd_initial_deposition_date.filter(hasValue);
                    if (depDates.length) {
                        s.header.depositionDate = depDates[0];
                    }
                }
            }
            else if (cif.database_PDB_rev) {
                if (cif.database_PDB_rev.date) {
                    ensureArray$1(cif.database_PDB_rev, 'date');
                    var dates$1 = cif.database_PDB_rev.date.filter(hasValue);
                    if (dates$1.length) {
                        s.header.releaseDate = dates$1[0];
                    }
                }
                if (cif.database_PDB_rev.date_original) {
                    ensureArray$1(cif.database_PDB_rev, 'date_original');
                    var depDates$1 = cif.database_PDB_rev.date_original.filter(hasValue);
                    if (depDates$1.length) {
                        s.header.depositionDate = depDates$1[0];
                    }
                }
            }
            if (cif.reflns && cif.reflns.d_resolution_high) {
                if (hasValue(cif.reflns.d_resolution_high)) {
                    s.header.resolution = parseFloat(cif.reflns.d_resolution_high);
                }
            }
            else if (cif.refine && cif.refine.ls_d_res_high) {
                if (hasValue(cif.refine.ls_d_res_high)) {
                    s.header.resolution = parseFloat(cif.refine.ls_d_res_high);
                }
            }
            if (cif.refine && cif.refine.ls_R_factor_R_free) {
                if (hasValue(cif.refine.ls_R_factor_R_free)) {
                    s.header.rFree = parseFloat(cif.refine.ls_R_factor_R_free);
                }
            }
            if (cif.refine && cif.refine.ls_R_factor_R_work) {
                if (hasValue(cif.refine.ls_R_factor_R_work)) {
                    s.header.rWork = parseFloat(cif.refine.ls_R_factor_R_work);
                }
            }
            if (cif.exptl && cif.exptl.method) {
                ensureArray$1(cif.exptl, 'method');
                s.header.experimentalMethods = cif.exptl.method.map(function (m) {
                    return m.replace(reTrimQuotes, '');
                });
            }
            sb.finalize();
            s.finalizeAtoms();
            calculateBonds(s);
            s.finalizeBonds();
            if (!secStruct) {
                calculateSecondaryStructure(s);
            }
            else {
                assignSecondaryStructure(s, secStruct);
            }
            buildUnitcellAssembly(s);
            s.extraData.cif = cif;
        }
        if (Debug)
            { Log.timeEnd('CifParser._parse ' + this.name); }
    };

    Object.defineProperties( CifParser.prototype, prototypeAccessors );

    return CifParser;
}(StructureParser));
ParserRegistry$1.add('cif', CifParser);
ParserRegistry$1.add('mcif', CifParser);
ParserRegistry$1.add('mmcif', CifParser);

/**
 * @file Gro Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var GroParser = /*@__PURE__*/(function (StructureParser$$1) {
    function GroParser () {
        StructureParser$$1.apply(this, arguments);
    }

    if ( StructureParser$$1 ) GroParser.__proto__ = StructureParser$$1;
    GroParser.prototype = Object.create( StructureParser$$1 && StructureParser$$1.prototype );
    GroParser.prototype.constructor = GroParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'gro'; };
    GroParser.prototype._parse = function _parse () {
        // http://manual.gromacs.org/current/online/gro.html
        if (Debug)
            { Log.time('GroParser._parse ' + this.name); }
        var s = this.structure;
        var sb = this.structureBuilder;
        var firstModelOnly = this.firstModelOnly;
        var asTrajectory = this.asTrajectory;
        var cAlphaOnly = this.cAlphaOnly;
        var frames = s.frames;
        var boxes = s.boxes;
        var currentFrame, currentCoord;
        var firstLines = this.streamer.peekLines(3);
        s.title = firstLines[0].trim();
        // determine number of decimal places
        var ndec = firstLines[2].length - firstLines[2].lastIndexOf('.') - 1;
        var lpos = 5 + ndec;
        var xpos = 20;
        var ypos = 20 + lpos;
        var zpos = 20 + 2 * lpos;
        //
        var atomname, resname, resno, serial;
        var atomCount = parseInt(firstLines[1]);
        var modelLineCount = atomCount + 3;
        var atomMap = s.atomMap;
        var atomStore = s.atomStore;
        atomStore.resize(atomCount);
        var idx = 0;
        var modelIdx = 0;
        var lineNo = 0;
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                ++lineNo;
                var l = lineNo - 1;
                var line = lines[i];
                if (!line)
                    { continue; }
                if (l % modelLineCount === 0) {
                    // Log.log( "title", line )
                    if (asTrajectory) {
                        currentFrame = new Float32Array(atomCount * 3);
                        frames.push(currentFrame);
                        currentCoord = 0;
                    }
                }
                else if (l % modelLineCount === 1) ;
                else if (l % modelLineCount === modelLineCount - 1) {
                    var str = line.trim().split(/\s+/);
                    var box = new Float32Array(9);
                    box[0] = parseFloat(str[0]) * 10;
                    box[4] = parseFloat(str[1]) * 10;
                    box[8] = parseFloat(str[2]) * 10;
                    boxes.push(box);
                    if (firstModelOnly) {
                        return true;
                    }
                    modelIdx += 1;
                }
                else {
                    atomname = line.substr(10, 5).trim();
                    if (cAlphaOnly && atomname !== 'CA')
                        { continue; }
                    var x = parseFloat(line.substr(xpos, lpos)) * 10;
                    var y = parseFloat(line.substr(ypos, lpos)) * 10;
                    var z = parseFloat(line.substr(zpos, lpos)) * 10;
                    if (asTrajectory) {
                        var j = currentCoord * 3;
                        currentFrame[j + 0] = x;
                        currentFrame[j + 1] = y;
                        currentFrame[j + 2] = z;
                        currentCoord += 1;
                        if (l > modelLineCount)
                            { continue; }
                    }
                    resname = line.substr(5, 5).trim();
                    resno = parseInt(line.substr(0, 5));
                    serial = parseInt(line.substr(15, 5));
                    atomStore.growIfFull();
                    atomStore.atomTypeId[idx] = atomMap.add(atomname);
                    atomStore.x[idx] = x;
                    atomStore.y[idx] = y;
                    atomStore.z[idx] = z;
                    atomStore.serial[idx] = serial;
                    sb.addAtom(modelIdx, '', '', resname, resno, 0, 'l');
                    idx += 1;
                }
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        sb.finalize();
        s.finalizeAtoms();
        calculateChainnames(s);
        calculateBonds(s);
        s.finalizeBonds();
        calculateSecondaryStructure(s);
        if (Debug)
            { Log.timeEnd('GroParser._parse ' + this.name); }
    };

    Object.defineProperties( GroParser.prototype, prototypeAccessors );

    return GroParser;
}(StructureParser));
ParserRegistry$1.add('gro', GroParser);

/**
 * @file utf8-utils
 * @private
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * mostly copied from https://github.com/creationix/msgpack-js-browser
 * by Tim Caswell <tim@creationix.com>, MIT License, Copyright (c) 2013
 */

/**
 * @file mmtf-constants
 * @private
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var PassThroughFields = [
    "mmtfVersion", "mmtfProducer",
    "unitCell", "spaceGroup", "structureId", "title",
    "depositionDate", "releaseDate",
    "experimentalMethods", "resolution", "rFree", "rWork",
    "bioAssemblyList", "ncsOperatorList", "entityList", "groupList",
    "numBonds", "numAtoms", "numGroups", "numChains", "numModels",
    "groupsPerChain", "chainsPerModel" ];

var EncodedFields = [
	// required
    "xCoordList", "yCoordList", "zCoordList",
    "groupIdList", "groupTypeList",
    "chainIdList",
    // optional
    "bFactorList", "atomIdList", "altLocList", "occupancyList",
    "secStructList", "insCodeList", "sequenceIndexList",
    "chainNameList",
    "bondAtomList", "bondOrderList"
];

var AllFields = PassThroughFields.concat( EncodedFields );

/**
 * @file mmtf-utils
 * @private
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

/**
 * mmtf utils module.
 * @module MmtfUtils
 */


function getView( ctor, typedArray, elemSize ){
    return typedArray ? new ctor(
        typedArray.buffer,
        typedArray.byteOffset,
        typedArray.byteLength / ( elemSize || 1 )
    ) : undefined;
}

function getDataView( typedArray ){
    return getView( DataView, typedArray );
}

/**
 * get an Uint8Array view on the input array memory
 * @static
 * @param  {TypedArray} dataArray - input array
 * @return {Uint8Array} new view on the input array memory
 */
function getUint8View( typedArray ){
    return getView( Uint8Array, typedArray );
}

/**
 * get an Int8Array view on the input array memory
 * @static
 * @param  {TypedArray} dataArray - input array
 * @return {Int8Array} new view on the input array memory
 */
function getInt8View( typedArray ){
    return getView( Int8Array, typedArray );
}

/**
 * get an Int32Array view on the input array memory
 * @static
 * @param  {TypedArray} dataArray - input array
 * @return {Int32Array} new view on the input array memory
 */
function getInt32View( typedArray ){
    return getView( Int32Array, typedArray, 4 );
}

function getFloat32View( typedArray ){
    return getView( Float32Array, typedArray, 4 );
}


/**
 * get an Int16Array copy of the the input array data
 * @static
 * @param  {TypedArray} view - input data in big endian format
 * @param  {Int16Array} [dataArray] - pre-allocated output array
 * @return {Int16Array} copy of the input array data
 */
function decodeInt16( bytes, output ){
    var n = bytes.length / 2;
    if( !output ) { output = new Int16Array( n ); }
    for( var i = 0, i2 = 0; i < n; ++i, i2 += 2 ){
        output[ i ] = bytes[ i2 ] << 8 ^ bytes[ i2 + 1 ] << 0;
    }
    return output;
}

/**
 * get an Int32Array copy of the the input array data
 * @static
 * @param  {TypedArray} view - input data in big endian format
 * @param  {Int32Array} [dataArray] - pre-allocated output array
 * @return {Int32Array} copy of the input array data
 */
function decodeInt32( bytes, output ){
    var n = bytes.length / 4;
    if( !output ) { output = new Int32Array( n ); }
    for( var i = 0, i4 = 0; i < n; ++i, i4 += 4 ){
        output[ i ] = (
            bytes[ i4     ] << 24 ^ bytes[ i4 + 1 ] << 16 ^
            bytes[ i4 + 2 ] <<  8 ^ bytes[ i4 + 3 ] <<  0
        );
    }
    return output;
}

function decodeFloat32( bytes, output ){
    var n = bytes.length;
    if( !output ) { output = new Float32Array( n / 4 ); }
    var dvOut = getDataView( output );
    var dvIn = getDataView( bytes );
    for( var i = 0, i4 = 0, il = n / 4; i < il; ++i, i4 += 4 ){
        dvOut.setFloat32( i4, dvIn.getFloat32( i4 ), true );
    }
    return output;
}

/**
 * decode integers into floats using given divisor
 * example:
 *     intArray: [ 12, 34, 543, 687, 2, 0, 4689 ]
 *     divisor: 100
 *     return: [ 0.12, 0.34, 5.43, 6.87, 0.02, 0.00, 46.89 ]
 * @static
 * @param  {TypedArray|Array} intArray - input array containing integers
 * @param  {Number} divisor - number to devide the integers to obtain floats
 * @param  {Float32Array} [dataArray] - pre-allocated output array
 * @return {Float32Array} decoded array
 */
function decodeInteger( intArray, divisor, output ){
    var n = intArray.length;
    var invDiv = 1/divisor;
    if( !output ) { output = new Float32Array( n ); }
    for( var i = 0; i < n; ++i ){
        // multiply by inverse of the divisor which is faster then division
        output[ i ] = intArray[ i ] * invDiv;
    }
    return output;
}



/**
 * perform run-length decoding of input array
 * example:
 *     array: [ 0, 2, 3, 5 ]  // pairs of values and length of a run
 *     return: [ 0, 0, 3, 3, 3, 3, 3 ]
 * @static
 * @param  {TypedArray|Array} array - run-length encoded input array
 * @param  {TypedArray|Array} [dataArray] - pre-allocated output array
 * @return {TypedArray|Array} decoded array
 */
function decodeRun( array, output ){
    var i, il;
    if( !output ){
        // calculate the length the decoded array will have
        var fullLength = 0;
        for( i = 0, il = array.length; i < il; i+=2 ){
            fullLength += array[ i + 1 ];
        }
        // create a new array of the same type of the input array
        output = new array.constructor( fullLength );
    }
    var dataOffset = 0;
    for( i = 0, il = array.length; i < il; i+=2 ){
        var value = array[ i ];  // value to be repeated
        var length = array[ i + 1 ];  // number of repeats
        for( var j = 0; j < length; ++j ){
            output[ dataOffset ] = value;
            ++dataOffset;
        }
    }
    return output;
}



/**
 * perform delta decoding of the input array
 * by iterativly adding the ith element's value to the i+1th
 * example:
 *     dataArray: [ 0, 2, 1, 2, 1, 1, -4, -2, 9 ]
 *     return: [ 0, 2, 3, 5, 6, 7, 3, 1, 10 ]
 * @static
 * @param  {TypedArray|Array} dataArray - delta encoded input array
 * @return {TypedArray|Array} decoded array
 */
function decodeDelta( array, output ){
    var n = array.length;
    if( !output ) { output = new array.constructor( n ); }
    if( n ) { output[ 0 ] = array[ 0 ]; }
    for( var i = 1; i < n; ++i ){
        output[ i ] = array[ i ] + output[ i - 1 ];
    }
    return output;
}



/**
 * [decodePacking description]
 * @param  {Int16Array|Int8Array} int16or8 [description]
 * @param  {Int32Array} output   [description]
 * @return {Int32Array}          [description]
 */
function decodePacking( int16or8, output ){
    var upperLimit = int16or8 instanceof Int8Array ? 0x7F : 0x7FFF;
    var lowerLimit = -upperLimit - 1;
    var n = int16or8.length;
    var i, j;
    if( !output ){
        var fullLength = 0;
        for( i = 0; i < n; ++i ){
            if( int16or8[ i ] < upperLimit && int16or8[ i ] > lowerLimit ){
                ++fullLength;
            }
        }
        output = new Int32Array( fullLength );
    }
    i = 0;
    j = 0;
    while( i < n ){
        var value = 0;
        while( int16or8[ i ] === upperLimit || int16or8[ i ] === lowerLimit ){
            value += int16or8[ i ];
            ++i;
        }
        value += int16or8[ i ];
        ++i;
        output[ j ] = value;
        ++j;
    }
    return output;
}



function decodeDeltaRun( array, output ){
    return decodeDelta( decodeRun( array ), output );
}



/**
 * perform run-length decoding followed (@see decodeRunLength)
 * by decoding integers into floats using given divisor (@see decodeIntegerToFloat)
 * example:
 *     array: [ 320, 3, 100, 2 ]
 *     divisor: 100
 *     return: [ 3.20, 3.20, 3.20, 1.00, 1.00 ]
 * @static
 * @param  {Uint8Array} array - run-length encoded int32 array as bytes in big endian format
 * @param  {Integer} divisor - number to devide the integers to obtain floats
 * @param  {Float32Array} dataArray - pre-allocated output array
 * @return {Float32Array} decoded array
 */
function decodeIntegerRun( intArray, divisor, output ){
    return decodeInteger(
        decodeRun( intArray, getInt32View( output ) ), divisor, output
    );
}



function decodeIntegerDelta( intArray, divisor, output ){
    return decodeInteger(
        decodeDelta( intArray, getInt32View( output ) ), divisor, output
    );
}



function decodeIntegerPacking( int16or8, divisor, output ){
    return decodeInteger(
        decodePacking( int16or8, getInt32View( output ) ), divisor, output
    );
}

function decodeIntegerDeltaPacking( int16or8, divisor, output ){
    var unpacked = decodePacking( int16or8, getInt32View( output ) );
    return decodeIntegerDelta( unpacked, divisor, getFloat32View( unpacked ) );
}



function decodeBytes( bytes ){
    var dv = getDataView( bytes );
    var type = dv.getInt32( 0 );
    var size = dv.getInt32( 4 );
    var param = bytes.subarray( 8, 12 );
    var bytes = bytes.subarray( 12 );
    return [ type, bytes, size, param ];
}

/**
 * @file msgpack-decode
 * @private
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

/**
 * msgpack decode module.
 * @module MsgpackDecode
 */

/**
 * decode binary encoded MessagePack v5 (http://msgpack.org/) data
 * @static
 * @param  {Uint8Array} buffer - binary encoded MessagePack data
 * @return {Object|Array|String|Number|Boolean|null} decoded Messagepack data
 */
function decodeMsgpack(buffer) {
  // Loosely based on
  // The MIT License (MIT)
  // Copyright (c) 2013 Tim Caswell <tim@creationix.com>
  // https://github.com/creationix/msgpack-js
  var offset = 0;
  var dataView = new DataView(buffer.buffer);

  /**
   * decode all key-value pairs of a map into an object
   * @param  {Integer} length - number of key-value pairs
   * @return {Object} decoded map
   */
  function map(length) {
    var value = {};
    for (var i = 0; i < length; i++) {
      var key = parse();
      value[key] = parse();
    }
    return value;
  }

  /**
   * decode binary array
   * @param  {Integer} length - number of elements in the array
   * @return {Uint8Array} decoded array
   */
  function bin(length) {
    var value = buffer.subarray(offset, offset + length);
    offset += length;
    return value;
  }

  /**
   * decode string
   * @param  {Integer} length - number string characters
   * @return {String} decoded string
   */
  function str(length) {
    var array = buffer.subarray(offset, offset + length);
    offset += length;
    // limit number of arguments to String.fromCharCode to something
    // browsers can handle, see http://stackoverflow.com/a/22747272
    var chunkSize = 0xffff;
    if(length > chunkSize){
      var c = [];
      for(var i = 0; i < array.length; i += chunkSize) {
        c.push(String.fromCharCode.apply(
          null, array.subarray(i, i + chunkSize)
        ));
      }
      return c.join("");
    }else{
      return String.fromCharCode.apply(null, array);
    }
  }

  /**
   * decode array
   * @param  {Integer} length - number of array elements
   * @return {Array} decoded array
   */
  function array(length) {
    var value = new Array(length);
    for (var i = 0; i < length; i++) {
      value[i] = parse();
    }
    return value;
  }

  /**
   * recursively parse the MessagePack data
   * @return {Object|Array|String|Number|Boolean|null} decoded MessagePack data
   */
  function parse() {
    var type = buffer[offset];
    var value, length;
    // Positive FixInt
    if ((type & 0x80) === 0x00) {
      offset++;
      return type;
    }
    // FixMap
    if ((type & 0xf0) === 0x80) {
      length = type & 0x0f;
      offset++;
      return map(length);
    }
    // FixArray
    if ((type & 0xf0) === 0x90) {
      length = type & 0x0f;
      offset++;
      return array(length);
    }
    // FixStr
    if ((type & 0xe0) === 0xa0) {
      length = type & 0x1f;
      offset++;
      return str(length);
    }
    // Negative FixInt
    if ((type & 0xe0) === 0xe0) {
      value = dataView.getInt8(offset);
      offset++;
      return value;
    }
    switch (type) {
    // nil
    case 0xc0:
      offset++;
      return null;
    // 0xc1: (never used, could be employed for padding)
    // false
    case 0xc2:
      offset++;
      return false;
    // true
    case 0xc3:
      offset++;
      return true;
    // bin 8
    case 0xc4:
      length = dataView.getUint8(offset + 1);
      offset += 2;
      return bin(length);
    // bin 16
    case 0xc5:
      length = dataView.getUint16(offset + 1);
      offset += 3;
      return bin(length);
    // bin 32
    case 0xc6:
      length = dataView.getUint32(offset + 1);
      offset += 5;
      return bin(length);
    // // ext 8
    // case 0xc7:
    //   length = dataView.getUint8(offset + 1);
    //   extType = dataView.getUint8(offset + 2);
    //   offset += 3;
    //   return [extType, bin(length)];
    // // ext 16
    // case 0xc8:
    //   length = dataView.getUint16(offset + 1);
    //   extType = dataView.getUint8(offset + 3);
    //   offset += 4;
    //   return [extType, bin(length)];
    // // ext 32
    // case 0xc9:
    //   length = dataView.getUint32(offset + 1);
    //   extType = dataView.getUint8(offset + 5);
    //   offset += 6;
    //   return [extType, bin(length)];
    // float 32
    case 0xca:
      value = dataView.getFloat32(offset + 1);
      offset += 5;
      return value;
    // float 64
    case 0xcb:
      value = dataView.getFloat64(offset + 1);
      offset += 9;
      return value;
    // uint8
    case 0xcc:
      value = buffer[offset + 1];
      offset += 2;
      return value;
    // uint 16
    case 0xcd:
      value = dataView.getUint16(offset + 1);
      offset += 3;
      return value;
    // uint 32
    case 0xce:
      value = dataView.getUint32(offset + 1);
      offset += 5;
      return value;
    // // uint64
    // case 0xcf:
    //   // FIXME not available/representable in JS
    //   // largest possible int in JS is 2^53
    //   // value = dataView.getUint64(offset + 1);
    //   offset += 9;
    //   return 0;
    // int 8
    case 0xd0:
      value = dataView.getInt8(offset + 1);
      offset += 2;
      return value;
    // int 16
    case 0xd1:
      value = dataView.getInt16(offset + 1);
      offset += 3;
      return value;
    // int 32
    case 0xd2:
      value = dataView.getInt32(offset + 1);
      offset += 5;
      return value;
    // // int 64
    // case 0xd3:
    //   // FIXME not available/representable in JS
    //   // largest possible int in JS is 2^53
    //   // value = dataView.getInt64(offset + 1);
    //   offset += 9;
    //   return 0;

    // // fixext 1
    // case 0xd4:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(1)];
    // // fixext 2
    // case 0xd5:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(2)];
    // // fixext 4
    // case 0xd6:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(4)];
    // // fixext 8
    // case 0xd7:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(8)];
    // // fixext 16
    // case 0xd8:
    //   extType = dataView.getUint8(offset + 1);
    //   offset += 2;
    //   return [extType, bin(16)];
    // str 8
    case 0xd9:
      length = dataView.getUint8(offset + 1);
      offset += 2;
      return str(length);
    // str 16
    case 0xda:
      length = dataView.getUint16(offset + 1);
      offset += 3;
      return str(length);
    // str 32
    case 0xdb:
      length = dataView.getUint32(offset + 1);
      offset += 5;
      return str(length);
    // array 16
    case 0xdc:
      length = dataView.getUint16(offset + 1);
      offset += 3;
      return array(length);
    // array 32
    case 0xdd:
      length = dataView.getUint32(offset + 1);
      offset += 5;
      return array(length);
    // map 16:
    case 0xde:
      length = dataView.getUint16(offset + 1);
      offset += 3;
      return map(length);
    // map 32
    case 0xdf:
      length = dataView.getUint32(offset + 1);
      offset += 5;
      return map(length);
    }

    throw new Error("Unknown type 0x" + type.toString(16));
  }

  // start the recursive parsing
  return parse();
}

/**
 * Fields shared in encoded and decoded mmtf data objects.
 * @typedef {Object} module:MmtfDecode.SharedMmtfData
 * @property {String} mmtfVersion - MMTF specification version
 * @property {String} mmtfProducer - Program that created the file
 * @property {Float[]} [unitCell] - Crystallographic unit cell
 * @property {Float} unitCell.0 - x length
 * @property {Float} unitCell.1 - y length
 * @property {Float} unitCell.2 - z length
 * @property {Float} unitCell.3 - alpha angle
 * @property {Float} unitCell.4 - beta angle
 * @property {Float} unitCell.5 - gamma angle
 * @property {String} [spaceGroup] - Hermann-Mauguin symbol
 * @property {String} [structureId] - Some reference, e.g. a PDB ID
 * @property {String} [title] - Short description
 * @property {String} [depositionDate] - Deposition date in YYYY-MM-DD format
 * @property {String} [releaseDate] - Release date in YYYY-MM-DD format
 * @property {String[]} [experimentalMethods] - Structure determination methods
 * @property {Float} [resolution] - Resolution in Å
 * @property {Float} [rFree] - R-free value
 * @property {Float} [rWork] - R-work value
 * @property {Integer} numBonds - Number of bonds
 * @property {Integer} numAtoms - Number of atoms
 * @property {Integer} numGroups - Number of groups (residues)
 * @property {Integer} numChains - Number of chains
 * @property {Integer} numModels - Number of models
 * @property {Integer[]} chainsPerModel - List of number of chains in each model
 * @property {Integer[]} groupsPerChain - List of number of groups in each chain
 * @property {Entity[]} [entityList] - List of entity objects
 * @property {Integer[]} entityList.chainIndexList - Pointers into chain data fields
 * @property {String} entityList.description - Description of the entity
 * @property {String} entityList.type - Name of the entity type
 * @property {String} entityList.sequence - One letter code sequence
 * @property {Assembly[]} [bioAssemblyList] - List of assembly objects
 * @property {Transform[]} bioAssemblyList.transformList - List of transform objects
 * @property {Integer[]} bioAssemblyList.transformList.chainIndexList - Pointers into chain data fields
 * @property {Float[]} bioAssemblyList.transformList.matrix - 4x4 transformation matrix
 * @property {Array[]} [ncsOperatorList] - List of ncs operator matrices
 * @property {Float[]} ncsOperatorList. - 4x4 transformation matrix
 * @property {GroupType[]} groupList - List of groupType objects
 * @property {Integer[]} groupList.formalChargeList - List of atom formal charges
 * @property {String[]} groupList.elementList - List of elements
 * @property {String[]} groupList.atomNameList - List of atom names
 * @property {Integer[]} groupList.bondAtomList - List of bonded atom indices
 * @property {Integer[]} groupList.bondOrderList - List of bond orders
 * @property {String} groupList.groupName - The name of the group
 * @property {String} groupList.singleLetterCode - The single letter code
 * @property {String} groupList.chemCompType -  The chemical component type
 */

/**
 * Encoded mmtf data object. Also includes the fields from {@link module:MmtfDecode.SharedMmtfData}. See MMTF specification on how they are encoded.
 * @typedef {Object} module:MmtfDecode.EncodedMmtfData
 * @mixes module:MmtfDecode.SharedMmtfData
 * @property {Uint8Array} [bondAtomList] - Encoded bonded atom indices
 * @property {Uint8Array} [bondOrderList] - Encoded bond orders
 * @property {Uint8Array} xCoordBig - Encoded x coordinates in Å, part 1
 * @property {Uint8Array} xCoordSmall - Encoded x coordinates in Å, part 2
 * @property {Uint8Array} yCoordBig - Encoded y coordinates in Å, part 1
 * @property {Uint8Array} yCoordSmall - Encoded y coordinates in Å, part 2
 * @property {Uint8Array} yCoordBig - Encoded y coordinates in Å, part 1
 * @property {Uint8Array} yCoordSmall - Encoded y coordinates in Å, part 2
 * @property {Uint8Array} [bFactorBig] - Encoded B-factors in Å^2, part 1
 * @property {Uint8Array} [bFactorSmall] - Encoded B-factors in Å^2, part 2
 * @property {Uint8Array} [atomIdList] - Encoded  atom ids
 * @property {Uint8Array} [altLocList] - Encoded alternate location labels
 * @property {Uint8Array} [occupancyList] - Encoded occupancies
 * @property {Uint8Array} groupIdList - Encoded group ids
 * @property {Uint8Array} groupTypeList - Encoded group types
 * @property {Uint8Array} [secStructList] - Encoded secondary structure codes
 * @property {Uint8Array} [insCodeList] - Encoded insertion codes
 * @property {Uint8Array} [seuenceIdList] - Encoded sequence ids
 * @property {Uint8Array} chainIdList - Encoded chain ids
 * @property {Uint8Array} [chainNameList] - Encoded chain names
 */

/**
 * Decoded mmtf data object. Also includes fields the from {@link module:MmtfDecode.SharedMmtfData}.
 * @typedef {Object} module:MmtfDecode.MmtfData
 * @mixes module:MmtfDecode.SharedMmtfData
 * @property {Int32Array} [bondAtomList] - List of bonded atom indices
 * @property {Uint8Array} [bondOrderList] - List of bond orders
 * @property {Float32Array} xCoordList - List of x coordinates in Å
 * @property {Float32Array} yCoordList - List of y coordinates in Å
 * @property {Float32Array} zCoordList - List of z coordinates in Å
 * @property {Float32Array} [bFactorList] - List of B-factors in Å^2
 * @property {Int32Array} [atomIdList] - List of atom ids
 * @property {Uint8Array} [altLocList] - List of alternate location labels
 * @property {Float32Array} [occupancyList] - List of occupancies
 * @property {Int32Array} groupIdList - List of group ids
 * @property {Int32Array} groupTypeList - List of group types
 * @property {Int8Array} [secStructList] - List of secondary structure codes, encoding
 *    0: pi helix, 1: bend, 2: alpha helix, 3: extended,
 *    4: 3-10 helix, 5: bridge, 6: turn, 7: coil, -1: undefined
 * @property {Uint8Array} [insCodeList] - List of insertion codes
 * @property {Int32Array} [seuenceIdList] - List of sequence ids
 * @property {Uint8Array} chainIdList - List of chain ids
 * @property {Uint8Array} [chainNameList] - List of chain names
 */


/**
 * [performDecoding description]
 * @param  {Integer} bytes [description]
 * @param  {Integer} size  [description]
 * @param  {Uint8Array} param [description]
 * @return {TypedArray}       [description]
 */
function performDecoding( type, bytes, size, param ){

    switch( type ){
        case 1:
            return decodeFloat32( bytes );
        case 2:
            return getInt8View( bytes );
        case 3:
            return decodeInt16( bytes );
        case 4:
            return decodeInt32( bytes );
        case 5:
            // var length = decodeInt32( param )[ 0 ];
            return getUint8View( bytes );  // interpret as string array
        case 6:
            // interpret as char array
            return decodeRun( decodeInt32( bytes ), new Uint8Array( size ) );
        case 7:
            return decodeRun( decodeInt32( bytes ) )
        case 8:
            return decodeDeltaRun( decodeInt32( bytes ) );
        case 9:
            return decodeIntegerRun( decodeInt32( bytes ), decodeInt32( param )[ 0 ] );
        case 10:
            return decodeIntegerDeltaPacking( decodeInt16( bytes ), decodeInt32( param )[ 0 ] );
        case 11:
            return decodeInteger( decodeInt16( bytes ), decodeInt32( param )[ 0 ] );
        case 12:
            return decodeIntegerPacking( decodeInt16( bytes ), decodeInt32( param )[ 0 ] );
        case 13:
            return decodeIntegerPacking( getInt8View( bytes ), decodeInt32( param )[ 0 ] );
        case 14:
            return decodePacking( decodeInt16( bytes ) );
        case 15:
            return decodePacking( getInt8View( bytes ) );
    }

}

/**
 * Decode MMTF fields
 * @static
 * @param  {Object} inputDict - encoded MMTF data
 * @param  {Object} [params] - decoding parameters
 * @param  {String[]} params.ignoreFields - names of optional fields not to decode
 * @return {module:MmtfDecode.MmtfData} mmtfData
 */
function decodeMmtf( inputDict, params ){

    params = params || {};
    var ignoreFields = params.ignoreFields;
    var outputDict = {};

    AllFields.forEach( function( name ){
        var ignore = ignoreFields ? ignoreFields.indexOf( name ) !== -1 : false;
        var data = inputDict[ name ];
        if( !ignore && data !== undefined ){
            if( data instanceof Uint8Array ){
                outputDict[ name ] = performDecoding.apply( null, decodeBytes( data ) );
            }else{
                outputDict[ name ] = data;
            }
        }
    } );

    return outputDict;

}

/**
 * @file Mmtf Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var SstrucMap = {
    '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) // NA
};
var MmtfParser = /*@__PURE__*/(function (StructureParser$$1) {
    function MmtfParser () {
        StructureParser$$1.apply(this, arguments);
    }

    if ( StructureParser$$1 ) MmtfParser.__proto__ = StructureParser$$1;
    MmtfParser.prototype = Object.create( StructureParser$$1 && StructureParser$$1.prototype );
    MmtfParser.prototype.constructor = MmtfParser;

    var prototypeAccessors = { type: { configurable: true },isBinary: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'mmtf'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    MmtfParser.prototype._parse = function _parse () {
        // https://github.com/rcsb/mmtf
        if (Debug)
            { Log.time('MmtfParser._parse ' + this.name); }
        var i, il, j, jl, groupData;
        var s = this.structure;
        var sd = decodeMmtf(decodeMsgpack(this.streamer.data));
        // structure header
        var headerFields = [
            'depositionDate', 'releaseDate', 'resolution',
            'rFree', 'rWork', 'experimentalMethods'
        ];
        headerFields.forEach(function (name) {
            if (sd[name] !== undefined) {
                s.header[name] = sd[name];
            }
        });
        var numBonds, numAtoms, numGroups, numChains, numModels;
        var chainsPerModel;
        s.id = sd.structureId;
        s.title = sd.title;
        s.atomStore.addField('formalCharge', 1, 'int8');
        if (this.firstModelOnly || this.asTrajectory) {
            numModels = 1;
            numChains = sd.chainsPerModel[0];
            numGroups = 0;
            for (i = 0, il = numChains; i < il; ++i) {
                numGroups += sd.groupsPerChain[i];
            }
            numAtoms = 0;
            for (i = 0, il = numGroups; i < il; ++i) {
                groupData = sd.groupList[sd.groupTypeList[i]];
                numAtoms += groupData.atomNameList.length;
            }
            numBonds = sd.numBonds;
            chainsPerModel = [numChains];
        }
        else {
            numBonds = sd.numBonds;
            numAtoms = sd.numAtoms;
            numGroups = sd.numGroups;
            numChains = sd.numChains;
            numModels = sd.numModels;
            chainsPerModel = sd.chainsPerModel;
        }
        numBonds += numGroups; // add numGroups to have space for polymer bonds
        //
        if (this.asTrajectory) {
            for (i = 0, il = sd.numModels; i < il; ++i) {
                var frame = new Float32Array(numAtoms * 3);
                var frameAtomOffset = numAtoms * i;
                for (j = 0; j < numAtoms; ++j) {
                    var j3 = j * 3;
                    var offset = j + frameAtomOffset;
                    frame[j3] = sd.xCoordList[offset];
                    frame[j3 + 1] = sd.yCoordList[offset];
                    frame[j3 + 2] = sd.zCoordList[offset];
                }
                s.frames.push(frame);
            }
        }
        // bondStore
        var bAtomIndex1 = new Uint32Array(numBonds);
        var bAtomIndex2 = new Uint32Array(numBonds);
        var bBondOrder = new Uint8Array(numBonds);
        var aGroupIndex = new Uint32Array(numAtoms);
        var aFormalCharge = new Int8Array(numAtoms);
        var gChainIndex = new Uint32Array(numGroups);
        var gAtomOffset = new Uint32Array(numGroups);
        var gAtomCount = new Uint16Array(numGroups);
        var cModelIndex = new Uint16Array(numChains);
        var cGroupOffset = new Uint32Array(numChains);
        var cGroupCount = new Uint32Array(numChains);
        var mChainOffset = new Uint32Array(numModels);
        var mChainCount = new Uint32Array(numModels);
        // set-up model-chain relations
        var chainOffset = 0;
        for (i = 0, il = numModels; i < il; ++i) {
            var modelChainCount = chainsPerModel[i];
            mChainOffset[i] = chainOffset;
            mChainCount[i] = modelChainCount;
            for (j = 0; j < modelChainCount; ++j) {
                cModelIndex[j + chainOffset] = i;
            }
            chainOffset += modelChainCount;
        }
        // set-up chain-residue relations
        var groupsPerChain = sd.groupsPerChain;
        var groupOffset = 0;
        for (i = 0, il = numChains; i < il; ++i) {
            var chainGroupCount = groupsPerChain[i];
            cGroupOffset[i] = groupOffset;
            cGroupCount[i] = chainGroupCount;
            for (j = 0; j < chainGroupCount; ++j) {
                gChainIndex[j + groupOffset] = i;
            }
            groupOffset += chainGroupCount;
        }
        /// ///
        // get data from group map
        var atomOffset = 0;
        var bondOffset = 0;
        for (i = 0, il = numGroups; i < il; ++i) {
            groupData = sd.groupList[sd.groupTypeList[i]];
            var groupAtomCount = groupData.atomNameList.length;
            var groupFormalChargeList = groupData.formalChargeList;
            var groupBondAtomList = groupData.bondAtomList;
            var groupBondOrderList = groupData.bondOrderList;
            for (j = 0, jl = groupBondOrderList.length; j < jl; ++j) {
                bAtomIndex1[bondOffset] = atomOffset + groupBondAtomList[j * 2];
                bAtomIndex2[bondOffset] = atomOffset + groupBondAtomList[j * 2 + 1];
                bBondOrder[bondOffset] = groupBondOrderList[j];
                bondOffset += 1;
            }
            //
            gAtomOffset[i] = atomOffset;
            gAtomCount[i] = groupAtomCount;
            for (j = 0; j < groupAtomCount; ++j) {
                aGroupIndex[atomOffset] = i;
                aFormalCharge[atomOffset] = groupFormalChargeList[j];
                atomOffset += 1;
            }
        }
        // extra bonds
        var bondAtomList = sd.bondAtomList;
        if (bondAtomList) {
            if (sd.bondOrderList) {
                bBondOrder.set(sd.bondOrderList, bondOffset);
            }
            for (i = 0, il = bondAtomList.length; i < il; i += 2) {
                var atomIndex1 = bondAtomList[i];
                var atomIndex2 = bondAtomList[i + 1];
                if (atomIndex1 < numAtoms && atomIndex2 < numAtoms) {
                    bAtomIndex1[bondOffset] = atomIndex1;
                    bAtomIndex2[bondOffset] = atomIndex2;
                    bondOffset += 1;
                }
            }
        }
        //
        s.bondStore.length = bBondOrder.length;
        s.bondStore.count = bondOffset;
        s.bondStore.atomIndex1 = bAtomIndex1;
        s.bondStore.atomIndex2 = bAtomIndex2;
        s.bondStore.bondOrder = bBondOrder;
        s.atomStore.length = numAtoms;
        s.atomStore.count = numAtoms;
        s.atomStore.residueIndex = aGroupIndex;
        s.atomStore.atomTypeId = new Uint16Array(numAtoms);
        s.atomStore.x = sd.xCoordList.subarray(0, numAtoms);
        s.atomStore.y = sd.yCoordList.subarray(0, numAtoms);
        s.atomStore.z = sd.zCoordList.subarray(0, numAtoms);
        s.atomStore.serial = sd.atomIdList.subarray(0, numAtoms);
        s.atomStore.bfactor = sd.bFactorList.subarray(0, numAtoms);
        s.atomStore.altloc = sd.altLocList.subarray(0, numAtoms);
        s.atomStore.occupancy = sd.occupancyList.subarray(0, numAtoms);
        s.atomStore.formalCharge = aFormalCharge;
        s.residueStore.length = numGroups;
        s.residueStore.count = numGroups;
        s.residueStore.chainIndex = gChainIndex;
        s.residueStore.residueTypeId = sd.groupTypeList;
        s.residueStore.atomOffset = gAtomOffset;
        s.residueStore.atomCount = gAtomCount;
        s.residueStore.resno = sd.groupIdList.subarray(0, numGroups);
        s.residueStore.sstruc = sd.secStructList.subarray(0, numGroups);
        s.residueStore.inscode = sd.insCodeList.subarray(0, numGroups);
        s.chainStore.length = numChains;
        s.chainStore.count = numChains;
        s.chainStore.entityIndex = new Uint16Array(numChains);
        s.chainStore.modelIndex = cModelIndex;
        s.chainStore.residueOffset = cGroupOffset;
        s.chainStore.residueCount = cGroupCount;
        s.chainStore.chainname = sd.chainNameList.subarray(0, numChains * 4);
        s.chainStore.chainid = sd.chainIdList.subarray(0, numChains * 4);
        s.modelStore.length = numModels;
        s.modelStore.count = numModels;
        s.modelStore.chainOffset = mChainOffset;
        s.modelStore.chainCount = mChainCount;
        //
        var groupTypeDict = {};
        for (i = 0, il = sd.groupList.length; i < il; ++i) {
            var groupType = sd.groupList[i];
            var atomTypeIdList = [];
            for (j = 0, jl = groupType.atomNameList.length; j < jl; ++j) {
                var element = groupType.elementList[j].toUpperCase();
                var atomname = groupType.atomNameList[j];
                atomTypeIdList.push(s.atomMap.add(atomname, element));
            }
            var chemCompType = groupType.chemCompType.toUpperCase();
            var hetFlag = ChemCompHetero.includes(chemCompType);
            var numGroupBonds = groupType.bondOrderList.length;
            var atomIndices1 = new Array(numGroupBonds);
            var atomIndices2 = new Array(numGroupBonds);
            for (j = 0; j < numGroupBonds; ++j) {
                atomIndices1[j] = groupType.bondAtomList[j * 2];
                atomIndices2[j] = groupType.bondAtomList[j * 2 + 1];
            }
            var bonds = {
                atomIndices1: atomIndices1,
                atomIndices2: atomIndices2,
                bondOrders: groupType.bondOrderList
            };
            groupTypeDict[i] = s.residueMap.add(groupType.groupName, atomTypeIdList, hetFlag, chemCompType, bonds);
        }
        for (i = 0, il = numGroups; i < il; ++i) {
            s.residueStore.residueTypeId[i] = groupTypeDict[s.residueStore.residueTypeId[i]];
        }
        for (i = 0, il = s.atomStore.count; i < il; ++i) {
            var residueIndex = s.atomStore.residueIndex[i];
            var residueType = s.residueMap.list[s.residueStore.residueTypeId[residueIndex]];
            var resAtomOffset = s.residueStore.atomOffset[residueIndex];
            s.atomStore.atomTypeId[i] = residueType.atomTypeIdList[i - resAtomOffset];
        }
        if (sd.secStructList) {
            var secStructLength = sd.secStructList.length;
            for (i = 0, il = s.residueStore.count; i < il; ++i) {
                // with ( i % secStructLength ) secStruct entries are reused
                var sstruc = SstrucMap[s.residueStore.sstruc[i % secStructLength]];
                if (sstruc !== undefined)
                    { s.residueStore.sstruc[i] = sstruc; }
            }
        }
        //
        if (sd.entityList) {
            sd.entityList.forEach(function (e, i) {
                s.entityList[i] = new Entity(s, i, e.description, e.type, e.chainIndexList);
            });
        }
        if (sd.bioAssemblyList) {
            sd.bioAssemblyList.forEach(function (_assembly, k) {
                var id = k + 1;
                var assembly = new Assembly('' + id);
                s.biomolDict['BU' + id] = assembly;
                var chainToPart = {};
                _assembly.transformList.forEach(function (_transform) {
                    var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().fromArray(_transform.matrix).transpose();
                    var chainList = _transform.chainIndexList.map(function (chainIndex) {
                        var chainname = '';
                        for (var k = 0; k < 4; ++k) {
                            var code = sd.chainNameList[chainIndex * 4 + k];
                            if (code) {
                                chainname += String.fromCharCode(code);
                            }
                            else {
                                break;
                            }
                        }
                        return chainname;
                    });
                    var part = chainToPart[chainList.toString()];
                    if (part) {
                        part.matrixList.push(matrix);
                    }
                    else {
                        chainToPart[chainList.toString()] = assembly.addPart([matrix], chainList);
                    }
                });
            });
        }
        if (sd.ncsOperatorList) {
            var ncsName = 'NCS';
            var ncsAssembly = new Assembly(ncsName);
            var ncsPart = ncsAssembly.addPart();
            sd.ncsOperatorList.forEach(function (_operator) {
                var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().fromArray(_operator).transpose();
                ncsPart.matrixList.push(matrix);
            });
            if (ncsPart.matrixList.length > 0) {
                s.biomolDict[ncsName] = ncsAssembly;
            }
        }
        var uc = sd.unitCell;
        if (uc && Array.isArray(uc) && uc[0]) {
            s.unitcell = new Unitcell({
                a: uc[0],
                b: uc[1],
                c: uc[2],
                alpha: uc[3],
                beta: uc[4],
                gamma: uc[5],
                spacegroup: sd.spaceGroup
            });
        }
        else {
            s.unitcell = undefined;
        }
        // calculate backbone bonds
        calculateBondsBetween(s, true);
        // calculate rung bonds
        calculateBondsWithin(s, true);
        s.finalizeAtoms();
        s.finalizeBonds();
        buildUnitcellAssembly(s);
        if (Debug)
            { Log.timeEnd('MmtfParser._parse ' + this.name); }
    };

    Object.defineProperties( MmtfParser.prototype, prototypeAccessors );

    return MmtfParser;
}(StructureParser));
ParserRegistry$1.add('mmtf', MmtfParser);

/**
 * @file Mol2 Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var reWhitespace$2 = /\s+/;
var bondTypes = {
    '1': 1,
    '2': 2,
    '3': 3,
    'am': 1,
    'ar': 1,
    'du': 1,
    'un': 1,
    'nc': 0 // not connected
};
var Mol2Parser = /*@__PURE__*/(function (StructureParser$$1) {
    function Mol2Parser () {
        StructureParser$$1.apply(this, arguments);
    }

    if ( StructureParser$$1 ) Mol2Parser.__proto__ = StructureParser$$1;
    Mol2Parser.prototype = Object.create( StructureParser$$1 && StructureParser$$1.prototype );
    Mol2Parser.prototype.constructor = Mol2Parser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'mol2'; };
    Mol2Parser.prototype._parse = function _parse () {
        // http://paulbourke.net/dataformats/mol2/
        if (Debug)
            { Log.time('Mol2Parser._parse ' + this.name); }
        var s = this.structure;
        var sb = this.structureBuilder;
        var firstModelOnly = this.firstModelOnly;
        var asTrajectory = this.asTrajectory;
        var frames = s.frames;
        var doFrames = false;
        var currentFrame, currentCoord;
        var atomMap = s.atomMap;
        var atomStore = s.atomStore;
        atomStore.resize(Math.round(this.streamer.data.length / 60));
        atomStore.addField('partialCharge', 1, 'float32');
        var idx = 0;
        var moleculeLineNo = 0;
        var modelAtomIdxStart = 0;
        var modelIdx = -1;
        var numAtoms = 0;
        var currentRecordType = 0;
        var moleculeRecordType = 1;
        var atomRecordType = 2;
        var bondRecordType = 3;
        var ap1 = s.getAtomProxy();
        var ap2 = s.getAtomProxy();
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                var line = lines[i].trim();
                if (line === '' || line[0] === '#')
                    { continue; }
                if (line[0] === '@') {
                    if (line === '@<TRIPOS>MOLECULE') {
                        currentRecordType = moleculeRecordType;
                        moleculeLineNo = 0;
                        ++modelIdx;
                    }
                    else if (line === '@<TRIPOS>ATOM') {
                        currentRecordType = atomRecordType;
                        modelAtomIdxStart = atomStore.count;
                        if (asTrajectory) {
                            currentCoord = 0;
                            currentFrame = new Float32Array(numAtoms * 3);
                            frames.push(currentFrame);
                            if (modelIdx > 0)
                                { doFrames = true; }
                        }
                    }
                    else if (line === '@<TRIPOS>BOND') {
                        currentRecordType = bondRecordType;
                    }
                    else {
                        currentRecordType = 0;
                    }
                }
                else if (currentRecordType === moleculeRecordType) {
                    if (moleculeLineNo === 0) {
                        s.title = line;
                        s.id = line;
                    }
                    else if (moleculeLineNo === 1) {
                        var ls = line.split(reWhitespace$2);
                        numAtoms = parseInt(ls[0]);
                        // num_atoms [num_bonds [num_subst [num_feat [num_sets]]]]
                    }
                    ++moleculeLineNo;
                }
                else if (currentRecordType === atomRecordType) {
                    var ls$1 = line.split(reWhitespace$2);
                    if (firstModelOnly && modelIdx > 0)
                        { continue; }
                    var x = parseFloat(ls$1[2]);
                    var y = parseFloat(ls$1[3]);
                    var z = parseFloat(ls$1[4]);
                    if (asTrajectory) {
                        var j = currentCoord * 3;
                        currentFrame[j + 0] = x;
                        currentFrame[j + 1] = y;
                        currentFrame[j + 2] = z;
                        currentCoord += 1;
                        if (doFrames)
                            { continue; }
                    }
                    var serial = ls$1[0];
                    var atomname = ls$1[1];
                    var element = ls$1[5].split('.')[0];
                    var resno = ls$1[6] ? parseInt(ls$1[6]) : 1;
                    var resname = ls$1[7] ? ls$1[7] : '';
                    var partialCharge = ls$1[8] ? parseFloat(ls$1[8]) : 0.0;
                    atomStore.growIfFull();
                    atomStore.atomTypeId[idx] = atomMap.add(atomname, element);
                    atomStore.x[idx] = x;
                    atomStore.y[idx] = y;
                    atomStore.z[idx] = z;
                    atomStore.serial[idx] = serial;
                    atomStore.partialCharge[idx] = partialCharge;
                    sb.addAtom(modelIdx, '', '', resname, resno, 1);
                    idx += 1;
                }
                else if (currentRecordType === bondRecordType) {
                    if (firstModelOnly && modelIdx > 0)
                        { continue; }
                    if (asTrajectory && modelIdx > 0)
                        { continue; }
                    var ls$2 = line.split(reWhitespace$2);
                    // ls[ 0 ] is bond id
                    ap1.index = parseInt(ls$2[1]) - 1 + modelAtomIdxStart;
                    ap2.index = parseInt(ls$2[2]) - 1 + modelAtomIdxStart;
                    var order = bondTypes[ls$2[3]];
                    s.bondStore.addBond(ap1, ap2, order);
                }
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        sb.finalize();
        s.finalizeAtoms();
        calculateChainnames(s);
        calculateBondsWithin(s, true);
        calculateBondsBetween(s, true);
        s.finalizeBonds();
        assignResidueTypeBonds(s);
        calculateSecondaryStructure(s);
        if (Debug)
            { Log.timeEnd('Mol2Parser._parse ' + this.name); }
    };

    Object.defineProperties( Mol2Parser.prototype, prototypeAccessors );

    return Mol2Parser;
}(StructureParser));
ParserRegistry$1.add('mol2', Mol2Parser);

/**
 * @file Pdbqt Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// autodock variant of PDB format with
// - atom partial charges (empty column in pdb format)
// - atom types (bfactor column in pdb format)
// http://autodock.scripps.edu/faqs-help/faq/what-is-the-format-of-a-pdbqt-file
var PdbqtParser = /*@__PURE__*/(function (PdbParser$$1) {
    function PdbqtParser () {
        PdbParser$$1.apply(this, arguments);
    }

    if ( PdbParser$$1 ) PdbqtParser.__proto__ = PdbParser$$1;
    PdbqtParser.prototype = Object.create( PdbParser$$1 && PdbParser$$1.prototype );
    PdbqtParser.prototype.constructor = PdbqtParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'pdbqt'; };

    Object.defineProperties( PdbqtParser.prototype, prototypeAccessors );

    return PdbqtParser;
}(PdbParser));
ParserRegistry$1.add('pdbqt', PdbqtParser);

/**
 * @file Pqr Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// http://www.poissonboltzmann.org/docs/file-format-info/
var PqrParser = /*@__PURE__*/(function (PdbParser$$1) {
    function PqrParser () {
        PdbParser$$1.apply(this, arguments);
    }

    if ( PdbParser$$1 ) PqrParser.__proto__ = PdbParser$$1;
    PqrParser.prototype = Object.create( PdbParser$$1 && PdbParser$$1.prototype );
    PqrParser.prototype.constructor = PqrParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'pqr'; };

    Object.defineProperties( PqrParser.prototype, prototypeAccessors );

    return PqrParser;
}(PdbParser));
ParserRegistry$1.add('pqr', PqrParser);

/**
 * @file Sdf Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var reItem = /> +<(.+)>/;
var SdfParser = /*@__PURE__*/(function (StructureParser$$1) {
    function SdfParser () {
        StructureParser$$1.apply(this, arguments);
    }

    if ( StructureParser$$1 ) SdfParser.__proto__ = StructureParser$$1;
    SdfParser.prototype = Object.create( StructureParser$$1 && StructureParser$$1.prototype );
    SdfParser.prototype.constructor = SdfParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'sdf'; };
    SdfParser.prototype._parse = function _parse () {
        // https://en.wikipedia.org/wiki/Chemical_table_file#SDF
        // http://download.accelrys.com/freeware/ctfile-formats/ctfile-formats.zip
        if (Debug)
            { Log.time('SdfParser._parse ' + this.name); }
        var s = this.structure;
        var sb = this.structureBuilder;
        var firstModelOnly = this.firstModelOnly;
        var asTrajectory = this.asTrajectory;
        var headerLines = this.streamer.peekLines(2);
        s.id = headerLines[0].trim();
        s.title = headerLines[1].trim();
        var frames = s.frames;
        var doFrames = false;
        var currentFrame, currentCoord;
        var atomMap = s.atomMap;
        var atomStore = s.atomStore;
        atomStore.resize(Math.round(this.streamer.data.length / 50));
        atomStore.addField('formalCharge', 1, 'int8');
        var ap1 = s.getAtomProxy();
        var ap2 = s.getAtomProxy();
        var idx = 0;
        var lineNo = 0;
        var modelIdx = 0;
        var modelAtomIdxStart = 0;
        var sdfData = [];
        var currentItem = false;
        var currentData = {};
        var mItem;
        s.extraData.sdf = sdfData;
        var atomCount, bondCount, atomStart, atomEnd, bondStart, bondEnd;
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                var line = lines[i];
                if (line.substr(0, 4) === '$$$$') {
                    lineNo = -1;
                    ++modelIdx;
                    modelAtomIdxStart = atomStore.count;
                    sdfData.push(currentData);
                    currentData = {};
                    currentItem = false;
                }
                else if (lineNo === 3) {
                    atomCount = parseInt(line.substr(0, 3));
                    bondCount = parseInt(line.substr(3, 3));
                    atomStart = 4;
                    atomEnd = atomStart + atomCount;
                    bondStart = atomEnd;
                    bondEnd = bondStart + bondCount;
                    if (asTrajectory) {
                        currentCoord = 0;
                        currentFrame = new Float32Array(atomCount * 3);
                        frames.push(currentFrame);
                        if (modelIdx > 0)
                            { doFrames = true; }
                    }
                }
                else if (lineNo >= atomStart && lineNo < atomEnd) {
                    if (firstModelOnly && modelIdx > 0)
                        { continue; }
                    var x = parseFloat(line.substr(0, 10));
                    var y = parseFloat(line.substr(10, 10));
                    var z = parseFloat(line.substr(20, 10));
                    if (asTrajectory) {
                        var j = currentCoord * 3;
                        currentFrame[j + 0] = x;
                        currentFrame[j + 1] = y;
                        currentFrame[j + 2] = z;
                        currentCoord += 1;
                        if (doFrames)
                            { continue; }
                    }
                    var element = line.substr(31, 3).trim();
                    var atomname = element + (idx + 1);
                    atomStore.growIfFull();
                    atomStore.atomTypeId[idx] = atomMap.add(atomname, element);
                    atomStore.x[idx] = x;
                    atomStore.y[idx] = y;
                    atomStore.z[idx] = z;
                    atomStore.serial[idx] = idx;
                    atomStore.formalCharge[idx] = 0;
                    sb.addAtom(modelIdx, '', '', 'HET', 1, 1);
                    idx += 1;
                }
                else if (lineNo >= bondStart && lineNo < bondEnd) {
                    if (firstModelOnly && modelIdx > 0)
                        { continue; }
                    if (asTrajectory && modelIdx > 0)
                        { continue; }
                    ap1.index = parseInt(line.substr(0, 3)) - 1 + modelAtomIdxStart;
                    ap2.index = parseInt(line.substr(3, 3)) - 1 + modelAtomIdxStart;
                    var order = parseInt(line.substr(6, 3));
                    s.bondStore.addBond(ap1, ap2, order);
                }
                else if (line.match(/M {2}CHG/)) {
                    var chargeCount = parseInt(line.substr(6, 3));
                    for (var ci = 0, coffset = 10; ci < chargeCount; ++ci, coffset += 8) {
                        var aToken = parseInt(line.substr(coffset, 3));
                        var atomIdx = aToken - 1 + modelAtomIdxStart;
                        var cToken = parseInt(line.substr(coffset + 4, 3));
                        atomStore.formalCharge[atomIdx] = cToken;
                    }
                    // eslint-disable-next-line no-cond-assign
                }
                else if (mItem = line.match(reItem)) {
                    currentItem = mItem[1];
                    currentData[currentItem] = [];
                }
                else if (currentItem !== false && line) {
                    currentData[currentItem].push(line);
                }
                ++lineNo;
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        sb.finalize();
        s.finalizeAtoms();
        s.finalizeBonds();
        assignResidueTypeBonds(s);
        if (Debug)
            { Log.timeEnd('SdfParser._parse ' + this.name); }
    };
    SdfParser.prototype._postProcess = function _postProcess () {
        assignResidueTypeBonds(this.structure);
    };

    Object.defineProperties( SdfParser.prototype, prototypeAccessors );

    return SdfParser;
}(StructureParser));
ParserRegistry$1.add('sdf', SdfParser);
ParserRegistry$1.add('sd', SdfParser);
ParserRegistry$1.add('mol', SdfParser);

/**
 * @file Prmtop Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var amberChargeUnitFactor = 18.2223;
function parseIntSubstr(line, start, length) {
    return parseInt(line.substr(start, length).trim());
}
var PrmtopParser = /*@__PURE__*/(function (StructureParser$$1) {
    function PrmtopParser () {
        StructureParser$$1.apply(this, arguments);
    }

    if ( StructureParser$$1 ) PrmtopParser.__proto__ = StructureParser$$1;
    PrmtopParser.prototype = Object.create( StructureParser$$1 && StructureParser$$1.prototype );
    PrmtopParser.prototype.constructor = PrmtopParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'prmtop'; };
    PrmtopParser.prototype._parse = function _parse () {
        // http://ambermd.org/prmtop.pdf
        // http://ambermd.org/formats.html#topology
        if (Debug)
            { Log.time('PrmtopParser._parse ' + this.name); }
        var s = this.structure;
        var sb = this.structureBuilder;
        //
        var atomMap = s.atomMap;
        var atomStore = s.atomStore;
        atomStore.addField('partialCharge', 1, 'float32');
        atomStore.addField('radius', 1, 'float32');
        var title = [];
        var pointersDict = {};
        var pointers = [
            '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'
        ];
        pointers.forEach(function (name) { pointersDict[name] = 0; });
        var atomNames;
        var charges;
        var radii;
        var bAtomIndex1;
        var bAtomIndex2;
        var bBondOrder = new Uint8Array(0);
        var residueLabels;
        var residuePointers;
        var mode;
        // let currentFormat
        var curIdx;
        var bondIdx;
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                var line = lines[i];
                var lt = line.trim();
                if (!lt) {
                    continue;
                }
                else if (line.startsWith('%FORMAT')) ;
                else if (line.startsWith('%FLAG')) {
                    var flag = line.substr(5).trim();
                    curIdx = 0;
                    if (flag === 'TITLE') {
                        mode = 0 /* Title */;
                    }
                    else if (flag === 'POINTERS') {
                        mode = 1 /* Pointers */;
                    }
                    else if (flag === 'ATOM_NAME') {
                        mode = 2 /* AtomName */;
                    }
                    else if (flag === 'CHARGE') {
                        mode = 3 /* Charge */;
                    }
                    else if (flag === 'MASS') {
                        mode = 4 /* Mass */;
                    }
                    else if (flag === 'RESIDUE_LABEL') {
                        mode = 5 /* ResidueLabel */;
                    }
                    else if (flag === 'RESIDUE_POINTER') {
                        mode = 6 /* ResiduePointer */;
                    }
                    else if (flag === 'BONDS_INC_HYDROGEN') {
                        bondIdx = 0;
                        mode = 7 /* BondsIncHydrogen */;
                    }
                    else if (flag === 'BONDS_WITHOUT_HYDROGEN') {
                        bondIdx = pointersDict['NBONH'];
                        mode = 8 /* BondsWithoutHydrogen */;
                    }
                    else if (flag === 'RADII') {
                        mode = 9 /* Radii */;
                    }
                    else {
                        mode = undefined;
                    }
                }
                else if (mode === 0 /* Title */) {
                    title.push(lt);
                }
                else if (mode === 1 /* Pointers */) {
                    var n = Math.min(curIdx + 10, 32);
                    for (var i$1 = 0; curIdx < n; ++i$1, ++curIdx) {
                        pointersDict[pointers[curIdx]] = parseInt(line.substr(i$1 * 8, 8).trim());
                    }
                    atomNames = new Array(pointersDict.NATOM);
                    charges = new Float32Array(pointersDict.NATOM);
                    radii = new Float32Array(pointersDict.NATOM);
                    atomStore.resize(pointersDict.NATOM);
                    var bondCount = pointersDict.NBONH + pointersDict.MBONA;
                    bAtomIndex1 = new Uint32Array(bondCount);
                    bAtomIndex2 = new Uint32Array(bondCount);
                    bBondOrder = new Uint8Array(bondCount);
                    residueLabels = new Array(pointersDict.NRES);
                    residuePointers = new Uint32Array(pointersDict.NRES);
                }
                else if (mode === 2 /* AtomName */) {
                    var n$1 = Math.min(curIdx + 20, pointersDict.NATOM);
                    for (var i$2 = 0; curIdx < n$1; ++i$2, ++curIdx) {
                        atomNames[curIdx] = line.substr(i$2 * 4, 4).trim();
                    }
                }
                else if (mode === 3 /* Charge */) {
                    var n$2 = Math.min(curIdx + 5, pointersDict.NATOM);
                    for (var i$3 = 0; curIdx < n$2; ++i$3, ++curIdx) {
                        charges[curIdx] = parseFloat(line.substr(i$3 * 16, 16)) / amberChargeUnitFactor;
                    }
                }
                else if (mode === 4 /* Mass */) ;
                else if (mode === 5 /* ResidueLabel */) {
                    var n$3 = Math.min(curIdx + 20, pointersDict.NRES);
                    for (var i$4 = 0; curIdx < n$3; ++i$4, ++curIdx) {
                        residueLabels[curIdx] = line.substr(i$4 * 4, 4).trim();
                    }
                }
                else if (mode === 6 /* ResiduePointer */) {
                    var n$4 = Math.min(curIdx + 10, pointersDict.NRES);
                    for (var i$5 = 0; curIdx < n$4; ++i$5, ++curIdx) {
                        residuePointers[curIdx] = parseIntSubstr(line, i$5 * 8, 8);
                    }
                }
                else if (mode === 7 /* BondsIncHydrogen */) {
                    var n$5 = Math.min(curIdx + 10, pointersDict.NBONH * 3);
                    for (var i$6 = 0; curIdx < n$5; ++i$6, ++curIdx) {
                        var r = curIdx % 3;
                        if (r === 0) {
                            bAtomIndex1[bondIdx] = parseIntSubstr(line, i$6 * 8, 8) / 3;
                        }
                        if (r === 1) {
                            bAtomIndex2[bondIdx] = parseIntSubstr(line, i$6 * 8, 8) / 3;
                            bBondOrder[bondIdx] = 1;
                            ++bondIdx;
                        }
                    }
                }
                else if (mode === 8 /* BondsWithoutHydrogen */) {
                    var n$6 = Math.min(curIdx + 10, pointersDict.MBONA * 3);
                    for (var i$7 = 0; curIdx < n$6; ++i$7, ++curIdx) {
                        var r$1 = curIdx % 3;
                        if (r$1 === 0) {
                            bAtomIndex1[bondIdx] = parseIntSubstr(line, i$7 * 8, 8) / 3;
                        }
                        if (r$1 === 1) {
                            bAtomIndex2[bondIdx] = parseIntSubstr(line, i$7 * 8, 8) / 3;
                            bBondOrder[bondIdx] = 1;
                            ++bondIdx;
                        }
                    }
                }
                else if (mode === 9 /* Radii */) {
                    var n$7 = Math.min(curIdx + 5, pointersDict.NATOM);
                    for (var i$8 = 0; curIdx < n$7; ++i$8, ++curIdx) {
                        radii[curIdx] = parseFloat(line.substr(i$8 * 16, 16));
                    }
                }
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        s.title = title.join(' ');
        var atomCount = pointersDict.NATOM;
        var curResIdx = 0;
        var curResname = residueLabels[0];
        var curResno = 1;
        for (var i = 0; i < atomCount; ++i) {
            if (i + 1 === residuePointers[curResIdx + 1]) {
                ++curResIdx;
                curResname = residueLabels[curResIdx];
                curResno = curResIdx + 1;
            }
            atomStore.atomTypeId[i] = atomMap.add(atomNames[i]);
            atomStore.serial[i] = i + 1;
            sb.addAtom(0, '', '', curResname, curResno);
        }
        atomStore.partialCharge.set(charges);
        atomStore.radius.set(radii);
        s.bondStore.length = bBondOrder.length;
        s.bondStore.count = bBondOrder.length;
        s.bondStore.atomIndex1 = bAtomIndex1;
        s.bondStore.atomIndex2 = bAtomIndex2;
        s.bondStore.bondOrder = bBondOrder;
        sb.finalize();
        s.finalizeAtoms();
        s.finalizeBonds();
        calculateBondsWithin(s, true);
        calculateBondsBetween(s, true, true);
        calculateChainnames(s, true);
        assignResidueTypeBonds(s);
        if (Debug)
            { Log.timeEnd('PrmtopParser._parse ' + this.name); }
    };

    Object.defineProperties( PrmtopParser.prototype, prototypeAccessors );

    return PrmtopParser;
}(StructureParser));
ParserRegistry$1.add('prmtop', PrmtopParser);
ParserRegistry$1.add('parm7', PrmtopParser);

/**
 * @file Psf Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var TitleMode = 1;
var AtomMode = 2;
var BondMode = 3;
var AngleMode = 4;
var DihedralMode = 5;
var ImproperMode = 6;
var reWhitespace$3 = /\s+/;
var reTitle = /(^\*|REMARK)*/;
var PsfParser = /*@__PURE__*/(function (StructureParser$$1) {
    function PsfParser () {
        StructureParser$$1.apply(this, arguments);
    }

    if ( StructureParser$$1 ) PsfParser.__proto__ = StructureParser$$1;
    PsfParser.prototype = Object.create( StructureParser$$1 && StructureParser$$1.prototype );
    PsfParser.prototype.constructor = PsfParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'psf'; };
    PsfParser.prototype._parse = function _parse () {
        // http://www.ks.uiuc.edu/Training/Tutorials/namd/namd-tutorial-unix-html/node23.html
        if (Debug)
            { Log.time('PsfParser._parse ' + this.name); }
        var s = this.structure;
        var sb = this.structureBuilder;
        //
        var atomMap = s.atomMap;
        var atomStore = s.atomStore;
        atomStore.addField('partialCharge', 1, 'float32');
        var title = [];
        var mode;
        var chainid;
        var lastSegid;
        var idx = 0;
        var chainIdx = 0;
        var bondIdx = 0;
        var bAtomIndex1, bAtomIndex2, bBondOrder;
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                var line = lines[i].trim();
                if (!line) {
                    mode = undefined;
                    continue;
                }
                if (mode === AtomMode) {
                    var ls = line.split(reWhitespace$3);
                    var serial = parseInt(ls[0]);
                    var segid = ls[1];
                    var resno = parseInt(ls[2]);
                    var resname = ls[3];
                    var atomname = ls[4];
                    var charge = parseFloat(ls[6]);
                    if (segid !== lastSegid) {
                        chainid = getChainname(chainIdx);
                        ++chainIdx;
                    }
                    atomStore.growIfFull();
                    atomStore.atomTypeId[idx] = atomMap.add(atomname);
                    atomStore.serial[idx] = serial;
                    atomStore.partialCharge[idx] = charge;
                    sb.addAtom(0, chainid, chainid, resname, resno);
                    idx += 1;
                    lastSegid = segid;
                }
                else if (mode === BondMode) {
                    var ls$1 = line.split(reWhitespace$3);
                    for (var j = 0, m = ls$1.length; j < m; j += 2) {
                        bAtomIndex1[bondIdx] = parseInt(ls$1[j]) - 1;
                        bAtomIndex2[bondIdx] = parseInt(ls$1[j + 1]) - 1;
                        bBondOrder[bondIdx] = 1;
                        bondIdx += 1;
                    }
                }
                else if (mode === TitleMode) {
                    title.push(line.replace(reTitle, '').trim());
                }
                else if (mode === AngleMode) ;
                else if (mode === DihedralMode) ;
                else if (mode === ImproperMode) ;
                else if (line.includes('!NATOM')) {
                    mode = AtomMode;
                    var numAtoms = parseInt(line.split(reWhitespace$3)[0]);
                    atomStore.resize(numAtoms);
                }
                else if (line.includes('!NBOND')) {
                    mode = BondMode;
                    var numBonds = parseInt(line.split(reWhitespace$3)[0]);
                    bAtomIndex1 = new Uint32Array(numBonds);
                    bAtomIndex2 = new Uint32Array(numBonds);
                    bBondOrder = new Uint8Array(numBonds);
                }
                else if (line.includes('!NTITLE')) {
                    mode = TitleMode;
                }
                else if (line.includes('!NTHETA')) {
                    mode = AngleMode;
                }
                else if (line.includes('!NPHI')) {
                    mode = DihedralMode;
                }
                else if (line.includes('!NIMPHI')) {
                    mode = ImproperMode;
                }
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        s.title = title.join(' ');
        s.bondStore.length = bBondOrder.length;
        s.bondStore.count = bondIdx;
        s.bondStore.atomIndex1 = bAtomIndex1;
        s.bondStore.atomIndex2 = bAtomIndex2;
        s.bondStore.bondOrder = bBondOrder;
        sb.finalize();
        s.finalizeAtoms();
        s.finalizeBonds();
        calculateBondsWithin(s, true);
        calculateBondsBetween(s, true, true);
        assignResidueTypeBonds(s);
        if (Debug)
            { Log.timeEnd('PsfParser._parse ' + this.name); }
    };

    Object.defineProperties( PsfParser.prototype, prototypeAccessors );

    return PsfParser;
}(StructureParser));
ParserRegistry$1.add('psf', PsfParser);

/**
 * @file Top Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var reField = /\[ (.+) \]/;
var reWhitespace$4 = /\s+/;
var TopParser = /*@__PURE__*/(function (StructureParser$$1) {
    function TopParser () {
        StructureParser$$1.apply(this, arguments);
    }

    if ( StructureParser$$1 ) TopParser.__proto__ = StructureParser$$1;
    TopParser.prototype = Object.create( StructureParser$$1 && StructureParser$$1.prototype );
    TopParser.prototype.constructor = TopParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'top'; };
    TopParser.prototype._parse = function _parse () {
        // http://manual.gromacs.org/online/top.html
        if (Debug)
            { Log.time('TopParser._parse ' + this.name); }
        var s = this.structure;
        var sb = this.structureBuilder;
        //
        var atomMap = s.atomMap;
        var bondStore = s.bondStore;
        var atomStore = s.atomStore;
        atomStore.addField('partialCharge', 1, 'float32');
        var molecules = [];
        var moleculetypeDict = {};
        var currentMoleculetype;
        var mode;
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                var line = lines[i];
                var lt = line.trim();
                if (!lt || lt[0] === '*' || lt[0] === ';') {
                    continue;
                }
                if (lt.startsWith('#include')) {
                    throw new Error('TopParser: #include statements not allowed');
                }
                var fieldMatch = line.match(reField);
                if (fieldMatch !== null) {
                    var name = fieldMatch[1];
                    if (name === 'moleculetype') {
                        mode = 2 /* Moleculetype */;
                        currentMoleculetype = {
                            atoms: [],
                            bonds: []
                        };
                    }
                    else if (name === 'atoms') {
                        mode = 3 /* Atoms */;
                    }
                    else if (name === 'bonds') {
                        mode = 4 /* Bonds */;
                    }
                    else if (name === 'system') {
                        mode = 0 /* System */;
                    }
                    else if (name === 'molecules') {
                        mode = 1 /* Molecules */;
                    }
                    else {
                        mode = undefined;
                    }
                    continue;
                }
                var cIdx = lt.indexOf(';');
                if (cIdx !== -1) {
                    lt = lt.substring(0, cIdx).trim();
                }
                if (mode === 2 /* Moleculetype */) {
                    var molName = lt.split(reWhitespace$4)[0];
                    moleculetypeDict[molName] = currentMoleculetype;
                }
                else if (mode === 3 /* Atoms */) {
                    var ls = lt.split(reWhitespace$4);
                    currentMoleculetype.atoms.push([
                        parseInt(ls[2]),
                        ls[3],
                        ls[4],
                        parseFloat(ls[6]) // charge
                    ]);
                }
                else if (mode === 4 /* Bonds */) {
                    var ls$1 = lt.split(reWhitespace$4);
                    currentMoleculetype.bonds.push([
                        parseInt(ls$1[0]),
                        parseInt(ls$1[1]) // aj
                    ]);
                }
                else if (mode === 0 /* System */) {
                    s.title = lt;
                }
                else if (mode === 1 /* Molecules */) {
                    var ls$2 = lt.split(reWhitespace$4);
                    molecules.push([
                        ls$2[0],
                        parseInt(ls$2[1]) // count
                    ]);
                }
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        var atomCount = 0;
        var bondCount = 0;
        molecules.forEach(function (val) {
            var name = val[0];
            var molCount = val[1];
            var molType = moleculetypeDict[name];
            atomCount += molCount * molType.atoms.length;
            bondCount += molCount * molType.bonds.length;
        });
        atomStore.resize(atomCount);
        bondStore.resize(bondCount);
        var atomIdx = 0;
        var resIdx = 0;
        var chainidIdx = 0;
        var chainnameIdx = 0;
        var bondIdx = 0;
        var atomOffset = 0;
        var lastResno;
        molecules.forEach(function (val) {
            var name = val[0];
            var molCount = val[1];
            var molType = moleculetypeDict[name];
            var chainname = getChainname(chainnameIdx);
            var loop = function ( i ) {
                lastResno = -1;
                var chainid = WaterNames.includes(name) ? chainname : getChainname(chainidIdx);
                molType.atoms.forEach(function (atomData) {
                    var resno = atomData[0];
                    var resname = atomData[1];
                    var atomname = atomData[2];
                    var charge = atomData[3];
                    if (resno !== lastResno) {
                        ++resIdx;
                    }
                    atomStore.atomTypeId[atomIdx] = atomMap.add(atomname);
                    atomStore.serial[atomIdx] = atomIdx + 1;
                    atomStore.partialCharge[atomIdx] = charge;
                    sb.addAtom(0, chainname, chainid, resname, resIdx + 1);
                    ++atomIdx;
                    lastResno = resno;
                });
                molType.bonds.forEach(function (bondData) {
                    bondStore.atomIndex1[bondIdx] = atomOffset + bondData[0] - 1;
                    bondStore.atomIndex2[bondIdx] = atomOffset + bondData[1] - 1;
                    ++bondIdx;
                });
                ++chainidIdx;
                atomOffset += molType.atoms.length;
            };

            for (var i = 0; i < molCount; ++i) loop( i );
            ++chainnameIdx;
        });
        bondStore.count = bondCount;
        sb.finalize();
        s.finalizeAtoms();
        s.finalizeBonds();
        calculateBondsWithin(s, true);
        calculateBondsBetween(s, true, true);
        assignResidueTypeBonds(s);
        if (Debug)
            { Log.timeEnd('TopParser._parse ' + this.name); }
    };

    Object.defineProperties( TopParser.prototype, prototypeAccessors );

    return TopParser;
}(StructureParser));
ParserRegistry$1.add('top', TopParser);

/**
 * @file Trajectory Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var TrajectoryParser = /*@__PURE__*/(function (Parser$$1) {
    function TrajectoryParser(streamer, params) {
        Parser$$1.call(this, streamer, params);
        this.frames = new Frames(this.name, this.path);
    }

    if ( Parser$$1 ) TrajectoryParser.__proto__ = Parser$$1;
    TrajectoryParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    TrajectoryParser.prototype.constructor = TrajectoryParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'trajectory'; };
    prototypeAccessors.__objName.get = function () { return 'frames'; };

    Object.defineProperties( TrajectoryParser.prototype, prototypeAccessors );

    return TrajectoryParser;
}(Parser));

/**
 * @file Dcd Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var charmmTimeUnitFactor = 20.45482949774598;
var DcdParser = /*@__PURE__*/(function (TrajectoryParser$$1) {
    function DcdParser () {
        TrajectoryParser$$1.apply(this, arguments);
    }

    if ( TrajectoryParser$$1 ) DcdParser.__proto__ = TrajectoryParser$$1;
    DcdParser.prototype = Object.create( TrajectoryParser$$1 && TrajectoryParser$$1.prototype );
    DcdParser.prototype.constructor = DcdParser;

    var prototypeAccessors = { type: { configurable: true },isBinary: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'dcd'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    DcdParser.prototype._parse = function _parse () {
        // http://www.ks.uiuc.edu/Research/vmd/plugins/molfile/dcdplugin.html
        // The DCD format is structured as follows
        //   (FORTRAN UNFORMATTED, with Fortran data type descriptions):
        // HDR     NSET    ISTRT   NSAVC   5-ZEROS NATOM-NFREAT    DELTA   9-ZEROS
        // `CORD'  #files  step 1  step    zeroes  (zero)          timestep  (zeroes)
        //                         interval
        // C*4     INT     INT     INT     5INT    INT             DOUBLE  9INT
        // ==========================================================================
        // NTITLE          TITLE
        // INT (=2)        C*MAXTITL
        //                 (=32)
        // ==========================================================================
        // NATOM
        // #atoms
        // INT
        // ==========================================================================
        // X(I), I=1,NATOM         (DOUBLE)
        // Y(I), I=1,NATOM
        // Z(I), I=1,NATOM
        // ==========================================================================
        if (Debug)
            { Log.time('DcdParser._parse ' + this.name); }
        var bin = ensureBuffer(this.streamer.data);
        var dv = new DataView(bin);
        var f = this.frames;
        var coordinates = f.coordinates;
        var boxes = f.boxes;
        var header = {};
        var nextPos = 0;
        // header block
        var intView = new Int32Array(bin, 0, 23);
        var ef = intView[0] !== dv.getInt32(0); // endianess flag
        // swap byte order when big endian (84 indicates little endian)
        if (intView[0] !== 84) {
            var n = bin.byteLength;
            for (var i = 0; i < n; i += 4) {
                dv.setFloat32(i, dv.getFloat32(i), true);
            }
        }
        if (intView[0] !== 84) {
            Log.error('dcd bad format, header block start');
        }
        // format indicator, should read 'CORD'
        var formatString = String.fromCharCode(dv.getUint8(4), dv.getUint8(5), dv.getUint8(6), dv.getUint8(7));
        if (formatString !== 'CORD') {
            Log.error('dcd bad format, format string');
        }
        var isCharmm = false;
        var extraBlock = false;
        var fourDims = false;
        // version field in charmm, unused in X-PLOR
        if (intView[22] !== 0) {
            isCharmm = true;
            if (intView[12] !== 0)
                { extraBlock = true; }
            if (intView[13] === 1)
                { fourDims = true; }
        }
        header.NSET = intView[2];
        header.ISTART = intView[3];
        header.NSAVC = intView[4];
        header.NAMNF = intView[10];
        if (isCharmm) {
            header.DELTA = dv.getFloat32(44, ef);
        }
        else {
            header.DELTA = dv.getFloat64(44, ef);
        }
        if (intView[22] !== 84) {
            Log.error('dcd bad format, header block end');
        }
        nextPos = nextPos + 21 * 4 + 8;
        // title block
        var titleLength = dv.getInt32(nextPos, ef);
        var titlePos = nextPos + 1;
        if ((titleLength - 4) % 80 !== 0) {
            Log.error('dcd bad format, title block start');
        }
        header.TITLE = uint8ToString(new Uint8Array(bin, titlePos, titleLength));
        if (dv.getInt32(titlePos + titleLength + 4 - 1, ef) !== titleLength) {
            Log.error('dcd bad format, title block end');
        }
        nextPos = nextPos + titleLength + 8;
        // natom block
        if (dv.getInt32(nextPos, ef) !== 4) {
            Log.error('dcd bad format, natom block start');
        }
        header.NATOM = dv.getInt32(nextPos + 4, ef);
        if (dv.getInt32(nextPos + 8, ef) !== 4) {
            Log.error('dcd bad format, natom block end');
        }
        nextPos = nextPos + 4 + 8;
        // fixed atoms block
        if (header.NAMNF > 0) {
            // TODO read coordinates and indices of fixed atoms
            Log.error('dcd format with fixed atoms unsupported, aborting');
            return;
        }
        // frames
        var natom = header.NATOM;
        var natom4 = natom * 4;
        for (var i$1 = 0, n$1 = header.NSET; i$1 < n$1; ++i$1) {
            if (extraBlock) {
                nextPos += 4; // block start
                // unitcell: A, alpha, B, beta, gamma, C (doubles)
                var box = new Float32Array(9);
                box[0] = dv.getFloat64(nextPos, ef);
                box[4] = dv.getFloat64(nextPos + 2 * 8, ef);
                box[8] = dv.getFloat64(nextPos + 5 * 8, ef);
                boxes.push(box);
                nextPos += 48;
                nextPos += 4; // block end
            }
            // xyz coordinates
            var coord = new Float32Array(natom * 3);
            for (var j = 0; j < 3; ++j) {
                if (dv.getInt32(nextPos, ef) !== natom4) {
                    Log.error('dcd bad format, coord block start', i$1, j);
                }
                nextPos += 4; // block start
                var c = new Float32Array(bin, nextPos, natom);
                for (var k = 0; k < natom; ++k) {
                    coord[3 * k + j] = c[k];
                }
                nextPos += natom4;
                if (dv.getInt32(nextPos, ef) !== natom4) {
                    Log.error('dcd bad format, coord block end', i$1, j);
                }
                nextPos += 4; // block end
            }
            coordinates.push(coord);
            if (fourDims) {
                var bytes = dv.getInt32(nextPos, ef);
                nextPos += 4 + bytes + 4; // block start + skip + block end
            }
        }
        if (header.DELTA) {
            f.deltaTime = header.DELTA * charmmTimeUnitFactor;
        }
        if (header.ISTART >= 1) {
            f.timeOffset = (header.ISTART - 1) * f.deltaTime;
        }
        // console.log(header)
        // console.log(header.TITLE)
        // console.log('isCharmm', isCharmm, 'extraBlock', extraBlock, 'fourDims, fourDims)
        if (Debug)
            { Log.timeEnd('DcdParser._parse ' + this.name); }
    };

    Object.defineProperties( DcdParser.prototype, prototypeAccessors );

    return DcdParser;
}(TrajectoryParser));
ParserRegistry$1.add('dcd', DcdParser);

/**
 * @file Netcdf Reader
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 *
 * Adapted from https://github.com/cheminfo-js/netcdfjs
 * MIT License, Copyright (c) 2016 cheminfo
 */
/**
 * Throws a non-valid NetCDF exception if the statement it's true
 * @ignore
 * @param {boolean} statement - Throws if true
 * @param {string} reason - Reason to throw
 */
function notNetcdf(statement, reason) {
    if (statement) {
        throw new TypeError('Not a valid NetCDF v3.x file: ' + reason);
    }
}
/**
 * Moves 1, 2, or 3 bytes to next 4-byte boundary
 * @ignore
 * @param {IOBuffer} buffer - Buffer for the file data
 */
function padding(buffer) {
    if ((buffer.offset % 4) !== 0) {
        buffer.skip(4 - (buffer.offset % 4));
    }
}
/**
 * Reads the name
 * @ignore
 * @param {IOBuffer} buffer - Buffer for the file data
 * @return {string} - Name
 */
function readName(buffer) {
    // Read name
    var nameLength = buffer.readUint32();
    var name = buffer.readChars(nameLength);
    // validate name
    // TODO
    // Apply padding
    padding(buffer);
    return name;
}
var types = {
    BYTE: 1,
    CHAR: 2,
    SHORT: 3,
    INT: 4,
    FLOAT: 5,
    DOUBLE: 6
};
/**
 * Parse a number into their respective type
 * @ignore
 * @param {number} type - integer that represents the type
 * @return {string} - parsed value of the type
 */
function num2str(type) {
    switch (Number(type)) {
        case types.BYTE:
            return 'byte';
        case types.CHAR:
            return 'char';
        case types.SHORT:
            return 'short';
        case types.INT:
            return 'int';
        case types.FLOAT:
            return 'float';
        case types.DOUBLE:
            return 'double';
        default:
            return 'undefined';
    }
}
/**
 * Parse a number type identifier to his size in bytes
 * @ignore
 * @param {number} type - integer that represents the type
 * @return {number} -size of the type
 */
function num2bytes(type) {
    switch (Number(type)) {
        case types.BYTE:
            return 1;
        case types.CHAR:
            return 1;
        case types.SHORT:
            return 2;
        case types.INT:
            return 4;
        case types.FLOAT:
            return 4;
        case types.DOUBLE:
            return 8;
        default:
            return -1;
    }
}
/**
 * Reverse search of num2str
 * @ignore
 * @param {string} type - string that represents the type
 * @return {number} - parsed value of the type
 */
function str2num(type) {
    switch (String(type)) {
        case 'byte':
            return types.BYTE;
        case 'char':
            return types.CHAR;
        case 'short':
            return types.SHORT;
        case 'int':
            return types.INT;
        case 'float':
            return types.FLOAT;
        case 'double':
            return types.DOUBLE;
        default:
            return -1;
    }
}
/**
 * Auxiliary function to read numeric data
 * @ignore
 * @param {number} size - Size of the element to read
 * @param {function} bufferReader - Function to read next value
 * @return {Array<number>|number}
 */
function readNumber(size, bufferReader) {
    if (size !== 1) {
        var numbers = new Array(size);
        for (var i = 0; i < size; i++) {
            numbers[i] = bufferReader();
        }
        return numbers;
    }
    else {
        return bufferReader();
    }
}
/**
 * Given a type and a size reads the next element
 * @ignore
 * @param {IOBuffer} buffer - Buffer for the file data
 * @param {number} type - Type of the data to read
 * @param {number} size - Size of the element to read
 * @return {string|Array<number>|number}
 */
function readType(buffer, type, size) {
    switch (type) {
        case types.BYTE:
            return buffer.readBytes(size);
        case types.CHAR:
            return trimNull(buffer.readChars(size));
        case types.SHORT:
            return readNumber(size, buffer.readInt16.bind(buffer));
        case types.INT:
            return readNumber(size, buffer.readInt32.bind(buffer));
        case types.FLOAT:
            return readNumber(size, buffer.readFloat32.bind(buffer));
        case types.DOUBLE:
            return readNumber(size, buffer.readFloat64.bind(buffer));
        default:
            notNetcdf(true, 'non valid type ' + type);
            return undefined;
    }
}
/**
 * Removes null terminate value
 * @ignore
 * @param {string} value - String to trim
 * @return {string} - Trimmed string
 */
function trimNull(value) {
    if (value.charCodeAt(value.length - 1) === 0) {
        return value.substring(0, value.length - 1);
    }
    return value;
}
// const STREAMING = 4294967295;
/**
 * Read data for the given non-record variable
 * @ignore
 * @param {IOBuffer} buffer - Buffer for the file data
 * @param {object} variable - Variable metadata
 * @return {Array} - Data of the element
 */
function nonRecord(buffer, variable) {
    // variable type
    var type = str2num(variable.type);
    // size of the data
    var size = variable.size / num2bytes(type);
    // iterates over the data
    var data = new Array(size);
    for (var i = 0; i < size; i++) {
        data[i] = readType(buffer, type, 1);
    }
    return data;
}
/**
 * Read data for the given record variable
 * @ignore
 * @param {IOBuffer} buffer - Buffer for the file data
 * @param {object} variable - Variable metadata
 * @param {object} recordDimension - Record dimension metadata
 * @return {Array} - Data of the element
 */
function record(buffer, variable, recordDimension) {
    // variable type
    var type = str2num(variable.type);
    var width = variable.size ? variable.size / num2bytes(type) : 1;
    // size of the data
    // TODO streaming data
    var size = recordDimension.length;
    // iterates over the data
    var data = new Array(size);
    var step = recordDimension.recordStep;
    for (var i = 0; i < size; i++) {
        var currentOffset = buffer.offset;
        data[i] = readType(buffer, type, width);
        buffer.seek(currentOffset + step);
    }
    return data;
}
// Grammar constants
var ZERO = 0;
var NC_DIMENSION = 10;
var NC_VARIABLE = 11;
var NC_ATTRIBUTE = 12;
/**
 * Read the header of the file
 * @ignore
 * @param {IOBuffer} buffer - Buffer for the file data
 * @param {number} version - Version of the file
 * @return {object} - Object with the fields:
 *  * `recordDimension`: Number with the length of record dimension
 *  * `dimensions`: List of dimensions
 *  * `globalAttributes`: List of global attributes
 *  * `variables`: List of variables
 */
function header(buffer, version) {
    // Length of record dimension
    // sum of the varSize's of all the record variables.
    var header = { recordDimension: { length: buffer.readUint32() } };
    // Version
    header.version = version;
    // List of dimensions
    var dimList = dimensionsList(buffer);
    header.recordDimension.id = dimList.recordId;
    header.recordDimension.name = dimList.recordName;
    header.dimensions = dimList.dimensions;
    // List of global attributes
    header.globalAttributes = attributesList(buffer);
    // List of variables
    var variables = variablesList(buffer, dimList.recordId, version);
    header.variables = variables.variables;
    header.recordDimension.recordStep = variables.recordStep;
    return header;
}
/**
 * List of dimensions
 * @ignore
 * @param {IOBuffer} buffer - Buffer for the file data
 * @return {object} - List of dimensions and record dimension with:
 *  * `name`: String with the name of the dimension
 *  * `size`: Number with the size of the dimension
 */
function dimensionsList(buffer) {
    var dimensions, recordId, recordName;
    var dimList = buffer.readUint32();
    if (dimList === ZERO) {
        notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of dimensions');
        return [];
    }
    else {
        notNetcdf((dimList !== NC_DIMENSION), 'wrong tag for list of dimensions');
        // Length of dimensions
        var dimensionSize = buffer.readUint32();
        dimensions = new Array(dimensionSize);
        for (var dim = 0; dim < dimensionSize; dim++) {
            // Read name
            var name = readName(buffer);
            // Read dimension size
            var size = buffer.readUint32();
            if (size === 0) {
                recordId = dim;
                recordName = name;
            }
            dimensions[dim] = {
                name: name,
                size: size
            };
        }
        return {
            dimensions: dimensions,
            recordId: recordId,
            recordName: recordName
        };
    }
}
/**
 * List of attributes
 * @ignore
 * @param {IOBuffer} buffer - Buffer for the file data
 * @return {Array<object>} - List of attributes with:
 *  * `name`: String with the name of the attribute
 *  * `type`: String with the type of the attribute
 *  * `value`: A number or string with the value of the attribute
 */
function attributesList(buffer) {
    var attributes;
    var gAttList = buffer.readUint32();
    if (gAttList === ZERO) {
        notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of attributes');
        return [];
    }
    else {
        notNetcdf((gAttList !== NC_ATTRIBUTE), 'wrong tag for list of attributes');
        // Length of attributes
        var attributeSize = buffer.readUint32();
        attributes = new Array(attributeSize);
        for (var gAtt = 0; gAtt < attributeSize; gAtt++) {
            // Read name
            var name = readName(buffer);
            // Read type
            var type = buffer.readUint32();
            notNetcdf(((type < 1) || (type > 6)), 'non valid type ' + type);
            // Read attribute
            var size = buffer.readUint32();
            var value = readType(buffer, type, size);
            // Apply padding
            padding(buffer);
            attributes[gAtt] = {
                name: name,
                type: num2str(type),
                value: value
            };
        }
    }
    return attributes;
}
/**
 * List of variables
 * @ignore
 * @param {IOBuffer} buffer - Buffer for the file data
 * @param {number} recordId - Id if the record dimension
 * @param {number} version - Version of the file
 * @return {object} - Number of recordStep and list of variables with:
 *  * `name`: String with the name of the variable
 *  * `dimensions`: Array with the dimension IDs of the variable
 *  * `attributes`: Array with the attributes of the variable
 *  * `type`: String with the type of the variable
 *  * `size`: Number with the size of the variable
 *  * `offset`: Number with the offset where of the variable begins
 *  * `record`: True if is a record variable, false otherwise
 */
function variablesList(buffer, recordId, version) {
    var varList = buffer.readUint32();
    var recordStep = 0;
    var variables;
    if (varList === ZERO) {
        notNetcdf((buffer.readUint32() !== ZERO), 'wrong empty tag for list of variables');
        return [];
    }
    else {
        notNetcdf((varList !== NC_VARIABLE), 'wrong tag for list of variables');
        // Length of variables
        var variableSize = buffer.readUint32();
        variables = new Array(variableSize);
        for (var v = 0; v < variableSize; v++) {
            // Read name
            var name = readName(buffer);
            // Read dimensionality of the variable
            var dimensionality = buffer.readUint32();
            // Index into the list of dimensions
            var dimensionsIds = new Array(dimensionality);
            for (var dim = 0; dim < dimensionality; dim++) {
                dimensionsIds[dim] = buffer.readUint32();
            }
            // Read variables size
            var attributes = attributesList(buffer);
            // Read type
            var type = buffer.readUint32();
            notNetcdf(((type < 1) && (type > 6)), 'non valid type ' + type);
            // Read variable size
            // The 32-bit varSize field is not large enough to contain the
            // size of variables that require more than 2^32 - 4 bytes,
            // so 2^32 - 1 is used in the varSize field for such variables.
            var varSize = buffer.readUint32();
            // Read offset
            var offset = buffer.readUint32();
            if (version === 2) {
                notNetcdf((offset > 0), 'offsets larger than 4GB not supported');
                offset = buffer.readUint32();
            }
            // Count amount of record variables
            if (dimensionsIds[0] === recordId) {
                recordStep += varSize;
            }
            variables[v] = {
                name: name,
                dimensions: dimensionsIds,
                attributes: attributes,
                type: num2str(type),
                size: varSize,
                offset: offset,
                record: (dimensionsIds[0] === recordId)
            };
        }
    }
    return {
        variables: variables,
        recordStep: recordStep
    };
}
/**
 * Reads a NetCDF v3.x file
 * https://www.unidata.ucar.edu/software/netcdf/docs/file_format_specifications.html
 */
var NetcdfReader = function NetcdfReader(data) {
    var buffer = new IOBuffer(data);
    buffer.setBigEndian();
    // Validate that it's a NetCDF file
    notNetcdf((buffer.readChars(3) !== 'CDF'), 'should start with CDF');
    // Check the NetCDF format
    var version = buffer.readByte();
    notNetcdf((version > 2), 'unknown version');
    // Read the header
    this.header = header(buffer, version);
    this.buffer = buffer;
};

var prototypeAccessors$y = { version: { configurable: true },recordDimension: { configurable: true },dimensions: { configurable: true },globalAttributes: { configurable: true },variables: { configurable: true } };
/**
 * @return {string} - Version for the NetCDF format
 */
prototypeAccessors$y.version.get = function () {
    if (this.header.version === 1) {
        return 'classic format';
    }
    else {
        return '64-bit offset format';
    }
};
/**
 * @return {object} - Metadata for the record dimension
 *  * `length`: Number of elements in the record dimension
 *  * `id`: Id number in the list of dimensions for the record dimension
 *  * `name`: String with the name of the record dimension
 *  * `recordStep`: Number with the record variables step size
 */
prototypeAccessors$y.recordDimension.get = function () {
    return this.header.recordDimension;
};
/**
 * @return {Array<object>} - List of dimensions with:
 *  * `name`: String with the name of the dimension
 *  * `size`: Number with the size of the dimension
 */
prototypeAccessors$y.dimensions.get = function () {
    return this.header.dimensions;
};
/**
 * @return {Array<object>} - List of global attributes with:
 *  * `name`: String with the name of the attribute
 *  * `type`: String with the type of the attribute
 *  * `value`: A number or string with the value of the attribute
 */
prototypeAccessors$y.globalAttributes.get = function () {
    return this.header.globalAttributes;
};
/**
 * @return {Array<object>} - List of variables with:
 *  * `name`: String with the name of the variable
 *  * `dimensions`: Array with the dimension IDs of the variable
 *  * `attributes`: Array with the attributes of the variable
 *  * `type`: String with the type of the variable
 *  * `size`: Number with the size of the variable
 *  * `offset`: Number with the offset where of the variable begins
 *  * `record`: True if is a record variable, false otherwise
 */
prototypeAccessors$y.variables.get = function () {
    return this.header.variables;
};
/**
 * Checks if a variable is available
 * @param {string|object} variableName - Name of the variable to check
 * @return {Boolean} - Variable existence
 */
NetcdfReader.prototype.hasDataVariable = function hasDataVariable (variableName) {
    return this.header.variables.findIndex(function (val) {
        return val.name === variableName;
    }) !== -1;
};
/**
 * Retrieves the data for a given variable
 * @param {string|object} variableName - Name of the variable to search or variable object
 * @return {Array} - List with the variable values
 */
NetcdfReader.prototype.getDataVariable = function getDataVariable (variableName) {
    var variable;
    if (typeof variableName === 'string') {
        // search the variable
        variable = this.header.variables.find(function (val) {
            return val.name === variableName;
        });
    }
    else {
        variable = variableName;
    }
    // throws if variable not found
    notNetcdf((variable === undefined), 'variable not found');
    // go to the offset position
    this.buffer.seek(variable.offset);
    if (variable.record) {
        // record variable case
        return record(this.buffer, variable, this.header.recordDimension);
    }
    else {
        // non-record variable case
        return nonRecord(this.buffer, variable);
    }
};

Object.defineProperties( NetcdfReader.prototype, prototypeAccessors$y );

/**
 * @file Nctraj Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var NctrajParser = /*@__PURE__*/(function (TrajectoryParser$$1) {
    function NctrajParser () {
        TrajectoryParser$$1.apply(this, arguments);
    }

    if ( TrajectoryParser$$1 ) NctrajParser.__proto__ = TrajectoryParser$$1;
    NctrajParser.prototype = Object.create( TrajectoryParser$$1 && TrajectoryParser$$1.prototype );
    NctrajParser.prototype.constructor = NctrajParser;

    var prototypeAccessors = { type: { configurable: true },isBinary: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'nctraj'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    NctrajParser.prototype._parse = function _parse () {
        // http://ambermd.org/netcdf/nctraj.xhtml
        if (Debug)
            { Log.time('NctrajParser._parse ' + this.name); }
        var netcdfReader = new NetcdfReader(this.streamer.data);
        var f = this.frames;
        var coordinates = f.coordinates;
        var boxes = f.boxes;
        var times = f.times;
        netcdfReader.getDataVariable('coordinates').forEach(function (c) {
            coordinates.push(new Float32Array(c));
        });
        if (netcdfReader.hasDataVariable('cell_lengths')) {
            netcdfReader.getDataVariable('cell_lengths').forEach(function (b) {
                boxes.push(new Float32Array(b));
            });
        }
        if (netcdfReader.hasDataVariable('time')) {
            netcdfReader.getDataVariable('time').forEach(function (t) {
                times.push(t);
            });
        }
        if (times.length >= 1) {
            f.timeOffset = times[0];
        }
        if (times.length >= 2) {
            f.deltaTime = times[1] - times[0];
        }
        if (Debug)
            { Log.timeEnd('NctrajParser._parse ' + this.name); }
    };

    Object.defineProperties( NctrajParser.prototype, prototypeAccessors );

    return NctrajParser;
}(TrajectoryParser));
ParserRegistry$1.add('nctraj', NctrajParser);
ParserRegistry$1.add('ncdf', NctrajParser);
ParserRegistry$1.add('nc', NctrajParser);

/**
 * @file Trr Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var TrrParser = /*@__PURE__*/(function (TrajectoryParser$$1) {
    function TrrParser () {
        TrajectoryParser$$1.apply(this, arguments);
    }

    if ( TrajectoryParser$$1 ) TrrParser.__proto__ = TrajectoryParser$$1;
    TrrParser.prototype = Object.create( TrajectoryParser$$1 && TrajectoryParser$$1.prototype );
    TrrParser.prototype.constructor = TrrParser;

    var prototypeAccessors = { type: { configurable: true },isBinary: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'trr'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    TrrParser.prototype._parse = function _parse () {
        // https://github.com/gromacs/gromacs/blob/master/src/gromacs/fileio/trrio.cpp
        if (Debug)
            { Log.time('TrrParser._parse ' + this.name); }
        var bin = ensureBuffer(this.streamer.data);
        var dv = new DataView(bin);
        var f = this.frames;
        var coordinates = f.coordinates;
        var boxes = f.boxes;
        var times = f.times;
        var offset = 0;
        while (true) {
            // const magicnum = dv.getInt32(offset)
            // const i1 = dv.getFloat32(offset + 4)
            offset += 8;
            var versionSize = dv.getInt32(offset);
            offset += 4;
            offset += versionSize;
            // const irSize = dv.getInt32(offset)
            // const eSize = dv.getInt32(offset + 4)
            var boxSize = dv.getInt32(offset + 8);
            var virSize = dv.getInt32(offset + 12);
            var presSize = dv.getInt32(offset + 16);
            // const topSize = dv.getInt32(offset + 20)
            // const symSize = dv.getInt32(offset + 24)
            var coordSize = dv.getInt32(offset + 28);
            var velocitySize = dv.getInt32(offset + 32);
            var forceSize = dv.getInt32(offset + 36);
            var natoms = dv.getInt32(offset + 40);
            // const step = dv.getInt32(offset + 44)
            // const nre = dv.getInt32(offset + 48)
            offset += 52;
            var floatSize = boxSize / 9;
            var natoms3 = natoms * 3;
            // let lambda
            if (floatSize === 8) {
                times.push(dv.getFloat64(offset));
                // lambda = dv.getFloat64(offset + 8)
            }
            else {
                times.push(dv.getFloat32(offset));
                // lambda = dv.getFloat32(offset + 4)
            }
            offset += 2 * floatSize;
            if (boxSize) {
                var box = new Float32Array(9);
                if (floatSize === 8) {
                    for (var i = 0; i < 9; ++i) {
                        box[i] = dv.getFloat64(offset) * 10;
                        offset += 8;
                    }
                }
                else {
                    for (var i$1 = 0; i$1 < 9; ++i$1) {
                        box[i$1] = dv.getFloat32(offset) * 10;
                        offset += 4;
                    }
                }
                boxes.push(box);
            }
            // ignore, unused
            offset += virSize;
            // ignore, unused
            offset += presSize;
            if (coordSize) {
                var frameCoords = (void 0);
                if (floatSize === 8) {
                    frameCoords = new Float32Array(natoms3);
                    for (var i$2 = 0; i$2 < natoms3; ++i$2) {
                        frameCoords[i$2] = dv.getFloat64(offset) * 10;
                        offset += 8;
                    }
                }
                else {
                    var tmp = new Uint32Array(bin, offset, natoms3);
                    for (var i$3 = 0; i$3 < natoms3; ++i$3) {
                        var value = tmp[i$3];
                        tmp[i$3] = (((value & 0xFF) << 24) | ((value & 0xFF00) << 8) |
                            ((value >> 8) & 0xFF00) | ((value >> 24) & 0xFF));
                    }
                    frameCoords = new Float32Array(bin, offset, natoms3);
                    for (var i$4 = 0; i$4 < natoms3; ++i$4) {
                        frameCoords[i$4] *= 10;
                        offset += 4;
                    }
                }
                coordinates.push(frameCoords);
            }
            // ignore, unused
            offset += velocitySize;
            // ignore, unused
            offset += forceSize;
            if (offset >= bin.byteLength)
                { break; }
        }
        if (times.length >= 1) {
            f.timeOffset = times[0];
        }
        if (times.length >= 2) {
            f.deltaTime = times[1] - times[0];
        }
        if (Debug)
            { Log.timeEnd('TrrParser._parse ' + this.name); }
    };

    Object.defineProperties( TrrParser.prototype, prototypeAccessors );

    return TrrParser;
}(TrajectoryParser));
ParserRegistry$1.add('trr', TrrParser);

/**
 * @file Xtc Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var MagicInts = 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
]);
var FirstIdx = 9;
// const LastIdx = MagicInts.length
function sizeOfInt(size) {
    var num = 1;
    var numOfBits = 0;
    while (size >= num && numOfBits < 32) {
        numOfBits++;
        num <<= 1;
    }
    return numOfBits;
}
var _tmpBytes = new Uint8Array(32);
function sizeOfInts(numOfInts, sizes) {
    var numOfBytes = 1;
    var numOfBits = 0;
    _tmpBytes[0] = 1;
    for (var i = 0; i < numOfInts; i++) {
        var bytecnt = (void 0);
        var tmp = 0;
        for (bytecnt = 0; bytecnt < numOfBytes; bytecnt++) {
            tmp += _tmpBytes[bytecnt] * sizes[i];
            _tmpBytes[bytecnt] = tmp & 0xff;
            tmp >>= 8;
        }
        while (tmp !== 0) {
            _tmpBytes[bytecnt++] = tmp & 0xff;
            tmp >>= 8;
        }
        numOfBytes = bytecnt;
    }
    var num = 1;
    numOfBytes--;
    while (_tmpBytes[numOfBytes] >= num) {
        numOfBits++;
        num *= 2;
    }
    return numOfBits + numOfBytes * 8;
}
function decodeBits(buf, cbuf, numOfBits, buf2) {
    var mask = (1 << numOfBits) - 1;
    var lastBB0 = buf2[1];
    var lastBB1 = buf2[2];
    var cnt = buf[0];
    var num = 0;
    while (numOfBits >= 8) {
        lastBB1 = (lastBB1 << 8) | cbuf[cnt++];
        num |= (lastBB1 >> lastBB0) << (numOfBits - 8);
        numOfBits -= 8;
    }
    if (numOfBits > 0) {
        if (lastBB0 < numOfBits) {
            lastBB0 += 8;
            lastBB1 = (lastBB1 << 8) | cbuf[cnt++];
        }
        lastBB0 -= numOfBits;
        num |= (lastBB1 >> lastBB0) & ((1 << numOfBits) - 1);
    }
    num &= mask;
    buf[0] = cnt;
    buf[1] = lastBB0;
    buf[2] = lastBB1;
    return num;
}
var _tmpIntBytes = new Int32Array(32);
function decodeInts(buf, cbuf, numOfInts, numOfBits, sizes, nums, buf2) {
    var numOfBytes = 0;
    _tmpIntBytes[1] = 0;
    _tmpIntBytes[2] = 0;
    _tmpIntBytes[3] = 0;
    while (numOfBits > 8) {
        // this is inversed??? why??? because of the endiannness???
        _tmpIntBytes[numOfBytes++] = decodeBits(buf, cbuf, 8, buf2);
        numOfBits -= 8;
    }
    if (numOfBits > 0) {
        _tmpIntBytes[numOfBytes++] = decodeBits(buf, cbuf, numOfBits, buf2);
    }
    for (var i = numOfInts - 1; i > 0; i--) {
        var num = 0;
        for (var j = numOfBytes - 1; j >= 0; j--) {
            num = (num << 8) | _tmpIntBytes[j];
            var p = (num / sizes[i]) | 0;
            _tmpIntBytes[j] = p;
            num = num - p * sizes[i];
        }
        nums[i] = num;
    }
    nums[0] = (_tmpIntBytes[0] |
        (_tmpIntBytes[1] << 8) |
        (_tmpIntBytes[2] << 16) |
        (_tmpIntBytes[3] << 24));
}
var XtcParser = /*@__PURE__*/(function (TrajectoryParser$$1) {
    function XtcParser () {
        TrajectoryParser$$1.apply(this, arguments);
    }

    if ( TrajectoryParser$$1 ) XtcParser.__proto__ = TrajectoryParser$$1;
    XtcParser.prototype = Object.create( TrajectoryParser$$1 && TrajectoryParser$$1.prototype );
    XtcParser.prototype.constructor = XtcParser;

    var prototypeAccessors = { type: { configurable: true },isBinary: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'xtc'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    XtcParser.prototype._parse = function _parse () {
        // https://github.com/gromacs/gromacs/blob/master/src/gromacs/fileio/xtcio.cpp
        // https://github.com/gromacs/gromacs/blob/master/src/gromacs/fileio/libxdrf.cpp
        if (Debug)
            { Log.time('XtcParser._parse ' + this.name); }
        var bin = ensureBuffer(this.streamer.data);
        var dv = new DataView(bin);
        var f = this.frames;
        var coordinates = f.coordinates;
        var boxes = f.boxes;
        var times = f.times;
        var minMaxInt = new Int32Array(6);
        var sizeint = new Int32Array(3);
        var bitsizeint = new Int32Array(3);
        var sizesmall = new Uint32Array(3);
        var thiscoord = new Float32Array(3);
        var prevcoord = new Float32Array(3);
        var offset = 0;
        var buf = new Int32Array(3);
        var buf2 = new Uint32Array(buf.buffer);
        while (true) {
            var frameCoords = (void 0);
            // const magicnum = dv.getInt32(offset)
            var natoms = dv.getInt32(offset + 4);
            // const step = dv.getInt32(offset + 8)
            offset += 12;
            var natoms3 = natoms * 3;
            times.push(dv.getFloat32(offset));
            offset += 4;
            var box = new Float32Array(9);
            for (var i = 0; i < 9; ++i) {
                box[i] = dv.getFloat32(offset) * 10;
                offset += 4;
            }
            boxes.push(box);
            if (natoms <= 9) { // no compression
                frameCoords = new Float32Array(natoms);
                for (var i$1 = 0; i$1 < natoms; ++i$1) {
                    frameCoords[i$1] = dv.getFloat32(offset);
                    offset += 4;
                }
            }
            else {
                buf[0] = buf[1] = buf[2] = 0.0;
                sizeint[0] = sizeint[1] = sizeint[2] = 0;
                sizesmall[0] = sizesmall[1] = sizesmall[2] = 0;
                bitsizeint[0] = bitsizeint[1] = bitsizeint[2] = 0;
                thiscoord[0] = thiscoord[1] = thiscoord[2] = 0;
                prevcoord[0] = prevcoord[1] = prevcoord[2] = 0;
                frameCoords = new Float32Array(natoms3);
                var lfp = 0;
                var lsize = dv.getInt32(offset);
                offset += 4;
                var precision = dv.getFloat32(offset);
                offset += 4;
                minMaxInt[0] = dv.getInt32(offset);
                minMaxInt[1] = dv.getInt32(offset + 4);
                minMaxInt[2] = dv.getInt32(offset + 8);
                minMaxInt[3] = dv.getInt32(offset + 12);
                minMaxInt[4] = dv.getInt32(offset + 16);
                minMaxInt[5] = dv.getInt32(offset + 20);
                sizeint[0] = minMaxInt[3] - minMaxInt[0] + 1;
                sizeint[1] = minMaxInt[4] - minMaxInt[1] + 1;
                sizeint[2] = minMaxInt[5] - minMaxInt[2] + 1;
                offset += 24;
                var bitsize = (void 0);
                if ((sizeint[0] | sizeint[1] | sizeint[2]) > 0xffffff) {
                    bitsizeint[0] = sizeOfInt(sizeint[0]);
                    bitsizeint[1] = sizeOfInt(sizeint[1]);
                    bitsizeint[2] = sizeOfInt(sizeint[2]);
                    bitsize = 0; // flag the use of large sizes
                }
                else {
                    bitsize = sizeOfInts(3, sizeint);
                }
                var smallidx = dv.getInt32(offset);
                offset += 4;
                // if (smallidx == 0) {alert("Undocumented error 1"); return;}
                // let tmpIdx = smallidx + 8
                // const maxidx = (LastIdx < tmpIdx) ? LastIdx : tmpIdx
                // const minidx = maxidx - 8  // often this equal smallidx
                var tmpIdx = smallidx - 1;
                tmpIdx = (FirstIdx > tmpIdx) ? FirstIdx : tmpIdx;
                var smaller = (MagicInts[tmpIdx] / 2) | 0;
                var smallnum = (MagicInts[smallidx] / 2) | 0;
                sizesmall[0] = sizesmall[1] = sizesmall[2] = MagicInts[smallidx];
                // larger = MagicInts[maxidx]
                var adz = Math.ceil(dv.getInt32(offset) / 4) * 4;
                offset += 4;
                // if (tmpIdx == 0) {alert("Undocumented error 2"); return;}
                // buf = new Int32Array(bin, offset);
                // buf8 = new Uint8Array(bin, offset);
                // tmpIdx += 3; rndup = tmpIdx%4;
                // for (i=tmpIdx+rndup-1; i>=tmpIdx; i--) buf8[i] = 0;
                // now unpack buf2...
                var invPrecision = 1.0 / precision;
                var run = 0;
                var i$2 = 0;
                var buf8 = new Uint8Array(bin, offset); // 229...
                thiscoord[0] = thiscoord[1] = thiscoord[2] = 0;
                while (i$2 < lsize) {
                    if (bitsize === 0) {
                        thiscoord[0] = decodeBits(buf, buf8, bitsizeint[0], buf2);
                        thiscoord[1] = decodeBits(buf, buf8, bitsizeint[1], buf2);
                        thiscoord[2] = decodeBits(buf, buf8, bitsizeint[2], buf2);
                    }
                    else {
                        decodeInts(buf, buf8, 3, bitsize, sizeint, thiscoord, buf2);
                    }
                    i$2++;
                    thiscoord[0] += minMaxInt[0];
                    thiscoord[1] += minMaxInt[1];
                    thiscoord[2] += minMaxInt[2];
                    prevcoord[0] = thiscoord[0];
                    prevcoord[1] = thiscoord[1];
                    prevcoord[2] = thiscoord[2];
                    var flag = decodeBits(buf, buf8, 1, buf2);
                    var isSmaller = 0;
                    if (flag === 1) {
                        run = decodeBits(buf, buf8, 5, buf2);
                        isSmaller = run % 3;
                        run -= isSmaller;
                        isSmaller--;
                    }
                    // if ((lfp-ptrstart)+run > size3){
                    //   fprintf(stderr, "(xdrfile error) Buffer overrun during decompression.\n");
                    //   return 0;
                    // }
                    if (run > 0) {
                        thiscoord[0] = thiscoord[1] = thiscoord[2] = 0;
                        for (var k = 0; k < run; k += 3) {
                            decodeInts(buf, buf8, 3, smallidx, sizesmall, thiscoord, buf2);
                            i$2++;
                            thiscoord[0] += prevcoord[0] - smallnum;
                            thiscoord[1] += prevcoord[1] - smallnum;
                            thiscoord[2] += prevcoord[2] - smallnum;
                            if (k === 0) {
                                // interchange first with second atom for
                                // better compression of water molecules
                                var tmpSwap = thiscoord[0];
                                thiscoord[0] = prevcoord[0];
                                prevcoord[0] = tmpSwap;
                                tmpSwap = thiscoord[1];
                                thiscoord[1] = prevcoord[1];
                                prevcoord[1] = tmpSwap;
                                tmpSwap = thiscoord[2];
                                thiscoord[2] = prevcoord[2];
                                prevcoord[2] = tmpSwap;
                                frameCoords[lfp++] = prevcoord[0] * invPrecision;
                                frameCoords[lfp++] = prevcoord[1] * invPrecision;
                                frameCoords[lfp++] = prevcoord[2] * invPrecision;
                            }
                            else {
                                prevcoord[0] = thiscoord[0];
                                prevcoord[1] = thiscoord[1];
                                prevcoord[2] = thiscoord[2];
                            }
                            frameCoords[lfp++] = thiscoord[0] * invPrecision;
                            frameCoords[lfp++] = thiscoord[1] * invPrecision;
                            frameCoords[lfp++] = thiscoord[2] * invPrecision;
                        }
                    }
                    else {
                        frameCoords[lfp++] = thiscoord[0] * invPrecision;
                        frameCoords[lfp++] = thiscoord[1] * invPrecision;
                        frameCoords[lfp++] = thiscoord[2] * invPrecision;
                    }
                    smallidx += isSmaller;
                    if (isSmaller < 0) {
                        smallnum = smaller;
                        if (smallidx > FirstIdx) {
                            smaller = (MagicInts[smallidx - 1] / 2) | 0;
                        }
                        else {
                            smaller = 0;
                        }
                    }
                    else if (isSmaller > 0) {
                        smaller = smallnum;
                        smallnum = (MagicInts[smallidx] / 2) | 0;
                    }
                    sizesmall[0] = sizesmall[1] = sizesmall[2] = MagicInts[smallidx];
                    if (sizesmall[0] === 0 || sizesmall[1] === 0 || sizesmall[2] === 0) {
                        console.error('(xdrfile error) Undefined error.');
                        return;
                    }
                }
                offset += adz;
            }
            for (var c = 0; c < natoms3; c++) {
                frameCoords[c] *= 10;
            }
            coordinates.push(frameCoords);
            if (offset >= bin.byteLength)
                { break; }
        }
        if (times.length >= 1) {
            f.timeOffset = times[0];
        }
        if (times.length >= 2) {
            f.deltaTime = times[1] - times[0];
        }
        if (Debug)
            { Log.timeEnd('XtcParser._parse ' + this.name); }
    };

    Object.defineProperties( XtcParser.prototype, prototypeAccessors );

    return XtcParser;
}(TrajectoryParser));
ParserRegistry$1.add('xtc', XtcParser);

/**
 * @file Volume Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var VolumeParser = /*@__PURE__*/(function (Parser$$1) {
    function VolumeParser(streamer, params) {
        var p = params || {};
        Parser$$1.call(this, streamer, p);
        this.volume = new Volume(this.name, this.path);
        this.voxelSize = defaults(p.voxelSize, 1);
    }

    if ( Parser$$1 ) VolumeParser.__proto__ = Parser$$1;
    VolumeParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    VolumeParser.prototype.constructor = VolumeParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'volume'; };
    prototypeAccessors.__objName.get = function () { return 'volume'; };
    VolumeParser.prototype._afterParse = function _afterParse () {
        this.volume.setMatrix(this.getMatrix());
        Parser$$1.prototype._afterParse.call(this);
    };
    VolumeParser.prototype.getMatrix = function getMatrix () {
        return new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
    };

    Object.defineProperties( VolumeParser.prototype, prototypeAccessors );

    return VolumeParser;
}(Parser));

/**
 * @file Cube Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
// @author Johanna Tiemann <johanna.tiemann@googlemail.com>
// @author Alexander Rose <alexander.rose@weirdbyte.de>
var reWhitespace$5 = /\s+/;
var reScientificNotation = /-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/g;
var bohrToAngstromFactor = 0.529177210859;
var CubeParser = /*@__PURE__*/(function (VolumeParser$$1) {
    function CubeParser () {
        VolumeParser$$1.apply(this, arguments);
    }

    if ( VolumeParser$$1 ) CubeParser.__proto__ = VolumeParser$$1;
    CubeParser.prototype = Object.create( VolumeParser$$1 && VolumeParser$$1.prototype );
    CubeParser.prototype.constructor = CubeParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'cube'; };
    CubeParser.prototype._parse = function _parse () {
        // http://paulbourke.net/dataformats/cube/
        if (Debug)
            { Log.time('CubeParser._parse ' + this.name); }
        var v = this.volume;
        var headerLines = this.streamer.peekLines(6);
        var header = {};
        var scaleFactor = bohrToAngstromFactor * this.voxelSize;
        function h(k, l) {
            var field = headerLines[k].trim().split(reWhitespace$5)[l];
            return parseFloat(field);
        }
        header.atomCount = Math.abs(h(2, 0)); // Number of atoms
        header.originX = h(2, 1) * bohrToAngstromFactor; // Position of origin of volumetric data
        header.originY = h(2, 2) * bohrToAngstromFactor;
        header.originZ = h(2, 3) * bohrToAngstromFactor;
        header.NVX = h(3, 0); // Number of voxels
        header.NVY = h(4, 0);
        header.NVZ = h(5, 0);
        header.basisX = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](h(3, 1), h(3, 2), h(3, 3))
            .multiplyScalar(scaleFactor);
        header.basisY = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](h(4, 1), h(4, 2), h(4, 3))
            .multiplyScalar(scaleFactor);
        header.basisZ = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](h(5, 1), h(5, 2), h(5, 3))
            .multiplyScalar(scaleFactor);
        var data = new Float32Array(header.NVX * header.NVY * header.NVZ);
        var count = 0;
        var lineNo = 0;
        var oribitalFlag = h(2, 0) > 0 ? 0 : 1;
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                var line = lines[i].trim();
                if (line !== '' && lineNo >= header.atomCount + 6 + oribitalFlag) {
                    var m = line.match(reScientificNotation);
                    for (var j = 0, lj = m.length; j < lj; ++j) {
                        data[count] = parseFloat(m[j]);
                        ++count;
                    }
                }
                ++lineNo;
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        v.header = header;
        v.setData(data, header.NVZ, header.NVY, header.NVX);
        if (Debug)
            { Log.timeEnd('CubeParser._parse ' + this.name); }
    };
    CubeParser.prototype.getMatrix = function getMatrix () {
        var h = this.volume.header;
        var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeTranslation(h.originX, h.originY, h.originZ));
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeBasis(h.basisZ, h.basisY, h.basisX));
        return matrix;
    };

    Object.defineProperties( CubeParser.prototype, prototypeAccessors );

    return CubeParser;
}(VolumeParser));
ParserRegistry$1.add('cub', CubeParser);
ParserRegistry$1.add('cube', CubeParser);

/**
 * @file Dsn6 Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var Dsn6Parser = /*@__PURE__*/(function (VolumeParser$$1) {
    function Dsn6Parser () {
        VolumeParser$$1.apply(this, arguments);
    }

    if ( VolumeParser$$1 ) Dsn6Parser.__proto__ = VolumeParser$$1;
    Dsn6Parser.prototype = Object.create( VolumeParser$$1 && VolumeParser$$1.prototype );
    Dsn6Parser.prototype.constructor = Dsn6Parser;

    var prototypeAccessors = { type: { configurable: true },isBinary: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'dsn6'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    Dsn6Parser.prototype._parse = function _parse () {
        // DSN6 http://www.uoxray.uoregon.edu/tnt/manual/node104.html
        // BRIX http://svn.cgl.ucsf.edu/svn/chimera/trunk/libs/VolumeData/dsn6/brix-1.html
        if (Debug)
            { Log.time('Dsn6Parser._parse ' + this.name); }
        var v = this.volume;
        var header = {};
        var divisor, summand;
        var bin = ensureBuffer(this.streamer.data);
        var intView = new Int16Array(bin);
        var byteView = new Uint8Array(bin);
        var brixStr = String.fromCharCode.apply(null, byteView.subarray(0, 512));
        if (brixStr.startsWith(':-)')) {
            header.xStart = parseInt(brixStr.substr(10, 5)); // NXSTART
            header.yStart = parseInt(brixStr.substr(15, 5));
            header.zStart = parseInt(brixStr.substr(20, 5));
            header.xExtent = parseInt(brixStr.substr(32, 5)); // NX
            header.yExtent = parseInt(brixStr.substr(38, 5));
            header.zExtent = parseInt(brixStr.substr(42, 5));
            header.xRate = parseInt(brixStr.substr(52, 5)); // MX
            header.yRate = parseInt(brixStr.substr(58, 5));
            header.zRate = parseInt(brixStr.substr(62, 5));
            header.xlen = parseFloat(brixStr.substr(73, 10)) * this.voxelSize;
            header.ylen = parseFloat(brixStr.substr(83, 10)) * this.voxelSize;
            header.zlen = parseFloat(brixStr.substr(93, 10)) * this.voxelSize;
            header.alpha = parseFloat(brixStr.substr(103, 10));
            header.beta = parseFloat(brixStr.substr(113, 10));
            header.gamma = parseFloat(brixStr.substr(123, 10));
            divisor = parseFloat(brixStr.substr(138, 12)) / 100;
            summand = parseInt(brixStr.substr(155, 8));
            header.sigma = parseFloat(brixStr.substr(170, 12)) * 100;
        }
        else {
            // swap byte order when big endian
            if (intView[18] !== 100) {
                for (var i$1 = 0, n = intView.length; i$1 < n; ++i$1) {
                    var val = intView[i$1];
                    intView[i$1] = ((val & 0xff) << 8) | ((val >> 8) & 0xff);
                }
            }
            header.xStart = intView[0]; // NXSTART
            header.yStart = intView[1];
            header.zStart = intView[2];
            header.xExtent = intView[3]; // NX
            header.yExtent = intView[4];
            header.zExtent = intView[5];
            header.xRate = intView[6]; // MX
            header.yRate = intView[7];
            header.zRate = intView[8];
            var factor = 1 / intView[17];
            var scalingFactor = factor * this.voxelSize;
            header.xlen = intView[9] * scalingFactor;
            header.ylen = intView[10] * scalingFactor;
            header.zlen = intView[11] * scalingFactor;
            header.alpha = intView[12] * factor;
            header.beta = intView[13] * factor;
            header.gamma = intView[14] * factor;
            divisor = intView[15] / 100;
            summand = intView[16];
            header.gamma = intView[14] * factor;
        }
        v.header = header;
        if (Debug)
            { Log.log(header, divisor, summand); }
        var data = new Float32Array(header.xExtent * header.yExtent * header.zExtent);
        var offset = 512;
        var xBlocks = Math.ceil(header.xExtent / 8);
        var yBlocks = Math.ceil(header.yExtent / 8);
        var zBlocks = Math.ceil(header.zExtent / 8);
        // loop over blocks
        for (var zz = 0; zz < zBlocks; ++zz) {
            for (var yy = 0; yy < yBlocks; ++yy) {
                for (var xx = 0; xx < xBlocks; ++xx) {
                    // loop inside block
                    for (var k = 0; k < 8; ++k) {
                        var z = 8 * zz + k;
                        for (var j = 0; j < 8; ++j) {
                            var y = 8 * yy + j;
                            for (var i = 0; i < 8; ++i) {
                                var x = 8 * xx + i;
                                // check if remaining slice-part contains data
                                if (x < header.xExtent && y < header.yExtent && z < header.zExtent) {
                                    var idx = ((((x * header.yExtent) + y) * header.zExtent) + z);
                                    data[idx] = (byteView[offset] - summand) / divisor;
                                    ++offset;
                                }
                                else {
                                    offset += 8 - i;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        v.setData(data, header.zExtent, header.yExtent, header.xExtent);
        if (header.sigma) {
            v.setStats(undefined, undefined, undefined, header.sigma);
        }
        if (Debug)
            { Log.timeEnd('Dsn6Parser._parse ' + this.name); }
    };
    Dsn6Parser.prototype.getMatrix = function getMatrix () {
        var h = this.volume.header;
        var basisX = [
            h.xlen,
            0,
            0
        ];
        var basisY = [
            h.ylen * Math.cos(Math.PI / 180.0 * h.gamma),
            h.ylen * Math.sin(Math.PI / 180.0 * h.gamma),
            0
        ];
        var basisZ = [
            h.zlen * Math.cos(Math.PI / 180.0 * h.beta),
            h.zlen * (Math.cos(Math.PI / 180.0 * h.alpha) -
                Math.cos(Math.PI / 180.0 * h.gamma) *
                    Math.cos(Math.PI / 180.0 * h.beta)) / Math.sin(Math.PI / 180.0 * h.gamma),
            0
        ];
        basisZ[2] = Math.sqrt(h.zlen * h.zlen * Math.sin(Math.PI / 180.0 * h.beta) *
            Math.sin(Math.PI / 180.0 * h.beta) - basisZ[1] * basisZ[1]);
        var basis = [[], basisX, basisY, basisZ];
        var nxyz = [0, h.xRate, h.yRate, h.zRate];
        var mapcrs = [0, 1, 2, 3];
        var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
        matrix.set(basis[mapcrs[1]][0] / nxyz[mapcrs[1]], basis[mapcrs[2]][0] / nxyz[mapcrs[2]], basis[mapcrs[3]][0] / nxyz[mapcrs[3]], 0, basis[mapcrs[1]][1] / nxyz[mapcrs[1]], basis[mapcrs[2]][1] / nxyz[mapcrs[2]], basis[mapcrs[3]][1] / nxyz[mapcrs[3]], 0, basis[mapcrs[1]][2] / nxyz[mapcrs[1]], basis[mapcrs[2]][2] / nxyz[mapcrs[2]], basis[mapcrs[3]][2] / nxyz[mapcrs[3]], 0, 0, 0, 0, 1);
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeRotationY(degToRad(90)));
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeTranslation(-h.zStart, h.yStart, h.xStart));
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeScale(-1, 1, 1));
        return matrix;
    };

    Object.defineProperties( Dsn6Parser.prototype, prototypeAccessors );

    return Dsn6Parser;
}(VolumeParser));
ParserRegistry$1.add('dsn6', Dsn6Parser);
ParserRegistry$1.add('brix', Dsn6Parser);

/**
 * @file Dx Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var reWhitespace$6 = /\s+/;
var DxParser = /*@__PURE__*/(function (VolumeParser$$1) {
    function DxParser () {
        VolumeParser$$1.apply(this, arguments);
    }

    if ( VolumeParser$$1 ) DxParser.__proto__ = VolumeParser$$1;
    DxParser.prototype = Object.create( VolumeParser$$1 && VolumeParser$$1.prototype );
    DxParser.prototype.constructor = DxParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'dx'; };
    DxParser.prototype._parse = function _parse () {
        // http://apbs-pdb2pqr.readthedocs.io/en/latest/formats/opendx.html
        if (Debug)
            { Log.time('DxParser._parse ' + this.name); }
        var v = this.volume;
        var headerLines = this.streamer.peekLines(30);
        var headerInfo = this.parseHeaderLines(headerLines);
        var header = this.volume.header;
        var dataLineStart = headerInfo.dataLineStart;
        var size = header.nx * header.ny * header.nz;
        var data = new Float32Array(size);
        var count = 0;
        var lineNo = 0;
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                if (count < size && lineNo > dataLineStart) {
                    var line = lines[i].trim();
                    if (line !== '') {
                        var ls = line.split(reWhitespace$6);
                        for (var j = 0, lj = ls.length; j < lj; ++j) {
                            data[count] = parseFloat(ls[j]);
                            ++count;
                        }
                    }
                }
                ++lineNo;
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        v.setData(data, header.nz, header.ny, header.nx);
        if (Debug)
            { Log.timeEnd('DxParser._parse ' + this.name); }
    };
    DxParser.prototype.parseHeaderLines = function parseHeaderLines (headerLines) {
        var header = {};
        var n = headerLines.length;
        var dataLineStart = 0;
        var headerByteCount = 0;
        var deltaLineCount = 0;
        for (var i = 0; i < n; ++i) {
            var ls = (void 0);
            var line = headerLines[i];
            if (line.startsWith('object 1')) {
                ls = line.split(reWhitespace$6);
                header.nx = parseInt(ls[5]);
                header.ny = parseInt(ls[6]);
                header.nz = parseInt(ls[7]);
            }
            else if (line.startsWith('origin')) {
                ls = line.split(reWhitespace$6);
                header.xmin = parseFloat(ls[1]);
                header.ymin = parseFloat(ls[2]);
                header.zmin = parseFloat(ls[3]);
            }
            else if (line.startsWith('delta')) {
                ls = line.split(reWhitespace$6);
                if (deltaLineCount === 0) {
                    header.hx = parseFloat(ls[1]) * this.voxelSize;
                }
                else if (deltaLineCount === 1) {
                    header.hy = parseFloat(ls[2]) * this.voxelSize;
                }
                else if (deltaLineCount === 2) {
                    header.hz = parseFloat(ls[3]) * this.voxelSize;
                }
                deltaLineCount += 1;
            }
            else if (line.startsWith('object 3')) {
                dataLineStart = i;
                headerByteCount += line.length + 1;
                break;
            }
            headerByteCount += line.length + 1;
        }
        this.volume.header = header;
        return {
            dataLineStart: dataLineStart,
            headerByteCount: headerByteCount
        };
    };
    DxParser.prototype.getMatrix = function getMatrix () {
        var h = this.volume.header;
        var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeRotationY(degToRad(90)));
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeTranslation(-h.zmin, h.ymin, h.xmin));
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeScale(-h.hz, h.hy, h.hx));
        return matrix;
    };

    Object.defineProperties( DxParser.prototype, prototypeAccessors );

    return DxParser;
}(VolumeParser));
ParserRegistry$1.add('dx', DxParser);

/**
 * @file Dxbin Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var DxbinParser = /*@__PURE__*/(function (DxParser$$1) {
    function DxbinParser () {
        DxParser$$1.apply(this, arguments);
    }

    if ( DxParser$$1 ) DxbinParser.__proto__ = DxParser$$1;
    DxbinParser.prototype = Object.create( DxParser$$1 && DxParser$$1.prototype );
    DxbinParser.prototype.constructor = DxbinParser;

    var prototypeAccessors = { type: { configurable: true },isBinary: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'dxbin'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    DxbinParser.prototype._parse = function _parse () {
        // https://github.com/Electrostatics/apbs-pdb2pqr/issues/216
        if (Debug)
            { Log.time('DxbinParser._parse ' + this.name); }
        var bin = ensureBuffer(this.streamer.data);
        var headerLines = uint8ToLines(new Uint8Array(bin, 0, 1000));
        var headerInfo = this.parseHeaderLines(headerLines);
        var header = this.volume.header;
        var headerByteCount = headerInfo.headerByteCount;
        var size = header.nx * header.ny * header.nz;
        var dv = new DataView(bin);
        var data = new Float32Array(size);
        for (var i = 0; i < size; ++i) {
            data[i] = dv.getFloat64(i * 8 + headerByteCount, true);
        }
        this.volume.setData(data, header.nz, header.ny, header.nx);
        if (Debug)
            { Log.timeEnd('DxbinParser._parse ' + this.name); }
    };

    Object.defineProperties( DxbinParser.prototype, prototypeAccessors );

    return DxbinParser;
}(DxParser));
ParserRegistry$1.add('dxbin', DxbinParser);

/**
 * @file Mrc Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var MrcParser = /*@__PURE__*/(function (VolumeParser$$1) {
    function MrcParser () {
        VolumeParser$$1.apply(this, arguments);
    }

    if ( VolumeParser$$1 ) MrcParser.__proto__ = VolumeParser$$1;
    MrcParser.prototype = Object.create( VolumeParser$$1 && VolumeParser$$1.prototype );
    MrcParser.prototype.constructor = MrcParser;

    var prototypeAccessors = { type: { configurable: true },isBinary: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'mrc'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    MrcParser.prototype._parse = function _parse () {
        // MRC
        // http://ami.scripps.edu/software/mrctools/mrc_specification.php
        // http://www2.mrc-lmb.cam.ac.uk/research/locally-developed-software/image-processing-software/#image
        // http://bio3d.colorado.edu/imod/doc/mrc_format.txt
        // CCP4 (MAP)
        // http://www.ccp4.ac.uk/html/maplib.html
        // MRC format does not use the skew transformation header records (words 25-37)
        // CCP4 format does not use the ORIGIN header records (words 50-52)
        if (Debug)
            { Log.time('MrcParser._parse ' + this.name); }
        var v = this.volume;
        var header = {};
        var bin = ensureBuffer(this.streamer.data);
        var intView = new Int32Array(bin, 0, 56);
        var floatView = new Float32Array(bin, 0, 56);
        var dv = new DataView(bin);
        // 53  MAP         Character string 'MAP ' to identify file type
        header.MAP = String.fromCharCode(dv.getUint8(52 * 4), dv.getUint8(52 * 4 + 1), dv.getUint8(52 * 4 + 2), dv.getUint8(52 * 4 + 3));
        // 54  MACHST      Machine stamp indicating machine type which wrote file
        //                 17 and 17 for big-endian or 68 and 65 for little-endian
        header.MACHST = [dv.getUint8(53 * 4), dv.getUint8(53 * 4 + 1)];
        // swap byte order when big endian
        if (header.MACHST[0] === 17 && header.MACHST[1] === 17) {
            var n = bin.byteLength;
            for (var i = 0; i < n; i += 4) {
                dv.setFloat32(i, dv.getFloat32(i), true);
            }
        }
        header.NX = intView[0]; // NC - columns (fastest changing)
        header.NY = intView[1]; // NR - rows
        header.NZ = intView[2]; // NS - sections (slowest changing)
        // mode
        //  0 image : signed 8-bit bytes range -128 to 127
        //  1 image : 16-bit halfwords
        //  2 image : 32-bit reals
        //  3 transform : complex 16-bit integers
        //  4 transform : complex 32-bit reals
        //  6 image : unsigned 16-bit range 0 to 65535
        // 16 image: unsigned char * 3 (for rgb data, non-standard)
        //
        // Note: Mode 2 is the normal mode used in the CCP4 programs.
        //       Other modes than 2 and 0 may NOT WORK
        header.MODE = intView[3];
        // start
        header.NXSTART = intView[4]; // NCSTART - first column
        header.NYSTART = intView[5]; // NRSTART - first row
        header.NZSTART = intView[6]; // NSSTART - first section
        // intervals
        header.MX = intView[7]; // intervals along x
        header.MY = intView[8]; // intervals along y
        header.MZ = intView[9]; // intervals along z
        // cell length (Angstroms in CCP4)
        header.xlen = floatView[10] * this.voxelSize;
        header.ylen = floatView[11] * this.voxelSize;
        header.zlen = floatView[12] * this.voxelSize;
        // cell angle (Degrees)
        header.alpha = floatView[13];
        header.beta = floatView[14];
        header.gamma = floatView[15];
        // axis correspondence (1,2,3 for X,Y,Z)
        header.MAPC = intView[16]; // column
        header.MAPR = intView[17]; // row
        header.MAPS = intView[18]; // section
        // density statistics
        header.DMIN = floatView[19];
        header.DMAX = floatView[20];
        header.DMEAN = floatView[21];
        // space group number 0 or 1 (default=0)
        header.ISPG = intView[22];
        // number of bytes used for symmetry data (0 or 80)
        header.NSYMBT = intView[23];
        // Flag for skew transformation, =0 none, =1 if foll
        header.LSKFLG = intView[24];
        // 26-34  SKWMAT  Skew matrix S (in order S11, S12, S13, S21 etc) if
        //                LSKFLG .ne. 0.
        // 35-37  SKWTRN  Skew translation t if LSKFLG != 0.
        //                Skew transformation is from standard orthogonal
        //                coordinate frame (as used for atoms) to orthogonal
        //                map frame, as Xo(map) = S * (Xo(atoms) - t)
        // 38      future use       (some of these are used by the MSUBSX routines
        //  .          "              in MAPBRICK, MAPCONT and FRODO)
        //  .          "   (all set to zero by default)
        //  .          "
        // 52          "
        // 50-52 origin in X,Y,Z used for transforms
        header.originX = floatView[49];
        header.originY = floatView[50];
        header.originZ = floatView[51];
        // 53  MAP         Character string 'MAP ' to identify file type
        // => see top of this parser
        // 54  MACHST      Machine stamp indicating machine type which wrote file
        // => see top of this parser
        // Rms deviation of map from mean density
        header.ARMS = floatView[54];
        // 56      NLABL           Number of labels being used
        // 57-256  LABEL(20,10)    10  80 character text labels (ie. A4 format)
        v.header = header;
        // Log.log( header );
        var data;
        if (header.MODE === 2) {
            data = new Float32Array(bin, 256 * 4 + header.NSYMBT, header.NX * header.NY * header.NZ);
        }
        else if (header.MODE === 0) {
            data = new Float32Array(new Int8Array(bin, 256 * 4 + header.NSYMBT, header.NX * header.NY * header.NZ));
            // based on uglymol (https://github.com/uglymol/uglymol) by Marcin Wojdyr (wojdyr)
            // if the file was converted by mapmode2to0 - scale the data
            if (intView[39] === -128 && intView[40] === 127) {
                // scaling f(x)=b1*x+b0 such that f(-128)=min and f(127)=max
                var b1 = (header.DMAX - header.DMIN) / 255.0;
                var b0 = 0.5 * (header.DMIN + header.DMAX + b1);
                for (var j = 0, jl = data.length; j < jl; ++j) {
                    data[j] = b1 * data[j] + b0;
                }
            }
        }
        else {
            Log.error('MrcParser unknown mode', header.MODE);
        }
        v.setData(data, header.NX, header.NY, header.NZ);
        if (header.ARMS !== 0) {
            v.setStats(header.DMIN, header.DMAX, header.DMEAN, header.ARMS);
        }
        if (Debug)
            { Log.timeEnd('MrcParser._parse ' + this.name); }
    };
    MrcParser.prototype.getMatrix = function getMatrix () {
        var h = this.volume.header;
        var basisX = [
            h.xlen,
            0,
            0
        ];
        var basisY = [
            h.ylen * Math.cos(Math.PI / 180.0 * h.gamma),
            h.ylen * Math.sin(Math.PI / 180.0 * h.gamma),
            0
        ];
        var basisZ = [
            h.zlen * Math.cos(Math.PI / 180.0 * h.beta),
            h.zlen * (Math.cos(Math.PI / 180.0 * h.alpha) -
                Math.cos(Math.PI / 180.0 * h.gamma) *
                    Math.cos(Math.PI / 180.0 * h.beta)) / Math.sin(Math.PI / 180.0 * h.gamma),
            0
        ];
        basisZ[2] = Math.sqrt(h.zlen * h.zlen * Math.sin(Math.PI / 180.0 * h.beta) *
            Math.sin(Math.PI / 180.0 * h.beta) - basisZ[1] * basisZ[1]);
        var basis = [[], basisX, basisY, basisZ];
        var nxyz = [0, h.MX, h.MY, h.MZ];
        var mapcrs = [0, h.MAPC, h.MAPR, h.MAPS];
        var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
        matrix.set(basis[mapcrs[1]][0] / nxyz[mapcrs[1]], basis[mapcrs[2]][0] / nxyz[mapcrs[2]], basis[mapcrs[3]][0] / nxyz[mapcrs[3]], 0, basis[mapcrs[1]][1] / nxyz[mapcrs[1]], basis[mapcrs[2]][1] / nxyz[mapcrs[2]], basis[mapcrs[3]][1] / nxyz[mapcrs[3]], 0, basis[mapcrs[1]][2] / nxyz[mapcrs[1]], basis[mapcrs[2]][2] / nxyz[mapcrs[2]], basis[mapcrs[3]][2] / nxyz[mapcrs[3]], 0, 0, 0, 0, 1);
        matrix.setPosition(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](h.originX, h.originY, h.originZ));
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeTranslation(h.NXSTART, h.NYSTART, h.NZSTART));
        return matrix;
    };

    Object.defineProperties( MrcParser.prototype, prototypeAccessors );

    return MrcParser;
}(VolumeParser));
ParserRegistry$1.add('mrc', MrcParser);
ParserRegistry$1.add('ccp4', MrcParser);
ParserRegistry$1.add('map', MrcParser);

/**
 * @file Xplor Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var reWhitespace$7 = /\s+/;
function parseNumberLine(line) {
    return line.trim().split(reWhitespace$7).map(parseFloat);
}
var XplorParser = /*@__PURE__*/(function (VolumeParser$$1) {
    function XplorParser () {
        VolumeParser$$1.apply(this, arguments);
    }

    if ( VolumeParser$$1 ) XplorParser.__proto__ = VolumeParser$$1;
    XplorParser.prototype = Object.create( VolumeParser$$1 && VolumeParser$$1.prototype );
    XplorParser.prototype.constructor = XplorParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'xplor'; };
    XplorParser.prototype._parse = function _parse () {
        // http://hincklab.uthscsa.edu/html/soft_packs/msi_docs/insight980/xplor/formats.html
        // http://www.mrc-lmb.cam.ac.uk/public/xtal/doc/cns/cns_1.3/tutorial/formats/maps/text.html
        if (Debug)
            { Log.time('XplorParser._parse ' + this.name); }
        var v = this.volume;
        var headerLines = this.streamer.peekLines(8);
        var header = {};
        var infoStart;
        if (headerLines[2].startsWith('REMARKS')) {
            infoStart = parseInt(headerLines[1].substring(0, 8)) + 2;
        }
        else {
            infoStart = 5;
        }
        var dataStart = infoStart + 3;
        var gridInfo = parseNumberLine(headerLines[infoStart]);
        header.NA = gridInfo[0];
        header.AMIN = gridInfo[1];
        header.AMAX = gridInfo[2];
        header.NB = gridInfo[3];
        header.BMIN = gridInfo[4];
        header.BMAX = gridInfo[5];
        header.NC = gridInfo[6];
        header.CMIN = gridInfo[7];
        header.CMAX = gridInfo[8];
        var cellInfo = parseNumberLine(headerLines[infoStart + 1]);
        header.a = cellInfo[0] * this.voxelSize;
        header.b = cellInfo[1] * this.voxelSize;
        header.c = cellInfo[2] * this.voxelSize;
        header.alpha = cellInfo[3];
        header.beta = cellInfo[4];
        header.gamma = cellInfo[5];
        var na = header.AMAX - header.AMIN + 1;
        var nb = header.BMAX - header.BMIN + 1;
        var nc = header.CMAX - header.CMIN + 1;
        var n = na * nb * nc;
        var data = new Float32Array(n);
        var lineSection = Math.ceil(1 + (na * nb) / 6);
        var count = 0;
        var lineNo = 0;
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                var line = lines[i];
                if (lineNo >= dataStart && (lineNo - dataStart) % lineSection !== 0 && count < n) {
                    for (var j = 0, lj = 6; j < lj; ++j) {
                        var value = parseFloat(line.substr(12 * j, 12));
                        if (isNaN(value)) {
                            break;
                        } // Last line of map section
                        data[count++] = value;
                    }
                }
                else if (count === n) {
                    var lt = line.trim();
                    if (lt && lt !== '-9999') {
                        var ls = parseNumberLine(line);
                        header.RAVE = ls[0];
                        header.RSIGMA = ls[1];
                    }
                }
                ++lineNo;
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        v.header = header;
        v.setData(data, na, nb, nc);
        if (header.RAVE !== 0 && header.RSIGMA !== 1) {
            v.setStats(undefined, undefined, header.RAVE, header.RSIGMA);
        }
        if (Debug)
            { Log.timeEnd('XplorParser._parse ' + this.name); }
    };
    XplorParser.prototype.getMatrix = function getMatrix () {
        var h = this.volume.header;
        var basisX = [
            h.a,
            0,
            0
        ];
        var basisY = [
            h.b * Math.cos(Math.PI / 180.0 * h.gamma),
            h.b * Math.sin(Math.PI / 180.0 * h.gamma),
            0
        ];
        var basisZ = [
            h.c * Math.cos(Math.PI / 180.0 * h.beta),
            h.c * (Math.cos(Math.PI / 180.0 * h.alpha) -
                Math.cos(Math.PI / 180.0 * h.gamma) *
                    Math.cos(Math.PI / 180.0 * h.beta)) / Math.sin(Math.PI / 180.0 * h.gamma),
            0
        ];
        basisZ[2] = Math.sqrt(h.c * h.c * Math.sin(Math.PI / 180.0 * h.beta) *
            Math.sin(Math.PI / 180.0 * h.beta) - basisZ[1] * basisZ[1]);
        var basis = [[], basisX, basisY, basisZ];
        var nxyz = [0, h.NA, h.NB, h.NC];
        var mapcrs = [0, 1, 2, 3];
        var matrix = new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]();
        matrix.set(basis[mapcrs[1]][0] / nxyz[mapcrs[1]], basis[mapcrs[2]][0] / nxyz[mapcrs[2]], basis[mapcrs[3]][0] / nxyz[mapcrs[3]], 0, basis[mapcrs[1]][1] / nxyz[mapcrs[1]], basis[mapcrs[2]][1] / nxyz[mapcrs[2]], basis[mapcrs[3]][1] / nxyz[mapcrs[3]], 0, basis[mapcrs[1]][2] / nxyz[mapcrs[1]], basis[mapcrs[2]][2] / nxyz[mapcrs[2]], basis[mapcrs[3]][2] / nxyz[mapcrs[3]], 0, 0, 0, 0, 1);
        matrix.multiply(new __WEBPACK_IMPORTED_MODULE_0_three__["y" /* Matrix4 */]().makeTranslation(h.AMIN, h.BMIN, h.CMIN));
        return matrix;
    };

    Object.defineProperties( XplorParser.prototype, prototypeAccessors );

    return XplorParser;
}(VolumeParser));
ParserRegistry$1.add('xplor', XplorParser);
ParserRegistry$1.add('cns', XplorParser);

/**
 * @file Kin Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function hsvToRgb(h, s, v) {
    h /= 360;
    s /= 100;
    v /= 100;
    var r, g, b;
    var i = Math.floor(h * 6);
    var f = h * 6 - i;
    var p = v * (1 - s);
    var q = v * (1 - f * s);
    var t = v * (1 - (1 - f) * s);
    switch (i % 6) {
        case 0:
            r = v;
            g = t;
            b = p;
            break;
        case 1:
            r = q;
            g = v;
            b = p;
            break;
        case 2:
            r = p;
            g = v;
            b = t;
            break;
        case 3:
            r = p;
            g = q;
            b = v;
            break;
        case 4:
            r = t;
            g = p;
            b = v;
            break;
        case 5:
            r = v;
            g = p;
            b = q;
            break;
    }
    return [r, g, b];
}
var ColorDict = {
    red: hsvToRgb(0, 100, 100),
    orange: hsvToRgb(20, 100, 100),
    gold: hsvToRgb(40, 100, 100),
    yellow: hsvToRgb(60, 100, 100),
    lime: hsvToRgb(80, 100, 100),
    green: hsvToRgb(120, 80, 100),
    sea: hsvToRgb(150, 100, 100),
    cyan: hsvToRgb(180, 100, 85),
    sky: hsvToRgb(210, 75, 95),
    blue: hsvToRgb(240, 70, 100),
    purple: hsvToRgb(275, 75, 100),
    magenta: hsvToRgb(300, 95, 100),
    hotpink: hsvToRgb(335, 100, 100),
    pink: hsvToRgb(350, 55, 100),
    peach: hsvToRgb(25, 75, 100),
    lilac: hsvToRgb(275, 55, 100),
    pinktint: hsvToRgb(340, 30, 100),
    peachtint: hsvToRgb(25, 50, 100),
    yellowtint: hsvToRgb(60, 50, 100),
    greentint: hsvToRgb(135, 40, 100),
    bluetint: hsvToRgb(220, 40, 100),
    lilactint: hsvToRgb(275, 35, 100),
    white: hsvToRgb(0, 0, 100),
    gray: hsvToRgb(0, 0, 50),
    brown: hsvToRgb(20, 45, 75),
    deadwhite: [1, 1, 1],
    deadblack: [0, 0, 0],
    invisible: [0, 0, 0]
};
var reWhitespaceComma = /[\s,]+/;
var reCurlyWhitespace = /[^{}\s]*{[^{}]+}|[^{}\s]+/g;
var reTrimCurly = /^{+|}+$/g;
var reTrimQuotes$1 = /^['"]+|['"]+$/g;
var reCollapseEqual = /\s*=\s*/g;
function parseListDef(line) {
    var name;
    var defaultColor;
    var master = [];
    var width;
    line = line.replace(reCollapseEqual, '=');
    var lm = line.match(reCurlyWhitespace);
    for (var j = 1; j < lm.length; ++j) {
        var e = lm[j];
        if (e[0] === '{') {
            name = e.substring(1, e.length - 1);
        }
        else {
            var es = e.split('=');
            if (es.length === 2) {
                if (es[0] === 'color') {
                    defaultColor = ColorDict[es[1]];
                }
                else if (es[0] === 'width') {
                    width = parseInt(es[1]);
                }
                else if (es[0] === 'master') {
                    master.push(es[1].replace(reTrimCurly, ''));
                }
            }
        }
    }
    return {
        listName: name,
        listColor: defaultColor,
        listMasters: master,
        listWidth: width
    };
}
function parseListElm(line) {
    line = line.trim();
    var idx1 = line.indexOf('{');
    var idx2 = line.indexOf('}');
    var ls = line.substr(idx2 + 1).split(reWhitespaceComma);
    var label = line.substr(idx1 + 1, idx2 - 1);
    var position = [
        parseFloat(ls[ls.length - 3]),
        parseFloat(ls[ls.length - 2]),
        parseFloat(ls[ls.length - 1])
    ];
    var color, width, radius;
    var lineBreak = false;
    var triangleBreak = false;
    for (var lsindex = 4; lsindex <= ls.length; lsindex++) {
        var literal = ls[ls.length - lsindex];
        if (literal in ColorDict) {
            color = ColorDict[ls[ls.length - lsindex]];
        }
        if (literal.startsWith('width')) {
            width = parseInt(literal.substring(5));
        }
        if (literal.startsWith('r=')) {
            radius = parseFloat(literal.split('=')[1]);
        }
        if (literal.startsWith('P')) {
            lineBreak = true;
        }
        if (literal.startsWith('X')) {
            triangleBreak = true;
        }
    }
    // const color = line[ idx2 + 1 ] === ' ' ? undefined : ColorDict[ ls[ 0 ] ]
    return {
        label: label,
        position: position,
        color: color,
        radius: radius,
        width: width,
        isLineBreak: lineBreak,
        isTriangleBreak: triangleBreak
    };
}
function parseStr(line) {
    var start = line.indexOf('{');
    var end = line.indexOf('}');
    return line.substring(start !== -1 ? start + 1 : 0, end !== -1 ? end : undefined).trim();
}
function parseFlag(line) {
    var end = line.indexOf('}');
    return end === -1 ? undefined : line.substr(end + 1).trim();
}
function parseGroup(line) {
    var name = '';
    var master = [];
    var flags = {};
    line = line.replace(reCollapseEqual, '=');
    var lm = line.match(reCurlyWhitespace);
    for (var j = 1; j < lm.length; ++j) {
        var e = lm[j];
        if (e[0] === '{') {
            name = e.substring(1, e.length - 1);
        }
        else {
            var es = e.split('=');
            if (es.length === 2) {
                if (es[0] === 'master') {
                    master.push(es[1].replace(reTrimCurly, ''));
                }
                else {
                    flags[es[0]] = es[1].replace(reTrimCurly, '');
                }
            }
            else {
                flags[es[0]] = true;
            }
        }
    }
    return { groupName: name,
        groupFlags: flags,
        groupMasters: master
    };
}
function convertKinTriangleArrays(ribbonObject) {
    // have to convert ribbons/triangle lists from stripdrawmode to normal drawmode
    // index                    [ 0 1 2 3 4 5 6 7 8 91011 ]
    // label [ 0 1 2 3 4 5 ] to [ 0 1 2 1 2 3 2 3 4 3 4 5 ]
    // convertedindex                                      [ 0 1 2 3 4 5 6 7 8 91011121314151617181920212223242526 ]
    // index          [ 0 1 2 3 4 5 6 7 8 91011121314 ]    [ 0 1 2 3 4 5 6 7 8 3 4 5 6 7 8 91011 6 7 8 91011121314 ]
    // position/color [ 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 ] to [ 0 0 0 1 1 1 2 2 2 1 1 1 2 2 2 3 3 3 2 2 2 3 3 3 4 4 4 ]
    var labelArray = ribbonObject.labelArray;
    var positionArray = ribbonObject.positionArray;
    var colorArray = ribbonObject.colorArray;
    var breakArray = ribbonObject.breakArray;
    var convertedLabels = [];
    for (var i = 0; i < (labelArray.length - 2) * 3; ++i) {
        convertedLabels[i] = labelArray[i - Math.floor(i / 3) * 2];
    }
    var convertedBreaks = [];
    for (var i$1 = 0; i$1 < (breakArray.length - 2) * 3; ++i$1) {
        convertedBreaks[i$1] = breakArray[i$1 - Math.floor(i$1 / 3) * 2];
    }
    var convertedPositions = [];
    for (var i$2 = 0; i$2 < (positionArray.length / 3 - 2) * 9; ++i$2) {
        convertedPositions[i$2] = positionArray[i$2 - Math.floor(i$2 / 9) * 6];
    }
    var convertedColors = [];
    for (var i$3 = 0; i$3 < (colorArray.length / 3 - 2) * 9; ++i$3) {
        convertedColors[i$3] = colorArray[i$3 - Math.floor(i$3 / 9) * 6];
    }
    var vector3Positions = [];
    for (var i$4 = 0; i$4 < (convertedPositions.length) / 3; ++i$4) {
        vector3Positions.push(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](convertedPositions[i$4 * 3], convertedPositions[i$4 * 3] + 1, convertedPositions[i$4 * 3] + 2));
    }
    //let normals = []
    //for (let i = 0; i < vector3Positions.length - 1; ++i) {
    //  let normalVec3 = vector3Positions[i].cross(vector3Positions[i + 1])
    //  normals.push(normalVec3.x)
    //  normals.push(normalVec3.y)
    //  normals.push(normalVec3.z)
    //}
    return {
        name: ribbonObject.name,
        masterArray: ribbonObject.masterArray,
        labelArray: convertedLabels,
        positionArray: convertedPositions,
        breakArray: convertedBreaks,
        colorArray: convertedColors
    };
}
function removePointBreaksTriangleArrays(convertedRibbonObject) {
    // after converting ribbon/triangle arrys to drawmode, removed point break triangles
    // label [ 0 1 2 3 4 5 ] to [ 0 1 2 1 2 3 2 3 4 3 4 5 ]
    // position/color [ 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 ] to [ 0 0 0 1 1 1 2 2 2 1 1 1 2 2 2 3 3 3 2 2 2 3 3 3 4 4 4 ]
    var labelArray = convertedRibbonObject.labelArray;
    var positionArray = convertedRibbonObject.positionArray;
    var colorArray = convertedRibbonObject.colorArray;
    var breakArray = convertedRibbonObject.breakArray;
    var editedLabels = [];
    var editedPositions = [];
    var editedColors = [];
    var editedBreaks = [];
    for (var i = 0; i < breakArray.length / 3; i++) {
        var breakPointer = i * 3;
        var positionPointer = i * 9;
        if (!breakArray[breakPointer + 1] && !breakArray[breakPointer + 2]) {
            editedLabels.push(labelArray[breakPointer]);
            editedLabels.push(labelArray[breakPointer + 1]);
            editedLabels.push(labelArray[breakPointer + 2]);
            editedBreaks.push(breakArray[breakPointer]);
            editedBreaks.push(breakArray[breakPointer + 1]);
            editedBreaks.push(breakArray[breakPointer + 2]);
            editedPositions.push(positionArray[positionPointer]);
            editedPositions.push(positionArray[positionPointer + 1]);
            editedPositions.push(positionArray[positionPointer + 2]);
            editedPositions.push(positionArray[positionPointer + 3]);
            editedPositions.push(positionArray[positionPointer + 4]);
            editedPositions.push(positionArray[positionPointer + 5]);
            editedPositions.push(positionArray[positionPointer + 6]);
            editedPositions.push(positionArray[positionPointer + 7]);
            editedPositions.push(positionArray[positionPointer + 8]);
            editedColors.push(colorArray[positionPointer]);
            editedColors.push(colorArray[positionPointer + 1]);
            editedColors.push(colorArray[positionPointer + 2]);
            editedColors.push(colorArray[positionPointer + 3]);
            editedColors.push(colorArray[positionPointer + 4]);
            editedColors.push(colorArray[positionPointer + 5]);
            editedColors.push(colorArray[positionPointer + 6]);
            editedColors.push(colorArray[positionPointer + 7]);
            editedColors.push(colorArray[positionPointer + 8]);
        }
    }
    return {
        name: convertedRibbonObject.name,
        masterArray: convertedRibbonObject.masterArray,
        labelArray: editedLabels,
        positionArray: editedPositions,
        breakArray: editedBreaks,
        colorArray: editedColors
    };
}
var KinParser = /*@__PURE__*/(function (Parser$$1) {
    function KinParser () {
        Parser$$1.apply(this, arguments);
    }

    if ( Parser$$1 ) KinParser.__proto__ = Parser$$1;
    KinParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    KinParser.prototype.constructor = KinParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'kin'; };
    prototypeAccessors.__objName.get = function () { return 'kinemage'; };
    KinParser.prototype._parse = function _parse () {
        // http://kinemage.biochem.duke.edu/software/king.php
        if (Debug)
            { Log.time(("KinParser._parse " + (this.name))); }
        var kinemage = {
            kinemage: undefined,
            onewidth: undefined,
            '1viewid': undefined,
            pdbfile: undefined,
            texts: [],
            text: '',
            captions: [],
            caption: '',
            groupDict: {},
            subgroupDict: {},
            masterDict: {},
            pointmasterDict: {},
            dotLists: [],
            vectorLists: [],
            ballLists: [],
            ribbonLists: []
        };
        this.kinemage = kinemage;
        var currentGroupMasters;
        var currentSubgroupMasters;
        var isDotList = false;
        var prevDotLabel = '';
        var dotDefaultColor;
        var dotLabel, dotPosition, dotColor;
        var isVectorList = false;
        var prevVecLabel = '';
        var prevVecPosition = null;
        var prevVecColor = null;
        var vecDefaultColor, vecDefaultWidth;
        var vecLabel1, vecLabel2, vecPosition1, vecPosition2, vecColor1, vecColor2;
        var isBallList = false;
        var prevBallLabel = '';
        var ballRadius, ballDefaultColor;
        var ballLabel, ballPosition, ballColor;
        var isRibbonList = false;
        var prevRibbonPointLabel = '';
        var ribbonListDefaultColor;
        var ribbonPointLabelArray, ribbonPointPositionArray, ribbonPointBreakArray, ribbonPointColorArray;
        var isText = false;
        var isCaption = false;
        // @vectorlist {mc} color= white  master= {mainchain}
        // { n   thr A   1  B13.79 1crnFH} P 17.047, 14.099, 3.625 { n   thr A   1  B13.79 1crnFH} L 17.047, 14.099, 3.625
        // @dotlist {x} color=white master={vdw contact} master={dots}
        // { CB  THR   1  A}sky  'P' 18.915,14.199,5.024
        function _parseChunkOfLines(_i, _n, lines) {
            for (var i = _i; i < _n; ++i) {
                var line = lines[i];
                if (line[0] === '@') {
                    isDotList = false;
                    isVectorList = false;
                    isBallList = false;
                    isRibbonList = false;
                    isText = false;
                    isCaption = false;
                }
                if (!line) {
                    isDotList = false;
                    isVectorList = false;
                    isBallList = false;
                    isRibbonList = false;
                }
                else if (line.startsWith('@dotlist')) {
                    // @dotlist {x} color=white master={vdw contact} master={dots}
                    var ref = parseListDef(line);
                    var listColor = ref.listColor;
                    var listName = ref.listName;
                    var listMasters = ref.listMasters;
                    isDotList = true;
                    prevDotLabel = '';
                    dotLabel = [];
                    dotPosition = [];
                    dotColor = [];
                    dotDefaultColor = listColor;
                    if (currentGroupMasters) {
                        listMasters = listMasters.concat(currentGroupMasters);
                    }
                    if (currentSubgroupMasters) {
                        listMasters = listMasters.concat(currentSubgroupMasters);
                    }
                    kinemage.dotLists.push({
                        name: listName,
                        masterArray: listMasters,
                        labelArray: dotLabel,
                        positionArray: dotPosition,
                        colorArray: dotColor
                    });
                }
                else if (line.startsWith('@vectorlist')) {
                    // @vectorlist {x} color=white master={small overlap} master={dots}
                    var ref$1 = parseListDef(line);
                    var listMasters$1 = ref$1.listMasters;
                    var listName$1 = ref$1.listName;
                    var listWidth = ref$1.listWidth;
                    var listColor$1 = ref$1.listColor;
                    if (listMasters$1) {
                        listMasters$1.forEach(function (name) {
                            if (!kinemage.masterDict[name]) {
                                kinemage.masterDict[name] = {
                                    indent: false,
                                    visible: false
                                };
                            }
                        });
                    }
                    isVectorList = true;
                    prevVecLabel = '';
                    prevVecPosition = null;
                    prevVecColor = null;
                    vecLabel1 = [];
                    vecLabel2 = [];
                    vecPosition1 = [];
                    vecPosition2 = [];
                    vecColor1 = [];
                    vecColor2 = [];
                    vecDefaultColor = listColor$1;
                    vecDefaultWidth = [];
                    if (listWidth) {
                        vecDefaultWidth.push(listWidth);
                    }
                    if (currentGroupMasters) {
                        listMasters$1 = listMasters$1.concat(currentGroupMasters);
                    }
                    if (currentSubgroupMasters) {
                        listMasters$1 = listMasters$1.concat(currentSubgroupMasters);
                    }
                    kinemage.vectorLists.push({
                        name: listName$1,
                        masterArray: listMasters$1,
                        label1Array: vecLabel1,
                        label2Array: vecLabel2,
                        position1Array: vecPosition1,
                        position2Array: vecPosition2,
                        color1Array: vecColor1,
                        color2Array: vecColor2,
                        width: vecDefaultWidth
                    });
                }
                else if (line.startsWith('@balllist')) {
                    var ref$2 = parseListDef(line);
                    var listName$2 = ref$2.listName;
                    var listColor$2 = ref$2.listColor;
                    var listMasters$2 = ref$2.listMasters;
                    if (listMasters$2) {
                        listMasters$2.forEach(function (name) {
                            if (!kinemage.masterDict[name]) {
                                kinemage.masterDict[name] = {
                                    indent: false,
                                    visible: false
                                };
                            }
                        });
                    }
                    isBallList = true;
                    prevBallLabel = '';
                    ballLabel = [];
                    ballRadius = [];
                    ballPosition = [];
                    ballColor = [];
                    ballDefaultColor = listColor$2;
                    if (currentGroupMasters) {
                        listMasters$2 = listMasters$2.concat(currentGroupMasters);
                    }
                    if (currentSubgroupMasters) {
                        listMasters$2 = listMasters$2.concat(currentSubgroupMasters);
                    }
                    kinemage.ballLists.push({
                        name: listName$2,
                        masterArray: listMasters$2,
                        labelArray: ballLabel,
                        radiusArray: ballRadius,
                        positionArray: ballPosition,
                        colorArray: ballColor
                    });
                }
                else if (line.startsWith('@ribbonlist') || line.startsWith('@trianglelist')) {
                    var ref$3 = parseListDef(line);
                    var listMasters$3 = ref$3.listMasters;
                    var listName$3 = ref$3.listName;
                    var listColor$3 = ref$3.listColor;
                    if (listMasters$3) {
                        listMasters$3.forEach(function (name) {
                            if (!kinemage.masterDict[name]) {
                                kinemage.masterDict[name] = {
                                    indent: false,
                                    visible: false
                                };
                            }
                        });
                    }
                    isRibbonList = true;
                    prevRibbonPointLabel = '';
                    ribbonPointLabelArray = [];
                    ribbonPointPositionArray = [];
                    ribbonPointBreakArray = [];
                    ribbonPointColorArray = [];
                    ribbonListDefaultColor = listColor$3;
                    if (currentGroupMasters) {
                        listMasters$3 = listMasters$3.concat(currentGroupMasters);
                    }
                    if (currentSubgroupMasters) {
                        listMasters$3 = listMasters$3.concat(currentSubgroupMasters);
                    }
                    kinemage.ribbonLists.push({
                        name: listName$3,
                        masterArray: listMasters$3,
                        labelArray: ribbonPointLabelArray,
                        positionArray: ribbonPointPositionArray,
                        breakArray: ribbonPointBreakArray,
                        colorArray: ribbonPointColorArray
                    });
                }
                else if (line.startsWith('@text')) {
                    isText = true;
                    kinemage.texts.push(line.substr(5));
                }
                else if (line.startsWith('@caption')) {
                    isCaption = true;
                    kinemage.captions.push(line.substr(8));
                }
                else if (isDotList) {
                    // { CB  THR   1  A}sky  'P' 18.915,14.199,5.024
                    var ref$4 = parseListElm(line);
                    var label = ref$4.label;
                    var color = ref$4.color;
                    var position = ref$4.position;
                    if (label === '"') {
                        label = prevDotLabel;
                    }
                    else {
                        prevDotLabel = label;
                    }
                    if (color === undefined) {
                        color = dotDefaultColor;
                    }
                    dotLabel.push(label);
                    dotPosition.push.apply(dotPosition, position);
                    dotColor.push.apply(dotColor, color);
                }
                else if (isVectorList) {
                    // { n   thr A   1  B13.79 1crnFH} P 17.047, 14.099, 3.625 { n   thr A   1  B13.79 1crnFH} L 17.047, 14.099, 3.625
                    var doubleLine = line.replace(/(?!^){/g, '\n{');
                    var splitLine = doubleLine.split(/\n/);
                    for (var i2 = 0; i2 < splitLine.length; i2++) {
                        var singlePointLine = splitLine[i2];
                        var ref$5 = parseListElm(singlePointLine);
                        var label$1 = ref$5.label;
                        var color$1 = ref$5.color;
                        var width = ref$5.width;
                        var position$1 = ref$5.position;
                        var isLineBreak = ref$5.isLineBreak;
                        if (label$1 === '"') {
                            label$1 = prevVecLabel;
                        }
                        else {
                            prevVecLabel = label$1;
                        }
                        if (color$1 === undefined) {
                            color$1 = vecDefaultColor;
                        }
                        if (!isLineBreak) {
                            if (prevVecPosition !== null) {
                                if (width) {
                                    vecDefaultWidth.push(width);
                                }
                                vecLabel1.push(prevVecLabel);
                                vecPosition1.push.apply(vecPosition1, prevVecPosition);
                                vecColor1.push.apply(vecColor1, prevVecColor);
                                vecLabel2.push(label$1);
                                vecPosition2.push.apply(vecPosition2, position$1);
                                vecColor2.push.apply(vecColor2, color$1);
                            }
                        }
                        prevVecLabel = label$1;
                        prevVecPosition = position$1;
                        prevVecColor = color$1;
                    }
                }
                else if (isBallList) {
                    // {cb arg A   1   1.431 -106.80} r=1.431  39.085, 8.083, 22.182
                    var ref$6 = parseListElm(line);
                    var label$2 = ref$6.label;
                    var radius = ref$6.radius;
                    var color$2 = ref$6.color;
                    var position$2 = ref$6.position;
                    if (label$2 === '"') {
                        label$2 = prevBallLabel;
                    }
                    else {
                        prevBallLabel = label$2;
                    }
                    if (radius === undefined) {
                        radius = 1; // temporary default radius
                    }
                    if (color$2 === undefined) {
                        color$2 = ballDefaultColor;
                    }
                    ballLabel.push(label$2);
                    ballRadius.push(radius);
                    ballPosition.push.apply(ballPosition, position$2);
                    ballColor.push.apply(ballColor, color$2);
                }
                else if (isRibbonList) {
                    var ref$7 = parseListElm(line);
                    var label$3 = ref$7.label;
                    var color$3 = ref$7.color;
                    var position$3 = ref$7.position;
                    var isTriangleBreak = ref$7.isTriangleBreak;
                    if (label$3 === '"') {
                        label$3 = prevRibbonPointLabel;
                    }
                    else {
                        prevRibbonPointLabel = label$3;
                    }
                    if (color$3 === undefined) {
                        color$3 = ribbonListDefaultColor;
                    }
                    ribbonPointLabelArray.push(label$3);
                    ribbonPointPositionArray.push.apply(ribbonPointPositionArray, position$3);
                    ribbonPointBreakArray.push(isTriangleBreak);
                    ribbonPointColorArray.push.apply(ribbonPointColorArray, color$3);
                }
                else if (isText) {
                    kinemage.texts.push(line);
                }
                else if (isCaption) {
                    kinemage.captions.push(line);
                }
                else if (line.startsWith('@kinemage')) {
                    kinemage.kinemage = parseInt(line.substr(9).trim());
                }
                else if (line.startsWith('@onewidth')) {
                    kinemage.onewidth = true;
                }
                else if (line.startsWith('@1viewid')) {
                    kinemage['1viewid'] = parseStr(line);
                }
                else if (line.startsWith('@pdbfile')) {
                    kinemage.pdbfile = parseStr(line);
                }
                else if (line.startsWith('@group')) {
                    var ref$8 = parseGroup(line);
                    var groupName = ref$8.groupName;
                    var groupFlags = ref$8.groupFlags;
                    var groupMasters = ref$8.groupMasters;
                    if (!kinemage.groupDict[groupName]) {
                        kinemage.groupDict[groupName] = {
                            dominant: false,
                            animate: false
                        };
                        currentGroupMasters = groupMasters;
                    }
                    if (currentGroupMasters) {
                        currentGroupMasters.forEach(function (master) {
                            if (!kinemage.masterDict[master]) {
                                kinemage.masterDict[master] = {
                                    indent: false,
                                    visible: false
                                };
                            }
                        });
                    }
                    for (var key in groupFlags) {
                        kinemage.groupDict[groupName][key] = groupFlags[key];
                    }
                }
                else if (line.startsWith('@subgroup')) {
                    var ref$9 = parseGroup(line);
                    var groupName$1 = ref$9.groupName;
                    var groupFlags$1 = ref$9.groupFlags;
                    var groupMasters$1 = ref$9.groupMasters;
                    if (!kinemage.subgroupDict[groupName$1]) {
                        kinemage.subgroupDict[groupName$1] = {
                            dominant: false,
                            animate: false
                        };
                        currentSubgroupMasters = groupMasters$1;
                    }
                    if (currentSubgroupMasters) {
                        currentSubgroupMasters.forEach(function (master) {
                            if (!kinemage.masterDict[master]) {
                                kinemage.masterDict[master] = {
                                    indent: false,
                                    visible: false
                                };
                            }
                        });
                    }
                    for (var key$1 in groupFlags$1) {
                        kinemage.subgroupDict[groupName$1][key$1] = groupFlags$1[key$1];
                    }
                }
                else if (line.startsWith('@master')) {
                    var name = parseStr(line);
                    var flag = parseFlag(line);
                    if (!kinemage.masterDict[name]) {
                        kinemage.masterDict[name] = {
                            indent: false,
                            visible: false
                        };
                    }
                    if (flag === 'on') {
                        kinemage.masterDict[name].visible = true;
                    }
                    else if (flag === 'off') {
                        kinemage.masterDict[name].visible = false;
                    }
                    else if (flag === 'indent') {
                        kinemage.masterDict[name].indent = true;
                    }
                }
                else if (line.startsWith('@pointmaster')) {
                    var ref$10 = parseGroup(line);
                    var groupName$2 = ref$10.groupName;
                    var groupFlags$2 = ref$10.groupFlags;
                    kinemage.pointmasterDict[groupName$2] = {
                        id: Object.keys(groupFlags$2)[0].replace(reTrimQuotes$1, '')
                    };
                }
                else {
                    console.log(line);
                }
            }
        }
        this.streamer.eachChunkOfLines(function (lines /*, chunkNo, chunkCount */) {
            _parseChunkOfLines(0, lines.length, lines);
        });
        kinemage.text = kinemage.texts.join('\n').trim();
        kinemage.caption = kinemage.captions.join('\n').trim();
        if (kinemage.ribbonLists) {
            var convertedLists = [];
            kinemage.ribbonLists.forEach(function (listObject) {
                convertedLists.push(removePointBreaksTriangleArrays(convertKinTriangleArrays(listObject)));
            });
            kinemage.ribbonLists = convertedLists;
        }
        if (Debug)
            { Log.timeEnd(("KinParser._parse " + (this.name))); }
    };

    Object.defineProperties( KinParser.prototype, prototypeAccessors );

    return KinParser;
}(Parser));
ParserRegistry$1.add('kin', KinParser);

/**
 * @file Surface Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var SurfaceParser = /*@__PURE__*/(function (Parser$$1) {
    function SurfaceParser(streamer, params) {
        Parser$$1.call(this, streamer, params);
        this.loader = this.getLoader();
        this.surface = new Surface(this.name, this.path);
    }

    if ( Parser$$1 ) SurfaceParser.__proto__ = Parser$$1;
    SurfaceParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    SurfaceParser.prototype.constructor = SurfaceParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'surface'; };
    prototypeAccessors.__objName.get = function () { return 'surface'; };
    SurfaceParser.prototype._parse = function _parse () {
        var geometry = this.loader.parse(this.streamer.asText());
        this.surface.fromGeometry(geometry);
    };

    Object.defineProperties( SurfaceParser.prototype, prototypeAccessors );

    return SurfaceParser;
}(Parser));

/**
 * @file Obj Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * OBJLoader
 * @class
 * @private
 * @author mrdoob / http://mrdoob.com/
 */
var OBJLoader = (function OBJLoader() {
    this.regexp = {
        // v float float float
        vertex_pattern: /^v\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)/,
        // vn float float float
        normal_pattern: /^vn\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)/,
        // vt float float
        uv_pattern: /^vt\s+([\d.+\-eE]+)\s+([\d.+\-eE]+)/,
        // f vertex vertex vertex
        face_vertex: /^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,
        // f vertex/uv vertex/uv vertex/uv
        face_vertex_uv: /^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,
        // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
        face_vertex_uv_normal: /^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,
        // f vertex//normal vertex//normal vertex//normal
        face_vertex_normal: /^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,
        // o object_name | g group_name
        object_pattern: /^[og]\s*(.+)?/,
        // s boolean
        smoothing_pattern: /^s\s+(\d+|on|off)/,
        // mtllib file_reference
        material_library_pattern: /^mtllib /,
        // usemtl material_name
        material_use_pattern: /^usemtl /
    };
});
OBJLoader.prototype = {
    constructor: OBJLoader,
    setPath: function (value) {
        this.path = value;
    },
    _createParserState: function () {
        var state = {
            objects: [],
            object: {},
            vertices: [],
            normals: [],
            startObject: function (name, fromDeclaration) {
                // If the current object (initial from reset) is not from a g/o declaration in the parsed
                // file. We need to use it for the first parsed g/o to keep things in sync.
                if (this.object && this.object.fromDeclaration === false) {
                    this.object.name = name;
                    this.object.fromDeclaration = (fromDeclaration !== false);
                    return;
                }
                this.object = {
                    name: name || '',
                    geometry: {
                        vertices: [],
                        normals: []
                    },
                    fromDeclaration: (fromDeclaration !== false)
                };
                this.objects.push(this.object);
            },
            parseVertexIndex: function (value, len) {
                var index = parseInt(value, 10);
                return (index >= 0 ? index - 1 : index + len / 3) * 3;
            },
            parseNormalIndex: function (value, len) {
                var index = parseInt(value, 10);
                return (index >= 0 ? index - 1 : index + len / 3) * 3;
            },
            addVertex: function (a, b, c) {
                var src = this.vertices;
                var dst = this.object.geometry.vertices;
                dst.push(src[a + 0]);
                dst.push(src[a + 1]);
                dst.push(src[a + 2]);
                dst.push(src[b + 0]);
                dst.push(src[b + 1]);
                dst.push(src[b + 2]);
                dst.push(src[c + 0]);
                dst.push(src[c + 1]);
                dst.push(src[c + 2]);
            },
            addVertexLine: function (a) {
                var src = this.vertices;
                var dst = this.object.geometry.vertices;
                dst.push(src[a + 0]);
                dst.push(src[a + 1]);
                dst.push(src[a + 2]);
            },
            addNormal: function (a, b, c) {
                var src = this.normals;
                var dst = this.object.geometry.normals;
                dst.push(src[a + 0]);
                dst.push(src[a + 1]);
                dst.push(src[a + 2]);
                dst.push(src[b + 0]);
                dst.push(src[b + 1]);
                dst.push(src[b + 2]);
                dst.push(src[c + 0]);
                dst.push(src[c + 1]);
                dst.push(src[c + 2]);
            },
            addFace: function (a, b, c, d, na, nb, nc, nd) {
                var vLen = this.vertices.length;
                var ia = this.parseVertexIndex(a, vLen);
                var ib = this.parseVertexIndex(b, vLen);
                var ic = this.parseVertexIndex(c, vLen);
                var id;
                if (d === undefined) {
                    this.addVertex(ia, ib, ic);
                }
                else {
                    id = this.parseVertexIndex(d, vLen);
                    this.addVertex(ia, ib, id);
                    this.addVertex(ib, ic, id);
                }
                if (na !== undefined) {
                    // Normals are many times the same. If so, skip function call and parseInt.
                    var nLen = this.normals.length;
                    ia = this.parseNormalIndex(na, nLen);
                    ib = na === nb ? ia : this.parseNormalIndex(nb, nLen);
                    ic = na === nc ? ia : this.parseNormalIndex(nc, nLen);
                    if (d === undefined) {
                        this.addNormal(ia, ib, ic);
                    }
                    else {
                        id = this.parseNormalIndex(nd, nLen);
                        this.addNormal(ia, ib, id);
                        this.addNormal(ib, ic, id);
                    }
                }
            },
            addLineGeometry: function (vertices) {
                this.object.geometry.type = 'Line';
                var vLen = this.vertices.length;
                for (var vi = 0, l = vertices.length; vi < l; vi++) {
                    this.addVertexLine(this.parseVertexIndex(vertices[vi], vLen));
                }
            }
        };
        state.startObject('', false);
        return state;
    },
    parse: function (text) {
        var state = this._createParserState();
        if (text.indexOf('\r\n') !== -1) {
            // This is faster than String.split with regex that splits on both
            text = text.replace(/\r\n/g, '\n');
        }
        if (text.indexOf('\\\n') !== -1) {
            // join lines separated by a line continuation character (\)
            text = text.replace(/\\\n/g, '');
        }
        var i, l;
        var lines = text.split('\n');
        var line = '';
        var lineFirstChar = '';
        var lineSecondChar = '';
        var lineLength = 0;
        var result = [];
        // Faster to just trim left side of the line. Use if available.
        var trimLeft = (typeof ''.trimLeft === 'function');
        for (i = 0, l = lines.length; i < l; i++) {
            line = lines[i];
            line = trimLeft ? line.trimLeft() : line.trim();
            lineLength = line.length;
            if (lineLength === 0)
                { continue; }
            lineFirstChar = line.charAt(0);
            // @todo invoke passed in handler if any
            if (lineFirstChar === '#')
                { continue; }
            if (lineFirstChar === 'v') {
                lineSecondChar = line.charAt(1);
                if (lineSecondChar === ' ' && (result = this.regexp.vertex_pattern.exec(line)) !== null) {
                    // 0                  1      2      3
                    // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
                    state.vertices.push(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
                }
                else if (lineSecondChar === 'n' && (result = this.regexp.normal_pattern.exec(line)) !== null) {
                    // 0                   1      2      3
                    // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
                    state.normals.push(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
                }
                else if (lineSecondChar === 't' && this.regexp.uv_pattern.exec(line) !== null) ;
                else {
                    throw new Error("Unexpected vertex/normal/uv line: '" + line + "'");
                }
            }
            else if (lineFirstChar === 'f') {
                if ((result = this.regexp.face_vertex_uv_normal.exec(line)) !== null) {
                    // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
                    // 0                        1    2    3    4    5    6    7    8    9   10         11         12
                    // ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]
                    state.addFace(result[1], result[4], result[7], result[10], 
                    // result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ],  // ignore uv part
                    result[3], result[6], result[9], result[12]);
                }
                else if (this.regexp.face_vertex_uv.exec(line) !== null) ;
                else if ((result = this.regexp.face_vertex_normal.exec(line)) !== null) {
                    // f vertex//normal vertex//normal vertex//normal
                    // 0                     1    2    3    4    5    6   7          8
                    // ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]
                    state.addFace(result[1], result[3], result[5], result[7], result[2], result[4], result[6], result[8]);
                }
                else if ((result = this.regexp.face_vertex.exec(line)) !== null) {
                    // f vertex vertex vertex
                    // 0            1    2    3   4
                    // ["f 1 2 3", "1", "2", "3", undefined]
                    state.addFace(result[1], result[2], result[3], result[4]);
                }
                else {
                    throw new Error("Unexpected face line: '" + line + "'");
                }
            }
            else if (lineFirstChar === 'l') {
                var lineParts = line.substring(1).trim().split(' ');
                var lineVertices = [];
                var lineUVs = [];
                if (line.indexOf('/') === -1) {
                    lineVertices = lineParts;
                }
                else {
                    for (var li = 0, llen = lineParts.length; li < llen; li++) {
                        var parts = lineParts[li].split('/');
                        if (parts[0] !== '')
                            { lineVertices.push(parts[0]); }
                        if (parts[1] !== '')
                            { lineUVs.push(parts[1]); }
                    }
                }
                state.addLineGeometry(lineVertices, lineUVs);
            }
            else if ((result = this.regexp.object_pattern.exec(line)) !== null) {
                // o object_name
                // or
                // g group_name
                var name = result[0].substr(1).trim();
                state.startObject(name);
                // ignore material related lines
                // eslint-disable-next-line no-empty
            }
            else if (this.regexp.material_use_pattern.test(line)) ;
            else if (this.regexp.material_library_pattern.test(line)) ;
            else if (this.regexp.smoothing_pattern.exec(line) !== null) ;
            else {
                // Handle null terminated files without exception
                if (line === '\0')
                    { continue; }
                throw new Error("Unexpected line: '" + line + "'");
            }
        }
        var container = [];
        for (i = 0, l = state.objects.length; i < l; i++) {
            var object = state.objects[i];
            var geometry = object.geometry;
            // Skip o/g line declarations that did not follow with any faces
            if (geometry.vertices.length === 0)
                { continue; }
            var buffergeometry = new __WEBPACK_IMPORTED_MODULE_0_three__["g" /* BufferGeometry */]();
            buffergeometry.setAttribute('position', new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](new Float32Array(geometry.vertices), 3));
            if (geometry.normals.length > 0) {
                buffergeometry.setAttribute('normal', new __WEBPACK_IMPORTED_MODULE_0_three__["f" /* BufferAttribute */](new Float32Array(geometry.normals), 3));
            }
            else {
                buffergeometry.computeVertexNormals();
            }
            container.push(buffergeometry);
        }
        return container;
    }
};
var ObjParser = /*@__PURE__*/(function (SurfaceParser$$1) {
    function ObjParser () {
        SurfaceParser$$1.apply(this, arguments);
    }

    if ( SurfaceParser$$1 ) ObjParser.__proto__ = SurfaceParser$$1;
    ObjParser.prototype = Object.create( SurfaceParser$$1 && SurfaceParser$$1.prototype );
    ObjParser.prototype.constructor = ObjParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'obj'; };
    ObjParser.prototype.getLoader = function getLoader () {
        return new OBJLoader();
    };

    Object.defineProperties( ObjParser.prototype, prototypeAccessors );

    return ObjParser;
}(SurfaceParser));
ParserRegistry$1.add('obj', ObjParser);

/**
 * @file Ply Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var PLYLoader = (function PLYLoader() {
    this.propertyNameMapping = {};
});
PLYLoader.prototype = {
    constructor: PLYLoader,
    setPropertyNameMapping: function (mapping) {
        this.propertyNameMapping = mapping;
    },
    bin2str: function (buf) {
        var arrayBuffer = new Uint8Array(buf);
        var str = '';
        for (var i = 0; i < buf.byteLength; i++) {
            str += String.fromCharCode(arrayBuffer[i]); // implicitly assumes little-endian
        }
        return str;
    },
    isASCII: function (data) {
        var header = this.parseHeader(this.bin2str(data));
        return header.format === 'ascii';
    },
    parse: function (data) {
        if (data instanceof ArrayBuffer) {
            return (this.isASCII(data)
                ? this.parseASCII(this.bin2str(data))
                : this.parseBinary(data));
        }
        else {
            return this.parseASCII(data);
        }
    },
    parseHeader: function (data) {
        var patternHeader = /ply([\s\S]*)end_header\s/;
        var headerText = '';
        var headerLength = 0;
        var result = patternHeader.exec(data);
        if (result !== null) {
            headerText = result[1];
            headerLength = result[0].length;
        }
        var header = {
            comments: [],
            elements: [],
            headerLength: headerLength
        };
        var lines = headerText.split('\n');
        var currentElement, lineType, lineValues;
        function makePlyElementProperty(propertValues, propertyNameMapping) {
            var property = {
                type: propertValues[0]
            };
            if (property.type === 'list') {
                property.name = propertValues[3];
                property.countType = propertValues[1];
                property.itemType = propertValues[2];
            }
            else {
                property.name = propertValues[1];
            }
            if (property.name in propertyNameMapping) {
                property.name = propertyNameMapping[property.name];
            }
            return property;
        }
        for (var i = 0; i < lines.length; i++) {
            var line = lines[i];
            line = line.trim();
            if (line === '') {
                continue;
            }
            lineValues = line.split(/\s+/);
            lineType = lineValues.shift();
            line = lineValues.join(' ');
            switch (lineType) {
                case 'format':
                    header.format = lineValues[0];
                    header.version = lineValues[1];
                    break;
                case 'comment':
                    header.comments.push(line);
                    break;
                case 'element':
                    if (currentElement !== undefined) {
                        header.elements.push(currentElement);
                    }
                    currentElement = {};
                    currentElement.name = lineValues[0];
                    currentElement.count = parseInt(lineValues[1]);
                    currentElement.properties = [];
                    break;
                case 'property':
                    currentElement.properties.push(makePlyElementProperty(lineValues, this.propertyNameMapping));
                    break;
                default:
                    console.log('unhandled', lineType, lineValues);
            }
        }
        if (currentElement !== undefined) {
            header.elements.push(currentElement);
        }
        return header;
    },
    parseASCIINumber: function (n, type) {
        switch (type) {
            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(n);
            case 'float':
            case 'double':
            case 'float32':
            case 'float64':
                return parseFloat(n);
        }
    },
    parseASCIIElement: function (properties, line) {
        var values = line.split(/\s+/);
        var element = {};
        for (var i = 0; i < properties.length; i++) {
            if (properties[i].type === 'list') {
                var list = [];
                var n = this.parseASCIINumber(values.shift(), properties[i].countType);
                for (var j = 0; j < n; j++) {
                    list.push(this.parseASCIINumber(values.shift(), properties[i].itemType));
                }
                element[properties[i].name] = list;
            }
            else {
                element[properties[i].name] = this.parseASCIINumber(values.shift(), properties[i].type);
            }
        }
        return element;
    },
    parseASCII: function (data) {
        // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
        var geometry = new __WEBPACK_IMPORTED_MODULE_0_three__["s" /* Geometry */]();
        var result;
        var header = this.parseHeader(data);
        var patternBody = /end_header\s([\s\S]*)$/;
        var body = '';
        if ((result = patternBody.exec(data)) !== null) {
            body = result[1];
        }
        var lines = body.split('\n');
        var currentElement = 0;
        var currentElementCount = 0;
        geometry.useColor = false;
        for (var i = 0; i < lines.length; i++) {
            var line = lines[i];
            line = line.trim();
            if (line === '') {
                continue;
            }
            if (currentElementCount >= header.elements[currentElement].count) {
                currentElement++;
                currentElementCount = 0;
            }
            var element = this.parseASCIIElement(header.elements[currentElement].properties, line);
            this.handleElement(geometry, header.elements[currentElement].name, element);
            currentElementCount++;
        }
        return this.postProcess(geometry);
    },
    postProcess: function (geometry) {
        if (geometry.useColor) {
            for (var i = 0; i < geometry.faces.length; i++) {
                geometry.faces[i].vertexColors = [
                    geometry.colors[geometry.faces[i].a],
                    geometry.colors[geometry.faces[i].b],
                    geometry.colors[geometry.faces[i].c]
                ];
            }
            geometry.elementsNeedUpdate = true;
        }
        geometry.computeBoundingSphere();
        return geometry;
    },
    handleElement: function (geometry, elementName, element) {
        if (elementName === 'vertex') {
            geometry.vertices.push(new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */](element.x, element.y, element.z));
            if ('red' in element && 'green' in element && 'blue' in element) {
                geometry.useColor = true;
                var color = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */]();
                color.setRGB(element.red / 255.0, element.green / 255.0, element.blue / 255.0);
                geometry.colors.push(color);
            }
        }
        else if (elementName === 'face') {
            var vertexIndices = element.vertex_indices;
            if (vertexIndices.length === 3) {
                geometry.faces.push(new __WEBPACK_IMPORTED_MODULE_0_three__["o" /* Face3 */](vertexIndices[0], vertexIndices[1], vertexIndices[2]));
            }
            else if (vertexIndices.length === 4) {
                geometry.faces.push(new __WEBPACK_IMPORTED_MODULE_0_three__["o" /* Face3 */](vertexIndices[0], vertexIndices[1], vertexIndices[3]), new __WEBPACK_IMPORTED_MODULE_0_three__["o" /* Face3 */](vertexIndices[1], vertexIndices[2], vertexIndices[3]));
            }
        }
    },
    binaryRead: function (dataview, at, type, littleEndian) {
        switch (type) {
            // corespondences for non-specific length types here match rply:
            case 'int8':
            case 'char': return [dataview.getInt8(at), 1];
            case 'uint8':
            case 'uchar': return [dataview.getUint8(at), 1];
            case 'int16':
            case 'short': return [dataview.getInt16(at, littleEndian), 2];
            case 'uint16':
            case 'ushort': return [dataview.getUint16(at, littleEndian), 2];
            case 'int32':
            case 'int': return [dataview.getInt32(at, littleEndian), 4];
            case 'uint32':
            case 'uint': return [dataview.getUint32(at, littleEndian), 4];
            case 'float32':
            case 'float': return [dataview.getFloat32(at, littleEndian), 4];
            case 'float64':
            case 'double': return [dataview.getFloat64(at, littleEndian), 8];
        }
    },
    binaryReadElement: function (dataview, at, properties, littleEndian) {
        var element = {};
        var result;
        var read = 0;
        for (var i = 0; i < properties.length; i++) {
            if (properties[i].type === 'list') {
                var list = [];
                result = this.binaryRead(dataview, at + read, properties[i].countType, littleEndian);
                var n = result[0];
                read += result[1];
                for (var j = 0; j < n; j++) {
                    result = this.binaryRead(dataview, at + read, properties[i].itemType, littleEndian);
                    list.push(result[0]);
                    read += result[1];
                }
                element[properties[i].name] = list;
            }
            else {
                result = this.binaryRead(dataview, at + read, properties[i].type, littleEndian);
                element[properties[i].name] = result[0];
                read += result[1];
            }
        }
        return [element, read];
    },
    parseBinary: function (data) {
        var geometry = new __WEBPACK_IMPORTED_MODULE_0_three__["s" /* Geometry */]();
        var header = this.parseHeader(this.bin2str(data));
        var littleEndian = (header.format === 'binary_little_endian');
        var body = new DataView(data, header.headerLength);
        var result;
        var loc = 0;
        for (var currentElement = 0; currentElement < header.elements.length; currentElement++) {
            for (var currentElementCount = 0; currentElementCount < header.elements[currentElement].count; currentElementCount++) {
                result = this.binaryReadElement(body, loc, header.elements[currentElement].properties, littleEndian);
                loc += result[1];
                var element = result[0];
                this.handleElement(geometry, header.elements[currentElement].name, element);
            }
        }
        return this.postProcess(geometry);
    }
};
var PlyParser = /*@__PURE__*/(function (SurfaceParser$$1) {
    function PlyParser () {
        SurfaceParser$$1.apply(this, arguments);
    }

    if ( SurfaceParser$$1 ) PlyParser.__proto__ = SurfaceParser$$1;
    PlyParser.prototype = Object.create( SurfaceParser$$1 && SurfaceParser$$1.prototype );
    PlyParser.prototype.constructor = PlyParser;

    var prototypeAccessors = { type: { configurable: true } };

    prototypeAccessors.type.get = function () { return 'ply'; };
    PlyParser.prototype.getLoader = function getLoader () {
        return new PLYLoader();
    };

    Object.defineProperties( PlyParser.prototype, prototypeAccessors );

    return PlyParser;
}(SurfaceParser));
ParserRegistry$1.add('ply', PlyParser);

/**
 * @file Csv Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * CSV parser
 */
var CsvParser = /*@__PURE__*/(function (Parser$$1) {
    function CsvParser(streamer, params) {
        var p = params || {};
        Parser$$1.call(this, streamer, p);
        this.delimiter = defaults(p.delimiter, ',');
        this.comment = defaults(p.comment, '#');
        this.columnNames = defaults(p.columnNames, false);
        this.table = {
            name: this.name,
            path: this.path,
            columnNames: [],
            data: []
        };
    }

    if ( Parser$$1 ) CsvParser.__proto__ = Parser$$1;
    CsvParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    CsvParser.prototype.constructor = CsvParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'csv'; };
    prototypeAccessors.__objName.get = function () { return 'table'; };
    CsvParser.prototype._parse = function _parse () {
        var this$1 = this;

        var data = this.table.data;
        var reDelimiter = new RegExp('\\s*' + this.delimiter + '\\s*');
        var j = 0;
        this.streamer.eachChunkOfLines(function (chunk) {
            var n = chunk.length;
            for (var i = 0; i < n; ++i) {
                var line = chunk[i].trim();
                if (line.startsWith(this$1.comment))
                    { continue; }
                var values = line.split(reDelimiter);
                if (j === 0) {
                    this$1.table.columnNames = values;
                }
                else if (line) {
                    data.push(values);
                }
                ++j;
            }
        });
    };

    Object.defineProperties( CsvParser.prototype, prototypeAccessors );

    return CsvParser;
}(Parser));
ParserRegistry$1.add('csv', CsvParser);

/**
 * @file Json Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var JsonParser = /*@__PURE__*/(function (Parser$$1) {
    function JsonParser(streamer, params) {
        var p = params || {};
        Parser$$1.call(this, streamer, p);
        this.string = defaults(p.string, false);
        this.json = {
            name: this.name,
            path: this.path,
            data: {}
        };
    }

    if ( Parser$$1 ) JsonParser.__proto__ = Parser$$1;
    JsonParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    JsonParser.prototype.constructor = JsonParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true },isJson: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'json'; };
    prototypeAccessors.__objName.get = function () { return 'json'; };
    prototypeAccessors.isJson.get = function () { return true; };
    JsonParser.prototype._parse = function _parse () {
        if (this.streamer.isBinary() || this.string) {
            this.json.data = JSON.parse(this.streamer.asText());
        }
        else {
            this.json.data = this.streamer.data;
        }
    };

    Object.defineProperties( JsonParser.prototype, prototypeAccessors );

    return JsonParser;
}(Parser));
ParserRegistry$1.add('json', JsonParser);

/**
 * @file Msgpack Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var MsgpackParser = /*@__PURE__*/(function (Parser$$1) {
    function MsgpackParser(streamer, params) {
        var p = params || {};
        Parser$$1.call(this, streamer, p);
        this.msgpack = {
            name: this.name,
            path: this.path,
            data: undefined
        };
    }

    if ( Parser$$1 ) MsgpackParser.__proto__ = Parser$$1;
    MsgpackParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    MsgpackParser.prototype.constructor = MsgpackParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true },isBinary: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'msgpack'; };
    prototypeAccessors.__objName.get = function () { return 'msgpack'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    MsgpackParser.prototype._parse = function _parse () {
        if (Debug)
            { Log.time('MsgpackParser._parse ' + this.name); }
        this.msgpack.data = decodeMsgpack(this.streamer.data);
        if (Debug)
            { Log.timeEnd('MsgpackParser._parse ' + this.name); }
    };

    Object.defineProperties( MsgpackParser.prototype, prototypeAccessors );

    return MsgpackParser;
}(Parser));
ParserRegistry$1.add('msgpack', MsgpackParser);

/**
 * @file Netcdf Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var NetcdfParser = /*@__PURE__*/(function (Parser$$1) {
    function NetcdfParser(streamer, params) {
        var p = params || {};
        Parser$$1.call(this, streamer, p);
        this.netcdf = {
            name: this.name,
            path: this.path,
            data: undefined
        };
    }

    if ( Parser$$1 ) NetcdfParser.__proto__ = Parser$$1;
    NetcdfParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    NetcdfParser.prototype.constructor = NetcdfParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true },isBinary: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'netcdf'; };
    prototypeAccessors.__objName.get = function () { return 'netcdf'; };
    prototypeAccessors.isBinary.get = function () { return true; };
    NetcdfParser.prototype._parse = function _parse () {
        if (Debug)
            { Log.time('NetcdfParser._parse ' + this.name); }
        this.netcdf.data = new NetcdfReader(this.streamer.data);
        if (Debug)
            { Log.timeEnd('NetcdfParser._parse ' + this.name); }
    };

    Object.defineProperties( NetcdfParser.prototype, prototypeAccessors );

    return NetcdfParser;
}(Parser));
ParserRegistry$1.add('netcdf', NetcdfParser);

/**
 * @file Text Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var TextParser = /*@__PURE__*/(function (Parser$$1) {
    function TextParser(streamer, params) {
        Parser$$1.call(this, streamer, params);
        this.text = {
            name: this.name,
            path: this.path,
            data: ''
        };
    }

    if ( Parser$$1 ) TextParser.__proto__ = Parser$$1;
    TextParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    TextParser.prototype.constructor = TextParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'text'; };
    prototypeAccessors.__objName.get = function () { return 'text'; };
    TextParser.prototype._parse = function _parse () {
        this.text.data = this.streamer.asText();
    };

    Object.defineProperties( TextParser.prototype, prototypeAccessors );

    return TextParser;
}(Parser));
ParserRegistry$1.add('txt', TextParser);
ParserRegistry$1.add('text', TextParser);

/**
 * @file Parse Xml
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var reStrip = /^['"]|['"]$/g;
var reTag = /^<([\w-:.]+)\s*/;
var reContent = /^([^<]*)/;
var reAttr = /([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/;
function strip(val) {
    return val.replace(reStrip, '');
}
function parseXml(xml) {
    // trim and strip comments
    xml = xml.trim().replace(/<!--[\s\S]*?-->/g, '');
    return document();
    function document() {
        return {
            declaration: declaration(),
            root: tag()
        };
    }
    function declaration() {
        var m = match(/^<\?xml\s*/);
        if (!m)
            { return; }
        // tag
        var node = {
            attributes: {}
        };
        // attributes
        while (!(eos() || is('?>'))) {
            var attr = attribute();
            if (!attr)
                { return node; }
            node.attributes[attr.name] = attr.value;
        }
        match(/\?>\s*/);
        return node;
    }
    function tag() {
        var m = match(reTag);
        if (!m)
            { return; }
        // name
        var node = {
            name: m[1],
            attributes: {},
            children: []
        };
        // attributes
        while (!(eos() || is('>') || is('?>') || is('/>'))) {
            var attr = attribute();
            if (!attr)
                { return node; }
            node.attributes[attr.name] = attr.value;
        }
        // self closing tag
        if (match(/^\s*\/>\s*/)) {
            return node;
        }
        match(/\??>\s*/);
        // content
        node.content = content();
        // children
        var child;
        while ((child = tag())) {
            node.children.push(child);
        }
        // closing
        match(/^<\/[\w-:.]+>\s*/);
        return node;
    }
    function content() {
        var m = match(reContent);
        if (m)
            { return m[1]; }
        return '';
    }
    function attribute() {
        var m = match(reAttr);
        if (!m)
            { return; }
        return { name: m[1], value: strip(m[2]) };
    }
    function match(re) {
        var m = xml.match(re);
        if (!m)
            { return; }
        xml = xml.slice(m[0].length);
        return m;
    }
    function eos() {
        return xml.length === 0;
    }
    function is(prefix) {
        return xml.indexOf(prefix) === 0;
    }
}

/**
 * @file Xml Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var XmlParser = /*@__PURE__*/(function (Parser$$1) {
    function XmlParser(streamer, params) {
        var p = params || {};
        Parser$$1.call(this, streamer, p);
        this.useDomParser = defaults(p.useDomParser, false);
        this.xml = {
            name: this.name,
            path: this.path,
            data: {}
        };
    }

    if ( Parser$$1 ) XmlParser.__proto__ = Parser$$1;
    XmlParser.prototype = Object.create( Parser$$1 && Parser$$1.prototype );
    XmlParser.prototype.constructor = XmlParser;

    var prototypeAccessors = { type: { configurable: true },__objName: { configurable: true },isXml: { configurable: true } };
    prototypeAccessors.type.get = function () { return 'xml'; };
    prototypeAccessors.__objName.get = function () { return 'xml'; };
    prototypeAccessors.isXml.get = function () { return true; };
    XmlParser.prototype.__xmlParser = function __xmlParser (xml) {
        return parseXml(xml);
    };
    XmlParser.prototype.__domParser = function __domParser (xml) {
        var domParser = new window.DOMParser();
        return domParser.parseFromString(xml, 'text/xml');
    };
    XmlParser.prototype._parse = function _parse () {
        if (Debug)
            { Log.time('XmlParser._parse ' + this.name); }
        if (this.useDomParser) {
            if (this.streamer.data instanceof Document) { //TS conversion: stripped the window prefix from window.Document
                this.xml.data = this.streamer.data;
            }
            else {
                this.xml.data = this.__domParser(this.streamer.asText());
            }
        }
        else {
            this.xml.data = this.__xmlParser(this.streamer.asText());
        }
        if (Debug)
            { Log.timeEnd('XmlParser._parse ' + this.name); }
    };

    Object.defineProperties( XmlParser.prototype, prototypeAccessors );

    return XmlParser;
}(Parser));
ParserRegistry$1.add('xml', XmlParser);

/**
 * @file Validation
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function getNamedItem(a, name) {
    var item = a.getNamedItem(name);
    return item !== null ? item.value : '';
}
function getSele(a, atomname, useAltcode) {
    if ( useAltcode === void 0 ) useAltcode = false;

    var icode = getNamedItem(a, 'icode').trim();
    var chain = getNamedItem(a, 'chain').trim();
    var altcode = getNamedItem(a, 'altcode');
    var sele = getNamedItem(a, 'resnum');
    if (icode)
        { sele += '^' + icode; }
    if (chain)
        { sele += ':' + chain; }
    if (atomname)
        { sele += '.' + atomname; }
    if (useAltcode && altcode.trim())
        { sele += '%' + altcode; }
    sele += '/' + (parseInt(getNamedItem(a, 'model')) - 1);
    return sele;
}
function getResSele(a) {
    var chain = getNamedItem(a, 'chain').trim();
    var rescode = getNamedItem(a, 'rescode');
    var resnum = getNamedItem(a, 'resnum');
    var sele = "[" + rescode + "]" + resnum;
    if (chain)
        { sele += ":" + chain; }
    return sele;
}
function setBitDict(dict, key, bit) {
    if (dict[key] === undefined) {
        dict[key] = bit;
    }
    else {
        dict[key] |= bit;
    }
}
function hasAttrValue(attr, value) {
    return attr !== null && attr.value === value;
}
function getAtomSele(ap) {
    var icode = ap.inscode;
    var chain = ap.chainname;
    var atomname = ap.atomname;
    var altcode = ap.altloc;
    var sele = ap.resno + '';
    if (icode)
        { sele += '^' + icode; }
    if (chain)
        { sele += ':' + chain; }
    if (atomname)
        { sele += '.' + atomname; }
    if (altcode)
        { sele += '%' + altcode; }
    sele += '/' + ap.modelIndex;
    return sele;
}
function getProblemCount(clashDict, g, ga) {
    var geoProblemCount = 0;
    var clashes = g.getElementsByTagName('clash');
    for (var j = 0, jl = clashes.length; j < jl; ++j) {
        if (clashDict[getNamedItem(clashes[j].attributes, 'cid')]) {
            geoProblemCount += 1;
            break;
        }
    }
    var angleOutliers = g.getElementsByTagName('angle-outlier');
    if (angleOutliers.length > 0) {
        geoProblemCount += 1;
    }
    var bondOutliers = g.getElementsByTagName('bond-outlier');
    if (bondOutliers.length > 0) {
        geoProblemCount += 1;
    }
    var planeOutliers = g.getElementsByTagName('plane-outlier');
    if (planeOutliers.length > 0) {
        geoProblemCount += 1;
    }
    if (hasAttrValue(ga.getNamedItem('rota'), 'OUTLIER')) {
        geoProblemCount += 1;
    }
    if (hasAttrValue(ga.getNamedItem('rama'), 'OUTLIER')) {
        geoProblemCount += 1;
    }
    if (hasAttrValue(ga.getNamedItem('RNApucker'), 'outlier')) {
        geoProblemCount += 1;
    }
    return geoProblemCount;
}
var Validation = function Validation(name, path) {
    this.name = name;
    this.path = path;
    this.rsrzDict = {};
    this.rsccDict = {};
    /**
     * Random Coil Index (RCI) - evaluates the proximity of residue structural
     * and dynamic properties to the properties of flexible random coil regions
     * from NMR chemical shifts.
     *
     * Mark V. Berjanskii and David S. Wishart (2005)
     * A Simple Method To Predict Protein Flexibility Using Secondary Chemical Shifts
     * J. Am. Chem. Soc., 2005, 127 (43), pp 14970–14971
     * http://pubs.acs.org/doi/abs/10.1021/ja054842f
     *
     * Mark V. Berjanskii and David S. Wishart (2008)
     * Application of the random coil index to studying protein flexibility.
     * J Biomol NMR. 2008 Jan;40(1):31-48. Epub 2007 Nov 6.
     * http://www.springerlink.com/content/2966482w10306126/
     */
    this.rciDict = {};
    this.clashDict = {};
    this.clashArray = [];
    this.geoDict = {};
    this.geoAtomDict = {};
    this.atomDict = {};
    this.clashSele = 'NONE';
};

var prototypeAccessors$z = { type: { configurable: true } };
prototypeAccessors$z.type.get = function () { return 'validation'; };
Validation.prototype.fromXml = function fromXml (xml) {
    if (Debug)
        { Log.time('Validation.fromXml'); }
    var rsrzDict = this.rsrzDict;
    var rsccDict = this.rsccDict;
    var rciDict = this.rciDict;
    var clashDict = this.clashDict;
    var clashArray = this.clashArray;
    var geoDict = this.geoDict;
    var geoAtomDict = this.geoAtomDict;
    var atomDict = this.atomDict;
    var entries = xml.getElementsByTagName('Entry');
    if (entries.length === 1) {
        var chemicalShiftLists = entries[0].getElementsByTagName('chemical_shift_list');
        if (chemicalShiftLists.length === 1) {
            var randomCoilIndices = chemicalShiftLists[0].getElementsByTagName('random_coil_index');
            for (var j = 0, jl = randomCoilIndices.length; j < jl; ++j) {
                var rcia = randomCoilIndices[j].attributes;
                var sele = getResSele(rcia);
                rciDict[sele] = parseFloat(getNamedItem(rcia, 'value'));
            }
        }
    }
    var groups = xml.getElementsByTagName('ModelledSubgroup');
    var _clashDict = {};
    var clashList = [];
    if (Debug)
        { Log.time('Validation.fromXml#clashDict'); }
    for (var i = 0, il = groups.length; i < il; ++i) {
        var g = groups[i];
        var ga = g.attributes;
        var sele$1 = getSele(ga);
        if (ga.getNamedItem('rsrz') !== null) {
            rsrzDict[sele$1] = parseFloat(getNamedItem(ga, 'rsrz'));
        }
        if (ga.getNamedItem('rscc') !== null) {
            rsccDict[sele$1] = parseFloat(getNamedItem(ga, 'rscc'));
        }
        var seleAttr = xml.createAttribute('sele');
        seleAttr.value = sele$1;
        ga.setNamedItem(seleAttr);
        var clashes = g.getElementsByTagName('clash');
        for (var j$1 = 0, jl$1 = clashes.length; j$1 < jl$1; ++j$1) {
            var ca = clashes[j$1].attributes;
            var atom = getNamedItem(ca, 'atom');
            if (guessElement(atom) !== 'H') {
                var cid = getNamedItem(ca, 'cid');
                var atomSele = getSele(ga, atom, true);
                atomDict[atomSele] = true;
                if (_clashDict[cid] === undefined) {
                    _clashDict[cid] = {
                        sele1: atomSele,
                        res1: sele$1
                    };
                }
                else {
                    var c = _clashDict[cid];
                    if (c.res1 !== sele$1) {
                        c.sele2 = atomSele;
                        c.res2 = sele$1;
                        clashList.push(c.res1, sele$1);
                        clashDict[cid] = c;
                        clashArray.push(c);
                    }
                }
            }
        }
    }
    if (Debug)
        { Log.timeEnd('Validation.fromXml#clashDict'); }
    for (var i$1 = 0, il$1 = groups.length; i$1 < il$1; ++i$1) {
        var g$1 = groups[i$1];
        var ga$1 = g$1.attributes;
        var sele$2 = getNamedItem(ga$1, 'sele');
        var isPolymer = getNamedItem(ga$1, 'seq') !== '.';
        if (isPolymer) {
            var geoProblemCount = getProblemCount(clashDict, g$1, ga$1);
            if (geoProblemCount > 0) {
                geoDict[sele$2] = geoProblemCount;
            }
        }
        else {
            var clashes$1 = g$1.getElementsByTagName('clash');
            var mogBondOutliers = g$1.getElementsByTagName('mog-bond-outlier');
            var mogAngleOutliers = g$1.getElementsByTagName('mog-angle-outlier');
            if (mogBondOutliers.length > 0 || mogAngleOutliers.length > 0 || clashes$1.length > 0) {
                var atomDict$1 = {};
                geoAtomDict[sele$2] = atomDict$1;
                for (var j$2 = 0, jl$2 = clashes$1.length; j$2 < jl$2; ++j$2) {
                    var ca$1 = clashes$1[j$2].attributes;
                    if (clashDict[getNamedItem(ca$1, 'cid')]) {
                        setBitDict(atomDict$1, getNamedItem(ca$1, 'atom'), 1);
                    }
                }
                for (var j$3 = 0, jl$3 = mogBondOutliers.length; j$3 < jl$3; ++j$3) {
                    var mbo = mogBondOutliers[j$3].attributes;
                    getNamedItem(mbo, 'atoms').split(',').forEach(function (atomname) {
                        setBitDict(atomDict$1, atomname, 2);
                    });
                }
                for (var j$4 = 0, jl$4 = mogAngleOutliers.length; j$4 < jl$4; ++j$4) {
                    var mao = mogAngleOutliers[j$4].attributes;
                    getNamedItem(mao, 'atoms').split(',').forEach(function (atomname) {
                        setBitDict(atomDict$1, atomname, 4);
                    });
                }
            }
        }
    }
    this.clashSele = clashList.length ? clashList.join(' OR ') : 'NONE';
    if (Debug)
        { Log.timeEnd('Validation.fromXml'); }
};
Validation.prototype.getClashData = function getClashData (params) {
    if (Debug)
        { Log.time('Validation.getClashData'); }
    var p = params || {};
    var s = p.structure;
    var atomSet = s.atomSet; // TODO
    var c = new __WEBPACK_IMPORTED_MODULE_0_three__["i" /* Color */](defaults(p.color, '#f0027f'));
    var ap1 = s.getAtomProxy();
    var ap2 = s.getAtomProxy();
    var vDir = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var vPos1 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var vPos2 = new __WEBPACK_IMPORTED_MODULE_0_three__["X" /* Vector3 */]();
    var clashArray = this.clashArray;
    var n = clashArray.length;
    var position1 = new Float32Array(n * 3);
    var position2 = new Float32Array(n * 3);
    var color = uniformArray3(n, c.r, c.g, c.b);
    var radius = new Float32Array(n);
    var picking = new Float32Array(n);
    if (Debug)
        { Log.time('Validation.getClashData#atomDict'); }
    var atomDict = this.atomDict;
    s.eachAtom(function (ap) {
        var sele = getAtomSele(ap);
        if (atomDict[sele] === true) {
            atomDict[sele] = ap.index;
        }
    });
    if (Debug)
        { Log.timeEnd('Validation.getClashData#atomDict'); }
    var i = 0;
    clashArray.forEach(function (c, idx) {
        ap1.index = atomDict[c.sele1]; // TODO
        ap2.index = atomDict[c.sele2]; // TODO
        if (ap1.index === undefined || ap2.index === undefined ||
            !atomSet.isSet(ap1.index, ap2.index))
            { return; }
        vDir.subVectors(ap2, ap1).setLength(ap1.vdw); // TODO
        vPos1.copy(ap1).add(vDir); // TODO
        vDir.subVectors(ap1, ap2).setLength(ap2.vdw); // TODO
        vPos2.copy(ap2).add(vDir); // TODO
        var dHalf = ap1.distanceTo(ap2) / 2;
        var r1 = Math.sqrt(ap1.vdw * ap1.vdw - dHalf * dHalf);
        var r2 = Math.sqrt(ap2.vdw * ap2.vdw - dHalf * dHalf);
        vPos1.toArray(position1, i * 3); // TODO
        vPos2.toArray(position2, i * 3);
        radius[i] = (r1 + r2) / 2;
        picking[i] = idx;
        ++i;
    });
    if (Debug)
        { Log.timeEnd('Validation.getClashData'); }
    return {
        position1: position1.subarray(0, i * 3),
        position2: position2.subarray(0, i * 3),
        color: color.subarray(0, i * 3),
        color2: color.subarray(0, i * 3),
        radius: radius.subarray(0, i),
        picking: new ClashPicker(picking.subarray(0, i), this, s)
    };
};

Object.defineProperties( Validation.prototype, prototypeAccessors$z );

/**
 * @file Validation Parser
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var ValidationParser = /*@__PURE__*/(function (XmlParser$$1) {
    function ValidationParser(streamer, params) {
        var p = params || {};
        XmlParser$$1.call(this, streamer, p);
        this.useDomParser = true;
        this.validation = new Validation(this.name, this.path);
    }

    if ( XmlParser$$1 ) ValidationParser.__proto__ = XmlParser$$1;
    ValidationParser.prototype = Object.create( XmlParser$$1 && XmlParser$$1.prototype );
    ValidationParser.prototype.constructor = ValidationParser;

    var prototypeAccessors = { __objName: { configurable: true },isXml: { configurable: true } };
    prototypeAccessors.__objName.get = function () { return 'validation'; };
    prototypeAccessors.isXml.get = function () { return true; };
    ValidationParser.prototype._parse = function _parse () {
        XmlParser$$1.prototype._parse.call(this);
        if (Debug)
            { Log.time('ValidationParser._parse ' + this.name); }
        this.validation.fromXml(this.xml.data);
        if (Debug)
            { Log.timeEnd('ValidationParser._parse ' + this.name); }
    };

    Object.defineProperties( ValidationParser.prototype, prototypeAccessors );

    return ValidationParser;
}(XmlParser));
ParserRegistry$1.add('validation', ValidationParser);

// https://github.com/nodeca/pako
// MIT License, Copyright (c) 2014 by Vitaly Puzrin


// 'use strict';


// var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
//                 (typeof Uint16Array !== 'undefined') &&
//                 (typeof Int32Array !== 'undefined');


function assign(obj /*from1, from2, from3, ...*/) {
  var sources = Array.prototype.slice.call(arguments, 1);
  while (sources.length) {
    var source = sources.shift();
    if (!source) { continue; }

    if (typeof source !== 'object') {
      throw new TypeError(source + 'must be non-object');
    }

    for (var p in source) {
      if (source.hasOwnProperty(p)) {
        obj[p] = source[p];
      }
    }
  }

  return obj;
}


// reduce buffer size, avoiding mem copy
function shrinkBuf(buf, size) {
  if (buf.length === size) { return buf; }
  if (buf.subarray) { return buf.subarray(0, size); }
  buf.length = size;
  return buf;
}


function arraySet(dest, src, src_offs, len, dest_offs) {
  if (src.subarray && dest.subarray) {
    dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
    return;
  }
  // Fallback to ordinary array
  for (var i = 0; i < len; i++) {
    dest[dest_offs + i] = src[src_offs + i];
  }
}

// Join array of chunks to single array.
function flattenChunks(chunks) {
  var i, l, len, pos, chunk, result;

  // calculate data length
  len = 0;
  for (i = 0, l = chunks.length; i < l; i++) {
    len += chunks[i].length;
  }

  // join chunks
  result = new Uint8Array(len);
  pos = 0;
  for (i = 0, l = chunks.length; i < l; i++) {
    chunk = chunks[i];
    result.set(chunk, pos);
    pos += chunk.length;
  }

  return result;
}

// 'use strict';

// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.

function adler32(adler, buf, len, pos) {
  var s1 = (adler & 0xffff) |0,
      s2 = ((adler >>> 16) & 0xffff) |0,
      n = 0;

  while (len !== 0) {
    // Set limit ~ twice less than 5552, to keep
    // s2 in 31-bits, because we force signed ints.
    // in other case %= will fail.
    n = len > 2000 ? 2000 : len;
    len -= n;

    do {
      s1 = (s1 + buf[pos++]) |0;
      s2 = (s2 + s1) |0;
    } while (--n);

    s1 %= 65521;
    s2 %= 65521;
  }

  return (s1 | (s2 << 16)) |0;
}

// 'use strict';

// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.


// Use ordinary array, since untyped makes no boost here
function makeTable() {
  var c, table = [];

  for (var n = 0; n < 256; n++) {
    c = n;
    for (var k = 0; k < 8; k++) {
      c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
    }
    table[n] = c;
  }

  return table;
}

// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();


function crc32(crc, buf, len, pos) {
  var t = crcTable,
      end = pos + len;

  crc ^= -1;

  for (var i = pos; i < end; i++) {
    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  }

  return (crc ^ (-1)); // >>> 0;
}

// 'use strict';

// See state defs from inflate.js
var BAD$1 = 30;       /* got a data error -- remain here until reset */
var TYPE$1 = 12;      /* i: waiting for type bits, including last-flag bit */

/*
   Decode literal, length, and distance codes and write out the resulting
   literal and match bytes until either not enough input or output is
   available, an end-of-block is encountered, or a data error is encountered.
   When large enough input and output buffers are supplied to inflate(), for
   example, a 16K input buffer and a 64K output buffer, more than 95% of the
   inflate execution time is spent in this routine.

   Entry assumptions:

        state.mode === LEN
        strm.avail_in >= 6
        strm.avail_out >= 258
        start >= strm.avail_out
        state.bits < 8

   On return, state.mode is one of:

        LEN -- ran out of enough output space or enough available input
        TYPE -- reached end of block code, inflate() to interpret next block
        BAD -- error in block data

   Notes:

    - The maximum input bits used by a length/distance pair is 15 bits for the
      length code, 5 bits for the length extra, 15 bits for the distance code,
      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
      Therefore if strm.avail_in >= 6, then there is enough input to avoid
      checking for available input while decoding.

    - The maximum bytes that a single length/distance pair can output is 258
      bytes, which is the maximum length that can be coded.  inflate_fast()
      requires strm.avail_out >= 258 for each loop to avoid checking for
      output space.
 */
// module.exports =
function inflate_fast(strm, start) {
  var state;
  var _in;                    /* local strm.input */
  var last;                   /* have enough input while in < last */
  var _out;                   /* local strm.output */
  var beg;                    /* inflate()'s initial strm.output */
  var end;                    /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
  var dmax;                   /* maximum distance from zlib header */
//#endif
  var wsize;                  /* window size or zero if not using window */
  var whave;                  /* valid bytes in the window */
  var wnext;                  /* window write index */
  // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  var s_window;               /* allocated sliding window, if wsize != 0 */
  var hold;                   /* local strm.hold */
  var bits;                   /* local strm.bits */
  var lcode;                  /* local strm.lencode */
  var dcode;                  /* local strm.distcode */
  var lmask;                  /* mask for first level of length codes */
  var dmask;                  /* mask for first level of distance codes */
  var here;                   /* retrieved table entry */
  var op;                     /* code bits, operation, extra bits, or */
                              /*  window position, window bytes to copy */
  var len;                    /* match length, unused bytes */
  var dist;                   /* match distance */
  var from;                   /* where to copy match from */
  var from_source;


  var input, output; // JS specific, because we have no pointers

  /* copy state to local variables */
  state = strm.state;
  //here = state.here;
  _in = strm.next_in;
  input = strm.input;
  last = _in + (strm.avail_in - 5);
  _out = strm.next_out;
  output = strm.output;
  beg = _out - (start - strm.avail_out);
  end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
  dmax = state.dmax;
//#endif
  wsize = state.wsize;
  whave = state.whave;
  wnext = state.wnext;
  s_window = state.window;
  hold = state.hold;
  bits = state.bits;
  lcode = state.lencode;
  dcode = state.distcode;
  lmask = (1 << state.lenbits) - 1;
  dmask = (1 << state.distbits) - 1;


  /* decode literals and length/distances until end-of-block or not enough
     input data or output space */

  top:
  do {
    if (bits < 15) {
      hold += input[_in++] << bits;
      bits += 8;
      hold += input[_in++] << bits;
      bits += 8;
    }

    here = lcode[hold & lmask];

    dolen:
    for (;;) { // Goto emulation
      op = here >>> 24/*here.bits*/;
      hold >>>= op;
      bits -= op;
      op = (here >>> 16) & 0xff/*here.op*/;
      if (op === 0) {                          /* literal */
        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
        //        "inflate:         literal '%c'\n" :
        //        "inflate:         literal 0x%02x\n", here.val));
        output[_out++] = here & 0xffff/*here.val*/;
      }
      else if (op & 16) {                     /* length base */
        len = here & 0xffff/*here.val*/;
        op &= 15;                           /* number of extra bits */
        if (op) {
          if (bits < op) {
            hold += input[_in++] << bits;
            bits += 8;
          }
          len += hold & ((1 << op) - 1);
          hold >>>= op;
          bits -= op;
        }
        //Tracevv((stderr, "inflate:         length %u\n", len));
        if (bits < 15) {
          hold += input[_in++] << bits;
          bits += 8;
          hold += input[_in++] << bits;
          bits += 8;
        }
        here = dcode[hold & dmask];

        dodist:
        for (;;) { // goto emulation
          op = here >>> 24/*here.bits*/;
          hold >>>= op;
          bits -= op;
          op = (here >>> 16) & 0xff/*here.op*/;

          if (op & 16) {                      /* distance base */
            dist = here & 0xffff/*here.val*/;
            op &= 15;                       /* number of extra bits */
            if (bits < op) {
              hold += input[_in++] << bits;
              bits += 8;
              if (bits < op) {
                hold += input[_in++] << bits;
                bits += 8;
              }
            }
            dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
            if (dist > dmax) {
              strm.msg = 'invalid distance too far back';
              state.mode = BAD$1;
              break top;
            }
//#endif
            hold >>>= op;
            bits -= op;
            //Tracevv((stderr, "inflate:         distance %u\n", dist));
            op = _out - beg;                /* max distance in output */
            if (dist > op) {                /* see if copy from window */
              op = dist - op;               /* distance back in window */
              if (op > whave) {
                if (state.sane) {
                  strm.msg = 'invalid distance too far back';
                  state.mode = BAD$1;
                  break top;
                }

// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
//                if (len <= op - whave) {
//                  do {
//                    output[_out++] = 0;
//                  } while (--len);
//                  continue top;
//                }
//                len -= op - whave;
//                do {
//                  output[_out++] = 0;
//                } while (--op > whave);
//                if (op === 0) {
//                  from = _out - dist;
//                  do {
//                    output[_out++] = output[from++];
//                  } while (--len);
//                  continue top;
//                }
//#endif
              }
              from = 0; // window index
              from_source = s_window;
              if (wnext === 0) {           /* very common case */
                from += wsize - op;
                if (op < len) {         /* some from window */
                  len -= op;
                  do {
                    output[_out++] = s_window[from++];
                  } while (--op);
                  from = _out - dist;  /* rest from output */
                  from_source = output;
                }
              }
              else if (wnext < op) {      /* wrap around window */
                from += wsize + wnext - op;
                op -= wnext;
                if (op < len) {         /* some from end of window */
                  len -= op;
                  do {
                    output[_out++] = s_window[from++];
                  } while (--op);
                  from = 0;
                  if (wnext < len) {  /* some from start of window */
                    op = wnext;
                    len -= op;
                    do {
                      output[_out++] = s_window[from++];
                    } while (--op);
                    from = _out - dist;      /* rest from output */
                    from_source = output;
                  }
                }
              }
              else {                      /* contiguous in window */
                from += wnext - op;
                if (op < len) {         /* some from window */
                  len -= op;
                  do {
                    output[_out++] = s_window[from++];
                  } while (--op);
                  from = _out - dist;  /* rest from output */
                  from_source = output;
                }
              }
              while (len > 2) {
                output[_out++] = from_source[from++];
                output[_out++] = from_source[from++];
                output[_out++] = from_source[from++];
                len -= 3;
              }
              if (len) {
                output[_out++] = from_source[from++];
                if (len > 1) {
                  output[_out++] = from_source[from++];
                }
              }
            }
            else {
              from = _out - dist;          /* copy direct from output */
              do {                        /* minimum length is three */
                output[_out++] = output[from++];
                output[_out++] = output[from++];
                output[_out++] = output[from++];
                len -= 3;
              } while (len > 2);
              if (len) {
                output[_out++] = output[from++];
                if (len > 1) {
                  output[_out++] = output[from++];
                }
              }
            }
          }
          else if ((op & 64) === 0) {          /* 2nd level distance code */
            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
            continue dodist;
          }
          else {
            strm.msg = 'invalid distance code';
            state.mode = BAD$1;
            break top;
          }

          break; // need to emulate goto via "continue"
        }
      }
      else if ((op & 64) === 0) {              /* 2nd level length code */
        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
        continue dolen;
      }
      else if (op & 32) {                     /* end-of-block */
        //Tracevv((stderr, "inflate:         end of block\n"));
        state.mode = TYPE$1;
        break top;
      }
      else {
        strm.msg = 'invalid literal/length code';
        state.mode = BAD$1;
        break top;
      }

      break; // need to emulate goto via "continue"
    }
  } while (_in < last && _out < end);

  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  len = bits >> 3;
  _in -= len;
  bits -= len << 3;
  hold &= (1 << bits) - 1;

  /* update state and return */
  strm.next_in = _in;
  strm.next_out = _out;
  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  state.hold = hold;
  state.bits = bits;
  return;
}
// 'use strict';


// var utils = require('../utils/common');

var MAXBITS = 15;
var ENOUGH_LENS$1 = 852;
var ENOUGH_DISTS$1 = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);

var CODES$1 = 0;
var LENS$1 = 1;
var DISTS$1 = 2;

var lbase = [ /* Length codes 257..285 base */
  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
];

var lext = [ /* Length codes 257..285 extra */
  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
];

var dbase = [ /* Distance codes 0..29 base */
  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
];

var dext = [ /* Distance codes 0..29 extra */
  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
];

// module.exports =
function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
  var bits = opts.bits;
      //here = opts.here; /* table entry for duplication */

  var len = 0;               /* a code's length in bits */
  var sym = 0;               /* index of code symbols */
  var min = 0, max = 0;          /* minimum and maximum code lengths */
  var root = 0;              /* number of index bits for root table */
  var curr = 0;              /* number of index bits for current table */
  var drop = 0;              /* code bits to drop for sub-table */
  var left = 0;                   /* number of prefix codes available */
  var used = 0;              /* code entries in table used */
  var huff = 0;              /* Huffman code */
  var incr;              /* for incrementing code, index */
  var fill;              /* index for replicating entries */
  var low;               /* low bits for current root entry */
  var mask;              /* mask for low root bits */
  var next;             /* next available space in table */
  var base = null;     /* base value table to use */
  var base_index = 0;
//  var shoextra;    /* extra bits table to use */
  var end;                    /* use base and extra for symbol > end */
  var count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];    /* number of codes of each length */
  var offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1];     /* offsets in table for each length */
  var extra = null;
  var extra_index = 0;

  var here_bits, here_op, here_val;

  /*
   Process a set of code lengths to create a canonical Huffman code.  The
   code lengths are lens[0..codes-1].  Each length corresponds to the
   symbols 0..codes-1.  The Huffman code is generated by first sorting the
   symbols by length from short to long, and retaining the symbol order
   for codes with equal lengths.  Then the code starts with all zero bits
   for the first code of the shortest length, and the codes are integer
   increments for the same length, and zeros are appended as the length
   increases.  For the deflate format, these bits are stored backwards
   from their more natural integer increment ordering, and so when the
   decoding tables are built in the large loop below, the integer codes
   are incremented backwards.

   This routine assumes, but does not check, that all of the entries in
   lens[] are in the range 0..MAXBITS.  The caller must assure this.
   1..MAXBITS is interpreted as that code length.  zero means that that
   symbol does not occur in this code.

   The codes are sorted by computing a count of codes for each length,
   creating from that a table of starting indices for each length in the
   sorted table, and then entering the symbols in order in the sorted
   table.  The sorted table is work[], with that space being provided by
   the caller.

   The length counts are used for other purposes as well, i.e. finding
   the minimum and maximum length codes, determining if there are any
   codes at all, checking for a valid set of lengths, and looking ahead
   at length counts to determine sub-table sizes when building the
   decoding tables.
   */

  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  for (len = 0; len <= MAXBITS; len++) {
    count[len] = 0;
  }
  for (sym = 0; sym < codes; sym++) {
    count[lens[lens_index + sym]]++;
  }

  /* bound code lengths, force root to be within code lengths */
  root = bits;
  for (max = MAXBITS; max >= 1; max--) {
    if (count[max] !== 0) { break; }
  }
  if (root > max) {
    root = max;
  }
  if (max === 0) {                     /* no symbols to code at all */
    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
    table[table_index++] = (1 << 24) | (64 << 16) | 0;


    //table.op[opts.table_index] = 64;
    //table.bits[opts.table_index] = 1;
    //table.val[opts.table_index++] = 0;
    table[table_index++] = (1 << 24) | (64 << 16) | 0;

    opts.bits = 1;
    return 0;     /* no symbols, but wait for decoding to report error */
  }
  for (min = 1; min < max; min++) {
    if (count[min] !== 0) { break; }
  }
  if (root < min) {
    root = min;
  }

  /* check for an over-subscribed or incomplete set of lengths */
  left = 1;
  for (len = 1; len <= MAXBITS; len++) {
    left <<= 1;
    left -= count[len];
    if (left < 0) {
      return -1;
    }        /* over-subscribed */
  }
  if (left > 0 && (type === CODES$1 || max !== 1)) {
    return -1;                      /* incomplete set */
  }

  /* generate offsets into symbol table for each length for sorting */
  offs[1] = 0;
  for (len = 1; len < MAXBITS; len++) {
    offs[len + 1] = offs[len] + count[len];
  }

  /* sort symbols by length, by symbol order within each length */
  for (sym = 0; sym < codes; sym++) {
    if (lens[lens_index + sym] !== 0) {
      work[offs[lens[lens_index + sym]]++] = sym;
    }
  }

  /*
   Create and fill in decoding tables.  In this loop, the table being
   filled is at next and has curr index bits.  The code being used is huff
   with length len.  That code is converted to an index by dropping drop
   bits off of the bottom.  For codes where len is less than drop + curr,
   those top drop + curr - len bits are incremented through all values to
   fill the table with replicated entries.

   root is the number of index bits for the root table.  When len exceeds
   root, sub-tables are created pointed to by the root entry with an index
   of the low root bits of huff.  This is saved in low to check for when a
   new sub-table should be started.  drop is zero when the root table is
   being filled, and drop is root when sub-tables are being filled.

   When a new sub-table is needed, it is necessary to look ahead in the
   code lengths to determine what size sub-table is needed.  The length
   counts are used for this, and so count[] is decremented as codes are
   entered in the tables.

   used keeps track of how many table entries have been allocated from the
   provided *table space.  It is checked for LENS and DIST tables against
   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
   the initial root table size constants.  See the comments in inftrees.h
   for more information.

   sym increments through all symbols, and the loop terminates when
   all codes of length max, i.e. all codes, have been processed.  This
   routine permits incomplete codes, so another loop after this one fills
   in the rest of the decoding tables with invalid code markers.
   */

  /* set up for code type */
  // poor man optimization - use if-else instead of switch,
  // to avoid deopts in old v8
  if (type === CODES$1) {
    base = extra = work;    /* dummy value--not used */
    end = 19;

  } else if (type === LENS$1) {
    base = lbase;
    base_index -= 257;
    extra = lext;
    extra_index -= 257;
    end = 256;

  } else {                    /* DISTS */
    base = dbase;
    extra = dext;
    end = -1;
  }

  /* initialize opts for loop */
  huff = 0;                   /* starting code */
  sym = 0;                    /* starting code symbol */
  len = min;                  /* starting code length */
  next = table_index;              /* current table to fill in */
  curr = root;                /* current table index bits */
  drop = 0;                   /* current bits to drop from code for index */
  low = -1;                   /* trigger new sub-table when len > root */
  used = 1 << root;          /* use root table entries */
  mask = used - 1;            /* mask for comparing low */

  /* check available table space */
  if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
    (type === DISTS$1 && used > ENOUGH_DISTS$1)) {
    return 1;
  }
  /* process all codes and make table entries */
  for (;;) {
    /* create table entry */
    here_bits = len - drop;
    if (work[sym] < end) {
      here_op = 0;
      here_val = work[sym];
    }
    else if (work[sym] > end) {
      here_op = extra[extra_index + work[sym]];
      here_val = base[base_index + work[sym]];
    }
    else {
      here_op = 32 + 64;         /* end of block */
      here_val = 0;
    }

    /* replicate for those indices with low len bits equal to huff */
    incr = 1 << (len - drop);
    fill = 1 << curr;
    min = fill;                 /* save offset to next table */
    do {
      fill -= incr;
      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
    } while (fill !== 0);

    /* backwards increment the len-bit code huff */
    incr = 1 << (len - 1);
    while (huff & incr) {
      incr >>= 1;
    }
    if (incr !== 0) {
      huff &= incr - 1;
      huff += incr;
    } else {
      huff = 0;
    }

    /* go to next symbol, update count, len */
    sym++;
    if (--count[len] === 0) {
      if (len === max) { break; }
      len = lens[lens_index + work[sym]];
    }

    /* create new sub-table if needed */
    if (len > root && (huff & mask) !== low) {
      /* if first time, transition to sub-tables */
      if (drop === 0) {
        drop = root;
      }

      /* increment past last table */
      next += min;            /* here min is 1 << curr */

      /* determine length of next table */
      curr = len - drop;
      left = 1 << curr;
      while (curr + drop < max) {
        left -= count[curr + drop];
        if (left <= 0) { break; }
        curr++;
        left <<= 1;
      }

      /* check for enough space */
      used += 1 << curr;
      if ((type === LENS$1 && used > ENOUGH_LENS$1) ||
        (type === DISTS$1 && used > ENOUGH_DISTS$1)) {
        return 1;
      }

      /* point entry in root table to sub-table */
      low = huff & mask;
      /*table.op[low] = curr;
      table.bits[low] = root;
      table.val[low] = next - opts.table_index;*/
      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
    }
  }

  /* fill in remaining table entry if code is incomplete (guaranteed to have
   at most one remaining entry, since if the code is incomplete, the
   maximum code length that was allowed to get this far is one bit) */
  if (huff !== 0) {
    //table.op[next + huff] = 64;            /* invalid code marker */
    //table.bits[next + huff] = len - drop;
    //table.val[next + huff] = 0;
    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  }

  /* set return parameters */
  //opts.table_index += used;
  opts.bits = root;
  return 0;
}
// 'use strict';


// var utils         = require('../utils/common');
// var adler32       = require('./adler32');
// var crc32         = require('./crc32');
// var inflate_fast  = require('./inffast');
// var inflate_table = require('./inftrees');

var CODES = 0;
var LENS = 1;
var DISTS = 2;

/* Public constants ==========================================================*/
/* ===========================================================================*/


/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH      = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH    = 2;
//var Z_FULL_FLUSH    = 3;
var Z_FINISH        = 4;
var Z_BLOCK         = 5;
var Z_TREES         = 6;


/* Return codes for the compression/decompression functions. Negative values
 * are errors, positive values are used for special but normal events.
 */
var Z_OK            = 0;
var Z_STREAM_END    = 1;
var Z_NEED_DICT     = 2;
//var Z_ERRNO         = -1;
var Z_STREAM_ERROR  = -2;
var Z_DATA_ERROR    = -3;
var Z_MEM_ERROR     = -4;
var Z_BUF_ERROR     = -5;
//var Z_VERSION_ERROR = -6;

/* The deflate compression method */
var Z_DEFLATED  = 8;


/* STATES ====================================================================*/
/* ===========================================================================*/


var    HEAD = 1;       /* i: waiting for magic header */
var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
var    TIME = 3;       /* i: waiting for modification time (gzip) */
var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
var    NAME = 7;       /* i: waiting for end of file name (gzip) */
var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
var    HCRC = 9;       /* i: waiting for header crc (gzip) */
var    DICTID = 10;    /* i: waiting for dictionary check value */
var    DICT = 11;      /* waiting for inflateSetDictionary() call */
var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
var        STORED = 14;    /* i: waiting for stored size (length and complement) */
var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
var        LENLENS = 18;   /* i: waiting for code length code lengths */
var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
var            LEN = 21;       /* i: waiting for length/lit/eob code */
var            LENEXT = 22;    /* i: waiting for length extra bits */
var            DIST = 23;      /* i: waiting for distance code */
var            DISTEXT = 24;   /* i: waiting for distance extra bits */
var            MATCH = 25;     /* o: waiting for output space to copy string */
var            LIT = 26;       /* o: waiting for output space to write literal */
var    CHECK = 27;     /* i: waiting for 32-bit check value */
var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
var    DONE = 29;      /* finished check, done -- remain here until reset */
var    BAD = 30;       /* got a data error -- remain here until reset */
var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */

/* ===========================================================================*/



var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
function zswap32(q) {
  return  (((q >>> 24) & 0xff) +
          ((q >>> 8) & 0xff00) +
          ((q & 0xff00) << 8) +
          ((q & 0xff) << 24));
}


function InflateState() {
  this.mode = 0;             /* current inflate mode */
  this.last = false;          /* true if processing last block */
  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
  this.havedict = false;      /* true if dictionary provided */
  this.flags = 0;             /* gzip header method and flags (0 if zlib) */
  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
  this.check = 0;             /* protected copy of check value */
  this.total = 0;             /* protected copy of output count */
  // TODO: may be {}
  this.head = null;           /* where to save gzip header information */

  /* sliding window */
  this.wbits = 0;             /* log base 2 of requested window size */
  this.wsize = 0;             /* window size or zero if not using window */
  this.whave = 0;             /* valid bytes in the window */
  this.wnext = 0;             /* window write index */
  this.window = null;         /* allocated sliding window, if needed */

  /* bit accumulator */
  this.hold = 0;              /* input bit accumulator */
  this.bits = 0;              /* number of bits in "in" */

  /* for string and stored block copying */
  this.length = 0;            /* literal or length of data to copy */
  this.offset = 0;            /* distance back to copy string from */

  /* for table and code decoding */
  this.extra = 0;             /* extra bits needed */

  /* fixed and dynamic code tables */
  this.lencode = null;          /* starting table for length/literal codes */
  this.distcode = null;         /* starting table for distance codes */
  this.lenbits = 0;           /* index bits for lencode */
  this.distbits = 0;          /* index bits for distcode */

  /* dynamic table building */
  this.ncode = 0;             /* number of code length code lengths */
  this.nlen = 0;              /* number of length code lengths */
  this.ndist = 0;             /* number of distance code lengths */
  this.have = 0;              /* number of code lengths in lens[] */
  this.next = null;              /* next available space in codes[] */

  this.lens = new Uint16Array(320); /* temporary storage for code lengths */
  this.work = new Uint16Array(288); /* work area for code table building */

  /*
   because we don't have pointers in js, we use lencode and distcode directly
   as buffers so we don't need codes
  */
  //this.codes = new Buf32(ENOUGH);       /* space for code tables */
  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
  this.sane = 0;                   /* if false, allow invalid distance too far */
  this.back = 0;                   /* bits back of last unprocessed length/lit */
  this.was = 0;                    /* initial length of match */
}

function inflateResetKeep(strm) {
  var state;

  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;
  strm.total_in = strm.total_out = state.total = 0;
  strm.msg = ''; /*Z_NULL*/
  if (state.wrap) {       /* to support ill-conceived Java test suite */
    strm.adler = state.wrap & 1;
  }
  state.mode = HEAD;
  state.last = 0;
  state.havedict = 0;
  state.dmax = 32768;
  state.head = null/*Z_NULL*/;
  state.hold = 0;
  state.bits = 0;
  //state.lencode = state.distcode = state.next = state.codes;
  state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);
  state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);

  state.sane = 1;
  state.back = -1;
  //Tracev((stderr, "inflate: reset\n"));
  return Z_OK;
}

function inflateReset(strm) {
  var state;

  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;
  state.wsize = 0;
  state.whave = 0;
  state.wnext = 0;
  return inflateResetKeep(strm);

}

function inflateReset2(strm, windowBits) {
  var wrap;
  var state;

  /* get the state */
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;

  /* extract wrap request from windowBits parameter */
  if (windowBits < 0) {
    wrap = 0;
    windowBits = -windowBits;
  }
  else {
    wrap = (windowBits >> 4) + 1;
    if (windowBits < 48) {
      windowBits &= 15;
    }
  }

  /* set number of window bits, free window if different */
  if (windowBits && (windowBits < 8 || windowBits > 15)) {
    return Z_STREAM_ERROR;
  }
  if (state.window !== null && state.wbits !== windowBits) {
    state.window = null;
  }

  /* update state and reset the rest of it */
  state.wrap = wrap;
  state.wbits = windowBits;
  return inflateReset(strm);
}

function inflateInit2(strm, windowBits) {
  var ret;
  var state;

  if (!strm) { return Z_STREAM_ERROR; }
  //strm.msg = Z_NULL;                 /* in case we return an error */

  state = new InflateState();

  //if (state === Z_NULL) return Z_MEM_ERROR;
  //Tracev((stderr, "inflate: allocated\n"));
  strm.state = state;
  state.window = null/*Z_NULL*/;
  ret = inflateReset2(strm, windowBits);
  if (ret !== Z_OK) {
    strm.state = null/*Z_NULL*/;
  }
  return ret;
}

/*
 Return state with length and distance decoding tables and index sizes set to
 fixed code decoding.  Normally this returns fixed tables from inffixed.h.
 If BUILDFIXED is defined, then instead this routine builds the tables the
 first time it's called, and returns those tables the first time and
 thereafter.  This reduces the size of the code by about 2K bytes, in
 exchange for a little execution time.  However, BUILDFIXED should not be
 used for threaded applications, since the rewriting of the tables and virgin
 may not be thread-safe.
 */
var virgin = true;

var lenfix;
var distfix;
// We have no pointers in JS, so keep tables separate

function fixedtables(state) {
  /* build fixed huffman tables if first call (may not be thread safe) */
  if (virgin) {
    var sym;

    lenfix = new Int32Array(512);
    distfix = new Int32Array(32);

    /* literal/length table */
    sym = 0;
    while (sym < 144) { state.lens[sym++] = 8; }
    while (sym < 256) { state.lens[sym++] = 9; }
    while (sym < 280) { state.lens[sym++] = 7; }
    while (sym < 288) { state.lens[sym++] = 8; }

    inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, { bits: 9 });

    /* distance table */
    sym = 0;
    while (sym < 32) { state.lens[sym++] = 5; }

    inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, { bits: 5 });

    /* do this just once */
    virgin = false;
  }

  state.lencode = lenfix;
  state.lenbits = 9;
  state.distcode = distfix;
  state.distbits = 5;
}


/*
 Update the window with the last wsize (normally 32K) bytes written before
 returning.  If window does not exist yet, create it.  This is only called
 when a window is already in use, or when output has been written during this
 inflate call, but the end of the deflate stream has not been reached yet.
 It is also called to create a window for dictionary data when a dictionary
 is loaded.

 Providing output buffers larger than 32K to inflate() should provide a speed
 advantage, since only the last 32K of output is copied to the sliding window
 upon return from inflate(), and since all distances after the first 32K of
 output will fall in the output data, making match copies simpler and faster.
 The advantage may be dependent on the size of the processor's data caches.
 */
function updatewindow(strm, src, end, copy) {
  var dist;
  var state = strm.state;

  /* if it hasn't been done already, allocate space for the window */
  if (state.window === null) {
    state.wsize = 1 << state.wbits;
    state.wnext = 0;
    state.whave = 0;

    state.window = new Uint8Array(state.wsize);
  }

  /* copy state->wsize or less output bytes into the circular window */
  if (copy >= state.wsize) {
    arraySet(state.window, src, end - state.wsize, state.wsize, 0);
    state.wnext = 0;
    state.whave = state.wsize;
  }
  else {
    dist = state.wsize - state.wnext;
    if (dist > copy) {
      dist = copy;
    }
    //zmemcpy(state->window + state->wnext, end - copy, dist);
    arraySet(state.window, src, end - copy, dist, state.wnext);
    copy -= dist;
    if (copy) {
      //zmemcpy(state->window, end - copy, copy);
      arraySet(state.window, src, end - copy, copy, 0);
      state.wnext = copy;
      state.whave = state.wsize;
    }
    else {
      state.wnext += dist;
      if (state.wnext === state.wsize) { state.wnext = 0; }
      if (state.whave < state.wsize) { state.whave += dist; }
    }
  }
  return 0;
}

function inflate(strm, flush) {
  var state;
  var input, output;          // input/output buffers
  var next;                   /* next input INDEX */
  var put;                    /* next output INDEX */
  var have, left;             /* available input and output */
  var hold;                   /* bit buffer */
  var bits;                   /* bits in bit buffer */
  var _in, _out;              /* save starting available input and output */
  var copy;                   /* number of stored or match bytes to copy */
  var from;                   /* where to copy match bytes from */
  var from_source;
  var here = 0;               /* current decoding table entry */
  var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  //var last;                   /* parent table entry */
  var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  var len;                    /* length to copy for repeats, bits to drop */
  var ret;                    /* return code */
  var hbuf = new Uint8Array(4);    /* buffer for gzip header crc calculation */
  var opts;

  var n; // temporary var for NEED_BITS

  var order = /* permutation of code lengths */
    [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];


  if (!strm || !strm.state || !strm.output ||
      (!strm.input && strm.avail_in !== 0)) {
    return Z_STREAM_ERROR;
  }

  state = strm.state;
  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */


  //--- LOAD() ---
  put = strm.next_out;
  output = strm.output;
  left = strm.avail_out;
  next = strm.next_in;
  input = strm.input;
  have = strm.avail_in;
  hold = state.hold;
  bits = state.bits;
  //---

  _in = have;
  _out = left;
  ret = Z_OK;

  inf_leave: // goto emulation
  for (;;) {
    switch (state.mode) {
    case HEAD:
      if (state.wrap === 0) {
        state.mode = TYPEDO;
        break;
      }
      //=== NEEDBITS(16);
      while (bits < 16) {
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
      }
      //===//
      if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
        state.check = 0/*crc32(0L, Z_NULL, 0)*/;
        //=== CRC2(state.check, hold);
        hbuf[0] = hold & 0xff;
        hbuf[1] = (hold >>> 8) & 0xff;
        state.check = crc32(state.check, hbuf, 2, 0);
        //===//

        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        state.mode = FLAGS;
        break;
      }
      state.flags = 0;           /* expect zlib header */
      if (state.head) {
        state.head.done = false;
      }
      if (!(state.wrap & 1) ||   /* check if zlib header allowed */
        (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
        strm.msg = 'incorrect header check';
        state.mode = BAD;
        break;
      }
      if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
        strm.msg = 'unknown compression method';
        state.mode = BAD;
        break;
      }
      //--- DROPBITS(4) ---//
      hold >>>= 4;
      bits -= 4;
      //---//
      len = (hold & 0x0f)/*BITS(4)*/ + 8;
      if (state.wbits === 0) {
        state.wbits = len;
      }
      else if (len > state.wbits) {
        strm.msg = 'invalid window size';
        state.mode = BAD;
        break;
      }
      state.dmax = 1 << len;
      //Tracev((stderr, "inflate:   zlib header ok\n"));
      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
      state.mode = hold & 0x200 ? DICTID : TYPE;
      //=== INITBITS();
      hold = 0;
      bits = 0;
      //===//
      break;
    case FLAGS:
      //=== NEEDBITS(16); */
      while (bits < 16) {
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
      }
      //===//
      state.flags = hold;
      if ((state.flags & 0xff) !== Z_DEFLATED) {
        strm.msg = 'unknown compression method';
        state.mode = BAD;
        break;
      }
      if (state.flags & 0xe000) {
        strm.msg = 'unknown header flags set';
        state.mode = BAD;
        break;
      }
      if (state.head) {
        state.head.text = ((hold >> 8) & 1);
      }
      if (state.flags & 0x0200) {
        //=== CRC2(state.check, hold);
        hbuf[0] = hold & 0xff;
        hbuf[1] = (hold >>> 8) & 0xff;
        state.check = crc32(state.check, hbuf, 2, 0);
        //===//
      }
      //=== INITBITS();
      hold = 0;
      bits = 0;
      //===//
      state.mode = TIME;
      /* falls through */
    case TIME:
      //=== NEEDBITS(32); */
      while (bits < 32) {
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
      }
      //===//
      if (state.head) {
        state.head.time = hold;
      }
      if (state.flags & 0x0200) {
        //=== CRC4(state.check, hold)
        hbuf[0] = hold & 0xff;
        hbuf[1] = (hold >>> 8) & 0xff;
        hbuf[2] = (hold >>> 16) & 0xff;
        hbuf[3] = (hold >>> 24) & 0xff;
        state.check = crc32(state.check, hbuf, 4, 0);
        //===
      }
      //=== INITBITS();
      hold = 0;
      bits = 0;
      //===//
      state.mode = OS;
      /* falls through */
    case OS:
      //=== NEEDBITS(16); */
      while (bits < 16) {
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
      }
      //===//
      if (state.head) {
        state.head.xflags = (hold & 0xff);
        state.head.os = (hold >> 8);
      }
      if (state.flags & 0x0200) {
        //=== CRC2(state.check, hold);
        hbuf[0] = hold & 0xff;
        hbuf[1] = (hold >>> 8) & 0xff;
        state.check = crc32(state.check, hbuf, 2, 0);
        //===//
      }
      //=== INITBITS();
      hold = 0;
      bits = 0;
      //===//
      state.mode = EXLEN;
      /* falls through */
    case EXLEN:
      if (state.flags & 0x0400) {
        //=== NEEDBITS(16); */
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.length = hold;
        if (state.head) {
          state.head.extra_len = hold;
        }
        if (state.flags & 0x0200) {
          //=== CRC2(state.check, hold);
          hbuf[0] = hold & 0xff;
          hbuf[1] = (hold >>> 8) & 0xff;
          state.check = crc32(state.check, hbuf, 2, 0);
          //===//
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
      }
      else if (state.head) {
        state.head.extra = null/*Z_NULL*/;
      }
      state.mode = EXTRA;
      /* falls through */
    case EXTRA:
      if (state.flags & 0x0400) {
        copy = state.length;
        if (copy > have) { copy = have; }
        if (copy) {
          if (state.head) {
            len = state.head.extra_len - state.length;
            if (!state.head.extra) {
              // Use untyped array for more conveniend processing later
              state.head.extra = new Array(state.head.extra_len);
            }
            arraySet(
              state.head.extra,
              input,
              next,
              // extra field is limited to 65536 bytes
              // - no need for additional size check
              copy,
              /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
              len
            );
            //zmemcpy(state.head.extra + len, next,
            //        len + copy > state.head.extra_max ?
            //        state.head.extra_max - len : copy);
          }
          if (state.flags & 0x0200) {
            state.check = crc32(state.check, input, copy, next);
          }
          have -= copy;
          next += copy;
          state.length -= copy;
        }
        if (state.length) { break inf_leave; }
      }
      state.length = 0;
      state.mode = NAME;
      /* falls through */
    case NAME:
      if (state.flags & 0x0800) {
        if (have === 0) { break inf_leave; }
        copy = 0;
        do {
          // TODO: 2 or 1 bytes?
          len = input[next + copy++];
          /* use constant limit because in js we should not preallocate memory */
          if (state.head && len &&
              (state.length < 65536 /*state.head.name_max*/)) {
            state.head.name += String.fromCharCode(len);
          }
        } while (len && copy < have);

        if (state.flags & 0x0200) {
          state.check = crc32(state.check, input, copy, next);
        }
        have -= copy;
        next += copy;
        if (len) { break inf_leave; }
      }
      else if (state.head) {
        state.head.name = null;
      }
      state.length = 0;
      state.mode = COMMENT;
      /* falls through */
    case COMMENT:
      if (state.flags & 0x1000) {
        if (have === 0) { break inf_leave; }
        copy = 0;
        do {
          len = input[next + copy++];
          /* use constant limit because in js we should not preallocate memory */
          if (state.head && len &&
              (state.length < 65536 /*state.head.comm_max*/)) {
            state.head.comment += String.fromCharCode(len);
          }
        } while (len && copy < have);
        if (state.flags & 0x0200) {
          state.check = crc32(state.check, input, copy, next);
        }
        have -= copy;
        next += copy;
        if (len) { break inf_leave; }
      }
      else if (state.head) {
        state.head.comment = null;
      }
      state.mode = HCRC;
      /* falls through */
    case HCRC:
      if (state.flags & 0x0200) {
        //=== NEEDBITS(16); */
        while (bits < 16) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if (hold !== (state.check & 0xffff)) {
          strm.msg = 'header crc mismatch';
          state.mode = BAD;
          break;
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
      }
      if (state.head) {
        state.head.hcrc = ((state.flags >> 9) & 1);
        state.head.done = true;
      }
      strm.adler = state.check = 0;
      state.mode = TYPE;
      break;
    case DICTID:
      //=== NEEDBITS(32); */
      while (bits < 32) {
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
      }
      //===//
      strm.adler = state.check = zswap32(hold);
      //=== INITBITS();
      hold = 0;
      bits = 0;
      //===//
      state.mode = DICT;
      /* falls through */
    case DICT:
      if (state.havedict === 0) {
        //--- RESTORE() ---
        strm.next_out = put;
        strm.avail_out = left;
        strm.next_in = next;
        strm.avail_in = have;
        state.hold = hold;
        state.bits = bits;
        //---
        return Z_NEED_DICT;
      }
      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
      state.mode = TYPE;
      /* falls through */
    case TYPE:
      if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
      /* falls through */
    case TYPEDO:
      if (state.last) {
        //--- BYTEBITS() ---//
        hold >>>= bits & 7;
        bits -= bits & 7;
        //---//
        state.mode = CHECK;
        break;
      }
      //=== NEEDBITS(3); */
      while (bits < 3) {
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
      }
      //===//
      state.last = (hold & 0x01)/*BITS(1)*/;
      //--- DROPBITS(1) ---//
      hold >>>= 1;
      bits -= 1;
      //---//

      switch ((hold & 0x03)/*BITS(2)*/) {
      case 0:                             /* stored block */
        //Tracev((stderr, "inflate:     stored block%s\n",
        //        state.last ? " (last)" : ""));
        state.mode = STORED;
        break;
      case 1:                             /* fixed block */
        fixedtables(state);
        //Tracev((stderr, "inflate:     fixed codes block%s\n",
        //        state.last ? " (last)" : ""));
        state.mode = LEN_;             /* decode codes */
        if (flush === Z_TREES) {
          //--- DROPBITS(2) ---//
          hold >>>= 2;
          bits -= 2;
          //---//
          break inf_leave;
        }
        break;
      case 2:                             /* dynamic block */
        //Tracev((stderr, "inflate:     dynamic codes block%s\n",
        //        state.last ? " (last)" : ""));
        state.mode = TABLE;
        break;
      case 3:
        strm.msg = 'invalid block type';
        state.mode = BAD;
      }
      //--- DROPBITS(2) ---//
      hold >>>= 2;
      bits -= 2;
      //---//
      break;
    case STORED:
      //--- BYTEBITS() ---// /* go to byte boundary */
      hold >>>= bits & 7;
      bits -= bits & 7;
      //---//
      //=== NEEDBITS(32); */
      while (bits < 32) {
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
      }
      //===//
      if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
        strm.msg = 'invalid stored block lengths';
        state.mode = BAD;
        break;
      }
      state.length = hold & 0xffff;
      //Tracev((stderr, "inflate:       stored length %u\n",
      //        state.length));
      //=== INITBITS();
      hold = 0;
      bits = 0;
      //===//
      state.mode = COPY_;
      if (flush === Z_TREES) { break inf_leave; }
      /* falls through */
    case COPY_:
      state.mode = COPY;
      /* falls through */
    case COPY:
      copy = state.length;
      if (copy) {
        if (copy > have) { copy = have; }
        if (copy > left) { copy = left; }
        if (copy === 0) { break inf_leave; }
        //--- zmemcpy(put, next, copy); ---
        arraySet(output, input, next, copy, put);
        //---//
        have -= copy;
        next += copy;
        left -= copy;
        put += copy;
        state.length -= copy;
        break;
      }
      //Tracev((stderr, "inflate:       stored end\n"));
      state.mode = TYPE;
      break;
    case TABLE:
      //=== NEEDBITS(14); */
      while (bits < 14) {
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
      }
      //===//
      state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
      //--- DROPBITS(5) ---//
      hold >>>= 5;
      bits -= 5;
      //---//
      state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
      //--- DROPBITS(5) ---//
      hold >>>= 5;
      bits -= 5;
      //---//
      state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
      //--- DROPBITS(4) ---//
      hold >>>= 4;
      bits -= 4;
      //---//
//#ifndef PKZIP_BUG_WORKAROUND
      if (state.nlen > 286 || state.ndist > 30) {
        strm.msg = 'too many length or distance symbols';
        state.mode = BAD;
        break;
      }
//#endif
      //Tracev((stderr, "inflate:       table sizes ok\n"));
      state.have = 0;
      state.mode = LENLENS;
      /* falls through */
    case LENLENS:
      while (state.have < state.ncode) {
        //=== NEEDBITS(3);
        while (bits < 3) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
        //--- DROPBITS(3) ---//
        hold >>>= 3;
        bits -= 3;
        //---//
      }
      while (state.have < 19) {
        state.lens[order[state.have++]] = 0;
      }
      // We have separate tables & no pointers. 2 commented lines below not needed.
      //state.next = state.codes;
      //state.lencode = state.next;
      // Switch to use dynamic table
      state.lencode = state.lendyn;
      state.lenbits = 7;

      opts = { bits: state.lenbits };
      ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
      state.lenbits = opts.bits;

      if (ret) {
        strm.msg = 'invalid code lengths set';
        state.mode = BAD;
        break;
      }
      //Tracev((stderr, "inflate:       code lengths ok\n"));
      state.have = 0;
      state.mode = CODELENS;
      /* falls through */
    case CODELENS:
      while (state.have < state.nlen + state.ndist) {
        for (;;) {
          here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
          here_bits = here >>> 24;
          here_op = (here >>> 16) & 0xff;
          here_val = here & 0xffff;

          if ((here_bits) <= bits) { break; }
          //--- PULLBYTE() ---//
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
          //---//
        }
        if (here_val < 16) {
          //--- DROPBITS(here.bits) ---//
          hold >>>= here_bits;
          bits -= here_bits;
          //---//
          state.lens[state.have++] = here_val;
        }
        else {
          if (here_val === 16) {
            //=== NEEDBITS(here.bits + 2);
            n = here_bits + 2;
            while (bits < n) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            //--- DROPBITS(here.bits) ---//
            hold >>>= here_bits;
            bits -= here_bits;
            //---//
            if (state.have === 0) {
              strm.msg = 'invalid bit length repeat';
              state.mode = BAD;
              break;
            }
            len = state.lens[state.have - 1];
            copy = 3 + (hold & 0x03);//BITS(2);
            //--- DROPBITS(2) ---//
            hold >>>= 2;
            bits -= 2;
            //---//
          }
          else if (here_val === 17) {
            //=== NEEDBITS(here.bits + 3);
            n = here_bits + 3;
            while (bits < n) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            //--- DROPBITS(here.bits) ---//
            hold >>>= here_bits;
            bits -= here_bits;
            //---//
            len = 0;
            copy = 3 + (hold & 0x07);//BITS(3);
            //--- DROPBITS(3) ---//
            hold >>>= 3;
            bits -= 3;
            //---//
          }
          else {
            //=== NEEDBITS(here.bits + 7);
            n = here_bits + 7;
            while (bits < n) {
              if (have === 0) { break inf_leave; }
              have--;
              hold += input[next++] << bits;
              bits += 8;
            }
            //===//
            //--- DROPBITS(here.bits) ---//
            hold >>>= here_bits;
            bits -= here_bits;
            //---//
            len = 0;
            copy = 11 + (hold & 0x7f);//BITS(7);
            //--- DROPBITS(7) ---//
            hold >>>= 7;
            bits -= 7;
            //---//
          }
          if (state.have + copy > state.nlen + state.ndist) {
            strm.msg = 'invalid bit length repeat';
            state.mode = BAD;
            break;
          }
          while (copy--) {
            state.lens[state.have++] = len;
          }
        }
      }

      /* handle error breaks in while */
      if (state.mode === BAD) { break; }

      /* check for end-of-block code (better have one) */
      if (state.lens[256] === 0) {
        strm.msg = 'invalid code -- missing end-of-block';
        state.mode = BAD;
        break;
      }

      /* build code tables -- note: do not change the lenbits or distbits
         values here (9 and 6) without reading the comments in inftrees.h
         concerning the ENOUGH constants, which depend on those values */
      state.lenbits = 9;

      opts = { bits: state.lenbits };
      ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
      // We have separate tables & no pointers. 2 commented lines below not needed.
      // state.next_index = opts.table_index;
      state.lenbits = opts.bits;
      // state.lencode = state.next;

      if (ret) {
        strm.msg = 'invalid literal/lengths set';
        state.mode = BAD;
        break;
      }

      state.distbits = 6;
      //state.distcode.copy(state.codes);
      // Switch to use dynamic table
      state.distcode = state.distdyn;
      opts = { bits: state.distbits };
      ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
      // We have separate tables & no pointers. 2 commented lines below not needed.
      // state.next_index = opts.table_index;
      state.distbits = opts.bits;
      // state.distcode = state.next;

      if (ret) {
        strm.msg = 'invalid distances set';
        state.mode = BAD;
        break;
      }
      //Tracev((stderr, 'inflate:       codes ok\n'));
      state.mode = LEN_;
      if (flush === Z_TREES) { break inf_leave; }
      /* falls through */
    case LEN_:
      state.mode = LEN;
      /* falls through */
    case LEN:
      if (have >= 6 && left >= 258) {
        //--- RESTORE() ---
        strm.next_out = put;
        strm.avail_out = left;
        strm.next_in = next;
        strm.avail_in = have;
        state.hold = hold;
        state.bits = bits;
        //---
        inflate_fast(strm, _out);
        //--- LOAD() ---
        put = strm.next_out;
        output = strm.output;
        left = strm.avail_out;
        next = strm.next_in;
        input = strm.input;
        have = strm.avail_in;
        hold = state.hold;
        bits = state.bits;
        //---

        if (state.mode === TYPE) {
          state.back = -1;
        }
        break;
      }
      state.back = 0;
      for (;;) {
        here = state.lencode[hold & ((1 << state.lenbits) - 1)];  /*BITS(state.lenbits)*/
        here_bits = here >>> 24;
        here_op = (here >>> 16) & 0xff;
        here_val = here & 0xffff;

        if (here_bits <= bits) { break; }
        //--- PULLBYTE() ---//
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
        //---//
      }
      if (here_op && (here_op & 0xf0) === 0) {
        last_bits = here_bits;
        last_op = here_op;
        last_val = here_val;
        for (;;) {
          here = state.lencode[last_val +
                  ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
          here_bits = here >>> 24;
          here_op = (here >>> 16) & 0xff;
          here_val = here & 0xffff;

          if ((last_bits + here_bits) <= bits) { break; }
          //--- PULLBYTE() ---//
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
          //---//
        }
        //--- DROPBITS(last.bits) ---//
        hold >>>= last_bits;
        bits -= last_bits;
        //---//
        state.back += last_bits;
      }
      //--- DROPBITS(here.bits) ---//
      hold >>>= here_bits;
      bits -= here_bits;
      //---//
      state.back += here_bits;
      state.length = here_val;
      if (here_op === 0) {
        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
        //        "inflate:         literal '%c'\n" :
        //        "inflate:         literal 0x%02x\n", here.val));
        state.mode = LIT;
        break;
      }
      if (here_op & 32) {
        //Tracevv((stderr, "inflate:         end of block\n"));
        state.back = -1;
        state.mode = TYPE;
        break;
      }
      if (here_op & 64) {
        strm.msg = 'invalid literal/length code';
        state.mode = BAD;
        break;
      }
      state.extra = here_op & 15;
      state.mode = LENEXT;
      /* falls through */
    case LENEXT:
      if (state.extra) {
        //=== NEEDBITS(state.extra);
        n = state.extra;
        while (bits < n) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
        //--- DROPBITS(state.extra) ---//
        hold >>>= state.extra;
        bits -= state.extra;
        //---//
        state.back += state.extra;
      }
      //Tracevv((stderr, "inflate:         length %u\n", state.length));
      state.was = state.length;
      state.mode = DIST;
      /* falls through */
    case DIST:
      for (;;) {
        here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
        here_bits = here >>> 24;
        here_op = (here >>> 16) & 0xff;
        here_val = here & 0xffff;

        if ((here_bits) <= bits) { break; }
        //--- PULLBYTE() ---//
        if (have === 0) { break inf_leave; }
        have--;
        hold += input[next++] << bits;
        bits += 8;
        //---//
      }
      if ((here_op & 0xf0) === 0) {
        last_bits = here_bits;
        last_op = here_op;
        last_val = here_val;
        for (;;) {
          here = state.distcode[last_val +
                  ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
          here_bits = here >>> 24;
          here_op = (here >>> 16) & 0xff;
          here_val = here & 0xffff;

          if ((last_bits + here_bits) <= bits) { break; }
          //--- PULLBYTE() ---//
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
          //---//
        }
        //--- DROPBITS(last.bits) ---//
        hold >>>= last_bits;
        bits -= last_bits;
        //---//
        state.back += last_bits;
      }
      //--- DROPBITS(here.bits) ---//
      hold >>>= here_bits;
      bits -= here_bits;
      //---//
      state.back += here_bits;
      if (here_op & 64) {
        strm.msg = 'invalid distance code';
        state.mode = BAD;
        break;
      }
      state.offset = here_val;
      state.extra = (here_op) & 15;
      state.mode = DISTEXT;
      /* falls through */
    case DISTEXT:
      if (state.extra) {
        //=== NEEDBITS(state.extra);
        n = state.extra;
        while (bits < n) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
        //--- DROPBITS(state.extra) ---//
        hold >>>= state.extra;
        bits -= state.extra;
        //---//
        state.back += state.extra;
      }
//#ifdef INFLATE_STRICT
      if (state.offset > state.dmax) {
        strm.msg = 'invalid distance too far back';
        state.mode = BAD;
        break;
      }
//#endif
      //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
      state.mode = MATCH;
      /* falls through */
    case MATCH:
      if (left === 0) { break inf_leave; }
      copy = _out - left;
      if (state.offset > copy) {         /* copy from window */
        copy = state.offset - copy;
        if (copy > state.whave) {
          if (state.sane) {
            strm.msg = 'invalid distance too far back';
            state.mode = BAD;
            break;
          }
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
//          Trace((stderr, "inflate.c too far\n"));
//          copy -= state.whave;
//          if (copy > state.length) { copy = state.length; }
//          if (copy > left) { copy = left; }
//          left -= copy;
//          state.length -= copy;
//          do {
//            output[put++] = 0;
//          } while (--copy);
//          if (state.length === 0) { state.mode = LEN; }
//          break;
//#endif
        }
        if (copy > state.wnext) {
          copy -= state.wnext;
          from = state.wsize - copy;
        }
        else {
          from = state.wnext - copy;
        }
        if (copy > state.length) { copy = state.length; }
        from_source = state.window;
      }
      else {                              /* copy from output */
        from_source = output;
        from = put - state.offset;
        copy = state.length;
      }
      if (copy > left) { copy = left; }
      left -= copy;
      state.length -= copy;
      do {
        output[put++] = from_source[from++];
      } while (--copy);
      if (state.length === 0) { state.mode = LEN; }
      break;
    case LIT:
      if (left === 0) { break inf_leave; }
      output[put++] = state.length;
      left--;
      state.mode = LEN;
      break;
    case CHECK:
      if (state.wrap) {
        //=== NEEDBITS(32);
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          // Use '|' insdead of '+' to make sure that result is signed
          hold |= input[next++] << bits;
          bits += 8;
        }
        //===//
        _out -= left;
        strm.total_out += _out;
        state.total += _out;
        if (_out) {
          strm.adler = state.check =
              /*UPDATE(state.check, put - _out, _out);*/
              (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));

        }
        _out = left;
        // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
        if ((state.flags ? hold : zswap32(hold)) !== state.check) {
          strm.msg = 'incorrect data check';
          state.mode = BAD;
          break;
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        //Tracev((stderr, "inflate:   check matches trailer\n"));
      }
      state.mode = LENGTH;
      /* falls through */
    case LENGTH:
      if (state.wrap && state.flags) {
        //=== NEEDBITS(32);
        while (bits < 32) {
          if (have === 0) { break inf_leave; }
          have--;
          hold += input[next++] << bits;
          bits += 8;
        }
        //===//
        if (hold !== (state.total & 0xffffffff)) {
          strm.msg = 'incorrect length check';
          state.mode = BAD;
          break;
        }
        //=== INITBITS();
        hold = 0;
        bits = 0;
        //===//
        //Tracev((stderr, "inflate:   length matches trailer\n"));
      }
      state.mode = DONE;
      /* falls through */
    case DONE:
      ret = Z_STREAM_END;
      break inf_leave;
    case BAD:
      ret = Z_DATA_ERROR;
      break inf_leave;
    case MEM:
      return Z_MEM_ERROR;
    case SYNC:
      /* falls through */
    default:
      return Z_STREAM_ERROR;
    }
  }

  // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"

  /*
     Return from inflate(), updating the total counts and the check value.
     If there was no progress during the inflate() call, return a buffer
     error.  Call updatewindow() to create and/or update the window state.
     Note: a memory error from inflate() is non-recoverable.
   */

  //--- RESTORE() ---
  strm.next_out = put;
  strm.avail_out = left;
  strm.next_in = next;
  strm.avail_in = have;
  state.hold = hold;
  state.bits = bits;
  //---

  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
                      (state.mode < CHECK || flush !== Z_FINISH))) {
    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;
  }
  _in -= strm.avail_in;
  _out -= strm.avail_out;
  strm.total_in += _in;
  strm.total_out += _out;
  state.total += _out;
  if (state.wrap && _out) {
    strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
      (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  }
  strm.data_type = state.bits + (state.last ? 64 : 0) +
                    (state.mode === TYPE ? 128 : 0) +
                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
    ret = Z_BUF_ERROR;
  }
  return ret;
}

function inflateEnd(strm) {

  if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
    return Z_STREAM_ERROR;
  }

  var state = strm.state;
  if (state.window) {
    state.window = null;
  }
  strm.state = null;
  return Z_OK;
}

function inflateGetHeader(strm, head) {
  var state;

  /* check state */
  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  state = strm.state;
  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }

  /* save header structure */
  state.head = head;
  head.done = false;
  return Z_OK;
}

function inflateSetDictionary(strm, dictionary) {
  var dictLength = dictionary.length;

  var state;
  var dictid;
  var ret;

  /* check state */
  if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  state = strm.state;

  if (state.wrap !== 0 && state.mode !== DICT) {
    return Z_STREAM_ERROR;
  }

  /* check for correct dictionary identifier */
  if (state.mode === DICT) {
    dictid = 1; /* adler32(0, null, 0)*/
    /* dictid = adler32(dictid, dictionary, dictLength); */
    dictid = adler32(dictid, dictionary, dictLength, 0);
    if (dictid !== state.check) {
      return Z_DATA_ERROR;
    }
  }
  /* copy dictionary to window using updatewindow(), which will amend the
   existing dictionary if appropriate */
  ret = updatewindow(strm, dictionary, dictLength, dictLength);
  if (ret) {
    state.mode = MEM;
    return Z_MEM_ERROR;
  }
  state.havedict = 1;
  // Tracev((stderr, "inflate:   dictionary set\n"));
  return Z_OK;
}

// String encode/decode helpers
// 'use strict';


// var utils = require('./common');


// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;

try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }


// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new Uint8Array(256);
for (var q = 0; q < 256; q++) {
  _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start


// convert string to array (typed, when possible)
function string2buf(str) {
  var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;

  // count binary size
  for (m_pos = 0; m_pos < str_len; m_pos++) {
    c = str.charCodeAt(m_pos);
    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
      c2 = str.charCodeAt(m_pos + 1);
      if ((c2 & 0xfc00) === 0xdc00) {
        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
        m_pos++;
      }
    }
    buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  }

  // allocate buffer
  buf = new Uint8Array(buf_len);

  // convert
  for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
    c = str.charCodeAt(m_pos);
    if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
      c2 = str.charCodeAt(m_pos + 1);
      if ((c2 & 0xfc00) === 0xdc00) {
        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
        m_pos++;
      }
    }
    if (c < 0x80) {
      /* one byte */
      buf[i++] = c;
    } else if (c < 0x800) {
      /* two bytes */
      buf[i++] = 0xC0 | (c >>> 6);
      buf[i++] = 0x80 | (c & 0x3f);
    } else if (c < 0x10000) {
      /* three bytes */
      buf[i++] = 0xE0 | (c >>> 12);
      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
      buf[i++] = 0x80 | (c & 0x3f);
    } else {
      /* four bytes */
      buf[i++] = 0xf0 | (c >>> 18);
      buf[i++] = 0x80 | (c >>> 12 & 0x3f);
      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
      buf[i++] = 0x80 | (c & 0x3f);
    }
  }

  return buf;
}

// Helper (used in 2 places)
function _buf2binstring(buf, len) {
  // use fallback for big arrays to avoid stack overflow
  if (len < 65537) {
    if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
      return String.fromCharCode.apply(null, shrinkBuf(buf, len));
    }
  }

  var result = '';
  for (var i = 0; i < len; i++) {
    result += String.fromCharCode(buf[i]);
  }
  return result;
}


// Convert binary string (typed, when possible)
function binstring2buf(str) {
  var buf = new Uint8Array(str.length);
  for (var i = 0, len = buf.length; i < len; i++) {
    buf[i] = str.charCodeAt(i);
  }
  return buf;
}


// convert array to string
function buf2string(buf, max) {
  var i, out, c, c_len;
  var len = max || buf.length;

  // Reserve max possible length (2 words per char)
  // NB: by unknown reasons, Array is significantly faster for
  //     String.fromCharCode.apply than Uint16Array.
  var utf16buf = new Array(len * 2);

  for (out = 0, i = 0; i < len;) {
    c = buf[i++];
    // quick process ascii
    if (c < 0x80) { utf16buf[out++] = c; continue; }

    c_len = _utf8len[c];
    // skip 5 & 6 byte codes
    if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }

    // apply mask on first byte
    c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
    // join the rest
    while (c_len > 1 && i < len) {
      c = (c << 6) | (buf[i++] & 0x3f);
      c_len--;
    }

    // terminated by end of string?
    if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }

    if (c < 0x10000) {
      utf16buf[out++] = c;
    } else {
      c -= 0x10000;
      utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
      utf16buf[out++] = 0xdc00 | (c & 0x3ff);
    }
  }

  return _buf2binstring(utf16buf, out);
}


// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max   - length limit (mandatory);
function utf8border(buf, max) {
  var pos;

  max = max || buf.length;
  if (max > buf.length) { max = buf.length; }

  // go back from last position, until start of sequence found
  pos = max - 1;
  while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }

  // Fuckup - very small and broken sequence,
  // return max, because we should return something anyway.
  if (pos < 0) { return max; }

  // If we came to start of buffer - that means vuffer is too small,
  // return max too.
  if (pos === 0) { return max; }

  return (pos + _utf8len[buf[pos]] > max) ? pos : max;
}

/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH        = 0;
var Z_SYNC_FLUSH      = 2;
var Z_FINISH$1          = 4;
/* Return codes for the compression/decompression functions. Negative values
  * are errors, positive values are used for special but normal events.
  */
var Z_OK$1              =  0;
var Z_STREAM_END$1      =  1;
var Z_NEED_DICT$1       =  2;
//export var Z_MEM_ERROR     = -4;
var Z_BUF_ERROR$1       = -5;

// 'use strict';

var messages = {
  2:      'need dictionary',     /* Z_NEED_DICT       2  */
  1:      'stream end',          /* Z_STREAM_END      1  */
  0:      '',                    /* Z_OK              0  */
  '-1':   'file error',          /* Z_ERRNO         (-1) */
  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
};

// 'use strict';


function ZStream() {
  /* next input byte */
  this.input = null; // JS specific, because we have no pointers
  this.next_in = 0;
  /* number of bytes available at input */
  this.avail_in = 0;
  /* total number of input bytes read so far */
  this.total_in = 0;
  /* next output byte should be put there */
  this.output = null; // JS specific, because we have no pointers
  this.next_out = 0;
  /* remaining free space at output */
  this.avail_out = 0;
  /* total number of bytes output so far */
  this.total_out = 0;
  /* last error message, NULL if no error */
  this.msg = ''/*Z_NULL*/;
  /* not visible by applications */
  this.state = null;
  /* best guess about the data type: binary or text */
  this.data_type = 2/*Z_UNKNOWN*/;
  /* adler32 value of the uncompressed data */
  this.adler = 0;
}

// 'use strict';


function GZheader() {
  /* true if compressed data believed to be text */
  this.text       = 0;
  /* modification time */
  this.time       = 0;
  /* extra flags (not used when writing a gzip file) */
  this.xflags     = 0;
  /* operating system */
  this.os         = 0;
  /* pointer to extra field or Z_NULL if none */
  this.extra      = null;
  /* extra field length (valid if extra != Z_NULL) */
  this.extra_len  = 0; // Actually, we don't need it in JS,
                       // but leave for few code modifications

  //
  // Setup limits is not necessary because in js we should not preallocate memory
  // for inflate use constant limit in 65536 bytes
  //

  /* space at extra (only when reading header) */
  // this.extra_max  = 0;
  /* pointer to zero-terminated file name or Z_NULL */
  this.name       = '';
  /* space at name (only when reading header) */
  // this.name_max   = 0;
  /* pointer to zero-terminated comment or Z_NULL */
  this.comment    = '';
  /* space at comment (only when reading header) */
  // this.comm_max   = 0;
  /* true if there was or will be a header crc */
  this.hcrc       = 0;
  /* true when done reading gzip header (not used when writing a gzip file) */
  this.done       = false;
}

// 'use strict';


// var zlib_inflate = require('./zlib/inflate');
// var utils        = require('./utils/common');
// var strings      = require('./utils/strings');
// var c            = require('./zlib/constants');
// var msg          = require('./zlib/messages');
// var ZStream      = require('./zlib/zstream');
// var GZheader     = require('./zlib/gzheader');

var toString = Object.prototype.toString;

/**
 * class Inflate
 *
 * Generic JS-style wrapper for zlib calls. If you don't need
 * streaming behaviour - use more simple functions: [[inflate]]
 * and [[inflateRaw]].
 **/

/* internal
 * inflate.chunks -> Array
 *
 * Chunks of output data, if [[Inflate#onData]] not overriden.
 **/

/**
 * Inflate.result -> Uint8Array|Array|String
 *
 * Uncompressed result, generated by default [[Inflate#onData]]
 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
 * push a chunk with explicit flush (call [[Inflate#push]] with
 * `Z_SYNC_FLUSH` param).
 **/

/**
 * Inflate.err -> Number
 *
 * Error code after inflate finished. 0 (Z_OK) on success.
 * Should be checked if broken data possible.
 **/

/**
 * Inflate.msg -> String
 *
 * Error message, if [[Inflate.err]] != 0
 **/


/**
 * new Inflate(options)
 * - options (Object): zlib inflate options.
 *
 * Creates new inflator instance with specified params. Throws exception
 * on bad params. Supported options:
 *
 * - `windowBits`
 * - `dictionary`
 *
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
 * for more information on these.
 *
 * Additional options, for internal needs:
 *
 * - `chunkSize` - size of generated data chunks (16K by default)
 * - `raw` (Boolean) - do raw inflate
 * - `to` (String) - if equal to 'string', then result will be converted
 *   from utf8 to utf16 (javascript) string. When string output requested,
 *   chunk length can differ from `chunkSize`, depending on content.
 *
 * By default, when no options set, autodetect deflate/gzip data format via
 * wrapper header.
 *
 * ##### Example:
 *
 * ```javascript
 * var pako = require('pako')
 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
 *
 * var inflate = new pako.Inflate({ level: 3});
 *
 * inflate.push(chunk1, false);
 * inflate.push(chunk2, true);  // true -> last chunk
 *
 * if (inflate.err) { throw new Error(inflate.err); }
 *
 * console.log(inflate.result);
 * ```
 **/
function Inflate(options) {
  if (!(this instanceof Inflate)) { return new Inflate(options); }

  this.options = assign({
    chunkSize: 16384,
    windowBits: 0,
    to: ''
  }, options || {});

  var opt = this.options;

  // Force window size for `raw` data, if not set directly,
  // because we have no header for autodetect.
  if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
    opt.windowBits = -opt.windowBits;
    if (opt.windowBits === 0) { opt.windowBits = -15; }
  }

  // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
      !(options && options.windowBits)) {
    opt.windowBits += 32;
  }

  // Gzip header has no info about windows size, we can do autodetect only
  // for deflate. So, if window size not set, force it to max when gzip possible
  if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
    // bit 3 (16) -> gzipped data
    // bit 4 (32) -> autodetect gzip/deflate
    if ((opt.windowBits & 15) === 0) {
      opt.windowBits |= 15;
    }
  }

  this.err    = 0;      // error code, if happens (0 = Z_OK)
  this.msg    = '';     // error message
  this.ended  = false;  // used to avoid multiple onEnd() calls
  this.chunks = [];     // chunks of compressed data

  this.strm   = new ZStream();
  this.strm.avail_out = 0;

  var status  = inflateInit2(
    this.strm,
    opt.windowBits
  );

  if (status !== Z_OK$1) {
    throw new Error(messages[status]);
  }

  this.header = new GZheader();

  inflateGetHeader(this.strm, this.header);
}

/**
 * Inflate#push(data[, mode]) -> Boolean
 * - data (Uint8Array|Array|ArrayBuffer|String): input data
 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
 *
 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
 * new output chunks. Returns `true` on success. The last data block must have
 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
 *
 * On fail call [[Inflate#onEnd]] with error code and return false.
 *
 * We strongly recommend to use `Uint8Array` on input for best speed (output
 * format is detected automatically). Also, don't skip last param and always
 * use the same type in your code (boolean or number). That will improve JS speed.
 *
 * For regular `Array`-s make sure all elements are [0..255].
 *
 * ##### Example
 *
 * ```javascript
 * push(chunk, false); // push one of data chunks
 * ...
 * push(chunk, true);  // push last chunk
 * ```
 **/
Inflate.prototype.push = function (data, mode) {
  var strm = this.strm;
  var chunkSize = this.options.chunkSize;
  var dictionary = this.options.dictionary;
  var status, _mode;
  var next_out_utf8, tail, utf8str;
  var dict;

  // Flag to properly process Z_BUF_ERROR on testing inflate call
  // when we check that all output data was flushed.
  var allowBufError = false;

  if (this.ended) { return false; }
  _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH$1 : Z_NO_FLUSH);

  // Convert data if needed
  if (typeof data === 'string') {
    // Only binary strings can be decompressed on practice
    strm.input = binstring2buf(data);
  } else if (toString.call(data) === '[object ArrayBuffer]') {
    strm.input = new Uint8Array(data);
  } else {
    strm.input = data;
  }

  strm.next_in = 0;
  strm.avail_in = strm.input.length;

  do {
    if (strm.avail_out === 0) {
      strm.output = new Uint8Array(chunkSize);
      strm.next_out = 0;
      strm.avail_out = chunkSize;
    }

    status = inflate(strm, Z_NO_FLUSH);    /* no bad return value */

    if (status === Z_NEED_DICT$1 && dictionary) {
      // Convert data if needed
      if (typeof dictionary === 'string') {
        dict = string2buf(dictionary);
      } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
        dict = new Uint8Array(dictionary);
      } else {
        dict = dictionary;
      }

      status = inflateSetDictionary(this.strm, dict);

    }

    if (status === Z_BUF_ERROR$1 && allowBufError === true) {
      status = Z_OK$1;
      allowBufError = false;
    }

    if (status !== Z_STREAM_END$1 && status !== Z_OK$1) {
      this.onEnd(status);
      this.ended = true;
      return false;
    }

    if (strm.next_out) {
      if (strm.avail_out === 0 || status === Z_STREAM_END$1 || (strm.avail_in === 0 && (_mode === Z_FINISH$1 || _mode === Z_SYNC_FLUSH))) {

        if (this.options.to === 'string') {

          next_out_utf8 = utf8border(strm.output, strm.next_out);

          tail = strm.next_out - next_out_utf8;
          utf8str = buf2string(strm.output, next_out_utf8);

          // move tail
          strm.next_out = tail;
          strm.avail_out = chunkSize - tail;
          if (tail) { arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }

          this.onData(utf8str);

        } else {
          this.onData(shrinkBuf(strm.output, strm.next_out));
        }
      }
    }

    // When no more input data, we should check that internal inflate buffers
    // are flushed. The only way to do it when avail_out = 0 - run one more
    // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
    // Here we set flag to process this error properly.
    //
    // NOTE. Deflate does not return error in this case and does not needs such
    // logic.
    if (strm.avail_in === 0 && strm.avail_out === 0) {
      allowBufError = true;
    }

  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END$1);

  if (status === Z_STREAM_END$1) {
    _mode = Z_FINISH$1;
  }

  // Finalize on the last chunk.
  if (_mode === Z_FINISH$1) {
    status = inflateEnd(this.strm);
    this.onEnd(status);
    this.ended = true;
    return status === Z_OK$1;
  }

  // callback interim results if Z_SYNC_FLUSH.
  if (_mode === Z_SYNC_FLUSH) {
    this.onEnd(Z_OK$1);
    strm.avail_out = 0;
    return true;
  }

  return true;
};


/**
 * Inflate#onData(chunk) -> Void
 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
 *   on js engine support. When string output requested, each chunk
 *   will be string.
 *
 * By default, stores data blocks in `chunks[]` property and glue
 * those in `onEnd`. Override this handler, if you need another behaviour.
 **/
Inflate.prototype.onData = function (chunk) {
  this.chunks.push(chunk);
};


/**
 * Inflate#onEnd(status) -> Void
 * - status (Number): inflate status. 0 (Z_OK) on success,
 *   other if not.
 *
 * Called either after you tell inflate that the input stream is
 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
 * or if an error happened. By default - join collected chunks,
 * free memory and fill `results` / `err` properties.
 **/
Inflate.prototype.onEnd = function (status) {
  // On success - join
  if (status === Z_OK$1) {
    if (this.options.to === 'string') {
      // Glue & convert here, until we teach pako to send
      // utf8 alligned strings to onData
      this.result = this.chunks.join('');
    } else {
      this.result = flattenChunks(this.chunks);
    }
  }
  this.chunks = [];
  this.err = status;
  this.msg = this.strm.msg;
};


/**
 * inflate(data[, options]) -> Uint8Array|Array|String
 * - data (Uint8Array|Array|String): input data to decompress.
 * - options (Object): zlib inflate options.
 *
 * Decompress `data` with inflate/ungzip and `options`. Autodetect
 * format via wrapper header by default. That's why we don't provide
 * separate `ungzip` method.
 *
 * Supported options are:
 *
 * - windowBits
 *
 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
 * for more information.
 *
 * Sugar (options):
 *
 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
 *   negative windowBits implicitly.
 * - `to` (String) - if equal to 'string', then result will be converted
 *   from utf8 to utf16 (javascript) string. When string output requested,
 *   chunk length can differ from `chunkSize`, depending on content.
 *
 *
 * ##### Example:
 *
 * ```javascript
 * var pako = require('pako')
 *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
 *   , output;
 *
 * try {
 *   output = pako.inflate(input);
 * } catch (err)
 *   console.log(err);
 * }
 * ```
 **/
function doInflate(input, options) {
  var inflator = new Inflate(options);

  inflator.push(input, true);

  // That will never happens, if you don't cheat with options :)
  if (inflator.err) { throw inflator.msg; }

  return inflator.result;
}

/**
 * @file Gzip Decompressor
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
function gzipDecompress(data) {
    var decompressedData;
    if (data instanceof ArrayBuffer) {
        data = new Uint8Array(data);
    }
    try {
        decompressedData = doInflate(data);
    }
    catch (e) {
        decompressedData = data; // assume it is already uncompressed
    }
    return decompressedData;
}
DecompressorRegistry.add('gz', gzipDecompress);

/**
 * @file Datasource
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
/**
 * Datasource base class
 * @interface
 */
var Datasource = function Datasource () {};

/**
 * @file RCSB Datasource
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var baseUrl$1 = '//files.rcsb.org/download/';
var mmtfBaseUrl = '//mmtf.rcsb.org/v1.0/';
var mmtfFullUrl = mmtfBaseUrl + 'full/';
var mmtfReducedUrl = mmtfBaseUrl + 'reduced/';
var RcsbDatasource = /*@__PURE__*/(function (Datasource$$1) {
    function RcsbDatasource () {
        Datasource$$1.apply(this, arguments);
    }

    if ( Datasource$$1 ) RcsbDatasource.__proto__ = Datasource$$1;
    RcsbDatasource.prototype = Object.create( Datasource$$1 && Datasource$$1.prototype );
    RcsbDatasource.prototype.constructor = RcsbDatasource;

    RcsbDatasource.prototype.getUrl = function getUrl (src) {
        // valid path are
        // XXXX.pdb, XXXX.pdb.gz, XXXX.cif, XXXX.cif.gz, XXXX.mmtf, XXXX.bb.mmtf
        // XXXX defaults to XXXX.cif
        var info = getFileInfo(src);
        var pdbid = info.name.substr(0, 4);
        var url;
        if (['pdb', 'cif'].includes(info.ext) &&
            (info.compressed === false || info.compressed === 'gz')) {
            url = baseUrl$1 + info.path;
        }
        else if (info.ext === 'mmtf') {
            if (info.base.endsWith('.bb')) {
                url = mmtfReducedUrl + pdbid;
            }
            else {
                url = mmtfFullUrl + pdbid;
            }
        }
        else if (!info.ext) {
            url = mmtfFullUrl + pdbid;
        }
        else {
            Log.warn('unsupported ext', info.ext);
            url = mmtfFullUrl + pdbid;
        }
        return getProtocol() + url;
    };
    RcsbDatasource.prototype.getExt = function getExt (src) {
        var ext = getFileInfo(src).ext;
        return ext ? ext : 'mmtf';
    };

    return RcsbDatasource;
}(Datasource));
DatasourceRegistry.add('rcsb', new RcsbDatasource());

/**
 * @file PubChem Datasource
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var baseUrl$2 = '//pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/';
var suffixUrl = '/SDF?record_type=3d';
var PubchemDatasource = /*@__PURE__*/(function (Datasource$$1) {
    function PubchemDatasource () {
        Datasource$$1.apply(this, arguments);
    }

    if ( Datasource$$1 ) PubchemDatasource.__proto__ = Datasource$$1;
    PubchemDatasource.prototype = Object.create( Datasource$$1 && Datasource$$1.prototype );
    PubchemDatasource.prototype.constructor = PubchemDatasource;

    PubchemDatasource.prototype.getUrl = function getUrl (src) {
        var info = getFileInfo(src);
        var cid = info.name;
        var url;
        if (!info.ext || info.ext === 'sdf') {
            url = baseUrl$2 + cid + suffixUrl;
        }
        else {
            Log.warn('unsupported ext', info.ext);
            url = baseUrl$2 + cid + suffixUrl;
        }
        return getProtocol() + url;
    };
    PubchemDatasource.prototype.getExt = function getExt (src) {
        var ext = getFileInfo(src).ext;
        return ext ? ext : 'sdf';
    };

    return PubchemDatasource;
}(Datasource));
DatasourceRegistry.add('pubchem', new PubchemDatasource());

/**
 * @file Pass Through Datasource
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var PassThroughDatasource = /*@__PURE__*/(function (Datasource$$1) {
    function PassThroughDatasource () {
        Datasource$$1.apply(this, arguments);
    }

    if ( Datasource$$1 ) PassThroughDatasource.__proto__ = Datasource$$1;
    PassThroughDatasource.prototype = Object.create( Datasource$$1 && Datasource$$1.prototype );
    PassThroughDatasource.prototype.constructor = PassThroughDatasource;

    PassThroughDatasource.prototype.getUrl = function getUrl (path) {
        return path;
    };
    PassThroughDatasource.prototype.getExt = function getExt (path) {
        return getFileInfo(path).ext;
    };

    return PassThroughDatasource;
}(Datasource));
DatasourceRegistry.add('ftp', new PassThroughDatasource());
DatasourceRegistry.add('http', new PassThroughDatasource());
DatasourceRegistry.add('https', new PassThroughDatasource());

/**
 * @file Static Datasource
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var reProtocol = /^((http|https|ftp):)*\/\//;
var StaticDatasource = /*@__PURE__*/(function (Datasource$$1) {
    function StaticDatasource(baseUrl) {
        if ( baseUrl === void 0 ) baseUrl = '';

        Datasource$$1.call(this);
        this.baseUrl = baseUrl;
    }

    if ( Datasource$$1 ) StaticDatasource.__proto__ = Datasource$$1;
    StaticDatasource.prototype = Object.create( Datasource$$1 && Datasource$$1.prototype );
    StaticDatasource.prototype.constructor = StaticDatasource;
    StaticDatasource.prototype.getUrl = function getUrl (src) {
        var info = getFileInfo(src);
        var url = this.baseUrl + info.path;
        if (!reProtocol.test(this.baseUrl)) {
            url = getAbsolutePath(url);
        }
        return url;
    };
    StaticDatasource.prototype.getExt = function getExt (src) {
        return getFileInfo(src).ext;
    };

    return StaticDatasource;
}(Datasource));

/**
 * @file MDsrv Datasource
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @private
 */
var MdsrvDatasource = /*@__PURE__*/(function (Datasource$$1) {
    function MdsrvDatasource(baseUrl) {
        if ( baseUrl === void 0 ) baseUrl = '';

        Datasource$$1.call(this);
        this.baseUrl = baseUrl;
    }

    if ( Datasource$$1 ) MdsrvDatasource.__proto__ = Datasource$$1;
    MdsrvDatasource.prototype = Object.create( Datasource$$1 && Datasource$$1.prototype );
    MdsrvDatasource.prototype.constructor = MdsrvDatasource;
    MdsrvDatasource.prototype.getListing = function getListing (path) {
        if ( path === void 0 ) path = '';

        var url = (this.baseUrl) + "dir/" + path;
        if (url[url.length - 1] !== '/')
            { url += '/'; }
        return autoLoad(url, {
            ext: 'json'
        }).then(function (jsonData) { return ({
            path: path,
            data: jsonData.data
        }); });
    };
    MdsrvDatasource.prototype.getUrl = function getUrl (src) {
        var info = getFileInfo(src);
        return ((this.baseUrl) + "file/" + (info.path) + (info.query));
    };
    MdsrvDatasource.prototype.getCountUrl = function getCountUrl (src) {
        var info = getFileInfo(src);
        return ((this.baseUrl) + "traj/numframes/" + (info.path) + (info.query));
    };
    MdsrvDatasource.prototype.getFrameUrl = function getFrameUrl (src, frameIndex) {
        var info = getFileInfo(src);
        return ((this.baseUrl) + "traj/frame/" + frameIndex + "/" + (info.path) + (info.query));
    };
    MdsrvDatasource.prototype.getFrameParams = function getFrameParams (src, atomIndices) {
        return ("atomIndices=" + (atomIndices.join(';')));
    };
    MdsrvDatasource.prototype.getPathUrl = function getPathUrl (src, atomIndex) {
        var info = getFileInfo(src);
        return ((this.baseUrl) + "traj/path/" + atomIndex + "/" + (info.path) + (info.query));
    };
    MdsrvDatasource.prototype.getExt = function getExt (src) {
        return getFileInfo(src).ext;
    };

    return MdsrvDatasource;
}(Datasource));

/**
 * @file UI Parameters
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function BooleanParam() { return { type: 'boolean' }; }
function ColorParam() { return { type: 'color' }; }
function IntegerParam(max, min) {
    return { type: 'integer', max: max, min: min };
}
function NumberParam(precision, max, min) {
    return { type: 'number', precision: precision, max: max, min: min };
}
function RangeParam(step, max, min) {
    return { type: 'range', step: step, max: max, min: min };
}
function SelectParam() {
    var options = [], len = arguments.length;
    while ( len-- ) options[ len ] = arguments[ len ];

    return { type: 'select', options: options.reduce(function (o, k) {
        var obj;

        return (Object.assign(Object.assign({}, o), ( obj = {}, obj[k] = k, obj )));
    }, {}) };
}
var UIStageParameters = {
    backgroundColor: ColorParam(),
    quality: SelectParam('auto', 'low', 'medium', 'high'),
    sampleLevel: RangeParam(1, 5, -1),
    impostor: BooleanParam(),
    workerDefault: BooleanParam(),
    rotateSpeed: NumberParam(1, 10, 0),
    zoomSpeed: NumberParam(1, 10, 0),
    panSpeed: NumberParam(1, 10, 0),
    clipNear: RangeParam(1, 100, 0),
    clipFar: RangeParam(1, 100, 0),
    clipDist: IntegerParam(200, 0),
    clipMode: SelectParam('scene', 'camera'),
    clipScale: SelectParam('relative', 'absolute'),
    fogNear: RangeParam(1, 100, 0),
    fogFar: RangeParam(1, 100, 0),
    cameraType: SelectParam('perspective', 'orthographic', 'stereo'),
    cameraEyeSep: NumberParam(3, 1.0, 0.01),
    cameraFov: RangeParam(1, 120, 15),
    lightColor: ColorParam(),
    lightIntensity: NumberParam(2, 10, 0),
    ambientColor: ColorParam(),
    ambientIntensity: NumberParam(2, 10, 0),
    hoverTimeout: IntegerParam(10000, -1),
    tooltip: BooleanParam(),
    mousePreset: SelectParam.apply(void 0, Object.keys(MouseActionPresets))
};

var version$1 = "2.0.0-dev.39";

/**
 * @file Version
 * @private
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/**
 * Version name
 * @type {String}
 */
var Version = version$1;

/**
 * @file ngl
 * @private
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
if (!window.Promise) {
    window.Promise = __WEBPACK_IMPORTED_MODULE_4_promise_polyfill__["a" /* default */];
}


//# 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__(128);



// 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__(64);




// 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__(72);



// 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__(88);




// 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__(65);



// 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__(80);
/* 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) {

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;


/***/ }),
/* 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__(122);
/* 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__(123);
/* 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__(54);
/* 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__(55);
/* 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__(124);
/* 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__(56);
/* 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__(125);
/* 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__(126);
/* 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__(127);
/* 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__(57);
/* 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__(58);
/* 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__(129);
/* 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__(59);
/* 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__(60);
/* 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__(131);
/* 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__(65);
/* 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__(132);
/* 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__(134);
/* 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__(135);
/* 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__(136);
/* 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__(137);
/* 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__(138);
/* 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__(66);
/* 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__(67);
/* 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__(68);
/* 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__(69);
/* 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__(139);
/* 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__(140);
/* 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__(141);
/* 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__(71);
/* 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__(142);
/* 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__(143);
/* 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__(61);
/* 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__(75);
/* 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__(72);
/* 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__(144);
/* 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__(145);
/* 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__(76);
/* 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__(146);
/* 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__(147);
/* 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__(79);
/* 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__(149);
/* 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__(150);
/* 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__(151);
/* 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__(152);
/* 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__(74);
/* 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__(81);
/* 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__(153);
/* 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__(154);
/* 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__(82);
/* 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__(155);
/* 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__(156);
/* 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__(157);
/* 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__(158);
/* 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__(159);
/* 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__(160);
/* 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__(83);
/* 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__(161);
/* 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__(84);
/* 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__(86);
/* 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__(87);
/* 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__(88);
/* 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__(162);
/* 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__(90);
/* 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__(163);
/* 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__(164);
/* 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__(165);
/* 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__(166);
/* 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__(167);
/* 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__(168);
/* 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__(169);
/* 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__(170);
/* 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__(92);
/* 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__(171);
/* 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__(172);
/* 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__(93);
/* 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__(173);
/* 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__(174);
/* 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__(175);
/* 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__(176);
/* 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__(177);
/* 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__(94);
/* 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__(178);
/* 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__(95);
/* 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__(180);
/* 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__(181);
/* 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__(96);
/* 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__(182);
/* 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__(97);
/* 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__(183);
/* 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__(184);
/* 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__(185);
/* 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__(99);
/* 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__(186);
/* 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__(187);
/* 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__(98);
/* 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__(100);
/* 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__(188);
/* 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__(189);
/* 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__(190);
/* 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__(191);
/* 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__(192);
/* 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__(193);
/* 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__(58);
/* 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__(63);


// 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__(85);


// 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__(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";

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 */
/* unused harmony export LinearEncoding */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", 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__, "x", function() { return Matrix3; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "y", function() { return Matrix4; });
/* unused harmony export MaxEquation */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "z", 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__, "A", 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__, "B", function() { return NoBlending; });
/* unused harmony export NoColors */
/* unused harmony export NoToneMapping */
/* unused harmony export NormalAnimationBlendMode */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", 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__, "D", 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__, "E", 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__, "F", function() { return PerspectiveCamera; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "G", function() { return Plane; });
/* unused harmony export PlaneBufferGeometry */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "H", 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__, "I", 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__, "J", 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__, "K", 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__, "L", function() { return Scene; });
/* unused harmony export SceneUtils */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "M", function() { return ShaderChunk; });
/* unused harmony export ShaderLib */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "N", 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__, "O", 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__, "P", 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__, "Q", 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__, "R", 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__, "S", function() { return Uniform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "T", function() { return UniformsLib; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "U", function() { return UniformsUtils; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "V", 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__, "W", function() { return Vector2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "X", 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__, "Y", function() { return WebGLRenderTarget; });
/* unused harmony export WebGLRenderTargetCube */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Z", 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 */
/* unused harmony export 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, 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));


/***/ }),
/* 54 */
/***/ (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;
}


/***/ }),
/* 55 */
/***/ (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]';
}


/***/ }),
/* 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 */])('Number'));


/***/ }),
/* 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 */])('Symbol'));


/***/ }),
/* 58 */
/***/ (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'));


/***/ }),
/* 59 */
/***/ (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__(56);



// 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);
}


/***/ }),
/* 60 */
/***/ (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__(61);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__isBufferLike_js__ = __webpack_require__(130);





// 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));


/***/ }),
/* 61 */
/***/ (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;
  };
}


/***/ }),
/* 62 */
/***/ (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 */];
  }
}


/***/ }),
/* 63 */
/***/ (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];
  };
}


/***/ }),
/* 64 */
/***/ (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);
    }
  }
}


/***/ }),
/* 65 */
/***/ (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;
}


/***/ }),
/* 66 */
/***/ (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;
}


/***/ }),
/* 67 */
/***/ (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();
}


/***/ }),
/* 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);



// 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 */]));


/***/ }),
/* 69 */
/***/ (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));


/***/ }),
/* 70 */
/***/ (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;
}


/***/ }),
/* 71 */
/***/ (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__(54);




// 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;
}


/***/ }),
/* 72 */
/***/ (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;


/***/ }),
/* 73 */
/***/ (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);
}


/***/ }),
/* 74 */
/***/ (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__(73);



// 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;


/***/ }),
/* 75 */
/***/ (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(){}


/***/ }),
/* 76 */
/***/ (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));
}


/***/ }),
/* 77 */
/***/ (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;
  };
}


/***/ }),
/* 78 */
/***/ (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;'
});


/***/ }),
/* 79 */
/***/ (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
});


/***/ }),
/* 80 */
/***/ (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__(70);
/* 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;
}


/***/ }),
/* 81 */
/***/ (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__(80);




// 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;
}));


/***/ }),
/* 82 */
/***/ (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);
}));


/***/ }),
/* 83 */
/***/ (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;
  };
}


/***/ }),
/* 84 */
/***/ (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;
  }
}


/***/ }),
/* 85 */
/***/ (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;
  };
}


/***/ }),
/* 86 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createPredicateIndexFinder_js__ = __webpack_require__(85);


// 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));


/***/ }),
/* 87 */
/***/ (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;
}


/***/ }),
/* 88 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sortedIndex_js__ = __webpack_require__(87);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__findIndex_js__ = __webpack_require__(48);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__createIndexFinder_js__ = __webpack_require__(89);




// 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 */]));


/***/ }),
/* 89 */
/***/ (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__(59);




// 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;
  };
}


/***/ }),
/* 90 */
/***/ (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__(84);




// 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];
}


/***/ }),
/* 91 */
/***/ (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);
  };
}


/***/ }),
/* 92 */
/***/ (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;
}


/***/ }),
/* 93 */
/***/ (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__(76);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__toArray_js__ = __webpack_require__(94);






// 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);
}


/***/ }),
/* 94 */
/***/ (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);
}


/***/ }),
/* 95 */
/***/ (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__(179);
/* 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;
}));


/***/ }),
/* 96 */
/***/ (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)));
}


/***/ }),
/* 97 */
/***/ (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);
}


/***/ }),
/* 98 */
/***/ (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);
  });
}));


/***/ }),
/* 99 */
/***/ (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__(55);
/* 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;
}


/***/ }),
/* 100 */
/***/ (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__(92);
/* 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;
}


/***/ }),
/* 101 */
/***/ (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;
}


/***/ }),
/* 102 */
/***/ (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, 

/***/ }),
/* 103 */
/***/ (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, 

/***/ }),
/* 104 */
/***/ (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
};

} );


/***/ }),
/* 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";

// $.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 );
			}
		}
	}
};

} );


/***/ }),
/* 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.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;
};

} );


/***/ }),
/* 107 */
/***/ (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" );
	}
};

} );


/***/ }),
/* 108 */
/***/ (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;

} );


/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "f83a8b8886694eaef4505dd80af7a430.png";

/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = {};
var loadedModules = [
    __webpack_require__(111),
];
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=

/***/ }),
/* 111 */
/***/ (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__(102);
__webpack_require__(194);
__webpack_require__(50);
__webpack_require__(103);
__webpack_require__(195);
__webpack_require__(196); // FIXME: remove?
__webpack_require__(212); // FIXME: remove?
const gui_1 = __webpack_require__(241);
const fullscreen_1 = __webpack_require__(242);
const color_1 = __webpack_require__(243);
const theme_1 = __webpack_require__(244);
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 = 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');
            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(that.model.get("_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"
            that.model.get("_ngl_msg_archive").forEach(function (msg) {
                if (msg.fire_embed) {
                    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) {
        // 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;
                        }
                        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, 

/***/ }),
/* 112 */
/***/ (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__(113)(module)))

/***/ }),
/* 113 */
/***/ (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;
};


/***/ }),
/* 114 */
/***/ (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


/***/ }),
/* 115 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(setImmediate) {/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__finally__ = __webpack_require__(119);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__allSettled__ = __webpack_require__(120);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__any__ = __webpack_require__(121);




// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;

function isArray(x) {
  return Boolean(x && typeof x.length !== 'undefined');
}

function noop() {}

// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
  return function() {
    fn.apply(thisArg, arguments);
  };
}

/**
 * @constructor
 * @param {Function} fn
 */
function Promise(fn) {
  if (!(this instanceof Promise))
    throw new TypeError('Promises must be constructed via new');
  if (typeof fn !== 'function') throw new TypeError('not a function');
  /** @type {!number} */
  this._state = 0;
  /** @type {!boolean} */
  this._handled = false;
  /** @type {Promise|undefined} */
  this._value = undefined;
  /** @type {!Array<!Function>} */
  this._deferreds = [];

  doResolve(fn, this);
}

function handle(self, deferred) {
  while (self._state === 3) {
    self = self._value;
  }
  if (self._state === 0) {
    self._deferreds.push(deferred);
    return;
  }
  self._handled = true;
  Promise._immediateFn(function() {
    var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
    if (cb === null) {
      (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
      return;
    }
    var ret;
    try {
      ret = cb(self._value);
    } catch (e) {
      reject(deferred.promise, e);
      return;
    }
    resolve(deferred.promise, ret);
  });
}

function resolve(self, newValue) {
  try {
    // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
    if (newValue === self)
      throw new TypeError('A promise cannot be resolved with itself.');
    if (
      newValue &&
      (typeof newValue === 'object' || typeof newValue === 'function')
    ) {
      var then = newValue.then;
      if (newValue instanceof Promise) {
        self._state = 3;
        self._value = newValue;
        finale(self);
        return;
      } else if (typeof then === 'function') {
        doResolve(bind(then, newValue), self);
        return;
      }
    }
    self._state = 1;
    self._value = newValue;
    finale(self);
  } catch (e) {
    reject(self, e);
  }
}

function reject(self, newValue) {
  self._state = 2;
  self._value = newValue;
  finale(self);
}

function finale(self) {
  if (self._state === 2 && self._deferreds.length === 0) {
    Promise._immediateFn(function() {
      if (!self._handled) {
        Promise._unhandledRejectionFn(self._value);
      }
    });
  }

  for (var i = 0, len = self._deferreds.length; i < len; i++) {
    handle(self, self._deferreds[i]);
  }
  self._deferreds = null;
}

/**
 * @constructor
 */
function Handler(onFulfilled, onRejected, promise) {
  this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  this.promise = promise;
}

/**
 * Take a potentially misbehaving resolver function and make sure
 * onFulfilled and onRejected are only called once.
 *
 * Makes no guarantees about asynchrony.
 */
function doResolve(fn, self) {
  var done = false;
  try {
    fn(
      function(value) {
        if (done) return;
        done = true;
        resolve(self, value);
      },
      function(reason) {
        if (done) return;
        done = true;
        reject(self, reason);
      }
    );
  } catch (ex) {
    if (done) return;
    done = true;
    reject(self, ex);
  }
}

Promise.prototype['catch'] = function(onRejected) {
  return this.then(null, onRejected);
};

Promise.prototype.then = function(onFulfilled, onRejected) {
  // @ts-ignore
  var prom = new this.constructor(noop);

  handle(this, new Handler(onFulfilled, onRejected, prom));
  return prom;
};

Promise.prototype['finally'] = __WEBPACK_IMPORTED_MODULE_0__finally__["a" /* default */];

Promise.all = function(arr) {
  return new Promise(function(resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.all accepts an array'));
    }

    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return resolve([]);
    var remaining = args.length;

    function res(i, val) {
      try {
        if (val && (typeof val === 'object' || typeof val === 'function')) {
          var then = val.then;
          if (typeof then === 'function') {
            then.call(
              val,
              function(val) {
                res(i, val);
              },
              reject
            );
            return;
          }
        }
        args[i] = val;
        if (--remaining === 0) {
          resolve(args);
        }
      } catch (ex) {
        reject(ex);
      }
    }

    for (var i = 0; i < args.length; i++) {
      res(i, args[i]);
    }
  });
};

Promise.any = __WEBPACK_IMPORTED_MODULE_2__any__["a" /* default */];

Promise.allSettled = __WEBPACK_IMPORTED_MODULE_1__allSettled__["a" /* default */];

Promise.resolve = function(value) {
  if (value && typeof value === 'object' && value.constructor === Promise) {
    return value;
  }

  return new Promise(function(resolve) {
    resolve(value);
  });
};

Promise.reject = function(value) {
  return new Promise(function(resolve, reject) {
    reject(value);
  });
};

Promise.race = function(arr) {
  return new Promise(function(resolve, reject) {
    if (!isArray(arr)) {
      return reject(new TypeError('Promise.race accepts an array'));
    }

    for (var i = 0, len = arr.length; i < len; i++) {
      Promise.resolve(arr[i]).then(resolve, reject);
    }
  });
};

// Use polyfill for setImmediate for performance gains
Promise._immediateFn =
  // @ts-ignore
  (typeof setImmediate === 'function' &&
    function(fn) {
      // @ts-ignore
      setImmediate(fn);
    }) ||
  function(fn) {
    setTimeoutFunc(fn, 0);
  };

Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  if (typeof console !== 'undefined' && console) {
    console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  }
};

/* harmony default export */ __webpack_exports__["a"] = (Promise);

/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(116).setImmediate))

/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
            (typeof self !== "undefined" && self) ||
            window;
var apply = Function.prototype.apply;

// DOM APIs, for completeness

exports.setTimeout = function() {
  return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
  return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
  if (timeout) {
    timeout.close();
  }
};

function Timeout(id, clearFn) {
  this._id = id;
  this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
  this._clearFn.call(scope, this._id);
};

// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = msecs;
};

exports.unenroll = function(item) {
  clearTimeout(item._idleTimeoutId);
  item._idleTimeout = -1;
};

exports._unrefActive = exports.active = function(item) {
  clearTimeout(item._idleTimeoutId);

  var msecs = item._idleTimeout;
  if (msecs >= 0) {
    item._idleTimeoutId = setTimeout(function onTimeout() {
      if (item._onTimeout)
        item._onTimeout();
    }, msecs);
  }
};

// setimmediate attaches itself to the global object
__webpack_require__(117);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto.  Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
                       (typeof global !== "undefined" && global.setImmediate) ||
                       (this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
                         (typeof global !== "undefined" && global.clearImmediate) ||
                         (this && this.clearImmediate);

/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33)))

/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {

/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
    "use strict";

    if (global.setImmediate) {
        return;
    }

    var nextHandle = 1; // Spec says greater than zero
    var tasksByHandle = {};
    var currentlyRunningATask = false;
    var doc = global.document;
    var registerImmediate;

    function setImmediate(callback) {
      // Callback can either be a function or a string
      if (typeof callback !== "function") {
        callback = new Function("" + callback);
      }
      // Copy function arguments
      var args = new Array(arguments.length - 1);
      for (var i = 0; i < args.length; i++) {
          args[i] = arguments[i + 1];
      }
      // Store and register the task
      var task = { callback: callback, args: args };
      tasksByHandle[nextHandle] = task;
      registerImmediate(nextHandle);
      return nextHandle++;
    }

    function clearImmediate(handle) {
        delete tasksByHandle[handle];
    }

    function run(task) {
        var callback = task.callback;
        var args = task.args;
        switch (args.length) {
        case 0:
            callback();
            break;
        case 1:
            callback(args[0]);
            break;
        case 2:
            callback(args[0], args[1]);
            break;
        case 3:
            callback(args[0], args[1], args[2]);
            break;
        default:
            callback.apply(undefined, args);
            break;
        }
    }

    function runIfPresent(handle) {
        // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
        // So if we're currently running a task, we'll need to delay this invocation.
        if (currentlyRunningATask) {
            // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
            // "too much recursion" error.
            setTimeout(runIfPresent, 0, handle);
        } else {
            var task = tasksByHandle[handle];
            if (task) {
                currentlyRunningATask = true;
                try {
                    run(task);
                } finally {
                    clearImmediate(handle);
                    currentlyRunningATask = false;
                }
            }
        }
    }

    function installNextTickImplementation() {
        registerImmediate = function(handle) {
            process.nextTick(function () { runIfPresent(handle); });
        };
    }

    function canUsePostMessage() {
        // The test against `importScripts` prevents this implementation from being installed inside a web worker,
        // where `global.postMessage` means something completely different and can't be used for this purpose.
        if (global.postMessage && !global.importScripts) {
            var postMessageIsAsynchronous = true;
            var oldOnMessage = global.onmessage;
            global.onmessage = function() {
                postMessageIsAsynchronous = false;
            };
            global.postMessage("", "*");
            global.onmessage = oldOnMessage;
            return postMessageIsAsynchronous;
        }
    }

    function installPostMessageImplementation() {
        // Installs an event handler on `global` for the `message` event: see
        // * https://developer.mozilla.org/en/DOM/window.postMessage
        // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages

        var messagePrefix = "setImmediate$" + Math.random() + "$";
        var onGlobalMessage = function(event) {
            if (event.source === global &&
                typeof event.data === "string" &&
                event.data.indexOf(messagePrefix) === 0) {
                runIfPresent(+event.data.slice(messagePrefix.length));
            }
        };

        if (global.addEventListener) {
            global.addEventListener("message", onGlobalMessage, false);
        } else {
            global.attachEvent("onmessage", onGlobalMessage);
        }

        registerImmediate = function(handle) {
            global.postMessage(messagePrefix + handle, "*");
        };
    }

    function installMessageChannelImplementation() {
        var channel = new MessageChannel();
        channel.port1.onmessage = function(event) {
            var handle = event.data;
            runIfPresent(handle);
        };

        registerImmediate = function(handle) {
            channel.port2.postMessage(handle);
        };
    }

    function installReadyStateChangeImplementation() {
        var html = doc.documentElement;
        registerImmediate = function(handle) {
            // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
            // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
            var script = doc.createElement("script");
            script.onreadystatechange = function () {
                runIfPresent(handle);
                script.onreadystatechange = null;
                html.removeChild(script);
                script = null;
            };
            html.appendChild(script);
        };
    }

    function installSetTimeoutImplementation() {
        registerImmediate = function(handle) {
            setTimeout(runIfPresent, 0, handle);
        };
    }

    // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
    var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
    attachTo = attachTo && attachTo.setTimeout ? attachTo : global;

    // Don't get fooled by e.g. browserify environments.
    if ({}.toString.call(global.process) === "[object process]") {
        // For Node.js before 0.9
        installNextTickImplementation();

    } else if (canUsePostMessage()) {
        // For non-IE10 modern browsers
        installPostMessageImplementation();

    } else if (global.MessageChannel) {
        // For web workers, where supported
        installMessageChannelImplementation();

    } else if (doc && "onreadystatechange" in doc.createElement("script")) {
        // For IE 6–8
        installReadyStateChangeImplementation();

    } else {
        // For older browsers
        installSetTimeoutImplementation();
    }

    attachTo.setImmediate = setImmediate;
    attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));

/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(33), __webpack_require__(118)))

/***/ }),
/* 118 */
/***/ (function(module, exports) {

// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };


/***/ }),
/* 119 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/**
 * @this {Promise}
 */
function finallyConstructor(callback) {
  var constructor = this.constructor;
  return this.then(
    function(value) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function() {
        return value;
      });
    },
    function(reason) {
      // @ts-ignore
      return constructor.resolve(callback()).then(function() {
        // @ts-ignore
        return constructor.reject(reason);
      });
    }
  );
}

/* harmony default export */ __webpack_exports__["a"] = (finallyConstructor);


/***/ }),
/* 120 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
function allSettled(arr) {
  var P = this;
  return new P(function(resolve, reject) {
    if (!(arr && typeof arr.length !== 'undefined')) {
      return reject(
        new TypeError(
          typeof arr +
            ' ' +
            arr +
            ' is not iterable(cannot read property Symbol(Symbol.iterator))'
        )
      );
    }
    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return resolve([]);
    var remaining = args.length;

    function res(i, val) {
      if (val && (typeof val === 'object' || typeof val === 'function')) {
        var then = val.then;
        if (typeof then === 'function') {
          then.call(
            val,
            function(val) {
              res(i, val);
            },
            function(e) {
              args[i] = { status: 'rejected', reason: e };
              if (--remaining === 0) {
                resolve(args);
              }
            }
          );
          return;
        }
      }
      args[i] = { status: 'fulfilled', value: val };
      if (--remaining === 0) {
        resolve(args);
      }
    }

    for (var i = 0; i < args.length; i++) {
      res(i, args[i]);
    }
  });
}

/* harmony default export */ __webpack_exports__["a"] = (allSettled);


/***/ }),
/* 121 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/**
 * @constructor
 */
function AggregateError(errors, message) {
  (this.name = 'AggregateError'), (this.errors = errors);
  this.message = message || '';
}
AggregateError.prototype = Error.prototype;

function any(arr) {
  var P = this;
  return new P(function(resolve, reject) {
    if (!(arr && typeof arr.length !== 'undefined')) {
      return reject(new TypeError('Promise.any accepts an array'));
    }

    var args = Array.prototype.slice.call(arr);
    if (args.length === 0) return reject();

    var rejectionReasons = [];
    for (var i = 0; i < args.length; i++) {
      try {
        P.resolve(args[i])
          .then(resolve)
          .catch(function(error) {
            rejectionReasons.push(error);
            if (rejectionReasons.length === args.length) {
              reject(
                new AggregateError(
                  rejectionReasons,
                  'All promises were rejected'
                )
              );
            }
          });
      } catch (ex) {
        reject(ex);
      }
    }
  });
}

/* harmony default export */ __webpack_exports__["a"] = (any);


/***/ }),
/* 122 */
/***/ (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"] = (_);


/***/ }),
/* 123 */
/***/ (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;
}


/***/ }),
/* 124 */
/***/ (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);
}


/***/ }),
/* 125 */
/***/ (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'));


/***/ }),
/* 126 */
/***/ (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'));


/***/ }),
/* 127 */
/***/ (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'));


/***/ }),
/* 128 */
/***/ (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'));


/***/ }),
/* 129 */
/***/ (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__(57);



// 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));
}


/***/ }),
/* 130 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createSizePropertyCheck_js__ = __webpack_require__(62);
/* 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 */]));


/***/ }),
/* 131 */
/***/ (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;
}


/***/ }),
/* 132 */
/***/ (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__(60);
/* 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__(133);











// 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);
}


/***/ }),
/* 133 */
/***/ (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)
  );
}


/***/ }),
/* 134 */
/***/ (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'));


/***/ }),
/* 135 */
/***/ (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'));


/***/ }),
/* 136 */
/***/ (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'));


/***/ }),
/* 137 */
/***/ (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'));


/***/ }),
/* 138 */
/***/ (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;
}


/***/ }),
/* 139 */
/***/ (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__(70);
/* 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;
}


/***/ }),
/* 140 */
/***/ (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__(68);




// 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);
}


/***/ }),
/* 141 */
/***/ (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;
}


/***/ }),
/* 142 */
/***/ (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;
}


/***/ }),
/* 143 */
/***/ (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;
}


/***/ }),
/* 144 */
/***/ (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__(75);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__get_js__ = __webpack_require__(71);



// 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);
  };
}


/***/ }),
/* 145 */
/***/ (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;
}


/***/ }),
/* 146 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createEscaper_js__ = __webpack_require__(77);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__escapeMap_js__ = __webpack_require__(78);



// 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 */]));


/***/ }),
/* 147 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createEscaper_js__ = __webpack_require__(77);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__unescapeMap_js__ = __webpack_require__(148);



// 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 */]));


/***/ }),
/* 148 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__invert_js__ = __webpack_require__(66);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__escapeMap_js__ = __webpack_require__(78);



// 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 */]));


/***/ }),
/* 149 */
/***/ (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__(69);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__underscore_js__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__templateSettings_js__ = __webpack_require__(79);




// 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;
}


/***/ }),
/* 150 */
/***/ (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;
}


/***/ }),
/* 151 */
/***/ (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;
}


/***/ }),
/* 152 */
/***/ (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;
}


/***/ }),
/* 153 */
/***/ (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__(81);




// 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;
}));


/***/ }),
/* 154 */
/***/ (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;
}


/***/ }),
/* 155 */
/***/ (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__(82);
/* 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));


/***/ }),
/* 156 */
/***/ (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;
}


/***/ }),
/* 157 */
/***/ (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;
}


/***/ }),
/* 158 */
/***/ (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);
}


/***/ }),
/* 159 */
/***/ (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;
  };
}


/***/ }),
/* 160 */
/***/ (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);
    }
  };
}


/***/ }),
/* 161 */
/***/ (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__(83);



// 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));


/***/ }),
/* 162 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__findLastIndex_js__ = __webpack_require__(86);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__createIndexFinder_js__ = __webpack_require__(89);



// 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 */]));


/***/ }),
/* 163 */
/***/ (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__(90);
/* 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));
}


/***/ }),
/* 164 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createReduce_js__ = __webpack_require__(91);


// **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));


/***/ }),
/* 165 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__createReduce_js__ = __webpack_require__(91);


// 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));


/***/ }),
/* 166 */
/***/ (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);
}


/***/ }),
/* 167 */
/***/ (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;
}


/***/ }),
/* 168 */
/***/ (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;
}


/***/ }),
/* 169 */
/***/ (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);
  });
}));


/***/ }),
/* 170 */
/***/ (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));
}


/***/ }),
/* 171 */
/***/ (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;
}


/***/ }),
/* 172 */
/***/ (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__(93);


// Shuffle a collection.
function shuffle(obj) {
  return Object(__WEBPACK_IMPORTED_MODULE_0__sample_js__["a" /* default */])(obj, Infinity);
}


/***/ }),
/* 173 */
/***/ (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');
}


/***/ }),
/* 174 */
/***/ (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];
}));


/***/ }),
/* 175 */
/***/ (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;
}));


/***/ }),
/* 176 */
/***/ (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;
}));


/***/ }),
/* 177 */
/***/ (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));


/***/ }),
/* 178 */
/***/ (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;
}


/***/ }),
/* 179 */
/***/ (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;
}


/***/ }),
/* 180 */
/***/ (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__(95);








// 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);
}));


/***/ }),
/* 181 */
/***/ (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__(96);


// 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);
}


/***/ }),
/* 182 */
/***/ (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__(97);


// 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));
}


/***/ }),
/* 183 */
/***/ (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);
}


/***/ }),
/* 184 */
/***/ (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);
}


/***/ }),
/* 185 */
/***/ (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__(98);



// 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);
}));


/***/ }),
/* 186 */
/***/ (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__(99);
/* 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));
}));


/***/ }),
/* 187 */
/***/ (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;
}


/***/ }),
/* 188 */
/***/ (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__(100);



// 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 */]));


/***/ }),
/* 189 */
/***/ (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;
}


/***/ }),
/* 190 */
/***/ (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;
}


/***/ }),
/* 191 */
/***/ (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;
}


/***/ }),
/* 192 */
/***/ (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__(67);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__setup_js__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__chainResult_js__ = __webpack_require__(101);






// 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 */];
}


/***/ }),
/* 193 */
/***/ (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__(101);





// 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 */]);


/***/ }),
/* 194 */
/***/ (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, 

/***/ }),
/* 195 */
/***/ (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__(103).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, 

/***/ }),
/* 196 */
/***/ (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__(197),
			__webpack_require__(203),
			__webpack_require__(51),
			__webpack_require__(207),
			__webpack_require__(108),
			__webpack_require__(104),
			__webpack_require__(209),
			__webpack_require__(106),
			__webpack_require__(107),
			__webpack_require__(210),
			__webpack_require__(211),
			__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;

} );


/***/ }),
/* 197 */
/***/ (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__(198),
			__webpack_require__(199),

			__webpack_require__(104),
			__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;

} );


/***/ }),
/* 198 */
/***/ (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" );
		}
	}
} );
} );


/***/ }),
/* 199 */
/***/ (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__(200),
			__webpack_require__(202),
			__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;

} );


/***/ }),
/* 200 */
/***/ (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__(201),
			__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" );
		}
	}
};

} );


/***/ }),
/* 201 */
/***/ (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 );
};

} );


/***/ }),
/* 202 */
/***/ (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 );
};

} );


/***/ }),
/* 203 */
/***/ (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__(205),
			__webpack_require__(105),
			__webpack_require__(106),
			__webpack_require__(107),
			__webpack_require__(206),
			__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;

} );


/***/ }),
/* 204 */
/***/ (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() );
} );


/***/ }),
/* 205 */
/***/ (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 ] );
		}
} );
} );


/***/ }),
/* 206 */
/***/ (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;
};

} );


/***/ }),
/* 207 */
/***/ (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__(208),
			__webpack_require__(105),
			__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;

} );


/***/ }),
/* 208 */
/***/ (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" );
	}
} );

} );


/***/ }),
/* 209 */
/***/ (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;

} );


/***/ }),
/* 210 */
/***/ (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__(108) ], __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 );
	}
} );

} );


/***/ }),
/* 211 */
/***/ (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" );
			}
		} );
	}
} );

} );


/***/ }),
/* 212 */
/***/ (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__(213);
if(typeof content === 'string') content = [[module.i, content, '']];
// add the styles to the DOM
var update = __webpack_require__(240)(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(); });
}

/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports
exports.i(__webpack_require__(214), "");
exports.i(__webpack_require__(234), "");

// 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


/***/ }),
/* 214 */
/***/ (function(module, exports, __webpack_require__) {

exports = module.exports = __webpack_require__(2)();
// imports
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), "");
exports.i(__webpack_require__(227), "");
exports.i(__webpack_require__(228), "");
exports.i(__webpack_require__(229), "");
exports.i(__webpack_require__(230), "");
exports.i(__webpack_require__(231), "");
exports.i(__webpack_require__(232), "");
exports.i(__webpack_require__(233), "");

// 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


/***/ }),
/* 215 */
/***/ (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


/***/ }),
/* 216 */
/***/ (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


/***/ }),
/* 217 */
/***/ (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


/***/ }),
/* 218 */
/***/ (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


/***/ }),
/* 219 */
/***/ (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


/***/ }),
/* 220 */
/***/ (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


/***/ }),
/* 221 */
/***/ (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


/***/ }),
/* 222 */
/***/ (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


/***/ }),
/* 223 */
/***/ (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


/***/ }),
/* 224 */
/***/ (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


/***/ }),
/* 225 */
/***/ (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


/***/ }),
/* 226 */
/***/ (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


/***/ }),
/* 227 */
/***/ (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


/***/ }),
/* 228 */
/***/ (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


/***/ }),
/* 229 */
/***/ (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


/***/ }),
/* 230 */
/***/ (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


/***/ }),
/* 231 */
/***/ (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


/***/ }),
/* 232 */
/***/ (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


/***/ }),
/* 233 */
/***/ (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


/***/ }),
/* 234 */
/***/ (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__(109) + ");\n}\n.ui-widget-header .ui-icon {\n\tbackground-image: url(" + __webpack_require__(109) + ");\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__(235) + ");\n}\n.ui-state-active .ui-icon,\n.ui-button:active .ui-icon {\n\tbackground-image: url(" + __webpack_require__(236) + ");\n}\n.ui-state-highlight .ui-icon,\n.ui-button .ui-state-highlight.ui-icon {\n\tbackground-image: url(" + __webpack_require__(237) + ");\n}\n.ui-state-error .ui-icon,\n.ui-state-error-text .ui-icon {\n\tbackground-image: url(" + __webpack_require__(238) + ");\n}\n.ui-button .ui-icon {\n\tbackground-image: url(" + __webpack_require__(239) + ");\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


/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "91b1966e761a8e0c0b83450f676e8fe4.png";

/***/ }),
/* 236 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "47d227801c1ad6c59d033bc151848c07.png";

/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "efbf84f0f6384f5c303ea15ebb299a08.png";

/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "dd8125ead27254818e47e1a08814e83a.png";

/***/ }),
/* 239 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__.p + "5e7882c25f80ead21c4b7fa3d8e7c1a3.png";

/***/ }),
/* 240 */
/***/ (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);
}


/***/ }),
/* 241 */
/***/ (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__(102);
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, 

/***/ }),
/* 242 */
/***/ (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();
        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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZnVsbHNjcmVlbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9mdWxsc2NyZWVuLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7OztBQUFBLGlEQUFnRDtBQUNoRCwyQkFBMEI7QUFDMUIsaUNBQWlDO0FBR2pDLE1BQ00sZUFBZ0IsU0FBUSxPQUFPLENBQUMsY0FBYztJQUNoRCxRQUFRO1FBQ0osdUNBQ1csS0FBSyxDQUFDLFFBQVEsRUFBRSxLQUNuQixXQUFXLEVBQUUsaUJBQWlCLEVBQzlCLGFBQWEsRUFBRSxvQkFBb0IsRUFDbkMscUJBQXFCLEVBQUUsT0FBTyxDQUFDLGlCQUFpQixDQUFDLENBQUMsT0FBTyxFQUN6RCxVQUFVLEVBQUUsZ0JBQWdCLEVBQzVCLFlBQVksRUFBRSxvQkFBb0IsRUFDbEMsb0JBQW9CLEVBQUUsT0FBTyxDQUFDLGlCQUFpQixDQUFDLENBQUMsT0FBTyxJQUMzRDtJQUNMLENBQUM7Q0FDUjtBQWJELDBDQWFDO0FBRUQsTUFDTSxHQUFHO0NBQ1I7QUFGRCxrQkFFQztBQUdELE1BQ00sY0FBZSxTQUFRLGVBQVE7SUFFakMsTUFBTTtRQUNGLElBQUksQ0FBQyxLQUFLLEdBQUcsSUFBSSxHQUFHLENBQUMsS0FBSyxFQUFFLENBQUE7UUFDNUIsSUFBSSxJQUFJLEdBQUcsSUFBSSxDQUFBO1FBQ2YsSUFBSSxDQUFDLEtBQUssQ0FBQyxFQUFFLENBQUMsWUFBWSxFQUFFLFVBQVMsR0FBRztZQUNwQyxJQUFJLENBQUMsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFBO1FBQ3BCLENBQUMsQ0FBQyxDQUFBO1FBQ0YsSUFBSSxDQUFDLGFBQWEsRUFBRSxDQUFBO0lBQ3hCLENBQUM7SUFFRCxVQUFVLENBQUMsUUFBUTtRQUNmLElBQUksSUFBSSxHQUFHLElBQUksQ0FBQTtRQUNmLElBQUksQ0FBQyxLQUFLLENBQUMsY0FBYyxDQUFDLFNBQVMsQ0FBQyxRQUFRLENBQUMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxLQUFLLEVBQUUsRUFBRTtZQUN6RCxJQUFJLEdBQUcsR0FBRyxNQUFNLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQTtZQUNyQyxLQUFLLENBQUMsS0FBSyxDQUFDLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxDQUFDLElBQUksRUFBRSxFQUFFO2dCQUMzQixJQUFJLENBQUMsS0FBSyxDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxFQUFFLENBQUMsQ0FBQTtZQUN4QyxDQUFDLENBQUMsQ0FBQTtRQUNOLENBQUMsQ0FBQyxDQUFBO0lBQ04sQ0FBQztJQUVELGFBQWE7UUFDVCxJQUFJLElBQUksR0FBRyxJQUFJLENBQUE7UUFDZixJQUFJLENBQUMsS0FBSyxDQUFDLE9BQU8sQ0FBQyxpQkFBaUIsQ0FBQyxHQUFHLENBQUMsVUFBVSxZQUFZO1lBQzNELElBQUksQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLGdCQUFnQixFQUFFLFlBQVksQ0FBQyxDQUFBO1lBQzlDLElBQUksQ0FBQyxLQUFLLEVBQUUsQ0FBQTtRQUNoQixDQUFDLENBQUMsQ0FBQTtJQUNOLENBQUM7SUFFRCxXQUFXLENBQUMsSUFBSTtRQUNaLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUNmLENBQUM7SUFFRCxNQUFNLENBQUMsR0FBRztRQUNOLElBQUksYUFBYSxJQUFJLEdBQUcsRUFBQztZQUNyQixJQUFJLENBQUMsV0FBVyxDQUFDLEdBQUcsQ0FBQyxXQUFXLENBQUMsQ0FBQTtTQUNwQztJQUNMLENBQUM7Q0FDSjtBQXZDRCx3Q0F1Q0MifQ==

/***/ }),
/* 243 */
/***/ (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==

/***/ }),
/* 244 */
/***/ (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